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 << 20)
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_APOLL_MULTI_POLLED (REQ_F_APOLL_MULTISHOT | REQ_F_POLLED)
122 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
125 u32 head ____cacheline_aligned_in_smp;
126 u32 tail ____cacheline_aligned_in_smp;
130 * This data is shared with the application through the mmap at offsets
131 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
133 * The offsets to the member fields are published through struct
134 * io_sqring_offsets when calling io_uring_setup.
138 * Head and tail offsets into the ring; the offsets need to be
139 * masked to get valid indices.
141 * The kernel controls head of the sq ring and the tail of the cq ring,
142 * and the application controls tail of the sq ring and the head of the
145 struct io_uring sq, cq;
147 * Bitmasks to apply to head and tail offsets (constant, equals
150 u32 sq_ring_mask, cq_ring_mask;
151 /* Ring sizes (constant, power of 2) */
152 u32 sq_ring_entries, cq_ring_entries;
154 * Number of invalid entries dropped by the kernel due to
155 * invalid index stored in array
157 * Written by the kernel, shouldn't be modified by the
158 * application (i.e. get number of "new events" by comparing to
161 * After a new SQ head value was read by the application this
162 * counter includes all submissions that were dropped reaching
163 * the new SQ head (and possibly more).
169 * Written by the kernel, shouldn't be modified by the
172 * The application needs a full memory barrier before checking
173 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
179 * Written by the application, shouldn't be modified by the
184 * Number of completion events lost because the queue was full;
185 * this should be avoided by the application by making sure
186 * there are not more requests pending than there is space in
187 * the completion queue.
189 * Written by the kernel, shouldn't be modified by the
190 * application (i.e. get number of "new events" by comparing to
193 * As completion events come in out of order this counter is not
194 * ordered with any other data.
198 * Ring buffer of completion events.
200 * The kernel writes completion events fresh every time they are
201 * produced, so the application is allowed to modify pending
204 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
207 struct io_mapped_ubuf {
210 unsigned int nr_bvecs;
211 unsigned long acct_pages;
212 struct bio_vec bvec[];
217 struct io_overflow_cqe {
218 struct list_head list;
219 struct io_uring_cqe cqe;
223 * FFS_SCM is only available on 64-bit archs, for 32-bit we just define it as 0
224 * and define IO_URING_SCM_ALL. For this case, we use SCM for all files as we
225 * can't safely always dereference the file when the task has exited and ring
226 * cleanup is done. If a file is tracked and part of SCM, then unix gc on
227 * process exit may reap it before __io_sqe_files_unregister() is run.
229 #define FFS_NOWAIT 0x1UL
230 #define FFS_ISREG 0x2UL
231 #if defined(CONFIG_64BIT)
232 #define FFS_SCM 0x4UL
234 #define IO_URING_SCM_ALL
235 #define FFS_SCM 0x0UL
237 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG|FFS_SCM)
239 struct io_fixed_file {
240 /* file * with additional FFS_* flags */
241 unsigned long file_ptr;
245 struct list_head list;
250 struct io_mapped_ubuf *buf;
254 struct io_file_table {
255 struct io_fixed_file *files;
256 unsigned long *bitmap;
257 unsigned int alloc_hint;
260 struct io_rsrc_node {
261 struct percpu_ref refs;
262 struct list_head node;
263 struct list_head rsrc_list;
264 struct io_rsrc_data *rsrc_data;
265 struct llist_node llist;
269 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
271 struct io_rsrc_data {
272 struct io_ring_ctx *ctx;
278 struct completion done;
282 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
283 struct io_buffer_list {
285 * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
286 * then these are classic provided buffers and ->buf_list is used.
289 struct list_head buf_list;
291 struct page **buf_pages;
292 struct io_uring_buf_ring *buf_ring;
297 /* below is for ring provided buffers */
305 struct list_head list;
312 struct io_restriction {
313 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
314 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
315 u8 sqe_flags_allowed;
316 u8 sqe_flags_required;
321 IO_SQ_THREAD_SHOULD_STOP = 0,
322 IO_SQ_THREAD_SHOULD_PARK,
327 atomic_t park_pending;
330 /* ctx's that are using this sqd */
331 struct list_head ctx_list;
333 struct task_struct *thread;
334 struct wait_queue_head wait;
336 unsigned sq_thread_idle;
342 struct completion exited;
345 #define IO_COMPL_BATCH 32
346 #define IO_REQ_CACHE_SIZE 32
347 #define IO_REQ_ALLOC_BATCH 8
349 struct io_submit_link {
350 struct io_kiocb *head;
351 struct io_kiocb *last;
354 struct io_submit_state {
355 /* inline/task_work completion list, under ->uring_lock */
356 struct io_wq_work_node free_list;
357 /* batch completion logic */
358 struct io_wq_work_list compl_reqs;
359 struct io_submit_link link;
364 unsigned short submit_nr;
365 struct blk_plug plug;
369 struct eventfd_ctx *cq_ev_fd;
370 unsigned int eventfd_async: 1;
374 #define BGID_ARRAY 64
377 /* const or read-mostly hot data */
379 struct percpu_ref refs;
381 struct io_rings *rings;
383 enum task_work_notify_mode notify_method;
384 unsigned int compat: 1;
385 unsigned int drain_next: 1;
386 unsigned int restricted: 1;
387 unsigned int off_timeout_used: 1;
388 unsigned int drain_active: 1;
389 unsigned int drain_disabled: 1;
390 unsigned int has_evfd: 1;
391 unsigned int syscall_iopoll: 1;
392 } ____cacheline_aligned_in_smp;
394 /* submission data */
396 struct mutex uring_lock;
399 * Ring buffer of indices into array of io_uring_sqe, which is
400 * mmapped by the application using the IORING_OFF_SQES offset.
402 * This indirection could e.g. be used to assign fixed
403 * io_uring_sqe entries to operations and only submit them to
404 * the queue when needed.
406 * The kernel modifies neither the indices array nor the entries
410 struct io_uring_sqe *sq_sqes;
411 unsigned cached_sq_head;
413 struct list_head defer_list;
416 * Fixed resources fast path, should be accessed only under
417 * uring_lock, and updated through io_uring_register(2)
419 struct io_rsrc_node *rsrc_node;
420 int rsrc_cached_refs;
422 struct io_file_table file_table;
423 unsigned nr_user_files;
424 unsigned nr_user_bufs;
425 struct io_mapped_ubuf **user_bufs;
427 struct io_submit_state submit_state;
429 struct io_buffer_list *io_bl;
430 struct xarray io_bl_xa;
431 struct list_head io_buffers_cache;
433 struct list_head timeout_list;
434 struct list_head ltimeout_list;
435 struct list_head cq_overflow_list;
436 struct list_head apoll_cache;
437 struct xarray personalities;
439 unsigned sq_thread_idle;
440 } ____cacheline_aligned_in_smp;
442 /* IRQ completion list, under ->completion_lock */
443 struct io_wq_work_list locked_free_list;
444 unsigned int locked_free_nr;
446 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
447 struct io_sq_data *sq_data; /* if using sq thread polling */
449 struct wait_queue_head sqo_sq_wait;
450 struct list_head sqd_list;
452 unsigned long check_cq;
456 * We cache a range of free CQEs we can use, once exhausted it
457 * should go through a slower range setup, see __io_get_cqe()
459 struct io_uring_cqe *cqe_cached;
460 struct io_uring_cqe *cqe_sentinel;
462 unsigned cached_cq_tail;
464 struct io_ev_fd __rcu *io_ev_fd;
465 struct wait_queue_head cq_wait;
467 atomic_t cq_timeouts;
468 unsigned cq_last_tm_flush;
469 } ____cacheline_aligned_in_smp;
472 spinlock_t completion_lock;
474 spinlock_t timeout_lock;
477 * ->iopoll_list is protected by the ctx->uring_lock for
478 * io_uring instances that don't use IORING_SETUP_SQPOLL.
479 * For SQPOLL, only the single threaded io_sq_thread() will
480 * manipulate the list, hence no extra locking is needed there.
482 struct io_wq_work_list iopoll_list;
483 struct hlist_head *cancel_hash;
484 unsigned cancel_hash_bits;
485 bool poll_multi_queue;
487 struct list_head io_buffers_comp;
488 } ____cacheline_aligned_in_smp;
490 struct io_restriction restrictions;
492 /* slow path rsrc auxilary data, used by update/register */
494 struct io_rsrc_node *rsrc_backup_node;
495 struct io_mapped_ubuf *dummy_ubuf;
496 struct io_rsrc_data *file_data;
497 struct io_rsrc_data *buf_data;
499 struct delayed_work rsrc_put_work;
500 struct llist_head rsrc_put_llist;
501 struct list_head rsrc_ref_list;
502 spinlock_t rsrc_ref_lock;
504 struct list_head io_buffers_pages;
507 /* Keep this last, we don't need it for the fast path */
509 #if defined(CONFIG_UNIX)
510 struct socket *ring_sock;
512 /* hashed buffered write serialization */
513 struct io_wq_hash *hash_map;
515 /* Only used for accounting purposes */
516 struct user_struct *user;
517 struct mm_struct *mm_account;
519 /* ctx exit and cancelation */
520 struct llist_head fallback_llist;
521 struct delayed_work fallback_work;
522 struct work_struct exit_work;
523 struct list_head tctx_list;
524 struct completion ref_comp;
526 bool iowq_limits_set;
531 * Arbitrary limit, can be raised if need be
533 #define IO_RINGFD_REG_MAX 16
535 struct io_uring_task {
536 /* submission side */
539 struct wait_queue_head wait;
540 const struct io_ring_ctx *last;
542 struct percpu_counter inflight;
545 spinlock_t task_lock;
546 struct io_wq_work_list task_list;
547 struct io_wq_work_list prio_task_list;
548 struct callback_head task_work;
549 struct file **registered_rings;
554 * First field must be the file pointer in all the
555 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
557 struct io_poll_iocb {
559 struct wait_queue_head *head;
561 struct wait_queue_entry wait;
564 struct io_poll_update {
570 bool update_user_data;
579 struct io_timeout_data {
580 struct io_kiocb *req;
581 struct hrtimer timer;
582 struct timespec64 ts;
583 enum hrtimer_mode mode;
589 struct sockaddr __user *addr;
590 int __user *addr_len;
593 unsigned long nofile;
603 unsigned long nofile;
625 struct list_head list;
626 /* head of the link, used by linked timeouts only */
627 struct io_kiocb *head;
628 /* for linked completions */
629 struct io_kiocb *prev;
632 struct io_timeout_rem {
637 struct timespec64 ts;
643 /* NOTE: kiocb has the file as the first member, so don't do it here */
652 struct sockaddr __user *addr;
659 struct compat_msghdr __user *umsg_compat;
660 struct user_msghdr __user *umsg;
673 struct filename *filename;
675 unsigned long nofile;
678 struct io_rsrc_update {
704 struct epoll_event event;
708 struct file *file_out;
716 struct io_provide_buf {
730 struct filename *filename;
731 struct statx __user *buffer;
743 struct filename *oldpath;
744 struct filename *newpath;
752 struct filename *filename;
759 struct filename *filename;
765 struct filename *oldpath;
766 struct filename *newpath;
773 struct filename *oldpath;
774 struct filename *newpath;
790 struct io_async_connect {
791 struct sockaddr_storage address;
794 struct io_async_msghdr {
795 struct iovec fast_iov[UIO_FASTIOV];
796 /* points to an allocated iov, if NULL we use fast_iov instead */
797 struct iovec *free_iov;
798 struct sockaddr __user *uaddr;
800 struct sockaddr_storage addr;
804 struct iov_iter iter;
805 struct iov_iter_state iter_state;
806 struct iovec fast_iov[UIO_FASTIOV];
810 struct io_rw_state s;
811 const struct iovec *free_iovec;
813 struct wait_page_queue wpq;
818 struct xattr_ctx ctx;
819 struct filename *filename;
823 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
824 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
825 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
826 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
827 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
828 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
829 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
831 /* first byte is taken by user flags, shift it to not overlap */
836 REQ_F_LINK_TIMEOUT_BIT,
837 REQ_F_NEED_CLEANUP_BIT,
839 REQ_F_BUFFER_SELECTED_BIT,
840 REQ_F_BUFFER_RING_BIT,
841 REQ_F_COMPLETE_INLINE_BIT,
845 REQ_F_ARM_LTIMEOUT_BIT,
846 REQ_F_ASYNC_DATA_BIT,
847 REQ_F_SKIP_LINK_CQES_BIT,
848 REQ_F_SINGLE_POLL_BIT,
849 REQ_F_DOUBLE_POLL_BIT,
850 REQ_F_PARTIAL_IO_BIT,
851 REQ_F_APOLL_MULTISHOT_BIT,
852 /* keep async read/write and isreg together and in order */
853 REQ_F_SUPPORT_NOWAIT_BIT,
856 /* not a real bit, just to check we're not overflowing the space */
862 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
863 /* drain existing IO first */
864 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
866 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
867 /* doesn't sever on completion < 0 */
868 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
870 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
871 /* IOSQE_BUFFER_SELECT */
872 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
873 /* IOSQE_CQE_SKIP_SUCCESS */
874 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
876 /* fail rest of links */
877 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
878 /* on inflight list, should be cancelled and waited on exit reliably */
879 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
880 /* read/write uses file position */
881 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
882 /* must not punt to workers */
883 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
884 /* has or had linked timeout */
885 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
887 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
888 /* already went through poll handler */
889 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
890 /* buffer already selected */
891 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
892 /* buffer selected from ring, needs commit */
893 REQ_F_BUFFER_RING = BIT(REQ_F_BUFFER_RING_BIT),
894 /* completion is deferred through io_comp_state */
895 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
896 /* caller should reissue async */
897 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
898 /* supports async reads/writes */
899 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
901 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
902 /* has creds assigned */
903 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
904 /* skip refcounting if not set */
905 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
906 /* there is a linked timeout that has to be armed */
907 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
908 /* ->async_data allocated */
909 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
910 /* don't post CQEs while failing linked requests */
911 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
912 /* single poll may be active */
913 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
914 /* double poll may active */
915 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
916 /* request has already done partial IO */
917 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
918 /* fast poll multishot mode */
919 REQ_F_APOLL_MULTISHOT = BIT(REQ_F_APOLL_MULTISHOT_BIT),
923 struct io_poll_iocb poll;
924 struct io_poll_iocb *double_poll;
927 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
929 struct io_task_work {
931 struct io_wq_work_node node;
932 struct llist_node fallback_node;
934 io_req_tw_func_t func;
938 IORING_RSRC_FILE = 0,
939 IORING_RSRC_BUFFER = 1,
945 /* fd initially, then cflags for completion */
953 IO_CHECK_CQ_OVERFLOW_BIT,
954 IO_CHECK_CQ_DROPPED_BIT,
958 * NOTE! Each of the iocb union members has the file pointer
959 * as the first entry in their struct definition. So you can
960 * access the file pointer through any of the sub-structs,
961 * or directly as just 'file' in this struct.
967 struct io_poll_iocb poll;
968 struct io_poll_update poll_update;
969 struct io_accept accept;
971 struct io_cancel cancel;
972 struct io_timeout timeout;
973 struct io_timeout_rem timeout_rem;
974 struct io_connect connect;
975 struct io_sr_msg sr_msg;
977 struct io_close close;
978 struct io_rsrc_update rsrc_update;
979 struct io_fadvise fadvise;
980 struct io_madvise madvise;
981 struct io_epoll epoll;
982 struct io_splice splice;
983 struct io_provide_buf pbuf;
984 struct io_statx statx;
985 struct io_shutdown shutdown;
986 struct io_rename rename;
987 struct io_unlink unlink;
988 struct io_mkdir mkdir;
989 struct io_symlink symlink;
990 struct io_hardlink hardlink;
992 struct io_xattr xattr;
993 struct io_socket sock;
995 struct io_uring_cmd uring_cmd;
999 /* polled IO has completed */
1000 u8 iopoll_completed;
1002 * Can be either a fixed buffer index, or used with provided buffers.
1003 * For the latter, before issue it points to the buffer group ID,
1004 * and after selection it points to the buffer ID itself.
1011 struct io_ring_ctx *ctx;
1012 struct task_struct *task;
1014 struct io_rsrc_node *rsrc_node;
1017 /* store used ubuf, so we can prevent reloading */
1018 struct io_mapped_ubuf *imu;
1020 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
1021 struct io_buffer *kbuf;
1024 * stores buffer ID for ring provided buffers, valid IFF
1025 * REQ_F_BUFFER_RING is set.
1027 struct io_buffer_list *buf_list;
1031 /* used by request caches, completion batching and iopoll */
1032 struct io_wq_work_node comp_list;
1033 /* cache ->apoll->events */
1034 __poll_t apoll_events;
1038 struct io_task_work io_task_work;
1039 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1041 struct hlist_node hash_node;
1047 /* internal polling, see IORING_FEAT_FAST_POLL */
1048 struct async_poll *apoll;
1049 /* opcode allocated if it needs to store data for async defer */
1051 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1052 struct io_kiocb *link;
1053 /* custom credentials, valid IFF REQ_F_CREDS is set */
1054 const struct cred *creds;
1055 struct io_wq_work work;
1058 struct io_tctx_node {
1059 struct list_head ctx_node;
1060 struct task_struct *task;
1061 struct io_ring_ctx *ctx;
1064 struct io_defer_entry {
1065 struct list_head list;
1066 struct io_kiocb *req;
1070 struct io_cancel_data {
1071 struct io_ring_ctx *ctx;
1081 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
1082 * the following sqe if SQE128 is used.
1084 #define uring_cmd_pdu_size(is_sqe128) \
1085 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
1086 offsetof(struct io_uring_sqe, cmd))
1089 /* needs req->file assigned */
1090 unsigned needs_file : 1;
1091 /* should block plug */
1093 /* hash wq insertion if file is a regular file */
1094 unsigned hash_reg_file : 1;
1095 /* unbound wq insertion if file is a non-regular file */
1096 unsigned unbound_nonreg_file : 1;
1097 /* set if opcode supports polled "wait" */
1098 unsigned pollin : 1;
1099 unsigned pollout : 1;
1100 unsigned poll_exclusive : 1;
1101 /* op supports buffer selection */
1102 unsigned buffer_select : 1;
1103 /* do prep async if is going to be punted */
1104 unsigned needs_async_setup : 1;
1105 /* opcode is not supported by this kernel */
1106 unsigned not_supported : 1;
1108 unsigned audit_skip : 1;
1109 /* supports ioprio */
1110 unsigned ioprio : 1;
1111 /* supports iopoll */
1112 unsigned iopoll : 1;
1113 /* size of async data needed, if any */
1114 unsigned short async_size;
1117 static const struct io_op_def io_op_defs[] = {
1123 [IORING_OP_READV] = {
1125 .unbound_nonreg_file = 1,
1128 .needs_async_setup = 1,
1133 .async_size = sizeof(struct io_async_rw),
1135 [IORING_OP_WRITEV] = {
1138 .unbound_nonreg_file = 1,
1140 .needs_async_setup = 1,
1145 .async_size = sizeof(struct io_async_rw),
1147 [IORING_OP_FSYNC] = {
1151 [IORING_OP_READ_FIXED] = {
1153 .unbound_nonreg_file = 1,
1159 .async_size = sizeof(struct io_async_rw),
1161 [IORING_OP_WRITE_FIXED] = {
1164 .unbound_nonreg_file = 1,
1170 .async_size = sizeof(struct io_async_rw),
1172 [IORING_OP_POLL_ADD] = {
1174 .unbound_nonreg_file = 1,
1177 [IORING_OP_POLL_REMOVE] = {
1180 [IORING_OP_SYNC_FILE_RANGE] = {
1184 [IORING_OP_SENDMSG] = {
1186 .unbound_nonreg_file = 1,
1188 .needs_async_setup = 1,
1189 .async_size = sizeof(struct io_async_msghdr),
1191 [IORING_OP_RECVMSG] = {
1193 .unbound_nonreg_file = 1,
1196 .needs_async_setup = 1,
1197 .async_size = sizeof(struct io_async_msghdr),
1199 [IORING_OP_TIMEOUT] = {
1201 .async_size = sizeof(struct io_timeout_data),
1203 [IORING_OP_TIMEOUT_REMOVE] = {
1204 /* used by timeout updates' prep() */
1207 [IORING_OP_ACCEPT] = {
1209 .unbound_nonreg_file = 1,
1211 .poll_exclusive = 1,
1212 .ioprio = 1, /* used for flags */
1214 [IORING_OP_ASYNC_CANCEL] = {
1217 [IORING_OP_LINK_TIMEOUT] = {
1219 .async_size = sizeof(struct io_timeout_data),
1221 [IORING_OP_CONNECT] = {
1223 .unbound_nonreg_file = 1,
1225 .needs_async_setup = 1,
1226 .async_size = sizeof(struct io_async_connect),
1228 [IORING_OP_FALLOCATE] = {
1231 [IORING_OP_OPENAT] = {},
1232 [IORING_OP_CLOSE] = {},
1233 [IORING_OP_FILES_UPDATE] = {
1237 [IORING_OP_STATX] = {
1240 [IORING_OP_READ] = {
1242 .unbound_nonreg_file = 1,
1249 .async_size = sizeof(struct io_async_rw),
1251 [IORING_OP_WRITE] = {
1254 .unbound_nonreg_file = 1,
1260 .async_size = sizeof(struct io_async_rw),
1262 [IORING_OP_FADVISE] = {
1266 [IORING_OP_MADVISE] = {},
1267 [IORING_OP_SEND] = {
1269 .unbound_nonreg_file = 1,
1273 [IORING_OP_RECV] = {
1275 .unbound_nonreg_file = 1,
1280 [IORING_OP_OPENAT2] = {
1282 [IORING_OP_EPOLL_CTL] = {
1283 .unbound_nonreg_file = 1,
1286 [IORING_OP_SPLICE] = {
1289 .unbound_nonreg_file = 1,
1292 [IORING_OP_PROVIDE_BUFFERS] = {
1296 [IORING_OP_REMOVE_BUFFERS] = {
1303 .unbound_nonreg_file = 1,
1306 [IORING_OP_SHUTDOWN] = {
1309 [IORING_OP_RENAMEAT] = {},
1310 [IORING_OP_UNLINKAT] = {},
1311 [IORING_OP_MKDIRAT] = {},
1312 [IORING_OP_SYMLINKAT] = {},
1313 [IORING_OP_LINKAT] = {},
1314 [IORING_OP_MSG_RING] = {
1318 [IORING_OP_FSETXATTR] = {
1321 [IORING_OP_SETXATTR] = {},
1322 [IORING_OP_FGETXATTR] = {
1325 [IORING_OP_GETXATTR] = {},
1326 [IORING_OP_SOCKET] = {
1329 [IORING_OP_URING_CMD] = {
1332 .needs_async_setup = 1,
1333 .async_size = uring_cmd_pdu_size(1),
1337 /* requests with any of those set should undergo io_disarm_next() */
1338 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1339 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1341 static bool io_disarm_next(struct io_kiocb *req);
1342 static void io_uring_del_tctx_node(unsigned long index);
1343 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1344 struct task_struct *task,
1346 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1348 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1349 static void io_dismantle_req(struct io_kiocb *req);
1350 static void io_queue_linked_timeout(struct io_kiocb *req);
1351 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1352 struct io_uring_rsrc_update2 *up,
1354 static void io_clean_op(struct io_kiocb *req);
1355 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1356 unsigned issue_flags);
1357 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1358 static void io_drop_inflight_file(struct io_kiocb *req);
1359 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1360 static void io_queue_sqe(struct io_kiocb *req);
1361 static void io_rsrc_put_work(struct work_struct *work);
1363 static void io_req_task_queue(struct io_kiocb *req);
1364 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1365 static int io_req_prep_async(struct io_kiocb *req);
1367 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1368 unsigned int issue_flags, u32 slot_index);
1369 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1371 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1372 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1373 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1375 static struct kmem_cache *req_cachep;
1377 static const struct file_operations io_uring_fops;
1379 const char *io_uring_get_opcode(u8 opcode)
1381 switch ((enum io_uring_op)opcode) {
1384 case IORING_OP_READV:
1386 case IORING_OP_WRITEV:
1388 case IORING_OP_FSYNC:
1390 case IORING_OP_READ_FIXED:
1391 return "READ_FIXED";
1392 case IORING_OP_WRITE_FIXED:
1393 return "WRITE_FIXED";
1394 case IORING_OP_POLL_ADD:
1396 case IORING_OP_POLL_REMOVE:
1397 return "POLL_REMOVE";
1398 case IORING_OP_SYNC_FILE_RANGE:
1399 return "SYNC_FILE_RANGE";
1400 case IORING_OP_SENDMSG:
1402 case IORING_OP_RECVMSG:
1404 case IORING_OP_TIMEOUT:
1406 case IORING_OP_TIMEOUT_REMOVE:
1407 return "TIMEOUT_REMOVE";
1408 case IORING_OP_ACCEPT:
1410 case IORING_OP_ASYNC_CANCEL:
1411 return "ASYNC_CANCEL";
1412 case IORING_OP_LINK_TIMEOUT:
1413 return "LINK_TIMEOUT";
1414 case IORING_OP_CONNECT:
1416 case IORING_OP_FALLOCATE:
1418 case IORING_OP_OPENAT:
1420 case IORING_OP_CLOSE:
1422 case IORING_OP_FILES_UPDATE:
1423 return "FILES_UPDATE";
1424 case IORING_OP_STATX:
1426 case IORING_OP_READ:
1428 case IORING_OP_WRITE:
1430 case IORING_OP_FADVISE:
1432 case IORING_OP_MADVISE:
1434 case IORING_OP_SEND:
1436 case IORING_OP_RECV:
1438 case IORING_OP_OPENAT2:
1440 case IORING_OP_EPOLL_CTL:
1442 case IORING_OP_SPLICE:
1444 case IORING_OP_PROVIDE_BUFFERS:
1445 return "PROVIDE_BUFFERS";
1446 case IORING_OP_REMOVE_BUFFERS:
1447 return "REMOVE_BUFFERS";
1450 case IORING_OP_SHUTDOWN:
1452 case IORING_OP_RENAMEAT:
1454 case IORING_OP_UNLINKAT:
1456 case IORING_OP_MKDIRAT:
1458 case IORING_OP_SYMLINKAT:
1460 case IORING_OP_LINKAT:
1462 case IORING_OP_MSG_RING:
1464 case IORING_OP_FSETXATTR:
1466 case IORING_OP_SETXATTR:
1468 case IORING_OP_FGETXATTR:
1470 case IORING_OP_GETXATTR:
1472 case IORING_OP_SOCKET:
1474 case IORING_OP_URING_CMD:
1476 case IORING_OP_LAST:
1482 struct sock *io_uring_get_socket(struct file *file)
1484 #if defined(CONFIG_UNIX)
1485 if (file->f_op == &io_uring_fops) {
1486 struct io_ring_ctx *ctx = file->private_data;
1488 return ctx->ring_sock->sk;
1493 EXPORT_SYMBOL(io_uring_get_socket);
1495 #if defined(CONFIG_UNIX)
1496 static inline bool io_file_need_scm(struct file *filp)
1498 #if defined(IO_URING_SCM_ALL)
1501 return !!unix_get_socket(filp);
1505 static inline bool io_file_need_scm(struct file *filp)
1511 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1513 lockdep_assert_held(&ctx->uring_lock);
1514 if (issue_flags & IO_URING_F_UNLOCKED)
1515 mutex_unlock(&ctx->uring_lock);
1518 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1521 * "Normal" inline submissions always hold the uring_lock, since we
1522 * grab it from the system call. Same is true for the SQPOLL offload.
1523 * The only exception is when we've detached the request and issue it
1524 * from an async worker thread, grab the lock for that case.
1526 if (issue_flags & IO_URING_F_UNLOCKED)
1527 mutex_lock(&ctx->uring_lock);
1528 lockdep_assert_held(&ctx->uring_lock);
1531 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1534 mutex_lock(&ctx->uring_lock);
1539 #define io_for_each_link(pos, head) \
1540 for (pos = (head); pos; pos = pos->link)
1543 * Shamelessly stolen from the mm implementation of page reference checking,
1544 * see commit f958d7b528b1 for details.
1546 #define req_ref_zero_or_close_to_overflow(req) \
1547 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1549 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1551 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1552 return atomic_inc_not_zero(&req->refs);
1555 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1557 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1560 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1561 return atomic_dec_and_test(&req->refs);
1564 static inline void req_ref_get(struct io_kiocb *req)
1566 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1567 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1568 atomic_inc(&req->refs);
1571 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1573 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1574 __io_submit_flush_completions(ctx);
1577 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1579 if (!(req->flags & REQ_F_REFCOUNT)) {
1580 req->flags |= REQ_F_REFCOUNT;
1581 atomic_set(&req->refs, nr);
1585 static inline void io_req_set_refcount(struct io_kiocb *req)
1587 __io_req_set_refcount(req, 1);
1590 #define IO_RSRC_REF_BATCH 100
1592 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1594 percpu_ref_put_many(&node->refs, nr);
1597 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1598 struct io_ring_ctx *ctx)
1599 __must_hold(&ctx->uring_lock)
1601 struct io_rsrc_node *node = req->rsrc_node;
1604 if (node == ctx->rsrc_node)
1605 ctx->rsrc_cached_refs++;
1607 io_rsrc_put_node(node, 1);
1611 static inline void io_req_put_rsrc(struct io_kiocb *req)
1614 io_rsrc_put_node(req->rsrc_node, 1);
1617 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1618 __must_hold(&ctx->uring_lock)
1620 if (ctx->rsrc_cached_refs) {
1621 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1622 ctx->rsrc_cached_refs = 0;
1626 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1627 __must_hold(&ctx->uring_lock)
1629 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1630 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1633 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1634 struct io_ring_ctx *ctx,
1635 unsigned int issue_flags)
1637 if (!req->rsrc_node) {
1638 req->rsrc_node = ctx->rsrc_node;
1640 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1641 lockdep_assert_held(&ctx->uring_lock);
1642 ctx->rsrc_cached_refs--;
1643 if (unlikely(ctx->rsrc_cached_refs < 0))
1644 io_rsrc_refs_refill(ctx);
1646 percpu_ref_get(&req->rsrc_node->refs);
1651 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1653 if (req->flags & REQ_F_BUFFER_RING) {
1655 req->buf_list->head++;
1656 req->flags &= ~REQ_F_BUFFER_RING;
1658 list_add(&req->kbuf->list, list);
1659 req->flags &= ~REQ_F_BUFFER_SELECTED;
1662 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1665 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1667 lockdep_assert_held(&req->ctx->completion_lock);
1669 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1671 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1674 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1675 unsigned issue_flags)
1677 unsigned int cflags;
1679 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1683 * We can add this buffer back to two lists:
1685 * 1) The io_buffers_cache list. This one is protected by the
1686 * ctx->uring_lock. If we already hold this lock, add back to this
1687 * list as we can grab it from issue as well.
1688 * 2) The io_buffers_comp list. This one is protected by the
1689 * ctx->completion_lock.
1691 * We migrate buffers from the comp_list to the issue cache list
1694 if (req->flags & REQ_F_BUFFER_RING) {
1695 /* no buffers to recycle for this case */
1696 cflags = __io_put_kbuf(req, NULL);
1697 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1698 struct io_ring_ctx *ctx = req->ctx;
1700 spin_lock(&ctx->completion_lock);
1701 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1702 spin_unlock(&ctx->completion_lock);
1704 lockdep_assert_held(&req->ctx->uring_lock);
1706 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1712 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1715 if (ctx->io_bl && bgid < BGID_ARRAY)
1716 return &ctx->io_bl[bgid];
1718 return xa_load(&ctx->io_bl_xa, bgid);
1721 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1723 struct io_ring_ctx *ctx = req->ctx;
1724 struct io_buffer_list *bl;
1725 struct io_buffer *buf;
1727 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1729 /* don't recycle if we already did IO to this buffer */
1730 if (req->flags & REQ_F_PARTIAL_IO)
1733 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1734 * the flag and hence ensure that bl->head doesn't get incremented.
1735 * If the tail has already been incremented, hang on to it.
1737 if (req->flags & REQ_F_BUFFER_RING) {
1738 if (req->buf_list) {
1739 req->buf_index = req->buf_list->bgid;
1740 req->flags &= ~REQ_F_BUFFER_RING;
1745 io_ring_submit_lock(ctx, issue_flags);
1748 bl = io_buffer_get_list(ctx, buf->bgid);
1749 list_add(&buf->list, &bl->buf_list);
1750 req->flags &= ~REQ_F_BUFFER_SELECTED;
1751 req->buf_index = buf->bgid;
1753 io_ring_submit_unlock(ctx, issue_flags);
1756 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1758 __must_hold(&req->ctx->timeout_lock)
1760 if (task && head->task != task)
1766 * As io_match_task() but protected against racing with linked timeouts.
1767 * User must not hold timeout_lock.
1769 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1772 if (task && head->task != task)
1777 static inline bool req_has_async_data(struct io_kiocb *req)
1779 return req->flags & REQ_F_ASYNC_DATA;
1782 static inline void req_set_fail(struct io_kiocb *req)
1784 req->flags |= REQ_F_FAIL;
1785 if (req->flags & REQ_F_CQE_SKIP) {
1786 req->flags &= ~REQ_F_CQE_SKIP;
1787 req->flags |= REQ_F_SKIP_LINK_CQES;
1791 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1797 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1799 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1802 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1804 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1806 complete(&ctx->ref_comp);
1809 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1811 return !req->timeout.off;
1814 static __cold void io_fallback_req_func(struct work_struct *work)
1816 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1817 fallback_work.work);
1818 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1819 struct io_kiocb *req, *tmp;
1820 bool locked = false;
1822 percpu_ref_get(&ctx->refs);
1823 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1824 req->io_task_work.func(req, &locked);
1827 io_submit_flush_completions(ctx);
1828 mutex_unlock(&ctx->uring_lock);
1830 percpu_ref_put(&ctx->refs);
1833 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1835 struct io_ring_ctx *ctx;
1838 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1842 xa_init(&ctx->io_bl_xa);
1845 * Use 5 bits less than the max cq entries, that should give us around
1846 * 32 entries per hash list if totally full and uniformly spread.
1848 hash_bits = ilog2(p->cq_entries);
1852 ctx->cancel_hash_bits = hash_bits;
1853 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1855 if (!ctx->cancel_hash)
1857 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1859 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1860 if (!ctx->dummy_ubuf)
1862 /* set invalid range, so io_import_fixed() fails meeting it */
1863 ctx->dummy_ubuf->ubuf = -1UL;
1865 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1866 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1869 ctx->flags = p->flags;
1870 init_waitqueue_head(&ctx->sqo_sq_wait);
1871 INIT_LIST_HEAD(&ctx->sqd_list);
1872 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1873 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1874 INIT_LIST_HEAD(&ctx->apoll_cache);
1875 init_completion(&ctx->ref_comp);
1876 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1877 mutex_init(&ctx->uring_lock);
1878 init_waitqueue_head(&ctx->cq_wait);
1879 spin_lock_init(&ctx->completion_lock);
1880 spin_lock_init(&ctx->timeout_lock);
1881 INIT_WQ_LIST(&ctx->iopoll_list);
1882 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1883 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1884 INIT_LIST_HEAD(&ctx->defer_list);
1885 INIT_LIST_HEAD(&ctx->timeout_list);
1886 INIT_LIST_HEAD(&ctx->ltimeout_list);
1887 spin_lock_init(&ctx->rsrc_ref_lock);
1888 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1889 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1890 init_llist_head(&ctx->rsrc_put_llist);
1891 INIT_LIST_HEAD(&ctx->tctx_list);
1892 ctx->submit_state.free_list.next = NULL;
1893 INIT_WQ_LIST(&ctx->locked_free_list);
1894 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1895 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1898 kfree(ctx->dummy_ubuf);
1899 kfree(ctx->cancel_hash);
1901 xa_destroy(&ctx->io_bl_xa);
1906 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1908 struct io_rings *r = ctx->rings;
1910 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1914 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1916 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1917 struct io_ring_ctx *ctx = req->ctx;
1919 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1925 static inline bool io_req_ffs_set(struct io_kiocb *req)
1927 return req->flags & REQ_F_FIXED_FILE;
1930 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1932 if (WARN_ON_ONCE(!req->link))
1935 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1936 req->flags |= REQ_F_LINK_TIMEOUT;
1938 /* linked timeouts should have two refs once prep'ed */
1939 io_req_set_refcount(req);
1940 __io_req_set_refcount(req->link, 2);
1944 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1946 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1948 return __io_prep_linked_timeout(req);
1951 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1953 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1956 static inline void io_arm_ltimeout(struct io_kiocb *req)
1958 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1959 __io_arm_ltimeout(req);
1962 static void io_prep_async_work(struct io_kiocb *req)
1964 const struct io_op_def *def = &io_op_defs[req->opcode];
1965 struct io_ring_ctx *ctx = req->ctx;
1967 if (!(req->flags & REQ_F_CREDS)) {
1968 req->flags |= REQ_F_CREDS;
1969 req->creds = get_current_cred();
1972 req->work.list.next = NULL;
1973 req->work.flags = 0;
1974 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1975 if (req->flags & REQ_F_FORCE_ASYNC)
1976 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1978 if (req->flags & REQ_F_ISREG) {
1979 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1980 io_wq_hash_work(&req->work, file_inode(req->file));
1981 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1982 if (def->unbound_nonreg_file)
1983 req->work.flags |= IO_WQ_WORK_UNBOUND;
1987 static void io_prep_async_link(struct io_kiocb *req)
1989 struct io_kiocb *cur;
1991 if (req->flags & REQ_F_LINK_TIMEOUT) {
1992 struct io_ring_ctx *ctx = req->ctx;
1994 spin_lock_irq(&ctx->timeout_lock);
1995 io_for_each_link(cur, req)
1996 io_prep_async_work(cur);
1997 spin_unlock_irq(&ctx->timeout_lock);
1999 io_for_each_link(cur, req)
2000 io_prep_async_work(cur);
2004 static inline void io_req_add_compl_list(struct io_kiocb *req)
2006 struct io_submit_state *state = &req->ctx->submit_state;
2008 if (!(req->flags & REQ_F_CQE_SKIP))
2009 state->flush_cqes = true;
2010 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
2013 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
2015 struct io_kiocb *link = io_prep_linked_timeout(req);
2016 struct io_uring_task *tctx = req->task->io_uring;
2019 BUG_ON(!tctx->io_wq);
2021 /* init ->work of the whole link before punting */
2022 io_prep_async_link(req);
2025 * Not expected to happen, but if we do have a bug where this _can_
2026 * happen, catch it here and ensure the request is marked as
2027 * canceled. That will make io-wq go through the usual work cancel
2028 * procedure rather than attempt to run this request (or create a new
2031 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
2032 req->work.flags |= IO_WQ_WORK_CANCEL;
2034 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
2035 req->opcode, req->flags, &req->work,
2036 io_wq_is_hashed(&req->work));
2037 io_wq_enqueue(tctx->io_wq, &req->work);
2039 io_queue_linked_timeout(link);
2042 static void io_kill_timeout(struct io_kiocb *req, int status)
2043 __must_hold(&req->ctx->completion_lock)
2044 __must_hold(&req->ctx->timeout_lock)
2046 struct io_timeout_data *io = req->async_data;
2048 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2051 atomic_set(&req->ctx->cq_timeouts,
2052 atomic_read(&req->ctx->cq_timeouts) + 1);
2053 list_del_init(&req->timeout.list);
2054 io_req_tw_post_queue(req, status, 0);
2058 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
2060 while (!list_empty(&ctx->defer_list)) {
2061 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
2062 struct io_defer_entry, list);
2064 if (req_need_defer(de->req, de->seq))
2066 list_del_init(&de->list);
2067 io_req_task_queue(de->req);
2072 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
2073 __must_hold(&ctx->completion_lock)
2075 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
2076 struct io_kiocb *req, *tmp;
2078 spin_lock_irq(&ctx->timeout_lock);
2079 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
2080 u32 events_needed, events_got;
2082 if (io_is_timeout_noseq(req))
2086 * Since seq can easily wrap around over time, subtract
2087 * the last seq at which timeouts were flushed before comparing.
2088 * Assuming not more than 2^31-1 events have happened since,
2089 * these subtractions won't have wrapped, so we can check if
2090 * target is in [last_seq, current_seq] by comparing the two.
2092 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
2093 events_got = seq - ctx->cq_last_tm_flush;
2094 if (events_got < events_needed)
2097 io_kill_timeout(req, 0);
2099 ctx->cq_last_tm_flush = seq;
2100 spin_unlock_irq(&ctx->timeout_lock);
2103 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
2105 /* order cqe stores with ring update */
2106 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
2109 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
2111 if (ctx->off_timeout_used || ctx->drain_active) {
2112 spin_lock(&ctx->completion_lock);
2113 if (ctx->off_timeout_used)
2114 io_flush_timeouts(ctx);
2115 if (ctx->drain_active)
2116 io_queue_deferred(ctx);
2117 io_commit_cqring(ctx);
2118 spin_unlock(&ctx->completion_lock);
2121 io_eventfd_signal(ctx);
2124 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
2126 struct io_rings *r = ctx->rings;
2128 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
2131 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
2133 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
2137 * writes to the cq entry need to come after reading head; the
2138 * control dependency is enough as we're using WRITE_ONCE to
2141 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
2143 struct io_rings *rings = ctx->rings;
2144 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
2145 unsigned int shift = 0;
2146 unsigned int free, queued, len;
2148 if (ctx->flags & IORING_SETUP_CQE32)
2151 /* userspace may cheat modifying the tail, be safe and do min */
2152 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2153 free = ctx->cq_entries - queued;
2154 /* we need a contiguous range, limit based on the current array offset */
2155 len = min(free, ctx->cq_entries - off);
2159 ctx->cached_cq_tail++;
2160 ctx->cqe_cached = &rings->cqes[off];
2161 ctx->cqe_sentinel = ctx->cqe_cached + len;
2163 return &rings->cqes[off << shift];
2166 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2168 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2169 struct io_uring_cqe *cqe = ctx->cqe_cached;
2171 if (ctx->flags & IORING_SETUP_CQE32) {
2172 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2177 ctx->cached_cq_tail++;
2182 return __io_get_cqe(ctx);
2185 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2187 struct io_ev_fd *ev_fd;
2191 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2192 * and eventfd_signal
2194 ev_fd = rcu_dereference(ctx->io_ev_fd);
2197 * Check again if ev_fd exists incase an io_eventfd_unregister call
2198 * completed between the NULL check of ctx->io_ev_fd at the start of
2199 * the function and rcu_read_lock.
2201 if (unlikely(!ev_fd))
2203 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2206 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2207 eventfd_signal(ev_fd->cq_ev_fd, 1);
2212 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2215 * wake_up_all() may seem excessive, but io_wake_function() and
2216 * io_should_wake() handle the termination of the loop and only
2217 * wake as many waiters as we need to.
2219 if (wq_has_sleeper(&ctx->cq_wait))
2220 wake_up_all(&ctx->cq_wait);
2224 * This should only get called when at least one event has been posted.
2225 * Some applications rely on the eventfd notification count only changing
2226 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2227 * 1:1 relationship between how many times this function is called (and
2228 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2230 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2232 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2234 __io_commit_cqring_flush(ctx);
2236 io_cqring_wake(ctx);
2239 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2241 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2243 __io_commit_cqring_flush(ctx);
2245 if (ctx->flags & IORING_SETUP_SQPOLL)
2246 io_cqring_wake(ctx);
2249 /* Returns true if there are no backlogged entries after the flush */
2250 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2252 bool all_flushed, posted;
2253 size_t cqe_size = sizeof(struct io_uring_cqe);
2255 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2258 if (ctx->flags & IORING_SETUP_CQE32)
2262 spin_lock(&ctx->completion_lock);
2263 while (!list_empty(&ctx->cq_overflow_list)) {
2264 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2265 struct io_overflow_cqe *ocqe;
2269 ocqe = list_first_entry(&ctx->cq_overflow_list,
2270 struct io_overflow_cqe, list);
2272 memcpy(cqe, &ocqe->cqe, cqe_size);
2274 io_account_cq_overflow(ctx);
2277 list_del(&ocqe->list);
2281 all_flushed = list_empty(&ctx->cq_overflow_list);
2283 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2284 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2287 io_commit_cqring(ctx);
2288 spin_unlock(&ctx->completion_lock);
2290 io_cqring_ev_posted(ctx);
2294 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2298 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2299 /* iopoll syncs against uring_lock, not completion_lock */
2300 if (ctx->flags & IORING_SETUP_IOPOLL)
2301 mutex_lock(&ctx->uring_lock);
2302 ret = __io_cqring_overflow_flush(ctx, false);
2303 if (ctx->flags & IORING_SETUP_IOPOLL)
2304 mutex_unlock(&ctx->uring_lock);
2310 static void __io_put_task(struct task_struct *task, int nr)
2312 struct io_uring_task *tctx = task->io_uring;
2314 percpu_counter_sub(&tctx->inflight, nr);
2315 if (unlikely(atomic_read(&tctx->in_idle)))
2316 wake_up(&tctx->wait);
2317 put_task_struct_many(task, nr);
2320 /* must to be called somewhat shortly after putting a request */
2321 static inline void io_put_task(struct task_struct *task, int nr)
2323 if (likely(task == current))
2324 task->io_uring->cached_refs += nr;
2326 __io_put_task(task, nr);
2329 static void io_task_refs_refill(struct io_uring_task *tctx)
2331 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2333 percpu_counter_add(&tctx->inflight, refill);
2334 refcount_add(refill, ¤t->usage);
2335 tctx->cached_refs += refill;
2338 static inline void io_get_task_refs(int nr)
2340 struct io_uring_task *tctx = current->io_uring;
2342 tctx->cached_refs -= nr;
2343 if (unlikely(tctx->cached_refs < 0))
2344 io_task_refs_refill(tctx);
2347 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2349 struct io_uring_task *tctx = task->io_uring;
2350 unsigned int refs = tctx->cached_refs;
2353 tctx->cached_refs = 0;
2354 percpu_counter_sub(&tctx->inflight, refs);
2355 put_task_struct_many(task, refs);
2359 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2360 s32 res, u32 cflags, u64 extra1,
2363 struct io_overflow_cqe *ocqe;
2364 size_t ocq_size = sizeof(struct io_overflow_cqe);
2365 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2368 ocq_size += sizeof(struct io_uring_cqe);
2370 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2371 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2374 * If we're in ring overflow flush mode, or in task cancel mode,
2375 * or cannot allocate an overflow entry, then we need to drop it
2378 io_account_cq_overflow(ctx);
2379 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2382 if (list_empty(&ctx->cq_overflow_list)) {
2383 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2384 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2387 ocqe->cqe.user_data = user_data;
2388 ocqe->cqe.res = res;
2389 ocqe->cqe.flags = cflags;
2391 ocqe->cqe.big_cqe[0] = extra1;
2392 ocqe->cqe.big_cqe[1] = extra2;
2394 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2398 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2399 s32 res, u32 cflags)
2401 struct io_uring_cqe *cqe;
2404 * If we can't get a cq entry, userspace overflowed the
2405 * submission (by quite a lot). Increment the overflow count in
2408 cqe = io_get_cqe(ctx);
2410 WRITE_ONCE(cqe->user_data, user_data);
2411 WRITE_ONCE(cqe->res, res);
2412 WRITE_ONCE(cqe->flags, cflags);
2415 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2418 static inline bool __io_fill_cqe_req_filled(struct io_ring_ctx *ctx,
2419 struct io_kiocb *req)
2421 struct io_uring_cqe *cqe;
2423 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2424 req->cqe.res, req->cqe.flags, 0, 0);
2427 * If we can't get a cq entry, userspace overflowed the
2428 * submission (by quite a lot). Increment the overflow count in
2431 cqe = io_get_cqe(ctx);
2433 memcpy(cqe, &req->cqe, sizeof(*cqe));
2436 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2437 req->cqe.res, req->cqe.flags, 0, 0);
2440 static inline bool __io_fill_cqe32_req_filled(struct io_ring_ctx *ctx,
2441 struct io_kiocb *req)
2443 struct io_uring_cqe *cqe;
2444 u64 extra1 = req->extra1;
2445 u64 extra2 = req->extra2;
2447 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2448 req->cqe.res, req->cqe.flags, extra1, extra2);
2451 * If we can't get a cq entry, userspace overflowed the
2452 * submission (by quite a lot). Increment the overflow count in
2455 cqe = io_get_cqe(ctx);
2457 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2458 cqe->big_cqe[0] = extra1;
2459 cqe->big_cqe[1] = extra2;
2463 return io_cqring_event_overflow(ctx, req->cqe.user_data, req->cqe.res,
2464 req->cqe.flags, extra1, extra2);
2467 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2469 trace_io_uring_complete(req->ctx, req, req->cqe.user_data, res, cflags, 0, 0);
2470 return __io_fill_cqe(req->ctx, req->cqe.user_data, res, cflags);
2473 static inline void __io_fill_cqe32_req(struct io_kiocb *req, s32 res, u32 cflags,
2474 u64 extra1, u64 extra2)
2476 struct io_ring_ctx *ctx = req->ctx;
2477 struct io_uring_cqe *cqe;
2479 if (WARN_ON_ONCE(!(ctx->flags & IORING_SETUP_CQE32)))
2481 if (req->flags & REQ_F_CQE_SKIP)
2484 trace_io_uring_complete(ctx, req, req->cqe.user_data, res, cflags,
2488 * If we can't get a cq entry, userspace overflowed the
2489 * submission (by quite a lot). Increment the overflow count in
2492 cqe = io_get_cqe(ctx);
2494 WRITE_ONCE(cqe->user_data, req->cqe.user_data);
2495 WRITE_ONCE(cqe->res, res);
2496 WRITE_ONCE(cqe->flags, cflags);
2497 WRITE_ONCE(cqe->big_cqe[0], extra1);
2498 WRITE_ONCE(cqe->big_cqe[1], extra2);
2502 io_cqring_event_overflow(ctx, req->cqe.user_data, res, cflags, extra1, extra2);
2505 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2506 s32 res, u32 cflags)
2509 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2510 return __io_fill_cqe(ctx, user_data, res, cflags);
2513 static void __io_req_complete_put(struct io_kiocb *req)
2516 * If we're the last reference to this request, add to our locked
2519 if (req_ref_put_and_test(req)) {
2520 struct io_ring_ctx *ctx = req->ctx;
2522 if (req->flags & IO_REQ_LINK_FLAGS) {
2523 if (req->flags & IO_DISARM_MASK)
2524 io_disarm_next(req);
2526 io_req_task_queue(req->link);
2530 io_req_put_rsrc(req);
2532 * Selected buffer deallocation in io_clean_op() assumes that
2533 * we don't hold ->completion_lock. Clean them here to avoid
2536 io_put_kbuf_comp(req);
2537 io_dismantle_req(req);
2538 io_put_task(req->task, 1);
2539 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2540 ctx->locked_free_nr++;
2544 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2547 if (!(req->flags & REQ_F_CQE_SKIP))
2548 __io_fill_cqe_req(req, res, cflags);
2549 __io_req_complete_put(req);
2552 static void __io_req_complete_post32(struct io_kiocb *req, s32 res,
2553 u32 cflags, u64 extra1, u64 extra2)
2555 if (!(req->flags & REQ_F_CQE_SKIP))
2556 __io_fill_cqe32_req(req, res, cflags, extra1, extra2);
2557 __io_req_complete_put(req);
2560 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2562 struct io_ring_ctx *ctx = req->ctx;
2564 spin_lock(&ctx->completion_lock);
2565 __io_req_complete_post(req, res, cflags);
2566 io_commit_cqring(ctx);
2567 spin_unlock(&ctx->completion_lock);
2568 io_cqring_ev_posted(ctx);
2571 static void io_req_complete_post32(struct io_kiocb *req, s32 res,
2572 u32 cflags, u64 extra1, u64 extra2)
2574 struct io_ring_ctx *ctx = req->ctx;
2576 spin_lock(&ctx->completion_lock);
2577 __io_req_complete_post32(req, res, cflags, extra1, extra2);
2578 io_commit_cqring(ctx);
2579 spin_unlock(&ctx->completion_lock);
2580 io_cqring_ev_posted(ctx);
2583 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2587 req->cqe.flags = cflags;
2588 req->flags |= REQ_F_COMPLETE_INLINE;
2591 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2592 s32 res, u32 cflags)
2594 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2595 io_req_complete_state(req, res, cflags);
2597 io_req_complete_post(req, res, cflags);
2600 static inline void __io_req_complete32(struct io_kiocb *req,
2601 unsigned int issue_flags, s32 res,
2602 u32 cflags, u64 extra1, u64 extra2)
2604 if (issue_flags & IO_URING_F_COMPLETE_DEFER) {
2605 io_req_complete_state(req, res, cflags);
2606 req->extra1 = extra1;
2607 req->extra2 = extra2;
2609 io_req_complete_post32(req, res, cflags, extra1, extra2);
2613 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2617 __io_req_complete(req, 0, res, 0);
2620 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2623 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2627 * Don't initialise the fields below on every allocation, but do that in
2628 * advance and keep them valid across allocations.
2630 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2634 req->async_data = NULL;
2635 /* not necessary, but safer to zero */
2639 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2640 struct io_submit_state *state)
2642 spin_lock(&ctx->completion_lock);
2643 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2644 ctx->locked_free_nr = 0;
2645 spin_unlock(&ctx->completion_lock);
2648 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2650 return !ctx->submit_state.free_list.next;
2654 * A request might get retired back into the request caches even before opcode
2655 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2656 * Because of that, io_alloc_req() should be called only under ->uring_lock
2657 * and with extra caution to not get a request that is still worked on.
2659 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2660 __must_hold(&ctx->uring_lock)
2662 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2663 void *reqs[IO_REQ_ALLOC_BATCH];
2667 * If we have more than a batch's worth of requests in our IRQ side
2668 * locked cache, grab the lock and move them over to our submission
2671 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2672 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2673 if (!io_req_cache_empty(ctx))
2677 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2680 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2681 * retry single alloc to be on the safe side.
2683 if (unlikely(ret <= 0)) {
2684 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2690 percpu_ref_get_many(&ctx->refs, ret);
2691 for (i = 0; i < ret; i++) {
2692 struct io_kiocb *req = reqs[i];
2694 io_preinit_req(req, ctx);
2695 io_req_add_to_cache(req, ctx);
2700 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2702 if (unlikely(io_req_cache_empty(ctx)))
2703 return __io_alloc_req_refill(ctx);
2707 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2709 struct io_wq_work_node *node;
2711 node = wq_stack_extract(&ctx->submit_state.free_list);
2712 return container_of(node, struct io_kiocb, comp_list);
2715 static inline void io_put_file(struct file *file)
2721 static inline void io_dismantle_req(struct io_kiocb *req)
2723 unsigned int flags = req->flags;
2725 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2727 if (!(flags & REQ_F_FIXED_FILE))
2728 io_put_file(req->file);
2731 static __cold void io_free_req(struct io_kiocb *req)
2733 struct io_ring_ctx *ctx = req->ctx;
2735 io_req_put_rsrc(req);
2736 io_dismantle_req(req);
2737 io_put_task(req->task, 1);
2739 spin_lock(&ctx->completion_lock);
2740 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2741 ctx->locked_free_nr++;
2742 spin_unlock(&ctx->completion_lock);
2745 static inline void io_remove_next_linked(struct io_kiocb *req)
2747 struct io_kiocb *nxt = req->link;
2749 req->link = nxt->link;
2753 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2754 __must_hold(&req->ctx->completion_lock)
2755 __must_hold(&req->ctx->timeout_lock)
2757 struct io_kiocb *link = req->link;
2759 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2760 struct io_timeout_data *io = link->async_data;
2762 io_remove_next_linked(req);
2763 link->timeout.head = NULL;
2764 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2765 list_del(&link->timeout.list);
2772 static void io_fail_links(struct io_kiocb *req)
2773 __must_hold(&req->ctx->completion_lock)
2775 struct io_kiocb *nxt, *link = req->link;
2776 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2780 long res = -ECANCELED;
2782 if (link->flags & REQ_F_FAIL)
2783 res = link->cqe.res;
2788 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2792 link->flags |= REQ_F_CQE_SKIP;
2794 link->flags &= ~REQ_F_CQE_SKIP;
2795 __io_req_complete_post(link, res, 0);
2800 static bool io_disarm_next(struct io_kiocb *req)
2801 __must_hold(&req->ctx->completion_lock)
2803 struct io_kiocb *link = NULL;
2804 bool posted = false;
2806 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2808 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2809 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2810 io_remove_next_linked(req);
2811 io_req_tw_post_queue(link, -ECANCELED, 0);
2814 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2815 struct io_ring_ctx *ctx = req->ctx;
2817 spin_lock_irq(&ctx->timeout_lock);
2818 link = io_disarm_linked_timeout(req);
2819 spin_unlock_irq(&ctx->timeout_lock);
2822 io_req_tw_post_queue(link, -ECANCELED, 0);
2825 if (unlikely((req->flags & REQ_F_FAIL) &&
2826 !(req->flags & REQ_F_HARDLINK))) {
2827 posted |= (req->link != NULL);
2833 static void __io_req_find_next_prep(struct io_kiocb *req)
2835 struct io_ring_ctx *ctx = req->ctx;
2838 spin_lock(&ctx->completion_lock);
2839 posted = io_disarm_next(req);
2840 io_commit_cqring(ctx);
2841 spin_unlock(&ctx->completion_lock);
2843 io_cqring_ev_posted(ctx);
2846 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2848 struct io_kiocb *nxt;
2851 * If LINK is set, we have dependent requests in this chain. If we
2852 * didn't fail this request, queue the first one up, moving any other
2853 * dependencies to the next request. In case of failure, fail the rest
2856 if (unlikely(req->flags & IO_DISARM_MASK))
2857 __io_req_find_next_prep(req);
2863 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2867 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2868 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2870 io_submit_flush_completions(ctx);
2871 mutex_unlock(&ctx->uring_lock);
2874 percpu_ref_put(&ctx->refs);
2877 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2879 io_commit_cqring(ctx);
2880 spin_unlock(&ctx->completion_lock);
2881 io_cqring_ev_posted(ctx);
2884 static void handle_prev_tw_list(struct io_wq_work_node *node,
2885 struct io_ring_ctx **ctx, bool *uring_locked)
2887 if (*ctx && !*uring_locked)
2888 spin_lock(&(*ctx)->completion_lock);
2891 struct io_wq_work_node *next = node->next;
2892 struct io_kiocb *req = container_of(node, struct io_kiocb,
2895 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2897 if (req->ctx != *ctx) {
2898 if (unlikely(!*uring_locked && *ctx))
2899 ctx_commit_and_unlock(*ctx);
2901 ctx_flush_and_put(*ctx, uring_locked);
2903 /* if not contended, grab and improve batching */
2904 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2905 percpu_ref_get(&(*ctx)->refs);
2906 if (unlikely(!*uring_locked))
2907 spin_lock(&(*ctx)->completion_lock);
2909 if (likely(*uring_locked))
2910 req->io_task_work.func(req, uring_locked);
2912 __io_req_complete_post(req, req->cqe.res,
2913 io_put_kbuf_comp(req));
2917 if (unlikely(!*uring_locked))
2918 ctx_commit_and_unlock(*ctx);
2921 static void handle_tw_list(struct io_wq_work_node *node,
2922 struct io_ring_ctx **ctx, bool *locked)
2925 struct io_wq_work_node *next = node->next;
2926 struct io_kiocb *req = container_of(node, struct io_kiocb,
2929 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2931 if (req->ctx != *ctx) {
2932 ctx_flush_and_put(*ctx, locked);
2934 /* if not contended, grab and improve batching */
2935 *locked = mutex_trylock(&(*ctx)->uring_lock);
2936 percpu_ref_get(&(*ctx)->refs);
2938 req->io_task_work.func(req, locked);
2943 static void tctx_task_work(struct callback_head *cb)
2945 bool uring_locked = false;
2946 struct io_ring_ctx *ctx = NULL;
2947 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2951 struct io_wq_work_node *node1, *node2;
2953 spin_lock_irq(&tctx->task_lock);
2954 node1 = tctx->prio_task_list.first;
2955 node2 = tctx->task_list.first;
2956 INIT_WQ_LIST(&tctx->task_list);
2957 INIT_WQ_LIST(&tctx->prio_task_list);
2958 if (!node2 && !node1)
2959 tctx->task_running = false;
2960 spin_unlock_irq(&tctx->task_lock);
2961 if (!node2 && !node1)
2965 handle_prev_tw_list(node1, &ctx, &uring_locked);
2967 handle_tw_list(node2, &ctx, &uring_locked);
2970 if (data_race(!tctx->task_list.first) &&
2971 data_race(!tctx->prio_task_list.first) && uring_locked)
2972 io_submit_flush_completions(ctx);
2975 ctx_flush_and_put(ctx, &uring_locked);
2977 /* relaxed read is enough as only the task itself sets ->in_idle */
2978 if (unlikely(atomic_read(&tctx->in_idle)))
2979 io_uring_drop_tctx_refs(current);
2982 static void __io_req_task_work_add(struct io_kiocb *req,
2983 struct io_uring_task *tctx,
2984 struct io_wq_work_list *list)
2986 struct io_ring_ctx *ctx = req->ctx;
2987 struct io_wq_work_node *node;
2988 unsigned long flags;
2991 io_drop_inflight_file(req);
2993 spin_lock_irqsave(&tctx->task_lock, flags);
2994 wq_list_add_tail(&req->io_task_work.node, list);
2995 running = tctx->task_running;
2997 tctx->task_running = true;
2998 spin_unlock_irqrestore(&tctx->task_lock, flags);
3000 /* task_work already pending, we're done */
3004 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
3005 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
3007 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
3010 spin_lock_irqsave(&tctx->task_lock, flags);
3011 tctx->task_running = false;
3012 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
3013 spin_unlock_irqrestore(&tctx->task_lock, flags);
3016 req = container_of(node, struct io_kiocb, io_task_work.node);
3018 if (llist_add(&req->io_task_work.fallback_node,
3019 &req->ctx->fallback_llist))
3020 schedule_delayed_work(&req->ctx->fallback_work, 1);
3024 static void io_req_task_work_add(struct io_kiocb *req)
3026 struct io_uring_task *tctx = req->task->io_uring;
3028 __io_req_task_work_add(req, tctx, &tctx->task_list);
3031 static void io_req_task_prio_work_add(struct io_kiocb *req)
3033 struct io_uring_task *tctx = req->task->io_uring;
3035 if (req->ctx->flags & IORING_SETUP_SQPOLL)
3036 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
3038 __io_req_task_work_add(req, tctx, &tctx->task_list);
3041 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
3043 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
3046 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
3049 req->cqe.flags = cflags;
3050 req->io_task_work.func = io_req_tw_post;
3051 io_req_task_work_add(req);
3054 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
3056 /* not needed for normal modes, but SQPOLL depends on it */
3057 io_tw_lock(req->ctx, locked);
3058 io_req_complete_failed(req, req->cqe.res);
3061 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
3063 io_tw_lock(req->ctx, locked);
3064 /* req->task == current here, checking PF_EXITING is safe */
3065 if (likely(!(req->task->flags & PF_EXITING)))
3068 io_req_complete_failed(req, -EFAULT);
3071 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
3074 req->io_task_work.func = io_req_task_cancel;
3075 io_req_task_work_add(req);
3078 static void io_req_task_queue(struct io_kiocb *req)
3080 req->io_task_work.func = io_req_task_submit;
3081 io_req_task_work_add(req);
3084 static void io_req_task_queue_reissue(struct io_kiocb *req)
3086 req->io_task_work.func = io_queue_iowq;
3087 io_req_task_work_add(req);
3090 static void io_queue_next(struct io_kiocb *req)
3092 struct io_kiocb *nxt = io_req_find_next(req);
3095 io_req_task_queue(nxt);
3098 static void io_free_batch_list(struct io_ring_ctx *ctx,
3099 struct io_wq_work_node *node)
3100 __must_hold(&ctx->uring_lock)
3102 struct task_struct *task = NULL;
3106 struct io_kiocb *req = container_of(node, struct io_kiocb,
3109 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
3110 if (req->flags & REQ_F_REFCOUNT) {
3111 node = req->comp_list.next;
3112 if (!req_ref_put_and_test(req))
3115 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3116 struct async_poll *apoll = req->apoll;
3118 if (apoll->double_poll)
3119 kfree(apoll->double_poll);
3120 list_add(&apoll->poll.wait.entry,
3122 req->flags &= ~REQ_F_POLLED;
3124 if (req->flags & IO_REQ_LINK_FLAGS)
3126 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
3129 if (!(req->flags & REQ_F_FIXED_FILE))
3130 io_put_file(req->file);
3132 io_req_put_rsrc_locked(req, ctx);
3134 if (req->task != task) {
3136 io_put_task(task, task_refs);
3141 node = req->comp_list.next;
3142 io_req_add_to_cache(req, ctx);
3146 io_put_task(task, task_refs);
3149 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
3150 __must_hold(&ctx->uring_lock)
3152 struct io_wq_work_node *node, *prev;
3153 struct io_submit_state *state = &ctx->submit_state;
3155 if (state->flush_cqes) {
3156 spin_lock(&ctx->completion_lock);
3157 wq_list_for_each(node, prev, &state->compl_reqs) {
3158 struct io_kiocb *req = container_of(node, struct io_kiocb,
3161 if (!(req->flags & REQ_F_CQE_SKIP)) {
3162 if (!(ctx->flags & IORING_SETUP_CQE32))
3163 __io_fill_cqe_req_filled(ctx, req);
3165 __io_fill_cqe32_req_filled(ctx, req);
3169 io_commit_cqring(ctx);
3170 spin_unlock(&ctx->completion_lock);
3171 io_cqring_ev_posted(ctx);
3172 state->flush_cqes = false;
3175 io_free_batch_list(ctx, state->compl_reqs.first);
3176 INIT_WQ_LIST(&state->compl_reqs);
3180 * Drop reference to request, return next in chain (if there is one) if this
3181 * was the last reference to this request.
3183 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
3185 struct io_kiocb *nxt = NULL;
3187 if (req_ref_put_and_test(req)) {
3188 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
3189 nxt = io_req_find_next(req);
3195 static inline void io_put_req(struct io_kiocb *req)
3197 if (req_ref_put_and_test(req)) {
3203 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
3205 /* See comment at the top of this file */
3207 return __io_cqring_events(ctx);
3210 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
3212 struct io_rings *rings = ctx->rings;
3214 /* make sure SQ entry isn't read before tail */
3215 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3218 static inline bool io_run_task_work(void)
3220 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3221 __set_current_state(TASK_RUNNING);
3222 clear_notify_signal();
3223 if (task_work_pending(current))
3231 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3233 struct io_wq_work_node *pos, *start, *prev;
3234 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3235 DEFINE_IO_COMP_BATCH(iob);
3239 * Only spin for completions if we don't have multiple devices hanging
3240 * off our complete list.
3242 if (ctx->poll_multi_queue || force_nonspin)
3243 poll_flags |= BLK_POLL_ONESHOT;
3245 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3246 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3247 struct kiocb *kiocb = &req->rw.kiocb;
3251 * Move completed and retryable entries to our local lists.
3252 * If we find a request that requires polling, break out
3253 * and complete those lists first, if we have entries there.
3255 if (READ_ONCE(req->iopoll_completed))
3258 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3259 if (unlikely(ret < 0))
3262 poll_flags |= BLK_POLL_ONESHOT;
3264 /* iopoll may have completed current req */
3265 if (!rq_list_empty(iob.req_list) ||
3266 READ_ONCE(req->iopoll_completed))
3270 if (!rq_list_empty(iob.req_list))
3276 wq_list_for_each_resume(pos, prev) {
3277 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3279 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3280 if (!smp_load_acquire(&req->iopoll_completed))
3283 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3285 __io_fill_cqe_req(req, req->cqe.res, io_put_kbuf(req, 0));
3288 if (unlikely(!nr_events))
3291 io_commit_cqring(ctx);
3292 io_cqring_ev_posted_iopoll(ctx);
3293 pos = start ? start->next : ctx->iopoll_list.first;
3294 wq_list_cut(&ctx->iopoll_list, prev, start);
3295 io_free_batch_list(ctx, pos);
3300 * We can't just wait for polled events to come to us, we have to actively
3301 * find and complete them.
3303 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3305 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3308 mutex_lock(&ctx->uring_lock);
3309 while (!wq_list_empty(&ctx->iopoll_list)) {
3310 /* let it sleep and repeat later if can't complete a request */
3311 if (io_do_iopoll(ctx, true) == 0)
3314 * Ensure we allow local-to-the-cpu processing to take place,
3315 * in this case we need to ensure that we reap all events.
3316 * Also let task_work, etc. to progress by releasing the mutex
3318 if (need_resched()) {
3319 mutex_unlock(&ctx->uring_lock);
3321 mutex_lock(&ctx->uring_lock);
3324 mutex_unlock(&ctx->uring_lock);
3327 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3329 unsigned int nr_events = 0;
3331 unsigned long check_cq;
3334 * Don't enter poll loop if we already have events pending.
3335 * If we do, we can potentially be spinning for commands that
3336 * already triggered a CQE (eg in error).
3338 check_cq = READ_ONCE(ctx->check_cq);
3339 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3340 __io_cqring_overflow_flush(ctx, false);
3341 if (io_cqring_events(ctx))
3345 * Similarly do not spin if we have not informed the user of any
3348 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3353 * If a submit got punted to a workqueue, we can have the
3354 * application entering polling for a command before it gets
3355 * issued. That app will hold the uring_lock for the duration
3356 * of the poll right here, so we need to take a breather every
3357 * now and then to ensure that the issue has a chance to add
3358 * the poll to the issued list. Otherwise we can spin here
3359 * forever, while the workqueue is stuck trying to acquire the
3362 if (wq_list_empty(&ctx->iopoll_list)) {
3363 u32 tail = ctx->cached_cq_tail;
3365 mutex_unlock(&ctx->uring_lock);
3367 mutex_lock(&ctx->uring_lock);
3369 /* some requests don't go through iopoll_list */
3370 if (tail != ctx->cached_cq_tail ||
3371 wq_list_empty(&ctx->iopoll_list))
3374 ret = io_do_iopoll(ctx, !min);
3379 } while (nr_events < min && !need_resched());
3384 static void kiocb_end_write(struct io_kiocb *req)
3387 * Tell lockdep we inherited freeze protection from submission
3390 if (req->flags & REQ_F_ISREG) {
3391 struct super_block *sb = file_inode(req->file)->i_sb;
3393 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3399 static bool io_resubmit_prep(struct io_kiocb *req)
3401 struct io_async_rw *rw = req->async_data;
3403 if (!req_has_async_data(req))
3404 return !io_req_prep_async(req);
3405 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3409 static bool io_rw_should_reissue(struct io_kiocb *req)
3411 umode_t mode = file_inode(req->file)->i_mode;
3412 struct io_ring_ctx *ctx = req->ctx;
3414 if (!S_ISBLK(mode) && !S_ISREG(mode))
3416 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3417 !(ctx->flags & IORING_SETUP_IOPOLL)))
3420 * If ref is dying, we might be running poll reap from the exit work.
3421 * Don't attempt to reissue from that path, just let it fail with
3424 if (percpu_ref_is_dying(&ctx->refs))
3427 * Play it safe and assume not safe to re-import and reissue if we're
3428 * not in the original thread group (or in task context).
3430 if (!same_thread_group(req->task, current) || !in_task())
3435 static bool io_resubmit_prep(struct io_kiocb *req)
3439 static bool io_rw_should_reissue(struct io_kiocb *req)
3445 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3447 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3448 kiocb_end_write(req);
3449 fsnotify_modify(req->file);
3451 fsnotify_access(req->file);
3453 if (unlikely(res != req->cqe.res)) {
3454 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3455 io_rw_should_reissue(req)) {
3456 req->flags |= REQ_F_REISSUE;
3465 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3467 int res = req->cqe.res;
3470 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3471 io_req_add_compl_list(req);
3473 io_req_complete_post(req, res,
3474 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3478 static void __io_complete_rw(struct io_kiocb *req, long res,
3479 unsigned int issue_flags)
3481 if (__io_complete_rw_common(req, res))
3483 __io_req_complete(req, issue_flags, req->cqe.res,
3484 io_put_kbuf(req, issue_flags));
3487 static void io_complete_rw(struct kiocb *kiocb, long res)
3489 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3491 if (__io_complete_rw_common(req, res))
3494 req->io_task_work.func = io_req_task_complete;
3495 io_req_task_prio_work_add(req);
3498 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3500 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3502 if (kiocb->ki_flags & IOCB_WRITE)
3503 kiocb_end_write(req);
3504 if (unlikely(res != req->cqe.res)) {
3505 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3506 req->flags |= REQ_F_REISSUE;
3512 /* order with io_iopoll_complete() checking ->iopoll_completed */
3513 smp_store_release(&req->iopoll_completed, 1);
3517 * After the iocb has been issued, it's safe to be found on the poll list.
3518 * Adding the kiocb to the list AFTER submission ensures that we don't
3519 * find it from a io_do_iopoll() thread before the issuer is done
3520 * accessing the kiocb cookie.
3522 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3524 struct io_ring_ctx *ctx = req->ctx;
3525 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3527 /* workqueue context doesn't hold uring_lock, grab it now */
3528 if (unlikely(needs_lock))
3529 mutex_lock(&ctx->uring_lock);
3532 * Track whether we have multiple files in our lists. This will impact
3533 * how we do polling eventually, not spinning if we're on potentially
3534 * different devices.
3536 if (wq_list_empty(&ctx->iopoll_list)) {
3537 ctx->poll_multi_queue = false;
3538 } else if (!ctx->poll_multi_queue) {
3539 struct io_kiocb *list_req;
3541 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3543 if (list_req->file != req->file)
3544 ctx->poll_multi_queue = true;
3548 * For fast devices, IO may have already completed. If it has, add
3549 * it to the front so we find it first.
3551 if (READ_ONCE(req->iopoll_completed))
3552 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3554 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3556 if (unlikely(needs_lock)) {
3558 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3559 * in sq thread task context or in io worker task context. If
3560 * current task context is sq thread, we don't need to check
3561 * whether should wake up sq thread.
3563 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3564 wq_has_sleeper(&ctx->sq_data->wait))
3565 wake_up(&ctx->sq_data->wait);
3567 mutex_unlock(&ctx->uring_lock);
3571 static bool io_bdev_nowait(struct block_device *bdev)
3573 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3577 * If we tracked the file through the SCM inflight mechanism, we could support
3578 * any file. For now, just ensure that anything potentially problematic is done
3581 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3583 if (S_ISBLK(mode)) {
3584 if (IS_ENABLED(CONFIG_BLOCK) &&
3585 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3591 if (S_ISREG(mode)) {
3592 if (IS_ENABLED(CONFIG_BLOCK) &&
3593 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3594 file->f_op != &io_uring_fops)
3599 /* any ->read/write should understand O_NONBLOCK */
3600 if (file->f_flags & O_NONBLOCK)
3602 return file->f_mode & FMODE_NOWAIT;
3606 * If we tracked the file through the SCM inflight mechanism, we could support
3607 * any file. For now, just ensure that anything potentially problematic is done
3610 static unsigned int io_file_get_flags(struct file *file)
3612 umode_t mode = file_inode(file)->i_mode;
3613 unsigned int res = 0;
3617 if (__io_file_supports_nowait(file, mode))
3619 if (io_file_need_scm(file))
3624 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3626 return req->flags & REQ_F_SUPPORT_NOWAIT;
3629 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3631 struct kiocb *kiocb = &req->rw.kiocb;
3635 kiocb->ki_pos = READ_ONCE(sqe->off);
3637 ioprio = READ_ONCE(sqe->ioprio);
3639 ret = ioprio_check_cap(ioprio);
3643 kiocb->ki_ioprio = ioprio;
3645 kiocb->ki_ioprio = get_current_ioprio();
3649 req->rw.addr = READ_ONCE(sqe->addr);
3650 req->rw.len = READ_ONCE(sqe->len);
3651 req->rw.flags = READ_ONCE(sqe->rw_flags);
3652 /* used for fixed read/write too - just read unconditionally */
3653 req->buf_index = READ_ONCE(sqe->buf_index);
3657 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3663 case -ERESTARTNOINTR:
3664 case -ERESTARTNOHAND:
3665 case -ERESTART_RESTARTBLOCK:
3667 * We can't just restart the syscall, since previously
3668 * submitted sqes may already be in progress. Just fail this
3674 kiocb->ki_complete(kiocb, ret);
3678 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3680 struct kiocb *kiocb = &req->rw.kiocb;
3682 if (kiocb->ki_pos != -1)
3683 return &kiocb->ki_pos;
3685 if (!(req->file->f_mode & FMODE_STREAM)) {
3686 req->flags |= REQ_F_CUR_POS;
3687 kiocb->ki_pos = req->file->f_pos;
3688 return &kiocb->ki_pos;
3695 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3696 unsigned int issue_flags)
3698 struct io_async_rw *io = req->async_data;
3700 /* add previously done IO, if any */
3701 if (req_has_async_data(req) && io->bytes_done > 0) {
3703 ret = io->bytes_done;
3705 ret += io->bytes_done;
3708 if (req->flags & REQ_F_CUR_POS)
3709 req->file->f_pos = req->rw.kiocb.ki_pos;
3710 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3711 __io_complete_rw(req, ret, issue_flags);
3713 io_rw_done(&req->rw.kiocb, ret);
3715 if (req->flags & REQ_F_REISSUE) {
3716 req->flags &= ~REQ_F_REISSUE;
3717 if (io_resubmit_prep(req))
3718 io_req_task_queue_reissue(req);
3720 io_req_task_queue_fail(req, ret);
3724 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3725 struct io_mapped_ubuf *imu)
3727 size_t len = req->rw.len;
3728 u64 buf_end, buf_addr = req->rw.addr;
3731 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3733 /* not inside the mapped region */
3734 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3738 * May not be a start of buffer, set size appropriately
3739 * and advance us to the beginning.
3741 offset = buf_addr - imu->ubuf;
3742 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3746 * Don't use iov_iter_advance() here, as it's really slow for
3747 * using the latter parts of a big fixed buffer - it iterates
3748 * over each segment manually. We can cheat a bit here, because
3751 * 1) it's a BVEC iter, we set it up
3752 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3753 * first and last bvec
3755 * So just find our index, and adjust the iterator afterwards.
3756 * If the offset is within the first bvec (or the whole first
3757 * bvec, just use iov_iter_advance(). This makes it easier
3758 * since we can just skip the first segment, which may not
3759 * be PAGE_SIZE aligned.
3761 const struct bio_vec *bvec = imu->bvec;
3763 if (offset <= bvec->bv_len) {
3764 iov_iter_advance(iter, offset);
3766 unsigned long seg_skip;
3768 /* skip first vec */
3769 offset -= bvec->bv_len;
3770 seg_skip = 1 + (offset >> PAGE_SHIFT);
3772 iter->bvec = bvec + seg_skip;
3773 iter->nr_segs -= seg_skip;
3774 iter->count -= bvec->bv_len + offset;
3775 iter->iov_offset = offset & ~PAGE_MASK;
3782 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3783 unsigned int issue_flags)
3785 struct io_mapped_ubuf *imu = req->imu;
3786 u16 index, buf_index = req->buf_index;
3789 struct io_ring_ctx *ctx = req->ctx;
3791 if (unlikely(buf_index >= ctx->nr_user_bufs))
3793 io_req_set_rsrc_node(req, ctx, issue_flags);
3794 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3795 imu = READ_ONCE(ctx->user_bufs[index]);
3798 return __io_import_fixed(req, rw, iter, imu);
3801 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3802 struct io_buffer_list *bl, unsigned int bgid)
3805 if (bgid < BGID_ARRAY)
3808 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3811 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3812 struct io_buffer_list *bl)
3814 if (!list_empty(&bl->buf_list)) {
3815 struct io_buffer *kbuf;
3817 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3818 list_del(&kbuf->list);
3819 if (*len > kbuf->len)
3821 req->flags |= REQ_F_BUFFER_SELECTED;
3823 req->buf_index = kbuf->bid;
3824 return u64_to_user_ptr(kbuf->addr);
3829 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3830 struct io_buffer_list *bl,
3831 unsigned int issue_flags)
3833 struct io_uring_buf_ring *br = bl->buf_ring;
3834 struct io_uring_buf *buf;
3835 __u32 head = bl->head;
3837 if (unlikely(smp_load_acquire(&br->tail) == head)) {
3838 io_ring_submit_unlock(req->ctx, issue_flags);
3843 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3844 buf = &br->bufs[head];
3846 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3847 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE - 1;
3848 buf = page_address(bl->buf_pages[index]);
3851 if (*len > buf->len)
3853 req->flags |= REQ_F_BUFFER_RING;
3855 req->buf_index = buf->bid;
3857 if (issue_flags & IO_URING_F_UNLOCKED) {
3859 * If we came in unlocked, we have no choice but to consume the
3860 * buffer here. This does mean it'll be pinned until the IO
3861 * completes. But coming in unlocked means we're in io-wq
3862 * context, hence there should be no further retry. For the
3863 * locked case, the caller must ensure to call the commit when
3864 * the transfer completes (or if we get -EAGAIN and must poll
3867 req->buf_list = NULL;
3870 return u64_to_user_ptr(buf->addr);
3873 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3874 unsigned int issue_flags)
3876 struct io_ring_ctx *ctx = req->ctx;
3877 struct io_buffer_list *bl;
3878 void __user *ret = NULL;
3880 io_ring_submit_lock(req->ctx, issue_flags);
3882 bl = io_buffer_get_list(ctx, req->buf_index);
3884 if (bl->buf_nr_pages)
3885 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3887 ret = io_provided_buffer_select(req, len, bl);
3889 io_ring_submit_unlock(req->ctx, issue_flags);
3893 #ifdef CONFIG_COMPAT
3894 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3895 unsigned int issue_flags)
3897 struct compat_iovec __user *uiov;
3898 compat_ssize_t clen;
3902 uiov = u64_to_user_ptr(req->rw.addr);
3903 if (!access_ok(uiov, sizeof(*uiov)))
3905 if (__get_user(clen, &uiov->iov_len))
3911 buf = io_buffer_select(req, &len, issue_flags);
3914 req->rw.addr = (unsigned long) buf;
3915 iov[0].iov_base = buf;
3916 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3921 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3922 unsigned int issue_flags)
3924 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3928 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3931 len = iov[0].iov_len;
3934 buf = io_buffer_select(req, &len, issue_flags);
3937 req->rw.addr = (unsigned long) buf;
3938 iov[0].iov_base = buf;
3939 req->rw.len = iov[0].iov_len = len;
3943 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3944 unsigned int issue_flags)
3946 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3947 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3948 iov[0].iov_len = req->rw.len;
3951 if (req->rw.len != 1)
3954 #ifdef CONFIG_COMPAT
3955 if (req->ctx->compat)
3956 return io_compat_import(req, iov, issue_flags);
3959 return __io_iov_buffer_select(req, iov, issue_flags);
3962 static inline bool io_do_buffer_select(struct io_kiocb *req)
3964 if (!(req->flags & REQ_F_BUFFER_SELECT))
3966 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3969 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3970 struct io_rw_state *s,
3971 unsigned int issue_flags)
3973 struct iov_iter *iter = &s->iter;
3974 u8 opcode = req->opcode;
3975 struct iovec *iovec;
3980 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3981 ret = io_import_fixed(req, rw, iter, issue_flags);
3983 return ERR_PTR(ret);
3987 buf = u64_to_user_ptr(req->rw.addr);
3988 sqe_len = req->rw.len;
3990 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3991 if (io_do_buffer_select(req)) {
3992 buf = io_buffer_select(req, &sqe_len, issue_flags);
3994 return ERR_PTR(-ENOBUFS);
3995 req->rw.addr = (unsigned long) buf;
3996 req->rw.len = sqe_len;
3999 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
4001 return ERR_PTR(ret);
4005 iovec = s->fast_iov;
4006 if (req->flags & REQ_F_BUFFER_SELECT) {
4007 ret = io_iov_buffer_select(req, iovec, issue_flags);
4009 return ERR_PTR(ret);
4010 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
4014 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
4016 if (unlikely(ret < 0))
4017 return ERR_PTR(ret);
4021 static inline int io_import_iovec(int rw, struct io_kiocb *req,
4022 struct iovec **iovec, struct io_rw_state *s,
4023 unsigned int issue_flags)
4025 *iovec = __io_import_iovec(rw, req, s, issue_flags);
4026 if (unlikely(IS_ERR(*iovec)))
4027 return PTR_ERR(*iovec);
4029 iov_iter_save_state(&s->iter, &s->iter_state);
4033 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
4035 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
4039 * For files that don't have ->read_iter() and ->write_iter(), handle them
4040 * by looping over ->read() or ->write() manually.
4042 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
4044 struct kiocb *kiocb = &req->rw.kiocb;
4045 struct file *file = req->file;
4050 * Don't support polled IO through this interface, and we can't
4051 * support non-blocking either. For the latter, this just causes
4052 * the kiocb to be handled from an async context.
4054 if (kiocb->ki_flags & IOCB_HIPRI)
4056 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
4057 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
4060 ppos = io_kiocb_ppos(kiocb);
4062 while (iov_iter_count(iter)) {
4066 if (!iov_iter_is_bvec(iter)) {
4067 iovec = iov_iter_iovec(iter);
4069 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
4070 iovec.iov_len = req->rw.len;
4074 nr = file->f_op->read(file, iovec.iov_base,
4075 iovec.iov_len, ppos);
4077 nr = file->f_op->write(file, iovec.iov_base,
4078 iovec.iov_len, ppos);
4087 if (!iov_iter_is_bvec(iter)) {
4088 iov_iter_advance(iter, nr);
4095 if (nr != iovec.iov_len)
4102 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
4103 const struct iovec *fast_iov, struct iov_iter *iter)
4105 struct io_async_rw *rw = req->async_data;
4107 memcpy(&rw->s.iter, iter, sizeof(*iter));
4108 rw->free_iovec = iovec;
4110 /* can only be fixed buffers, no need to do anything */
4111 if (iov_iter_is_bvec(iter))
4114 unsigned iov_off = 0;
4116 rw->s.iter.iov = rw->s.fast_iov;
4117 if (iter->iov != fast_iov) {
4118 iov_off = iter->iov - fast_iov;
4119 rw->s.iter.iov += iov_off;
4121 if (rw->s.fast_iov != fast_iov)
4122 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
4123 sizeof(struct iovec) * iter->nr_segs);
4125 req->flags |= REQ_F_NEED_CLEANUP;
4129 static inline bool io_alloc_async_data(struct io_kiocb *req)
4131 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
4132 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
4133 if (req->async_data) {
4134 req->flags |= REQ_F_ASYNC_DATA;
4140 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
4141 struct io_rw_state *s, bool force)
4143 if (!force && !io_op_defs[req->opcode].needs_async_setup)
4145 if (!req_has_async_data(req)) {
4146 struct io_async_rw *iorw;
4148 if (io_alloc_async_data(req)) {
4153 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
4154 iorw = req->async_data;
4155 /* we've copied and mapped the iter, ensure state is saved */
4156 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
4161 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
4163 struct io_async_rw *iorw = req->async_data;
4167 /* submission path, ->uring_lock should already be taken */
4168 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
4169 if (unlikely(ret < 0))
4172 iorw->bytes_done = 0;
4173 iorw->free_iovec = iov;
4175 req->flags |= REQ_F_NEED_CLEANUP;
4180 * This is our waitqueue callback handler, registered through __folio_lock_async()
4181 * when we initially tried to do the IO with the iocb armed our waitqueue.
4182 * This gets called when the page is unlocked, and we generally expect that to
4183 * happen when the page IO is completed and the page is now uptodate. This will
4184 * queue a task_work based retry of the operation, attempting to copy the data
4185 * again. If the latter fails because the page was NOT uptodate, then we will
4186 * do a thread based blocking retry of the operation. That's the unexpected
4189 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
4190 int sync, void *arg)
4192 struct wait_page_queue *wpq;
4193 struct io_kiocb *req = wait->private;
4194 struct wait_page_key *key = arg;
4196 wpq = container_of(wait, struct wait_page_queue, wait);
4198 if (!wake_page_match(wpq, key))
4201 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
4202 list_del_init(&wait->entry);
4203 io_req_task_queue(req);
4208 * This controls whether a given IO request should be armed for async page
4209 * based retry. If we return false here, the request is handed to the async
4210 * worker threads for retry. If we're doing buffered reads on a regular file,
4211 * we prepare a private wait_page_queue entry and retry the operation. This
4212 * will either succeed because the page is now uptodate and unlocked, or it
4213 * will register a callback when the page is unlocked at IO completion. Through
4214 * that callback, io_uring uses task_work to setup a retry of the operation.
4215 * That retry will attempt the buffered read again. The retry will generally
4216 * succeed, or in rare cases where it fails, we then fall back to using the
4217 * async worker threads for a blocking retry.
4219 static bool io_rw_should_retry(struct io_kiocb *req)
4221 struct io_async_rw *rw = req->async_data;
4222 struct wait_page_queue *wait = &rw->wpq;
4223 struct kiocb *kiocb = &req->rw.kiocb;
4225 /* never retry for NOWAIT, we just complete with -EAGAIN */
4226 if (req->flags & REQ_F_NOWAIT)
4229 /* Only for buffered IO */
4230 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4234 * just use poll if we can, and don't attempt if the fs doesn't
4235 * support callback based unlocks
4237 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4240 wait->wait.func = io_async_buf_func;
4241 wait->wait.private = req;
4242 wait->wait.flags = 0;
4243 INIT_LIST_HEAD(&wait->wait.entry);
4244 kiocb->ki_flags |= IOCB_WAITQ;
4245 kiocb->ki_flags &= ~IOCB_NOWAIT;
4246 kiocb->ki_waitq = wait;
4250 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4252 if (likely(req->file->f_op->read_iter))
4253 return call_read_iter(req->file, &req->rw.kiocb, iter);
4254 else if (req->file->f_op->read)
4255 return loop_rw_iter(READ, req, iter);
4260 static bool need_read_all(struct io_kiocb *req)
4262 return req->flags & REQ_F_ISREG ||
4263 S_ISBLK(file_inode(req->file)->i_mode);
4266 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4268 struct kiocb *kiocb = &req->rw.kiocb;
4269 struct io_ring_ctx *ctx = req->ctx;
4270 struct file *file = req->file;
4273 if (unlikely(!file || !(file->f_mode & mode)))
4276 if (!io_req_ffs_set(req))
4277 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4279 kiocb->ki_flags = iocb_flags(file);
4280 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4285 * If the file is marked O_NONBLOCK, still allow retry for it if it
4286 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4287 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4289 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4290 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4291 req->flags |= REQ_F_NOWAIT;
4293 if (ctx->flags & IORING_SETUP_IOPOLL) {
4294 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4297 kiocb->private = NULL;
4298 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4299 kiocb->ki_complete = io_complete_rw_iopoll;
4300 req->iopoll_completed = 0;
4302 if (kiocb->ki_flags & IOCB_HIPRI)
4304 kiocb->ki_complete = io_complete_rw;
4310 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4312 struct io_rw_state __s, *s = &__s;
4313 struct iovec *iovec;
4314 struct kiocb *kiocb = &req->rw.kiocb;
4315 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4316 struct io_async_rw *rw;
4320 if (!req_has_async_data(req)) {
4321 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4322 if (unlikely(ret < 0))
4326 * Safe and required to re-import if we're using provided
4327 * buffers, as we dropped the selected one before retry.
4329 if (req->flags & REQ_F_BUFFER_SELECT) {
4330 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4331 if (unlikely(ret < 0))
4335 rw = req->async_data;
4338 * We come here from an earlier attempt, restore our state to
4339 * match in case it doesn't. It's cheap enough that we don't
4340 * need to make this conditional.
4342 iov_iter_restore(&s->iter, &s->iter_state);
4345 ret = io_rw_init_file(req, FMODE_READ);
4346 if (unlikely(ret)) {
4350 req->cqe.res = iov_iter_count(&s->iter);
4352 if (force_nonblock) {
4353 /* If the file doesn't support async, just async punt */
4354 if (unlikely(!io_file_supports_nowait(req))) {
4355 ret = io_setup_async_rw(req, iovec, s, true);
4356 return ret ?: -EAGAIN;
4358 kiocb->ki_flags |= IOCB_NOWAIT;
4360 /* Ensure we clear previously set non-block flag */
4361 kiocb->ki_flags &= ~IOCB_NOWAIT;
4364 ppos = io_kiocb_update_pos(req);
4366 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4367 if (unlikely(ret)) {
4372 ret = io_iter_do_read(req, &s->iter);
4374 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4375 req->flags &= ~REQ_F_REISSUE;
4376 /* if we can poll, just do that */
4377 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4379 /* IOPOLL retry should happen for io-wq threads */
4380 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4382 /* no retry on NONBLOCK nor RWF_NOWAIT */
4383 if (req->flags & REQ_F_NOWAIT)
4386 } else if (ret == -EIOCBQUEUED) {
4388 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4389 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4390 /* read all, failed, already did sync or don't want to retry */
4395 * Don't depend on the iter state matching what was consumed, or being
4396 * untouched in case of error. Restore it and we'll advance it
4397 * manually if we need to.
4399 iov_iter_restore(&s->iter, &s->iter_state);
4401 ret2 = io_setup_async_rw(req, iovec, s, true);
4406 rw = req->async_data;
4409 * Now use our persistent iterator and state, if we aren't already.
4410 * We've restored and mapped the iter to match.
4415 * We end up here because of a partial read, either from
4416 * above or inside this loop. Advance the iter by the bytes
4417 * that were consumed.
4419 iov_iter_advance(&s->iter, ret);
4420 if (!iov_iter_count(&s->iter))
4422 rw->bytes_done += ret;
4423 iov_iter_save_state(&s->iter, &s->iter_state);
4425 /* if we can retry, do so with the callbacks armed */
4426 if (!io_rw_should_retry(req)) {
4427 kiocb->ki_flags &= ~IOCB_WAITQ;
4432 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4433 * we get -EIOCBQUEUED, then we'll get a notification when the
4434 * desired page gets unlocked. We can also get a partial read
4435 * here, and if we do, then just retry at the new offset.
4437 ret = io_iter_do_read(req, &s->iter);
4438 if (ret == -EIOCBQUEUED)
4440 /* we got some bytes, but not all. retry. */
4441 kiocb->ki_flags &= ~IOCB_WAITQ;
4442 iov_iter_restore(&s->iter, &s->iter_state);
4445 kiocb_done(req, ret, issue_flags);
4447 /* it's faster to check here then delegate to kfree */
4453 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4455 struct io_rw_state __s, *s = &__s;
4456 struct iovec *iovec;
4457 struct kiocb *kiocb = &req->rw.kiocb;
4458 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4462 if (!req_has_async_data(req)) {
4463 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4464 if (unlikely(ret < 0))
4467 struct io_async_rw *rw = req->async_data;
4470 iov_iter_restore(&s->iter, &s->iter_state);
4473 ret = io_rw_init_file(req, FMODE_WRITE);
4474 if (unlikely(ret)) {
4478 req->cqe.res = iov_iter_count(&s->iter);
4480 if (force_nonblock) {
4481 /* If the file doesn't support async, just async punt */
4482 if (unlikely(!io_file_supports_nowait(req)))
4485 /* file path doesn't support NOWAIT for non-direct_IO */
4486 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4487 (req->flags & REQ_F_ISREG))
4490 kiocb->ki_flags |= IOCB_NOWAIT;
4492 /* Ensure we clear previously set non-block flag */
4493 kiocb->ki_flags &= ~IOCB_NOWAIT;
4496 ppos = io_kiocb_update_pos(req);
4498 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4503 * Open-code file_start_write here to grab freeze protection,
4504 * which will be released by another thread in
4505 * io_complete_rw(). Fool lockdep by telling it the lock got
4506 * released so that it doesn't complain about the held lock when
4507 * we return to userspace.
4509 if (req->flags & REQ_F_ISREG) {
4510 sb_start_write(file_inode(req->file)->i_sb);
4511 __sb_writers_release(file_inode(req->file)->i_sb,
4514 kiocb->ki_flags |= IOCB_WRITE;
4516 if (likely(req->file->f_op->write_iter))
4517 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4518 else if (req->file->f_op->write)
4519 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4523 if (req->flags & REQ_F_REISSUE) {
4524 req->flags &= ~REQ_F_REISSUE;
4529 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4530 * retry them without IOCB_NOWAIT.
4532 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4534 /* no retry on NONBLOCK nor RWF_NOWAIT */
4535 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4537 if (!force_nonblock || ret2 != -EAGAIN) {
4538 /* IOPOLL retry should happen for io-wq threads */
4539 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4542 kiocb_done(req, ret2, issue_flags);
4545 iov_iter_restore(&s->iter, &s->iter_state);
4546 ret = io_setup_async_rw(req, iovec, s, false);
4547 return ret ?: -EAGAIN;
4550 /* it's reportedly faster than delegating the null check to kfree() */
4556 static int io_renameat_prep(struct io_kiocb *req,
4557 const struct io_uring_sqe *sqe)
4559 struct io_rename *ren = &req->rename;
4560 const char __user *oldf, *newf;
4562 if (sqe->buf_index || sqe->splice_fd_in)
4564 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4567 ren->old_dfd = READ_ONCE(sqe->fd);
4568 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4569 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4570 ren->new_dfd = READ_ONCE(sqe->len);
4571 ren->flags = READ_ONCE(sqe->rename_flags);
4573 ren->oldpath = getname(oldf);
4574 if (IS_ERR(ren->oldpath))
4575 return PTR_ERR(ren->oldpath);
4577 ren->newpath = getname(newf);
4578 if (IS_ERR(ren->newpath)) {
4579 putname(ren->oldpath);
4580 return PTR_ERR(ren->newpath);
4583 req->flags |= REQ_F_NEED_CLEANUP;
4587 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4589 struct io_rename *ren = &req->rename;
4592 if (issue_flags & IO_URING_F_NONBLOCK)
4595 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4596 ren->newpath, ren->flags);
4598 req->flags &= ~REQ_F_NEED_CLEANUP;
4599 io_req_complete(req, ret);
4603 static inline void __io_xattr_finish(struct io_kiocb *req)
4605 struct io_xattr *ix = &req->xattr;
4608 putname(ix->filename);
4610 kfree(ix->ctx.kname);
4611 kvfree(ix->ctx.kvalue);
4614 static void io_xattr_finish(struct io_kiocb *req, int ret)
4616 req->flags &= ~REQ_F_NEED_CLEANUP;
4618 __io_xattr_finish(req);
4619 io_req_complete(req, ret);
4622 static int __io_getxattr_prep(struct io_kiocb *req,
4623 const struct io_uring_sqe *sqe)
4625 struct io_xattr *ix = &req->xattr;
4626 const char __user *name;
4629 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4632 ix->filename = NULL;
4633 ix->ctx.kvalue = NULL;
4634 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4635 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4636 ix->ctx.size = READ_ONCE(sqe->len);
4637 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4642 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4646 ret = strncpy_from_user(ix->ctx.kname->name, name,
4647 sizeof(ix->ctx.kname->name));
4648 if (!ret || ret == sizeof(ix->ctx.kname->name))
4651 kfree(ix->ctx.kname);
4655 req->flags |= REQ_F_NEED_CLEANUP;
4659 static int io_fgetxattr_prep(struct io_kiocb *req,
4660 const struct io_uring_sqe *sqe)
4662 return __io_getxattr_prep(req, sqe);
4665 static int io_getxattr_prep(struct io_kiocb *req,
4666 const struct io_uring_sqe *sqe)
4668 struct io_xattr *ix = &req->xattr;
4669 const char __user *path;
4672 ret = __io_getxattr_prep(req, sqe);
4676 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4678 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4679 if (IS_ERR(ix->filename)) {
4680 ret = PTR_ERR(ix->filename);
4681 ix->filename = NULL;
4687 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4689 struct io_xattr *ix = &req->xattr;
4692 if (issue_flags & IO_URING_F_NONBLOCK)
4695 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4696 req->file->f_path.dentry,
4699 io_xattr_finish(req, ret);
4703 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4705 struct io_xattr *ix = &req->xattr;
4706 unsigned int lookup_flags = LOOKUP_FOLLOW;
4710 if (issue_flags & IO_URING_F_NONBLOCK)
4714 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4716 ret = do_getxattr(mnt_user_ns(path.mnt),
4721 if (retry_estale(ret, lookup_flags)) {
4722 lookup_flags |= LOOKUP_REVAL;
4727 io_xattr_finish(req, ret);
4731 static int __io_setxattr_prep(struct io_kiocb *req,
4732 const struct io_uring_sqe *sqe)
4734 struct io_xattr *ix = &req->xattr;
4735 const char __user *name;
4738 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4741 ix->filename = NULL;
4742 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4743 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4744 ix->ctx.kvalue = NULL;
4745 ix->ctx.size = READ_ONCE(sqe->len);
4746 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4748 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4752 ret = setxattr_copy(name, &ix->ctx);
4754 kfree(ix->ctx.kname);
4758 req->flags |= REQ_F_NEED_CLEANUP;
4762 static int io_setxattr_prep(struct io_kiocb *req,
4763 const struct io_uring_sqe *sqe)
4765 struct io_xattr *ix = &req->xattr;
4766 const char __user *path;
4769 ret = __io_setxattr_prep(req, sqe);
4773 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4775 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4776 if (IS_ERR(ix->filename)) {
4777 ret = PTR_ERR(ix->filename);
4778 ix->filename = NULL;
4784 static int io_fsetxattr_prep(struct io_kiocb *req,
4785 const struct io_uring_sqe *sqe)
4787 return __io_setxattr_prep(req, sqe);
4790 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4793 struct io_xattr *ix = &req->xattr;
4796 ret = mnt_want_write(path->mnt);
4798 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4799 mnt_drop_write(path->mnt);
4805 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4809 if (issue_flags & IO_URING_F_NONBLOCK)
4812 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4813 io_xattr_finish(req, ret);
4818 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4820 struct io_xattr *ix = &req->xattr;
4821 unsigned int lookup_flags = LOOKUP_FOLLOW;
4825 if (issue_flags & IO_URING_F_NONBLOCK)
4829 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4831 ret = __io_setxattr(req, issue_flags, &path);
4833 if (retry_estale(ret, lookup_flags)) {
4834 lookup_flags |= LOOKUP_REVAL;
4839 io_xattr_finish(req, ret);
4843 static int io_unlinkat_prep(struct io_kiocb *req,
4844 const struct io_uring_sqe *sqe)
4846 struct io_unlink *un = &req->unlink;
4847 const char __user *fname;
4849 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4851 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4854 un->dfd = READ_ONCE(sqe->fd);
4856 un->flags = READ_ONCE(sqe->unlink_flags);
4857 if (un->flags & ~AT_REMOVEDIR)
4860 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4861 un->filename = getname(fname);
4862 if (IS_ERR(un->filename))
4863 return PTR_ERR(un->filename);
4865 req->flags |= REQ_F_NEED_CLEANUP;
4869 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4871 struct io_unlink *un = &req->unlink;
4874 if (issue_flags & IO_URING_F_NONBLOCK)
4877 if (un->flags & AT_REMOVEDIR)
4878 ret = do_rmdir(un->dfd, un->filename);
4880 ret = do_unlinkat(un->dfd, un->filename);
4882 req->flags &= ~REQ_F_NEED_CLEANUP;
4883 io_req_complete(req, ret);
4887 static int io_mkdirat_prep(struct io_kiocb *req,
4888 const struct io_uring_sqe *sqe)
4890 struct io_mkdir *mkd = &req->mkdir;
4891 const char __user *fname;
4893 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4895 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4898 mkd->dfd = READ_ONCE(sqe->fd);
4899 mkd->mode = READ_ONCE(sqe->len);
4901 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4902 mkd->filename = getname(fname);
4903 if (IS_ERR(mkd->filename))
4904 return PTR_ERR(mkd->filename);
4906 req->flags |= REQ_F_NEED_CLEANUP;
4910 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4912 struct io_mkdir *mkd = &req->mkdir;
4915 if (issue_flags & IO_URING_F_NONBLOCK)
4918 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4920 req->flags &= ~REQ_F_NEED_CLEANUP;
4921 io_req_complete(req, ret);
4925 static int io_symlinkat_prep(struct io_kiocb *req,
4926 const struct io_uring_sqe *sqe)
4928 struct io_symlink *sl = &req->symlink;
4929 const char __user *oldpath, *newpath;
4931 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4933 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4936 sl->new_dfd = READ_ONCE(sqe->fd);
4937 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4938 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4940 sl->oldpath = getname(oldpath);
4941 if (IS_ERR(sl->oldpath))
4942 return PTR_ERR(sl->oldpath);
4944 sl->newpath = getname(newpath);
4945 if (IS_ERR(sl->newpath)) {
4946 putname(sl->oldpath);
4947 return PTR_ERR(sl->newpath);
4950 req->flags |= REQ_F_NEED_CLEANUP;
4954 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4956 struct io_symlink *sl = &req->symlink;
4959 if (issue_flags & IO_URING_F_NONBLOCK)
4962 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4964 req->flags &= ~REQ_F_NEED_CLEANUP;
4965 io_req_complete(req, ret);
4969 static int io_linkat_prep(struct io_kiocb *req,
4970 const struct io_uring_sqe *sqe)
4972 struct io_hardlink *lnk = &req->hardlink;
4973 const char __user *oldf, *newf;
4975 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4977 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4980 lnk->old_dfd = READ_ONCE(sqe->fd);
4981 lnk->new_dfd = READ_ONCE(sqe->len);
4982 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4983 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4984 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4986 lnk->oldpath = getname(oldf);
4987 if (IS_ERR(lnk->oldpath))
4988 return PTR_ERR(lnk->oldpath);
4990 lnk->newpath = getname(newf);
4991 if (IS_ERR(lnk->newpath)) {
4992 putname(lnk->oldpath);
4993 return PTR_ERR(lnk->newpath);
4996 req->flags |= REQ_F_NEED_CLEANUP;
5000 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
5002 struct io_hardlink *lnk = &req->hardlink;
5005 if (issue_flags & IO_URING_F_NONBLOCK)
5008 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
5009 lnk->newpath, lnk->flags);
5011 req->flags &= ~REQ_F_NEED_CLEANUP;
5012 io_req_complete(req, ret);
5016 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
5018 req->uring_cmd.task_work_cb(&req->uring_cmd);
5021 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
5022 void (*task_work_cb)(struct io_uring_cmd *))
5024 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5026 req->uring_cmd.task_work_cb = task_work_cb;
5027 req->io_task_work.func = io_uring_cmd_work;
5028 io_req_task_prio_work_add(req);
5030 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
5033 * Called by consumers of io_uring_cmd, if they originally returned
5034 * -EIOCBQUEUED upon receiving the command.
5036 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
5038 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5042 if (req->ctx->flags & IORING_SETUP_CQE32)
5043 __io_req_complete32(req, 0, ret, 0, res2, 0);
5045 io_req_complete(req, ret);
5047 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
5049 static int io_uring_cmd_prep_async(struct io_kiocb *req)
5053 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
5055 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
5059 static int io_uring_cmd_prep(struct io_kiocb *req,
5060 const struct io_uring_sqe *sqe)
5062 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5066 ioucmd->cmd = sqe->cmd;
5067 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
5071 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
5073 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5074 struct io_ring_ctx *ctx = req->ctx;
5075 struct file *file = req->file;
5078 if (!req->file->f_op->uring_cmd)
5081 if (ctx->flags & IORING_SETUP_SQE128)
5082 issue_flags |= IO_URING_F_SQE128;
5083 if (ctx->flags & IORING_SETUP_CQE32)
5084 issue_flags |= IO_URING_F_CQE32;
5085 if (ctx->flags & IORING_SETUP_IOPOLL)
5086 issue_flags |= IO_URING_F_IOPOLL;
5088 if (req_has_async_data(req))
5089 ioucmd->cmd = req->async_data;
5091 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
5092 if (ret == -EAGAIN) {
5093 if (!req_has_async_data(req)) {
5094 if (io_alloc_async_data(req))
5096 io_uring_cmd_prep_async(req);
5101 if (ret != -EIOCBQUEUED)
5102 io_uring_cmd_done(ioucmd, ret, 0);
5106 static int io_shutdown_prep(struct io_kiocb *req,
5107 const struct io_uring_sqe *sqe)
5109 #if defined(CONFIG_NET)
5110 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
5111 sqe->buf_index || sqe->splice_fd_in))
5114 req->shutdown.how = READ_ONCE(sqe->len);
5121 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
5123 #if defined(CONFIG_NET)
5124 struct socket *sock;
5127 if (issue_flags & IO_URING_F_NONBLOCK)
5130 sock = sock_from_file(req->file);
5131 if (unlikely(!sock))
5134 ret = __sys_shutdown_sock(sock, req->shutdown.how);
5135 io_req_complete(req, ret);
5142 static int __io_splice_prep(struct io_kiocb *req,
5143 const struct io_uring_sqe *sqe)
5145 struct io_splice *sp = &req->splice;
5146 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
5148 sp->len = READ_ONCE(sqe->len);
5149 sp->flags = READ_ONCE(sqe->splice_flags);
5150 if (unlikely(sp->flags & ~valid_flags))
5152 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
5156 static int io_tee_prep(struct io_kiocb *req,
5157 const struct io_uring_sqe *sqe)
5159 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
5161 return __io_splice_prep(req, sqe);
5164 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
5166 struct io_splice *sp = &req->splice;
5167 struct file *out = sp->file_out;
5168 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5172 if (issue_flags & IO_URING_F_NONBLOCK)
5175 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5176 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5178 in = io_file_get_normal(req, sp->splice_fd_in);
5185 ret = do_tee(in, out, sp->len, flags);
5187 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5192 __io_req_complete(req, 0, ret, 0);
5196 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5198 struct io_splice *sp = &req->splice;
5200 sp->off_in = READ_ONCE(sqe->splice_off_in);
5201 sp->off_out = READ_ONCE(sqe->off);
5202 return __io_splice_prep(req, sqe);
5205 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5207 struct io_splice *sp = &req->splice;
5208 struct file *out = sp->file_out;
5209 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5210 loff_t *poff_in, *poff_out;
5214 if (issue_flags & IO_URING_F_NONBLOCK)
5217 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5218 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5220 in = io_file_get_normal(req, sp->splice_fd_in);
5226 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5227 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5230 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5232 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5237 __io_req_complete(req, 0, ret, 0);
5241 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5244 * If the ring is setup with CQE32, relay back addr/addr
5246 if (req->ctx->flags & IORING_SETUP_CQE32) {
5247 req->nop.extra1 = READ_ONCE(sqe->addr);
5248 req->nop.extra2 = READ_ONCE(sqe->addr2);
5255 * IORING_OP_NOP just posts a completion event, nothing else.
5257 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5259 unsigned int cflags;
5262 if (req->flags & REQ_F_BUFFER_SELECT) {
5265 buf = io_buffer_select(req, &len, issue_flags);
5270 cflags = io_put_kbuf(req, issue_flags);
5271 if (!(req->ctx->flags & IORING_SETUP_CQE32))
5272 __io_req_complete(req, issue_flags, 0, cflags);
5274 __io_req_complete32(req, issue_flags, 0, cflags,
5275 req->nop.extra1, req->nop.extra2);
5279 static int io_msg_ring_prep(struct io_kiocb *req,
5280 const struct io_uring_sqe *sqe)
5282 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5283 sqe->buf_index || sqe->personality))
5286 req->msg.user_data = READ_ONCE(sqe->off);
5287 req->msg.len = READ_ONCE(sqe->len);
5291 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5293 struct io_ring_ctx *target_ctx;
5294 struct io_msg *msg = &req->msg;
5299 if (req->file->f_op != &io_uring_fops)
5303 target_ctx = req->file->private_data;
5305 spin_lock(&target_ctx->completion_lock);
5306 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5307 io_commit_cqring(target_ctx);
5308 spin_unlock(&target_ctx->completion_lock);
5311 io_cqring_ev_posted(target_ctx);
5318 __io_req_complete(req, issue_flags, ret, 0);
5319 /* put file to avoid an attempt to IOPOLL the req */
5320 io_put_file(req->file);
5325 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5327 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5330 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5331 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5334 req->sync.off = READ_ONCE(sqe->off);
5335 req->sync.len = READ_ONCE(sqe->len);
5339 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5341 loff_t end = req->sync.off + req->sync.len;
5344 /* fsync always requires a blocking context */
5345 if (issue_flags & IO_URING_F_NONBLOCK)
5348 ret = vfs_fsync_range(req->file, req->sync.off,
5349 end > 0 ? end : LLONG_MAX,
5350 req->sync.flags & IORING_FSYNC_DATASYNC);
5351 io_req_complete(req, ret);
5355 static int io_fallocate_prep(struct io_kiocb *req,
5356 const struct io_uring_sqe *sqe)
5358 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5361 req->sync.off = READ_ONCE(sqe->off);
5362 req->sync.len = READ_ONCE(sqe->addr);
5363 req->sync.mode = READ_ONCE(sqe->len);
5367 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5371 /* fallocate always requiring blocking context */
5372 if (issue_flags & IO_URING_F_NONBLOCK)
5374 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5377 fsnotify_modify(req->file);
5378 io_req_complete(req, ret);
5382 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5384 const char __user *fname;
5387 if (unlikely(sqe->buf_index))
5389 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5392 /* open.how should be already initialised */
5393 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5394 req->open.how.flags |= O_LARGEFILE;
5396 req->open.dfd = READ_ONCE(sqe->fd);
5397 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5398 req->open.filename = getname(fname);
5399 if (IS_ERR(req->open.filename)) {
5400 ret = PTR_ERR(req->open.filename);
5401 req->open.filename = NULL;
5405 req->open.file_slot = READ_ONCE(sqe->file_index);
5406 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5409 req->open.nofile = rlimit(RLIMIT_NOFILE);
5410 req->flags |= REQ_F_NEED_CLEANUP;
5414 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5416 u64 mode = READ_ONCE(sqe->len);
5417 u64 flags = READ_ONCE(sqe->open_flags);
5419 req->open.how = build_open_how(flags, mode);
5420 return __io_openat_prep(req, sqe);
5423 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5425 struct open_how __user *how;
5429 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5430 len = READ_ONCE(sqe->len);
5431 if (len < OPEN_HOW_SIZE_VER0)
5434 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5439 return __io_openat_prep(req, sqe);
5442 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5444 struct io_file_table *table = &ctx->file_table;
5445 unsigned long nr = ctx->nr_user_files;
5448 if (table->alloc_hint >= nr)
5449 table->alloc_hint = 0;
5452 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5454 table->alloc_hint = ret + 1;
5457 if (!table->alloc_hint)
5460 nr = table->alloc_hint;
5461 table->alloc_hint = 0;
5467 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5468 struct file *file, unsigned int file_slot)
5470 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5471 struct io_ring_ctx *ctx = req->ctx;
5475 io_ring_submit_lock(ctx, issue_flags);
5476 ret = io_file_bitmap_get(ctx);
5477 if (unlikely(ret < 0)) {
5478 io_ring_submit_unlock(ctx, issue_flags);
5487 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5489 io_ring_submit_unlock(ctx, issue_flags);
5497 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5499 struct open_flags op;
5501 bool resolve_nonblock, nonblock_set;
5502 bool fixed = !!req->open.file_slot;
5505 ret = build_open_flags(&req->open.how, &op);
5508 nonblock_set = op.open_flag & O_NONBLOCK;
5509 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5510 if (issue_flags & IO_URING_F_NONBLOCK) {
5512 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5513 * it'll always -EAGAIN
5515 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5517 op.lookup_flags |= LOOKUP_CACHED;
5518 op.open_flag |= O_NONBLOCK;
5522 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5527 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5530 * We could hang on to this 'fd' on retrying, but seems like
5531 * marginal gain for something that is now known to be a slower
5532 * path. So just put it, and we'll get a new one when we retry.
5537 ret = PTR_ERR(file);
5538 /* only retry if RESOLVE_CACHED wasn't already set by application */
5539 if (ret == -EAGAIN &&
5540 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5545 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5546 file->f_flags &= ~O_NONBLOCK;
5547 fsnotify_open(file);
5550 fd_install(ret, file);
5552 ret = io_fixed_fd_install(req, issue_flags, file,
5553 req->open.file_slot);
5555 putname(req->open.filename);
5556 req->flags &= ~REQ_F_NEED_CLEANUP;
5559 __io_req_complete(req, issue_flags, ret, 0);
5563 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5565 return io_openat2(req, issue_flags);
5568 static int io_remove_buffers_prep(struct io_kiocb *req,
5569 const struct io_uring_sqe *sqe)
5571 struct io_provide_buf *p = &req->pbuf;
5574 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5578 tmp = READ_ONCE(sqe->fd);
5579 if (!tmp || tmp > USHRT_MAX)
5582 memset(p, 0, sizeof(*p));
5584 p->bgid = READ_ONCE(sqe->buf_group);
5588 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5589 struct io_buffer_list *bl, unsigned nbufs)
5593 /* shouldn't happen */
5597 if (bl->buf_nr_pages) {
5600 i = bl->buf_ring->tail - bl->head;
5601 for (j = 0; j < bl->buf_nr_pages; j++)
5602 unpin_user_page(bl->buf_pages[j]);
5603 kvfree(bl->buf_pages);
5604 bl->buf_pages = NULL;
5605 bl->buf_nr_pages = 0;
5606 /* make sure it's seen as empty */
5607 INIT_LIST_HEAD(&bl->buf_list);
5611 /* the head kbuf is the list itself */
5612 while (!list_empty(&bl->buf_list)) {
5613 struct io_buffer *nxt;
5615 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5616 list_del(&nxt->list);
5626 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5628 struct io_provide_buf *p = &req->pbuf;
5629 struct io_ring_ctx *ctx = req->ctx;
5630 struct io_buffer_list *bl;
5633 io_ring_submit_lock(ctx, issue_flags);
5636 bl = io_buffer_get_list(ctx, p->bgid);
5639 /* can't use provide/remove buffers command on mapped buffers */
5640 if (!bl->buf_nr_pages)
5641 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5646 /* complete before unlock, IOPOLL may need the lock */
5647 __io_req_complete(req, issue_flags, ret, 0);
5648 io_ring_submit_unlock(ctx, issue_flags);
5652 static int io_provide_buffers_prep(struct io_kiocb *req,
5653 const struct io_uring_sqe *sqe)
5655 unsigned long size, tmp_check;
5656 struct io_provide_buf *p = &req->pbuf;
5659 if (sqe->rw_flags || sqe->splice_fd_in)
5662 tmp = READ_ONCE(sqe->fd);
5663 if (!tmp || tmp > USHRT_MAX)
5666 p->addr = READ_ONCE(sqe->addr);
5667 p->len = READ_ONCE(sqe->len);
5669 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5672 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5675 size = (unsigned long)p->len * p->nbufs;
5676 if (!access_ok(u64_to_user_ptr(p->addr), size))
5679 p->bgid = READ_ONCE(sqe->buf_group);
5680 tmp = READ_ONCE(sqe->off);
5681 if (tmp > USHRT_MAX)
5687 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5689 struct io_buffer *buf;
5694 * Completions that don't happen inline (eg not under uring_lock) will
5695 * add to ->io_buffers_comp. If we don't have any free buffers, check
5696 * the completion list and splice those entries first.
5698 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5699 spin_lock(&ctx->completion_lock);
5700 if (!list_empty(&ctx->io_buffers_comp)) {
5701 list_splice_init(&ctx->io_buffers_comp,
5702 &ctx->io_buffers_cache);
5703 spin_unlock(&ctx->completion_lock);
5706 spin_unlock(&ctx->completion_lock);
5710 * No free buffers and no completion entries either. Allocate a new
5711 * page worth of buffer entries and add those to our freelist.
5713 page = alloc_page(GFP_KERNEL_ACCOUNT);
5717 list_add(&page->lru, &ctx->io_buffers_pages);
5719 buf = page_address(page);
5720 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5721 while (bufs_in_page) {
5722 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5730 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5731 struct io_buffer_list *bl)
5733 struct io_buffer *buf;
5734 u64 addr = pbuf->addr;
5735 int i, bid = pbuf->bid;
5737 for (i = 0; i < pbuf->nbufs; i++) {
5738 if (list_empty(&ctx->io_buffers_cache) &&
5739 io_refill_buffer_cache(ctx))
5741 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5743 list_move_tail(&buf->list, &bl->buf_list);
5745 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5747 buf->bgid = pbuf->bgid;
5753 return i ? 0 : -ENOMEM;
5756 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5760 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5765 for (i = 0; i < BGID_ARRAY; i++) {
5766 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5767 ctx->io_bl[i].bgid = i;
5773 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5775 struct io_provide_buf *p = &req->pbuf;
5776 struct io_ring_ctx *ctx = req->ctx;
5777 struct io_buffer_list *bl;
5780 io_ring_submit_lock(ctx, issue_flags);
5782 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5783 ret = io_init_bl_list(ctx);
5788 bl = io_buffer_get_list(ctx, p->bgid);
5789 if (unlikely(!bl)) {
5790 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5795 INIT_LIST_HEAD(&bl->buf_list);
5796 ret = io_buffer_add_list(ctx, bl, p->bgid);
5802 /* can't add buffers via this command for a mapped buffer ring */
5803 if (bl->buf_nr_pages) {
5808 ret = io_add_buffers(ctx, p, bl);
5812 /* complete before unlock, IOPOLL may need the lock */
5813 __io_req_complete(req, issue_flags, ret, 0);
5814 io_ring_submit_unlock(ctx, issue_flags);
5818 static int io_epoll_ctl_prep(struct io_kiocb *req,
5819 const struct io_uring_sqe *sqe)
5821 #if defined(CONFIG_EPOLL)
5822 if (sqe->buf_index || sqe->splice_fd_in)
5825 req->epoll.epfd = READ_ONCE(sqe->fd);
5826 req->epoll.op = READ_ONCE(sqe->len);
5827 req->epoll.fd = READ_ONCE(sqe->off);
5829 if (ep_op_has_event(req->epoll.op)) {
5830 struct epoll_event __user *ev;
5832 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5833 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5843 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5845 #if defined(CONFIG_EPOLL)
5846 struct io_epoll *ie = &req->epoll;
5848 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5850 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5851 if (force_nonblock && ret == -EAGAIN)
5856 __io_req_complete(req, issue_flags, ret, 0);
5863 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5865 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5866 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5869 req->madvise.addr = READ_ONCE(sqe->addr);
5870 req->madvise.len = READ_ONCE(sqe->len);
5871 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5878 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5880 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5881 struct io_madvise *ma = &req->madvise;
5884 if (issue_flags & IO_URING_F_NONBLOCK)
5887 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5888 io_req_complete(req, ret);
5895 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5897 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5900 req->fadvise.offset = READ_ONCE(sqe->off);
5901 req->fadvise.len = READ_ONCE(sqe->len);
5902 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5906 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5908 struct io_fadvise *fa = &req->fadvise;
5911 if (issue_flags & IO_URING_F_NONBLOCK) {
5912 switch (fa->advice) {
5913 case POSIX_FADV_NORMAL:
5914 case POSIX_FADV_RANDOM:
5915 case POSIX_FADV_SEQUENTIAL:
5922 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5925 __io_req_complete(req, issue_flags, ret, 0);
5929 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5931 const char __user *path;
5933 if (sqe->buf_index || sqe->splice_fd_in)
5935 if (req->flags & REQ_F_FIXED_FILE)
5938 req->statx.dfd = READ_ONCE(sqe->fd);
5939 req->statx.mask = READ_ONCE(sqe->len);
5940 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5941 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5942 req->statx.flags = READ_ONCE(sqe->statx_flags);
5944 req->statx.filename = getname_flags(path,
5945 getname_statx_lookup_flags(req->statx.flags),
5948 if (IS_ERR(req->statx.filename)) {
5949 int ret = PTR_ERR(req->statx.filename);
5951 req->statx.filename = NULL;
5955 req->flags |= REQ_F_NEED_CLEANUP;
5959 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5961 struct io_statx *ctx = &req->statx;
5964 if (issue_flags & IO_URING_F_NONBLOCK)
5967 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5969 io_req_complete(req, ret);
5973 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5975 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5977 if (req->flags & REQ_F_FIXED_FILE)
5980 req->close.fd = READ_ONCE(sqe->fd);
5981 req->close.file_slot = READ_ONCE(sqe->file_index);
5982 if (req->close.file_slot && req->close.fd)
5988 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5990 struct files_struct *files = current->files;
5991 struct io_close *close = &req->close;
5992 struct fdtable *fdt;
5993 struct file *file = NULL;
5996 if (req->close.file_slot) {
5997 ret = io_close_fixed(req, issue_flags);
6001 spin_lock(&files->file_lock);
6002 fdt = files_fdtable(files);
6003 if (close->fd >= fdt->max_fds) {
6004 spin_unlock(&files->file_lock);
6007 file = rcu_dereference_protected(fdt->fd[close->fd],
6008 lockdep_is_held(&files->file_lock));
6009 if (!file || file->f_op == &io_uring_fops) {
6010 spin_unlock(&files->file_lock);
6015 /* if the file has a flush method, be safe and punt to async */
6016 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
6017 spin_unlock(&files->file_lock);
6021 ret = __close_fd_get_file(close->fd, &file);
6022 spin_unlock(&files->file_lock);
6029 /* No ->flush() or already async, safely close from here */
6030 ret = filp_close(file, current->files);
6036 __io_req_complete(req, issue_flags, ret, 0);
6040 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6042 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
6045 req->sync.off = READ_ONCE(sqe->off);
6046 req->sync.len = READ_ONCE(sqe->len);
6047 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
6051 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
6055 /* sync_file_range always requires a blocking context */
6056 if (issue_flags & IO_URING_F_NONBLOCK)
6059 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
6061 io_req_complete(req, ret);
6065 #if defined(CONFIG_NET)
6066 static bool io_net_retry(struct socket *sock, int flags)
6068 if (!(flags & MSG_WAITALL))
6070 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
6073 static int io_setup_async_msg(struct io_kiocb *req,
6074 struct io_async_msghdr *kmsg)
6076 struct io_async_msghdr *async_msg = req->async_data;
6080 if (io_alloc_async_data(req)) {
6081 kfree(kmsg->free_iov);
6084 async_msg = req->async_data;
6085 req->flags |= REQ_F_NEED_CLEANUP;
6086 memcpy(async_msg, kmsg, sizeof(*kmsg));
6087 async_msg->msg.msg_name = &async_msg->addr;
6088 /* if were using fast_iov, set it to the new one */
6089 if (!async_msg->free_iov)
6090 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
6095 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
6096 struct io_async_msghdr *iomsg)
6098 iomsg->msg.msg_name = &iomsg->addr;
6099 iomsg->free_iov = iomsg->fast_iov;
6100 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
6101 req->sr_msg.msg_flags, &iomsg->free_iov);
6104 static int io_sendmsg_prep_async(struct io_kiocb *req)
6108 ret = io_sendmsg_copy_hdr(req, req->async_data);
6110 req->flags |= REQ_F_NEED_CLEANUP;
6114 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6116 struct io_sr_msg *sr = &req->sr_msg;
6118 if (unlikely(sqe->file_index))
6120 if (unlikely(sqe->addr2 || sqe->file_index))
6123 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6124 sr->len = READ_ONCE(sqe->len);
6125 sr->flags = READ_ONCE(sqe->addr2);
6126 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6128 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6129 if (sr->msg_flags & MSG_DONTWAIT)
6130 req->flags |= REQ_F_NOWAIT;
6132 #ifdef CONFIG_COMPAT
6133 if (req->ctx->compat)
6134 sr->msg_flags |= MSG_CMSG_COMPAT;
6140 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
6142 struct io_async_msghdr iomsg, *kmsg;
6143 struct io_sr_msg *sr = &req->sr_msg;
6144 struct socket *sock;
6149 sock = sock_from_file(req->file);
6150 if (unlikely(!sock))
6153 if (req_has_async_data(req)) {
6154 kmsg = req->async_data;
6156 ret = io_sendmsg_copy_hdr(req, &iomsg);
6162 if (!(req->flags & REQ_F_POLLED) &&
6163 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6164 return io_setup_async_msg(req, kmsg);
6166 flags = sr->msg_flags;
6167 if (issue_flags & IO_URING_F_NONBLOCK)
6168 flags |= MSG_DONTWAIT;
6169 if (flags & MSG_WAITALL)
6170 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6172 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
6174 if (ret < min_ret) {
6175 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6176 return io_setup_async_msg(req, kmsg);
6177 if (ret == -ERESTARTSYS)
6179 if (ret > 0 && io_net_retry(sock, flags)) {
6181 req->flags |= REQ_F_PARTIAL_IO;
6182 return io_setup_async_msg(req, kmsg);
6186 /* fast path, check for non-NULL to avoid function call */
6188 kfree(kmsg->free_iov);
6189 req->flags &= ~REQ_F_NEED_CLEANUP;
6192 else if (sr->done_io)
6194 __io_req_complete(req, issue_flags, ret, 0);
6198 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6200 struct io_sr_msg *sr = &req->sr_msg;
6203 struct socket *sock;
6208 if (!(req->flags & REQ_F_POLLED) &&
6209 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6212 sock = sock_from_file(req->file);
6213 if (unlikely(!sock))
6216 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6220 msg.msg_name = NULL;
6221 msg.msg_control = NULL;
6222 msg.msg_controllen = 0;
6223 msg.msg_namelen = 0;
6225 flags = sr->msg_flags;
6226 if (issue_flags & IO_URING_F_NONBLOCK)
6227 flags |= MSG_DONTWAIT;
6228 if (flags & MSG_WAITALL)
6229 min_ret = iov_iter_count(&msg.msg_iter);
6231 msg.msg_flags = flags;
6232 ret = sock_sendmsg(sock, &msg);
6233 if (ret < min_ret) {
6234 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6236 if (ret == -ERESTARTSYS)
6238 if (ret > 0 && io_net_retry(sock, flags)) {
6242 req->flags |= REQ_F_PARTIAL_IO;
6249 else if (sr->done_io)
6251 __io_req_complete(req, issue_flags, ret, 0);
6255 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6256 struct io_async_msghdr *iomsg)
6258 struct io_sr_msg *sr = &req->sr_msg;
6259 struct iovec __user *uiov;
6263 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6264 &iomsg->uaddr, &uiov, &iov_len);
6268 if (req->flags & REQ_F_BUFFER_SELECT) {
6271 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6273 sr->len = iomsg->fast_iov[0].iov_len;
6274 iomsg->free_iov = NULL;
6276 iomsg->free_iov = iomsg->fast_iov;
6277 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6278 &iomsg->free_iov, &iomsg->msg.msg_iter,
6287 #ifdef CONFIG_COMPAT
6288 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6289 struct io_async_msghdr *iomsg)
6291 struct io_sr_msg *sr = &req->sr_msg;
6292 struct compat_iovec __user *uiov;
6297 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6302 uiov = compat_ptr(ptr);
6303 if (req->flags & REQ_F_BUFFER_SELECT) {
6304 compat_ssize_t clen;
6308 if (!access_ok(uiov, sizeof(*uiov)))
6310 if (__get_user(clen, &uiov->iov_len))
6315 iomsg->free_iov = NULL;
6317 iomsg->free_iov = iomsg->fast_iov;
6318 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6319 UIO_FASTIOV, &iomsg->free_iov,
6320 &iomsg->msg.msg_iter, true);
6329 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6330 struct io_async_msghdr *iomsg)
6332 iomsg->msg.msg_name = &iomsg->addr;
6334 #ifdef CONFIG_COMPAT
6335 if (req->ctx->compat)
6336 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6339 return __io_recvmsg_copy_hdr(req, iomsg);
6342 static int io_recvmsg_prep_async(struct io_kiocb *req)
6346 ret = io_recvmsg_copy_hdr(req, req->async_data);
6348 req->flags |= REQ_F_NEED_CLEANUP;
6352 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6354 struct io_sr_msg *sr = &req->sr_msg;
6356 if (unlikely(sqe->file_index))
6358 if (unlikely(sqe->addr2 || sqe->file_index))
6361 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6362 sr->len = READ_ONCE(sqe->len);
6363 sr->flags = READ_ONCE(sqe->addr2);
6364 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6366 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6367 if (sr->msg_flags & MSG_DONTWAIT)
6368 req->flags |= REQ_F_NOWAIT;
6370 #ifdef CONFIG_COMPAT
6371 if (req->ctx->compat)
6372 sr->msg_flags |= MSG_CMSG_COMPAT;
6378 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6380 struct io_async_msghdr iomsg, *kmsg;
6381 struct io_sr_msg *sr = &req->sr_msg;
6382 struct socket *sock;
6383 unsigned int cflags;
6385 int ret, min_ret = 0;
6386 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6388 sock = sock_from_file(req->file);
6389 if (unlikely(!sock))
6392 if (req_has_async_data(req)) {
6393 kmsg = req->async_data;
6395 ret = io_recvmsg_copy_hdr(req, &iomsg);
6401 if (!(req->flags & REQ_F_POLLED) &&
6402 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6403 return io_setup_async_msg(req, kmsg);
6405 if (io_do_buffer_select(req)) {
6408 buf = io_buffer_select(req, &sr->len, issue_flags);
6411 kmsg->fast_iov[0].iov_base = buf;
6412 kmsg->fast_iov[0].iov_len = sr->len;
6413 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6417 flags = sr->msg_flags;
6419 flags |= MSG_DONTWAIT;
6420 if (flags & MSG_WAITALL)
6421 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6423 kmsg->msg.msg_get_inq = 1;
6424 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6425 if (ret < min_ret) {
6426 if (ret == -EAGAIN && force_nonblock)
6427 return io_setup_async_msg(req, kmsg);
6428 if (ret == -ERESTARTSYS)
6430 if (ret > 0 && io_net_retry(sock, flags)) {
6432 req->flags |= REQ_F_PARTIAL_IO;
6433 return io_setup_async_msg(req, kmsg);
6436 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6440 /* fast path, check for non-NULL to avoid function call */
6442 kfree(kmsg->free_iov);
6443 req->flags &= ~REQ_F_NEED_CLEANUP;
6446 else if (sr->done_io)
6448 cflags = io_put_kbuf(req, issue_flags);
6449 if (kmsg->msg.msg_inq)
6450 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6451 __io_req_complete(req, issue_flags, ret, cflags);
6455 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6457 struct io_sr_msg *sr = &req->sr_msg;
6459 struct socket *sock;
6461 unsigned int cflags;
6463 int ret, min_ret = 0;
6464 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6466 if (!(req->flags & REQ_F_POLLED) &&
6467 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6470 sock = sock_from_file(req->file);
6471 if (unlikely(!sock))
6474 if (io_do_buffer_select(req)) {
6477 buf = io_buffer_select(req, &sr->len, issue_flags);
6483 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6487 msg.msg_name = NULL;
6488 msg.msg_namelen = 0;
6489 msg.msg_control = NULL;
6490 msg.msg_get_inq = 1;
6492 msg.msg_controllen = 0;
6493 msg.msg_iocb = NULL;
6495 flags = sr->msg_flags;
6497 flags |= MSG_DONTWAIT;
6498 if (flags & MSG_WAITALL)
6499 min_ret = iov_iter_count(&msg.msg_iter);
6501 ret = sock_recvmsg(sock, &msg, flags);
6502 if (ret < min_ret) {
6503 if (ret == -EAGAIN && force_nonblock)
6505 if (ret == -ERESTARTSYS)
6507 if (ret > 0 && io_net_retry(sock, flags)) {
6511 req->flags |= REQ_F_PARTIAL_IO;
6515 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6522 else if (sr->done_io)
6524 cflags = io_put_kbuf(req, issue_flags);
6526 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6527 __io_req_complete(req, issue_flags, ret, cflags);
6531 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6533 struct io_accept *accept = &req->accept;
6536 if (sqe->len || sqe->buf_index)
6539 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6540 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6541 accept->flags = READ_ONCE(sqe->accept_flags);
6542 accept->nofile = rlimit(RLIMIT_NOFILE);
6543 flags = READ_ONCE(sqe->ioprio);
6544 if (flags & ~IORING_ACCEPT_MULTISHOT)
6547 accept->file_slot = READ_ONCE(sqe->file_index);
6548 if (accept->file_slot) {
6549 if (accept->flags & SOCK_CLOEXEC)
6551 if (flags & IORING_ACCEPT_MULTISHOT &&
6552 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6555 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6557 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6558 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6559 if (flags & IORING_ACCEPT_MULTISHOT)
6560 req->flags |= REQ_F_APOLL_MULTISHOT;
6564 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6566 struct io_ring_ctx *ctx = req->ctx;
6567 struct io_accept *accept = &req->accept;
6568 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6569 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6570 bool fixed = !!accept->file_slot;
6576 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6577 if (unlikely(fd < 0))
6580 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6585 ret = PTR_ERR(file);
6586 if (ret == -EAGAIN && force_nonblock) {
6588 * if it's multishot and polled, we don't need to
6589 * return EAGAIN to arm the poll infra since it
6590 * has already been done
6592 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6593 IO_APOLL_MULTI_POLLED)
6597 if (ret == -ERESTARTSYS)
6600 } else if (!fixed) {
6601 fd_install(fd, file);
6604 ret = io_fixed_fd_install(req, issue_flags, file,
6608 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6609 __io_req_complete(req, issue_flags, ret, 0);
6615 spin_lock(&ctx->completion_lock);
6616 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6618 io_commit_cqring(ctx);
6619 spin_unlock(&ctx->completion_lock);
6621 io_cqring_ev_posted(ctx);
6630 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6632 struct io_socket *sock = &req->sock;
6634 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6637 sock->domain = READ_ONCE(sqe->fd);
6638 sock->type = READ_ONCE(sqe->off);
6639 sock->protocol = READ_ONCE(sqe->len);
6640 sock->file_slot = READ_ONCE(sqe->file_index);
6641 sock->nofile = rlimit(RLIMIT_NOFILE);
6643 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6644 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6646 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6651 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6653 struct io_socket *sock = &req->sock;
6654 bool fixed = !!sock->file_slot;
6659 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6660 if (unlikely(fd < 0))
6663 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6667 ret = PTR_ERR(file);
6668 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6670 if (ret == -ERESTARTSYS)
6673 } else if (!fixed) {
6674 fd_install(fd, file);
6677 ret = io_install_fixed_file(req, file, issue_flags,
6678 sock->file_slot - 1);
6680 __io_req_complete(req, issue_flags, ret, 0);
6684 static int io_connect_prep_async(struct io_kiocb *req)
6686 struct io_async_connect *io = req->async_data;
6687 struct io_connect *conn = &req->connect;
6689 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6692 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6694 struct io_connect *conn = &req->connect;
6696 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6699 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6700 conn->addr_len = READ_ONCE(sqe->addr2);
6704 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6706 struct io_async_connect __io, *io;
6707 unsigned file_flags;
6709 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6711 if (req_has_async_data(req)) {
6712 io = req->async_data;
6714 ret = move_addr_to_kernel(req->connect.addr,
6715 req->connect.addr_len,
6722 file_flags = force_nonblock ? O_NONBLOCK : 0;
6724 ret = __sys_connect_file(req->file, &io->address,
6725 req->connect.addr_len, file_flags);
6726 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6727 if (req_has_async_data(req))
6729 if (io_alloc_async_data(req)) {
6733 memcpy(req->async_data, &__io, sizeof(__io));
6736 if (ret == -ERESTARTSYS)
6741 __io_req_complete(req, issue_flags, ret, 0);
6744 #else /* !CONFIG_NET */
6745 #define IO_NETOP_FN(op) \
6746 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6748 return -EOPNOTSUPP; \
6751 #define IO_NETOP_PREP(op) \
6753 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6755 return -EOPNOTSUPP; \
6758 #define IO_NETOP_PREP_ASYNC(op) \
6760 static int io_##op##_prep_async(struct io_kiocb *req) \
6762 return -EOPNOTSUPP; \
6765 IO_NETOP_PREP_ASYNC(sendmsg);
6766 IO_NETOP_PREP_ASYNC(recvmsg);
6767 IO_NETOP_PREP_ASYNC(connect);
6768 IO_NETOP_PREP(accept);
6769 IO_NETOP_PREP(socket);
6772 #endif /* CONFIG_NET */
6774 struct io_poll_table {
6775 struct poll_table_struct pt;
6776 struct io_kiocb *req;
6781 #define IO_POLL_CANCEL_FLAG BIT(31)
6782 #define IO_POLL_REF_MASK GENMASK(30, 0)
6785 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6786 * bump it and acquire ownership. It's disallowed to modify requests while not
6787 * owning it, that prevents from races for enqueueing task_work's and b/w
6788 * arming poll and wakeups.
6790 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6792 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6795 static void io_poll_mark_cancelled(struct io_kiocb *req)
6797 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6800 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6802 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6803 if (req->opcode == IORING_OP_POLL_ADD)
6804 return req->async_data;
6805 return req->apoll->double_poll;
6808 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6810 if (req->opcode == IORING_OP_POLL_ADD)
6812 return &req->apoll->poll;
6815 static void io_poll_req_insert(struct io_kiocb *req)
6817 struct io_ring_ctx *ctx = req->ctx;
6818 struct hlist_head *list;
6820 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6821 hlist_add_head(&req->hash_node, list);
6824 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6825 wait_queue_func_t wake_func)
6828 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6829 /* mask in events that we always want/need */
6830 poll->events = events | IO_POLL_UNMASK;
6831 INIT_LIST_HEAD(&poll->wait.entry);
6832 init_waitqueue_func_entry(&poll->wait, wake_func);
6835 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6837 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6840 spin_lock_irq(&head->lock);
6841 list_del_init(&poll->wait.entry);
6843 spin_unlock_irq(&head->lock);
6847 static void io_poll_remove_entries(struct io_kiocb *req)
6850 * Nothing to do if neither of those flags are set. Avoid dipping
6851 * into the poll/apoll/double cachelines if we can.
6853 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6857 * While we hold the waitqueue lock and the waitqueue is nonempty,
6858 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6859 * lock in the first place can race with the waitqueue being freed.
6861 * We solve this as eventpoll does: by taking advantage of the fact that
6862 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6863 * we enter rcu_read_lock() and see that the pointer to the queue is
6864 * non-NULL, we can then lock it without the memory being freed out from
6867 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6868 * case the caller deletes the entry from the queue, leaving it empty.
6869 * In that case, only RCU prevents the queue memory from being freed.
6872 if (req->flags & REQ_F_SINGLE_POLL)
6873 io_poll_remove_entry(io_poll_get_single(req));
6874 if (req->flags & REQ_F_DOUBLE_POLL)
6875 io_poll_remove_entry(io_poll_get_double(req));
6879 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6881 * All poll tw should go through this. Checks for poll events, manages
6882 * references, does rewait, etc.
6884 * Returns a negative error on failure. >0 when no action require, which is
6885 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6886 * the request, then the mask is stored in req->cqe.res.
6888 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6890 struct io_ring_ctx *ctx = req->ctx;
6893 /* req->task == current here, checking PF_EXITING is safe */
6894 if (unlikely(req->task->flags & PF_EXITING))
6898 v = atomic_read(&req->poll_refs);
6900 /* tw handler should be the owner, and so have some references */
6901 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6903 if (v & IO_POLL_CANCEL_FLAG)
6906 if (!req->cqe.res) {
6907 struct poll_table_struct pt = { ._key = req->apoll_events };
6908 unsigned flags = locked ? 0 : IO_URING_F_UNLOCKED;
6910 if (unlikely(!io_assign_file(req, flags)))
6912 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6915 if ((unlikely(!req->cqe.res)))
6917 if (req->apoll_events & EPOLLONESHOT)
6920 /* multishot, just fill a CQE and proceed */
6921 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6922 __poll_t mask = mangle_poll(req->cqe.res &
6926 spin_lock(&ctx->completion_lock);
6927 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6928 mask, IORING_CQE_F_MORE);
6929 io_commit_cqring(ctx);
6930 spin_unlock(&ctx->completion_lock);
6932 io_cqring_ev_posted(ctx);
6938 io_tw_lock(req->ctx, locked);
6939 if (unlikely(req->task->flags & PF_EXITING))
6941 ret = io_issue_sqe(req,
6942 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6947 * Release all references, retry if someone tried to restart
6948 * task_work while we were executing it.
6950 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6955 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6957 struct io_ring_ctx *ctx = req->ctx;
6960 ret = io_poll_check_events(req, locked);
6965 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6971 io_poll_remove_entries(req);
6972 spin_lock(&ctx->completion_lock);
6973 hash_del(&req->hash_node);
6974 __io_req_complete_post(req, req->cqe.res, 0);
6975 io_commit_cqring(ctx);
6976 spin_unlock(&ctx->completion_lock);
6977 io_cqring_ev_posted(ctx);
6980 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6982 struct io_ring_ctx *ctx = req->ctx;
6985 ret = io_poll_check_events(req, locked);
6989 io_poll_remove_entries(req);
6990 spin_lock(&ctx->completion_lock);
6991 hash_del(&req->hash_node);
6992 spin_unlock(&ctx->completion_lock);
6995 io_req_task_submit(req, locked);
6997 io_req_complete_failed(req, ret);
7000 static void __io_poll_execute(struct io_kiocb *req, int mask, __poll_t events)
7002 req->cqe.res = mask;
7004 * This is useful for poll that is armed on behalf of another
7005 * request, and where the wakeup path could be on a different
7006 * CPU. We want to avoid pulling in req->apoll->events for that
7009 req->apoll_events = events;
7010 if (req->opcode == IORING_OP_POLL_ADD)
7011 req->io_task_work.func = io_poll_task_func;
7013 req->io_task_work.func = io_apoll_task_func;
7015 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
7016 io_req_task_work_add(req);
7019 static inline void io_poll_execute(struct io_kiocb *req, int res,
7022 if (io_poll_get_ownership(req))
7023 __io_poll_execute(req, res, events);
7026 static void io_poll_cancel_req(struct io_kiocb *req)
7028 io_poll_mark_cancelled(req);
7029 /* kick tw, which should complete the request */
7030 io_poll_execute(req, 0, 0);
7033 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
7034 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
7035 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
7037 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
7040 struct io_kiocb *req = wqe_to_req(wait);
7041 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
7043 __poll_t mask = key_to_poll(key);
7045 if (unlikely(mask & POLLFREE)) {
7046 io_poll_mark_cancelled(req);
7047 /* we have to kick tw in case it's not already */
7048 io_poll_execute(req, 0, poll->events);
7051 * If the waitqueue is being freed early but someone is already
7052 * holds ownership over it, we have to tear down the request as
7053 * best we can. That means immediately removing the request from
7054 * its waitqueue and preventing all further accesses to the
7055 * waitqueue via the request.
7057 list_del_init(&poll->wait.entry);
7060 * Careful: this *must* be the last step, since as soon
7061 * as req->head is NULL'ed out, the request can be
7062 * completed and freed, since aio_poll_complete_work()
7063 * will no longer need to take the waitqueue lock.
7065 smp_store_release(&poll->head, NULL);
7069 /* for instances that support it check for an event match first */
7070 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
7073 if (io_poll_get_ownership(req)) {
7074 /* optional, saves extra locking for removal in tw handler */
7075 if (mask && poll->events & EPOLLONESHOT) {
7076 list_del_init(&poll->wait.entry);
7078 if (wqe_is_double(wait))
7079 req->flags &= ~REQ_F_DOUBLE_POLL;
7081 req->flags &= ~REQ_F_SINGLE_POLL;
7083 __io_poll_execute(req, mask, poll->events);
7088 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
7089 struct wait_queue_head *head,
7090 struct io_poll_iocb **poll_ptr)
7092 struct io_kiocb *req = pt->req;
7093 unsigned long wqe_private = (unsigned long) req;
7096 * The file being polled uses multiple waitqueues for poll handling
7097 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
7100 if (unlikely(pt->nr_entries)) {
7101 struct io_poll_iocb *first = poll;
7103 /* double add on the same waitqueue head, ignore */
7104 if (first->head == head)
7106 /* already have a 2nd entry, fail a third attempt */
7108 if ((*poll_ptr)->head == head)
7110 pt->error = -EINVAL;
7114 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
7116 pt->error = -ENOMEM;
7119 /* mark as double wq entry */
7121 req->flags |= REQ_F_DOUBLE_POLL;
7122 io_init_poll_iocb(poll, first->events, first->wait.func);
7124 if (req->opcode == IORING_OP_POLL_ADD)
7125 req->flags |= REQ_F_ASYNC_DATA;
7128 req->flags |= REQ_F_SINGLE_POLL;
7131 poll->wait.private = (void *) wqe_private;
7133 if (poll->events & EPOLLEXCLUSIVE)
7134 add_wait_queue_exclusive(head, &poll->wait);
7136 add_wait_queue(head, &poll->wait);
7139 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
7140 struct poll_table_struct *p)
7142 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7144 __io_queue_proc(&pt->req->poll, pt, head,
7145 (struct io_poll_iocb **) &pt->req->async_data);
7148 static int __io_arm_poll_handler(struct io_kiocb *req,
7149 struct io_poll_iocb *poll,
7150 struct io_poll_table *ipt, __poll_t mask)
7152 struct io_ring_ctx *ctx = req->ctx;
7155 INIT_HLIST_NODE(&req->hash_node);
7156 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
7157 io_init_poll_iocb(poll, mask, io_poll_wake);
7158 poll->file = req->file;
7160 ipt->pt._key = mask;
7163 ipt->nr_entries = 0;
7166 * Take the ownership to delay any tw execution up until we're done
7167 * with poll arming. see io_poll_get_ownership().
7169 atomic_set(&req->poll_refs, 1);
7170 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
7172 if (mask && (poll->events & EPOLLONESHOT)) {
7173 io_poll_remove_entries(req);
7174 /* no one else has access to the req, forget about the ref */
7177 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
7178 io_poll_remove_entries(req);
7180 ipt->error = -EINVAL;
7184 spin_lock(&ctx->completion_lock);
7185 io_poll_req_insert(req);
7186 spin_unlock(&ctx->completion_lock);
7189 /* can't multishot if failed, just queue the event we've got */
7190 if (unlikely(ipt->error || !ipt->nr_entries))
7191 poll->events |= EPOLLONESHOT;
7192 __io_poll_execute(req, mask, poll->events);
7197 * Release ownership. If someone tried to queue a tw while it was
7198 * locked, kick it off for them.
7200 v = atomic_dec_return(&req->poll_refs);
7201 if (unlikely(v & IO_POLL_REF_MASK))
7202 __io_poll_execute(req, 0, poll->events);
7206 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7207 struct poll_table_struct *p)
7209 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7210 struct async_poll *apoll = pt->req->apoll;
7212 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7221 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7223 const struct io_op_def *def = &io_op_defs[req->opcode];
7224 struct io_ring_ctx *ctx = req->ctx;
7225 struct async_poll *apoll;
7226 struct io_poll_table ipt;
7227 __poll_t mask = POLLPRI | POLLERR;
7230 if (!def->pollin && !def->pollout)
7231 return IO_APOLL_ABORTED;
7232 if (!file_can_poll(req->file))
7233 return IO_APOLL_ABORTED;
7234 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7235 return IO_APOLL_ABORTED;
7236 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7237 mask |= EPOLLONESHOT;
7240 mask |= EPOLLIN | EPOLLRDNORM;
7242 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7243 if ((req->opcode == IORING_OP_RECVMSG) &&
7244 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7247 mask |= EPOLLOUT | EPOLLWRNORM;
7249 if (def->poll_exclusive)
7250 mask |= EPOLLEXCLUSIVE;
7251 if (req->flags & REQ_F_POLLED) {
7253 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7254 !list_empty(&ctx->apoll_cache)) {
7255 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7257 list_del_init(&apoll->poll.wait.entry);
7259 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7260 if (unlikely(!apoll))
7261 return IO_APOLL_ABORTED;
7263 apoll->double_poll = NULL;
7265 req->flags |= REQ_F_POLLED;
7266 ipt.pt._qproc = io_async_queue_proc;
7268 io_kbuf_recycle(req, issue_flags);
7270 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7271 if (ret || ipt.error)
7272 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7274 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7275 mask, apoll->poll.events);
7280 * Returns true if we found and killed one or more poll requests
7282 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7283 struct task_struct *tsk, bool cancel_all)
7285 struct hlist_node *tmp;
7286 struct io_kiocb *req;
7290 spin_lock(&ctx->completion_lock);
7291 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7292 struct hlist_head *list;
7294 list = &ctx->cancel_hash[i];
7295 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7296 if (io_match_task_safe(req, tsk, cancel_all)) {
7297 hlist_del_init(&req->hash_node);
7298 io_poll_cancel_req(req);
7303 spin_unlock(&ctx->completion_lock);
7307 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7308 struct io_cancel_data *cd)
7309 __must_hold(&ctx->completion_lock)
7311 struct hlist_head *list;
7312 struct io_kiocb *req;
7314 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7315 hlist_for_each_entry(req, list, hash_node) {
7316 if (cd->data != req->cqe.user_data)
7318 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7320 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7321 if (cd->seq == req->work.cancel_seq)
7323 req->work.cancel_seq = cd->seq;
7330 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7331 struct io_cancel_data *cd)
7332 __must_hold(&ctx->completion_lock)
7334 struct io_kiocb *req;
7337 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7338 struct hlist_head *list;
7340 list = &ctx->cancel_hash[i];
7341 hlist_for_each_entry(req, list, hash_node) {
7342 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7343 req->file != cd->file)
7345 if (cd->seq == req->work.cancel_seq)
7347 req->work.cancel_seq = cd->seq;
7354 static bool io_poll_disarm(struct io_kiocb *req)
7355 __must_hold(&ctx->completion_lock)
7357 if (!io_poll_get_ownership(req))
7359 io_poll_remove_entries(req);
7360 hash_del(&req->hash_node);
7364 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7365 __must_hold(&ctx->completion_lock)
7367 struct io_kiocb *req;
7369 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7370 req = io_poll_file_find(ctx, cd);
7372 req = io_poll_find(ctx, false, cd);
7375 io_poll_cancel_req(req);
7379 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7384 events = READ_ONCE(sqe->poll32_events);
7386 events = swahw32(events);
7388 if (!(flags & IORING_POLL_ADD_MULTI))
7389 events |= EPOLLONESHOT;
7390 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7393 static int io_poll_update_prep(struct io_kiocb *req,
7394 const struct io_uring_sqe *sqe)
7396 struct io_poll_update *upd = &req->poll_update;
7399 if (sqe->buf_index || sqe->splice_fd_in)
7401 flags = READ_ONCE(sqe->len);
7402 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7403 IORING_POLL_ADD_MULTI))
7405 /* meaningless without update */
7406 if (flags == IORING_POLL_ADD_MULTI)
7409 upd->old_user_data = READ_ONCE(sqe->addr);
7410 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7411 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7413 upd->new_user_data = READ_ONCE(sqe->off);
7414 if (!upd->update_user_data && upd->new_user_data)
7416 if (upd->update_events)
7417 upd->events = io_poll_parse_events(sqe, flags);
7418 else if (sqe->poll32_events)
7424 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7426 struct io_poll_iocb *poll = &req->poll;
7429 if (sqe->buf_index || sqe->off || sqe->addr)
7431 flags = READ_ONCE(sqe->len);
7432 if (flags & ~IORING_POLL_ADD_MULTI)
7434 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7437 io_req_set_refcount(req);
7438 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
7442 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7444 struct io_poll_iocb *poll = &req->poll;
7445 struct io_poll_table ipt;
7448 ipt.pt._qproc = io_poll_queue_proc;
7450 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7451 ret = ret ?: ipt.error;
7453 __io_req_complete(req, issue_flags, ret, 0);
7457 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
7459 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7460 struct io_ring_ctx *ctx = req->ctx;
7461 struct io_kiocb *preq;
7465 spin_lock(&ctx->completion_lock);
7466 preq = io_poll_find(ctx, true, &cd);
7467 if (!preq || !io_poll_disarm(preq)) {
7468 spin_unlock(&ctx->completion_lock);
7469 ret = preq ? -EALREADY : -ENOENT;
7472 spin_unlock(&ctx->completion_lock);
7474 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7475 /* only mask one event flags, keep behavior flags */
7476 if (req->poll_update.update_events) {
7477 preq->poll.events &= ~0xffff;
7478 preq->poll.events |= req->poll_update.events & 0xffff;
7479 preq->poll.events |= IO_POLL_UNMASK;
7481 if (req->poll_update.update_user_data)
7482 preq->cqe.user_data = req->poll_update.new_user_data;
7484 ret2 = io_poll_add(preq, issue_flags);
7485 /* successfully updated, don't complete poll request */
7491 preq->cqe.res = -ECANCELED;
7492 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7493 io_req_task_complete(preq, &locked);
7497 /* complete update request, we're done with it */
7498 __io_req_complete(req, issue_flags, ret, 0);
7502 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7504 struct io_timeout_data *data = container_of(timer,
7505 struct io_timeout_data, timer);
7506 struct io_kiocb *req = data->req;
7507 struct io_ring_ctx *ctx = req->ctx;
7508 unsigned long flags;
7510 spin_lock_irqsave(&ctx->timeout_lock, flags);
7511 list_del_init(&req->timeout.list);
7512 atomic_set(&req->ctx->cq_timeouts,
7513 atomic_read(&req->ctx->cq_timeouts) + 1);
7514 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7516 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7519 req->cqe.res = -ETIME;
7520 req->io_task_work.func = io_req_task_complete;
7521 io_req_task_work_add(req);
7522 return HRTIMER_NORESTART;
7525 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7526 struct io_cancel_data *cd)
7527 __must_hold(&ctx->timeout_lock)
7529 struct io_timeout_data *io;
7530 struct io_kiocb *req;
7533 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7534 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7535 cd->data != req->cqe.user_data)
7537 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7538 if (cd->seq == req->work.cancel_seq)
7540 req->work.cancel_seq = cd->seq;
7546 return ERR_PTR(-ENOENT);
7548 io = req->async_data;
7549 if (hrtimer_try_to_cancel(&io->timer) == -1)
7550 return ERR_PTR(-EALREADY);
7551 list_del_init(&req->timeout.list);
7555 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7556 __must_hold(&ctx->completion_lock)
7558 struct io_kiocb *req;
7560 spin_lock_irq(&ctx->timeout_lock);
7561 req = io_timeout_extract(ctx, cd);
7562 spin_unlock_irq(&ctx->timeout_lock);
7565 return PTR_ERR(req);
7566 io_req_task_queue_fail(req, -ECANCELED);
7570 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7572 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7573 case IORING_TIMEOUT_BOOTTIME:
7574 return CLOCK_BOOTTIME;
7575 case IORING_TIMEOUT_REALTIME:
7576 return CLOCK_REALTIME;
7578 /* can't happen, vetted at prep time */
7582 return CLOCK_MONOTONIC;
7586 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7587 struct timespec64 *ts, enum hrtimer_mode mode)
7588 __must_hold(&ctx->timeout_lock)
7590 struct io_timeout_data *io;
7591 struct io_kiocb *req;
7594 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7595 found = user_data == req->cqe.user_data;
7602 io = req->async_data;
7603 if (hrtimer_try_to_cancel(&io->timer) == -1)
7605 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7606 io->timer.function = io_link_timeout_fn;
7607 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7611 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7612 struct timespec64 *ts, enum hrtimer_mode mode)
7613 __must_hold(&ctx->timeout_lock)
7615 struct io_cancel_data cd = { .data = user_data, };
7616 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7617 struct io_timeout_data *data;
7620 return PTR_ERR(req);
7622 req->timeout.off = 0; /* noseq */
7623 data = req->async_data;
7624 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7625 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7626 data->timer.function = io_timeout_fn;
7627 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7631 static int io_timeout_remove_prep(struct io_kiocb *req,
7632 const struct io_uring_sqe *sqe)
7634 struct io_timeout_rem *tr = &req->timeout_rem;
7636 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7638 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7641 tr->ltimeout = false;
7642 tr->addr = READ_ONCE(sqe->addr);
7643 tr->flags = READ_ONCE(sqe->timeout_flags);
7644 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7645 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7647 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7648 tr->ltimeout = true;
7649 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7651 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7653 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7655 } else if (tr->flags) {
7656 /* timeout removal doesn't support flags */
7663 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7665 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7670 * Remove or update an existing timeout command
7672 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7674 struct io_timeout_rem *tr = &req->timeout_rem;
7675 struct io_ring_ctx *ctx = req->ctx;
7678 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7679 struct io_cancel_data cd = { .data = tr->addr, };
7681 spin_lock(&ctx->completion_lock);
7682 ret = io_timeout_cancel(ctx, &cd);
7683 spin_unlock(&ctx->completion_lock);
7685 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7687 spin_lock_irq(&ctx->timeout_lock);
7689 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7691 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7692 spin_unlock_irq(&ctx->timeout_lock);
7697 io_req_complete_post(req, ret, 0);
7701 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
7702 bool is_timeout_link)
7704 struct io_timeout_data *data;
7706 u32 off = READ_ONCE(sqe->off);
7708 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7710 if (off && is_timeout_link)
7712 flags = READ_ONCE(sqe->timeout_flags);
7713 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7714 IORING_TIMEOUT_ETIME_SUCCESS))
7716 /* more than one clock specified is invalid, obviously */
7717 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7720 INIT_LIST_HEAD(&req->timeout.list);
7721 req->timeout.off = off;
7722 if (unlikely(off && !req->ctx->off_timeout_used))
7723 req->ctx->off_timeout_used = true;
7725 if (WARN_ON_ONCE(req_has_async_data(req)))
7727 if (io_alloc_async_data(req))
7730 data = req->async_data;
7732 data->flags = flags;
7734 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7737 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7740 INIT_LIST_HEAD(&req->timeout.list);
7741 data->mode = io_translate_timeout_mode(flags);
7742 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7744 if (is_timeout_link) {
7745 struct io_submit_link *link = &req->ctx->submit_state.link;
7749 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7751 req->timeout.head = link->last;
7752 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7757 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7759 struct io_ring_ctx *ctx = req->ctx;
7760 struct io_timeout_data *data = req->async_data;
7761 struct list_head *entry;
7762 u32 tail, off = req->timeout.off;
7764 spin_lock_irq(&ctx->timeout_lock);
7767 * sqe->off holds how many events that need to occur for this
7768 * timeout event to be satisfied. If it isn't set, then this is
7769 * a pure timeout request, sequence isn't used.
7771 if (io_is_timeout_noseq(req)) {
7772 entry = ctx->timeout_list.prev;
7776 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7777 req->timeout.target_seq = tail + off;
7779 /* Update the last seq here in case io_flush_timeouts() hasn't.
7780 * This is safe because ->completion_lock is held, and submissions
7781 * and completions are never mixed in the same ->completion_lock section.
7783 ctx->cq_last_tm_flush = tail;
7786 * Insertion sort, ensuring the first entry in the list is always
7787 * the one we need first.
7789 list_for_each_prev(entry, &ctx->timeout_list) {
7790 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7793 if (io_is_timeout_noseq(nxt))
7795 /* nxt.seq is behind @tail, otherwise would've been completed */
7796 if (off >= nxt->timeout.target_seq - tail)
7800 list_add(&req->timeout.list, entry);
7801 data->timer.function = io_timeout_fn;
7802 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7803 spin_unlock_irq(&ctx->timeout_lock);
7807 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7809 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7810 struct io_cancel_data *cd = data;
7812 if (req->ctx != cd->ctx)
7814 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7816 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7817 if (req->file != cd->file)
7820 if (req->cqe.user_data != cd->data)
7823 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7824 if (cd->seq == req->work.cancel_seq)
7826 req->work.cancel_seq = cd->seq;
7831 static int io_async_cancel_one(struct io_uring_task *tctx,
7832 struct io_cancel_data *cd)
7834 enum io_wq_cancel cancel_ret;
7838 if (!tctx || !tctx->io_wq)
7841 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7842 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7843 switch (cancel_ret) {
7844 case IO_WQ_CANCEL_OK:
7847 case IO_WQ_CANCEL_RUNNING:
7850 case IO_WQ_CANCEL_NOTFOUND:
7858 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7860 struct io_ring_ctx *ctx = req->ctx;
7863 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7865 ret = io_async_cancel_one(req->task->io_uring, cd);
7867 * Fall-through even for -EALREADY, as we may have poll armed
7868 * that need unarming.
7873 spin_lock(&ctx->completion_lock);
7874 ret = io_poll_cancel(ctx, cd);
7877 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7878 ret = io_timeout_cancel(ctx, cd);
7880 spin_unlock(&ctx->completion_lock);
7884 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7885 IORING_ASYNC_CANCEL_ANY)
7887 static int io_async_cancel_prep(struct io_kiocb *req,
7888 const struct io_uring_sqe *sqe)
7890 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7892 if (sqe->off || sqe->len || sqe->splice_fd_in)
7895 req->cancel.addr = READ_ONCE(sqe->addr);
7896 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7897 if (req->cancel.flags & ~CANCEL_FLAGS)
7899 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7900 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7902 req->cancel.fd = READ_ONCE(sqe->fd);
7908 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7909 unsigned int issue_flags)
7911 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7912 struct io_ring_ctx *ctx = cd->ctx;
7913 struct io_tctx_node *node;
7917 ret = io_try_cancel(req, cd);
7925 /* slow path, try all io-wq's */
7926 io_ring_submit_lock(ctx, issue_flags);
7928 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7929 struct io_uring_task *tctx = node->task->io_uring;
7931 ret = io_async_cancel_one(tctx, cd);
7932 if (ret != -ENOENT) {
7938 io_ring_submit_unlock(ctx, issue_flags);
7939 return all ? nr : ret;
7942 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7944 struct io_cancel_data cd = {
7946 .data = req->cancel.addr,
7947 .flags = req->cancel.flags,
7948 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7952 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7953 if (req->flags & REQ_F_FIXED_FILE)
7954 req->file = io_file_get_fixed(req, req->cancel.fd,
7957 req->file = io_file_get_normal(req, req->cancel.fd);
7962 cd.file = req->file;
7965 ret = __io_async_cancel(&cd, req, issue_flags);
7969 io_req_complete_post(req, ret, 0);
7973 static int io_rsrc_update_prep(struct io_kiocb *req,
7974 const struct io_uring_sqe *sqe)
7976 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7978 if (sqe->rw_flags || sqe->splice_fd_in)
7981 req->rsrc_update.offset = READ_ONCE(sqe->off);
7982 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7983 if (!req->rsrc_update.nr_args)
7985 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7989 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7991 struct io_ring_ctx *ctx = req->ctx;
7992 struct io_uring_rsrc_update2 up;
7995 up.offset = req->rsrc_update.offset;
7996 up.data = req->rsrc_update.arg;
8002 io_ring_submit_lock(ctx, issue_flags);
8003 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
8004 &up, req->rsrc_update.nr_args);
8005 io_ring_submit_unlock(ctx, issue_flags);
8009 __io_req_complete(req, issue_flags, ret, 0);
8013 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
8015 switch (req->opcode) {
8017 return io_nop_prep(req, sqe);
8018 case IORING_OP_READV:
8019 case IORING_OP_READ_FIXED:
8020 case IORING_OP_READ:
8021 case IORING_OP_WRITEV:
8022 case IORING_OP_WRITE_FIXED:
8023 case IORING_OP_WRITE:
8024 return io_prep_rw(req, sqe);
8025 case IORING_OP_POLL_ADD:
8026 return io_poll_add_prep(req, sqe);
8027 case IORING_OP_POLL_REMOVE:
8028 return io_poll_update_prep(req, sqe);
8029 case IORING_OP_FSYNC:
8030 return io_fsync_prep(req, sqe);
8031 case IORING_OP_SYNC_FILE_RANGE:
8032 return io_sfr_prep(req, sqe);
8033 case IORING_OP_SENDMSG:
8034 case IORING_OP_SEND:
8035 return io_sendmsg_prep(req, sqe);
8036 case IORING_OP_RECVMSG:
8037 case IORING_OP_RECV:
8038 return io_recvmsg_prep(req, sqe);
8039 case IORING_OP_CONNECT:
8040 return io_connect_prep(req, sqe);
8041 case IORING_OP_TIMEOUT:
8042 return io_timeout_prep(req, sqe, false);
8043 case IORING_OP_TIMEOUT_REMOVE:
8044 return io_timeout_remove_prep(req, sqe);
8045 case IORING_OP_ASYNC_CANCEL:
8046 return io_async_cancel_prep(req, sqe);
8047 case IORING_OP_LINK_TIMEOUT:
8048 return io_timeout_prep(req, sqe, true);
8049 case IORING_OP_ACCEPT:
8050 return io_accept_prep(req, sqe);
8051 case IORING_OP_FALLOCATE:
8052 return io_fallocate_prep(req, sqe);
8053 case IORING_OP_OPENAT:
8054 return io_openat_prep(req, sqe);
8055 case IORING_OP_CLOSE:
8056 return io_close_prep(req, sqe);
8057 case IORING_OP_FILES_UPDATE:
8058 return io_rsrc_update_prep(req, sqe);
8059 case IORING_OP_STATX:
8060 return io_statx_prep(req, sqe);
8061 case IORING_OP_FADVISE:
8062 return io_fadvise_prep(req, sqe);
8063 case IORING_OP_MADVISE:
8064 return io_madvise_prep(req, sqe);
8065 case IORING_OP_OPENAT2:
8066 return io_openat2_prep(req, sqe);
8067 case IORING_OP_EPOLL_CTL:
8068 return io_epoll_ctl_prep(req, sqe);
8069 case IORING_OP_SPLICE:
8070 return io_splice_prep(req, sqe);
8071 case IORING_OP_PROVIDE_BUFFERS:
8072 return io_provide_buffers_prep(req, sqe);
8073 case IORING_OP_REMOVE_BUFFERS:
8074 return io_remove_buffers_prep(req, sqe);
8076 return io_tee_prep(req, sqe);
8077 case IORING_OP_SHUTDOWN:
8078 return io_shutdown_prep(req, sqe);
8079 case IORING_OP_RENAMEAT:
8080 return io_renameat_prep(req, sqe);
8081 case IORING_OP_UNLINKAT:
8082 return io_unlinkat_prep(req, sqe);
8083 case IORING_OP_MKDIRAT:
8084 return io_mkdirat_prep(req, sqe);
8085 case IORING_OP_SYMLINKAT:
8086 return io_symlinkat_prep(req, sqe);
8087 case IORING_OP_LINKAT:
8088 return io_linkat_prep(req, sqe);
8089 case IORING_OP_MSG_RING:
8090 return io_msg_ring_prep(req, sqe);
8091 case IORING_OP_FSETXATTR:
8092 return io_fsetxattr_prep(req, sqe);
8093 case IORING_OP_SETXATTR:
8094 return io_setxattr_prep(req, sqe);
8095 case IORING_OP_FGETXATTR:
8096 return io_fgetxattr_prep(req, sqe);
8097 case IORING_OP_GETXATTR:
8098 return io_getxattr_prep(req, sqe);
8099 case IORING_OP_SOCKET:
8100 return io_socket_prep(req, sqe);
8101 case IORING_OP_URING_CMD:
8102 return io_uring_cmd_prep(req, sqe);
8105 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
8110 static int io_req_prep_async(struct io_kiocb *req)
8112 const struct io_op_def *def = &io_op_defs[req->opcode];
8114 /* assign early for deferred execution for non-fixed file */
8115 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
8116 req->file = io_file_get_normal(req, req->cqe.fd);
8117 if (!def->needs_async_setup)
8119 if (WARN_ON_ONCE(req_has_async_data(req)))
8121 if (io_alloc_async_data(req))
8124 switch (req->opcode) {
8125 case IORING_OP_READV:
8126 return io_rw_prep_async(req, READ);
8127 case IORING_OP_WRITEV:
8128 return io_rw_prep_async(req, WRITE);
8129 case IORING_OP_SENDMSG:
8130 return io_sendmsg_prep_async(req);
8131 case IORING_OP_RECVMSG:
8132 return io_recvmsg_prep_async(req);
8133 case IORING_OP_CONNECT:
8134 return io_connect_prep_async(req);
8135 case IORING_OP_URING_CMD:
8136 return io_uring_cmd_prep_async(req);
8138 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
8143 static u32 io_get_sequence(struct io_kiocb *req)
8145 u32 seq = req->ctx->cached_sq_head;
8146 struct io_kiocb *cur;
8148 /* need original cached_sq_head, but it was increased for each req */
8149 io_for_each_link(cur, req)
8154 static __cold void io_drain_req(struct io_kiocb *req)
8156 struct io_ring_ctx *ctx = req->ctx;
8157 struct io_defer_entry *de;
8159 u32 seq = io_get_sequence(req);
8161 /* Still need defer if there is pending req in defer list. */
8162 spin_lock(&ctx->completion_lock);
8163 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
8164 spin_unlock(&ctx->completion_lock);
8166 ctx->drain_active = false;
8167 io_req_task_queue(req);
8170 spin_unlock(&ctx->completion_lock);
8172 ret = io_req_prep_async(req);
8175 io_req_complete_failed(req, ret);
8178 io_prep_async_link(req);
8179 de = kmalloc(sizeof(*de), GFP_KERNEL);
8185 spin_lock(&ctx->completion_lock);
8186 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
8187 spin_unlock(&ctx->completion_lock);
8192 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
8195 list_add_tail(&de->list, &ctx->defer_list);
8196 spin_unlock(&ctx->completion_lock);
8199 static void io_clean_op(struct io_kiocb *req)
8201 if (req->flags & REQ_F_BUFFER_SELECTED) {
8202 spin_lock(&req->ctx->completion_lock);
8203 io_put_kbuf_comp(req);
8204 spin_unlock(&req->ctx->completion_lock);
8207 if (req->flags & REQ_F_NEED_CLEANUP) {
8208 switch (req->opcode) {
8209 case IORING_OP_READV:
8210 case IORING_OP_READ_FIXED:
8211 case IORING_OP_READ:
8212 case IORING_OP_WRITEV:
8213 case IORING_OP_WRITE_FIXED:
8214 case IORING_OP_WRITE: {
8215 struct io_async_rw *io = req->async_data;
8217 kfree(io->free_iovec);
8220 case IORING_OP_RECVMSG:
8221 case IORING_OP_SENDMSG: {
8222 struct io_async_msghdr *io = req->async_data;
8224 kfree(io->free_iov);
8227 case IORING_OP_OPENAT:
8228 case IORING_OP_OPENAT2:
8229 if (req->open.filename)
8230 putname(req->open.filename);
8232 case IORING_OP_RENAMEAT:
8233 putname(req->rename.oldpath);
8234 putname(req->rename.newpath);
8236 case IORING_OP_UNLINKAT:
8237 putname(req->unlink.filename);
8239 case IORING_OP_MKDIRAT:
8240 putname(req->mkdir.filename);
8242 case IORING_OP_SYMLINKAT:
8243 putname(req->symlink.oldpath);
8244 putname(req->symlink.newpath);
8246 case IORING_OP_LINKAT:
8247 putname(req->hardlink.oldpath);
8248 putname(req->hardlink.newpath);
8250 case IORING_OP_STATX:
8251 if (req->statx.filename)
8252 putname(req->statx.filename);
8254 case IORING_OP_SETXATTR:
8255 case IORING_OP_FSETXATTR:
8256 case IORING_OP_GETXATTR:
8257 case IORING_OP_FGETXATTR:
8258 __io_xattr_finish(req);
8262 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8263 kfree(req->apoll->double_poll);
8267 if (req->flags & REQ_F_CREDS)
8268 put_cred(req->creds);
8269 if (req->flags & REQ_F_ASYNC_DATA) {
8270 kfree(req->async_data);
8271 req->async_data = NULL;
8273 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8276 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8278 if (req->file || !io_op_defs[req->opcode].needs_file)
8281 if (req->flags & REQ_F_FIXED_FILE)
8282 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8284 req->file = io_file_get_normal(req, req->cqe.fd);
8289 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8291 const struct cred *creds = NULL;
8294 if (unlikely(!io_assign_file(req, issue_flags)))
8297 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8298 creds = override_creds(req->creds);
8300 if (!io_op_defs[req->opcode].audit_skip)
8301 audit_uring_entry(req->opcode);
8303 switch (req->opcode) {
8305 ret = io_nop(req, issue_flags);
8307 case IORING_OP_READV:
8308 case IORING_OP_READ_FIXED:
8309 case IORING_OP_READ:
8310 ret = io_read(req, issue_flags);
8312 case IORING_OP_WRITEV:
8313 case IORING_OP_WRITE_FIXED:
8314 case IORING_OP_WRITE:
8315 ret = io_write(req, issue_flags);
8317 case IORING_OP_FSYNC:
8318 ret = io_fsync(req, issue_flags);
8320 case IORING_OP_POLL_ADD:
8321 ret = io_poll_add(req, issue_flags);
8323 case IORING_OP_POLL_REMOVE:
8324 ret = io_poll_update(req, issue_flags);
8326 case IORING_OP_SYNC_FILE_RANGE:
8327 ret = io_sync_file_range(req, issue_flags);
8329 case IORING_OP_SENDMSG:
8330 ret = io_sendmsg(req, issue_flags);
8332 case IORING_OP_SEND:
8333 ret = io_send(req, issue_flags);
8335 case IORING_OP_RECVMSG:
8336 ret = io_recvmsg(req, issue_flags);
8338 case IORING_OP_RECV:
8339 ret = io_recv(req, issue_flags);
8341 case IORING_OP_TIMEOUT:
8342 ret = io_timeout(req, issue_flags);
8344 case IORING_OP_TIMEOUT_REMOVE:
8345 ret = io_timeout_remove(req, issue_flags);
8347 case IORING_OP_ACCEPT:
8348 ret = io_accept(req, issue_flags);
8350 case IORING_OP_CONNECT:
8351 ret = io_connect(req, issue_flags);
8353 case IORING_OP_ASYNC_CANCEL:
8354 ret = io_async_cancel(req, issue_flags);
8356 case IORING_OP_FALLOCATE:
8357 ret = io_fallocate(req, issue_flags);
8359 case IORING_OP_OPENAT:
8360 ret = io_openat(req, issue_flags);
8362 case IORING_OP_CLOSE:
8363 ret = io_close(req, issue_flags);
8365 case IORING_OP_FILES_UPDATE:
8366 ret = io_files_update(req, issue_flags);
8368 case IORING_OP_STATX:
8369 ret = io_statx(req, issue_flags);
8371 case IORING_OP_FADVISE:
8372 ret = io_fadvise(req, issue_flags);
8374 case IORING_OP_MADVISE:
8375 ret = io_madvise(req, issue_flags);
8377 case IORING_OP_OPENAT2:
8378 ret = io_openat2(req, issue_flags);
8380 case IORING_OP_EPOLL_CTL:
8381 ret = io_epoll_ctl(req, issue_flags);
8383 case IORING_OP_SPLICE:
8384 ret = io_splice(req, issue_flags);
8386 case IORING_OP_PROVIDE_BUFFERS:
8387 ret = io_provide_buffers(req, issue_flags);
8389 case IORING_OP_REMOVE_BUFFERS:
8390 ret = io_remove_buffers(req, issue_flags);
8393 ret = io_tee(req, issue_flags);
8395 case IORING_OP_SHUTDOWN:
8396 ret = io_shutdown(req, issue_flags);
8398 case IORING_OP_RENAMEAT:
8399 ret = io_renameat(req, issue_flags);
8401 case IORING_OP_UNLINKAT:
8402 ret = io_unlinkat(req, issue_flags);
8404 case IORING_OP_MKDIRAT:
8405 ret = io_mkdirat(req, issue_flags);
8407 case IORING_OP_SYMLINKAT:
8408 ret = io_symlinkat(req, issue_flags);
8410 case IORING_OP_LINKAT:
8411 ret = io_linkat(req, issue_flags);
8413 case IORING_OP_MSG_RING:
8414 ret = io_msg_ring(req, issue_flags);
8416 case IORING_OP_FSETXATTR:
8417 ret = io_fsetxattr(req, issue_flags);
8419 case IORING_OP_SETXATTR:
8420 ret = io_setxattr(req, issue_flags);
8422 case IORING_OP_FGETXATTR:
8423 ret = io_fgetxattr(req, issue_flags);
8425 case IORING_OP_GETXATTR:
8426 ret = io_getxattr(req, issue_flags);
8428 case IORING_OP_SOCKET:
8429 ret = io_socket(req, issue_flags);
8431 case IORING_OP_URING_CMD:
8432 ret = io_uring_cmd(req, issue_flags);
8439 if (!io_op_defs[req->opcode].audit_skip)
8440 audit_uring_exit(!ret, ret);
8443 revert_creds(creds);
8446 /* If the op doesn't have a file, we're not polling for it */
8447 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8448 io_iopoll_req_issued(req, issue_flags);
8453 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8455 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8457 req = io_put_req_find_next(req);
8458 return req ? &req->work : NULL;
8461 static void io_wq_submit_work(struct io_wq_work *work)
8463 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8464 const struct io_op_def *def = &io_op_defs[req->opcode];
8465 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8466 bool needs_poll = false;
8467 int ret = 0, err = -ECANCELED;
8469 /* one will be dropped by ->io_free_work() after returning to io-wq */
8470 if (!(req->flags & REQ_F_REFCOUNT))
8471 __io_req_set_refcount(req, 2);
8475 io_arm_ltimeout(req);
8477 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8478 if (work->flags & IO_WQ_WORK_CANCEL) {
8480 io_req_task_queue_fail(req, err);
8483 if (!io_assign_file(req, issue_flags)) {
8485 work->flags |= IO_WQ_WORK_CANCEL;
8489 if (req->flags & REQ_F_FORCE_ASYNC) {
8490 bool opcode_poll = def->pollin || def->pollout;
8492 if (opcode_poll && file_can_poll(req->file)) {
8494 issue_flags |= IO_URING_F_NONBLOCK;
8499 ret = io_issue_sqe(req, issue_flags);
8503 * We can get EAGAIN for iopolled IO even though we're
8504 * forcing a sync submission from here, since we can't
8505 * wait for request slots on the block side.
8508 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8514 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8516 /* aborted or ready, in either case retry blocking */
8518 issue_flags &= ~IO_URING_F_NONBLOCK;
8521 /* avoid locking problems by failing it from a clean context */
8523 io_req_task_queue_fail(req, ret);
8526 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8529 return &table->files[i];
8532 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8535 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8537 return (struct file *) (slot->file_ptr & FFS_MASK);
8540 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8542 unsigned long file_ptr = (unsigned long) file;
8544 file_ptr |= io_file_get_flags(file);
8545 file_slot->file_ptr = file_ptr;
8548 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8549 unsigned int issue_flags)
8551 struct io_ring_ctx *ctx = req->ctx;
8552 struct file *file = NULL;
8553 unsigned long file_ptr;
8555 io_ring_submit_lock(ctx, issue_flags);
8557 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8559 fd = array_index_nospec(fd, ctx->nr_user_files);
8560 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8561 file = (struct file *) (file_ptr & FFS_MASK);
8562 file_ptr &= ~FFS_MASK;
8563 /* mask in overlapping REQ_F and FFS bits */
8564 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8565 io_req_set_rsrc_node(req, ctx, 0);
8566 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8568 io_ring_submit_unlock(ctx, issue_flags);
8573 * Drop the file for requeue operations. Only used of req->file is the
8574 * io_uring descriptor itself.
8576 static void io_drop_inflight_file(struct io_kiocb *req)
8578 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
8581 req->flags &= ~REQ_F_INFLIGHT;
8585 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8587 struct file *file = fget(fd);
8589 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8591 /* we don't allow fixed io_uring files */
8592 if (file && file->f_op == &io_uring_fops)
8593 req->flags |= REQ_F_INFLIGHT;
8597 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8599 struct io_kiocb *prev = req->timeout.prev;
8603 if (!(req->task->flags & PF_EXITING)) {
8604 struct io_cancel_data cd = {
8606 .data = prev->cqe.user_data,
8609 ret = io_try_cancel(req, &cd);
8611 io_req_complete_post(req, ret ?: -ETIME, 0);
8614 io_req_complete_post(req, -ETIME, 0);
8618 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8620 struct io_timeout_data *data = container_of(timer,
8621 struct io_timeout_data, timer);
8622 struct io_kiocb *prev, *req = data->req;
8623 struct io_ring_ctx *ctx = req->ctx;
8624 unsigned long flags;
8626 spin_lock_irqsave(&ctx->timeout_lock, flags);
8627 prev = req->timeout.head;
8628 req->timeout.head = NULL;
8631 * We don't expect the list to be empty, that will only happen if we
8632 * race with the completion of the linked work.
8635 io_remove_next_linked(prev);
8636 if (!req_ref_inc_not_zero(prev))
8639 list_del(&req->timeout.list);
8640 req->timeout.prev = prev;
8641 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8643 req->io_task_work.func = io_req_task_link_timeout;
8644 io_req_task_work_add(req);
8645 return HRTIMER_NORESTART;
8648 static void io_queue_linked_timeout(struct io_kiocb *req)
8650 struct io_ring_ctx *ctx = req->ctx;
8652 spin_lock_irq(&ctx->timeout_lock);
8654 * If the back reference is NULL, then our linked request finished
8655 * before we got a chance to setup the timer
8657 if (req->timeout.head) {
8658 struct io_timeout_data *data = req->async_data;
8660 data->timer.function = io_link_timeout_fn;
8661 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8663 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8665 spin_unlock_irq(&ctx->timeout_lock);
8666 /* drop submission reference */
8670 static void io_queue_async(struct io_kiocb *req, int ret)
8671 __must_hold(&req->ctx->uring_lock)
8673 struct io_kiocb *linked_timeout;
8675 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8676 io_req_complete_failed(req, ret);
8680 linked_timeout = io_prep_linked_timeout(req);
8682 switch (io_arm_poll_handler(req, 0)) {
8683 case IO_APOLL_READY:
8684 io_req_task_queue(req);
8686 case IO_APOLL_ABORTED:
8688 * Queued up for async execution, worker will release
8689 * submit reference when the iocb is actually submitted.
8691 io_queue_iowq(req, NULL);
8698 io_queue_linked_timeout(linked_timeout);
8701 static inline void io_queue_sqe(struct io_kiocb *req)
8702 __must_hold(&req->ctx->uring_lock)
8706 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8708 if (req->flags & REQ_F_COMPLETE_INLINE) {
8709 io_req_add_compl_list(req);
8713 * We async punt it if the file wasn't marked NOWAIT, or if the file
8714 * doesn't support non-blocking read/write attempts
8717 io_arm_ltimeout(req);
8719 io_queue_async(req, ret);
8722 static void io_queue_sqe_fallback(struct io_kiocb *req)
8723 __must_hold(&req->ctx->uring_lock)
8725 if (unlikely(req->flags & REQ_F_FAIL)) {
8727 * We don't submit, fail them all, for that replace hardlinks
8728 * with normal links. Extra REQ_F_LINK is tolerated.
8730 req->flags &= ~REQ_F_HARDLINK;
8731 req->flags |= REQ_F_LINK;
8732 io_req_complete_failed(req, req->cqe.res);
8733 } else if (unlikely(req->ctx->drain_active)) {
8736 int ret = io_req_prep_async(req);
8739 io_req_complete_failed(req, ret);
8741 io_queue_iowq(req, NULL);
8746 * Check SQE restrictions (opcode and flags).
8748 * Returns 'true' if SQE is allowed, 'false' otherwise.
8750 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8751 struct io_kiocb *req,
8752 unsigned int sqe_flags)
8754 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8757 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8758 ctx->restrictions.sqe_flags_required)
8761 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8762 ctx->restrictions.sqe_flags_required))
8768 static void io_init_req_drain(struct io_kiocb *req)
8770 struct io_ring_ctx *ctx = req->ctx;
8771 struct io_kiocb *head = ctx->submit_state.link.head;
8773 ctx->drain_active = true;
8776 * If we need to drain a request in the middle of a link, drain
8777 * the head request and the next request/link after the current
8778 * link. Considering sequential execution of links,
8779 * REQ_F_IO_DRAIN will be maintained for every request of our
8782 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8783 ctx->drain_next = true;
8787 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8788 const struct io_uring_sqe *sqe)
8789 __must_hold(&ctx->uring_lock)
8791 unsigned int sqe_flags;
8795 /* req is partially pre-initialised, see io_preinit_req() */
8796 req->opcode = opcode = READ_ONCE(sqe->opcode);
8797 /* same numerical values with corresponding REQ_F_*, safe to copy */
8798 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8799 req->cqe.user_data = READ_ONCE(sqe->user_data);
8801 req->rsrc_node = NULL;
8802 req->task = current;
8804 if (unlikely(opcode >= IORING_OP_LAST)) {
8808 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8809 /* enforce forwards compatibility on users */
8810 if (sqe_flags & ~SQE_VALID_FLAGS)
8812 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8813 if (!io_op_defs[opcode].buffer_select)
8815 req->buf_index = READ_ONCE(sqe->buf_group);
8817 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8818 ctx->drain_disabled = true;
8819 if (sqe_flags & IOSQE_IO_DRAIN) {
8820 if (ctx->drain_disabled)
8822 io_init_req_drain(req);
8825 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8826 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8828 /* knock it to the slow queue path, will be drained there */
8829 if (ctx->drain_active)
8830 req->flags |= REQ_F_FORCE_ASYNC;
8831 /* if there is no link, we're at "next" request and need to drain */
8832 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8833 ctx->drain_next = false;
8834 ctx->drain_active = true;
8835 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8839 if (!io_op_defs[opcode].ioprio && sqe->ioprio)
8841 if (!io_op_defs[opcode].iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8844 if (io_op_defs[opcode].needs_file) {
8845 struct io_submit_state *state = &ctx->submit_state;
8847 req->cqe.fd = READ_ONCE(sqe->fd);
8850 * Plug now if we have more than 2 IO left after this, and the
8851 * target is potentially a read/write to block based storage.
8853 if (state->need_plug && io_op_defs[opcode].plug) {
8854 state->plug_started = true;
8855 state->need_plug = false;
8856 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8860 personality = READ_ONCE(sqe->personality);
8864 req->creds = xa_load(&ctx->personalities, personality);
8867 get_cred(req->creds);
8868 ret = security_uring_override_creds(req->creds);
8870 put_cred(req->creds);
8873 req->flags |= REQ_F_CREDS;
8876 return io_req_prep(req, sqe);
8879 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8880 struct io_kiocb *req, int ret)
8882 struct io_ring_ctx *ctx = req->ctx;
8883 struct io_submit_link *link = &ctx->submit_state.link;
8884 struct io_kiocb *head = link->head;
8886 trace_io_uring_req_failed(sqe, ctx, req, ret);
8889 * Avoid breaking links in the middle as it renders links with SQPOLL
8890 * unusable. Instead of failing eagerly, continue assembling the link if
8891 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8892 * should find the flag and handle the rest.
8894 req_fail_link_node(req, ret);
8895 if (head && !(head->flags & REQ_F_FAIL))
8896 req_fail_link_node(head, -ECANCELED);
8898 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8900 link->last->link = req;
8904 io_queue_sqe_fallback(req);
8909 link->last->link = req;
8916 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8917 const struct io_uring_sqe *sqe)
8918 __must_hold(&ctx->uring_lock)
8920 struct io_submit_link *link = &ctx->submit_state.link;
8923 ret = io_init_req(ctx, req, sqe);
8925 return io_submit_fail_init(sqe, req, ret);
8927 /* don't need @sqe from now on */
8928 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8930 ctx->flags & IORING_SETUP_SQPOLL);
8933 * If we already have a head request, queue this one for async
8934 * submittal once the head completes. If we don't have a head but
8935 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8936 * submitted sync once the chain is complete. If none of those
8937 * conditions are true (normal request), then just queue it.
8939 if (unlikely(link->head)) {
8940 ret = io_req_prep_async(req);
8942 return io_submit_fail_init(sqe, req, ret);
8944 trace_io_uring_link(ctx, req, link->head);
8945 link->last->link = req;
8948 if (req->flags & IO_REQ_LINK_FLAGS)
8950 /* last request of the link, flush it */
8953 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8956 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8957 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8958 if (req->flags & IO_REQ_LINK_FLAGS) {
8963 io_queue_sqe_fallback(req);
8973 * Batched submission is done, ensure local IO is flushed out.
8975 static void io_submit_state_end(struct io_ring_ctx *ctx)
8977 struct io_submit_state *state = &ctx->submit_state;
8979 if (unlikely(state->link.head))
8980 io_queue_sqe_fallback(state->link.head);
8981 /* flush only after queuing links as they can generate completions */
8982 io_submit_flush_completions(ctx);
8983 if (state->plug_started)
8984 blk_finish_plug(&state->plug);
8988 * Start submission side cache.
8990 static void io_submit_state_start(struct io_submit_state *state,
8991 unsigned int max_ios)
8993 state->plug_started = false;
8994 state->need_plug = max_ios > 2;
8995 state->submit_nr = max_ios;
8996 /* set only head, no need to init link_last in advance */
8997 state->link.head = NULL;
9000 static void io_commit_sqring(struct io_ring_ctx *ctx)
9002 struct io_rings *rings = ctx->rings;
9005 * Ensure any loads from the SQEs are done at this point,
9006 * since once we write the new head, the application could
9007 * write new data to them.
9009 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
9013 * Fetch an sqe, if one is available. Note this returns a pointer to memory
9014 * that is mapped by userspace. This means that care needs to be taken to
9015 * ensure that reads are stable, as we cannot rely on userspace always
9016 * being a good citizen. If members of the sqe are validated and then later
9017 * used, it's important that those reads are done through READ_ONCE() to
9018 * prevent a re-load down the line.
9020 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
9022 unsigned head, mask = ctx->sq_entries - 1;
9023 unsigned sq_idx = ctx->cached_sq_head++ & mask;
9026 * The cached sq head (or cq tail) serves two purposes:
9028 * 1) allows us to batch the cost of updating the user visible
9030 * 2) allows the kernel side to track the head on its own, even
9031 * though the application is the one updating it.
9033 head = READ_ONCE(ctx->sq_array[sq_idx]);
9034 if (likely(head < ctx->sq_entries)) {
9035 /* double index for 128-byte SQEs, twice as long */
9036 if (ctx->flags & IORING_SETUP_SQE128)
9038 return &ctx->sq_sqes[head];
9041 /* drop invalid entries */
9043 WRITE_ONCE(ctx->rings->sq_dropped,
9044 READ_ONCE(ctx->rings->sq_dropped) + 1);
9048 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
9049 __must_hold(&ctx->uring_lock)
9051 unsigned int entries = io_sqring_entries(ctx);
9055 if (unlikely(!entries))
9057 /* make sure SQ entry isn't read before tail */
9058 ret = left = min3(nr, ctx->sq_entries, entries);
9059 io_get_task_refs(left);
9060 io_submit_state_start(&ctx->submit_state, left);
9063 const struct io_uring_sqe *sqe;
9064 struct io_kiocb *req;
9066 if (unlikely(!io_alloc_req_refill(ctx)))
9068 req = io_alloc_req(ctx);
9069 sqe = io_get_sqe(ctx);
9070 if (unlikely(!sqe)) {
9071 io_req_add_to_cache(req, ctx);
9076 * Continue submitting even for sqe failure if the
9077 * ring was setup with IORING_SETUP_SUBMIT_ALL
9079 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
9080 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
9086 if (unlikely(left)) {
9088 /* try again if it submitted nothing and can't allocate a req */
9089 if (!ret && io_req_cache_empty(ctx))
9091 current->io_uring->cached_refs += left;
9094 io_submit_state_end(ctx);
9095 /* Commit SQ ring head once we've consumed and submitted all SQEs */
9096 io_commit_sqring(ctx);
9100 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
9102 return READ_ONCE(sqd->state);
9105 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
9107 unsigned int to_submit;
9110 to_submit = io_sqring_entries(ctx);
9111 /* if we're handling multiple rings, cap submit size for fairness */
9112 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
9113 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
9115 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
9116 const struct cred *creds = NULL;
9118 if (ctx->sq_creds != current_cred())
9119 creds = override_creds(ctx->sq_creds);
9121 mutex_lock(&ctx->uring_lock);
9122 if (!wq_list_empty(&ctx->iopoll_list))
9123 io_do_iopoll(ctx, true);
9126 * Don't submit if refs are dying, good for io_uring_register(),
9127 * but also it is relied upon by io_ring_exit_work()
9129 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
9130 !(ctx->flags & IORING_SETUP_R_DISABLED))
9131 ret = io_submit_sqes(ctx, to_submit);
9132 mutex_unlock(&ctx->uring_lock);
9134 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
9135 wake_up(&ctx->sqo_sq_wait);
9137 revert_creds(creds);
9143 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
9145 struct io_ring_ctx *ctx;
9146 unsigned sq_thread_idle = 0;
9148 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9149 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
9150 sqd->sq_thread_idle = sq_thread_idle;
9153 static bool io_sqd_handle_event(struct io_sq_data *sqd)
9155 bool did_sig = false;
9156 struct ksignal ksig;
9158 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
9159 signal_pending(current)) {
9160 mutex_unlock(&sqd->lock);
9161 if (signal_pending(current))
9162 did_sig = get_signal(&ksig);
9164 mutex_lock(&sqd->lock);
9166 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9169 static int io_sq_thread(void *data)
9171 struct io_sq_data *sqd = data;
9172 struct io_ring_ctx *ctx;
9173 unsigned long timeout = 0;
9174 char buf[TASK_COMM_LEN];
9177 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
9178 set_task_comm(current, buf);
9180 if (sqd->sq_cpu != -1)
9181 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
9183 set_cpus_allowed_ptr(current, cpu_online_mask);
9184 current->flags |= PF_NO_SETAFFINITY;
9186 audit_alloc_kernel(current);
9188 mutex_lock(&sqd->lock);
9190 bool cap_entries, sqt_spin = false;
9192 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
9193 if (io_sqd_handle_event(sqd))
9195 timeout = jiffies + sqd->sq_thread_idle;
9198 cap_entries = !list_is_singular(&sqd->ctx_list);
9199 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9200 int ret = __io_sq_thread(ctx, cap_entries);
9202 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
9205 if (io_run_task_work())
9208 if (sqt_spin || !time_after(jiffies, timeout)) {
9211 timeout = jiffies + sqd->sq_thread_idle;
9215 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
9216 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
9217 bool needs_sched = true;
9219 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9220 atomic_or(IORING_SQ_NEED_WAKEUP,
9221 &ctx->rings->sq_flags);
9222 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
9223 !wq_list_empty(&ctx->iopoll_list)) {
9224 needs_sched = false;
9229 * Ensure the store of the wakeup flag is not
9230 * reordered with the load of the SQ tail
9232 smp_mb__after_atomic();
9234 if (io_sqring_entries(ctx)) {
9235 needs_sched = false;
9241 mutex_unlock(&sqd->lock);
9243 mutex_lock(&sqd->lock);
9245 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9246 atomic_andnot(IORING_SQ_NEED_WAKEUP,
9247 &ctx->rings->sq_flags);
9250 finish_wait(&sqd->wait, &wait);
9251 timeout = jiffies + sqd->sq_thread_idle;
9254 io_uring_cancel_generic(true, sqd);
9256 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9257 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9259 mutex_unlock(&sqd->lock);
9261 audit_free(current);
9263 complete(&sqd->exited);
9267 struct io_wait_queue {
9268 struct wait_queue_entry wq;
9269 struct io_ring_ctx *ctx;
9271 unsigned nr_timeouts;
9274 static inline bool io_should_wake(struct io_wait_queue *iowq)
9276 struct io_ring_ctx *ctx = iowq->ctx;
9277 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9280 * Wake up if we have enough events, or if a timeout occurred since we
9281 * started waiting. For timeouts, we always want to return to userspace,
9282 * regardless of event count.
9284 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9287 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9288 int wake_flags, void *key)
9290 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9294 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9295 * the task, and the next invocation will do it.
9297 if (io_should_wake(iowq) ||
9298 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9299 return autoremove_wake_function(curr, mode, wake_flags, key);
9303 static int io_run_task_work_sig(void)
9305 if (io_run_task_work())
9307 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9308 return -ERESTARTSYS;
9309 if (task_sigpending(current))
9314 /* when returns >0, the caller should retry */
9315 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9316 struct io_wait_queue *iowq,
9320 unsigned long check_cq;
9322 /* make sure we run task_work before checking for signals */
9323 ret = io_run_task_work_sig();
9324 if (ret || io_should_wake(iowq))
9326 check_cq = READ_ONCE(ctx->check_cq);
9327 /* let the caller flush overflows, retry */
9328 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9330 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9332 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9338 * Wait until events become available, if we don't already have some. The
9339 * application must reap them itself, as they reside on the shared cq ring.
9341 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9342 const sigset_t __user *sig, size_t sigsz,
9343 struct __kernel_timespec __user *uts)
9345 struct io_wait_queue iowq;
9346 struct io_rings *rings = ctx->rings;
9347 ktime_t timeout = KTIME_MAX;
9351 io_cqring_overflow_flush(ctx);
9352 if (io_cqring_events(ctx) >= min_events)
9354 if (!io_run_task_work())
9359 #ifdef CONFIG_COMPAT
9360 if (in_compat_syscall())
9361 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9365 ret = set_user_sigmask(sig, sigsz);
9372 struct timespec64 ts;
9374 if (get_timespec64(&ts, uts))
9376 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9379 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9380 iowq.wq.private = current;
9381 INIT_LIST_HEAD(&iowq.wq.entry);
9383 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9384 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9386 trace_io_uring_cqring_wait(ctx, min_events);
9388 /* if we can't even flush overflow, don't wait for more */
9389 if (!io_cqring_overflow_flush(ctx)) {
9393 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9394 TASK_INTERRUPTIBLE);
9395 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9399 finish_wait(&ctx->cq_wait, &iowq.wq);
9400 restore_saved_sigmask_unless(ret == -EINTR);
9402 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9405 static void io_free_page_table(void **table, size_t size)
9407 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9409 for (i = 0; i < nr_tables; i++)
9414 static __cold void **io_alloc_page_table(size_t size)
9416 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9417 size_t init_size = size;
9420 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9424 for (i = 0; i < nr_tables; i++) {
9425 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9427 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9429 io_free_page_table(table, init_size);
9437 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9439 percpu_ref_exit(&ref_node->refs);
9443 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9445 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9446 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9447 unsigned long flags;
9448 bool first_add = false;
9449 unsigned long delay = HZ;
9451 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9454 /* if we are mid-quiesce then do not delay */
9455 if (node->rsrc_data->quiesce)
9458 while (!list_empty(&ctx->rsrc_ref_list)) {
9459 node = list_first_entry(&ctx->rsrc_ref_list,
9460 struct io_rsrc_node, node);
9461 /* recycle ref nodes in order */
9464 list_del(&node->node);
9465 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9467 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9470 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9473 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9475 struct io_rsrc_node *ref_node;
9477 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9481 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9486 INIT_LIST_HEAD(&ref_node->node);
9487 INIT_LIST_HEAD(&ref_node->rsrc_list);
9488 ref_node->done = false;
9492 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9493 struct io_rsrc_data *data_to_kill)
9494 __must_hold(&ctx->uring_lock)
9496 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9497 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9499 io_rsrc_refs_drop(ctx);
9502 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9504 rsrc_node->rsrc_data = data_to_kill;
9505 spin_lock_irq(&ctx->rsrc_ref_lock);
9506 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9507 spin_unlock_irq(&ctx->rsrc_ref_lock);
9509 atomic_inc(&data_to_kill->refs);
9510 percpu_ref_kill(&rsrc_node->refs);
9511 ctx->rsrc_node = NULL;
9514 if (!ctx->rsrc_node) {
9515 ctx->rsrc_node = ctx->rsrc_backup_node;
9516 ctx->rsrc_backup_node = NULL;
9520 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9522 if (ctx->rsrc_backup_node)
9524 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9525 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9528 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9529 struct io_ring_ctx *ctx)
9533 /* As we may drop ->uring_lock, other task may have started quiesce */
9537 data->quiesce = true;
9539 ret = io_rsrc_node_switch_start(ctx);
9542 io_rsrc_node_switch(ctx, data);
9544 /* kill initial ref, already quiesced if zero */
9545 if (atomic_dec_and_test(&data->refs))
9547 mutex_unlock(&ctx->uring_lock);
9548 flush_delayed_work(&ctx->rsrc_put_work);
9549 ret = wait_for_completion_interruptible(&data->done);
9551 mutex_lock(&ctx->uring_lock);
9552 if (atomic_read(&data->refs) > 0) {
9554 * it has been revived by another thread while
9557 mutex_unlock(&ctx->uring_lock);
9563 atomic_inc(&data->refs);
9564 /* wait for all works potentially completing data->done */
9565 flush_delayed_work(&ctx->rsrc_put_work);
9566 reinit_completion(&data->done);
9568 ret = io_run_task_work_sig();
9569 mutex_lock(&ctx->uring_lock);
9571 data->quiesce = false;
9576 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9578 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9579 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9581 return &data->tags[table_idx][off];
9584 static void io_rsrc_data_free(struct io_rsrc_data *data)
9586 size_t size = data->nr * sizeof(data->tags[0][0]);
9589 io_free_page_table((void **)data->tags, size);
9593 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9594 u64 __user *utags, unsigned nr,
9595 struct io_rsrc_data **pdata)
9597 struct io_rsrc_data *data;
9601 data = kzalloc(sizeof(*data), GFP_KERNEL);
9604 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9612 data->do_put = do_put;
9615 for (i = 0; i < nr; i++) {
9616 u64 *tag_slot = io_get_tag_slot(data, i);
9618 if (copy_from_user(tag_slot, &utags[i],
9624 atomic_set(&data->refs, 1);
9625 init_completion(&data->done);
9629 io_rsrc_data_free(data);
9633 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9635 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9636 GFP_KERNEL_ACCOUNT);
9637 if (unlikely(!table->files))
9640 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9641 if (unlikely(!table->bitmap)) {
9642 kvfree(table->files);
9649 static void io_free_file_tables(struct io_file_table *table)
9651 kvfree(table->files);
9652 bitmap_free(table->bitmap);
9653 table->files = NULL;
9654 table->bitmap = NULL;
9657 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9659 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9660 __set_bit(bit, table->bitmap);
9661 if (bit == table->alloc_hint)
9662 table->alloc_hint++;
9665 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9667 __clear_bit(bit, table->bitmap);
9668 table->alloc_hint = bit;
9671 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9673 #if !defined(IO_URING_SCM_ALL)
9676 for (i = 0; i < ctx->nr_user_files; i++) {
9677 struct file *file = io_file_from_index(ctx, i);
9681 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9683 io_file_bitmap_clear(&ctx->file_table, i);
9688 #if defined(CONFIG_UNIX)
9689 if (ctx->ring_sock) {
9690 struct sock *sock = ctx->ring_sock->sk;
9691 struct sk_buff *skb;
9693 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9697 io_free_file_tables(&ctx->file_table);
9698 io_rsrc_data_free(ctx->file_data);
9699 ctx->file_data = NULL;
9700 ctx->nr_user_files = 0;
9703 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9707 if (!ctx->file_data)
9709 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9711 __io_sqe_files_unregister(ctx);
9715 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9716 __releases(&sqd->lock)
9718 WARN_ON_ONCE(sqd->thread == current);
9721 * Do the dance but not conditional clear_bit() because it'd race with
9722 * other threads incrementing park_pending and setting the bit.
9724 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9725 if (atomic_dec_return(&sqd->park_pending))
9726 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9727 mutex_unlock(&sqd->lock);
9730 static void io_sq_thread_park(struct io_sq_data *sqd)
9731 __acquires(&sqd->lock)
9733 WARN_ON_ONCE(sqd->thread == current);
9735 atomic_inc(&sqd->park_pending);
9736 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9737 mutex_lock(&sqd->lock);
9739 wake_up_process(sqd->thread);
9742 static void io_sq_thread_stop(struct io_sq_data *sqd)
9744 WARN_ON_ONCE(sqd->thread == current);
9745 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9747 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9748 mutex_lock(&sqd->lock);
9750 wake_up_process(sqd->thread);
9751 mutex_unlock(&sqd->lock);
9752 wait_for_completion(&sqd->exited);
9755 static void io_put_sq_data(struct io_sq_data *sqd)
9757 if (refcount_dec_and_test(&sqd->refs)) {
9758 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9760 io_sq_thread_stop(sqd);
9765 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9767 struct io_sq_data *sqd = ctx->sq_data;
9770 io_sq_thread_park(sqd);
9771 list_del_init(&ctx->sqd_list);
9772 io_sqd_update_thread_idle(sqd);
9773 io_sq_thread_unpark(sqd);
9775 io_put_sq_data(sqd);
9776 ctx->sq_data = NULL;
9780 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9782 struct io_ring_ctx *ctx_attach;
9783 struct io_sq_data *sqd;
9786 f = fdget(p->wq_fd);
9788 return ERR_PTR(-ENXIO);
9789 if (f.file->f_op != &io_uring_fops) {
9791 return ERR_PTR(-EINVAL);
9794 ctx_attach = f.file->private_data;
9795 sqd = ctx_attach->sq_data;
9798 return ERR_PTR(-EINVAL);
9800 if (sqd->task_tgid != current->tgid) {
9802 return ERR_PTR(-EPERM);
9805 refcount_inc(&sqd->refs);
9810 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9813 struct io_sq_data *sqd;
9816 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9817 sqd = io_attach_sq_data(p);
9822 /* fall through for EPERM case, setup new sqd/task */
9823 if (PTR_ERR(sqd) != -EPERM)
9827 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9829 return ERR_PTR(-ENOMEM);
9831 atomic_set(&sqd->park_pending, 0);
9832 refcount_set(&sqd->refs, 1);
9833 INIT_LIST_HEAD(&sqd->ctx_list);
9834 mutex_init(&sqd->lock);
9835 init_waitqueue_head(&sqd->wait);
9836 init_completion(&sqd->exited);
9841 * Ensure the UNIX gc is aware of our file set, so we are certain that
9842 * the io_uring can be safely unregistered on process exit, even if we have
9843 * loops in the file referencing. We account only files that can hold other
9844 * files because otherwise they can't form a loop and so are not interesting
9847 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9849 #if defined(CONFIG_UNIX)
9850 struct sock *sk = ctx->ring_sock->sk;
9851 struct sk_buff_head *head = &sk->sk_receive_queue;
9852 struct scm_fp_list *fpl;
9853 struct sk_buff *skb;
9855 if (likely(!io_file_need_scm(file)))
9859 * See if we can merge this file into an existing skb SCM_RIGHTS
9860 * file set. If there's no room, fall back to allocating a new skb
9861 * and filling it in.
9863 spin_lock_irq(&head->lock);
9864 skb = skb_peek(head);
9865 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9866 __skb_unlink(skb, head);
9869 spin_unlock_irq(&head->lock);
9872 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9876 skb = alloc_skb(0, GFP_KERNEL);
9882 fpl->user = get_uid(current_user());
9883 fpl->max = SCM_MAX_FD;
9886 UNIXCB(skb).fp = fpl;
9888 skb->destructor = unix_destruct_scm;
9889 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9892 fpl = UNIXCB(skb).fp;
9893 fpl->fp[fpl->count++] = get_file(file);
9894 unix_inflight(fpl->user, file);
9895 skb_queue_head(head, skb);
9901 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9903 struct file *file = prsrc->file;
9904 #if defined(CONFIG_UNIX)
9905 struct sock *sock = ctx->ring_sock->sk;
9906 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9907 struct sk_buff *skb;
9910 if (!io_file_need_scm(file)) {
9915 __skb_queue_head_init(&list);
9918 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9919 * remove this entry and rearrange the file array.
9921 skb = skb_dequeue(head);
9923 struct scm_fp_list *fp;
9925 fp = UNIXCB(skb).fp;
9926 for (i = 0; i < fp->count; i++) {
9929 if (fp->fp[i] != file)
9932 unix_notinflight(fp->user, fp->fp[i]);
9933 left = fp->count - 1 - i;
9935 memmove(&fp->fp[i], &fp->fp[i + 1],
9936 left * sizeof(struct file *));
9943 __skb_queue_tail(&list, skb);
9953 __skb_queue_tail(&list, skb);
9955 skb = skb_dequeue(head);
9958 if (skb_peek(&list)) {
9959 spin_lock_irq(&head->lock);
9960 while ((skb = __skb_dequeue(&list)) != NULL)
9961 __skb_queue_tail(head, skb);
9962 spin_unlock_irq(&head->lock);
9969 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9971 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9972 struct io_ring_ctx *ctx = rsrc_data->ctx;
9973 struct io_rsrc_put *prsrc, *tmp;
9975 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9976 list_del(&prsrc->list);
9979 if (ctx->flags & IORING_SETUP_IOPOLL)
9980 mutex_lock(&ctx->uring_lock);
9982 spin_lock(&ctx->completion_lock);
9983 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9984 io_commit_cqring(ctx);
9985 spin_unlock(&ctx->completion_lock);
9986 io_cqring_ev_posted(ctx);
9988 if (ctx->flags & IORING_SETUP_IOPOLL)
9989 mutex_unlock(&ctx->uring_lock);
9992 rsrc_data->do_put(ctx, prsrc);
9996 io_rsrc_node_destroy(ref_node);
9997 if (atomic_dec_and_test(&rsrc_data->refs))
9998 complete(&rsrc_data->done);
10001 static void io_rsrc_put_work(struct work_struct *work)
10003 struct io_ring_ctx *ctx;
10004 struct llist_node *node;
10006 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
10007 node = llist_del_all(&ctx->rsrc_put_llist);
10010 struct io_rsrc_node *ref_node;
10011 struct llist_node *next = node->next;
10013 ref_node = llist_entry(node, struct io_rsrc_node, llist);
10014 __io_rsrc_put_work(ref_node);
10019 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
10020 unsigned nr_args, u64 __user *tags)
10022 __s32 __user *fds = (__s32 __user *) arg;
10027 if (ctx->file_data)
10031 if (nr_args > IORING_MAX_FIXED_FILES)
10033 if (nr_args > rlimit(RLIMIT_NOFILE))
10035 ret = io_rsrc_node_switch_start(ctx);
10038 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
10043 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
10044 io_rsrc_data_free(ctx->file_data);
10045 ctx->file_data = NULL;
10049 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
10050 struct io_fixed_file *file_slot;
10052 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
10056 /* allow sparse sets */
10057 if (!fds || fd == -1) {
10059 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
10066 if (unlikely(!file))
10070 * Don't allow io_uring instances to be registered. If UNIX
10071 * isn't enabled, then this causes a reference cycle and this
10072 * instance can never get freed. If UNIX is enabled we'll
10073 * handle it just fine, but there's still no point in allowing
10074 * a ring fd as it doesn't support regular read/write anyway.
10076 if (file->f_op == &io_uring_fops) {
10080 ret = io_scm_file_account(ctx, file);
10085 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10086 io_fixed_file_set(file_slot, file);
10087 io_file_bitmap_set(&ctx->file_table, i);
10090 io_rsrc_node_switch(ctx, NULL);
10093 __io_sqe_files_unregister(ctx);
10097 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
10098 struct io_rsrc_node *node, void *rsrc)
10100 u64 *tag_slot = io_get_tag_slot(data, idx);
10101 struct io_rsrc_put *prsrc;
10103 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
10107 prsrc->tag = *tag_slot;
10109 prsrc->rsrc = rsrc;
10110 list_add(&prsrc->list, &node->rsrc_list);
10114 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
10115 unsigned int issue_flags, u32 slot_index)
10117 struct io_ring_ctx *ctx = req->ctx;
10118 bool needs_switch = false;
10119 struct io_fixed_file *file_slot;
10122 io_ring_submit_lock(ctx, issue_flags);
10123 if (file->f_op == &io_uring_fops)
10126 if (!ctx->file_data)
10129 if (slot_index >= ctx->nr_user_files)
10132 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
10133 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
10135 if (file_slot->file_ptr) {
10136 struct file *old_file;
10138 ret = io_rsrc_node_switch_start(ctx);
10142 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10143 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
10144 ctx->rsrc_node, old_file);
10147 file_slot->file_ptr = 0;
10148 io_file_bitmap_clear(&ctx->file_table, slot_index);
10149 needs_switch = true;
10152 ret = io_scm_file_account(ctx, file);
10154 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
10155 io_fixed_file_set(file_slot, file);
10156 io_file_bitmap_set(&ctx->file_table, slot_index);
10160 io_rsrc_node_switch(ctx, ctx->file_data);
10161 io_ring_submit_unlock(ctx, issue_flags);
10167 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
10169 unsigned int offset = req->close.file_slot - 1;
10170 struct io_ring_ctx *ctx = req->ctx;
10171 struct io_fixed_file *file_slot;
10175 io_ring_submit_lock(ctx, issue_flags);
10177 if (unlikely(!ctx->file_data))
10180 if (offset >= ctx->nr_user_files)
10182 ret = io_rsrc_node_switch_start(ctx);
10186 offset = array_index_nospec(offset, ctx->nr_user_files);
10187 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
10189 if (!file_slot->file_ptr)
10192 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10193 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
10197 file_slot->file_ptr = 0;
10198 io_file_bitmap_clear(&ctx->file_table, offset);
10199 io_rsrc_node_switch(ctx, ctx->file_data);
10202 io_ring_submit_unlock(ctx, issue_flags);
10206 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
10207 struct io_uring_rsrc_update2 *up,
10210 u64 __user *tags = u64_to_user_ptr(up->tags);
10211 __s32 __user *fds = u64_to_user_ptr(up->data);
10212 struct io_rsrc_data *data = ctx->file_data;
10213 struct io_fixed_file *file_slot;
10215 int fd, i, err = 0;
10217 bool needs_switch = false;
10219 if (!ctx->file_data)
10221 if (up->offset + nr_args > ctx->nr_user_files)
10224 for (done = 0; done < nr_args; done++) {
10227 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
10228 copy_from_user(&fd, &fds[done], sizeof(fd))) {
10232 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
10236 if (fd == IORING_REGISTER_FILES_SKIP)
10239 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
10240 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10242 if (file_slot->file_ptr) {
10243 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10244 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
10247 file_slot->file_ptr = 0;
10248 io_file_bitmap_clear(&ctx->file_table, i);
10249 needs_switch = true;
10258 * Don't allow io_uring instances to be registered. If
10259 * UNIX isn't enabled, then this causes a reference
10260 * cycle and this instance can never get freed. If UNIX
10261 * is enabled we'll handle it just fine, but there's
10262 * still no point in allowing a ring fd as it doesn't
10263 * support regular read/write anyway.
10265 if (file->f_op == &io_uring_fops) {
10270 err = io_scm_file_account(ctx, file);
10275 *io_get_tag_slot(data, i) = tag;
10276 io_fixed_file_set(file_slot, file);
10277 io_file_bitmap_set(&ctx->file_table, i);
10282 io_rsrc_node_switch(ctx, data);
10283 return done ? done : err;
10286 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
10287 struct task_struct *task)
10289 struct io_wq_hash *hash;
10290 struct io_wq_data data;
10291 unsigned int concurrency;
10293 mutex_lock(&ctx->uring_lock);
10294 hash = ctx->hash_map;
10296 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10298 mutex_unlock(&ctx->uring_lock);
10299 return ERR_PTR(-ENOMEM);
10301 refcount_set(&hash->refs, 1);
10302 init_waitqueue_head(&hash->wait);
10303 ctx->hash_map = hash;
10305 mutex_unlock(&ctx->uring_lock);
10309 data.free_work = io_wq_free_work;
10310 data.do_work = io_wq_submit_work;
10312 /* Do QD, or 4 * CPUS, whatever is smallest */
10313 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10315 return io_wq_create(concurrency, &data);
10318 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10319 struct io_ring_ctx *ctx)
10321 struct io_uring_task *tctx;
10324 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10325 if (unlikely(!tctx))
10328 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10329 sizeof(struct file *), GFP_KERNEL);
10330 if (unlikely(!tctx->registered_rings)) {
10335 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10336 if (unlikely(ret)) {
10337 kfree(tctx->registered_rings);
10342 tctx->io_wq = io_init_wq_offload(ctx, task);
10343 if (IS_ERR(tctx->io_wq)) {
10344 ret = PTR_ERR(tctx->io_wq);
10345 percpu_counter_destroy(&tctx->inflight);
10346 kfree(tctx->registered_rings);
10351 xa_init(&tctx->xa);
10352 init_waitqueue_head(&tctx->wait);
10353 atomic_set(&tctx->in_idle, 0);
10354 task->io_uring = tctx;
10355 spin_lock_init(&tctx->task_lock);
10356 INIT_WQ_LIST(&tctx->task_list);
10357 INIT_WQ_LIST(&tctx->prio_task_list);
10358 init_task_work(&tctx->task_work, tctx_task_work);
10362 void __io_uring_free(struct task_struct *tsk)
10364 struct io_uring_task *tctx = tsk->io_uring;
10366 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10367 WARN_ON_ONCE(tctx->io_wq);
10368 WARN_ON_ONCE(tctx->cached_refs);
10370 kfree(tctx->registered_rings);
10371 percpu_counter_destroy(&tctx->inflight);
10373 tsk->io_uring = NULL;
10376 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10377 struct io_uring_params *p)
10381 /* Retain compatibility with failing for an invalid attach attempt */
10382 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10383 IORING_SETUP_ATTACH_WQ) {
10386 f = fdget(p->wq_fd);
10389 if (f.file->f_op != &io_uring_fops) {
10395 if (ctx->flags & IORING_SETUP_SQPOLL) {
10396 struct task_struct *tsk;
10397 struct io_sq_data *sqd;
10400 ret = security_uring_sqpoll();
10404 sqd = io_get_sq_data(p, &attached);
10406 ret = PTR_ERR(sqd);
10410 ctx->sq_creds = get_current_cred();
10411 ctx->sq_data = sqd;
10412 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10413 if (!ctx->sq_thread_idle)
10414 ctx->sq_thread_idle = HZ;
10416 io_sq_thread_park(sqd);
10417 list_add(&ctx->sqd_list, &sqd->ctx_list);
10418 io_sqd_update_thread_idle(sqd);
10419 /* don't attach to a dying SQPOLL thread, would be racy */
10420 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10421 io_sq_thread_unpark(sqd);
10428 if (p->flags & IORING_SETUP_SQ_AFF) {
10429 int cpu = p->sq_thread_cpu;
10432 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10439 sqd->task_pid = current->pid;
10440 sqd->task_tgid = current->tgid;
10441 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10443 ret = PTR_ERR(tsk);
10448 ret = io_uring_alloc_task_context(tsk, ctx);
10449 wake_up_new_task(tsk);
10452 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10453 /* Can't have SQ_AFF without SQPOLL */
10460 complete(&ctx->sq_data->exited);
10462 io_sq_thread_finish(ctx);
10466 static inline void __io_unaccount_mem(struct user_struct *user,
10467 unsigned long nr_pages)
10469 atomic_long_sub(nr_pages, &user->locked_vm);
10472 static inline int __io_account_mem(struct user_struct *user,
10473 unsigned long nr_pages)
10475 unsigned long page_limit, cur_pages, new_pages;
10477 /* Don't allow more pages than we can safely lock */
10478 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10481 cur_pages = atomic_long_read(&user->locked_vm);
10482 new_pages = cur_pages + nr_pages;
10483 if (new_pages > page_limit)
10485 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10486 new_pages) != cur_pages);
10491 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10494 __io_unaccount_mem(ctx->user, nr_pages);
10496 if (ctx->mm_account)
10497 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10500 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10505 ret = __io_account_mem(ctx->user, nr_pages);
10510 if (ctx->mm_account)
10511 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10516 static void io_mem_free(void *ptr)
10523 page = virt_to_head_page(ptr);
10524 if (put_page_testzero(page))
10525 free_compound_page(page);
10528 static void *io_mem_alloc(size_t size)
10530 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10532 return (void *) __get_free_pages(gfp, get_order(size));
10535 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10536 unsigned int cq_entries, size_t *sq_offset)
10538 struct io_rings *rings;
10539 size_t off, sq_array_size;
10541 off = struct_size(rings, cqes, cq_entries);
10542 if (off == SIZE_MAX)
10544 if (ctx->flags & IORING_SETUP_CQE32) {
10545 if (check_shl_overflow(off, 1, &off))
10550 off = ALIGN(off, SMP_CACHE_BYTES);
10558 sq_array_size = array_size(sizeof(u32), sq_entries);
10559 if (sq_array_size == SIZE_MAX)
10562 if (check_add_overflow(off, sq_array_size, &off))
10568 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10570 struct io_mapped_ubuf *imu = *slot;
10573 if (imu != ctx->dummy_ubuf) {
10574 for (i = 0; i < imu->nr_bvecs; i++)
10575 unpin_user_page(imu->bvec[i].bv_page);
10576 if (imu->acct_pages)
10577 io_unaccount_mem(ctx, imu->acct_pages);
10583 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10585 io_buffer_unmap(ctx, &prsrc->buf);
10589 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10593 for (i = 0; i < ctx->nr_user_bufs; i++)
10594 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10595 kfree(ctx->user_bufs);
10596 io_rsrc_data_free(ctx->buf_data);
10597 ctx->user_bufs = NULL;
10598 ctx->buf_data = NULL;
10599 ctx->nr_user_bufs = 0;
10602 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10606 if (!ctx->buf_data)
10609 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10611 __io_sqe_buffers_unregister(ctx);
10615 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10616 void __user *arg, unsigned index)
10618 struct iovec __user *src;
10620 #ifdef CONFIG_COMPAT
10622 struct compat_iovec __user *ciovs;
10623 struct compat_iovec ciov;
10625 ciovs = (struct compat_iovec __user *) arg;
10626 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10629 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10630 dst->iov_len = ciov.iov_len;
10634 src = (struct iovec __user *) arg;
10635 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10641 * Not super efficient, but this is just a registration time. And we do cache
10642 * the last compound head, so generally we'll only do a full search if we don't
10645 * We check if the given compound head page has already been accounted, to
10646 * avoid double accounting it. This allows us to account the full size of the
10647 * page, not just the constituent pages of a huge page.
10649 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10650 int nr_pages, struct page *hpage)
10654 /* check current page array */
10655 for (i = 0; i < nr_pages; i++) {
10656 if (!PageCompound(pages[i]))
10658 if (compound_head(pages[i]) == hpage)
10662 /* check previously registered pages */
10663 for (i = 0; i < ctx->nr_user_bufs; i++) {
10664 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10666 for (j = 0; j < imu->nr_bvecs; j++) {
10667 if (!PageCompound(imu->bvec[j].bv_page))
10669 if (compound_head(imu->bvec[j].bv_page) == hpage)
10677 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10678 int nr_pages, struct io_mapped_ubuf *imu,
10679 struct page **last_hpage)
10683 imu->acct_pages = 0;
10684 for (i = 0; i < nr_pages; i++) {
10685 if (!PageCompound(pages[i])) {
10688 struct page *hpage;
10690 hpage = compound_head(pages[i]);
10691 if (hpage == *last_hpage)
10693 *last_hpage = hpage;
10694 if (headpage_already_acct(ctx, pages, i, hpage))
10696 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10700 if (!imu->acct_pages)
10703 ret = io_account_mem(ctx, imu->acct_pages);
10705 imu->acct_pages = 0;
10709 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10712 unsigned long start, end, nr_pages;
10713 struct vm_area_struct **vmas = NULL;
10714 struct page **pages = NULL;
10715 int i, pret, ret = -ENOMEM;
10717 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10718 start = ubuf >> PAGE_SHIFT;
10719 nr_pages = end - start;
10721 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10725 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10731 mmap_read_lock(current->mm);
10732 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10734 if (pret == nr_pages) {
10735 /* don't support file backed memory */
10736 for (i = 0; i < nr_pages; i++) {
10737 struct vm_area_struct *vma = vmas[i];
10739 if (vma_is_shmem(vma))
10741 if (vma->vm_file &&
10742 !is_file_hugepages(vma->vm_file)) {
10747 *npages = nr_pages;
10749 ret = pret < 0 ? pret : -EFAULT;
10751 mmap_read_unlock(current->mm);
10754 * if we did partial map, or found file backed vmas,
10755 * release any pages we did get
10758 unpin_user_pages(pages, pret);
10766 pages = ERR_PTR(ret);
10771 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10772 struct io_mapped_ubuf **pimu,
10773 struct page **last_hpage)
10775 struct io_mapped_ubuf *imu = NULL;
10776 struct page **pages = NULL;
10779 int ret, nr_pages, i;
10781 if (!iov->iov_base) {
10782 *pimu = ctx->dummy_ubuf;
10789 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10791 if (IS_ERR(pages)) {
10792 ret = PTR_ERR(pages);
10797 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10801 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10803 unpin_user_pages(pages, nr_pages);
10807 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10808 size = iov->iov_len;
10809 for (i = 0; i < nr_pages; i++) {
10812 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10813 imu->bvec[i].bv_page = pages[i];
10814 imu->bvec[i].bv_len = vec_len;
10815 imu->bvec[i].bv_offset = off;
10819 /* store original address for later verification */
10820 imu->ubuf = (unsigned long) iov->iov_base;
10821 imu->ubuf_end = imu->ubuf + iov->iov_len;
10822 imu->nr_bvecs = nr_pages;
10832 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10834 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10835 return ctx->user_bufs ? 0 : -ENOMEM;
10838 static int io_buffer_validate(struct iovec *iov)
10840 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10843 * Don't impose further limits on the size and buffer
10844 * constraints here, we'll -EINVAL later when IO is
10845 * submitted if they are wrong.
10847 if (!iov->iov_base)
10848 return iov->iov_len ? -EFAULT : 0;
10852 /* arbitrary limit, but we need something */
10853 if (iov->iov_len > SZ_1G)
10856 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10862 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10863 unsigned int nr_args, u64 __user *tags)
10865 struct page *last_hpage = NULL;
10866 struct io_rsrc_data *data;
10870 if (ctx->user_bufs)
10872 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10874 ret = io_rsrc_node_switch_start(ctx);
10877 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10880 ret = io_buffers_map_alloc(ctx, nr_args);
10882 io_rsrc_data_free(data);
10886 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10888 ret = io_copy_iov(ctx, &iov, arg, i);
10891 ret = io_buffer_validate(&iov);
10895 memset(&iov, 0, sizeof(iov));
10898 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10903 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10909 WARN_ON_ONCE(ctx->buf_data);
10911 ctx->buf_data = data;
10913 __io_sqe_buffers_unregister(ctx);
10915 io_rsrc_node_switch(ctx, NULL);
10919 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10920 struct io_uring_rsrc_update2 *up,
10921 unsigned int nr_args)
10923 u64 __user *tags = u64_to_user_ptr(up->tags);
10924 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10925 struct page *last_hpage = NULL;
10926 bool needs_switch = false;
10930 if (!ctx->buf_data)
10932 if (up->offset + nr_args > ctx->nr_user_bufs)
10935 for (done = 0; done < nr_args; done++) {
10936 struct io_mapped_ubuf *imu;
10937 int offset = up->offset + done;
10940 err = io_copy_iov(ctx, &iov, iovs, done);
10943 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10947 err = io_buffer_validate(&iov);
10950 if (!iov.iov_base && tag) {
10954 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10958 i = array_index_nospec(offset, ctx->nr_user_bufs);
10959 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10960 err = io_queue_rsrc_removal(ctx->buf_data, i,
10961 ctx->rsrc_node, ctx->user_bufs[i]);
10962 if (unlikely(err)) {
10963 io_buffer_unmap(ctx, &imu);
10966 ctx->user_bufs[i] = NULL;
10967 needs_switch = true;
10970 ctx->user_bufs[i] = imu;
10971 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10975 io_rsrc_node_switch(ctx, ctx->buf_data);
10976 return done ? done : err;
10979 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10980 unsigned int eventfd_async)
10982 struct io_ev_fd *ev_fd;
10983 __s32 __user *fds = arg;
10986 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10987 lockdep_is_held(&ctx->uring_lock));
10991 if (copy_from_user(&fd, fds, sizeof(*fds)))
10994 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10998 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10999 if (IS_ERR(ev_fd->cq_ev_fd)) {
11000 int ret = PTR_ERR(ev_fd->cq_ev_fd);
11004 ev_fd->eventfd_async = eventfd_async;
11005 ctx->has_evfd = true;
11006 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
11010 static void io_eventfd_put(struct rcu_head *rcu)
11012 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
11014 eventfd_ctx_put(ev_fd->cq_ev_fd);
11018 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
11020 struct io_ev_fd *ev_fd;
11022 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11023 lockdep_is_held(&ctx->uring_lock));
11025 ctx->has_evfd = false;
11026 rcu_assign_pointer(ctx->io_ev_fd, NULL);
11027 call_rcu(&ev_fd->rcu, io_eventfd_put);
11034 static void io_destroy_buffers(struct io_ring_ctx *ctx)
11036 struct io_buffer_list *bl;
11037 unsigned long index;
11040 for (i = 0; i < BGID_ARRAY; i++) {
11043 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
11046 xa_for_each(&ctx->io_bl_xa, index, bl) {
11047 xa_erase(&ctx->io_bl_xa, bl->bgid);
11048 __io_remove_buffers(ctx, bl, -1U);
11051 while (!list_empty(&ctx->io_buffers_pages)) {
11054 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
11055 list_del_init(&page->lru);
11060 static void io_req_caches_free(struct io_ring_ctx *ctx)
11062 struct io_submit_state *state = &ctx->submit_state;
11065 mutex_lock(&ctx->uring_lock);
11066 io_flush_cached_locked_reqs(ctx, state);
11068 while (!io_req_cache_empty(ctx)) {
11069 struct io_wq_work_node *node;
11070 struct io_kiocb *req;
11072 node = wq_stack_extract(&state->free_list);
11073 req = container_of(node, struct io_kiocb, comp_list);
11074 kmem_cache_free(req_cachep, req);
11078 percpu_ref_put_many(&ctx->refs, nr);
11079 mutex_unlock(&ctx->uring_lock);
11082 static void io_wait_rsrc_data(struct io_rsrc_data *data)
11084 if (data && !atomic_dec_and_test(&data->refs))
11085 wait_for_completion(&data->done);
11088 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
11090 struct async_poll *apoll;
11092 while (!list_empty(&ctx->apoll_cache)) {
11093 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
11095 list_del(&apoll->poll.wait.entry);
11100 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
11102 io_sq_thread_finish(ctx);
11104 if (ctx->mm_account) {
11105 mmdrop(ctx->mm_account);
11106 ctx->mm_account = NULL;
11109 io_rsrc_refs_drop(ctx);
11110 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
11111 io_wait_rsrc_data(ctx->buf_data);
11112 io_wait_rsrc_data(ctx->file_data);
11114 mutex_lock(&ctx->uring_lock);
11116 __io_sqe_buffers_unregister(ctx);
11117 if (ctx->file_data)
11118 __io_sqe_files_unregister(ctx);
11120 __io_cqring_overflow_flush(ctx, true);
11121 io_eventfd_unregister(ctx);
11122 io_flush_apoll_cache(ctx);
11123 mutex_unlock(&ctx->uring_lock);
11124 io_destroy_buffers(ctx);
11126 put_cred(ctx->sq_creds);
11128 /* there are no registered resources left, nobody uses it */
11129 if (ctx->rsrc_node)
11130 io_rsrc_node_destroy(ctx->rsrc_node);
11131 if (ctx->rsrc_backup_node)
11132 io_rsrc_node_destroy(ctx->rsrc_backup_node);
11133 flush_delayed_work(&ctx->rsrc_put_work);
11134 flush_delayed_work(&ctx->fallback_work);
11136 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
11137 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
11139 #if defined(CONFIG_UNIX)
11140 if (ctx->ring_sock) {
11141 ctx->ring_sock->file = NULL; /* so that iput() is called */
11142 sock_release(ctx->ring_sock);
11145 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
11147 io_mem_free(ctx->rings);
11148 io_mem_free(ctx->sq_sqes);
11150 percpu_ref_exit(&ctx->refs);
11151 free_uid(ctx->user);
11152 io_req_caches_free(ctx);
11154 io_wq_put_hash(ctx->hash_map);
11155 kfree(ctx->cancel_hash);
11156 kfree(ctx->dummy_ubuf);
11158 xa_destroy(&ctx->io_bl_xa);
11162 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
11164 struct io_ring_ctx *ctx = file->private_data;
11167 poll_wait(file, &ctx->cq_wait, wait);
11169 * synchronizes with barrier from wq_has_sleeper call in
11173 if (!io_sqring_full(ctx))
11174 mask |= EPOLLOUT | EPOLLWRNORM;
11177 * Don't flush cqring overflow list here, just do a simple check.
11178 * Otherwise there could possible be ABBA deadlock:
11181 * lock(&ctx->uring_lock);
11183 * lock(&ctx->uring_lock);
11186 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
11187 * pushs them to do the flush.
11189 if (io_cqring_events(ctx) ||
11190 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
11191 mask |= EPOLLIN | EPOLLRDNORM;
11196 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
11198 const struct cred *creds;
11200 creds = xa_erase(&ctx->personalities, id);
11209 struct io_tctx_exit {
11210 struct callback_head task_work;
11211 struct completion completion;
11212 struct io_ring_ctx *ctx;
11215 static __cold void io_tctx_exit_cb(struct callback_head *cb)
11217 struct io_uring_task *tctx = current->io_uring;
11218 struct io_tctx_exit *work;
11220 work = container_of(cb, struct io_tctx_exit, task_work);
11222 * When @in_idle, we're in cancellation and it's racy to remove the
11223 * node. It'll be removed by the end of cancellation, just ignore it.
11225 if (!atomic_read(&tctx->in_idle))
11226 io_uring_del_tctx_node((unsigned long)work->ctx);
11227 complete(&work->completion);
11230 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
11232 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11234 return req->ctx == data;
11237 static __cold void io_ring_exit_work(struct work_struct *work)
11239 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
11240 unsigned long timeout = jiffies + HZ * 60 * 5;
11241 unsigned long interval = HZ / 20;
11242 struct io_tctx_exit exit;
11243 struct io_tctx_node *node;
11247 * If we're doing polled IO and end up having requests being
11248 * submitted async (out-of-line), then completions can come in while
11249 * we're waiting for refs to drop. We need to reap these manually,
11250 * as nobody else will be looking for them.
11253 io_uring_try_cancel_requests(ctx, NULL, true);
11254 if (ctx->sq_data) {
11255 struct io_sq_data *sqd = ctx->sq_data;
11256 struct task_struct *tsk;
11258 io_sq_thread_park(sqd);
11260 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
11261 io_wq_cancel_cb(tsk->io_uring->io_wq,
11262 io_cancel_ctx_cb, ctx, true);
11263 io_sq_thread_unpark(sqd);
11266 io_req_caches_free(ctx);
11268 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
11269 /* there is little hope left, don't run it too often */
11270 interval = HZ * 60;
11272 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
11274 init_completion(&exit.completion);
11275 init_task_work(&exit.task_work, io_tctx_exit_cb);
11278 * Some may use context even when all refs and requests have been put,
11279 * and they are free to do so while still holding uring_lock or
11280 * completion_lock, see io_req_task_submit(). Apart from other work,
11281 * this lock/unlock section also waits them to finish.
11283 mutex_lock(&ctx->uring_lock);
11284 while (!list_empty(&ctx->tctx_list)) {
11285 WARN_ON_ONCE(time_after(jiffies, timeout));
11287 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
11289 /* don't spin on a single task if cancellation failed */
11290 list_rotate_left(&ctx->tctx_list);
11291 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
11292 if (WARN_ON_ONCE(ret))
11295 mutex_unlock(&ctx->uring_lock);
11296 wait_for_completion(&exit.completion);
11297 mutex_lock(&ctx->uring_lock);
11299 mutex_unlock(&ctx->uring_lock);
11300 spin_lock(&ctx->completion_lock);
11301 spin_unlock(&ctx->completion_lock);
11303 io_ring_ctx_free(ctx);
11306 /* Returns true if we found and killed one or more timeouts */
11307 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
11308 struct task_struct *tsk, bool cancel_all)
11310 struct io_kiocb *req, *tmp;
11313 spin_lock(&ctx->completion_lock);
11314 spin_lock_irq(&ctx->timeout_lock);
11315 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11316 if (io_match_task(req, tsk, cancel_all)) {
11317 io_kill_timeout(req, -ECANCELED);
11321 spin_unlock_irq(&ctx->timeout_lock);
11322 io_commit_cqring(ctx);
11323 spin_unlock(&ctx->completion_lock);
11325 io_cqring_ev_posted(ctx);
11326 return canceled != 0;
11329 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11331 unsigned long index;
11332 struct creds *creds;
11334 mutex_lock(&ctx->uring_lock);
11335 percpu_ref_kill(&ctx->refs);
11337 __io_cqring_overflow_flush(ctx, true);
11338 xa_for_each(&ctx->personalities, index, creds)
11339 io_unregister_personality(ctx, index);
11340 mutex_unlock(&ctx->uring_lock);
11342 /* failed during ring init, it couldn't have issued any requests */
11344 io_kill_timeouts(ctx, NULL, true);
11345 io_poll_remove_all(ctx, NULL, true);
11346 /* if we failed setting up the ctx, we might not have any rings */
11347 io_iopoll_try_reap_events(ctx);
11350 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11352 * Use system_unbound_wq to avoid spawning tons of event kworkers
11353 * if we're exiting a ton of rings at the same time. It just adds
11354 * noise and overhead, there's no discernable change in runtime
11355 * over using system_wq.
11357 queue_work(system_unbound_wq, &ctx->exit_work);
11360 static int io_uring_release(struct inode *inode, struct file *file)
11362 struct io_ring_ctx *ctx = file->private_data;
11364 file->private_data = NULL;
11365 io_ring_ctx_wait_and_kill(ctx);
11369 struct io_task_cancel {
11370 struct task_struct *task;
11374 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11376 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11377 struct io_task_cancel *cancel = data;
11379 return io_match_task_safe(req, cancel->task, cancel->all);
11382 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11383 struct task_struct *task,
11386 struct io_defer_entry *de;
11389 spin_lock(&ctx->completion_lock);
11390 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11391 if (io_match_task_safe(de->req, task, cancel_all)) {
11392 list_cut_position(&list, &ctx->defer_list, &de->list);
11396 spin_unlock(&ctx->completion_lock);
11397 if (list_empty(&list))
11400 while (!list_empty(&list)) {
11401 de = list_first_entry(&list, struct io_defer_entry, list);
11402 list_del_init(&de->list);
11403 io_req_complete_failed(de->req, -ECANCELED);
11409 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11411 struct io_tctx_node *node;
11412 enum io_wq_cancel cret;
11415 mutex_lock(&ctx->uring_lock);
11416 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11417 struct io_uring_task *tctx = node->task->io_uring;
11420 * io_wq will stay alive while we hold uring_lock, because it's
11421 * killed after ctx nodes, which requires to take the lock.
11423 if (!tctx || !tctx->io_wq)
11425 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11426 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11428 mutex_unlock(&ctx->uring_lock);
11433 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11434 struct task_struct *task,
11437 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11438 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11440 /* failed during ring init, it couldn't have issued any requests */
11445 enum io_wq_cancel cret;
11449 ret |= io_uring_try_cancel_iowq(ctx);
11450 } else if (tctx && tctx->io_wq) {
11452 * Cancels requests of all rings, not only @ctx, but
11453 * it's fine as the task is in exit/exec.
11455 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11457 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11460 /* SQPOLL thread does its own polling */
11461 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11462 (ctx->sq_data && ctx->sq_data->thread == current)) {
11463 while (!wq_list_empty(&ctx->iopoll_list)) {
11464 io_iopoll_try_reap_events(ctx);
11469 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11470 ret |= io_poll_remove_all(ctx, task, cancel_all);
11471 ret |= io_kill_timeouts(ctx, task, cancel_all);
11473 ret |= io_run_task_work();
11480 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11482 struct io_uring_task *tctx = current->io_uring;
11483 struct io_tctx_node *node;
11486 if (unlikely(!tctx)) {
11487 ret = io_uring_alloc_task_context(current, ctx);
11491 tctx = current->io_uring;
11492 if (ctx->iowq_limits_set) {
11493 unsigned int limits[2] = { ctx->iowq_limits[0],
11494 ctx->iowq_limits[1], };
11496 ret = io_wq_max_workers(tctx->io_wq, limits);
11501 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11502 node = kmalloc(sizeof(*node), GFP_KERNEL);
11506 node->task = current;
11508 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11509 node, GFP_KERNEL));
11515 mutex_lock(&ctx->uring_lock);
11516 list_add(&node->ctx_node, &ctx->tctx_list);
11517 mutex_unlock(&ctx->uring_lock);
11524 * Note that this task has used io_uring. We use it for cancelation purposes.
11526 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11528 struct io_uring_task *tctx = current->io_uring;
11530 if (likely(tctx && tctx->last == ctx))
11532 return __io_uring_add_tctx_node(ctx);
11536 * Remove this io_uring_file -> task mapping.
11538 static __cold void io_uring_del_tctx_node(unsigned long index)
11540 struct io_uring_task *tctx = current->io_uring;
11541 struct io_tctx_node *node;
11545 node = xa_erase(&tctx->xa, index);
11549 WARN_ON_ONCE(current != node->task);
11550 WARN_ON_ONCE(list_empty(&node->ctx_node));
11552 mutex_lock(&node->ctx->uring_lock);
11553 list_del(&node->ctx_node);
11554 mutex_unlock(&node->ctx->uring_lock);
11556 if (tctx->last == node->ctx)
11561 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11563 struct io_wq *wq = tctx->io_wq;
11564 struct io_tctx_node *node;
11565 unsigned long index;
11567 xa_for_each(&tctx->xa, index, node) {
11568 io_uring_del_tctx_node(index);
11573 * Must be after io_uring_del_tctx_node() (removes nodes under
11574 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11576 io_wq_put_and_exit(wq);
11577 tctx->io_wq = NULL;
11581 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11585 return percpu_counter_sum(&tctx->inflight);
11589 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11590 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11592 static __cold void io_uring_cancel_generic(bool cancel_all,
11593 struct io_sq_data *sqd)
11595 struct io_uring_task *tctx = current->io_uring;
11596 struct io_ring_ctx *ctx;
11600 WARN_ON_ONCE(sqd && sqd->thread != current);
11602 if (!current->io_uring)
11605 io_wq_exit_start(tctx->io_wq);
11607 atomic_inc(&tctx->in_idle);
11609 io_uring_drop_tctx_refs(current);
11610 /* read completions before cancelations */
11611 inflight = tctx_inflight(tctx, !cancel_all);
11616 struct io_tctx_node *node;
11617 unsigned long index;
11619 xa_for_each(&tctx->xa, index, node) {
11620 /* sqpoll task will cancel all its requests */
11621 if (node->ctx->sq_data)
11623 io_uring_try_cancel_requests(node->ctx, current,
11627 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11628 io_uring_try_cancel_requests(ctx, current,
11632 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11633 io_run_task_work();
11634 io_uring_drop_tctx_refs(current);
11637 * If we've seen completions, retry without waiting. This
11638 * avoids a race where a completion comes in before we did
11639 * prepare_to_wait().
11641 if (inflight == tctx_inflight(tctx, !cancel_all))
11643 finish_wait(&tctx->wait, &wait);
11646 io_uring_clean_tctx(tctx);
11649 * We shouldn't run task_works after cancel, so just leave
11650 * ->in_idle set for normal exit.
11652 atomic_dec(&tctx->in_idle);
11653 /* for exec all current's requests should be gone, kill tctx */
11654 __io_uring_free(current);
11658 void __io_uring_cancel(bool cancel_all)
11660 io_uring_cancel_generic(cancel_all, NULL);
11663 void io_uring_unreg_ringfd(void)
11665 struct io_uring_task *tctx = current->io_uring;
11668 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11669 if (tctx->registered_rings[i]) {
11670 fput(tctx->registered_rings[i]);
11671 tctx->registered_rings[i] = NULL;
11676 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11677 int start, int end)
11682 for (offset = start; offset < end; offset++) {
11683 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11684 if (tctx->registered_rings[offset])
11690 } else if (file->f_op != &io_uring_fops) {
11692 return -EOPNOTSUPP;
11694 tctx->registered_rings[offset] = file;
11702 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11703 * invocation. User passes in an array of struct io_uring_rsrc_update
11704 * with ->data set to the ring_fd, and ->offset given for the desired
11705 * index. If no index is desired, application may set ->offset == -1U
11706 * and we'll find an available index. Returns number of entries
11707 * successfully processed, or < 0 on error if none were processed.
11709 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11712 struct io_uring_rsrc_update __user *arg = __arg;
11713 struct io_uring_rsrc_update reg;
11714 struct io_uring_task *tctx;
11717 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11720 mutex_unlock(&ctx->uring_lock);
11721 ret = io_uring_add_tctx_node(ctx);
11722 mutex_lock(&ctx->uring_lock);
11726 tctx = current->io_uring;
11727 for (i = 0; i < nr_args; i++) {
11730 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11740 if (reg.offset == -1U) {
11742 end = IO_RINGFD_REG_MAX;
11744 if (reg.offset >= IO_RINGFD_REG_MAX) {
11748 start = reg.offset;
11752 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11757 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11758 fput(tctx->registered_rings[reg.offset]);
11759 tctx->registered_rings[reg.offset] = NULL;
11765 return i ? i : ret;
11768 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11771 struct io_uring_rsrc_update __user *arg = __arg;
11772 struct io_uring_task *tctx = current->io_uring;
11773 struct io_uring_rsrc_update reg;
11776 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11781 for (i = 0; i < nr_args; i++) {
11782 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11786 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11791 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11792 if (tctx->registered_rings[reg.offset]) {
11793 fput(tctx->registered_rings[reg.offset]);
11794 tctx->registered_rings[reg.offset] = NULL;
11798 return i ? i : ret;
11801 static void *io_uring_validate_mmap_request(struct file *file,
11802 loff_t pgoff, size_t sz)
11804 struct io_ring_ctx *ctx = file->private_data;
11805 loff_t offset = pgoff << PAGE_SHIFT;
11810 case IORING_OFF_SQ_RING:
11811 case IORING_OFF_CQ_RING:
11814 case IORING_OFF_SQES:
11815 ptr = ctx->sq_sqes;
11818 return ERR_PTR(-EINVAL);
11821 page = virt_to_head_page(ptr);
11822 if (sz > page_size(page))
11823 return ERR_PTR(-EINVAL);
11830 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11832 size_t sz = vma->vm_end - vma->vm_start;
11836 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11838 return PTR_ERR(ptr);
11840 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11841 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11844 #else /* !CONFIG_MMU */
11846 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11848 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11851 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11853 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11856 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11857 unsigned long addr, unsigned long len,
11858 unsigned long pgoff, unsigned long flags)
11862 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11864 return PTR_ERR(ptr);
11866 return (unsigned long) ptr;
11869 #endif /* !CONFIG_MMU */
11871 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11876 if (!io_sqring_full(ctx))
11878 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11880 if (!io_sqring_full(ctx))
11883 } while (!signal_pending(current));
11885 finish_wait(&ctx->sqo_sq_wait, &wait);
11889 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11891 if (flags & IORING_ENTER_EXT_ARG) {
11892 struct io_uring_getevents_arg arg;
11894 if (argsz != sizeof(arg))
11896 if (copy_from_user(&arg, argp, sizeof(arg)))
11902 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11903 struct __kernel_timespec __user **ts,
11904 const sigset_t __user **sig)
11906 struct io_uring_getevents_arg arg;
11909 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11910 * is just a pointer to the sigset_t.
11912 if (!(flags & IORING_ENTER_EXT_ARG)) {
11913 *sig = (const sigset_t __user *) argp;
11919 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11920 * timespec and sigset_t pointers if good.
11922 if (*argsz != sizeof(arg))
11924 if (copy_from_user(&arg, argp, sizeof(arg)))
11928 *sig = u64_to_user_ptr(arg.sigmask);
11929 *argsz = arg.sigmask_sz;
11930 *ts = u64_to_user_ptr(arg.ts);
11934 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11935 u32, min_complete, u32, flags, const void __user *, argp,
11938 struct io_ring_ctx *ctx;
11942 io_run_task_work();
11944 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11945 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11946 IORING_ENTER_REGISTERED_RING)))
11950 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11951 * need only dereference our task private array to find it.
11953 if (flags & IORING_ENTER_REGISTERED_RING) {
11954 struct io_uring_task *tctx = current->io_uring;
11956 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11958 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11959 f.file = tctx->registered_rings[fd];
11960 if (unlikely(!f.file))
11964 if (unlikely(!f.file))
11969 if (unlikely(f.file->f_op != &io_uring_fops))
11973 ctx = f.file->private_data;
11974 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11978 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11982 * For SQ polling, the thread will do all submissions and completions.
11983 * Just return the requested submit count, and wake the thread if
11984 * we were asked to.
11987 if (ctx->flags & IORING_SETUP_SQPOLL) {
11988 io_cqring_overflow_flush(ctx);
11990 if (unlikely(ctx->sq_data->thread == NULL)) {
11994 if (flags & IORING_ENTER_SQ_WAKEUP)
11995 wake_up(&ctx->sq_data->wait);
11996 if (flags & IORING_ENTER_SQ_WAIT) {
11997 ret = io_sqpoll_wait_sq(ctx);
12002 } else if (to_submit) {
12003 ret = io_uring_add_tctx_node(ctx);
12007 mutex_lock(&ctx->uring_lock);
12008 ret = io_submit_sqes(ctx, to_submit);
12009 if (ret != to_submit) {
12010 mutex_unlock(&ctx->uring_lock);
12013 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
12014 goto iopoll_locked;
12015 mutex_unlock(&ctx->uring_lock);
12017 if (flags & IORING_ENTER_GETEVENTS) {
12019 if (ctx->syscall_iopoll) {
12021 * We disallow the app entering submit/complete with
12022 * polling, but we still need to lock the ring to
12023 * prevent racing with polled issue that got punted to
12026 mutex_lock(&ctx->uring_lock);
12028 ret2 = io_validate_ext_arg(flags, argp, argsz);
12029 if (likely(!ret2)) {
12030 min_complete = min(min_complete,
12032 ret2 = io_iopoll_check(ctx, min_complete);
12034 mutex_unlock(&ctx->uring_lock);
12036 const sigset_t __user *sig;
12037 struct __kernel_timespec __user *ts;
12039 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
12040 if (likely(!ret2)) {
12041 min_complete = min(min_complete,
12043 ret2 = io_cqring_wait(ctx, min_complete, sig,
12052 * EBADR indicates that one or more CQE were dropped.
12053 * Once the user has been informed we can clear the bit
12054 * as they are obviously ok with those drops.
12056 if (unlikely(ret2 == -EBADR))
12057 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
12063 percpu_ref_put(&ctx->refs);
12065 if (!(flags & IORING_ENTER_REGISTERED_RING))
12070 #ifdef CONFIG_PROC_FS
12071 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
12072 const struct cred *cred)
12074 struct user_namespace *uns = seq_user_ns(m);
12075 struct group_info *gi;
12080 seq_printf(m, "%5d\n", id);
12081 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
12082 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
12083 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
12084 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
12085 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
12086 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
12087 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
12088 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
12089 seq_puts(m, "\n\tGroups:\t");
12090 gi = cred->group_info;
12091 for (g = 0; g < gi->ngroups; g++) {
12092 seq_put_decimal_ull(m, g ? " " : "",
12093 from_kgid_munged(uns, gi->gid[g]));
12095 seq_puts(m, "\n\tCapEff:\t");
12096 cap = cred->cap_effective;
12097 CAP_FOR_EACH_U32(__capi)
12098 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
12103 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
12104 struct seq_file *m)
12106 struct io_sq_data *sq = NULL;
12107 struct io_overflow_cqe *ocqe;
12108 struct io_rings *r = ctx->rings;
12109 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
12110 unsigned int sq_head = READ_ONCE(r->sq.head);
12111 unsigned int sq_tail = READ_ONCE(r->sq.tail);
12112 unsigned int cq_head = READ_ONCE(r->cq.head);
12113 unsigned int cq_tail = READ_ONCE(r->cq.tail);
12114 unsigned int cq_shift = 0;
12115 unsigned int sq_entries, cq_entries;
12117 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
12124 * we may get imprecise sqe and cqe info if uring is actively running
12125 * since we get cached_sq_head and cached_cq_tail without uring_lock
12126 * and sq_tail and cq_head are changed by userspace. But it's ok since
12127 * we usually use these info when it is stuck.
12129 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
12130 seq_printf(m, "SqHead:\t%u\n", sq_head);
12131 seq_printf(m, "SqTail:\t%u\n", sq_tail);
12132 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
12133 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
12134 seq_printf(m, "CqHead:\t%u\n", cq_head);
12135 seq_printf(m, "CqTail:\t%u\n", cq_tail);
12136 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
12137 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
12138 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
12139 for (i = 0; i < sq_entries; i++) {
12140 unsigned int entry = i + sq_head;
12141 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
12142 struct io_uring_sqe *sqe;
12144 if (sq_idx > sq_mask)
12146 sqe = &ctx->sq_sqes[sq_idx];
12147 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
12148 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
12151 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
12152 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
12153 for (i = 0; i < cq_entries; i++) {
12154 unsigned int entry = i + cq_head;
12155 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
12158 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
12159 entry & cq_mask, cqe->user_data, cqe->res,
12162 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
12163 "extra1:%llu, extra2:%llu\n",
12164 entry & cq_mask, cqe->user_data, cqe->res,
12165 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
12170 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
12171 * since fdinfo case grabs it in the opposite direction of normal use
12172 * cases. If we fail to get the lock, we just don't iterate any
12173 * structures that could be going away outside the io_uring mutex.
12175 has_lock = mutex_trylock(&ctx->uring_lock);
12177 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
12183 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
12184 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
12185 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
12186 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
12187 struct file *f = io_file_from_index(ctx, i);
12190 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
12192 seq_printf(m, "%5u: <none>\n", i);
12194 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
12195 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
12196 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
12197 unsigned int len = buf->ubuf_end - buf->ubuf;
12199 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
12201 if (has_lock && !xa_empty(&ctx->personalities)) {
12202 unsigned long index;
12203 const struct cred *cred;
12205 seq_printf(m, "Personalities:\n");
12206 xa_for_each(&ctx->personalities, index, cred)
12207 io_uring_show_cred(m, index, cred);
12210 mutex_unlock(&ctx->uring_lock);
12212 seq_puts(m, "PollList:\n");
12213 spin_lock(&ctx->completion_lock);
12214 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
12215 struct hlist_head *list = &ctx->cancel_hash[i];
12216 struct io_kiocb *req;
12218 hlist_for_each_entry(req, list, hash_node)
12219 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
12220 task_work_pending(req->task));
12223 seq_puts(m, "CqOverflowList:\n");
12224 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
12225 struct io_uring_cqe *cqe = &ocqe->cqe;
12227 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
12228 cqe->user_data, cqe->res, cqe->flags);
12232 spin_unlock(&ctx->completion_lock);
12235 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
12237 struct io_ring_ctx *ctx = f->private_data;
12239 if (percpu_ref_tryget(&ctx->refs)) {
12240 __io_uring_show_fdinfo(ctx, m);
12241 percpu_ref_put(&ctx->refs);
12246 static const struct file_operations io_uring_fops = {
12247 .release = io_uring_release,
12248 .mmap = io_uring_mmap,
12250 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
12251 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
12253 .poll = io_uring_poll,
12254 #ifdef CONFIG_PROC_FS
12255 .show_fdinfo = io_uring_show_fdinfo,
12259 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
12260 struct io_uring_params *p)
12262 struct io_rings *rings;
12263 size_t size, sq_array_offset;
12265 /* make sure these are sane, as we already accounted them */
12266 ctx->sq_entries = p->sq_entries;
12267 ctx->cq_entries = p->cq_entries;
12269 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
12270 if (size == SIZE_MAX)
12273 rings = io_mem_alloc(size);
12277 ctx->rings = rings;
12278 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
12279 rings->sq_ring_mask = p->sq_entries - 1;
12280 rings->cq_ring_mask = p->cq_entries - 1;
12281 rings->sq_ring_entries = p->sq_entries;
12282 rings->cq_ring_entries = p->cq_entries;
12284 if (p->flags & IORING_SETUP_SQE128)
12285 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
12287 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
12288 if (size == SIZE_MAX) {
12289 io_mem_free(ctx->rings);
12294 ctx->sq_sqes = io_mem_alloc(size);
12295 if (!ctx->sq_sqes) {
12296 io_mem_free(ctx->rings);
12304 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
12308 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
12312 ret = io_uring_add_tctx_node(ctx);
12317 fd_install(fd, file);
12322 * Allocate an anonymous fd, this is what constitutes the application
12323 * visible backing of an io_uring instance. The application mmaps this
12324 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12325 * we have to tie this fd to a socket for file garbage collection purposes.
12327 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12330 #if defined(CONFIG_UNIX)
12333 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12336 return ERR_PTR(ret);
12339 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12340 O_RDWR | O_CLOEXEC, NULL);
12341 #if defined(CONFIG_UNIX)
12342 if (IS_ERR(file)) {
12343 sock_release(ctx->ring_sock);
12344 ctx->ring_sock = NULL;
12346 ctx->ring_sock->file = file;
12352 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12353 struct io_uring_params __user *params)
12355 struct io_ring_ctx *ctx;
12361 if (entries > IORING_MAX_ENTRIES) {
12362 if (!(p->flags & IORING_SETUP_CLAMP))
12364 entries = IORING_MAX_ENTRIES;
12368 * Use twice as many entries for the CQ ring. It's possible for the
12369 * application to drive a higher depth than the size of the SQ ring,
12370 * since the sqes are only used at submission time. This allows for
12371 * some flexibility in overcommitting a bit. If the application has
12372 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12373 * of CQ ring entries manually.
12375 p->sq_entries = roundup_pow_of_two(entries);
12376 if (p->flags & IORING_SETUP_CQSIZE) {
12378 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12379 * to a power-of-two, if it isn't already. We do NOT impose
12380 * any cq vs sq ring sizing.
12382 if (!p->cq_entries)
12384 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12385 if (!(p->flags & IORING_SETUP_CLAMP))
12387 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12389 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12390 if (p->cq_entries < p->sq_entries)
12393 p->cq_entries = 2 * p->sq_entries;
12396 ctx = io_ring_ctx_alloc(p);
12401 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12402 * space applications don't need to do io completion events
12403 * polling again, they can rely on io_sq_thread to do polling
12404 * work, which can reduce cpu usage and uring_lock contention.
12406 if (ctx->flags & IORING_SETUP_IOPOLL &&
12407 !(ctx->flags & IORING_SETUP_SQPOLL))
12408 ctx->syscall_iopoll = 1;
12410 ctx->compat = in_compat_syscall();
12411 if (!capable(CAP_IPC_LOCK))
12412 ctx->user = get_uid(current_user());
12415 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12416 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12419 if (ctx->flags & IORING_SETUP_SQPOLL) {
12420 /* IPI related flags don't make sense with SQPOLL */
12421 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12422 IORING_SETUP_TASKRUN_FLAG))
12424 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12425 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12426 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12428 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12430 ctx->notify_method = TWA_SIGNAL;
12434 * This is just grabbed for accounting purposes. When a process exits,
12435 * the mm is exited and dropped before the files, hence we need to hang
12436 * on to this mm purely for the purposes of being able to unaccount
12437 * memory (locked/pinned vm). It's not used for anything else.
12439 mmgrab(current->mm);
12440 ctx->mm_account = current->mm;
12442 ret = io_allocate_scq_urings(ctx, p);
12446 ret = io_sq_offload_create(ctx, p);
12449 /* always set a rsrc node */
12450 ret = io_rsrc_node_switch_start(ctx);
12453 io_rsrc_node_switch(ctx, NULL);
12455 memset(&p->sq_off, 0, sizeof(p->sq_off));
12456 p->sq_off.head = offsetof(struct io_rings, sq.head);
12457 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12458 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12459 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12460 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12461 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12462 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12464 memset(&p->cq_off, 0, sizeof(p->cq_off));
12465 p->cq_off.head = offsetof(struct io_rings, cq.head);
12466 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12467 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12468 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12469 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12470 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12471 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12473 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12474 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12475 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12476 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12477 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12478 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12479 IORING_FEAT_LINKED_FILE;
12481 if (copy_to_user(params, p, sizeof(*p))) {
12486 file = io_uring_get_file(ctx);
12487 if (IS_ERR(file)) {
12488 ret = PTR_ERR(file);
12493 * Install ring fd as the very last thing, so we don't risk someone
12494 * having closed it before we finish setup
12496 ret = io_uring_install_fd(ctx, file);
12498 /* fput will clean it up */
12503 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12506 io_ring_ctx_wait_and_kill(ctx);
12511 * Sets up an aio uring context, and returns the fd. Applications asks for a
12512 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12513 * params structure passed in.
12515 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12517 struct io_uring_params p;
12520 if (copy_from_user(&p, params, sizeof(p)))
12522 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12527 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12528 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12529 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12530 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12531 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12532 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12535 return io_uring_create(entries, &p, params);
12538 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12539 struct io_uring_params __user *, params)
12541 return io_uring_setup(entries, params);
12544 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12547 struct io_uring_probe *p;
12551 size = struct_size(p, ops, nr_args);
12552 if (size == SIZE_MAX)
12554 p = kzalloc(size, GFP_KERNEL);
12559 if (copy_from_user(p, arg, size))
12562 if (memchr_inv(p, 0, size))
12565 p->last_op = IORING_OP_LAST - 1;
12566 if (nr_args > IORING_OP_LAST)
12567 nr_args = IORING_OP_LAST;
12569 for (i = 0; i < nr_args; i++) {
12571 if (!io_op_defs[i].not_supported)
12572 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12577 if (copy_to_user(arg, p, size))
12584 static int io_register_personality(struct io_ring_ctx *ctx)
12586 const struct cred *creds;
12590 creds = get_current_cred();
12592 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12593 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12601 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12602 void __user *arg, unsigned int nr_args)
12604 struct io_uring_restriction *res;
12608 /* Restrictions allowed only if rings started disabled */
12609 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12612 /* We allow only a single restrictions registration */
12613 if (ctx->restrictions.registered)
12616 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12619 size = array_size(nr_args, sizeof(*res));
12620 if (size == SIZE_MAX)
12623 res = memdup_user(arg, size);
12625 return PTR_ERR(res);
12629 for (i = 0; i < nr_args; i++) {
12630 switch (res[i].opcode) {
12631 case IORING_RESTRICTION_REGISTER_OP:
12632 if (res[i].register_op >= IORING_REGISTER_LAST) {
12637 __set_bit(res[i].register_op,
12638 ctx->restrictions.register_op);
12640 case IORING_RESTRICTION_SQE_OP:
12641 if (res[i].sqe_op >= IORING_OP_LAST) {
12646 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12648 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12649 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12651 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12652 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12661 /* Reset all restrictions if an error happened */
12663 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12665 ctx->restrictions.registered = true;
12671 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12673 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12676 if (ctx->restrictions.registered)
12677 ctx->restricted = 1;
12679 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12680 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12681 wake_up(&ctx->sq_data->wait);
12685 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12686 struct io_uring_rsrc_update2 *up,
12692 if (check_add_overflow(up->offset, nr_args, &tmp))
12694 err = io_rsrc_node_switch_start(ctx);
12699 case IORING_RSRC_FILE:
12700 return __io_sqe_files_update(ctx, up, nr_args);
12701 case IORING_RSRC_BUFFER:
12702 return __io_sqe_buffers_update(ctx, up, nr_args);
12707 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12710 struct io_uring_rsrc_update2 up;
12714 memset(&up, 0, sizeof(up));
12715 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12717 if (up.resv || up.resv2)
12719 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12722 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12723 unsigned size, unsigned type)
12725 struct io_uring_rsrc_update2 up;
12727 if (size != sizeof(up))
12729 if (copy_from_user(&up, arg, sizeof(up)))
12731 if (!up.nr || up.resv || up.resv2)
12733 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12736 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12737 unsigned int size, unsigned int type)
12739 struct io_uring_rsrc_register rr;
12741 /* keep it extendible */
12742 if (size != sizeof(rr))
12745 memset(&rr, 0, sizeof(rr));
12746 if (copy_from_user(&rr, arg, size))
12748 if (!rr.nr || rr.resv2)
12750 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12754 case IORING_RSRC_FILE:
12755 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12757 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12758 rr.nr, u64_to_user_ptr(rr.tags));
12759 case IORING_RSRC_BUFFER:
12760 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12762 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12763 rr.nr, u64_to_user_ptr(rr.tags));
12768 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12769 void __user *arg, unsigned len)
12771 struct io_uring_task *tctx = current->io_uring;
12772 cpumask_var_t new_mask;
12775 if (!tctx || !tctx->io_wq)
12778 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12781 cpumask_clear(new_mask);
12782 if (len > cpumask_size())
12783 len = cpumask_size();
12785 if (in_compat_syscall()) {
12786 ret = compat_get_bitmap(cpumask_bits(new_mask),
12787 (const compat_ulong_t __user *)arg,
12788 len * 8 /* CHAR_BIT */);
12790 ret = copy_from_user(new_mask, arg, len);
12794 free_cpumask_var(new_mask);
12798 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12799 free_cpumask_var(new_mask);
12803 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12805 struct io_uring_task *tctx = current->io_uring;
12807 if (!tctx || !tctx->io_wq)
12810 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12813 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12815 __must_hold(&ctx->uring_lock)
12817 struct io_tctx_node *node;
12818 struct io_uring_task *tctx = NULL;
12819 struct io_sq_data *sqd = NULL;
12820 __u32 new_count[2];
12823 if (copy_from_user(new_count, arg, sizeof(new_count)))
12825 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12826 if (new_count[i] > INT_MAX)
12829 if (ctx->flags & IORING_SETUP_SQPOLL) {
12830 sqd = ctx->sq_data;
12833 * Observe the correct sqd->lock -> ctx->uring_lock
12834 * ordering. Fine to drop uring_lock here, we hold
12835 * a ref to the ctx.
12837 refcount_inc(&sqd->refs);
12838 mutex_unlock(&ctx->uring_lock);
12839 mutex_lock(&sqd->lock);
12840 mutex_lock(&ctx->uring_lock);
12842 tctx = sqd->thread->io_uring;
12845 tctx = current->io_uring;
12848 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12850 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12852 ctx->iowq_limits[i] = new_count[i];
12853 ctx->iowq_limits_set = true;
12855 if (tctx && tctx->io_wq) {
12856 ret = io_wq_max_workers(tctx->io_wq, new_count);
12860 memset(new_count, 0, sizeof(new_count));
12864 mutex_unlock(&sqd->lock);
12865 io_put_sq_data(sqd);
12868 if (copy_to_user(arg, new_count, sizeof(new_count)))
12871 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12875 /* now propagate the restriction to all registered users */
12876 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12877 struct io_uring_task *tctx = node->task->io_uring;
12879 if (WARN_ON_ONCE(!tctx->io_wq))
12882 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12883 new_count[i] = ctx->iowq_limits[i];
12884 /* ignore errors, it always returns zero anyway */
12885 (void)io_wq_max_workers(tctx->io_wq, new_count);
12890 mutex_unlock(&sqd->lock);
12891 io_put_sq_data(sqd);
12896 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12898 struct io_uring_buf_ring *br;
12899 struct io_uring_buf_reg reg;
12900 struct io_buffer_list *bl;
12901 struct page **pages;
12904 if (copy_from_user(®, arg, sizeof(reg)))
12907 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12909 if (!reg.ring_addr)
12911 if (reg.ring_addr & ~PAGE_MASK)
12913 if (!is_power_of_2(reg.ring_entries))
12916 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12917 int ret = io_init_bl_list(ctx);
12922 bl = io_buffer_get_list(ctx, reg.bgid);
12924 /* if mapped buffer ring OR classic exists, don't allow */
12925 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12928 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12933 pages = io_pin_pages(reg.ring_addr,
12934 struct_size(br, bufs, reg.ring_entries),
12936 if (IS_ERR(pages)) {
12938 return PTR_ERR(pages);
12941 br = page_address(pages[0]);
12942 bl->buf_pages = pages;
12943 bl->buf_nr_pages = nr_pages;
12944 bl->nr_entries = reg.ring_entries;
12946 bl->mask = reg.ring_entries - 1;
12947 io_buffer_add_list(ctx, bl, reg.bgid);
12951 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12953 struct io_uring_buf_reg reg;
12954 struct io_buffer_list *bl;
12956 if (copy_from_user(®, arg, sizeof(reg)))
12958 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12961 bl = io_buffer_get_list(ctx, reg.bgid);
12964 if (!bl->buf_nr_pages)
12967 __io_remove_buffers(ctx, bl, -1U);
12968 if (bl->bgid >= BGID_ARRAY) {
12969 xa_erase(&ctx->io_bl_xa, bl->bgid);
12975 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12976 void __user *arg, unsigned nr_args)
12977 __releases(ctx->uring_lock)
12978 __acquires(ctx->uring_lock)
12983 * We're inside the ring mutex, if the ref is already dying, then
12984 * someone else killed the ctx or is already going through
12985 * io_uring_register().
12987 if (percpu_ref_is_dying(&ctx->refs))
12990 if (ctx->restricted) {
12991 if (opcode >= IORING_REGISTER_LAST)
12993 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12994 if (!test_bit(opcode, ctx->restrictions.register_op))
12999 case IORING_REGISTER_BUFFERS:
13003 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
13005 case IORING_UNREGISTER_BUFFERS:
13007 if (arg || nr_args)
13009 ret = io_sqe_buffers_unregister(ctx);
13011 case IORING_REGISTER_FILES:
13015 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
13017 case IORING_UNREGISTER_FILES:
13019 if (arg || nr_args)
13021 ret = io_sqe_files_unregister(ctx);
13023 case IORING_REGISTER_FILES_UPDATE:
13024 ret = io_register_files_update(ctx, arg, nr_args);
13026 case IORING_REGISTER_EVENTFD:
13030 ret = io_eventfd_register(ctx, arg, 0);
13032 case IORING_REGISTER_EVENTFD_ASYNC:
13036 ret = io_eventfd_register(ctx, arg, 1);
13038 case IORING_UNREGISTER_EVENTFD:
13040 if (arg || nr_args)
13042 ret = io_eventfd_unregister(ctx);
13044 case IORING_REGISTER_PROBE:
13046 if (!arg || nr_args > 256)
13048 ret = io_probe(ctx, arg, nr_args);
13050 case IORING_REGISTER_PERSONALITY:
13052 if (arg || nr_args)
13054 ret = io_register_personality(ctx);
13056 case IORING_UNREGISTER_PERSONALITY:
13060 ret = io_unregister_personality(ctx, nr_args);
13062 case IORING_REGISTER_ENABLE_RINGS:
13064 if (arg || nr_args)
13066 ret = io_register_enable_rings(ctx);
13068 case IORING_REGISTER_RESTRICTIONS:
13069 ret = io_register_restrictions(ctx, arg, nr_args);
13071 case IORING_REGISTER_FILES2:
13072 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
13074 case IORING_REGISTER_FILES_UPDATE2:
13075 ret = io_register_rsrc_update(ctx, arg, nr_args,
13078 case IORING_REGISTER_BUFFERS2:
13079 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
13081 case IORING_REGISTER_BUFFERS_UPDATE:
13082 ret = io_register_rsrc_update(ctx, arg, nr_args,
13083 IORING_RSRC_BUFFER);
13085 case IORING_REGISTER_IOWQ_AFF:
13087 if (!arg || !nr_args)
13089 ret = io_register_iowq_aff(ctx, arg, nr_args);
13091 case IORING_UNREGISTER_IOWQ_AFF:
13093 if (arg || nr_args)
13095 ret = io_unregister_iowq_aff(ctx);
13097 case IORING_REGISTER_IOWQ_MAX_WORKERS:
13099 if (!arg || nr_args != 2)
13101 ret = io_register_iowq_max_workers(ctx, arg);
13103 case IORING_REGISTER_RING_FDS:
13104 ret = io_ringfd_register(ctx, arg, nr_args);
13106 case IORING_UNREGISTER_RING_FDS:
13107 ret = io_ringfd_unregister(ctx, arg, nr_args);
13109 case IORING_REGISTER_PBUF_RING:
13111 if (!arg || nr_args != 1)
13113 ret = io_register_pbuf_ring(ctx, arg);
13115 case IORING_UNREGISTER_PBUF_RING:
13117 if (!arg || nr_args != 1)
13119 ret = io_unregister_pbuf_ring(ctx, arg);
13129 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
13130 void __user *, arg, unsigned int, nr_args)
13132 struct io_ring_ctx *ctx;
13141 if (f.file->f_op != &io_uring_fops)
13144 ctx = f.file->private_data;
13146 io_run_task_work();
13148 mutex_lock(&ctx->uring_lock);
13149 ret = __io_uring_register(ctx, opcode, arg, nr_args);
13150 mutex_unlock(&ctx->uring_lock);
13151 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
13157 static int __init io_uring_init(void)
13159 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13160 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13161 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13164 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13165 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13166 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13167 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13168 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13169 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13170 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13171 BUILD_BUG_SQE_ELEM(8, __u64, off);
13172 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13173 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13174 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13175 BUILD_BUG_SQE_ELEM(24, __u32, len);
13176 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13177 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13178 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13179 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13180 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13181 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13182 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13183 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13184 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13185 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13186 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13187 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13188 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13189 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13190 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13191 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13192 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13193 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13194 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13195 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13196 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13197 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13199 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13200 sizeof(struct io_uring_rsrc_update));
13201 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13202 sizeof(struct io_uring_rsrc_update2));
13204 /* ->buf_index is u16 */
13205 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13206 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13207 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13208 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13209 offsetof(struct io_uring_buf_ring, tail));
13211 /* should fit into one byte */
13212 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13213 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13214 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13216 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13217 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13219 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13221 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13223 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13227 __initcall(io_uring_init);