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>
90 #include "../fs/internal.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_INFLIGHT | REQ_F_CREDS | \
118 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
121 #define IO_APOLL_MULTI_POLLED (REQ_F_APOLL_MULTISHOT | REQ_F_POLLED)
123 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
126 u32 head ____cacheline_aligned_in_smp;
127 u32 tail ____cacheline_aligned_in_smp;
131 * This data is shared with the application through the mmap at offsets
132 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
134 * The offsets to the member fields are published through struct
135 * io_sqring_offsets when calling io_uring_setup.
139 * Head and tail offsets into the ring; the offsets need to be
140 * masked to get valid indices.
142 * The kernel controls head of the sq ring and the tail of the cq ring,
143 * and the application controls tail of the sq ring and the head of the
146 struct io_uring sq, cq;
148 * Bitmasks to apply to head and tail offsets (constant, equals
151 u32 sq_ring_mask, cq_ring_mask;
152 /* Ring sizes (constant, power of 2) */
153 u32 sq_ring_entries, cq_ring_entries;
155 * Number of invalid entries dropped by the kernel due to
156 * invalid index stored in array
158 * Written by the kernel, shouldn't be modified by the
159 * application (i.e. get number of "new events" by comparing to
162 * After a new SQ head value was read by the application this
163 * counter includes all submissions that were dropped reaching
164 * the new SQ head (and possibly more).
170 * Written by the kernel, shouldn't be modified by the
173 * The application needs a full memory barrier before checking
174 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
180 * Written by the application, shouldn't be modified by the
185 * Number of completion events lost because the queue was full;
186 * this should be avoided by the application by making sure
187 * there are not more requests pending than there is space in
188 * the completion queue.
190 * Written by the kernel, shouldn't be modified by the
191 * application (i.e. get number of "new events" by comparing to
194 * As completion events come in out of order this counter is not
195 * ordered with any other data.
199 * Ring buffer of completion events.
201 * The kernel writes completion events fresh every time they are
202 * produced, so the application is allowed to modify pending
205 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
208 struct io_mapped_ubuf {
211 unsigned int nr_bvecs;
212 unsigned long acct_pages;
213 struct bio_vec bvec[];
218 struct io_overflow_cqe {
219 struct list_head list;
220 struct io_uring_cqe cqe;
224 * FFS_SCM is only available on 64-bit archs, for 32-bit we just define it as 0
225 * and define IO_URING_SCM_ALL. For this case, we use SCM for all files as we
226 * can't safely always dereference the file when the task has exited and ring
227 * cleanup is done. If a file is tracked and part of SCM, then unix gc on
228 * process exit may reap it before __io_sqe_files_unregister() is run.
230 #define FFS_NOWAIT 0x1UL
231 #define FFS_ISREG 0x2UL
232 #if defined(CONFIG_64BIT)
233 #define FFS_SCM 0x4UL
235 #define IO_URING_SCM_ALL
236 #define FFS_SCM 0x0UL
238 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG|FFS_SCM)
240 struct io_fixed_file {
241 /* file * with additional FFS_* flags */
242 unsigned long file_ptr;
246 struct list_head list;
251 struct io_mapped_ubuf *buf;
255 struct io_file_table {
256 struct io_fixed_file *files;
257 unsigned long *bitmap;
258 unsigned int alloc_hint;
261 struct io_rsrc_node {
262 struct percpu_ref refs;
263 struct list_head node;
264 struct list_head rsrc_list;
265 struct io_rsrc_data *rsrc_data;
266 struct llist_node llist;
270 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
272 struct io_rsrc_data {
273 struct io_ring_ctx *ctx;
279 struct completion done;
283 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
284 struct io_buffer_list {
286 * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
287 * then these are classic provided buffers and ->buf_list is used.
290 struct list_head buf_list;
292 struct page **buf_pages;
293 struct io_uring_buf_ring *buf_ring;
298 /* below is for ring provided buffers */
306 struct list_head list;
313 struct io_restriction {
314 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
315 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
316 u8 sqe_flags_allowed;
317 u8 sqe_flags_required;
322 IO_SQ_THREAD_SHOULD_STOP = 0,
323 IO_SQ_THREAD_SHOULD_PARK,
328 atomic_t park_pending;
331 /* ctx's that are using this sqd */
332 struct list_head ctx_list;
334 struct task_struct *thread;
335 struct wait_queue_head wait;
337 unsigned sq_thread_idle;
343 struct completion exited;
346 #define IO_COMPL_BATCH 32
347 #define IO_REQ_CACHE_SIZE 32
348 #define IO_REQ_ALLOC_BATCH 8
350 struct io_submit_link {
351 struct io_kiocb *head;
352 struct io_kiocb *last;
355 struct io_submit_state {
356 /* inline/task_work completion list, under ->uring_lock */
357 struct io_wq_work_node free_list;
358 /* batch completion logic */
359 struct io_wq_work_list compl_reqs;
360 struct io_submit_link link;
365 unsigned short submit_nr;
366 struct blk_plug plug;
370 struct eventfd_ctx *cq_ev_fd;
371 unsigned int eventfd_async: 1;
375 #define BGID_ARRAY 64
378 /* const or read-mostly hot data */
380 struct percpu_ref refs;
382 struct io_rings *rings;
384 enum task_work_notify_mode notify_method;
385 unsigned int compat: 1;
386 unsigned int drain_next: 1;
387 unsigned int restricted: 1;
388 unsigned int off_timeout_used: 1;
389 unsigned int drain_active: 1;
390 unsigned int drain_disabled: 1;
391 unsigned int has_evfd: 1;
392 unsigned int syscall_iopoll: 1;
393 } ____cacheline_aligned_in_smp;
395 /* submission data */
397 struct mutex uring_lock;
400 * Ring buffer of indices into array of io_uring_sqe, which is
401 * mmapped by the application using the IORING_OFF_SQES offset.
403 * This indirection could e.g. be used to assign fixed
404 * io_uring_sqe entries to operations and only submit them to
405 * the queue when needed.
407 * The kernel modifies neither the indices array nor the entries
411 struct io_uring_sqe *sq_sqes;
412 unsigned cached_sq_head;
414 struct list_head defer_list;
417 * Fixed resources fast path, should be accessed only under
418 * uring_lock, and updated through io_uring_register(2)
420 struct io_rsrc_node *rsrc_node;
421 int rsrc_cached_refs;
423 struct io_file_table file_table;
424 unsigned nr_user_files;
425 unsigned nr_user_bufs;
426 struct io_mapped_ubuf **user_bufs;
428 struct io_submit_state submit_state;
430 struct io_buffer_list *io_bl;
431 struct xarray io_bl_xa;
432 struct list_head io_buffers_cache;
434 struct list_head timeout_list;
435 struct list_head ltimeout_list;
436 struct list_head cq_overflow_list;
437 struct list_head apoll_cache;
438 struct xarray personalities;
440 unsigned sq_thread_idle;
441 } ____cacheline_aligned_in_smp;
443 /* IRQ completion list, under ->completion_lock */
444 struct io_wq_work_list locked_free_list;
445 unsigned int locked_free_nr;
447 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
448 struct io_sq_data *sq_data; /* if using sq thread polling */
450 struct wait_queue_head sqo_sq_wait;
451 struct list_head sqd_list;
453 unsigned long check_cq;
457 * We cache a range of free CQEs we can use, once exhausted it
458 * should go through a slower range setup, see __io_get_cqe()
460 struct io_uring_cqe *cqe_cached;
461 struct io_uring_cqe *cqe_sentinel;
463 unsigned cached_cq_tail;
465 struct io_ev_fd __rcu *io_ev_fd;
466 struct wait_queue_head cq_wait;
468 atomic_t cq_timeouts;
469 unsigned cq_last_tm_flush;
470 } ____cacheline_aligned_in_smp;
473 spinlock_t completion_lock;
475 spinlock_t timeout_lock;
478 * ->iopoll_list is protected by the ctx->uring_lock for
479 * io_uring instances that don't use IORING_SETUP_SQPOLL.
480 * For SQPOLL, only the single threaded io_sq_thread() will
481 * manipulate the list, hence no extra locking is needed there.
483 struct io_wq_work_list iopoll_list;
484 struct hlist_head *cancel_hash;
485 unsigned cancel_hash_bits;
486 bool poll_multi_queue;
488 struct list_head io_buffers_comp;
489 } ____cacheline_aligned_in_smp;
491 struct io_restriction restrictions;
493 /* slow path rsrc auxilary data, used by update/register */
495 struct io_rsrc_node *rsrc_backup_node;
496 struct io_mapped_ubuf *dummy_ubuf;
497 struct io_rsrc_data *file_data;
498 struct io_rsrc_data *buf_data;
500 struct delayed_work rsrc_put_work;
501 struct llist_head rsrc_put_llist;
502 struct list_head rsrc_ref_list;
503 spinlock_t rsrc_ref_lock;
505 struct list_head io_buffers_pages;
508 /* Keep this last, we don't need it for the fast path */
510 #if defined(CONFIG_UNIX)
511 struct socket *ring_sock;
513 /* hashed buffered write serialization */
514 struct io_wq_hash *hash_map;
516 /* Only used for accounting purposes */
517 struct user_struct *user;
518 struct mm_struct *mm_account;
520 /* ctx exit and cancelation */
521 struct llist_head fallback_llist;
522 struct delayed_work fallback_work;
523 struct work_struct exit_work;
524 struct list_head tctx_list;
525 struct completion ref_comp;
527 bool iowq_limits_set;
532 * Arbitrary limit, can be raised if need be
534 #define IO_RINGFD_REG_MAX 16
536 struct io_uring_task {
537 /* submission side */
540 struct wait_queue_head wait;
541 const struct io_ring_ctx *last;
543 struct percpu_counter inflight;
544 atomic_t inflight_tracked;
547 spinlock_t task_lock;
548 struct io_wq_work_list task_list;
549 struct io_wq_work_list prio_task_list;
550 struct callback_head task_work;
551 struct file **registered_rings;
556 * First field must be the file pointer in all the
557 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
561 struct wait_queue_head *head;
563 struct wait_queue_entry wait;
566 struct io_poll_update {
572 bool update_user_data;
581 struct io_timeout_data {
582 struct io_kiocb *req;
583 struct hrtimer timer;
584 struct timespec64 ts;
585 enum hrtimer_mode mode;
591 struct sockaddr __user *addr;
592 int __user *addr_len;
595 unsigned long nofile;
605 unsigned long nofile;
627 struct list_head list;
628 /* head of the link, used by linked timeouts only */
629 struct io_kiocb *head;
630 /* for linked completions */
631 struct io_kiocb *prev;
634 struct io_timeout_rem {
639 struct timespec64 ts;
645 /* NOTE: kiocb has the file as the first member, so don't do it here */
654 struct sockaddr __user *addr;
661 struct compat_msghdr __user *umsg_compat;
662 struct user_msghdr __user *umsg;
675 struct filename *filename;
677 unsigned long nofile;
680 struct io_rsrc_update {
706 struct epoll_event event;
710 struct file *file_out;
718 struct io_provide_buf {
732 struct filename *filename;
733 struct statx __user *buffer;
745 struct filename *oldpath;
746 struct filename *newpath;
754 struct filename *filename;
761 struct filename *filename;
767 struct filename *oldpath;
768 struct filename *newpath;
775 struct filename *oldpath;
776 struct filename *newpath;
786 struct io_async_connect {
787 struct sockaddr_storage address;
790 struct io_async_msghdr {
791 struct iovec fast_iov[UIO_FASTIOV];
792 /* points to an allocated iov, if NULL we use fast_iov instead */
793 struct iovec *free_iov;
794 struct sockaddr __user *uaddr;
796 struct sockaddr_storage addr;
800 struct iov_iter iter;
801 struct iov_iter_state iter_state;
802 struct iovec fast_iov[UIO_FASTIOV];
806 struct io_rw_state s;
807 const struct iovec *free_iovec;
809 struct wait_page_queue wpq;
814 struct xattr_ctx ctx;
815 struct filename *filename;
819 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
820 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
821 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
822 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
823 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
824 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
825 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
827 /* first byte is taken by user flags, shift it to not overlap */
832 REQ_F_LINK_TIMEOUT_BIT,
833 REQ_F_NEED_CLEANUP_BIT,
835 REQ_F_BUFFER_SELECTED_BIT,
836 REQ_F_BUFFER_RING_BIT,
837 REQ_F_COMPLETE_INLINE_BIT,
841 REQ_F_ARM_LTIMEOUT_BIT,
842 REQ_F_ASYNC_DATA_BIT,
843 REQ_F_SKIP_LINK_CQES_BIT,
844 REQ_F_SINGLE_POLL_BIT,
845 REQ_F_DOUBLE_POLL_BIT,
846 REQ_F_PARTIAL_IO_BIT,
847 REQ_F_CQE32_INIT_BIT,
848 REQ_F_APOLL_MULTISHOT_BIT,
849 REQ_F_CLEAR_POLLIN_BIT,
850 /* keep async read/write and isreg together and in order */
851 REQ_F_SUPPORT_NOWAIT_BIT,
854 /* not a real bit, just to check we're not overflowing the space */
860 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
861 /* drain existing IO first */
862 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
864 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
865 /* doesn't sever on completion < 0 */
866 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
868 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
869 /* IOSQE_BUFFER_SELECT */
870 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
871 /* IOSQE_CQE_SKIP_SUCCESS */
872 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
874 /* fail rest of links */
875 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
876 /* on inflight list, should be cancelled and waited on exit reliably */
877 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
878 /* read/write uses file position */
879 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
880 /* must not punt to workers */
881 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
882 /* has or had linked timeout */
883 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
885 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
886 /* already went through poll handler */
887 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
888 /* buffer already selected */
889 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
890 /* buffer selected from ring, needs commit */
891 REQ_F_BUFFER_RING = BIT(REQ_F_BUFFER_RING_BIT),
892 /* completion is deferred through io_comp_state */
893 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
894 /* caller should reissue async */
895 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
896 /* supports async reads/writes */
897 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
899 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
900 /* has creds assigned */
901 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
902 /* skip refcounting if not set */
903 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
904 /* there is a linked timeout that has to be armed */
905 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
906 /* ->async_data allocated */
907 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
908 /* don't post CQEs while failing linked requests */
909 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
910 /* single poll may be active */
911 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
912 /* double poll may active */
913 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
914 /* request has already done partial IO */
915 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
916 /* fast poll multishot mode */
917 REQ_F_APOLL_MULTISHOT = BIT(REQ_F_APOLL_MULTISHOT_BIT),
918 /* ->extra1 and ->extra2 are initialised */
919 REQ_F_CQE32_INIT = BIT(REQ_F_CQE32_INIT_BIT),
920 /* recvmsg special flag, clear EPOLLIN */
921 REQ_F_CLEAR_POLLIN = BIT(REQ_F_CLEAR_POLLIN_BIT),
926 struct io_poll *double_poll;
929 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
931 struct io_task_work {
933 struct io_wq_work_node node;
934 struct llist_node fallback_node;
936 io_req_tw_func_t func;
940 IORING_RSRC_FILE = 0,
941 IORING_RSRC_BUFFER = 1,
947 /* fd initially, then cflags for completion */
955 IO_CHECK_CQ_OVERFLOW_BIT,
956 IO_CHECK_CQ_DROPPED_BIT,
960 * Each request type overlays its private data structure on top of this one.
961 * They must not exceed this one in size.
965 /* each command gets 56 bytes of data */
969 #define io_kiocb_to_cmd(req) ((void *) &(req)->cmd)
970 #define cmd_to_io_kiocb(ptr) ((struct io_kiocb *) ptr)
975 * NOTE! Each of the io_kiocb union members has the file pointer
976 * as the first entry in their struct definition. So you can
977 * access the file pointer through any of the sub-structs,
978 * or directly as just 'file' in this struct.
981 struct io_cmd_data cmd;
982 struct io_rsrc_update rsrc_update;
983 struct io_fadvise fadvise;
984 struct io_madvise madvise;
985 struct io_epoll epoll;
986 struct io_splice splice;
987 struct io_provide_buf pbuf;
988 struct io_statx statx;
989 struct io_rename rename;
990 struct io_unlink unlink;
991 struct io_mkdir mkdir;
992 struct io_symlink symlink;
993 struct io_hardlink hardlink;
995 struct io_xattr xattr;
996 struct io_uring_cmd uring_cmd;
1000 /* polled IO has completed */
1001 u8 iopoll_completed;
1003 * Can be either a fixed buffer index, or used with provided buffers.
1004 * For the latter, before issue it points to the buffer group ID,
1005 * and after selection it points to the buffer ID itself.
1012 struct io_ring_ctx *ctx;
1013 struct task_struct *task;
1015 struct io_rsrc_node *rsrc_node;
1018 /* store used ubuf, so we can prevent reloading */
1019 struct io_mapped_ubuf *imu;
1021 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
1022 struct io_buffer *kbuf;
1025 * stores buffer ID for ring provided buffers, valid IFF
1026 * REQ_F_BUFFER_RING is set.
1028 struct io_buffer_list *buf_list;
1032 /* used by request caches, completion batching and iopoll */
1033 struct io_wq_work_node comp_list;
1034 /* cache ->apoll->events */
1035 __poll_t apoll_events;
1039 struct io_task_work io_task_work;
1040 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1042 struct hlist_node hash_node;
1048 /* internal polling, see IORING_FEAT_FAST_POLL */
1049 struct async_poll *apoll;
1050 /* opcode allocated if it needs to store data for async defer */
1052 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1053 struct io_kiocb *link;
1054 /* custom credentials, valid IFF REQ_F_CREDS is set */
1055 const struct cred *creds;
1056 struct io_wq_work work;
1059 struct io_tctx_node {
1060 struct list_head ctx_node;
1061 struct task_struct *task;
1062 struct io_ring_ctx *ctx;
1065 struct io_defer_entry {
1066 struct list_head list;
1067 struct io_kiocb *req;
1071 struct io_cancel_data {
1072 struct io_ring_ctx *ctx;
1082 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
1083 * the following sqe if SQE128 is used.
1085 #define uring_cmd_pdu_size(is_sqe128) \
1086 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
1087 offsetof(struct io_uring_sqe, cmd))
1090 /* needs req->file assigned */
1091 unsigned needs_file : 1;
1092 /* should block plug */
1094 /* hash wq insertion if file is a regular file */
1095 unsigned hash_reg_file : 1;
1096 /* unbound wq insertion if file is a non-regular file */
1097 unsigned unbound_nonreg_file : 1;
1098 /* set if opcode supports polled "wait" */
1099 unsigned pollin : 1;
1100 unsigned pollout : 1;
1101 unsigned poll_exclusive : 1;
1102 /* op supports buffer selection */
1103 unsigned buffer_select : 1;
1104 /* opcode is not supported by this kernel */
1105 unsigned not_supported : 1;
1107 unsigned audit_skip : 1;
1108 /* supports ioprio */
1109 unsigned ioprio : 1;
1110 /* supports iopoll */
1111 unsigned iopoll : 1;
1112 /* size of async data needed, if any */
1113 unsigned short async_size;
1115 int (*prep)(struct io_kiocb *, const struct io_uring_sqe *);
1116 int (*issue)(struct io_kiocb *, unsigned int);
1117 int (*prep_async)(struct io_kiocb *);
1120 static const struct io_op_def io_op_defs[];
1122 /* requests with any of those set should undergo io_disarm_next() */
1123 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1124 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1126 static bool io_disarm_next(struct io_kiocb *req);
1127 static void io_uring_del_tctx_node(unsigned long index);
1128 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1129 struct task_struct *task,
1131 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1133 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1134 static void io_dismantle_req(struct io_kiocb *req);
1135 static void io_queue_linked_timeout(struct io_kiocb *req);
1136 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1137 struct io_uring_rsrc_update2 *up,
1139 static void io_clean_op(struct io_kiocb *req);
1140 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1141 unsigned issue_flags);
1142 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1143 static void io_queue_sqe(struct io_kiocb *req);
1144 static void io_rsrc_put_work(struct work_struct *work);
1146 static void io_req_task_queue(struct io_kiocb *req);
1147 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1148 static int io_req_prep_async(struct io_kiocb *req);
1150 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1151 unsigned int issue_flags, u32 slot_index);
1152 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
1153 unsigned int offset);
1154 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1156 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1157 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1158 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1160 static struct kmem_cache *req_cachep;
1162 static const struct file_operations io_uring_fops;
1164 const char *io_uring_get_opcode(u8 opcode)
1166 switch ((enum io_uring_op)opcode) {
1169 case IORING_OP_READV:
1171 case IORING_OP_WRITEV:
1173 case IORING_OP_FSYNC:
1175 case IORING_OP_READ_FIXED:
1176 return "READ_FIXED";
1177 case IORING_OP_WRITE_FIXED:
1178 return "WRITE_FIXED";
1179 case IORING_OP_POLL_ADD:
1181 case IORING_OP_POLL_REMOVE:
1182 return "POLL_REMOVE";
1183 case IORING_OP_SYNC_FILE_RANGE:
1184 return "SYNC_FILE_RANGE";
1185 case IORING_OP_SENDMSG:
1187 case IORING_OP_RECVMSG:
1189 case IORING_OP_TIMEOUT:
1191 case IORING_OP_TIMEOUT_REMOVE:
1192 return "TIMEOUT_REMOVE";
1193 case IORING_OP_ACCEPT:
1195 case IORING_OP_ASYNC_CANCEL:
1196 return "ASYNC_CANCEL";
1197 case IORING_OP_LINK_TIMEOUT:
1198 return "LINK_TIMEOUT";
1199 case IORING_OP_CONNECT:
1201 case IORING_OP_FALLOCATE:
1203 case IORING_OP_OPENAT:
1205 case IORING_OP_CLOSE:
1207 case IORING_OP_FILES_UPDATE:
1208 return "FILES_UPDATE";
1209 case IORING_OP_STATX:
1211 case IORING_OP_READ:
1213 case IORING_OP_WRITE:
1215 case IORING_OP_FADVISE:
1217 case IORING_OP_MADVISE:
1219 case IORING_OP_SEND:
1221 case IORING_OP_RECV:
1223 case IORING_OP_OPENAT2:
1225 case IORING_OP_EPOLL_CTL:
1227 case IORING_OP_SPLICE:
1229 case IORING_OP_PROVIDE_BUFFERS:
1230 return "PROVIDE_BUFFERS";
1231 case IORING_OP_REMOVE_BUFFERS:
1232 return "REMOVE_BUFFERS";
1235 case IORING_OP_SHUTDOWN:
1237 case IORING_OP_RENAMEAT:
1239 case IORING_OP_UNLINKAT:
1241 case IORING_OP_MKDIRAT:
1243 case IORING_OP_SYMLINKAT:
1245 case IORING_OP_LINKAT:
1247 case IORING_OP_MSG_RING:
1249 case IORING_OP_FSETXATTR:
1251 case IORING_OP_SETXATTR:
1253 case IORING_OP_FGETXATTR:
1255 case IORING_OP_GETXATTR:
1257 case IORING_OP_SOCKET:
1259 case IORING_OP_URING_CMD:
1261 case IORING_OP_LAST:
1267 struct sock *io_uring_get_socket(struct file *file)
1269 #if defined(CONFIG_UNIX)
1270 if (file->f_op == &io_uring_fops) {
1271 struct io_ring_ctx *ctx = file->private_data;
1273 return ctx->ring_sock->sk;
1278 EXPORT_SYMBOL(io_uring_get_socket);
1280 #if defined(CONFIG_UNIX)
1281 static inline bool io_file_need_scm(struct file *filp)
1283 #if defined(IO_URING_SCM_ALL)
1286 return !!unix_get_socket(filp);
1290 static inline bool io_file_need_scm(struct file *filp)
1296 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1298 lockdep_assert_held(&ctx->uring_lock);
1299 if (issue_flags & IO_URING_F_UNLOCKED)
1300 mutex_unlock(&ctx->uring_lock);
1303 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1306 * "Normal" inline submissions always hold the uring_lock, since we
1307 * grab it from the system call. Same is true for the SQPOLL offload.
1308 * The only exception is when we've detached the request and issue it
1309 * from an async worker thread, grab the lock for that case.
1311 if (issue_flags & IO_URING_F_UNLOCKED)
1312 mutex_lock(&ctx->uring_lock);
1313 lockdep_assert_held(&ctx->uring_lock);
1316 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1319 mutex_lock(&ctx->uring_lock);
1324 #define io_for_each_link(pos, head) \
1325 for (pos = (head); pos; pos = pos->link)
1328 * Shamelessly stolen from the mm implementation of page reference checking,
1329 * see commit f958d7b528b1 for details.
1331 #define req_ref_zero_or_close_to_overflow(req) \
1332 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1334 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1336 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1337 return atomic_inc_not_zero(&req->refs);
1340 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1342 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1345 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1346 return atomic_dec_and_test(&req->refs);
1349 static inline void req_ref_get(struct io_kiocb *req)
1351 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1352 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1353 atomic_inc(&req->refs);
1356 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1358 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1359 __io_submit_flush_completions(ctx);
1362 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1364 if (!(req->flags & REQ_F_REFCOUNT)) {
1365 req->flags |= REQ_F_REFCOUNT;
1366 atomic_set(&req->refs, nr);
1370 static inline void io_req_set_refcount(struct io_kiocb *req)
1372 __io_req_set_refcount(req, 1);
1375 #define IO_RSRC_REF_BATCH 100
1377 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1379 percpu_ref_put_many(&node->refs, nr);
1382 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1383 struct io_ring_ctx *ctx)
1384 __must_hold(&ctx->uring_lock)
1386 struct io_rsrc_node *node = req->rsrc_node;
1389 if (node == ctx->rsrc_node)
1390 ctx->rsrc_cached_refs++;
1392 io_rsrc_put_node(node, 1);
1396 static inline void io_req_put_rsrc(struct io_kiocb *req)
1399 io_rsrc_put_node(req->rsrc_node, 1);
1402 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1403 __must_hold(&ctx->uring_lock)
1405 if (ctx->rsrc_cached_refs) {
1406 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1407 ctx->rsrc_cached_refs = 0;
1411 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1412 __must_hold(&ctx->uring_lock)
1414 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1415 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1418 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1419 struct io_ring_ctx *ctx,
1420 unsigned int issue_flags)
1422 if (!req->rsrc_node) {
1423 req->rsrc_node = ctx->rsrc_node;
1425 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1426 lockdep_assert_held(&ctx->uring_lock);
1427 ctx->rsrc_cached_refs--;
1428 if (unlikely(ctx->rsrc_cached_refs < 0))
1429 io_rsrc_refs_refill(ctx);
1431 percpu_ref_get(&req->rsrc_node->refs);
1436 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1438 if (req->flags & REQ_F_BUFFER_RING) {
1440 req->buf_list->head++;
1441 req->flags &= ~REQ_F_BUFFER_RING;
1443 list_add(&req->kbuf->list, list);
1444 req->flags &= ~REQ_F_BUFFER_SELECTED;
1447 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1450 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1452 lockdep_assert_held(&req->ctx->completion_lock);
1454 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1456 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1459 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1460 unsigned issue_flags)
1462 unsigned int cflags;
1464 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1468 * We can add this buffer back to two lists:
1470 * 1) The io_buffers_cache list. This one is protected by the
1471 * ctx->uring_lock. If we already hold this lock, add back to this
1472 * list as we can grab it from issue as well.
1473 * 2) The io_buffers_comp list. This one is protected by the
1474 * ctx->completion_lock.
1476 * We migrate buffers from the comp_list to the issue cache list
1479 if (req->flags & REQ_F_BUFFER_RING) {
1480 /* no buffers to recycle for this case */
1481 cflags = __io_put_kbuf(req, NULL);
1482 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1483 struct io_ring_ctx *ctx = req->ctx;
1485 spin_lock(&ctx->completion_lock);
1486 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1487 spin_unlock(&ctx->completion_lock);
1489 lockdep_assert_held(&req->ctx->uring_lock);
1491 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1497 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1500 if (ctx->io_bl && bgid < BGID_ARRAY)
1501 return &ctx->io_bl[bgid];
1503 return xa_load(&ctx->io_bl_xa, bgid);
1506 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1508 struct io_ring_ctx *ctx = req->ctx;
1509 struct io_buffer_list *bl;
1510 struct io_buffer *buf;
1512 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1515 * For legacy provided buffer mode, don't recycle if we already did
1516 * IO to this buffer. For ring-mapped provided buffer mode, we should
1517 * increment ring->head to explicitly monopolize the buffer to avoid
1520 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
1521 (req->flags & REQ_F_PARTIAL_IO))
1525 * READV uses fields in `struct io_rw` (len/addr) to stash the selected
1526 * buffer data. However if that buffer is recycled the original request
1527 * data stored in addr is lost. Therefore forbid recycling for now.
1529 if (req->opcode == IORING_OP_READV)
1533 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1534 * the flag and hence ensure that bl->head doesn't get incremented.
1535 * If the tail has already been incremented, hang on to it.
1537 if (req->flags & REQ_F_BUFFER_RING) {
1538 if (req->buf_list) {
1539 if (req->flags & REQ_F_PARTIAL_IO) {
1540 req->buf_list->head++;
1541 req->buf_list = NULL;
1543 req->buf_index = req->buf_list->bgid;
1544 req->flags &= ~REQ_F_BUFFER_RING;
1550 io_ring_submit_lock(ctx, issue_flags);
1553 bl = io_buffer_get_list(ctx, buf->bgid);
1554 list_add(&buf->list, &bl->buf_list);
1555 req->flags &= ~REQ_F_BUFFER_SELECTED;
1556 req->buf_index = buf->bgid;
1558 io_ring_submit_unlock(ctx, issue_flags);
1561 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1563 __must_hold(&req->ctx->timeout_lock)
1565 struct io_kiocb *req;
1567 if (task && head->task != task)
1572 io_for_each_link(req, head) {
1573 if (req->flags & REQ_F_INFLIGHT)
1579 static bool io_match_linked(struct io_kiocb *head)
1581 struct io_kiocb *req;
1583 io_for_each_link(req, head) {
1584 if (req->flags & REQ_F_INFLIGHT)
1591 * As io_match_task() but protected against racing with linked timeouts.
1592 * User must not hold timeout_lock.
1594 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1599 if (task && head->task != task)
1604 if (head->flags & REQ_F_LINK_TIMEOUT) {
1605 struct io_ring_ctx *ctx = head->ctx;
1607 /* protect against races with linked timeouts */
1608 spin_lock_irq(&ctx->timeout_lock);
1609 matched = io_match_linked(head);
1610 spin_unlock_irq(&ctx->timeout_lock);
1612 matched = io_match_linked(head);
1617 static inline bool req_has_async_data(struct io_kiocb *req)
1619 return req->flags & REQ_F_ASYNC_DATA;
1622 static inline void req_set_fail(struct io_kiocb *req)
1624 req->flags |= REQ_F_FAIL;
1625 if (req->flags & REQ_F_CQE_SKIP) {
1626 req->flags &= ~REQ_F_CQE_SKIP;
1627 req->flags |= REQ_F_SKIP_LINK_CQES;
1631 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1637 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1639 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1642 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1644 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1646 complete(&ctx->ref_comp);
1649 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1651 struct io_timeout *timeout = io_kiocb_to_cmd(req);
1653 return !timeout->off;
1656 static __cold void io_fallback_req_func(struct work_struct *work)
1658 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1659 fallback_work.work);
1660 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1661 struct io_kiocb *req, *tmp;
1662 bool locked = false;
1664 percpu_ref_get(&ctx->refs);
1665 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1666 req->io_task_work.func(req, &locked);
1669 io_submit_flush_completions(ctx);
1670 mutex_unlock(&ctx->uring_lock);
1672 percpu_ref_put(&ctx->refs);
1675 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1677 struct io_ring_ctx *ctx;
1680 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1684 xa_init(&ctx->io_bl_xa);
1687 * Use 5 bits less than the max cq entries, that should give us around
1688 * 32 entries per hash list if totally full and uniformly spread.
1690 hash_bits = ilog2(p->cq_entries);
1694 ctx->cancel_hash_bits = hash_bits;
1695 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1697 if (!ctx->cancel_hash)
1699 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1701 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1702 if (!ctx->dummy_ubuf)
1704 /* set invalid range, so io_import_fixed() fails meeting it */
1705 ctx->dummy_ubuf->ubuf = -1UL;
1707 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1708 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1711 ctx->flags = p->flags;
1712 init_waitqueue_head(&ctx->sqo_sq_wait);
1713 INIT_LIST_HEAD(&ctx->sqd_list);
1714 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1715 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1716 INIT_LIST_HEAD(&ctx->apoll_cache);
1717 init_completion(&ctx->ref_comp);
1718 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1719 mutex_init(&ctx->uring_lock);
1720 init_waitqueue_head(&ctx->cq_wait);
1721 spin_lock_init(&ctx->completion_lock);
1722 spin_lock_init(&ctx->timeout_lock);
1723 INIT_WQ_LIST(&ctx->iopoll_list);
1724 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1725 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1726 INIT_LIST_HEAD(&ctx->defer_list);
1727 INIT_LIST_HEAD(&ctx->timeout_list);
1728 INIT_LIST_HEAD(&ctx->ltimeout_list);
1729 spin_lock_init(&ctx->rsrc_ref_lock);
1730 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1731 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1732 init_llist_head(&ctx->rsrc_put_llist);
1733 INIT_LIST_HEAD(&ctx->tctx_list);
1734 ctx->submit_state.free_list.next = NULL;
1735 INIT_WQ_LIST(&ctx->locked_free_list);
1736 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1737 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1740 kfree(ctx->dummy_ubuf);
1741 kfree(ctx->cancel_hash);
1743 xa_destroy(&ctx->io_bl_xa);
1748 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1750 struct io_rings *r = ctx->rings;
1752 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1756 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1758 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1759 struct io_ring_ctx *ctx = req->ctx;
1761 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1767 static inline bool io_req_ffs_set(struct io_kiocb *req)
1769 return req->flags & REQ_F_FIXED_FILE;
1772 static inline void io_req_track_inflight(struct io_kiocb *req)
1774 if (!(req->flags & REQ_F_INFLIGHT)) {
1775 req->flags |= REQ_F_INFLIGHT;
1776 atomic_inc(&req->task->io_uring->inflight_tracked);
1780 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1782 if (WARN_ON_ONCE(!req->link))
1785 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1786 req->flags |= REQ_F_LINK_TIMEOUT;
1788 /* linked timeouts should have two refs once prep'ed */
1789 io_req_set_refcount(req);
1790 __io_req_set_refcount(req->link, 2);
1794 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1796 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1798 return __io_prep_linked_timeout(req);
1801 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1803 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1806 static inline void io_arm_ltimeout(struct io_kiocb *req)
1808 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1809 __io_arm_ltimeout(req);
1812 static void io_prep_async_work(struct io_kiocb *req)
1814 const struct io_op_def *def = &io_op_defs[req->opcode];
1815 struct io_ring_ctx *ctx = req->ctx;
1817 if (!(req->flags & REQ_F_CREDS)) {
1818 req->flags |= REQ_F_CREDS;
1819 req->creds = get_current_cred();
1822 req->work.list.next = NULL;
1823 req->work.flags = 0;
1824 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1825 if (req->flags & REQ_F_FORCE_ASYNC)
1826 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1828 if (req->flags & REQ_F_ISREG) {
1829 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1830 io_wq_hash_work(&req->work, file_inode(req->file));
1831 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1832 if (def->unbound_nonreg_file)
1833 req->work.flags |= IO_WQ_WORK_UNBOUND;
1837 static void io_prep_async_link(struct io_kiocb *req)
1839 struct io_kiocb *cur;
1841 if (req->flags & REQ_F_LINK_TIMEOUT) {
1842 struct io_ring_ctx *ctx = req->ctx;
1844 spin_lock_irq(&ctx->timeout_lock);
1845 io_for_each_link(cur, req)
1846 io_prep_async_work(cur);
1847 spin_unlock_irq(&ctx->timeout_lock);
1849 io_for_each_link(cur, req)
1850 io_prep_async_work(cur);
1854 static inline void io_req_add_compl_list(struct io_kiocb *req)
1856 struct io_submit_state *state = &req->ctx->submit_state;
1858 if (!(req->flags & REQ_F_CQE_SKIP))
1859 state->flush_cqes = true;
1860 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1863 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1865 struct io_kiocb *link = io_prep_linked_timeout(req);
1866 struct io_uring_task *tctx = req->task->io_uring;
1869 BUG_ON(!tctx->io_wq);
1871 /* init ->work of the whole link before punting */
1872 io_prep_async_link(req);
1875 * Not expected to happen, but if we do have a bug where this _can_
1876 * happen, catch it here and ensure the request is marked as
1877 * canceled. That will make io-wq go through the usual work cancel
1878 * procedure rather than attempt to run this request (or create a new
1881 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1882 req->work.flags |= IO_WQ_WORK_CANCEL;
1884 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1885 req->opcode, req->flags, &req->work,
1886 io_wq_is_hashed(&req->work));
1887 io_wq_enqueue(tctx->io_wq, &req->work);
1889 io_queue_linked_timeout(link);
1892 static void io_kill_timeout(struct io_kiocb *req, int status)
1893 __must_hold(&req->ctx->completion_lock)
1894 __must_hold(&req->ctx->timeout_lock)
1896 struct io_timeout_data *io = req->async_data;
1898 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1899 struct io_timeout *timeout = io_kiocb_to_cmd(req);
1903 atomic_set(&req->ctx->cq_timeouts,
1904 atomic_read(&req->ctx->cq_timeouts) + 1);
1905 list_del_init(&timeout->list);
1906 io_req_tw_post_queue(req, status, 0);
1910 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1912 while (!list_empty(&ctx->defer_list)) {
1913 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1914 struct io_defer_entry, list);
1916 if (req_need_defer(de->req, de->seq))
1918 list_del_init(&de->list);
1919 io_req_task_queue(de->req);
1924 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1925 __must_hold(&ctx->completion_lock)
1927 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1928 struct io_timeout *timeout, *tmp;
1930 spin_lock_irq(&ctx->timeout_lock);
1931 list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
1932 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
1933 u32 events_needed, events_got;
1935 if (io_is_timeout_noseq(req))
1939 * Since seq can easily wrap around over time, subtract
1940 * the last seq at which timeouts were flushed before comparing.
1941 * Assuming not more than 2^31-1 events have happened since,
1942 * these subtractions won't have wrapped, so we can check if
1943 * target is in [last_seq, current_seq] by comparing the two.
1945 events_needed = timeout->target_seq - ctx->cq_last_tm_flush;
1946 events_got = seq - ctx->cq_last_tm_flush;
1947 if (events_got < events_needed)
1950 io_kill_timeout(req, 0);
1952 ctx->cq_last_tm_flush = seq;
1953 spin_unlock_irq(&ctx->timeout_lock);
1956 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1958 /* order cqe stores with ring update */
1959 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1962 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1964 if (ctx->off_timeout_used || ctx->drain_active) {
1965 spin_lock(&ctx->completion_lock);
1966 if (ctx->off_timeout_used)
1967 io_flush_timeouts(ctx);
1968 if (ctx->drain_active)
1969 io_queue_deferred(ctx);
1970 io_commit_cqring(ctx);
1971 spin_unlock(&ctx->completion_lock);
1974 io_eventfd_signal(ctx);
1977 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1979 struct io_rings *r = ctx->rings;
1981 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1984 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1986 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1990 * writes to the cq entry need to come after reading head; the
1991 * control dependency is enough as we're using WRITE_ONCE to
1994 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1996 struct io_rings *rings = ctx->rings;
1997 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1998 unsigned int shift = 0;
1999 unsigned int free, queued, len;
2001 if (ctx->flags & IORING_SETUP_CQE32)
2004 /* userspace may cheat modifying the tail, be safe and do min */
2005 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2006 free = ctx->cq_entries - queued;
2007 /* we need a contiguous range, limit based on the current array offset */
2008 len = min(free, ctx->cq_entries - off);
2012 ctx->cached_cq_tail++;
2013 ctx->cqe_cached = &rings->cqes[off];
2014 ctx->cqe_sentinel = ctx->cqe_cached + len;
2016 return &rings->cqes[off << shift];
2019 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2021 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2022 struct io_uring_cqe *cqe = ctx->cqe_cached;
2024 if (ctx->flags & IORING_SETUP_CQE32) {
2025 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2030 ctx->cached_cq_tail++;
2035 return __io_get_cqe(ctx);
2038 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2040 struct io_ev_fd *ev_fd;
2044 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2045 * and eventfd_signal
2047 ev_fd = rcu_dereference(ctx->io_ev_fd);
2050 * Check again if ev_fd exists incase an io_eventfd_unregister call
2051 * completed between the NULL check of ctx->io_ev_fd at the start of
2052 * the function and rcu_read_lock.
2054 if (unlikely(!ev_fd))
2056 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2059 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2060 eventfd_signal(ev_fd->cq_ev_fd, 1);
2065 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2068 * wake_up_all() may seem excessive, but io_wake_function() and
2069 * io_should_wake() handle the termination of the loop and only
2070 * wake as many waiters as we need to.
2072 if (wq_has_sleeper(&ctx->cq_wait))
2073 wake_up_all(&ctx->cq_wait);
2077 * This should only get called when at least one event has been posted.
2078 * Some applications rely on the eventfd notification count only changing
2079 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2080 * 1:1 relationship between how many times this function is called (and
2081 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2083 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2085 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2087 __io_commit_cqring_flush(ctx);
2089 io_cqring_wake(ctx);
2092 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2094 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2096 __io_commit_cqring_flush(ctx);
2098 if (ctx->flags & IORING_SETUP_SQPOLL)
2099 io_cqring_wake(ctx);
2102 /* Returns true if there are no backlogged entries after the flush */
2103 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2105 bool all_flushed, posted;
2106 size_t cqe_size = sizeof(struct io_uring_cqe);
2108 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2111 if (ctx->flags & IORING_SETUP_CQE32)
2115 spin_lock(&ctx->completion_lock);
2116 while (!list_empty(&ctx->cq_overflow_list)) {
2117 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2118 struct io_overflow_cqe *ocqe;
2122 ocqe = list_first_entry(&ctx->cq_overflow_list,
2123 struct io_overflow_cqe, list);
2125 memcpy(cqe, &ocqe->cqe, cqe_size);
2127 io_account_cq_overflow(ctx);
2130 list_del(&ocqe->list);
2134 all_flushed = list_empty(&ctx->cq_overflow_list);
2136 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2137 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2140 io_commit_cqring(ctx);
2141 spin_unlock(&ctx->completion_lock);
2143 io_cqring_ev_posted(ctx);
2147 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2151 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2152 /* iopoll syncs against uring_lock, not completion_lock */
2153 if (ctx->flags & IORING_SETUP_IOPOLL)
2154 mutex_lock(&ctx->uring_lock);
2155 ret = __io_cqring_overflow_flush(ctx, false);
2156 if (ctx->flags & IORING_SETUP_IOPOLL)
2157 mutex_unlock(&ctx->uring_lock);
2163 static void __io_put_task(struct task_struct *task, int nr)
2165 struct io_uring_task *tctx = task->io_uring;
2167 percpu_counter_sub(&tctx->inflight, nr);
2168 if (unlikely(atomic_read(&tctx->in_idle)))
2169 wake_up(&tctx->wait);
2170 put_task_struct_many(task, nr);
2173 /* must to be called somewhat shortly after putting a request */
2174 static inline void io_put_task(struct task_struct *task, int nr)
2176 if (likely(task == current))
2177 task->io_uring->cached_refs += nr;
2179 __io_put_task(task, nr);
2182 static void io_task_refs_refill(struct io_uring_task *tctx)
2184 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2186 percpu_counter_add(&tctx->inflight, refill);
2187 refcount_add(refill, ¤t->usage);
2188 tctx->cached_refs += refill;
2191 static inline void io_get_task_refs(int nr)
2193 struct io_uring_task *tctx = current->io_uring;
2195 tctx->cached_refs -= nr;
2196 if (unlikely(tctx->cached_refs < 0))
2197 io_task_refs_refill(tctx);
2200 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2202 struct io_uring_task *tctx = task->io_uring;
2203 unsigned int refs = tctx->cached_refs;
2206 tctx->cached_refs = 0;
2207 percpu_counter_sub(&tctx->inflight, refs);
2208 put_task_struct_many(task, refs);
2212 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2213 s32 res, u32 cflags, u64 extra1,
2216 struct io_overflow_cqe *ocqe;
2217 size_t ocq_size = sizeof(struct io_overflow_cqe);
2218 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2221 ocq_size += sizeof(struct io_uring_cqe);
2223 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2224 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2227 * If we're in ring overflow flush mode, or in task cancel mode,
2228 * or cannot allocate an overflow entry, then we need to drop it
2231 io_account_cq_overflow(ctx);
2232 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2235 if (list_empty(&ctx->cq_overflow_list)) {
2236 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2237 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2240 ocqe->cqe.user_data = user_data;
2241 ocqe->cqe.res = res;
2242 ocqe->cqe.flags = cflags;
2244 ocqe->cqe.big_cqe[0] = extra1;
2245 ocqe->cqe.big_cqe[1] = extra2;
2247 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2251 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
2252 struct io_kiocb *req)
2254 struct io_uring_cqe *cqe;
2256 if (!(ctx->flags & IORING_SETUP_CQE32)) {
2257 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2258 req->cqe.res, req->cqe.flags, 0, 0);
2261 * If we can't get a cq entry, userspace overflowed the
2262 * submission (by quite a lot). Increment the overflow count in
2265 cqe = io_get_cqe(ctx);
2267 memcpy(cqe, &req->cqe, sizeof(*cqe));
2271 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2272 req->cqe.res, req->cqe.flags,
2275 u64 extra1 = 0, extra2 = 0;
2277 if (req->flags & REQ_F_CQE32_INIT) {
2278 extra1 = req->extra1;
2279 extra2 = req->extra2;
2282 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2283 req->cqe.res, req->cqe.flags, extra1, extra2);
2286 * If we can't get a cq entry, userspace overflowed the
2287 * submission (by quite a lot). Increment the overflow count in
2290 cqe = io_get_cqe(ctx);
2292 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2293 WRITE_ONCE(cqe->big_cqe[0], extra1);
2294 WRITE_ONCE(cqe->big_cqe[1], extra2);
2298 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2299 req->cqe.res, req->cqe.flags,
2304 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2305 s32 res, u32 cflags)
2307 struct io_uring_cqe *cqe;
2310 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2313 * If we can't get a cq entry, userspace overflowed the
2314 * submission (by quite a lot). Increment the overflow count in
2317 cqe = io_get_cqe(ctx);
2319 WRITE_ONCE(cqe->user_data, user_data);
2320 WRITE_ONCE(cqe->res, res);
2321 WRITE_ONCE(cqe->flags, cflags);
2323 if (ctx->flags & IORING_SETUP_CQE32) {
2324 WRITE_ONCE(cqe->big_cqe[0], 0);
2325 WRITE_ONCE(cqe->big_cqe[1], 0);
2329 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2332 static void __io_req_complete_put(struct io_kiocb *req)
2335 * If we're the last reference to this request, add to our locked
2338 if (req_ref_put_and_test(req)) {
2339 struct io_ring_ctx *ctx = req->ctx;
2341 if (req->flags & IO_REQ_LINK_FLAGS) {
2342 if (req->flags & IO_DISARM_MASK)
2343 io_disarm_next(req);
2345 io_req_task_queue(req->link);
2349 io_req_put_rsrc(req);
2351 * Selected buffer deallocation in io_clean_op() assumes that
2352 * we don't hold ->completion_lock. Clean them here to avoid
2355 io_put_kbuf_comp(req);
2356 io_dismantle_req(req);
2357 io_put_task(req->task, 1);
2358 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2359 ctx->locked_free_nr++;
2363 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2366 if (!(req->flags & REQ_F_CQE_SKIP)) {
2368 req->cqe.flags = cflags;
2369 __io_fill_cqe_req(req->ctx, req);
2371 __io_req_complete_put(req);
2374 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2376 struct io_ring_ctx *ctx = req->ctx;
2378 spin_lock(&ctx->completion_lock);
2379 __io_req_complete_post(req, res, cflags);
2380 io_commit_cqring(ctx);
2381 spin_unlock(&ctx->completion_lock);
2382 io_cqring_ev_posted(ctx);
2385 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2389 req->cqe.flags = cflags;
2390 req->flags |= REQ_F_COMPLETE_INLINE;
2393 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2394 s32 res, u32 cflags)
2396 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2397 io_req_complete_state(req, res, cflags);
2399 io_req_complete_post(req, res, cflags);
2402 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2406 __io_req_complete(req, 0, res, 0);
2409 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2412 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2416 * Don't initialise the fields below on every allocation, but do that in
2417 * advance and keep them valid across allocations.
2419 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2423 req->async_data = NULL;
2424 /* not necessary, but safer to zero */
2428 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2429 struct io_submit_state *state)
2431 spin_lock(&ctx->completion_lock);
2432 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2433 ctx->locked_free_nr = 0;
2434 spin_unlock(&ctx->completion_lock);
2437 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2439 return !ctx->submit_state.free_list.next;
2443 * A request might get retired back into the request caches even before opcode
2444 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2445 * Because of that, io_alloc_req() should be called only under ->uring_lock
2446 * and with extra caution to not get a request that is still worked on.
2448 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2449 __must_hold(&ctx->uring_lock)
2451 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2452 void *reqs[IO_REQ_ALLOC_BATCH];
2456 * If we have more than a batch's worth of requests in our IRQ side
2457 * locked cache, grab the lock and move them over to our submission
2460 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2461 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2462 if (!io_req_cache_empty(ctx))
2466 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2469 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2470 * retry single alloc to be on the safe side.
2472 if (unlikely(ret <= 0)) {
2473 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2479 percpu_ref_get_many(&ctx->refs, ret);
2480 for (i = 0; i < ret; i++) {
2481 struct io_kiocb *req = reqs[i];
2483 io_preinit_req(req, ctx);
2484 io_req_add_to_cache(req, ctx);
2489 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2491 if (unlikely(io_req_cache_empty(ctx)))
2492 return __io_alloc_req_refill(ctx);
2496 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2498 struct io_wq_work_node *node;
2500 node = wq_stack_extract(&ctx->submit_state.free_list);
2501 return container_of(node, struct io_kiocb, comp_list);
2504 static inline void io_put_file(struct file *file)
2510 static inline void io_dismantle_req(struct io_kiocb *req)
2512 unsigned int flags = req->flags;
2514 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2516 if (!(flags & REQ_F_FIXED_FILE))
2517 io_put_file(req->file);
2520 static __cold void io_free_req(struct io_kiocb *req)
2522 struct io_ring_ctx *ctx = req->ctx;
2524 io_req_put_rsrc(req);
2525 io_dismantle_req(req);
2526 io_put_task(req->task, 1);
2528 spin_lock(&ctx->completion_lock);
2529 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2530 ctx->locked_free_nr++;
2531 spin_unlock(&ctx->completion_lock);
2534 static inline void io_remove_next_linked(struct io_kiocb *req)
2536 struct io_kiocb *nxt = req->link;
2538 req->link = nxt->link;
2542 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2543 __must_hold(&req->ctx->completion_lock)
2544 __must_hold(&req->ctx->timeout_lock)
2546 struct io_kiocb *link = req->link;
2548 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2549 struct io_timeout_data *io = link->async_data;
2550 struct io_timeout *timeout = io_kiocb_to_cmd(link);
2552 io_remove_next_linked(req);
2553 timeout->head = NULL;
2554 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2555 list_del(&timeout->list);
2562 static void io_fail_links(struct io_kiocb *req)
2563 __must_hold(&req->ctx->completion_lock)
2565 struct io_kiocb *nxt, *link = req->link;
2566 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2570 long res = -ECANCELED;
2572 if (link->flags & REQ_F_FAIL)
2573 res = link->cqe.res;
2578 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2582 link->flags |= REQ_F_CQE_SKIP;
2584 link->flags &= ~REQ_F_CQE_SKIP;
2585 __io_req_complete_post(link, res, 0);
2590 static bool io_disarm_next(struct io_kiocb *req)
2591 __must_hold(&req->ctx->completion_lock)
2593 struct io_kiocb *link = NULL;
2594 bool posted = false;
2596 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2598 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2599 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2600 io_remove_next_linked(req);
2601 io_req_tw_post_queue(link, -ECANCELED, 0);
2604 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2605 struct io_ring_ctx *ctx = req->ctx;
2607 spin_lock_irq(&ctx->timeout_lock);
2608 link = io_disarm_linked_timeout(req);
2609 spin_unlock_irq(&ctx->timeout_lock);
2612 io_req_tw_post_queue(link, -ECANCELED, 0);
2615 if (unlikely((req->flags & REQ_F_FAIL) &&
2616 !(req->flags & REQ_F_HARDLINK))) {
2617 posted |= (req->link != NULL);
2623 static void __io_req_find_next_prep(struct io_kiocb *req)
2625 struct io_ring_ctx *ctx = req->ctx;
2628 spin_lock(&ctx->completion_lock);
2629 posted = io_disarm_next(req);
2630 io_commit_cqring(ctx);
2631 spin_unlock(&ctx->completion_lock);
2633 io_cqring_ev_posted(ctx);
2636 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2638 struct io_kiocb *nxt;
2641 * If LINK is set, we have dependent requests in this chain. If we
2642 * didn't fail this request, queue the first one up, moving any other
2643 * dependencies to the next request. In case of failure, fail the rest
2646 if (unlikely(req->flags & IO_DISARM_MASK))
2647 __io_req_find_next_prep(req);
2653 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2657 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2658 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2660 io_submit_flush_completions(ctx);
2661 mutex_unlock(&ctx->uring_lock);
2664 percpu_ref_put(&ctx->refs);
2667 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2669 io_commit_cqring(ctx);
2670 spin_unlock(&ctx->completion_lock);
2671 io_cqring_ev_posted(ctx);
2674 static void handle_prev_tw_list(struct io_wq_work_node *node,
2675 struct io_ring_ctx **ctx, bool *uring_locked)
2677 if (*ctx && !*uring_locked)
2678 spin_lock(&(*ctx)->completion_lock);
2681 struct io_wq_work_node *next = node->next;
2682 struct io_kiocb *req = container_of(node, struct io_kiocb,
2685 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2687 if (req->ctx != *ctx) {
2688 if (unlikely(!*uring_locked && *ctx))
2689 ctx_commit_and_unlock(*ctx);
2691 ctx_flush_and_put(*ctx, uring_locked);
2693 /* if not contended, grab and improve batching */
2694 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2695 percpu_ref_get(&(*ctx)->refs);
2696 if (unlikely(!*uring_locked))
2697 spin_lock(&(*ctx)->completion_lock);
2699 if (likely(*uring_locked))
2700 req->io_task_work.func(req, uring_locked);
2702 __io_req_complete_post(req, req->cqe.res,
2703 io_put_kbuf_comp(req));
2707 if (unlikely(!*uring_locked))
2708 ctx_commit_and_unlock(*ctx);
2711 static void handle_tw_list(struct io_wq_work_node *node,
2712 struct io_ring_ctx **ctx, bool *locked)
2715 struct io_wq_work_node *next = node->next;
2716 struct io_kiocb *req = container_of(node, struct io_kiocb,
2719 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2721 if (req->ctx != *ctx) {
2722 ctx_flush_and_put(*ctx, locked);
2724 /* if not contended, grab and improve batching */
2725 *locked = mutex_trylock(&(*ctx)->uring_lock);
2726 percpu_ref_get(&(*ctx)->refs);
2728 req->io_task_work.func(req, locked);
2733 static void tctx_task_work(struct callback_head *cb)
2735 bool uring_locked = false;
2736 struct io_ring_ctx *ctx = NULL;
2737 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2741 struct io_wq_work_node *node1, *node2;
2743 spin_lock_irq(&tctx->task_lock);
2744 node1 = tctx->prio_task_list.first;
2745 node2 = tctx->task_list.first;
2746 INIT_WQ_LIST(&tctx->task_list);
2747 INIT_WQ_LIST(&tctx->prio_task_list);
2748 if (!node2 && !node1)
2749 tctx->task_running = false;
2750 spin_unlock_irq(&tctx->task_lock);
2751 if (!node2 && !node1)
2755 handle_prev_tw_list(node1, &ctx, &uring_locked);
2757 handle_tw_list(node2, &ctx, &uring_locked);
2760 if (data_race(!tctx->task_list.first) &&
2761 data_race(!tctx->prio_task_list.first) && uring_locked)
2762 io_submit_flush_completions(ctx);
2765 ctx_flush_and_put(ctx, &uring_locked);
2767 /* relaxed read is enough as only the task itself sets ->in_idle */
2768 if (unlikely(atomic_read(&tctx->in_idle)))
2769 io_uring_drop_tctx_refs(current);
2772 static void __io_req_task_work_add(struct io_kiocb *req,
2773 struct io_uring_task *tctx,
2774 struct io_wq_work_list *list)
2776 struct io_ring_ctx *ctx = req->ctx;
2777 struct io_wq_work_node *node;
2778 unsigned long flags;
2781 spin_lock_irqsave(&tctx->task_lock, flags);
2782 wq_list_add_tail(&req->io_task_work.node, list);
2783 running = tctx->task_running;
2785 tctx->task_running = true;
2786 spin_unlock_irqrestore(&tctx->task_lock, flags);
2788 /* task_work already pending, we're done */
2792 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2793 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2795 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2798 spin_lock_irqsave(&tctx->task_lock, flags);
2799 tctx->task_running = false;
2800 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2801 spin_unlock_irqrestore(&tctx->task_lock, flags);
2804 req = container_of(node, struct io_kiocb, io_task_work.node);
2806 if (llist_add(&req->io_task_work.fallback_node,
2807 &req->ctx->fallback_llist))
2808 schedule_delayed_work(&req->ctx->fallback_work, 1);
2812 static void io_req_task_work_add(struct io_kiocb *req)
2814 struct io_uring_task *tctx = req->task->io_uring;
2816 __io_req_task_work_add(req, tctx, &tctx->task_list);
2819 static void io_req_task_prio_work_add(struct io_kiocb *req)
2821 struct io_uring_task *tctx = req->task->io_uring;
2823 if (req->ctx->flags & IORING_SETUP_SQPOLL)
2824 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
2826 __io_req_task_work_add(req, tctx, &tctx->task_list);
2829 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2831 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2834 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2837 req->cqe.flags = cflags;
2838 req->io_task_work.func = io_req_tw_post;
2839 io_req_task_work_add(req);
2842 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2844 /* not needed for normal modes, but SQPOLL depends on it */
2845 io_tw_lock(req->ctx, locked);
2846 io_req_complete_failed(req, req->cqe.res);
2849 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2851 io_tw_lock(req->ctx, locked);
2852 /* req->task == current here, checking PF_EXITING is safe */
2853 if (likely(!(req->task->flags & PF_EXITING)))
2856 io_req_complete_failed(req, -EFAULT);
2859 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2862 req->io_task_work.func = io_req_task_cancel;
2863 io_req_task_work_add(req);
2866 static void io_req_task_queue(struct io_kiocb *req)
2868 req->io_task_work.func = io_req_task_submit;
2869 io_req_task_work_add(req);
2872 static void io_req_task_queue_reissue(struct io_kiocb *req)
2874 req->io_task_work.func = io_queue_iowq;
2875 io_req_task_work_add(req);
2878 static void io_queue_next(struct io_kiocb *req)
2880 struct io_kiocb *nxt = io_req_find_next(req);
2883 io_req_task_queue(nxt);
2886 static void io_free_batch_list(struct io_ring_ctx *ctx,
2887 struct io_wq_work_node *node)
2888 __must_hold(&ctx->uring_lock)
2890 struct task_struct *task = NULL;
2894 struct io_kiocb *req = container_of(node, struct io_kiocb,
2897 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2898 if (req->flags & REQ_F_REFCOUNT) {
2899 node = req->comp_list.next;
2900 if (!req_ref_put_and_test(req))
2903 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2904 struct async_poll *apoll = req->apoll;
2906 if (apoll->double_poll)
2907 kfree(apoll->double_poll);
2908 list_add(&apoll->poll.wait.entry,
2910 req->flags &= ~REQ_F_POLLED;
2912 if (req->flags & IO_REQ_LINK_FLAGS)
2914 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2917 if (!(req->flags & REQ_F_FIXED_FILE))
2918 io_put_file(req->file);
2920 io_req_put_rsrc_locked(req, ctx);
2922 if (req->task != task) {
2924 io_put_task(task, task_refs);
2929 node = req->comp_list.next;
2930 io_req_add_to_cache(req, ctx);
2934 io_put_task(task, task_refs);
2937 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2938 __must_hold(&ctx->uring_lock)
2940 struct io_wq_work_node *node, *prev;
2941 struct io_submit_state *state = &ctx->submit_state;
2943 if (state->flush_cqes) {
2944 spin_lock(&ctx->completion_lock);
2945 wq_list_for_each(node, prev, &state->compl_reqs) {
2946 struct io_kiocb *req = container_of(node, struct io_kiocb,
2949 if (!(req->flags & REQ_F_CQE_SKIP))
2950 __io_fill_cqe_req(ctx, req);
2953 io_commit_cqring(ctx);
2954 spin_unlock(&ctx->completion_lock);
2955 io_cqring_ev_posted(ctx);
2956 state->flush_cqes = false;
2959 io_free_batch_list(ctx, state->compl_reqs.first);
2960 INIT_WQ_LIST(&state->compl_reqs);
2964 * Drop reference to request, return next in chain (if there is one) if this
2965 * was the last reference to this request.
2967 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2969 struct io_kiocb *nxt = NULL;
2971 if (req_ref_put_and_test(req)) {
2972 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2973 nxt = io_req_find_next(req);
2979 static inline void io_put_req(struct io_kiocb *req)
2981 if (req_ref_put_and_test(req)) {
2987 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2989 /* See comment at the top of this file */
2991 return __io_cqring_events(ctx);
2994 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2996 struct io_rings *rings = ctx->rings;
2998 /* make sure SQ entry isn't read before tail */
2999 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3002 static inline bool io_run_task_work(void)
3004 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3005 __set_current_state(TASK_RUNNING);
3006 clear_notify_signal();
3007 if (task_work_pending(current))
3015 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3017 struct io_wq_work_node *pos, *start, *prev;
3018 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3019 DEFINE_IO_COMP_BATCH(iob);
3023 * Only spin for completions if we don't have multiple devices hanging
3024 * off our complete list.
3026 if (ctx->poll_multi_queue || force_nonspin)
3027 poll_flags |= BLK_POLL_ONESHOT;
3029 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3030 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3031 struct io_rw *rw = io_kiocb_to_cmd(req);
3035 * Move completed and retryable entries to our local lists.
3036 * If we find a request that requires polling, break out
3037 * and complete those lists first, if we have entries there.
3039 if (READ_ONCE(req->iopoll_completed))
3042 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
3043 if (unlikely(ret < 0))
3046 poll_flags |= BLK_POLL_ONESHOT;
3048 /* iopoll may have completed current req */
3049 if (!rq_list_empty(iob.req_list) ||
3050 READ_ONCE(req->iopoll_completed))
3054 if (!rq_list_empty(iob.req_list))
3060 wq_list_for_each_resume(pos, prev) {
3061 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3063 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3064 if (!smp_load_acquire(&req->iopoll_completed))
3067 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3070 req->cqe.flags = io_put_kbuf(req, 0);
3071 __io_fill_cqe_req(req->ctx, req);
3074 if (unlikely(!nr_events))
3077 io_commit_cqring(ctx);
3078 io_cqring_ev_posted_iopoll(ctx);
3079 pos = start ? start->next : ctx->iopoll_list.first;
3080 wq_list_cut(&ctx->iopoll_list, prev, start);
3081 io_free_batch_list(ctx, pos);
3086 * We can't just wait for polled events to come to us, we have to actively
3087 * find and complete them.
3089 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3091 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3094 mutex_lock(&ctx->uring_lock);
3095 while (!wq_list_empty(&ctx->iopoll_list)) {
3096 /* let it sleep and repeat later if can't complete a request */
3097 if (io_do_iopoll(ctx, true) == 0)
3100 * Ensure we allow local-to-the-cpu processing to take place,
3101 * in this case we need to ensure that we reap all events.
3102 * Also let task_work, etc. to progress by releasing the mutex
3104 if (need_resched()) {
3105 mutex_unlock(&ctx->uring_lock);
3107 mutex_lock(&ctx->uring_lock);
3110 mutex_unlock(&ctx->uring_lock);
3113 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3115 unsigned int nr_events = 0;
3117 unsigned long check_cq;
3120 * Don't enter poll loop if we already have events pending.
3121 * If we do, we can potentially be spinning for commands that
3122 * already triggered a CQE (eg in error).
3124 check_cq = READ_ONCE(ctx->check_cq);
3125 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3126 __io_cqring_overflow_flush(ctx, false);
3127 if (io_cqring_events(ctx))
3131 * Similarly do not spin if we have not informed the user of any
3134 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3139 * If a submit got punted to a workqueue, we can have the
3140 * application entering polling for a command before it gets
3141 * issued. That app will hold the uring_lock for the duration
3142 * of the poll right here, so we need to take a breather every
3143 * now and then to ensure that the issue has a chance to add
3144 * the poll to the issued list. Otherwise we can spin here
3145 * forever, while the workqueue is stuck trying to acquire the
3148 if (wq_list_empty(&ctx->iopoll_list)) {
3149 u32 tail = ctx->cached_cq_tail;
3151 mutex_unlock(&ctx->uring_lock);
3153 mutex_lock(&ctx->uring_lock);
3155 /* some requests don't go through iopoll_list */
3156 if (tail != ctx->cached_cq_tail ||
3157 wq_list_empty(&ctx->iopoll_list))
3160 ret = io_do_iopoll(ctx, !min);
3165 } while (nr_events < min && !need_resched());
3170 static void kiocb_end_write(struct io_kiocb *req)
3173 * Tell lockdep we inherited freeze protection from submission
3176 if (req->flags & REQ_F_ISREG) {
3177 struct super_block *sb = file_inode(req->file)->i_sb;
3179 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3185 static bool io_resubmit_prep(struct io_kiocb *req)
3187 struct io_async_rw *io = req->async_data;
3189 if (!req_has_async_data(req))
3190 return !io_req_prep_async(req);
3191 iov_iter_restore(&io->s.iter, &io->s.iter_state);
3195 static bool io_rw_should_reissue(struct io_kiocb *req)
3197 umode_t mode = file_inode(req->file)->i_mode;
3198 struct io_ring_ctx *ctx = req->ctx;
3200 if (!S_ISBLK(mode) && !S_ISREG(mode))
3202 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3203 !(ctx->flags & IORING_SETUP_IOPOLL)))
3206 * If ref is dying, we might be running poll reap from the exit work.
3207 * Don't attempt to reissue from that path, just let it fail with
3210 if (percpu_ref_is_dying(&ctx->refs))
3213 * Play it safe and assume not safe to re-import and reissue if we're
3214 * not in the original thread group (or in task context).
3216 if (!same_thread_group(req->task, current) || !in_task())
3221 static bool io_resubmit_prep(struct io_kiocb *req)
3225 static bool io_rw_should_reissue(struct io_kiocb *req)
3231 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3233 struct io_rw *rw = io_kiocb_to_cmd(req);
3235 if (rw->kiocb.ki_flags & IOCB_WRITE) {
3236 kiocb_end_write(req);
3237 fsnotify_modify(req->file);
3239 fsnotify_access(req->file);
3241 if (unlikely(res != req->cqe.res)) {
3242 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3243 io_rw_should_reissue(req)) {
3244 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3253 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3255 int res = req->cqe.res;
3258 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3259 io_req_add_compl_list(req);
3261 io_req_complete_post(req, res,
3262 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3266 static void __io_complete_rw(struct io_kiocb *req, long res,
3267 unsigned int issue_flags)
3269 if (__io_complete_rw_common(req, res))
3271 __io_req_complete(req, issue_flags, req->cqe.res,
3272 io_put_kbuf(req, issue_flags));
3275 static void io_complete_rw(struct kiocb *kiocb, long res)
3277 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
3278 struct io_kiocb *req = cmd_to_io_kiocb(rw);
3280 if (__io_complete_rw_common(req, res))
3283 req->io_task_work.func = io_req_task_complete;
3284 io_req_task_prio_work_add(req);
3287 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3289 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
3290 struct io_kiocb *req = cmd_to_io_kiocb(rw);
3292 if (kiocb->ki_flags & IOCB_WRITE)
3293 kiocb_end_write(req);
3294 if (unlikely(res != req->cqe.res)) {
3295 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3296 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3302 /* order with io_iopoll_complete() checking ->iopoll_completed */
3303 smp_store_release(&req->iopoll_completed, 1);
3307 * After the iocb has been issued, it's safe to be found on the poll list.
3308 * Adding the kiocb to the list AFTER submission ensures that we don't
3309 * find it from a io_do_iopoll() thread before the issuer is done
3310 * accessing the kiocb cookie.
3312 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3314 struct io_ring_ctx *ctx = req->ctx;
3315 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3317 /* workqueue context doesn't hold uring_lock, grab it now */
3318 if (unlikely(needs_lock))
3319 mutex_lock(&ctx->uring_lock);
3322 * Track whether we have multiple files in our lists. This will impact
3323 * how we do polling eventually, not spinning if we're on potentially
3324 * different devices.
3326 if (wq_list_empty(&ctx->iopoll_list)) {
3327 ctx->poll_multi_queue = false;
3328 } else if (!ctx->poll_multi_queue) {
3329 struct io_kiocb *list_req;
3331 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3333 if (list_req->file != req->file)
3334 ctx->poll_multi_queue = true;
3338 * For fast devices, IO may have already completed. If it has, add
3339 * it to the front so we find it first.
3341 if (READ_ONCE(req->iopoll_completed))
3342 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3344 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3346 if (unlikely(needs_lock)) {
3348 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3349 * in sq thread task context or in io worker task context. If
3350 * current task context is sq thread, we don't need to check
3351 * whether should wake up sq thread.
3353 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3354 wq_has_sleeper(&ctx->sq_data->wait))
3355 wake_up(&ctx->sq_data->wait);
3357 mutex_unlock(&ctx->uring_lock);
3361 static bool io_bdev_nowait(struct block_device *bdev)
3363 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3367 * If we tracked the file through the SCM inflight mechanism, we could support
3368 * any file. For now, just ensure that anything potentially problematic is done
3371 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3373 if (S_ISBLK(mode)) {
3374 if (IS_ENABLED(CONFIG_BLOCK) &&
3375 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3381 if (S_ISREG(mode)) {
3382 if (IS_ENABLED(CONFIG_BLOCK) &&
3383 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3384 file->f_op != &io_uring_fops)
3389 /* any ->read/write should understand O_NONBLOCK */
3390 if (file->f_flags & O_NONBLOCK)
3392 return file->f_mode & FMODE_NOWAIT;
3396 * If we tracked the file through the SCM inflight mechanism, we could support
3397 * any file. For now, just ensure that anything potentially problematic is done
3400 static unsigned int io_file_get_flags(struct file *file)
3402 umode_t mode = file_inode(file)->i_mode;
3403 unsigned int res = 0;
3407 if (__io_file_supports_nowait(file, mode))
3409 if (io_file_need_scm(file))
3414 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3416 return req->flags & REQ_F_SUPPORT_NOWAIT;
3419 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3421 struct io_rw *rw = io_kiocb_to_cmd(req);
3425 rw->kiocb.ki_pos = READ_ONCE(sqe->off);
3426 /* used for fixed read/write too - just read unconditionally */
3427 req->buf_index = READ_ONCE(sqe->buf_index);
3429 if (req->opcode == IORING_OP_READ_FIXED ||
3430 req->opcode == IORING_OP_WRITE_FIXED) {
3431 struct io_ring_ctx *ctx = req->ctx;
3434 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3436 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3437 req->imu = ctx->user_bufs[index];
3438 io_req_set_rsrc_node(req, ctx, 0);
3441 ioprio = READ_ONCE(sqe->ioprio);
3443 ret = ioprio_check_cap(ioprio);
3447 rw->kiocb.ki_ioprio = ioprio;
3449 rw->kiocb.ki_ioprio = get_current_ioprio();
3452 rw->addr = READ_ONCE(sqe->addr);
3453 rw->len = READ_ONCE(sqe->len);
3454 rw->flags = READ_ONCE(sqe->rw_flags);
3458 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3464 case -ERESTARTNOINTR:
3465 case -ERESTARTNOHAND:
3466 case -ERESTART_RESTARTBLOCK:
3468 * We can't just restart the syscall, since previously
3469 * submitted sqes may already be in progress. Just fail this
3475 kiocb->ki_complete(kiocb, ret);
3479 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3481 struct io_rw *rw = io_kiocb_to_cmd(req);
3483 if (rw->kiocb.ki_pos != -1)
3484 return &rw->kiocb.ki_pos;
3486 if (!(req->file->f_mode & FMODE_STREAM)) {
3487 req->flags |= REQ_F_CUR_POS;
3488 rw->kiocb.ki_pos = req->file->f_pos;
3489 return &rw->kiocb.ki_pos;
3492 rw->kiocb.ki_pos = 0;
3496 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3497 unsigned int issue_flags)
3499 struct io_async_rw *io = req->async_data;
3500 struct io_rw *rw = io_kiocb_to_cmd(req);
3502 /* add previously done IO, if any */
3503 if (req_has_async_data(req) && io->bytes_done > 0) {
3505 ret = io->bytes_done;
3507 ret += io->bytes_done;
3510 if (req->flags & REQ_F_CUR_POS)
3511 req->file->f_pos = rw->kiocb.ki_pos;
3512 if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
3513 __io_complete_rw(req, ret, issue_flags);
3515 io_rw_done(&rw->kiocb, ret);
3517 if (req->flags & REQ_F_REISSUE) {
3518 req->flags &= ~REQ_F_REISSUE;
3519 if (io_resubmit_prep(req))
3520 io_req_task_queue_reissue(req);
3522 io_req_task_queue_fail(req, ret);
3526 static int __io_import_fixed(struct io_kiocb *req, int ddir,
3527 struct iov_iter *iter, struct io_mapped_ubuf *imu)
3529 struct io_rw *rw = io_kiocb_to_cmd(req);
3530 size_t len = rw->len;
3531 u64 buf_end, buf_addr = rw->addr;
3534 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3536 /* not inside the mapped region */
3537 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3541 * May not be a start of buffer, set size appropriately
3542 * and advance us to the beginning.
3544 offset = buf_addr - imu->ubuf;
3545 iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
3549 * Don't use iov_iter_advance() here, as it's really slow for
3550 * using the latter parts of a big fixed buffer - it iterates
3551 * over each segment manually. We can cheat a bit here, because
3554 * 1) it's a BVEC iter, we set it up
3555 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3556 * first and last bvec
3558 * So just find our index, and adjust the iterator afterwards.
3559 * If the offset is within the first bvec (or the whole first
3560 * bvec, just use iov_iter_advance(). This makes it easier
3561 * since we can just skip the first segment, which may not
3562 * be PAGE_SIZE aligned.
3564 const struct bio_vec *bvec = imu->bvec;
3566 if (offset <= bvec->bv_len) {
3567 iov_iter_advance(iter, offset);
3569 unsigned long seg_skip;
3571 /* skip first vec */
3572 offset -= bvec->bv_len;
3573 seg_skip = 1 + (offset >> PAGE_SHIFT);
3575 iter->bvec = bvec + seg_skip;
3576 iter->nr_segs -= seg_skip;
3577 iter->count -= bvec->bv_len + offset;
3578 iter->iov_offset = offset & ~PAGE_MASK;
3585 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3586 unsigned int issue_flags)
3588 if (WARN_ON_ONCE(!req->imu))
3590 return __io_import_fixed(req, rw, iter, req->imu);
3593 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3594 struct io_buffer_list *bl, unsigned int bgid)
3597 if (bgid < BGID_ARRAY)
3600 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3603 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3604 struct io_buffer_list *bl)
3606 if (!list_empty(&bl->buf_list)) {
3607 struct io_buffer *kbuf;
3609 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3610 list_del(&kbuf->list);
3611 if (*len > kbuf->len)
3613 req->flags |= REQ_F_BUFFER_SELECTED;
3615 req->buf_index = kbuf->bid;
3616 return u64_to_user_ptr(kbuf->addr);
3621 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3622 struct io_buffer_list *bl,
3623 unsigned int issue_flags)
3625 struct io_uring_buf_ring *br = bl->buf_ring;
3626 struct io_uring_buf *buf;
3627 __u16 head = bl->head;
3629 if (unlikely(smp_load_acquire(&br->tail) == head))
3633 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3634 buf = &br->bufs[head];
3636 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3637 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3638 buf = page_address(bl->buf_pages[index]);
3641 if (*len > buf->len)
3643 req->flags |= REQ_F_BUFFER_RING;
3645 req->buf_index = buf->bid;
3647 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3649 * If we came in unlocked, we have no choice but to consume the
3650 * buffer here. This does mean it'll be pinned until the IO
3651 * completes. But coming in unlocked means we're in io-wq
3652 * context, hence there should be no further retry. For the
3653 * locked case, the caller must ensure to call the commit when
3654 * the transfer completes (or if we get -EAGAIN and must poll
3657 req->buf_list = NULL;
3660 return u64_to_user_ptr(buf->addr);
3663 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3664 unsigned int issue_flags)
3666 struct io_ring_ctx *ctx = req->ctx;
3667 struct io_buffer_list *bl;
3668 void __user *ret = NULL;
3670 io_ring_submit_lock(req->ctx, issue_flags);
3672 bl = io_buffer_get_list(ctx, req->buf_index);
3674 if (bl->buf_nr_pages)
3675 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3677 ret = io_provided_buffer_select(req, len, bl);
3679 io_ring_submit_unlock(req->ctx, issue_flags);
3683 #ifdef CONFIG_COMPAT
3684 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3685 unsigned int issue_flags)
3687 struct io_rw *rw = io_kiocb_to_cmd(req);
3688 struct compat_iovec __user *uiov;
3689 compat_ssize_t clen;
3693 uiov = u64_to_user_ptr(rw->addr);
3694 if (!access_ok(uiov, sizeof(*uiov)))
3696 if (__get_user(clen, &uiov->iov_len))
3702 buf = io_buffer_select(req, &len, issue_flags);
3705 rw->addr = (unsigned long) buf;
3706 iov[0].iov_base = buf;
3707 rw->len = iov[0].iov_len = (compat_size_t) len;
3712 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3713 unsigned int issue_flags)
3715 struct io_rw *rw = io_kiocb_to_cmd(req);
3716 struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
3720 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3723 len = iov[0].iov_len;
3726 buf = io_buffer_select(req, &len, issue_flags);
3729 rw->addr = (unsigned long) buf;
3730 iov[0].iov_base = buf;
3731 rw->len = iov[0].iov_len = len;
3735 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3736 unsigned int issue_flags)
3738 struct io_rw *rw = io_kiocb_to_cmd(req);
3740 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3741 iov[0].iov_base = u64_to_user_ptr(rw->addr);
3742 iov[0].iov_len = rw->len;
3748 #ifdef CONFIG_COMPAT
3749 if (req->ctx->compat)
3750 return io_compat_import(req, iov, issue_flags);
3753 return __io_iov_buffer_select(req, iov, issue_flags);
3756 static inline bool io_do_buffer_select(struct io_kiocb *req)
3758 if (!(req->flags & REQ_F_BUFFER_SELECT))
3760 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3763 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
3764 struct io_rw_state *s,
3765 unsigned int issue_flags)
3767 struct io_rw *rw = io_kiocb_to_cmd(req);
3768 struct iov_iter *iter = &s->iter;
3769 u8 opcode = req->opcode;
3770 struct iovec *iovec;
3775 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3776 ret = io_import_fixed(req, ddir, iter, issue_flags);
3778 return ERR_PTR(ret);
3782 buf = u64_to_user_ptr(rw->addr);
3785 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3786 if (io_do_buffer_select(req)) {
3787 buf = io_buffer_select(req, &sqe_len, issue_flags);
3789 return ERR_PTR(-ENOBUFS);
3790 rw->addr = (unsigned long) buf;
3794 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
3796 return ERR_PTR(ret);
3800 iovec = s->fast_iov;
3801 if (req->flags & REQ_F_BUFFER_SELECT) {
3802 ret = io_iov_buffer_select(req, iovec, issue_flags);
3804 return ERR_PTR(ret);
3805 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
3809 ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3811 if (unlikely(ret < 0))
3812 return ERR_PTR(ret);
3816 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3817 struct iovec **iovec, struct io_rw_state *s,
3818 unsigned int issue_flags)
3820 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3821 if (unlikely(IS_ERR(*iovec)))
3822 return PTR_ERR(*iovec);
3824 iov_iter_save_state(&s->iter, &s->iter_state);
3828 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3830 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3834 * For files that don't have ->read_iter() and ->write_iter(), handle them
3835 * by looping over ->read() or ->write() manually.
3837 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
3839 struct kiocb *kiocb = &rw->kiocb;
3840 struct file *file = kiocb->ki_filp;
3845 * Don't support polled IO through this interface, and we can't
3846 * support non-blocking either. For the latter, this just causes
3847 * the kiocb to be handled from an async context.
3849 if (kiocb->ki_flags & IOCB_HIPRI)
3851 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3852 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3855 ppos = io_kiocb_ppos(kiocb);
3857 while (iov_iter_count(iter)) {
3861 if (!iov_iter_is_bvec(iter)) {
3862 iovec = iov_iter_iovec(iter);
3864 iovec.iov_base = u64_to_user_ptr(rw->addr);
3865 iovec.iov_len = rw->len;
3869 nr = file->f_op->read(file, iovec.iov_base,
3870 iovec.iov_len, ppos);
3872 nr = file->f_op->write(file, iovec.iov_base,
3873 iovec.iov_len, ppos);
3882 if (!iov_iter_is_bvec(iter)) {
3883 iov_iter_advance(iter, nr);
3890 if (nr != iovec.iov_len)
3897 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3898 const struct iovec *fast_iov, struct iov_iter *iter)
3900 struct io_async_rw *io = req->async_data;
3902 memcpy(&io->s.iter, iter, sizeof(*iter));
3903 io->free_iovec = iovec;
3905 /* can only be fixed buffers, no need to do anything */
3906 if (iov_iter_is_bvec(iter))
3909 unsigned iov_off = 0;
3911 io->s.iter.iov = io->s.fast_iov;
3912 if (iter->iov != fast_iov) {
3913 iov_off = iter->iov - fast_iov;
3914 io->s.iter.iov += iov_off;
3916 if (io->s.fast_iov != fast_iov)
3917 memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
3918 sizeof(struct iovec) * iter->nr_segs);
3920 req->flags |= REQ_F_NEED_CLEANUP;
3924 static inline bool io_alloc_async_data(struct io_kiocb *req)
3926 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3927 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3928 if (req->async_data) {
3929 req->flags |= REQ_F_ASYNC_DATA;
3935 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3936 struct io_rw_state *s, bool force)
3938 if (!force && !io_op_defs[req->opcode].prep_async)
3940 if (!req_has_async_data(req)) {
3941 struct io_async_rw *iorw;
3943 if (io_alloc_async_data(req)) {
3948 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3949 iorw = req->async_data;
3950 /* we've copied and mapped the iter, ensure state is saved */
3951 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3956 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3958 struct io_async_rw *iorw = req->async_data;
3962 /* submission path, ->uring_lock should already be taken */
3963 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3964 if (unlikely(ret < 0))
3967 iorw->bytes_done = 0;
3968 iorw->free_iovec = iov;
3970 req->flags |= REQ_F_NEED_CLEANUP;
3974 static int io_readv_prep_async(struct io_kiocb *req)
3976 return io_rw_prep_async(req, READ);
3979 static int io_writev_prep_async(struct io_kiocb *req)
3981 return io_rw_prep_async(req, WRITE);
3985 * This is our waitqueue callback handler, registered through __folio_lock_async()
3986 * when we initially tried to do the IO with the iocb armed our waitqueue.
3987 * This gets called when the page is unlocked, and we generally expect that to
3988 * happen when the page IO is completed and the page is now uptodate. This will
3989 * queue a task_work based retry of the operation, attempting to copy the data
3990 * again. If the latter fails because the page was NOT uptodate, then we will
3991 * do a thread based blocking retry of the operation. That's the unexpected
3994 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3995 int sync, void *arg)
3997 struct wait_page_queue *wpq;
3998 struct io_kiocb *req = wait->private;
3999 struct io_rw *rw = io_kiocb_to_cmd(req);
4000 struct wait_page_key *key = arg;
4002 wpq = container_of(wait, struct wait_page_queue, wait);
4004 if (!wake_page_match(wpq, key))
4007 rw->kiocb.ki_flags &= ~IOCB_WAITQ;
4008 list_del_init(&wait->entry);
4009 io_req_task_queue(req);
4014 * This controls whether a given IO request should be armed for async page
4015 * based retry. If we return false here, the request is handed to the async
4016 * worker threads for retry. If we're doing buffered reads on a regular file,
4017 * we prepare a private wait_page_queue entry and retry the operation. This
4018 * will either succeed because the page is now uptodate and unlocked, or it
4019 * will register a callback when the page is unlocked at IO completion. Through
4020 * that callback, io_uring uses task_work to setup a retry of the operation.
4021 * That retry will attempt the buffered read again. The retry will generally
4022 * succeed, or in rare cases where it fails, we then fall back to using the
4023 * async worker threads for a blocking retry.
4025 static bool io_rw_should_retry(struct io_kiocb *req)
4027 struct io_async_rw *io = req->async_data;
4028 struct wait_page_queue *wait = &io->wpq;
4029 struct io_rw *rw = io_kiocb_to_cmd(req);
4030 struct kiocb *kiocb = &rw->kiocb;
4032 /* never retry for NOWAIT, we just complete with -EAGAIN */
4033 if (req->flags & REQ_F_NOWAIT)
4036 /* Only for buffered IO */
4037 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4041 * just use poll if we can, and don't attempt if the fs doesn't
4042 * support callback based unlocks
4044 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4047 wait->wait.func = io_async_buf_func;
4048 wait->wait.private = req;
4049 wait->wait.flags = 0;
4050 INIT_LIST_HEAD(&wait->wait.entry);
4051 kiocb->ki_flags |= IOCB_WAITQ;
4052 kiocb->ki_flags &= ~IOCB_NOWAIT;
4053 kiocb->ki_waitq = wait;
4057 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
4059 struct file *file = rw->kiocb.ki_filp;
4061 if (likely(file->f_op->read_iter))
4062 return call_read_iter(file, &rw->kiocb, iter);
4063 else if (file->f_op->read)
4064 return loop_rw_iter(READ, rw, iter);
4069 static bool need_read_all(struct io_kiocb *req)
4071 return req->flags & REQ_F_ISREG ||
4072 S_ISBLK(file_inode(req->file)->i_mode);
4075 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4077 struct io_rw *rw = io_kiocb_to_cmd(req);
4078 struct kiocb *kiocb = &rw->kiocb;
4079 struct io_ring_ctx *ctx = req->ctx;
4080 struct file *file = req->file;
4083 if (unlikely(!file || !(file->f_mode & mode)))
4086 if (!io_req_ffs_set(req))
4087 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4089 kiocb->ki_flags = iocb_flags(file);
4090 ret = kiocb_set_rw_flags(kiocb, rw->flags);
4095 * If the file is marked O_NONBLOCK, still allow retry for it if it
4096 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4097 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4099 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4100 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4101 req->flags |= REQ_F_NOWAIT;
4103 if (ctx->flags & IORING_SETUP_IOPOLL) {
4104 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4107 kiocb->private = NULL;
4108 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4109 kiocb->ki_complete = io_complete_rw_iopoll;
4110 req->iopoll_completed = 0;
4112 if (kiocb->ki_flags & IOCB_HIPRI)
4114 kiocb->ki_complete = io_complete_rw;
4120 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4122 struct io_rw *rw = io_kiocb_to_cmd(req);
4123 struct io_rw_state __s, *s = &__s;
4124 struct iovec *iovec;
4125 struct kiocb *kiocb = &rw->kiocb;
4126 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4127 struct io_async_rw *io;
4131 if (!req_has_async_data(req)) {
4132 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4133 if (unlikely(ret < 0))
4136 io = req->async_data;
4140 * Safe and required to re-import if we're using provided
4141 * buffers, as we dropped the selected one before retry.
4143 if (io_do_buffer_select(req)) {
4144 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4145 if (unlikely(ret < 0))
4150 * We come here from an earlier attempt, restore our state to
4151 * match in case it doesn't. It's cheap enough that we don't
4152 * need to make this conditional.
4154 iov_iter_restore(&s->iter, &s->iter_state);
4157 ret = io_rw_init_file(req, FMODE_READ);
4158 if (unlikely(ret)) {
4162 req->cqe.res = iov_iter_count(&s->iter);
4164 if (force_nonblock) {
4165 /* If the file doesn't support async, just async punt */
4166 if (unlikely(!io_file_supports_nowait(req))) {
4167 ret = io_setup_async_rw(req, iovec, s, true);
4168 return ret ?: -EAGAIN;
4170 kiocb->ki_flags |= IOCB_NOWAIT;
4172 /* Ensure we clear previously set non-block flag */
4173 kiocb->ki_flags &= ~IOCB_NOWAIT;
4176 ppos = io_kiocb_update_pos(req);
4178 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4179 if (unlikely(ret)) {
4184 ret = io_iter_do_read(rw, &s->iter);
4186 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4187 req->flags &= ~REQ_F_REISSUE;
4188 /* if we can poll, just do that */
4189 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4191 /* IOPOLL retry should happen for io-wq threads */
4192 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4194 /* no retry on NONBLOCK nor RWF_NOWAIT */
4195 if (req->flags & REQ_F_NOWAIT)
4198 } else if (ret == -EIOCBQUEUED) {
4200 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4201 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4202 /* read all, failed, already did sync or don't want to retry */
4207 * Don't depend on the iter state matching what was consumed, or being
4208 * untouched in case of error. Restore it and we'll advance it
4209 * manually if we need to.
4211 iov_iter_restore(&s->iter, &s->iter_state);
4213 ret2 = io_setup_async_rw(req, iovec, s, true);
4218 io = req->async_data;
4221 * Now use our persistent iterator and state, if we aren't already.
4222 * We've restored and mapped the iter to match.
4227 * We end up here because of a partial read, either from
4228 * above or inside this loop. Advance the iter by the bytes
4229 * that were consumed.
4231 iov_iter_advance(&s->iter, ret);
4232 if (!iov_iter_count(&s->iter))
4234 io->bytes_done += ret;
4235 iov_iter_save_state(&s->iter, &s->iter_state);
4237 /* if we can retry, do so with the callbacks armed */
4238 if (!io_rw_should_retry(req)) {
4239 kiocb->ki_flags &= ~IOCB_WAITQ;
4244 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4245 * we get -EIOCBQUEUED, then we'll get a notification when the
4246 * desired page gets unlocked. We can also get a partial read
4247 * here, and if we do, then just retry at the new offset.
4249 ret = io_iter_do_read(rw, &s->iter);
4250 if (ret == -EIOCBQUEUED)
4252 /* we got some bytes, but not all. retry. */
4253 kiocb->ki_flags &= ~IOCB_WAITQ;
4254 iov_iter_restore(&s->iter, &s->iter_state);
4257 kiocb_done(req, ret, issue_flags);
4259 /* it's faster to check here then delegate to kfree */
4265 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4267 struct io_rw *rw = io_kiocb_to_cmd(req);
4268 struct io_rw_state __s, *s = &__s;
4269 struct iovec *iovec;
4270 struct kiocb *kiocb = &rw->kiocb;
4271 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4275 if (!req_has_async_data(req)) {
4276 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4277 if (unlikely(ret < 0))
4280 struct io_async_rw *io = req->async_data;
4283 iov_iter_restore(&s->iter, &s->iter_state);
4286 ret = io_rw_init_file(req, FMODE_WRITE);
4287 if (unlikely(ret)) {
4291 req->cqe.res = iov_iter_count(&s->iter);
4293 if (force_nonblock) {
4294 /* If the file doesn't support async, just async punt */
4295 if (unlikely(!io_file_supports_nowait(req)))
4298 /* file path doesn't support NOWAIT for non-direct_IO */
4299 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4300 (req->flags & REQ_F_ISREG))
4303 kiocb->ki_flags |= IOCB_NOWAIT;
4305 /* Ensure we clear previously set non-block flag */
4306 kiocb->ki_flags &= ~IOCB_NOWAIT;
4309 ppos = io_kiocb_update_pos(req);
4311 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4316 * Open-code file_start_write here to grab freeze protection,
4317 * which will be released by another thread in
4318 * io_complete_rw(). Fool lockdep by telling it the lock got
4319 * released so that it doesn't complain about the held lock when
4320 * we return to userspace.
4322 if (req->flags & REQ_F_ISREG) {
4323 sb_start_write(file_inode(req->file)->i_sb);
4324 __sb_writers_release(file_inode(req->file)->i_sb,
4327 kiocb->ki_flags |= IOCB_WRITE;
4329 if (likely(req->file->f_op->write_iter))
4330 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4331 else if (req->file->f_op->write)
4332 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
4336 if (req->flags & REQ_F_REISSUE) {
4337 req->flags &= ~REQ_F_REISSUE;
4342 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4343 * retry them without IOCB_NOWAIT.
4345 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4347 /* no retry on NONBLOCK nor RWF_NOWAIT */
4348 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4350 if (!force_nonblock || ret2 != -EAGAIN) {
4351 /* IOPOLL retry should happen for io-wq threads */
4352 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4355 kiocb_done(req, ret2, issue_flags);
4358 iov_iter_restore(&s->iter, &s->iter_state);
4359 ret = io_setup_async_rw(req, iovec, s, false);
4360 return ret ?: -EAGAIN;
4363 /* it's reportedly faster than delegating the null check to kfree() */
4369 static int io_renameat_prep(struct io_kiocb *req,
4370 const struct io_uring_sqe *sqe)
4372 struct io_rename *ren = &req->rename;
4373 const char __user *oldf, *newf;
4375 if (sqe->buf_index || sqe->splice_fd_in)
4377 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4380 ren->old_dfd = READ_ONCE(sqe->fd);
4381 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4382 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4383 ren->new_dfd = READ_ONCE(sqe->len);
4384 ren->flags = READ_ONCE(sqe->rename_flags);
4386 ren->oldpath = getname(oldf);
4387 if (IS_ERR(ren->oldpath))
4388 return PTR_ERR(ren->oldpath);
4390 ren->newpath = getname(newf);
4391 if (IS_ERR(ren->newpath)) {
4392 putname(ren->oldpath);
4393 return PTR_ERR(ren->newpath);
4396 req->flags |= REQ_F_NEED_CLEANUP;
4400 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4402 struct io_rename *ren = &req->rename;
4405 if (issue_flags & IO_URING_F_NONBLOCK)
4408 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4409 ren->newpath, ren->flags);
4411 req->flags &= ~REQ_F_NEED_CLEANUP;
4412 io_req_complete(req, ret);
4416 static inline void __io_xattr_finish(struct io_kiocb *req)
4418 struct io_xattr *ix = &req->xattr;
4421 putname(ix->filename);
4423 kfree(ix->ctx.kname);
4424 kvfree(ix->ctx.kvalue);
4427 static void io_xattr_finish(struct io_kiocb *req, int ret)
4429 req->flags &= ~REQ_F_NEED_CLEANUP;
4431 __io_xattr_finish(req);
4432 io_req_complete(req, ret);
4435 static int __io_getxattr_prep(struct io_kiocb *req,
4436 const struct io_uring_sqe *sqe)
4438 struct io_xattr *ix = &req->xattr;
4439 const char __user *name;
4442 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4445 ix->filename = NULL;
4446 ix->ctx.kvalue = NULL;
4447 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4448 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4449 ix->ctx.size = READ_ONCE(sqe->len);
4450 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4455 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4459 ret = strncpy_from_user(ix->ctx.kname->name, name,
4460 sizeof(ix->ctx.kname->name));
4461 if (!ret || ret == sizeof(ix->ctx.kname->name))
4464 kfree(ix->ctx.kname);
4468 req->flags |= REQ_F_NEED_CLEANUP;
4472 static int io_fgetxattr_prep(struct io_kiocb *req,
4473 const struct io_uring_sqe *sqe)
4475 return __io_getxattr_prep(req, sqe);
4478 static int io_getxattr_prep(struct io_kiocb *req,
4479 const struct io_uring_sqe *sqe)
4481 struct io_xattr *ix = &req->xattr;
4482 const char __user *path;
4485 ret = __io_getxattr_prep(req, sqe);
4489 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4491 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4492 if (IS_ERR(ix->filename)) {
4493 ret = PTR_ERR(ix->filename);
4494 ix->filename = NULL;
4500 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4502 struct io_xattr *ix = &req->xattr;
4505 if (issue_flags & IO_URING_F_NONBLOCK)
4508 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4509 req->file->f_path.dentry,
4512 io_xattr_finish(req, ret);
4516 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4518 struct io_xattr *ix = &req->xattr;
4519 unsigned int lookup_flags = LOOKUP_FOLLOW;
4523 if (issue_flags & IO_URING_F_NONBLOCK)
4527 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4529 ret = do_getxattr(mnt_user_ns(path.mnt),
4534 if (retry_estale(ret, lookup_flags)) {
4535 lookup_flags |= LOOKUP_REVAL;
4540 io_xattr_finish(req, ret);
4544 static int __io_setxattr_prep(struct io_kiocb *req,
4545 const struct io_uring_sqe *sqe)
4547 struct io_xattr *ix = &req->xattr;
4548 const char __user *name;
4551 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4554 ix->filename = NULL;
4555 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4556 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4557 ix->ctx.kvalue = NULL;
4558 ix->ctx.size = READ_ONCE(sqe->len);
4559 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4561 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4565 ret = setxattr_copy(name, &ix->ctx);
4567 kfree(ix->ctx.kname);
4571 req->flags |= REQ_F_NEED_CLEANUP;
4575 static int io_setxattr_prep(struct io_kiocb *req,
4576 const struct io_uring_sqe *sqe)
4578 struct io_xattr *ix = &req->xattr;
4579 const char __user *path;
4582 ret = __io_setxattr_prep(req, sqe);
4586 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4588 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4589 if (IS_ERR(ix->filename)) {
4590 ret = PTR_ERR(ix->filename);
4591 ix->filename = NULL;
4597 static int io_fsetxattr_prep(struct io_kiocb *req,
4598 const struct io_uring_sqe *sqe)
4600 return __io_setxattr_prep(req, sqe);
4603 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4606 struct io_xattr *ix = &req->xattr;
4609 ret = mnt_want_write(path->mnt);
4611 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4612 mnt_drop_write(path->mnt);
4618 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4622 if (issue_flags & IO_URING_F_NONBLOCK)
4625 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4626 io_xattr_finish(req, ret);
4631 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4633 struct io_xattr *ix = &req->xattr;
4634 unsigned int lookup_flags = LOOKUP_FOLLOW;
4638 if (issue_flags & IO_URING_F_NONBLOCK)
4642 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4644 ret = __io_setxattr(req, issue_flags, &path);
4646 if (retry_estale(ret, lookup_flags)) {
4647 lookup_flags |= LOOKUP_REVAL;
4652 io_xattr_finish(req, ret);
4656 static int io_unlinkat_prep(struct io_kiocb *req,
4657 const struct io_uring_sqe *sqe)
4659 struct io_unlink *un = &req->unlink;
4660 const char __user *fname;
4662 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4664 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4667 un->dfd = READ_ONCE(sqe->fd);
4669 un->flags = READ_ONCE(sqe->unlink_flags);
4670 if (un->flags & ~AT_REMOVEDIR)
4673 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4674 un->filename = getname(fname);
4675 if (IS_ERR(un->filename))
4676 return PTR_ERR(un->filename);
4678 req->flags |= REQ_F_NEED_CLEANUP;
4682 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4684 struct io_unlink *un = &req->unlink;
4687 if (issue_flags & IO_URING_F_NONBLOCK)
4690 if (un->flags & AT_REMOVEDIR)
4691 ret = do_rmdir(un->dfd, un->filename);
4693 ret = do_unlinkat(un->dfd, un->filename);
4695 req->flags &= ~REQ_F_NEED_CLEANUP;
4696 io_req_complete(req, ret);
4700 static int io_mkdirat_prep(struct io_kiocb *req,
4701 const struct io_uring_sqe *sqe)
4703 struct io_mkdir *mkd = &req->mkdir;
4704 const char __user *fname;
4706 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4708 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4711 mkd->dfd = READ_ONCE(sqe->fd);
4712 mkd->mode = READ_ONCE(sqe->len);
4714 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4715 mkd->filename = getname(fname);
4716 if (IS_ERR(mkd->filename))
4717 return PTR_ERR(mkd->filename);
4719 req->flags |= REQ_F_NEED_CLEANUP;
4723 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4725 struct io_mkdir *mkd = &req->mkdir;
4728 if (issue_flags & IO_URING_F_NONBLOCK)
4731 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4733 req->flags &= ~REQ_F_NEED_CLEANUP;
4734 io_req_complete(req, ret);
4738 static int io_symlinkat_prep(struct io_kiocb *req,
4739 const struct io_uring_sqe *sqe)
4741 struct io_symlink *sl = &req->symlink;
4742 const char __user *oldpath, *newpath;
4744 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4746 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4749 sl->new_dfd = READ_ONCE(sqe->fd);
4750 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4751 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4753 sl->oldpath = getname(oldpath);
4754 if (IS_ERR(sl->oldpath))
4755 return PTR_ERR(sl->oldpath);
4757 sl->newpath = getname(newpath);
4758 if (IS_ERR(sl->newpath)) {
4759 putname(sl->oldpath);
4760 return PTR_ERR(sl->newpath);
4763 req->flags |= REQ_F_NEED_CLEANUP;
4767 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4769 struct io_symlink *sl = &req->symlink;
4772 if (issue_flags & IO_URING_F_NONBLOCK)
4775 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4777 req->flags &= ~REQ_F_NEED_CLEANUP;
4778 io_req_complete(req, ret);
4782 static int io_linkat_prep(struct io_kiocb *req,
4783 const struct io_uring_sqe *sqe)
4785 struct io_hardlink *lnk = &req->hardlink;
4786 const char __user *oldf, *newf;
4788 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4790 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4793 lnk->old_dfd = READ_ONCE(sqe->fd);
4794 lnk->new_dfd = READ_ONCE(sqe->len);
4795 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4796 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4797 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4799 lnk->oldpath = getname(oldf);
4800 if (IS_ERR(lnk->oldpath))
4801 return PTR_ERR(lnk->oldpath);
4803 lnk->newpath = getname(newf);
4804 if (IS_ERR(lnk->newpath)) {
4805 putname(lnk->oldpath);
4806 return PTR_ERR(lnk->newpath);
4809 req->flags |= REQ_F_NEED_CLEANUP;
4813 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4815 struct io_hardlink *lnk = &req->hardlink;
4818 if (issue_flags & IO_URING_F_NONBLOCK)
4821 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4822 lnk->newpath, lnk->flags);
4824 req->flags &= ~REQ_F_NEED_CLEANUP;
4825 io_req_complete(req, ret);
4829 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
4831 req->uring_cmd.task_work_cb(&req->uring_cmd);
4834 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
4835 void (*task_work_cb)(struct io_uring_cmd *))
4837 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4839 req->uring_cmd.task_work_cb = task_work_cb;
4840 req->io_task_work.func = io_uring_cmd_work;
4841 io_req_task_work_add(req);
4843 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
4845 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
4846 u64 extra1, u64 extra2)
4848 req->extra1 = extra1;
4849 req->extra2 = extra2;
4850 req->flags |= REQ_F_CQE32_INIT;
4854 * Called by consumers of io_uring_cmd, if they originally returned
4855 * -EIOCBQUEUED upon receiving the command.
4857 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
4859 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4864 if (req->ctx->flags & IORING_SETUP_CQE32)
4865 io_req_set_cqe32_extra(req, res2, 0);
4866 io_req_complete(req, ret);
4868 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
4870 static int io_uring_cmd_prep_async(struct io_kiocb *req)
4874 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
4876 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
4880 static int io_uring_cmd_prep(struct io_kiocb *req,
4881 const struct io_uring_sqe *sqe)
4883 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4885 if (sqe->rw_flags || sqe->__pad1)
4887 ioucmd->cmd = sqe->cmd;
4888 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
4892 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
4894 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4895 struct io_ring_ctx *ctx = req->ctx;
4896 struct file *file = req->file;
4899 if (!req->file->f_op->uring_cmd)
4902 if (ctx->flags & IORING_SETUP_SQE128)
4903 issue_flags |= IO_URING_F_SQE128;
4904 if (ctx->flags & IORING_SETUP_CQE32)
4905 issue_flags |= IO_URING_F_CQE32;
4906 if (ctx->flags & IORING_SETUP_IOPOLL)
4907 issue_flags |= IO_URING_F_IOPOLL;
4909 if (req_has_async_data(req))
4910 ioucmd->cmd = req->async_data;
4912 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
4913 if (ret == -EAGAIN) {
4914 if (!req_has_async_data(req)) {
4915 if (io_alloc_async_data(req))
4917 io_uring_cmd_prep_async(req);
4922 if (ret != -EIOCBQUEUED)
4923 io_uring_cmd_done(ioucmd, ret, 0);
4927 static int __io_splice_prep(struct io_kiocb *req,
4928 const struct io_uring_sqe *sqe)
4930 struct io_splice *sp = &req->splice;
4931 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4933 sp->len = READ_ONCE(sqe->len);
4934 sp->flags = READ_ONCE(sqe->splice_flags);
4935 if (unlikely(sp->flags & ~valid_flags))
4937 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4941 static int io_tee_prep(struct io_kiocb *req,
4942 const struct io_uring_sqe *sqe)
4944 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4946 return __io_splice_prep(req, sqe);
4949 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4951 struct io_splice *sp = &req->splice;
4952 struct file *out = sp->file_out;
4953 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4957 if (issue_flags & IO_URING_F_NONBLOCK)
4960 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4961 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4963 in = io_file_get_normal(req, sp->splice_fd_in);
4970 ret = do_tee(in, out, sp->len, flags);
4972 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4977 __io_req_complete(req, 0, ret, 0);
4981 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4983 struct io_splice *sp = &req->splice;
4985 sp->off_in = READ_ONCE(sqe->splice_off_in);
4986 sp->off_out = READ_ONCE(sqe->off);
4987 return __io_splice_prep(req, sqe);
4990 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4992 struct io_splice *sp = &req->splice;
4993 struct file *out = sp->file_out;
4994 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4995 loff_t *poff_in, *poff_out;
4999 if (issue_flags & IO_URING_F_NONBLOCK)
5002 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5003 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5005 in = io_file_get_normal(req, sp->splice_fd_in);
5011 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5012 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5015 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5017 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5022 __io_req_complete(req, 0, ret, 0);
5026 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5032 * IORING_OP_NOP just posts a completion event, nothing else.
5034 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5036 __io_req_complete(req, issue_flags, 0, 0);
5040 static int io_msg_ring_prep(struct io_kiocb *req,
5041 const struct io_uring_sqe *sqe)
5043 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5044 sqe->buf_index || sqe->personality))
5047 req->msg.user_data = READ_ONCE(sqe->off);
5048 req->msg.len = READ_ONCE(sqe->len);
5052 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5054 struct io_ring_ctx *target_ctx;
5055 struct io_msg *msg = &req->msg;
5060 if (req->file->f_op != &io_uring_fops)
5064 target_ctx = req->file->private_data;
5066 spin_lock(&target_ctx->completion_lock);
5067 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5068 io_commit_cqring(target_ctx);
5069 spin_unlock(&target_ctx->completion_lock);
5072 io_cqring_ev_posted(target_ctx);
5079 __io_req_complete(req, issue_flags, ret, 0);
5080 /* put file to avoid an attempt to IOPOLL the req */
5081 io_put_file(req->file);
5086 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5088 struct io_sync *sync = io_kiocb_to_cmd(req);
5090 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5093 sync->flags = READ_ONCE(sqe->fsync_flags);
5094 if (unlikely(sync->flags & ~IORING_FSYNC_DATASYNC))
5097 sync->off = READ_ONCE(sqe->off);
5098 sync->len = READ_ONCE(sqe->len);
5102 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5104 struct io_sync *sync = io_kiocb_to_cmd(req);
5105 loff_t end = sync->off + sync->len;
5108 /* fsync always requires a blocking context */
5109 if (issue_flags & IO_URING_F_NONBLOCK)
5112 ret = vfs_fsync_range(req->file, sync->off, end > 0 ? end : LLONG_MAX,
5113 sync->flags & IORING_FSYNC_DATASYNC);
5114 io_req_complete(req, ret);
5118 static int io_fallocate_prep(struct io_kiocb *req,
5119 const struct io_uring_sqe *sqe)
5121 struct io_sync *sync = io_kiocb_to_cmd(req);
5123 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5126 sync->off = READ_ONCE(sqe->off);
5127 sync->len = READ_ONCE(sqe->addr);
5128 sync->mode = READ_ONCE(sqe->len);
5132 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5134 struct io_sync *sync = io_kiocb_to_cmd(req);
5137 /* fallocate always requiring blocking context */
5138 if (issue_flags & IO_URING_F_NONBLOCK)
5140 ret = vfs_fallocate(req->file, sync->mode, sync->off, sync->len);
5142 fsnotify_modify(req->file);
5143 io_req_complete(req, ret);
5147 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5149 struct io_open *open = io_kiocb_to_cmd(req);
5150 const char __user *fname;
5153 if (unlikely(sqe->buf_index))
5155 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5158 /* open.how should be already initialised */
5159 if (!(open->how.flags & O_PATH) && force_o_largefile())
5160 open->how.flags |= O_LARGEFILE;
5162 open->dfd = READ_ONCE(sqe->fd);
5163 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5164 open->filename = getname(fname);
5165 if (IS_ERR(open->filename)) {
5166 ret = PTR_ERR(open->filename);
5167 open->filename = NULL;
5171 open->file_slot = READ_ONCE(sqe->file_index);
5172 if (open->file_slot && (open->how.flags & O_CLOEXEC))
5175 open->nofile = rlimit(RLIMIT_NOFILE);
5176 req->flags |= REQ_F_NEED_CLEANUP;
5180 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5182 struct io_open *open = io_kiocb_to_cmd(req);
5183 u64 mode = READ_ONCE(sqe->len);
5184 u64 flags = READ_ONCE(sqe->open_flags);
5186 open->how = build_open_how(flags, mode);
5187 return __io_openat_prep(req, sqe);
5190 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5192 struct io_open *open = io_kiocb_to_cmd(req);
5193 struct open_how __user *how;
5197 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5198 len = READ_ONCE(sqe->len);
5199 if (len < OPEN_HOW_SIZE_VER0)
5202 ret = copy_struct_from_user(&open->how, sizeof(open->how), how, len);
5206 return __io_openat_prep(req, sqe);
5209 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5211 struct io_file_table *table = &ctx->file_table;
5212 unsigned long nr = ctx->nr_user_files;
5216 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5220 if (!table->alloc_hint)
5223 nr = table->alloc_hint;
5224 table->alloc_hint = 0;
5231 * Note when io_fixed_fd_install() returns error value, it will ensure
5232 * fput() is called correspondingly.
5234 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5235 struct file *file, unsigned int file_slot)
5237 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5238 struct io_ring_ctx *ctx = req->ctx;
5241 io_ring_submit_lock(ctx, issue_flags);
5244 ret = io_file_bitmap_get(ctx);
5245 if (unlikely(ret < 0))
5252 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5253 if (!ret && alloc_slot)
5256 io_ring_submit_unlock(ctx, issue_flags);
5257 if (unlikely(ret < 0))
5262 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5264 struct io_open *open = io_kiocb_to_cmd(req);
5265 struct open_flags op;
5267 bool resolve_nonblock, nonblock_set;
5268 bool fixed = !!open->file_slot;
5271 ret = build_open_flags(&open->how, &op);
5274 nonblock_set = op.open_flag & O_NONBLOCK;
5275 resolve_nonblock = open->how.resolve & RESOLVE_CACHED;
5276 if (issue_flags & IO_URING_F_NONBLOCK) {
5278 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5279 * it'll always -EAGAIN
5281 if (open->how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5283 op.lookup_flags |= LOOKUP_CACHED;
5284 op.open_flag |= O_NONBLOCK;
5288 ret = __get_unused_fd_flags(open->how.flags, open->nofile);
5293 file = do_filp_open(open->dfd, open->filename, &op);
5296 * We could hang on to this 'fd' on retrying, but seems like
5297 * marginal gain for something that is now known to be a slower
5298 * path. So just put it, and we'll get a new one when we retry.
5303 ret = PTR_ERR(file);
5304 /* only retry if RESOLVE_CACHED wasn't already set by application */
5305 if (ret == -EAGAIN &&
5306 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5311 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5312 file->f_flags &= ~O_NONBLOCK;
5313 fsnotify_open(file);
5316 fd_install(ret, file);
5318 ret = io_fixed_fd_install(req, issue_flags, file,
5321 putname(open->filename);
5322 req->flags &= ~REQ_F_NEED_CLEANUP;
5325 __io_req_complete(req, issue_flags, ret, 0);
5329 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5331 return io_openat2(req, issue_flags);
5334 static int io_remove_buffers_prep(struct io_kiocb *req,
5335 const struct io_uring_sqe *sqe)
5337 struct io_provide_buf *p = &req->pbuf;
5340 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5344 tmp = READ_ONCE(sqe->fd);
5345 if (!tmp || tmp > USHRT_MAX)
5348 memset(p, 0, sizeof(*p));
5350 p->bgid = READ_ONCE(sqe->buf_group);
5354 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5355 struct io_buffer_list *bl, unsigned nbufs)
5359 /* shouldn't happen */
5363 if (bl->buf_nr_pages) {
5366 i = bl->buf_ring->tail - bl->head;
5367 for (j = 0; j < bl->buf_nr_pages; j++)
5368 unpin_user_page(bl->buf_pages[j]);
5369 kvfree(bl->buf_pages);
5370 bl->buf_pages = NULL;
5371 bl->buf_nr_pages = 0;
5372 /* make sure it's seen as empty */
5373 INIT_LIST_HEAD(&bl->buf_list);
5377 /* the head kbuf is the list itself */
5378 while (!list_empty(&bl->buf_list)) {
5379 struct io_buffer *nxt;
5381 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5382 list_del(&nxt->list);
5392 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5394 struct io_provide_buf *p = &req->pbuf;
5395 struct io_ring_ctx *ctx = req->ctx;
5396 struct io_buffer_list *bl;
5399 io_ring_submit_lock(ctx, issue_flags);
5402 bl = io_buffer_get_list(ctx, p->bgid);
5405 /* can't use provide/remove buffers command on mapped buffers */
5406 if (!bl->buf_nr_pages)
5407 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5412 /* complete before unlock, IOPOLL may need the lock */
5413 __io_req_complete(req, issue_flags, ret, 0);
5414 io_ring_submit_unlock(ctx, issue_flags);
5418 static int io_provide_buffers_prep(struct io_kiocb *req,
5419 const struct io_uring_sqe *sqe)
5421 unsigned long size, tmp_check;
5422 struct io_provide_buf *p = &req->pbuf;
5425 if (sqe->rw_flags || sqe->splice_fd_in)
5428 tmp = READ_ONCE(sqe->fd);
5429 if (!tmp || tmp > USHRT_MAX)
5432 p->addr = READ_ONCE(sqe->addr);
5433 p->len = READ_ONCE(sqe->len);
5435 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5438 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5441 size = (unsigned long)p->len * p->nbufs;
5442 if (!access_ok(u64_to_user_ptr(p->addr), size))
5445 p->bgid = READ_ONCE(sqe->buf_group);
5446 tmp = READ_ONCE(sqe->off);
5447 if (tmp > USHRT_MAX)
5453 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5455 struct io_buffer *buf;
5460 * Completions that don't happen inline (eg not under uring_lock) will
5461 * add to ->io_buffers_comp. If we don't have any free buffers, check
5462 * the completion list and splice those entries first.
5464 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5465 spin_lock(&ctx->completion_lock);
5466 if (!list_empty(&ctx->io_buffers_comp)) {
5467 list_splice_init(&ctx->io_buffers_comp,
5468 &ctx->io_buffers_cache);
5469 spin_unlock(&ctx->completion_lock);
5472 spin_unlock(&ctx->completion_lock);
5476 * No free buffers and no completion entries either. Allocate a new
5477 * page worth of buffer entries and add those to our freelist.
5479 page = alloc_page(GFP_KERNEL_ACCOUNT);
5483 list_add(&page->lru, &ctx->io_buffers_pages);
5485 buf = page_address(page);
5486 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5487 while (bufs_in_page) {
5488 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5496 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5497 struct io_buffer_list *bl)
5499 struct io_buffer *buf;
5500 u64 addr = pbuf->addr;
5501 int i, bid = pbuf->bid;
5503 for (i = 0; i < pbuf->nbufs; i++) {
5504 if (list_empty(&ctx->io_buffers_cache) &&
5505 io_refill_buffer_cache(ctx))
5507 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5509 list_move_tail(&buf->list, &bl->buf_list);
5511 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5513 buf->bgid = pbuf->bgid;
5519 return i ? 0 : -ENOMEM;
5522 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5526 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5531 for (i = 0; i < BGID_ARRAY; i++) {
5532 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5533 ctx->io_bl[i].bgid = i;
5539 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5541 struct io_provide_buf *p = &req->pbuf;
5542 struct io_ring_ctx *ctx = req->ctx;
5543 struct io_buffer_list *bl;
5546 io_ring_submit_lock(ctx, issue_flags);
5548 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5549 ret = io_init_bl_list(ctx);
5554 bl = io_buffer_get_list(ctx, p->bgid);
5555 if (unlikely(!bl)) {
5556 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5561 INIT_LIST_HEAD(&bl->buf_list);
5562 ret = io_buffer_add_list(ctx, bl, p->bgid);
5568 /* can't add buffers via this command for a mapped buffer ring */
5569 if (bl->buf_nr_pages) {
5574 ret = io_add_buffers(ctx, p, bl);
5578 /* complete before unlock, IOPOLL may need the lock */
5579 __io_req_complete(req, issue_flags, ret, 0);
5580 io_ring_submit_unlock(ctx, issue_flags);
5584 static int io_epoll_ctl_prep(struct io_kiocb *req,
5585 const struct io_uring_sqe *sqe)
5587 #if defined(CONFIG_EPOLL)
5588 if (sqe->buf_index || sqe->splice_fd_in)
5591 req->epoll.epfd = READ_ONCE(sqe->fd);
5592 req->epoll.op = READ_ONCE(sqe->len);
5593 req->epoll.fd = READ_ONCE(sqe->off);
5595 if (ep_op_has_event(req->epoll.op)) {
5596 struct epoll_event __user *ev;
5598 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5599 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5609 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5611 #if defined(CONFIG_EPOLL)
5612 struct io_epoll *ie = &req->epoll;
5614 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5616 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5617 if (force_nonblock && ret == -EAGAIN)
5622 __io_req_complete(req, issue_flags, ret, 0);
5629 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5631 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5632 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5635 req->madvise.addr = READ_ONCE(sqe->addr);
5636 req->madvise.len = READ_ONCE(sqe->len);
5637 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5644 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5646 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5647 struct io_madvise *ma = &req->madvise;
5650 if (issue_flags & IO_URING_F_NONBLOCK)
5653 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5654 io_req_complete(req, ret);
5661 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5663 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5666 req->fadvise.offset = READ_ONCE(sqe->off);
5667 req->fadvise.len = READ_ONCE(sqe->len);
5668 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5672 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5674 struct io_fadvise *fa = &req->fadvise;
5677 if (issue_flags & IO_URING_F_NONBLOCK) {
5678 switch (fa->advice) {
5679 case POSIX_FADV_NORMAL:
5680 case POSIX_FADV_RANDOM:
5681 case POSIX_FADV_SEQUENTIAL:
5688 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5691 __io_req_complete(req, issue_flags, ret, 0);
5695 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5697 const char __user *path;
5699 if (sqe->buf_index || sqe->splice_fd_in)
5701 if (req->flags & REQ_F_FIXED_FILE)
5704 req->statx.dfd = READ_ONCE(sqe->fd);
5705 req->statx.mask = READ_ONCE(sqe->len);
5706 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5707 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5708 req->statx.flags = READ_ONCE(sqe->statx_flags);
5710 req->statx.filename = getname_flags(path,
5711 getname_statx_lookup_flags(req->statx.flags),
5714 if (IS_ERR(req->statx.filename)) {
5715 int ret = PTR_ERR(req->statx.filename);
5717 req->statx.filename = NULL;
5721 req->flags |= REQ_F_NEED_CLEANUP;
5725 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5727 struct io_statx *ctx = &req->statx;
5730 if (issue_flags & IO_URING_F_NONBLOCK)
5733 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5735 io_req_complete(req, ret);
5739 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5741 struct io_close *close = io_kiocb_to_cmd(req);
5743 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5745 if (req->flags & REQ_F_FIXED_FILE)
5748 close->fd = READ_ONCE(sqe->fd);
5749 close->file_slot = READ_ONCE(sqe->file_index);
5750 if (close->file_slot && close->fd)
5756 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5758 struct files_struct *files = current->files;
5759 struct io_close *close = io_kiocb_to_cmd(req);
5760 struct fdtable *fdt;
5764 if (close->file_slot) {
5765 ret = io_close_fixed(req, issue_flags);
5769 spin_lock(&files->file_lock);
5770 fdt = files_fdtable(files);
5771 if (close->fd >= fdt->max_fds) {
5772 spin_unlock(&files->file_lock);
5775 file = rcu_dereference_protected(fdt->fd[close->fd],
5776 lockdep_is_held(&files->file_lock));
5777 if (!file || file->f_op == &io_uring_fops) {
5778 spin_unlock(&files->file_lock);
5782 /* if the file has a flush method, be safe and punt to async */
5783 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5784 spin_unlock(&files->file_lock);
5788 file = __close_fd_get_file(close->fd);
5789 spin_unlock(&files->file_lock);
5793 /* No ->flush() or already async, safely close from here */
5794 ret = filp_close(file, current->files);
5798 __io_req_complete(req, issue_flags, ret, 0);
5802 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5804 struct io_sync *sync = io_kiocb_to_cmd(req);
5806 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5809 sync->off = READ_ONCE(sqe->off);
5810 sync->len = READ_ONCE(sqe->len);
5811 sync->flags = READ_ONCE(sqe->sync_range_flags);
5815 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5817 struct io_sync *sync = io_kiocb_to_cmd(req);
5820 /* sync_file_range always requires a blocking context */
5821 if (issue_flags & IO_URING_F_NONBLOCK)
5824 ret = sync_file_range(req->file, sync->off, sync->len, sync->flags);
5825 io_req_complete(req, ret);
5829 #if defined(CONFIG_NET)
5830 static int io_shutdown_prep(struct io_kiocb *req,
5831 const struct io_uring_sqe *sqe)
5833 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
5835 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
5836 sqe->buf_index || sqe->splice_fd_in))
5839 shutdown->how = READ_ONCE(sqe->len);
5843 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
5845 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
5846 struct socket *sock;
5849 if (issue_flags & IO_URING_F_NONBLOCK)
5852 sock = sock_from_file(req->file);
5853 if (unlikely(!sock))
5856 ret = __sys_shutdown_sock(sock, shutdown->how);
5857 io_req_complete(req, ret);
5861 static bool io_net_retry(struct socket *sock, int flags)
5863 if (!(flags & MSG_WAITALL))
5865 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5868 static int io_setup_async_msg(struct io_kiocb *req,
5869 struct io_async_msghdr *kmsg)
5871 struct io_async_msghdr *async_msg = req->async_data;
5875 if (io_alloc_async_data(req)) {
5876 kfree(kmsg->free_iov);
5879 async_msg = req->async_data;
5880 req->flags |= REQ_F_NEED_CLEANUP;
5881 memcpy(async_msg, kmsg, sizeof(*kmsg));
5882 async_msg->msg.msg_name = &async_msg->addr;
5883 /* if were using fast_iov, set it to the new one */
5884 if (!async_msg->free_iov)
5885 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5890 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5891 struct io_async_msghdr *iomsg)
5893 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5895 iomsg->msg.msg_name = &iomsg->addr;
5896 iomsg->free_iov = iomsg->fast_iov;
5897 return sendmsg_copy_msghdr(&iomsg->msg, sr->umsg, sr->msg_flags,
5901 static int io_sendmsg_prep_async(struct io_kiocb *req)
5905 ret = io_sendmsg_copy_hdr(req, req->async_data);
5907 req->flags |= REQ_F_NEED_CLEANUP;
5911 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5913 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5915 if (unlikely(sqe->file_index || sqe->addr2))
5918 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5919 sr->len = READ_ONCE(sqe->len);
5920 sr->flags = READ_ONCE(sqe->ioprio);
5921 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5923 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5924 if (sr->msg_flags & MSG_DONTWAIT)
5925 req->flags |= REQ_F_NOWAIT;
5927 #ifdef CONFIG_COMPAT
5928 if (req->ctx->compat)
5929 sr->msg_flags |= MSG_CMSG_COMPAT;
5935 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5937 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5938 struct io_async_msghdr iomsg, *kmsg;
5939 struct socket *sock;
5944 sock = sock_from_file(req->file);
5945 if (unlikely(!sock))
5948 if (req_has_async_data(req)) {
5949 kmsg = req->async_data;
5951 ret = io_sendmsg_copy_hdr(req, &iomsg);
5957 if (!(req->flags & REQ_F_POLLED) &&
5958 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5959 return io_setup_async_msg(req, kmsg);
5961 flags = sr->msg_flags;
5962 if (issue_flags & IO_URING_F_NONBLOCK)
5963 flags |= MSG_DONTWAIT;
5964 if (flags & MSG_WAITALL)
5965 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5967 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5969 if (ret < min_ret) {
5970 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5971 return io_setup_async_msg(req, kmsg);
5972 if (ret == -ERESTARTSYS)
5974 if (ret > 0 && io_net_retry(sock, flags)) {
5976 req->flags |= REQ_F_PARTIAL_IO;
5977 return io_setup_async_msg(req, kmsg);
5981 /* fast path, check for non-NULL to avoid function call */
5983 kfree(kmsg->free_iov);
5984 req->flags &= ~REQ_F_NEED_CLEANUP;
5987 else if (sr->done_io)
5989 __io_req_complete(req, issue_flags, ret, 0);
5993 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5995 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5998 struct socket *sock;
6003 if (!(req->flags & REQ_F_POLLED) &&
6004 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6007 sock = sock_from_file(req->file);
6008 if (unlikely(!sock))
6011 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6015 msg.msg_name = NULL;
6016 msg.msg_control = NULL;
6017 msg.msg_controllen = 0;
6018 msg.msg_namelen = 0;
6020 flags = sr->msg_flags;
6021 if (issue_flags & IO_URING_F_NONBLOCK)
6022 flags |= MSG_DONTWAIT;
6023 if (flags & MSG_WAITALL)
6024 min_ret = iov_iter_count(&msg.msg_iter);
6026 msg.msg_flags = flags;
6027 ret = sock_sendmsg(sock, &msg);
6028 if (ret < min_ret) {
6029 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6031 if (ret == -ERESTARTSYS)
6033 if (ret > 0 && io_net_retry(sock, flags)) {
6037 req->flags |= REQ_F_PARTIAL_IO;
6044 else if (sr->done_io)
6046 __io_req_complete(req, issue_flags, ret, 0);
6050 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6051 struct io_async_msghdr *iomsg)
6053 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6054 struct iovec __user *uiov;
6058 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6059 &iomsg->uaddr, &uiov, &iov_len);
6063 if (req->flags & REQ_F_BUFFER_SELECT) {
6066 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6068 sr->len = iomsg->fast_iov[0].iov_len;
6069 iomsg->free_iov = NULL;
6071 iomsg->free_iov = iomsg->fast_iov;
6072 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6073 &iomsg->free_iov, &iomsg->msg.msg_iter,
6082 #ifdef CONFIG_COMPAT
6083 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6084 struct io_async_msghdr *iomsg)
6086 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6087 struct compat_iovec __user *uiov;
6092 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6097 uiov = compat_ptr(ptr);
6098 if (req->flags & REQ_F_BUFFER_SELECT) {
6099 compat_ssize_t clen;
6103 if (!access_ok(uiov, sizeof(*uiov)))
6105 if (__get_user(clen, &uiov->iov_len))
6110 iomsg->free_iov = NULL;
6112 iomsg->free_iov = iomsg->fast_iov;
6113 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6114 UIO_FASTIOV, &iomsg->free_iov,
6115 &iomsg->msg.msg_iter, true);
6124 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6125 struct io_async_msghdr *iomsg)
6127 iomsg->msg.msg_name = &iomsg->addr;
6129 #ifdef CONFIG_COMPAT
6130 if (req->ctx->compat)
6131 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6134 return __io_recvmsg_copy_hdr(req, iomsg);
6137 static int io_recvmsg_prep_async(struct io_kiocb *req)
6141 ret = io_recvmsg_copy_hdr(req, req->async_data);
6143 req->flags |= REQ_F_NEED_CLEANUP;
6147 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6149 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6151 if (unlikely(sqe->file_index || sqe->addr2))
6154 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6155 sr->len = READ_ONCE(sqe->len);
6156 sr->flags = READ_ONCE(sqe->ioprio);
6157 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6159 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6160 if (sr->msg_flags & MSG_DONTWAIT)
6161 req->flags |= REQ_F_NOWAIT;
6162 if (sr->msg_flags & MSG_ERRQUEUE)
6163 req->flags |= REQ_F_CLEAR_POLLIN;
6165 #ifdef CONFIG_COMPAT
6166 if (req->ctx->compat)
6167 sr->msg_flags |= MSG_CMSG_COMPAT;
6173 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6175 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6176 struct io_async_msghdr iomsg, *kmsg;
6177 struct socket *sock;
6178 unsigned int cflags;
6180 int ret, min_ret = 0;
6181 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6183 sock = sock_from_file(req->file);
6184 if (unlikely(!sock))
6187 if (req_has_async_data(req)) {
6188 kmsg = req->async_data;
6190 ret = io_recvmsg_copy_hdr(req, &iomsg);
6196 if (!(req->flags & REQ_F_POLLED) &&
6197 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6198 return io_setup_async_msg(req, kmsg);
6200 if (io_do_buffer_select(req)) {
6203 buf = io_buffer_select(req, &sr->len, issue_flags);
6206 kmsg->fast_iov[0].iov_base = buf;
6207 kmsg->fast_iov[0].iov_len = sr->len;
6208 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6212 flags = sr->msg_flags;
6214 flags |= MSG_DONTWAIT;
6215 if (flags & MSG_WAITALL)
6216 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6218 kmsg->msg.msg_get_inq = 1;
6219 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6220 if (ret < min_ret) {
6221 if (ret == -EAGAIN && force_nonblock)
6222 return io_setup_async_msg(req, kmsg);
6223 if (ret == -ERESTARTSYS)
6225 if (ret > 0 && io_net_retry(sock, flags)) {
6227 req->flags |= REQ_F_PARTIAL_IO;
6228 return io_setup_async_msg(req, kmsg);
6231 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6235 /* fast path, check for non-NULL to avoid function call */
6237 kfree(kmsg->free_iov);
6238 req->flags &= ~REQ_F_NEED_CLEANUP;
6241 else if (sr->done_io)
6243 cflags = io_put_kbuf(req, issue_flags);
6244 if (kmsg->msg.msg_inq)
6245 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6246 __io_req_complete(req, issue_flags, ret, cflags);
6250 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6252 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6254 struct socket *sock;
6256 unsigned int cflags;
6258 int ret, min_ret = 0;
6259 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6261 if (!(req->flags & REQ_F_POLLED) &&
6262 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6265 sock = sock_from_file(req->file);
6266 if (unlikely(!sock))
6269 if (io_do_buffer_select(req)) {
6272 buf = io_buffer_select(req, &sr->len, issue_flags);
6278 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6282 msg.msg_name = NULL;
6283 msg.msg_namelen = 0;
6284 msg.msg_control = NULL;
6285 msg.msg_get_inq = 1;
6287 msg.msg_controllen = 0;
6288 msg.msg_iocb = NULL;
6290 flags = sr->msg_flags;
6292 flags |= MSG_DONTWAIT;
6293 if (flags & MSG_WAITALL)
6294 min_ret = iov_iter_count(&msg.msg_iter);
6296 ret = sock_recvmsg(sock, &msg, flags);
6297 if (ret < min_ret) {
6298 if (ret == -EAGAIN && force_nonblock)
6300 if (ret == -ERESTARTSYS)
6302 if (ret > 0 && io_net_retry(sock, flags)) {
6306 req->flags |= REQ_F_PARTIAL_IO;
6310 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6317 else if (sr->done_io)
6319 cflags = io_put_kbuf(req, issue_flags);
6321 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6322 __io_req_complete(req, issue_flags, ret, cflags);
6326 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6328 struct io_accept *accept = io_kiocb_to_cmd(req);
6331 if (sqe->len || sqe->buf_index)
6334 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6335 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6336 accept->flags = READ_ONCE(sqe->accept_flags);
6337 accept->nofile = rlimit(RLIMIT_NOFILE);
6338 flags = READ_ONCE(sqe->ioprio);
6339 if (flags & ~IORING_ACCEPT_MULTISHOT)
6342 accept->file_slot = READ_ONCE(sqe->file_index);
6343 if (accept->file_slot) {
6344 if (accept->flags & SOCK_CLOEXEC)
6346 if (flags & IORING_ACCEPT_MULTISHOT &&
6347 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6350 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6352 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6353 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6354 if (flags & IORING_ACCEPT_MULTISHOT)
6355 req->flags |= REQ_F_APOLL_MULTISHOT;
6359 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6361 struct io_ring_ctx *ctx = req->ctx;
6362 struct io_accept *accept = io_kiocb_to_cmd(req);
6363 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6364 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6365 bool fixed = !!accept->file_slot;
6371 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6372 if (unlikely(fd < 0))
6375 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6380 ret = PTR_ERR(file);
6381 if (ret == -EAGAIN && force_nonblock) {
6383 * if it's multishot and polled, we don't need to
6384 * return EAGAIN to arm the poll infra since it
6385 * has already been done
6387 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6388 IO_APOLL_MULTI_POLLED)
6392 if (ret == -ERESTARTSYS)
6395 } else if (!fixed) {
6396 fd_install(fd, file);
6399 ret = io_fixed_fd_install(req, issue_flags, file,
6403 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6404 __io_req_complete(req, issue_flags, ret, 0);
6410 spin_lock(&ctx->completion_lock);
6411 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6413 io_commit_cqring(ctx);
6414 spin_unlock(&ctx->completion_lock);
6416 io_cqring_ev_posted(ctx);
6425 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6427 struct io_socket *sock = io_kiocb_to_cmd(req);
6429 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6432 sock->domain = READ_ONCE(sqe->fd);
6433 sock->type = READ_ONCE(sqe->off);
6434 sock->protocol = READ_ONCE(sqe->len);
6435 sock->file_slot = READ_ONCE(sqe->file_index);
6436 sock->nofile = rlimit(RLIMIT_NOFILE);
6438 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6439 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6441 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6446 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6448 struct io_socket *sock = io_kiocb_to_cmd(req);
6449 bool fixed = !!sock->file_slot;
6454 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6455 if (unlikely(fd < 0))
6458 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6462 ret = PTR_ERR(file);
6463 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6465 if (ret == -ERESTARTSYS)
6468 } else if (!fixed) {
6469 fd_install(fd, file);
6472 ret = io_fixed_fd_install(req, issue_flags, file,
6475 __io_req_complete(req, issue_flags, ret, 0);
6479 static int io_connect_prep_async(struct io_kiocb *req)
6481 struct io_async_connect *io = req->async_data;
6482 struct io_connect *conn = io_kiocb_to_cmd(req);
6484 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6487 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6489 struct io_connect *conn = io_kiocb_to_cmd(req);
6491 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6494 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6495 conn->addr_len = READ_ONCE(sqe->addr2);
6499 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6501 struct io_connect *connect = io_kiocb_to_cmd(req);
6502 struct io_async_connect __io, *io;
6503 unsigned file_flags;
6505 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6507 if (req_has_async_data(req)) {
6508 io = req->async_data;
6510 ret = move_addr_to_kernel(connect->addr,
6518 file_flags = force_nonblock ? O_NONBLOCK : 0;
6520 ret = __sys_connect_file(req->file, &io->address,
6521 connect->addr_len, file_flags);
6522 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6523 if (req_has_async_data(req))
6525 if (io_alloc_async_data(req)) {
6529 memcpy(req->async_data, &__io, sizeof(__io));
6532 if (ret == -ERESTARTSYS)
6537 __io_req_complete(req, issue_flags, ret, 0);
6540 #else /* !CONFIG_NET */
6541 #define IO_NETOP_FN(op) \
6542 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6544 return -EOPNOTSUPP; \
6547 #define IO_NETOP_PREP(op) \
6549 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6551 return -EOPNOTSUPP; \
6554 #define IO_NETOP_PREP_ASYNC(op) \
6556 static int io_##op##_prep_async(struct io_kiocb *req) \
6558 return -EOPNOTSUPP; \
6561 IO_NETOP_PREP_ASYNC(sendmsg);
6562 IO_NETOP_PREP_ASYNC(recvmsg);
6563 IO_NETOP_PREP_ASYNC(connect);
6564 IO_NETOP_PREP(accept);
6565 IO_NETOP_PREP(socket);
6566 IO_NETOP_PREP(shutdown);
6569 #endif /* CONFIG_NET */
6571 struct io_poll_table {
6572 struct poll_table_struct pt;
6573 struct io_kiocb *req;
6578 #define IO_POLL_CANCEL_FLAG BIT(31)
6579 #define IO_POLL_REF_MASK GENMASK(30, 0)
6582 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6583 * bump it and acquire ownership. It's disallowed to modify requests while not
6584 * owning it, that prevents from races for enqueueing task_work's and b/w
6585 * arming poll and wakeups.
6587 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6589 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6592 static void io_poll_mark_cancelled(struct io_kiocb *req)
6594 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6597 static struct io_poll *io_poll_get_double(struct io_kiocb *req)
6599 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6600 if (req->opcode == IORING_OP_POLL_ADD)
6601 return req->async_data;
6602 return req->apoll->double_poll;
6605 static struct io_poll *io_poll_get_single(struct io_kiocb *req)
6607 if (req->opcode == IORING_OP_POLL_ADD)
6608 return io_kiocb_to_cmd(req);
6609 return &req->apoll->poll;
6612 static void io_poll_req_insert(struct io_kiocb *req)
6614 struct io_ring_ctx *ctx = req->ctx;
6615 struct hlist_head *list;
6617 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6618 hlist_add_head(&req->hash_node, list);
6621 static void io_init_poll_iocb(struct io_poll *poll, __poll_t events,
6622 wait_queue_func_t wake_func)
6625 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6626 /* mask in events that we always want/need */
6627 poll->events = events | IO_POLL_UNMASK;
6628 INIT_LIST_HEAD(&poll->wait.entry);
6629 init_waitqueue_func_entry(&poll->wait, wake_func);
6632 static inline void io_poll_remove_entry(struct io_poll *poll)
6634 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6637 spin_lock_irq(&head->lock);
6638 list_del_init(&poll->wait.entry);
6640 spin_unlock_irq(&head->lock);
6644 static void io_poll_remove_entries(struct io_kiocb *req)
6647 * Nothing to do if neither of those flags are set. Avoid dipping
6648 * into the poll/apoll/double cachelines if we can.
6650 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6654 * While we hold the waitqueue lock and the waitqueue is nonempty,
6655 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6656 * lock in the first place can race with the waitqueue being freed.
6658 * We solve this as eventpoll does: by taking advantage of the fact that
6659 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6660 * we enter rcu_read_lock() and see that the pointer to the queue is
6661 * non-NULL, we can then lock it without the memory being freed out from
6664 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6665 * case the caller deletes the entry from the queue, leaving it empty.
6666 * In that case, only RCU prevents the queue memory from being freed.
6669 if (req->flags & REQ_F_SINGLE_POLL)
6670 io_poll_remove_entry(io_poll_get_single(req));
6671 if (req->flags & REQ_F_DOUBLE_POLL)
6672 io_poll_remove_entry(io_poll_get_double(req));
6676 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6678 * All poll tw should go through this. Checks for poll events, manages
6679 * references, does rewait, etc.
6681 * Returns a negative error on failure. >0 when no action require, which is
6682 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6683 * the request, then the mask is stored in req->cqe.res.
6685 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6687 struct io_ring_ctx *ctx = req->ctx;
6690 /* req->task == current here, checking PF_EXITING is safe */
6691 if (unlikely(req->task->flags & PF_EXITING))
6695 v = atomic_read(&req->poll_refs);
6697 /* tw handler should be the owner, and so have some references */
6698 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6700 if (v & IO_POLL_CANCEL_FLAG)
6703 if (!req->cqe.res) {
6704 struct poll_table_struct pt = { ._key = req->apoll_events };
6705 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6708 if ((unlikely(!req->cqe.res)))
6710 if (req->apoll_events & EPOLLONESHOT)
6713 /* multishot, just fill a CQE and proceed */
6714 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6715 __poll_t mask = mangle_poll(req->cqe.res &
6719 spin_lock(&ctx->completion_lock);
6720 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6721 mask, IORING_CQE_F_MORE);
6722 io_commit_cqring(ctx);
6723 spin_unlock(&ctx->completion_lock);
6725 io_cqring_ev_posted(ctx);
6731 io_tw_lock(req->ctx, locked);
6732 if (unlikely(req->task->flags & PF_EXITING))
6734 ret = io_issue_sqe(req,
6735 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6740 * Release all references, retry if someone tried to restart
6741 * task_work while we were executing it.
6743 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6748 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6750 struct io_ring_ctx *ctx = req->ctx;
6753 ret = io_poll_check_events(req, locked);
6758 struct io_poll *poll = io_kiocb_to_cmd(req);
6760 req->cqe.res = mangle_poll(req->cqe.res & poll->events);
6766 io_poll_remove_entries(req);
6767 spin_lock(&ctx->completion_lock);
6768 hash_del(&req->hash_node);
6769 __io_req_complete_post(req, req->cqe.res, 0);
6770 io_commit_cqring(ctx);
6771 spin_unlock(&ctx->completion_lock);
6772 io_cqring_ev_posted(ctx);
6775 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6777 struct io_ring_ctx *ctx = req->ctx;
6780 ret = io_poll_check_events(req, locked);
6784 io_poll_remove_entries(req);
6785 spin_lock(&ctx->completion_lock);
6786 hash_del(&req->hash_node);
6787 spin_unlock(&ctx->completion_lock);
6790 io_req_task_submit(req, locked);
6792 io_req_complete_failed(req, ret);
6795 static void __io_poll_execute(struct io_kiocb *req, int mask,
6796 __poll_t __maybe_unused events)
6798 req->cqe.res = mask;
6800 * This is useful for poll that is armed on behalf of another
6801 * request, and where the wakeup path could be on a different
6802 * CPU. We want to avoid pulling in req->apoll->events for that
6805 if (req->opcode == IORING_OP_POLL_ADD)
6806 req->io_task_work.func = io_poll_task_func;
6808 req->io_task_work.func = io_apoll_task_func;
6810 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6811 io_req_task_work_add(req);
6814 static inline void io_poll_execute(struct io_kiocb *req, int res,
6817 if (io_poll_get_ownership(req))
6818 __io_poll_execute(req, res, events);
6821 static void io_poll_cancel_req(struct io_kiocb *req)
6823 io_poll_mark_cancelled(req);
6824 /* kick tw, which should complete the request */
6825 io_poll_execute(req, 0, 0);
6828 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6829 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6830 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
6832 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6835 struct io_kiocb *req = wqe_to_req(wait);
6836 struct io_poll *poll = container_of(wait, struct io_poll, wait);
6837 __poll_t mask = key_to_poll(key);
6839 if (unlikely(mask & POLLFREE)) {
6840 io_poll_mark_cancelled(req);
6841 /* we have to kick tw in case it's not already */
6842 io_poll_execute(req, 0, poll->events);
6845 * If the waitqueue is being freed early but someone is already
6846 * holds ownership over it, we have to tear down the request as
6847 * best we can. That means immediately removing the request from
6848 * its waitqueue and preventing all further accesses to the
6849 * waitqueue via the request.
6851 list_del_init(&poll->wait.entry);
6854 * Careful: this *must* be the last step, since as soon
6855 * as req->head is NULL'ed out, the request can be
6856 * completed and freed, since aio_poll_complete_work()
6857 * will no longer need to take the waitqueue lock.
6859 smp_store_release(&poll->head, NULL);
6863 /* for instances that support it check for an event match first */
6864 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
6867 if (io_poll_get_ownership(req)) {
6868 /* optional, saves extra locking for removal in tw handler */
6869 if (mask && poll->events & EPOLLONESHOT) {
6870 list_del_init(&poll->wait.entry);
6872 if (wqe_is_double(wait))
6873 req->flags &= ~REQ_F_DOUBLE_POLL;
6875 req->flags &= ~REQ_F_SINGLE_POLL;
6877 __io_poll_execute(req, mask, poll->events);
6882 static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt,
6883 struct wait_queue_head *head,
6884 struct io_poll **poll_ptr)
6886 struct io_kiocb *req = pt->req;
6887 unsigned long wqe_private = (unsigned long) req;
6890 * The file being polled uses multiple waitqueues for poll handling
6891 * (e.g. one for read, one for write). Setup a separate io_poll
6894 if (unlikely(pt->nr_entries)) {
6895 struct io_poll *first = poll;
6897 /* double add on the same waitqueue head, ignore */
6898 if (first->head == head)
6900 /* already have a 2nd entry, fail a third attempt */
6902 if ((*poll_ptr)->head == head)
6904 pt->error = -EINVAL;
6908 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6910 pt->error = -ENOMEM;
6913 /* mark as double wq entry */
6915 req->flags |= REQ_F_DOUBLE_POLL;
6916 io_init_poll_iocb(poll, first->events, first->wait.func);
6918 if (req->opcode == IORING_OP_POLL_ADD)
6919 req->flags |= REQ_F_ASYNC_DATA;
6922 req->flags |= REQ_F_SINGLE_POLL;
6925 poll->wait.private = (void *) wqe_private;
6927 if (poll->events & EPOLLEXCLUSIVE)
6928 add_wait_queue_exclusive(head, &poll->wait);
6930 add_wait_queue(head, &poll->wait);
6933 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6934 struct poll_table_struct *p)
6936 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6937 struct io_poll *poll = io_kiocb_to_cmd(pt->req);
6939 __io_queue_proc(poll, pt, head,
6940 (struct io_poll **) &pt->req->async_data);
6943 static int __io_arm_poll_handler(struct io_kiocb *req,
6944 struct io_poll *poll,
6945 struct io_poll_table *ipt, __poll_t mask)
6947 struct io_ring_ctx *ctx = req->ctx;
6950 INIT_HLIST_NODE(&req->hash_node);
6951 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
6952 io_init_poll_iocb(poll, mask, io_poll_wake);
6953 poll->file = req->file;
6955 req->apoll_events = poll->events;
6957 ipt->pt._key = mask;
6960 ipt->nr_entries = 0;
6963 * Take the ownership to delay any tw execution up until we're done
6964 * with poll arming. see io_poll_get_ownership().
6966 atomic_set(&req->poll_refs, 1);
6967 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6969 if (mask && (poll->events & EPOLLONESHOT)) {
6970 io_poll_remove_entries(req);
6971 /* no one else has access to the req, forget about the ref */
6974 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6975 io_poll_remove_entries(req);
6977 ipt->error = -EINVAL;
6981 spin_lock(&ctx->completion_lock);
6982 io_poll_req_insert(req);
6983 spin_unlock(&ctx->completion_lock);
6986 /* can't multishot if failed, just queue the event we've got */
6987 if (unlikely(ipt->error || !ipt->nr_entries)) {
6988 poll->events |= EPOLLONESHOT;
6989 req->apoll_events |= EPOLLONESHOT;
6992 __io_poll_execute(req, mask, poll->events);
6997 * Release ownership. If someone tried to queue a tw while it was
6998 * locked, kick it off for them.
7000 v = atomic_dec_return(&req->poll_refs);
7001 if (unlikely(v & IO_POLL_REF_MASK))
7002 __io_poll_execute(req, 0, poll->events);
7006 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7007 struct poll_table_struct *p)
7009 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7010 struct async_poll *apoll = pt->req->apoll;
7012 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7021 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7023 const struct io_op_def *def = &io_op_defs[req->opcode];
7024 struct io_ring_ctx *ctx = req->ctx;
7025 struct async_poll *apoll;
7026 struct io_poll_table ipt;
7027 __poll_t mask = POLLPRI | POLLERR;
7030 if (!def->pollin && !def->pollout)
7031 return IO_APOLL_ABORTED;
7032 if (!file_can_poll(req->file))
7033 return IO_APOLL_ABORTED;
7034 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7035 return IO_APOLL_ABORTED;
7036 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7037 mask |= EPOLLONESHOT;
7040 mask |= EPOLLIN | EPOLLRDNORM;
7042 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7043 if (req->flags & REQ_F_CLEAR_POLLIN)
7046 mask |= EPOLLOUT | EPOLLWRNORM;
7048 if (def->poll_exclusive)
7049 mask |= EPOLLEXCLUSIVE;
7050 if (req->flags & REQ_F_POLLED) {
7052 kfree(apoll->double_poll);
7053 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7054 !list_empty(&ctx->apoll_cache)) {
7055 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7057 list_del_init(&apoll->poll.wait.entry);
7059 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7060 if (unlikely(!apoll))
7061 return IO_APOLL_ABORTED;
7063 apoll->double_poll = NULL;
7065 req->flags |= REQ_F_POLLED;
7066 ipt.pt._qproc = io_async_queue_proc;
7068 io_kbuf_recycle(req, issue_flags);
7070 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7071 if (ret || ipt.error)
7072 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7074 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7075 mask, apoll->poll.events);
7080 * Returns true if we found and killed one or more poll requests
7082 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7083 struct task_struct *tsk, bool cancel_all)
7085 struct hlist_node *tmp;
7086 struct io_kiocb *req;
7090 spin_lock(&ctx->completion_lock);
7091 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7092 struct hlist_head *list;
7094 list = &ctx->cancel_hash[i];
7095 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7096 if (io_match_task_safe(req, tsk, cancel_all)) {
7097 hlist_del_init(&req->hash_node);
7098 io_poll_cancel_req(req);
7103 spin_unlock(&ctx->completion_lock);
7107 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7108 struct io_cancel_data *cd)
7109 __must_hold(&ctx->completion_lock)
7111 struct hlist_head *list;
7112 struct io_kiocb *req;
7114 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7115 hlist_for_each_entry(req, list, hash_node) {
7116 if (cd->data != req->cqe.user_data)
7118 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7120 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7121 if (cd->seq == req->work.cancel_seq)
7123 req->work.cancel_seq = cd->seq;
7130 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7131 struct io_cancel_data *cd)
7132 __must_hold(&ctx->completion_lock)
7134 struct io_kiocb *req;
7137 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7138 struct hlist_head *list;
7140 list = &ctx->cancel_hash[i];
7141 hlist_for_each_entry(req, list, hash_node) {
7142 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7143 req->file != cd->file)
7145 if (cd->seq == req->work.cancel_seq)
7147 req->work.cancel_seq = cd->seq;
7154 static bool io_poll_disarm(struct io_kiocb *req)
7155 __must_hold(&ctx->completion_lock)
7157 if (!io_poll_get_ownership(req))
7159 io_poll_remove_entries(req);
7160 hash_del(&req->hash_node);
7164 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7165 __must_hold(&ctx->completion_lock)
7167 struct io_kiocb *req;
7169 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7170 req = io_poll_file_find(ctx, cd);
7172 req = io_poll_find(ctx, false, cd);
7175 io_poll_cancel_req(req);
7179 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7184 events = READ_ONCE(sqe->poll32_events);
7186 events = swahw32(events);
7188 if (!(flags & IORING_POLL_ADD_MULTI))
7189 events |= EPOLLONESHOT;
7190 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7193 static int io_poll_remove_prep(struct io_kiocb *req,
7194 const struct io_uring_sqe *sqe)
7196 struct io_poll_update *upd = io_kiocb_to_cmd(req);
7199 if (sqe->buf_index || sqe->splice_fd_in)
7201 flags = READ_ONCE(sqe->len);
7202 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7203 IORING_POLL_ADD_MULTI))
7205 /* meaningless without update */
7206 if (flags == IORING_POLL_ADD_MULTI)
7209 upd->old_user_data = READ_ONCE(sqe->addr);
7210 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7211 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7213 upd->new_user_data = READ_ONCE(sqe->off);
7214 if (!upd->update_user_data && upd->new_user_data)
7216 if (upd->update_events)
7217 upd->events = io_poll_parse_events(sqe, flags);
7218 else if (sqe->poll32_events)
7224 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7226 struct io_poll *poll = io_kiocb_to_cmd(req);
7229 if (sqe->buf_index || sqe->off || sqe->addr)
7231 flags = READ_ONCE(sqe->len);
7232 if (flags & ~IORING_POLL_ADD_MULTI)
7234 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7237 io_req_set_refcount(req);
7238 poll->events = io_poll_parse_events(sqe, flags);
7242 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7244 struct io_poll *poll = io_kiocb_to_cmd(req);
7245 struct io_poll_table ipt;
7248 ipt.pt._qproc = io_poll_queue_proc;
7250 ret = __io_arm_poll_handler(req, poll, &ipt, poll->events);
7251 if (!ret && ipt.error)
7253 ret = ret ?: ipt.error;
7255 __io_req_complete(req, issue_flags, ret, 0);
7259 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7261 struct io_poll_update *poll_update = io_kiocb_to_cmd(req);
7262 struct io_cancel_data cd = { .data = poll_update->old_user_data, };
7263 struct io_ring_ctx *ctx = req->ctx;
7264 struct io_kiocb *preq;
7268 spin_lock(&ctx->completion_lock);
7269 preq = io_poll_find(ctx, true, &cd);
7270 if (!preq || !io_poll_disarm(preq)) {
7271 spin_unlock(&ctx->completion_lock);
7272 ret = preq ? -EALREADY : -ENOENT;
7275 spin_unlock(&ctx->completion_lock);
7277 if (poll_update->update_events || poll_update->update_user_data) {
7278 /* only mask one event flags, keep behavior flags */
7279 if (poll_update->update_events) {
7280 struct io_poll *poll = io_kiocb_to_cmd(preq);
7282 poll->events &= ~0xffff;
7283 poll->events |= poll_update->events & 0xffff;
7284 poll->events |= IO_POLL_UNMASK;
7286 if (poll_update->update_user_data)
7287 preq->cqe.user_data = poll_update->new_user_data;
7289 ret2 = io_poll_add(preq, issue_flags);
7290 /* successfully updated, don't complete poll request */
7296 preq->cqe.res = -ECANCELED;
7297 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7298 io_req_task_complete(preq, &locked);
7302 /* complete update request, we're done with it */
7303 __io_req_complete(req, issue_flags, ret, 0);
7307 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7309 struct io_timeout_data *data = container_of(timer,
7310 struct io_timeout_data, timer);
7311 struct io_kiocb *req = data->req;
7312 struct io_timeout *timeout = io_kiocb_to_cmd(req);
7313 struct io_ring_ctx *ctx = req->ctx;
7314 unsigned long flags;
7316 spin_lock_irqsave(&ctx->timeout_lock, flags);
7317 list_del_init(&timeout->list);
7318 atomic_set(&req->ctx->cq_timeouts,
7319 atomic_read(&req->ctx->cq_timeouts) + 1);
7320 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7322 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7325 req->cqe.res = -ETIME;
7326 req->io_task_work.func = io_req_task_complete;
7327 io_req_task_work_add(req);
7328 return HRTIMER_NORESTART;
7331 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7332 struct io_cancel_data *cd)
7333 __must_hold(&ctx->timeout_lock)
7335 struct io_timeout *timeout;
7336 struct io_timeout_data *io;
7337 struct io_kiocb *req = NULL;
7339 list_for_each_entry(timeout, &ctx->timeout_list, list) {
7340 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
7342 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7343 cd->data != tmp->cqe.user_data)
7345 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7346 if (cd->seq == tmp->work.cancel_seq)
7348 tmp->work.cancel_seq = cd->seq;
7354 return ERR_PTR(-ENOENT);
7356 io = req->async_data;
7357 if (hrtimer_try_to_cancel(&io->timer) == -1)
7358 return ERR_PTR(-EALREADY);
7359 timeout = io_kiocb_to_cmd(req);
7360 list_del_init(&timeout->list);
7364 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7365 __must_hold(&ctx->completion_lock)
7367 struct io_kiocb *req;
7369 spin_lock_irq(&ctx->timeout_lock);
7370 req = io_timeout_extract(ctx, cd);
7371 spin_unlock_irq(&ctx->timeout_lock);
7374 return PTR_ERR(req);
7375 io_req_task_queue_fail(req, -ECANCELED);
7379 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7381 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7382 case IORING_TIMEOUT_BOOTTIME:
7383 return CLOCK_BOOTTIME;
7384 case IORING_TIMEOUT_REALTIME:
7385 return CLOCK_REALTIME;
7387 /* can't happen, vetted at prep time */
7391 return CLOCK_MONOTONIC;
7395 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7396 struct timespec64 *ts, enum hrtimer_mode mode)
7397 __must_hold(&ctx->timeout_lock)
7399 struct io_timeout_data *io;
7400 struct io_timeout *timeout;
7401 struct io_kiocb *req = NULL;
7403 list_for_each_entry(timeout, &ctx->ltimeout_list, list) {
7404 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
7406 if (user_data == tmp->cqe.user_data) {
7414 io = req->async_data;
7415 if (hrtimer_try_to_cancel(&io->timer) == -1)
7417 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7418 io->timer.function = io_link_timeout_fn;
7419 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7423 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7424 struct timespec64 *ts, enum hrtimer_mode mode)
7425 __must_hold(&ctx->timeout_lock)
7427 struct io_cancel_data cd = { .data = user_data, };
7428 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7429 struct io_timeout *timeout = io_kiocb_to_cmd(req);
7430 struct io_timeout_data *data;
7433 return PTR_ERR(req);
7435 timeout->off = 0; /* noseq */
7436 data = req->async_data;
7437 list_add_tail(&timeout->list, &ctx->timeout_list);
7438 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7439 data->timer.function = io_timeout_fn;
7440 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7444 static int io_timeout_remove_prep(struct io_kiocb *req,
7445 const struct io_uring_sqe *sqe)
7447 struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
7449 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7451 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7454 tr->ltimeout = false;
7455 tr->addr = READ_ONCE(sqe->addr);
7456 tr->flags = READ_ONCE(sqe->timeout_flags);
7457 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7458 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7460 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7461 tr->ltimeout = true;
7462 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7464 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7466 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7468 } else if (tr->flags) {
7469 /* timeout removal doesn't support flags */
7476 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7478 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7483 * Remove or update an existing timeout command
7485 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7487 struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
7488 struct io_ring_ctx *ctx = req->ctx;
7491 if (!(tr->flags & IORING_TIMEOUT_UPDATE)) {
7492 struct io_cancel_data cd = { .data = tr->addr, };
7494 spin_lock(&ctx->completion_lock);
7495 ret = io_timeout_cancel(ctx, &cd);
7496 spin_unlock(&ctx->completion_lock);
7498 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7500 spin_lock_irq(&ctx->timeout_lock);
7502 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7504 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7505 spin_unlock_irq(&ctx->timeout_lock);
7510 io_req_complete_post(req, ret, 0);
7514 static int __io_timeout_prep(struct io_kiocb *req,
7515 const struct io_uring_sqe *sqe,
7516 bool is_timeout_link)
7518 struct io_timeout *timeout = io_kiocb_to_cmd(req);
7519 struct io_timeout_data *data;
7521 u32 off = READ_ONCE(sqe->off);
7523 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7525 if (off && is_timeout_link)
7527 flags = READ_ONCE(sqe->timeout_flags);
7528 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7529 IORING_TIMEOUT_ETIME_SUCCESS))
7531 /* more than one clock specified is invalid, obviously */
7532 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7535 INIT_LIST_HEAD(&timeout->list);
7537 if (unlikely(off && !req->ctx->off_timeout_used))
7538 req->ctx->off_timeout_used = true;
7540 if (WARN_ON_ONCE(req_has_async_data(req)))
7542 if (io_alloc_async_data(req))
7545 data = req->async_data;
7547 data->flags = flags;
7549 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7552 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7555 INIT_LIST_HEAD(&timeout->list);
7556 data->mode = io_translate_timeout_mode(flags);
7557 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7559 if (is_timeout_link) {
7560 struct io_submit_link *link = &req->ctx->submit_state.link;
7564 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7566 timeout->head = link->last;
7567 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7572 static int io_timeout_prep(struct io_kiocb *req,
7573 const struct io_uring_sqe *sqe)
7575 return __io_timeout_prep(req, sqe, false);
7578 static int io_link_timeout_prep(struct io_kiocb *req,
7579 const struct io_uring_sqe *sqe)
7581 return __io_timeout_prep(req, sqe, true);
7584 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7586 struct io_timeout *timeout = io_kiocb_to_cmd(req);
7587 struct io_ring_ctx *ctx = req->ctx;
7588 struct io_timeout_data *data = req->async_data;
7589 struct list_head *entry;
7590 u32 tail, off = timeout->off;
7592 spin_lock_irq(&ctx->timeout_lock);
7595 * sqe->off holds how many events that need to occur for this
7596 * timeout event to be satisfied. If it isn't set, then this is
7597 * a pure timeout request, sequence isn't used.
7599 if (io_is_timeout_noseq(req)) {
7600 entry = ctx->timeout_list.prev;
7604 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7605 timeout->target_seq = tail + off;
7607 /* Update the last seq here in case io_flush_timeouts() hasn't.
7608 * This is safe because ->completion_lock is held, and submissions
7609 * and completions are never mixed in the same ->completion_lock section.
7611 ctx->cq_last_tm_flush = tail;
7614 * Insertion sort, ensuring the first entry in the list is always
7615 * the one we need first.
7617 list_for_each_prev(entry, &ctx->timeout_list) {
7618 struct io_timeout *nextt = list_entry(entry, struct io_timeout, list);
7619 struct io_kiocb *nxt = cmd_to_io_kiocb(nextt);
7621 if (io_is_timeout_noseq(nxt))
7623 /* nxt.seq is behind @tail, otherwise would've been completed */
7624 if (off >= nextt->target_seq - tail)
7628 list_add(&timeout->list, entry);
7629 data->timer.function = io_timeout_fn;
7630 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7631 spin_unlock_irq(&ctx->timeout_lock);
7635 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7637 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7638 struct io_cancel_data *cd = data;
7640 if (req->ctx != cd->ctx)
7642 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7644 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7645 if (req->file != cd->file)
7648 if (req->cqe.user_data != cd->data)
7651 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7652 if (cd->seq == req->work.cancel_seq)
7654 req->work.cancel_seq = cd->seq;
7659 static int io_async_cancel_one(struct io_uring_task *tctx,
7660 struct io_cancel_data *cd)
7662 enum io_wq_cancel cancel_ret;
7666 if (!tctx || !tctx->io_wq)
7669 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7670 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7671 switch (cancel_ret) {
7672 case IO_WQ_CANCEL_OK:
7675 case IO_WQ_CANCEL_RUNNING:
7678 case IO_WQ_CANCEL_NOTFOUND:
7686 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7688 struct io_ring_ctx *ctx = req->ctx;
7691 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7693 ret = io_async_cancel_one(req->task->io_uring, cd);
7695 * Fall-through even for -EALREADY, as we may have poll armed
7696 * that need unarming.
7701 spin_lock(&ctx->completion_lock);
7702 ret = io_poll_cancel(ctx, cd);
7705 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7706 ret = io_timeout_cancel(ctx, cd);
7708 spin_unlock(&ctx->completion_lock);
7712 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7713 IORING_ASYNC_CANCEL_ANY)
7715 static int io_async_cancel_prep(struct io_kiocb *req,
7716 const struct io_uring_sqe *sqe)
7718 struct io_cancel *cancel = io_kiocb_to_cmd(req);
7720 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7722 if (sqe->off || sqe->len || sqe->splice_fd_in)
7725 cancel->addr = READ_ONCE(sqe->addr);
7726 cancel->flags = READ_ONCE(sqe->cancel_flags);
7727 if (cancel->flags & ~CANCEL_FLAGS)
7729 if (cancel->flags & IORING_ASYNC_CANCEL_FD) {
7730 if (cancel->flags & IORING_ASYNC_CANCEL_ANY)
7732 cancel->fd = READ_ONCE(sqe->fd);
7738 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7739 unsigned int issue_flags)
7741 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7742 struct io_ring_ctx *ctx = cd->ctx;
7743 struct io_tctx_node *node;
7747 ret = io_try_cancel(req, cd);
7755 /* slow path, try all io-wq's */
7756 io_ring_submit_lock(ctx, issue_flags);
7758 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7759 struct io_uring_task *tctx = node->task->io_uring;
7761 ret = io_async_cancel_one(tctx, cd);
7762 if (ret != -ENOENT) {
7768 io_ring_submit_unlock(ctx, issue_flags);
7769 return all ? nr : ret;
7772 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7774 struct io_cancel *cancel = io_kiocb_to_cmd(req);
7775 struct io_cancel_data cd = {
7777 .data = cancel->addr,
7778 .flags = cancel->flags,
7779 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7783 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7784 if (req->flags & REQ_F_FIXED_FILE)
7785 req->file = io_file_get_fixed(req, cancel->fd,
7788 req->file = io_file_get_normal(req, cancel->fd);
7793 cd.file = req->file;
7796 ret = __io_async_cancel(&cd, req, issue_flags);
7800 io_req_complete_post(req, ret, 0);
7804 static int io_files_update_prep(struct io_kiocb *req,
7805 const struct io_uring_sqe *sqe)
7807 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7809 if (sqe->rw_flags || sqe->splice_fd_in)
7812 req->rsrc_update.offset = READ_ONCE(sqe->off);
7813 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7814 if (!req->rsrc_update.nr_args)
7816 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7820 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7821 unsigned int issue_flags)
7823 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7828 if (!req->ctx->file_data)
7831 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7832 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7842 ret = io_fixed_fd_install(req, issue_flags, file,
7843 IORING_FILE_INDEX_ALLOC);
7846 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
7847 __io_close_fixed(req, issue_flags, ret);
7858 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7860 struct io_ring_ctx *ctx = req->ctx;
7861 struct io_uring_rsrc_update2 up;
7864 up.offset = req->rsrc_update.offset;
7865 up.data = req->rsrc_update.arg;
7871 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
7872 ret = io_files_update_with_index_alloc(req, issue_flags);
7874 io_ring_submit_lock(ctx, issue_flags);
7875 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
7876 &up, req->rsrc_update.nr_args);
7877 io_ring_submit_unlock(ctx, issue_flags);
7882 __io_req_complete(req, issue_flags, ret, 0);
7886 static int io_req_prep_async(struct io_kiocb *req)
7888 const struct io_op_def *def = &io_op_defs[req->opcode];
7890 /* assign early for deferred execution for non-fixed file */
7891 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
7892 req->file = io_file_get_normal(req, req->cqe.fd);
7893 if (!def->prep_async)
7895 if (WARN_ON_ONCE(req_has_async_data(req)))
7897 if (io_alloc_async_data(req))
7900 return def->prep_async(req);
7903 static u32 io_get_sequence(struct io_kiocb *req)
7905 u32 seq = req->ctx->cached_sq_head;
7906 struct io_kiocb *cur;
7908 /* need original cached_sq_head, but it was increased for each req */
7909 io_for_each_link(cur, req)
7914 static __cold void io_drain_req(struct io_kiocb *req)
7916 struct io_ring_ctx *ctx = req->ctx;
7917 struct io_defer_entry *de;
7919 u32 seq = io_get_sequence(req);
7921 /* Still need defer if there is pending req in defer list. */
7922 spin_lock(&ctx->completion_lock);
7923 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7924 spin_unlock(&ctx->completion_lock);
7926 ctx->drain_active = false;
7927 io_req_task_queue(req);
7930 spin_unlock(&ctx->completion_lock);
7932 ret = io_req_prep_async(req);
7935 io_req_complete_failed(req, ret);
7938 io_prep_async_link(req);
7939 de = kmalloc(sizeof(*de), GFP_KERNEL);
7945 spin_lock(&ctx->completion_lock);
7946 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7947 spin_unlock(&ctx->completion_lock);
7952 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7955 list_add_tail(&de->list, &ctx->defer_list);
7956 spin_unlock(&ctx->completion_lock);
7959 static void io_clean_op(struct io_kiocb *req)
7961 if (req->flags & REQ_F_BUFFER_SELECTED) {
7962 spin_lock(&req->ctx->completion_lock);
7963 io_put_kbuf_comp(req);
7964 spin_unlock(&req->ctx->completion_lock);
7967 if (req->flags & REQ_F_NEED_CLEANUP) {
7968 switch (req->opcode) {
7969 case IORING_OP_READV:
7970 case IORING_OP_READ_FIXED:
7971 case IORING_OP_READ:
7972 case IORING_OP_WRITEV:
7973 case IORING_OP_WRITE_FIXED:
7974 case IORING_OP_WRITE: {
7975 struct io_async_rw *io = req->async_data;
7977 kfree(io->free_iovec);
7980 case IORING_OP_RECVMSG:
7981 case IORING_OP_SENDMSG: {
7982 struct io_async_msghdr *io = req->async_data;
7984 kfree(io->free_iov);
7987 case IORING_OP_OPENAT:
7988 case IORING_OP_OPENAT2: {
7989 struct io_open *open = io_kiocb_to_cmd(req);
7992 putname(open->filename);
7995 case IORING_OP_RENAMEAT:
7996 putname(req->rename.oldpath);
7997 putname(req->rename.newpath);
7999 case IORING_OP_UNLINKAT:
8000 putname(req->unlink.filename);
8002 case IORING_OP_MKDIRAT:
8003 putname(req->mkdir.filename);
8005 case IORING_OP_SYMLINKAT:
8006 putname(req->symlink.oldpath);
8007 putname(req->symlink.newpath);
8009 case IORING_OP_LINKAT:
8010 putname(req->hardlink.oldpath);
8011 putname(req->hardlink.newpath);
8013 case IORING_OP_STATX:
8014 if (req->statx.filename)
8015 putname(req->statx.filename);
8017 case IORING_OP_SETXATTR:
8018 case IORING_OP_FSETXATTR:
8019 case IORING_OP_GETXATTR:
8020 case IORING_OP_FGETXATTR:
8021 __io_xattr_finish(req);
8025 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8026 kfree(req->apoll->double_poll);
8030 if (req->flags & REQ_F_INFLIGHT) {
8031 struct io_uring_task *tctx = req->task->io_uring;
8033 atomic_dec(&tctx->inflight_tracked);
8035 if (req->flags & REQ_F_CREDS)
8036 put_cred(req->creds);
8037 if (req->flags & REQ_F_ASYNC_DATA) {
8038 kfree(req->async_data);
8039 req->async_data = NULL;
8041 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8044 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8046 if (req->file || !io_op_defs[req->opcode].needs_file)
8049 if (req->flags & REQ_F_FIXED_FILE)
8050 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8052 req->file = io_file_get_normal(req, req->cqe.fd);
8057 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8059 const struct io_op_def *def = &io_op_defs[req->opcode];
8060 const struct cred *creds = NULL;
8063 if (unlikely(!io_assign_file(req, issue_flags)))
8066 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8067 creds = override_creds(req->creds);
8069 if (!def->audit_skip)
8070 audit_uring_entry(req->opcode);
8072 ret = def->issue(req, issue_flags);
8074 if (!def->audit_skip)
8075 audit_uring_exit(!ret, ret);
8078 revert_creds(creds);
8081 /* If the op doesn't have a file, we're not polling for it */
8082 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8083 io_iopoll_req_issued(req, issue_flags);
8088 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8090 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8092 req = io_put_req_find_next(req);
8093 return req ? &req->work : NULL;
8096 static void io_wq_submit_work(struct io_wq_work *work)
8098 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8099 const struct io_op_def *def = &io_op_defs[req->opcode];
8100 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8101 bool needs_poll = false;
8102 int ret = 0, err = -ECANCELED;
8104 /* one will be dropped by ->io_free_work() after returning to io-wq */
8105 if (!(req->flags & REQ_F_REFCOUNT))
8106 __io_req_set_refcount(req, 2);
8110 io_arm_ltimeout(req);
8112 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8113 if (work->flags & IO_WQ_WORK_CANCEL) {
8115 io_req_task_queue_fail(req, err);
8118 if (!io_assign_file(req, issue_flags)) {
8120 work->flags |= IO_WQ_WORK_CANCEL;
8124 if (req->flags & REQ_F_FORCE_ASYNC) {
8125 bool opcode_poll = def->pollin || def->pollout;
8127 if (opcode_poll && file_can_poll(req->file)) {
8129 issue_flags |= IO_URING_F_NONBLOCK;
8134 ret = io_issue_sqe(req, issue_flags);
8138 * We can get EAGAIN for iopolled IO even though we're
8139 * forcing a sync submission from here, since we can't
8140 * wait for request slots on the block side.
8143 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8149 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8151 /* aborted or ready, in either case retry blocking */
8153 issue_flags &= ~IO_URING_F_NONBLOCK;
8156 /* avoid locking problems by failing it from a clean context */
8158 io_req_task_queue_fail(req, ret);
8161 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8164 return &table->files[i];
8167 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8170 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8172 return (struct file *) (slot->file_ptr & FFS_MASK);
8175 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8177 unsigned long file_ptr = (unsigned long) file;
8179 file_ptr |= io_file_get_flags(file);
8180 file_slot->file_ptr = file_ptr;
8183 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8184 unsigned int issue_flags)
8186 struct io_ring_ctx *ctx = req->ctx;
8187 struct file *file = NULL;
8188 unsigned long file_ptr;
8190 io_ring_submit_lock(ctx, issue_flags);
8192 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8194 fd = array_index_nospec(fd, ctx->nr_user_files);
8195 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8196 file = (struct file *) (file_ptr & FFS_MASK);
8197 file_ptr &= ~FFS_MASK;
8198 /* mask in overlapping REQ_F and FFS bits */
8199 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8200 io_req_set_rsrc_node(req, ctx, 0);
8201 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8203 io_ring_submit_unlock(ctx, issue_flags);
8207 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8209 struct file *file = fget(fd);
8211 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8213 /* we don't allow fixed io_uring files */
8214 if (file && file->f_op == &io_uring_fops)
8215 io_req_track_inflight(req);
8219 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8221 struct io_timeout *timeout = io_kiocb_to_cmd(req);
8222 struct io_kiocb *prev = timeout->prev;
8226 if (!(req->task->flags & PF_EXITING)) {
8227 struct io_cancel_data cd = {
8229 .data = prev->cqe.user_data,
8232 ret = io_try_cancel(req, &cd);
8234 io_req_complete_post(req, ret ?: -ETIME, 0);
8237 io_req_complete_post(req, -ETIME, 0);
8241 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8243 struct io_timeout_data *data = container_of(timer,
8244 struct io_timeout_data, timer);
8245 struct io_kiocb *prev, *req = data->req;
8246 struct io_timeout *timeout = io_kiocb_to_cmd(req);
8247 struct io_ring_ctx *ctx = req->ctx;
8248 unsigned long flags;
8250 spin_lock_irqsave(&ctx->timeout_lock, flags);
8251 prev = timeout->head;
8252 timeout->head = NULL;
8255 * We don't expect the list to be empty, that will only happen if we
8256 * race with the completion of the linked work.
8259 io_remove_next_linked(prev);
8260 if (!req_ref_inc_not_zero(prev))
8263 list_del(&timeout->list);
8264 timeout->prev = prev;
8265 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8267 req->io_task_work.func = io_req_task_link_timeout;
8268 io_req_task_work_add(req);
8269 return HRTIMER_NORESTART;
8272 static void io_queue_linked_timeout(struct io_kiocb *req)
8274 struct io_timeout *timeout = io_kiocb_to_cmd(req);
8275 struct io_ring_ctx *ctx = req->ctx;
8277 spin_lock_irq(&ctx->timeout_lock);
8279 * If the back reference is NULL, then our linked request finished
8280 * before we got a chance to setup the timer
8282 if (timeout->head) {
8283 struct io_timeout_data *data = req->async_data;
8285 data->timer.function = io_link_timeout_fn;
8286 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8288 list_add_tail(&timeout->list, &ctx->ltimeout_list);
8290 spin_unlock_irq(&ctx->timeout_lock);
8291 /* drop submission reference */
8295 static void io_queue_async(struct io_kiocb *req, int ret)
8296 __must_hold(&req->ctx->uring_lock)
8298 struct io_kiocb *linked_timeout;
8300 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8301 io_req_complete_failed(req, ret);
8305 linked_timeout = io_prep_linked_timeout(req);
8307 switch (io_arm_poll_handler(req, 0)) {
8308 case IO_APOLL_READY:
8309 io_req_task_queue(req);
8311 case IO_APOLL_ABORTED:
8313 * Queued up for async execution, worker will release
8314 * submit reference when the iocb is actually submitted.
8316 io_kbuf_recycle(req, 0);
8317 io_queue_iowq(req, NULL);
8324 io_queue_linked_timeout(linked_timeout);
8327 static inline void io_queue_sqe(struct io_kiocb *req)
8328 __must_hold(&req->ctx->uring_lock)
8332 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8334 if (req->flags & REQ_F_COMPLETE_INLINE) {
8335 io_req_add_compl_list(req);
8339 * We async punt it if the file wasn't marked NOWAIT, or if the file
8340 * doesn't support non-blocking read/write attempts
8343 io_arm_ltimeout(req);
8345 io_queue_async(req, ret);
8348 static void io_queue_sqe_fallback(struct io_kiocb *req)
8349 __must_hold(&req->ctx->uring_lock)
8351 if (unlikely(req->flags & REQ_F_FAIL)) {
8353 * We don't submit, fail them all, for that replace hardlinks
8354 * with normal links. Extra REQ_F_LINK is tolerated.
8356 req->flags &= ~REQ_F_HARDLINK;
8357 req->flags |= REQ_F_LINK;
8358 io_req_complete_failed(req, req->cqe.res);
8359 } else if (unlikely(req->ctx->drain_active)) {
8362 int ret = io_req_prep_async(req);
8365 io_req_complete_failed(req, ret);
8367 io_queue_iowq(req, NULL);
8372 * Check SQE restrictions (opcode and flags).
8374 * Returns 'true' if SQE is allowed, 'false' otherwise.
8376 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8377 struct io_kiocb *req,
8378 unsigned int sqe_flags)
8380 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8383 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8384 ctx->restrictions.sqe_flags_required)
8387 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8388 ctx->restrictions.sqe_flags_required))
8394 static void io_init_req_drain(struct io_kiocb *req)
8396 struct io_ring_ctx *ctx = req->ctx;
8397 struct io_kiocb *head = ctx->submit_state.link.head;
8399 ctx->drain_active = true;
8402 * If we need to drain a request in the middle of a link, drain
8403 * the head request and the next request/link after the current
8404 * link. Considering sequential execution of links,
8405 * REQ_F_IO_DRAIN will be maintained for every request of our
8408 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8409 ctx->drain_next = true;
8413 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8414 const struct io_uring_sqe *sqe)
8415 __must_hold(&ctx->uring_lock)
8417 const struct io_op_def *def;
8418 unsigned int sqe_flags;
8422 /* req is partially pre-initialised, see io_preinit_req() */
8423 req->opcode = opcode = READ_ONCE(sqe->opcode);
8424 /* same numerical values with corresponding REQ_F_*, safe to copy */
8425 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8426 req->cqe.user_data = READ_ONCE(sqe->user_data);
8428 req->rsrc_node = NULL;
8429 req->task = current;
8431 if (unlikely(opcode >= IORING_OP_LAST)) {
8435 def = &io_op_defs[opcode];
8436 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8437 /* enforce forwards compatibility on users */
8438 if (sqe_flags & ~SQE_VALID_FLAGS)
8440 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8441 if (!def->buffer_select)
8443 req->buf_index = READ_ONCE(sqe->buf_group);
8445 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8446 ctx->drain_disabled = true;
8447 if (sqe_flags & IOSQE_IO_DRAIN) {
8448 if (ctx->drain_disabled)
8450 io_init_req_drain(req);
8453 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8454 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8456 /* knock it to the slow queue path, will be drained there */
8457 if (ctx->drain_active)
8458 req->flags |= REQ_F_FORCE_ASYNC;
8459 /* if there is no link, we're at "next" request and need to drain */
8460 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8461 ctx->drain_next = false;
8462 ctx->drain_active = true;
8463 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8467 if (!def->ioprio && sqe->ioprio)
8469 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8472 if (def->needs_file) {
8473 struct io_submit_state *state = &ctx->submit_state;
8475 req->cqe.fd = READ_ONCE(sqe->fd);
8478 * Plug now if we have more than 2 IO left after this, and the
8479 * target is potentially a read/write to block based storage.
8481 if (state->need_plug && def->plug) {
8482 state->plug_started = true;
8483 state->need_plug = false;
8484 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8488 personality = READ_ONCE(sqe->personality);
8492 req->creds = xa_load(&ctx->personalities, personality);
8495 get_cred(req->creds);
8496 ret = security_uring_override_creds(req->creds);
8498 put_cred(req->creds);
8501 req->flags |= REQ_F_CREDS;
8504 return def->prep(req, sqe);
8507 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8508 struct io_kiocb *req, int ret)
8510 struct io_ring_ctx *ctx = req->ctx;
8511 struct io_submit_link *link = &ctx->submit_state.link;
8512 struct io_kiocb *head = link->head;
8514 trace_io_uring_req_failed(sqe, ctx, req, ret);
8517 * Avoid breaking links in the middle as it renders links with SQPOLL
8518 * unusable. Instead of failing eagerly, continue assembling the link if
8519 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8520 * should find the flag and handle the rest.
8522 req_fail_link_node(req, ret);
8523 if (head && !(head->flags & REQ_F_FAIL))
8524 req_fail_link_node(head, -ECANCELED);
8526 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8528 link->last->link = req;
8532 io_queue_sqe_fallback(req);
8537 link->last->link = req;
8544 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8545 const struct io_uring_sqe *sqe)
8546 __must_hold(&ctx->uring_lock)
8548 struct io_submit_link *link = &ctx->submit_state.link;
8551 ret = io_init_req(ctx, req, sqe);
8553 return io_submit_fail_init(sqe, req, ret);
8555 /* don't need @sqe from now on */
8556 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8558 ctx->flags & IORING_SETUP_SQPOLL);
8561 * If we already have a head request, queue this one for async
8562 * submittal once the head completes. If we don't have a head but
8563 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8564 * submitted sync once the chain is complete. If none of those
8565 * conditions are true (normal request), then just queue it.
8567 if (unlikely(link->head)) {
8568 ret = io_req_prep_async(req);
8570 return io_submit_fail_init(sqe, req, ret);
8572 trace_io_uring_link(ctx, req, link->head);
8573 link->last->link = req;
8576 if (req->flags & IO_REQ_LINK_FLAGS)
8578 /* last request of the link, flush it */
8581 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8584 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8585 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8586 if (req->flags & IO_REQ_LINK_FLAGS) {
8591 io_queue_sqe_fallback(req);
8601 * Batched submission is done, ensure local IO is flushed out.
8603 static void io_submit_state_end(struct io_ring_ctx *ctx)
8605 struct io_submit_state *state = &ctx->submit_state;
8607 if (unlikely(state->link.head))
8608 io_queue_sqe_fallback(state->link.head);
8609 /* flush only after queuing links as they can generate completions */
8610 io_submit_flush_completions(ctx);
8611 if (state->plug_started)
8612 blk_finish_plug(&state->plug);
8616 * Start submission side cache.
8618 static void io_submit_state_start(struct io_submit_state *state,
8619 unsigned int max_ios)
8621 state->plug_started = false;
8622 state->need_plug = max_ios > 2;
8623 state->submit_nr = max_ios;
8624 /* set only head, no need to init link_last in advance */
8625 state->link.head = NULL;
8628 static void io_commit_sqring(struct io_ring_ctx *ctx)
8630 struct io_rings *rings = ctx->rings;
8633 * Ensure any loads from the SQEs are done at this point,
8634 * since once we write the new head, the application could
8635 * write new data to them.
8637 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
8641 * Fetch an sqe, if one is available. Note this returns a pointer to memory
8642 * that is mapped by userspace. This means that care needs to be taken to
8643 * ensure that reads are stable, as we cannot rely on userspace always
8644 * being a good citizen. If members of the sqe are validated and then later
8645 * used, it's important that those reads are done through READ_ONCE() to
8646 * prevent a re-load down the line.
8648 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
8650 unsigned head, mask = ctx->sq_entries - 1;
8651 unsigned sq_idx = ctx->cached_sq_head++ & mask;
8654 * The cached sq head (or cq tail) serves two purposes:
8656 * 1) allows us to batch the cost of updating the user visible
8658 * 2) allows the kernel side to track the head on its own, even
8659 * though the application is the one updating it.
8661 head = READ_ONCE(ctx->sq_array[sq_idx]);
8662 if (likely(head < ctx->sq_entries)) {
8663 /* double index for 128-byte SQEs, twice as long */
8664 if (ctx->flags & IORING_SETUP_SQE128)
8666 return &ctx->sq_sqes[head];
8669 /* drop invalid entries */
8671 WRITE_ONCE(ctx->rings->sq_dropped,
8672 READ_ONCE(ctx->rings->sq_dropped) + 1);
8676 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
8677 __must_hold(&ctx->uring_lock)
8679 unsigned int entries = io_sqring_entries(ctx);
8683 if (unlikely(!entries))
8685 /* make sure SQ entry isn't read before tail */
8686 ret = left = min3(nr, ctx->sq_entries, entries);
8687 io_get_task_refs(left);
8688 io_submit_state_start(&ctx->submit_state, left);
8691 const struct io_uring_sqe *sqe;
8692 struct io_kiocb *req;
8694 if (unlikely(!io_alloc_req_refill(ctx)))
8696 req = io_alloc_req(ctx);
8697 sqe = io_get_sqe(ctx);
8698 if (unlikely(!sqe)) {
8699 io_req_add_to_cache(req, ctx);
8704 * Continue submitting even for sqe failure if the
8705 * ring was setup with IORING_SETUP_SUBMIT_ALL
8707 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
8708 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
8714 if (unlikely(left)) {
8716 /* try again if it submitted nothing and can't allocate a req */
8717 if (!ret && io_req_cache_empty(ctx))
8719 current->io_uring->cached_refs += left;
8722 io_submit_state_end(ctx);
8723 /* Commit SQ ring head once we've consumed and submitted all SQEs */
8724 io_commit_sqring(ctx);
8728 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
8730 return READ_ONCE(sqd->state);
8733 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
8735 unsigned int to_submit;
8738 to_submit = io_sqring_entries(ctx);
8739 /* if we're handling multiple rings, cap submit size for fairness */
8740 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
8741 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
8743 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
8744 const struct cred *creds = NULL;
8746 if (ctx->sq_creds != current_cred())
8747 creds = override_creds(ctx->sq_creds);
8749 mutex_lock(&ctx->uring_lock);
8750 if (!wq_list_empty(&ctx->iopoll_list))
8751 io_do_iopoll(ctx, true);
8754 * Don't submit if refs are dying, good for io_uring_register(),
8755 * but also it is relied upon by io_ring_exit_work()
8757 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
8758 !(ctx->flags & IORING_SETUP_R_DISABLED))
8759 ret = io_submit_sqes(ctx, to_submit);
8760 mutex_unlock(&ctx->uring_lock);
8762 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8763 wake_up(&ctx->sqo_sq_wait);
8765 revert_creds(creds);
8771 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8773 struct io_ring_ctx *ctx;
8774 unsigned sq_thread_idle = 0;
8776 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8777 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8778 sqd->sq_thread_idle = sq_thread_idle;
8781 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8783 bool did_sig = false;
8784 struct ksignal ksig;
8786 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8787 signal_pending(current)) {
8788 mutex_unlock(&sqd->lock);
8789 if (signal_pending(current))
8790 did_sig = get_signal(&ksig);
8792 mutex_lock(&sqd->lock);
8794 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8797 static int io_sq_thread(void *data)
8799 struct io_sq_data *sqd = data;
8800 struct io_ring_ctx *ctx;
8801 unsigned long timeout = 0;
8802 char buf[TASK_COMM_LEN];
8805 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8806 set_task_comm(current, buf);
8808 if (sqd->sq_cpu != -1)
8809 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8811 set_cpus_allowed_ptr(current, cpu_online_mask);
8812 current->flags |= PF_NO_SETAFFINITY;
8814 audit_alloc_kernel(current);
8816 mutex_lock(&sqd->lock);
8818 bool cap_entries, sqt_spin = false;
8820 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8821 if (io_sqd_handle_event(sqd))
8823 timeout = jiffies + sqd->sq_thread_idle;
8826 cap_entries = !list_is_singular(&sqd->ctx_list);
8827 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8828 int ret = __io_sq_thread(ctx, cap_entries);
8830 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8833 if (io_run_task_work())
8836 if (sqt_spin || !time_after(jiffies, timeout)) {
8839 timeout = jiffies + sqd->sq_thread_idle;
8843 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8844 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8845 bool needs_sched = true;
8847 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8848 atomic_or(IORING_SQ_NEED_WAKEUP,
8849 &ctx->rings->sq_flags);
8850 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8851 !wq_list_empty(&ctx->iopoll_list)) {
8852 needs_sched = false;
8857 * Ensure the store of the wakeup flag is not
8858 * reordered with the load of the SQ tail
8860 smp_mb__after_atomic();
8862 if (io_sqring_entries(ctx)) {
8863 needs_sched = false;
8869 mutex_unlock(&sqd->lock);
8871 mutex_lock(&sqd->lock);
8873 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8874 atomic_andnot(IORING_SQ_NEED_WAKEUP,
8875 &ctx->rings->sq_flags);
8878 finish_wait(&sqd->wait, &wait);
8879 timeout = jiffies + sqd->sq_thread_idle;
8882 io_uring_cancel_generic(true, sqd);
8884 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8885 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
8887 mutex_unlock(&sqd->lock);
8889 audit_free(current);
8891 complete(&sqd->exited);
8895 struct io_wait_queue {
8896 struct wait_queue_entry wq;
8897 struct io_ring_ctx *ctx;
8899 unsigned nr_timeouts;
8902 static inline bool io_should_wake(struct io_wait_queue *iowq)
8904 struct io_ring_ctx *ctx = iowq->ctx;
8905 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8908 * Wake up if we have enough events, or if a timeout occurred since we
8909 * started waiting. For timeouts, we always want to return to userspace,
8910 * regardless of event count.
8912 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8915 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8916 int wake_flags, void *key)
8918 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8922 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8923 * the task, and the next invocation will do it.
8925 if (io_should_wake(iowq) ||
8926 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
8927 return autoremove_wake_function(curr, mode, wake_flags, key);
8931 static int io_run_task_work_sig(void)
8933 if (io_run_task_work())
8935 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8936 return -ERESTARTSYS;
8937 if (task_sigpending(current))
8942 /* when returns >0, the caller should retry */
8943 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8944 struct io_wait_queue *iowq,
8948 unsigned long check_cq;
8950 /* make sure we run task_work before checking for signals */
8951 ret = io_run_task_work_sig();
8952 if (ret || io_should_wake(iowq))
8954 check_cq = READ_ONCE(ctx->check_cq);
8955 /* let the caller flush overflows, retry */
8956 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
8958 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
8960 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8966 * Wait until events become available, if we don't already have some. The
8967 * application must reap them itself, as they reside on the shared cq ring.
8969 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8970 const sigset_t __user *sig, size_t sigsz,
8971 struct __kernel_timespec __user *uts)
8973 struct io_wait_queue iowq;
8974 struct io_rings *rings = ctx->rings;
8975 ktime_t timeout = KTIME_MAX;
8979 io_cqring_overflow_flush(ctx);
8980 if (io_cqring_events(ctx) >= min_events)
8982 if (!io_run_task_work())
8987 #ifdef CONFIG_COMPAT
8988 if (in_compat_syscall())
8989 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8993 ret = set_user_sigmask(sig, sigsz);
9000 struct timespec64 ts;
9002 if (get_timespec64(&ts, uts))
9004 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9007 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9008 iowq.wq.private = current;
9009 INIT_LIST_HEAD(&iowq.wq.entry);
9011 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9012 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9014 trace_io_uring_cqring_wait(ctx, min_events);
9016 /* if we can't even flush overflow, don't wait for more */
9017 if (!io_cqring_overflow_flush(ctx)) {
9021 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9022 TASK_INTERRUPTIBLE);
9023 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9027 finish_wait(&ctx->cq_wait, &iowq.wq);
9028 restore_saved_sigmask_unless(ret == -EINTR);
9030 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9033 static void io_free_page_table(void **table, size_t size)
9035 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9037 for (i = 0; i < nr_tables; i++)
9042 static __cold void **io_alloc_page_table(size_t size)
9044 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9045 size_t init_size = size;
9048 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9052 for (i = 0; i < nr_tables; i++) {
9053 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9055 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9057 io_free_page_table(table, init_size);
9065 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9067 percpu_ref_exit(&ref_node->refs);
9071 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9073 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9074 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9075 unsigned long flags;
9076 bool first_add = false;
9077 unsigned long delay = HZ;
9079 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9082 /* if we are mid-quiesce then do not delay */
9083 if (node->rsrc_data->quiesce)
9086 while (!list_empty(&ctx->rsrc_ref_list)) {
9087 node = list_first_entry(&ctx->rsrc_ref_list,
9088 struct io_rsrc_node, node);
9089 /* recycle ref nodes in order */
9092 list_del(&node->node);
9093 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9095 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9098 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9101 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9103 struct io_rsrc_node *ref_node;
9105 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9109 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9114 INIT_LIST_HEAD(&ref_node->node);
9115 INIT_LIST_HEAD(&ref_node->rsrc_list);
9116 ref_node->done = false;
9120 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9121 struct io_rsrc_data *data_to_kill)
9122 __must_hold(&ctx->uring_lock)
9124 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9125 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9127 io_rsrc_refs_drop(ctx);
9130 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9132 rsrc_node->rsrc_data = data_to_kill;
9133 spin_lock_irq(&ctx->rsrc_ref_lock);
9134 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9135 spin_unlock_irq(&ctx->rsrc_ref_lock);
9137 atomic_inc(&data_to_kill->refs);
9138 percpu_ref_kill(&rsrc_node->refs);
9139 ctx->rsrc_node = NULL;
9142 if (!ctx->rsrc_node) {
9143 ctx->rsrc_node = ctx->rsrc_backup_node;
9144 ctx->rsrc_backup_node = NULL;
9148 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9150 if (ctx->rsrc_backup_node)
9152 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9153 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9156 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9157 struct io_ring_ctx *ctx)
9161 /* As we may drop ->uring_lock, other task may have started quiesce */
9165 data->quiesce = true;
9167 ret = io_rsrc_node_switch_start(ctx);
9170 io_rsrc_node_switch(ctx, data);
9172 /* kill initial ref, already quiesced if zero */
9173 if (atomic_dec_and_test(&data->refs))
9175 mutex_unlock(&ctx->uring_lock);
9176 flush_delayed_work(&ctx->rsrc_put_work);
9177 ret = wait_for_completion_interruptible(&data->done);
9179 mutex_lock(&ctx->uring_lock);
9180 if (atomic_read(&data->refs) > 0) {
9182 * it has been revived by another thread while
9185 mutex_unlock(&ctx->uring_lock);
9191 atomic_inc(&data->refs);
9192 /* wait for all works potentially completing data->done */
9193 flush_delayed_work(&ctx->rsrc_put_work);
9194 reinit_completion(&data->done);
9196 ret = io_run_task_work_sig();
9197 mutex_lock(&ctx->uring_lock);
9199 data->quiesce = false;
9204 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9206 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9207 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9209 return &data->tags[table_idx][off];
9212 static void io_rsrc_data_free(struct io_rsrc_data *data)
9214 size_t size = data->nr * sizeof(data->tags[0][0]);
9217 io_free_page_table((void **)data->tags, size);
9221 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9222 u64 __user *utags, unsigned nr,
9223 struct io_rsrc_data **pdata)
9225 struct io_rsrc_data *data;
9229 data = kzalloc(sizeof(*data), GFP_KERNEL);
9232 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9240 data->do_put = do_put;
9243 for (i = 0; i < nr; i++) {
9244 u64 *tag_slot = io_get_tag_slot(data, i);
9246 if (copy_from_user(tag_slot, &utags[i],
9252 atomic_set(&data->refs, 1);
9253 init_completion(&data->done);
9257 io_rsrc_data_free(data);
9261 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9263 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9264 GFP_KERNEL_ACCOUNT);
9265 if (unlikely(!table->files))
9268 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9269 if (unlikely(!table->bitmap)) {
9270 kvfree(table->files);
9277 static void io_free_file_tables(struct io_file_table *table)
9279 kvfree(table->files);
9280 bitmap_free(table->bitmap);
9281 table->files = NULL;
9282 table->bitmap = NULL;
9285 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9287 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9288 __set_bit(bit, table->bitmap);
9289 table->alloc_hint = bit + 1;
9292 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9294 __clear_bit(bit, table->bitmap);
9295 table->alloc_hint = bit;
9298 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9300 #if !defined(IO_URING_SCM_ALL)
9303 for (i = 0; i < ctx->nr_user_files; i++) {
9304 struct file *file = io_file_from_index(ctx, i);
9308 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9310 io_file_bitmap_clear(&ctx->file_table, i);
9315 #if defined(CONFIG_UNIX)
9316 if (ctx->ring_sock) {
9317 struct sock *sock = ctx->ring_sock->sk;
9318 struct sk_buff *skb;
9320 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9324 io_free_file_tables(&ctx->file_table);
9325 io_rsrc_data_free(ctx->file_data);
9326 ctx->file_data = NULL;
9327 ctx->nr_user_files = 0;
9330 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9332 unsigned nr = ctx->nr_user_files;
9335 if (!ctx->file_data)
9339 * Quiesce may unlock ->uring_lock, and while it's not held
9340 * prevent new requests using the table.
9342 ctx->nr_user_files = 0;
9343 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9344 ctx->nr_user_files = nr;
9346 __io_sqe_files_unregister(ctx);
9350 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9351 __releases(&sqd->lock)
9353 WARN_ON_ONCE(sqd->thread == current);
9356 * Do the dance but not conditional clear_bit() because it'd race with
9357 * other threads incrementing park_pending and setting the bit.
9359 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9360 if (atomic_dec_return(&sqd->park_pending))
9361 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9362 mutex_unlock(&sqd->lock);
9365 static void io_sq_thread_park(struct io_sq_data *sqd)
9366 __acquires(&sqd->lock)
9368 WARN_ON_ONCE(sqd->thread == current);
9370 atomic_inc(&sqd->park_pending);
9371 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9372 mutex_lock(&sqd->lock);
9374 wake_up_process(sqd->thread);
9377 static void io_sq_thread_stop(struct io_sq_data *sqd)
9379 WARN_ON_ONCE(sqd->thread == current);
9380 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9382 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9383 mutex_lock(&sqd->lock);
9385 wake_up_process(sqd->thread);
9386 mutex_unlock(&sqd->lock);
9387 wait_for_completion(&sqd->exited);
9390 static void io_put_sq_data(struct io_sq_data *sqd)
9392 if (refcount_dec_and_test(&sqd->refs)) {
9393 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9395 io_sq_thread_stop(sqd);
9400 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9402 struct io_sq_data *sqd = ctx->sq_data;
9405 io_sq_thread_park(sqd);
9406 list_del_init(&ctx->sqd_list);
9407 io_sqd_update_thread_idle(sqd);
9408 io_sq_thread_unpark(sqd);
9410 io_put_sq_data(sqd);
9411 ctx->sq_data = NULL;
9415 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9417 struct io_ring_ctx *ctx_attach;
9418 struct io_sq_data *sqd;
9421 f = fdget(p->wq_fd);
9423 return ERR_PTR(-ENXIO);
9424 if (f.file->f_op != &io_uring_fops) {
9426 return ERR_PTR(-EINVAL);
9429 ctx_attach = f.file->private_data;
9430 sqd = ctx_attach->sq_data;
9433 return ERR_PTR(-EINVAL);
9435 if (sqd->task_tgid != current->tgid) {
9437 return ERR_PTR(-EPERM);
9440 refcount_inc(&sqd->refs);
9445 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9448 struct io_sq_data *sqd;
9451 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9452 sqd = io_attach_sq_data(p);
9457 /* fall through for EPERM case, setup new sqd/task */
9458 if (PTR_ERR(sqd) != -EPERM)
9462 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9464 return ERR_PTR(-ENOMEM);
9466 atomic_set(&sqd->park_pending, 0);
9467 refcount_set(&sqd->refs, 1);
9468 INIT_LIST_HEAD(&sqd->ctx_list);
9469 mutex_init(&sqd->lock);
9470 init_waitqueue_head(&sqd->wait);
9471 init_completion(&sqd->exited);
9476 * Ensure the UNIX gc is aware of our file set, so we are certain that
9477 * the io_uring can be safely unregistered on process exit, even if we have
9478 * loops in the file referencing. We account only files that can hold other
9479 * files because otherwise they can't form a loop and so are not interesting
9482 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9484 #if defined(CONFIG_UNIX)
9485 struct sock *sk = ctx->ring_sock->sk;
9486 struct sk_buff_head *head = &sk->sk_receive_queue;
9487 struct scm_fp_list *fpl;
9488 struct sk_buff *skb;
9490 if (likely(!io_file_need_scm(file)))
9494 * See if we can merge this file into an existing skb SCM_RIGHTS
9495 * file set. If there's no room, fall back to allocating a new skb
9496 * and filling it in.
9498 spin_lock_irq(&head->lock);
9499 skb = skb_peek(head);
9500 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9501 __skb_unlink(skb, head);
9504 spin_unlock_irq(&head->lock);
9507 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9511 skb = alloc_skb(0, GFP_KERNEL);
9517 fpl->user = get_uid(current_user());
9518 fpl->max = SCM_MAX_FD;
9521 UNIXCB(skb).fp = fpl;
9523 skb->destructor = unix_destruct_scm;
9524 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9527 fpl = UNIXCB(skb).fp;
9528 fpl->fp[fpl->count++] = get_file(file);
9529 unix_inflight(fpl->user, file);
9530 skb_queue_head(head, skb);
9536 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9538 struct file *file = prsrc->file;
9539 #if defined(CONFIG_UNIX)
9540 struct sock *sock = ctx->ring_sock->sk;
9541 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9542 struct sk_buff *skb;
9545 if (!io_file_need_scm(file)) {
9550 __skb_queue_head_init(&list);
9553 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9554 * remove this entry and rearrange the file array.
9556 skb = skb_dequeue(head);
9558 struct scm_fp_list *fp;
9560 fp = UNIXCB(skb).fp;
9561 for (i = 0; i < fp->count; i++) {
9564 if (fp->fp[i] != file)
9567 unix_notinflight(fp->user, fp->fp[i]);
9568 left = fp->count - 1 - i;
9570 memmove(&fp->fp[i], &fp->fp[i + 1],
9571 left * sizeof(struct file *));
9578 __skb_queue_tail(&list, skb);
9588 __skb_queue_tail(&list, skb);
9590 skb = skb_dequeue(head);
9593 if (skb_peek(&list)) {
9594 spin_lock_irq(&head->lock);
9595 while ((skb = __skb_dequeue(&list)) != NULL)
9596 __skb_queue_tail(head, skb);
9597 spin_unlock_irq(&head->lock);
9604 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9606 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9607 struct io_ring_ctx *ctx = rsrc_data->ctx;
9608 struct io_rsrc_put *prsrc, *tmp;
9610 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9611 list_del(&prsrc->list);
9614 if (ctx->flags & IORING_SETUP_IOPOLL)
9615 mutex_lock(&ctx->uring_lock);
9617 spin_lock(&ctx->completion_lock);
9618 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9619 io_commit_cqring(ctx);
9620 spin_unlock(&ctx->completion_lock);
9621 io_cqring_ev_posted(ctx);
9623 if (ctx->flags & IORING_SETUP_IOPOLL)
9624 mutex_unlock(&ctx->uring_lock);
9627 rsrc_data->do_put(ctx, prsrc);
9631 io_rsrc_node_destroy(ref_node);
9632 if (atomic_dec_and_test(&rsrc_data->refs))
9633 complete(&rsrc_data->done);
9636 static void io_rsrc_put_work(struct work_struct *work)
9638 struct io_ring_ctx *ctx;
9639 struct llist_node *node;
9641 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
9642 node = llist_del_all(&ctx->rsrc_put_llist);
9645 struct io_rsrc_node *ref_node;
9646 struct llist_node *next = node->next;
9648 ref_node = llist_entry(node, struct io_rsrc_node, llist);
9649 __io_rsrc_put_work(ref_node);
9654 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
9655 unsigned nr_args, u64 __user *tags)
9657 __s32 __user *fds = (__s32 __user *) arg;
9666 if (nr_args > IORING_MAX_FIXED_FILES)
9668 if (nr_args > rlimit(RLIMIT_NOFILE))
9670 ret = io_rsrc_node_switch_start(ctx);
9673 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9678 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
9679 io_rsrc_data_free(ctx->file_data);
9680 ctx->file_data = NULL;
9684 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9685 struct io_fixed_file *file_slot;
9687 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
9691 /* allow sparse sets */
9692 if (!fds || fd == -1) {
9694 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9701 if (unlikely(!file))
9705 * Don't allow io_uring instances to be registered. If UNIX
9706 * isn't enabled, then this causes a reference cycle and this
9707 * instance can never get freed. If UNIX is enabled we'll
9708 * handle it just fine, but there's still no point in allowing
9709 * a ring fd as it doesn't support regular read/write anyway.
9711 if (file->f_op == &io_uring_fops) {
9715 ret = io_scm_file_account(ctx, file);
9720 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9721 io_fixed_file_set(file_slot, file);
9722 io_file_bitmap_set(&ctx->file_table, i);
9725 io_rsrc_node_switch(ctx, NULL);
9728 __io_sqe_files_unregister(ctx);
9732 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9733 struct io_rsrc_node *node, void *rsrc)
9735 u64 *tag_slot = io_get_tag_slot(data, idx);
9736 struct io_rsrc_put *prsrc;
9738 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9742 prsrc->tag = *tag_slot;
9745 list_add(&prsrc->list, &node->rsrc_list);
9749 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9750 unsigned int issue_flags, u32 slot_index)
9751 __must_hold(&req->ctx->uring_lock)
9753 struct io_ring_ctx *ctx = req->ctx;
9754 bool needs_switch = false;
9755 struct io_fixed_file *file_slot;
9758 if (file->f_op == &io_uring_fops)
9760 if (!ctx->file_data)
9762 if (slot_index >= ctx->nr_user_files)
9765 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9766 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9768 if (file_slot->file_ptr) {
9769 struct file *old_file;
9771 ret = io_rsrc_node_switch_start(ctx);
9775 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9776 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9777 ctx->rsrc_node, old_file);
9780 file_slot->file_ptr = 0;
9781 io_file_bitmap_clear(&ctx->file_table, slot_index);
9782 needs_switch = true;
9785 ret = io_scm_file_account(ctx, file);
9787 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9788 io_fixed_file_set(file_slot, file);
9789 io_file_bitmap_set(&ctx->file_table, slot_index);
9793 io_rsrc_node_switch(ctx, ctx->file_data);
9799 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
9800 unsigned int offset)
9802 struct io_ring_ctx *ctx = req->ctx;
9803 struct io_fixed_file *file_slot;
9807 io_ring_submit_lock(ctx, issue_flags);
9809 if (unlikely(!ctx->file_data))
9812 if (offset >= ctx->nr_user_files)
9814 ret = io_rsrc_node_switch_start(ctx);
9818 offset = array_index_nospec(offset, ctx->nr_user_files);
9819 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9821 if (!file_slot->file_ptr)
9824 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9825 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9829 file_slot->file_ptr = 0;
9830 io_file_bitmap_clear(&ctx->file_table, offset);
9831 io_rsrc_node_switch(ctx, ctx->file_data);
9834 io_ring_submit_unlock(ctx, issue_flags);
9838 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9840 struct io_close *close = io_kiocb_to_cmd(req);
9842 return __io_close_fixed(req, issue_flags, close->file_slot - 1);
9845 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9846 struct io_uring_rsrc_update2 *up,
9849 u64 __user *tags = u64_to_user_ptr(up->tags);
9850 __s32 __user *fds = u64_to_user_ptr(up->data);
9851 struct io_rsrc_data *data = ctx->file_data;
9852 struct io_fixed_file *file_slot;
9856 bool needs_switch = false;
9858 if (!ctx->file_data)
9860 if (up->offset + nr_args > ctx->nr_user_files)
9863 for (done = 0; done < nr_args; done++) {
9866 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9867 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9871 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9875 if (fd == IORING_REGISTER_FILES_SKIP)
9878 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9879 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9881 if (file_slot->file_ptr) {
9882 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9883 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9886 file_slot->file_ptr = 0;
9887 io_file_bitmap_clear(&ctx->file_table, i);
9888 needs_switch = true;
9897 * Don't allow io_uring instances to be registered. If
9898 * UNIX isn't enabled, then this causes a reference
9899 * cycle and this instance can never get freed. If UNIX
9900 * is enabled we'll handle it just fine, but there's
9901 * still no point in allowing a ring fd as it doesn't
9902 * support regular read/write anyway.
9904 if (file->f_op == &io_uring_fops) {
9909 err = io_scm_file_account(ctx, file);
9914 *io_get_tag_slot(data, i) = tag;
9915 io_fixed_file_set(file_slot, file);
9916 io_file_bitmap_set(&ctx->file_table, i);
9921 io_rsrc_node_switch(ctx, data);
9922 return done ? done : err;
9925 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9926 struct task_struct *task)
9928 struct io_wq_hash *hash;
9929 struct io_wq_data data;
9930 unsigned int concurrency;
9932 mutex_lock(&ctx->uring_lock);
9933 hash = ctx->hash_map;
9935 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9937 mutex_unlock(&ctx->uring_lock);
9938 return ERR_PTR(-ENOMEM);
9940 refcount_set(&hash->refs, 1);
9941 init_waitqueue_head(&hash->wait);
9942 ctx->hash_map = hash;
9944 mutex_unlock(&ctx->uring_lock);
9948 data.free_work = io_wq_free_work;
9949 data.do_work = io_wq_submit_work;
9951 /* Do QD, or 4 * CPUS, whatever is smallest */
9952 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9954 return io_wq_create(concurrency, &data);
9957 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9958 struct io_ring_ctx *ctx)
9960 struct io_uring_task *tctx;
9963 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9964 if (unlikely(!tctx))
9967 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9968 sizeof(struct file *), GFP_KERNEL);
9969 if (unlikely(!tctx->registered_rings)) {
9974 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9975 if (unlikely(ret)) {
9976 kfree(tctx->registered_rings);
9981 tctx->io_wq = io_init_wq_offload(ctx, task);
9982 if (IS_ERR(tctx->io_wq)) {
9983 ret = PTR_ERR(tctx->io_wq);
9984 percpu_counter_destroy(&tctx->inflight);
9985 kfree(tctx->registered_rings);
9991 init_waitqueue_head(&tctx->wait);
9992 atomic_set(&tctx->in_idle, 0);
9993 atomic_set(&tctx->inflight_tracked, 0);
9994 task->io_uring = tctx;
9995 spin_lock_init(&tctx->task_lock);
9996 INIT_WQ_LIST(&tctx->task_list);
9997 INIT_WQ_LIST(&tctx->prio_task_list);
9998 init_task_work(&tctx->task_work, tctx_task_work);
10002 void __io_uring_free(struct task_struct *tsk)
10004 struct io_uring_task *tctx = tsk->io_uring;
10006 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10007 WARN_ON_ONCE(tctx->io_wq);
10008 WARN_ON_ONCE(tctx->cached_refs);
10010 kfree(tctx->registered_rings);
10011 percpu_counter_destroy(&tctx->inflight);
10013 tsk->io_uring = NULL;
10016 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10017 struct io_uring_params *p)
10021 /* Retain compatibility with failing for an invalid attach attempt */
10022 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10023 IORING_SETUP_ATTACH_WQ) {
10026 f = fdget(p->wq_fd);
10029 if (f.file->f_op != &io_uring_fops) {
10035 if (ctx->flags & IORING_SETUP_SQPOLL) {
10036 struct task_struct *tsk;
10037 struct io_sq_data *sqd;
10040 ret = security_uring_sqpoll();
10044 sqd = io_get_sq_data(p, &attached);
10046 ret = PTR_ERR(sqd);
10050 ctx->sq_creds = get_current_cred();
10051 ctx->sq_data = sqd;
10052 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10053 if (!ctx->sq_thread_idle)
10054 ctx->sq_thread_idle = HZ;
10056 io_sq_thread_park(sqd);
10057 list_add(&ctx->sqd_list, &sqd->ctx_list);
10058 io_sqd_update_thread_idle(sqd);
10059 /* don't attach to a dying SQPOLL thread, would be racy */
10060 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10061 io_sq_thread_unpark(sqd);
10068 if (p->flags & IORING_SETUP_SQ_AFF) {
10069 int cpu = p->sq_thread_cpu;
10072 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10079 sqd->task_pid = current->pid;
10080 sqd->task_tgid = current->tgid;
10081 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10083 ret = PTR_ERR(tsk);
10088 ret = io_uring_alloc_task_context(tsk, ctx);
10089 wake_up_new_task(tsk);
10092 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10093 /* Can't have SQ_AFF without SQPOLL */
10100 complete(&ctx->sq_data->exited);
10102 io_sq_thread_finish(ctx);
10106 static inline void __io_unaccount_mem(struct user_struct *user,
10107 unsigned long nr_pages)
10109 atomic_long_sub(nr_pages, &user->locked_vm);
10112 static inline int __io_account_mem(struct user_struct *user,
10113 unsigned long nr_pages)
10115 unsigned long page_limit, cur_pages, new_pages;
10117 /* Don't allow more pages than we can safely lock */
10118 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10121 cur_pages = atomic_long_read(&user->locked_vm);
10122 new_pages = cur_pages + nr_pages;
10123 if (new_pages > page_limit)
10125 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10126 new_pages) != cur_pages);
10131 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10134 __io_unaccount_mem(ctx->user, nr_pages);
10136 if (ctx->mm_account)
10137 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10140 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10145 ret = __io_account_mem(ctx->user, nr_pages);
10150 if (ctx->mm_account)
10151 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10156 static void io_mem_free(void *ptr)
10163 page = virt_to_head_page(ptr);
10164 if (put_page_testzero(page))
10165 free_compound_page(page);
10168 static void *io_mem_alloc(size_t size)
10170 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10172 return (void *) __get_free_pages(gfp, get_order(size));
10175 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10176 unsigned int cq_entries, size_t *sq_offset)
10178 struct io_rings *rings;
10179 size_t off, sq_array_size;
10181 off = struct_size(rings, cqes, cq_entries);
10182 if (off == SIZE_MAX)
10184 if (ctx->flags & IORING_SETUP_CQE32) {
10185 if (check_shl_overflow(off, 1, &off))
10190 off = ALIGN(off, SMP_CACHE_BYTES);
10198 sq_array_size = array_size(sizeof(u32), sq_entries);
10199 if (sq_array_size == SIZE_MAX)
10202 if (check_add_overflow(off, sq_array_size, &off))
10208 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10210 struct io_mapped_ubuf *imu = *slot;
10213 if (imu != ctx->dummy_ubuf) {
10214 for (i = 0; i < imu->nr_bvecs; i++)
10215 unpin_user_page(imu->bvec[i].bv_page);
10216 if (imu->acct_pages)
10217 io_unaccount_mem(ctx, imu->acct_pages);
10223 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10225 io_buffer_unmap(ctx, &prsrc->buf);
10229 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10233 for (i = 0; i < ctx->nr_user_bufs; i++)
10234 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10235 kfree(ctx->user_bufs);
10236 io_rsrc_data_free(ctx->buf_data);
10237 ctx->user_bufs = NULL;
10238 ctx->buf_data = NULL;
10239 ctx->nr_user_bufs = 0;
10242 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10244 unsigned nr = ctx->nr_user_bufs;
10247 if (!ctx->buf_data)
10251 * Quiesce may unlock ->uring_lock, and while it's not held
10252 * prevent new requests using the table.
10254 ctx->nr_user_bufs = 0;
10255 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10256 ctx->nr_user_bufs = nr;
10258 __io_sqe_buffers_unregister(ctx);
10262 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10263 void __user *arg, unsigned index)
10265 struct iovec __user *src;
10267 #ifdef CONFIG_COMPAT
10269 struct compat_iovec __user *ciovs;
10270 struct compat_iovec ciov;
10272 ciovs = (struct compat_iovec __user *) arg;
10273 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10276 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10277 dst->iov_len = ciov.iov_len;
10281 src = (struct iovec __user *) arg;
10282 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10288 * Not super efficient, but this is just a registration time. And we do cache
10289 * the last compound head, so generally we'll only do a full search if we don't
10292 * We check if the given compound head page has already been accounted, to
10293 * avoid double accounting it. This allows us to account the full size of the
10294 * page, not just the constituent pages of a huge page.
10296 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10297 int nr_pages, struct page *hpage)
10301 /* check current page array */
10302 for (i = 0; i < nr_pages; i++) {
10303 if (!PageCompound(pages[i]))
10305 if (compound_head(pages[i]) == hpage)
10309 /* check previously registered pages */
10310 for (i = 0; i < ctx->nr_user_bufs; i++) {
10311 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10313 for (j = 0; j < imu->nr_bvecs; j++) {
10314 if (!PageCompound(imu->bvec[j].bv_page))
10316 if (compound_head(imu->bvec[j].bv_page) == hpage)
10324 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10325 int nr_pages, struct io_mapped_ubuf *imu,
10326 struct page **last_hpage)
10330 imu->acct_pages = 0;
10331 for (i = 0; i < nr_pages; i++) {
10332 if (!PageCompound(pages[i])) {
10335 struct page *hpage;
10337 hpage = compound_head(pages[i]);
10338 if (hpage == *last_hpage)
10340 *last_hpage = hpage;
10341 if (headpage_already_acct(ctx, pages, i, hpage))
10343 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10347 if (!imu->acct_pages)
10350 ret = io_account_mem(ctx, imu->acct_pages);
10352 imu->acct_pages = 0;
10356 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10359 unsigned long start, end, nr_pages;
10360 struct vm_area_struct **vmas = NULL;
10361 struct page **pages = NULL;
10362 int i, pret, ret = -ENOMEM;
10364 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10365 start = ubuf >> PAGE_SHIFT;
10366 nr_pages = end - start;
10368 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10372 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10378 mmap_read_lock(current->mm);
10379 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10381 if (pret == nr_pages) {
10382 /* don't support file backed memory */
10383 for (i = 0; i < nr_pages; i++) {
10384 struct vm_area_struct *vma = vmas[i];
10386 if (vma_is_shmem(vma))
10388 if (vma->vm_file &&
10389 !is_file_hugepages(vma->vm_file)) {
10394 *npages = nr_pages;
10396 ret = pret < 0 ? pret : -EFAULT;
10398 mmap_read_unlock(current->mm);
10401 * if we did partial map, or found file backed vmas,
10402 * release any pages we did get
10405 unpin_user_pages(pages, pret);
10413 pages = ERR_PTR(ret);
10418 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10419 struct io_mapped_ubuf **pimu,
10420 struct page **last_hpage)
10422 struct io_mapped_ubuf *imu = NULL;
10423 struct page **pages = NULL;
10426 int ret, nr_pages, i;
10428 if (!iov->iov_base) {
10429 *pimu = ctx->dummy_ubuf;
10436 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10438 if (IS_ERR(pages)) {
10439 ret = PTR_ERR(pages);
10444 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10448 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10450 unpin_user_pages(pages, nr_pages);
10454 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10455 size = iov->iov_len;
10456 for (i = 0; i < nr_pages; i++) {
10459 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10460 imu->bvec[i].bv_page = pages[i];
10461 imu->bvec[i].bv_len = vec_len;
10462 imu->bvec[i].bv_offset = off;
10466 /* store original address for later verification */
10467 imu->ubuf = (unsigned long) iov->iov_base;
10468 imu->ubuf_end = imu->ubuf + iov->iov_len;
10469 imu->nr_bvecs = nr_pages;
10479 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10481 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10482 return ctx->user_bufs ? 0 : -ENOMEM;
10485 static int io_buffer_validate(struct iovec *iov)
10487 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10490 * Don't impose further limits on the size and buffer
10491 * constraints here, we'll -EINVAL later when IO is
10492 * submitted if they are wrong.
10494 if (!iov->iov_base)
10495 return iov->iov_len ? -EFAULT : 0;
10499 /* arbitrary limit, but we need something */
10500 if (iov->iov_len > SZ_1G)
10503 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10509 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10510 unsigned int nr_args, u64 __user *tags)
10512 struct page *last_hpage = NULL;
10513 struct io_rsrc_data *data;
10517 if (ctx->user_bufs)
10519 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10521 ret = io_rsrc_node_switch_start(ctx);
10524 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10527 ret = io_buffers_map_alloc(ctx, nr_args);
10529 io_rsrc_data_free(data);
10533 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10535 ret = io_copy_iov(ctx, &iov, arg, i);
10538 ret = io_buffer_validate(&iov);
10542 memset(&iov, 0, sizeof(iov));
10545 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10550 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10556 WARN_ON_ONCE(ctx->buf_data);
10558 ctx->buf_data = data;
10560 __io_sqe_buffers_unregister(ctx);
10562 io_rsrc_node_switch(ctx, NULL);
10566 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10567 struct io_uring_rsrc_update2 *up,
10568 unsigned int nr_args)
10570 u64 __user *tags = u64_to_user_ptr(up->tags);
10571 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10572 struct page *last_hpage = NULL;
10573 bool needs_switch = false;
10577 if (!ctx->buf_data)
10579 if (up->offset + nr_args > ctx->nr_user_bufs)
10582 for (done = 0; done < nr_args; done++) {
10583 struct io_mapped_ubuf *imu;
10584 int offset = up->offset + done;
10587 err = io_copy_iov(ctx, &iov, iovs, done);
10590 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10594 err = io_buffer_validate(&iov);
10597 if (!iov.iov_base && tag) {
10601 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10605 i = array_index_nospec(offset, ctx->nr_user_bufs);
10606 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10607 err = io_queue_rsrc_removal(ctx->buf_data, i,
10608 ctx->rsrc_node, ctx->user_bufs[i]);
10609 if (unlikely(err)) {
10610 io_buffer_unmap(ctx, &imu);
10613 ctx->user_bufs[i] = NULL;
10614 needs_switch = true;
10617 ctx->user_bufs[i] = imu;
10618 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10622 io_rsrc_node_switch(ctx, ctx->buf_data);
10623 return done ? done : err;
10626 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10627 unsigned int eventfd_async)
10629 struct io_ev_fd *ev_fd;
10630 __s32 __user *fds = arg;
10633 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10634 lockdep_is_held(&ctx->uring_lock));
10638 if (copy_from_user(&fd, fds, sizeof(*fds)))
10641 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10645 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10646 if (IS_ERR(ev_fd->cq_ev_fd)) {
10647 int ret = PTR_ERR(ev_fd->cq_ev_fd);
10651 ev_fd->eventfd_async = eventfd_async;
10652 ctx->has_evfd = true;
10653 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10657 static void io_eventfd_put(struct rcu_head *rcu)
10659 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10661 eventfd_ctx_put(ev_fd->cq_ev_fd);
10665 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10667 struct io_ev_fd *ev_fd;
10669 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10670 lockdep_is_held(&ctx->uring_lock));
10672 ctx->has_evfd = false;
10673 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10674 call_rcu(&ev_fd->rcu, io_eventfd_put);
10681 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10683 struct io_buffer_list *bl;
10684 unsigned long index;
10687 for (i = 0; i < BGID_ARRAY; i++) {
10690 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
10693 xa_for_each(&ctx->io_bl_xa, index, bl) {
10694 xa_erase(&ctx->io_bl_xa, bl->bgid);
10695 __io_remove_buffers(ctx, bl, -1U);
10699 while (!list_empty(&ctx->io_buffers_pages)) {
10702 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10703 list_del_init(&page->lru);
10708 static void io_req_caches_free(struct io_ring_ctx *ctx)
10710 struct io_submit_state *state = &ctx->submit_state;
10713 mutex_lock(&ctx->uring_lock);
10714 io_flush_cached_locked_reqs(ctx, state);
10716 while (!io_req_cache_empty(ctx)) {
10717 struct io_wq_work_node *node;
10718 struct io_kiocb *req;
10720 node = wq_stack_extract(&state->free_list);
10721 req = container_of(node, struct io_kiocb, comp_list);
10722 kmem_cache_free(req_cachep, req);
10726 percpu_ref_put_many(&ctx->refs, nr);
10727 mutex_unlock(&ctx->uring_lock);
10730 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10732 if (data && !atomic_dec_and_test(&data->refs))
10733 wait_for_completion(&data->done);
10736 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10738 struct async_poll *apoll;
10740 while (!list_empty(&ctx->apoll_cache)) {
10741 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10743 list_del(&apoll->poll.wait.entry);
10748 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10750 io_sq_thread_finish(ctx);
10752 if (ctx->mm_account) {
10753 mmdrop(ctx->mm_account);
10754 ctx->mm_account = NULL;
10757 io_rsrc_refs_drop(ctx);
10758 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10759 io_wait_rsrc_data(ctx->buf_data);
10760 io_wait_rsrc_data(ctx->file_data);
10762 mutex_lock(&ctx->uring_lock);
10764 __io_sqe_buffers_unregister(ctx);
10765 if (ctx->file_data)
10766 __io_sqe_files_unregister(ctx);
10768 __io_cqring_overflow_flush(ctx, true);
10769 io_eventfd_unregister(ctx);
10770 io_flush_apoll_cache(ctx);
10771 mutex_unlock(&ctx->uring_lock);
10772 io_destroy_buffers(ctx);
10774 put_cred(ctx->sq_creds);
10776 /* there are no registered resources left, nobody uses it */
10777 if (ctx->rsrc_node)
10778 io_rsrc_node_destroy(ctx->rsrc_node);
10779 if (ctx->rsrc_backup_node)
10780 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10781 flush_delayed_work(&ctx->rsrc_put_work);
10782 flush_delayed_work(&ctx->fallback_work);
10784 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10785 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10787 #if defined(CONFIG_UNIX)
10788 if (ctx->ring_sock) {
10789 ctx->ring_sock->file = NULL; /* so that iput() is called */
10790 sock_release(ctx->ring_sock);
10793 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10795 io_mem_free(ctx->rings);
10796 io_mem_free(ctx->sq_sqes);
10798 percpu_ref_exit(&ctx->refs);
10799 free_uid(ctx->user);
10800 io_req_caches_free(ctx);
10802 io_wq_put_hash(ctx->hash_map);
10803 kfree(ctx->cancel_hash);
10804 kfree(ctx->dummy_ubuf);
10806 xa_destroy(&ctx->io_bl_xa);
10810 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10812 struct io_ring_ctx *ctx = file->private_data;
10815 poll_wait(file, &ctx->cq_wait, wait);
10817 * synchronizes with barrier from wq_has_sleeper call in
10821 if (!io_sqring_full(ctx))
10822 mask |= EPOLLOUT | EPOLLWRNORM;
10825 * Don't flush cqring overflow list here, just do a simple check.
10826 * Otherwise there could possible be ABBA deadlock:
10829 * lock(&ctx->uring_lock);
10831 * lock(&ctx->uring_lock);
10834 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10835 * pushs them to do the flush.
10837 if (io_cqring_events(ctx) ||
10838 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
10839 mask |= EPOLLIN | EPOLLRDNORM;
10844 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10846 const struct cred *creds;
10848 creds = xa_erase(&ctx->personalities, id);
10857 struct io_tctx_exit {
10858 struct callback_head task_work;
10859 struct completion completion;
10860 struct io_ring_ctx *ctx;
10863 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10865 struct io_uring_task *tctx = current->io_uring;
10866 struct io_tctx_exit *work;
10868 work = container_of(cb, struct io_tctx_exit, task_work);
10870 * When @in_idle, we're in cancellation and it's racy to remove the
10871 * node. It'll be removed by the end of cancellation, just ignore it.
10873 if (!atomic_read(&tctx->in_idle))
10874 io_uring_del_tctx_node((unsigned long)work->ctx);
10875 complete(&work->completion);
10878 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10880 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10882 return req->ctx == data;
10885 static __cold void io_ring_exit_work(struct work_struct *work)
10887 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10888 unsigned long timeout = jiffies + HZ * 60 * 5;
10889 unsigned long interval = HZ / 20;
10890 struct io_tctx_exit exit;
10891 struct io_tctx_node *node;
10895 * If we're doing polled IO and end up having requests being
10896 * submitted async (out-of-line), then completions can come in while
10897 * we're waiting for refs to drop. We need to reap these manually,
10898 * as nobody else will be looking for them.
10901 io_uring_try_cancel_requests(ctx, NULL, true);
10902 if (ctx->sq_data) {
10903 struct io_sq_data *sqd = ctx->sq_data;
10904 struct task_struct *tsk;
10906 io_sq_thread_park(sqd);
10908 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10909 io_wq_cancel_cb(tsk->io_uring->io_wq,
10910 io_cancel_ctx_cb, ctx, true);
10911 io_sq_thread_unpark(sqd);
10914 io_req_caches_free(ctx);
10916 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10917 /* there is little hope left, don't run it too often */
10918 interval = HZ * 60;
10920 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10922 init_completion(&exit.completion);
10923 init_task_work(&exit.task_work, io_tctx_exit_cb);
10926 * Some may use context even when all refs and requests have been put,
10927 * and they are free to do so while still holding uring_lock or
10928 * completion_lock, see io_req_task_submit(). Apart from other work,
10929 * this lock/unlock section also waits them to finish.
10931 mutex_lock(&ctx->uring_lock);
10932 while (!list_empty(&ctx->tctx_list)) {
10933 WARN_ON_ONCE(time_after(jiffies, timeout));
10935 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10937 /* don't spin on a single task if cancellation failed */
10938 list_rotate_left(&ctx->tctx_list);
10939 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10940 if (WARN_ON_ONCE(ret))
10943 mutex_unlock(&ctx->uring_lock);
10944 wait_for_completion(&exit.completion);
10945 mutex_lock(&ctx->uring_lock);
10947 mutex_unlock(&ctx->uring_lock);
10948 spin_lock(&ctx->completion_lock);
10949 spin_unlock(&ctx->completion_lock);
10951 io_ring_ctx_free(ctx);
10954 /* Returns true if we found and killed one or more timeouts */
10955 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10956 struct task_struct *tsk, bool cancel_all)
10958 struct io_timeout *timeout, *tmp;
10961 spin_lock(&ctx->completion_lock);
10962 spin_lock_irq(&ctx->timeout_lock);
10963 list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
10964 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
10966 if (io_match_task(req, tsk, cancel_all)) {
10967 io_kill_timeout(req, -ECANCELED);
10971 spin_unlock_irq(&ctx->timeout_lock);
10972 io_commit_cqring(ctx);
10973 spin_unlock(&ctx->completion_lock);
10975 io_cqring_ev_posted(ctx);
10976 return canceled != 0;
10979 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10981 unsigned long index;
10982 struct creds *creds;
10984 mutex_lock(&ctx->uring_lock);
10985 percpu_ref_kill(&ctx->refs);
10987 __io_cqring_overflow_flush(ctx, true);
10988 xa_for_each(&ctx->personalities, index, creds)
10989 io_unregister_personality(ctx, index);
10990 mutex_unlock(&ctx->uring_lock);
10992 /* failed during ring init, it couldn't have issued any requests */
10994 io_kill_timeouts(ctx, NULL, true);
10995 io_poll_remove_all(ctx, NULL, true);
10996 /* if we failed setting up the ctx, we might not have any rings */
10997 io_iopoll_try_reap_events(ctx);
11000 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11002 * Use system_unbound_wq to avoid spawning tons of event kworkers
11003 * if we're exiting a ton of rings at the same time. It just adds
11004 * noise and overhead, there's no discernable change in runtime
11005 * over using system_wq.
11007 queue_work(system_unbound_wq, &ctx->exit_work);
11010 static int io_uring_release(struct inode *inode, struct file *file)
11012 struct io_ring_ctx *ctx = file->private_data;
11014 file->private_data = NULL;
11015 io_ring_ctx_wait_and_kill(ctx);
11019 struct io_task_cancel {
11020 struct task_struct *task;
11024 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11026 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11027 struct io_task_cancel *cancel = data;
11029 return io_match_task_safe(req, cancel->task, cancel->all);
11032 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11033 struct task_struct *task,
11036 struct io_defer_entry *de;
11039 spin_lock(&ctx->completion_lock);
11040 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11041 if (io_match_task_safe(de->req, task, cancel_all)) {
11042 list_cut_position(&list, &ctx->defer_list, &de->list);
11046 spin_unlock(&ctx->completion_lock);
11047 if (list_empty(&list))
11050 while (!list_empty(&list)) {
11051 de = list_first_entry(&list, struct io_defer_entry, list);
11052 list_del_init(&de->list);
11053 io_req_complete_failed(de->req, -ECANCELED);
11059 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11061 struct io_tctx_node *node;
11062 enum io_wq_cancel cret;
11065 mutex_lock(&ctx->uring_lock);
11066 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11067 struct io_uring_task *tctx = node->task->io_uring;
11070 * io_wq will stay alive while we hold uring_lock, because it's
11071 * killed after ctx nodes, which requires to take the lock.
11073 if (!tctx || !tctx->io_wq)
11075 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11076 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11078 mutex_unlock(&ctx->uring_lock);
11083 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11084 struct task_struct *task,
11087 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11088 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11090 /* failed during ring init, it couldn't have issued any requests */
11095 enum io_wq_cancel cret;
11099 ret |= io_uring_try_cancel_iowq(ctx);
11100 } else if (tctx && tctx->io_wq) {
11102 * Cancels requests of all rings, not only @ctx, but
11103 * it's fine as the task is in exit/exec.
11105 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11107 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11110 /* SQPOLL thread does its own polling */
11111 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11112 (ctx->sq_data && ctx->sq_data->thread == current)) {
11113 while (!wq_list_empty(&ctx->iopoll_list)) {
11114 io_iopoll_try_reap_events(ctx);
11119 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11120 ret |= io_poll_remove_all(ctx, task, cancel_all);
11121 ret |= io_kill_timeouts(ctx, task, cancel_all);
11123 ret |= io_run_task_work();
11130 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11132 struct io_uring_task *tctx = current->io_uring;
11133 struct io_tctx_node *node;
11136 if (unlikely(!tctx)) {
11137 ret = io_uring_alloc_task_context(current, ctx);
11141 tctx = current->io_uring;
11142 if (ctx->iowq_limits_set) {
11143 unsigned int limits[2] = { ctx->iowq_limits[0],
11144 ctx->iowq_limits[1], };
11146 ret = io_wq_max_workers(tctx->io_wq, limits);
11151 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11152 node = kmalloc(sizeof(*node), GFP_KERNEL);
11156 node->task = current;
11158 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11159 node, GFP_KERNEL));
11165 mutex_lock(&ctx->uring_lock);
11166 list_add(&node->ctx_node, &ctx->tctx_list);
11167 mutex_unlock(&ctx->uring_lock);
11174 * Note that this task has used io_uring. We use it for cancelation purposes.
11176 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11178 struct io_uring_task *tctx = current->io_uring;
11180 if (likely(tctx && tctx->last == ctx))
11182 return __io_uring_add_tctx_node(ctx);
11186 * Remove this io_uring_file -> task mapping.
11188 static __cold void io_uring_del_tctx_node(unsigned long index)
11190 struct io_uring_task *tctx = current->io_uring;
11191 struct io_tctx_node *node;
11195 node = xa_erase(&tctx->xa, index);
11199 WARN_ON_ONCE(current != node->task);
11200 WARN_ON_ONCE(list_empty(&node->ctx_node));
11202 mutex_lock(&node->ctx->uring_lock);
11203 list_del(&node->ctx_node);
11204 mutex_unlock(&node->ctx->uring_lock);
11206 if (tctx->last == node->ctx)
11211 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11213 struct io_wq *wq = tctx->io_wq;
11214 struct io_tctx_node *node;
11215 unsigned long index;
11217 xa_for_each(&tctx->xa, index, node) {
11218 io_uring_del_tctx_node(index);
11223 * Must be after io_uring_del_tctx_node() (removes nodes under
11224 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11226 io_wq_put_and_exit(wq);
11227 tctx->io_wq = NULL;
11231 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11234 return atomic_read(&tctx->inflight_tracked);
11235 return percpu_counter_sum(&tctx->inflight);
11239 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11240 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11242 static __cold void io_uring_cancel_generic(bool cancel_all,
11243 struct io_sq_data *sqd)
11245 struct io_uring_task *tctx = current->io_uring;
11246 struct io_ring_ctx *ctx;
11250 WARN_ON_ONCE(sqd && sqd->thread != current);
11252 if (!current->io_uring)
11255 io_wq_exit_start(tctx->io_wq);
11257 atomic_inc(&tctx->in_idle);
11259 io_uring_drop_tctx_refs(current);
11260 /* read completions before cancelations */
11261 inflight = tctx_inflight(tctx, !cancel_all);
11266 struct io_tctx_node *node;
11267 unsigned long index;
11269 xa_for_each(&tctx->xa, index, node) {
11270 /* sqpoll task will cancel all its requests */
11271 if (node->ctx->sq_data)
11273 io_uring_try_cancel_requests(node->ctx, current,
11277 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11278 io_uring_try_cancel_requests(ctx, current,
11282 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11283 io_run_task_work();
11284 io_uring_drop_tctx_refs(current);
11287 * If we've seen completions, retry without waiting. This
11288 * avoids a race where a completion comes in before we did
11289 * prepare_to_wait().
11291 if (inflight == tctx_inflight(tctx, !cancel_all))
11293 finish_wait(&tctx->wait, &wait);
11296 io_uring_clean_tctx(tctx);
11299 * We shouldn't run task_works after cancel, so just leave
11300 * ->in_idle set for normal exit.
11302 atomic_dec(&tctx->in_idle);
11303 /* for exec all current's requests should be gone, kill tctx */
11304 __io_uring_free(current);
11308 void __io_uring_cancel(bool cancel_all)
11310 io_uring_cancel_generic(cancel_all, NULL);
11313 void io_uring_unreg_ringfd(void)
11315 struct io_uring_task *tctx = current->io_uring;
11318 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11319 if (tctx->registered_rings[i]) {
11320 fput(tctx->registered_rings[i]);
11321 tctx->registered_rings[i] = NULL;
11326 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11327 int start, int end)
11332 for (offset = start; offset < end; offset++) {
11333 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11334 if (tctx->registered_rings[offset])
11340 } else if (file->f_op != &io_uring_fops) {
11342 return -EOPNOTSUPP;
11344 tctx->registered_rings[offset] = file;
11352 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11353 * invocation. User passes in an array of struct io_uring_rsrc_update
11354 * with ->data set to the ring_fd, and ->offset given for the desired
11355 * index. If no index is desired, application may set ->offset == -1U
11356 * and we'll find an available index. Returns number of entries
11357 * successfully processed, or < 0 on error if none were processed.
11359 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11362 struct io_uring_rsrc_update __user *arg = __arg;
11363 struct io_uring_rsrc_update reg;
11364 struct io_uring_task *tctx;
11367 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11370 mutex_unlock(&ctx->uring_lock);
11371 ret = io_uring_add_tctx_node(ctx);
11372 mutex_lock(&ctx->uring_lock);
11376 tctx = current->io_uring;
11377 for (i = 0; i < nr_args; i++) {
11380 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11390 if (reg.offset == -1U) {
11392 end = IO_RINGFD_REG_MAX;
11394 if (reg.offset >= IO_RINGFD_REG_MAX) {
11398 start = reg.offset;
11402 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11407 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11408 fput(tctx->registered_rings[reg.offset]);
11409 tctx->registered_rings[reg.offset] = NULL;
11415 return i ? i : ret;
11418 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11421 struct io_uring_rsrc_update __user *arg = __arg;
11422 struct io_uring_task *tctx = current->io_uring;
11423 struct io_uring_rsrc_update reg;
11426 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11431 for (i = 0; i < nr_args; i++) {
11432 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11436 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11441 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11442 if (tctx->registered_rings[reg.offset]) {
11443 fput(tctx->registered_rings[reg.offset]);
11444 tctx->registered_rings[reg.offset] = NULL;
11448 return i ? i : ret;
11451 static void *io_uring_validate_mmap_request(struct file *file,
11452 loff_t pgoff, size_t sz)
11454 struct io_ring_ctx *ctx = file->private_data;
11455 loff_t offset = pgoff << PAGE_SHIFT;
11460 case IORING_OFF_SQ_RING:
11461 case IORING_OFF_CQ_RING:
11464 case IORING_OFF_SQES:
11465 ptr = ctx->sq_sqes;
11468 return ERR_PTR(-EINVAL);
11471 page = virt_to_head_page(ptr);
11472 if (sz > page_size(page))
11473 return ERR_PTR(-EINVAL);
11480 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11482 size_t sz = vma->vm_end - vma->vm_start;
11486 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11488 return PTR_ERR(ptr);
11490 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11491 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11494 #else /* !CONFIG_MMU */
11496 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11498 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11501 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11503 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11506 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11507 unsigned long addr, unsigned long len,
11508 unsigned long pgoff, unsigned long flags)
11512 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11514 return PTR_ERR(ptr);
11516 return (unsigned long) ptr;
11519 #endif /* !CONFIG_MMU */
11521 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11526 if (!io_sqring_full(ctx))
11528 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11530 if (!io_sqring_full(ctx))
11533 } while (!signal_pending(current));
11535 finish_wait(&ctx->sqo_sq_wait, &wait);
11539 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11541 if (flags & IORING_ENTER_EXT_ARG) {
11542 struct io_uring_getevents_arg arg;
11544 if (argsz != sizeof(arg))
11546 if (copy_from_user(&arg, argp, sizeof(arg)))
11552 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11553 struct __kernel_timespec __user **ts,
11554 const sigset_t __user **sig)
11556 struct io_uring_getevents_arg arg;
11559 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11560 * is just a pointer to the sigset_t.
11562 if (!(flags & IORING_ENTER_EXT_ARG)) {
11563 *sig = (const sigset_t __user *) argp;
11569 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11570 * timespec and sigset_t pointers if good.
11572 if (*argsz != sizeof(arg))
11574 if (copy_from_user(&arg, argp, sizeof(arg)))
11578 *sig = u64_to_user_ptr(arg.sigmask);
11579 *argsz = arg.sigmask_sz;
11580 *ts = u64_to_user_ptr(arg.ts);
11584 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11585 u32, min_complete, u32, flags, const void __user *, argp,
11588 struct io_ring_ctx *ctx;
11592 io_run_task_work();
11594 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11595 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11596 IORING_ENTER_REGISTERED_RING)))
11600 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11601 * need only dereference our task private array to find it.
11603 if (flags & IORING_ENTER_REGISTERED_RING) {
11604 struct io_uring_task *tctx = current->io_uring;
11606 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11608 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11609 f.file = tctx->registered_rings[fd];
11615 if (unlikely(!f.file))
11619 if (unlikely(f.file->f_op != &io_uring_fops))
11623 ctx = f.file->private_data;
11624 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11628 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11632 * For SQ polling, the thread will do all submissions and completions.
11633 * Just return the requested submit count, and wake the thread if
11634 * we were asked to.
11637 if (ctx->flags & IORING_SETUP_SQPOLL) {
11638 io_cqring_overflow_flush(ctx);
11640 if (unlikely(ctx->sq_data->thread == NULL)) {
11644 if (flags & IORING_ENTER_SQ_WAKEUP)
11645 wake_up(&ctx->sq_data->wait);
11646 if (flags & IORING_ENTER_SQ_WAIT) {
11647 ret = io_sqpoll_wait_sq(ctx);
11652 } else if (to_submit) {
11653 ret = io_uring_add_tctx_node(ctx);
11657 mutex_lock(&ctx->uring_lock);
11658 ret = io_submit_sqes(ctx, to_submit);
11659 if (ret != to_submit) {
11660 mutex_unlock(&ctx->uring_lock);
11663 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
11664 goto iopoll_locked;
11665 mutex_unlock(&ctx->uring_lock);
11667 if (flags & IORING_ENTER_GETEVENTS) {
11669 if (ctx->syscall_iopoll) {
11671 * We disallow the app entering submit/complete with
11672 * polling, but we still need to lock the ring to
11673 * prevent racing with polled issue that got punted to
11676 mutex_lock(&ctx->uring_lock);
11678 ret2 = io_validate_ext_arg(flags, argp, argsz);
11679 if (likely(!ret2)) {
11680 min_complete = min(min_complete,
11682 ret2 = io_iopoll_check(ctx, min_complete);
11684 mutex_unlock(&ctx->uring_lock);
11686 const sigset_t __user *sig;
11687 struct __kernel_timespec __user *ts;
11689 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
11690 if (likely(!ret2)) {
11691 min_complete = min(min_complete,
11693 ret2 = io_cqring_wait(ctx, min_complete, sig,
11702 * EBADR indicates that one or more CQE were dropped.
11703 * Once the user has been informed we can clear the bit
11704 * as they are obviously ok with those drops.
11706 if (unlikely(ret2 == -EBADR))
11707 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
11713 percpu_ref_put(&ctx->refs);
11719 #ifdef CONFIG_PROC_FS
11720 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11721 const struct cred *cred)
11723 struct user_namespace *uns = seq_user_ns(m);
11724 struct group_info *gi;
11729 seq_printf(m, "%5d\n", id);
11730 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11731 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11732 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11733 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11734 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11735 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11736 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11737 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11738 seq_puts(m, "\n\tGroups:\t");
11739 gi = cred->group_info;
11740 for (g = 0; g < gi->ngroups; g++) {
11741 seq_put_decimal_ull(m, g ? " " : "",
11742 from_kgid_munged(uns, gi->gid[g]));
11744 seq_puts(m, "\n\tCapEff:\t");
11745 cap = cred->cap_effective;
11746 CAP_FOR_EACH_U32(__capi)
11747 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11752 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11753 struct seq_file *m)
11755 struct io_sq_data *sq = NULL;
11756 struct io_overflow_cqe *ocqe;
11757 struct io_rings *r = ctx->rings;
11758 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11759 unsigned int sq_head = READ_ONCE(r->sq.head);
11760 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11761 unsigned int cq_head = READ_ONCE(r->cq.head);
11762 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11763 unsigned int cq_shift = 0;
11764 unsigned int sq_entries, cq_entries;
11766 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
11773 * we may get imprecise sqe and cqe info if uring is actively running
11774 * since we get cached_sq_head and cached_cq_tail without uring_lock
11775 * and sq_tail and cq_head are changed by userspace. But it's ok since
11776 * we usually use these info when it is stuck.
11778 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11779 seq_printf(m, "SqHead:\t%u\n", sq_head);
11780 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11781 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11782 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11783 seq_printf(m, "CqHead:\t%u\n", cq_head);
11784 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11785 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11786 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11787 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11788 for (i = 0; i < sq_entries; i++) {
11789 unsigned int entry = i + sq_head;
11790 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11791 struct io_uring_sqe *sqe;
11793 if (sq_idx > sq_mask)
11795 sqe = &ctx->sq_sqes[sq_idx];
11796 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11797 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11800 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11801 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11802 for (i = 0; i < cq_entries; i++) {
11803 unsigned int entry = i + cq_head;
11804 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
11807 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11808 entry & cq_mask, cqe->user_data, cqe->res,
11811 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
11812 "extra1:%llu, extra2:%llu\n",
11813 entry & cq_mask, cqe->user_data, cqe->res,
11814 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
11819 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11820 * since fdinfo case grabs it in the opposite direction of normal use
11821 * cases. If we fail to get the lock, we just don't iterate any
11822 * structures that could be going away outside the io_uring mutex.
11824 has_lock = mutex_trylock(&ctx->uring_lock);
11826 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11832 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11833 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11834 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11835 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11836 struct file *f = io_file_from_index(ctx, i);
11839 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11841 seq_printf(m, "%5u: <none>\n", i);
11843 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11844 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11845 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11846 unsigned int len = buf->ubuf_end - buf->ubuf;
11848 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11850 if (has_lock && !xa_empty(&ctx->personalities)) {
11851 unsigned long index;
11852 const struct cred *cred;
11854 seq_printf(m, "Personalities:\n");
11855 xa_for_each(&ctx->personalities, index, cred)
11856 io_uring_show_cred(m, index, cred);
11859 mutex_unlock(&ctx->uring_lock);
11861 seq_puts(m, "PollList:\n");
11862 spin_lock(&ctx->completion_lock);
11863 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11864 struct hlist_head *list = &ctx->cancel_hash[i];
11865 struct io_kiocb *req;
11867 hlist_for_each_entry(req, list, hash_node)
11868 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11869 task_work_pending(req->task));
11872 seq_puts(m, "CqOverflowList:\n");
11873 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11874 struct io_uring_cqe *cqe = &ocqe->cqe;
11876 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11877 cqe->user_data, cqe->res, cqe->flags);
11881 spin_unlock(&ctx->completion_lock);
11884 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11886 struct io_ring_ctx *ctx = f->private_data;
11888 if (percpu_ref_tryget(&ctx->refs)) {
11889 __io_uring_show_fdinfo(ctx, m);
11890 percpu_ref_put(&ctx->refs);
11895 static const struct file_operations io_uring_fops = {
11896 .release = io_uring_release,
11897 .mmap = io_uring_mmap,
11899 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11900 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11902 .poll = io_uring_poll,
11903 #ifdef CONFIG_PROC_FS
11904 .show_fdinfo = io_uring_show_fdinfo,
11908 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11909 struct io_uring_params *p)
11911 struct io_rings *rings;
11912 size_t size, sq_array_offset;
11914 /* make sure these are sane, as we already accounted them */
11915 ctx->sq_entries = p->sq_entries;
11916 ctx->cq_entries = p->cq_entries;
11918 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
11919 if (size == SIZE_MAX)
11922 rings = io_mem_alloc(size);
11926 ctx->rings = rings;
11927 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11928 rings->sq_ring_mask = p->sq_entries - 1;
11929 rings->cq_ring_mask = p->cq_entries - 1;
11930 rings->sq_ring_entries = p->sq_entries;
11931 rings->cq_ring_entries = p->cq_entries;
11933 if (p->flags & IORING_SETUP_SQE128)
11934 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
11936 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11937 if (size == SIZE_MAX) {
11938 io_mem_free(ctx->rings);
11943 ctx->sq_sqes = io_mem_alloc(size);
11944 if (!ctx->sq_sqes) {
11945 io_mem_free(ctx->rings);
11953 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11957 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11961 ret = io_uring_add_tctx_node(ctx);
11966 fd_install(fd, file);
11971 * Allocate an anonymous fd, this is what constitutes the application
11972 * visible backing of an io_uring instance. The application mmaps this
11973 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11974 * we have to tie this fd to a socket for file garbage collection purposes.
11976 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11979 #if defined(CONFIG_UNIX)
11982 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11985 return ERR_PTR(ret);
11988 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11989 O_RDWR | O_CLOEXEC, NULL);
11990 #if defined(CONFIG_UNIX)
11991 if (IS_ERR(file)) {
11992 sock_release(ctx->ring_sock);
11993 ctx->ring_sock = NULL;
11995 ctx->ring_sock->file = file;
12001 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12002 struct io_uring_params __user *params)
12004 struct io_ring_ctx *ctx;
12010 if (entries > IORING_MAX_ENTRIES) {
12011 if (!(p->flags & IORING_SETUP_CLAMP))
12013 entries = IORING_MAX_ENTRIES;
12017 * Use twice as many entries for the CQ ring. It's possible for the
12018 * application to drive a higher depth than the size of the SQ ring,
12019 * since the sqes are only used at submission time. This allows for
12020 * some flexibility in overcommitting a bit. If the application has
12021 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12022 * of CQ ring entries manually.
12024 p->sq_entries = roundup_pow_of_two(entries);
12025 if (p->flags & IORING_SETUP_CQSIZE) {
12027 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12028 * to a power-of-two, if it isn't already. We do NOT impose
12029 * any cq vs sq ring sizing.
12031 if (!p->cq_entries)
12033 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12034 if (!(p->flags & IORING_SETUP_CLAMP))
12036 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12038 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12039 if (p->cq_entries < p->sq_entries)
12042 p->cq_entries = 2 * p->sq_entries;
12045 ctx = io_ring_ctx_alloc(p);
12050 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12051 * space applications don't need to do io completion events
12052 * polling again, they can rely on io_sq_thread to do polling
12053 * work, which can reduce cpu usage and uring_lock contention.
12055 if (ctx->flags & IORING_SETUP_IOPOLL &&
12056 !(ctx->flags & IORING_SETUP_SQPOLL))
12057 ctx->syscall_iopoll = 1;
12059 ctx->compat = in_compat_syscall();
12060 if (!capable(CAP_IPC_LOCK))
12061 ctx->user = get_uid(current_user());
12064 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12065 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12068 if (ctx->flags & IORING_SETUP_SQPOLL) {
12069 /* IPI related flags don't make sense with SQPOLL */
12070 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12071 IORING_SETUP_TASKRUN_FLAG))
12073 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12074 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12075 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12077 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12079 ctx->notify_method = TWA_SIGNAL;
12083 * This is just grabbed for accounting purposes. When a process exits,
12084 * the mm is exited and dropped before the files, hence we need to hang
12085 * on to this mm purely for the purposes of being able to unaccount
12086 * memory (locked/pinned vm). It's not used for anything else.
12088 mmgrab(current->mm);
12089 ctx->mm_account = current->mm;
12091 ret = io_allocate_scq_urings(ctx, p);
12095 ret = io_sq_offload_create(ctx, p);
12098 /* always set a rsrc node */
12099 ret = io_rsrc_node_switch_start(ctx);
12102 io_rsrc_node_switch(ctx, NULL);
12104 memset(&p->sq_off, 0, sizeof(p->sq_off));
12105 p->sq_off.head = offsetof(struct io_rings, sq.head);
12106 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12107 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12108 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12109 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12110 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12111 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12113 memset(&p->cq_off, 0, sizeof(p->cq_off));
12114 p->cq_off.head = offsetof(struct io_rings, cq.head);
12115 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12116 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12117 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12118 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12119 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12120 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12122 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12123 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12124 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12125 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12126 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12127 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12128 IORING_FEAT_LINKED_FILE;
12130 if (copy_to_user(params, p, sizeof(*p))) {
12135 file = io_uring_get_file(ctx);
12136 if (IS_ERR(file)) {
12137 ret = PTR_ERR(file);
12142 * Install ring fd as the very last thing, so we don't risk someone
12143 * having closed it before we finish setup
12145 ret = io_uring_install_fd(ctx, file);
12147 /* fput will clean it up */
12152 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12155 io_ring_ctx_wait_and_kill(ctx);
12160 * Sets up an aio uring context, and returns the fd. Applications asks for a
12161 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12162 * params structure passed in.
12164 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12166 struct io_uring_params p;
12169 if (copy_from_user(&p, params, sizeof(p)))
12171 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12176 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12177 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12178 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12179 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12180 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12181 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12184 return io_uring_create(entries, &p, params);
12187 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12188 struct io_uring_params __user *, params)
12190 return io_uring_setup(entries, params);
12193 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12196 struct io_uring_probe *p;
12200 size = struct_size(p, ops, nr_args);
12201 if (size == SIZE_MAX)
12203 p = kzalloc(size, GFP_KERNEL);
12208 if (copy_from_user(p, arg, size))
12211 if (memchr_inv(p, 0, size))
12214 p->last_op = IORING_OP_LAST - 1;
12215 if (nr_args > IORING_OP_LAST)
12216 nr_args = IORING_OP_LAST;
12218 for (i = 0; i < nr_args; i++) {
12220 if (!io_op_defs[i].not_supported)
12221 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12226 if (copy_to_user(arg, p, size))
12233 static int io_register_personality(struct io_ring_ctx *ctx)
12235 const struct cred *creds;
12239 creds = get_current_cred();
12241 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12242 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12250 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12251 void __user *arg, unsigned int nr_args)
12253 struct io_uring_restriction *res;
12257 /* Restrictions allowed only if rings started disabled */
12258 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12261 /* We allow only a single restrictions registration */
12262 if (ctx->restrictions.registered)
12265 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12268 size = array_size(nr_args, sizeof(*res));
12269 if (size == SIZE_MAX)
12272 res = memdup_user(arg, size);
12274 return PTR_ERR(res);
12278 for (i = 0; i < nr_args; i++) {
12279 switch (res[i].opcode) {
12280 case IORING_RESTRICTION_REGISTER_OP:
12281 if (res[i].register_op >= IORING_REGISTER_LAST) {
12286 __set_bit(res[i].register_op,
12287 ctx->restrictions.register_op);
12289 case IORING_RESTRICTION_SQE_OP:
12290 if (res[i].sqe_op >= IORING_OP_LAST) {
12295 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12297 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12298 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12300 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12301 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12310 /* Reset all restrictions if an error happened */
12312 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12314 ctx->restrictions.registered = true;
12320 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12322 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12325 if (ctx->restrictions.registered)
12326 ctx->restricted = 1;
12328 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12329 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12330 wake_up(&ctx->sq_data->wait);
12334 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12335 struct io_uring_rsrc_update2 *up,
12341 if (check_add_overflow(up->offset, nr_args, &tmp))
12343 err = io_rsrc_node_switch_start(ctx);
12348 case IORING_RSRC_FILE:
12349 return __io_sqe_files_update(ctx, up, nr_args);
12350 case IORING_RSRC_BUFFER:
12351 return __io_sqe_buffers_update(ctx, up, nr_args);
12356 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12359 struct io_uring_rsrc_update2 up;
12363 memset(&up, 0, sizeof(up));
12364 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12366 if (up.resv || up.resv2)
12368 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12371 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12372 unsigned size, unsigned type)
12374 struct io_uring_rsrc_update2 up;
12376 if (size != sizeof(up))
12378 if (copy_from_user(&up, arg, sizeof(up)))
12380 if (!up.nr || up.resv || up.resv2)
12382 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12385 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12386 unsigned int size, unsigned int type)
12388 struct io_uring_rsrc_register rr;
12390 /* keep it extendible */
12391 if (size != sizeof(rr))
12394 memset(&rr, 0, sizeof(rr));
12395 if (copy_from_user(&rr, arg, size))
12397 if (!rr.nr || rr.resv2)
12399 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12403 case IORING_RSRC_FILE:
12404 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12406 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12407 rr.nr, u64_to_user_ptr(rr.tags));
12408 case IORING_RSRC_BUFFER:
12409 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12411 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12412 rr.nr, u64_to_user_ptr(rr.tags));
12417 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12418 void __user *arg, unsigned len)
12420 struct io_uring_task *tctx = current->io_uring;
12421 cpumask_var_t new_mask;
12424 if (!tctx || !tctx->io_wq)
12427 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12430 cpumask_clear(new_mask);
12431 if (len > cpumask_size())
12432 len = cpumask_size();
12434 if (in_compat_syscall()) {
12435 ret = compat_get_bitmap(cpumask_bits(new_mask),
12436 (const compat_ulong_t __user *)arg,
12437 len * 8 /* CHAR_BIT */);
12439 ret = copy_from_user(new_mask, arg, len);
12443 free_cpumask_var(new_mask);
12447 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12448 free_cpumask_var(new_mask);
12452 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12454 struct io_uring_task *tctx = current->io_uring;
12456 if (!tctx || !tctx->io_wq)
12459 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12462 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12464 __must_hold(&ctx->uring_lock)
12466 struct io_tctx_node *node;
12467 struct io_uring_task *tctx = NULL;
12468 struct io_sq_data *sqd = NULL;
12469 __u32 new_count[2];
12472 if (copy_from_user(new_count, arg, sizeof(new_count)))
12474 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12475 if (new_count[i] > INT_MAX)
12478 if (ctx->flags & IORING_SETUP_SQPOLL) {
12479 sqd = ctx->sq_data;
12482 * Observe the correct sqd->lock -> ctx->uring_lock
12483 * ordering. Fine to drop uring_lock here, we hold
12484 * a ref to the ctx.
12486 refcount_inc(&sqd->refs);
12487 mutex_unlock(&ctx->uring_lock);
12488 mutex_lock(&sqd->lock);
12489 mutex_lock(&ctx->uring_lock);
12491 tctx = sqd->thread->io_uring;
12494 tctx = current->io_uring;
12497 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12499 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12501 ctx->iowq_limits[i] = new_count[i];
12502 ctx->iowq_limits_set = true;
12504 if (tctx && tctx->io_wq) {
12505 ret = io_wq_max_workers(tctx->io_wq, new_count);
12509 memset(new_count, 0, sizeof(new_count));
12513 mutex_unlock(&sqd->lock);
12514 io_put_sq_data(sqd);
12517 if (copy_to_user(arg, new_count, sizeof(new_count)))
12520 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12524 /* now propagate the restriction to all registered users */
12525 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12526 struct io_uring_task *tctx = node->task->io_uring;
12528 if (WARN_ON_ONCE(!tctx->io_wq))
12531 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12532 new_count[i] = ctx->iowq_limits[i];
12533 /* ignore errors, it always returns zero anyway */
12534 (void)io_wq_max_workers(tctx->io_wq, new_count);
12539 mutex_unlock(&sqd->lock);
12540 io_put_sq_data(sqd);
12545 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12547 struct io_uring_buf_ring *br;
12548 struct io_uring_buf_reg reg;
12549 struct io_buffer_list *bl, *free_bl = NULL;
12550 struct page **pages;
12553 if (copy_from_user(®, arg, sizeof(reg)))
12556 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12558 if (!reg.ring_addr)
12560 if (reg.ring_addr & ~PAGE_MASK)
12562 if (!is_power_of_2(reg.ring_entries))
12565 /* cannot disambiguate full vs empty due to head/tail size */
12566 if (reg.ring_entries >= 65536)
12569 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12570 int ret = io_init_bl_list(ctx);
12575 bl = io_buffer_get_list(ctx, reg.bgid);
12577 /* if mapped buffer ring OR classic exists, don't allow */
12578 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12581 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12586 pages = io_pin_pages(reg.ring_addr,
12587 struct_size(br, bufs, reg.ring_entries),
12589 if (IS_ERR(pages)) {
12591 return PTR_ERR(pages);
12594 br = page_address(pages[0]);
12595 bl->buf_pages = pages;
12596 bl->buf_nr_pages = nr_pages;
12597 bl->nr_entries = reg.ring_entries;
12599 bl->mask = reg.ring_entries - 1;
12600 io_buffer_add_list(ctx, bl, reg.bgid);
12604 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12606 struct io_uring_buf_reg reg;
12607 struct io_buffer_list *bl;
12609 if (copy_from_user(®, arg, sizeof(reg)))
12611 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12614 bl = io_buffer_get_list(ctx, reg.bgid);
12617 if (!bl->buf_nr_pages)
12620 __io_remove_buffers(ctx, bl, -1U);
12621 if (bl->bgid >= BGID_ARRAY) {
12622 xa_erase(&ctx->io_bl_xa, bl->bgid);
12628 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12629 void __user *arg, unsigned nr_args)
12630 __releases(ctx->uring_lock)
12631 __acquires(ctx->uring_lock)
12636 * We're inside the ring mutex, if the ref is already dying, then
12637 * someone else killed the ctx or is already going through
12638 * io_uring_register().
12640 if (percpu_ref_is_dying(&ctx->refs))
12643 if (ctx->restricted) {
12644 if (opcode >= IORING_REGISTER_LAST)
12646 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12647 if (!test_bit(opcode, ctx->restrictions.register_op))
12652 case IORING_REGISTER_BUFFERS:
12656 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
12658 case IORING_UNREGISTER_BUFFERS:
12660 if (arg || nr_args)
12662 ret = io_sqe_buffers_unregister(ctx);
12664 case IORING_REGISTER_FILES:
12668 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
12670 case IORING_UNREGISTER_FILES:
12672 if (arg || nr_args)
12674 ret = io_sqe_files_unregister(ctx);
12676 case IORING_REGISTER_FILES_UPDATE:
12677 ret = io_register_files_update(ctx, arg, nr_args);
12679 case IORING_REGISTER_EVENTFD:
12683 ret = io_eventfd_register(ctx, arg, 0);
12685 case IORING_REGISTER_EVENTFD_ASYNC:
12689 ret = io_eventfd_register(ctx, arg, 1);
12691 case IORING_UNREGISTER_EVENTFD:
12693 if (arg || nr_args)
12695 ret = io_eventfd_unregister(ctx);
12697 case IORING_REGISTER_PROBE:
12699 if (!arg || nr_args > 256)
12701 ret = io_probe(ctx, arg, nr_args);
12703 case IORING_REGISTER_PERSONALITY:
12705 if (arg || nr_args)
12707 ret = io_register_personality(ctx);
12709 case IORING_UNREGISTER_PERSONALITY:
12713 ret = io_unregister_personality(ctx, nr_args);
12715 case IORING_REGISTER_ENABLE_RINGS:
12717 if (arg || nr_args)
12719 ret = io_register_enable_rings(ctx);
12721 case IORING_REGISTER_RESTRICTIONS:
12722 ret = io_register_restrictions(ctx, arg, nr_args);
12724 case IORING_REGISTER_FILES2:
12725 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
12727 case IORING_REGISTER_FILES_UPDATE2:
12728 ret = io_register_rsrc_update(ctx, arg, nr_args,
12731 case IORING_REGISTER_BUFFERS2:
12732 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
12734 case IORING_REGISTER_BUFFERS_UPDATE:
12735 ret = io_register_rsrc_update(ctx, arg, nr_args,
12736 IORING_RSRC_BUFFER);
12738 case IORING_REGISTER_IOWQ_AFF:
12740 if (!arg || !nr_args)
12742 ret = io_register_iowq_aff(ctx, arg, nr_args);
12744 case IORING_UNREGISTER_IOWQ_AFF:
12746 if (arg || nr_args)
12748 ret = io_unregister_iowq_aff(ctx);
12750 case IORING_REGISTER_IOWQ_MAX_WORKERS:
12752 if (!arg || nr_args != 2)
12754 ret = io_register_iowq_max_workers(ctx, arg);
12756 case IORING_REGISTER_RING_FDS:
12757 ret = io_ringfd_register(ctx, arg, nr_args);
12759 case IORING_UNREGISTER_RING_FDS:
12760 ret = io_ringfd_unregister(ctx, arg, nr_args);
12762 case IORING_REGISTER_PBUF_RING:
12764 if (!arg || nr_args != 1)
12766 ret = io_register_pbuf_ring(ctx, arg);
12768 case IORING_UNREGISTER_PBUF_RING:
12770 if (!arg || nr_args != 1)
12772 ret = io_unregister_pbuf_ring(ctx, arg);
12782 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
12783 void __user *, arg, unsigned int, nr_args)
12785 struct io_ring_ctx *ctx;
12794 if (f.file->f_op != &io_uring_fops)
12797 ctx = f.file->private_data;
12799 io_run_task_work();
12801 mutex_lock(&ctx->uring_lock);
12802 ret = __io_uring_register(ctx, opcode, arg, nr_args);
12803 mutex_unlock(&ctx->uring_lock);
12804 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
12810 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
12816 static const struct io_op_def io_op_defs[] = {
12817 [IORING_OP_NOP] = {
12820 .prep = io_nop_prep,
12823 [IORING_OP_READV] = {
12825 .unbound_nonreg_file = 1,
12827 .buffer_select = 1,
12832 .async_size = sizeof(struct io_async_rw),
12833 .prep = io_prep_rw,
12835 .prep_async = io_readv_prep_async,
12837 [IORING_OP_WRITEV] = {
12839 .hash_reg_file = 1,
12840 .unbound_nonreg_file = 1,
12846 .async_size = sizeof(struct io_async_rw),
12847 .prep = io_prep_rw,
12849 .prep_async = io_writev_prep_async,
12851 [IORING_OP_FSYNC] = {
12854 .prep = io_fsync_prep,
12857 [IORING_OP_READ_FIXED] = {
12859 .unbound_nonreg_file = 1,
12865 .async_size = sizeof(struct io_async_rw),
12866 .prep = io_prep_rw,
12869 [IORING_OP_WRITE_FIXED] = {
12871 .hash_reg_file = 1,
12872 .unbound_nonreg_file = 1,
12878 .async_size = sizeof(struct io_async_rw),
12879 .prep = io_prep_rw,
12882 [IORING_OP_POLL_ADD] = {
12884 .unbound_nonreg_file = 1,
12886 .prep = io_poll_add_prep,
12887 .issue = io_poll_add,
12889 [IORING_OP_POLL_REMOVE] = {
12891 .prep = io_poll_remove_prep,
12892 .issue = io_poll_remove,
12894 [IORING_OP_SYNC_FILE_RANGE] = {
12897 .prep = io_sfr_prep,
12898 .issue = io_sync_file_range,
12900 [IORING_OP_SENDMSG] = {
12902 .unbound_nonreg_file = 1,
12905 .async_size = sizeof(struct io_async_msghdr),
12906 .prep = io_sendmsg_prep,
12907 .issue = io_sendmsg,
12908 .prep_async = io_sendmsg_prep_async,
12910 [IORING_OP_RECVMSG] = {
12912 .unbound_nonreg_file = 1,
12914 .buffer_select = 1,
12916 .async_size = sizeof(struct io_async_msghdr),
12917 .prep = io_recvmsg_prep,
12918 .issue = io_recvmsg,
12919 .prep_async = io_recvmsg_prep_async,
12921 [IORING_OP_TIMEOUT] = {
12923 .async_size = sizeof(struct io_timeout_data),
12924 .prep = io_timeout_prep,
12925 .issue = io_timeout,
12927 [IORING_OP_TIMEOUT_REMOVE] = {
12928 /* used by timeout updates' prep() */
12930 .prep = io_timeout_remove_prep,
12931 .issue = io_timeout_remove,
12933 [IORING_OP_ACCEPT] = {
12935 .unbound_nonreg_file = 1,
12937 .poll_exclusive = 1,
12938 .ioprio = 1, /* used for flags */
12939 .prep = io_accept_prep,
12940 .issue = io_accept,
12942 [IORING_OP_ASYNC_CANCEL] = {
12944 .prep = io_async_cancel_prep,
12945 .issue = io_async_cancel,
12947 [IORING_OP_LINK_TIMEOUT] = {
12949 .async_size = sizeof(struct io_timeout_data),
12950 .prep = io_link_timeout_prep,
12951 .issue = io_no_issue,
12953 [IORING_OP_CONNECT] = {
12955 .unbound_nonreg_file = 1,
12957 .async_size = sizeof(struct io_async_connect),
12958 .prep = io_connect_prep,
12959 .issue = io_connect,
12960 .prep_async = io_connect_prep_async,
12962 [IORING_OP_FALLOCATE] = {
12964 .prep = io_fallocate_prep,
12965 .issue = io_fallocate,
12967 [IORING_OP_OPENAT] = {
12968 .prep = io_openat_prep,
12969 .issue = io_openat,
12971 [IORING_OP_CLOSE] = {
12972 .prep = io_close_prep,
12975 [IORING_OP_FILES_UPDATE] = {
12978 .prep = io_files_update_prep,
12979 .issue = io_files_update,
12981 [IORING_OP_STATX] = {
12983 .prep = io_statx_prep,
12986 [IORING_OP_READ] = {
12988 .unbound_nonreg_file = 1,
12990 .buffer_select = 1,
12995 .async_size = sizeof(struct io_async_rw),
12996 .prep = io_prep_rw,
12999 [IORING_OP_WRITE] = {
13001 .hash_reg_file = 1,
13002 .unbound_nonreg_file = 1,
13008 .async_size = sizeof(struct io_async_rw),
13009 .prep = io_prep_rw,
13012 [IORING_OP_FADVISE] = {
13015 .prep = io_fadvise_prep,
13016 .issue = io_fadvise,
13018 [IORING_OP_MADVISE] = {
13019 .prep = io_madvise_prep,
13020 .issue = io_madvise,
13022 [IORING_OP_SEND] = {
13024 .unbound_nonreg_file = 1,
13028 .prep = io_sendmsg_prep,
13031 [IORING_OP_RECV] = {
13033 .unbound_nonreg_file = 1,
13035 .buffer_select = 1,
13038 .prep = io_recvmsg_prep,
13041 [IORING_OP_OPENAT2] = {
13042 .prep = io_openat2_prep,
13043 .issue = io_openat2,
13045 [IORING_OP_EPOLL_CTL] = {
13046 .unbound_nonreg_file = 1,
13048 .prep = io_epoll_ctl_prep,
13049 .issue = io_epoll_ctl,
13051 [IORING_OP_SPLICE] = {
13053 .hash_reg_file = 1,
13054 .unbound_nonreg_file = 1,
13056 .prep = io_splice_prep,
13057 .issue = io_splice,
13059 [IORING_OP_PROVIDE_BUFFERS] = {
13062 .prep = io_provide_buffers_prep,
13063 .issue = io_provide_buffers,
13065 [IORING_OP_REMOVE_BUFFERS] = {
13068 .prep = io_remove_buffers_prep,
13069 .issue = io_remove_buffers,
13071 [IORING_OP_TEE] = {
13073 .hash_reg_file = 1,
13074 .unbound_nonreg_file = 1,
13076 .prep = io_tee_prep,
13079 [IORING_OP_SHUTDOWN] = {
13081 .prep = io_shutdown_prep,
13082 .issue = io_shutdown,
13084 [IORING_OP_RENAMEAT] = {
13085 .prep = io_renameat_prep,
13086 .issue = io_renameat,
13088 [IORING_OP_UNLINKAT] = {
13089 .prep = io_unlinkat_prep,
13090 .issue = io_unlinkat,
13092 [IORING_OP_MKDIRAT] = {
13093 .prep = io_mkdirat_prep,
13094 .issue = io_mkdirat,
13096 [IORING_OP_SYMLINKAT] = {
13097 .prep = io_symlinkat_prep,
13098 .issue = io_symlinkat,
13100 [IORING_OP_LINKAT] = {
13101 .prep = io_linkat_prep,
13102 .issue = io_linkat,
13104 [IORING_OP_MSG_RING] = {
13107 .prep = io_msg_ring_prep,
13108 .issue = io_msg_ring,
13110 [IORING_OP_FSETXATTR] = {
13112 .prep = io_fsetxattr_prep,
13113 .issue = io_fsetxattr,
13115 [IORING_OP_SETXATTR] = {
13116 .prep = io_setxattr_prep,
13117 .issue = io_setxattr,
13119 [IORING_OP_FGETXATTR] = {
13121 .prep = io_fgetxattr_prep,
13122 .issue = io_fgetxattr,
13124 [IORING_OP_GETXATTR] = {
13125 .prep = io_getxattr_prep,
13126 .issue = io_getxattr,
13128 [IORING_OP_SOCKET] = {
13130 .prep = io_socket_prep,
13131 .issue = io_socket,
13133 [IORING_OP_URING_CMD] = {
13136 .async_size = uring_cmd_pdu_size(1),
13137 .prep = io_uring_cmd_prep,
13138 .issue = io_uring_cmd,
13139 .prep_async = io_uring_cmd_prep_async,
13143 static int __init io_uring_init(void)
13147 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13148 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13149 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13152 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13153 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13154 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13155 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13156 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13157 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13158 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13159 BUILD_BUG_SQE_ELEM(8, __u64, off);
13160 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13161 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13162 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13163 BUILD_BUG_SQE_ELEM(24, __u32, len);
13164 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13165 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13166 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13167 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13168 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13169 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13170 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13171 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13172 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13173 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13174 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13175 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13176 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13177 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13178 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13179 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13180 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13181 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13182 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13183 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13184 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13185 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13187 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13188 sizeof(struct io_uring_rsrc_update));
13189 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13190 sizeof(struct io_uring_rsrc_update2));
13192 /* ->buf_index is u16 */
13193 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13194 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13195 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13196 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13197 offsetof(struct io_uring_buf_ring, tail));
13199 /* should fit into one byte */
13200 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13201 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13202 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13204 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13205 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13207 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13209 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13211 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
13212 BUG_ON(!io_op_defs[i].prep);
13213 BUG_ON(!io_op_defs[i].issue);
13216 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13220 __initcall(io_uring_init);