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>
83 #include <linux/xattr.h>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
98 #define IORING_MAX_FIXED_FILES (1U << 15)
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100 IORING_REGISTER_LAST + IORING_OP_LAST)
102 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
103 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
104 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
106 #define IORING_MAX_REG_BUFFERS (1U << 14)
108 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
111 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
114 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
115 REQ_F_POLLED | REQ_F_CREDS | REQ_F_ASYNC_DATA)
117 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
120 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
123 u32 head ____cacheline_aligned_in_smp;
124 u32 tail ____cacheline_aligned_in_smp;
128 * This data is shared with the application through the mmap at offsets
129 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
131 * The offsets to the member fields are published through struct
132 * io_sqring_offsets when calling io_uring_setup.
136 * Head and tail offsets into the ring; the offsets need to be
137 * masked to get valid indices.
139 * The kernel controls head of the sq ring and the tail of the cq ring,
140 * and the application controls tail of the sq ring and the head of the
143 struct io_uring sq, cq;
145 * Bitmasks to apply to head and tail offsets (constant, equals
148 u32 sq_ring_mask, cq_ring_mask;
149 /* Ring sizes (constant, power of 2) */
150 u32 sq_ring_entries, cq_ring_entries;
152 * Number of invalid entries dropped by the kernel due to
153 * invalid index stored in array
155 * Written by the kernel, shouldn't be modified by the
156 * application (i.e. get number of "new events" by comparing to
159 * After a new SQ head value was read by the application this
160 * counter includes all submissions that were dropped reaching
161 * the new SQ head (and possibly more).
167 * Written by the kernel, shouldn't be modified by the
170 * The application needs a full memory barrier before checking
171 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
177 * Written by the application, shouldn't be modified by the
182 * Number of completion events lost because the queue was full;
183 * this should be avoided by the application by making sure
184 * there are not more requests pending than there is space in
185 * the completion queue.
187 * Written by the kernel, shouldn't be modified by the
188 * application (i.e. get number of "new events" by comparing to
191 * As completion events come in out of order this counter is not
192 * ordered with any other data.
196 * Ring buffer of completion events.
198 * The kernel writes completion events fresh every time they are
199 * produced, so the application is allowed to modify pending
202 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
205 enum io_uring_cmd_flags {
206 IO_URING_F_COMPLETE_DEFER = 1,
207 IO_URING_F_UNLOCKED = 2,
208 /* int's last bit, sign checks are usually faster than a bit test */
209 IO_URING_F_NONBLOCK = INT_MIN,
212 struct io_mapped_ubuf {
215 unsigned int nr_bvecs;
216 unsigned long acct_pages;
217 struct bio_vec bvec[];
222 struct io_overflow_cqe {
223 struct list_head list;
224 struct io_uring_cqe cqe;
228 * FFS_SCM is only available on 64-bit archs, for 32-bit we just define it as 0
229 * and define IO_URING_SCM_ALL. For this case, we use SCM for all files as we
230 * can't safely always dereference the file when the task has exited and ring
231 * cleanup is done. If a file is tracked and part of SCM, then unix gc on
232 * process exit may reap it before __io_sqe_files_unregister() is run.
234 #define FFS_NOWAIT 0x1UL
235 #define FFS_ISREG 0x2UL
236 #if defined(CONFIG_64BIT)
237 #define FFS_SCM 0x4UL
239 #define IO_URING_SCM_ALL
240 #define FFS_SCM 0x0UL
242 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG|FFS_SCM)
244 struct io_fixed_file {
245 /* file * with additional FFS_* flags */
246 unsigned long file_ptr;
250 struct list_head list;
255 struct io_mapped_ubuf *buf;
259 struct io_file_table {
260 struct io_fixed_file *files;
263 struct io_rsrc_node {
264 struct percpu_ref refs;
265 struct list_head node;
266 struct list_head rsrc_list;
267 struct io_rsrc_data *rsrc_data;
268 struct llist_node llist;
272 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
274 struct io_rsrc_data {
275 struct io_ring_ctx *ctx;
281 struct completion done;
285 struct io_buffer_list {
286 struct list_head buf_list;
291 struct list_head list;
298 struct io_restriction {
299 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
300 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
301 u8 sqe_flags_allowed;
302 u8 sqe_flags_required;
307 IO_SQ_THREAD_SHOULD_STOP = 0,
308 IO_SQ_THREAD_SHOULD_PARK,
313 atomic_t park_pending;
316 /* ctx's that are using this sqd */
317 struct list_head ctx_list;
319 struct task_struct *thread;
320 struct wait_queue_head wait;
322 unsigned sq_thread_idle;
328 struct completion exited;
331 #define IO_COMPL_BATCH 32
332 #define IO_REQ_CACHE_SIZE 32
333 #define IO_REQ_ALLOC_BATCH 8
335 struct io_submit_link {
336 struct io_kiocb *head;
337 struct io_kiocb *last;
340 struct io_submit_state {
341 /* inline/task_work completion list, under ->uring_lock */
342 struct io_wq_work_node free_list;
343 /* batch completion logic */
344 struct io_wq_work_list compl_reqs;
345 struct io_submit_link link;
350 unsigned short submit_nr;
351 struct blk_plug plug;
355 struct eventfd_ctx *cq_ev_fd;
356 unsigned int eventfd_async: 1;
360 #define BGID_ARRAY 64
363 /* const or read-mostly hot data */
365 struct percpu_ref refs;
367 struct io_rings *rings;
369 enum task_work_notify_mode notify_method;
370 unsigned int compat: 1;
371 unsigned int drain_next: 1;
372 unsigned int restricted: 1;
373 unsigned int off_timeout_used: 1;
374 unsigned int drain_active: 1;
375 unsigned int drain_disabled: 1;
376 unsigned int has_evfd: 1;
377 unsigned int syscall_iopoll: 1;
378 } ____cacheline_aligned_in_smp;
380 /* submission data */
382 struct mutex uring_lock;
385 * Ring buffer of indices into array of io_uring_sqe, which is
386 * mmapped by the application using the IORING_OFF_SQES offset.
388 * This indirection could e.g. be used to assign fixed
389 * io_uring_sqe entries to operations and only submit them to
390 * the queue when needed.
392 * The kernel modifies neither the indices array nor the entries
396 struct io_uring_sqe *sq_sqes;
397 unsigned cached_sq_head;
399 struct list_head defer_list;
402 * Fixed resources fast path, should be accessed only under
403 * uring_lock, and updated through io_uring_register(2)
405 struct io_rsrc_node *rsrc_node;
406 int rsrc_cached_refs;
408 struct io_file_table file_table;
409 unsigned nr_user_files;
410 unsigned nr_user_bufs;
411 struct io_mapped_ubuf **user_bufs;
413 struct io_submit_state submit_state;
415 struct io_buffer_list *io_bl;
416 struct xarray io_bl_xa;
417 struct list_head io_buffers_cache;
419 struct list_head timeout_list;
420 struct list_head ltimeout_list;
421 struct list_head cq_overflow_list;
422 struct list_head apoll_cache;
423 struct xarray personalities;
425 unsigned sq_thread_idle;
426 } ____cacheline_aligned_in_smp;
428 /* IRQ completion list, under ->completion_lock */
429 struct io_wq_work_list locked_free_list;
430 unsigned int locked_free_nr;
432 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
433 struct io_sq_data *sq_data; /* if using sq thread polling */
435 struct wait_queue_head sqo_sq_wait;
436 struct list_head sqd_list;
438 unsigned long check_cq;
442 * We cache a range of free CQEs we can use, once exhausted it
443 * should go through a slower range setup, see __io_get_cqe()
445 struct io_uring_cqe *cqe_cached;
446 struct io_uring_cqe *cqe_sentinel;
448 unsigned cached_cq_tail;
450 struct io_ev_fd __rcu *io_ev_fd;
451 struct wait_queue_head cq_wait;
453 atomic_t cq_timeouts;
454 unsigned cq_last_tm_flush;
455 } ____cacheline_aligned_in_smp;
458 spinlock_t completion_lock;
460 spinlock_t timeout_lock;
463 * ->iopoll_list is protected by the ctx->uring_lock for
464 * io_uring instances that don't use IORING_SETUP_SQPOLL.
465 * For SQPOLL, only the single threaded io_sq_thread() will
466 * manipulate the list, hence no extra locking is needed there.
468 struct io_wq_work_list iopoll_list;
469 struct hlist_head *cancel_hash;
470 unsigned cancel_hash_bits;
471 bool poll_multi_queue;
473 struct list_head io_buffers_comp;
474 } ____cacheline_aligned_in_smp;
476 struct io_restriction restrictions;
478 /* slow path rsrc auxilary data, used by update/register */
480 struct io_rsrc_node *rsrc_backup_node;
481 struct io_mapped_ubuf *dummy_ubuf;
482 struct io_rsrc_data *file_data;
483 struct io_rsrc_data *buf_data;
485 struct delayed_work rsrc_put_work;
486 struct llist_head rsrc_put_llist;
487 struct list_head rsrc_ref_list;
488 spinlock_t rsrc_ref_lock;
490 struct list_head io_buffers_pages;
493 /* Keep this last, we don't need it for the fast path */
495 #if defined(CONFIG_UNIX)
496 struct socket *ring_sock;
498 /* hashed buffered write serialization */
499 struct io_wq_hash *hash_map;
501 /* Only used for accounting purposes */
502 struct user_struct *user;
503 struct mm_struct *mm_account;
505 /* ctx exit and cancelation */
506 struct llist_head fallback_llist;
507 struct delayed_work fallback_work;
508 struct work_struct exit_work;
509 struct list_head tctx_list;
510 struct completion ref_comp;
512 bool iowq_limits_set;
517 * Arbitrary limit, can be raised if need be
519 #define IO_RINGFD_REG_MAX 16
521 struct io_uring_task {
522 /* submission side */
525 struct wait_queue_head wait;
526 const struct io_ring_ctx *last;
528 struct percpu_counter inflight;
531 spinlock_t task_lock;
532 struct io_wq_work_list task_list;
533 struct io_wq_work_list prior_task_list;
534 struct callback_head task_work;
535 struct file **registered_rings;
540 * First field must be the file pointer in all the
541 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
543 struct io_poll_iocb {
545 struct wait_queue_head *head;
547 struct wait_queue_entry wait;
550 struct io_poll_update {
556 bool update_user_data;
565 struct io_timeout_data {
566 struct io_kiocb *req;
567 struct hrtimer timer;
568 struct timespec64 ts;
569 enum hrtimer_mode mode;
575 struct sockaddr __user *addr;
576 int __user *addr_len;
579 unsigned long nofile;
589 unsigned long nofile;
611 struct list_head list;
612 /* head of the link, used by linked timeouts only */
613 struct io_kiocb *head;
614 /* for linked completions */
615 struct io_kiocb *prev;
618 struct io_timeout_rem {
623 struct timespec64 ts;
629 /* NOTE: kiocb has the file as the first member, so don't do it here */
638 struct sockaddr __user *addr;
645 struct compat_msghdr __user *umsg_compat;
646 struct user_msghdr __user *umsg;
659 struct filename *filename;
661 unsigned long nofile;
664 struct io_rsrc_update {
690 struct epoll_event event;
694 struct file *file_out;
702 struct io_provide_buf {
716 struct filename *filename;
717 struct statx __user *buffer;
729 struct filename *oldpath;
730 struct filename *newpath;
738 struct filename *filename;
745 struct filename *filename;
751 struct filename *oldpath;
752 struct filename *newpath;
759 struct filename *oldpath;
760 struct filename *newpath;
770 struct io_async_connect {
771 struct sockaddr_storage address;
774 struct io_async_msghdr {
775 struct iovec fast_iov[UIO_FASTIOV];
776 /* points to an allocated iov, if NULL we use fast_iov instead */
777 struct iovec *free_iov;
778 struct sockaddr __user *uaddr;
780 struct sockaddr_storage addr;
784 struct iov_iter iter;
785 struct iov_iter_state iter_state;
786 struct iovec fast_iov[UIO_FASTIOV];
790 struct io_rw_state s;
791 const struct iovec *free_iovec;
793 struct wait_page_queue wpq;
798 struct xattr_ctx ctx;
799 struct filename *filename;
803 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
804 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
805 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
806 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
807 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
808 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
809 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
811 /* first byte is taken by user flags, shift it to not overlap */
816 REQ_F_LINK_TIMEOUT_BIT,
817 REQ_F_NEED_CLEANUP_BIT,
819 REQ_F_BUFFER_SELECTED_BIT,
820 REQ_F_COMPLETE_INLINE_BIT,
824 REQ_F_ARM_LTIMEOUT_BIT,
825 REQ_F_ASYNC_DATA_BIT,
826 REQ_F_SKIP_LINK_CQES_BIT,
827 REQ_F_SINGLE_POLL_BIT,
828 REQ_F_DOUBLE_POLL_BIT,
829 REQ_F_PARTIAL_IO_BIT,
830 /* keep async read/write and isreg together and in order */
831 REQ_F_SUPPORT_NOWAIT_BIT,
834 /* not a real bit, just to check we're not overflowing the space */
840 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
841 /* drain existing IO first */
842 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
844 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
845 /* doesn't sever on completion < 0 */
846 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
848 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
849 /* IOSQE_BUFFER_SELECT */
850 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
851 /* IOSQE_CQE_SKIP_SUCCESS */
852 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
854 /* fail rest of links */
855 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
856 /* on inflight list, should be cancelled and waited on exit reliably */
857 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
858 /* read/write uses file position */
859 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
860 /* must not punt to workers */
861 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
862 /* has or had linked timeout */
863 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
865 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
866 /* already went through poll handler */
867 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
868 /* buffer already selected */
869 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
870 /* completion is deferred through io_comp_state */
871 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
872 /* caller should reissue async */
873 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
874 /* supports async reads/writes */
875 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
877 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
878 /* has creds assigned */
879 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
880 /* skip refcounting if not set */
881 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
882 /* there is a linked timeout that has to be armed */
883 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
884 /* ->async_data allocated */
885 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
886 /* don't post CQEs while failing linked requests */
887 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
888 /* single poll may be active */
889 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
890 /* double poll may active */
891 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
892 /* request has already done partial IO */
893 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
897 struct io_poll_iocb poll;
898 struct io_poll_iocb *double_poll;
901 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
903 struct io_task_work {
905 struct io_wq_work_node node;
906 struct llist_node fallback_node;
908 io_req_tw_func_t func;
912 IORING_RSRC_FILE = 0,
913 IORING_RSRC_BUFFER = 1,
919 /* fd initially, then cflags for completion */
927 IO_CHECK_CQ_OVERFLOW_BIT,
928 IO_CHECK_CQ_DROPPED_BIT,
932 * NOTE! Each of the iocb union members has the file pointer
933 * as the first entry in their struct definition. So you can
934 * access the file pointer through any of the sub-structs,
935 * or directly as just 'file' in this struct.
941 struct io_poll_iocb poll;
942 struct io_poll_update poll_update;
943 struct io_accept accept;
945 struct io_cancel cancel;
946 struct io_timeout timeout;
947 struct io_timeout_rem timeout_rem;
948 struct io_connect connect;
949 struct io_sr_msg sr_msg;
951 struct io_close close;
952 struct io_rsrc_update rsrc_update;
953 struct io_fadvise fadvise;
954 struct io_madvise madvise;
955 struct io_epoll epoll;
956 struct io_splice splice;
957 struct io_provide_buf pbuf;
958 struct io_statx statx;
959 struct io_shutdown shutdown;
960 struct io_rename rename;
961 struct io_unlink unlink;
962 struct io_mkdir mkdir;
963 struct io_symlink symlink;
964 struct io_hardlink hardlink;
966 struct io_xattr xattr;
967 struct io_socket sock;
971 /* polled IO has completed */
974 * Can be either a fixed buffer index, or used with provided buffers.
975 * For the latter, before issue it points to the buffer group ID,
976 * and after selection it points to the buffer ID itself.
983 struct io_ring_ctx *ctx;
984 struct task_struct *task;
986 struct io_rsrc_node *rsrc_node;
989 /* store used ubuf, so we can prevent reloading */
990 struct io_mapped_ubuf *imu;
992 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
993 struct io_buffer *kbuf;
997 /* used by request caches, completion batching and iopoll */
998 struct io_wq_work_node comp_list;
999 /* cache ->apoll->events */
1004 struct io_task_work io_task_work;
1005 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1007 struct hlist_node hash_node;
1013 /* internal polling, see IORING_FEAT_FAST_POLL */
1014 struct async_poll *apoll;
1015 /* opcode allocated if it needs to store data for async defer */
1017 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1018 struct io_kiocb *link;
1019 /* custom credentials, valid IFF REQ_F_CREDS is set */
1020 const struct cred *creds;
1021 struct io_wq_work work;
1024 struct io_tctx_node {
1025 struct list_head ctx_node;
1026 struct task_struct *task;
1027 struct io_ring_ctx *ctx;
1030 struct io_defer_entry {
1031 struct list_head list;
1032 struct io_kiocb *req;
1036 struct io_cancel_data {
1037 struct io_ring_ctx *ctx;
1047 /* needs req->file assigned */
1048 unsigned needs_file : 1;
1049 /* should block plug */
1051 /* hash wq insertion if file is a regular file */
1052 unsigned hash_reg_file : 1;
1053 /* unbound wq insertion if file is a non-regular file */
1054 unsigned unbound_nonreg_file : 1;
1055 /* set if opcode supports polled "wait" */
1056 unsigned pollin : 1;
1057 unsigned pollout : 1;
1058 unsigned poll_exclusive : 1;
1059 /* op supports buffer selection */
1060 unsigned buffer_select : 1;
1061 /* do prep async if is going to be punted */
1062 unsigned needs_async_setup : 1;
1063 /* opcode is not supported by this kernel */
1064 unsigned not_supported : 1;
1066 unsigned audit_skip : 1;
1067 /* supports ioprio */
1068 unsigned ioprio : 1;
1069 /* supports iopoll */
1070 unsigned iopoll : 1;
1071 /* size of async data needed, if any */
1072 unsigned short async_size;
1075 static const struct io_op_def io_op_defs[] = {
1080 [IORING_OP_READV] = {
1082 .unbound_nonreg_file = 1,
1085 .needs_async_setup = 1,
1090 .async_size = sizeof(struct io_async_rw),
1092 [IORING_OP_WRITEV] = {
1095 .unbound_nonreg_file = 1,
1097 .needs_async_setup = 1,
1102 .async_size = sizeof(struct io_async_rw),
1104 [IORING_OP_FSYNC] = {
1108 [IORING_OP_READ_FIXED] = {
1110 .unbound_nonreg_file = 1,
1116 .async_size = sizeof(struct io_async_rw),
1118 [IORING_OP_WRITE_FIXED] = {
1121 .unbound_nonreg_file = 1,
1127 .async_size = sizeof(struct io_async_rw),
1129 [IORING_OP_POLL_ADD] = {
1131 .unbound_nonreg_file = 1,
1134 [IORING_OP_POLL_REMOVE] = {
1137 [IORING_OP_SYNC_FILE_RANGE] = {
1141 [IORING_OP_SENDMSG] = {
1143 .unbound_nonreg_file = 1,
1145 .needs_async_setup = 1,
1146 .async_size = sizeof(struct io_async_msghdr),
1148 [IORING_OP_RECVMSG] = {
1150 .unbound_nonreg_file = 1,
1153 .needs_async_setup = 1,
1154 .async_size = sizeof(struct io_async_msghdr),
1156 [IORING_OP_TIMEOUT] = {
1158 .async_size = sizeof(struct io_timeout_data),
1160 [IORING_OP_TIMEOUT_REMOVE] = {
1161 /* used by timeout updates' prep() */
1164 [IORING_OP_ACCEPT] = {
1166 .unbound_nonreg_file = 1,
1168 .poll_exclusive = 1,
1170 [IORING_OP_ASYNC_CANCEL] = {
1173 [IORING_OP_LINK_TIMEOUT] = {
1175 .async_size = sizeof(struct io_timeout_data),
1177 [IORING_OP_CONNECT] = {
1179 .unbound_nonreg_file = 1,
1181 .needs_async_setup = 1,
1182 .async_size = sizeof(struct io_async_connect),
1184 [IORING_OP_FALLOCATE] = {
1187 [IORING_OP_OPENAT] = {},
1188 [IORING_OP_CLOSE] = {},
1189 [IORING_OP_FILES_UPDATE] = {
1193 [IORING_OP_STATX] = {
1196 [IORING_OP_READ] = {
1198 .unbound_nonreg_file = 1,
1205 .async_size = sizeof(struct io_async_rw),
1207 [IORING_OP_WRITE] = {
1210 .unbound_nonreg_file = 1,
1216 .async_size = sizeof(struct io_async_rw),
1218 [IORING_OP_FADVISE] = {
1222 [IORING_OP_MADVISE] = {},
1223 [IORING_OP_SEND] = {
1225 .unbound_nonreg_file = 1,
1229 [IORING_OP_RECV] = {
1231 .unbound_nonreg_file = 1,
1236 [IORING_OP_OPENAT2] = {
1238 [IORING_OP_EPOLL_CTL] = {
1239 .unbound_nonreg_file = 1,
1242 [IORING_OP_SPLICE] = {
1245 .unbound_nonreg_file = 1,
1248 [IORING_OP_PROVIDE_BUFFERS] = {
1252 [IORING_OP_REMOVE_BUFFERS] = {
1259 .unbound_nonreg_file = 1,
1262 [IORING_OP_SHUTDOWN] = {
1265 [IORING_OP_RENAMEAT] = {},
1266 [IORING_OP_UNLINKAT] = {},
1267 [IORING_OP_MKDIRAT] = {},
1268 [IORING_OP_SYMLINKAT] = {},
1269 [IORING_OP_LINKAT] = {},
1270 [IORING_OP_MSG_RING] = {
1274 [IORING_OP_FSETXATTR] = {
1277 [IORING_OP_SETXATTR] = {},
1278 [IORING_OP_FGETXATTR] = {
1281 [IORING_OP_GETXATTR] = {},
1282 [IORING_OP_SOCKET] = {
1287 /* requests with any of those set should undergo io_disarm_next() */
1288 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1289 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1291 static bool io_disarm_next(struct io_kiocb *req);
1292 static void io_uring_del_tctx_node(unsigned long index);
1293 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1294 struct task_struct *task,
1296 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1298 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1299 static void io_dismantle_req(struct io_kiocb *req);
1300 static void io_queue_linked_timeout(struct io_kiocb *req);
1301 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1302 struct io_uring_rsrc_update2 *up,
1304 static void io_clean_op(struct io_kiocb *req);
1305 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1306 unsigned issue_flags);
1307 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1308 static void io_drop_inflight_file(struct io_kiocb *req);
1309 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1310 static void io_queue_sqe(struct io_kiocb *req);
1311 static void io_rsrc_put_work(struct work_struct *work);
1313 static void io_req_task_queue(struct io_kiocb *req);
1314 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1315 static int io_req_prep_async(struct io_kiocb *req);
1317 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1318 unsigned int issue_flags, u32 slot_index);
1319 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1321 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1322 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1323 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1325 static struct kmem_cache *req_cachep;
1327 static const struct file_operations io_uring_fops;
1329 const char *io_uring_get_opcode(u8 opcode)
1331 switch ((enum io_uring_op)opcode) {
1334 case IORING_OP_READV:
1336 case IORING_OP_WRITEV:
1338 case IORING_OP_FSYNC:
1340 case IORING_OP_READ_FIXED:
1341 return "READ_FIXED";
1342 case IORING_OP_WRITE_FIXED:
1343 return "WRITE_FIXED";
1344 case IORING_OP_POLL_ADD:
1346 case IORING_OP_POLL_REMOVE:
1347 return "POLL_REMOVE";
1348 case IORING_OP_SYNC_FILE_RANGE:
1349 return "SYNC_FILE_RANGE";
1350 case IORING_OP_SENDMSG:
1352 case IORING_OP_RECVMSG:
1354 case IORING_OP_TIMEOUT:
1356 case IORING_OP_TIMEOUT_REMOVE:
1357 return "TIMEOUT_REMOVE";
1358 case IORING_OP_ACCEPT:
1360 case IORING_OP_ASYNC_CANCEL:
1361 return "ASYNC_CANCEL";
1362 case IORING_OP_LINK_TIMEOUT:
1363 return "LINK_TIMEOUT";
1364 case IORING_OP_CONNECT:
1366 case IORING_OP_FALLOCATE:
1368 case IORING_OP_OPENAT:
1370 case IORING_OP_CLOSE:
1372 case IORING_OP_FILES_UPDATE:
1373 return "FILES_UPDATE";
1374 case IORING_OP_STATX:
1376 case IORING_OP_READ:
1378 case IORING_OP_WRITE:
1380 case IORING_OP_FADVISE:
1382 case IORING_OP_MADVISE:
1384 case IORING_OP_SEND:
1386 case IORING_OP_RECV:
1388 case IORING_OP_OPENAT2:
1390 case IORING_OP_EPOLL_CTL:
1392 case IORING_OP_SPLICE:
1394 case IORING_OP_PROVIDE_BUFFERS:
1395 return "PROVIDE_BUFFERS";
1396 case IORING_OP_REMOVE_BUFFERS:
1397 return "REMOVE_BUFFERS";
1400 case IORING_OP_SHUTDOWN:
1402 case IORING_OP_RENAMEAT:
1404 case IORING_OP_UNLINKAT:
1406 case IORING_OP_MKDIRAT:
1408 case IORING_OP_SYMLINKAT:
1410 case IORING_OP_LINKAT:
1412 case IORING_OP_MSG_RING:
1414 case IORING_OP_FSETXATTR:
1416 case IORING_OP_SETXATTR:
1418 case IORING_OP_FGETXATTR:
1420 case IORING_OP_GETXATTR:
1422 case IORING_OP_SOCKET:
1424 case IORING_OP_LAST:
1430 struct sock *io_uring_get_socket(struct file *file)
1432 #if defined(CONFIG_UNIX)
1433 if (file->f_op == &io_uring_fops) {
1434 struct io_ring_ctx *ctx = file->private_data;
1436 return ctx->ring_sock->sk;
1441 EXPORT_SYMBOL(io_uring_get_socket);
1443 #if defined(CONFIG_UNIX)
1444 static inline bool io_file_need_scm(struct file *filp)
1446 #if defined(IO_URING_SCM_ALL)
1449 return !!unix_get_socket(filp);
1453 static inline bool io_file_need_scm(struct file *filp)
1459 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1461 lockdep_assert_held(&ctx->uring_lock);
1462 if (issue_flags & IO_URING_F_UNLOCKED)
1463 mutex_unlock(&ctx->uring_lock);
1466 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1469 * "Normal" inline submissions always hold the uring_lock, since we
1470 * grab it from the system call. Same is true for the SQPOLL offload.
1471 * The only exception is when we've detached the request and issue it
1472 * from an async worker thread, grab the lock for that case.
1474 if (issue_flags & IO_URING_F_UNLOCKED)
1475 mutex_lock(&ctx->uring_lock);
1476 lockdep_assert_held(&ctx->uring_lock);
1479 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1482 mutex_lock(&ctx->uring_lock);
1487 #define io_for_each_link(pos, head) \
1488 for (pos = (head); pos; pos = pos->link)
1491 * Shamelessly stolen from the mm implementation of page reference checking,
1492 * see commit f958d7b528b1 for details.
1494 #define req_ref_zero_or_close_to_overflow(req) \
1495 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1497 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1499 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1500 return atomic_inc_not_zero(&req->refs);
1503 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1505 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1508 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1509 return atomic_dec_and_test(&req->refs);
1512 static inline void req_ref_get(struct io_kiocb *req)
1514 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1515 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1516 atomic_inc(&req->refs);
1519 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1521 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1522 __io_submit_flush_completions(ctx);
1525 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1527 if (!(req->flags & REQ_F_REFCOUNT)) {
1528 req->flags |= REQ_F_REFCOUNT;
1529 atomic_set(&req->refs, nr);
1533 static inline void io_req_set_refcount(struct io_kiocb *req)
1535 __io_req_set_refcount(req, 1);
1538 #define IO_RSRC_REF_BATCH 100
1540 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1542 percpu_ref_put_many(&node->refs, nr);
1545 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1546 struct io_ring_ctx *ctx)
1547 __must_hold(&ctx->uring_lock)
1549 struct io_rsrc_node *node = req->rsrc_node;
1552 if (node == ctx->rsrc_node)
1553 ctx->rsrc_cached_refs++;
1555 io_rsrc_put_node(node, 1);
1559 static inline void io_req_put_rsrc(struct io_kiocb *req)
1562 io_rsrc_put_node(req->rsrc_node, 1);
1565 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1566 __must_hold(&ctx->uring_lock)
1568 if (ctx->rsrc_cached_refs) {
1569 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1570 ctx->rsrc_cached_refs = 0;
1574 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1575 __must_hold(&ctx->uring_lock)
1577 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1578 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1581 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1582 struct io_ring_ctx *ctx,
1583 unsigned int issue_flags)
1585 if (!req->rsrc_node) {
1586 req->rsrc_node = ctx->rsrc_node;
1588 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1589 lockdep_assert_held(&ctx->uring_lock);
1590 ctx->rsrc_cached_refs--;
1591 if (unlikely(ctx->rsrc_cached_refs < 0))
1592 io_rsrc_refs_refill(ctx);
1594 percpu_ref_get(&req->rsrc_node->refs);
1599 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1601 req->flags &= ~REQ_F_BUFFER_SELECTED;
1602 list_add(&req->kbuf->list, list);
1604 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1607 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1609 lockdep_assert_held(&req->ctx->completion_lock);
1611 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1613 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1616 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1617 unsigned issue_flags)
1619 unsigned int cflags;
1621 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1625 * We can add this buffer back to two lists:
1627 * 1) The io_buffers_cache list. This one is protected by the
1628 * ctx->uring_lock. If we already hold this lock, add back to this
1629 * list as we can grab it from issue as well.
1630 * 2) The io_buffers_comp list. This one is protected by the
1631 * ctx->completion_lock.
1633 * We migrate buffers from the comp_list to the issue cache list
1636 if (issue_flags & IO_URING_F_UNLOCKED) {
1637 struct io_ring_ctx *ctx = req->ctx;
1639 spin_lock(&ctx->completion_lock);
1640 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1641 spin_unlock(&ctx->completion_lock);
1643 lockdep_assert_held(&req->ctx->uring_lock);
1645 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1651 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1654 if (ctx->io_bl && bgid < BGID_ARRAY)
1655 return &ctx->io_bl[bgid];
1657 return xa_load(&ctx->io_bl_xa, bgid);
1660 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1662 struct io_ring_ctx *ctx = req->ctx;
1663 struct io_buffer_list *bl;
1664 struct io_buffer *buf;
1666 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1668 /* don't recycle if we already did IO to this buffer */
1669 if (req->flags & REQ_F_PARTIAL_IO)
1672 io_ring_submit_lock(ctx, issue_flags);
1675 bl = io_buffer_get_list(ctx, buf->bgid);
1676 list_add(&buf->list, &bl->buf_list);
1677 req->flags &= ~REQ_F_BUFFER_SELECTED;
1678 req->buf_index = buf->bgid;
1680 io_ring_submit_unlock(ctx, issue_flags);
1683 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1685 __must_hold(&req->ctx->timeout_lock)
1687 if (task && head->task != task)
1693 * As io_match_task() but protected against racing with linked timeouts.
1694 * User must not hold timeout_lock.
1696 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1699 if (task && head->task != task)
1704 static inline bool req_has_async_data(struct io_kiocb *req)
1706 return req->flags & REQ_F_ASYNC_DATA;
1709 static inline void req_set_fail(struct io_kiocb *req)
1711 req->flags |= REQ_F_FAIL;
1712 if (req->flags & REQ_F_CQE_SKIP) {
1713 req->flags &= ~REQ_F_CQE_SKIP;
1714 req->flags |= REQ_F_SKIP_LINK_CQES;
1718 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1724 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1726 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1729 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1731 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1733 complete(&ctx->ref_comp);
1736 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1738 return !req->timeout.off;
1741 static __cold void io_fallback_req_func(struct work_struct *work)
1743 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1744 fallback_work.work);
1745 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1746 struct io_kiocb *req, *tmp;
1747 bool locked = false;
1749 percpu_ref_get(&ctx->refs);
1750 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1751 req->io_task_work.func(req, &locked);
1754 io_submit_flush_completions(ctx);
1755 mutex_unlock(&ctx->uring_lock);
1757 percpu_ref_put(&ctx->refs);
1760 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1762 struct io_ring_ctx *ctx;
1765 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1769 xa_init(&ctx->io_bl_xa);
1772 * Use 5 bits less than the max cq entries, that should give us around
1773 * 32 entries per hash list if totally full and uniformly spread.
1775 hash_bits = ilog2(p->cq_entries);
1779 ctx->cancel_hash_bits = hash_bits;
1780 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1782 if (!ctx->cancel_hash)
1784 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1786 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1787 if (!ctx->dummy_ubuf)
1789 /* set invalid range, so io_import_fixed() fails meeting it */
1790 ctx->dummy_ubuf->ubuf = -1UL;
1792 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1793 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1796 ctx->flags = p->flags;
1797 init_waitqueue_head(&ctx->sqo_sq_wait);
1798 INIT_LIST_HEAD(&ctx->sqd_list);
1799 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1800 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1801 INIT_LIST_HEAD(&ctx->apoll_cache);
1802 init_completion(&ctx->ref_comp);
1803 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1804 mutex_init(&ctx->uring_lock);
1805 init_waitqueue_head(&ctx->cq_wait);
1806 spin_lock_init(&ctx->completion_lock);
1807 spin_lock_init(&ctx->timeout_lock);
1808 INIT_WQ_LIST(&ctx->iopoll_list);
1809 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1810 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1811 INIT_LIST_HEAD(&ctx->defer_list);
1812 INIT_LIST_HEAD(&ctx->timeout_list);
1813 INIT_LIST_HEAD(&ctx->ltimeout_list);
1814 spin_lock_init(&ctx->rsrc_ref_lock);
1815 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1816 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1817 init_llist_head(&ctx->rsrc_put_llist);
1818 INIT_LIST_HEAD(&ctx->tctx_list);
1819 ctx->submit_state.free_list.next = NULL;
1820 INIT_WQ_LIST(&ctx->locked_free_list);
1821 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1822 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1825 kfree(ctx->dummy_ubuf);
1826 kfree(ctx->cancel_hash);
1828 xa_destroy(&ctx->io_bl_xa);
1833 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1835 struct io_rings *r = ctx->rings;
1837 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1841 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1843 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1844 struct io_ring_ctx *ctx = req->ctx;
1846 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1852 static inline bool io_req_ffs_set(struct io_kiocb *req)
1854 return req->flags & REQ_F_FIXED_FILE;
1857 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1859 if (WARN_ON_ONCE(!req->link))
1862 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1863 req->flags |= REQ_F_LINK_TIMEOUT;
1865 /* linked timeouts should have two refs once prep'ed */
1866 io_req_set_refcount(req);
1867 __io_req_set_refcount(req->link, 2);
1871 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1873 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1875 return __io_prep_linked_timeout(req);
1878 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1880 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1883 static inline void io_arm_ltimeout(struct io_kiocb *req)
1885 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1886 __io_arm_ltimeout(req);
1889 static void io_prep_async_work(struct io_kiocb *req)
1891 const struct io_op_def *def = &io_op_defs[req->opcode];
1892 struct io_ring_ctx *ctx = req->ctx;
1894 if (!(req->flags & REQ_F_CREDS)) {
1895 req->flags |= REQ_F_CREDS;
1896 req->creds = get_current_cred();
1899 req->work.list.next = NULL;
1900 req->work.flags = 0;
1901 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1902 if (req->flags & REQ_F_FORCE_ASYNC)
1903 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1905 if (req->flags & REQ_F_ISREG) {
1906 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1907 io_wq_hash_work(&req->work, file_inode(req->file));
1908 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1909 if (def->unbound_nonreg_file)
1910 req->work.flags |= IO_WQ_WORK_UNBOUND;
1914 static void io_prep_async_link(struct io_kiocb *req)
1916 struct io_kiocb *cur;
1918 if (req->flags & REQ_F_LINK_TIMEOUT) {
1919 struct io_ring_ctx *ctx = req->ctx;
1921 spin_lock_irq(&ctx->timeout_lock);
1922 io_for_each_link(cur, req)
1923 io_prep_async_work(cur);
1924 spin_unlock_irq(&ctx->timeout_lock);
1926 io_for_each_link(cur, req)
1927 io_prep_async_work(cur);
1931 static inline void io_req_add_compl_list(struct io_kiocb *req)
1933 struct io_submit_state *state = &req->ctx->submit_state;
1935 if (!(req->flags & REQ_F_CQE_SKIP))
1936 state->flush_cqes = true;
1937 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1940 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1942 struct io_kiocb *link = io_prep_linked_timeout(req);
1943 struct io_uring_task *tctx = req->task->io_uring;
1946 BUG_ON(!tctx->io_wq);
1948 /* init ->work of the whole link before punting */
1949 io_prep_async_link(req);
1952 * Not expected to happen, but if we do have a bug where this _can_
1953 * happen, catch it here and ensure the request is marked as
1954 * canceled. That will make io-wq go through the usual work cancel
1955 * procedure rather than attempt to run this request (or create a new
1958 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1959 req->work.flags |= IO_WQ_WORK_CANCEL;
1961 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1962 req->opcode, req->flags, &req->work,
1963 io_wq_is_hashed(&req->work));
1964 io_wq_enqueue(tctx->io_wq, &req->work);
1966 io_queue_linked_timeout(link);
1969 static void io_kill_timeout(struct io_kiocb *req, int status)
1970 __must_hold(&req->ctx->completion_lock)
1971 __must_hold(&req->ctx->timeout_lock)
1973 struct io_timeout_data *io = req->async_data;
1975 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1978 atomic_set(&req->ctx->cq_timeouts,
1979 atomic_read(&req->ctx->cq_timeouts) + 1);
1980 list_del_init(&req->timeout.list);
1981 io_req_tw_post_queue(req, status, 0);
1985 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1987 while (!list_empty(&ctx->defer_list)) {
1988 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1989 struct io_defer_entry, list);
1991 if (req_need_defer(de->req, de->seq))
1993 list_del_init(&de->list);
1994 io_req_task_queue(de->req);
1999 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
2000 __must_hold(&ctx->completion_lock)
2002 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
2003 struct io_kiocb *req, *tmp;
2005 spin_lock_irq(&ctx->timeout_lock);
2006 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
2007 u32 events_needed, events_got;
2009 if (io_is_timeout_noseq(req))
2013 * Since seq can easily wrap around over time, subtract
2014 * the last seq at which timeouts were flushed before comparing.
2015 * Assuming not more than 2^31-1 events have happened since,
2016 * these subtractions won't have wrapped, so we can check if
2017 * target is in [last_seq, current_seq] by comparing the two.
2019 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
2020 events_got = seq - ctx->cq_last_tm_flush;
2021 if (events_got < events_needed)
2024 io_kill_timeout(req, 0);
2026 ctx->cq_last_tm_flush = seq;
2027 spin_unlock_irq(&ctx->timeout_lock);
2030 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
2032 /* order cqe stores with ring update */
2033 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
2036 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
2038 if (ctx->off_timeout_used || ctx->drain_active) {
2039 spin_lock(&ctx->completion_lock);
2040 if (ctx->off_timeout_used)
2041 io_flush_timeouts(ctx);
2042 if (ctx->drain_active)
2043 io_queue_deferred(ctx);
2044 io_commit_cqring(ctx);
2045 spin_unlock(&ctx->completion_lock);
2048 io_eventfd_signal(ctx);
2051 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
2053 struct io_rings *r = ctx->rings;
2055 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
2058 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
2060 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
2064 * writes to the cq entry need to come after reading head; the
2065 * control dependency is enough as we're using WRITE_ONCE to
2068 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
2070 struct io_rings *rings = ctx->rings;
2071 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
2072 unsigned int shift = 0;
2073 unsigned int free, queued, len;
2075 if (ctx->flags & IORING_SETUP_CQE32)
2078 /* userspace may cheat modifying the tail, be safe and do min */
2079 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2080 free = ctx->cq_entries - queued;
2081 /* we need a contiguous range, limit based on the current array offset */
2082 len = min(free, ctx->cq_entries - off);
2086 ctx->cached_cq_tail++;
2087 ctx->cqe_cached = &rings->cqes[off];
2088 ctx->cqe_sentinel = ctx->cqe_cached + len;
2090 return &rings->cqes[off << shift];
2093 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2095 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2096 struct io_uring_cqe *cqe = ctx->cqe_cached;
2098 if (ctx->flags & IORING_SETUP_CQE32) {
2099 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2104 ctx->cached_cq_tail++;
2109 return __io_get_cqe(ctx);
2112 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2114 struct io_ev_fd *ev_fd;
2118 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2119 * and eventfd_signal
2121 ev_fd = rcu_dereference(ctx->io_ev_fd);
2124 * Check again if ev_fd exists incase an io_eventfd_unregister call
2125 * completed between the NULL check of ctx->io_ev_fd at the start of
2126 * the function and rcu_read_lock.
2128 if (unlikely(!ev_fd))
2130 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2133 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2134 eventfd_signal(ev_fd->cq_ev_fd, 1);
2139 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2142 * wake_up_all() may seem excessive, but io_wake_function() and
2143 * io_should_wake() handle the termination of the loop and only
2144 * wake as many waiters as we need to.
2146 if (wq_has_sleeper(&ctx->cq_wait))
2147 wake_up_all(&ctx->cq_wait);
2151 * This should only get called when at least one event has been posted.
2152 * Some applications rely on the eventfd notification count only changing
2153 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2154 * 1:1 relationship between how many times this function is called (and
2155 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2157 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2159 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2161 __io_commit_cqring_flush(ctx);
2163 io_cqring_wake(ctx);
2166 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2168 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2170 __io_commit_cqring_flush(ctx);
2172 if (ctx->flags & IORING_SETUP_SQPOLL)
2173 io_cqring_wake(ctx);
2176 /* Returns true if there are no backlogged entries after the flush */
2177 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2179 bool all_flushed, posted;
2180 size_t cqe_size = sizeof(struct io_uring_cqe);
2182 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2185 if (ctx->flags & IORING_SETUP_CQE32)
2189 spin_lock(&ctx->completion_lock);
2190 while (!list_empty(&ctx->cq_overflow_list)) {
2191 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2192 struct io_overflow_cqe *ocqe;
2196 ocqe = list_first_entry(&ctx->cq_overflow_list,
2197 struct io_overflow_cqe, list);
2199 memcpy(cqe, &ocqe->cqe, cqe_size);
2201 io_account_cq_overflow(ctx);
2204 list_del(&ocqe->list);
2208 all_flushed = list_empty(&ctx->cq_overflow_list);
2210 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2211 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2214 io_commit_cqring(ctx);
2215 spin_unlock(&ctx->completion_lock);
2217 io_cqring_ev_posted(ctx);
2221 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2225 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2226 /* iopoll syncs against uring_lock, not completion_lock */
2227 if (ctx->flags & IORING_SETUP_IOPOLL)
2228 mutex_lock(&ctx->uring_lock);
2229 ret = __io_cqring_overflow_flush(ctx, false);
2230 if (ctx->flags & IORING_SETUP_IOPOLL)
2231 mutex_unlock(&ctx->uring_lock);
2237 static void __io_put_task(struct task_struct *task, int nr)
2239 struct io_uring_task *tctx = task->io_uring;
2241 percpu_counter_sub(&tctx->inflight, nr);
2242 if (unlikely(atomic_read(&tctx->in_idle)))
2243 wake_up(&tctx->wait);
2244 put_task_struct_many(task, nr);
2247 /* must to be called somewhat shortly after putting a request */
2248 static inline void io_put_task(struct task_struct *task, int nr)
2250 if (likely(task == current))
2251 task->io_uring->cached_refs += nr;
2253 __io_put_task(task, nr);
2256 static void io_task_refs_refill(struct io_uring_task *tctx)
2258 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2260 percpu_counter_add(&tctx->inflight, refill);
2261 refcount_add(refill, ¤t->usage);
2262 tctx->cached_refs += refill;
2265 static inline void io_get_task_refs(int nr)
2267 struct io_uring_task *tctx = current->io_uring;
2269 tctx->cached_refs -= nr;
2270 if (unlikely(tctx->cached_refs < 0))
2271 io_task_refs_refill(tctx);
2274 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2276 struct io_uring_task *tctx = task->io_uring;
2277 unsigned int refs = tctx->cached_refs;
2280 tctx->cached_refs = 0;
2281 percpu_counter_sub(&tctx->inflight, refs);
2282 put_task_struct_many(task, refs);
2286 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2287 s32 res, u32 cflags, u64 extra1,
2290 struct io_overflow_cqe *ocqe;
2291 size_t ocq_size = sizeof(struct io_overflow_cqe);
2292 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2295 ocq_size += sizeof(struct io_uring_cqe);
2297 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2298 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2301 * If we're in ring overflow flush mode, or in task cancel mode,
2302 * or cannot allocate an overflow entry, then we need to drop it
2305 io_account_cq_overflow(ctx);
2306 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2309 if (list_empty(&ctx->cq_overflow_list)) {
2310 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2311 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2314 ocqe->cqe.user_data = user_data;
2315 ocqe->cqe.res = res;
2316 ocqe->cqe.flags = cflags;
2318 ocqe->cqe.big_cqe[0] = extra1;
2319 ocqe->cqe.big_cqe[1] = extra2;
2321 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2325 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2326 s32 res, u32 cflags)
2328 struct io_uring_cqe *cqe;
2331 * If we can't get a cq entry, userspace overflowed the
2332 * submission (by quite a lot). Increment the overflow count in
2335 cqe = io_get_cqe(ctx);
2337 WRITE_ONCE(cqe->user_data, user_data);
2338 WRITE_ONCE(cqe->res, res);
2339 WRITE_ONCE(cqe->flags, cflags);
2342 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2345 static inline bool __io_fill_cqe_req_filled(struct io_ring_ctx *ctx,
2346 struct io_kiocb *req)
2348 struct io_uring_cqe *cqe;
2350 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2351 req->cqe.res, req->cqe.flags, 0, 0);
2354 * If we can't get a cq entry, userspace overflowed the
2355 * submission (by quite a lot). Increment the overflow count in
2358 cqe = io_get_cqe(ctx);
2360 memcpy(cqe, &req->cqe, sizeof(*cqe));
2363 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2364 req->cqe.res, req->cqe.flags, 0, 0);
2367 static inline bool __io_fill_cqe32_req_filled(struct io_ring_ctx *ctx,
2368 struct io_kiocb *req)
2370 struct io_uring_cqe *cqe;
2371 u64 extra1 = req->extra1;
2372 u64 extra2 = req->extra2;
2374 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2375 req->cqe.res, req->cqe.flags, extra1, extra2);
2378 * If we can't get a cq entry, userspace overflowed the
2379 * submission (by quite a lot). Increment the overflow count in
2382 cqe = io_get_cqe(ctx);
2384 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2385 cqe->big_cqe[0] = extra1;
2386 cqe->big_cqe[1] = extra2;
2390 return io_cqring_event_overflow(ctx, req->cqe.user_data, req->cqe.res,
2391 req->cqe.flags, extra1, extra2);
2394 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2396 trace_io_uring_complete(req->ctx, req, req->cqe.user_data, res, cflags, 0, 0);
2397 return __io_fill_cqe(req->ctx, req->cqe.user_data, res, cflags);
2400 static inline void __io_fill_cqe32_req(struct io_kiocb *req, s32 res, u32 cflags,
2401 u64 extra1, u64 extra2)
2403 struct io_ring_ctx *ctx = req->ctx;
2404 struct io_uring_cqe *cqe;
2406 if (WARN_ON_ONCE(!(ctx->flags & IORING_SETUP_CQE32)))
2408 if (req->flags & REQ_F_CQE_SKIP)
2411 trace_io_uring_complete(ctx, req, req->cqe.user_data, res, cflags,
2415 * If we can't get a cq entry, userspace overflowed the
2416 * submission (by quite a lot). Increment the overflow count in
2419 cqe = io_get_cqe(ctx);
2421 WRITE_ONCE(cqe->user_data, req->cqe.user_data);
2422 WRITE_ONCE(cqe->res, res);
2423 WRITE_ONCE(cqe->flags, cflags);
2424 WRITE_ONCE(cqe->big_cqe[0], extra1);
2425 WRITE_ONCE(cqe->big_cqe[1], extra2);
2429 io_cqring_event_overflow(ctx, req->cqe.user_data, res, cflags, extra1, extra2);
2432 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2433 s32 res, u32 cflags)
2436 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2437 return __io_fill_cqe(ctx, user_data, res, cflags);
2440 static void __io_req_complete_put(struct io_kiocb *req)
2443 * If we're the last reference to this request, add to our locked
2446 if (req_ref_put_and_test(req)) {
2447 struct io_ring_ctx *ctx = req->ctx;
2449 if (req->flags & IO_REQ_LINK_FLAGS) {
2450 if (req->flags & IO_DISARM_MASK)
2451 io_disarm_next(req);
2453 io_req_task_queue(req->link);
2457 io_req_put_rsrc(req);
2459 * Selected buffer deallocation in io_clean_op() assumes that
2460 * we don't hold ->completion_lock. Clean them here to avoid
2463 io_put_kbuf_comp(req);
2464 io_dismantle_req(req);
2465 io_put_task(req->task, 1);
2466 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2467 ctx->locked_free_nr++;
2471 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2474 if (!(req->flags & REQ_F_CQE_SKIP))
2475 __io_fill_cqe_req(req, res, cflags);
2476 __io_req_complete_put(req);
2479 static void __io_req_complete_post32(struct io_kiocb *req, s32 res,
2480 u32 cflags, u64 extra1, u64 extra2)
2482 if (!(req->flags & REQ_F_CQE_SKIP))
2483 __io_fill_cqe32_req(req, res, cflags, extra1, extra2);
2484 __io_req_complete_put(req);
2487 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2489 struct io_ring_ctx *ctx = req->ctx;
2491 spin_lock(&ctx->completion_lock);
2492 __io_req_complete_post(req, res, cflags);
2493 io_commit_cqring(ctx);
2494 spin_unlock(&ctx->completion_lock);
2495 io_cqring_ev_posted(ctx);
2498 static void io_req_complete_post32(struct io_kiocb *req, s32 res,
2499 u32 cflags, u64 extra1, u64 extra2)
2501 struct io_ring_ctx *ctx = req->ctx;
2503 spin_lock(&ctx->completion_lock);
2504 __io_req_complete_post32(req, res, cflags, extra1, extra2);
2505 io_commit_cqring(ctx);
2506 spin_unlock(&ctx->completion_lock);
2507 io_cqring_ev_posted(ctx);
2510 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2514 req->cqe.flags = cflags;
2515 req->flags |= REQ_F_COMPLETE_INLINE;
2518 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2519 s32 res, u32 cflags)
2521 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2522 io_req_complete_state(req, res, cflags);
2524 io_req_complete_post(req, res, cflags);
2527 static inline void __io_req_complete32(struct io_kiocb *req,
2528 unsigned int issue_flags, s32 res,
2529 u32 cflags, u64 extra1, u64 extra2)
2531 if (issue_flags & IO_URING_F_COMPLETE_DEFER) {
2532 io_req_complete_state(req, res, cflags);
2533 req->extra1 = extra1;
2534 req->extra2 = extra2;
2536 io_req_complete_post32(req, res, cflags, extra1, extra2);
2540 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2542 __io_req_complete(req, 0, res, 0);
2545 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2548 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2552 * Don't initialise the fields below on every allocation, but do that in
2553 * advance and keep them valid across allocations.
2555 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2559 req->async_data = NULL;
2560 /* not necessary, but safer to zero */
2564 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2565 struct io_submit_state *state)
2567 spin_lock(&ctx->completion_lock);
2568 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2569 ctx->locked_free_nr = 0;
2570 spin_unlock(&ctx->completion_lock);
2573 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2575 return !ctx->submit_state.free_list.next;
2579 * A request might get retired back into the request caches even before opcode
2580 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2581 * Because of that, io_alloc_req() should be called only under ->uring_lock
2582 * and with extra caution to not get a request that is still worked on.
2584 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2585 __must_hold(&ctx->uring_lock)
2587 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2588 void *reqs[IO_REQ_ALLOC_BATCH];
2592 * If we have more than a batch's worth of requests in our IRQ side
2593 * locked cache, grab the lock and move them over to our submission
2596 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2597 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2598 if (!io_req_cache_empty(ctx))
2602 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2605 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2606 * retry single alloc to be on the safe side.
2608 if (unlikely(ret <= 0)) {
2609 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2615 percpu_ref_get_many(&ctx->refs, ret);
2616 for (i = 0; i < ret; i++) {
2617 struct io_kiocb *req = reqs[i];
2619 io_preinit_req(req, ctx);
2620 io_req_add_to_cache(req, ctx);
2625 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2627 if (unlikely(io_req_cache_empty(ctx)))
2628 return __io_alloc_req_refill(ctx);
2632 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2634 struct io_wq_work_node *node;
2636 node = wq_stack_extract(&ctx->submit_state.free_list);
2637 return container_of(node, struct io_kiocb, comp_list);
2640 static inline void io_put_file(struct file *file)
2646 static inline void io_dismantle_req(struct io_kiocb *req)
2648 unsigned int flags = req->flags;
2650 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2652 if (!(flags & REQ_F_FIXED_FILE))
2653 io_put_file(req->file);
2656 static __cold void io_free_req(struct io_kiocb *req)
2658 struct io_ring_ctx *ctx = req->ctx;
2660 io_req_put_rsrc(req);
2661 io_dismantle_req(req);
2662 io_put_task(req->task, 1);
2664 spin_lock(&ctx->completion_lock);
2665 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2666 ctx->locked_free_nr++;
2667 spin_unlock(&ctx->completion_lock);
2670 static inline void io_remove_next_linked(struct io_kiocb *req)
2672 struct io_kiocb *nxt = req->link;
2674 req->link = nxt->link;
2678 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2679 __must_hold(&req->ctx->completion_lock)
2680 __must_hold(&req->ctx->timeout_lock)
2682 struct io_kiocb *link = req->link;
2684 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2685 struct io_timeout_data *io = link->async_data;
2687 io_remove_next_linked(req);
2688 link->timeout.head = NULL;
2689 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2690 list_del(&link->timeout.list);
2697 static void io_fail_links(struct io_kiocb *req)
2698 __must_hold(&req->ctx->completion_lock)
2700 struct io_kiocb *nxt, *link = req->link;
2701 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2705 long res = -ECANCELED;
2707 if (link->flags & REQ_F_FAIL)
2708 res = link->cqe.res;
2713 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2717 link->flags |= REQ_F_CQE_SKIP;
2719 link->flags &= ~REQ_F_CQE_SKIP;
2720 __io_req_complete_post(link, res, 0);
2725 static bool io_disarm_next(struct io_kiocb *req)
2726 __must_hold(&req->ctx->completion_lock)
2728 struct io_kiocb *link = NULL;
2729 bool posted = false;
2731 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2733 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2734 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2735 io_remove_next_linked(req);
2736 io_req_tw_post_queue(link, -ECANCELED, 0);
2739 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2740 struct io_ring_ctx *ctx = req->ctx;
2742 spin_lock_irq(&ctx->timeout_lock);
2743 link = io_disarm_linked_timeout(req);
2744 spin_unlock_irq(&ctx->timeout_lock);
2747 io_req_tw_post_queue(link, -ECANCELED, 0);
2750 if (unlikely((req->flags & REQ_F_FAIL) &&
2751 !(req->flags & REQ_F_HARDLINK))) {
2752 posted |= (req->link != NULL);
2758 static void __io_req_find_next_prep(struct io_kiocb *req)
2760 struct io_ring_ctx *ctx = req->ctx;
2763 spin_lock(&ctx->completion_lock);
2764 posted = io_disarm_next(req);
2765 io_commit_cqring(ctx);
2766 spin_unlock(&ctx->completion_lock);
2768 io_cqring_ev_posted(ctx);
2771 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2773 struct io_kiocb *nxt;
2776 * If LINK is set, we have dependent requests in this chain. If we
2777 * didn't fail this request, queue the first one up, moving any other
2778 * dependencies to the next request. In case of failure, fail the rest
2781 if (unlikely(req->flags & IO_DISARM_MASK))
2782 __io_req_find_next_prep(req);
2788 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2792 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2793 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2795 io_submit_flush_completions(ctx);
2796 mutex_unlock(&ctx->uring_lock);
2799 percpu_ref_put(&ctx->refs);
2802 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2804 io_commit_cqring(ctx);
2805 spin_unlock(&ctx->completion_lock);
2806 io_cqring_ev_posted(ctx);
2809 static void handle_prev_tw_list(struct io_wq_work_node *node,
2810 struct io_ring_ctx **ctx, bool *uring_locked)
2812 if (*ctx && !*uring_locked)
2813 spin_lock(&(*ctx)->completion_lock);
2816 struct io_wq_work_node *next = node->next;
2817 struct io_kiocb *req = container_of(node, struct io_kiocb,
2820 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2822 if (req->ctx != *ctx) {
2823 if (unlikely(!*uring_locked && *ctx))
2824 ctx_commit_and_unlock(*ctx);
2826 ctx_flush_and_put(*ctx, uring_locked);
2828 /* if not contended, grab and improve batching */
2829 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2830 percpu_ref_get(&(*ctx)->refs);
2831 if (unlikely(!*uring_locked))
2832 spin_lock(&(*ctx)->completion_lock);
2834 if (likely(*uring_locked))
2835 req->io_task_work.func(req, uring_locked);
2837 __io_req_complete_post(req, req->cqe.res,
2838 io_put_kbuf_comp(req));
2842 if (unlikely(!*uring_locked))
2843 ctx_commit_and_unlock(*ctx);
2846 static void handle_tw_list(struct io_wq_work_node *node,
2847 struct io_ring_ctx **ctx, bool *locked)
2850 struct io_wq_work_node *next = node->next;
2851 struct io_kiocb *req = container_of(node, struct io_kiocb,
2854 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2856 if (req->ctx != *ctx) {
2857 ctx_flush_and_put(*ctx, locked);
2859 /* if not contended, grab and improve batching */
2860 *locked = mutex_trylock(&(*ctx)->uring_lock);
2861 percpu_ref_get(&(*ctx)->refs);
2863 req->io_task_work.func(req, locked);
2868 static void tctx_task_work(struct callback_head *cb)
2870 bool uring_locked = false;
2871 struct io_ring_ctx *ctx = NULL;
2872 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2876 struct io_wq_work_node *node1, *node2;
2878 spin_lock_irq(&tctx->task_lock);
2879 node1 = tctx->prior_task_list.first;
2880 node2 = tctx->task_list.first;
2881 INIT_WQ_LIST(&tctx->task_list);
2882 INIT_WQ_LIST(&tctx->prior_task_list);
2883 if (!node2 && !node1)
2884 tctx->task_running = false;
2885 spin_unlock_irq(&tctx->task_lock);
2886 if (!node2 && !node1)
2890 handle_prev_tw_list(node1, &ctx, &uring_locked);
2892 handle_tw_list(node2, &ctx, &uring_locked);
2895 if (data_race(!tctx->task_list.first) &&
2896 data_race(!tctx->prior_task_list.first) && uring_locked)
2897 io_submit_flush_completions(ctx);
2900 ctx_flush_and_put(ctx, &uring_locked);
2902 /* relaxed read is enough as only the task itself sets ->in_idle */
2903 if (unlikely(atomic_read(&tctx->in_idle)))
2904 io_uring_drop_tctx_refs(current);
2907 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2909 struct task_struct *tsk = req->task;
2910 struct io_ring_ctx *ctx = req->ctx;
2911 struct io_uring_task *tctx = tsk->io_uring;
2912 struct io_wq_work_node *node;
2913 unsigned long flags;
2916 WARN_ON_ONCE(!tctx);
2918 io_drop_inflight_file(req);
2920 spin_lock_irqsave(&tctx->task_lock, flags);
2922 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2924 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2925 running = tctx->task_running;
2927 tctx->task_running = true;
2928 spin_unlock_irqrestore(&tctx->task_lock, flags);
2930 /* task_work already pending, we're done */
2934 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2935 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2937 if (likely(!task_work_add(tsk, &tctx->task_work, ctx->notify_method)))
2940 spin_lock_irqsave(&tctx->task_lock, flags);
2941 tctx->task_running = false;
2942 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2943 spin_unlock_irqrestore(&tctx->task_lock, flags);
2946 req = container_of(node, struct io_kiocb, io_task_work.node);
2948 if (llist_add(&req->io_task_work.fallback_node,
2949 &req->ctx->fallback_llist))
2950 schedule_delayed_work(&req->ctx->fallback_work, 1);
2954 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2956 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2959 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2962 req->cqe.flags = cflags;
2963 req->io_task_work.func = io_req_tw_post;
2964 io_req_task_work_add(req, false);
2967 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2969 /* not needed for normal modes, but SQPOLL depends on it */
2970 io_tw_lock(req->ctx, locked);
2971 io_req_complete_failed(req, req->cqe.res);
2974 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2976 io_tw_lock(req->ctx, locked);
2977 /* req->task == current here, checking PF_EXITING is safe */
2978 if (likely(!(req->task->flags & PF_EXITING)))
2981 io_req_complete_failed(req, -EFAULT);
2984 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2987 req->io_task_work.func = io_req_task_cancel;
2988 io_req_task_work_add(req, false);
2991 static void io_req_task_queue(struct io_kiocb *req)
2993 req->io_task_work.func = io_req_task_submit;
2994 io_req_task_work_add(req, false);
2997 static void io_req_task_queue_reissue(struct io_kiocb *req)
2999 req->io_task_work.func = io_queue_iowq;
3000 io_req_task_work_add(req, false);
3003 static void io_queue_next(struct io_kiocb *req)
3005 struct io_kiocb *nxt = io_req_find_next(req);
3008 io_req_task_queue(nxt);
3011 static void io_free_batch_list(struct io_ring_ctx *ctx,
3012 struct io_wq_work_node *node)
3013 __must_hold(&ctx->uring_lock)
3015 struct task_struct *task = NULL;
3019 struct io_kiocb *req = container_of(node, struct io_kiocb,
3022 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
3023 if (req->flags & REQ_F_REFCOUNT) {
3024 node = req->comp_list.next;
3025 if (!req_ref_put_and_test(req))
3028 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3029 struct async_poll *apoll = req->apoll;
3031 if (apoll->double_poll)
3032 kfree(apoll->double_poll);
3033 list_add(&apoll->poll.wait.entry,
3035 req->flags &= ~REQ_F_POLLED;
3037 if (req->flags & IO_REQ_LINK_FLAGS)
3039 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
3042 if (!(req->flags & REQ_F_FIXED_FILE))
3043 io_put_file(req->file);
3045 io_req_put_rsrc_locked(req, ctx);
3047 if (req->task != task) {
3049 io_put_task(task, task_refs);
3054 node = req->comp_list.next;
3055 io_req_add_to_cache(req, ctx);
3059 io_put_task(task, task_refs);
3062 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
3063 __must_hold(&ctx->uring_lock)
3065 struct io_wq_work_node *node, *prev;
3066 struct io_submit_state *state = &ctx->submit_state;
3068 if (state->flush_cqes) {
3069 spin_lock(&ctx->completion_lock);
3070 wq_list_for_each(node, prev, &state->compl_reqs) {
3071 struct io_kiocb *req = container_of(node, struct io_kiocb,
3074 if (!(req->flags & REQ_F_CQE_SKIP)) {
3075 if (!(ctx->flags & IORING_SETUP_CQE32))
3076 __io_fill_cqe_req_filled(ctx, req);
3078 __io_fill_cqe32_req_filled(ctx, req);
3082 io_commit_cqring(ctx);
3083 spin_unlock(&ctx->completion_lock);
3084 io_cqring_ev_posted(ctx);
3085 state->flush_cqes = false;
3088 io_free_batch_list(ctx, state->compl_reqs.first);
3089 INIT_WQ_LIST(&state->compl_reqs);
3093 * Drop reference to request, return next in chain (if there is one) if this
3094 * was the last reference to this request.
3096 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
3098 struct io_kiocb *nxt = NULL;
3100 if (req_ref_put_and_test(req)) {
3101 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
3102 nxt = io_req_find_next(req);
3108 static inline void io_put_req(struct io_kiocb *req)
3110 if (req_ref_put_and_test(req)) {
3116 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
3118 /* See comment at the top of this file */
3120 return __io_cqring_events(ctx);
3123 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
3125 struct io_rings *rings = ctx->rings;
3127 /* make sure SQ entry isn't read before tail */
3128 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3131 static inline bool io_run_task_work(void)
3133 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3134 __set_current_state(TASK_RUNNING);
3135 clear_notify_signal();
3136 if (task_work_pending(current))
3144 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3146 struct io_wq_work_node *pos, *start, *prev;
3147 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3148 DEFINE_IO_COMP_BATCH(iob);
3152 * Only spin for completions if we don't have multiple devices hanging
3153 * off our complete list.
3155 if (ctx->poll_multi_queue || force_nonspin)
3156 poll_flags |= BLK_POLL_ONESHOT;
3158 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3159 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3160 struct kiocb *kiocb = &req->rw.kiocb;
3164 * Move completed and retryable entries to our local lists.
3165 * If we find a request that requires polling, break out
3166 * and complete those lists first, if we have entries there.
3168 if (READ_ONCE(req->iopoll_completed))
3171 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3172 if (unlikely(ret < 0))
3175 poll_flags |= BLK_POLL_ONESHOT;
3177 /* iopoll may have completed current req */
3178 if (!rq_list_empty(iob.req_list) ||
3179 READ_ONCE(req->iopoll_completed))
3183 if (!rq_list_empty(iob.req_list))
3189 wq_list_for_each_resume(pos, prev) {
3190 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3192 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3193 if (!smp_load_acquire(&req->iopoll_completed))
3196 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3198 __io_fill_cqe_req(req, req->cqe.res, io_put_kbuf(req, 0));
3201 if (unlikely(!nr_events))
3204 io_commit_cqring(ctx);
3205 io_cqring_ev_posted_iopoll(ctx);
3206 pos = start ? start->next : ctx->iopoll_list.first;
3207 wq_list_cut(&ctx->iopoll_list, prev, start);
3208 io_free_batch_list(ctx, pos);
3213 * We can't just wait for polled events to come to us, we have to actively
3214 * find and complete them.
3216 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3218 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3221 mutex_lock(&ctx->uring_lock);
3222 while (!wq_list_empty(&ctx->iopoll_list)) {
3223 /* let it sleep and repeat later if can't complete a request */
3224 if (io_do_iopoll(ctx, true) == 0)
3227 * Ensure we allow local-to-the-cpu processing to take place,
3228 * in this case we need to ensure that we reap all events.
3229 * Also let task_work, etc. to progress by releasing the mutex
3231 if (need_resched()) {
3232 mutex_unlock(&ctx->uring_lock);
3234 mutex_lock(&ctx->uring_lock);
3237 mutex_unlock(&ctx->uring_lock);
3240 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3242 unsigned int nr_events = 0;
3244 unsigned long check_cq;
3247 * Don't enter poll loop if we already have events pending.
3248 * If we do, we can potentially be spinning for commands that
3249 * already triggered a CQE (eg in error).
3251 check_cq = READ_ONCE(ctx->check_cq);
3252 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3253 __io_cqring_overflow_flush(ctx, false);
3254 if (io_cqring_events(ctx))
3258 * Similarly do not spin if we have not informed the user of any
3261 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3266 * If a submit got punted to a workqueue, we can have the
3267 * application entering polling for a command before it gets
3268 * issued. That app will hold the uring_lock for the duration
3269 * of the poll right here, so we need to take a breather every
3270 * now and then to ensure that the issue has a chance to add
3271 * the poll to the issued list. Otherwise we can spin here
3272 * forever, while the workqueue is stuck trying to acquire the
3275 if (wq_list_empty(&ctx->iopoll_list)) {
3276 u32 tail = ctx->cached_cq_tail;
3278 mutex_unlock(&ctx->uring_lock);
3280 mutex_lock(&ctx->uring_lock);
3282 /* some requests don't go through iopoll_list */
3283 if (tail != ctx->cached_cq_tail ||
3284 wq_list_empty(&ctx->iopoll_list))
3287 ret = io_do_iopoll(ctx, !min);
3292 } while (nr_events < min && !need_resched());
3297 static void kiocb_end_write(struct io_kiocb *req)
3300 * Tell lockdep we inherited freeze protection from submission
3303 if (req->flags & REQ_F_ISREG) {
3304 struct super_block *sb = file_inode(req->file)->i_sb;
3306 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3312 static bool io_resubmit_prep(struct io_kiocb *req)
3314 struct io_async_rw *rw = req->async_data;
3316 if (!req_has_async_data(req))
3317 return !io_req_prep_async(req);
3318 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3322 static bool io_rw_should_reissue(struct io_kiocb *req)
3324 umode_t mode = file_inode(req->file)->i_mode;
3325 struct io_ring_ctx *ctx = req->ctx;
3327 if (!S_ISBLK(mode) && !S_ISREG(mode))
3329 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3330 !(ctx->flags & IORING_SETUP_IOPOLL)))
3333 * If ref is dying, we might be running poll reap from the exit work.
3334 * Don't attempt to reissue from that path, just let it fail with
3337 if (percpu_ref_is_dying(&ctx->refs))
3340 * Play it safe and assume not safe to re-import and reissue if we're
3341 * not in the original thread group (or in task context).
3343 if (!same_thread_group(req->task, current) || !in_task())
3348 static bool io_resubmit_prep(struct io_kiocb *req)
3352 static bool io_rw_should_reissue(struct io_kiocb *req)
3358 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3360 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3361 kiocb_end_write(req);
3362 fsnotify_modify(req->file);
3364 fsnotify_access(req->file);
3366 if (unlikely(res != req->cqe.res)) {
3367 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3368 io_rw_should_reissue(req)) {
3369 req->flags |= REQ_F_REISSUE;
3378 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3380 int res = req->cqe.res;
3383 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3384 io_req_add_compl_list(req);
3386 io_req_complete_post(req, res,
3387 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3391 static void __io_complete_rw(struct io_kiocb *req, long res,
3392 unsigned int issue_flags)
3394 if (__io_complete_rw_common(req, res))
3396 __io_req_complete(req, issue_flags, req->cqe.res,
3397 io_put_kbuf(req, issue_flags));
3400 static void io_complete_rw(struct kiocb *kiocb, long res)
3402 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3404 if (__io_complete_rw_common(req, res))
3407 req->io_task_work.func = io_req_task_complete;
3408 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3411 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3413 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3415 if (kiocb->ki_flags & IOCB_WRITE)
3416 kiocb_end_write(req);
3417 if (unlikely(res != req->cqe.res)) {
3418 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3419 req->flags |= REQ_F_REISSUE;
3425 /* order with io_iopoll_complete() checking ->iopoll_completed */
3426 smp_store_release(&req->iopoll_completed, 1);
3430 * After the iocb has been issued, it's safe to be found on the poll list.
3431 * Adding the kiocb to the list AFTER submission ensures that we don't
3432 * find it from a io_do_iopoll() thread before the issuer is done
3433 * accessing the kiocb cookie.
3435 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3437 struct io_ring_ctx *ctx = req->ctx;
3438 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3440 /* workqueue context doesn't hold uring_lock, grab it now */
3441 if (unlikely(needs_lock))
3442 mutex_lock(&ctx->uring_lock);
3445 * Track whether we have multiple files in our lists. This will impact
3446 * how we do polling eventually, not spinning if we're on potentially
3447 * different devices.
3449 if (wq_list_empty(&ctx->iopoll_list)) {
3450 ctx->poll_multi_queue = false;
3451 } else if (!ctx->poll_multi_queue) {
3452 struct io_kiocb *list_req;
3454 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3456 if (list_req->file != req->file)
3457 ctx->poll_multi_queue = true;
3461 * For fast devices, IO may have already completed. If it has, add
3462 * it to the front so we find it first.
3464 if (READ_ONCE(req->iopoll_completed))
3465 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3467 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3469 if (unlikely(needs_lock)) {
3471 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3472 * in sq thread task context or in io worker task context. If
3473 * current task context is sq thread, we don't need to check
3474 * whether should wake up sq thread.
3476 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3477 wq_has_sleeper(&ctx->sq_data->wait))
3478 wake_up(&ctx->sq_data->wait);
3480 mutex_unlock(&ctx->uring_lock);
3484 static bool io_bdev_nowait(struct block_device *bdev)
3486 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3490 * If we tracked the file through the SCM inflight mechanism, we could support
3491 * any file. For now, just ensure that anything potentially problematic is done
3494 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3496 if (S_ISBLK(mode)) {
3497 if (IS_ENABLED(CONFIG_BLOCK) &&
3498 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3504 if (S_ISREG(mode)) {
3505 if (IS_ENABLED(CONFIG_BLOCK) &&
3506 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3507 file->f_op != &io_uring_fops)
3512 /* any ->read/write should understand O_NONBLOCK */
3513 if (file->f_flags & O_NONBLOCK)
3515 return file->f_mode & FMODE_NOWAIT;
3519 * If we tracked the file through the SCM inflight mechanism, we could support
3520 * any file. For now, just ensure that anything potentially problematic is done
3523 static unsigned int io_file_get_flags(struct file *file)
3525 umode_t mode = file_inode(file)->i_mode;
3526 unsigned int res = 0;
3530 if (__io_file_supports_nowait(file, mode))
3532 if (io_file_need_scm(file))
3537 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3539 return req->flags & REQ_F_SUPPORT_NOWAIT;
3542 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3544 struct kiocb *kiocb = &req->rw.kiocb;
3548 kiocb->ki_pos = READ_ONCE(sqe->off);
3550 ioprio = READ_ONCE(sqe->ioprio);
3552 ret = ioprio_check_cap(ioprio);
3556 kiocb->ki_ioprio = ioprio;
3558 kiocb->ki_ioprio = get_current_ioprio();
3562 req->rw.addr = READ_ONCE(sqe->addr);
3563 req->rw.len = READ_ONCE(sqe->len);
3564 req->rw.flags = READ_ONCE(sqe->rw_flags);
3565 /* used for fixed read/write too - just read unconditionally */
3566 req->buf_index = READ_ONCE(sqe->buf_index);
3570 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3576 case -ERESTARTNOINTR:
3577 case -ERESTARTNOHAND:
3578 case -ERESTART_RESTARTBLOCK:
3580 * We can't just restart the syscall, since previously
3581 * submitted sqes may already be in progress. Just fail this
3587 kiocb->ki_complete(kiocb, ret);
3591 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3593 struct kiocb *kiocb = &req->rw.kiocb;
3595 if (kiocb->ki_pos != -1)
3596 return &kiocb->ki_pos;
3598 if (!(req->file->f_mode & FMODE_STREAM)) {
3599 req->flags |= REQ_F_CUR_POS;
3600 kiocb->ki_pos = req->file->f_pos;
3601 return &kiocb->ki_pos;
3608 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3609 unsigned int issue_flags)
3611 struct io_async_rw *io = req->async_data;
3613 /* add previously done IO, if any */
3614 if (req_has_async_data(req) && io->bytes_done > 0) {
3616 ret = io->bytes_done;
3618 ret += io->bytes_done;
3621 if (req->flags & REQ_F_CUR_POS)
3622 req->file->f_pos = req->rw.kiocb.ki_pos;
3623 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3624 __io_complete_rw(req, ret, issue_flags);
3626 io_rw_done(&req->rw.kiocb, ret);
3628 if (req->flags & REQ_F_REISSUE) {
3629 req->flags &= ~REQ_F_REISSUE;
3630 if (io_resubmit_prep(req))
3631 io_req_task_queue_reissue(req);
3633 io_req_task_queue_fail(req, ret);
3637 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3638 struct io_mapped_ubuf *imu)
3640 size_t len = req->rw.len;
3641 u64 buf_end, buf_addr = req->rw.addr;
3644 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3646 /* not inside the mapped region */
3647 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3651 * May not be a start of buffer, set size appropriately
3652 * and advance us to the beginning.
3654 offset = buf_addr - imu->ubuf;
3655 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3659 * Don't use iov_iter_advance() here, as it's really slow for
3660 * using the latter parts of a big fixed buffer - it iterates
3661 * over each segment manually. We can cheat a bit here, because
3664 * 1) it's a BVEC iter, we set it up
3665 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3666 * first and last bvec
3668 * So just find our index, and adjust the iterator afterwards.
3669 * If the offset is within the first bvec (or the whole first
3670 * bvec, just use iov_iter_advance(). This makes it easier
3671 * since we can just skip the first segment, which may not
3672 * be PAGE_SIZE aligned.
3674 const struct bio_vec *bvec = imu->bvec;
3676 if (offset <= bvec->bv_len) {
3677 iov_iter_advance(iter, offset);
3679 unsigned long seg_skip;
3681 /* skip first vec */
3682 offset -= bvec->bv_len;
3683 seg_skip = 1 + (offset >> PAGE_SHIFT);
3685 iter->bvec = bvec + seg_skip;
3686 iter->nr_segs -= seg_skip;
3687 iter->count -= bvec->bv_len + offset;
3688 iter->iov_offset = offset & ~PAGE_MASK;
3695 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3696 unsigned int issue_flags)
3698 struct io_mapped_ubuf *imu = req->imu;
3699 u16 index, buf_index = req->buf_index;
3702 struct io_ring_ctx *ctx = req->ctx;
3704 if (unlikely(buf_index >= ctx->nr_user_bufs))
3706 io_req_set_rsrc_node(req, ctx, issue_flags);
3707 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3708 imu = READ_ONCE(ctx->user_bufs[index]);
3711 return __io_import_fixed(req, rw, iter, imu);
3714 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3715 struct io_buffer_list *bl, unsigned int bgid)
3718 if (bgid < BGID_ARRAY)
3721 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3724 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3725 struct io_buffer_list *bl,
3726 unsigned int issue_flags)
3728 struct io_buffer *kbuf;
3730 if (list_empty(&bl->buf_list))
3731 return ERR_PTR(-ENOBUFS);
3733 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3734 list_del(&kbuf->list);
3735 if (*len > kbuf->len)
3737 req->flags |= REQ_F_BUFFER_SELECTED;
3739 req->buf_index = kbuf->bid;
3740 io_ring_submit_unlock(req->ctx, issue_flags);
3741 return u64_to_user_ptr(kbuf->addr);
3744 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3745 unsigned int issue_flags)
3747 struct io_ring_ctx *ctx = req->ctx;
3748 struct io_buffer_list *bl;
3750 io_ring_submit_lock(req->ctx, issue_flags);
3752 bl = io_buffer_get_list(ctx, req->buf_index);
3753 if (unlikely(!bl)) {
3754 io_ring_submit_unlock(req->ctx, issue_flags);
3755 return ERR_PTR(-ENOBUFS);
3758 /* selection helpers drop the submit lock again, if needed */
3759 return io_provided_buffer_select(req, len, bl, issue_flags);
3762 #ifdef CONFIG_COMPAT
3763 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3764 unsigned int issue_flags)
3766 struct compat_iovec __user *uiov;
3767 compat_ssize_t clen;
3771 uiov = u64_to_user_ptr(req->rw.addr);
3772 if (!access_ok(uiov, sizeof(*uiov)))
3774 if (__get_user(clen, &uiov->iov_len))
3780 buf = io_buffer_select(req, &len, issue_flags);
3782 return PTR_ERR(buf);
3783 req->rw.addr = (unsigned long) buf;
3784 iov[0].iov_base = buf;
3785 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3790 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3791 unsigned int issue_flags)
3793 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3797 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3800 len = iov[0].iov_len;
3803 buf = io_buffer_select(req, &len, issue_flags);
3805 return PTR_ERR(buf);
3806 req->rw.addr = (unsigned long) buf;
3807 iov[0].iov_base = buf;
3808 req->rw.len = iov[0].iov_len = len;
3812 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3813 unsigned int issue_flags)
3815 if (req->flags & REQ_F_BUFFER_SELECTED) {
3816 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3817 iov[0].iov_len = req->rw.len;
3820 if (req->rw.len != 1)
3823 #ifdef CONFIG_COMPAT
3824 if (req->ctx->compat)
3825 return io_compat_import(req, iov, issue_flags);
3828 return __io_iov_buffer_select(req, iov, issue_flags);
3831 static inline bool io_do_buffer_select(struct io_kiocb *req)
3833 if (!(req->flags & REQ_F_BUFFER_SELECT))
3835 return !(req->flags & REQ_F_BUFFER_SELECTED);
3838 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3839 struct io_rw_state *s,
3840 unsigned int issue_flags)
3842 struct iov_iter *iter = &s->iter;
3843 u8 opcode = req->opcode;
3844 struct iovec *iovec;
3849 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3850 ret = io_import_fixed(req, rw, iter, issue_flags);
3852 return ERR_PTR(ret);
3856 buf = u64_to_user_ptr(req->rw.addr);
3857 sqe_len = req->rw.len;
3859 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3860 if (io_do_buffer_select(req)) {
3861 buf = io_buffer_select(req, &sqe_len, issue_flags);
3863 return ERR_CAST(buf);
3864 req->rw.addr = (unsigned long) buf;
3865 req->rw.len = sqe_len;
3868 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3870 return ERR_PTR(ret);
3874 iovec = s->fast_iov;
3875 if (req->flags & REQ_F_BUFFER_SELECT) {
3876 ret = io_iov_buffer_select(req, iovec, issue_flags);
3878 return ERR_PTR(ret);
3879 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3883 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3885 if (unlikely(ret < 0))
3886 return ERR_PTR(ret);
3890 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3891 struct iovec **iovec, struct io_rw_state *s,
3892 unsigned int issue_flags)
3894 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3895 if (unlikely(IS_ERR(*iovec)))
3896 return PTR_ERR(*iovec);
3898 iov_iter_save_state(&s->iter, &s->iter_state);
3902 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3904 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3908 * For files that don't have ->read_iter() and ->write_iter(), handle them
3909 * by looping over ->read() or ->write() manually.
3911 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3913 struct kiocb *kiocb = &req->rw.kiocb;
3914 struct file *file = req->file;
3919 * Don't support polled IO through this interface, and we can't
3920 * support non-blocking either. For the latter, this just causes
3921 * the kiocb to be handled from an async context.
3923 if (kiocb->ki_flags & IOCB_HIPRI)
3925 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3926 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3929 ppos = io_kiocb_ppos(kiocb);
3931 while (iov_iter_count(iter)) {
3935 if (!iov_iter_is_bvec(iter)) {
3936 iovec = iov_iter_iovec(iter);
3938 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3939 iovec.iov_len = req->rw.len;
3943 nr = file->f_op->read(file, iovec.iov_base,
3944 iovec.iov_len, ppos);
3946 nr = file->f_op->write(file, iovec.iov_base,
3947 iovec.iov_len, ppos);
3956 if (!iov_iter_is_bvec(iter)) {
3957 iov_iter_advance(iter, nr);
3964 if (nr != iovec.iov_len)
3971 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3972 const struct iovec *fast_iov, struct iov_iter *iter)
3974 struct io_async_rw *rw = req->async_data;
3976 memcpy(&rw->s.iter, iter, sizeof(*iter));
3977 rw->free_iovec = iovec;
3979 /* can only be fixed buffers, no need to do anything */
3980 if (iov_iter_is_bvec(iter))
3983 unsigned iov_off = 0;
3985 rw->s.iter.iov = rw->s.fast_iov;
3986 if (iter->iov != fast_iov) {
3987 iov_off = iter->iov - fast_iov;
3988 rw->s.iter.iov += iov_off;
3990 if (rw->s.fast_iov != fast_iov)
3991 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3992 sizeof(struct iovec) * iter->nr_segs);
3994 req->flags |= REQ_F_NEED_CLEANUP;
3998 static inline bool io_alloc_async_data(struct io_kiocb *req)
4000 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
4001 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
4002 if (req->async_data) {
4003 req->flags |= REQ_F_ASYNC_DATA;
4009 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
4010 struct io_rw_state *s, bool force)
4012 if (!force && !io_op_defs[req->opcode].needs_async_setup)
4014 if (!req_has_async_data(req)) {
4015 struct io_async_rw *iorw;
4017 if (io_alloc_async_data(req)) {
4022 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
4023 iorw = req->async_data;
4024 /* we've copied and mapped the iter, ensure state is saved */
4025 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
4030 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
4032 struct io_async_rw *iorw = req->async_data;
4036 /* submission path, ->uring_lock should already be taken */
4037 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
4038 if (unlikely(ret < 0))
4041 iorw->bytes_done = 0;
4042 iorw->free_iovec = iov;
4044 req->flags |= REQ_F_NEED_CLEANUP;
4049 * This is our waitqueue callback handler, registered through __folio_lock_async()
4050 * when we initially tried to do the IO with the iocb armed our waitqueue.
4051 * This gets called when the page is unlocked, and we generally expect that to
4052 * happen when the page IO is completed and the page is now uptodate. This will
4053 * queue a task_work based retry of the operation, attempting to copy the data
4054 * again. If the latter fails because the page was NOT uptodate, then we will
4055 * do a thread based blocking retry of the operation. That's the unexpected
4058 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
4059 int sync, void *arg)
4061 struct wait_page_queue *wpq;
4062 struct io_kiocb *req = wait->private;
4063 struct wait_page_key *key = arg;
4065 wpq = container_of(wait, struct wait_page_queue, wait);
4067 if (!wake_page_match(wpq, key))
4070 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
4071 list_del_init(&wait->entry);
4072 io_req_task_queue(req);
4077 * This controls whether a given IO request should be armed for async page
4078 * based retry. If we return false here, the request is handed to the async
4079 * worker threads for retry. If we're doing buffered reads on a regular file,
4080 * we prepare a private wait_page_queue entry and retry the operation. This
4081 * will either succeed because the page is now uptodate and unlocked, or it
4082 * will register a callback when the page is unlocked at IO completion. Through
4083 * that callback, io_uring uses task_work to setup a retry of the operation.
4084 * That retry will attempt the buffered read again. The retry will generally
4085 * succeed, or in rare cases where it fails, we then fall back to using the
4086 * async worker threads for a blocking retry.
4088 static bool io_rw_should_retry(struct io_kiocb *req)
4090 struct io_async_rw *rw = req->async_data;
4091 struct wait_page_queue *wait = &rw->wpq;
4092 struct kiocb *kiocb = &req->rw.kiocb;
4094 /* never retry for NOWAIT, we just complete with -EAGAIN */
4095 if (req->flags & REQ_F_NOWAIT)
4098 /* Only for buffered IO */
4099 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4103 * just use poll if we can, and don't attempt if the fs doesn't
4104 * support callback based unlocks
4106 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4109 wait->wait.func = io_async_buf_func;
4110 wait->wait.private = req;
4111 wait->wait.flags = 0;
4112 INIT_LIST_HEAD(&wait->wait.entry);
4113 kiocb->ki_flags |= IOCB_WAITQ;
4114 kiocb->ki_flags &= ~IOCB_NOWAIT;
4115 kiocb->ki_waitq = wait;
4119 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4121 if (likely(req->file->f_op->read_iter))
4122 return call_read_iter(req->file, &req->rw.kiocb, iter);
4123 else if (req->file->f_op->read)
4124 return loop_rw_iter(READ, req, iter);
4129 static bool need_read_all(struct io_kiocb *req)
4131 return req->flags & REQ_F_ISREG ||
4132 S_ISBLK(file_inode(req->file)->i_mode);
4135 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4137 struct kiocb *kiocb = &req->rw.kiocb;
4138 struct io_ring_ctx *ctx = req->ctx;
4139 struct file *file = req->file;
4142 if (unlikely(!file || !(file->f_mode & mode)))
4145 if (!io_req_ffs_set(req))
4146 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4148 kiocb->ki_flags = iocb_flags(file);
4149 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4154 * If the file is marked O_NONBLOCK, still allow retry for it if it
4155 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4156 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4158 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4159 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4160 req->flags |= REQ_F_NOWAIT;
4162 if (ctx->flags & IORING_SETUP_IOPOLL) {
4163 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4166 kiocb->private = NULL;
4167 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4168 kiocb->ki_complete = io_complete_rw_iopoll;
4169 req->iopoll_completed = 0;
4171 if (kiocb->ki_flags & IOCB_HIPRI)
4173 kiocb->ki_complete = io_complete_rw;
4179 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4181 struct io_rw_state __s, *s = &__s;
4182 struct iovec *iovec;
4183 struct kiocb *kiocb = &req->rw.kiocb;
4184 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4185 struct io_async_rw *rw;
4189 if (!req_has_async_data(req)) {
4190 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4191 if (unlikely(ret < 0))
4195 * Safe and required to re-import if we're using provided
4196 * buffers, as we dropped the selected one before retry.
4198 if (req->flags & REQ_F_BUFFER_SELECT) {
4199 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4200 if (unlikely(ret < 0))
4204 rw = req->async_data;
4207 * We come here from an earlier attempt, restore our state to
4208 * match in case it doesn't. It's cheap enough that we don't
4209 * need to make this conditional.
4211 iov_iter_restore(&s->iter, &s->iter_state);
4214 ret = io_rw_init_file(req, FMODE_READ);
4215 if (unlikely(ret)) {
4219 req->cqe.res = iov_iter_count(&s->iter);
4221 if (force_nonblock) {
4222 /* If the file doesn't support async, just async punt */
4223 if (unlikely(!io_file_supports_nowait(req))) {
4224 ret = io_setup_async_rw(req, iovec, s, true);
4225 return ret ?: -EAGAIN;
4227 kiocb->ki_flags |= IOCB_NOWAIT;
4229 /* Ensure we clear previously set non-block flag */
4230 kiocb->ki_flags &= ~IOCB_NOWAIT;
4233 ppos = io_kiocb_update_pos(req);
4235 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4236 if (unlikely(ret)) {
4241 ret = io_iter_do_read(req, &s->iter);
4243 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4244 req->flags &= ~REQ_F_REISSUE;
4245 /* if we can poll, just do that */
4246 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4248 /* IOPOLL retry should happen for io-wq threads */
4249 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4251 /* no retry on NONBLOCK nor RWF_NOWAIT */
4252 if (req->flags & REQ_F_NOWAIT)
4255 } else if (ret == -EIOCBQUEUED) {
4257 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4258 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4259 /* read all, failed, already did sync or don't want to retry */
4264 * Don't depend on the iter state matching what was consumed, or being
4265 * untouched in case of error. Restore it and we'll advance it
4266 * manually if we need to.
4268 iov_iter_restore(&s->iter, &s->iter_state);
4270 ret2 = io_setup_async_rw(req, iovec, s, true);
4275 rw = req->async_data;
4278 * Now use our persistent iterator and state, if we aren't already.
4279 * We've restored and mapped the iter to match.
4284 * We end up here because of a partial read, either from
4285 * above or inside this loop. Advance the iter by the bytes
4286 * that were consumed.
4288 iov_iter_advance(&s->iter, ret);
4289 if (!iov_iter_count(&s->iter))
4291 rw->bytes_done += ret;
4292 iov_iter_save_state(&s->iter, &s->iter_state);
4294 /* if we can retry, do so with the callbacks armed */
4295 if (!io_rw_should_retry(req)) {
4296 kiocb->ki_flags &= ~IOCB_WAITQ;
4301 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4302 * we get -EIOCBQUEUED, then we'll get a notification when the
4303 * desired page gets unlocked. We can also get a partial read
4304 * here, and if we do, then just retry at the new offset.
4306 ret = io_iter_do_read(req, &s->iter);
4307 if (ret == -EIOCBQUEUED)
4309 /* we got some bytes, but not all. retry. */
4310 kiocb->ki_flags &= ~IOCB_WAITQ;
4311 iov_iter_restore(&s->iter, &s->iter_state);
4314 kiocb_done(req, ret, issue_flags);
4316 /* it's faster to check here then delegate to kfree */
4322 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4324 struct io_rw_state __s, *s = &__s;
4325 struct iovec *iovec;
4326 struct kiocb *kiocb = &req->rw.kiocb;
4327 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4331 if (!req_has_async_data(req)) {
4332 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4333 if (unlikely(ret < 0))
4336 struct io_async_rw *rw = req->async_data;
4339 iov_iter_restore(&s->iter, &s->iter_state);
4342 ret = io_rw_init_file(req, FMODE_WRITE);
4343 if (unlikely(ret)) {
4347 req->cqe.res = iov_iter_count(&s->iter);
4349 if (force_nonblock) {
4350 /* If the file doesn't support async, just async punt */
4351 if (unlikely(!io_file_supports_nowait(req)))
4354 /* file path doesn't support NOWAIT for non-direct_IO */
4355 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4356 (req->flags & REQ_F_ISREG))
4359 kiocb->ki_flags |= IOCB_NOWAIT;
4361 /* Ensure we clear previously set non-block flag */
4362 kiocb->ki_flags &= ~IOCB_NOWAIT;
4365 ppos = io_kiocb_update_pos(req);
4367 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4372 * Open-code file_start_write here to grab freeze protection,
4373 * which will be released by another thread in
4374 * io_complete_rw(). Fool lockdep by telling it the lock got
4375 * released so that it doesn't complain about the held lock when
4376 * we return to userspace.
4378 if (req->flags & REQ_F_ISREG) {
4379 sb_start_write(file_inode(req->file)->i_sb);
4380 __sb_writers_release(file_inode(req->file)->i_sb,
4383 kiocb->ki_flags |= IOCB_WRITE;
4385 if (likely(req->file->f_op->write_iter))
4386 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4387 else if (req->file->f_op->write)
4388 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4392 if (req->flags & REQ_F_REISSUE) {
4393 req->flags &= ~REQ_F_REISSUE;
4398 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4399 * retry them without IOCB_NOWAIT.
4401 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4403 /* no retry on NONBLOCK nor RWF_NOWAIT */
4404 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4406 if (!force_nonblock || ret2 != -EAGAIN) {
4407 /* IOPOLL retry should happen for io-wq threads */
4408 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4411 kiocb_done(req, ret2, issue_flags);
4414 iov_iter_restore(&s->iter, &s->iter_state);
4415 ret = io_setup_async_rw(req, iovec, s, false);
4416 return ret ?: -EAGAIN;
4419 /* it's reportedly faster than delegating the null check to kfree() */
4425 static int io_renameat_prep(struct io_kiocb *req,
4426 const struct io_uring_sqe *sqe)
4428 struct io_rename *ren = &req->rename;
4429 const char __user *oldf, *newf;
4431 if (sqe->buf_index || sqe->splice_fd_in)
4433 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4436 ren->old_dfd = READ_ONCE(sqe->fd);
4437 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4438 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4439 ren->new_dfd = READ_ONCE(sqe->len);
4440 ren->flags = READ_ONCE(sqe->rename_flags);
4442 ren->oldpath = getname(oldf);
4443 if (IS_ERR(ren->oldpath))
4444 return PTR_ERR(ren->oldpath);
4446 ren->newpath = getname(newf);
4447 if (IS_ERR(ren->newpath)) {
4448 putname(ren->oldpath);
4449 return PTR_ERR(ren->newpath);
4452 req->flags |= REQ_F_NEED_CLEANUP;
4456 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4458 struct io_rename *ren = &req->rename;
4461 if (issue_flags & IO_URING_F_NONBLOCK)
4464 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4465 ren->newpath, ren->flags);
4467 req->flags &= ~REQ_F_NEED_CLEANUP;
4470 io_req_complete(req, ret);
4474 static inline void __io_xattr_finish(struct io_kiocb *req)
4476 struct io_xattr *ix = &req->xattr;
4479 putname(ix->filename);
4481 kfree(ix->ctx.kname);
4482 kvfree(ix->ctx.kvalue);
4485 static void io_xattr_finish(struct io_kiocb *req, int ret)
4487 req->flags &= ~REQ_F_NEED_CLEANUP;
4489 __io_xattr_finish(req);
4493 io_req_complete(req, ret);
4496 static int __io_getxattr_prep(struct io_kiocb *req,
4497 const struct io_uring_sqe *sqe)
4499 struct io_xattr *ix = &req->xattr;
4500 const char __user *name;
4503 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4505 if (unlikely(sqe->ioprio))
4507 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4510 ix->filename = NULL;
4511 ix->ctx.kvalue = NULL;
4512 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4513 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4514 ix->ctx.size = READ_ONCE(sqe->len);
4515 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4520 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4524 ret = strncpy_from_user(ix->ctx.kname->name, name,
4525 sizeof(ix->ctx.kname->name));
4526 if (!ret || ret == sizeof(ix->ctx.kname->name))
4529 kfree(ix->ctx.kname);
4533 req->flags |= REQ_F_NEED_CLEANUP;
4537 static int io_fgetxattr_prep(struct io_kiocb *req,
4538 const struct io_uring_sqe *sqe)
4540 return __io_getxattr_prep(req, sqe);
4543 static int io_getxattr_prep(struct io_kiocb *req,
4544 const struct io_uring_sqe *sqe)
4546 struct io_xattr *ix = &req->xattr;
4547 const char __user *path;
4550 ret = __io_getxattr_prep(req, sqe);
4554 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4556 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4557 if (IS_ERR(ix->filename)) {
4558 ret = PTR_ERR(ix->filename);
4559 ix->filename = NULL;
4565 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4567 struct io_xattr *ix = &req->xattr;
4570 if (issue_flags & IO_URING_F_NONBLOCK)
4573 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4574 req->file->f_path.dentry,
4577 io_xattr_finish(req, ret);
4581 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4583 struct io_xattr *ix = &req->xattr;
4584 unsigned int lookup_flags = LOOKUP_FOLLOW;
4588 if (issue_flags & IO_URING_F_NONBLOCK)
4592 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4594 ret = do_getxattr(mnt_user_ns(path.mnt),
4599 if (retry_estale(ret, lookup_flags)) {
4600 lookup_flags |= LOOKUP_REVAL;
4605 io_xattr_finish(req, ret);
4609 static int __io_setxattr_prep(struct io_kiocb *req,
4610 const struct io_uring_sqe *sqe)
4612 struct io_xattr *ix = &req->xattr;
4613 const char __user *name;
4616 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4618 if (unlikely(sqe->ioprio))
4620 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4623 ix->filename = NULL;
4624 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4625 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4626 ix->ctx.kvalue = NULL;
4627 ix->ctx.size = READ_ONCE(sqe->len);
4628 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4630 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4634 ret = setxattr_copy(name, &ix->ctx);
4636 kfree(ix->ctx.kname);
4640 req->flags |= REQ_F_NEED_CLEANUP;
4644 static int io_setxattr_prep(struct io_kiocb *req,
4645 const struct io_uring_sqe *sqe)
4647 struct io_xattr *ix = &req->xattr;
4648 const char __user *path;
4651 ret = __io_setxattr_prep(req, sqe);
4655 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4657 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4658 if (IS_ERR(ix->filename)) {
4659 ret = PTR_ERR(ix->filename);
4660 ix->filename = NULL;
4666 static int io_fsetxattr_prep(struct io_kiocb *req,
4667 const struct io_uring_sqe *sqe)
4669 return __io_setxattr_prep(req, sqe);
4672 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4675 struct io_xattr *ix = &req->xattr;
4678 ret = mnt_want_write(path->mnt);
4680 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4681 mnt_drop_write(path->mnt);
4687 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4691 if (issue_flags & IO_URING_F_NONBLOCK)
4694 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4695 io_xattr_finish(req, ret);
4700 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4702 struct io_xattr *ix = &req->xattr;
4703 unsigned int lookup_flags = LOOKUP_FOLLOW;
4707 if (issue_flags & IO_URING_F_NONBLOCK)
4711 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4713 ret = __io_setxattr(req, issue_flags, &path);
4715 if (retry_estale(ret, lookup_flags)) {
4716 lookup_flags |= LOOKUP_REVAL;
4721 io_xattr_finish(req, ret);
4725 static int io_unlinkat_prep(struct io_kiocb *req,
4726 const struct io_uring_sqe *sqe)
4728 struct io_unlink *un = &req->unlink;
4729 const char __user *fname;
4731 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4733 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4736 un->dfd = READ_ONCE(sqe->fd);
4738 un->flags = READ_ONCE(sqe->unlink_flags);
4739 if (un->flags & ~AT_REMOVEDIR)
4742 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4743 un->filename = getname(fname);
4744 if (IS_ERR(un->filename))
4745 return PTR_ERR(un->filename);
4747 req->flags |= REQ_F_NEED_CLEANUP;
4751 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4753 struct io_unlink *un = &req->unlink;
4756 if (issue_flags & IO_URING_F_NONBLOCK)
4759 if (un->flags & AT_REMOVEDIR)
4760 ret = do_rmdir(un->dfd, un->filename);
4762 ret = do_unlinkat(un->dfd, un->filename);
4764 req->flags &= ~REQ_F_NEED_CLEANUP;
4767 io_req_complete(req, ret);
4771 static int io_mkdirat_prep(struct io_kiocb *req,
4772 const struct io_uring_sqe *sqe)
4774 struct io_mkdir *mkd = &req->mkdir;
4775 const char __user *fname;
4777 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4779 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4782 mkd->dfd = READ_ONCE(sqe->fd);
4783 mkd->mode = READ_ONCE(sqe->len);
4785 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4786 mkd->filename = getname(fname);
4787 if (IS_ERR(mkd->filename))
4788 return PTR_ERR(mkd->filename);
4790 req->flags |= REQ_F_NEED_CLEANUP;
4794 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4796 struct io_mkdir *mkd = &req->mkdir;
4799 if (issue_flags & IO_URING_F_NONBLOCK)
4802 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4804 req->flags &= ~REQ_F_NEED_CLEANUP;
4807 io_req_complete(req, ret);
4811 static int io_symlinkat_prep(struct io_kiocb *req,
4812 const struct io_uring_sqe *sqe)
4814 struct io_symlink *sl = &req->symlink;
4815 const char __user *oldpath, *newpath;
4817 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4819 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4822 sl->new_dfd = READ_ONCE(sqe->fd);
4823 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4824 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4826 sl->oldpath = getname(oldpath);
4827 if (IS_ERR(sl->oldpath))
4828 return PTR_ERR(sl->oldpath);
4830 sl->newpath = getname(newpath);
4831 if (IS_ERR(sl->newpath)) {
4832 putname(sl->oldpath);
4833 return PTR_ERR(sl->newpath);
4836 req->flags |= REQ_F_NEED_CLEANUP;
4840 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4842 struct io_symlink *sl = &req->symlink;
4845 if (issue_flags & IO_URING_F_NONBLOCK)
4848 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4850 req->flags &= ~REQ_F_NEED_CLEANUP;
4853 io_req_complete(req, ret);
4857 static int io_linkat_prep(struct io_kiocb *req,
4858 const struct io_uring_sqe *sqe)
4860 struct io_hardlink *lnk = &req->hardlink;
4861 const char __user *oldf, *newf;
4863 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4865 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4868 lnk->old_dfd = READ_ONCE(sqe->fd);
4869 lnk->new_dfd = READ_ONCE(sqe->len);
4870 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4871 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4872 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4874 lnk->oldpath = getname(oldf);
4875 if (IS_ERR(lnk->oldpath))
4876 return PTR_ERR(lnk->oldpath);
4878 lnk->newpath = getname(newf);
4879 if (IS_ERR(lnk->newpath)) {
4880 putname(lnk->oldpath);
4881 return PTR_ERR(lnk->newpath);
4884 req->flags |= REQ_F_NEED_CLEANUP;
4888 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4890 struct io_hardlink *lnk = &req->hardlink;
4893 if (issue_flags & IO_URING_F_NONBLOCK)
4896 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4897 lnk->newpath, lnk->flags);
4899 req->flags &= ~REQ_F_NEED_CLEANUP;
4902 io_req_complete(req, ret);
4906 static int io_shutdown_prep(struct io_kiocb *req,
4907 const struct io_uring_sqe *sqe)
4909 #if defined(CONFIG_NET)
4910 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
4911 sqe->buf_index || sqe->splice_fd_in))
4914 req->shutdown.how = READ_ONCE(sqe->len);
4921 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4923 #if defined(CONFIG_NET)
4924 struct socket *sock;
4927 if (issue_flags & IO_URING_F_NONBLOCK)
4930 sock = sock_from_file(req->file);
4931 if (unlikely(!sock))
4934 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4937 io_req_complete(req, ret);
4944 static int __io_splice_prep(struct io_kiocb *req,
4945 const struct io_uring_sqe *sqe)
4947 struct io_splice *sp = &req->splice;
4948 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4950 sp->len = READ_ONCE(sqe->len);
4951 sp->flags = READ_ONCE(sqe->splice_flags);
4952 if (unlikely(sp->flags & ~valid_flags))
4954 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4958 static int io_tee_prep(struct io_kiocb *req,
4959 const struct io_uring_sqe *sqe)
4961 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4963 return __io_splice_prep(req, sqe);
4966 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4968 struct io_splice *sp = &req->splice;
4969 struct file *out = sp->file_out;
4970 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4974 if (issue_flags & IO_URING_F_NONBLOCK)
4977 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4978 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4980 in = io_file_get_normal(req, sp->splice_fd_in);
4987 ret = do_tee(in, out, sp->len, flags);
4989 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4994 io_req_complete(req, ret);
4998 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5000 struct io_splice *sp = &req->splice;
5002 sp->off_in = READ_ONCE(sqe->splice_off_in);
5003 sp->off_out = READ_ONCE(sqe->off);
5004 return __io_splice_prep(req, sqe);
5007 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5009 struct io_splice *sp = &req->splice;
5010 struct file *out = sp->file_out;
5011 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5012 loff_t *poff_in, *poff_out;
5016 if (issue_flags & IO_URING_F_NONBLOCK)
5019 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5020 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5022 in = io_file_get_normal(req, sp->splice_fd_in);
5028 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5029 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5032 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5034 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5039 io_req_complete(req, ret);
5044 * IORING_OP_NOP just posts a completion event, nothing else.
5046 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5048 __io_req_complete(req, issue_flags, 0, 0);
5052 static int io_msg_ring_prep(struct io_kiocb *req,
5053 const struct io_uring_sqe *sqe)
5055 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5056 sqe->buf_index || sqe->personality))
5059 req->msg.user_data = READ_ONCE(sqe->off);
5060 req->msg.len = READ_ONCE(sqe->len);
5064 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5066 struct io_ring_ctx *target_ctx;
5067 struct io_msg *msg = &req->msg;
5072 if (req->file->f_op != &io_uring_fops)
5076 target_ctx = req->file->private_data;
5078 spin_lock(&target_ctx->completion_lock);
5079 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5080 io_commit_cqring(target_ctx);
5081 spin_unlock(&target_ctx->completion_lock);
5084 io_cqring_ev_posted(target_ctx);
5091 __io_req_complete(req, issue_flags, ret, 0);
5095 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5097 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5100 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5101 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5104 req->sync.off = READ_ONCE(sqe->off);
5105 req->sync.len = READ_ONCE(sqe->len);
5109 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5111 loff_t end = req->sync.off + req->sync.len;
5114 /* fsync always requires a blocking context */
5115 if (issue_flags & IO_URING_F_NONBLOCK)
5118 ret = vfs_fsync_range(req->file, req->sync.off,
5119 end > 0 ? end : LLONG_MAX,
5120 req->sync.flags & IORING_FSYNC_DATASYNC);
5123 io_req_complete(req, ret);
5127 static int io_fallocate_prep(struct io_kiocb *req,
5128 const struct io_uring_sqe *sqe)
5130 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5133 req->sync.off = READ_ONCE(sqe->off);
5134 req->sync.len = READ_ONCE(sqe->addr);
5135 req->sync.mode = READ_ONCE(sqe->len);
5139 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5143 /* fallocate always requiring blocking context */
5144 if (issue_flags & IO_URING_F_NONBLOCK)
5146 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5151 fsnotify_modify(req->file);
5152 io_req_complete(req, ret);
5156 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5158 const char __user *fname;
5161 if (unlikely(sqe->buf_index))
5163 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5166 /* open.how should be already initialised */
5167 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5168 req->open.how.flags |= O_LARGEFILE;
5170 req->open.dfd = READ_ONCE(sqe->fd);
5171 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5172 req->open.filename = getname(fname);
5173 if (IS_ERR(req->open.filename)) {
5174 ret = PTR_ERR(req->open.filename);
5175 req->open.filename = NULL;
5179 req->open.file_slot = READ_ONCE(sqe->file_index);
5180 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5183 req->open.nofile = rlimit(RLIMIT_NOFILE);
5184 req->flags |= REQ_F_NEED_CLEANUP;
5188 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5190 u64 mode = READ_ONCE(sqe->len);
5191 u64 flags = READ_ONCE(sqe->open_flags);
5193 req->open.how = build_open_how(flags, mode);
5194 return __io_openat_prep(req, sqe);
5197 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5199 struct open_how __user *how;
5203 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5204 len = READ_ONCE(sqe->len);
5205 if (len < OPEN_HOW_SIZE_VER0)
5208 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5213 return __io_openat_prep(req, sqe);
5216 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5218 struct open_flags op;
5220 bool resolve_nonblock, nonblock_set;
5221 bool fixed = !!req->open.file_slot;
5224 ret = build_open_flags(&req->open.how, &op);
5227 nonblock_set = op.open_flag & O_NONBLOCK;
5228 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5229 if (issue_flags & IO_URING_F_NONBLOCK) {
5231 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5232 * it'll always -EAGAIN
5234 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5236 op.lookup_flags |= LOOKUP_CACHED;
5237 op.open_flag |= O_NONBLOCK;
5241 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5246 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5249 * We could hang on to this 'fd' on retrying, but seems like
5250 * marginal gain for something that is now known to be a slower
5251 * path. So just put it, and we'll get a new one when we retry.
5256 ret = PTR_ERR(file);
5257 /* only retry if RESOLVE_CACHED wasn't already set by application */
5258 if (ret == -EAGAIN &&
5259 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5264 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5265 file->f_flags &= ~O_NONBLOCK;
5266 fsnotify_open(file);
5269 fd_install(ret, file);
5271 ret = io_install_fixed_file(req, file, issue_flags,
5272 req->open.file_slot - 1);
5274 putname(req->open.filename);
5275 req->flags &= ~REQ_F_NEED_CLEANUP;
5278 __io_req_complete(req, issue_flags, ret, 0);
5282 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5284 return io_openat2(req, issue_flags);
5287 static int io_remove_buffers_prep(struct io_kiocb *req,
5288 const struct io_uring_sqe *sqe)
5290 struct io_provide_buf *p = &req->pbuf;
5293 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5297 tmp = READ_ONCE(sqe->fd);
5298 if (!tmp || tmp > USHRT_MAX)
5301 memset(p, 0, sizeof(*p));
5303 p->bgid = READ_ONCE(sqe->buf_group);
5307 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5308 struct io_buffer_list *bl, unsigned nbufs)
5312 /* shouldn't happen */
5316 /* the head kbuf is the list itself */
5317 while (!list_empty(&bl->buf_list)) {
5318 struct io_buffer *nxt;
5320 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5321 list_del(&nxt->list);
5331 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5333 struct io_provide_buf *p = &req->pbuf;
5334 struct io_ring_ctx *ctx = req->ctx;
5335 struct io_buffer_list *bl;
5338 io_ring_submit_lock(ctx, issue_flags);
5341 bl = io_buffer_get_list(ctx, p->bgid);
5343 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5347 /* complete before unlock, IOPOLL may need the lock */
5348 __io_req_complete(req, issue_flags, ret, 0);
5349 io_ring_submit_unlock(ctx, issue_flags);
5353 static int io_provide_buffers_prep(struct io_kiocb *req,
5354 const struct io_uring_sqe *sqe)
5356 unsigned long size, tmp_check;
5357 struct io_provide_buf *p = &req->pbuf;
5360 if (sqe->rw_flags || sqe->splice_fd_in)
5363 tmp = READ_ONCE(sqe->fd);
5364 if (!tmp || tmp > USHRT_MAX)
5367 p->addr = READ_ONCE(sqe->addr);
5368 p->len = READ_ONCE(sqe->len);
5370 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5373 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5376 size = (unsigned long)p->len * p->nbufs;
5377 if (!access_ok(u64_to_user_ptr(p->addr), size))
5380 p->bgid = READ_ONCE(sqe->buf_group);
5381 tmp = READ_ONCE(sqe->off);
5382 if (tmp > USHRT_MAX)
5388 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5390 struct io_buffer *buf;
5395 * Completions that don't happen inline (eg not under uring_lock) will
5396 * add to ->io_buffers_comp. If we don't have any free buffers, check
5397 * the completion list and splice those entries first.
5399 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5400 spin_lock(&ctx->completion_lock);
5401 if (!list_empty(&ctx->io_buffers_comp)) {
5402 list_splice_init(&ctx->io_buffers_comp,
5403 &ctx->io_buffers_cache);
5404 spin_unlock(&ctx->completion_lock);
5407 spin_unlock(&ctx->completion_lock);
5411 * No free buffers and no completion entries either. Allocate a new
5412 * page worth of buffer entries and add those to our freelist.
5414 page = alloc_page(GFP_KERNEL_ACCOUNT);
5418 list_add(&page->lru, &ctx->io_buffers_pages);
5420 buf = page_address(page);
5421 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5422 while (bufs_in_page) {
5423 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5431 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5432 struct io_buffer_list *bl)
5434 struct io_buffer *buf;
5435 u64 addr = pbuf->addr;
5436 int i, bid = pbuf->bid;
5438 for (i = 0; i < pbuf->nbufs; i++) {
5439 if (list_empty(&ctx->io_buffers_cache) &&
5440 io_refill_buffer_cache(ctx))
5442 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5444 list_move_tail(&buf->list, &bl->buf_list);
5446 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5448 buf->bgid = pbuf->bgid;
5454 return i ? 0 : -ENOMEM;
5457 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5461 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5466 for (i = 0; i < BGID_ARRAY; i++) {
5467 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5468 ctx->io_bl[i].bgid = i;
5474 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5476 struct io_provide_buf *p = &req->pbuf;
5477 struct io_ring_ctx *ctx = req->ctx;
5478 struct io_buffer_list *bl;
5481 io_ring_submit_lock(ctx, issue_flags);
5483 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5484 ret = io_init_bl_list(ctx);
5489 bl = io_buffer_get_list(ctx, p->bgid);
5490 if (unlikely(!bl)) {
5491 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
5496 ret = io_buffer_add_list(ctx, bl, p->bgid);
5503 ret = io_add_buffers(ctx, p, bl);
5507 /* complete before unlock, IOPOLL may need the lock */
5508 __io_req_complete(req, issue_flags, ret, 0);
5509 io_ring_submit_unlock(ctx, issue_flags);
5513 static int io_epoll_ctl_prep(struct io_kiocb *req,
5514 const struct io_uring_sqe *sqe)
5516 #if defined(CONFIG_EPOLL)
5517 if (sqe->buf_index || sqe->splice_fd_in)
5520 req->epoll.epfd = READ_ONCE(sqe->fd);
5521 req->epoll.op = READ_ONCE(sqe->len);
5522 req->epoll.fd = READ_ONCE(sqe->off);
5524 if (ep_op_has_event(req->epoll.op)) {
5525 struct epoll_event __user *ev;
5527 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5528 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5538 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5540 #if defined(CONFIG_EPOLL)
5541 struct io_epoll *ie = &req->epoll;
5543 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5545 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5546 if (force_nonblock && ret == -EAGAIN)
5551 __io_req_complete(req, issue_flags, ret, 0);
5558 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5560 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5561 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5564 req->madvise.addr = READ_ONCE(sqe->addr);
5565 req->madvise.len = READ_ONCE(sqe->len);
5566 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5573 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5575 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5576 struct io_madvise *ma = &req->madvise;
5579 if (issue_flags & IO_URING_F_NONBLOCK)
5582 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5585 io_req_complete(req, ret);
5592 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5594 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5597 req->fadvise.offset = READ_ONCE(sqe->off);
5598 req->fadvise.len = READ_ONCE(sqe->len);
5599 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5603 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5605 struct io_fadvise *fa = &req->fadvise;
5608 if (issue_flags & IO_URING_F_NONBLOCK) {
5609 switch (fa->advice) {
5610 case POSIX_FADV_NORMAL:
5611 case POSIX_FADV_RANDOM:
5612 case POSIX_FADV_SEQUENTIAL:
5619 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5622 __io_req_complete(req, issue_flags, ret, 0);
5626 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5628 const char __user *path;
5630 if (sqe->buf_index || sqe->splice_fd_in)
5632 if (req->flags & REQ_F_FIXED_FILE)
5635 req->statx.dfd = READ_ONCE(sqe->fd);
5636 req->statx.mask = READ_ONCE(sqe->len);
5637 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5638 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5639 req->statx.flags = READ_ONCE(sqe->statx_flags);
5641 req->statx.filename = getname_flags(path,
5642 getname_statx_lookup_flags(req->statx.flags),
5645 if (IS_ERR(req->statx.filename)) {
5646 int ret = PTR_ERR(req->statx.filename);
5648 req->statx.filename = NULL;
5652 req->flags |= REQ_F_NEED_CLEANUP;
5656 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5658 struct io_statx *ctx = &req->statx;
5661 if (issue_flags & IO_URING_F_NONBLOCK)
5664 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5669 io_req_complete(req, ret);
5673 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5675 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5677 if (req->flags & REQ_F_FIXED_FILE)
5680 req->close.fd = READ_ONCE(sqe->fd);
5681 req->close.file_slot = READ_ONCE(sqe->file_index);
5682 if (req->close.file_slot && req->close.fd)
5688 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5690 struct files_struct *files = current->files;
5691 struct io_close *close = &req->close;
5692 struct fdtable *fdt;
5693 struct file *file = NULL;
5696 if (req->close.file_slot) {
5697 ret = io_close_fixed(req, issue_flags);
5701 spin_lock(&files->file_lock);
5702 fdt = files_fdtable(files);
5703 if (close->fd >= fdt->max_fds) {
5704 spin_unlock(&files->file_lock);
5707 file = fdt->fd[close->fd];
5708 if (!file || file->f_op == &io_uring_fops) {
5709 spin_unlock(&files->file_lock);
5714 /* if the file has a flush method, be safe and punt to async */
5715 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5716 spin_unlock(&files->file_lock);
5720 ret = __close_fd_get_file(close->fd, &file);
5721 spin_unlock(&files->file_lock);
5728 /* No ->flush() or already async, safely close from here */
5729 ret = filp_close(file, current->files);
5735 __io_req_complete(req, issue_flags, ret, 0);
5739 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5741 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5744 req->sync.off = READ_ONCE(sqe->off);
5745 req->sync.len = READ_ONCE(sqe->len);
5746 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5750 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5754 /* sync_file_range always requires a blocking context */
5755 if (issue_flags & IO_URING_F_NONBLOCK)
5758 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5762 io_req_complete(req, ret);
5766 #if defined(CONFIG_NET)
5767 static bool io_net_retry(struct socket *sock, int flags)
5769 if (!(flags & MSG_WAITALL))
5771 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5774 static int io_setup_async_msg(struct io_kiocb *req,
5775 struct io_async_msghdr *kmsg)
5777 struct io_async_msghdr *async_msg = req->async_data;
5781 if (io_alloc_async_data(req)) {
5782 kfree(kmsg->free_iov);
5785 async_msg = req->async_data;
5786 req->flags |= REQ_F_NEED_CLEANUP;
5787 memcpy(async_msg, kmsg, sizeof(*kmsg));
5788 async_msg->msg.msg_name = &async_msg->addr;
5789 /* if were using fast_iov, set it to the new one */
5790 if (!async_msg->free_iov)
5791 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5796 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5797 struct io_async_msghdr *iomsg)
5799 iomsg->msg.msg_name = &iomsg->addr;
5800 iomsg->free_iov = iomsg->fast_iov;
5801 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5802 req->sr_msg.msg_flags, &iomsg->free_iov);
5805 static int io_sendmsg_prep_async(struct io_kiocb *req)
5809 ret = io_sendmsg_copy_hdr(req, req->async_data);
5811 req->flags |= REQ_F_NEED_CLEANUP;
5815 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5817 struct io_sr_msg *sr = &req->sr_msg;
5819 if (unlikely(sqe->file_index))
5821 if (unlikely(sqe->addr2 || sqe->file_index))
5824 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5825 sr->len = READ_ONCE(sqe->len);
5826 sr->flags = READ_ONCE(sqe->addr2);
5827 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5829 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5830 if (sr->msg_flags & MSG_DONTWAIT)
5831 req->flags |= REQ_F_NOWAIT;
5833 #ifdef CONFIG_COMPAT
5834 if (req->ctx->compat)
5835 sr->msg_flags |= MSG_CMSG_COMPAT;
5841 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5843 struct io_async_msghdr iomsg, *kmsg;
5844 struct io_sr_msg *sr = &req->sr_msg;
5845 struct socket *sock;
5850 sock = sock_from_file(req->file);
5851 if (unlikely(!sock))
5854 if (req_has_async_data(req)) {
5855 kmsg = req->async_data;
5857 ret = io_sendmsg_copy_hdr(req, &iomsg);
5863 if (!(req->flags & REQ_F_POLLED) &&
5864 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5865 return io_setup_async_msg(req, kmsg);
5867 flags = sr->msg_flags;
5868 if (issue_flags & IO_URING_F_NONBLOCK)
5869 flags |= MSG_DONTWAIT;
5870 if (flags & MSG_WAITALL)
5871 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5873 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5875 if (ret < min_ret) {
5876 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5877 return io_setup_async_msg(req, kmsg);
5878 if (ret == -ERESTARTSYS)
5880 if (ret > 0 && io_net_retry(sock, flags)) {
5882 req->flags |= REQ_F_PARTIAL_IO;
5883 return io_setup_async_msg(req, kmsg);
5887 /* fast path, check for non-NULL to avoid function call */
5889 kfree(kmsg->free_iov);
5890 req->flags &= ~REQ_F_NEED_CLEANUP;
5893 else if (sr->done_io)
5895 __io_req_complete(req, issue_flags, ret, 0);
5899 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5901 struct io_sr_msg *sr = &req->sr_msg;
5904 struct socket *sock;
5909 if (!(req->flags & REQ_F_POLLED) &&
5910 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5913 sock = sock_from_file(req->file);
5914 if (unlikely(!sock))
5917 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5921 msg.msg_name = NULL;
5922 msg.msg_control = NULL;
5923 msg.msg_controllen = 0;
5924 msg.msg_namelen = 0;
5926 flags = sr->msg_flags;
5927 if (issue_flags & IO_URING_F_NONBLOCK)
5928 flags |= MSG_DONTWAIT;
5929 if (flags & MSG_WAITALL)
5930 min_ret = iov_iter_count(&msg.msg_iter);
5932 msg.msg_flags = flags;
5933 ret = sock_sendmsg(sock, &msg);
5934 if (ret < min_ret) {
5935 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5937 if (ret == -ERESTARTSYS)
5939 if (ret > 0 && io_net_retry(sock, flags)) {
5943 req->flags |= REQ_F_PARTIAL_IO;
5950 else if (sr->done_io)
5952 __io_req_complete(req, issue_flags, ret, 0);
5956 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5957 struct io_async_msghdr *iomsg)
5959 struct io_sr_msg *sr = &req->sr_msg;
5960 struct iovec __user *uiov;
5964 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5965 &iomsg->uaddr, &uiov, &iov_len);
5969 if (req->flags & REQ_F_BUFFER_SELECT) {
5972 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5974 sr->len = iomsg->fast_iov[0].iov_len;
5975 iomsg->free_iov = NULL;
5977 iomsg->free_iov = iomsg->fast_iov;
5978 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5979 &iomsg->free_iov, &iomsg->msg.msg_iter,
5988 #ifdef CONFIG_COMPAT
5989 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5990 struct io_async_msghdr *iomsg)
5992 struct io_sr_msg *sr = &req->sr_msg;
5993 struct compat_iovec __user *uiov;
5998 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6003 uiov = compat_ptr(ptr);
6004 if (req->flags & REQ_F_BUFFER_SELECT) {
6005 compat_ssize_t clen;
6009 if (!access_ok(uiov, sizeof(*uiov)))
6011 if (__get_user(clen, &uiov->iov_len))
6016 iomsg->free_iov = NULL;
6018 iomsg->free_iov = iomsg->fast_iov;
6019 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6020 UIO_FASTIOV, &iomsg->free_iov,
6021 &iomsg->msg.msg_iter, true);
6030 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6031 struct io_async_msghdr *iomsg)
6033 iomsg->msg.msg_name = &iomsg->addr;
6035 #ifdef CONFIG_COMPAT
6036 if (req->ctx->compat)
6037 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6040 return __io_recvmsg_copy_hdr(req, iomsg);
6043 static int io_recvmsg_prep_async(struct io_kiocb *req)
6047 ret = io_recvmsg_copy_hdr(req, req->async_data);
6049 req->flags |= REQ_F_NEED_CLEANUP;
6053 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6055 struct io_sr_msg *sr = &req->sr_msg;
6057 if (unlikely(sqe->file_index))
6059 if (unlikely(sqe->addr2 || sqe->file_index))
6062 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6063 sr->len = READ_ONCE(sqe->len);
6064 sr->flags = READ_ONCE(sqe->addr2);
6065 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6067 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6068 if (sr->msg_flags & MSG_DONTWAIT)
6069 req->flags |= REQ_F_NOWAIT;
6071 #ifdef CONFIG_COMPAT
6072 if (req->ctx->compat)
6073 sr->msg_flags |= MSG_CMSG_COMPAT;
6079 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6081 struct io_async_msghdr iomsg, *kmsg;
6082 struct io_sr_msg *sr = &req->sr_msg;
6083 struct socket *sock;
6085 int ret, min_ret = 0;
6086 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6088 sock = sock_from_file(req->file);
6089 if (unlikely(!sock))
6092 if (req_has_async_data(req)) {
6093 kmsg = req->async_data;
6095 ret = io_recvmsg_copy_hdr(req, &iomsg);
6101 if (!(req->flags & REQ_F_POLLED) &&
6102 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6103 return io_setup_async_msg(req, kmsg);
6105 if (io_do_buffer_select(req)) {
6108 buf = io_buffer_select(req, &sr->len, issue_flags);
6110 return PTR_ERR(buf);
6111 kmsg->fast_iov[0].iov_base = buf;
6112 kmsg->fast_iov[0].iov_len = sr->len;
6113 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6117 flags = sr->msg_flags;
6119 flags |= MSG_DONTWAIT;
6120 if (flags & MSG_WAITALL)
6121 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6123 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6124 if (ret < min_ret) {
6125 if (ret == -EAGAIN && force_nonblock)
6126 return io_setup_async_msg(req, kmsg);
6127 if (ret == -ERESTARTSYS)
6129 if (ret > 0 && io_net_retry(sock, flags)) {
6131 req->flags |= REQ_F_PARTIAL_IO;
6132 return io_setup_async_msg(req, kmsg);
6135 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6139 /* fast path, check for non-NULL to avoid function call */
6141 kfree(kmsg->free_iov);
6142 req->flags &= ~REQ_F_NEED_CLEANUP;
6145 else if (sr->done_io)
6147 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
6151 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6153 struct io_sr_msg *sr = &req->sr_msg;
6155 struct socket *sock;
6158 int ret, min_ret = 0;
6159 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6161 if (!(req->flags & REQ_F_POLLED) &&
6162 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6165 sock = sock_from_file(req->file);
6166 if (unlikely(!sock))
6169 if (io_do_buffer_select(req)) {
6172 buf = io_buffer_select(req, &sr->len, issue_flags);
6174 return PTR_ERR(buf);
6178 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6182 msg.msg_name = NULL;
6183 msg.msg_control = NULL;
6184 msg.msg_controllen = 0;
6185 msg.msg_namelen = 0;
6186 msg.msg_iocb = NULL;
6189 flags = sr->msg_flags;
6191 flags |= MSG_DONTWAIT;
6192 if (flags & MSG_WAITALL)
6193 min_ret = iov_iter_count(&msg.msg_iter);
6195 ret = sock_recvmsg(sock, &msg, flags);
6196 if (ret < min_ret) {
6197 if (ret == -EAGAIN && force_nonblock)
6199 if (ret == -ERESTARTSYS)
6201 if (ret > 0 && io_net_retry(sock, flags)) {
6205 req->flags |= REQ_F_PARTIAL_IO;
6209 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6216 else if (sr->done_io)
6218 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
6222 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6224 struct io_accept *accept = &req->accept;
6226 if (sqe->len || sqe->buf_index)
6229 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6230 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6231 accept->flags = READ_ONCE(sqe->accept_flags);
6232 accept->nofile = rlimit(RLIMIT_NOFILE);
6234 accept->file_slot = READ_ONCE(sqe->file_index);
6235 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
6237 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6239 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6240 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6244 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6246 struct io_accept *accept = &req->accept;
6247 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6248 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6249 bool fixed = !!accept->file_slot;
6254 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6255 if (unlikely(fd < 0))
6258 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6263 ret = PTR_ERR(file);
6264 if (ret == -EAGAIN && force_nonblock)
6266 if (ret == -ERESTARTSYS)
6269 } else if (!fixed) {
6270 fd_install(fd, file);
6273 ret = io_install_fixed_file(req, file, issue_flags,
6274 accept->file_slot - 1);
6276 __io_req_complete(req, issue_flags, ret, 0);
6280 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6282 struct io_socket *sock = &req->sock;
6284 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6286 if (sqe->ioprio || sqe->addr || sqe->rw_flags || sqe->buf_index)
6289 sock->domain = READ_ONCE(sqe->fd);
6290 sock->type = READ_ONCE(sqe->off);
6291 sock->protocol = READ_ONCE(sqe->len);
6292 sock->file_slot = READ_ONCE(sqe->file_index);
6293 sock->nofile = rlimit(RLIMIT_NOFILE);
6295 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6296 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6298 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6303 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6305 struct io_socket *sock = &req->sock;
6306 bool fixed = !!sock->file_slot;
6311 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6312 if (unlikely(fd < 0))
6315 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6319 ret = PTR_ERR(file);
6320 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6322 if (ret == -ERESTARTSYS)
6325 } else if (!fixed) {
6326 fd_install(fd, file);
6329 ret = io_install_fixed_file(req, file, issue_flags,
6330 sock->file_slot - 1);
6332 __io_req_complete(req, issue_flags, ret, 0);
6336 static int io_connect_prep_async(struct io_kiocb *req)
6338 struct io_async_connect *io = req->async_data;
6339 struct io_connect *conn = &req->connect;
6341 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6344 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6346 struct io_connect *conn = &req->connect;
6348 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6351 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6352 conn->addr_len = READ_ONCE(sqe->addr2);
6356 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6358 struct io_async_connect __io, *io;
6359 unsigned file_flags;
6361 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6363 if (req_has_async_data(req)) {
6364 io = req->async_data;
6366 ret = move_addr_to_kernel(req->connect.addr,
6367 req->connect.addr_len,
6374 file_flags = force_nonblock ? O_NONBLOCK : 0;
6376 ret = __sys_connect_file(req->file, &io->address,
6377 req->connect.addr_len, file_flags);
6378 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6379 if (req_has_async_data(req))
6381 if (io_alloc_async_data(req)) {
6385 memcpy(req->async_data, &__io, sizeof(__io));
6388 if (ret == -ERESTARTSYS)
6393 __io_req_complete(req, issue_flags, ret, 0);
6396 #else /* !CONFIG_NET */
6397 #define IO_NETOP_FN(op) \
6398 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6400 return -EOPNOTSUPP; \
6403 #define IO_NETOP_PREP(op) \
6405 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6407 return -EOPNOTSUPP; \
6410 #define IO_NETOP_PREP_ASYNC(op) \
6412 static int io_##op##_prep_async(struct io_kiocb *req) \
6414 return -EOPNOTSUPP; \
6417 IO_NETOP_PREP_ASYNC(sendmsg);
6418 IO_NETOP_PREP_ASYNC(recvmsg);
6419 IO_NETOP_PREP_ASYNC(connect);
6420 IO_NETOP_PREP(accept);
6421 IO_NETOP_PREP(socket);
6424 #endif /* CONFIG_NET */
6426 struct io_poll_table {
6427 struct poll_table_struct pt;
6428 struct io_kiocb *req;
6433 #define IO_POLL_CANCEL_FLAG BIT(31)
6434 #define IO_POLL_REF_MASK GENMASK(30, 0)
6437 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6438 * bump it and acquire ownership. It's disallowed to modify requests while not
6439 * owning it, that prevents from races for enqueueing task_work's and b/w
6440 * arming poll and wakeups.
6442 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6444 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6447 static void io_poll_mark_cancelled(struct io_kiocb *req)
6449 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6452 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6454 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6455 if (req->opcode == IORING_OP_POLL_ADD)
6456 return req->async_data;
6457 return req->apoll->double_poll;
6460 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6462 if (req->opcode == IORING_OP_POLL_ADD)
6464 return &req->apoll->poll;
6467 static void io_poll_req_insert(struct io_kiocb *req)
6469 struct io_ring_ctx *ctx = req->ctx;
6470 struct hlist_head *list;
6472 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6473 hlist_add_head(&req->hash_node, list);
6476 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6477 wait_queue_func_t wake_func)
6480 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6481 /* mask in events that we always want/need */
6482 poll->events = events | IO_POLL_UNMASK;
6483 INIT_LIST_HEAD(&poll->wait.entry);
6484 init_waitqueue_func_entry(&poll->wait, wake_func);
6487 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6489 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6492 spin_lock_irq(&head->lock);
6493 list_del_init(&poll->wait.entry);
6495 spin_unlock_irq(&head->lock);
6499 static void io_poll_remove_entries(struct io_kiocb *req)
6502 * Nothing to do if neither of those flags are set. Avoid dipping
6503 * into the poll/apoll/double cachelines if we can.
6505 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6509 * While we hold the waitqueue lock and the waitqueue is nonempty,
6510 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6511 * lock in the first place can race with the waitqueue being freed.
6513 * We solve this as eventpoll does: by taking advantage of the fact that
6514 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6515 * we enter rcu_read_lock() and see that the pointer to the queue is
6516 * non-NULL, we can then lock it without the memory being freed out from
6519 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6520 * case the caller deletes the entry from the queue, leaving it empty.
6521 * In that case, only RCU prevents the queue memory from being freed.
6524 if (req->flags & REQ_F_SINGLE_POLL)
6525 io_poll_remove_entry(io_poll_get_single(req));
6526 if (req->flags & REQ_F_DOUBLE_POLL)
6527 io_poll_remove_entry(io_poll_get_double(req));
6532 * All poll tw should go through this. Checks for poll events, manages
6533 * references, does rewait, etc.
6535 * Returns a negative error on failure. >0 when no action require, which is
6536 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6537 * the request, then the mask is stored in req->cqe.res.
6539 static int io_poll_check_events(struct io_kiocb *req, bool locked)
6541 struct io_ring_ctx *ctx = req->ctx;
6544 /* req->task == current here, checking PF_EXITING is safe */
6545 if (unlikely(req->task->flags & PF_EXITING))
6549 v = atomic_read(&req->poll_refs);
6551 /* tw handler should be the owner, and so have some references */
6552 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6554 if (v & IO_POLL_CANCEL_FLAG)
6557 if (!req->cqe.res) {
6558 struct poll_table_struct pt = { ._key = req->apoll_events };
6559 unsigned flags = locked ? 0 : IO_URING_F_UNLOCKED;
6561 if (unlikely(!io_assign_file(req, flags)))
6563 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6566 /* multishot, just fill an CQE and proceed */
6567 if (req->cqe.res && !(req->apoll_events & EPOLLONESHOT)) {
6568 __poll_t mask = mangle_poll(req->cqe.res & req->apoll_events);
6571 spin_lock(&ctx->completion_lock);
6572 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, mask,
6574 io_commit_cqring(ctx);
6575 spin_unlock(&ctx->completion_lock);
6576 if (unlikely(!filled))
6578 io_cqring_ev_posted(ctx);
6579 } else if (req->cqe.res) {
6584 * Release all references, retry if someone tried to restart
6585 * task_work while we were executing it.
6587 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6592 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6594 struct io_ring_ctx *ctx = req->ctx;
6597 ret = io_poll_check_events(req, *locked);
6602 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6608 io_poll_remove_entries(req);
6609 spin_lock(&ctx->completion_lock);
6610 hash_del(&req->hash_node);
6611 __io_req_complete_post(req, req->cqe.res, 0);
6612 io_commit_cqring(ctx);
6613 spin_unlock(&ctx->completion_lock);
6614 io_cqring_ev_posted(ctx);
6617 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6619 struct io_ring_ctx *ctx = req->ctx;
6622 ret = io_poll_check_events(req, *locked);
6626 io_poll_remove_entries(req);
6627 spin_lock(&ctx->completion_lock);
6628 hash_del(&req->hash_node);
6629 spin_unlock(&ctx->completion_lock);
6632 io_req_task_submit(req, locked);
6634 io_req_complete_failed(req, ret);
6637 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
6639 req->cqe.res = mask;
6641 * This is useful for poll that is armed on behalf of another
6642 * request, and where the wakeup path could be on a different
6643 * CPU. We want to avoid pulling in req->apoll->events for that
6646 req->apoll_events = events;
6647 if (req->opcode == IORING_OP_POLL_ADD)
6648 req->io_task_work.func = io_poll_task_func;
6650 req->io_task_work.func = io_apoll_task_func;
6652 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6653 io_req_task_work_add(req, false);
6656 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
6658 if (io_poll_get_ownership(req))
6659 __io_poll_execute(req, res, events);
6662 static void io_poll_cancel_req(struct io_kiocb *req)
6664 io_poll_mark_cancelled(req);
6665 /* kick tw, which should complete the request */
6666 io_poll_execute(req, 0, 0);
6669 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6670 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6672 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6675 struct io_kiocb *req = wqe_to_req(wait);
6676 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6678 __poll_t mask = key_to_poll(key);
6680 if (unlikely(mask & POLLFREE)) {
6681 io_poll_mark_cancelled(req);
6682 /* we have to kick tw in case it's not already */
6683 io_poll_execute(req, 0, poll->events);
6686 * If the waitqueue is being freed early but someone is already
6687 * holds ownership over it, we have to tear down the request as
6688 * best we can. That means immediately removing the request from
6689 * its waitqueue and preventing all further accesses to the
6690 * waitqueue via the request.
6692 list_del_init(&poll->wait.entry);
6695 * Careful: this *must* be the last step, since as soon
6696 * as req->head is NULL'ed out, the request can be
6697 * completed and freed, since aio_poll_complete_work()
6698 * will no longer need to take the waitqueue lock.
6700 smp_store_release(&poll->head, NULL);
6704 /* for instances that support it check for an event match first */
6705 if (mask && !(mask & poll->events))
6708 if (io_poll_get_ownership(req)) {
6709 /* optional, saves extra locking for removal in tw handler */
6710 if (mask && poll->events & EPOLLONESHOT) {
6711 list_del_init(&poll->wait.entry);
6713 if (wqe_is_double(wait))
6714 req->flags &= ~REQ_F_DOUBLE_POLL;
6716 req->flags &= ~REQ_F_SINGLE_POLL;
6718 __io_poll_execute(req, mask, poll->events);
6723 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6724 struct wait_queue_head *head,
6725 struct io_poll_iocb **poll_ptr)
6727 struct io_kiocb *req = pt->req;
6728 unsigned long wqe_private = (unsigned long) req;
6731 * The file being polled uses multiple waitqueues for poll handling
6732 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6735 if (unlikely(pt->nr_entries)) {
6736 struct io_poll_iocb *first = poll;
6738 /* double add on the same waitqueue head, ignore */
6739 if (first->head == head)
6741 /* already have a 2nd entry, fail a third attempt */
6743 if ((*poll_ptr)->head == head)
6745 pt->error = -EINVAL;
6749 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6751 pt->error = -ENOMEM;
6754 /* mark as double wq entry */
6756 req->flags |= REQ_F_DOUBLE_POLL;
6757 io_init_poll_iocb(poll, first->events, first->wait.func);
6759 if (req->opcode == IORING_OP_POLL_ADD)
6760 req->flags |= REQ_F_ASYNC_DATA;
6763 req->flags |= REQ_F_SINGLE_POLL;
6766 poll->wait.private = (void *) wqe_private;
6768 if (poll->events & EPOLLEXCLUSIVE)
6769 add_wait_queue_exclusive(head, &poll->wait);
6771 add_wait_queue(head, &poll->wait);
6774 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6775 struct poll_table_struct *p)
6777 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6779 __io_queue_proc(&pt->req->poll, pt, head,
6780 (struct io_poll_iocb **) &pt->req->async_data);
6783 static int __io_arm_poll_handler(struct io_kiocb *req,
6784 struct io_poll_iocb *poll,
6785 struct io_poll_table *ipt, __poll_t mask)
6787 struct io_ring_ctx *ctx = req->ctx;
6790 INIT_HLIST_NODE(&req->hash_node);
6791 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
6792 io_init_poll_iocb(poll, mask, io_poll_wake);
6793 poll->file = req->file;
6795 ipt->pt._key = mask;
6798 ipt->nr_entries = 0;
6801 * Take the ownership to delay any tw execution up until we're done
6802 * with poll arming. see io_poll_get_ownership().
6804 atomic_set(&req->poll_refs, 1);
6805 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6807 if (mask && (poll->events & EPOLLONESHOT)) {
6808 io_poll_remove_entries(req);
6809 /* no one else has access to the req, forget about the ref */
6812 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6813 io_poll_remove_entries(req);
6815 ipt->error = -EINVAL;
6819 spin_lock(&ctx->completion_lock);
6820 io_poll_req_insert(req);
6821 spin_unlock(&ctx->completion_lock);
6824 /* can't multishot if failed, just queue the event we've got */
6825 if (unlikely(ipt->error || !ipt->nr_entries))
6826 poll->events |= EPOLLONESHOT;
6827 __io_poll_execute(req, mask, poll->events);
6832 * Release ownership. If someone tried to queue a tw while it was
6833 * locked, kick it off for them.
6835 v = atomic_dec_return(&req->poll_refs);
6836 if (unlikely(v & IO_POLL_REF_MASK))
6837 __io_poll_execute(req, 0, poll->events);
6841 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6842 struct poll_table_struct *p)
6844 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6845 struct async_poll *apoll = pt->req->apoll;
6847 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6856 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6858 const struct io_op_def *def = &io_op_defs[req->opcode];
6859 struct io_ring_ctx *ctx = req->ctx;
6860 struct async_poll *apoll;
6861 struct io_poll_table ipt;
6862 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6865 if (!def->pollin && !def->pollout)
6866 return IO_APOLL_ABORTED;
6867 if (!file_can_poll(req->file))
6868 return IO_APOLL_ABORTED;
6869 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
6870 return IO_APOLL_ABORTED;
6873 mask |= POLLIN | POLLRDNORM;
6875 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6876 if ((req->opcode == IORING_OP_RECVMSG) &&
6877 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6880 mask |= POLLOUT | POLLWRNORM;
6882 if (def->poll_exclusive)
6883 mask |= EPOLLEXCLUSIVE;
6884 if (req->flags & REQ_F_POLLED) {
6886 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6887 !list_empty(&ctx->apoll_cache)) {
6888 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6890 list_del_init(&apoll->poll.wait.entry);
6892 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6893 if (unlikely(!apoll))
6894 return IO_APOLL_ABORTED;
6896 apoll->double_poll = NULL;
6898 req->flags |= REQ_F_POLLED;
6899 ipt.pt._qproc = io_async_queue_proc;
6901 io_kbuf_recycle(req, issue_flags);
6903 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6904 if (ret || ipt.error)
6905 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6907 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
6908 mask, apoll->poll.events);
6913 * Returns true if we found and killed one or more poll requests
6915 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6916 struct task_struct *tsk, bool cancel_all)
6918 struct hlist_node *tmp;
6919 struct io_kiocb *req;
6923 spin_lock(&ctx->completion_lock);
6924 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6925 struct hlist_head *list;
6927 list = &ctx->cancel_hash[i];
6928 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6929 if (io_match_task_safe(req, tsk, cancel_all)) {
6930 hlist_del_init(&req->hash_node);
6931 io_poll_cancel_req(req);
6936 spin_unlock(&ctx->completion_lock);
6940 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
6941 struct io_cancel_data *cd)
6942 __must_hold(&ctx->completion_lock)
6944 struct hlist_head *list;
6945 struct io_kiocb *req;
6947 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
6948 hlist_for_each_entry(req, list, hash_node) {
6949 if (cd->data != req->cqe.user_data)
6951 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6953 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
6954 if (cd->seq == req->work.cancel_seq)
6956 req->work.cancel_seq = cd->seq;
6963 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
6964 struct io_cancel_data *cd)
6965 __must_hold(&ctx->completion_lock)
6967 struct io_kiocb *req;
6970 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6971 struct hlist_head *list;
6973 list = &ctx->cancel_hash[i];
6974 hlist_for_each_entry(req, list, hash_node) {
6975 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
6976 req->file != cd->file)
6978 if (cd->seq == req->work.cancel_seq)
6980 req->work.cancel_seq = cd->seq;
6987 static bool io_poll_disarm(struct io_kiocb *req)
6988 __must_hold(&ctx->completion_lock)
6990 if (!io_poll_get_ownership(req))
6992 io_poll_remove_entries(req);
6993 hash_del(&req->hash_node);
6997 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
6998 __must_hold(&ctx->completion_lock)
7000 struct io_kiocb *req;
7002 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7003 req = io_poll_file_find(ctx, cd);
7005 req = io_poll_find(ctx, false, cd);
7008 io_poll_cancel_req(req);
7012 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7017 events = READ_ONCE(sqe->poll32_events);
7019 events = swahw32(events);
7021 if (!(flags & IORING_POLL_ADD_MULTI))
7022 events |= EPOLLONESHOT;
7023 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7026 static int io_poll_update_prep(struct io_kiocb *req,
7027 const struct io_uring_sqe *sqe)
7029 struct io_poll_update *upd = &req->poll_update;
7032 if (sqe->buf_index || sqe->splice_fd_in)
7034 flags = READ_ONCE(sqe->len);
7035 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7036 IORING_POLL_ADD_MULTI))
7038 /* meaningless without update */
7039 if (flags == IORING_POLL_ADD_MULTI)
7042 upd->old_user_data = READ_ONCE(sqe->addr);
7043 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7044 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7046 upd->new_user_data = READ_ONCE(sqe->off);
7047 if (!upd->update_user_data && upd->new_user_data)
7049 if (upd->update_events)
7050 upd->events = io_poll_parse_events(sqe, flags);
7051 else if (sqe->poll32_events)
7057 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7059 struct io_poll_iocb *poll = &req->poll;
7062 if (sqe->buf_index || sqe->off || sqe->addr)
7064 flags = READ_ONCE(sqe->len);
7065 if (flags & ~IORING_POLL_ADD_MULTI)
7067 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7070 io_req_set_refcount(req);
7071 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
7075 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7077 struct io_poll_iocb *poll = &req->poll;
7078 struct io_poll_table ipt;
7081 ipt.pt._qproc = io_poll_queue_proc;
7083 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7084 ret = ret ?: ipt.error;
7086 __io_req_complete(req, issue_flags, ret, 0);
7090 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
7092 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7093 struct io_ring_ctx *ctx = req->ctx;
7094 struct io_kiocb *preq;
7098 spin_lock(&ctx->completion_lock);
7099 preq = io_poll_find(ctx, true, &cd);
7100 if (!preq || !io_poll_disarm(preq)) {
7101 spin_unlock(&ctx->completion_lock);
7102 ret = preq ? -EALREADY : -ENOENT;
7105 spin_unlock(&ctx->completion_lock);
7107 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7108 /* only mask one event flags, keep behavior flags */
7109 if (req->poll_update.update_events) {
7110 preq->poll.events &= ~0xffff;
7111 preq->poll.events |= req->poll_update.events & 0xffff;
7112 preq->poll.events |= IO_POLL_UNMASK;
7114 if (req->poll_update.update_user_data)
7115 preq->cqe.user_data = req->poll_update.new_user_data;
7117 ret2 = io_poll_add(preq, issue_flags);
7118 /* successfully updated, don't complete poll request */
7124 preq->cqe.res = -ECANCELED;
7125 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7126 io_req_task_complete(preq, &locked);
7130 /* complete update request, we're done with it */
7131 __io_req_complete(req, issue_flags, ret, 0);
7135 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7137 struct io_timeout_data *data = container_of(timer,
7138 struct io_timeout_data, timer);
7139 struct io_kiocb *req = data->req;
7140 struct io_ring_ctx *ctx = req->ctx;
7141 unsigned long flags;
7143 spin_lock_irqsave(&ctx->timeout_lock, flags);
7144 list_del_init(&req->timeout.list);
7145 atomic_set(&req->ctx->cq_timeouts,
7146 atomic_read(&req->ctx->cq_timeouts) + 1);
7147 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7149 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7152 req->cqe.res = -ETIME;
7153 req->io_task_work.func = io_req_task_complete;
7154 io_req_task_work_add(req, false);
7155 return HRTIMER_NORESTART;
7158 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7159 struct io_cancel_data *cd)
7160 __must_hold(&ctx->timeout_lock)
7162 struct io_timeout_data *io;
7163 struct io_kiocb *req;
7166 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7167 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7168 cd->data != req->cqe.user_data)
7170 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7171 if (cd->seq == req->work.cancel_seq)
7173 req->work.cancel_seq = cd->seq;
7179 return ERR_PTR(-ENOENT);
7181 io = req->async_data;
7182 if (hrtimer_try_to_cancel(&io->timer) == -1)
7183 return ERR_PTR(-EALREADY);
7184 list_del_init(&req->timeout.list);
7188 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7189 __must_hold(&ctx->completion_lock)
7191 struct io_kiocb *req;
7193 spin_lock_irq(&ctx->timeout_lock);
7194 req = io_timeout_extract(ctx, cd);
7195 spin_unlock_irq(&ctx->timeout_lock);
7198 return PTR_ERR(req);
7199 io_req_task_queue_fail(req, -ECANCELED);
7203 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7205 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7206 case IORING_TIMEOUT_BOOTTIME:
7207 return CLOCK_BOOTTIME;
7208 case IORING_TIMEOUT_REALTIME:
7209 return CLOCK_REALTIME;
7211 /* can't happen, vetted at prep time */
7215 return CLOCK_MONOTONIC;
7219 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7220 struct timespec64 *ts, enum hrtimer_mode mode)
7221 __must_hold(&ctx->timeout_lock)
7223 struct io_timeout_data *io;
7224 struct io_kiocb *req;
7227 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7228 found = user_data == req->cqe.user_data;
7235 io = req->async_data;
7236 if (hrtimer_try_to_cancel(&io->timer) == -1)
7238 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7239 io->timer.function = io_link_timeout_fn;
7240 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7244 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7245 struct timespec64 *ts, enum hrtimer_mode mode)
7246 __must_hold(&ctx->timeout_lock)
7248 struct io_cancel_data cd = { .data = user_data, };
7249 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7250 struct io_timeout_data *data;
7253 return PTR_ERR(req);
7255 req->timeout.off = 0; /* noseq */
7256 data = req->async_data;
7257 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7258 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7259 data->timer.function = io_timeout_fn;
7260 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7264 static int io_timeout_remove_prep(struct io_kiocb *req,
7265 const struct io_uring_sqe *sqe)
7267 struct io_timeout_rem *tr = &req->timeout_rem;
7269 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7271 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7274 tr->ltimeout = false;
7275 tr->addr = READ_ONCE(sqe->addr);
7276 tr->flags = READ_ONCE(sqe->timeout_flags);
7277 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7278 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7280 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7281 tr->ltimeout = true;
7282 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7284 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7286 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7288 } else if (tr->flags) {
7289 /* timeout removal doesn't support flags */
7296 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7298 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7303 * Remove or update an existing timeout command
7305 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7307 struct io_timeout_rem *tr = &req->timeout_rem;
7308 struct io_ring_ctx *ctx = req->ctx;
7311 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7312 struct io_cancel_data cd = { .data = tr->addr, };
7314 spin_lock(&ctx->completion_lock);
7315 ret = io_timeout_cancel(ctx, &cd);
7316 spin_unlock(&ctx->completion_lock);
7318 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7320 spin_lock_irq(&ctx->timeout_lock);
7322 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7324 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7325 spin_unlock_irq(&ctx->timeout_lock);
7330 io_req_complete_post(req, ret, 0);
7334 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
7335 bool is_timeout_link)
7337 struct io_timeout_data *data;
7339 u32 off = READ_ONCE(sqe->off);
7341 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7343 if (off && is_timeout_link)
7345 flags = READ_ONCE(sqe->timeout_flags);
7346 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7347 IORING_TIMEOUT_ETIME_SUCCESS))
7349 /* more than one clock specified is invalid, obviously */
7350 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7353 INIT_LIST_HEAD(&req->timeout.list);
7354 req->timeout.off = off;
7355 if (unlikely(off && !req->ctx->off_timeout_used))
7356 req->ctx->off_timeout_used = true;
7358 if (WARN_ON_ONCE(req_has_async_data(req)))
7360 if (io_alloc_async_data(req))
7363 data = req->async_data;
7365 data->flags = flags;
7367 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7370 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7373 INIT_LIST_HEAD(&req->timeout.list);
7374 data->mode = io_translate_timeout_mode(flags);
7375 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7377 if (is_timeout_link) {
7378 struct io_submit_link *link = &req->ctx->submit_state.link;
7382 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7384 req->timeout.head = link->last;
7385 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7390 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7392 struct io_ring_ctx *ctx = req->ctx;
7393 struct io_timeout_data *data = req->async_data;
7394 struct list_head *entry;
7395 u32 tail, off = req->timeout.off;
7397 spin_lock_irq(&ctx->timeout_lock);
7400 * sqe->off holds how many events that need to occur for this
7401 * timeout event to be satisfied. If it isn't set, then this is
7402 * a pure timeout request, sequence isn't used.
7404 if (io_is_timeout_noseq(req)) {
7405 entry = ctx->timeout_list.prev;
7409 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7410 req->timeout.target_seq = tail + off;
7412 /* Update the last seq here in case io_flush_timeouts() hasn't.
7413 * This is safe because ->completion_lock is held, and submissions
7414 * and completions are never mixed in the same ->completion_lock section.
7416 ctx->cq_last_tm_flush = tail;
7419 * Insertion sort, ensuring the first entry in the list is always
7420 * the one we need first.
7422 list_for_each_prev(entry, &ctx->timeout_list) {
7423 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7426 if (io_is_timeout_noseq(nxt))
7428 /* nxt.seq is behind @tail, otherwise would've been completed */
7429 if (off >= nxt->timeout.target_seq - tail)
7433 list_add(&req->timeout.list, entry);
7434 data->timer.function = io_timeout_fn;
7435 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7436 spin_unlock_irq(&ctx->timeout_lock);
7440 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7442 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7443 struct io_cancel_data *cd = data;
7445 if (req->ctx != cd->ctx)
7447 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7449 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7450 if (req->file != cd->file)
7453 if (req->cqe.user_data != cd->data)
7456 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7457 if (cd->seq == req->work.cancel_seq)
7459 req->work.cancel_seq = cd->seq;
7464 static int io_async_cancel_one(struct io_uring_task *tctx,
7465 struct io_cancel_data *cd)
7467 enum io_wq_cancel cancel_ret;
7471 if (!tctx || !tctx->io_wq)
7474 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7475 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7476 switch (cancel_ret) {
7477 case IO_WQ_CANCEL_OK:
7480 case IO_WQ_CANCEL_RUNNING:
7483 case IO_WQ_CANCEL_NOTFOUND:
7491 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7493 struct io_ring_ctx *ctx = req->ctx;
7496 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7498 ret = io_async_cancel_one(req->task->io_uring, cd);
7500 * Fall-through even for -EALREADY, as we may have poll armed
7501 * that need unarming.
7506 spin_lock(&ctx->completion_lock);
7507 ret = io_poll_cancel(ctx, cd);
7510 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7511 ret = io_timeout_cancel(ctx, cd);
7513 spin_unlock(&ctx->completion_lock);
7517 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7518 IORING_ASYNC_CANCEL_ANY)
7520 static int io_async_cancel_prep(struct io_kiocb *req,
7521 const struct io_uring_sqe *sqe)
7523 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7525 if (sqe->off || sqe->len || sqe->splice_fd_in)
7528 req->cancel.addr = READ_ONCE(sqe->addr);
7529 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7530 if (req->cancel.flags & ~CANCEL_FLAGS)
7532 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7533 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7535 req->cancel.fd = READ_ONCE(sqe->fd);
7541 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7542 unsigned int issue_flags)
7544 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7545 struct io_ring_ctx *ctx = cd->ctx;
7546 struct io_tctx_node *node;
7550 ret = io_try_cancel(req, cd);
7558 /* slow path, try all io-wq's */
7559 io_ring_submit_lock(ctx, issue_flags);
7561 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7562 struct io_uring_task *tctx = node->task->io_uring;
7564 ret = io_async_cancel_one(tctx, cd);
7565 if (ret != -ENOENT) {
7571 io_ring_submit_unlock(ctx, issue_flags);
7572 return all ? nr : ret;
7575 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7577 struct io_cancel_data cd = {
7579 .data = req->cancel.addr,
7580 .flags = req->cancel.flags,
7581 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7585 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7586 if (req->flags & REQ_F_FIXED_FILE)
7587 req->file = io_file_get_fixed(req, req->cancel.fd,
7590 req->file = io_file_get_normal(req, req->cancel.fd);
7595 cd.file = req->file;
7598 ret = __io_async_cancel(&cd, req, issue_flags);
7602 io_req_complete_post(req, ret, 0);
7606 static int io_rsrc_update_prep(struct io_kiocb *req,
7607 const struct io_uring_sqe *sqe)
7609 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7611 if (sqe->rw_flags || sqe->splice_fd_in)
7614 req->rsrc_update.offset = READ_ONCE(sqe->off);
7615 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7616 if (!req->rsrc_update.nr_args)
7618 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7622 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7624 struct io_ring_ctx *ctx = req->ctx;
7625 struct io_uring_rsrc_update2 up;
7628 up.offset = req->rsrc_update.offset;
7629 up.data = req->rsrc_update.arg;
7635 io_ring_submit_lock(ctx, issue_flags);
7636 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
7637 &up, req->rsrc_update.nr_args);
7638 io_ring_submit_unlock(ctx, issue_flags);
7642 __io_req_complete(req, issue_flags, ret, 0);
7646 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7648 switch (req->opcode) {
7651 case IORING_OP_READV:
7652 case IORING_OP_READ_FIXED:
7653 case IORING_OP_READ:
7654 case IORING_OP_WRITEV:
7655 case IORING_OP_WRITE_FIXED:
7656 case IORING_OP_WRITE:
7657 return io_prep_rw(req, sqe);
7658 case IORING_OP_POLL_ADD:
7659 return io_poll_add_prep(req, sqe);
7660 case IORING_OP_POLL_REMOVE:
7661 return io_poll_update_prep(req, sqe);
7662 case IORING_OP_FSYNC:
7663 return io_fsync_prep(req, sqe);
7664 case IORING_OP_SYNC_FILE_RANGE:
7665 return io_sfr_prep(req, sqe);
7666 case IORING_OP_SENDMSG:
7667 case IORING_OP_SEND:
7668 return io_sendmsg_prep(req, sqe);
7669 case IORING_OP_RECVMSG:
7670 case IORING_OP_RECV:
7671 return io_recvmsg_prep(req, sqe);
7672 case IORING_OP_CONNECT:
7673 return io_connect_prep(req, sqe);
7674 case IORING_OP_TIMEOUT:
7675 return io_timeout_prep(req, sqe, false);
7676 case IORING_OP_TIMEOUT_REMOVE:
7677 return io_timeout_remove_prep(req, sqe);
7678 case IORING_OP_ASYNC_CANCEL:
7679 return io_async_cancel_prep(req, sqe);
7680 case IORING_OP_LINK_TIMEOUT:
7681 return io_timeout_prep(req, sqe, true);
7682 case IORING_OP_ACCEPT:
7683 return io_accept_prep(req, sqe);
7684 case IORING_OP_FALLOCATE:
7685 return io_fallocate_prep(req, sqe);
7686 case IORING_OP_OPENAT:
7687 return io_openat_prep(req, sqe);
7688 case IORING_OP_CLOSE:
7689 return io_close_prep(req, sqe);
7690 case IORING_OP_FILES_UPDATE:
7691 return io_rsrc_update_prep(req, sqe);
7692 case IORING_OP_STATX:
7693 return io_statx_prep(req, sqe);
7694 case IORING_OP_FADVISE:
7695 return io_fadvise_prep(req, sqe);
7696 case IORING_OP_MADVISE:
7697 return io_madvise_prep(req, sqe);
7698 case IORING_OP_OPENAT2:
7699 return io_openat2_prep(req, sqe);
7700 case IORING_OP_EPOLL_CTL:
7701 return io_epoll_ctl_prep(req, sqe);
7702 case IORING_OP_SPLICE:
7703 return io_splice_prep(req, sqe);
7704 case IORING_OP_PROVIDE_BUFFERS:
7705 return io_provide_buffers_prep(req, sqe);
7706 case IORING_OP_REMOVE_BUFFERS:
7707 return io_remove_buffers_prep(req, sqe);
7709 return io_tee_prep(req, sqe);
7710 case IORING_OP_SHUTDOWN:
7711 return io_shutdown_prep(req, sqe);
7712 case IORING_OP_RENAMEAT:
7713 return io_renameat_prep(req, sqe);
7714 case IORING_OP_UNLINKAT:
7715 return io_unlinkat_prep(req, sqe);
7716 case IORING_OP_MKDIRAT:
7717 return io_mkdirat_prep(req, sqe);
7718 case IORING_OP_SYMLINKAT:
7719 return io_symlinkat_prep(req, sqe);
7720 case IORING_OP_LINKAT:
7721 return io_linkat_prep(req, sqe);
7722 case IORING_OP_MSG_RING:
7723 return io_msg_ring_prep(req, sqe);
7724 case IORING_OP_FSETXATTR:
7725 return io_fsetxattr_prep(req, sqe);
7726 case IORING_OP_SETXATTR:
7727 return io_setxattr_prep(req, sqe);
7728 case IORING_OP_FGETXATTR:
7729 return io_fgetxattr_prep(req, sqe);
7730 case IORING_OP_GETXATTR:
7731 return io_getxattr_prep(req, sqe);
7732 case IORING_OP_SOCKET:
7733 return io_socket_prep(req, sqe);
7736 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
7741 static int io_req_prep_async(struct io_kiocb *req)
7743 const struct io_op_def *def = &io_op_defs[req->opcode];
7745 /* assign early for deferred execution for non-fixed file */
7746 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
7747 req->file = io_file_get_normal(req, req->cqe.fd);
7748 if (!def->needs_async_setup)
7750 if (WARN_ON_ONCE(req_has_async_data(req)))
7752 if (io_alloc_async_data(req))
7755 switch (req->opcode) {
7756 case IORING_OP_READV:
7757 return io_rw_prep_async(req, READ);
7758 case IORING_OP_WRITEV:
7759 return io_rw_prep_async(req, WRITE);
7760 case IORING_OP_SENDMSG:
7761 return io_sendmsg_prep_async(req);
7762 case IORING_OP_RECVMSG:
7763 return io_recvmsg_prep_async(req);
7764 case IORING_OP_CONNECT:
7765 return io_connect_prep_async(req);
7767 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7772 static u32 io_get_sequence(struct io_kiocb *req)
7774 u32 seq = req->ctx->cached_sq_head;
7775 struct io_kiocb *cur;
7777 /* need original cached_sq_head, but it was increased for each req */
7778 io_for_each_link(cur, req)
7783 static __cold void io_drain_req(struct io_kiocb *req)
7785 struct io_ring_ctx *ctx = req->ctx;
7786 struct io_defer_entry *de;
7788 u32 seq = io_get_sequence(req);
7790 /* Still need defer if there is pending req in defer list. */
7791 spin_lock(&ctx->completion_lock);
7792 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7793 spin_unlock(&ctx->completion_lock);
7795 ctx->drain_active = false;
7796 io_req_task_queue(req);
7799 spin_unlock(&ctx->completion_lock);
7801 ret = io_req_prep_async(req);
7804 io_req_complete_failed(req, ret);
7807 io_prep_async_link(req);
7808 de = kmalloc(sizeof(*de), GFP_KERNEL);
7814 spin_lock(&ctx->completion_lock);
7815 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7816 spin_unlock(&ctx->completion_lock);
7821 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7824 list_add_tail(&de->list, &ctx->defer_list);
7825 spin_unlock(&ctx->completion_lock);
7828 static void io_clean_op(struct io_kiocb *req)
7830 if (req->flags & REQ_F_BUFFER_SELECTED) {
7831 spin_lock(&req->ctx->completion_lock);
7832 io_put_kbuf_comp(req);
7833 spin_unlock(&req->ctx->completion_lock);
7836 if (req->flags & REQ_F_NEED_CLEANUP) {
7837 switch (req->opcode) {
7838 case IORING_OP_READV:
7839 case IORING_OP_READ_FIXED:
7840 case IORING_OP_READ:
7841 case IORING_OP_WRITEV:
7842 case IORING_OP_WRITE_FIXED:
7843 case IORING_OP_WRITE: {
7844 struct io_async_rw *io = req->async_data;
7846 kfree(io->free_iovec);
7849 case IORING_OP_RECVMSG:
7850 case IORING_OP_SENDMSG: {
7851 struct io_async_msghdr *io = req->async_data;
7853 kfree(io->free_iov);
7856 case IORING_OP_OPENAT:
7857 case IORING_OP_OPENAT2:
7858 if (req->open.filename)
7859 putname(req->open.filename);
7861 case IORING_OP_RENAMEAT:
7862 putname(req->rename.oldpath);
7863 putname(req->rename.newpath);
7865 case IORING_OP_UNLINKAT:
7866 putname(req->unlink.filename);
7868 case IORING_OP_MKDIRAT:
7869 putname(req->mkdir.filename);
7871 case IORING_OP_SYMLINKAT:
7872 putname(req->symlink.oldpath);
7873 putname(req->symlink.newpath);
7875 case IORING_OP_LINKAT:
7876 putname(req->hardlink.oldpath);
7877 putname(req->hardlink.newpath);
7879 case IORING_OP_STATX:
7880 if (req->statx.filename)
7881 putname(req->statx.filename);
7883 case IORING_OP_SETXATTR:
7884 case IORING_OP_FSETXATTR:
7885 case IORING_OP_GETXATTR:
7886 case IORING_OP_FGETXATTR:
7887 __io_xattr_finish(req);
7891 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7892 kfree(req->apoll->double_poll);
7896 if (req->flags & REQ_F_CREDS)
7897 put_cred(req->creds);
7898 if (req->flags & REQ_F_ASYNC_DATA) {
7899 kfree(req->async_data);
7900 req->async_data = NULL;
7902 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7905 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
7907 if (req->file || !io_op_defs[req->opcode].needs_file)
7910 if (req->flags & REQ_F_FIXED_FILE)
7911 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
7913 req->file = io_file_get_normal(req, req->cqe.fd);
7918 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7920 const struct cred *creds = NULL;
7923 if (unlikely(!io_assign_file(req, issue_flags)))
7926 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7927 creds = override_creds(req->creds);
7929 if (!io_op_defs[req->opcode].audit_skip)
7930 audit_uring_entry(req->opcode);
7932 switch (req->opcode) {
7934 ret = io_nop(req, issue_flags);
7936 case IORING_OP_READV:
7937 case IORING_OP_READ_FIXED:
7938 case IORING_OP_READ:
7939 ret = io_read(req, issue_flags);
7941 case IORING_OP_WRITEV:
7942 case IORING_OP_WRITE_FIXED:
7943 case IORING_OP_WRITE:
7944 ret = io_write(req, issue_flags);
7946 case IORING_OP_FSYNC:
7947 ret = io_fsync(req, issue_flags);
7949 case IORING_OP_POLL_ADD:
7950 ret = io_poll_add(req, issue_flags);
7952 case IORING_OP_POLL_REMOVE:
7953 ret = io_poll_update(req, issue_flags);
7955 case IORING_OP_SYNC_FILE_RANGE:
7956 ret = io_sync_file_range(req, issue_flags);
7958 case IORING_OP_SENDMSG:
7959 ret = io_sendmsg(req, issue_flags);
7961 case IORING_OP_SEND:
7962 ret = io_send(req, issue_flags);
7964 case IORING_OP_RECVMSG:
7965 ret = io_recvmsg(req, issue_flags);
7967 case IORING_OP_RECV:
7968 ret = io_recv(req, issue_flags);
7970 case IORING_OP_TIMEOUT:
7971 ret = io_timeout(req, issue_flags);
7973 case IORING_OP_TIMEOUT_REMOVE:
7974 ret = io_timeout_remove(req, issue_flags);
7976 case IORING_OP_ACCEPT:
7977 ret = io_accept(req, issue_flags);
7979 case IORING_OP_CONNECT:
7980 ret = io_connect(req, issue_flags);
7982 case IORING_OP_ASYNC_CANCEL:
7983 ret = io_async_cancel(req, issue_flags);
7985 case IORING_OP_FALLOCATE:
7986 ret = io_fallocate(req, issue_flags);
7988 case IORING_OP_OPENAT:
7989 ret = io_openat(req, issue_flags);
7991 case IORING_OP_CLOSE:
7992 ret = io_close(req, issue_flags);
7994 case IORING_OP_FILES_UPDATE:
7995 ret = io_files_update(req, issue_flags);
7997 case IORING_OP_STATX:
7998 ret = io_statx(req, issue_flags);
8000 case IORING_OP_FADVISE:
8001 ret = io_fadvise(req, issue_flags);
8003 case IORING_OP_MADVISE:
8004 ret = io_madvise(req, issue_flags);
8006 case IORING_OP_OPENAT2:
8007 ret = io_openat2(req, issue_flags);
8009 case IORING_OP_EPOLL_CTL:
8010 ret = io_epoll_ctl(req, issue_flags);
8012 case IORING_OP_SPLICE:
8013 ret = io_splice(req, issue_flags);
8015 case IORING_OP_PROVIDE_BUFFERS:
8016 ret = io_provide_buffers(req, issue_flags);
8018 case IORING_OP_REMOVE_BUFFERS:
8019 ret = io_remove_buffers(req, issue_flags);
8022 ret = io_tee(req, issue_flags);
8024 case IORING_OP_SHUTDOWN:
8025 ret = io_shutdown(req, issue_flags);
8027 case IORING_OP_RENAMEAT:
8028 ret = io_renameat(req, issue_flags);
8030 case IORING_OP_UNLINKAT:
8031 ret = io_unlinkat(req, issue_flags);
8033 case IORING_OP_MKDIRAT:
8034 ret = io_mkdirat(req, issue_flags);
8036 case IORING_OP_SYMLINKAT:
8037 ret = io_symlinkat(req, issue_flags);
8039 case IORING_OP_LINKAT:
8040 ret = io_linkat(req, issue_flags);
8042 case IORING_OP_MSG_RING:
8043 ret = io_msg_ring(req, issue_flags);
8045 case IORING_OP_FSETXATTR:
8046 ret = io_fsetxattr(req, issue_flags);
8048 case IORING_OP_SETXATTR:
8049 ret = io_setxattr(req, issue_flags);
8051 case IORING_OP_FGETXATTR:
8052 ret = io_fgetxattr(req, issue_flags);
8054 case IORING_OP_GETXATTR:
8055 ret = io_getxattr(req, issue_flags);
8057 case IORING_OP_SOCKET:
8058 ret = io_socket(req, issue_flags);
8065 if (!io_op_defs[req->opcode].audit_skip)
8066 audit_uring_exit(!ret, ret);
8069 revert_creds(creds);
8072 /* If the op doesn't have a file, we're not polling for it */
8073 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8074 io_iopoll_req_issued(req, issue_flags);
8079 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8081 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8083 req = io_put_req_find_next(req);
8084 return req ? &req->work : NULL;
8087 static void io_wq_submit_work(struct io_wq_work *work)
8089 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8090 const struct io_op_def *def = &io_op_defs[req->opcode];
8091 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8092 bool needs_poll = false;
8093 int ret = 0, err = -ECANCELED;
8095 /* one will be dropped by ->io_free_work() after returning to io-wq */
8096 if (!(req->flags & REQ_F_REFCOUNT))
8097 __io_req_set_refcount(req, 2);
8101 io_arm_ltimeout(req);
8103 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8104 if (work->flags & IO_WQ_WORK_CANCEL) {
8106 io_req_task_queue_fail(req, err);
8109 if (!io_assign_file(req, issue_flags)) {
8111 work->flags |= IO_WQ_WORK_CANCEL;
8115 if (req->flags & REQ_F_FORCE_ASYNC) {
8116 bool opcode_poll = def->pollin || def->pollout;
8118 if (opcode_poll && file_can_poll(req->file)) {
8120 issue_flags |= IO_URING_F_NONBLOCK;
8125 ret = io_issue_sqe(req, issue_flags);
8129 * We can get EAGAIN for iopolled IO even though we're
8130 * forcing a sync submission from here, since we can't
8131 * wait for request slots on the block side.
8138 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8140 /* aborted or ready, in either case retry blocking */
8142 issue_flags &= ~IO_URING_F_NONBLOCK;
8145 /* avoid locking problems by failing it from a clean context */
8147 io_req_task_queue_fail(req, ret);
8150 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8153 return &table->files[i];
8156 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8159 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8161 return (struct file *) (slot->file_ptr & FFS_MASK);
8164 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8166 unsigned long file_ptr = (unsigned long) file;
8168 file_ptr |= io_file_get_flags(file);
8169 file_slot->file_ptr = file_ptr;
8172 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8173 unsigned int issue_flags)
8175 struct io_ring_ctx *ctx = req->ctx;
8176 struct file *file = NULL;
8177 unsigned long file_ptr;
8179 io_ring_submit_lock(ctx, issue_flags);
8181 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8183 fd = array_index_nospec(fd, ctx->nr_user_files);
8184 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8185 file = (struct file *) (file_ptr & FFS_MASK);
8186 file_ptr &= ~FFS_MASK;
8187 /* mask in overlapping REQ_F and FFS bits */
8188 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8189 io_req_set_rsrc_node(req, ctx, 0);
8191 io_ring_submit_unlock(ctx, issue_flags);
8196 * Drop the file for requeue operations. Only used of req->file is the
8197 * io_uring descriptor itself.
8199 static void io_drop_inflight_file(struct io_kiocb *req)
8201 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
8204 req->flags &= ~REQ_F_INFLIGHT;
8208 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8210 struct file *file = fget(fd);
8212 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8214 /* we don't allow fixed io_uring files */
8215 if (file && file->f_op == &io_uring_fops)
8216 req->flags |= REQ_F_INFLIGHT;
8220 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8222 struct io_kiocb *prev = req->timeout.prev;
8226 if (!(req->task->flags & PF_EXITING)) {
8227 struct io_cancel_data cd = {
8229 .data = prev->cqe.user_data,
8232 ret = io_try_cancel(req, &cd);
8234 io_req_complete_post(req, ret ?: -ETIME, 0);
8237 io_req_complete_post(req, -ETIME, 0);
8241 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8243 struct io_timeout_data *data = container_of(timer,
8244 struct io_timeout_data, timer);
8245 struct io_kiocb *prev, *req = data->req;
8246 struct io_ring_ctx *ctx = req->ctx;
8247 unsigned long flags;
8249 spin_lock_irqsave(&ctx->timeout_lock, flags);
8250 prev = req->timeout.head;
8251 req->timeout.head = NULL;
8254 * We don't expect the list to be empty, that will only happen if we
8255 * race with the completion of the linked work.
8258 io_remove_next_linked(prev);
8259 if (!req_ref_inc_not_zero(prev))
8262 list_del(&req->timeout.list);
8263 req->timeout.prev = prev;
8264 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8266 req->io_task_work.func = io_req_task_link_timeout;
8267 io_req_task_work_add(req, false);
8268 return HRTIMER_NORESTART;
8271 static void io_queue_linked_timeout(struct io_kiocb *req)
8273 struct io_ring_ctx *ctx = req->ctx;
8275 spin_lock_irq(&ctx->timeout_lock);
8277 * If the back reference is NULL, then our linked request finished
8278 * before we got a chance to setup the timer
8280 if (req->timeout.head) {
8281 struct io_timeout_data *data = req->async_data;
8283 data->timer.function = io_link_timeout_fn;
8284 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8286 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8288 spin_unlock_irq(&ctx->timeout_lock);
8289 /* drop submission reference */
8293 static void io_queue_async(struct io_kiocb *req, int ret)
8294 __must_hold(&req->ctx->uring_lock)
8296 struct io_kiocb *linked_timeout;
8298 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8299 io_req_complete_failed(req, ret);
8303 linked_timeout = io_prep_linked_timeout(req);
8305 switch (io_arm_poll_handler(req, 0)) {
8306 case IO_APOLL_READY:
8307 io_req_task_queue(req);
8309 case IO_APOLL_ABORTED:
8311 * Queued up for async execution, worker will release
8312 * submit reference when the iocb is actually submitted.
8314 io_queue_iowq(req, NULL);
8321 io_queue_linked_timeout(linked_timeout);
8324 static inline void io_queue_sqe(struct io_kiocb *req)
8325 __must_hold(&req->ctx->uring_lock)
8329 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8331 if (req->flags & REQ_F_COMPLETE_INLINE) {
8332 io_req_add_compl_list(req);
8336 * We async punt it if the file wasn't marked NOWAIT, or if the file
8337 * doesn't support non-blocking read/write attempts
8340 io_arm_ltimeout(req);
8342 io_queue_async(req, ret);
8345 static void io_queue_sqe_fallback(struct io_kiocb *req)
8346 __must_hold(&req->ctx->uring_lock)
8348 if (unlikely(req->flags & REQ_F_FAIL)) {
8350 * We don't submit, fail them all, for that replace hardlinks
8351 * with normal links. Extra REQ_F_LINK is tolerated.
8353 req->flags &= ~REQ_F_HARDLINK;
8354 req->flags |= REQ_F_LINK;
8355 io_req_complete_failed(req, req->cqe.res);
8356 } else if (unlikely(req->ctx->drain_active)) {
8359 int ret = io_req_prep_async(req);
8362 io_req_complete_failed(req, ret);
8364 io_queue_iowq(req, NULL);
8369 * Check SQE restrictions (opcode and flags).
8371 * Returns 'true' if SQE is allowed, 'false' otherwise.
8373 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8374 struct io_kiocb *req,
8375 unsigned int sqe_flags)
8377 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8380 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8381 ctx->restrictions.sqe_flags_required)
8384 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8385 ctx->restrictions.sqe_flags_required))
8391 static void io_init_req_drain(struct io_kiocb *req)
8393 struct io_ring_ctx *ctx = req->ctx;
8394 struct io_kiocb *head = ctx->submit_state.link.head;
8396 ctx->drain_active = true;
8399 * If we need to drain a request in the middle of a link, drain
8400 * the head request and the next request/link after the current
8401 * link. Considering sequential execution of links,
8402 * REQ_F_IO_DRAIN will be maintained for every request of our
8405 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8406 ctx->drain_next = true;
8410 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8411 const struct io_uring_sqe *sqe)
8412 __must_hold(&ctx->uring_lock)
8414 unsigned int sqe_flags;
8418 /* req is partially pre-initialised, see io_preinit_req() */
8419 req->opcode = opcode = READ_ONCE(sqe->opcode);
8420 /* same numerical values with corresponding REQ_F_*, safe to copy */
8421 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8422 req->cqe.user_data = READ_ONCE(sqe->user_data);
8424 req->rsrc_node = NULL;
8425 req->task = current;
8427 if (unlikely(opcode >= IORING_OP_LAST)) {
8431 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8432 /* enforce forwards compatibility on users */
8433 if (sqe_flags & ~SQE_VALID_FLAGS)
8435 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8436 if (!io_op_defs[opcode].buffer_select)
8438 req->buf_index = READ_ONCE(sqe->buf_group);
8440 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8441 ctx->drain_disabled = true;
8442 if (sqe_flags & IOSQE_IO_DRAIN) {
8443 if (ctx->drain_disabled)
8445 io_init_req_drain(req);
8448 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8449 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8451 /* knock it to the slow queue path, will be drained there */
8452 if (ctx->drain_active)
8453 req->flags |= REQ_F_FORCE_ASYNC;
8454 /* if there is no link, we're at "next" request and need to drain */
8455 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8456 ctx->drain_next = false;
8457 ctx->drain_active = true;
8458 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8462 if (!io_op_defs[opcode].ioprio && sqe->ioprio)
8464 if (!io_op_defs[opcode].iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8467 if (io_op_defs[opcode].needs_file) {
8468 struct io_submit_state *state = &ctx->submit_state;
8470 req->cqe.fd = READ_ONCE(sqe->fd);
8473 * Plug now if we have more than 2 IO left after this, and the
8474 * target is potentially a read/write to block based storage.
8476 if (state->need_plug && io_op_defs[opcode].plug) {
8477 state->plug_started = true;
8478 state->need_plug = false;
8479 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8483 personality = READ_ONCE(sqe->personality);
8487 req->creds = xa_load(&ctx->personalities, personality);
8490 get_cred(req->creds);
8491 ret = security_uring_override_creds(req->creds);
8493 put_cred(req->creds);
8496 req->flags |= REQ_F_CREDS;
8499 return io_req_prep(req, sqe);
8502 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8503 struct io_kiocb *req, int ret)
8505 struct io_ring_ctx *ctx = req->ctx;
8506 struct io_submit_link *link = &ctx->submit_state.link;
8507 struct io_kiocb *head = link->head;
8509 trace_io_uring_req_failed(sqe, ctx, req, ret);
8512 * Avoid breaking links in the middle as it renders links with SQPOLL
8513 * unusable. Instead of failing eagerly, continue assembling the link if
8514 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8515 * should find the flag and handle the rest.
8517 req_fail_link_node(req, ret);
8518 if (head && !(head->flags & REQ_F_FAIL))
8519 req_fail_link_node(head, -ECANCELED);
8521 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8523 link->last->link = req;
8527 io_queue_sqe_fallback(req);
8532 link->last->link = req;
8539 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8540 const struct io_uring_sqe *sqe)
8541 __must_hold(&ctx->uring_lock)
8543 struct io_submit_link *link = &ctx->submit_state.link;
8546 ret = io_init_req(ctx, req, sqe);
8548 return io_submit_fail_init(sqe, req, ret);
8550 /* don't need @sqe from now on */
8551 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8553 ctx->flags & IORING_SETUP_SQPOLL);
8556 * If we already have a head request, queue this one for async
8557 * submittal once the head completes. If we don't have a head but
8558 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8559 * submitted sync once the chain is complete. If none of those
8560 * conditions are true (normal request), then just queue it.
8562 if (unlikely(link->head)) {
8563 ret = io_req_prep_async(req);
8565 return io_submit_fail_init(sqe, req, ret);
8567 trace_io_uring_link(ctx, req, link->head);
8568 link->last->link = req;
8571 if (req->flags & IO_REQ_LINK_FLAGS)
8573 /* last request of the link, flush it */
8576 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8579 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8580 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8581 if (req->flags & IO_REQ_LINK_FLAGS) {
8586 io_queue_sqe_fallback(req);
8596 * Batched submission is done, ensure local IO is flushed out.
8598 static void io_submit_state_end(struct io_ring_ctx *ctx)
8600 struct io_submit_state *state = &ctx->submit_state;
8602 if (unlikely(state->link.head))
8603 io_queue_sqe_fallback(state->link.head);
8604 /* flush only after queuing links as they can generate completions */
8605 io_submit_flush_completions(ctx);
8606 if (state->plug_started)
8607 blk_finish_plug(&state->plug);
8611 * Start submission side cache.
8613 static void io_submit_state_start(struct io_submit_state *state,
8614 unsigned int max_ios)
8616 state->plug_started = false;
8617 state->need_plug = max_ios > 2;
8618 state->submit_nr = max_ios;
8619 /* set only head, no need to init link_last in advance */
8620 state->link.head = NULL;
8623 static void io_commit_sqring(struct io_ring_ctx *ctx)
8625 struct io_rings *rings = ctx->rings;
8628 * Ensure any loads from the SQEs are done at this point,
8629 * since once we write the new head, the application could
8630 * write new data to them.
8632 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
8636 * Fetch an sqe, if one is available. Note this returns a pointer to memory
8637 * that is mapped by userspace. This means that care needs to be taken to
8638 * ensure that reads are stable, as we cannot rely on userspace always
8639 * being a good citizen. If members of the sqe are validated and then later
8640 * used, it's important that those reads are done through READ_ONCE() to
8641 * prevent a re-load down the line.
8643 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
8645 unsigned head, mask = ctx->sq_entries - 1;
8646 unsigned sq_idx = ctx->cached_sq_head++ & mask;
8649 * The cached sq head (or cq tail) serves two purposes:
8651 * 1) allows us to batch the cost of updating the user visible
8653 * 2) allows the kernel side to track the head on its own, even
8654 * though the application is the one updating it.
8656 head = READ_ONCE(ctx->sq_array[sq_idx]);
8657 if (likely(head < ctx->sq_entries)) {
8658 /* double index for 128-byte SQEs, twice as long */
8659 if (ctx->flags & IORING_SETUP_SQE128)
8661 return &ctx->sq_sqes[head];
8664 /* drop invalid entries */
8666 WRITE_ONCE(ctx->rings->sq_dropped,
8667 READ_ONCE(ctx->rings->sq_dropped) + 1);
8671 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
8672 __must_hold(&ctx->uring_lock)
8674 unsigned int entries = io_sqring_entries(ctx);
8678 if (unlikely(!entries))
8680 /* make sure SQ entry isn't read before tail */
8681 ret = left = min3(nr, ctx->sq_entries, entries);
8682 io_get_task_refs(left);
8683 io_submit_state_start(&ctx->submit_state, left);
8686 const struct io_uring_sqe *sqe;
8687 struct io_kiocb *req;
8689 if (unlikely(!io_alloc_req_refill(ctx)))
8691 req = io_alloc_req(ctx);
8692 sqe = io_get_sqe(ctx);
8693 if (unlikely(!sqe)) {
8694 io_req_add_to_cache(req, ctx);
8699 * Continue submitting even for sqe failure if the
8700 * ring was setup with IORING_SETUP_SUBMIT_ALL
8702 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
8703 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
8709 if (unlikely(left)) {
8711 /* try again if it submitted nothing and can't allocate a req */
8712 if (!ret && io_req_cache_empty(ctx))
8714 current->io_uring->cached_refs += left;
8717 io_submit_state_end(ctx);
8718 /* Commit SQ ring head once we've consumed and submitted all SQEs */
8719 io_commit_sqring(ctx);
8723 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
8725 return READ_ONCE(sqd->state);
8728 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
8730 unsigned int to_submit;
8733 to_submit = io_sqring_entries(ctx);
8734 /* if we're handling multiple rings, cap submit size for fairness */
8735 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
8736 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
8738 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
8739 const struct cred *creds = NULL;
8741 if (ctx->sq_creds != current_cred())
8742 creds = override_creds(ctx->sq_creds);
8744 mutex_lock(&ctx->uring_lock);
8745 if (!wq_list_empty(&ctx->iopoll_list))
8746 io_do_iopoll(ctx, true);
8749 * Don't submit if refs are dying, good for io_uring_register(),
8750 * but also it is relied upon by io_ring_exit_work()
8752 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
8753 !(ctx->flags & IORING_SETUP_R_DISABLED))
8754 ret = io_submit_sqes(ctx, to_submit);
8755 mutex_unlock(&ctx->uring_lock);
8757 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8758 wake_up(&ctx->sqo_sq_wait);
8760 revert_creds(creds);
8766 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8768 struct io_ring_ctx *ctx;
8769 unsigned sq_thread_idle = 0;
8771 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8772 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8773 sqd->sq_thread_idle = sq_thread_idle;
8776 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8778 bool did_sig = false;
8779 struct ksignal ksig;
8781 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8782 signal_pending(current)) {
8783 mutex_unlock(&sqd->lock);
8784 if (signal_pending(current))
8785 did_sig = get_signal(&ksig);
8787 mutex_lock(&sqd->lock);
8789 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8792 static int io_sq_thread(void *data)
8794 struct io_sq_data *sqd = data;
8795 struct io_ring_ctx *ctx;
8796 unsigned long timeout = 0;
8797 char buf[TASK_COMM_LEN];
8800 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8801 set_task_comm(current, buf);
8803 if (sqd->sq_cpu != -1)
8804 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8806 set_cpus_allowed_ptr(current, cpu_online_mask);
8807 current->flags |= PF_NO_SETAFFINITY;
8809 audit_alloc_kernel(current);
8811 mutex_lock(&sqd->lock);
8813 bool cap_entries, sqt_spin = false;
8815 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8816 if (io_sqd_handle_event(sqd))
8818 timeout = jiffies + sqd->sq_thread_idle;
8821 cap_entries = !list_is_singular(&sqd->ctx_list);
8822 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8823 int ret = __io_sq_thread(ctx, cap_entries);
8825 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8828 if (io_run_task_work())
8831 if (sqt_spin || !time_after(jiffies, timeout)) {
8834 timeout = jiffies + sqd->sq_thread_idle;
8838 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8839 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8840 bool needs_sched = true;
8842 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8843 atomic_or(IORING_SQ_NEED_WAKEUP,
8844 &ctx->rings->sq_flags);
8845 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8846 !wq_list_empty(&ctx->iopoll_list)) {
8847 needs_sched = false;
8852 * Ensure the store of the wakeup flag is not
8853 * reordered with the load of the SQ tail
8855 smp_mb__after_atomic();
8857 if (io_sqring_entries(ctx)) {
8858 needs_sched = false;
8864 mutex_unlock(&sqd->lock);
8866 mutex_lock(&sqd->lock);
8868 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8869 atomic_andnot(IORING_SQ_NEED_WAKEUP,
8870 &ctx->rings->sq_flags);
8873 finish_wait(&sqd->wait, &wait);
8874 timeout = jiffies + sqd->sq_thread_idle;
8877 io_uring_cancel_generic(true, sqd);
8879 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8880 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
8882 mutex_unlock(&sqd->lock);
8884 audit_free(current);
8886 complete(&sqd->exited);
8890 struct io_wait_queue {
8891 struct wait_queue_entry wq;
8892 struct io_ring_ctx *ctx;
8894 unsigned nr_timeouts;
8897 static inline bool io_should_wake(struct io_wait_queue *iowq)
8899 struct io_ring_ctx *ctx = iowq->ctx;
8900 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8903 * Wake up if we have enough events, or if a timeout occurred since we
8904 * started waiting. For timeouts, we always want to return to userspace,
8905 * regardless of event count.
8907 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8910 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8911 int wake_flags, void *key)
8913 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8917 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8918 * the task, and the next invocation will do it.
8920 if (io_should_wake(iowq) ||
8921 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
8922 return autoremove_wake_function(curr, mode, wake_flags, key);
8926 static int io_run_task_work_sig(void)
8928 if (io_run_task_work())
8930 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8931 return -ERESTARTSYS;
8932 if (task_sigpending(current))
8937 /* when returns >0, the caller should retry */
8938 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8939 struct io_wait_queue *iowq,
8943 unsigned long check_cq;
8945 /* make sure we run task_work before checking for signals */
8946 ret = io_run_task_work_sig();
8947 if (ret || io_should_wake(iowq))
8949 check_cq = READ_ONCE(ctx->check_cq);
8950 /* let the caller flush overflows, retry */
8951 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
8953 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
8955 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8961 * Wait until events become available, if we don't already have some. The
8962 * application must reap them itself, as they reside on the shared cq ring.
8964 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8965 const sigset_t __user *sig, size_t sigsz,
8966 struct __kernel_timespec __user *uts)
8968 struct io_wait_queue iowq;
8969 struct io_rings *rings = ctx->rings;
8970 ktime_t timeout = KTIME_MAX;
8974 io_cqring_overflow_flush(ctx);
8975 if (io_cqring_events(ctx) >= min_events)
8977 if (!io_run_task_work())
8982 #ifdef CONFIG_COMPAT
8983 if (in_compat_syscall())
8984 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8988 ret = set_user_sigmask(sig, sigsz);
8995 struct timespec64 ts;
8997 if (get_timespec64(&ts, uts))
8999 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9002 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9003 iowq.wq.private = current;
9004 INIT_LIST_HEAD(&iowq.wq.entry);
9006 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9007 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9009 trace_io_uring_cqring_wait(ctx, min_events);
9011 /* if we can't even flush overflow, don't wait for more */
9012 if (!io_cqring_overflow_flush(ctx)) {
9016 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9017 TASK_INTERRUPTIBLE);
9018 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9022 finish_wait(&ctx->cq_wait, &iowq.wq);
9023 restore_saved_sigmask_unless(ret == -EINTR);
9025 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9028 static void io_free_page_table(void **table, size_t size)
9030 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9032 for (i = 0; i < nr_tables; i++)
9037 static __cold void **io_alloc_page_table(size_t size)
9039 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9040 size_t init_size = size;
9043 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9047 for (i = 0; i < nr_tables; i++) {
9048 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9050 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9052 io_free_page_table(table, init_size);
9060 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9062 percpu_ref_exit(&ref_node->refs);
9066 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9068 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9069 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9070 unsigned long flags;
9071 bool first_add = false;
9072 unsigned long delay = HZ;
9074 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9077 /* if we are mid-quiesce then do not delay */
9078 if (node->rsrc_data->quiesce)
9081 while (!list_empty(&ctx->rsrc_ref_list)) {
9082 node = list_first_entry(&ctx->rsrc_ref_list,
9083 struct io_rsrc_node, node);
9084 /* recycle ref nodes in order */
9087 list_del(&node->node);
9088 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9090 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9093 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9096 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9098 struct io_rsrc_node *ref_node;
9100 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9104 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9109 INIT_LIST_HEAD(&ref_node->node);
9110 INIT_LIST_HEAD(&ref_node->rsrc_list);
9111 ref_node->done = false;
9115 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9116 struct io_rsrc_data *data_to_kill)
9117 __must_hold(&ctx->uring_lock)
9119 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9120 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9122 io_rsrc_refs_drop(ctx);
9125 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9127 rsrc_node->rsrc_data = data_to_kill;
9128 spin_lock_irq(&ctx->rsrc_ref_lock);
9129 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9130 spin_unlock_irq(&ctx->rsrc_ref_lock);
9132 atomic_inc(&data_to_kill->refs);
9133 percpu_ref_kill(&rsrc_node->refs);
9134 ctx->rsrc_node = NULL;
9137 if (!ctx->rsrc_node) {
9138 ctx->rsrc_node = ctx->rsrc_backup_node;
9139 ctx->rsrc_backup_node = NULL;
9143 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9145 if (ctx->rsrc_backup_node)
9147 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9148 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9151 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9152 struct io_ring_ctx *ctx)
9156 /* As we may drop ->uring_lock, other task may have started quiesce */
9160 data->quiesce = true;
9162 ret = io_rsrc_node_switch_start(ctx);
9165 io_rsrc_node_switch(ctx, data);
9167 /* kill initial ref, already quiesced if zero */
9168 if (atomic_dec_and_test(&data->refs))
9170 mutex_unlock(&ctx->uring_lock);
9171 flush_delayed_work(&ctx->rsrc_put_work);
9172 ret = wait_for_completion_interruptible(&data->done);
9174 mutex_lock(&ctx->uring_lock);
9175 if (atomic_read(&data->refs) > 0) {
9177 * it has been revived by another thread while
9180 mutex_unlock(&ctx->uring_lock);
9186 atomic_inc(&data->refs);
9187 /* wait for all works potentially completing data->done */
9188 flush_delayed_work(&ctx->rsrc_put_work);
9189 reinit_completion(&data->done);
9191 ret = io_run_task_work_sig();
9192 mutex_lock(&ctx->uring_lock);
9194 data->quiesce = false;
9199 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9201 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9202 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9204 return &data->tags[table_idx][off];
9207 static void io_rsrc_data_free(struct io_rsrc_data *data)
9209 size_t size = data->nr * sizeof(data->tags[0][0]);
9212 io_free_page_table((void **)data->tags, size);
9216 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9217 u64 __user *utags, unsigned nr,
9218 struct io_rsrc_data **pdata)
9220 struct io_rsrc_data *data;
9224 data = kzalloc(sizeof(*data), GFP_KERNEL);
9227 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9235 data->do_put = do_put;
9238 for (i = 0; i < nr; i++) {
9239 u64 *tag_slot = io_get_tag_slot(data, i);
9241 if (copy_from_user(tag_slot, &utags[i],
9247 atomic_set(&data->refs, 1);
9248 init_completion(&data->done);
9252 io_rsrc_data_free(data);
9256 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9258 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9259 GFP_KERNEL_ACCOUNT);
9260 return !!table->files;
9263 static void io_free_file_tables(struct io_file_table *table)
9265 kvfree(table->files);
9266 table->files = NULL;
9269 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9271 #if !defined(IO_URING_SCM_ALL)
9274 for (i = 0; i < ctx->nr_user_files; i++) {
9275 struct file *file = io_file_from_index(ctx, i);
9279 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9285 #if defined(CONFIG_UNIX)
9286 if (ctx->ring_sock) {
9287 struct sock *sock = ctx->ring_sock->sk;
9288 struct sk_buff *skb;
9290 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9294 io_free_file_tables(&ctx->file_table);
9295 io_rsrc_data_free(ctx->file_data);
9296 ctx->file_data = NULL;
9297 ctx->nr_user_files = 0;
9300 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9304 if (!ctx->file_data)
9306 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9308 __io_sqe_files_unregister(ctx);
9312 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9313 __releases(&sqd->lock)
9315 WARN_ON_ONCE(sqd->thread == current);
9318 * Do the dance but not conditional clear_bit() because it'd race with
9319 * other threads incrementing park_pending and setting the bit.
9321 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9322 if (atomic_dec_return(&sqd->park_pending))
9323 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9324 mutex_unlock(&sqd->lock);
9327 static void io_sq_thread_park(struct io_sq_data *sqd)
9328 __acquires(&sqd->lock)
9330 WARN_ON_ONCE(sqd->thread == current);
9332 atomic_inc(&sqd->park_pending);
9333 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9334 mutex_lock(&sqd->lock);
9336 wake_up_process(sqd->thread);
9339 static void io_sq_thread_stop(struct io_sq_data *sqd)
9341 WARN_ON_ONCE(sqd->thread == current);
9342 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9344 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9345 mutex_lock(&sqd->lock);
9347 wake_up_process(sqd->thread);
9348 mutex_unlock(&sqd->lock);
9349 wait_for_completion(&sqd->exited);
9352 static void io_put_sq_data(struct io_sq_data *sqd)
9354 if (refcount_dec_and_test(&sqd->refs)) {
9355 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9357 io_sq_thread_stop(sqd);
9362 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9364 struct io_sq_data *sqd = ctx->sq_data;
9367 io_sq_thread_park(sqd);
9368 list_del_init(&ctx->sqd_list);
9369 io_sqd_update_thread_idle(sqd);
9370 io_sq_thread_unpark(sqd);
9372 io_put_sq_data(sqd);
9373 ctx->sq_data = NULL;
9377 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9379 struct io_ring_ctx *ctx_attach;
9380 struct io_sq_data *sqd;
9383 f = fdget(p->wq_fd);
9385 return ERR_PTR(-ENXIO);
9386 if (f.file->f_op != &io_uring_fops) {
9388 return ERR_PTR(-EINVAL);
9391 ctx_attach = f.file->private_data;
9392 sqd = ctx_attach->sq_data;
9395 return ERR_PTR(-EINVAL);
9397 if (sqd->task_tgid != current->tgid) {
9399 return ERR_PTR(-EPERM);
9402 refcount_inc(&sqd->refs);
9407 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9410 struct io_sq_data *sqd;
9413 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9414 sqd = io_attach_sq_data(p);
9419 /* fall through for EPERM case, setup new sqd/task */
9420 if (PTR_ERR(sqd) != -EPERM)
9424 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9426 return ERR_PTR(-ENOMEM);
9428 atomic_set(&sqd->park_pending, 0);
9429 refcount_set(&sqd->refs, 1);
9430 INIT_LIST_HEAD(&sqd->ctx_list);
9431 mutex_init(&sqd->lock);
9432 init_waitqueue_head(&sqd->wait);
9433 init_completion(&sqd->exited);
9438 * Ensure the UNIX gc is aware of our file set, so we are certain that
9439 * the io_uring can be safely unregistered on process exit, even if we have
9440 * loops in the file referencing. We account only files that can hold other
9441 * files because otherwise they can't form a loop and so are not interesting
9444 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9446 #if defined(CONFIG_UNIX)
9447 struct sock *sk = ctx->ring_sock->sk;
9448 struct sk_buff_head *head = &sk->sk_receive_queue;
9449 struct scm_fp_list *fpl;
9450 struct sk_buff *skb;
9452 if (likely(!io_file_need_scm(file)))
9456 * See if we can merge this file into an existing skb SCM_RIGHTS
9457 * file set. If there's no room, fall back to allocating a new skb
9458 * and filling it in.
9460 spin_lock_irq(&head->lock);
9461 skb = skb_peek(head);
9462 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9463 __skb_unlink(skb, head);
9466 spin_unlock_irq(&head->lock);
9469 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9473 skb = alloc_skb(0, GFP_KERNEL);
9479 fpl->user = get_uid(current_user());
9480 fpl->max = SCM_MAX_FD;
9483 UNIXCB(skb).fp = fpl;
9485 skb->destructor = unix_destruct_scm;
9486 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9489 fpl = UNIXCB(skb).fp;
9490 fpl->fp[fpl->count++] = get_file(file);
9491 unix_inflight(fpl->user, file);
9492 skb_queue_head(head, skb);
9498 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9500 struct file *file = prsrc->file;
9501 #if defined(CONFIG_UNIX)
9502 struct sock *sock = ctx->ring_sock->sk;
9503 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9504 struct sk_buff *skb;
9507 if (!io_file_need_scm(file)) {
9512 __skb_queue_head_init(&list);
9515 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9516 * remove this entry and rearrange the file array.
9518 skb = skb_dequeue(head);
9520 struct scm_fp_list *fp;
9522 fp = UNIXCB(skb).fp;
9523 for (i = 0; i < fp->count; i++) {
9526 if (fp->fp[i] != file)
9529 unix_notinflight(fp->user, fp->fp[i]);
9530 left = fp->count - 1 - i;
9532 memmove(&fp->fp[i], &fp->fp[i + 1],
9533 left * sizeof(struct file *));
9540 __skb_queue_tail(&list, skb);
9550 __skb_queue_tail(&list, skb);
9552 skb = skb_dequeue(head);
9555 if (skb_peek(&list)) {
9556 spin_lock_irq(&head->lock);
9557 while ((skb = __skb_dequeue(&list)) != NULL)
9558 __skb_queue_tail(head, skb);
9559 spin_unlock_irq(&head->lock);
9566 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9568 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9569 struct io_ring_ctx *ctx = rsrc_data->ctx;
9570 struct io_rsrc_put *prsrc, *tmp;
9572 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9573 list_del(&prsrc->list);
9576 if (ctx->flags & IORING_SETUP_IOPOLL)
9577 mutex_lock(&ctx->uring_lock);
9579 spin_lock(&ctx->completion_lock);
9580 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9581 io_commit_cqring(ctx);
9582 spin_unlock(&ctx->completion_lock);
9583 io_cqring_ev_posted(ctx);
9585 if (ctx->flags & IORING_SETUP_IOPOLL)
9586 mutex_unlock(&ctx->uring_lock);
9589 rsrc_data->do_put(ctx, prsrc);
9593 io_rsrc_node_destroy(ref_node);
9594 if (atomic_dec_and_test(&rsrc_data->refs))
9595 complete(&rsrc_data->done);
9598 static void io_rsrc_put_work(struct work_struct *work)
9600 struct io_ring_ctx *ctx;
9601 struct llist_node *node;
9603 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
9604 node = llist_del_all(&ctx->rsrc_put_llist);
9607 struct io_rsrc_node *ref_node;
9608 struct llist_node *next = node->next;
9610 ref_node = llist_entry(node, struct io_rsrc_node, llist);
9611 __io_rsrc_put_work(ref_node);
9616 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
9617 unsigned nr_args, u64 __user *tags)
9619 __s32 __user *fds = (__s32 __user *) arg;
9628 if (nr_args > IORING_MAX_FIXED_FILES)
9630 if (nr_args > rlimit(RLIMIT_NOFILE))
9632 ret = io_rsrc_node_switch_start(ctx);
9635 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9640 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
9641 io_rsrc_data_free(ctx->file_data);
9642 ctx->file_data = NULL;
9646 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9647 struct io_fixed_file *file_slot;
9649 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
9653 /* allow sparse sets */
9656 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9663 if (unlikely(!file))
9667 * Don't allow io_uring instances to be registered. If UNIX
9668 * isn't enabled, then this causes a reference cycle and this
9669 * instance can never get freed. If UNIX is enabled we'll
9670 * handle it just fine, but there's still no point in allowing
9671 * a ring fd as it doesn't support regular read/write anyway.
9673 if (file->f_op == &io_uring_fops) {
9677 ret = io_scm_file_account(ctx, file);
9682 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9683 io_fixed_file_set(file_slot, file);
9686 io_rsrc_node_switch(ctx, NULL);
9689 __io_sqe_files_unregister(ctx);
9693 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9694 struct io_rsrc_node *node, void *rsrc)
9696 u64 *tag_slot = io_get_tag_slot(data, idx);
9697 struct io_rsrc_put *prsrc;
9699 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9703 prsrc->tag = *tag_slot;
9706 list_add(&prsrc->list, &node->rsrc_list);
9710 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9711 unsigned int issue_flags, u32 slot_index)
9713 struct io_ring_ctx *ctx = req->ctx;
9714 bool needs_switch = false;
9715 struct io_fixed_file *file_slot;
9718 io_ring_submit_lock(ctx, issue_flags);
9719 if (file->f_op == &io_uring_fops)
9722 if (!ctx->file_data)
9725 if (slot_index >= ctx->nr_user_files)
9728 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9729 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9731 if (file_slot->file_ptr) {
9732 struct file *old_file;
9734 ret = io_rsrc_node_switch_start(ctx);
9738 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9739 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9740 ctx->rsrc_node, old_file);
9743 file_slot->file_ptr = 0;
9744 needs_switch = true;
9747 ret = io_scm_file_account(ctx, file);
9749 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9750 io_fixed_file_set(file_slot, file);
9754 io_rsrc_node_switch(ctx, ctx->file_data);
9755 io_ring_submit_unlock(ctx, issue_flags);
9761 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9763 unsigned int offset = req->close.file_slot - 1;
9764 struct io_ring_ctx *ctx = req->ctx;
9765 struct io_fixed_file *file_slot;
9769 io_ring_submit_lock(ctx, issue_flags);
9771 if (unlikely(!ctx->file_data))
9774 if (offset >= ctx->nr_user_files)
9776 ret = io_rsrc_node_switch_start(ctx);
9780 offset = array_index_nospec(offset, ctx->nr_user_files);
9781 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9783 if (!file_slot->file_ptr)
9786 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9787 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9791 file_slot->file_ptr = 0;
9792 io_rsrc_node_switch(ctx, ctx->file_data);
9795 io_ring_submit_unlock(ctx, issue_flags);
9799 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9800 struct io_uring_rsrc_update2 *up,
9803 u64 __user *tags = u64_to_user_ptr(up->tags);
9804 __s32 __user *fds = u64_to_user_ptr(up->data);
9805 struct io_rsrc_data *data = ctx->file_data;
9806 struct io_fixed_file *file_slot;
9810 bool needs_switch = false;
9812 if (!ctx->file_data)
9814 if (up->offset + nr_args > ctx->nr_user_files)
9817 for (done = 0; done < nr_args; done++) {
9820 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9821 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9825 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9829 if (fd == IORING_REGISTER_FILES_SKIP)
9832 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9833 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9835 if (file_slot->file_ptr) {
9836 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9837 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9840 file_slot->file_ptr = 0;
9841 needs_switch = true;
9850 * Don't allow io_uring instances to be registered. If
9851 * UNIX isn't enabled, then this causes a reference
9852 * cycle and this instance can never get freed. If UNIX
9853 * is enabled we'll handle it just fine, but there's
9854 * still no point in allowing a ring fd as it doesn't
9855 * support regular read/write anyway.
9857 if (file->f_op == &io_uring_fops) {
9862 err = io_scm_file_account(ctx, file);
9867 *io_get_tag_slot(data, i) = tag;
9868 io_fixed_file_set(file_slot, file);
9873 io_rsrc_node_switch(ctx, data);
9874 return done ? done : err;
9877 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9878 struct task_struct *task)
9880 struct io_wq_hash *hash;
9881 struct io_wq_data data;
9882 unsigned int concurrency;
9884 mutex_lock(&ctx->uring_lock);
9885 hash = ctx->hash_map;
9887 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9889 mutex_unlock(&ctx->uring_lock);
9890 return ERR_PTR(-ENOMEM);
9892 refcount_set(&hash->refs, 1);
9893 init_waitqueue_head(&hash->wait);
9894 ctx->hash_map = hash;
9896 mutex_unlock(&ctx->uring_lock);
9900 data.free_work = io_wq_free_work;
9901 data.do_work = io_wq_submit_work;
9903 /* Do QD, or 4 * CPUS, whatever is smallest */
9904 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9906 return io_wq_create(concurrency, &data);
9909 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9910 struct io_ring_ctx *ctx)
9912 struct io_uring_task *tctx;
9915 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9916 if (unlikely(!tctx))
9919 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9920 sizeof(struct file *), GFP_KERNEL);
9921 if (unlikely(!tctx->registered_rings)) {
9926 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9927 if (unlikely(ret)) {
9928 kfree(tctx->registered_rings);
9933 tctx->io_wq = io_init_wq_offload(ctx, task);
9934 if (IS_ERR(tctx->io_wq)) {
9935 ret = PTR_ERR(tctx->io_wq);
9936 percpu_counter_destroy(&tctx->inflight);
9937 kfree(tctx->registered_rings);
9943 init_waitqueue_head(&tctx->wait);
9944 atomic_set(&tctx->in_idle, 0);
9945 task->io_uring = tctx;
9946 spin_lock_init(&tctx->task_lock);
9947 INIT_WQ_LIST(&tctx->task_list);
9948 INIT_WQ_LIST(&tctx->prior_task_list);
9949 init_task_work(&tctx->task_work, tctx_task_work);
9953 void __io_uring_free(struct task_struct *tsk)
9955 struct io_uring_task *tctx = tsk->io_uring;
9957 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9958 WARN_ON_ONCE(tctx->io_wq);
9959 WARN_ON_ONCE(tctx->cached_refs);
9961 kfree(tctx->registered_rings);
9962 percpu_counter_destroy(&tctx->inflight);
9964 tsk->io_uring = NULL;
9967 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9968 struct io_uring_params *p)
9972 /* Retain compatibility with failing for an invalid attach attempt */
9973 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9974 IORING_SETUP_ATTACH_WQ) {
9977 f = fdget(p->wq_fd);
9980 if (f.file->f_op != &io_uring_fops) {
9986 if (ctx->flags & IORING_SETUP_SQPOLL) {
9987 struct task_struct *tsk;
9988 struct io_sq_data *sqd;
9991 ret = security_uring_sqpoll();
9995 sqd = io_get_sq_data(p, &attached);
10001 ctx->sq_creds = get_current_cred();
10002 ctx->sq_data = sqd;
10003 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10004 if (!ctx->sq_thread_idle)
10005 ctx->sq_thread_idle = HZ;
10007 io_sq_thread_park(sqd);
10008 list_add(&ctx->sqd_list, &sqd->ctx_list);
10009 io_sqd_update_thread_idle(sqd);
10010 /* don't attach to a dying SQPOLL thread, would be racy */
10011 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10012 io_sq_thread_unpark(sqd);
10019 if (p->flags & IORING_SETUP_SQ_AFF) {
10020 int cpu = p->sq_thread_cpu;
10023 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10030 sqd->task_pid = current->pid;
10031 sqd->task_tgid = current->tgid;
10032 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10034 ret = PTR_ERR(tsk);
10039 ret = io_uring_alloc_task_context(tsk, ctx);
10040 wake_up_new_task(tsk);
10043 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10044 /* Can't have SQ_AFF without SQPOLL */
10051 complete(&ctx->sq_data->exited);
10053 io_sq_thread_finish(ctx);
10057 static inline void __io_unaccount_mem(struct user_struct *user,
10058 unsigned long nr_pages)
10060 atomic_long_sub(nr_pages, &user->locked_vm);
10063 static inline int __io_account_mem(struct user_struct *user,
10064 unsigned long nr_pages)
10066 unsigned long page_limit, cur_pages, new_pages;
10068 /* Don't allow more pages than we can safely lock */
10069 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10072 cur_pages = atomic_long_read(&user->locked_vm);
10073 new_pages = cur_pages + nr_pages;
10074 if (new_pages > page_limit)
10076 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10077 new_pages) != cur_pages);
10082 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10085 __io_unaccount_mem(ctx->user, nr_pages);
10087 if (ctx->mm_account)
10088 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10091 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10096 ret = __io_account_mem(ctx->user, nr_pages);
10101 if (ctx->mm_account)
10102 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10107 static void io_mem_free(void *ptr)
10114 page = virt_to_head_page(ptr);
10115 if (put_page_testzero(page))
10116 free_compound_page(page);
10119 static void *io_mem_alloc(size_t size)
10121 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10123 return (void *) __get_free_pages(gfp, get_order(size));
10126 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10127 unsigned int cq_entries, size_t *sq_offset)
10129 struct io_rings *rings;
10130 size_t off, sq_array_size;
10132 off = struct_size(rings, cqes, cq_entries);
10133 if (off == SIZE_MAX)
10135 if (ctx->flags & IORING_SETUP_CQE32) {
10136 if (check_shl_overflow(off, 1, &off))
10141 off = ALIGN(off, SMP_CACHE_BYTES);
10149 sq_array_size = array_size(sizeof(u32), sq_entries);
10150 if (sq_array_size == SIZE_MAX)
10153 if (check_add_overflow(off, sq_array_size, &off))
10159 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10161 struct io_mapped_ubuf *imu = *slot;
10164 if (imu != ctx->dummy_ubuf) {
10165 for (i = 0; i < imu->nr_bvecs; i++)
10166 unpin_user_page(imu->bvec[i].bv_page);
10167 if (imu->acct_pages)
10168 io_unaccount_mem(ctx, imu->acct_pages);
10174 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10176 io_buffer_unmap(ctx, &prsrc->buf);
10180 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10184 for (i = 0; i < ctx->nr_user_bufs; i++)
10185 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10186 kfree(ctx->user_bufs);
10187 io_rsrc_data_free(ctx->buf_data);
10188 ctx->user_bufs = NULL;
10189 ctx->buf_data = NULL;
10190 ctx->nr_user_bufs = 0;
10193 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10197 if (!ctx->buf_data)
10200 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10202 __io_sqe_buffers_unregister(ctx);
10206 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10207 void __user *arg, unsigned index)
10209 struct iovec __user *src;
10211 #ifdef CONFIG_COMPAT
10213 struct compat_iovec __user *ciovs;
10214 struct compat_iovec ciov;
10216 ciovs = (struct compat_iovec __user *) arg;
10217 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10220 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10221 dst->iov_len = ciov.iov_len;
10225 src = (struct iovec __user *) arg;
10226 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10232 * Not super efficient, but this is just a registration time. And we do cache
10233 * the last compound head, so generally we'll only do a full search if we don't
10236 * We check if the given compound head page has already been accounted, to
10237 * avoid double accounting it. This allows us to account the full size of the
10238 * page, not just the constituent pages of a huge page.
10240 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10241 int nr_pages, struct page *hpage)
10245 /* check current page array */
10246 for (i = 0; i < nr_pages; i++) {
10247 if (!PageCompound(pages[i]))
10249 if (compound_head(pages[i]) == hpage)
10253 /* check previously registered pages */
10254 for (i = 0; i < ctx->nr_user_bufs; i++) {
10255 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10257 for (j = 0; j < imu->nr_bvecs; j++) {
10258 if (!PageCompound(imu->bvec[j].bv_page))
10260 if (compound_head(imu->bvec[j].bv_page) == hpage)
10268 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10269 int nr_pages, struct io_mapped_ubuf *imu,
10270 struct page **last_hpage)
10274 imu->acct_pages = 0;
10275 for (i = 0; i < nr_pages; i++) {
10276 if (!PageCompound(pages[i])) {
10279 struct page *hpage;
10281 hpage = compound_head(pages[i]);
10282 if (hpage == *last_hpage)
10284 *last_hpage = hpage;
10285 if (headpage_already_acct(ctx, pages, i, hpage))
10287 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10291 if (!imu->acct_pages)
10294 ret = io_account_mem(ctx, imu->acct_pages);
10296 imu->acct_pages = 0;
10300 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10301 struct io_mapped_ubuf **pimu,
10302 struct page **last_hpage)
10304 struct io_mapped_ubuf *imu = NULL;
10305 struct vm_area_struct **vmas = NULL;
10306 struct page **pages = NULL;
10307 unsigned long off, start, end, ubuf;
10309 int ret, pret, nr_pages, i;
10311 if (!iov->iov_base) {
10312 *pimu = ctx->dummy_ubuf;
10316 ubuf = (unsigned long) iov->iov_base;
10317 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10318 start = ubuf >> PAGE_SHIFT;
10319 nr_pages = end - start;
10324 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10328 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10333 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10338 mmap_read_lock(current->mm);
10339 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10341 if (pret == nr_pages) {
10342 /* don't support file backed memory */
10343 for (i = 0; i < nr_pages; i++) {
10344 struct vm_area_struct *vma = vmas[i];
10346 if (vma_is_shmem(vma))
10348 if (vma->vm_file &&
10349 !is_file_hugepages(vma->vm_file)) {
10355 ret = pret < 0 ? pret : -EFAULT;
10357 mmap_read_unlock(current->mm);
10360 * if we did partial map, or found file backed vmas,
10361 * release any pages we did get
10364 unpin_user_pages(pages, pret);
10368 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
10370 unpin_user_pages(pages, pret);
10374 off = ubuf & ~PAGE_MASK;
10375 size = iov->iov_len;
10376 for (i = 0; i < nr_pages; i++) {
10379 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10380 imu->bvec[i].bv_page = pages[i];
10381 imu->bvec[i].bv_len = vec_len;
10382 imu->bvec[i].bv_offset = off;
10386 /* store original address for later verification */
10388 imu->ubuf_end = ubuf + iov->iov_len;
10389 imu->nr_bvecs = nr_pages;
10400 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10402 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10403 return ctx->user_bufs ? 0 : -ENOMEM;
10406 static int io_buffer_validate(struct iovec *iov)
10408 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10411 * Don't impose further limits on the size and buffer
10412 * constraints here, we'll -EINVAL later when IO is
10413 * submitted if they are wrong.
10415 if (!iov->iov_base)
10416 return iov->iov_len ? -EFAULT : 0;
10420 /* arbitrary limit, but we need something */
10421 if (iov->iov_len > SZ_1G)
10424 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10430 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10431 unsigned int nr_args, u64 __user *tags)
10433 struct page *last_hpage = NULL;
10434 struct io_rsrc_data *data;
10438 if (ctx->user_bufs)
10440 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10442 ret = io_rsrc_node_switch_start(ctx);
10445 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10448 ret = io_buffers_map_alloc(ctx, nr_args);
10450 io_rsrc_data_free(data);
10454 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10455 ret = io_copy_iov(ctx, &iov, arg, i);
10458 ret = io_buffer_validate(&iov);
10461 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10466 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10472 WARN_ON_ONCE(ctx->buf_data);
10474 ctx->buf_data = data;
10476 __io_sqe_buffers_unregister(ctx);
10478 io_rsrc_node_switch(ctx, NULL);
10482 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10483 struct io_uring_rsrc_update2 *up,
10484 unsigned int nr_args)
10486 u64 __user *tags = u64_to_user_ptr(up->tags);
10487 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10488 struct page *last_hpage = NULL;
10489 bool needs_switch = false;
10493 if (!ctx->buf_data)
10495 if (up->offset + nr_args > ctx->nr_user_bufs)
10498 for (done = 0; done < nr_args; done++) {
10499 struct io_mapped_ubuf *imu;
10500 int offset = up->offset + done;
10503 err = io_copy_iov(ctx, &iov, iovs, done);
10506 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10510 err = io_buffer_validate(&iov);
10513 if (!iov.iov_base && tag) {
10517 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10521 i = array_index_nospec(offset, ctx->nr_user_bufs);
10522 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10523 err = io_queue_rsrc_removal(ctx->buf_data, i,
10524 ctx->rsrc_node, ctx->user_bufs[i]);
10525 if (unlikely(err)) {
10526 io_buffer_unmap(ctx, &imu);
10529 ctx->user_bufs[i] = NULL;
10530 needs_switch = true;
10533 ctx->user_bufs[i] = imu;
10534 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10538 io_rsrc_node_switch(ctx, ctx->buf_data);
10539 return done ? done : err;
10542 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10543 unsigned int eventfd_async)
10545 struct io_ev_fd *ev_fd;
10546 __s32 __user *fds = arg;
10549 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10550 lockdep_is_held(&ctx->uring_lock));
10554 if (copy_from_user(&fd, fds, sizeof(*fds)))
10557 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10561 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10562 if (IS_ERR(ev_fd->cq_ev_fd)) {
10563 int ret = PTR_ERR(ev_fd->cq_ev_fd);
10567 ev_fd->eventfd_async = eventfd_async;
10568 ctx->has_evfd = true;
10569 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10573 static void io_eventfd_put(struct rcu_head *rcu)
10575 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10577 eventfd_ctx_put(ev_fd->cq_ev_fd);
10581 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10583 struct io_ev_fd *ev_fd;
10585 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10586 lockdep_is_held(&ctx->uring_lock));
10588 ctx->has_evfd = false;
10589 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10590 call_rcu(&ev_fd->rcu, io_eventfd_put);
10597 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10599 struct io_buffer_list *bl;
10600 unsigned long index;
10603 for (i = 0; i < BGID_ARRAY; i++) {
10606 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
10609 xa_for_each(&ctx->io_bl_xa, index, bl) {
10610 xa_erase(&ctx->io_bl_xa, bl->bgid);
10611 __io_remove_buffers(ctx, bl, -1U);
10614 while (!list_empty(&ctx->io_buffers_pages)) {
10617 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10618 list_del_init(&page->lru);
10623 static void io_req_caches_free(struct io_ring_ctx *ctx)
10625 struct io_submit_state *state = &ctx->submit_state;
10628 mutex_lock(&ctx->uring_lock);
10629 io_flush_cached_locked_reqs(ctx, state);
10631 while (!io_req_cache_empty(ctx)) {
10632 struct io_wq_work_node *node;
10633 struct io_kiocb *req;
10635 node = wq_stack_extract(&state->free_list);
10636 req = container_of(node, struct io_kiocb, comp_list);
10637 kmem_cache_free(req_cachep, req);
10641 percpu_ref_put_many(&ctx->refs, nr);
10642 mutex_unlock(&ctx->uring_lock);
10645 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10647 if (data && !atomic_dec_and_test(&data->refs))
10648 wait_for_completion(&data->done);
10651 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10653 struct async_poll *apoll;
10655 while (!list_empty(&ctx->apoll_cache)) {
10656 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10658 list_del(&apoll->poll.wait.entry);
10663 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10665 io_sq_thread_finish(ctx);
10667 if (ctx->mm_account) {
10668 mmdrop(ctx->mm_account);
10669 ctx->mm_account = NULL;
10672 io_rsrc_refs_drop(ctx);
10673 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10674 io_wait_rsrc_data(ctx->buf_data);
10675 io_wait_rsrc_data(ctx->file_data);
10677 mutex_lock(&ctx->uring_lock);
10679 __io_sqe_buffers_unregister(ctx);
10680 if (ctx->file_data)
10681 __io_sqe_files_unregister(ctx);
10683 __io_cqring_overflow_flush(ctx, true);
10684 io_eventfd_unregister(ctx);
10685 io_flush_apoll_cache(ctx);
10686 mutex_unlock(&ctx->uring_lock);
10687 io_destroy_buffers(ctx);
10689 put_cred(ctx->sq_creds);
10691 /* there are no registered resources left, nobody uses it */
10692 if (ctx->rsrc_node)
10693 io_rsrc_node_destroy(ctx->rsrc_node);
10694 if (ctx->rsrc_backup_node)
10695 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10696 flush_delayed_work(&ctx->rsrc_put_work);
10697 flush_delayed_work(&ctx->fallback_work);
10699 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10700 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10702 #if defined(CONFIG_UNIX)
10703 if (ctx->ring_sock) {
10704 ctx->ring_sock->file = NULL; /* so that iput() is called */
10705 sock_release(ctx->ring_sock);
10708 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10710 io_mem_free(ctx->rings);
10711 io_mem_free(ctx->sq_sqes);
10713 percpu_ref_exit(&ctx->refs);
10714 free_uid(ctx->user);
10715 io_req_caches_free(ctx);
10717 io_wq_put_hash(ctx->hash_map);
10718 kfree(ctx->cancel_hash);
10719 kfree(ctx->dummy_ubuf);
10721 xa_destroy(&ctx->io_bl_xa);
10725 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10727 struct io_ring_ctx *ctx = file->private_data;
10730 poll_wait(file, &ctx->cq_wait, wait);
10732 * synchronizes with barrier from wq_has_sleeper call in
10736 if (!io_sqring_full(ctx))
10737 mask |= EPOLLOUT | EPOLLWRNORM;
10740 * Don't flush cqring overflow list here, just do a simple check.
10741 * Otherwise there could possible be ABBA deadlock:
10744 * lock(&ctx->uring_lock);
10746 * lock(&ctx->uring_lock);
10749 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10750 * pushs them to do the flush.
10752 if (io_cqring_events(ctx) ||
10753 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
10754 mask |= EPOLLIN | EPOLLRDNORM;
10759 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10761 const struct cred *creds;
10763 creds = xa_erase(&ctx->personalities, id);
10772 struct io_tctx_exit {
10773 struct callback_head task_work;
10774 struct completion completion;
10775 struct io_ring_ctx *ctx;
10778 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10780 struct io_uring_task *tctx = current->io_uring;
10781 struct io_tctx_exit *work;
10783 work = container_of(cb, struct io_tctx_exit, task_work);
10785 * When @in_idle, we're in cancellation and it's racy to remove the
10786 * node. It'll be removed by the end of cancellation, just ignore it.
10788 if (!atomic_read(&tctx->in_idle))
10789 io_uring_del_tctx_node((unsigned long)work->ctx);
10790 complete(&work->completion);
10793 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10795 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10797 return req->ctx == data;
10800 static __cold void io_ring_exit_work(struct work_struct *work)
10802 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10803 unsigned long timeout = jiffies + HZ * 60 * 5;
10804 unsigned long interval = HZ / 20;
10805 struct io_tctx_exit exit;
10806 struct io_tctx_node *node;
10810 * If we're doing polled IO and end up having requests being
10811 * submitted async (out-of-line), then completions can come in while
10812 * we're waiting for refs to drop. We need to reap these manually,
10813 * as nobody else will be looking for them.
10816 io_uring_try_cancel_requests(ctx, NULL, true);
10817 if (ctx->sq_data) {
10818 struct io_sq_data *sqd = ctx->sq_data;
10819 struct task_struct *tsk;
10821 io_sq_thread_park(sqd);
10823 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10824 io_wq_cancel_cb(tsk->io_uring->io_wq,
10825 io_cancel_ctx_cb, ctx, true);
10826 io_sq_thread_unpark(sqd);
10829 io_req_caches_free(ctx);
10831 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10832 /* there is little hope left, don't run it too often */
10833 interval = HZ * 60;
10835 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10837 init_completion(&exit.completion);
10838 init_task_work(&exit.task_work, io_tctx_exit_cb);
10841 * Some may use context even when all refs and requests have been put,
10842 * and they are free to do so while still holding uring_lock or
10843 * completion_lock, see io_req_task_submit(). Apart from other work,
10844 * this lock/unlock section also waits them to finish.
10846 mutex_lock(&ctx->uring_lock);
10847 while (!list_empty(&ctx->tctx_list)) {
10848 WARN_ON_ONCE(time_after(jiffies, timeout));
10850 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10852 /* don't spin on a single task if cancellation failed */
10853 list_rotate_left(&ctx->tctx_list);
10854 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10855 if (WARN_ON_ONCE(ret))
10858 mutex_unlock(&ctx->uring_lock);
10859 wait_for_completion(&exit.completion);
10860 mutex_lock(&ctx->uring_lock);
10862 mutex_unlock(&ctx->uring_lock);
10863 spin_lock(&ctx->completion_lock);
10864 spin_unlock(&ctx->completion_lock);
10866 io_ring_ctx_free(ctx);
10869 /* Returns true if we found and killed one or more timeouts */
10870 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10871 struct task_struct *tsk, bool cancel_all)
10873 struct io_kiocb *req, *tmp;
10876 spin_lock(&ctx->completion_lock);
10877 spin_lock_irq(&ctx->timeout_lock);
10878 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10879 if (io_match_task(req, tsk, cancel_all)) {
10880 io_kill_timeout(req, -ECANCELED);
10884 spin_unlock_irq(&ctx->timeout_lock);
10885 io_commit_cqring(ctx);
10886 spin_unlock(&ctx->completion_lock);
10888 io_cqring_ev_posted(ctx);
10889 return canceled != 0;
10892 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10894 unsigned long index;
10895 struct creds *creds;
10897 mutex_lock(&ctx->uring_lock);
10898 percpu_ref_kill(&ctx->refs);
10900 __io_cqring_overflow_flush(ctx, true);
10901 xa_for_each(&ctx->personalities, index, creds)
10902 io_unregister_personality(ctx, index);
10903 mutex_unlock(&ctx->uring_lock);
10905 /* failed during ring init, it couldn't have issued any requests */
10907 io_kill_timeouts(ctx, NULL, true);
10908 io_poll_remove_all(ctx, NULL, true);
10909 /* if we failed setting up the ctx, we might not have any rings */
10910 io_iopoll_try_reap_events(ctx);
10913 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10915 * Use system_unbound_wq to avoid spawning tons of event kworkers
10916 * if we're exiting a ton of rings at the same time. It just adds
10917 * noise and overhead, there's no discernable change in runtime
10918 * over using system_wq.
10920 queue_work(system_unbound_wq, &ctx->exit_work);
10923 static int io_uring_release(struct inode *inode, struct file *file)
10925 struct io_ring_ctx *ctx = file->private_data;
10927 file->private_data = NULL;
10928 io_ring_ctx_wait_and_kill(ctx);
10932 struct io_task_cancel {
10933 struct task_struct *task;
10937 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10939 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10940 struct io_task_cancel *cancel = data;
10942 return io_match_task_safe(req, cancel->task, cancel->all);
10945 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10946 struct task_struct *task,
10949 struct io_defer_entry *de;
10952 spin_lock(&ctx->completion_lock);
10953 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10954 if (io_match_task_safe(de->req, task, cancel_all)) {
10955 list_cut_position(&list, &ctx->defer_list, &de->list);
10959 spin_unlock(&ctx->completion_lock);
10960 if (list_empty(&list))
10963 while (!list_empty(&list)) {
10964 de = list_first_entry(&list, struct io_defer_entry, list);
10965 list_del_init(&de->list);
10966 io_req_complete_failed(de->req, -ECANCELED);
10972 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10974 struct io_tctx_node *node;
10975 enum io_wq_cancel cret;
10978 mutex_lock(&ctx->uring_lock);
10979 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10980 struct io_uring_task *tctx = node->task->io_uring;
10983 * io_wq will stay alive while we hold uring_lock, because it's
10984 * killed after ctx nodes, which requires to take the lock.
10986 if (!tctx || !tctx->io_wq)
10988 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10989 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10991 mutex_unlock(&ctx->uring_lock);
10996 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10997 struct task_struct *task,
11000 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11001 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11003 /* failed during ring init, it couldn't have issued any requests */
11008 enum io_wq_cancel cret;
11012 ret |= io_uring_try_cancel_iowq(ctx);
11013 } else if (tctx && tctx->io_wq) {
11015 * Cancels requests of all rings, not only @ctx, but
11016 * it's fine as the task is in exit/exec.
11018 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11020 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11023 /* SQPOLL thread does its own polling */
11024 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11025 (ctx->sq_data && ctx->sq_data->thread == current)) {
11026 while (!wq_list_empty(&ctx->iopoll_list)) {
11027 io_iopoll_try_reap_events(ctx);
11032 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11033 ret |= io_poll_remove_all(ctx, task, cancel_all);
11034 ret |= io_kill_timeouts(ctx, task, cancel_all);
11036 ret |= io_run_task_work();
11043 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11045 struct io_uring_task *tctx = current->io_uring;
11046 struct io_tctx_node *node;
11049 if (unlikely(!tctx)) {
11050 ret = io_uring_alloc_task_context(current, ctx);
11054 tctx = current->io_uring;
11055 if (ctx->iowq_limits_set) {
11056 unsigned int limits[2] = { ctx->iowq_limits[0],
11057 ctx->iowq_limits[1], };
11059 ret = io_wq_max_workers(tctx->io_wq, limits);
11064 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11065 node = kmalloc(sizeof(*node), GFP_KERNEL);
11069 node->task = current;
11071 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11072 node, GFP_KERNEL));
11078 mutex_lock(&ctx->uring_lock);
11079 list_add(&node->ctx_node, &ctx->tctx_list);
11080 mutex_unlock(&ctx->uring_lock);
11087 * Note that this task has used io_uring. We use it for cancelation purposes.
11089 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11091 struct io_uring_task *tctx = current->io_uring;
11093 if (likely(tctx && tctx->last == ctx))
11095 return __io_uring_add_tctx_node(ctx);
11099 * Remove this io_uring_file -> task mapping.
11101 static __cold void io_uring_del_tctx_node(unsigned long index)
11103 struct io_uring_task *tctx = current->io_uring;
11104 struct io_tctx_node *node;
11108 node = xa_erase(&tctx->xa, index);
11112 WARN_ON_ONCE(current != node->task);
11113 WARN_ON_ONCE(list_empty(&node->ctx_node));
11115 mutex_lock(&node->ctx->uring_lock);
11116 list_del(&node->ctx_node);
11117 mutex_unlock(&node->ctx->uring_lock);
11119 if (tctx->last == node->ctx)
11124 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11126 struct io_wq *wq = tctx->io_wq;
11127 struct io_tctx_node *node;
11128 unsigned long index;
11130 xa_for_each(&tctx->xa, index, node) {
11131 io_uring_del_tctx_node(index);
11136 * Must be after io_uring_del_tctx_node() (removes nodes under
11137 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11139 io_wq_put_and_exit(wq);
11140 tctx->io_wq = NULL;
11144 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11148 return percpu_counter_sum(&tctx->inflight);
11152 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11153 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11155 static __cold void io_uring_cancel_generic(bool cancel_all,
11156 struct io_sq_data *sqd)
11158 struct io_uring_task *tctx = current->io_uring;
11159 struct io_ring_ctx *ctx;
11163 WARN_ON_ONCE(sqd && sqd->thread != current);
11165 if (!current->io_uring)
11168 io_wq_exit_start(tctx->io_wq);
11170 atomic_inc(&tctx->in_idle);
11172 io_uring_drop_tctx_refs(current);
11173 /* read completions before cancelations */
11174 inflight = tctx_inflight(tctx, !cancel_all);
11179 struct io_tctx_node *node;
11180 unsigned long index;
11182 xa_for_each(&tctx->xa, index, node) {
11183 /* sqpoll task will cancel all its requests */
11184 if (node->ctx->sq_data)
11186 io_uring_try_cancel_requests(node->ctx, current,
11190 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11191 io_uring_try_cancel_requests(ctx, current,
11195 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11196 io_run_task_work();
11197 io_uring_drop_tctx_refs(current);
11200 * If we've seen completions, retry without waiting. This
11201 * avoids a race where a completion comes in before we did
11202 * prepare_to_wait().
11204 if (inflight == tctx_inflight(tctx, !cancel_all))
11206 finish_wait(&tctx->wait, &wait);
11209 io_uring_clean_tctx(tctx);
11212 * We shouldn't run task_works after cancel, so just leave
11213 * ->in_idle set for normal exit.
11215 atomic_dec(&tctx->in_idle);
11216 /* for exec all current's requests should be gone, kill tctx */
11217 __io_uring_free(current);
11221 void __io_uring_cancel(bool cancel_all)
11223 io_uring_cancel_generic(cancel_all, NULL);
11226 void io_uring_unreg_ringfd(void)
11228 struct io_uring_task *tctx = current->io_uring;
11231 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11232 if (tctx->registered_rings[i]) {
11233 fput(tctx->registered_rings[i]);
11234 tctx->registered_rings[i] = NULL;
11239 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11240 int start, int end)
11245 for (offset = start; offset < end; offset++) {
11246 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11247 if (tctx->registered_rings[offset])
11253 } else if (file->f_op != &io_uring_fops) {
11255 return -EOPNOTSUPP;
11257 tctx->registered_rings[offset] = file;
11265 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11266 * invocation. User passes in an array of struct io_uring_rsrc_update
11267 * with ->data set to the ring_fd, and ->offset given for the desired
11268 * index. If no index is desired, application may set ->offset == -1U
11269 * and we'll find an available index. Returns number of entries
11270 * successfully processed, or < 0 on error if none were processed.
11272 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11275 struct io_uring_rsrc_update __user *arg = __arg;
11276 struct io_uring_rsrc_update reg;
11277 struct io_uring_task *tctx;
11280 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11283 mutex_unlock(&ctx->uring_lock);
11284 ret = io_uring_add_tctx_node(ctx);
11285 mutex_lock(&ctx->uring_lock);
11289 tctx = current->io_uring;
11290 for (i = 0; i < nr_args; i++) {
11293 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11303 if (reg.offset == -1U) {
11305 end = IO_RINGFD_REG_MAX;
11307 if (reg.offset >= IO_RINGFD_REG_MAX) {
11311 start = reg.offset;
11315 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11320 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11321 fput(tctx->registered_rings[reg.offset]);
11322 tctx->registered_rings[reg.offset] = NULL;
11328 return i ? i : ret;
11331 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11334 struct io_uring_rsrc_update __user *arg = __arg;
11335 struct io_uring_task *tctx = current->io_uring;
11336 struct io_uring_rsrc_update reg;
11339 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11344 for (i = 0; i < nr_args; i++) {
11345 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11349 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11354 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11355 if (tctx->registered_rings[reg.offset]) {
11356 fput(tctx->registered_rings[reg.offset]);
11357 tctx->registered_rings[reg.offset] = NULL;
11361 return i ? i : ret;
11364 static void *io_uring_validate_mmap_request(struct file *file,
11365 loff_t pgoff, size_t sz)
11367 struct io_ring_ctx *ctx = file->private_data;
11368 loff_t offset = pgoff << PAGE_SHIFT;
11373 case IORING_OFF_SQ_RING:
11374 case IORING_OFF_CQ_RING:
11377 case IORING_OFF_SQES:
11378 ptr = ctx->sq_sqes;
11381 return ERR_PTR(-EINVAL);
11384 page = virt_to_head_page(ptr);
11385 if (sz > page_size(page))
11386 return ERR_PTR(-EINVAL);
11393 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11395 size_t sz = vma->vm_end - vma->vm_start;
11399 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11401 return PTR_ERR(ptr);
11403 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11404 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11407 #else /* !CONFIG_MMU */
11409 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11411 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11414 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11416 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11419 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11420 unsigned long addr, unsigned long len,
11421 unsigned long pgoff, unsigned long flags)
11425 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11427 return PTR_ERR(ptr);
11429 return (unsigned long) ptr;
11432 #endif /* !CONFIG_MMU */
11434 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11439 if (!io_sqring_full(ctx))
11441 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11443 if (!io_sqring_full(ctx))
11446 } while (!signal_pending(current));
11448 finish_wait(&ctx->sqo_sq_wait, &wait);
11452 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11454 if (flags & IORING_ENTER_EXT_ARG) {
11455 struct io_uring_getevents_arg arg;
11457 if (argsz != sizeof(arg))
11459 if (copy_from_user(&arg, argp, sizeof(arg)))
11465 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11466 struct __kernel_timespec __user **ts,
11467 const sigset_t __user **sig)
11469 struct io_uring_getevents_arg arg;
11472 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11473 * is just a pointer to the sigset_t.
11475 if (!(flags & IORING_ENTER_EXT_ARG)) {
11476 *sig = (const sigset_t __user *) argp;
11482 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11483 * timespec and sigset_t pointers if good.
11485 if (*argsz != sizeof(arg))
11487 if (copy_from_user(&arg, argp, sizeof(arg)))
11491 *sig = u64_to_user_ptr(arg.sigmask);
11492 *argsz = arg.sigmask_sz;
11493 *ts = u64_to_user_ptr(arg.ts);
11497 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11498 u32, min_complete, u32, flags, const void __user *, argp,
11501 struct io_ring_ctx *ctx;
11505 io_run_task_work();
11507 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11508 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11509 IORING_ENTER_REGISTERED_RING)))
11513 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11514 * need only dereference our task private array to find it.
11516 if (flags & IORING_ENTER_REGISTERED_RING) {
11517 struct io_uring_task *tctx = current->io_uring;
11519 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11521 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11522 f.file = tctx->registered_rings[fd];
11523 if (unlikely(!f.file))
11527 if (unlikely(!f.file))
11532 if (unlikely(f.file->f_op != &io_uring_fops))
11536 ctx = f.file->private_data;
11537 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11541 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11545 * For SQ polling, the thread will do all submissions and completions.
11546 * Just return the requested submit count, and wake the thread if
11547 * we were asked to.
11550 if (ctx->flags & IORING_SETUP_SQPOLL) {
11551 io_cqring_overflow_flush(ctx);
11553 if (unlikely(ctx->sq_data->thread == NULL)) {
11557 if (flags & IORING_ENTER_SQ_WAKEUP)
11558 wake_up(&ctx->sq_data->wait);
11559 if (flags & IORING_ENTER_SQ_WAIT) {
11560 ret = io_sqpoll_wait_sq(ctx);
11565 } else if (to_submit) {
11566 ret = io_uring_add_tctx_node(ctx);
11570 mutex_lock(&ctx->uring_lock);
11571 ret = io_submit_sqes(ctx, to_submit);
11572 if (ret != to_submit) {
11573 mutex_unlock(&ctx->uring_lock);
11576 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
11577 goto iopoll_locked;
11578 mutex_unlock(&ctx->uring_lock);
11580 if (flags & IORING_ENTER_GETEVENTS) {
11582 if (ctx->syscall_iopoll) {
11584 * We disallow the app entering submit/complete with
11585 * polling, but we still need to lock the ring to
11586 * prevent racing with polled issue that got punted to
11589 mutex_lock(&ctx->uring_lock);
11591 ret2 = io_validate_ext_arg(flags, argp, argsz);
11592 if (likely(!ret2)) {
11593 min_complete = min(min_complete,
11595 ret2 = io_iopoll_check(ctx, min_complete);
11597 mutex_unlock(&ctx->uring_lock);
11599 const sigset_t __user *sig;
11600 struct __kernel_timespec __user *ts;
11602 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
11603 if (likely(!ret2)) {
11604 min_complete = min(min_complete,
11606 ret2 = io_cqring_wait(ctx, min_complete, sig,
11615 * EBADR indicates that one or more CQE were dropped.
11616 * Once the user has been informed we can clear the bit
11617 * as they are obviously ok with those drops.
11619 if (unlikely(ret2 == -EBADR))
11620 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
11626 percpu_ref_put(&ctx->refs);
11628 if (!(flags & IORING_ENTER_REGISTERED_RING))
11633 #ifdef CONFIG_PROC_FS
11634 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11635 const struct cred *cred)
11637 struct user_namespace *uns = seq_user_ns(m);
11638 struct group_info *gi;
11643 seq_printf(m, "%5d\n", id);
11644 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11645 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11646 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11647 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11648 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11649 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11650 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11651 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11652 seq_puts(m, "\n\tGroups:\t");
11653 gi = cred->group_info;
11654 for (g = 0; g < gi->ngroups; g++) {
11655 seq_put_decimal_ull(m, g ? " " : "",
11656 from_kgid_munged(uns, gi->gid[g]));
11658 seq_puts(m, "\n\tCapEff:\t");
11659 cap = cred->cap_effective;
11660 CAP_FOR_EACH_U32(__capi)
11661 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11666 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11667 struct seq_file *m)
11669 struct io_sq_data *sq = NULL;
11670 struct io_overflow_cqe *ocqe;
11671 struct io_rings *r = ctx->rings;
11672 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11673 unsigned int sq_head = READ_ONCE(r->sq.head);
11674 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11675 unsigned int cq_head = READ_ONCE(r->cq.head);
11676 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11677 unsigned int cq_shift = 0;
11678 unsigned int sq_entries, cq_entries;
11680 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
11687 * we may get imprecise sqe and cqe info if uring is actively running
11688 * since we get cached_sq_head and cached_cq_tail without uring_lock
11689 * and sq_tail and cq_head are changed by userspace. But it's ok since
11690 * we usually use these info when it is stuck.
11692 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11693 seq_printf(m, "SqHead:\t%u\n", sq_head);
11694 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11695 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11696 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11697 seq_printf(m, "CqHead:\t%u\n", cq_head);
11698 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11699 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11700 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11701 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11702 for (i = 0; i < sq_entries; i++) {
11703 unsigned int entry = i + sq_head;
11704 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11705 struct io_uring_sqe *sqe;
11707 if (sq_idx > sq_mask)
11709 sqe = &ctx->sq_sqes[sq_idx];
11710 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11711 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11714 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11715 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11716 for (i = 0; i < cq_entries; i++) {
11717 unsigned int entry = i + cq_head;
11718 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
11721 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11722 entry & cq_mask, cqe->user_data, cqe->res,
11725 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
11726 "extra1:%llu, extra2:%llu\n",
11727 entry & cq_mask, cqe->user_data, cqe->res,
11728 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
11733 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11734 * since fdinfo case grabs it in the opposite direction of normal use
11735 * cases. If we fail to get the lock, we just don't iterate any
11736 * structures that could be going away outside the io_uring mutex.
11738 has_lock = mutex_trylock(&ctx->uring_lock);
11740 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11746 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11747 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11748 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11749 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11750 struct file *f = io_file_from_index(ctx, i);
11753 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11755 seq_printf(m, "%5u: <none>\n", i);
11757 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11758 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11759 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11760 unsigned int len = buf->ubuf_end - buf->ubuf;
11762 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11764 if (has_lock && !xa_empty(&ctx->personalities)) {
11765 unsigned long index;
11766 const struct cred *cred;
11768 seq_printf(m, "Personalities:\n");
11769 xa_for_each(&ctx->personalities, index, cred)
11770 io_uring_show_cred(m, index, cred);
11773 mutex_unlock(&ctx->uring_lock);
11775 seq_puts(m, "PollList:\n");
11776 spin_lock(&ctx->completion_lock);
11777 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11778 struct hlist_head *list = &ctx->cancel_hash[i];
11779 struct io_kiocb *req;
11781 hlist_for_each_entry(req, list, hash_node)
11782 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11783 task_work_pending(req->task));
11786 seq_puts(m, "CqOverflowList:\n");
11787 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11788 struct io_uring_cqe *cqe = &ocqe->cqe;
11790 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11791 cqe->user_data, cqe->res, cqe->flags);
11795 spin_unlock(&ctx->completion_lock);
11798 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11800 struct io_ring_ctx *ctx = f->private_data;
11802 if (percpu_ref_tryget(&ctx->refs)) {
11803 __io_uring_show_fdinfo(ctx, m);
11804 percpu_ref_put(&ctx->refs);
11809 static const struct file_operations io_uring_fops = {
11810 .release = io_uring_release,
11811 .mmap = io_uring_mmap,
11813 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11814 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11816 .poll = io_uring_poll,
11817 #ifdef CONFIG_PROC_FS
11818 .show_fdinfo = io_uring_show_fdinfo,
11822 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11823 struct io_uring_params *p)
11825 struct io_rings *rings;
11826 size_t size, sq_array_offset;
11828 /* make sure these are sane, as we already accounted them */
11829 ctx->sq_entries = p->sq_entries;
11830 ctx->cq_entries = p->cq_entries;
11832 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
11833 if (size == SIZE_MAX)
11836 rings = io_mem_alloc(size);
11840 ctx->rings = rings;
11841 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11842 rings->sq_ring_mask = p->sq_entries - 1;
11843 rings->cq_ring_mask = p->cq_entries - 1;
11844 rings->sq_ring_entries = p->sq_entries;
11845 rings->cq_ring_entries = p->cq_entries;
11847 if (p->flags & IORING_SETUP_SQE128)
11848 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
11850 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11851 if (size == SIZE_MAX) {
11852 io_mem_free(ctx->rings);
11857 ctx->sq_sqes = io_mem_alloc(size);
11858 if (!ctx->sq_sqes) {
11859 io_mem_free(ctx->rings);
11867 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11871 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11875 ret = io_uring_add_tctx_node(ctx);
11880 fd_install(fd, file);
11885 * Allocate an anonymous fd, this is what constitutes the application
11886 * visible backing of an io_uring instance. The application mmaps this
11887 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11888 * we have to tie this fd to a socket for file garbage collection purposes.
11890 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11893 #if defined(CONFIG_UNIX)
11896 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11899 return ERR_PTR(ret);
11902 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11903 O_RDWR | O_CLOEXEC, NULL);
11904 #if defined(CONFIG_UNIX)
11905 if (IS_ERR(file)) {
11906 sock_release(ctx->ring_sock);
11907 ctx->ring_sock = NULL;
11909 ctx->ring_sock->file = file;
11915 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11916 struct io_uring_params __user *params)
11918 struct io_ring_ctx *ctx;
11924 if (entries > IORING_MAX_ENTRIES) {
11925 if (!(p->flags & IORING_SETUP_CLAMP))
11927 entries = IORING_MAX_ENTRIES;
11931 * Use twice as many entries for the CQ ring. It's possible for the
11932 * application to drive a higher depth than the size of the SQ ring,
11933 * since the sqes are only used at submission time. This allows for
11934 * some flexibility in overcommitting a bit. If the application has
11935 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11936 * of CQ ring entries manually.
11938 p->sq_entries = roundup_pow_of_two(entries);
11939 if (p->flags & IORING_SETUP_CQSIZE) {
11941 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11942 * to a power-of-two, if it isn't already. We do NOT impose
11943 * any cq vs sq ring sizing.
11945 if (!p->cq_entries)
11947 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11948 if (!(p->flags & IORING_SETUP_CLAMP))
11950 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11952 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11953 if (p->cq_entries < p->sq_entries)
11956 p->cq_entries = 2 * p->sq_entries;
11959 ctx = io_ring_ctx_alloc(p);
11964 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
11965 * space applications don't need to do io completion events
11966 * polling again, they can rely on io_sq_thread to do polling
11967 * work, which can reduce cpu usage and uring_lock contention.
11969 if (ctx->flags & IORING_SETUP_IOPOLL &&
11970 !(ctx->flags & IORING_SETUP_SQPOLL))
11971 ctx->syscall_iopoll = 1;
11973 ctx->compat = in_compat_syscall();
11974 if (!capable(CAP_IPC_LOCK))
11975 ctx->user = get_uid(current_user());
11978 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
11979 * COOP_TASKRUN is set, then IPIs are never needed by the app.
11982 if (ctx->flags & IORING_SETUP_SQPOLL) {
11983 /* IPI related flags don't make sense with SQPOLL */
11984 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
11985 IORING_SETUP_TASKRUN_FLAG))
11987 ctx->notify_method = TWA_SIGNAL_NO_IPI;
11988 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
11989 ctx->notify_method = TWA_SIGNAL_NO_IPI;
11991 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
11993 ctx->notify_method = TWA_SIGNAL;
11997 * This is just grabbed for accounting purposes. When a process exits,
11998 * the mm is exited and dropped before the files, hence we need to hang
11999 * on to this mm purely for the purposes of being able to unaccount
12000 * memory (locked/pinned vm). It's not used for anything else.
12002 mmgrab(current->mm);
12003 ctx->mm_account = current->mm;
12005 ret = io_allocate_scq_urings(ctx, p);
12009 ret = io_sq_offload_create(ctx, p);
12012 /* always set a rsrc node */
12013 ret = io_rsrc_node_switch_start(ctx);
12016 io_rsrc_node_switch(ctx, NULL);
12018 memset(&p->sq_off, 0, sizeof(p->sq_off));
12019 p->sq_off.head = offsetof(struct io_rings, sq.head);
12020 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12021 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12022 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12023 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12024 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12025 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12027 memset(&p->cq_off, 0, sizeof(p->cq_off));
12028 p->cq_off.head = offsetof(struct io_rings, cq.head);
12029 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12030 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12031 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12032 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12033 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12034 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12036 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12037 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12038 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12039 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12040 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12041 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12042 IORING_FEAT_LINKED_FILE;
12044 if (copy_to_user(params, p, sizeof(*p))) {
12049 file = io_uring_get_file(ctx);
12050 if (IS_ERR(file)) {
12051 ret = PTR_ERR(file);
12056 * Install ring fd as the very last thing, so we don't risk someone
12057 * having closed it before we finish setup
12059 ret = io_uring_install_fd(ctx, file);
12061 /* fput will clean it up */
12066 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12069 io_ring_ctx_wait_and_kill(ctx);
12074 * Sets up an aio uring context, and returns the fd. Applications asks for a
12075 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12076 * params structure passed in.
12078 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12080 struct io_uring_params p;
12083 if (copy_from_user(&p, params, sizeof(p)))
12085 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12090 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12091 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12092 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12093 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12094 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12095 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12098 return io_uring_create(entries, &p, params);
12101 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12102 struct io_uring_params __user *, params)
12104 return io_uring_setup(entries, params);
12107 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12110 struct io_uring_probe *p;
12114 size = struct_size(p, ops, nr_args);
12115 if (size == SIZE_MAX)
12117 p = kzalloc(size, GFP_KERNEL);
12122 if (copy_from_user(p, arg, size))
12125 if (memchr_inv(p, 0, size))
12128 p->last_op = IORING_OP_LAST - 1;
12129 if (nr_args > IORING_OP_LAST)
12130 nr_args = IORING_OP_LAST;
12132 for (i = 0; i < nr_args; i++) {
12134 if (!io_op_defs[i].not_supported)
12135 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12140 if (copy_to_user(arg, p, size))
12147 static int io_register_personality(struct io_ring_ctx *ctx)
12149 const struct cred *creds;
12153 creds = get_current_cred();
12155 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12156 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12164 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12165 void __user *arg, unsigned int nr_args)
12167 struct io_uring_restriction *res;
12171 /* Restrictions allowed only if rings started disabled */
12172 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12175 /* We allow only a single restrictions registration */
12176 if (ctx->restrictions.registered)
12179 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12182 size = array_size(nr_args, sizeof(*res));
12183 if (size == SIZE_MAX)
12186 res = memdup_user(arg, size);
12188 return PTR_ERR(res);
12192 for (i = 0; i < nr_args; i++) {
12193 switch (res[i].opcode) {
12194 case IORING_RESTRICTION_REGISTER_OP:
12195 if (res[i].register_op >= IORING_REGISTER_LAST) {
12200 __set_bit(res[i].register_op,
12201 ctx->restrictions.register_op);
12203 case IORING_RESTRICTION_SQE_OP:
12204 if (res[i].sqe_op >= IORING_OP_LAST) {
12209 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12211 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12212 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12214 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12215 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12224 /* Reset all restrictions if an error happened */
12226 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12228 ctx->restrictions.registered = true;
12234 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12236 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12239 if (ctx->restrictions.registered)
12240 ctx->restricted = 1;
12242 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12243 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12244 wake_up(&ctx->sq_data->wait);
12248 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12249 struct io_uring_rsrc_update2 *up,
12255 if (check_add_overflow(up->offset, nr_args, &tmp))
12257 err = io_rsrc_node_switch_start(ctx);
12262 case IORING_RSRC_FILE:
12263 return __io_sqe_files_update(ctx, up, nr_args);
12264 case IORING_RSRC_BUFFER:
12265 return __io_sqe_buffers_update(ctx, up, nr_args);
12270 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12273 struct io_uring_rsrc_update2 up;
12277 memset(&up, 0, sizeof(up));
12278 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12280 if (up.resv || up.resv2)
12282 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12285 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12286 unsigned size, unsigned type)
12288 struct io_uring_rsrc_update2 up;
12290 if (size != sizeof(up))
12292 if (copy_from_user(&up, arg, sizeof(up)))
12294 if (!up.nr || up.resv || up.resv2)
12296 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12299 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12300 unsigned int size, unsigned int type)
12302 struct io_uring_rsrc_register rr;
12304 /* keep it extendible */
12305 if (size != sizeof(rr))
12308 memset(&rr, 0, sizeof(rr));
12309 if (copy_from_user(&rr, arg, size))
12311 if (!rr.nr || rr.resv || rr.resv2)
12315 case IORING_RSRC_FILE:
12316 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12317 rr.nr, u64_to_user_ptr(rr.tags));
12318 case IORING_RSRC_BUFFER:
12319 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12320 rr.nr, u64_to_user_ptr(rr.tags));
12325 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12326 void __user *arg, unsigned len)
12328 struct io_uring_task *tctx = current->io_uring;
12329 cpumask_var_t new_mask;
12332 if (!tctx || !tctx->io_wq)
12335 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12338 cpumask_clear(new_mask);
12339 if (len > cpumask_size())
12340 len = cpumask_size();
12342 if (in_compat_syscall()) {
12343 ret = compat_get_bitmap(cpumask_bits(new_mask),
12344 (const compat_ulong_t __user *)arg,
12345 len * 8 /* CHAR_BIT */);
12347 ret = copy_from_user(new_mask, arg, len);
12351 free_cpumask_var(new_mask);
12355 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12356 free_cpumask_var(new_mask);
12360 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12362 struct io_uring_task *tctx = current->io_uring;
12364 if (!tctx || !tctx->io_wq)
12367 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12370 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12372 __must_hold(&ctx->uring_lock)
12374 struct io_tctx_node *node;
12375 struct io_uring_task *tctx = NULL;
12376 struct io_sq_data *sqd = NULL;
12377 __u32 new_count[2];
12380 if (copy_from_user(new_count, arg, sizeof(new_count)))
12382 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12383 if (new_count[i] > INT_MAX)
12386 if (ctx->flags & IORING_SETUP_SQPOLL) {
12387 sqd = ctx->sq_data;
12390 * Observe the correct sqd->lock -> ctx->uring_lock
12391 * ordering. Fine to drop uring_lock here, we hold
12392 * a ref to the ctx.
12394 refcount_inc(&sqd->refs);
12395 mutex_unlock(&ctx->uring_lock);
12396 mutex_lock(&sqd->lock);
12397 mutex_lock(&ctx->uring_lock);
12399 tctx = sqd->thread->io_uring;
12402 tctx = current->io_uring;
12405 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12407 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12409 ctx->iowq_limits[i] = new_count[i];
12410 ctx->iowq_limits_set = true;
12412 if (tctx && tctx->io_wq) {
12413 ret = io_wq_max_workers(tctx->io_wq, new_count);
12417 memset(new_count, 0, sizeof(new_count));
12421 mutex_unlock(&sqd->lock);
12422 io_put_sq_data(sqd);
12425 if (copy_to_user(arg, new_count, sizeof(new_count)))
12428 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12432 /* now propagate the restriction to all registered users */
12433 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12434 struct io_uring_task *tctx = node->task->io_uring;
12436 if (WARN_ON_ONCE(!tctx->io_wq))
12439 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12440 new_count[i] = ctx->iowq_limits[i];
12441 /* ignore errors, it always returns zero anyway */
12442 (void)io_wq_max_workers(tctx->io_wq, new_count);
12447 mutex_unlock(&sqd->lock);
12448 io_put_sq_data(sqd);
12453 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12454 void __user *arg, unsigned nr_args)
12455 __releases(ctx->uring_lock)
12456 __acquires(ctx->uring_lock)
12461 * We're inside the ring mutex, if the ref is already dying, then
12462 * someone else killed the ctx or is already going through
12463 * io_uring_register().
12465 if (percpu_ref_is_dying(&ctx->refs))
12468 if (ctx->restricted) {
12469 if (opcode >= IORING_REGISTER_LAST)
12471 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12472 if (!test_bit(opcode, ctx->restrictions.register_op))
12477 case IORING_REGISTER_BUFFERS:
12478 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
12480 case IORING_UNREGISTER_BUFFERS:
12482 if (arg || nr_args)
12484 ret = io_sqe_buffers_unregister(ctx);
12486 case IORING_REGISTER_FILES:
12487 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
12489 case IORING_UNREGISTER_FILES:
12491 if (arg || nr_args)
12493 ret = io_sqe_files_unregister(ctx);
12495 case IORING_REGISTER_FILES_UPDATE:
12496 ret = io_register_files_update(ctx, arg, nr_args);
12498 case IORING_REGISTER_EVENTFD:
12502 ret = io_eventfd_register(ctx, arg, 0);
12504 case IORING_REGISTER_EVENTFD_ASYNC:
12508 ret = io_eventfd_register(ctx, arg, 1);
12510 case IORING_UNREGISTER_EVENTFD:
12512 if (arg || nr_args)
12514 ret = io_eventfd_unregister(ctx);
12516 case IORING_REGISTER_PROBE:
12518 if (!arg || nr_args > 256)
12520 ret = io_probe(ctx, arg, nr_args);
12522 case IORING_REGISTER_PERSONALITY:
12524 if (arg || nr_args)
12526 ret = io_register_personality(ctx);
12528 case IORING_UNREGISTER_PERSONALITY:
12532 ret = io_unregister_personality(ctx, nr_args);
12534 case IORING_REGISTER_ENABLE_RINGS:
12536 if (arg || nr_args)
12538 ret = io_register_enable_rings(ctx);
12540 case IORING_REGISTER_RESTRICTIONS:
12541 ret = io_register_restrictions(ctx, arg, nr_args);
12543 case IORING_REGISTER_FILES2:
12544 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
12546 case IORING_REGISTER_FILES_UPDATE2:
12547 ret = io_register_rsrc_update(ctx, arg, nr_args,
12550 case IORING_REGISTER_BUFFERS2:
12551 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
12553 case IORING_REGISTER_BUFFERS_UPDATE:
12554 ret = io_register_rsrc_update(ctx, arg, nr_args,
12555 IORING_RSRC_BUFFER);
12557 case IORING_REGISTER_IOWQ_AFF:
12559 if (!arg || !nr_args)
12561 ret = io_register_iowq_aff(ctx, arg, nr_args);
12563 case IORING_UNREGISTER_IOWQ_AFF:
12565 if (arg || nr_args)
12567 ret = io_unregister_iowq_aff(ctx);
12569 case IORING_REGISTER_IOWQ_MAX_WORKERS:
12571 if (!arg || nr_args != 2)
12573 ret = io_register_iowq_max_workers(ctx, arg);
12575 case IORING_REGISTER_RING_FDS:
12576 ret = io_ringfd_register(ctx, arg, nr_args);
12578 case IORING_UNREGISTER_RING_FDS:
12579 ret = io_ringfd_unregister(ctx, arg, nr_args);
12589 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
12590 void __user *, arg, unsigned int, nr_args)
12592 struct io_ring_ctx *ctx;
12601 if (f.file->f_op != &io_uring_fops)
12604 ctx = f.file->private_data;
12606 io_run_task_work();
12608 mutex_lock(&ctx->uring_lock);
12609 ret = __io_uring_register(ctx, opcode, arg, nr_args);
12610 mutex_unlock(&ctx->uring_lock);
12611 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
12617 static int __init io_uring_init(void)
12619 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
12620 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
12621 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
12624 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
12625 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
12626 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
12627 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
12628 BUILD_BUG_SQE_ELEM(1, __u8, flags);
12629 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
12630 BUILD_BUG_SQE_ELEM(4, __s32, fd);
12631 BUILD_BUG_SQE_ELEM(8, __u64, off);
12632 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
12633 BUILD_BUG_SQE_ELEM(16, __u64, addr);
12634 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
12635 BUILD_BUG_SQE_ELEM(24, __u32, len);
12636 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
12637 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
12638 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
12639 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
12640 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
12641 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
12642 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
12643 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
12644 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
12645 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
12646 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
12647 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
12648 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
12649 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
12650 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
12651 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
12652 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
12653 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
12654 BUILD_BUG_SQE_ELEM(42, __u16, personality);
12655 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
12656 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
12657 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
12659 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
12660 sizeof(struct io_uring_rsrc_update));
12661 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
12662 sizeof(struct io_uring_rsrc_update2));
12664 /* ->buf_index is u16 */
12665 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
12666 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
12668 /* should fit into one byte */
12669 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
12670 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
12671 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
12673 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
12674 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
12676 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
12678 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
12682 __initcall(io_uring_init);