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/blk-mq.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/audit.h>
82 #include <linux/security.h>
84 #define CREATE_TRACE_POINTS
85 #include <trace/events/io_uring.h>
87 #include <uapi/linux/io_uring.h>
92 #define IORING_MAX_ENTRIES 32768
93 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
97 #define IORING_MAX_FIXED_FILES (1U << 15)
98 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
99 IORING_REGISTER_LAST + IORING_OP_LAST)
101 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
102 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
103 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
105 #define IORING_MAX_REG_BUFFERS (1U << 14)
107 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
111 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_CREDS | REQ_F_ASYNC_DATA)
116 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
119 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
122 u32 head ____cacheline_aligned_in_smp;
123 u32 tail ____cacheline_aligned_in_smp;
127 * This data is shared with the application through the mmap at offsets
128 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
130 * The offsets to the member fields are published through struct
131 * io_sqring_offsets when calling io_uring_setup.
135 * Head and tail offsets into the ring; the offsets need to be
136 * masked to get valid indices.
138 * The kernel controls head of the sq ring and the tail of the cq ring,
139 * and the application controls tail of the sq ring and the head of the
142 struct io_uring sq, cq;
144 * Bitmasks to apply to head and tail offsets (constant, equals
147 u32 sq_ring_mask, cq_ring_mask;
148 /* Ring sizes (constant, power of 2) */
149 u32 sq_ring_entries, cq_ring_entries;
151 * Number of invalid entries dropped by the kernel due to
152 * invalid index stored in array
154 * Written by the kernel, shouldn't be modified by the
155 * application (i.e. get number of "new events" by comparing to
158 * After a new SQ head value was read by the application this
159 * counter includes all submissions that were dropped reaching
160 * the new SQ head (and possibly more).
166 * Written by the kernel, shouldn't be modified by the
169 * The application needs a full memory barrier before checking
170 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
176 * Written by the application, shouldn't be modified by the
181 * Number of completion events lost because the queue was full;
182 * this should be avoided by the application by making sure
183 * there are not more requests pending than there is space in
184 * the completion queue.
186 * Written by the kernel, shouldn't be modified by the
187 * application (i.e. get number of "new events" by comparing to
190 * As completion events come in out of order this counter is not
191 * ordered with any other data.
195 * Ring buffer of completion events.
197 * The kernel writes completion events fresh every time they are
198 * produced, so the application is allowed to modify pending
201 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
204 enum io_uring_cmd_flags {
205 IO_URING_F_COMPLETE_DEFER = 1,
206 IO_URING_F_UNLOCKED = 2,
207 /* int's last bit, sign checks are usually faster than a bit test */
208 IO_URING_F_NONBLOCK = INT_MIN,
211 struct io_mapped_ubuf {
214 unsigned int nr_bvecs;
215 unsigned long acct_pages;
216 struct bio_vec bvec[];
221 struct io_overflow_cqe {
222 struct io_uring_cqe cqe;
223 struct list_head list;
226 struct io_fixed_file {
227 /* file * with additional FFS_* flags */
228 unsigned long file_ptr;
232 struct list_head list;
237 struct io_mapped_ubuf *buf;
241 struct io_file_table {
242 struct io_fixed_file *files;
245 struct io_rsrc_node {
246 struct percpu_ref refs;
247 struct list_head node;
248 struct list_head rsrc_list;
249 struct io_rsrc_data *rsrc_data;
250 struct llist_node llist;
254 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
256 struct io_rsrc_data {
257 struct io_ring_ctx *ctx;
263 struct completion done;
267 struct io_buffer_list {
268 struct list_head list;
269 struct list_head buf_list;
274 struct list_head list;
281 struct io_restriction {
282 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
283 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
284 u8 sqe_flags_allowed;
285 u8 sqe_flags_required;
290 IO_SQ_THREAD_SHOULD_STOP = 0,
291 IO_SQ_THREAD_SHOULD_PARK,
296 atomic_t park_pending;
299 /* ctx's that are using this sqd */
300 struct list_head ctx_list;
302 struct task_struct *thread;
303 struct wait_queue_head wait;
305 unsigned sq_thread_idle;
311 struct completion exited;
314 #define IO_COMPL_BATCH 32
315 #define IO_REQ_CACHE_SIZE 32
316 #define IO_REQ_ALLOC_BATCH 8
318 struct io_submit_link {
319 struct io_kiocb *head;
320 struct io_kiocb *last;
323 struct io_submit_state {
324 /* inline/task_work completion list, under ->uring_lock */
325 struct io_wq_work_node free_list;
326 /* batch completion logic */
327 struct io_wq_work_list compl_reqs;
328 struct io_submit_link link;
333 unsigned short submit_nr;
334 struct blk_plug plug;
338 struct eventfd_ctx *cq_ev_fd;
339 unsigned int eventfd_async: 1;
343 #define IO_BUFFERS_HASH_BITS 5
346 /* const or read-mostly hot data */
348 struct percpu_ref refs;
350 struct io_rings *rings;
352 unsigned int compat: 1;
353 unsigned int drain_next: 1;
354 unsigned int restricted: 1;
355 unsigned int off_timeout_used: 1;
356 unsigned int drain_active: 1;
357 unsigned int drain_disabled: 1;
358 unsigned int has_evfd: 1;
359 unsigned int syscall_iopoll: 1;
360 } ____cacheline_aligned_in_smp;
362 /* submission data */
364 struct mutex uring_lock;
367 * Ring buffer of indices into array of io_uring_sqe, which is
368 * mmapped by the application using the IORING_OFF_SQES offset.
370 * This indirection could e.g. be used to assign fixed
371 * io_uring_sqe entries to operations and only submit them to
372 * the queue when needed.
374 * The kernel modifies neither the indices array nor the entries
378 struct io_uring_sqe *sq_sqes;
379 unsigned cached_sq_head;
381 struct list_head defer_list;
384 * Fixed resources fast path, should be accessed only under
385 * uring_lock, and updated through io_uring_register(2)
387 struct io_rsrc_node *rsrc_node;
388 int rsrc_cached_refs;
389 struct io_file_table file_table;
390 unsigned nr_user_files;
391 unsigned nr_user_bufs;
392 struct io_mapped_ubuf **user_bufs;
394 struct io_submit_state submit_state;
395 struct list_head timeout_list;
396 struct list_head ltimeout_list;
397 struct list_head cq_overflow_list;
398 struct list_head *io_buffers;
399 struct list_head io_buffers_cache;
400 struct list_head apoll_cache;
401 struct xarray personalities;
403 unsigned sq_thread_idle;
404 } ____cacheline_aligned_in_smp;
406 /* IRQ completion list, under ->completion_lock */
407 struct io_wq_work_list locked_free_list;
408 unsigned int locked_free_nr;
410 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
411 struct io_sq_data *sq_data; /* if using sq thread polling */
413 struct wait_queue_head sqo_sq_wait;
414 struct list_head sqd_list;
416 unsigned long check_cq_overflow;
419 unsigned cached_cq_tail;
421 struct io_ev_fd __rcu *io_ev_fd;
422 struct wait_queue_head cq_wait;
424 atomic_t cq_timeouts;
425 unsigned cq_last_tm_flush;
426 } ____cacheline_aligned_in_smp;
429 spinlock_t completion_lock;
431 spinlock_t timeout_lock;
434 * ->iopoll_list is protected by the ctx->uring_lock for
435 * io_uring instances that don't use IORING_SETUP_SQPOLL.
436 * For SQPOLL, only the single threaded io_sq_thread() will
437 * manipulate the list, hence no extra locking is needed there.
439 struct io_wq_work_list iopoll_list;
440 struct hlist_head *cancel_hash;
441 unsigned cancel_hash_bits;
442 bool poll_multi_queue;
444 struct list_head io_buffers_comp;
445 } ____cacheline_aligned_in_smp;
447 struct io_restriction restrictions;
449 /* slow path rsrc auxilary data, used by update/register */
451 struct io_rsrc_node *rsrc_backup_node;
452 struct io_mapped_ubuf *dummy_ubuf;
453 struct io_rsrc_data *file_data;
454 struct io_rsrc_data *buf_data;
456 struct delayed_work rsrc_put_work;
457 struct llist_head rsrc_put_llist;
458 struct list_head rsrc_ref_list;
459 spinlock_t rsrc_ref_lock;
461 struct list_head io_buffers_pages;
464 /* Keep this last, we don't need it for the fast path */
466 #if defined(CONFIG_UNIX)
467 struct socket *ring_sock;
469 /* hashed buffered write serialization */
470 struct io_wq_hash *hash_map;
472 /* Only used for accounting purposes */
473 struct user_struct *user;
474 struct mm_struct *mm_account;
476 /* ctx exit and cancelation */
477 struct llist_head fallback_llist;
478 struct delayed_work fallback_work;
479 struct work_struct exit_work;
480 struct list_head tctx_list;
481 struct completion ref_comp;
483 bool iowq_limits_set;
488 * Arbitrary limit, can be raised if need be
490 #define IO_RINGFD_REG_MAX 16
492 struct io_uring_task {
493 /* submission side */
496 struct wait_queue_head wait;
497 const struct io_ring_ctx *last;
499 struct percpu_counter inflight;
502 spinlock_t task_lock;
503 struct io_wq_work_list task_list;
504 struct io_wq_work_list prior_task_list;
505 struct callback_head task_work;
506 struct file **registered_rings;
511 * First field must be the file pointer in all the
512 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
514 struct io_poll_iocb {
516 struct wait_queue_head *head;
518 struct wait_queue_entry wait;
521 struct io_poll_update {
527 bool update_user_data;
536 struct io_timeout_data {
537 struct io_kiocb *req;
538 struct hrtimer timer;
539 struct timespec64 ts;
540 enum hrtimer_mode mode;
546 struct sockaddr __user *addr;
547 int __user *addr_len;
550 unsigned long nofile;
570 struct list_head list;
571 /* head of the link, used by linked timeouts only */
572 struct io_kiocb *head;
573 /* for linked completions */
574 struct io_kiocb *prev;
577 struct io_timeout_rem {
582 struct timespec64 ts;
588 /* NOTE: kiocb has the file as the first member, so don't do it here */
597 struct sockaddr __user *addr;
604 struct compat_msghdr __user *umsg_compat;
605 struct user_msghdr __user *umsg;
618 struct filename *filename;
620 unsigned long nofile;
623 struct io_rsrc_update {
649 struct epoll_event event;
653 struct file *file_out;
661 struct io_provide_buf {
675 struct filename *filename;
676 struct statx __user *buffer;
688 struct filename *oldpath;
689 struct filename *newpath;
697 struct filename *filename;
704 struct filename *filename;
710 struct filename *oldpath;
711 struct filename *newpath;
718 struct filename *oldpath;
719 struct filename *newpath;
729 struct io_async_connect {
730 struct sockaddr_storage address;
733 struct io_async_msghdr {
734 struct iovec fast_iov[UIO_FASTIOV];
735 /* points to an allocated iov, if NULL we use fast_iov instead */
736 struct iovec *free_iov;
737 struct sockaddr __user *uaddr;
739 struct sockaddr_storage addr;
743 struct iov_iter iter;
744 struct iov_iter_state iter_state;
745 struct iovec fast_iov[UIO_FASTIOV];
749 struct io_rw_state s;
750 const struct iovec *free_iovec;
752 struct wait_page_queue wpq;
756 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
757 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
758 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
759 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
760 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
761 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
762 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
764 /* first byte is taken by user flags, shift it to not overlap */
769 REQ_F_LINK_TIMEOUT_BIT,
770 REQ_F_NEED_CLEANUP_BIT,
772 REQ_F_BUFFER_SELECTED_BIT,
773 REQ_F_COMPLETE_INLINE_BIT,
777 REQ_F_ARM_LTIMEOUT_BIT,
778 REQ_F_ASYNC_DATA_BIT,
779 REQ_F_SKIP_LINK_CQES_BIT,
780 REQ_F_SINGLE_POLL_BIT,
781 REQ_F_DOUBLE_POLL_BIT,
782 REQ_F_PARTIAL_IO_BIT,
783 /* keep async read/write and isreg together and in order */
784 REQ_F_SUPPORT_NOWAIT_BIT,
787 /* not a real bit, just to check we're not overflowing the space */
793 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
794 /* drain existing IO first */
795 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
797 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
798 /* doesn't sever on completion < 0 */
799 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
801 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
802 /* IOSQE_BUFFER_SELECT */
803 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
804 /* IOSQE_CQE_SKIP_SUCCESS */
805 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
807 /* fail rest of links */
808 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
809 /* on inflight list, should be cancelled and waited on exit reliably */
810 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
811 /* read/write uses file position */
812 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
813 /* must not punt to workers */
814 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
815 /* has or had linked timeout */
816 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
818 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
819 /* already went through poll handler */
820 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
821 /* buffer already selected */
822 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
823 /* completion is deferred through io_comp_state */
824 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
825 /* caller should reissue async */
826 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
827 /* supports async reads/writes */
828 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
830 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
831 /* has creds assigned */
832 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
833 /* skip refcounting if not set */
834 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
835 /* there is a linked timeout that has to be armed */
836 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
837 /* ->async_data allocated */
838 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
839 /* don't post CQEs while failing linked requests */
840 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
841 /* single poll may be active */
842 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
843 /* double poll may active */
844 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
845 /* request has already done partial IO */
846 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
850 struct io_poll_iocb poll;
851 struct io_poll_iocb *double_poll;
854 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
856 struct io_task_work {
858 struct io_wq_work_node node;
859 struct llist_node fallback_node;
861 io_req_tw_func_t func;
865 IORING_RSRC_FILE = 0,
866 IORING_RSRC_BUFFER = 1,
870 * NOTE! Each of the iocb union members has the file pointer
871 * as the first entry in their struct definition. So you can
872 * access the file pointer through any of the sub-structs,
873 * or directly as just 'file' in this struct.
879 struct io_poll_iocb poll;
880 struct io_poll_update poll_update;
881 struct io_accept accept;
883 struct io_cancel cancel;
884 struct io_timeout timeout;
885 struct io_timeout_rem timeout_rem;
886 struct io_connect connect;
887 struct io_sr_msg sr_msg;
889 struct io_close close;
890 struct io_rsrc_update rsrc_update;
891 struct io_fadvise fadvise;
892 struct io_madvise madvise;
893 struct io_epoll epoll;
894 struct io_splice splice;
895 struct io_provide_buf pbuf;
896 struct io_statx statx;
897 struct io_shutdown shutdown;
898 struct io_rename rename;
899 struct io_unlink unlink;
900 struct io_mkdir mkdir;
901 struct io_symlink symlink;
902 struct io_hardlink hardlink;
907 /* polled IO has completed */
914 /* fd initially, then cflags for completion */
920 struct io_ring_ctx *ctx;
921 struct task_struct *task;
923 struct percpu_ref *fixed_rsrc_refs;
924 /* store used ubuf, so we can prevent reloading */
925 struct io_mapped_ubuf *imu;
928 /* used by request caches, completion batching and iopoll */
929 struct io_wq_work_node comp_list;
930 /* cache ->apoll->events */
935 struct io_task_work io_task_work;
936 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
937 struct hlist_node hash_node;
938 /* internal polling, see IORING_FEAT_FAST_POLL */
939 struct async_poll *apoll;
940 /* opcode allocated if it needs to store data for async defer */
942 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
943 struct io_buffer *kbuf;
944 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
945 struct io_kiocb *link;
946 /* custom credentials, valid IFF REQ_F_CREDS is set */
947 const struct cred *creds;
948 struct io_wq_work work;
951 struct io_tctx_node {
952 struct list_head ctx_node;
953 struct task_struct *task;
954 struct io_ring_ctx *ctx;
957 struct io_defer_entry {
958 struct list_head list;
959 struct io_kiocb *req;
964 /* needs req->file assigned */
965 unsigned needs_file : 1;
966 /* should block plug */
968 /* hash wq insertion if file is a regular file */
969 unsigned hash_reg_file : 1;
970 /* unbound wq insertion if file is a non-regular file */
971 unsigned unbound_nonreg_file : 1;
972 /* set if opcode supports polled "wait" */
974 unsigned pollout : 1;
975 unsigned poll_exclusive : 1;
976 /* op supports buffer selection */
977 unsigned buffer_select : 1;
978 /* do prep async if is going to be punted */
979 unsigned needs_async_setup : 1;
980 /* opcode is not supported by this kernel */
981 unsigned not_supported : 1;
983 unsigned audit_skip : 1;
984 /* size of async data needed, if any */
985 unsigned short async_size;
988 static const struct io_op_def io_op_defs[] = {
989 [IORING_OP_NOP] = {},
990 [IORING_OP_READV] = {
992 .unbound_nonreg_file = 1,
995 .needs_async_setup = 1,
998 .async_size = sizeof(struct io_async_rw),
1000 [IORING_OP_WRITEV] = {
1003 .unbound_nonreg_file = 1,
1005 .needs_async_setup = 1,
1008 .async_size = sizeof(struct io_async_rw),
1010 [IORING_OP_FSYNC] = {
1014 [IORING_OP_READ_FIXED] = {
1016 .unbound_nonreg_file = 1,
1020 .async_size = sizeof(struct io_async_rw),
1022 [IORING_OP_WRITE_FIXED] = {
1025 .unbound_nonreg_file = 1,
1029 .async_size = sizeof(struct io_async_rw),
1031 [IORING_OP_POLL_ADD] = {
1033 .unbound_nonreg_file = 1,
1036 [IORING_OP_POLL_REMOVE] = {
1039 [IORING_OP_SYNC_FILE_RANGE] = {
1043 [IORING_OP_SENDMSG] = {
1045 .unbound_nonreg_file = 1,
1047 .needs_async_setup = 1,
1048 .async_size = sizeof(struct io_async_msghdr),
1050 [IORING_OP_RECVMSG] = {
1052 .unbound_nonreg_file = 1,
1055 .needs_async_setup = 1,
1056 .async_size = sizeof(struct io_async_msghdr),
1058 [IORING_OP_TIMEOUT] = {
1060 .async_size = sizeof(struct io_timeout_data),
1062 [IORING_OP_TIMEOUT_REMOVE] = {
1063 /* used by timeout updates' prep() */
1066 [IORING_OP_ACCEPT] = {
1068 .unbound_nonreg_file = 1,
1070 .poll_exclusive = 1,
1072 [IORING_OP_ASYNC_CANCEL] = {
1075 [IORING_OP_LINK_TIMEOUT] = {
1077 .async_size = sizeof(struct io_timeout_data),
1079 [IORING_OP_CONNECT] = {
1081 .unbound_nonreg_file = 1,
1083 .needs_async_setup = 1,
1084 .async_size = sizeof(struct io_async_connect),
1086 [IORING_OP_FALLOCATE] = {
1089 [IORING_OP_OPENAT] = {},
1090 [IORING_OP_CLOSE] = {},
1091 [IORING_OP_FILES_UPDATE] = {
1094 [IORING_OP_STATX] = {
1097 [IORING_OP_READ] = {
1099 .unbound_nonreg_file = 1,
1104 .async_size = sizeof(struct io_async_rw),
1106 [IORING_OP_WRITE] = {
1109 .unbound_nonreg_file = 1,
1113 .async_size = sizeof(struct io_async_rw),
1115 [IORING_OP_FADVISE] = {
1119 [IORING_OP_MADVISE] = {},
1120 [IORING_OP_SEND] = {
1122 .unbound_nonreg_file = 1,
1126 [IORING_OP_RECV] = {
1128 .unbound_nonreg_file = 1,
1133 [IORING_OP_OPENAT2] = {
1135 [IORING_OP_EPOLL_CTL] = {
1136 .unbound_nonreg_file = 1,
1139 [IORING_OP_SPLICE] = {
1142 .unbound_nonreg_file = 1,
1145 [IORING_OP_PROVIDE_BUFFERS] = {
1148 [IORING_OP_REMOVE_BUFFERS] = {
1154 .unbound_nonreg_file = 1,
1157 [IORING_OP_SHUTDOWN] = {
1160 [IORING_OP_RENAMEAT] = {},
1161 [IORING_OP_UNLINKAT] = {},
1162 [IORING_OP_MKDIRAT] = {},
1163 [IORING_OP_SYMLINKAT] = {},
1164 [IORING_OP_LINKAT] = {},
1165 [IORING_OP_MSG_RING] = {
1170 /* requests with any of those set should undergo io_disarm_next() */
1171 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1173 static bool io_disarm_next(struct io_kiocb *req);
1174 static void io_uring_del_tctx_node(unsigned long index);
1175 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1176 struct task_struct *task,
1178 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1180 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1182 static void io_put_req(struct io_kiocb *req);
1183 static void io_put_req_deferred(struct io_kiocb *req);
1184 static void io_dismantle_req(struct io_kiocb *req);
1185 static void io_queue_linked_timeout(struct io_kiocb *req);
1186 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1187 struct io_uring_rsrc_update2 *up,
1189 static void io_clean_op(struct io_kiocb *req);
1190 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1191 unsigned issue_flags);
1192 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1193 static void io_drop_inflight_file(struct io_kiocb *req);
1194 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1195 static void __io_queue_sqe(struct io_kiocb *req);
1196 static void io_rsrc_put_work(struct work_struct *work);
1198 static void io_req_task_queue(struct io_kiocb *req);
1199 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1200 static int io_req_prep_async(struct io_kiocb *req);
1202 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1203 unsigned int issue_flags, u32 slot_index);
1204 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1206 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1207 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1209 static struct kmem_cache *req_cachep;
1211 static const struct file_operations io_uring_fops;
1213 struct sock *io_uring_get_socket(struct file *file)
1215 #if defined(CONFIG_UNIX)
1216 if (file->f_op == &io_uring_fops) {
1217 struct io_ring_ctx *ctx = file->private_data;
1219 return ctx->ring_sock->sk;
1224 EXPORT_SYMBOL(io_uring_get_socket);
1226 #if defined(CONFIG_UNIX)
1227 static inline bool io_file_need_scm(struct file *filp)
1229 return !!unix_get_socket(filp);
1232 static inline bool io_file_need_scm(struct file *filp)
1238 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1240 lockdep_assert_held(&ctx->uring_lock);
1241 if (issue_flags & IO_URING_F_UNLOCKED)
1242 mutex_unlock(&ctx->uring_lock);
1245 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1248 * "Normal" inline submissions always hold the uring_lock, since we
1249 * grab it from the system call. Same is true for the SQPOLL offload.
1250 * The only exception is when we've detached the request and issue it
1251 * from an async worker thread, grab the lock for that case.
1253 if (issue_flags & IO_URING_F_UNLOCKED)
1254 mutex_lock(&ctx->uring_lock);
1255 lockdep_assert_held(&ctx->uring_lock);
1258 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1261 mutex_lock(&ctx->uring_lock);
1266 #define io_for_each_link(pos, head) \
1267 for (pos = (head); pos; pos = pos->link)
1270 * Shamelessly stolen from the mm implementation of page reference checking,
1271 * see commit f958d7b528b1 for details.
1273 #define req_ref_zero_or_close_to_overflow(req) \
1274 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1276 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1278 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1279 return atomic_inc_not_zero(&req->refs);
1282 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1284 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1287 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1288 return atomic_dec_and_test(&req->refs);
1291 static inline void req_ref_get(struct io_kiocb *req)
1293 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1294 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1295 atomic_inc(&req->refs);
1298 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1300 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1301 __io_submit_flush_completions(ctx);
1304 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1306 if (!(req->flags & REQ_F_REFCOUNT)) {
1307 req->flags |= REQ_F_REFCOUNT;
1308 atomic_set(&req->refs, nr);
1312 static inline void io_req_set_refcount(struct io_kiocb *req)
1314 __io_req_set_refcount(req, 1);
1317 #define IO_RSRC_REF_BATCH 100
1319 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1320 struct io_ring_ctx *ctx)
1321 __must_hold(&ctx->uring_lock)
1323 struct percpu_ref *ref = req->fixed_rsrc_refs;
1326 if (ref == &ctx->rsrc_node->refs)
1327 ctx->rsrc_cached_refs++;
1329 percpu_ref_put(ref);
1333 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1335 if (req->fixed_rsrc_refs)
1336 percpu_ref_put(req->fixed_rsrc_refs);
1339 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1340 __must_hold(&ctx->uring_lock)
1342 if (ctx->rsrc_cached_refs) {
1343 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1344 ctx->rsrc_cached_refs = 0;
1348 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1349 __must_hold(&ctx->uring_lock)
1351 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1352 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1355 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1356 struct io_ring_ctx *ctx,
1357 unsigned int issue_flags)
1359 if (!req->fixed_rsrc_refs) {
1360 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1362 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1363 lockdep_assert_held(&ctx->uring_lock);
1364 ctx->rsrc_cached_refs--;
1365 if (unlikely(ctx->rsrc_cached_refs < 0))
1366 io_rsrc_refs_refill(ctx);
1368 percpu_ref_get(req->fixed_rsrc_refs);
1373 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1375 struct io_buffer *kbuf = req->kbuf;
1376 unsigned int cflags;
1378 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1379 req->flags &= ~REQ_F_BUFFER_SELECTED;
1380 list_add(&kbuf->list, list);
1385 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1387 lockdep_assert_held(&req->ctx->completion_lock);
1389 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1391 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1394 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1395 unsigned issue_flags)
1397 unsigned int cflags;
1399 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1403 * We can add this buffer back to two lists:
1405 * 1) The io_buffers_cache list. This one is protected by the
1406 * ctx->uring_lock. If we already hold this lock, add back to this
1407 * list as we can grab it from issue as well.
1408 * 2) The io_buffers_comp list. This one is protected by the
1409 * ctx->completion_lock.
1411 * We migrate buffers from the comp_list to the issue cache list
1414 if (issue_flags & IO_URING_F_UNLOCKED) {
1415 struct io_ring_ctx *ctx = req->ctx;
1417 spin_lock(&ctx->completion_lock);
1418 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1419 spin_unlock(&ctx->completion_lock);
1421 lockdep_assert_held(&req->ctx->uring_lock);
1423 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1429 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1432 struct list_head *hash_list;
1433 struct io_buffer_list *bl;
1435 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1436 list_for_each_entry(bl, hash_list, list)
1437 if (bl->bgid == bgid || bgid == -1U)
1443 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1445 struct io_ring_ctx *ctx = req->ctx;
1446 struct io_buffer_list *bl;
1447 struct io_buffer *buf;
1449 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1451 /* don't recycle if we already did IO to this buffer */
1452 if (req->flags & REQ_F_PARTIAL_IO)
1455 io_ring_submit_lock(ctx, issue_flags);
1458 bl = io_buffer_get_list(ctx, buf->bgid);
1459 list_add(&buf->list, &bl->buf_list);
1460 req->flags &= ~REQ_F_BUFFER_SELECTED;
1463 io_ring_submit_unlock(ctx, issue_flags);
1466 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1468 __must_hold(&req->ctx->timeout_lock)
1470 if (task && head->task != task)
1476 * As io_match_task() but protected against racing with linked timeouts.
1477 * User must not hold timeout_lock.
1479 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1482 if (task && head->task != task)
1487 static inline bool req_has_async_data(struct io_kiocb *req)
1489 return req->flags & REQ_F_ASYNC_DATA;
1492 static inline void req_set_fail(struct io_kiocb *req)
1494 req->flags |= REQ_F_FAIL;
1495 if (req->flags & REQ_F_CQE_SKIP) {
1496 req->flags &= ~REQ_F_CQE_SKIP;
1497 req->flags |= REQ_F_SKIP_LINK_CQES;
1501 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1507 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1509 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1511 complete(&ctx->ref_comp);
1514 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1516 return !req->timeout.off;
1519 static __cold void io_fallback_req_func(struct work_struct *work)
1521 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1522 fallback_work.work);
1523 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1524 struct io_kiocb *req, *tmp;
1525 bool locked = false;
1527 percpu_ref_get(&ctx->refs);
1528 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1529 req->io_task_work.func(req, &locked);
1532 io_submit_flush_completions(ctx);
1533 mutex_unlock(&ctx->uring_lock);
1535 percpu_ref_put(&ctx->refs);
1538 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1540 struct io_ring_ctx *ctx;
1543 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1548 * Use 5 bits less than the max cq entries, that should give us around
1549 * 32 entries per hash list if totally full and uniformly spread.
1551 hash_bits = ilog2(p->cq_entries);
1555 ctx->cancel_hash_bits = hash_bits;
1556 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1558 if (!ctx->cancel_hash)
1560 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1562 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1563 if (!ctx->dummy_ubuf)
1565 /* set invalid range, so io_import_fixed() fails meeting it */
1566 ctx->dummy_ubuf->ubuf = -1UL;
1568 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1569 sizeof(struct list_head), GFP_KERNEL);
1570 if (!ctx->io_buffers)
1572 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1573 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1575 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1576 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1579 ctx->flags = p->flags;
1580 init_waitqueue_head(&ctx->sqo_sq_wait);
1581 INIT_LIST_HEAD(&ctx->sqd_list);
1582 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1583 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1584 INIT_LIST_HEAD(&ctx->apoll_cache);
1585 init_completion(&ctx->ref_comp);
1586 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1587 mutex_init(&ctx->uring_lock);
1588 init_waitqueue_head(&ctx->cq_wait);
1589 spin_lock_init(&ctx->completion_lock);
1590 spin_lock_init(&ctx->timeout_lock);
1591 INIT_WQ_LIST(&ctx->iopoll_list);
1592 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1593 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1594 INIT_LIST_HEAD(&ctx->defer_list);
1595 INIT_LIST_HEAD(&ctx->timeout_list);
1596 INIT_LIST_HEAD(&ctx->ltimeout_list);
1597 spin_lock_init(&ctx->rsrc_ref_lock);
1598 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1599 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1600 init_llist_head(&ctx->rsrc_put_llist);
1601 INIT_LIST_HEAD(&ctx->tctx_list);
1602 ctx->submit_state.free_list.next = NULL;
1603 INIT_WQ_LIST(&ctx->locked_free_list);
1604 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1605 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1608 kfree(ctx->dummy_ubuf);
1609 kfree(ctx->cancel_hash);
1610 kfree(ctx->io_buffers);
1615 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1617 struct io_rings *r = ctx->rings;
1619 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1623 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1625 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1626 struct io_ring_ctx *ctx = req->ctx;
1628 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1634 #define FFS_NOWAIT 0x1UL
1635 #define FFS_ISREG 0x2UL
1636 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1638 static inline bool io_req_ffs_set(struct io_kiocb *req)
1640 return req->flags & REQ_F_FIXED_FILE;
1643 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1645 if (WARN_ON_ONCE(!req->link))
1648 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1649 req->flags |= REQ_F_LINK_TIMEOUT;
1651 /* linked timeouts should have two refs once prep'ed */
1652 io_req_set_refcount(req);
1653 __io_req_set_refcount(req->link, 2);
1657 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1659 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1661 return __io_prep_linked_timeout(req);
1664 static void io_prep_async_work(struct io_kiocb *req)
1666 const struct io_op_def *def = &io_op_defs[req->opcode];
1667 struct io_ring_ctx *ctx = req->ctx;
1669 if (!(req->flags & REQ_F_CREDS)) {
1670 req->flags |= REQ_F_CREDS;
1671 req->creds = get_current_cred();
1674 req->work.list.next = NULL;
1675 req->work.flags = 0;
1676 if (req->flags & REQ_F_FORCE_ASYNC)
1677 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1679 if (req->flags & REQ_F_ISREG) {
1680 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1681 io_wq_hash_work(&req->work, file_inode(req->file));
1682 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1683 if (def->unbound_nonreg_file)
1684 req->work.flags |= IO_WQ_WORK_UNBOUND;
1688 static void io_prep_async_link(struct io_kiocb *req)
1690 struct io_kiocb *cur;
1692 if (req->flags & REQ_F_LINK_TIMEOUT) {
1693 struct io_ring_ctx *ctx = req->ctx;
1695 spin_lock_irq(&ctx->timeout_lock);
1696 io_for_each_link(cur, req)
1697 io_prep_async_work(cur);
1698 spin_unlock_irq(&ctx->timeout_lock);
1700 io_for_each_link(cur, req)
1701 io_prep_async_work(cur);
1705 static inline void io_req_add_compl_list(struct io_kiocb *req)
1707 struct io_submit_state *state = &req->ctx->submit_state;
1709 if (!(req->flags & REQ_F_CQE_SKIP))
1710 state->flush_cqes = true;
1711 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1714 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1716 struct io_ring_ctx *ctx = req->ctx;
1717 struct io_kiocb *link = io_prep_linked_timeout(req);
1718 struct io_uring_task *tctx = req->task->io_uring;
1721 BUG_ON(!tctx->io_wq);
1723 /* init ->work of the whole link before punting */
1724 io_prep_async_link(req);
1727 * Not expected to happen, but if we do have a bug where this _can_
1728 * happen, catch it here and ensure the request is marked as
1729 * canceled. That will make io-wq go through the usual work cancel
1730 * procedure rather than attempt to run this request (or create a new
1733 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1734 req->work.flags |= IO_WQ_WORK_CANCEL;
1736 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1737 &req->work, io_wq_is_hashed(&req->work));
1738 io_wq_enqueue(tctx->io_wq, &req->work);
1740 io_queue_linked_timeout(link);
1743 static void io_kill_timeout(struct io_kiocb *req, int status)
1744 __must_hold(&req->ctx->completion_lock)
1745 __must_hold(&req->ctx->timeout_lock)
1747 struct io_timeout_data *io = req->async_data;
1749 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1752 atomic_set(&req->ctx->cq_timeouts,
1753 atomic_read(&req->ctx->cq_timeouts) + 1);
1754 list_del_init(&req->timeout.list);
1755 io_fill_cqe_req(req, status, 0);
1756 io_put_req_deferred(req);
1760 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1762 while (!list_empty(&ctx->defer_list)) {
1763 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1764 struct io_defer_entry, list);
1766 if (req_need_defer(de->req, de->seq))
1768 list_del_init(&de->list);
1769 io_req_task_queue(de->req);
1774 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1775 __must_hold(&ctx->completion_lock)
1777 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1778 struct io_kiocb *req, *tmp;
1780 spin_lock_irq(&ctx->timeout_lock);
1781 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1782 u32 events_needed, events_got;
1784 if (io_is_timeout_noseq(req))
1788 * Since seq can easily wrap around over time, subtract
1789 * the last seq at which timeouts were flushed before comparing.
1790 * Assuming not more than 2^31-1 events have happened since,
1791 * these subtractions won't have wrapped, so we can check if
1792 * target is in [last_seq, current_seq] by comparing the two.
1794 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1795 events_got = seq - ctx->cq_last_tm_flush;
1796 if (events_got < events_needed)
1799 io_kill_timeout(req, 0);
1801 ctx->cq_last_tm_flush = seq;
1802 spin_unlock_irq(&ctx->timeout_lock);
1805 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1807 /* order cqe stores with ring update */
1808 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1811 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1813 if (ctx->off_timeout_used || ctx->drain_active) {
1814 spin_lock(&ctx->completion_lock);
1815 if (ctx->off_timeout_used)
1816 io_flush_timeouts(ctx);
1817 if (ctx->drain_active)
1818 io_queue_deferred(ctx);
1819 io_commit_cqring(ctx);
1820 spin_unlock(&ctx->completion_lock);
1823 io_eventfd_signal(ctx);
1826 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1828 struct io_rings *r = ctx->rings;
1830 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1833 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1835 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1838 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1840 struct io_rings *rings = ctx->rings;
1841 unsigned tail, mask = ctx->cq_entries - 1;
1844 * writes to the cq entry need to come after reading head; the
1845 * control dependency is enough as we're using WRITE_ONCE to
1848 if (__io_cqring_events(ctx) == ctx->cq_entries)
1851 tail = ctx->cached_cq_tail++;
1852 return &rings->cqes[tail & mask];
1855 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1857 struct io_ev_fd *ev_fd;
1861 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1862 * and eventfd_signal
1864 ev_fd = rcu_dereference(ctx->io_ev_fd);
1867 * Check again if ev_fd exists incase an io_eventfd_unregister call
1868 * completed between the NULL check of ctx->io_ev_fd at the start of
1869 * the function and rcu_read_lock.
1871 if (unlikely(!ev_fd))
1873 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1876 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1877 eventfd_signal(ev_fd->cq_ev_fd, 1);
1882 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1885 * wake_up_all() may seem excessive, but io_wake_function() and
1886 * io_should_wake() handle the termination of the loop and only
1887 * wake as many waiters as we need to.
1889 if (wq_has_sleeper(&ctx->cq_wait))
1890 wake_up_all(&ctx->cq_wait);
1894 * This should only get called when at least one event has been posted.
1895 * Some applications rely on the eventfd notification count only changing
1896 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1897 * 1:1 relationship between how many times this function is called (and
1898 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1900 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1902 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1904 __io_commit_cqring_flush(ctx);
1906 io_cqring_wake(ctx);
1909 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1911 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1913 __io_commit_cqring_flush(ctx);
1915 if (ctx->flags & IORING_SETUP_SQPOLL)
1916 io_cqring_wake(ctx);
1919 /* Returns true if there are no backlogged entries after the flush */
1920 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1922 bool all_flushed, posted;
1924 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1928 spin_lock(&ctx->completion_lock);
1929 while (!list_empty(&ctx->cq_overflow_list)) {
1930 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1931 struct io_overflow_cqe *ocqe;
1935 ocqe = list_first_entry(&ctx->cq_overflow_list,
1936 struct io_overflow_cqe, list);
1938 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1940 io_account_cq_overflow(ctx);
1943 list_del(&ocqe->list);
1947 all_flushed = list_empty(&ctx->cq_overflow_list);
1949 clear_bit(0, &ctx->check_cq_overflow);
1950 WRITE_ONCE(ctx->rings->sq_flags,
1951 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1954 io_commit_cqring(ctx);
1955 spin_unlock(&ctx->completion_lock);
1957 io_cqring_ev_posted(ctx);
1961 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1965 if (test_bit(0, &ctx->check_cq_overflow)) {
1966 /* iopoll syncs against uring_lock, not completion_lock */
1967 if (ctx->flags & IORING_SETUP_IOPOLL)
1968 mutex_lock(&ctx->uring_lock);
1969 ret = __io_cqring_overflow_flush(ctx, false);
1970 if (ctx->flags & IORING_SETUP_IOPOLL)
1971 mutex_unlock(&ctx->uring_lock);
1977 static void __io_put_task(struct task_struct *task, int nr)
1979 struct io_uring_task *tctx = task->io_uring;
1981 percpu_counter_sub(&tctx->inflight, nr);
1982 if (unlikely(atomic_read(&tctx->in_idle)))
1983 wake_up(&tctx->wait);
1984 put_task_struct_many(task, nr);
1987 /* must to be called somewhat shortly after putting a request */
1988 static inline void io_put_task(struct task_struct *task, int nr)
1990 if (likely(task == current))
1991 task->io_uring->cached_refs += nr;
1993 __io_put_task(task, nr);
1996 static void io_task_refs_refill(struct io_uring_task *tctx)
1998 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2000 percpu_counter_add(&tctx->inflight, refill);
2001 refcount_add(refill, ¤t->usage);
2002 tctx->cached_refs += refill;
2005 static inline void io_get_task_refs(int nr)
2007 struct io_uring_task *tctx = current->io_uring;
2009 tctx->cached_refs -= nr;
2010 if (unlikely(tctx->cached_refs < 0))
2011 io_task_refs_refill(tctx);
2014 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2016 struct io_uring_task *tctx = task->io_uring;
2017 unsigned int refs = tctx->cached_refs;
2020 tctx->cached_refs = 0;
2021 percpu_counter_sub(&tctx->inflight, refs);
2022 put_task_struct_many(task, refs);
2026 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2027 s32 res, u32 cflags)
2029 struct io_overflow_cqe *ocqe;
2031 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2034 * If we're in ring overflow flush mode, or in task cancel mode,
2035 * or cannot allocate an overflow entry, then we need to drop it
2038 io_account_cq_overflow(ctx);
2041 if (list_empty(&ctx->cq_overflow_list)) {
2042 set_bit(0, &ctx->check_cq_overflow);
2043 WRITE_ONCE(ctx->rings->sq_flags,
2044 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2047 ocqe->cqe.user_data = user_data;
2048 ocqe->cqe.res = res;
2049 ocqe->cqe.flags = cflags;
2050 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2054 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2055 s32 res, u32 cflags)
2057 struct io_uring_cqe *cqe;
2060 * If we can't get a cq entry, userspace overflowed the
2061 * submission (by quite a lot). Increment the overflow count in
2064 cqe = io_get_cqe(ctx);
2066 WRITE_ONCE(cqe->user_data, user_data);
2067 WRITE_ONCE(cqe->res, res);
2068 WRITE_ONCE(cqe->flags, cflags);
2071 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2074 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2076 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2077 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
2080 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2082 if (!(req->flags & REQ_F_CQE_SKIP))
2083 __io_fill_cqe_req(req, res, cflags);
2086 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2087 s32 res, u32 cflags)
2090 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2091 return __io_fill_cqe(ctx, user_data, res, cflags);
2094 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2097 struct io_ring_ctx *ctx = req->ctx;
2099 if (!(req->flags & REQ_F_CQE_SKIP))
2100 __io_fill_cqe_req(req, res, cflags);
2102 * If we're the last reference to this request, add to our locked
2105 if (req_ref_put_and_test(req)) {
2106 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2107 if (req->flags & IO_DISARM_MASK)
2108 io_disarm_next(req);
2110 io_req_task_queue(req->link);
2114 io_req_put_rsrc(req, ctx);
2116 * Selected buffer deallocation in io_clean_op() assumes that
2117 * we don't hold ->completion_lock. Clean them here to avoid
2120 io_put_kbuf_comp(req);
2121 io_dismantle_req(req);
2122 io_put_task(req->task, 1);
2123 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2124 ctx->locked_free_nr++;
2128 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2131 struct io_ring_ctx *ctx = req->ctx;
2133 spin_lock(&ctx->completion_lock);
2134 __io_req_complete_post(req, res, cflags);
2135 io_commit_cqring(ctx);
2136 spin_unlock(&ctx->completion_lock);
2137 io_cqring_ev_posted(ctx);
2140 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2144 req->cflags = cflags;
2145 req->flags |= REQ_F_COMPLETE_INLINE;
2148 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2149 s32 res, u32 cflags)
2151 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2152 io_req_complete_state(req, res, cflags);
2154 io_req_complete_post(req, res, cflags);
2157 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2159 __io_req_complete(req, 0, res, 0);
2162 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2165 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2168 static void io_req_complete_fail_submit(struct io_kiocb *req)
2171 * We don't submit, fail them all, for that replace hardlinks with
2172 * normal links. Extra REQ_F_LINK is tolerated.
2174 req->flags &= ~REQ_F_HARDLINK;
2175 req->flags |= REQ_F_LINK;
2176 io_req_complete_failed(req, req->result);
2180 * Don't initialise the fields below on every allocation, but do that in
2181 * advance and keep them valid across allocations.
2183 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2187 req->async_data = NULL;
2188 /* not necessary, but safer to zero */
2192 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2193 struct io_submit_state *state)
2195 spin_lock(&ctx->completion_lock);
2196 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2197 ctx->locked_free_nr = 0;
2198 spin_unlock(&ctx->completion_lock);
2201 /* Returns true IFF there are requests in the cache */
2202 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2204 struct io_submit_state *state = &ctx->submit_state;
2207 * If we have more than a batch's worth of requests in our IRQ side
2208 * locked cache, grab the lock and move them over to our submission
2211 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2212 io_flush_cached_locked_reqs(ctx, state);
2213 return !!state->free_list.next;
2217 * A request might get retired back into the request caches even before opcode
2218 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2219 * Because of that, io_alloc_req() should be called only under ->uring_lock
2220 * and with extra caution to not get a request that is still worked on.
2222 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2223 __must_hold(&ctx->uring_lock)
2225 struct io_submit_state *state = &ctx->submit_state;
2226 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2227 void *reqs[IO_REQ_ALLOC_BATCH];
2228 struct io_kiocb *req;
2231 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2234 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2237 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2238 * retry single alloc to be on the safe side.
2240 if (unlikely(ret <= 0)) {
2241 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2247 percpu_ref_get_many(&ctx->refs, ret);
2248 for (i = 0; i < ret; i++) {
2251 io_preinit_req(req, ctx);
2252 wq_stack_add_head(&req->comp_list, &state->free_list);
2257 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2259 if (unlikely(!ctx->submit_state.free_list.next))
2260 return __io_alloc_req_refill(ctx);
2264 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2266 struct io_wq_work_node *node;
2268 node = wq_stack_extract(&ctx->submit_state.free_list);
2269 return container_of(node, struct io_kiocb, comp_list);
2272 static inline void io_put_file(struct file *file)
2278 static inline void io_dismantle_req(struct io_kiocb *req)
2280 unsigned int flags = req->flags;
2282 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2284 if (!(flags & REQ_F_FIXED_FILE))
2285 io_put_file(req->file);
2288 static __cold void __io_free_req(struct io_kiocb *req)
2290 struct io_ring_ctx *ctx = req->ctx;
2292 io_req_put_rsrc(req, ctx);
2293 io_dismantle_req(req);
2294 io_put_task(req->task, 1);
2296 spin_lock(&ctx->completion_lock);
2297 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2298 ctx->locked_free_nr++;
2299 spin_unlock(&ctx->completion_lock);
2302 static inline void io_remove_next_linked(struct io_kiocb *req)
2304 struct io_kiocb *nxt = req->link;
2306 req->link = nxt->link;
2310 static bool io_kill_linked_timeout(struct io_kiocb *req)
2311 __must_hold(&req->ctx->completion_lock)
2312 __must_hold(&req->ctx->timeout_lock)
2314 struct io_kiocb *link = req->link;
2316 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2317 struct io_timeout_data *io = link->async_data;
2319 io_remove_next_linked(req);
2320 link->timeout.head = NULL;
2321 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2322 list_del(&link->timeout.list);
2323 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2324 io_fill_cqe_req(link, -ECANCELED, 0);
2325 io_put_req_deferred(link);
2332 static void io_fail_links(struct io_kiocb *req)
2333 __must_hold(&req->ctx->completion_lock)
2335 struct io_kiocb *nxt, *link = req->link;
2336 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2340 long res = -ECANCELED;
2342 if (link->flags & REQ_F_FAIL)
2348 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2352 link->flags &= ~REQ_F_CQE_SKIP;
2353 io_fill_cqe_req(link, res, 0);
2355 io_put_req_deferred(link);
2360 static bool io_disarm_next(struct io_kiocb *req)
2361 __must_hold(&req->ctx->completion_lock)
2363 bool posted = false;
2365 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2366 struct io_kiocb *link = req->link;
2368 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2369 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2370 io_remove_next_linked(req);
2371 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2372 io_fill_cqe_req(link, -ECANCELED, 0);
2373 io_put_req_deferred(link);
2376 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2377 struct io_ring_ctx *ctx = req->ctx;
2379 spin_lock_irq(&ctx->timeout_lock);
2380 posted = io_kill_linked_timeout(req);
2381 spin_unlock_irq(&ctx->timeout_lock);
2383 if (unlikely((req->flags & REQ_F_FAIL) &&
2384 !(req->flags & REQ_F_HARDLINK))) {
2385 posted |= (req->link != NULL);
2391 static void __io_req_find_next_prep(struct io_kiocb *req)
2393 struct io_ring_ctx *ctx = req->ctx;
2396 spin_lock(&ctx->completion_lock);
2397 posted = io_disarm_next(req);
2398 io_commit_cqring(ctx);
2399 spin_unlock(&ctx->completion_lock);
2401 io_cqring_ev_posted(ctx);
2404 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2406 struct io_kiocb *nxt;
2409 * If LINK is set, we have dependent requests in this chain. If we
2410 * didn't fail this request, queue the first one up, moving any other
2411 * dependencies to the next request. In case of failure, fail the rest
2414 if (unlikely(req->flags & IO_DISARM_MASK))
2415 __io_req_find_next_prep(req);
2421 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2426 io_submit_flush_completions(ctx);
2427 mutex_unlock(&ctx->uring_lock);
2430 percpu_ref_put(&ctx->refs);
2433 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2435 io_commit_cqring(ctx);
2436 spin_unlock(&ctx->completion_lock);
2437 io_cqring_ev_posted(ctx);
2440 static void handle_prev_tw_list(struct io_wq_work_node *node,
2441 struct io_ring_ctx **ctx, bool *uring_locked)
2443 if (*ctx && !*uring_locked)
2444 spin_lock(&(*ctx)->completion_lock);
2447 struct io_wq_work_node *next = node->next;
2448 struct io_kiocb *req = container_of(node, struct io_kiocb,
2451 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2453 if (req->ctx != *ctx) {
2454 if (unlikely(!*uring_locked && *ctx))
2455 ctx_commit_and_unlock(*ctx);
2457 ctx_flush_and_put(*ctx, uring_locked);
2459 /* if not contended, grab and improve batching */
2460 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2461 percpu_ref_get(&(*ctx)->refs);
2462 if (unlikely(!*uring_locked))
2463 spin_lock(&(*ctx)->completion_lock);
2465 if (likely(*uring_locked))
2466 req->io_task_work.func(req, uring_locked);
2468 __io_req_complete_post(req, req->result,
2469 io_put_kbuf_comp(req));
2473 if (unlikely(!*uring_locked))
2474 ctx_commit_and_unlock(*ctx);
2477 static void handle_tw_list(struct io_wq_work_node *node,
2478 struct io_ring_ctx **ctx, bool *locked)
2481 struct io_wq_work_node *next = node->next;
2482 struct io_kiocb *req = container_of(node, struct io_kiocb,
2485 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2487 if (req->ctx != *ctx) {
2488 ctx_flush_and_put(*ctx, locked);
2490 /* if not contended, grab and improve batching */
2491 *locked = mutex_trylock(&(*ctx)->uring_lock);
2492 percpu_ref_get(&(*ctx)->refs);
2494 req->io_task_work.func(req, locked);
2499 static void tctx_task_work(struct callback_head *cb)
2501 bool uring_locked = false;
2502 struct io_ring_ctx *ctx = NULL;
2503 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2507 struct io_wq_work_node *node1, *node2;
2509 spin_lock_irq(&tctx->task_lock);
2510 node1 = tctx->prior_task_list.first;
2511 node2 = tctx->task_list.first;
2512 INIT_WQ_LIST(&tctx->task_list);
2513 INIT_WQ_LIST(&tctx->prior_task_list);
2514 if (!node2 && !node1)
2515 tctx->task_running = false;
2516 spin_unlock_irq(&tctx->task_lock);
2517 if (!node2 && !node1)
2521 handle_prev_tw_list(node1, &ctx, &uring_locked);
2523 handle_tw_list(node2, &ctx, &uring_locked);
2526 if (!tctx->task_list.first &&
2527 !tctx->prior_task_list.first && uring_locked)
2528 io_submit_flush_completions(ctx);
2531 ctx_flush_and_put(ctx, &uring_locked);
2533 /* relaxed read is enough as only the task itself sets ->in_idle */
2534 if (unlikely(atomic_read(&tctx->in_idle)))
2535 io_uring_drop_tctx_refs(current);
2538 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2540 struct task_struct *tsk = req->task;
2541 struct io_uring_task *tctx = tsk->io_uring;
2542 enum task_work_notify_mode notify;
2543 struct io_wq_work_node *node;
2544 unsigned long flags;
2547 WARN_ON_ONCE(!tctx);
2549 io_drop_inflight_file(req);
2551 spin_lock_irqsave(&tctx->task_lock, flags);
2553 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2555 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2556 running = tctx->task_running;
2558 tctx->task_running = true;
2559 spin_unlock_irqrestore(&tctx->task_lock, flags);
2561 /* task_work already pending, we're done */
2566 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2567 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2568 * processing task_work. There's no reliable way to tell if TWA_RESUME
2571 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2572 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2573 if (notify == TWA_NONE)
2574 wake_up_process(tsk);
2578 spin_lock_irqsave(&tctx->task_lock, flags);
2579 tctx->task_running = false;
2580 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2581 spin_unlock_irqrestore(&tctx->task_lock, flags);
2584 req = container_of(node, struct io_kiocb, io_task_work.node);
2586 if (llist_add(&req->io_task_work.fallback_node,
2587 &req->ctx->fallback_llist))
2588 schedule_delayed_work(&req->ctx->fallback_work, 1);
2592 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2594 struct io_ring_ctx *ctx = req->ctx;
2596 /* not needed for normal modes, but SQPOLL depends on it */
2597 io_tw_lock(ctx, locked);
2598 io_req_complete_failed(req, req->result);
2601 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2603 struct io_ring_ctx *ctx = req->ctx;
2605 io_tw_lock(ctx, locked);
2606 /* req->task == current here, checking PF_EXITING is safe */
2607 if (likely(!(req->task->flags & PF_EXITING)))
2608 __io_queue_sqe(req);
2610 io_req_complete_failed(req, -EFAULT);
2613 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2616 req->io_task_work.func = io_req_task_cancel;
2617 io_req_task_work_add(req, false);
2620 static void io_req_task_queue(struct io_kiocb *req)
2622 req->io_task_work.func = io_req_task_submit;
2623 io_req_task_work_add(req, false);
2626 static void io_req_task_queue_reissue(struct io_kiocb *req)
2628 req->io_task_work.func = io_queue_async_work;
2629 io_req_task_work_add(req, false);
2632 static void io_queue_next(struct io_kiocb *req)
2634 struct io_kiocb *nxt = io_req_find_next(req);
2637 io_req_task_queue(nxt);
2640 static void io_free_req(struct io_kiocb *req)
2646 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2651 static void io_free_batch_list(struct io_ring_ctx *ctx,
2652 struct io_wq_work_node *node)
2653 __must_hold(&ctx->uring_lock)
2655 struct task_struct *task = NULL;
2659 struct io_kiocb *req = container_of(node, struct io_kiocb,
2662 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2663 if (req->flags & REQ_F_REFCOUNT) {
2664 node = req->comp_list.next;
2665 if (!req_ref_put_and_test(req))
2668 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2669 struct async_poll *apoll = req->apoll;
2671 if (apoll->double_poll)
2672 kfree(apoll->double_poll);
2673 list_add(&apoll->poll.wait.entry,
2675 req->flags &= ~REQ_F_POLLED;
2677 if (req->flags & (REQ_F_LINK|REQ_F_HARDLINK))
2679 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2682 if (!(req->flags & REQ_F_FIXED_FILE))
2683 io_put_file(req->file);
2685 io_req_put_rsrc_locked(req, ctx);
2687 if (req->task != task) {
2689 io_put_task(task, task_refs);
2694 node = req->comp_list.next;
2695 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2699 io_put_task(task, task_refs);
2702 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2703 __must_hold(&ctx->uring_lock)
2705 struct io_wq_work_node *node, *prev;
2706 struct io_submit_state *state = &ctx->submit_state;
2708 if (state->flush_cqes) {
2709 spin_lock(&ctx->completion_lock);
2710 wq_list_for_each(node, prev, &state->compl_reqs) {
2711 struct io_kiocb *req = container_of(node, struct io_kiocb,
2714 if (!(req->flags & REQ_F_CQE_SKIP))
2715 __io_fill_cqe_req(req, req->result, req->cflags);
2718 io_commit_cqring(ctx);
2719 spin_unlock(&ctx->completion_lock);
2720 io_cqring_ev_posted(ctx);
2721 state->flush_cqes = false;
2724 io_free_batch_list(ctx, state->compl_reqs.first);
2725 INIT_WQ_LIST(&state->compl_reqs);
2729 * Drop reference to request, return next in chain (if there is one) if this
2730 * was the last reference to this request.
2732 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2734 struct io_kiocb *nxt = NULL;
2736 if (req_ref_put_and_test(req)) {
2737 if (unlikely(req->flags & (REQ_F_LINK|REQ_F_HARDLINK)))
2738 nxt = io_req_find_next(req);
2744 static inline void io_put_req(struct io_kiocb *req)
2746 if (req_ref_put_and_test(req))
2750 static inline void io_put_req_deferred(struct io_kiocb *req)
2752 if (req_ref_put_and_test(req)) {
2753 req->io_task_work.func = io_free_req_work;
2754 io_req_task_work_add(req, false);
2758 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2760 /* See comment at the top of this file */
2762 return __io_cqring_events(ctx);
2765 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2767 struct io_rings *rings = ctx->rings;
2769 /* make sure SQ entry isn't read before tail */
2770 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2773 static inline bool io_run_task_work(void)
2775 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2776 __set_current_state(TASK_RUNNING);
2777 clear_notify_signal();
2778 if (task_work_pending(current))
2786 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2788 struct io_wq_work_node *pos, *start, *prev;
2789 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2790 DEFINE_IO_COMP_BATCH(iob);
2794 * Only spin for completions if we don't have multiple devices hanging
2795 * off our complete list.
2797 if (ctx->poll_multi_queue || force_nonspin)
2798 poll_flags |= BLK_POLL_ONESHOT;
2800 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2801 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2802 struct kiocb *kiocb = &req->rw.kiocb;
2806 * Move completed and retryable entries to our local lists.
2807 * If we find a request that requires polling, break out
2808 * and complete those lists first, if we have entries there.
2810 if (READ_ONCE(req->iopoll_completed))
2813 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2814 if (unlikely(ret < 0))
2817 poll_flags |= BLK_POLL_ONESHOT;
2819 /* iopoll may have completed current req */
2820 if (!rq_list_empty(iob.req_list) ||
2821 READ_ONCE(req->iopoll_completed))
2825 if (!rq_list_empty(iob.req_list))
2831 wq_list_for_each_resume(pos, prev) {
2832 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2834 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2835 if (!smp_load_acquire(&req->iopoll_completed))
2838 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2840 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
2843 if (unlikely(!nr_events))
2846 io_commit_cqring(ctx);
2847 io_cqring_ev_posted_iopoll(ctx);
2848 pos = start ? start->next : ctx->iopoll_list.first;
2849 wq_list_cut(&ctx->iopoll_list, prev, start);
2850 io_free_batch_list(ctx, pos);
2855 * We can't just wait for polled events to come to us, we have to actively
2856 * find and complete them.
2858 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2860 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2863 mutex_lock(&ctx->uring_lock);
2864 while (!wq_list_empty(&ctx->iopoll_list)) {
2865 /* let it sleep and repeat later if can't complete a request */
2866 if (io_do_iopoll(ctx, true) == 0)
2869 * Ensure we allow local-to-the-cpu processing to take place,
2870 * in this case we need to ensure that we reap all events.
2871 * Also let task_work, etc. to progress by releasing the mutex
2873 if (need_resched()) {
2874 mutex_unlock(&ctx->uring_lock);
2876 mutex_lock(&ctx->uring_lock);
2879 mutex_unlock(&ctx->uring_lock);
2882 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2884 unsigned int nr_events = 0;
2888 * Don't enter poll loop if we already have events pending.
2889 * If we do, we can potentially be spinning for commands that
2890 * already triggered a CQE (eg in error).
2892 if (test_bit(0, &ctx->check_cq_overflow))
2893 __io_cqring_overflow_flush(ctx, false);
2894 if (io_cqring_events(ctx))
2898 * If a submit got punted to a workqueue, we can have the
2899 * application entering polling for a command before it gets
2900 * issued. That app will hold the uring_lock for the duration
2901 * of the poll right here, so we need to take a breather every
2902 * now and then to ensure that the issue has a chance to add
2903 * the poll to the issued list. Otherwise we can spin here
2904 * forever, while the workqueue is stuck trying to acquire the
2907 if (wq_list_empty(&ctx->iopoll_list)) {
2908 u32 tail = ctx->cached_cq_tail;
2910 mutex_unlock(&ctx->uring_lock);
2912 mutex_lock(&ctx->uring_lock);
2914 /* some requests don't go through iopoll_list */
2915 if (tail != ctx->cached_cq_tail ||
2916 wq_list_empty(&ctx->iopoll_list))
2919 ret = io_do_iopoll(ctx, !min);
2924 } while (nr_events < min && !need_resched());
2929 static void kiocb_end_write(struct io_kiocb *req)
2932 * Tell lockdep we inherited freeze protection from submission
2935 if (req->flags & REQ_F_ISREG) {
2936 struct super_block *sb = file_inode(req->file)->i_sb;
2938 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2944 static bool io_resubmit_prep(struct io_kiocb *req)
2946 struct io_async_rw *rw = req->async_data;
2948 if (!req_has_async_data(req))
2949 return !io_req_prep_async(req);
2950 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2954 static bool io_rw_should_reissue(struct io_kiocb *req)
2956 umode_t mode = file_inode(req->file)->i_mode;
2957 struct io_ring_ctx *ctx = req->ctx;
2959 if (!S_ISBLK(mode) && !S_ISREG(mode))
2961 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2962 !(ctx->flags & IORING_SETUP_IOPOLL)))
2965 * If ref is dying, we might be running poll reap from the exit work.
2966 * Don't attempt to reissue from that path, just let it fail with
2969 if (percpu_ref_is_dying(&ctx->refs))
2972 * Play it safe and assume not safe to re-import and reissue if we're
2973 * not in the original thread group (or in task context).
2975 if (!same_thread_group(req->task, current) || !in_task())
2980 static bool io_resubmit_prep(struct io_kiocb *req)
2984 static bool io_rw_should_reissue(struct io_kiocb *req)
2990 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2992 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
2993 kiocb_end_write(req);
2994 fsnotify_modify(req->file);
2996 fsnotify_access(req->file);
2998 if (unlikely(res != req->result)) {
2999 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3000 io_rw_should_reissue(req)) {
3001 req->flags |= REQ_F_REISSUE;
3010 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3012 int res = req->result;
3015 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3016 io_req_add_compl_list(req);
3018 io_req_complete_post(req, res,
3019 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3023 static void __io_complete_rw(struct io_kiocb *req, long res,
3024 unsigned int issue_flags)
3026 if (__io_complete_rw_common(req, res))
3028 __io_req_complete(req, issue_flags, req->result,
3029 io_put_kbuf(req, issue_flags));
3032 static void io_complete_rw(struct kiocb *kiocb, long res)
3034 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3036 if (__io_complete_rw_common(req, res))
3039 req->io_task_work.func = io_req_task_complete;
3040 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3043 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3045 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3047 if (kiocb->ki_flags & IOCB_WRITE)
3048 kiocb_end_write(req);
3049 if (unlikely(res != req->result)) {
3050 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3051 req->flags |= REQ_F_REISSUE;
3057 /* order with io_iopoll_complete() checking ->iopoll_completed */
3058 smp_store_release(&req->iopoll_completed, 1);
3062 * After the iocb has been issued, it's safe to be found on the poll list.
3063 * Adding the kiocb to the list AFTER submission ensures that we don't
3064 * find it from a io_do_iopoll() thread before the issuer is done
3065 * accessing the kiocb cookie.
3067 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3069 struct io_ring_ctx *ctx = req->ctx;
3070 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3072 /* workqueue context doesn't hold uring_lock, grab it now */
3073 if (unlikely(needs_lock))
3074 mutex_lock(&ctx->uring_lock);
3077 * Track whether we have multiple files in our lists. This will impact
3078 * how we do polling eventually, not spinning if we're on potentially
3079 * different devices.
3081 if (wq_list_empty(&ctx->iopoll_list)) {
3082 ctx->poll_multi_queue = false;
3083 } else if (!ctx->poll_multi_queue) {
3084 struct io_kiocb *list_req;
3086 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3088 if (list_req->file != req->file)
3089 ctx->poll_multi_queue = true;
3093 * For fast devices, IO may have already completed. If it has, add
3094 * it to the front so we find it first.
3096 if (READ_ONCE(req->iopoll_completed))
3097 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3099 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3101 if (unlikely(needs_lock)) {
3103 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3104 * in sq thread task context or in io worker task context. If
3105 * current task context is sq thread, we don't need to check
3106 * whether should wake up sq thread.
3108 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3109 wq_has_sleeper(&ctx->sq_data->wait))
3110 wake_up(&ctx->sq_data->wait);
3112 mutex_unlock(&ctx->uring_lock);
3116 static bool io_bdev_nowait(struct block_device *bdev)
3118 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3122 * If we tracked the file through the SCM inflight mechanism, we could support
3123 * any file. For now, just ensure that anything potentially problematic is done
3126 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3128 if (S_ISBLK(mode)) {
3129 if (IS_ENABLED(CONFIG_BLOCK) &&
3130 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3136 if (S_ISREG(mode)) {
3137 if (IS_ENABLED(CONFIG_BLOCK) &&
3138 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3139 file->f_op != &io_uring_fops)
3144 /* any ->read/write should understand O_NONBLOCK */
3145 if (file->f_flags & O_NONBLOCK)
3147 return file->f_mode & FMODE_NOWAIT;
3151 * If we tracked the file through the SCM inflight mechanism, we could support
3152 * any file. For now, just ensure that anything potentially problematic is done
3155 static unsigned int io_file_get_flags(struct file *file)
3157 umode_t mode = file_inode(file)->i_mode;
3158 unsigned int res = 0;
3162 if (__io_file_supports_nowait(file, mode))
3167 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3169 return req->flags & REQ_F_SUPPORT_NOWAIT;
3172 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3174 struct kiocb *kiocb = &req->rw.kiocb;
3178 kiocb->ki_pos = READ_ONCE(sqe->off);
3180 ioprio = READ_ONCE(sqe->ioprio);
3182 ret = ioprio_check_cap(ioprio);
3186 kiocb->ki_ioprio = ioprio;
3188 kiocb->ki_ioprio = get_current_ioprio();
3192 req->rw.addr = READ_ONCE(sqe->addr);
3193 req->rw.len = READ_ONCE(sqe->len);
3194 req->rw.flags = READ_ONCE(sqe->rw_flags);
3195 req->buf_index = READ_ONCE(sqe->buf_index);
3199 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3205 case -ERESTARTNOINTR:
3206 case -ERESTARTNOHAND:
3207 case -ERESTART_RESTARTBLOCK:
3209 * We can't just restart the syscall, since previously
3210 * submitted sqes may already be in progress. Just fail this
3216 kiocb->ki_complete(kiocb, ret);
3220 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3222 struct kiocb *kiocb = &req->rw.kiocb;
3224 if (kiocb->ki_pos != -1)
3225 return &kiocb->ki_pos;
3227 if (!(req->file->f_mode & FMODE_STREAM)) {
3228 req->flags |= REQ_F_CUR_POS;
3229 kiocb->ki_pos = req->file->f_pos;
3230 return &kiocb->ki_pos;
3237 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3238 unsigned int issue_flags)
3240 struct io_async_rw *io = req->async_data;
3242 /* add previously done IO, if any */
3243 if (req_has_async_data(req) && io->bytes_done > 0) {
3245 ret = io->bytes_done;
3247 ret += io->bytes_done;
3250 if (req->flags & REQ_F_CUR_POS)
3251 req->file->f_pos = req->rw.kiocb.ki_pos;
3252 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3253 __io_complete_rw(req, ret, issue_flags);
3255 io_rw_done(&req->rw.kiocb, ret);
3257 if (req->flags & REQ_F_REISSUE) {
3258 req->flags &= ~REQ_F_REISSUE;
3259 if (io_resubmit_prep(req))
3260 io_req_task_queue_reissue(req);
3262 io_req_task_queue_fail(req, ret);
3266 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3267 struct io_mapped_ubuf *imu)
3269 size_t len = req->rw.len;
3270 u64 buf_end, buf_addr = req->rw.addr;
3273 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3275 /* not inside the mapped region */
3276 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3280 * May not be a start of buffer, set size appropriately
3281 * and advance us to the beginning.
3283 offset = buf_addr - imu->ubuf;
3284 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3288 * Don't use iov_iter_advance() here, as it's really slow for
3289 * using the latter parts of a big fixed buffer - it iterates
3290 * over each segment manually. We can cheat a bit here, because
3293 * 1) it's a BVEC iter, we set it up
3294 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3295 * first and last bvec
3297 * So just find our index, and adjust the iterator afterwards.
3298 * If the offset is within the first bvec (or the whole first
3299 * bvec, just use iov_iter_advance(). This makes it easier
3300 * since we can just skip the first segment, which may not
3301 * be PAGE_SIZE aligned.
3303 const struct bio_vec *bvec = imu->bvec;
3305 if (offset <= bvec->bv_len) {
3306 iov_iter_advance(iter, offset);
3308 unsigned long seg_skip;
3310 /* skip first vec */
3311 offset -= bvec->bv_len;
3312 seg_skip = 1 + (offset >> PAGE_SHIFT);
3314 iter->bvec = bvec + seg_skip;
3315 iter->nr_segs -= seg_skip;
3316 iter->count -= bvec->bv_len + offset;
3317 iter->iov_offset = offset & ~PAGE_MASK;
3324 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3325 unsigned int issue_flags)
3327 struct io_mapped_ubuf *imu = req->imu;
3328 u16 index, buf_index = req->buf_index;
3331 struct io_ring_ctx *ctx = req->ctx;
3333 if (unlikely(buf_index >= ctx->nr_user_bufs))
3335 io_req_set_rsrc_node(req, ctx, issue_flags);
3336 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3337 imu = READ_ONCE(ctx->user_bufs[index]);
3340 return __io_import_fixed(req, rw, iter, imu);
3343 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3344 struct io_buffer_list *bl, unsigned int bgid)
3346 struct list_head *list;
3348 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3349 INIT_LIST_HEAD(&bl->buf_list);
3351 list_add(&bl->list, list);
3354 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3355 int bgid, unsigned int issue_flags)
3357 struct io_buffer *kbuf = req->kbuf;
3358 struct io_ring_ctx *ctx = req->ctx;
3359 struct io_buffer_list *bl;
3361 if (req->flags & REQ_F_BUFFER_SELECTED)
3364 io_ring_submit_lock(req->ctx, issue_flags);
3366 bl = io_buffer_get_list(ctx, bgid);
3367 if (bl && !list_empty(&bl->buf_list)) {
3368 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3369 list_del(&kbuf->list);
3370 if (*len > kbuf->len)
3372 req->flags |= REQ_F_BUFFER_SELECTED;
3375 kbuf = ERR_PTR(-ENOBUFS);
3378 io_ring_submit_unlock(req->ctx, issue_flags);
3382 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3383 unsigned int issue_flags)
3385 struct io_buffer *kbuf;
3388 bgid = req->buf_index;
3389 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3392 return u64_to_user_ptr(kbuf->addr);
3395 #ifdef CONFIG_COMPAT
3396 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3397 unsigned int issue_flags)
3399 struct compat_iovec __user *uiov;
3400 compat_ssize_t clen;
3404 uiov = u64_to_user_ptr(req->rw.addr);
3405 if (!access_ok(uiov, sizeof(*uiov)))
3407 if (__get_user(clen, &uiov->iov_len))
3413 buf = io_rw_buffer_select(req, &len, issue_flags);
3415 return PTR_ERR(buf);
3416 iov[0].iov_base = buf;
3417 iov[0].iov_len = (compat_size_t) len;
3422 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3423 unsigned int issue_flags)
3425 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3429 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3432 len = iov[0].iov_len;
3435 buf = io_rw_buffer_select(req, &len, issue_flags);
3437 return PTR_ERR(buf);
3438 iov[0].iov_base = buf;
3439 iov[0].iov_len = len;
3443 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3444 unsigned int issue_flags)
3446 if (req->flags & REQ_F_BUFFER_SELECTED) {
3447 struct io_buffer *kbuf = req->kbuf;
3449 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3450 iov[0].iov_len = kbuf->len;
3453 if (req->rw.len != 1)
3456 #ifdef CONFIG_COMPAT
3457 if (req->ctx->compat)
3458 return io_compat_import(req, iov, issue_flags);
3461 return __io_iov_buffer_select(req, iov, issue_flags);
3464 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3465 struct io_rw_state *s,
3466 unsigned int issue_flags)
3468 struct iov_iter *iter = &s->iter;
3469 u8 opcode = req->opcode;
3470 struct iovec *iovec;
3475 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3476 ret = io_import_fixed(req, rw, iter, issue_flags);
3478 return ERR_PTR(ret);
3482 /* buffer index only valid with fixed read/write, or buffer select */
3483 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3484 return ERR_PTR(-EINVAL);
3486 buf = u64_to_user_ptr(req->rw.addr);
3487 sqe_len = req->rw.len;
3489 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3490 if (req->flags & REQ_F_BUFFER_SELECT) {
3491 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3493 return ERR_CAST(buf);
3494 req->rw.len = sqe_len;
3497 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3499 return ERR_PTR(ret);
3503 iovec = s->fast_iov;
3504 if (req->flags & REQ_F_BUFFER_SELECT) {
3505 ret = io_iov_buffer_select(req, iovec, issue_flags);
3507 return ERR_PTR(ret);
3508 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3512 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3514 if (unlikely(ret < 0))
3515 return ERR_PTR(ret);
3519 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3520 struct iovec **iovec, struct io_rw_state *s,
3521 unsigned int issue_flags)
3523 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3524 if (unlikely(IS_ERR(*iovec)))
3525 return PTR_ERR(*iovec);
3527 iov_iter_save_state(&s->iter, &s->iter_state);
3531 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3533 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3537 * For files that don't have ->read_iter() and ->write_iter(), handle them
3538 * by looping over ->read() or ->write() manually.
3540 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3542 struct kiocb *kiocb = &req->rw.kiocb;
3543 struct file *file = req->file;
3548 * Don't support polled IO through this interface, and we can't
3549 * support non-blocking either. For the latter, this just causes
3550 * the kiocb to be handled from an async context.
3552 if (kiocb->ki_flags & IOCB_HIPRI)
3554 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3555 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3558 ppos = io_kiocb_ppos(kiocb);
3560 while (iov_iter_count(iter)) {
3564 if (!iov_iter_is_bvec(iter)) {
3565 iovec = iov_iter_iovec(iter);
3567 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3568 iovec.iov_len = req->rw.len;
3572 nr = file->f_op->read(file, iovec.iov_base,
3573 iovec.iov_len, ppos);
3575 nr = file->f_op->write(file, iovec.iov_base,
3576 iovec.iov_len, ppos);
3585 if (!iov_iter_is_bvec(iter)) {
3586 iov_iter_advance(iter, nr);
3593 if (nr != iovec.iov_len)
3600 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3601 const struct iovec *fast_iov, struct iov_iter *iter)
3603 struct io_async_rw *rw = req->async_data;
3605 memcpy(&rw->s.iter, iter, sizeof(*iter));
3606 rw->free_iovec = iovec;
3608 /* can only be fixed buffers, no need to do anything */
3609 if (iov_iter_is_bvec(iter))
3612 unsigned iov_off = 0;
3614 rw->s.iter.iov = rw->s.fast_iov;
3615 if (iter->iov != fast_iov) {
3616 iov_off = iter->iov - fast_iov;
3617 rw->s.iter.iov += iov_off;
3619 if (rw->s.fast_iov != fast_iov)
3620 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3621 sizeof(struct iovec) * iter->nr_segs);
3623 req->flags |= REQ_F_NEED_CLEANUP;
3627 static inline bool io_alloc_async_data(struct io_kiocb *req)
3629 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3630 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3631 if (req->async_data) {
3632 req->flags |= REQ_F_ASYNC_DATA;
3638 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3639 struct io_rw_state *s, bool force)
3641 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3643 if (!req_has_async_data(req)) {
3644 struct io_async_rw *iorw;
3646 if (io_alloc_async_data(req)) {
3651 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3652 iorw = req->async_data;
3653 /* we've copied and mapped the iter, ensure state is saved */
3654 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3659 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3661 struct io_async_rw *iorw = req->async_data;
3665 /* submission path, ->uring_lock should already be taken */
3666 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3667 if (unlikely(ret < 0))
3670 iorw->bytes_done = 0;
3671 iorw->free_iovec = iov;
3673 req->flags |= REQ_F_NEED_CLEANUP;
3678 * This is our waitqueue callback handler, registered through __folio_lock_async()
3679 * when we initially tried to do the IO with the iocb armed our waitqueue.
3680 * This gets called when the page is unlocked, and we generally expect that to
3681 * happen when the page IO is completed and the page is now uptodate. This will
3682 * queue a task_work based retry of the operation, attempting to copy the data
3683 * again. If the latter fails because the page was NOT uptodate, then we will
3684 * do a thread based blocking retry of the operation. That's the unexpected
3687 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3688 int sync, void *arg)
3690 struct wait_page_queue *wpq;
3691 struct io_kiocb *req = wait->private;
3692 struct wait_page_key *key = arg;
3694 wpq = container_of(wait, struct wait_page_queue, wait);
3696 if (!wake_page_match(wpq, key))
3699 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3700 list_del_init(&wait->entry);
3701 io_req_task_queue(req);
3706 * This controls whether a given IO request should be armed for async page
3707 * based retry. If we return false here, the request is handed to the async
3708 * worker threads for retry. If we're doing buffered reads on a regular file,
3709 * we prepare a private wait_page_queue entry and retry the operation. This
3710 * will either succeed because the page is now uptodate and unlocked, or it
3711 * will register a callback when the page is unlocked at IO completion. Through
3712 * that callback, io_uring uses task_work to setup a retry of the operation.
3713 * That retry will attempt the buffered read again. The retry will generally
3714 * succeed, or in rare cases where it fails, we then fall back to using the
3715 * async worker threads for a blocking retry.
3717 static bool io_rw_should_retry(struct io_kiocb *req)
3719 struct io_async_rw *rw = req->async_data;
3720 struct wait_page_queue *wait = &rw->wpq;
3721 struct kiocb *kiocb = &req->rw.kiocb;
3723 /* never retry for NOWAIT, we just complete with -EAGAIN */
3724 if (req->flags & REQ_F_NOWAIT)
3727 /* Only for buffered IO */
3728 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3732 * just use poll if we can, and don't attempt if the fs doesn't
3733 * support callback based unlocks
3735 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3738 wait->wait.func = io_async_buf_func;
3739 wait->wait.private = req;
3740 wait->wait.flags = 0;
3741 INIT_LIST_HEAD(&wait->wait.entry);
3742 kiocb->ki_flags |= IOCB_WAITQ;
3743 kiocb->ki_flags &= ~IOCB_NOWAIT;
3744 kiocb->ki_waitq = wait;
3748 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3750 if (likely(req->file->f_op->read_iter))
3751 return call_read_iter(req->file, &req->rw.kiocb, iter);
3752 else if (req->file->f_op->read)
3753 return loop_rw_iter(READ, req, iter);
3758 static bool need_read_all(struct io_kiocb *req)
3760 return req->flags & REQ_F_ISREG ||
3761 S_ISBLK(file_inode(req->file)->i_mode);
3764 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3766 struct kiocb *kiocb = &req->rw.kiocb;
3767 struct io_ring_ctx *ctx = req->ctx;
3768 struct file *file = req->file;
3771 if (unlikely(!file || !(file->f_mode & mode)))
3774 if (!io_req_ffs_set(req))
3775 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3777 kiocb->ki_flags = iocb_flags(file);
3778 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
3783 * If the file is marked O_NONBLOCK, still allow retry for it if it
3784 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3785 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3787 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3788 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3789 req->flags |= REQ_F_NOWAIT;
3791 if (ctx->flags & IORING_SETUP_IOPOLL) {
3792 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3795 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3796 kiocb->ki_complete = io_complete_rw_iopoll;
3797 req->iopoll_completed = 0;
3799 if (kiocb->ki_flags & IOCB_HIPRI)
3801 kiocb->ki_complete = io_complete_rw;
3807 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3809 struct io_rw_state __s, *s = &__s;
3810 struct iovec *iovec;
3811 struct kiocb *kiocb = &req->rw.kiocb;
3812 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3813 struct io_async_rw *rw;
3817 if (!req_has_async_data(req)) {
3818 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3819 if (unlikely(ret < 0))
3823 * Safe and required to re-import if we're using provided
3824 * buffers, as we dropped the selected one before retry.
3826 if (req->flags & REQ_F_BUFFER_SELECT) {
3827 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3828 if (unlikely(ret < 0))
3832 rw = req->async_data;
3835 * We come here from an earlier attempt, restore our state to
3836 * match in case it doesn't. It's cheap enough that we don't
3837 * need to make this conditional.
3839 iov_iter_restore(&s->iter, &s->iter_state);
3842 ret = io_rw_init_file(req, FMODE_READ);
3843 if (unlikely(ret)) {
3847 req->result = iov_iter_count(&s->iter);
3849 if (force_nonblock) {
3850 /* If the file doesn't support async, just async punt */
3851 if (unlikely(!io_file_supports_nowait(req))) {
3852 ret = io_setup_async_rw(req, iovec, s, true);
3853 return ret ?: -EAGAIN;
3855 kiocb->ki_flags |= IOCB_NOWAIT;
3857 /* Ensure we clear previously set non-block flag */
3858 kiocb->ki_flags &= ~IOCB_NOWAIT;
3861 ppos = io_kiocb_update_pos(req);
3863 ret = rw_verify_area(READ, req->file, ppos, req->result);
3864 if (unlikely(ret)) {
3869 ret = io_iter_do_read(req, &s->iter);
3871 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3872 req->flags &= ~REQ_F_REISSUE;
3873 /* if we can poll, just do that */
3874 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3876 /* IOPOLL retry should happen for io-wq threads */
3877 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3879 /* no retry on NONBLOCK nor RWF_NOWAIT */
3880 if (req->flags & REQ_F_NOWAIT)
3883 } else if (ret == -EIOCBQUEUED) {
3885 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3886 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3887 /* read all, failed, already did sync or don't want to retry */
3892 * Don't depend on the iter state matching what was consumed, or being
3893 * untouched in case of error. Restore it and we'll advance it
3894 * manually if we need to.
3896 iov_iter_restore(&s->iter, &s->iter_state);
3898 ret2 = io_setup_async_rw(req, iovec, s, true);
3903 rw = req->async_data;
3906 * Now use our persistent iterator and state, if we aren't already.
3907 * We've restored and mapped the iter to match.
3912 * We end up here because of a partial read, either from
3913 * above or inside this loop. Advance the iter by the bytes
3914 * that were consumed.
3916 iov_iter_advance(&s->iter, ret);
3917 if (!iov_iter_count(&s->iter))
3919 rw->bytes_done += ret;
3920 iov_iter_save_state(&s->iter, &s->iter_state);
3922 /* if we can retry, do so with the callbacks armed */
3923 if (!io_rw_should_retry(req)) {
3924 kiocb->ki_flags &= ~IOCB_WAITQ;
3929 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3930 * we get -EIOCBQUEUED, then we'll get a notification when the
3931 * desired page gets unlocked. We can also get a partial read
3932 * here, and if we do, then just retry at the new offset.
3934 ret = io_iter_do_read(req, &s->iter);
3935 if (ret == -EIOCBQUEUED)
3937 /* we got some bytes, but not all. retry. */
3938 kiocb->ki_flags &= ~IOCB_WAITQ;
3939 iov_iter_restore(&s->iter, &s->iter_state);
3942 kiocb_done(req, ret, issue_flags);
3944 /* it's faster to check here then delegate to kfree */
3950 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3952 struct io_rw_state __s, *s = &__s;
3953 struct iovec *iovec;
3954 struct kiocb *kiocb = &req->rw.kiocb;
3955 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3959 if (!req_has_async_data(req)) {
3960 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3961 if (unlikely(ret < 0))
3964 struct io_async_rw *rw = req->async_data;
3967 iov_iter_restore(&s->iter, &s->iter_state);
3970 ret = io_rw_init_file(req, FMODE_WRITE);
3971 if (unlikely(ret)) {
3975 req->result = iov_iter_count(&s->iter);
3977 if (force_nonblock) {
3978 /* If the file doesn't support async, just async punt */
3979 if (unlikely(!io_file_supports_nowait(req)))
3982 /* file path doesn't support NOWAIT for non-direct_IO */
3983 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3984 (req->flags & REQ_F_ISREG))
3987 kiocb->ki_flags |= IOCB_NOWAIT;
3989 /* Ensure we clear previously set non-block flag */
3990 kiocb->ki_flags &= ~IOCB_NOWAIT;
3993 ppos = io_kiocb_update_pos(req);
3995 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
4000 * Open-code file_start_write here to grab freeze protection,
4001 * which will be released by another thread in
4002 * io_complete_rw(). Fool lockdep by telling it the lock got
4003 * released so that it doesn't complain about the held lock when
4004 * we return to userspace.
4006 if (req->flags & REQ_F_ISREG) {
4007 sb_start_write(file_inode(req->file)->i_sb);
4008 __sb_writers_release(file_inode(req->file)->i_sb,
4011 kiocb->ki_flags |= IOCB_WRITE;
4013 if (likely(req->file->f_op->write_iter))
4014 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4015 else if (req->file->f_op->write)
4016 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4020 if (req->flags & REQ_F_REISSUE) {
4021 req->flags &= ~REQ_F_REISSUE;
4026 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4027 * retry them without IOCB_NOWAIT.
4029 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4031 /* no retry on NONBLOCK nor RWF_NOWAIT */
4032 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4034 if (!force_nonblock || ret2 != -EAGAIN) {
4035 /* IOPOLL retry should happen for io-wq threads */
4036 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4039 kiocb_done(req, ret2, issue_flags);
4042 iov_iter_restore(&s->iter, &s->iter_state);
4043 ret = io_setup_async_rw(req, iovec, s, false);
4044 return ret ?: -EAGAIN;
4047 /* it's reportedly faster than delegating the null check to kfree() */
4053 static int io_renameat_prep(struct io_kiocb *req,
4054 const struct io_uring_sqe *sqe)
4056 struct io_rename *ren = &req->rename;
4057 const char __user *oldf, *newf;
4059 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4061 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4063 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4066 ren->old_dfd = READ_ONCE(sqe->fd);
4067 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4068 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4069 ren->new_dfd = READ_ONCE(sqe->len);
4070 ren->flags = READ_ONCE(sqe->rename_flags);
4072 ren->oldpath = getname(oldf);
4073 if (IS_ERR(ren->oldpath))
4074 return PTR_ERR(ren->oldpath);
4076 ren->newpath = getname(newf);
4077 if (IS_ERR(ren->newpath)) {
4078 putname(ren->oldpath);
4079 return PTR_ERR(ren->newpath);
4082 req->flags |= REQ_F_NEED_CLEANUP;
4086 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4088 struct io_rename *ren = &req->rename;
4091 if (issue_flags & IO_URING_F_NONBLOCK)
4094 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4095 ren->newpath, ren->flags);
4097 req->flags &= ~REQ_F_NEED_CLEANUP;
4100 io_req_complete(req, ret);
4104 static int io_unlinkat_prep(struct io_kiocb *req,
4105 const struct io_uring_sqe *sqe)
4107 struct io_unlink *un = &req->unlink;
4108 const char __user *fname;
4110 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4112 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4115 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4118 un->dfd = READ_ONCE(sqe->fd);
4120 un->flags = READ_ONCE(sqe->unlink_flags);
4121 if (un->flags & ~AT_REMOVEDIR)
4124 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4125 un->filename = getname(fname);
4126 if (IS_ERR(un->filename))
4127 return PTR_ERR(un->filename);
4129 req->flags |= REQ_F_NEED_CLEANUP;
4133 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4135 struct io_unlink *un = &req->unlink;
4138 if (issue_flags & IO_URING_F_NONBLOCK)
4141 if (un->flags & AT_REMOVEDIR)
4142 ret = do_rmdir(un->dfd, un->filename);
4144 ret = do_unlinkat(un->dfd, un->filename);
4146 req->flags &= ~REQ_F_NEED_CLEANUP;
4149 io_req_complete(req, ret);
4153 static int io_mkdirat_prep(struct io_kiocb *req,
4154 const struct io_uring_sqe *sqe)
4156 struct io_mkdir *mkd = &req->mkdir;
4157 const char __user *fname;
4159 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4161 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4164 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4167 mkd->dfd = READ_ONCE(sqe->fd);
4168 mkd->mode = READ_ONCE(sqe->len);
4170 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4171 mkd->filename = getname(fname);
4172 if (IS_ERR(mkd->filename))
4173 return PTR_ERR(mkd->filename);
4175 req->flags |= REQ_F_NEED_CLEANUP;
4179 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4181 struct io_mkdir *mkd = &req->mkdir;
4184 if (issue_flags & IO_URING_F_NONBLOCK)
4187 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4189 req->flags &= ~REQ_F_NEED_CLEANUP;
4192 io_req_complete(req, ret);
4196 static int io_symlinkat_prep(struct io_kiocb *req,
4197 const struct io_uring_sqe *sqe)
4199 struct io_symlink *sl = &req->symlink;
4200 const char __user *oldpath, *newpath;
4202 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4204 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4207 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4210 sl->new_dfd = READ_ONCE(sqe->fd);
4211 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4212 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4214 sl->oldpath = getname(oldpath);
4215 if (IS_ERR(sl->oldpath))
4216 return PTR_ERR(sl->oldpath);
4218 sl->newpath = getname(newpath);
4219 if (IS_ERR(sl->newpath)) {
4220 putname(sl->oldpath);
4221 return PTR_ERR(sl->newpath);
4224 req->flags |= REQ_F_NEED_CLEANUP;
4228 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4230 struct io_symlink *sl = &req->symlink;
4233 if (issue_flags & IO_URING_F_NONBLOCK)
4236 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4238 req->flags &= ~REQ_F_NEED_CLEANUP;
4241 io_req_complete(req, ret);
4245 static int io_linkat_prep(struct io_kiocb *req,
4246 const struct io_uring_sqe *sqe)
4248 struct io_hardlink *lnk = &req->hardlink;
4249 const char __user *oldf, *newf;
4251 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4253 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4255 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4258 lnk->old_dfd = READ_ONCE(sqe->fd);
4259 lnk->new_dfd = READ_ONCE(sqe->len);
4260 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4261 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4262 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4264 lnk->oldpath = getname(oldf);
4265 if (IS_ERR(lnk->oldpath))
4266 return PTR_ERR(lnk->oldpath);
4268 lnk->newpath = getname(newf);
4269 if (IS_ERR(lnk->newpath)) {
4270 putname(lnk->oldpath);
4271 return PTR_ERR(lnk->newpath);
4274 req->flags |= REQ_F_NEED_CLEANUP;
4278 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4280 struct io_hardlink *lnk = &req->hardlink;
4283 if (issue_flags & IO_URING_F_NONBLOCK)
4286 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4287 lnk->newpath, lnk->flags);
4289 req->flags &= ~REQ_F_NEED_CLEANUP;
4292 io_req_complete(req, ret);
4296 static int io_shutdown_prep(struct io_kiocb *req,
4297 const struct io_uring_sqe *sqe)
4299 #if defined(CONFIG_NET)
4300 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4302 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4303 sqe->buf_index || sqe->splice_fd_in))
4306 req->shutdown.how = READ_ONCE(sqe->len);
4313 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4315 #if defined(CONFIG_NET)
4316 struct socket *sock;
4319 if (issue_flags & IO_URING_F_NONBLOCK)
4322 sock = sock_from_file(req->file);
4323 if (unlikely(!sock))
4326 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4329 io_req_complete(req, ret);
4336 static int __io_splice_prep(struct io_kiocb *req,
4337 const struct io_uring_sqe *sqe)
4339 struct io_splice *sp = &req->splice;
4340 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4342 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4345 sp->len = READ_ONCE(sqe->len);
4346 sp->flags = READ_ONCE(sqe->splice_flags);
4347 if (unlikely(sp->flags & ~valid_flags))
4349 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4353 static int io_tee_prep(struct io_kiocb *req,
4354 const struct io_uring_sqe *sqe)
4356 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4358 return __io_splice_prep(req, sqe);
4361 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4363 struct io_splice *sp = &req->splice;
4364 struct file *out = sp->file_out;
4365 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4369 if (issue_flags & IO_URING_F_NONBLOCK)
4372 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4373 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4375 in = io_file_get_normal(req, sp->splice_fd_in);
4382 ret = do_tee(in, out, sp->len, flags);
4384 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4389 io_req_complete(req, ret);
4393 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4395 struct io_splice *sp = &req->splice;
4397 sp->off_in = READ_ONCE(sqe->splice_off_in);
4398 sp->off_out = READ_ONCE(sqe->off);
4399 return __io_splice_prep(req, sqe);
4402 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4404 struct io_splice *sp = &req->splice;
4405 struct file *out = sp->file_out;
4406 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4407 loff_t *poff_in, *poff_out;
4411 if (issue_flags & IO_URING_F_NONBLOCK)
4414 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4415 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4417 in = io_file_get_normal(req, sp->splice_fd_in);
4423 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4424 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4427 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4429 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4434 io_req_complete(req, ret);
4439 * IORING_OP_NOP just posts a completion event, nothing else.
4441 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4443 struct io_ring_ctx *ctx = req->ctx;
4445 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4448 __io_req_complete(req, issue_flags, 0, 0);
4452 static int io_msg_ring_prep(struct io_kiocb *req,
4453 const struct io_uring_sqe *sqe)
4455 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4456 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4459 req->msg.user_data = READ_ONCE(sqe->off);
4460 req->msg.len = READ_ONCE(sqe->len);
4464 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4466 struct io_ring_ctx *target_ctx;
4467 struct io_msg *msg = &req->msg;
4472 if (req->file->f_op != &io_uring_fops)
4476 target_ctx = req->file->private_data;
4478 spin_lock(&target_ctx->completion_lock);
4479 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
4480 io_commit_cqring(target_ctx);
4481 spin_unlock(&target_ctx->completion_lock);
4484 io_cqring_ev_posted(target_ctx);
4491 __io_req_complete(req, issue_flags, ret, 0);
4495 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4497 struct io_ring_ctx *ctx = req->ctx;
4499 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4501 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4505 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4506 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4509 req->sync.off = READ_ONCE(sqe->off);
4510 req->sync.len = READ_ONCE(sqe->len);
4514 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4516 loff_t end = req->sync.off + req->sync.len;
4519 /* fsync always requires a blocking context */
4520 if (issue_flags & IO_URING_F_NONBLOCK)
4523 ret = vfs_fsync_range(req->file, req->sync.off,
4524 end > 0 ? end : LLONG_MAX,
4525 req->sync.flags & IORING_FSYNC_DATASYNC);
4528 io_req_complete(req, ret);
4532 static int io_fallocate_prep(struct io_kiocb *req,
4533 const struct io_uring_sqe *sqe)
4535 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4538 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4541 req->sync.off = READ_ONCE(sqe->off);
4542 req->sync.len = READ_ONCE(sqe->addr);
4543 req->sync.mode = READ_ONCE(sqe->len);
4547 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4551 /* fallocate always requiring blocking context */
4552 if (issue_flags & IO_URING_F_NONBLOCK)
4554 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4559 fsnotify_modify(req->file);
4560 io_req_complete(req, ret);
4564 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4566 const char __user *fname;
4569 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4571 if (unlikely(sqe->ioprio || sqe->buf_index))
4573 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4576 /* open.how should be already initialised */
4577 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4578 req->open.how.flags |= O_LARGEFILE;
4580 req->open.dfd = READ_ONCE(sqe->fd);
4581 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4582 req->open.filename = getname(fname);
4583 if (IS_ERR(req->open.filename)) {
4584 ret = PTR_ERR(req->open.filename);
4585 req->open.filename = NULL;
4589 req->open.file_slot = READ_ONCE(sqe->file_index);
4590 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4593 req->open.nofile = rlimit(RLIMIT_NOFILE);
4594 req->flags |= REQ_F_NEED_CLEANUP;
4598 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4600 u64 mode = READ_ONCE(sqe->len);
4601 u64 flags = READ_ONCE(sqe->open_flags);
4603 req->open.how = build_open_how(flags, mode);
4604 return __io_openat_prep(req, sqe);
4607 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4609 struct open_how __user *how;
4613 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4614 len = READ_ONCE(sqe->len);
4615 if (len < OPEN_HOW_SIZE_VER0)
4618 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4623 return __io_openat_prep(req, sqe);
4626 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4628 struct open_flags op;
4630 bool resolve_nonblock, nonblock_set;
4631 bool fixed = !!req->open.file_slot;
4634 ret = build_open_flags(&req->open.how, &op);
4637 nonblock_set = op.open_flag & O_NONBLOCK;
4638 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4639 if (issue_flags & IO_URING_F_NONBLOCK) {
4641 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4642 * it'll always -EAGAIN
4644 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4646 op.lookup_flags |= LOOKUP_CACHED;
4647 op.open_flag |= O_NONBLOCK;
4651 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4656 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4659 * We could hang on to this 'fd' on retrying, but seems like
4660 * marginal gain for something that is now known to be a slower
4661 * path. So just put it, and we'll get a new one when we retry.
4666 ret = PTR_ERR(file);
4667 /* only retry if RESOLVE_CACHED wasn't already set by application */
4668 if (ret == -EAGAIN &&
4669 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4674 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4675 file->f_flags &= ~O_NONBLOCK;
4676 fsnotify_open(file);
4679 fd_install(ret, file);
4681 ret = io_install_fixed_file(req, file, issue_flags,
4682 req->open.file_slot - 1);
4684 putname(req->open.filename);
4685 req->flags &= ~REQ_F_NEED_CLEANUP;
4688 __io_req_complete(req, issue_flags, ret, 0);
4692 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4694 return io_openat2(req, issue_flags);
4697 static int io_remove_buffers_prep(struct io_kiocb *req,
4698 const struct io_uring_sqe *sqe)
4700 struct io_provide_buf *p = &req->pbuf;
4703 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4707 tmp = READ_ONCE(sqe->fd);
4708 if (!tmp || tmp > USHRT_MAX)
4711 memset(p, 0, sizeof(*p));
4713 p->bgid = READ_ONCE(sqe->buf_group);
4717 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4718 struct io_buffer_list *bl, unsigned nbufs)
4722 /* shouldn't happen */
4726 /* the head kbuf is the list itself */
4727 while (!list_empty(&bl->buf_list)) {
4728 struct io_buffer *nxt;
4730 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4731 list_del(&nxt->list);
4741 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4743 struct io_provide_buf *p = &req->pbuf;
4744 struct io_ring_ctx *ctx = req->ctx;
4745 struct io_buffer_list *bl;
4748 io_ring_submit_lock(ctx, issue_flags);
4751 bl = io_buffer_get_list(ctx, p->bgid);
4753 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4757 /* complete before unlock, IOPOLL may need the lock */
4758 __io_req_complete(req, issue_flags, ret, 0);
4759 io_ring_submit_unlock(ctx, issue_flags);
4763 static int io_provide_buffers_prep(struct io_kiocb *req,
4764 const struct io_uring_sqe *sqe)
4766 unsigned long size, tmp_check;
4767 struct io_provide_buf *p = &req->pbuf;
4770 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4773 tmp = READ_ONCE(sqe->fd);
4774 if (!tmp || tmp > USHRT_MAX)
4777 p->addr = READ_ONCE(sqe->addr);
4778 p->len = READ_ONCE(sqe->len);
4780 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4783 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4786 size = (unsigned long)p->len * p->nbufs;
4787 if (!access_ok(u64_to_user_ptr(p->addr), size))
4790 p->bgid = READ_ONCE(sqe->buf_group);
4791 tmp = READ_ONCE(sqe->off);
4792 if (tmp > USHRT_MAX)
4798 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4800 struct io_buffer *buf;
4805 * Completions that don't happen inline (eg not under uring_lock) will
4806 * add to ->io_buffers_comp. If we don't have any free buffers, check
4807 * the completion list and splice those entries first.
4809 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4810 spin_lock(&ctx->completion_lock);
4811 if (!list_empty(&ctx->io_buffers_comp)) {
4812 list_splice_init(&ctx->io_buffers_comp,
4813 &ctx->io_buffers_cache);
4814 spin_unlock(&ctx->completion_lock);
4817 spin_unlock(&ctx->completion_lock);
4821 * No free buffers and no completion entries either. Allocate a new
4822 * page worth of buffer entries and add those to our freelist.
4824 page = alloc_page(GFP_KERNEL_ACCOUNT);
4828 list_add(&page->lru, &ctx->io_buffers_pages);
4830 buf = page_address(page);
4831 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4832 while (bufs_in_page) {
4833 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4841 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4842 struct io_buffer_list *bl)
4844 struct io_buffer *buf;
4845 u64 addr = pbuf->addr;
4846 int i, bid = pbuf->bid;
4848 for (i = 0; i < pbuf->nbufs; i++) {
4849 if (list_empty(&ctx->io_buffers_cache) &&
4850 io_refill_buffer_cache(ctx))
4852 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4854 list_move_tail(&buf->list, &bl->buf_list);
4856 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4858 buf->bgid = pbuf->bgid;
4864 return i ? 0 : -ENOMEM;
4867 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4869 struct io_provide_buf *p = &req->pbuf;
4870 struct io_ring_ctx *ctx = req->ctx;
4871 struct io_buffer_list *bl;
4874 io_ring_submit_lock(ctx, issue_flags);
4876 bl = io_buffer_get_list(ctx, p->bgid);
4877 if (unlikely(!bl)) {
4878 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4883 io_buffer_add_list(ctx, bl, p->bgid);
4886 ret = io_add_buffers(ctx, p, bl);
4890 /* complete before unlock, IOPOLL may need the lock */
4891 __io_req_complete(req, issue_flags, ret, 0);
4892 io_ring_submit_unlock(ctx, issue_flags);
4896 static int io_epoll_ctl_prep(struct io_kiocb *req,
4897 const struct io_uring_sqe *sqe)
4899 #if defined(CONFIG_EPOLL)
4900 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4902 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4905 req->epoll.epfd = READ_ONCE(sqe->fd);
4906 req->epoll.op = READ_ONCE(sqe->len);
4907 req->epoll.fd = READ_ONCE(sqe->off);
4909 if (ep_op_has_event(req->epoll.op)) {
4910 struct epoll_event __user *ev;
4912 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4913 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4923 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4925 #if defined(CONFIG_EPOLL)
4926 struct io_epoll *ie = &req->epoll;
4928 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4930 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4931 if (force_nonblock && ret == -EAGAIN)
4936 __io_req_complete(req, issue_flags, ret, 0);
4943 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4945 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4946 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4948 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4951 req->madvise.addr = READ_ONCE(sqe->addr);
4952 req->madvise.len = READ_ONCE(sqe->len);
4953 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4960 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4962 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4963 struct io_madvise *ma = &req->madvise;
4966 if (issue_flags & IO_URING_F_NONBLOCK)
4969 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4972 io_req_complete(req, ret);
4979 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4981 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4983 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4986 req->fadvise.offset = READ_ONCE(sqe->off);
4987 req->fadvise.len = READ_ONCE(sqe->len);
4988 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4992 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4994 struct io_fadvise *fa = &req->fadvise;
4997 if (issue_flags & IO_URING_F_NONBLOCK) {
4998 switch (fa->advice) {
4999 case POSIX_FADV_NORMAL:
5000 case POSIX_FADV_RANDOM:
5001 case POSIX_FADV_SEQUENTIAL:
5008 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5011 __io_req_complete(req, issue_flags, ret, 0);
5015 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5017 const char __user *path;
5019 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5021 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5023 if (req->flags & REQ_F_FIXED_FILE)
5026 req->statx.dfd = READ_ONCE(sqe->fd);
5027 req->statx.mask = READ_ONCE(sqe->len);
5028 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5029 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5030 req->statx.flags = READ_ONCE(sqe->statx_flags);
5032 req->statx.filename = getname_flags(path,
5033 getname_statx_lookup_flags(req->statx.flags),
5036 if (IS_ERR(req->statx.filename)) {
5037 int ret = PTR_ERR(req->statx.filename);
5039 req->statx.filename = NULL;
5043 req->flags |= REQ_F_NEED_CLEANUP;
5047 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5049 struct io_statx *ctx = &req->statx;
5052 if (issue_flags & IO_URING_F_NONBLOCK)
5055 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5060 io_req_complete(req, ret);
5064 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5066 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5068 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5069 sqe->rw_flags || sqe->buf_index)
5071 if (req->flags & REQ_F_FIXED_FILE)
5074 req->close.fd = READ_ONCE(sqe->fd);
5075 req->close.file_slot = READ_ONCE(sqe->file_index);
5076 if (req->close.file_slot && req->close.fd)
5082 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5084 struct files_struct *files = current->files;
5085 struct io_close *close = &req->close;
5086 struct fdtable *fdt;
5087 struct file *file = NULL;
5090 if (req->close.file_slot) {
5091 ret = io_close_fixed(req, issue_flags);
5095 spin_lock(&files->file_lock);
5096 fdt = files_fdtable(files);
5097 if (close->fd >= fdt->max_fds) {
5098 spin_unlock(&files->file_lock);
5101 file = fdt->fd[close->fd];
5102 if (!file || file->f_op == &io_uring_fops) {
5103 spin_unlock(&files->file_lock);
5108 /* if the file has a flush method, be safe and punt to async */
5109 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5110 spin_unlock(&files->file_lock);
5114 ret = __close_fd_get_file(close->fd, &file);
5115 spin_unlock(&files->file_lock);
5122 /* No ->flush() or already async, safely close from here */
5123 ret = filp_close(file, current->files);
5129 __io_req_complete(req, issue_flags, ret, 0);
5133 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5135 struct io_ring_ctx *ctx = req->ctx;
5137 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5139 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5143 req->sync.off = READ_ONCE(sqe->off);
5144 req->sync.len = READ_ONCE(sqe->len);
5145 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5149 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5153 /* sync_file_range always requires a blocking context */
5154 if (issue_flags & IO_URING_F_NONBLOCK)
5157 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5161 io_req_complete(req, ret);
5165 #if defined(CONFIG_NET)
5166 static int io_setup_async_msg(struct io_kiocb *req,
5167 struct io_async_msghdr *kmsg)
5169 struct io_async_msghdr *async_msg = req->async_data;
5173 if (io_alloc_async_data(req)) {
5174 kfree(kmsg->free_iov);
5177 async_msg = req->async_data;
5178 req->flags |= REQ_F_NEED_CLEANUP;
5179 memcpy(async_msg, kmsg, sizeof(*kmsg));
5180 async_msg->msg.msg_name = &async_msg->addr;
5181 /* if were using fast_iov, set it to the new one */
5182 if (!async_msg->free_iov)
5183 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5188 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5189 struct io_async_msghdr *iomsg)
5191 iomsg->msg.msg_name = &iomsg->addr;
5192 iomsg->free_iov = iomsg->fast_iov;
5193 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5194 req->sr_msg.msg_flags, &iomsg->free_iov);
5197 static int io_sendmsg_prep_async(struct io_kiocb *req)
5201 ret = io_sendmsg_copy_hdr(req, req->async_data);
5203 req->flags |= REQ_F_NEED_CLEANUP;
5207 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5209 struct io_sr_msg *sr = &req->sr_msg;
5211 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5214 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5215 sr->len = READ_ONCE(sqe->len);
5216 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5217 if (sr->msg_flags & MSG_DONTWAIT)
5218 req->flags |= REQ_F_NOWAIT;
5220 #ifdef CONFIG_COMPAT
5221 if (req->ctx->compat)
5222 sr->msg_flags |= MSG_CMSG_COMPAT;
5227 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5229 struct io_async_msghdr iomsg, *kmsg;
5230 struct socket *sock;
5235 sock = sock_from_file(req->file);
5236 if (unlikely(!sock))
5239 if (req_has_async_data(req)) {
5240 kmsg = req->async_data;
5242 ret = io_sendmsg_copy_hdr(req, &iomsg);
5248 flags = req->sr_msg.msg_flags;
5249 if (issue_flags & IO_URING_F_NONBLOCK)
5250 flags |= MSG_DONTWAIT;
5251 if (flags & MSG_WAITALL)
5252 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5254 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5256 if (ret < min_ret) {
5257 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5258 return io_setup_async_msg(req, kmsg);
5259 if (ret == -ERESTARTSYS)
5263 /* fast path, check for non-NULL to avoid function call */
5265 kfree(kmsg->free_iov);
5266 req->flags &= ~REQ_F_NEED_CLEANUP;
5267 __io_req_complete(req, issue_flags, ret, 0);
5271 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5273 struct io_sr_msg *sr = &req->sr_msg;
5276 struct socket *sock;
5281 sock = sock_from_file(req->file);
5282 if (unlikely(!sock))
5285 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5289 msg.msg_name = NULL;
5290 msg.msg_control = NULL;
5291 msg.msg_controllen = 0;
5292 msg.msg_namelen = 0;
5294 flags = req->sr_msg.msg_flags;
5295 if (issue_flags & IO_URING_F_NONBLOCK)
5296 flags |= MSG_DONTWAIT;
5297 if (flags & MSG_WAITALL)
5298 min_ret = iov_iter_count(&msg.msg_iter);
5300 msg.msg_flags = flags;
5301 ret = sock_sendmsg(sock, &msg);
5302 if (ret < min_ret) {
5303 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5305 if (ret == -ERESTARTSYS)
5309 __io_req_complete(req, issue_flags, ret, 0);
5313 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5314 struct io_async_msghdr *iomsg)
5316 struct io_sr_msg *sr = &req->sr_msg;
5317 struct iovec __user *uiov;
5321 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5322 &iomsg->uaddr, &uiov, &iov_len);
5326 if (req->flags & REQ_F_BUFFER_SELECT) {
5329 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5331 sr->len = iomsg->fast_iov[0].iov_len;
5332 iomsg->free_iov = NULL;
5334 iomsg->free_iov = iomsg->fast_iov;
5335 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5336 &iomsg->free_iov, &iomsg->msg.msg_iter,
5345 #ifdef CONFIG_COMPAT
5346 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5347 struct io_async_msghdr *iomsg)
5349 struct io_sr_msg *sr = &req->sr_msg;
5350 struct compat_iovec __user *uiov;
5355 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5360 uiov = compat_ptr(ptr);
5361 if (req->flags & REQ_F_BUFFER_SELECT) {
5362 compat_ssize_t clen;
5366 if (!access_ok(uiov, sizeof(*uiov)))
5368 if (__get_user(clen, &uiov->iov_len))
5373 iomsg->free_iov = NULL;
5375 iomsg->free_iov = iomsg->fast_iov;
5376 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5377 UIO_FASTIOV, &iomsg->free_iov,
5378 &iomsg->msg.msg_iter, true);
5387 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5388 struct io_async_msghdr *iomsg)
5390 iomsg->msg.msg_name = &iomsg->addr;
5392 #ifdef CONFIG_COMPAT
5393 if (req->ctx->compat)
5394 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5397 return __io_recvmsg_copy_hdr(req, iomsg);
5400 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5401 unsigned int issue_flags)
5403 struct io_sr_msg *sr = &req->sr_msg;
5405 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5408 static int io_recvmsg_prep_async(struct io_kiocb *req)
5412 ret = io_recvmsg_copy_hdr(req, req->async_data);
5414 req->flags |= REQ_F_NEED_CLEANUP;
5418 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5420 struct io_sr_msg *sr = &req->sr_msg;
5422 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5425 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5426 sr->len = READ_ONCE(sqe->len);
5427 sr->bgid = READ_ONCE(sqe->buf_group);
5428 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5429 if (sr->msg_flags & MSG_DONTWAIT)
5430 req->flags |= REQ_F_NOWAIT;
5432 #ifdef CONFIG_COMPAT
5433 if (req->ctx->compat)
5434 sr->msg_flags |= MSG_CMSG_COMPAT;
5440 static bool io_net_retry(struct socket *sock, int flags)
5442 if (!(flags & MSG_WAITALL))
5444 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5447 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5449 struct io_async_msghdr iomsg, *kmsg;
5450 struct io_sr_msg *sr = &req->sr_msg;
5451 struct socket *sock;
5452 struct io_buffer *kbuf;
5454 int ret, min_ret = 0;
5455 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5457 sock = sock_from_file(req->file);
5458 if (unlikely(!sock))
5461 if (req_has_async_data(req)) {
5462 kmsg = req->async_data;
5464 ret = io_recvmsg_copy_hdr(req, &iomsg);
5470 if (req->flags & REQ_F_BUFFER_SELECT) {
5471 kbuf = io_recv_buffer_select(req, issue_flags);
5473 return PTR_ERR(kbuf);
5474 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5475 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5476 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5477 1, req->sr_msg.len);
5480 flags = req->sr_msg.msg_flags;
5482 flags |= MSG_DONTWAIT;
5483 if (flags & MSG_WAITALL)
5484 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5486 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5487 kmsg->uaddr, flags);
5488 if (ret < min_ret) {
5489 if (ret == -EAGAIN && force_nonblock)
5490 return io_setup_async_msg(req, kmsg);
5491 if (ret == -ERESTARTSYS)
5493 if (ret > 0 && io_net_retry(sock, flags)) {
5495 req->flags |= REQ_F_PARTIAL_IO;
5496 return io_setup_async_msg(req, kmsg);
5499 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5503 /* fast path, check for non-NULL to avoid function call */
5505 kfree(kmsg->free_iov);
5506 req->flags &= ~REQ_F_NEED_CLEANUP;
5509 else if (sr->done_io)
5511 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5515 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5517 struct io_buffer *kbuf;
5518 struct io_sr_msg *sr = &req->sr_msg;
5520 void __user *buf = sr->buf;
5521 struct socket *sock;
5524 int ret, min_ret = 0;
5525 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5527 sock = sock_from_file(req->file);
5528 if (unlikely(!sock))
5531 if (req->flags & REQ_F_BUFFER_SELECT) {
5532 kbuf = io_recv_buffer_select(req, issue_flags);
5534 return PTR_ERR(kbuf);
5535 buf = u64_to_user_ptr(kbuf->addr);
5538 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5542 msg.msg_name = NULL;
5543 msg.msg_control = NULL;
5544 msg.msg_controllen = 0;
5545 msg.msg_namelen = 0;
5546 msg.msg_iocb = NULL;
5549 flags = req->sr_msg.msg_flags;
5551 flags |= MSG_DONTWAIT;
5552 if (flags & MSG_WAITALL)
5553 min_ret = iov_iter_count(&msg.msg_iter);
5555 ret = sock_recvmsg(sock, &msg, flags);
5556 if (ret < min_ret) {
5557 if (ret == -EAGAIN && force_nonblock)
5559 if (ret == -ERESTARTSYS)
5561 if (ret > 0 && io_net_retry(sock, flags)) {
5565 req->flags |= REQ_F_PARTIAL_IO;
5569 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5576 else if (sr->done_io)
5578 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5582 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5584 struct io_accept *accept = &req->accept;
5586 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5588 if (sqe->ioprio || sqe->len || sqe->buf_index)
5591 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5592 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5593 accept->flags = READ_ONCE(sqe->accept_flags);
5594 accept->nofile = rlimit(RLIMIT_NOFILE);
5596 accept->file_slot = READ_ONCE(sqe->file_index);
5597 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5599 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5601 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5602 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5606 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5608 struct io_accept *accept = &req->accept;
5609 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5610 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5611 bool fixed = !!accept->file_slot;
5616 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5617 if (unlikely(fd < 0))
5620 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5625 ret = PTR_ERR(file);
5626 if (ret == -EAGAIN && force_nonblock)
5628 if (ret == -ERESTARTSYS)
5631 } else if (!fixed) {
5632 fd_install(fd, file);
5635 ret = io_install_fixed_file(req, file, issue_flags,
5636 accept->file_slot - 1);
5638 __io_req_complete(req, issue_flags, ret, 0);
5642 static int io_connect_prep_async(struct io_kiocb *req)
5644 struct io_async_connect *io = req->async_data;
5645 struct io_connect *conn = &req->connect;
5647 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5650 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5652 struct io_connect *conn = &req->connect;
5654 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5656 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5660 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5661 conn->addr_len = READ_ONCE(sqe->addr2);
5665 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5667 struct io_async_connect __io, *io;
5668 unsigned file_flags;
5670 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5672 if (req_has_async_data(req)) {
5673 io = req->async_data;
5675 ret = move_addr_to_kernel(req->connect.addr,
5676 req->connect.addr_len,
5683 file_flags = force_nonblock ? O_NONBLOCK : 0;
5685 ret = __sys_connect_file(req->file, &io->address,
5686 req->connect.addr_len, file_flags);
5687 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5688 if (req_has_async_data(req))
5690 if (io_alloc_async_data(req)) {
5694 memcpy(req->async_data, &__io, sizeof(__io));
5697 if (ret == -ERESTARTSYS)
5702 __io_req_complete(req, issue_flags, ret, 0);
5705 #else /* !CONFIG_NET */
5706 #define IO_NETOP_FN(op) \
5707 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5709 return -EOPNOTSUPP; \
5712 #define IO_NETOP_PREP(op) \
5714 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5716 return -EOPNOTSUPP; \
5719 #define IO_NETOP_PREP_ASYNC(op) \
5721 static int io_##op##_prep_async(struct io_kiocb *req) \
5723 return -EOPNOTSUPP; \
5726 IO_NETOP_PREP_ASYNC(sendmsg);
5727 IO_NETOP_PREP_ASYNC(recvmsg);
5728 IO_NETOP_PREP_ASYNC(connect);
5729 IO_NETOP_PREP(accept);
5732 #endif /* CONFIG_NET */
5734 struct io_poll_table {
5735 struct poll_table_struct pt;
5736 struct io_kiocb *req;
5741 #define IO_POLL_CANCEL_FLAG BIT(31)
5742 #define IO_POLL_REF_MASK GENMASK(30, 0)
5745 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5746 * bump it and acquire ownership. It's disallowed to modify requests while not
5747 * owning it, that prevents from races for enqueueing task_work's and b/w
5748 * arming poll and wakeups.
5750 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5752 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5755 static void io_poll_mark_cancelled(struct io_kiocb *req)
5757 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5760 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5762 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5763 if (req->opcode == IORING_OP_POLL_ADD)
5764 return req->async_data;
5765 return req->apoll->double_poll;
5768 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5770 if (req->opcode == IORING_OP_POLL_ADD)
5772 return &req->apoll->poll;
5775 static void io_poll_req_insert(struct io_kiocb *req)
5777 struct io_ring_ctx *ctx = req->ctx;
5778 struct hlist_head *list;
5780 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5781 hlist_add_head(&req->hash_node, list);
5784 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5785 wait_queue_func_t wake_func)
5788 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5789 /* mask in events that we always want/need */
5790 poll->events = events | IO_POLL_UNMASK;
5791 INIT_LIST_HEAD(&poll->wait.entry);
5792 init_waitqueue_func_entry(&poll->wait, wake_func);
5795 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5797 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5800 spin_lock_irq(&head->lock);
5801 list_del_init(&poll->wait.entry);
5803 spin_unlock_irq(&head->lock);
5807 static void io_poll_remove_entries(struct io_kiocb *req)
5810 * Nothing to do if neither of those flags are set. Avoid dipping
5811 * into the poll/apoll/double cachelines if we can.
5813 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5817 * While we hold the waitqueue lock and the waitqueue is nonempty,
5818 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5819 * lock in the first place can race with the waitqueue being freed.
5821 * We solve this as eventpoll does: by taking advantage of the fact that
5822 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5823 * we enter rcu_read_lock() and see that the pointer to the queue is
5824 * non-NULL, we can then lock it without the memory being freed out from
5827 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5828 * case the caller deletes the entry from the queue, leaving it empty.
5829 * In that case, only RCU prevents the queue memory from being freed.
5832 if (req->flags & REQ_F_SINGLE_POLL)
5833 io_poll_remove_entry(io_poll_get_single(req));
5834 if (req->flags & REQ_F_DOUBLE_POLL)
5835 io_poll_remove_entry(io_poll_get_double(req));
5840 * All poll tw should go through this. Checks for poll events, manages
5841 * references, does rewait, etc.
5843 * Returns a negative error on failure. >0 when no action require, which is
5844 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5845 * the request, then the mask is stored in req->result.
5847 static int io_poll_check_events(struct io_kiocb *req, bool locked)
5849 struct io_ring_ctx *ctx = req->ctx;
5852 /* req->task == current here, checking PF_EXITING is safe */
5853 if (unlikely(req->task->flags & PF_EXITING))
5854 io_poll_mark_cancelled(req);
5857 v = atomic_read(&req->poll_refs);
5859 /* tw handler should be the owner, and so have some references */
5860 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5862 if (v & IO_POLL_CANCEL_FLAG)
5866 struct poll_table_struct pt = { ._key = req->apoll_events };
5867 unsigned flags = locked ? 0 : IO_URING_F_UNLOCKED;
5869 if (unlikely(!io_assign_file(req, flags)))
5871 req->result = vfs_poll(req->file, &pt) & req->apoll_events;
5874 /* multishot, just fill an CQE and proceed */
5875 if (req->result && !(req->apoll_events & EPOLLONESHOT)) {
5876 __poll_t mask = mangle_poll(req->result & req->apoll_events);
5879 spin_lock(&ctx->completion_lock);
5880 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5882 io_commit_cqring(ctx);
5883 spin_unlock(&ctx->completion_lock);
5884 if (unlikely(!filled))
5886 io_cqring_ev_posted(ctx);
5887 } else if (req->result) {
5892 * Release all references, retry if someone tried to restart
5893 * task_work while we were executing it.
5895 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5900 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5902 struct io_ring_ctx *ctx = req->ctx;
5905 ret = io_poll_check_events(req, *locked);
5910 req->result = mangle_poll(req->result & req->poll.events);
5916 io_poll_remove_entries(req);
5917 spin_lock(&ctx->completion_lock);
5918 hash_del(&req->hash_node);
5919 __io_req_complete_post(req, req->result, 0);
5920 io_commit_cqring(ctx);
5921 spin_unlock(&ctx->completion_lock);
5922 io_cqring_ev_posted(ctx);
5925 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5927 struct io_ring_ctx *ctx = req->ctx;
5930 ret = io_poll_check_events(req, *locked);
5934 io_poll_remove_entries(req);
5935 spin_lock(&ctx->completion_lock);
5936 hash_del(&req->hash_node);
5937 spin_unlock(&ctx->completion_lock);
5940 io_req_task_submit(req, locked);
5942 io_req_complete_failed(req, ret);
5945 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
5949 * This is useful for poll that is armed on behalf of another
5950 * request, and where the wakeup path could be on a different
5951 * CPU. We want to avoid pulling in req->apoll->events for that
5954 req->apoll_events = events;
5955 if (req->opcode == IORING_OP_POLL_ADD)
5956 req->io_task_work.func = io_poll_task_func;
5958 req->io_task_work.func = io_apoll_task_func;
5960 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
5961 io_req_task_work_add(req, false);
5964 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
5966 if (io_poll_get_ownership(req))
5967 __io_poll_execute(req, res, events);
5970 static void io_poll_cancel_req(struct io_kiocb *req)
5972 io_poll_mark_cancelled(req);
5973 /* kick tw, which should complete the request */
5974 io_poll_execute(req, 0, 0);
5977 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
5978 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
5980 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5983 struct io_kiocb *req = wqe_to_req(wait);
5984 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5986 __poll_t mask = key_to_poll(key);
5988 if (unlikely(mask & POLLFREE)) {
5989 io_poll_mark_cancelled(req);
5990 /* we have to kick tw in case it's not already */
5991 io_poll_execute(req, 0, poll->events);
5994 * If the waitqueue is being freed early but someone is already
5995 * holds ownership over it, we have to tear down the request as
5996 * best we can. That means immediately removing the request from
5997 * its waitqueue and preventing all further accesses to the
5998 * waitqueue via the request.
6000 list_del_init(&poll->wait.entry);
6003 * Careful: this *must* be the last step, since as soon
6004 * as req->head is NULL'ed out, the request can be
6005 * completed and freed, since aio_poll_complete_work()
6006 * will no longer need to take the waitqueue lock.
6008 smp_store_release(&poll->head, NULL);
6012 /* for instances that support it check for an event match first */
6013 if (mask && !(mask & poll->events))
6016 if (io_poll_get_ownership(req)) {
6017 /* optional, saves extra locking for removal in tw handler */
6018 if (mask && poll->events & EPOLLONESHOT) {
6019 list_del_init(&poll->wait.entry);
6021 if (wqe_is_double(wait))
6022 req->flags &= ~REQ_F_DOUBLE_POLL;
6024 req->flags &= ~REQ_F_SINGLE_POLL;
6026 __io_poll_execute(req, mask, poll->events);
6031 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6032 struct wait_queue_head *head,
6033 struct io_poll_iocb **poll_ptr)
6035 struct io_kiocb *req = pt->req;
6036 unsigned long wqe_private = (unsigned long) req;
6039 * The file being polled uses multiple waitqueues for poll handling
6040 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6043 if (unlikely(pt->nr_entries)) {
6044 struct io_poll_iocb *first = poll;
6046 /* double add on the same waitqueue head, ignore */
6047 if (first->head == head)
6049 /* already have a 2nd entry, fail a third attempt */
6051 if ((*poll_ptr)->head == head)
6053 pt->error = -EINVAL;
6057 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6059 pt->error = -ENOMEM;
6062 /* mark as double wq entry */
6064 req->flags |= REQ_F_DOUBLE_POLL;
6065 io_init_poll_iocb(poll, first->events, first->wait.func);
6067 if (req->opcode == IORING_OP_POLL_ADD)
6068 req->flags |= REQ_F_ASYNC_DATA;
6071 req->flags |= REQ_F_SINGLE_POLL;
6074 poll->wait.private = (void *) wqe_private;
6076 if (poll->events & EPOLLEXCLUSIVE)
6077 add_wait_queue_exclusive(head, &poll->wait);
6079 add_wait_queue(head, &poll->wait);
6082 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6083 struct poll_table_struct *p)
6085 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6087 __io_queue_proc(&pt->req->poll, pt, head,
6088 (struct io_poll_iocb **) &pt->req->async_data);
6091 static int __io_arm_poll_handler(struct io_kiocb *req,
6092 struct io_poll_iocb *poll,
6093 struct io_poll_table *ipt, __poll_t mask)
6095 struct io_ring_ctx *ctx = req->ctx;
6098 INIT_HLIST_NODE(&req->hash_node);
6099 io_init_poll_iocb(poll, mask, io_poll_wake);
6100 poll->file = req->file;
6102 ipt->pt._key = mask;
6105 ipt->nr_entries = 0;
6108 * Take the ownership to delay any tw execution up until we're done
6109 * with poll arming. see io_poll_get_ownership().
6111 atomic_set(&req->poll_refs, 1);
6112 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6114 if (mask && (poll->events & EPOLLONESHOT)) {
6115 io_poll_remove_entries(req);
6116 /* no one else has access to the req, forget about the ref */
6119 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6120 io_poll_remove_entries(req);
6122 ipt->error = -EINVAL;
6126 spin_lock(&ctx->completion_lock);
6127 io_poll_req_insert(req);
6128 spin_unlock(&ctx->completion_lock);
6131 /* can't multishot if failed, just queue the event we've got */
6132 if (unlikely(ipt->error || !ipt->nr_entries))
6133 poll->events |= EPOLLONESHOT;
6134 __io_poll_execute(req, mask, poll->events);
6139 * Release ownership. If someone tried to queue a tw while it was
6140 * locked, kick it off for them.
6142 v = atomic_dec_return(&req->poll_refs);
6143 if (unlikely(v & IO_POLL_REF_MASK))
6144 __io_poll_execute(req, 0, poll->events);
6148 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6149 struct poll_table_struct *p)
6151 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6152 struct async_poll *apoll = pt->req->apoll;
6154 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6163 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6165 const struct io_op_def *def = &io_op_defs[req->opcode];
6166 struct io_ring_ctx *ctx = req->ctx;
6167 struct async_poll *apoll;
6168 struct io_poll_table ipt;
6169 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6172 if (!def->pollin && !def->pollout)
6173 return IO_APOLL_ABORTED;
6174 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6175 return IO_APOLL_ABORTED;
6178 mask |= POLLIN | POLLRDNORM;
6180 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6181 if ((req->opcode == IORING_OP_RECVMSG) &&
6182 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6185 mask |= POLLOUT | POLLWRNORM;
6187 if (def->poll_exclusive)
6188 mask |= EPOLLEXCLUSIVE;
6189 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6190 !list_empty(&ctx->apoll_cache)) {
6191 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6193 list_del_init(&apoll->poll.wait.entry);
6195 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6196 if (unlikely(!apoll))
6197 return IO_APOLL_ABORTED;
6199 apoll->double_poll = NULL;
6201 req->flags |= REQ_F_POLLED;
6202 ipt.pt._qproc = io_async_queue_proc;
6204 io_kbuf_recycle(req, issue_flags);
6206 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6207 if (ret || ipt.error)
6208 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6210 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6211 mask, apoll->poll.events);
6216 * Returns true if we found and killed one or more poll requests
6218 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6219 struct task_struct *tsk, bool cancel_all)
6221 struct hlist_node *tmp;
6222 struct io_kiocb *req;
6226 spin_lock(&ctx->completion_lock);
6227 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6228 struct hlist_head *list;
6230 list = &ctx->cancel_hash[i];
6231 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6232 if (io_match_task_safe(req, tsk, cancel_all)) {
6233 hlist_del_init(&req->hash_node);
6234 io_poll_cancel_req(req);
6239 spin_unlock(&ctx->completion_lock);
6243 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6245 __must_hold(&ctx->completion_lock)
6247 struct hlist_head *list;
6248 struct io_kiocb *req;
6250 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6251 hlist_for_each_entry(req, list, hash_node) {
6252 if (sqe_addr != req->user_data)
6254 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6261 static bool io_poll_disarm(struct io_kiocb *req)
6262 __must_hold(&ctx->completion_lock)
6264 if (!io_poll_get_ownership(req))
6266 io_poll_remove_entries(req);
6267 hash_del(&req->hash_node);
6271 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6273 __must_hold(&ctx->completion_lock)
6275 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6279 io_poll_cancel_req(req);
6283 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6288 events = READ_ONCE(sqe->poll32_events);
6290 events = swahw32(events);
6292 if (!(flags & IORING_POLL_ADD_MULTI))
6293 events |= EPOLLONESHOT;
6294 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6297 static int io_poll_update_prep(struct io_kiocb *req,
6298 const struct io_uring_sqe *sqe)
6300 struct io_poll_update *upd = &req->poll_update;
6303 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6305 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6307 flags = READ_ONCE(sqe->len);
6308 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6309 IORING_POLL_ADD_MULTI))
6311 /* meaningless without update */
6312 if (flags == IORING_POLL_ADD_MULTI)
6315 upd->old_user_data = READ_ONCE(sqe->addr);
6316 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6317 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6319 upd->new_user_data = READ_ONCE(sqe->off);
6320 if (!upd->update_user_data && upd->new_user_data)
6322 if (upd->update_events)
6323 upd->events = io_poll_parse_events(sqe, flags);
6324 else if (sqe->poll32_events)
6330 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6332 struct io_poll_iocb *poll = &req->poll;
6335 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6337 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6339 flags = READ_ONCE(sqe->len);
6340 if (flags & ~IORING_POLL_ADD_MULTI)
6342 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6345 io_req_set_refcount(req);
6346 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
6350 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6352 struct io_poll_iocb *poll = &req->poll;
6353 struct io_poll_table ipt;
6356 ipt.pt._qproc = io_poll_queue_proc;
6358 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6359 ret = ret ?: ipt.error;
6361 __io_req_complete(req, issue_flags, ret, 0);
6365 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6367 struct io_ring_ctx *ctx = req->ctx;
6368 struct io_kiocb *preq;
6372 spin_lock(&ctx->completion_lock);
6373 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6374 if (!preq || !io_poll_disarm(preq)) {
6375 spin_unlock(&ctx->completion_lock);
6376 ret = preq ? -EALREADY : -ENOENT;
6379 spin_unlock(&ctx->completion_lock);
6381 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6382 /* only mask one event flags, keep behavior flags */
6383 if (req->poll_update.update_events) {
6384 preq->poll.events &= ~0xffff;
6385 preq->poll.events |= req->poll_update.events & 0xffff;
6386 preq->poll.events |= IO_POLL_UNMASK;
6388 if (req->poll_update.update_user_data)
6389 preq->user_data = req->poll_update.new_user_data;
6391 ret2 = io_poll_add(preq, issue_flags);
6392 /* successfully updated, don't complete poll request */
6398 preq->result = -ECANCELED;
6399 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6400 io_req_task_complete(preq, &locked);
6404 /* complete update request, we're done with it */
6405 __io_req_complete(req, issue_flags, ret, 0);
6409 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6411 struct io_timeout_data *data = container_of(timer,
6412 struct io_timeout_data, timer);
6413 struct io_kiocb *req = data->req;
6414 struct io_ring_ctx *ctx = req->ctx;
6415 unsigned long flags;
6417 spin_lock_irqsave(&ctx->timeout_lock, flags);
6418 list_del_init(&req->timeout.list);
6419 atomic_set(&req->ctx->cq_timeouts,
6420 atomic_read(&req->ctx->cq_timeouts) + 1);
6421 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6423 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6426 req->result = -ETIME;
6427 req->io_task_work.func = io_req_task_complete;
6428 io_req_task_work_add(req, false);
6429 return HRTIMER_NORESTART;
6432 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6434 __must_hold(&ctx->timeout_lock)
6436 struct io_timeout_data *io;
6437 struct io_kiocb *req;
6440 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6441 found = user_data == req->user_data;
6446 return ERR_PTR(-ENOENT);
6448 io = req->async_data;
6449 if (hrtimer_try_to_cancel(&io->timer) == -1)
6450 return ERR_PTR(-EALREADY);
6451 list_del_init(&req->timeout.list);
6455 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6456 __must_hold(&ctx->completion_lock)
6457 __must_hold(&ctx->timeout_lock)
6459 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6462 return PTR_ERR(req);
6463 io_req_task_queue_fail(req, -ECANCELED);
6467 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6469 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6470 case IORING_TIMEOUT_BOOTTIME:
6471 return CLOCK_BOOTTIME;
6472 case IORING_TIMEOUT_REALTIME:
6473 return CLOCK_REALTIME;
6475 /* can't happen, vetted at prep time */
6479 return CLOCK_MONOTONIC;
6483 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6484 struct timespec64 *ts, enum hrtimer_mode mode)
6485 __must_hold(&ctx->timeout_lock)
6487 struct io_timeout_data *io;
6488 struct io_kiocb *req;
6491 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6492 found = user_data == req->user_data;
6499 io = req->async_data;
6500 if (hrtimer_try_to_cancel(&io->timer) == -1)
6502 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6503 io->timer.function = io_link_timeout_fn;
6504 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6508 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6509 struct timespec64 *ts, enum hrtimer_mode mode)
6510 __must_hold(&ctx->timeout_lock)
6512 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6513 struct io_timeout_data *data;
6516 return PTR_ERR(req);
6518 req->timeout.off = 0; /* noseq */
6519 data = req->async_data;
6520 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6521 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6522 data->timer.function = io_timeout_fn;
6523 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6527 static int io_timeout_remove_prep(struct io_kiocb *req,
6528 const struct io_uring_sqe *sqe)
6530 struct io_timeout_rem *tr = &req->timeout_rem;
6532 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6534 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6536 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6539 tr->ltimeout = false;
6540 tr->addr = READ_ONCE(sqe->addr);
6541 tr->flags = READ_ONCE(sqe->timeout_flags);
6542 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6543 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6545 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6546 tr->ltimeout = true;
6547 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6549 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6551 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6553 } else if (tr->flags) {
6554 /* timeout removal doesn't support flags */
6561 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6563 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6568 * Remove or update an existing timeout command
6570 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6572 struct io_timeout_rem *tr = &req->timeout_rem;
6573 struct io_ring_ctx *ctx = req->ctx;
6576 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6577 spin_lock(&ctx->completion_lock);
6578 spin_lock_irq(&ctx->timeout_lock);
6579 ret = io_timeout_cancel(ctx, tr->addr);
6580 spin_unlock_irq(&ctx->timeout_lock);
6581 spin_unlock(&ctx->completion_lock);
6583 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6585 spin_lock_irq(&ctx->timeout_lock);
6587 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6589 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6590 spin_unlock_irq(&ctx->timeout_lock);
6595 io_req_complete_post(req, ret, 0);
6599 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6600 bool is_timeout_link)
6602 struct io_timeout_data *data;
6604 u32 off = READ_ONCE(sqe->off);
6606 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6608 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6611 if (off && is_timeout_link)
6613 flags = READ_ONCE(sqe->timeout_flags);
6614 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6615 IORING_TIMEOUT_ETIME_SUCCESS))
6617 /* more than one clock specified is invalid, obviously */
6618 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6621 INIT_LIST_HEAD(&req->timeout.list);
6622 req->timeout.off = off;
6623 if (unlikely(off && !req->ctx->off_timeout_used))
6624 req->ctx->off_timeout_used = true;
6626 if (WARN_ON_ONCE(req_has_async_data(req)))
6628 if (io_alloc_async_data(req))
6631 data = req->async_data;
6633 data->flags = flags;
6635 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6638 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6641 INIT_LIST_HEAD(&req->timeout.list);
6642 data->mode = io_translate_timeout_mode(flags);
6643 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6645 if (is_timeout_link) {
6646 struct io_submit_link *link = &req->ctx->submit_state.link;
6650 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6652 req->timeout.head = link->last;
6653 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6658 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6660 struct io_ring_ctx *ctx = req->ctx;
6661 struct io_timeout_data *data = req->async_data;
6662 struct list_head *entry;
6663 u32 tail, off = req->timeout.off;
6665 spin_lock_irq(&ctx->timeout_lock);
6668 * sqe->off holds how many events that need to occur for this
6669 * timeout event to be satisfied. If it isn't set, then this is
6670 * a pure timeout request, sequence isn't used.
6672 if (io_is_timeout_noseq(req)) {
6673 entry = ctx->timeout_list.prev;
6677 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6678 req->timeout.target_seq = tail + off;
6680 /* Update the last seq here in case io_flush_timeouts() hasn't.
6681 * This is safe because ->completion_lock is held, and submissions
6682 * and completions are never mixed in the same ->completion_lock section.
6684 ctx->cq_last_tm_flush = tail;
6687 * Insertion sort, ensuring the first entry in the list is always
6688 * the one we need first.
6690 list_for_each_prev(entry, &ctx->timeout_list) {
6691 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6694 if (io_is_timeout_noseq(nxt))
6696 /* nxt.seq is behind @tail, otherwise would've been completed */
6697 if (off >= nxt->timeout.target_seq - tail)
6701 list_add(&req->timeout.list, entry);
6702 data->timer.function = io_timeout_fn;
6703 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6704 spin_unlock_irq(&ctx->timeout_lock);
6708 struct io_cancel_data {
6709 struct io_ring_ctx *ctx;
6713 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6715 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6716 struct io_cancel_data *cd = data;
6718 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6721 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6722 struct io_ring_ctx *ctx)
6724 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6725 enum io_wq_cancel cancel_ret;
6728 if (!tctx || !tctx->io_wq)
6731 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6732 switch (cancel_ret) {
6733 case IO_WQ_CANCEL_OK:
6736 case IO_WQ_CANCEL_RUNNING:
6739 case IO_WQ_CANCEL_NOTFOUND:
6747 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6749 struct io_ring_ctx *ctx = req->ctx;
6752 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6754 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6756 * Fall-through even for -EALREADY, as we may have poll armed
6757 * that need unarming.
6762 spin_lock(&ctx->completion_lock);
6763 ret = io_poll_cancel(ctx, sqe_addr, false);
6767 spin_lock_irq(&ctx->timeout_lock);
6768 ret = io_timeout_cancel(ctx, sqe_addr);
6769 spin_unlock_irq(&ctx->timeout_lock);
6771 spin_unlock(&ctx->completion_lock);
6775 static int io_async_cancel_prep(struct io_kiocb *req,
6776 const struct io_uring_sqe *sqe)
6778 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6780 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6782 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6786 req->cancel.addr = READ_ONCE(sqe->addr);
6790 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6792 struct io_ring_ctx *ctx = req->ctx;
6793 u64 sqe_addr = req->cancel.addr;
6794 struct io_tctx_node *node;
6797 ret = io_try_cancel_userdata(req, sqe_addr);
6801 /* slow path, try all io-wq's */
6802 io_ring_submit_lock(ctx, issue_flags);
6804 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6805 struct io_uring_task *tctx = node->task->io_uring;
6807 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6811 io_ring_submit_unlock(ctx, issue_flags);
6815 io_req_complete_post(req, ret, 0);
6819 static int io_rsrc_update_prep(struct io_kiocb *req,
6820 const struct io_uring_sqe *sqe)
6822 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6824 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6827 req->rsrc_update.offset = READ_ONCE(sqe->off);
6828 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6829 if (!req->rsrc_update.nr_args)
6831 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6835 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6837 struct io_ring_ctx *ctx = req->ctx;
6838 struct io_uring_rsrc_update2 up;
6841 up.offset = req->rsrc_update.offset;
6842 up.data = req->rsrc_update.arg;
6848 io_ring_submit_lock(ctx, issue_flags);
6849 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6850 &up, req->rsrc_update.nr_args);
6851 io_ring_submit_unlock(ctx, issue_flags);
6855 __io_req_complete(req, issue_flags, ret, 0);
6859 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6861 switch (req->opcode) {
6864 case IORING_OP_READV:
6865 case IORING_OP_READ_FIXED:
6866 case IORING_OP_READ:
6867 case IORING_OP_WRITEV:
6868 case IORING_OP_WRITE_FIXED:
6869 case IORING_OP_WRITE:
6870 return io_prep_rw(req, sqe);
6871 case IORING_OP_POLL_ADD:
6872 return io_poll_add_prep(req, sqe);
6873 case IORING_OP_POLL_REMOVE:
6874 return io_poll_update_prep(req, sqe);
6875 case IORING_OP_FSYNC:
6876 return io_fsync_prep(req, sqe);
6877 case IORING_OP_SYNC_FILE_RANGE:
6878 return io_sfr_prep(req, sqe);
6879 case IORING_OP_SENDMSG:
6880 case IORING_OP_SEND:
6881 return io_sendmsg_prep(req, sqe);
6882 case IORING_OP_RECVMSG:
6883 case IORING_OP_RECV:
6884 return io_recvmsg_prep(req, sqe);
6885 case IORING_OP_CONNECT:
6886 return io_connect_prep(req, sqe);
6887 case IORING_OP_TIMEOUT:
6888 return io_timeout_prep(req, sqe, false);
6889 case IORING_OP_TIMEOUT_REMOVE:
6890 return io_timeout_remove_prep(req, sqe);
6891 case IORING_OP_ASYNC_CANCEL:
6892 return io_async_cancel_prep(req, sqe);
6893 case IORING_OP_LINK_TIMEOUT:
6894 return io_timeout_prep(req, sqe, true);
6895 case IORING_OP_ACCEPT:
6896 return io_accept_prep(req, sqe);
6897 case IORING_OP_FALLOCATE:
6898 return io_fallocate_prep(req, sqe);
6899 case IORING_OP_OPENAT:
6900 return io_openat_prep(req, sqe);
6901 case IORING_OP_CLOSE:
6902 return io_close_prep(req, sqe);
6903 case IORING_OP_FILES_UPDATE:
6904 return io_rsrc_update_prep(req, sqe);
6905 case IORING_OP_STATX:
6906 return io_statx_prep(req, sqe);
6907 case IORING_OP_FADVISE:
6908 return io_fadvise_prep(req, sqe);
6909 case IORING_OP_MADVISE:
6910 return io_madvise_prep(req, sqe);
6911 case IORING_OP_OPENAT2:
6912 return io_openat2_prep(req, sqe);
6913 case IORING_OP_EPOLL_CTL:
6914 return io_epoll_ctl_prep(req, sqe);
6915 case IORING_OP_SPLICE:
6916 return io_splice_prep(req, sqe);
6917 case IORING_OP_PROVIDE_BUFFERS:
6918 return io_provide_buffers_prep(req, sqe);
6919 case IORING_OP_REMOVE_BUFFERS:
6920 return io_remove_buffers_prep(req, sqe);
6922 return io_tee_prep(req, sqe);
6923 case IORING_OP_SHUTDOWN:
6924 return io_shutdown_prep(req, sqe);
6925 case IORING_OP_RENAMEAT:
6926 return io_renameat_prep(req, sqe);
6927 case IORING_OP_UNLINKAT:
6928 return io_unlinkat_prep(req, sqe);
6929 case IORING_OP_MKDIRAT:
6930 return io_mkdirat_prep(req, sqe);
6931 case IORING_OP_SYMLINKAT:
6932 return io_symlinkat_prep(req, sqe);
6933 case IORING_OP_LINKAT:
6934 return io_linkat_prep(req, sqe);
6935 case IORING_OP_MSG_RING:
6936 return io_msg_ring_prep(req, sqe);
6939 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6944 static int io_req_prep_async(struct io_kiocb *req)
6946 if (!io_op_defs[req->opcode].needs_async_setup)
6948 if (WARN_ON_ONCE(req_has_async_data(req)))
6950 if (io_alloc_async_data(req))
6953 switch (req->opcode) {
6954 case IORING_OP_READV:
6955 return io_rw_prep_async(req, READ);
6956 case IORING_OP_WRITEV:
6957 return io_rw_prep_async(req, WRITE);
6958 case IORING_OP_SENDMSG:
6959 return io_sendmsg_prep_async(req);
6960 case IORING_OP_RECVMSG:
6961 return io_recvmsg_prep_async(req);
6962 case IORING_OP_CONNECT:
6963 return io_connect_prep_async(req);
6965 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6970 static u32 io_get_sequence(struct io_kiocb *req)
6972 u32 seq = req->ctx->cached_sq_head;
6973 struct io_kiocb *cur;
6975 /* need original cached_sq_head, but it was increased for each req */
6976 io_for_each_link(cur, req)
6981 static __cold void io_drain_req(struct io_kiocb *req)
6983 struct io_ring_ctx *ctx = req->ctx;
6984 struct io_defer_entry *de;
6986 u32 seq = io_get_sequence(req);
6988 /* Still need defer if there is pending req in defer list. */
6989 spin_lock(&ctx->completion_lock);
6990 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6991 spin_unlock(&ctx->completion_lock);
6993 ctx->drain_active = false;
6994 io_req_task_queue(req);
6997 spin_unlock(&ctx->completion_lock);
6999 ret = io_req_prep_async(req);
7002 io_req_complete_failed(req, ret);
7005 io_prep_async_link(req);
7006 de = kmalloc(sizeof(*de), GFP_KERNEL);
7012 spin_lock(&ctx->completion_lock);
7013 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7014 spin_unlock(&ctx->completion_lock);
7019 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7022 list_add_tail(&de->list, &ctx->defer_list);
7023 spin_unlock(&ctx->completion_lock);
7026 static void io_clean_op(struct io_kiocb *req)
7028 if (req->flags & REQ_F_BUFFER_SELECTED) {
7029 spin_lock(&req->ctx->completion_lock);
7030 io_put_kbuf_comp(req);
7031 spin_unlock(&req->ctx->completion_lock);
7034 if (req->flags & REQ_F_NEED_CLEANUP) {
7035 switch (req->opcode) {
7036 case IORING_OP_READV:
7037 case IORING_OP_READ_FIXED:
7038 case IORING_OP_READ:
7039 case IORING_OP_WRITEV:
7040 case IORING_OP_WRITE_FIXED:
7041 case IORING_OP_WRITE: {
7042 struct io_async_rw *io = req->async_data;
7044 kfree(io->free_iovec);
7047 case IORING_OP_RECVMSG:
7048 case IORING_OP_SENDMSG: {
7049 struct io_async_msghdr *io = req->async_data;
7051 kfree(io->free_iov);
7054 case IORING_OP_OPENAT:
7055 case IORING_OP_OPENAT2:
7056 if (req->open.filename)
7057 putname(req->open.filename);
7059 case IORING_OP_RENAMEAT:
7060 putname(req->rename.oldpath);
7061 putname(req->rename.newpath);
7063 case IORING_OP_UNLINKAT:
7064 putname(req->unlink.filename);
7066 case IORING_OP_MKDIRAT:
7067 putname(req->mkdir.filename);
7069 case IORING_OP_SYMLINKAT:
7070 putname(req->symlink.oldpath);
7071 putname(req->symlink.newpath);
7073 case IORING_OP_LINKAT:
7074 putname(req->hardlink.oldpath);
7075 putname(req->hardlink.newpath);
7077 case IORING_OP_STATX:
7078 if (req->statx.filename)
7079 putname(req->statx.filename);
7083 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7084 kfree(req->apoll->double_poll);
7088 if (req->flags & REQ_F_CREDS)
7089 put_cred(req->creds);
7090 if (req->flags & REQ_F_ASYNC_DATA) {
7091 kfree(req->async_data);
7092 req->async_data = NULL;
7094 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7097 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
7099 if (req->file || !io_op_defs[req->opcode].needs_file)
7102 if (req->flags & REQ_F_FIXED_FILE)
7103 req->file = io_file_get_fixed(req, req->fd, issue_flags);
7105 req->file = io_file_get_normal(req, req->fd);
7110 req->result = -EBADF;
7114 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7116 const struct cred *creds = NULL;
7119 if (unlikely(!io_assign_file(req, issue_flags)))
7122 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7123 creds = override_creds(req->creds);
7125 if (!io_op_defs[req->opcode].audit_skip)
7126 audit_uring_entry(req->opcode);
7128 switch (req->opcode) {
7130 ret = io_nop(req, issue_flags);
7132 case IORING_OP_READV:
7133 case IORING_OP_READ_FIXED:
7134 case IORING_OP_READ:
7135 ret = io_read(req, issue_flags);
7137 case IORING_OP_WRITEV:
7138 case IORING_OP_WRITE_FIXED:
7139 case IORING_OP_WRITE:
7140 ret = io_write(req, issue_flags);
7142 case IORING_OP_FSYNC:
7143 ret = io_fsync(req, issue_flags);
7145 case IORING_OP_POLL_ADD:
7146 ret = io_poll_add(req, issue_flags);
7148 case IORING_OP_POLL_REMOVE:
7149 ret = io_poll_update(req, issue_flags);
7151 case IORING_OP_SYNC_FILE_RANGE:
7152 ret = io_sync_file_range(req, issue_flags);
7154 case IORING_OP_SENDMSG:
7155 ret = io_sendmsg(req, issue_flags);
7157 case IORING_OP_SEND:
7158 ret = io_send(req, issue_flags);
7160 case IORING_OP_RECVMSG:
7161 ret = io_recvmsg(req, issue_flags);
7163 case IORING_OP_RECV:
7164 ret = io_recv(req, issue_flags);
7166 case IORING_OP_TIMEOUT:
7167 ret = io_timeout(req, issue_flags);
7169 case IORING_OP_TIMEOUT_REMOVE:
7170 ret = io_timeout_remove(req, issue_flags);
7172 case IORING_OP_ACCEPT:
7173 ret = io_accept(req, issue_flags);
7175 case IORING_OP_CONNECT:
7176 ret = io_connect(req, issue_flags);
7178 case IORING_OP_ASYNC_CANCEL:
7179 ret = io_async_cancel(req, issue_flags);
7181 case IORING_OP_FALLOCATE:
7182 ret = io_fallocate(req, issue_flags);
7184 case IORING_OP_OPENAT:
7185 ret = io_openat(req, issue_flags);
7187 case IORING_OP_CLOSE:
7188 ret = io_close(req, issue_flags);
7190 case IORING_OP_FILES_UPDATE:
7191 ret = io_files_update(req, issue_flags);
7193 case IORING_OP_STATX:
7194 ret = io_statx(req, issue_flags);
7196 case IORING_OP_FADVISE:
7197 ret = io_fadvise(req, issue_flags);
7199 case IORING_OP_MADVISE:
7200 ret = io_madvise(req, issue_flags);
7202 case IORING_OP_OPENAT2:
7203 ret = io_openat2(req, issue_flags);
7205 case IORING_OP_EPOLL_CTL:
7206 ret = io_epoll_ctl(req, issue_flags);
7208 case IORING_OP_SPLICE:
7209 ret = io_splice(req, issue_flags);
7211 case IORING_OP_PROVIDE_BUFFERS:
7212 ret = io_provide_buffers(req, issue_flags);
7214 case IORING_OP_REMOVE_BUFFERS:
7215 ret = io_remove_buffers(req, issue_flags);
7218 ret = io_tee(req, issue_flags);
7220 case IORING_OP_SHUTDOWN:
7221 ret = io_shutdown(req, issue_flags);
7223 case IORING_OP_RENAMEAT:
7224 ret = io_renameat(req, issue_flags);
7226 case IORING_OP_UNLINKAT:
7227 ret = io_unlinkat(req, issue_flags);
7229 case IORING_OP_MKDIRAT:
7230 ret = io_mkdirat(req, issue_flags);
7232 case IORING_OP_SYMLINKAT:
7233 ret = io_symlinkat(req, issue_flags);
7235 case IORING_OP_LINKAT:
7236 ret = io_linkat(req, issue_flags);
7238 case IORING_OP_MSG_RING:
7239 ret = io_msg_ring(req, issue_flags);
7246 if (!io_op_defs[req->opcode].audit_skip)
7247 audit_uring_exit(!ret, ret);
7250 revert_creds(creds);
7253 /* If the op doesn't have a file, we're not polling for it */
7254 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7255 io_iopoll_req_issued(req, issue_flags);
7260 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7262 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7264 req = io_put_req_find_next(req);
7265 return req ? &req->work : NULL;
7268 static void io_wq_submit_work(struct io_wq_work *work)
7270 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7271 const struct io_op_def *def = &io_op_defs[req->opcode];
7272 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7273 bool needs_poll = false;
7274 struct io_kiocb *timeout;
7275 int ret = 0, err = -ECANCELED;
7277 /* one will be dropped by ->io_free_work() after returning to io-wq */
7278 if (!(req->flags & REQ_F_REFCOUNT))
7279 __io_req_set_refcount(req, 2);
7283 timeout = io_prep_linked_timeout(req);
7285 io_queue_linked_timeout(timeout);
7288 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7289 if (work->flags & IO_WQ_WORK_CANCEL) {
7291 io_req_task_queue_fail(req, err);
7294 if (!io_assign_file(req, issue_flags)) {
7296 work->flags |= IO_WQ_WORK_CANCEL;
7300 if (req->flags & REQ_F_FORCE_ASYNC) {
7301 bool opcode_poll = def->pollin || def->pollout;
7303 if (opcode_poll && file_can_poll(req->file)) {
7305 issue_flags |= IO_URING_F_NONBLOCK;
7310 ret = io_issue_sqe(req, issue_flags);
7314 * We can get EAGAIN for iopolled IO even though we're
7315 * forcing a sync submission from here, since we can't
7316 * wait for request slots on the block side.
7323 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7325 /* aborted or ready, in either case retry blocking */
7327 issue_flags &= ~IO_URING_F_NONBLOCK;
7330 /* avoid locking problems by failing it from a clean context */
7332 io_req_task_queue_fail(req, ret);
7335 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7338 return &table->files[i];
7341 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7344 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7346 return (struct file *) (slot->file_ptr & FFS_MASK);
7349 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7351 unsigned long file_ptr = (unsigned long) file;
7353 file_ptr |= io_file_get_flags(file);
7354 file_slot->file_ptr = file_ptr;
7357 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
7358 unsigned int issue_flags)
7360 struct io_ring_ctx *ctx = req->ctx;
7361 struct file *file = NULL;
7362 unsigned long file_ptr;
7364 if (issue_flags & IO_URING_F_UNLOCKED)
7365 mutex_lock(&ctx->uring_lock);
7367 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7369 fd = array_index_nospec(fd, ctx->nr_user_files);
7370 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7371 file = (struct file *) (file_ptr & FFS_MASK);
7372 file_ptr &= ~FFS_MASK;
7373 /* mask in overlapping REQ_F and FFS bits */
7374 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7375 io_req_set_rsrc_node(req, ctx, 0);
7377 if (issue_flags & IO_URING_F_UNLOCKED)
7378 mutex_unlock(&ctx->uring_lock);
7383 * Drop the file for requeue operations. Only used of req->file is the
7384 * io_uring descriptor itself.
7386 static void io_drop_inflight_file(struct io_kiocb *req)
7388 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
7391 req->flags &= ~REQ_F_INFLIGHT;
7395 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
7397 struct file *file = fget(fd);
7399 trace_io_uring_file_get(req->ctx, req, req->user_data, fd);
7401 /* we don't allow fixed io_uring files */
7402 if (file && file->f_op == &io_uring_fops)
7403 req->flags |= REQ_F_INFLIGHT;
7407 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7409 struct io_kiocb *prev = req->timeout.prev;
7413 if (!(req->task->flags & PF_EXITING))
7414 ret = io_try_cancel_userdata(req, prev->user_data);
7415 io_req_complete_post(req, ret ?: -ETIME, 0);
7418 io_req_complete_post(req, -ETIME, 0);
7422 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7424 struct io_timeout_data *data = container_of(timer,
7425 struct io_timeout_data, timer);
7426 struct io_kiocb *prev, *req = data->req;
7427 struct io_ring_ctx *ctx = req->ctx;
7428 unsigned long flags;
7430 spin_lock_irqsave(&ctx->timeout_lock, flags);
7431 prev = req->timeout.head;
7432 req->timeout.head = NULL;
7435 * We don't expect the list to be empty, that will only happen if we
7436 * race with the completion of the linked work.
7439 io_remove_next_linked(prev);
7440 if (!req_ref_inc_not_zero(prev))
7443 list_del(&req->timeout.list);
7444 req->timeout.prev = prev;
7445 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7447 req->io_task_work.func = io_req_task_link_timeout;
7448 io_req_task_work_add(req, false);
7449 return HRTIMER_NORESTART;
7452 static void io_queue_linked_timeout(struct io_kiocb *req)
7454 struct io_ring_ctx *ctx = req->ctx;
7456 spin_lock_irq(&ctx->timeout_lock);
7458 * If the back reference is NULL, then our linked request finished
7459 * before we got a chance to setup the timer
7461 if (req->timeout.head) {
7462 struct io_timeout_data *data = req->async_data;
7464 data->timer.function = io_link_timeout_fn;
7465 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7467 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7469 spin_unlock_irq(&ctx->timeout_lock);
7470 /* drop submission reference */
7474 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7475 __must_hold(&req->ctx->uring_lock)
7477 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7479 switch (io_arm_poll_handler(req, 0)) {
7480 case IO_APOLL_READY:
7481 io_req_task_queue(req);
7483 case IO_APOLL_ABORTED:
7485 * Queued up for async execution, worker will release
7486 * submit reference when the iocb is actually submitted.
7488 io_queue_async_work(req, NULL);
7495 io_queue_linked_timeout(linked_timeout);
7498 static inline void __io_queue_sqe(struct io_kiocb *req)
7499 __must_hold(&req->ctx->uring_lock)
7501 struct io_kiocb *linked_timeout;
7504 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7506 if (req->flags & REQ_F_COMPLETE_INLINE) {
7507 io_req_add_compl_list(req);
7511 * We async punt it if the file wasn't marked NOWAIT, or if the file
7512 * doesn't support non-blocking read/write attempts
7515 linked_timeout = io_prep_linked_timeout(req);
7517 io_queue_linked_timeout(linked_timeout);
7518 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7519 io_queue_sqe_arm_apoll(req);
7521 io_req_complete_failed(req, ret);
7525 static void io_queue_sqe_fallback(struct io_kiocb *req)
7526 __must_hold(&req->ctx->uring_lock)
7528 if (req->flags & REQ_F_FAIL) {
7529 io_req_complete_fail_submit(req);
7530 } else if (unlikely(req->ctx->drain_active)) {
7533 int ret = io_req_prep_async(req);
7536 io_req_complete_failed(req, ret);
7538 io_queue_async_work(req, NULL);
7542 static inline void io_queue_sqe(struct io_kiocb *req)
7543 __must_hold(&req->ctx->uring_lock)
7545 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7546 __io_queue_sqe(req);
7548 io_queue_sqe_fallback(req);
7552 * Check SQE restrictions (opcode and flags).
7554 * Returns 'true' if SQE is allowed, 'false' otherwise.
7556 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7557 struct io_kiocb *req,
7558 unsigned int sqe_flags)
7560 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7563 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7564 ctx->restrictions.sqe_flags_required)
7567 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7568 ctx->restrictions.sqe_flags_required))
7574 static void io_init_req_drain(struct io_kiocb *req)
7576 struct io_ring_ctx *ctx = req->ctx;
7577 struct io_kiocb *head = ctx->submit_state.link.head;
7579 ctx->drain_active = true;
7582 * If we need to drain a request in the middle of a link, drain
7583 * the head request and the next request/link after the current
7584 * link. Considering sequential execution of links,
7585 * REQ_F_IO_DRAIN will be maintained for every request of our
7588 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7589 ctx->drain_next = true;
7593 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7594 const struct io_uring_sqe *sqe)
7595 __must_hold(&ctx->uring_lock)
7597 unsigned int sqe_flags;
7601 /* req is partially pre-initialised, see io_preinit_req() */
7602 req->opcode = opcode = READ_ONCE(sqe->opcode);
7603 /* same numerical values with corresponding REQ_F_*, safe to copy */
7604 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7605 req->user_data = READ_ONCE(sqe->user_data);
7607 req->fixed_rsrc_refs = NULL;
7608 req->task = current;
7610 if (unlikely(opcode >= IORING_OP_LAST)) {
7614 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7615 /* enforce forwards compatibility on users */
7616 if (sqe_flags & ~SQE_VALID_FLAGS)
7618 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7619 !io_op_defs[opcode].buffer_select)
7621 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7622 ctx->drain_disabled = true;
7623 if (sqe_flags & IOSQE_IO_DRAIN) {
7624 if (ctx->drain_disabled)
7626 io_init_req_drain(req);
7629 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7630 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7632 /* knock it to the slow queue path, will be drained there */
7633 if (ctx->drain_active)
7634 req->flags |= REQ_F_FORCE_ASYNC;
7635 /* if there is no link, we're at "next" request and need to drain */
7636 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7637 ctx->drain_next = false;
7638 ctx->drain_active = true;
7639 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7643 if (io_op_defs[opcode].needs_file) {
7644 struct io_submit_state *state = &ctx->submit_state;
7646 req->fd = READ_ONCE(sqe->fd);
7649 * Plug now if we have more than 2 IO left after this, and the
7650 * target is potentially a read/write to block based storage.
7652 if (state->need_plug && io_op_defs[opcode].plug) {
7653 state->plug_started = true;
7654 state->need_plug = false;
7655 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7659 personality = READ_ONCE(sqe->personality);
7663 req->creds = xa_load(&ctx->personalities, personality);
7666 get_cred(req->creds);
7667 ret = security_uring_override_creds(req->creds);
7669 put_cred(req->creds);
7672 req->flags |= REQ_F_CREDS;
7675 return io_req_prep(req, sqe);
7678 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7679 const struct io_uring_sqe *sqe)
7680 __must_hold(&ctx->uring_lock)
7682 struct io_submit_link *link = &ctx->submit_state.link;
7685 ret = io_init_req(ctx, req, sqe);
7686 if (unlikely(ret)) {
7687 trace_io_uring_req_failed(sqe, ctx, req, ret);
7689 /* fail even hard links since we don't submit */
7692 * we can judge a link req is failed or cancelled by if
7693 * REQ_F_FAIL is set, but the head is an exception since
7694 * it may be set REQ_F_FAIL because of other req's failure
7695 * so let's leverage req->result to distinguish if a head
7696 * is set REQ_F_FAIL because of its failure or other req's
7697 * failure so that we can set the correct ret code for it.
7698 * init result here to avoid affecting the normal path.
7700 if (!(link->head->flags & REQ_F_FAIL))
7701 req_fail_link_node(link->head, -ECANCELED);
7702 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7704 * the current req is a normal req, we should return
7705 * error and thus break the submittion loop.
7707 io_req_complete_failed(req, ret);
7710 req_fail_link_node(req, ret);
7713 /* don't need @sqe from now on */
7714 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7716 ctx->flags & IORING_SETUP_SQPOLL);
7719 * If we already have a head request, queue this one for async
7720 * submittal once the head completes. If we don't have a head but
7721 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7722 * submitted sync once the chain is complete. If none of those
7723 * conditions are true (normal request), then just queue it.
7726 struct io_kiocb *head = link->head;
7728 if (!(req->flags & REQ_F_FAIL)) {
7729 ret = io_req_prep_async(req);
7730 if (unlikely(ret)) {
7731 req_fail_link_node(req, ret);
7732 if (!(head->flags & REQ_F_FAIL))
7733 req_fail_link_node(head, -ECANCELED);
7736 trace_io_uring_link(ctx, req, head);
7737 link->last->link = req;
7740 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7742 /* last request of a link, enqueue the link */
7745 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7756 * Batched submission is done, ensure local IO is flushed out.
7758 static void io_submit_state_end(struct io_ring_ctx *ctx)
7760 struct io_submit_state *state = &ctx->submit_state;
7762 if (state->link.head)
7763 io_queue_sqe(state->link.head);
7764 /* flush only after queuing links as they can generate completions */
7765 io_submit_flush_completions(ctx);
7766 if (state->plug_started)
7767 blk_finish_plug(&state->plug);
7771 * Start submission side cache.
7773 static void io_submit_state_start(struct io_submit_state *state,
7774 unsigned int max_ios)
7776 state->plug_started = false;
7777 state->need_plug = max_ios > 2;
7778 state->submit_nr = max_ios;
7779 /* set only head, no need to init link_last in advance */
7780 state->link.head = NULL;
7783 static void io_commit_sqring(struct io_ring_ctx *ctx)
7785 struct io_rings *rings = ctx->rings;
7788 * Ensure any loads from the SQEs are done at this point,
7789 * since once we write the new head, the application could
7790 * write new data to them.
7792 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7796 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7797 * that is mapped by userspace. This means that care needs to be taken to
7798 * ensure that reads are stable, as we cannot rely on userspace always
7799 * being a good citizen. If members of the sqe are validated and then later
7800 * used, it's important that those reads are done through READ_ONCE() to
7801 * prevent a re-load down the line.
7803 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7805 unsigned head, mask = ctx->sq_entries - 1;
7806 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7809 * The cached sq head (or cq tail) serves two purposes:
7811 * 1) allows us to batch the cost of updating the user visible
7813 * 2) allows the kernel side to track the head on its own, even
7814 * though the application is the one updating it.
7816 head = READ_ONCE(ctx->sq_array[sq_idx]);
7817 if (likely(head < ctx->sq_entries))
7818 return &ctx->sq_sqes[head];
7820 /* drop invalid entries */
7822 WRITE_ONCE(ctx->rings->sq_dropped,
7823 READ_ONCE(ctx->rings->sq_dropped) + 1);
7827 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7828 __must_hold(&ctx->uring_lock)
7830 unsigned int entries = io_sqring_entries(ctx);
7833 if (unlikely(!entries))
7835 /* make sure SQ entry isn't read before tail */
7836 nr = min3(nr, ctx->sq_entries, entries);
7837 io_get_task_refs(nr);
7839 io_submit_state_start(&ctx->submit_state, nr);
7841 const struct io_uring_sqe *sqe;
7842 struct io_kiocb *req;
7844 if (unlikely(!io_alloc_req_refill(ctx))) {
7846 submitted = -EAGAIN;
7849 req = io_alloc_req(ctx);
7850 sqe = io_get_sqe(ctx);
7851 if (unlikely(!sqe)) {
7852 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7855 /* will complete beyond this point, count as submitted */
7857 if (io_submit_sqe(ctx, req, sqe)) {
7859 * Continue submitting even for sqe failure if the
7860 * ring was setup with IORING_SETUP_SUBMIT_ALL
7862 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7865 } while (submitted < nr);
7867 if (unlikely(submitted != nr)) {
7868 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7869 int unused = nr - ref_used;
7871 current->io_uring->cached_refs += unused;
7874 io_submit_state_end(ctx);
7875 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7876 io_commit_sqring(ctx);
7881 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7883 return READ_ONCE(sqd->state);
7886 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7888 /* Tell userspace we may need a wakeup call */
7889 spin_lock(&ctx->completion_lock);
7890 WRITE_ONCE(ctx->rings->sq_flags,
7891 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7892 spin_unlock(&ctx->completion_lock);
7895 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7897 spin_lock(&ctx->completion_lock);
7898 WRITE_ONCE(ctx->rings->sq_flags,
7899 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7900 spin_unlock(&ctx->completion_lock);
7903 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7905 unsigned int to_submit;
7908 to_submit = io_sqring_entries(ctx);
7909 /* if we're handling multiple rings, cap submit size for fairness */
7910 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7911 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7913 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7914 const struct cred *creds = NULL;
7916 if (ctx->sq_creds != current_cred())
7917 creds = override_creds(ctx->sq_creds);
7919 mutex_lock(&ctx->uring_lock);
7920 if (!wq_list_empty(&ctx->iopoll_list))
7921 io_do_iopoll(ctx, true);
7924 * Don't submit if refs are dying, good for io_uring_register(),
7925 * but also it is relied upon by io_ring_exit_work()
7927 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7928 !(ctx->flags & IORING_SETUP_R_DISABLED))
7929 ret = io_submit_sqes(ctx, to_submit);
7930 mutex_unlock(&ctx->uring_lock);
7932 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7933 wake_up(&ctx->sqo_sq_wait);
7935 revert_creds(creds);
7941 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7943 struct io_ring_ctx *ctx;
7944 unsigned sq_thread_idle = 0;
7946 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7947 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7948 sqd->sq_thread_idle = sq_thread_idle;
7951 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7953 bool did_sig = false;
7954 struct ksignal ksig;
7956 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7957 signal_pending(current)) {
7958 mutex_unlock(&sqd->lock);
7959 if (signal_pending(current))
7960 did_sig = get_signal(&ksig);
7962 mutex_lock(&sqd->lock);
7964 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7967 static int io_sq_thread(void *data)
7969 struct io_sq_data *sqd = data;
7970 struct io_ring_ctx *ctx;
7971 unsigned long timeout = 0;
7972 char buf[TASK_COMM_LEN];
7975 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7976 set_task_comm(current, buf);
7978 if (sqd->sq_cpu != -1)
7979 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7981 set_cpus_allowed_ptr(current, cpu_online_mask);
7982 current->flags |= PF_NO_SETAFFINITY;
7984 audit_alloc_kernel(current);
7986 mutex_lock(&sqd->lock);
7988 bool cap_entries, sqt_spin = false;
7990 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7991 if (io_sqd_handle_event(sqd))
7993 timeout = jiffies + sqd->sq_thread_idle;
7996 cap_entries = !list_is_singular(&sqd->ctx_list);
7997 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7998 int ret = __io_sq_thread(ctx, cap_entries);
8000 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8003 if (io_run_task_work())
8006 if (sqt_spin || !time_after(jiffies, timeout)) {
8009 timeout = jiffies + sqd->sq_thread_idle;
8013 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8014 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8015 bool needs_sched = true;
8017 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8018 io_ring_set_wakeup_flag(ctx);
8020 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8021 !wq_list_empty(&ctx->iopoll_list)) {
8022 needs_sched = false;
8027 * Ensure the store of the wakeup flag is not
8028 * reordered with the load of the SQ tail
8032 if (io_sqring_entries(ctx)) {
8033 needs_sched = false;
8039 mutex_unlock(&sqd->lock);
8041 mutex_lock(&sqd->lock);
8043 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8044 io_ring_clear_wakeup_flag(ctx);
8047 finish_wait(&sqd->wait, &wait);
8048 timeout = jiffies + sqd->sq_thread_idle;
8051 io_uring_cancel_generic(true, sqd);
8053 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8054 io_ring_set_wakeup_flag(ctx);
8056 mutex_unlock(&sqd->lock);
8058 audit_free(current);
8060 complete(&sqd->exited);
8064 struct io_wait_queue {
8065 struct wait_queue_entry wq;
8066 struct io_ring_ctx *ctx;
8068 unsigned nr_timeouts;
8071 static inline bool io_should_wake(struct io_wait_queue *iowq)
8073 struct io_ring_ctx *ctx = iowq->ctx;
8074 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8077 * Wake up if we have enough events, or if a timeout occurred since we
8078 * started waiting. For timeouts, we always want to return to userspace,
8079 * regardless of event count.
8081 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8084 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8085 int wake_flags, void *key)
8087 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8091 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8092 * the task, and the next invocation will do it.
8094 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8095 return autoremove_wake_function(curr, mode, wake_flags, key);
8099 static int io_run_task_work_sig(void)
8101 if (io_run_task_work())
8103 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8104 return -ERESTARTSYS;
8105 if (task_sigpending(current))
8110 /* when returns >0, the caller should retry */
8111 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8112 struct io_wait_queue *iowq,
8117 /* make sure we run task_work before checking for signals */
8118 ret = io_run_task_work_sig();
8119 if (ret || io_should_wake(iowq))
8121 /* let the caller flush overflows, retry */
8122 if (test_bit(0, &ctx->check_cq_overflow))
8125 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8131 * Wait until events become available, if we don't already have some. The
8132 * application must reap them itself, as they reside on the shared cq ring.
8134 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8135 const sigset_t __user *sig, size_t sigsz,
8136 struct __kernel_timespec __user *uts)
8138 struct io_wait_queue iowq;
8139 struct io_rings *rings = ctx->rings;
8140 ktime_t timeout = KTIME_MAX;
8144 io_cqring_overflow_flush(ctx);
8145 if (io_cqring_events(ctx) >= min_events)
8147 if (!io_run_task_work())
8152 #ifdef CONFIG_COMPAT
8153 if (in_compat_syscall())
8154 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8158 ret = set_user_sigmask(sig, sigsz);
8165 struct timespec64 ts;
8167 if (get_timespec64(&ts, uts))
8169 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8172 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8173 iowq.wq.private = current;
8174 INIT_LIST_HEAD(&iowq.wq.entry);
8176 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8177 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8179 trace_io_uring_cqring_wait(ctx, min_events);
8181 /* if we can't even flush overflow, don't wait for more */
8182 if (!io_cqring_overflow_flush(ctx)) {
8186 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8187 TASK_INTERRUPTIBLE);
8188 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8192 finish_wait(&ctx->cq_wait, &iowq.wq);
8193 restore_saved_sigmask_unless(ret == -EINTR);
8195 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8198 static void io_free_page_table(void **table, size_t size)
8200 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8202 for (i = 0; i < nr_tables; i++)
8207 static __cold void **io_alloc_page_table(size_t size)
8209 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8210 size_t init_size = size;
8213 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8217 for (i = 0; i < nr_tables; i++) {
8218 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8220 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8222 io_free_page_table(table, init_size);
8230 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8232 percpu_ref_exit(&ref_node->refs);
8236 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8238 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8239 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8240 unsigned long flags;
8241 bool first_add = false;
8242 unsigned long delay = HZ;
8244 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8247 /* if we are mid-quiesce then do not delay */
8248 if (node->rsrc_data->quiesce)
8251 while (!list_empty(&ctx->rsrc_ref_list)) {
8252 node = list_first_entry(&ctx->rsrc_ref_list,
8253 struct io_rsrc_node, node);
8254 /* recycle ref nodes in order */
8257 list_del(&node->node);
8258 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8260 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8263 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8266 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8268 struct io_rsrc_node *ref_node;
8270 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8274 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8279 INIT_LIST_HEAD(&ref_node->node);
8280 INIT_LIST_HEAD(&ref_node->rsrc_list);
8281 ref_node->done = false;
8285 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8286 struct io_rsrc_data *data_to_kill)
8287 __must_hold(&ctx->uring_lock)
8289 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8290 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8292 io_rsrc_refs_drop(ctx);
8295 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8297 rsrc_node->rsrc_data = data_to_kill;
8298 spin_lock_irq(&ctx->rsrc_ref_lock);
8299 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8300 spin_unlock_irq(&ctx->rsrc_ref_lock);
8302 atomic_inc(&data_to_kill->refs);
8303 percpu_ref_kill(&rsrc_node->refs);
8304 ctx->rsrc_node = NULL;
8307 if (!ctx->rsrc_node) {
8308 ctx->rsrc_node = ctx->rsrc_backup_node;
8309 ctx->rsrc_backup_node = NULL;
8313 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8315 if (ctx->rsrc_backup_node)
8317 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8318 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8321 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8322 struct io_ring_ctx *ctx)
8326 /* As we may drop ->uring_lock, other task may have started quiesce */
8330 data->quiesce = true;
8332 ret = io_rsrc_node_switch_start(ctx);
8335 io_rsrc_node_switch(ctx, data);
8337 /* kill initial ref, already quiesced if zero */
8338 if (atomic_dec_and_test(&data->refs))
8340 mutex_unlock(&ctx->uring_lock);
8341 flush_delayed_work(&ctx->rsrc_put_work);
8342 ret = wait_for_completion_interruptible(&data->done);
8344 mutex_lock(&ctx->uring_lock);
8345 if (atomic_read(&data->refs) > 0) {
8347 * it has been revived by another thread while
8350 mutex_unlock(&ctx->uring_lock);
8356 atomic_inc(&data->refs);
8357 /* wait for all works potentially completing data->done */
8358 flush_delayed_work(&ctx->rsrc_put_work);
8359 reinit_completion(&data->done);
8361 ret = io_run_task_work_sig();
8362 mutex_lock(&ctx->uring_lock);
8364 data->quiesce = false;
8369 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8371 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8372 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8374 return &data->tags[table_idx][off];
8377 static void io_rsrc_data_free(struct io_rsrc_data *data)
8379 size_t size = data->nr * sizeof(data->tags[0][0]);
8382 io_free_page_table((void **)data->tags, size);
8386 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8387 u64 __user *utags, unsigned nr,
8388 struct io_rsrc_data **pdata)
8390 struct io_rsrc_data *data;
8394 data = kzalloc(sizeof(*data), GFP_KERNEL);
8397 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8405 data->do_put = do_put;
8408 for (i = 0; i < nr; i++) {
8409 u64 *tag_slot = io_get_tag_slot(data, i);
8411 if (copy_from_user(tag_slot, &utags[i],
8417 atomic_set(&data->refs, 1);
8418 init_completion(&data->done);
8422 io_rsrc_data_free(data);
8426 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8428 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8429 GFP_KERNEL_ACCOUNT);
8430 return !!table->files;
8433 static void io_free_file_tables(struct io_file_table *table)
8435 kvfree(table->files);
8436 table->files = NULL;
8439 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8443 for (i = 0; i < ctx->nr_user_files; i++) {
8444 struct file *file = io_file_from_index(ctx, i);
8446 if (!file || io_file_need_scm(file))
8448 io_fixed_file_slot(&ctx->file_table, i)->file_ptr = 0;
8452 #if defined(CONFIG_UNIX)
8453 if (ctx->ring_sock) {
8454 struct sock *sock = ctx->ring_sock->sk;
8455 struct sk_buff *skb;
8457 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8461 io_free_file_tables(&ctx->file_table);
8462 io_rsrc_data_free(ctx->file_data);
8463 ctx->file_data = NULL;
8464 ctx->nr_user_files = 0;
8467 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8471 if (!ctx->file_data)
8473 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8475 __io_sqe_files_unregister(ctx);
8479 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8480 __releases(&sqd->lock)
8482 WARN_ON_ONCE(sqd->thread == current);
8485 * Do the dance but not conditional clear_bit() because it'd race with
8486 * other threads incrementing park_pending and setting the bit.
8488 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8489 if (atomic_dec_return(&sqd->park_pending))
8490 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8491 mutex_unlock(&sqd->lock);
8494 static void io_sq_thread_park(struct io_sq_data *sqd)
8495 __acquires(&sqd->lock)
8497 WARN_ON_ONCE(sqd->thread == current);
8499 atomic_inc(&sqd->park_pending);
8500 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8501 mutex_lock(&sqd->lock);
8503 wake_up_process(sqd->thread);
8506 static void io_sq_thread_stop(struct io_sq_data *sqd)
8508 WARN_ON_ONCE(sqd->thread == current);
8509 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8511 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8512 mutex_lock(&sqd->lock);
8514 wake_up_process(sqd->thread);
8515 mutex_unlock(&sqd->lock);
8516 wait_for_completion(&sqd->exited);
8519 static void io_put_sq_data(struct io_sq_data *sqd)
8521 if (refcount_dec_and_test(&sqd->refs)) {
8522 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8524 io_sq_thread_stop(sqd);
8529 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8531 struct io_sq_data *sqd = ctx->sq_data;
8534 io_sq_thread_park(sqd);
8535 list_del_init(&ctx->sqd_list);
8536 io_sqd_update_thread_idle(sqd);
8537 io_sq_thread_unpark(sqd);
8539 io_put_sq_data(sqd);
8540 ctx->sq_data = NULL;
8544 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8546 struct io_ring_ctx *ctx_attach;
8547 struct io_sq_data *sqd;
8550 f = fdget(p->wq_fd);
8552 return ERR_PTR(-ENXIO);
8553 if (f.file->f_op != &io_uring_fops) {
8555 return ERR_PTR(-EINVAL);
8558 ctx_attach = f.file->private_data;
8559 sqd = ctx_attach->sq_data;
8562 return ERR_PTR(-EINVAL);
8564 if (sqd->task_tgid != current->tgid) {
8566 return ERR_PTR(-EPERM);
8569 refcount_inc(&sqd->refs);
8574 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8577 struct io_sq_data *sqd;
8580 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8581 sqd = io_attach_sq_data(p);
8586 /* fall through for EPERM case, setup new sqd/task */
8587 if (PTR_ERR(sqd) != -EPERM)
8591 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8593 return ERR_PTR(-ENOMEM);
8595 atomic_set(&sqd->park_pending, 0);
8596 refcount_set(&sqd->refs, 1);
8597 INIT_LIST_HEAD(&sqd->ctx_list);
8598 mutex_init(&sqd->lock);
8599 init_waitqueue_head(&sqd->wait);
8600 init_completion(&sqd->exited);
8605 * Ensure the UNIX gc is aware of our file set, so we are certain that
8606 * the io_uring can be safely unregistered on process exit, even if we have
8607 * loops in the file referencing. We account only files that can hold other
8608 * files because otherwise they can't form a loop and so are not interesting
8611 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file)
8613 #if defined(CONFIG_UNIX)
8614 struct sock *sk = ctx->ring_sock->sk;
8615 struct sk_buff_head *head = &sk->sk_receive_queue;
8616 struct scm_fp_list *fpl;
8617 struct sk_buff *skb;
8619 if (likely(!io_file_need_scm(file)))
8623 * See if we can merge this file into an existing skb SCM_RIGHTS
8624 * file set. If there's no room, fall back to allocating a new skb
8625 * and filling it in.
8627 spin_lock_irq(&head->lock);
8628 skb = skb_peek(head);
8629 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
8630 __skb_unlink(skb, head);
8633 spin_unlock_irq(&head->lock);
8636 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8640 skb = alloc_skb(0, GFP_KERNEL);
8646 fpl->user = get_uid(current_user());
8647 fpl->max = SCM_MAX_FD;
8650 UNIXCB(skb).fp = fpl;
8652 skb->destructor = unix_destruct_scm;
8653 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8656 fpl = UNIXCB(skb).fp;
8657 fpl->fp[fpl->count++] = get_file(file);
8658 unix_inflight(fpl->user, file);
8659 skb_queue_head(head, skb);
8665 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8667 struct file *file = prsrc->file;
8668 #if defined(CONFIG_UNIX)
8669 struct sock *sock = ctx->ring_sock->sk;
8670 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8671 struct sk_buff *skb;
8674 if (!io_file_need_scm(file)) {
8679 __skb_queue_head_init(&list);
8682 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8683 * remove this entry and rearrange the file array.
8685 skb = skb_dequeue(head);
8687 struct scm_fp_list *fp;
8689 fp = UNIXCB(skb).fp;
8690 for (i = 0; i < fp->count; i++) {
8693 if (fp->fp[i] != file)
8696 unix_notinflight(fp->user, fp->fp[i]);
8697 left = fp->count - 1 - i;
8699 memmove(&fp->fp[i], &fp->fp[i + 1],
8700 left * sizeof(struct file *));
8707 __skb_queue_tail(&list, skb);
8717 __skb_queue_tail(&list, skb);
8719 skb = skb_dequeue(head);
8722 if (skb_peek(&list)) {
8723 spin_lock_irq(&head->lock);
8724 while ((skb = __skb_dequeue(&list)) != NULL)
8725 __skb_queue_tail(head, skb);
8726 spin_unlock_irq(&head->lock);
8733 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8735 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8736 struct io_ring_ctx *ctx = rsrc_data->ctx;
8737 struct io_rsrc_put *prsrc, *tmp;
8739 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8740 list_del(&prsrc->list);
8743 if (ctx->flags & IORING_SETUP_IOPOLL)
8744 mutex_lock(&ctx->uring_lock);
8746 spin_lock(&ctx->completion_lock);
8747 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8748 io_commit_cqring(ctx);
8749 spin_unlock(&ctx->completion_lock);
8750 io_cqring_ev_posted(ctx);
8752 if (ctx->flags & IORING_SETUP_IOPOLL)
8753 mutex_unlock(&ctx->uring_lock);
8756 rsrc_data->do_put(ctx, prsrc);
8760 io_rsrc_node_destroy(ref_node);
8761 if (atomic_dec_and_test(&rsrc_data->refs))
8762 complete(&rsrc_data->done);
8765 static void io_rsrc_put_work(struct work_struct *work)
8767 struct io_ring_ctx *ctx;
8768 struct llist_node *node;
8770 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8771 node = llist_del_all(&ctx->rsrc_put_llist);
8774 struct io_rsrc_node *ref_node;
8775 struct llist_node *next = node->next;
8777 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8778 __io_rsrc_put_work(ref_node);
8783 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8784 unsigned nr_args, u64 __user *tags)
8786 __s32 __user *fds = (__s32 __user *) arg;
8795 if (nr_args > IORING_MAX_FIXED_FILES)
8797 if (nr_args > rlimit(RLIMIT_NOFILE))
8799 ret = io_rsrc_node_switch_start(ctx);
8802 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8807 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
8808 io_rsrc_data_free(ctx->file_data);
8809 ctx->file_data = NULL;
8813 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8814 struct io_fixed_file *file_slot;
8816 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8820 /* allow sparse sets */
8823 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8830 if (unlikely(!file))
8834 * Don't allow io_uring instances to be registered. If UNIX
8835 * isn't enabled, then this causes a reference cycle and this
8836 * instance can never get freed. If UNIX is enabled we'll
8837 * handle it just fine, but there's still no point in allowing
8838 * a ring fd as it doesn't support regular read/write anyway.
8840 if (file->f_op == &io_uring_fops) {
8844 ret = io_sqe_file_register(ctx, file);
8849 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8850 io_fixed_file_set(file_slot, file);
8853 io_rsrc_node_switch(ctx, NULL);
8856 __io_sqe_files_unregister(ctx);
8860 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8861 struct io_rsrc_node *node, void *rsrc)
8863 u64 *tag_slot = io_get_tag_slot(data, idx);
8864 struct io_rsrc_put *prsrc;
8866 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8870 prsrc->tag = *tag_slot;
8873 list_add(&prsrc->list, &node->rsrc_list);
8877 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8878 unsigned int issue_flags, u32 slot_index)
8880 struct io_ring_ctx *ctx = req->ctx;
8881 bool needs_switch = false;
8882 struct io_fixed_file *file_slot;
8885 io_ring_submit_lock(ctx, issue_flags);
8886 if (file->f_op == &io_uring_fops)
8889 if (!ctx->file_data)
8892 if (slot_index >= ctx->nr_user_files)
8895 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8896 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8898 if (file_slot->file_ptr) {
8899 struct file *old_file;
8901 ret = io_rsrc_node_switch_start(ctx);
8905 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8906 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8907 ctx->rsrc_node, old_file);
8910 file_slot->file_ptr = 0;
8911 needs_switch = true;
8914 ret = io_sqe_file_register(ctx, file);
8916 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8917 io_fixed_file_set(file_slot, file);
8921 io_rsrc_node_switch(ctx, ctx->file_data);
8922 io_ring_submit_unlock(ctx, issue_flags);
8928 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8930 unsigned int offset = req->close.file_slot - 1;
8931 struct io_ring_ctx *ctx = req->ctx;
8932 struct io_fixed_file *file_slot;
8936 io_ring_submit_lock(ctx, issue_flags);
8938 if (unlikely(!ctx->file_data))
8941 if (offset >= ctx->nr_user_files)
8943 ret = io_rsrc_node_switch_start(ctx);
8947 offset = array_index_nospec(offset, ctx->nr_user_files);
8948 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8950 if (!file_slot->file_ptr)
8953 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8954 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8958 file_slot->file_ptr = 0;
8959 io_rsrc_node_switch(ctx, ctx->file_data);
8962 io_ring_submit_unlock(ctx, issue_flags);
8966 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8967 struct io_uring_rsrc_update2 *up,
8970 u64 __user *tags = u64_to_user_ptr(up->tags);
8971 __s32 __user *fds = u64_to_user_ptr(up->data);
8972 struct io_rsrc_data *data = ctx->file_data;
8973 struct io_fixed_file *file_slot;
8977 bool needs_switch = false;
8979 if (!ctx->file_data)
8981 if (up->offset + nr_args > ctx->nr_user_files)
8984 for (done = 0; done < nr_args; done++) {
8987 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8988 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8992 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8996 if (fd == IORING_REGISTER_FILES_SKIP)
8999 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9000 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9002 if (file_slot->file_ptr) {
9003 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9004 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9007 file_slot->file_ptr = 0;
9008 needs_switch = true;
9017 * Don't allow io_uring instances to be registered. If
9018 * UNIX isn't enabled, then this causes a reference
9019 * cycle and this instance can never get freed. If UNIX
9020 * is enabled we'll handle it just fine, but there's
9021 * still no point in allowing a ring fd as it doesn't
9022 * support regular read/write anyway.
9024 if (file->f_op == &io_uring_fops) {
9029 err = io_sqe_file_register(ctx, file);
9034 *io_get_tag_slot(data, i) = tag;
9035 io_fixed_file_set(file_slot, file);
9040 io_rsrc_node_switch(ctx, data);
9041 return done ? done : err;
9044 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9045 struct task_struct *task)
9047 struct io_wq_hash *hash;
9048 struct io_wq_data data;
9049 unsigned int concurrency;
9051 mutex_lock(&ctx->uring_lock);
9052 hash = ctx->hash_map;
9054 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9056 mutex_unlock(&ctx->uring_lock);
9057 return ERR_PTR(-ENOMEM);
9059 refcount_set(&hash->refs, 1);
9060 init_waitqueue_head(&hash->wait);
9061 ctx->hash_map = hash;
9063 mutex_unlock(&ctx->uring_lock);
9067 data.free_work = io_wq_free_work;
9068 data.do_work = io_wq_submit_work;
9070 /* Do QD, or 4 * CPUS, whatever is smallest */
9071 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9073 return io_wq_create(concurrency, &data);
9076 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9077 struct io_ring_ctx *ctx)
9079 struct io_uring_task *tctx;
9082 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9083 if (unlikely(!tctx))
9086 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9087 sizeof(struct file *), GFP_KERNEL);
9088 if (unlikely(!tctx->registered_rings)) {
9093 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9094 if (unlikely(ret)) {
9095 kfree(tctx->registered_rings);
9100 tctx->io_wq = io_init_wq_offload(ctx, task);
9101 if (IS_ERR(tctx->io_wq)) {
9102 ret = PTR_ERR(tctx->io_wq);
9103 percpu_counter_destroy(&tctx->inflight);
9104 kfree(tctx->registered_rings);
9110 init_waitqueue_head(&tctx->wait);
9111 atomic_set(&tctx->in_idle, 0);
9112 task->io_uring = tctx;
9113 spin_lock_init(&tctx->task_lock);
9114 INIT_WQ_LIST(&tctx->task_list);
9115 INIT_WQ_LIST(&tctx->prior_task_list);
9116 init_task_work(&tctx->task_work, tctx_task_work);
9120 void __io_uring_free(struct task_struct *tsk)
9122 struct io_uring_task *tctx = tsk->io_uring;
9124 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9125 WARN_ON_ONCE(tctx->io_wq);
9126 WARN_ON_ONCE(tctx->cached_refs);
9128 kfree(tctx->registered_rings);
9129 percpu_counter_destroy(&tctx->inflight);
9131 tsk->io_uring = NULL;
9134 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9135 struct io_uring_params *p)
9139 /* Retain compatibility with failing for an invalid attach attempt */
9140 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9141 IORING_SETUP_ATTACH_WQ) {
9144 f = fdget(p->wq_fd);
9147 if (f.file->f_op != &io_uring_fops) {
9153 if (ctx->flags & IORING_SETUP_SQPOLL) {
9154 struct task_struct *tsk;
9155 struct io_sq_data *sqd;
9158 ret = security_uring_sqpoll();
9162 sqd = io_get_sq_data(p, &attached);
9168 ctx->sq_creds = get_current_cred();
9170 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9171 if (!ctx->sq_thread_idle)
9172 ctx->sq_thread_idle = HZ;
9174 io_sq_thread_park(sqd);
9175 list_add(&ctx->sqd_list, &sqd->ctx_list);
9176 io_sqd_update_thread_idle(sqd);
9177 /* don't attach to a dying SQPOLL thread, would be racy */
9178 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9179 io_sq_thread_unpark(sqd);
9186 if (p->flags & IORING_SETUP_SQ_AFF) {
9187 int cpu = p->sq_thread_cpu;
9190 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9197 sqd->task_pid = current->pid;
9198 sqd->task_tgid = current->tgid;
9199 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9206 ret = io_uring_alloc_task_context(tsk, ctx);
9207 wake_up_new_task(tsk);
9210 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9211 /* Can't have SQ_AFF without SQPOLL */
9218 complete(&ctx->sq_data->exited);
9220 io_sq_thread_finish(ctx);
9224 static inline void __io_unaccount_mem(struct user_struct *user,
9225 unsigned long nr_pages)
9227 atomic_long_sub(nr_pages, &user->locked_vm);
9230 static inline int __io_account_mem(struct user_struct *user,
9231 unsigned long nr_pages)
9233 unsigned long page_limit, cur_pages, new_pages;
9235 /* Don't allow more pages than we can safely lock */
9236 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9239 cur_pages = atomic_long_read(&user->locked_vm);
9240 new_pages = cur_pages + nr_pages;
9241 if (new_pages > page_limit)
9243 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9244 new_pages) != cur_pages);
9249 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9252 __io_unaccount_mem(ctx->user, nr_pages);
9254 if (ctx->mm_account)
9255 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9258 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9263 ret = __io_account_mem(ctx->user, nr_pages);
9268 if (ctx->mm_account)
9269 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9274 static void io_mem_free(void *ptr)
9281 page = virt_to_head_page(ptr);
9282 if (put_page_testzero(page))
9283 free_compound_page(page);
9286 static void *io_mem_alloc(size_t size)
9288 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9290 return (void *) __get_free_pages(gfp, get_order(size));
9293 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9296 struct io_rings *rings;
9297 size_t off, sq_array_size;
9299 off = struct_size(rings, cqes, cq_entries);
9300 if (off == SIZE_MAX)
9304 off = ALIGN(off, SMP_CACHE_BYTES);
9312 sq_array_size = array_size(sizeof(u32), sq_entries);
9313 if (sq_array_size == SIZE_MAX)
9316 if (check_add_overflow(off, sq_array_size, &off))
9322 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9324 struct io_mapped_ubuf *imu = *slot;
9327 if (imu != ctx->dummy_ubuf) {
9328 for (i = 0; i < imu->nr_bvecs; i++)
9329 unpin_user_page(imu->bvec[i].bv_page);
9330 if (imu->acct_pages)
9331 io_unaccount_mem(ctx, imu->acct_pages);
9337 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9339 io_buffer_unmap(ctx, &prsrc->buf);
9343 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9347 for (i = 0; i < ctx->nr_user_bufs; i++)
9348 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9349 kfree(ctx->user_bufs);
9350 io_rsrc_data_free(ctx->buf_data);
9351 ctx->user_bufs = NULL;
9352 ctx->buf_data = NULL;
9353 ctx->nr_user_bufs = 0;
9356 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9363 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9365 __io_sqe_buffers_unregister(ctx);
9369 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9370 void __user *arg, unsigned index)
9372 struct iovec __user *src;
9374 #ifdef CONFIG_COMPAT
9376 struct compat_iovec __user *ciovs;
9377 struct compat_iovec ciov;
9379 ciovs = (struct compat_iovec __user *) arg;
9380 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9383 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9384 dst->iov_len = ciov.iov_len;
9388 src = (struct iovec __user *) arg;
9389 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9395 * Not super efficient, but this is just a registration time. And we do cache
9396 * the last compound head, so generally we'll only do a full search if we don't
9399 * We check if the given compound head page has already been accounted, to
9400 * avoid double accounting it. This allows us to account the full size of the
9401 * page, not just the constituent pages of a huge page.
9403 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9404 int nr_pages, struct page *hpage)
9408 /* check current page array */
9409 for (i = 0; i < nr_pages; i++) {
9410 if (!PageCompound(pages[i]))
9412 if (compound_head(pages[i]) == hpage)
9416 /* check previously registered pages */
9417 for (i = 0; i < ctx->nr_user_bufs; i++) {
9418 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9420 for (j = 0; j < imu->nr_bvecs; j++) {
9421 if (!PageCompound(imu->bvec[j].bv_page))
9423 if (compound_head(imu->bvec[j].bv_page) == hpage)
9431 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9432 int nr_pages, struct io_mapped_ubuf *imu,
9433 struct page **last_hpage)
9437 imu->acct_pages = 0;
9438 for (i = 0; i < nr_pages; i++) {
9439 if (!PageCompound(pages[i])) {
9444 hpage = compound_head(pages[i]);
9445 if (hpage == *last_hpage)
9447 *last_hpage = hpage;
9448 if (headpage_already_acct(ctx, pages, i, hpage))
9450 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9454 if (!imu->acct_pages)
9457 ret = io_account_mem(ctx, imu->acct_pages);
9459 imu->acct_pages = 0;
9463 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9464 struct io_mapped_ubuf **pimu,
9465 struct page **last_hpage)
9467 struct io_mapped_ubuf *imu = NULL;
9468 struct vm_area_struct **vmas = NULL;
9469 struct page **pages = NULL;
9470 unsigned long off, start, end, ubuf;
9472 int ret, pret, nr_pages, i;
9474 if (!iov->iov_base) {
9475 *pimu = ctx->dummy_ubuf;
9479 ubuf = (unsigned long) iov->iov_base;
9480 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9481 start = ubuf >> PAGE_SHIFT;
9482 nr_pages = end - start;
9487 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9491 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9496 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9501 mmap_read_lock(current->mm);
9502 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9504 if (pret == nr_pages) {
9505 /* don't support file backed memory */
9506 for (i = 0; i < nr_pages; i++) {
9507 struct vm_area_struct *vma = vmas[i];
9509 if (vma_is_shmem(vma))
9512 !is_file_hugepages(vma->vm_file)) {
9518 ret = pret < 0 ? pret : -EFAULT;
9520 mmap_read_unlock(current->mm);
9523 * if we did partial map, or found file backed vmas,
9524 * release any pages we did get
9527 unpin_user_pages(pages, pret);
9531 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9533 unpin_user_pages(pages, pret);
9537 off = ubuf & ~PAGE_MASK;
9538 size = iov->iov_len;
9539 for (i = 0; i < nr_pages; i++) {
9542 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9543 imu->bvec[i].bv_page = pages[i];
9544 imu->bvec[i].bv_len = vec_len;
9545 imu->bvec[i].bv_offset = off;
9549 /* store original address for later verification */
9551 imu->ubuf_end = ubuf + iov->iov_len;
9552 imu->nr_bvecs = nr_pages;
9563 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9565 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9566 return ctx->user_bufs ? 0 : -ENOMEM;
9569 static int io_buffer_validate(struct iovec *iov)
9571 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9574 * Don't impose further limits on the size and buffer
9575 * constraints here, we'll -EINVAL later when IO is
9576 * submitted if they are wrong.
9579 return iov->iov_len ? -EFAULT : 0;
9583 /* arbitrary limit, but we need something */
9584 if (iov->iov_len > SZ_1G)
9587 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9593 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9594 unsigned int nr_args, u64 __user *tags)
9596 struct page *last_hpage = NULL;
9597 struct io_rsrc_data *data;
9603 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9605 ret = io_rsrc_node_switch_start(ctx);
9608 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9611 ret = io_buffers_map_alloc(ctx, nr_args);
9613 io_rsrc_data_free(data);
9617 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9618 ret = io_copy_iov(ctx, &iov, arg, i);
9621 ret = io_buffer_validate(&iov);
9624 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9629 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9635 WARN_ON_ONCE(ctx->buf_data);
9637 ctx->buf_data = data;
9639 __io_sqe_buffers_unregister(ctx);
9641 io_rsrc_node_switch(ctx, NULL);
9645 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9646 struct io_uring_rsrc_update2 *up,
9647 unsigned int nr_args)
9649 u64 __user *tags = u64_to_user_ptr(up->tags);
9650 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9651 struct page *last_hpage = NULL;
9652 bool needs_switch = false;
9658 if (up->offset + nr_args > ctx->nr_user_bufs)
9661 for (done = 0; done < nr_args; done++) {
9662 struct io_mapped_ubuf *imu;
9663 int offset = up->offset + done;
9666 err = io_copy_iov(ctx, &iov, iovs, done);
9669 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9673 err = io_buffer_validate(&iov);
9676 if (!iov.iov_base && tag) {
9680 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9684 i = array_index_nospec(offset, ctx->nr_user_bufs);
9685 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9686 err = io_queue_rsrc_removal(ctx->buf_data, i,
9687 ctx->rsrc_node, ctx->user_bufs[i]);
9688 if (unlikely(err)) {
9689 io_buffer_unmap(ctx, &imu);
9692 ctx->user_bufs[i] = NULL;
9693 needs_switch = true;
9696 ctx->user_bufs[i] = imu;
9697 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9701 io_rsrc_node_switch(ctx, ctx->buf_data);
9702 return done ? done : err;
9705 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9706 unsigned int eventfd_async)
9708 struct io_ev_fd *ev_fd;
9709 __s32 __user *fds = arg;
9712 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9713 lockdep_is_held(&ctx->uring_lock));
9717 if (copy_from_user(&fd, fds, sizeof(*fds)))
9720 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9724 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9725 if (IS_ERR(ev_fd->cq_ev_fd)) {
9726 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9730 ev_fd->eventfd_async = eventfd_async;
9731 ctx->has_evfd = true;
9732 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9736 static void io_eventfd_put(struct rcu_head *rcu)
9738 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9740 eventfd_ctx_put(ev_fd->cq_ev_fd);
9744 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9746 struct io_ev_fd *ev_fd;
9748 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9749 lockdep_is_held(&ctx->uring_lock));
9751 ctx->has_evfd = false;
9752 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9753 call_rcu(&ev_fd->rcu, io_eventfd_put);
9760 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9764 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9765 struct list_head *list = &ctx->io_buffers[i];
9767 while (!list_empty(list)) {
9768 struct io_buffer_list *bl;
9770 bl = list_first_entry(list, struct io_buffer_list, list);
9771 __io_remove_buffers(ctx, bl, -1U);
9772 list_del(&bl->list);
9777 while (!list_empty(&ctx->io_buffers_pages)) {
9780 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9781 list_del_init(&page->lru);
9786 static void io_req_caches_free(struct io_ring_ctx *ctx)
9788 struct io_submit_state *state = &ctx->submit_state;
9791 mutex_lock(&ctx->uring_lock);
9792 io_flush_cached_locked_reqs(ctx, state);
9794 while (state->free_list.next) {
9795 struct io_wq_work_node *node;
9796 struct io_kiocb *req;
9798 node = wq_stack_extract(&state->free_list);
9799 req = container_of(node, struct io_kiocb, comp_list);
9800 kmem_cache_free(req_cachep, req);
9804 percpu_ref_put_many(&ctx->refs, nr);
9805 mutex_unlock(&ctx->uring_lock);
9808 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9810 if (data && !atomic_dec_and_test(&data->refs))
9811 wait_for_completion(&data->done);
9814 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
9816 struct async_poll *apoll;
9818 while (!list_empty(&ctx->apoll_cache)) {
9819 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
9821 list_del(&apoll->poll.wait.entry);
9826 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9828 io_sq_thread_finish(ctx);
9830 if (ctx->mm_account) {
9831 mmdrop(ctx->mm_account);
9832 ctx->mm_account = NULL;
9835 io_rsrc_refs_drop(ctx);
9836 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9837 io_wait_rsrc_data(ctx->buf_data);
9838 io_wait_rsrc_data(ctx->file_data);
9840 mutex_lock(&ctx->uring_lock);
9842 __io_sqe_buffers_unregister(ctx);
9844 __io_sqe_files_unregister(ctx);
9846 __io_cqring_overflow_flush(ctx, true);
9847 io_eventfd_unregister(ctx);
9848 io_flush_apoll_cache(ctx);
9849 mutex_unlock(&ctx->uring_lock);
9850 io_destroy_buffers(ctx);
9852 put_cred(ctx->sq_creds);
9854 /* there are no registered resources left, nobody uses it */
9856 io_rsrc_node_destroy(ctx->rsrc_node);
9857 if (ctx->rsrc_backup_node)
9858 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9859 flush_delayed_work(&ctx->rsrc_put_work);
9860 flush_delayed_work(&ctx->fallback_work);
9862 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9863 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9865 #if defined(CONFIG_UNIX)
9866 if (ctx->ring_sock) {
9867 ctx->ring_sock->file = NULL; /* so that iput() is called */
9868 sock_release(ctx->ring_sock);
9871 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9873 io_mem_free(ctx->rings);
9874 io_mem_free(ctx->sq_sqes);
9876 percpu_ref_exit(&ctx->refs);
9877 free_uid(ctx->user);
9878 io_req_caches_free(ctx);
9880 io_wq_put_hash(ctx->hash_map);
9881 kfree(ctx->cancel_hash);
9882 kfree(ctx->dummy_ubuf);
9883 kfree(ctx->io_buffers);
9887 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9889 struct io_ring_ctx *ctx = file->private_data;
9892 poll_wait(file, &ctx->cq_wait, wait);
9894 * synchronizes with barrier from wq_has_sleeper call in
9898 if (!io_sqring_full(ctx))
9899 mask |= EPOLLOUT | EPOLLWRNORM;
9902 * Don't flush cqring overflow list here, just do a simple check.
9903 * Otherwise there could possible be ABBA deadlock:
9906 * lock(&ctx->uring_lock);
9908 * lock(&ctx->uring_lock);
9911 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9912 * pushs them to do the flush.
9914 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9915 mask |= EPOLLIN | EPOLLRDNORM;
9920 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9922 const struct cred *creds;
9924 creds = xa_erase(&ctx->personalities, id);
9933 struct io_tctx_exit {
9934 struct callback_head task_work;
9935 struct completion completion;
9936 struct io_ring_ctx *ctx;
9939 static __cold void io_tctx_exit_cb(struct callback_head *cb)
9941 struct io_uring_task *tctx = current->io_uring;
9942 struct io_tctx_exit *work;
9944 work = container_of(cb, struct io_tctx_exit, task_work);
9946 * When @in_idle, we're in cancellation and it's racy to remove the
9947 * node. It'll be removed by the end of cancellation, just ignore it.
9949 if (!atomic_read(&tctx->in_idle))
9950 io_uring_del_tctx_node((unsigned long)work->ctx);
9951 complete(&work->completion);
9954 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9956 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9958 return req->ctx == data;
9961 static __cold void io_ring_exit_work(struct work_struct *work)
9963 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9964 unsigned long timeout = jiffies + HZ * 60 * 5;
9965 unsigned long interval = HZ / 20;
9966 struct io_tctx_exit exit;
9967 struct io_tctx_node *node;
9971 * If we're doing polled IO and end up having requests being
9972 * submitted async (out-of-line), then completions can come in while
9973 * we're waiting for refs to drop. We need to reap these manually,
9974 * as nobody else will be looking for them.
9977 io_uring_try_cancel_requests(ctx, NULL, true);
9979 struct io_sq_data *sqd = ctx->sq_data;
9980 struct task_struct *tsk;
9982 io_sq_thread_park(sqd);
9984 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9985 io_wq_cancel_cb(tsk->io_uring->io_wq,
9986 io_cancel_ctx_cb, ctx, true);
9987 io_sq_thread_unpark(sqd);
9990 io_req_caches_free(ctx);
9992 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9993 /* there is little hope left, don't run it too often */
9996 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9998 init_completion(&exit.completion);
9999 init_task_work(&exit.task_work, io_tctx_exit_cb);
10002 * Some may use context even when all refs and requests have been put,
10003 * and they are free to do so while still holding uring_lock or
10004 * completion_lock, see io_req_task_submit(). Apart from other work,
10005 * this lock/unlock section also waits them to finish.
10007 mutex_lock(&ctx->uring_lock);
10008 while (!list_empty(&ctx->tctx_list)) {
10009 WARN_ON_ONCE(time_after(jiffies, timeout));
10011 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10013 /* don't spin on a single task if cancellation failed */
10014 list_rotate_left(&ctx->tctx_list);
10015 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10016 if (WARN_ON_ONCE(ret))
10019 mutex_unlock(&ctx->uring_lock);
10020 wait_for_completion(&exit.completion);
10021 mutex_lock(&ctx->uring_lock);
10023 mutex_unlock(&ctx->uring_lock);
10024 spin_lock(&ctx->completion_lock);
10025 spin_unlock(&ctx->completion_lock);
10027 io_ring_ctx_free(ctx);
10030 /* Returns true if we found and killed one or more timeouts */
10031 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10032 struct task_struct *tsk, bool cancel_all)
10034 struct io_kiocb *req, *tmp;
10037 spin_lock(&ctx->completion_lock);
10038 spin_lock_irq(&ctx->timeout_lock);
10039 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10040 if (io_match_task(req, tsk, cancel_all)) {
10041 io_kill_timeout(req, -ECANCELED);
10045 spin_unlock_irq(&ctx->timeout_lock);
10046 io_commit_cqring(ctx);
10047 spin_unlock(&ctx->completion_lock);
10049 io_cqring_ev_posted(ctx);
10050 return canceled != 0;
10053 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10055 unsigned long index;
10056 struct creds *creds;
10058 mutex_lock(&ctx->uring_lock);
10059 percpu_ref_kill(&ctx->refs);
10061 __io_cqring_overflow_flush(ctx, true);
10062 xa_for_each(&ctx->personalities, index, creds)
10063 io_unregister_personality(ctx, index);
10064 mutex_unlock(&ctx->uring_lock);
10066 /* failed during ring init, it couldn't have issued any requests */
10068 io_kill_timeouts(ctx, NULL, true);
10069 io_poll_remove_all(ctx, NULL, true);
10070 /* if we failed setting up the ctx, we might not have any rings */
10071 io_iopoll_try_reap_events(ctx);
10074 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10076 * Use system_unbound_wq to avoid spawning tons of event kworkers
10077 * if we're exiting a ton of rings at the same time. It just adds
10078 * noise and overhead, there's no discernable change in runtime
10079 * over using system_wq.
10081 queue_work(system_unbound_wq, &ctx->exit_work);
10084 static int io_uring_release(struct inode *inode, struct file *file)
10086 struct io_ring_ctx *ctx = file->private_data;
10088 file->private_data = NULL;
10089 io_ring_ctx_wait_and_kill(ctx);
10093 struct io_task_cancel {
10094 struct task_struct *task;
10098 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10100 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10101 struct io_task_cancel *cancel = data;
10103 return io_match_task_safe(req, cancel->task, cancel->all);
10106 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10107 struct task_struct *task,
10110 struct io_defer_entry *de;
10113 spin_lock(&ctx->completion_lock);
10114 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10115 if (io_match_task_safe(de->req, task, cancel_all)) {
10116 list_cut_position(&list, &ctx->defer_list, &de->list);
10120 spin_unlock(&ctx->completion_lock);
10121 if (list_empty(&list))
10124 while (!list_empty(&list)) {
10125 de = list_first_entry(&list, struct io_defer_entry, list);
10126 list_del_init(&de->list);
10127 io_req_complete_failed(de->req, -ECANCELED);
10133 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10135 struct io_tctx_node *node;
10136 enum io_wq_cancel cret;
10139 mutex_lock(&ctx->uring_lock);
10140 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10141 struct io_uring_task *tctx = node->task->io_uring;
10144 * io_wq will stay alive while we hold uring_lock, because it's
10145 * killed after ctx nodes, which requires to take the lock.
10147 if (!tctx || !tctx->io_wq)
10149 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10150 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10152 mutex_unlock(&ctx->uring_lock);
10157 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10158 struct task_struct *task,
10161 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10162 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10164 /* failed during ring init, it couldn't have issued any requests */
10169 enum io_wq_cancel cret;
10173 ret |= io_uring_try_cancel_iowq(ctx);
10174 } else if (tctx && tctx->io_wq) {
10176 * Cancels requests of all rings, not only @ctx, but
10177 * it's fine as the task is in exit/exec.
10179 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10181 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10184 /* SQPOLL thread does its own polling */
10185 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10186 (ctx->sq_data && ctx->sq_data->thread == current)) {
10187 while (!wq_list_empty(&ctx->iopoll_list)) {
10188 io_iopoll_try_reap_events(ctx);
10193 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10194 ret |= io_poll_remove_all(ctx, task, cancel_all);
10195 ret |= io_kill_timeouts(ctx, task, cancel_all);
10197 ret |= io_run_task_work();
10204 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10206 struct io_uring_task *tctx = current->io_uring;
10207 struct io_tctx_node *node;
10210 if (unlikely(!tctx)) {
10211 ret = io_uring_alloc_task_context(current, ctx);
10215 tctx = current->io_uring;
10216 if (ctx->iowq_limits_set) {
10217 unsigned int limits[2] = { ctx->iowq_limits[0],
10218 ctx->iowq_limits[1], };
10220 ret = io_wq_max_workers(tctx->io_wq, limits);
10225 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10226 node = kmalloc(sizeof(*node), GFP_KERNEL);
10230 node->task = current;
10232 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10233 node, GFP_KERNEL));
10239 mutex_lock(&ctx->uring_lock);
10240 list_add(&node->ctx_node, &ctx->tctx_list);
10241 mutex_unlock(&ctx->uring_lock);
10248 * Note that this task has used io_uring. We use it for cancelation purposes.
10250 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10252 struct io_uring_task *tctx = current->io_uring;
10254 if (likely(tctx && tctx->last == ctx))
10256 return __io_uring_add_tctx_node(ctx);
10260 * Remove this io_uring_file -> task mapping.
10262 static __cold void io_uring_del_tctx_node(unsigned long index)
10264 struct io_uring_task *tctx = current->io_uring;
10265 struct io_tctx_node *node;
10269 node = xa_erase(&tctx->xa, index);
10273 WARN_ON_ONCE(current != node->task);
10274 WARN_ON_ONCE(list_empty(&node->ctx_node));
10276 mutex_lock(&node->ctx->uring_lock);
10277 list_del(&node->ctx_node);
10278 mutex_unlock(&node->ctx->uring_lock);
10280 if (tctx->last == node->ctx)
10285 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10287 struct io_wq *wq = tctx->io_wq;
10288 struct io_tctx_node *node;
10289 unsigned long index;
10291 xa_for_each(&tctx->xa, index, node) {
10292 io_uring_del_tctx_node(index);
10297 * Must be after io_uring_del_tctx_node() (removes nodes under
10298 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10300 io_wq_put_and_exit(wq);
10301 tctx->io_wq = NULL;
10305 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10309 return percpu_counter_sum(&tctx->inflight);
10313 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10314 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10316 static __cold void io_uring_cancel_generic(bool cancel_all,
10317 struct io_sq_data *sqd)
10319 struct io_uring_task *tctx = current->io_uring;
10320 struct io_ring_ctx *ctx;
10324 WARN_ON_ONCE(sqd && sqd->thread != current);
10326 if (!current->io_uring)
10329 io_wq_exit_start(tctx->io_wq);
10331 atomic_inc(&tctx->in_idle);
10333 io_uring_drop_tctx_refs(current);
10334 /* read completions before cancelations */
10335 inflight = tctx_inflight(tctx, !cancel_all);
10340 struct io_tctx_node *node;
10341 unsigned long index;
10343 xa_for_each(&tctx->xa, index, node) {
10344 /* sqpoll task will cancel all its requests */
10345 if (node->ctx->sq_data)
10347 io_uring_try_cancel_requests(node->ctx, current,
10351 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10352 io_uring_try_cancel_requests(ctx, current,
10356 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10357 io_run_task_work();
10358 io_uring_drop_tctx_refs(current);
10361 * If we've seen completions, retry without waiting. This
10362 * avoids a race where a completion comes in before we did
10363 * prepare_to_wait().
10365 if (inflight == tctx_inflight(tctx, !cancel_all))
10367 finish_wait(&tctx->wait, &wait);
10370 io_uring_clean_tctx(tctx);
10373 * We shouldn't run task_works after cancel, so just leave
10374 * ->in_idle set for normal exit.
10376 atomic_dec(&tctx->in_idle);
10377 /* for exec all current's requests should be gone, kill tctx */
10378 __io_uring_free(current);
10382 void __io_uring_cancel(bool cancel_all)
10384 io_uring_cancel_generic(cancel_all, NULL);
10387 void io_uring_unreg_ringfd(void)
10389 struct io_uring_task *tctx = current->io_uring;
10392 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10393 if (tctx->registered_rings[i]) {
10394 fput(tctx->registered_rings[i]);
10395 tctx->registered_rings[i] = NULL;
10400 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10401 int start, int end)
10406 for (offset = start; offset < end; offset++) {
10407 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10408 if (tctx->registered_rings[offset])
10414 } else if (file->f_op != &io_uring_fops) {
10416 return -EOPNOTSUPP;
10418 tctx->registered_rings[offset] = file;
10426 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10427 * invocation. User passes in an array of struct io_uring_rsrc_update
10428 * with ->data set to the ring_fd, and ->offset given for the desired
10429 * index. If no index is desired, application may set ->offset == -1U
10430 * and we'll find an available index. Returns number of entries
10431 * successfully processed, or < 0 on error if none were processed.
10433 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10436 struct io_uring_rsrc_update __user *arg = __arg;
10437 struct io_uring_rsrc_update reg;
10438 struct io_uring_task *tctx;
10441 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10444 mutex_unlock(&ctx->uring_lock);
10445 ret = io_uring_add_tctx_node(ctx);
10446 mutex_lock(&ctx->uring_lock);
10450 tctx = current->io_uring;
10451 for (i = 0; i < nr_args; i++) {
10454 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10464 if (reg.offset == -1U) {
10466 end = IO_RINGFD_REG_MAX;
10468 if (reg.offset >= IO_RINGFD_REG_MAX) {
10472 start = reg.offset;
10476 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10481 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10482 fput(tctx->registered_rings[reg.offset]);
10483 tctx->registered_rings[reg.offset] = NULL;
10489 return i ? i : ret;
10492 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10495 struct io_uring_rsrc_update __user *arg = __arg;
10496 struct io_uring_task *tctx = current->io_uring;
10497 struct io_uring_rsrc_update reg;
10500 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10505 for (i = 0; i < nr_args; i++) {
10506 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10510 if (reg.resv || reg.offset >= IO_RINGFD_REG_MAX) {
10515 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10516 if (tctx->registered_rings[reg.offset]) {
10517 fput(tctx->registered_rings[reg.offset]);
10518 tctx->registered_rings[reg.offset] = NULL;
10522 return i ? i : ret;
10525 static void *io_uring_validate_mmap_request(struct file *file,
10526 loff_t pgoff, size_t sz)
10528 struct io_ring_ctx *ctx = file->private_data;
10529 loff_t offset = pgoff << PAGE_SHIFT;
10534 case IORING_OFF_SQ_RING:
10535 case IORING_OFF_CQ_RING:
10538 case IORING_OFF_SQES:
10539 ptr = ctx->sq_sqes;
10542 return ERR_PTR(-EINVAL);
10545 page = virt_to_head_page(ptr);
10546 if (sz > page_size(page))
10547 return ERR_PTR(-EINVAL);
10554 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10556 size_t sz = vma->vm_end - vma->vm_start;
10560 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10562 return PTR_ERR(ptr);
10564 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10565 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10568 #else /* !CONFIG_MMU */
10570 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10572 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10575 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10577 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10580 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10581 unsigned long addr, unsigned long len,
10582 unsigned long pgoff, unsigned long flags)
10586 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10588 return PTR_ERR(ptr);
10590 return (unsigned long) ptr;
10593 #endif /* !CONFIG_MMU */
10595 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10600 if (!io_sqring_full(ctx))
10602 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10604 if (!io_sqring_full(ctx))
10607 } while (!signal_pending(current));
10609 finish_wait(&ctx->sqo_sq_wait, &wait);
10613 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
10615 if (flags & IORING_ENTER_EXT_ARG) {
10616 struct io_uring_getevents_arg arg;
10618 if (argsz != sizeof(arg))
10620 if (copy_from_user(&arg, argp, sizeof(arg)))
10626 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10627 struct __kernel_timespec __user **ts,
10628 const sigset_t __user **sig)
10630 struct io_uring_getevents_arg arg;
10633 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10634 * is just a pointer to the sigset_t.
10636 if (!(flags & IORING_ENTER_EXT_ARG)) {
10637 *sig = (const sigset_t __user *) argp;
10643 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10644 * timespec and sigset_t pointers if good.
10646 if (*argsz != sizeof(arg))
10648 if (copy_from_user(&arg, argp, sizeof(arg)))
10652 *sig = u64_to_user_ptr(arg.sigmask);
10653 *argsz = arg.sigmask_sz;
10654 *ts = u64_to_user_ptr(arg.ts);
10658 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10659 u32, min_complete, u32, flags, const void __user *, argp,
10662 struct io_ring_ctx *ctx;
10667 io_run_task_work();
10669 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10670 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10671 IORING_ENTER_REGISTERED_RING)))
10675 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10676 * need only dereference our task private array to find it.
10678 if (flags & IORING_ENTER_REGISTERED_RING) {
10679 struct io_uring_task *tctx = current->io_uring;
10681 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10683 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10684 f.file = tctx->registered_rings[fd];
10685 if (unlikely(!f.file))
10689 if (unlikely(!f.file))
10694 if (unlikely(f.file->f_op != &io_uring_fops))
10698 ctx = f.file->private_data;
10699 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10703 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10707 * For SQ polling, the thread will do all submissions and completions.
10708 * Just return the requested submit count, and wake the thread if
10709 * we were asked to.
10712 if (ctx->flags & IORING_SETUP_SQPOLL) {
10713 io_cqring_overflow_flush(ctx);
10715 if (unlikely(ctx->sq_data->thread == NULL)) {
10719 if (flags & IORING_ENTER_SQ_WAKEUP)
10720 wake_up(&ctx->sq_data->wait);
10721 if (flags & IORING_ENTER_SQ_WAIT) {
10722 ret = io_sqpoll_wait_sq(ctx);
10726 submitted = to_submit;
10727 } else if (to_submit) {
10728 ret = io_uring_add_tctx_node(ctx);
10732 mutex_lock(&ctx->uring_lock);
10733 submitted = io_submit_sqes(ctx, to_submit);
10734 if (submitted != to_submit) {
10735 mutex_unlock(&ctx->uring_lock);
10738 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
10739 goto iopoll_locked;
10740 mutex_unlock(&ctx->uring_lock);
10742 if (flags & IORING_ENTER_GETEVENTS) {
10743 if (ctx->syscall_iopoll) {
10745 * We disallow the app entering submit/complete with
10746 * polling, but we still need to lock the ring to
10747 * prevent racing with polled issue that got punted to
10750 mutex_lock(&ctx->uring_lock);
10752 ret = io_validate_ext_arg(flags, argp, argsz);
10753 if (likely(!ret)) {
10754 min_complete = min(min_complete, ctx->cq_entries);
10755 ret = io_iopoll_check(ctx, min_complete);
10757 mutex_unlock(&ctx->uring_lock);
10759 const sigset_t __user *sig;
10760 struct __kernel_timespec __user *ts;
10762 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10765 min_complete = min(min_complete, ctx->cq_entries);
10766 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10771 percpu_ref_put(&ctx->refs);
10773 if (!(flags & IORING_ENTER_REGISTERED_RING))
10775 return submitted ? submitted : ret;
10778 #ifdef CONFIG_PROC_FS
10779 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10780 const struct cred *cred)
10782 struct user_namespace *uns = seq_user_ns(m);
10783 struct group_info *gi;
10788 seq_printf(m, "%5d\n", id);
10789 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10790 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10791 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10792 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10793 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10794 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10795 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10796 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10797 seq_puts(m, "\n\tGroups:\t");
10798 gi = cred->group_info;
10799 for (g = 0; g < gi->ngroups; g++) {
10800 seq_put_decimal_ull(m, g ? " " : "",
10801 from_kgid_munged(uns, gi->gid[g]));
10803 seq_puts(m, "\n\tCapEff:\t");
10804 cap = cred->cap_effective;
10805 CAP_FOR_EACH_U32(__capi)
10806 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10811 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10812 struct seq_file *m)
10814 struct io_sq_data *sq = NULL;
10815 struct io_overflow_cqe *ocqe;
10816 struct io_rings *r = ctx->rings;
10817 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10818 unsigned int sq_head = READ_ONCE(r->sq.head);
10819 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10820 unsigned int cq_head = READ_ONCE(r->cq.head);
10821 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10822 unsigned int sq_entries, cq_entries;
10827 * we may get imprecise sqe and cqe info if uring is actively running
10828 * since we get cached_sq_head and cached_cq_tail without uring_lock
10829 * and sq_tail and cq_head are changed by userspace. But it's ok since
10830 * we usually use these info when it is stuck.
10832 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10833 seq_printf(m, "SqHead:\t%u\n", sq_head);
10834 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10835 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10836 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10837 seq_printf(m, "CqHead:\t%u\n", cq_head);
10838 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10839 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10840 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10841 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10842 for (i = 0; i < sq_entries; i++) {
10843 unsigned int entry = i + sq_head;
10844 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10845 struct io_uring_sqe *sqe;
10847 if (sq_idx > sq_mask)
10849 sqe = &ctx->sq_sqes[sq_idx];
10850 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10851 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10854 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10855 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10856 for (i = 0; i < cq_entries; i++) {
10857 unsigned int entry = i + cq_head;
10858 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10860 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10861 entry & cq_mask, cqe->user_data, cqe->res,
10866 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10867 * since fdinfo case grabs it in the opposite direction of normal use
10868 * cases. If we fail to get the lock, we just don't iterate any
10869 * structures that could be going away outside the io_uring mutex.
10871 has_lock = mutex_trylock(&ctx->uring_lock);
10873 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10879 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10880 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10881 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10882 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10883 struct file *f = io_file_from_index(ctx, i);
10886 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10888 seq_printf(m, "%5u: <none>\n", i);
10890 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10891 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10892 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10893 unsigned int len = buf->ubuf_end - buf->ubuf;
10895 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10897 if (has_lock && !xa_empty(&ctx->personalities)) {
10898 unsigned long index;
10899 const struct cred *cred;
10901 seq_printf(m, "Personalities:\n");
10902 xa_for_each(&ctx->personalities, index, cred)
10903 io_uring_show_cred(m, index, cred);
10906 mutex_unlock(&ctx->uring_lock);
10908 seq_puts(m, "PollList:\n");
10909 spin_lock(&ctx->completion_lock);
10910 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10911 struct hlist_head *list = &ctx->cancel_hash[i];
10912 struct io_kiocb *req;
10914 hlist_for_each_entry(req, list, hash_node)
10915 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10916 task_work_pending(req->task));
10919 seq_puts(m, "CqOverflowList:\n");
10920 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10921 struct io_uring_cqe *cqe = &ocqe->cqe;
10923 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10924 cqe->user_data, cqe->res, cqe->flags);
10928 spin_unlock(&ctx->completion_lock);
10931 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10933 struct io_ring_ctx *ctx = f->private_data;
10935 if (percpu_ref_tryget(&ctx->refs)) {
10936 __io_uring_show_fdinfo(ctx, m);
10937 percpu_ref_put(&ctx->refs);
10942 static const struct file_operations io_uring_fops = {
10943 .release = io_uring_release,
10944 .mmap = io_uring_mmap,
10946 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10947 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10949 .poll = io_uring_poll,
10950 #ifdef CONFIG_PROC_FS
10951 .show_fdinfo = io_uring_show_fdinfo,
10955 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10956 struct io_uring_params *p)
10958 struct io_rings *rings;
10959 size_t size, sq_array_offset;
10961 /* make sure these are sane, as we already accounted them */
10962 ctx->sq_entries = p->sq_entries;
10963 ctx->cq_entries = p->cq_entries;
10965 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10966 if (size == SIZE_MAX)
10969 rings = io_mem_alloc(size);
10973 ctx->rings = rings;
10974 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10975 rings->sq_ring_mask = p->sq_entries - 1;
10976 rings->cq_ring_mask = p->cq_entries - 1;
10977 rings->sq_ring_entries = p->sq_entries;
10978 rings->cq_ring_entries = p->cq_entries;
10980 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10981 if (size == SIZE_MAX) {
10982 io_mem_free(ctx->rings);
10987 ctx->sq_sqes = io_mem_alloc(size);
10988 if (!ctx->sq_sqes) {
10989 io_mem_free(ctx->rings);
10997 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11001 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11005 ret = io_uring_add_tctx_node(ctx);
11010 fd_install(fd, file);
11015 * Allocate an anonymous fd, this is what constitutes the application
11016 * visible backing of an io_uring instance. The application mmaps this
11017 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11018 * we have to tie this fd to a socket for file garbage collection purposes.
11020 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11023 #if defined(CONFIG_UNIX)
11026 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11029 return ERR_PTR(ret);
11032 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11033 O_RDWR | O_CLOEXEC, NULL);
11034 #if defined(CONFIG_UNIX)
11035 if (IS_ERR(file)) {
11036 sock_release(ctx->ring_sock);
11037 ctx->ring_sock = NULL;
11039 ctx->ring_sock->file = file;
11045 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11046 struct io_uring_params __user *params)
11048 struct io_ring_ctx *ctx;
11054 if (entries > IORING_MAX_ENTRIES) {
11055 if (!(p->flags & IORING_SETUP_CLAMP))
11057 entries = IORING_MAX_ENTRIES;
11061 * Use twice as many entries for the CQ ring. It's possible for the
11062 * application to drive a higher depth than the size of the SQ ring,
11063 * since the sqes are only used at submission time. This allows for
11064 * some flexibility in overcommitting a bit. If the application has
11065 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11066 * of CQ ring entries manually.
11068 p->sq_entries = roundup_pow_of_two(entries);
11069 if (p->flags & IORING_SETUP_CQSIZE) {
11071 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11072 * to a power-of-two, if it isn't already. We do NOT impose
11073 * any cq vs sq ring sizing.
11075 if (!p->cq_entries)
11077 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11078 if (!(p->flags & IORING_SETUP_CLAMP))
11080 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11082 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11083 if (p->cq_entries < p->sq_entries)
11086 p->cq_entries = 2 * p->sq_entries;
11089 ctx = io_ring_ctx_alloc(p);
11094 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
11095 * space applications don't need to do io completion events
11096 * polling again, they can rely on io_sq_thread to do polling
11097 * work, which can reduce cpu usage and uring_lock contention.
11099 if (ctx->flags & IORING_SETUP_IOPOLL &&
11100 !(ctx->flags & IORING_SETUP_SQPOLL))
11101 ctx->syscall_iopoll = 1;
11103 ctx->compat = in_compat_syscall();
11104 if (!capable(CAP_IPC_LOCK))
11105 ctx->user = get_uid(current_user());
11108 * This is just grabbed for accounting purposes. When a process exits,
11109 * the mm is exited and dropped before the files, hence we need to hang
11110 * on to this mm purely for the purposes of being able to unaccount
11111 * memory (locked/pinned vm). It's not used for anything else.
11113 mmgrab(current->mm);
11114 ctx->mm_account = current->mm;
11116 ret = io_allocate_scq_urings(ctx, p);
11120 ret = io_sq_offload_create(ctx, p);
11123 /* always set a rsrc node */
11124 ret = io_rsrc_node_switch_start(ctx);
11127 io_rsrc_node_switch(ctx, NULL);
11129 memset(&p->sq_off, 0, sizeof(p->sq_off));
11130 p->sq_off.head = offsetof(struct io_rings, sq.head);
11131 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11132 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11133 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11134 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11135 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11136 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11138 memset(&p->cq_off, 0, sizeof(p->cq_off));
11139 p->cq_off.head = offsetof(struct io_rings, cq.head);
11140 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11141 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11142 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11143 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11144 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11145 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11147 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11148 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11149 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11150 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11151 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11152 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
11153 IORING_FEAT_LINKED_FILE;
11155 if (copy_to_user(params, p, sizeof(*p))) {
11160 file = io_uring_get_file(ctx);
11161 if (IS_ERR(file)) {
11162 ret = PTR_ERR(file);
11167 * Install ring fd as the very last thing, so we don't risk someone
11168 * having closed it before we finish setup
11170 ret = io_uring_install_fd(ctx, file);
11172 /* fput will clean it up */
11177 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11180 io_ring_ctx_wait_and_kill(ctx);
11185 * Sets up an aio uring context, and returns the fd. Applications asks for a
11186 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11187 * params structure passed in.
11189 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11191 struct io_uring_params p;
11194 if (copy_from_user(&p, params, sizeof(p)))
11196 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11201 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11202 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11203 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11204 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11207 return io_uring_create(entries, &p, params);
11210 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11211 struct io_uring_params __user *, params)
11213 return io_uring_setup(entries, params);
11216 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11219 struct io_uring_probe *p;
11223 size = struct_size(p, ops, nr_args);
11224 if (size == SIZE_MAX)
11226 p = kzalloc(size, GFP_KERNEL);
11231 if (copy_from_user(p, arg, size))
11234 if (memchr_inv(p, 0, size))
11237 p->last_op = IORING_OP_LAST - 1;
11238 if (nr_args > IORING_OP_LAST)
11239 nr_args = IORING_OP_LAST;
11241 for (i = 0; i < nr_args; i++) {
11243 if (!io_op_defs[i].not_supported)
11244 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11249 if (copy_to_user(arg, p, size))
11256 static int io_register_personality(struct io_ring_ctx *ctx)
11258 const struct cred *creds;
11262 creds = get_current_cred();
11264 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11265 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11273 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11274 void __user *arg, unsigned int nr_args)
11276 struct io_uring_restriction *res;
11280 /* Restrictions allowed only if rings started disabled */
11281 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11284 /* We allow only a single restrictions registration */
11285 if (ctx->restrictions.registered)
11288 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11291 size = array_size(nr_args, sizeof(*res));
11292 if (size == SIZE_MAX)
11295 res = memdup_user(arg, size);
11297 return PTR_ERR(res);
11301 for (i = 0; i < nr_args; i++) {
11302 switch (res[i].opcode) {
11303 case IORING_RESTRICTION_REGISTER_OP:
11304 if (res[i].register_op >= IORING_REGISTER_LAST) {
11309 __set_bit(res[i].register_op,
11310 ctx->restrictions.register_op);
11312 case IORING_RESTRICTION_SQE_OP:
11313 if (res[i].sqe_op >= IORING_OP_LAST) {
11318 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11320 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11321 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11323 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11324 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11333 /* Reset all restrictions if an error happened */
11335 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11337 ctx->restrictions.registered = true;
11343 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11345 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11348 if (ctx->restrictions.registered)
11349 ctx->restricted = 1;
11351 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11352 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11353 wake_up(&ctx->sq_data->wait);
11357 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11358 struct io_uring_rsrc_update2 *up,
11364 if (check_add_overflow(up->offset, nr_args, &tmp))
11366 err = io_rsrc_node_switch_start(ctx);
11371 case IORING_RSRC_FILE:
11372 return __io_sqe_files_update(ctx, up, nr_args);
11373 case IORING_RSRC_BUFFER:
11374 return __io_sqe_buffers_update(ctx, up, nr_args);
11379 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11382 struct io_uring_rsrc_update2 up;
11386 memset(&up, 0, sizeof(up));
11387 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11389 if (up.resv || up.resv2)
11391 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11394 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11395 unsigned size, unsigned type)
11397 struct io_uring_rsrc_update2 up;
11399 if (size != sizeof(up))
11401 if (copy_from_user(&up, arg, sizeof(up)))
11403 if (!up.nr || up.resv || up.resv2)
11405 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11408 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11409 unsigned int size, unsigned int type)
11411 struct io_uring_rsrc_register rr;
11413 /* keep it extendible */
11414 if (size != sizeof(rr))
11417 memset(&rr, 0, sizeof(rr));
11418 if (copy_from_user(&rr, arg, size))
11420 if (!rr.nr || rr.resv || rr.resv2)
11424 case IORING_RSRC_FILE:
11425 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11426 rr.nr, u64_to_user_ptr(rr.tags));
11427 case IORING_RSRC_BUFFER:
11428 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11429 rr.nr, u64_to_user_ptr(rr.tags));
11434 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11435 void __user *arg, unsigned len)
11437 struct io_uring_task *tctx = current->io_uring;
11438 cpumask_var_t new_mask;
11441 if (!tctx || !tctx->io_wq)
11444 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11447 cpumask_clear(new_mask);
11448 if (len > cpumask_size())
11449 len = cpumask_size();
11451 if (in_compat_syscall()) {
11452 ret = compat_get_bitmap(cpumask_bits(new_mask),
11453 (const compat_ulong_t __user *)arg,
11454 len * 8 /* CHAR_BIT */);
11456 ret = copy_from_user(new_mask, arg, len);
11460 free_cpumask_var(new_mask);
11464 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11465 free_cpumask_var(new_mask);
11469 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11471 struct io_uring_task *tctx = current->io_uring;
11473 if (!tctx || !tctx->io_wq)
11476 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11479 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11481 __must_hold(&ctx->uring_lock)
11483 struct io_tctx_node *node;
11484 struct io_uring_task *tctx = NULL;
11485 struct io_sq_data *sqd = NULL;
11486 __u32 new_count[2];
11489 if (copy_from_user(new_count, arg, sizeof(new_count)))
11491 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11492 if (new_count[i] > INT_MAX)
11495 if (ctx->flags & IORING_SETUP_SQPOLL) {
11496 sqd = ctx->sq_data;
11499 * Observe the correct sqd->lock -> ctx->uring_lock
11500 * ordering. Fine to drop uring_lock here, we hold
11501 * a ref to the ctx.
11503 refcount_inc(&sqd->refs);
11504 mutex_unlock(&ctx->uring_lock);
11505 mutex_lock(&sqd->lock);
11506 mutex_lock(&ctx->uring_lock);
11508 tctx = sqd->thread->io_uring;
11511 tctx = current->io_uring;
11514 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11516 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11518 ctx->iowq_limits[i] = new_count[i];
11519 ctx->iowq_limits_set = true;
11521 if (tctx && tctx->io_wq) {
11522 ret = io_wq_max_workers(tctx->io_wq, new_count);
11526 memset(new_count, 0, sizeof(new_count));
11530 mutex_unlock(&sqd->lock);
11531 io_put_sq_data(sqd);
11534 if (copy_to_user(arg, new_count, sizeof(new_count)))
11537 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11541 /* now propagate the restriction to all registered users */
11542 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11543 struct io_uring_task *tctx = node->task->io_uring;
11545 if (WARN_ON_ONCE(!tctx->io_wq))
11548 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11549 new_count[i] = ctx->iowq_limits[i];
11550 /* ignore errors, it always returns zero anyway */
11551 (void)io_wq_max_workers(tctx->io_wq, new_count);
11556 mutex_unlock(&sqd->lock);
11557 io_put_sq_data(sqd);
11562 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11563 void __user *arg, unsigned nr_args)
11564 __releases(ctx->uring_lock)
11565 __acquires(ctx->uring_lock)
11570 * We're inside the ring mutex, if the ref is already dying, then
11571 * someone else killed the ctx or is already going through
11572 * io_uring_register().
11574 if (percpu_ref_is_dying(&ctx->refs))
11577 if (ctx->restricted) {
11578 if (opcode >= IORING_REGISTER_LAST)
11580 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11581 if (!test_bit(opcode, ctx->restrictions.register_op))
11586 case IORING_REGISTER_BUFFERS:
11587 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11589 case IORING_UNREGISTER_BUFFERS:
11591 if (arg || nr_args)
11593 ret = io_sqe_buffers_unregister(ctx);
11595 case IORING_REGISTER_FILES:
11596 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11598 case IORING_UNREGISTER_FILES:
11600 if (arg || nr_args)
11602 ret = io_sqe_files_unregister(ctx);
11604 case IORING_REGISTER_FILES_UPDATE:
11605 ret = io_register_files_update(ctx, arg, nr_args);
11607 case IORING_REGISTER_EVENTFD:
11611 ret = io_eventfd_register(ctx, arg, 0);
11613 case IORING_REGISTER_EVENTFD_ASYNC:
11617 ret = io_eventfd_register(ctx, arg, 1);
11619 case IORING_UNREGISTER_EVENTFD:
11621 if (arg || nr_args)
11623 ret = io_eventfd_unregister(ctx);
11625 case IORING_REGISTER_PROBE:
11627 if (!arg || nr_args > 256)
11629 ret = io_probe(ctx, arg, nr_args);
11631 case IORING_REGISTER_PERSONALITY:
11633 if (arg || nr_args)
11635 ret = io_register_personality(ctx);
11637 case IORING_UNREGISTER_PERSONALITY:
11641 ret = io_unregister_personality(ctx, nr_args);
11643 case IORING_REGISTER_ENABLE_RINGS:
11645 if (arg || nr_args)
11647 ret = io_register_enable_rings(ctx);
11649 case IORING_REGISTER_RESTRICTIONS:
11650 ret = io_register_restrictions(ctx, arg, nr_args);
11652 case IORING_REGISTER_FILES2:
11653 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11655 case IORING_REGISTER_FILES_UPDATE2:
11656 ret = io_register_rsrc_update(ctx, arg, nr_args,
11659 case IORING_REGISTER_BUFFERS2:
11660 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11662 case IORING_REGISTER_BUFFERS_UPDATE:
11663 ret = io_register_rsrc_update(ctx, arg, nr_args,
11664 IORING_RSRC_BUFFER);
11666 case IORING_REGISTER_IOWQ_AFF:
11668 if (!arg || !nr_args)
11670 ret = io_register_iowq_aff(ctx, arg, nr_args);
11672 case IORING_UNREGISTER_IOWQ_AFF:
11674 if (arg || nr_args)
11676 ret = io_unregister_iowq_aff(ctx);
11678 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11680 if (!arg || nr_args != 2)
11682 ret = io_register_iowq_max_workers(ctx, arg);
11684 case IORING_REGISTER_RING_FDS:
11685 ret = io_ringfd_register(ctx, arg, nr_args);
11687 case IORING_UNREGISTER_RING_FDS:
11688 ret = io_ringfd_unregister(ctx, arg, nr_args);
11698 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11699 void __user *, arg, unsigned int, nr_args)
11701 struct io_ring_ctx *ctx;
11710 if (f.file->f_op != &io_uring_fops)
11713 ctx = f.file->private_data;
11715 io_run_task_work();
11717 mutex_lock(&ctx->uring_lock);
11718 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11719 mutex_unlock(&ctx->uring_lock);
11720 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11726 static int __init io_uring_init(void)
11728 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11729 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11730 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11733 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11734 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11735 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11736 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11737 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11738 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11739 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11740 BUILD_BUG_SQE_ELEM(8, __u64, off);
11741 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11742 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11743 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11744 BUILD_BUG_SQE_ELEM(24, __u32, len);
11745 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11746 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11747 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11748 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11749 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11750 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11751 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11752 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11753 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11754 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11755 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11756 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11757 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11758 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11759 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11760 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11761 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11762 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11763 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11764 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11765 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11767 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11768 sizeof(struct io_uring_rsrc_update));
11769 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11770 sizeof(struct io_uring_rsrc_update2));
11772 /* ->buf_index is u16 */
11773 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11775 /* should fit into one byte */
11776 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11777 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11778 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11780 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11781 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11783 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11787 __initcall(io_uring_init);