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_timeout timeout;
983 struct io_timeout_rem timeout_rem;
985 struct io_close close;
986 struct io_rsrc_update rsrc_update;
987 struct io_fadvise fadvise;
988 struct io_madvise madvise;
989 struct io_epoll epoll;
990 struct io_splice splice;
991 struct io_provide_buf pbuf;
992 struct io_statx statx;
993 struct io_rename rename;
994 struct io_unlink unlink;
995 struct io_mkdir mkdir;
996 struct io_symlink symlink;
997 struct io_hardlink hardlink;
999 struct io_xattr xattr;
1000 struct io_uring_cmd uring_cmd;
1004 /* polled IO has completed */
1005 u8 iopoll_completed;
1007 * Can be either a fixed buffer index, or used with provided buffers.
1008 * For the latter, before issue it points to the buffer group ID,
1009 * and after selection it points to the buffer ID itself.
1016 struct io_ring_ctx *ctx;
1017 struct task_struct *task;
1019 struct io_rsrc_node *rsrc_node;
1022 /* store used ubuf, so we can prevent reloading */
1023 struct io_mapped_ubuf *imu;
1025 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
1026 struct io_buffer *kbuf;
1029 * stores buffer ID for ring provided buffers, valid IFF
1030 * REQ_F_BUFFER_RING is set.
1032 struct io_buffer_list *buf_list;
1036 /* used by request caches, completion batching and iopoll */
1037 struct io_wq_work_node comp_list;
1038 /* cache ->apoll->events */
1039 __poll_t apoll_events;
1043 struct io_task_work io_task_work;
1044 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1046 struct hlist_node hash_node;
1052 /* internal polling, see IORING_FEAT_FAST_POLL */
1053 struct async_poll *apoll;
1054 /* opcode allocated if it needs to store data for async defer */
1056 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1057 struct io_kiocb *link;
1058 /* custom credentials, valid IFF REQ_F_CREDS is set */
1059 const struct cred *creds;
1060 struct io_wq_work work;
1063 struct io_tctx_node {
1064 struct list_head ctx_node;
1065 struct task_struct *task;
1066 struct io_ring_ctx *ctx;
1069 struct io_defer_entry {
1070 struct list_head list;
1071 struct io_kiocb *req;
1075 struct io_cancel_data {
1076 struct io_ring_ctx *ctx;
1086 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
1087 * the following sqe if SQE128 is used.
1089 #define uring_cmd_pdu_size(is_sqe128) \
1090 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
1091 offsetof(struct io_uring_sqe, cmd))
1094 /* needs req->file assigned */
1095 unsigned needs_file : 1;
1096 /* should block plug */
1098 /* hash wq insertion if file is a regular file */
1099 unsigned hash_reg_file : 1;
1100 /* unbound wq insertion if file is a non-regular file */
1101 unsigned unbound_nonreg_file : 1;
1102 /* set if opcode supports polled "wait" */
1103 unsigned pollin : 1;
1104 unsigned pollout : 1;
1105 unsigned poll_exclusive : 1;
1106 /* op supports buffer selection */
1107 unsigned buffer_select : 1;
1108 /* opcode is not supported by this kernel */
1109 unsigned not_supported : 1;
1111 unsigned audit_skip : 1;
1112 /* supports ioprio */
1113 unsigned ioprio : 1;
1114 /* supports iopoll */
1115 unsigned iopoll : 1;
1116 /* size of async data needed, if any */
1117 unsigned short async_size;
1119 int (*prep)(struct io_kiocb *, const struct io_uring_sqe *);
1120 int (*issue)(struct io_kiocb *, unsigned int);
1121 int (*prep_async)(struct io_kiocb *);
1124 static const struct io_op_def io_op_defs[];
1126 /* requests with any of those set should undergo io_disarm_next() */
1127 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1128 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1130 static bool io_disarm_next(struct io_kiocb *req);
1131 static void io_uring_del_tctx_node(unsigned long index);
1132 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1133 struct task_struct *task,
1135 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1137 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1138 static void io_dismantle_req(struct io_kiocb *req);
1139 static void io_queue_linked_timeout(struct io_kiocb *req);
1140 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1141 struct io_uring_rsrc_update2 *up,
1143 static void io_clean_op(struct io_kiocb *req);
1144 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1145 unsigned issue_flags);
1146 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1147 static void io_queue_sqe(struct io_kiocb *req);
1148 static void io_rsrc_put_work(struct work_struct *work);
1150 static void io_req_task_queue(struct io_kiocb *req);
1151 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1152 static int io_req_prep_async(struct io_kiocb *req);
1154 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1155 unsigned int issue_flags, u32 slot_index);
1156 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
1157 unsigned int offset);
1158 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1160 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1161 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1162 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1164 static struct kmem_cache *req_cachep;
1166 static const struct file_operations io_uring_fops;
1168 const char *io_uring_get_opcode(u8 opcode)
1170 switch ((enum io_uring_op)opcode) {
1173 case IORING_OP_READV:
1175 case IORING_OP_WRITEV:
1177 case IORING_OP_FSYNC:
1179 case IORING_OP_READ_FIXED:
1180 return "READ_FIXED";
1181 case IORING_OP_WRITE_FIXED:
1182 return "WRITE_FIXED";
1183 case IORING_OP_POLL_ADD:
1185 case IORING_OP_POLL_REMOVE:
1186 return "POLL_REMOVE";
1187 case IORING_OP_SYNC_FILE_RANGE:
1188 return "SYNC_FILE_RANGE";
1189 case IORING_OP_SENDMSG:
1191 case IORING_OP_RECVMSG:
1193 case IORING_OP_TIMEOUT:
1195 case IORING_OP_TIMEOUT_REMOVE:
1196 return "TIMEOUT_REMOVE";
1197 case IORING_OP_ACCEPT:
1199 case IORING_OP_ASYNC_CANCEL:
1200 return "ASYNC_CANCEL";
1201 case IORING_OP_LINK_TIMEOUT:
1202 return "LINK_TIMEOUT";
1203 case IORING_OP_CONNECT:
1205 case IORING_OP_FALLOCATE:
1207 case IORING_OP_OPENAT:
1209 case IORING_OP_CLOSE:
1211 case IORING_OP_FILES_UPDATE:
1212 return "FILES_UPDATE";
1213 case IORING_OP_STATX:
1215 case IORING_OP_READ:
1217 case IORING_OP_WRITE:
1219 case IORING_OP_FADVISE:
1221 case IORING_OP_MADVISE:
1223 case IORING_OP_SEND:
1225 case IORING_OP_RECV:
1227 case IORING_OP_OPENAT2:
1229 case IORING_OP_EPOLL_CTL:
1231 case IORING_OP_SPLICE:
1233 case IORING_OP_PROVIDE_BUFFERS:
1234 return "PROVIDE_BUFFERS";
1235 case IORING_OP_REMOVE_BUFFERS:
1236 return "REMOVE_BUFFERS";
1239 case IORING_OP_SHUTDOWN:
1241 case IORING_OP_RENAMEAT:
1243 case IORING_OP_UNLINKAT:
1245 case IORING_OP_MKDIRAT:
1247 case IORING_OP_SYMLINKAT:
1249 case IORING_OP_LINKAT:
1251 case IORING_OP_MSG_RING:
1253 case IORING_OP_FSETXATTR:
1255 case IORING_OP_SETXATTR:
1257 case IORING_OP_FGETXATTR:
1259 case IORING_OP_GETXATTR:
1261 case IORING_OP_SOCKET:
1263 case IORING_OP_URING_CMD:
1265 case IORING_OP_LAST:
1271 struct sock *io_uring_get_socket(struct file *file)
1273 #if defined(CONFIG_UNIX)
1274 if (file->f_op == &io_uring_fops) {
1275 struct io_ring_ctx *ctx = file->private_data;
1277 return ctx->ring_sock->sk;
1282 EXPORT_SYMBOL(io_uring_get_socket);
1284 #if defined(CONFIG_UNIX)
1285 static inline bool io_file_need_scm(struct file *filp)
1287 #if defined(IO_URING_SCM_ALL)
1290 return !!unix_get_socket(filp);
1294 static inline bool io_file_need_scm(struct file *filp)
1300 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1302 lockdep_assert_held(&ctx->uring_lock);
1303 if (issue_flags & IO_URING_F_UNLOCKED)
1304 mutex_unlock(&ctx->uring_lock);
1307 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1310 * "Normal" inline submissions always hold the uring_lock, since we
1311 * grab it from the system call. Same is true for the SQPOLL offload.
1312 * The only exception is when we've detached the request and issue it
1313 * from an async worker thread, grab the lock for that case.
1315 if (issue_flags & IO_URING_F_UNLOCKED)
1316 mutex_lock(&ctx->uring_lock);
1317 lockdep_assert_held(&ctx->uring_lock);
1320 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1323 mutex_lock(&ctx->uring_lock);
1328 #define io_for_each_link(pos, head) \
1329 for (pos = (head); pos; pos = pos->link)
1332 * Shamelessly stolen from the mm implementation of page reference checking,
1333 * see commit f958d7b528b1 for details.
1335 #define req_ref_zero_or_close_to_overflow(req) \
1336 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1338 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1340 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1341 return atomic_inc_not_zero(&req->refs);
1344 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1346 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1349 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1350 return atomic_dec_and_test(&req->refs);
1353 static inline void req_ref_get(struct io_kiocb *req)
1355 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1356 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1357 atomic_inc(&req->refs);
1360 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1362 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1363 __io_submit_flush_completions(ctx);
1366 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1368 if (!(req->flags & REQ_F_REFCOUNT)) {
1369 req->flags |= REQ_F_REFCOUNT;
1370 atomic_set(&req->refs, nr);
1374 static inline void io_req_set_refcount(struct io_kiocb *req)
1376 __io_req_set_refcount(req, 1);
1379 #define IO_RSRC_REF_BATCH 100
1381 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1383 percpu_ref_put_many(&node->refs, nr);
1386 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1387 struct io_ring_ctx *ctx)
1388 __must_hold(&ctx->uring_lock)
1390 struct io_rsrc_node *node = req->rsrc_node;
1393 if (node == ctx->rsrc_node)
1394 ctx->rsrc_cached_refs++;
1396 io_rsrc_put_node(node, 1);
1400 static inline void io_req_put_rsrc(struct io_kiocb *req)
1403 io_rsrc_put_node(req->rsrc_node, 1);
1406 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1407 __must_hold(&ctx->uring_lock)
1409 if (ctx->rsrc_cached_refs) {
1410 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1411 ctx->rsrc_cached_refs = 0;
1415 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1416 __must_hold(&ctx->uring_lock)
1418 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1419 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1422 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1423 struct io_ring_ctx *ctx,
1424 unsigned int issue_flags)
1426 if (!req->rsrc_node) {
1427 req->rsrc_node = ctx->rsrc_node;
1429 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1430 lockdep_assert_held(&ctx->uring_lock);
1431 ctx->rsrc_cached_refs--;
1432 if (unlikely(ctx->rsrc_cached_refs < 0))
1433 io_rsrc_refs_refill(ctx);
1435 percpu_ref_get(&req->rsrc_node->refs);
1440 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1442 if (req->flags & REQ_F_BUFFER_RING) {
1444 req->buf_list->head++;
1445 req->flags &= ~REQ_F_BUFFER_RING;
1447 list_add(&req->kbuf->list, list);
1448 req->flags &= ~REQ_F_BUFFER_SELECTED;
1451 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1454 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1456 lockdep_assert_held(&req->ctx->completion_lock);
1458 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1460 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1463 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1464 unsigned issue_flags)
1466 unsigned int cflags;
1468 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1472 * We can add this buffer back to two lists:
1474 * 1) The io_buffers_cache list. This one is protected by the
1475 * ctx->uring_lock. If we already hold this lock, add back to this
1476 * list as we can grab it from issue as well.
1477 * 2) The io_buffers_comp list. This one is protected by the
1478 * ctx->completion_lock.
1480 * We migrate buffers from the comp_list to the issue cache list
1483 if (req->flags & REQ_F_BUFFER_RING) {
1484 /* no buffers to recycle for this case */
1485 cflags = __io_put_kbuf(req, NULL);
1486 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1487 struct io_ring_ctx *ctx = req->ctx;
1489 spin_lock(&ctx->completion_lock);
1490 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1491 spin_unlock(&ctx->completion_lock);
1493 lockdep_assert_held(&req->ctx->uring_lock);
1495 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1501 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1504 if (ctx->io_bl && bgid < BGID_ARRAY)
1505 return &ctx->io_bl[bgid];
1507 return xa_load(&ctx->io_bl_xa, bgid);
1510 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1512 struct io_ring_ctx *ctx = req->ctx;
1513 struct io_buffer_list *bl;
1514 struct io_buffer *buf;
1516 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1519 * For legacy provided buffer mode, don't recycle if we already did
1520 * IO to this buffer. For ring-mapped provided buffer mode, we should
1521 * increment ring->head to explicitly monopolize the buffer to avoid
1524 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
1525 (req->flags & REQ_F_PARTIAL_IO))
1529 * READV uses fields in `struct io_rw` (len/addr) to stash the selected
1530 * buffer data. However if that buffer is recycled the original request
1531 * data stored in addr is lost. Therefore forbid recycling for now.
1533 if (req->opcode == IORING_OP_READV)
1537 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1538 * the flag and hence ensure that bl->head doesn't get incremented.
1539 * If the tail has already been incremented, hang on to it.
1541 if (req->flags & REQ_F_BUFFER_RING) {
1542 if (req->buf_list) {
1543 if (req->flags & REQ_F_PARTIAL_IO) {
1544 req->buf_list->head++;
1545 req->buf_list = NULL;
1547 req->buf_index = req->buf_list->bgid;
1548 req->flags &= ~REQ_F_BUFFER_RING;
1554 io_ring_submit_lock(ctx, issue_flags);
1557 bl = io_buffer_get_list(ctx, buf->bgid);
1558 list_add(&buf->list, &bl->buf_list);
1559 req->flags &= ~REQ_F_BUFFER_SELECTED;
1560 req->buf_index = buf->bgid;
1562 io_ring_submit_unlock(ctx, issue_flags);
1565 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1567 __must_hold(&req->ctx->timeout_lock)
1569 struct io_kiocb *req;
1571 if (task && head->task != task)
1576 io_for_each_link(req, head) {
1577 if (req->flags & REQ_F_INFLIGHT)
1583 static bool io_match_linked(struct io_kiocb *head)
1585 struct io_kiocb *req;
1587 io_for_each_link(req, head) {
1588 if (req->flags & REQ_F_INFLIGHT)
1595 * As io_match_task() but protected against racing with linked timeouts.
1596 * User must not hold timeout_lock.
1598 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1603 if (task && head->task != task)
1608 if (head->flags & REQ_F_LINK_TIMEOUT) {
1609 struct io_ring_ctx *ctx = head->ctx;
1611 /* protect against races with linked timeouts */
1612 spin_lock_irq(&ctx->timeout_lock);
1613 matched = io_match_linked(head);
1614 spin_unlock_irq(&ctx->timeout_lock);
1616 matched = io_match_linked(head);
1621 static inline bool req_has_async_data(struct io_kiocb *req)
1623 return req->flags & REQ_F_ASYNC_DATA;
1626 static inline void req_set_fail(struct io_kiocb *req)
1628 req->flags |= REQ_F_FAIL;
1629 if (req->flags & REQ_F_CQE_SKIP) {
1630 req->flags &= ~REQ_F_CQE_SKIP;
1631 req->flags |= REQ_F_SKIP_LINK_CQES;
1635 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1641 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1643 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1646 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1648 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1650 complete(&ctx->ref_comp);
1653 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1655 return !req->timeout.off;
1658 static __cold void io_fallback_req_func(struct work_struct *work)
1660 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1661 fallback_work.work);
1662 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1663 struct io_kiocb *req, *tmp;
1664 bool locked = false;
1666 percpu_ref_get(&ctx->refs);
1667 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1668 req->io_task_work.func(req, &locked);
1671 io_submit_flush_completions(ctx);
1672 mutex_unlock(&ctx->uring_lock);
1674 percpu_ref_put(&ctx->refs);
1677 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1679 struct io_ring_ctx *ctx;
1682 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1686 xa_init(&ctx->io_bl_xa);
1689 * Use 5 bits less than the max cq entries, that should give us around
1690 * 32 entries per hash list if totally full and uniformly spread.
1692 hash_bits = ilog2(p->cq_entries);
1696 ctx->cancel_hash_bits = hash_bits;
1697 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1699 if (!ctx->cancel_hash)
1701 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1703 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1704 if (!ctx->dummy_ubuf)
1706 /* set invalid range, so io_import_fixed() fails meeting it */
1707 ctx->dummy_ubuf->ubuf = -1UL;
1709 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1710 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1713 ctx->flags = p->flags;
1714 init_waitqueue_head(&ctx->sqo_sq_wait);
1715 INIT_LIST_HEAD(&ctx->sqd_list);
1716 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1717 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1718 INIT_LIST_HEAD(&ctx->apoll_cache);
1719 init_completion(&ctx->ref_comp);
1720 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1721 mutex_init(&ctx->uring_lock);
1722 init_waitqueue_head(&ctx->cq_wait);
1723 spin_lock_init(&ctx->completion_lock);
1724 spin_lock_init(&ctx->timeout_lock);
1725 INIT_WQ_LIST(&ctx->iopoll_list);
1726 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1727 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1728 INIT_LIST_HEAD(&ctx->defer_list);
1729 INIT_LIST_HEAD(&ctx->timeout_list);
1730 INIT_LIST_HEAD(&ctx->ltimeout_list);
1731 spin_lock_init(&ctx->rsrc_ref_lock);
1732 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1733 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1734 init_llist_head(&ctx->rsrc_put_llist);
1735 INIT_LIST_HEAD(&ctx->tctx_list);
1736 ctx->submit_state.free_list.next = NULL;
1737 INIT_WQ_LIST(&ctx->locked_free_list);
1738 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1739 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1742 kfree(ctx->dummy_ubuf);
1743 kfree(ctx->cancel_hash);
1745 xa_destroy(&ctx->io_bl_xa);
1750 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1752 struct io_rings *r = ctx->rings;
1754 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1758 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1760 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1761 struct io_ring_ctx *ctx = req->ctx;
1763 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1769 static inline bool io_req_ffs_set(struct io_kiocb *req)
1771 return req->flags & REQ_F_FIXED_FILE;
1774 static inline void io_req_track_inflight(struct io_kiocb *req)
1776 if (!(req->flags & REQ_F_INFLIGHT)) {
1777 req->flags |= REQ_F_INFLIGHT;
1778 atomic_inc(&req->task->io_uring->inflight_tracked);
1782 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1784 if (WARN_ON_ONCE(!req->link))
1787 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1788 req->flags |= REQ_F_LINK_TIMEOUT;
1790 /* linked timeouts should have two refs once prep'ed */
1791 io_req_set_refcount(req);
1792 __io_req_set_refcount(req->link, 2);
1796 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1798 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1800 return __io_prep_linked_timeout(req);
1803 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1805 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1808 static inline void io_arm_ltimeout(struct io_kiocb *req)
1810 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1811 __io_arm_ltimeout(req);
1814 static void io_prep_async_work(struct io_kiocb *req)
1816 const struct io_op_def *def = &io_op_defs[req->opcode];
1817 struct io_ring_ctx *ctx = req->ctx;
1819 if (!(req->flags & REQ_F_CREDS)) {
1820 req->flags |= REQ_F_CREDS;
1821 req->creds = get_current_cred();
1824 req->work.list.next = NULL;
1825 req->work.flags = 0;
1826 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1827 if (req->flags & REQ_F_FORCE_ASYNC)
1828 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1830 if (req->flags & REQ_F_ISREG) {
1831 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1832 io_wq_hash_work(&req->work, file_inode(req->file));
1833 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1834 if (def->unbound_nonreg_file)
1835 req->work.flags |= IO_WQ_WORK_UNBOUND;
1839 static void io_prep_async_link(struct io_kiocb *req)
1841 struct io_kiocb *cur;
1843 if (req->flags & REQ_F_LINK_TIMEOUT) {
1844 struct io_ring_ctx *ctx = req->ctx;
1846 spin_lock_irq(&ctx->timeout_lock);
1847 io_for_each_link(cur, req)
1848 io_prep_async_work(cur);
1849 spin_unlock_irq(&ctx->timeout_lock);
1851 io_for_each_link(cur, req)
1852 io_prep_async_work(cur);
1856 static inline void io_req_add_compl_list(struct io_kiocb *req)
1858 struct io_submit_state *state = &req->ctx->submit_state;
1860 if (!(req->flags & REQ_F_CQE_SKIP))
1861 state->flush_cqes = true;
1862 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1865 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1867 struct io_kiocb *link = io_prep_linked_timeout(req);
1868 struct io_uring_task *tctx = req->task->io_uring;
1871 BUG_ON(!tctx->io_wq);
1873 /* init ->work of the whole link before punting */
1874 io_prep_async_link(req);
1877 * Not expected to happen, but if we do have a bug where this _can_
1878 * happen, catch it here and ensure the request is marked as
1879 * canceled. That will make io-wq go through the usual work cancel
1880 * procedure rather than attempt to run this request (or create a new
1883 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1884 req->work.flags |= IO_WQ_WORK_CANCEL;
1886 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1887 req->opcode, req->flags, &req->work,
1888 io_wq_is_hashed(&req->work));
1889 io_wq_enqueue(tctx->io_wq, &req->work);
1891 io_queue_linked_timeout(link);
1894 static void io_kill_timeout(struct io_kiocb *req, int status)
1895 __must_hold(&req->ctx->completion_lock)
1896 __must_hold(&req->ctx->timeout_lock)
1898 struct io_timeout_data *io = req->async_data;
1900 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1903 atomic_set(&req->ctx->cq_timeouts,
1904 atomic_read(&req->ctx->cq_timeouts) + 1);
1905 list_del_init(&req->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_kiocb *req, *tmp;
1930 spin_lock_irq(&ctx->timeout_lock);
1931 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1932 u32 events_needed, events_got;
1934 if (io_is_timeout_noseq(req))
1938 * Since seq can easily wrap around over time, subtract
1939 * the last seq at which timeouts were flushed before comparing.
1940 * Assuming not more than 2^31-1 events have happened since,
1941 * these subtractions won't have wrapped, so we can check if
1942 * target is in [last_seq, current_seq] by comparing the two.
1944 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1945 events_got = seq - ctx->cq_last_tm_flush;
1946 if (events_got < events_needed)
1949 io_kill_timeout(req, 0);
1951 ctx->cq_last_tm_flush = seq;
1952 spin_unlock_irq(&ctx->timeout_lock);
1955 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1957 /* order cqe stores with ring update */
1958 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1961 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1963 if (ctx->off_timeout_used || ctx->drain_active) {
1964 spin_lock(&ctx->completion_lock);
1965 if (ctx->off_timeout_used)
1966 io_flush_timeouts(ctx);
1967 if (ctx->drain_active)
1968 io_queue_deferred(ctx);
1969 io_commit_cqring(ctx);
1970 spin_unlock(&ctx->completion_lock);
1973 io_eventfd_signal(ctx);
1976 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1978 struct io_rings *r = ctx->rings;
1980 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1983 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1985 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1989 * writes to the cq entry need to come after reading head; the
1990 * control dependency is enough as we're using WRITE_ONCE to
1993 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1995 struct io_rings *rings = ctx->rings;
1996 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1997 unsigned int shift = 0;
1998 unsigned int free, queued, len;
2000 if (ctx->flags & IORING_SETUP_CQE32)
2003 /* userspace may cheat modifying the tail, be safe and do min */
2004 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2005 free = ctx->cq_entries - queued;
2006 /* we need a contiguous range, limit based on the current array offset */
2007 len = min(free, ctx->cq_entries - off);
2011 ctx->cached_cq_tail++;
2012 ctx->cqe_cached = &rings->cqes[off];
2013 ctx->cqe_sentinel = ctx->cqe_cached + len;
2015 return &rings->cqes[off << shift];
2018 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2020 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2021 struct io_uring_cqe *cqe = ctx->cqe_cached;
2023 if (ctx->flags & IORING_SETUP_CQE32) {
2024 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2029 ctx->cached_cq_tail++;
2034 return __io_get_cqe(ctx);
2037 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2039 struct io_ev_fd *ev_fd;
2043 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2044 * and eventfd_signal
2046 ev_fd = rcu_dereference(ctx->io_ev_fd);
2049 * Check again if ev_fd exists incase an io_eventfd_unregister call
2050 * completed between the NULL check of ctx->io_ev_fd at the start of
2051 * the function and rcu_read_lock.
2053 if (unlikely(!ev_fd))
2055 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2058 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2059 eventfd_signal(ev_fd->cq_ev_fd, 1);
2064 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2067 * wake_up_all() may seem excessive, but io_wake_function() and
2068 * io_should_wake() handle the termination of the loop and only
2069 * wake as many waiters as we need to.
2071 if (wq_has_sleeper(&ctx->cq_wait))
2072 wake_up_all(&ctx->cq_wait);
2076 * This should only get called when at least one event has been posted.
2077 * Some applications rely on the eventfd notification count only changing
2078 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2079 * 1:1 relationship between how many times this function is called (and
2080 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2082 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2084 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2086 __io_commit_cqring_flush(ctx);
2088 io_cqring_wake(ctx);
2091 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2093 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2095 __io_commit_cqring_flush(ctx);
2097 if (ctx->flags & IORING_SETUP_SQPOLL)
2098 io_cqring_wake(ctx);
2101 /* Returns true if there are no backlogged entries after the flush */
2102 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2104 bool all_flushed, posted;
2105 size_t cqe_size = sizeof(struct io_uring_cqe);
2107 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2110 if (ctx->flags & IORING_SETUP_CQE32)
2114 spin_lock(&ctx->completion_lock);
2115 while (!list_empty(&ctx->cq_overflow_list)) {
2116 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2117 struct io_overflow_cqe *ocqe;
2121 ocqe = list_first_entry(&ctx->cq_overflow_list,
2122 struct io_overflow_cqe, list);
2124 memcpy(cqe, &ocqe->cqe, cqe_size);
2126 io_account_cq_overflow(ctx);
2129 list_del(&ocqe->list);
2133 all_flushed = list_empty(&ctx->cq_overflow_list);
2135 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2136 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2139 io_commit_cqring(ctx);
2140 spin_unlock(&ctx->completion_lock);
2142 io_cqring_ev_posted(ctx);
2146 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2150 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2151 /* iopoll syncs against uring_lock, not completion_lock */
2152 if (ctx->flags & IORING_SETUP_IOPOLL)
2153 mutex_lock(&ctx->uring_lock);
2154 ret = __io_cqring_overflow_flush(ctx, false);
2155 if (ctx->flags & IORING_SETUP_IOPOLL)
2156 mutex_unlock(&ctx->uring_lock);
2162 static void __io_put_task(struct task_struct *task, int nr)
2164 struct io_uring_task *tctx = task->io_uring;
2166 percpu_counter_sub(&tctx->inflight, nr);
2167 if (unlikely(atomic_read(&tctx->in_idle)))
2168 wake_up(&tctx->wait);
2169 put_task_struct_many(task, nr);
2172 /* must to be called somewhat shortly after putting a request */
2173 static inline void io_put_task(struct task_struct *task, int nr)
2175 if (likely(task == current))
2176 task->io_uring->cached_refs += nr;
2178 __io_put_task(task, nr);
2181 static void io_task_refs_refill(struct io_uring_task *tctx)
2183 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2185 percpu_counter_add(&tctx->inflight, refill);
2186 refcount_add(refill, ¤t->usage);
2187 tctx->cached_refs += refill;
2190 static inline void io_get_task_refs(int nr)
2192 struct io_uring_task *tctx = current->io_uring;
2194 tctx->cached_refs -= nr;
2195 if (unlikely(tctx->cached_refs < 0))
2196 io_task_refs_refill(tctx);
2199 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2201 struct io_uring_task *tctx = task->io_uring;
2202 unsigned int refs = tctx->cached_refs;
2205 tctx->cached_refs = 0;
2206 percpu_counter_sub(&tctx->inflight, refs);
2207 put_task_struct_many(task, refs);
2211 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2212 s32 res, u32 cflags, u64 extra1,
2215 struct io_overflow_cqe *ocqe;
2216 size_t ocq_size = sizeof(struct io_overflow_cqe);
2217 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2220 ocq_size += sizeof(struct io_uring_cqe);
2222 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2223 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2226 * If we're in ring overflow flush mode, or in task cancel mode,
2227 * or cannot allocate an overflow entry, then we need to drop it
2230 io_account_cq_overflow(ctx);
2231 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2234 if (list_empty(&ctx->cq_overflow_list)) {
2235 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2236 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2239 ocqe->cqe.user_data = user_data;
2240 ocqe->cqe.res = res;
2241 ocqe->cqe.flags = cflags;
2243 ocqe->cqe.big_cqe[0] = extra1;
2244 ocqe->cqe.big_cqe[1] = extra2;
2246 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2250 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
2251 struct io_kiocb *req)
2253 struct io_uring_cqe *cqe;
2255 if (!(ctx->flags & IORING_SETUP_CQE32)) {
2256 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2257 req->cqe.res, req->cqe.flags, 0, 0);
2260 * If we can't get a cq entry, userspace overflowed the
2261 * submission (by quite a lot). Increment the overflow count in
2264 cqe = io_get_cqe(ctx);
2266 memcpy(cqe, &req->cqe, sizeof(*cqe));
2270 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2271 req->cqe.res, req->cqe.flags,
2274 u64 extra1 = 0, extra2 = 0;
2276 if (req->flags & REQ_F_CQE32_INIT) {
2277 extra1 = req->extra1;
2278 extra2 = req->extra2;
2281 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2282 req->cqe.res, req->cqe.flags, extra1, extra2);
2285 * If we can't get a cq entry, userspace overflowed the
2286 * submission (by quite a lot). Increment the overflow count in
2289 cqe = io_get_cqe(ctx);
2291 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2292 WRITE_ONCE(cqe->big_cqe[0], extra1);
2293 WRITE_ONCE(cqe->big_cqe[1], extra2);
2297 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2298 req->cqe.res, req->cqe.flags,
2303 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2304 s32 res, u32 cflags)
2306 struct io_uring_cqe *cqe;
2309 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2312 * If we can't get a cq entry, userspace overflowed the
2313 * submission (by quite a lot). Increment the overflow count in
2316 cqe = io_get_cqe(ctx);
2318 WRITE_ONCE(cqe->user_data, user_data);
2319 WRITE_ONCE(cqe->res, res);
2320 WRITE_ONCE(cqe->flags, cflags);
2322 if (ctx->flags & IORING_SETUP_CQE32) {
2323 WRITE_ONCE(cqe->big_cqe[0], 0);
2324 WRITE_ONCE(cqe->big_cqe[1], 0);
2328 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2331 static void __io_req_complete_put(struct io_kiocb *req)
2334 * If we're the last reference to this request, add to our locked
2337 if (req_ref_put_and_test(req)) {
2338 struct io_ring_ctx *ctx = req->ctx;
2340 if (req->flags & IO_REQ_LINK_FLAGS) {
2341 if (req->flags & IO_DISARM_MASK)
2342 io_disarm_next(req);
2344 io_req_task_queue(req->link);
2348 io_req_put_rsrc(req);
2350 * Selected buffer deallocation in io_clean_op() assumes that
2351 * we don't hold ->completion_lock. Clean them here to avoid
2354 io_put_kbuf_comp(req);
2355 io_dismantle_req(req);
2356 io_put_task(req->task, 1);
2357 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2358 ctx->locked_free_nr++;
2362 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2365 if (!(req->flags & REQ_F_CQE_SKIP)) {
2367 req->cqe.flags = cflags;
2368 __io_fill_cqe_req(req->ctx, req);
2370 __io_req_complete_put(req);
2373 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2375 struct io_ring_ctx *ctx = req->ctx;
2377 spin_lock(&ctx->completion_lock);
2378 __io_req_complete_post(req, res, cflags);
2379 io_commit_cqring(ctx);
2380 spin_unlock(&ctx->completion_lock);
2381 io_cqring_ev_posted(ctx);
2384 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2388 req->cqe.flags = cflags;
2389 req->flags |= REQ_F_COMPLETE_INLINE;
2392 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2393 s32 res, u32 cflags)
2395 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2396 io_req_complete_state(req, res, cflags);
2398 io_req_complete_post(req, res, cflags);
2401 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2405 __io_req_complete(req, 0, res, 0);
2408 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2411 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2415 * Don't initialise the fields below on every allocation, but do that in
2416 * advance and keep them valid across allocations.
2418 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2422 req->async_data = NULL;
2423 /* not necessary, but safer to zero */
2427 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2428 struct io_submit_state *state)
2430 spin_lock(&ctx->completion_lock);
2431 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2432 ctx->locked_free_nr = 0;
2433 spin_unlock(&ctx->completion_lock);
2436 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2438 return !ctx->submit_state.free_list.next;
2442 * A request might get retired back into the request caches even before opcode
2443 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2444 * Because of that, io_alloc_req() should be called only under ->uring_lock
2445 * and with extra caution to not get a request that is still worked on.
2447 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2448 __must_hold(&ctx->uring_lock)
2450 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2451 void *reqs[IO_REQ_ALLOC_BATCH];
2455 * If we have more than a batch's worth of requests in our IRQ side
2456 * locked cache, grab the lock and move them over to our submission
2459 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2460 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2461 if (!io_req_cache_empty(ctx))
2465 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2468 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2469 * retry single alloc to be on the safe side.
2471 if (unlikely(ret <= 0)) {
2472 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2478 percpu_ref_get_many(&ctx->refs, ret);
2479 for (i = 0; i < ret; i++) {
2480 struct io_kiocb *req = reqs[i];
2482 io_preinit_req(req, ctx);
2483 io_req_add_to_cache(req, ctx);
2488 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2490 if (unlikely(io_req_cache_empty(ctx)))
2491 return __io_alloc_req_refill(ctx);
2495 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2497 struct io_wq_work_node *node;
2499 node = wq_stack_extract(&ctx->submit_state.free_list);
2500 return container_of(node, struct io_kiocb, comp_list);
2503 static inline void io_put_file(struct file *file)
2509 static inline void io_dismantle_req(struct io_kiocb *req)
2511 unsigned int flags = req->flags;
2513 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2515 if (!(flags & REQ_F_FIXED_FILE))
2516 io_put_file(req->file);
2519 static __cold void io_free_req(struct io_kiocb *req)
2521 struct io_ring_ctx *ctx = req->ctx;
2523 io_req_put_rsrc(req);
2524 io_dismantle_req(req);
2525 io_put_task(req->task, 1);
2527 spin_lock(&ctx->completion_lock);
2528 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2529 ctx->locked_free_nr++;
2530 spin_unlock(&ctx->completion_lock);
2533 static inline void io_remove_next_linked(struct io_kiocb *req)
2535 struct io_kiocb *nxt = req->link;
2537 req->link = nxt->link;
2541 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2542 __must_hold(&req->ctx->completion_lock)
2543 __must_hold(&req->ctx->timeout_lock)
2545 struct io_kiocb *link = req->link;
2547 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2548 struct io_timeout_data *io = link->async_data;
2550 io_remove_next_linked(req);
2551 link->timeout.head = NULL;
2552 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2553 list_del(&link->timeout.list);
2560 static void io_fail_links(struct io_kiocb *req)
2561 __must_hold(&req->ctx->completion_lock)
2563 struct io_kiocb *nxt, *link = req->link;
2564 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2568 long res = -ECANCELED;
2570 if (link->flags & REQ_F_FAIL)
2571 res = link->cqe.res;
2576 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2580 link->flags |= REQ_F_CQE_SKIP;
2582 link->flags &= ~REQ_F_CQE_SKIP;
2583 __io_req_complete_post(link, res, 0);
2588 static bool io_disarm_next(struct io_kiocb *req)
2589 __must_hold(&req->ctx->completion_lock)
2591 struct io_kiocb *link = NULL;
2592 bool posted = false;
2594 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2596 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2597 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2598 io_remove_next_linked(req);
2599 io_req_tw_post_queue(link, -ECANCELED, 0);
2602 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2603 struct io_ring_ctx *ctx = req->ctx;
2605 spin_lock_irq(&ctx->timeout_lock);
2606 link = io_disarm_linked_timeout(req);
2607 spin_unlock_irq(&ctx->timeout_lock);
2610 io_req_tw_post_queue(link, -ECANCELED, 0);
2613 if (unlikely((req->flags & REQ_F_FAIL) &&
2614 !(req->flags & REQ_F_HARDLINK))) {
2615 posted |= (req->link != NULL);
2621 static void __io_req_find_next_prep(struct io_kiocb *req)
2623 struct io_ring_ctx *ctx = req->ctx;
2626 spin_lock(&ctx->completion_lock);
2627 posted = io_disarm_next(req);
2628 io_commit_cqring(ctx);
2629 spin_unlock(&ctx->completion_lock);
2631 io_cqring_ev_posted(ctx);
2634 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2636 struct io_kiocb *nxt;
2639 * If LINK is set, we have dependent requests in this chain. If we
2640 * didn't fail this request, queue the first one up, moving any other
2641 * dependencies to the next request. In case of failure, fail the rest
2644 if (unlikely(req->flags & IO_DISARM_MASK))
2645 __io_req_find_next_prep(req);
2651 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2655 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2656 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2658 io_submit_flush_completions(ctx);
2659 mutex_unlock(&ctx->uring_lock);
2662 percpu_ref_put(&ctx->refs);
2665 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2667 io_commit_cqring(ctx);
2668 spin_unlock(&ctx->completion_lock);
2669 io_cqring_ev_posted(ctx);
2672 static void handle_prev_tw_list(struct io_wq_work_node *node,
2673 struct io_ring_ctx **ctx, bool *uring_locked)
2675 if (*ctx && !*uring_locked)
2676 spin_lock(&(*ctx)->completion_lock);
2679 struct io_wq_work_node *next = node->next;
2680 struct io_kiocb *req = container_of(node, struct io_kiocb,
2683 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2685 if (req->ctx != *ctx) {
2686 if (unlikely(!*uring_locked && *ctx))
2687 ctx_commit_and_unlock(*ctx);
2689 ctx_flush_and_put(*ctx, uring_locked);
2691 /* if not contended, grab and improve batching */
2692 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2693 percpu_ref_get(&(*ctx)->refs);
2694 if (unlikely(!*uring_locked))
2695 spin_lock(&(*ctx)->completion_lock);
2697 if (likely(*uring_locked))
2698 req->io_task_work.func(req, uring_locked);
2700 __io_req_complete_post(req, req->cqe.res,
2701 io_put_kbuf_comp(req));
2705 if (unlikely(!*uring_locked))
2706 ctx_commit_and_unlock(*ctx);
2709 static void handle_tw_list(struct io_wq_work_node *node,
2710 struct io_ring_ctx **ctx, bool *locked)
2713 struct io_wq_work_node *next = node->next;
2714 struct io_kiocb *req = container_of(node, struct io_kiocb,
2717 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2719 if (req->ctx != *ctx) {
2720 ctx_flush_and_put(*ctx, locked);
2722 /* if not contended, grab and improve batching */
2723 *locked = mutex_trylock(&(*ctx)->uring_lock);
2724 percpu_ref_get(&(*ctx)->refs);
2726 req->io_task_work.func(req, locked);
2731 static void tctx_task_work(struct callback_head *cb)
2733 bool uring_locked = false;
2734 struct io_ring_ctx *ctx = NULL;
2735 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2739 struct io_wq_work_node *node1, *node2;
2741 spin_lock_irq(&tctx->task_lock);
2742 node1 = tctx->prio_task_list.first;
2743 node2 = tctx->task_list.first;
2744 INIT_WQ_LIST(&tctx->task_list);
2745 INIT_WQ_LIST(&tctx->prio_task_list);
2746 if (!node2 && !node1)
2747 tctx->task_running = false;
2748 spin_unlock_irq(&tctx->task_lock);
2749 if (!node2 && !node1)
2753 handle_prev_tw_list(node1, &ctx, &uring_locked);
2755 handle_tw_list(node2, &ctx, &uring_locked);
2758 if (data_race(!tctx->task_list.first) &&
2759 data_race(!tctx->prio_task_list.first) && uring_locked)
2760 io_submit_flush_completions(ctx);
2763 ctx_flush_and_put(ctx, &uring_locked);
2765 /* relaxed read is enough as only the task itself sets ->in_idle */
2766 if (unlikely(atomic_read(&tctx->in_idle)))
2767 io_uring_drop_tctx_refs(current);
2770 static void __io_req_task_work_add(struct io_kiocb *req,
2771 struct io_uring_task *tctx,
2772 struct io_wq_work_list *list)
2774 struct io_ring_ctx *ctx = req->ctx;
2775 struct io_wq_work_node *node;
2776 unsigned long flags;
2779 spin_lock_irqsave(&tctx->task_lock, flags);
2780 wq_list_add_tail(&req->io_task_work.node, list);
2781 running = tctx->task_running;
2783 tctx->task_running = true;
2784 spin_unlock_irqrestore(&tctx->task_lock, flags);
2786 /* task_work already pending, we're done */
2790 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2791 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2793 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2796 spin_lock_irqsave(&tctx->task_lock, flags);
2797 tctx->task_running = false;
2798 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2799 spin_unlock_irqrestore(&tctx->task_lock, flags);
2802 req = container_of(node, struct io_kiocb, io_task_work.node);
2804 if (llist_add(&req->io_task_work.fallback_node,
2805 &req->ctx->fallback_llist))
2806 schedule_delayed_work(&req->ctx->fallback_work, 1);
2810 static void io_req_task_work_add(struct io_kiocb *req)
2812 struct io_uring_task *tctx = req->task->io_uring;
2814 __io_req_task_work_add(req, tctx, &tctx->task_list);
2817 static void io_req_task_prio_work_add(struct io_kiocb *req)
2819 struct io_uring_task *tctx = req->task->io_uring;
2821 if (req->ctx->flags & IORING_SETUP_SQPOLL)
2822 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
2824 __io_req_task_work_add(req, tctx, &tctx->task_list);
2827 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2829 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2832 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2835 req->cqe.flags = cflags;
2836 req->io_task_work.func = io_req_tw_post;
2837 io_req_task_work_add(req);
2840 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2842 /* not needed for normal modes, but SQPOLL depends on it */
2843 io_tw_lock(req->ctx, locked);
2844 io_req_complete_failed(req, req->cqe.res);
2847 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2849 io_tw_lock(req->ctx, locked);
2850 /* req->task == current here, checking PF_EXITING is safe */
2851 if (likely(!(req->task->flags & PF_EXITING)))
2854 io_req_complete_failed(req, -EFAULT);
2857 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2860 req->io_task_work.func = io_req_task_cancel;
2861 io_req_task_work_add(req);
2864 static void io_req_task_queue(struct io_kiocb *req)
2866 req->io_task_work.func = io_req_task_submit;
2867 io_req_task_work_add(req);
2870 static void io_req_task_queue_reissue(struct io_kiocb *req)
2872 req->io_task_work.func = io_queue_iowq;
2873 io_req_task_work_add(req);
2876 static void io_queue_next(struct io_kiocb *req)
2878 struct io_kiocb *nxt = io_req_find_next(req);
2881 io_req_task_queue(nxt);
2884 static void io_free_batch_list(struct io_ring_ctx *ctx,
2885 struct io_wq_work_node *node)
2886 __must_hold(&ctx->uring_lock)
2888 struct task_struct *task = NULL;
2892 struct io_kiocb *req = container_of(node, struct io_kiocb,
2895 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2896 if (req->flags & REQ_F_REFCOUNT) {
2897 node = req->comp_list.next;
2898 if (!req_ref_put_and_test(req))
2901 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2902 struct async_poll *apoll = req->apoll;
2904 if (apoll->double_poll)
2905 kfree(apoll->double_poll);
2906 list_add(&apoll->poll.wait.entry,
2908 req->flags &= ~REQ_F_POLLED;
2910 if (req->flags & IO_REQ_LINK_FLAGS)
2912 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2915 if (!(req->flags & REQ_F_FIXED_FILE))
2916 io_put_file(req->file);
2918 io_req_put_rsrc_locked(req, ctx);
2920 if (req->task != task) {
2922 io_put_task(task, task_refs);
2927 node = req->comp_list.next;
2928 io_req_add_to_cache(req, ctx);
2932 io_put_task(task, task_refs);
2935 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2936 __must_hold(&ctx->uring_lock)
2938 struct io_wq_work_node *node, *prev;
2939 struct io_submit_state *state = &ctx->submit_state;
2941 if (state->flush_cqes) {
2942 spin_lock(&ctx->completion_lock);
2943 wq_list_for_each(node, prev, &state->compl_reqs) {
2944 struct io_kiocb *req = container_of(node, struct io_kiocb,
2947 if (!(req->flags & REQ_F_CQE_SKIP))
2948 __io_fill_cqe_req(ctx, req);
2951 io_commit_cqring(ctx);
2952 spin_unlock(&ctx->completion_lock);
2953 io_cqring_ev_posted(ctx);
2954 state->flush_cqes = false;
2957 io_free_batch_list(ctx, state->compl_reqs.first);
2958 INIT_WQ_LIST(&state->compl_reqs);
2962 * Drop reference to request, return next in chain (if there is one) if this
2963 * was the last reference to this request.
2965 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2967 struct io_kiocb *nxt = NULL;
2969 if (req_ref_put_and_test(req)) {
2970 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2971 nxt = io_req_find_next(req);
2977 static inline void io_put_req(struct io_kiocb *req)
2979 if (req_ref_put_and_test(req)) {
2985 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2987 /* See comment at the top of this file */
2989 return __io_cqring_events(ctx);
2992 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2994 struct io_rings *rings = ctx->rings;
2996 /* make sure SQ entry isn't read before tail */
2997 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3000 static inline bool io_run_task_work(void)
3002 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3003 __set_current_state(TASK_RUNNING);
3004 clear_notify_signal();
3005 if (task_work_pending(current))
3013 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3015 struct io_wq_work_node *pos, *start, *prev;
3016 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3017 DEFINE_IO_COMP_BATCH(iob);
3021 * Only spin for completions if we don't have multiple devices hanging
3022 * off our complete list.
3024 if (ctx->poll_multi_queue || force_nonspin)
3025 poll_flags |= BLK_POLL_ONESHOT;
3027 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3028 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3029 struct io_rw *rw = io_kiocb_to_cmd(req);
3033 * Move completed and retryable entries to our local lists.
3034 * If we find a request that requires polling, break out
3035 * and complete those lists first, if we have entries there.
3037 if (READ_ONCE(req->iopoll_completed))
3040 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
3041 if (unlikely(ret < 0))
3044 poll_flags |= BLK_POLL_ONESHOT;
3046 /* iopoll may have completed current req */
3047 if (!rq_list_empty(iob.req_list) ||
3048 READ_ONCE(req->iopoll_completed))
3052 if (!rq_list_empty(iob.req_list))
3058 wq_list_for_each_resume(pos, prev) {
3059 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3061 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3062 if (!smp_load_acquire(&req->iopoll_completed))
3065 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3068 req->cqe.flags = io_put_kbuf(req, 0);
3069 __io_fill_cqe_req(req->ctx, req);
3072 if (unlikely(!nr_events))
3075 io_commit_cqring(ctx);
3076 io_cqring_ev_posted_iopoll(ctx);
3077 pos = start ? start->next : ctx->iopoll_list.first;
3078 wq_list_cut(&ctx->iopoll_list, prev, start);
3079 io_free_batch_list(ctx, pos);
3084 * We can't just wait for polled events to come to us, we have to actively
3085 * find and complete them.
3087 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3089 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3092 mutex_lock(&ctx->uring_lock);
3093 while (!wq_list_empty(&ctx->iopoll_list)) {
3094 /* let it sleep and repeat later if can't complete a request */
3095 if (io_do_iopoll(ctx, true) == 0)
3098 * Ensure we allow local-to-the-cpu processing to take place,
3099 * in this case we need to ensure that we reap all events.
3100 * Also let task_work, etc. to progress by releasing the mutex
3102 if (need_resched()) {
3103 mutex_unlock(&ctx->uring_lock);
3105 mutex_lock(&ctx->uring_lock);
3108 mutex_unlock(&ctx->uring_lock);
3111 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3113 unsigned int nr_events = 0;
3115 unsigned long check_cq;
3118 * Don't enter poll loop if we already have events pending.
3119 * If we do, we can potentially be spinning for commands that
3120 * already triggered a CQE (eg in error).
3122 check_cq = READ_ONCE(ctx->check_cq);
3123 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3124 __io_cqring_overflow_flush(ctx, false);
3125 if (io_cqring_events(ctx))
3129 * Similarly do not spin if we have not informed the user of any
3132 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3137 * If a submit got punted to a workqueue, we can have the
3138 * application entering polling for a command before it gets
3139 * issued. That app will hold the uring_lock for the duration
3140 * of the poll right here, so we need to take a breather every
3141 * now and then to ensure that the issue has a chance to add
3142 * the poll to the issued list. Otherwise we can spin here
3143 * forever, while the workqueue is stuck trying to acquire the
3146 if (wq_list_empty(&ctx->iopoll_list)) {
3147 u32 tail = ctx->cached_cq_tail;
3149 mutex_unlock(&ctx->uring_lock);
3151 mutex_lock(&ctx->uring_lock);
3153 /* some requests don't go through iopoll_list */
3154 if (tail != ctx->cached_cq_tail ||
3155 wq_list_empty(&ctx->iopoll_list))
3158 ret = io_do_iopoll(ctx, !min);
3163 } while (nr_events < min && !need_resched());
3168 static void kiocb_end_write(struct io_kiocb *req)
3171 * Tell lockdep we inherited freeze protection from submission
3174 if (req->flags & REQ_F_ISREG) {
3175 struct super_block *sb = file_inode(req->file)->i_sb;
3177 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3183 static bool io_resubmit_prep(struct io_kiocb *req)
3185 struct io_async_rw *io = req->async_data;
3187 if (!req_has_async_data(req))
3188 return !io_req_prep_async(req);
3189 iov_iter_restore(&io->s.iter, &io->s.iter_state);
3193 static bool io_rw_should_reissue(struct io_kiocb *req)
3195 umode_t mode = file_inode(req->file)->i_mode;
3196 struct io_ring_ctx *ctx = req->ctx;
3198 if (!S_ISBLK(mode) && !S_ISREG(mode))
3200 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3201 !(ctx->flags & IORING_SETUP_IOPOLL)))
3204 * If ref is dying, we might be running poll reap from the exit work.
3205 * Don't attempt to reissue from that path, just let it fail with
3208 if (percpu_ref_is_dying(&ctx->refs))
3211 * Play it safe and assume not safe to re-import and reissue if we're
3212 * not in the original thread group (or in task context).
3214 if (!same_thread_group(req->task, current) || !in_task())
3219 static bool io_resubmit_prep(struct io_kiocb *req)
3223 static bool io_rw_should_reissue(struct io_kiocb *req)
3229 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3231 struct io_rw *rw = io_kiocb_to_cmd(req);
3233 if (rw->kiocb.ki_flags & IOCB_WRITE) {
3234 kiocb_end_write(req);
3235 fsnotify_modify(req->file);
3237 fsnotify_access(req->file);
3239 if (unlikely(res != req->cqe.res)) {
3240 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3241 io_rw_should_reissue(req)) {
3242 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3251 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3253 int res = req->cqe.res;
3256 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3257 io_req_add_compl_list(req);
3259 io_req_complete_post(req, res,
3260 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3264 static void __io_complete_rw(struct io_kiocb *req, long res,
3265 unsigned int issue_flags)
3267 if (__io_complete_rw_common(req, res))
3269 __io_req_complete(req, issue_flags, req->cqe.res,
3270 io_put_kbuf(req, issue_flags));
3273 static void io_complete_rw(struct kiocb *kiocb, long res)
3275 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
3276 struct io_kiocb *req = cmd_to_io_kiocb(rw);
3278 if (__io_complete_rw_common(req, res))
3281 req->io_task_work.func = io_req_task_complete;
3282 io_req_task_prio_work_add(req);
3285 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3287 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
3288 struct io_kiocb *req = cmd_to_io_kiocb(rw);
3290 if (kiocb->ki_flags & IOCB_WRITE)
3291 kiocb_end_write(req);
3292 if (unlikely(res != req->cqe.res)) {
3293 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3294 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3300 /* order with io_iopoll_complete() checking ->iopoll_completed */
3301 smp_store_release(&req->iopoll_completed, 1);
3305 * After the iocb has been issued, it's safe to be found on the poll list.
3306 * Adding the kiocb to the list AFTER submission ensures that we don't
3307 * find it from a io_do_iopoll() thread before the issuer is done
3308 * accessing the kiocb cookie.
3310 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3312 struct io_ring_ctx *ctx = req->ctx;
3313 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3315 /* workqueue context doesn't hold uring_lock, grab it now */
3316 if (unlikely(needs_lock))
3317 mutex_lock(&ctx->uring_lock);
3320 * Track whether we have multiple files in our lists. This will impact
3321 * how we do polling eventually, not spinning if we're on potentially
3322 * different devices.
3324 if (wq_list_empty(&ctx->iopoll_list)) {
3325 ctx->poll_multi_queue = false;
3326 } else if (!ctx->poll_multi_queue) {
3327 struct io_kiocb *list_req;
3329 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3331 if (list_req->file != req->file)
3332 ctx->poll_multi_queue = true;
3336 * For fast devices, IO may have already completed. If it has, add
3337 * it to the front so we find it first.
3339 if (READ_ONCE(req->iopoll_completed))
3340 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3342 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3344 if (unlikely(needs_lock)) {
3346 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3347 * in sq thread task context or in io worker task context. If
3348 * current task context is sq thread, we don't need to check
3349 * whether should wake up sq thread.
3351 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3352 wq_has_sleeper(&ctx->sq_data->wait))
3353 wake_up(&ctx->sq_data->wait);
3355 mutex_unlock(&ctx->uring_lock);
3359 static bool io_bdev_nowait(struct block_device *bdev)
3361 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3365 * If we tracked the file through the SCM inflight mechanism, we could support
3366 * any file. For now, just ensure that anything potentially problematic is done
3369 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3371 if (S_ISBLK(mode)) {
3372 if (IS_ENABLED(CONFIG_BLOCK) &&
3373 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3379 if (S_ISREG(mode)) {
3380 if (IS_ENABLED(CONFIG_BLOCK) &&
3381 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3382 file->f_op != &io_uring_fops)
3387 /* any ->read/write should understand O_NONBLOCK */
3388 if (file->f_flags & O_NONBLOCK)
3390 return file->f_mode & FMODE_NOWAIT;
3394 * If we tracked the file through the SCM inflight mechanism, we could support
3395 * any file. For now, just ensure that anything potentially problematic is done
3398 static unsigned int io_file_get_flags(struct file *file)
3400 umode_t mode = file_inode(file)->i_mode;
3401 unsigned int res = 0;
3405 if (__io_file_supports_nowait(file, mode))
3407 if (io_file_need_scm(file))
3412 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3414 return req->flags & REQ_F_SUPPORT_NOWAIT;
3417 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3419 struct io_rw *rw = io_kiocb_to_cmd(req);
3423 rw->kiocb.ki_pos = READ_ONCE(sqe->off);
3424 /* used for fixed read/write too - just read unconditionally */
3425 req->buf_index = READ_ONCE(sqe->buf_index);
3427 if (req->opcode == IORING_OP_READ_FIXED ||
3428 req->opcode == IORING_OP_WRITE_FIXED) {
3429 struct io_ring_ctx *ctx = req->ctx;
3432 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3434 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3435 req->imu = ctx->user_bufs[index];
3436 io_req_set_rsrc_node(req, ctx, 0);
3439 ioprio = READ_ONCE(sqe->ioprio);
3441 ret = ioprio_check_cap(ioprio);
3445 rw->kiocb.ki_ioprio = ioprio;
3447 rw->kiocb.ki_ioprio = get_current_ioprio();
3450 rw->addr = READ_ONCE(sqe->addr);
3451 rw->len = READ_ONCE(sqe->len);
3452 rw->flags = READ_ONCE(sqe->rw_flags);
3456 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3462 case -ERESTARTNOINTR:
3463 case -ERESTARTNOHAND:
3464 case -ERESTART_RESTARTBLOCK:
3466 * We can't just restart the syscall, since previously
3467 * submitted sqes may already be in progress. Just fail this
3473 kiocb->ki_complete(kiocb, ret);
3477 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3479 struct io_rw *rw = io_kiocb_to_cmd(req);
3481 if (rw->kiocb.ki_pos != -1)
3482 return &rw->kiocb.ki_pos;
3484 if (!(req->file->f_mode & FMODE_STREAM)) {
3485 req->flags |= REQ_F_CUR_POS;
3486 rw->kiocb.ki_pos = req->file->f_pos;
3487 return &rw->kiocb.ki_pos;
3490 rw->kiocb.ki_pos = 0;
3494 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3495 unsigned int issue_flags)
3497 struct io_async_rw *io = req->async_data;
3498 struct io_rw *rw = io_kiocb_to_cmd(req);
3500 /* add previously done IO, if any */
3501 if (req_has_async_data(req) && io->bytes_done > 0) {
3503 ret = io->bytes_done;
3505 ret += io->bytes_done;
3508 if (req->flags & REQ_F_CUR_POS)
3509 req->file->f_pos = rw->kiocb.ki_pos;
3510 if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
3511 __io_complete_rw(req, ret, issue_flags);
3513 io_rw_done(&rw->kiocb, ret);
3515 if (req->flags & REQ_F_REISSUE) {
3516 req->flags &= ~REQ_F_REISSUE;
3517 if (io_resubmit_prep(req))
3518 io_req_task_queue_reissue(req);
3520 io_req_task_queue_fail(req, ret);
3524 static int __io_import_fixed(struct io_kiocb *req, int ddir,
3525 struct iov_iter *iter, struct io_mapped_ubuf *imu)
3527 struct io_rw *rw = io_kiocb_to_cmd(req);
3528 size_t len = rw->len;
3529 u64 buf_end, buf_addr = rw->addr;
3532 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3534 /* not inside the mapped region */
3535 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3539 * May not be a start of buffer, set size appropriately
3540 * and advance us to the beginning.
3542 offset = buf_addr - imu->ubuf;
3543 iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
3547 * Don't use iov_iter_advance() here, as it's really slow for
3548 * using the latter parts of a big fixed buffer - it iterates
3549 * over each segment manually. We can cheat a bit here, because
3552 * 1) it's a BVEC iter, we set it up
3553 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3554 * first and last bvec
3556 * So just find our index, and adjust the iterator afterwards.
3557 * If the offset is within the first bvec (or the whole first
3558 * bvec, just use iov_iter_advance(). This makes it easier
3559 * since we can just skip the first segment, which may not
3560 * be PAGE_SIZE aligned.
3562 const struct bio_vec *bvec = imu->bvec;
3564 if (offset <= bvec->bv_len) {
3565 iov_iter_advance(iter, offset);
3567 unsigned long seg_skip;
3569 /* skip first vec */
3570 offset -= bvec->bv_len;
3571 seg_skip = 1 + (offset >> PAGE_SHIFT);
3573 iter->bvec = bvec + seg_skip;
3574 iter->nr_segs -= seg_skip;
3575 iter->count -= bvec->bv_len + offset;
3576 iter->iov_offset = offset & ~PAGE_MASK;
3583 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3584 unsigned int issue_flags)
3586 if (WARN_ON_ONCE(!req->imu))
3588 return __io_import_fixed(req, rw, iter, req->imu);
3591 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3592 struct io_buffer_list *bl, unsigned int bgid)
3595 if (bgid < BGID_ARRAY)
3598 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3601 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3602 struct io_buffer_list *bl)
3604 if (!list_empty(&bl->buf_list)) {
3605 struct io_buffer *kbuf;
3607 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3608 list_del(&kbuf->list);
3609 if (*len > kbuf->len)
3611 req->flags |= REQ_F_BUFFER_SELECTED;
3613 req->buf_index = kbuf->bid;
3614 return u64_to_user_ptr(kbuf->addr);
3619 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3620 struct io_buffer_list *bl,
3621 unsigned int issue_flags)
3623 struct io_uring_buf_ring *br = bl->buf_ring;
3624 struct io_uring_buf *buf;
3625 __u16 head = bl->head;
3627 if (unlikely(smp_load_acquire(&br->tail) == head))
3631 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3632 buf = &br->bufs[head];
3634 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3635 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3636 buf = page_address(bl->buf_pages[index]);
3639 if (*len > buf->len)
3641 req->flags |= REQ_F_BUFFER_RING;
3643 req->buf_index = buf->bid;
3645 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3647 * If we came in unlocked, we have no choice but to consume the
3648 * buffer here. This does mean it'll be pinned until the IO
3649 * completes. But coming in unlocked means we're in io-wq
3650 * context, hence there should be no further retry. For the
3651 * locked case, the caller must ensure to call the commit when
3652 * the transfer completes (or if we get -EAGAIN and must poll
3655 req->buf_list = NULL;
3658 return u64_to_user_ptr(buf->addr);
3661 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3662 unsigned int issue_flags)
3664 struct io_ring_ctx *ctx = req->ctx;
3665 struct io_buffer_list *bl;
3666 void __user *ret = NULL;
3668 io_ring_submit_lock(req->ctx, issue_flags);
3670 bl = io_buffer_get_list(ctx, req->buf_index);
3672 if (bl->buf_nr_pages)
3673 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3675 ret = io_provided_buffer_select(req, len, bl);
3677 io_ring_submit_unlock(req->ctx, issue_flags);
3681 #ifdef CONFIG_COMPAT
3682 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3683 unsigned int issue_flags)
3685 struct io_rw *rw = io_kiocb_to_cmd(req);
3686 struct compat_iovec __user *uiov;
3687 compat_ssize_t clen;
3691 uiov = u64_to_user_ptr(rw->addr);
3692 if (!access_ok(uiov, sizeof(*uiov)))
3694 if (__get_user(clen, &uiov->iov_len))
3700 buf = io_buffer_select(req, &len, issue_flags);
3703 rw->addr = (unsigned long) buf;
3704 iov[0].iov_base = buf;
3705 rw->len = iov[0].iov_len = (compat_size_t) len;
3710 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3711 unsigned int issue_flags)
3713 struct io_rw *rw = io_kiocb_to_cmd(req);
3714 struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
3718 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3721 len = iov[0].iov_len;
3724 buf = io_buffer_select(req, &len, issue_flags);
3727 rw->addr = (unsigned long) buf;
3728 iov[0].iov_base = buf;
3729 rw->len = iov[0].iov_len = len;
3733 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3734 unsigned int issue_flags)
3736 struct io_rw *rw = io_kiocb_to_cmd(req);
3738 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3739 iov[0].iov_base = u64_to_user_ptr(rw->addr);
3740 iov[0].iov_len = rw->len;
3746 #ifdef CONFIG_COMPAT
3747 if (req->ctx->compat)
3748 return io_compat_import(req, iov, issue_flags);
3751 return __io_iov_buffer_select(req, iov, issue_flags);
3754 static inline bool io_do_buffer_select(struct io_kiocb *req)
3756 if (!(req->flags & REQ_F_BUFFER_SELECT))
3758 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3761 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
3762 struct io_rw_state *s,
3763 unsigned int issue_flags)
3765 struct io_rw *rw = io_kiocb_to_cmd(req);
3766 struct iov_iter *iter = &s->iter;
3767 u8 opcode = req->opcode;
3768 struct iovec *iovec;
3773 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3774 ret = io_import_fixed(req, ddir, iter, issue_flags);
3776 return ERR_PTR(ret);
3780 buf = u64_to_user_ptr(rw->addr);
3783 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3784 if (io_do_buffer_select(req)) {
3785 buf = io_buffer_select(req, &sqe_len, issue_flags);
3787 return ERR_PTR(-ENOBUFS);
3788 rw->addr = (unsigned long) buf;
3792 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
3794 return ERR_PTR(ret);
3798 iovec = s->fast_iov;
3799 if (req->flags & REQ_F_BUFFER_SELECT) {
3800 ret = io_iov_buffer_select(req, iovec, issue_flags);
3802 return ERR_PTR(ret);
3803 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
3807 ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3809 if (unlikely(ret < 0))
3810 return ERR_PTR(ret);
3814 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3815 struct iovec **iovec, struct io_rw_state *s,
3816 unsigned int issue_flags)
3818 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3819 if (unlikely(IS_ERR(*iovec)))
3820 return PTR_ERR(*iovec);
3822 iov_iter_save_state(&s->iter, &s->iter_state);
3826 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3828 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3832 * For files that don't have ->read_iter() and ->write_iter(), handle them
3833 * by looping over ->read() or ->write() manually.
3835 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
3837 struct kiocb *kiocb = &rw->kiocb;
3838 struct file *file = kiocb->ki_filp;
3843 * Don't support polled IO through this interface, and we can't
3844 * support non-blocking either. For the latter, this just causes
3845 * the kiocb to be handled from an async context.
3847 if (kiocb->ki_flags & IOCB_HIPRI)
3849 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3850 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3853 ppos = io_kiocb_ppos(kiocb);
3855 while (iov_iter_count(iter)) {
3859 if (!iov_iter_is_bvec(iter)) {
3860 iovec = iov_iter_iovec(iter);
3862 iovec.iov_base = u64_to_user_ptr(rw->addr);
3863 iovec.iov_len = rw->len;
3867 nr = file->f_op->read(file, iovec.iov_base,
3868 iovec.iov_len, ppos);
3870 nr = file->f_op->write(file, iovec.iov_base,
3871 iovec.iov_len, ppos);
3880 if (!iov_iter_is_bvec(iter)) {
3881 iov_iter_advance(iter, nr);
3888 if (nr != iovec.iov_len)
3895 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3896 const struct iovec *fast_iov, struct iov_iter *iter)
3898 struct io_async_rw *io = req->async_data;
3900 memcpy(&io->s.iter, iter, sizeof(*iter));
3901 io->free_iovec = iovec;
3903 /* can only be fixed buffers, no need to do anything */
3904 if (iov_iter_is_bvec(iter))
3907 unsigned iov_off = 0;
3909 io->s.iter.iov = io->s.fast_iov;
3910 if (iter->iov != fast_iov) {
3911 iov_off = iter->iov - fast_iov;
3912 io->s.iter.iov += iov_off;
3914 if (io->s.fast_iov != fast_iov)
3915 memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
3916 sizeof(struct iovec) * iter->nr_segs);
3918 req->flags |= REQ_F_NEED_CLEANUP;
3922 static inline bool io_alloc_async_data(struct io_kiocb *req)
3924 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3925 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3926 if (req->async_data) {
3927 req->flags |= REQ_F_ASYNC_DATA;
3933 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3934 struct io_rw_state *s, bool force)
3936 if (!force && !io_op_defs[req->opcode].prep_async)
3938 if (!req_has_async_data(req)) {
3939 struct io_async_rw *iorw;
3941 if (io_alloc_async_data(req)) {
3946 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3947 iorw = req->async_data;
3948 /* we've copied and mapped the iter, ensure state is saved */
3949 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3954 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3956 struct io_async_rw *iorw = req->async_data;
3960 /* submission path, ->uring_lock should already be taken */
3961 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3962 if (unlikely(ret < 0))
3965 iorw->bytes_done = 0;
3966 iorw->free_iovec = iov;
3968 req->flags |= REQ_F_NEED_CLEANUP;
3972 static int io_readv_prep_async(struct io_kiocb *req)
3974 return io_rw_prep_async(req, READ);
3977 static int io_writev_prep_async(struct io_kiocb *req)
3979 return io_rw_prep_async(req, WRITE);
3983 * This is our waitqueue callback handler, registered through __folio_lock_async()
3984 * when we initially tried to do the IO with the iocb armed our waitqueue.
3985 * This gets called when the page is unlocked, and we generally expect that to
3986 * happen when the page IO is completed and the page is now uptodate. This will
3987 * queue a task_work based retry of the operation, attempting to copy the data
3988 * again. If the latter fails because the page was NOT uptodate, then we will
3989 * do a thread based blocking retry of the operation. That's the unexpected
3992 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3993 int sync, void *arg)
3995 struct wait_page_queue *wpq;
3996 struct io_kiocb *req = wait->private;
3997 struct io_rw *rw = io_kiocb_to_cmd(req);
3998 struct wait_page_key *key = arg;
4000 wpq = container_of(wait, struct wait_page_queue, wait);
4002 if (!wake_page_match(wpq, key))
4005 rw->kiocb.ki_flags &= ~IOCB_WAITQ;
4006 list_del_init(&wait->entry);
4007 io_req_task_queue(req);
4012 * This controls whether a given IO request should be armed for async page
4013 * based retry. If we return false here, the request is handed to the async
4014 * worker threads for retry. If we're doing buffered reads on a regular file,
4015 * we prepare a private wait_page_queue entry and retry the operation. This
4016 * will either succeed because the page is now uptodate and unlocked, or it
4017 * will register a callback when the page is unlocked at IO completion. Through
4018 * that callback, io_uring uses task_work to setup a retry of the operation.
4019 * That retry will attempt the buffered read again. The retry will generally
4020 * succeed, or in rare cases where it fails, we then fall back to using the
4021 * async worker threads for a blocking retry.
4023 static bool io_rw_should_retry(struct io_kiocb *req)
4025 struct io_async_rw *io = req->async_data;
4026 struct wait_page_queue *wait = &io->wpq;
4027 struct io_rw *rw = io_kiocb_to_cmd(req);
4028 struct kiocb *kiocb = &rw->kiocb;
4030 /* never retry for NOWAIT, we just complete with -EAGAIN */
4031 if (req->flags & REQ_F_NOWAIT)
4034 /* Only for buffered IO */
4035 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4039 * just use poll if we can, and don't attempt if the fs doesn't
4040 * support callback based unlocks
4042 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4045 wait->wait.func = io_async_buf_func;
4046 wait->wait.private = req;
4047 wait->wait.flags = 0;
4048 INIT_LIST_HEAD(&wait->wait.entry);
4049 kiocb->ki_flags |= IOCB_WAITQ;
4050 kiocb->ki_flags &= ~IOCB_NOWAIT;
4051 kiocb->ki_waitq = wait;
4055 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
4057 struct file *file = rw->kiocb.ki_filp;
4059 if (likely(file->f_op->read_iter))
4060 return call_read_iter(file, &rw->kiocb, iter);
4061 else if (file->f_op->read)
4062 return loop_rw_iter(READ, rw, iter);
4067 static bool need_read_all(struct io_kiocb *req)
4069 return req->flags & REQ_F_ISREG ||
4070 S_ISBLK(file_inode(req->file)->i_mode);
4073 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4075 struct io_rw *rw = io_kiocb_to_cmd(req);
4076 struct kiocb *kiocb = &rw->kiocb;
4077 struct io_ring_ctx *ctx = req->ctx;
4078 struct file *file = req->file;
4081 if (unlikely(!file || !(file->f_mode & mode)))
4084 if (!io_req_ffs_set(req))
4085 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4087 kiocb->ki_flags = iocb_flags(file);
4088 ret = kiocb_set_rw_flags(kiocb, rw->flags);
4093 * If the file is marked O_NONBLOCK, still allow retry for it if it
4094 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4095 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4097 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4098 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4099 req->flags |= REQ_F_NOWAIT;
4101 if (ctx->flags & IORING_SETUP_IOPOLL) {
4102 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4105 kiocb->private = NULL;
4106 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4107 kiocb->ki_complete = io_complete_rw_iopoll;
4108 req->iopoll_completed = 0;
4110 if (kiocb->ki_flags & IOCB_HIPRI)
4112 kiocb->ki_complete = io_complete_rw;
4118 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4120 struct io_rw *rw = io_kiocb_to_cmd(req);
4121 struct io_rw_state __s, *s = &__s;
4122 struct iovec *iovec;
4123 struct kiocb *kiocb = &rw->kiocb;
4124 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4125 struct io_async_rw *io;
4129 if (!req_has_async_data(req)) {
4130 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4131 if (unlikely(ret < 0))
4134 io = req->async_data;
4138 * Safe and required to re-import if we're using provided
4139 * buffers, as we dropped the selected one before retry.
4141 if (io_do_buffer_select(req)) {
4142 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4143 if (unlikely(ret < 0))
4148 * We come here from an earlier attempt, restore our state to
4149 * match in case it doesn't. It's cheap enough that we don't
4150 * need to make this conditional.
4152 iov_iter_restore(&s->iter, &s->iter_state);
4155 ret = io_rw_init_file(req, FMODE_READ);
4156 if (unlikely(ret)) {
4160 req->cqe.res = iov_iter_count(&s->iter);
4162 if (force_nonblock) {
4163 /* If the file doesn't support async, just async punt */
4164 if (unlikely(!io_file_supports_nowait(req))) {
4165 ret = io_setup_async_rw(req, iovec, s, true);
4166 return ret ?: -EAGAIN;
4168 kiocb->ki_flags |= IOCB_NOWAIT;
4170 /* Ensure we clear previously set non-block flag */
4171 kiocb->ki_flags &= ~IOCB_NOWAIT;
4174 ppos = io_kiocb_update_pos(req);
4176 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4177 if (unlikely(ret)) {
4182 ret = io_iter_do_read(rw, &s->iter);
4184 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4185 req->flags &= ~REQ_F_REISSUE;
4186 /* if we can poll, just do that */
4187 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4189 /* IOPOLL retry should happen for io-wq threads */
4190 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4192 /* no retry on NONBLOCK nor RWF_NOWAIT */
4193 if (req->flags & REQ_F_NOWAIT)
4196 } else if (ret == -EIOCBQUEUED) {
4198 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4199 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4200 /* read all, failed, already did sync or don't want to retry */
4205 * Don't depend on the iter state matching what was consumed, or being
4206 * untouched in case of error. Restore it and we'll advance it
4207 * manually if we need to.
4209 iov_iter_restore(&s->iter, &s->iter_state);
4211 ret2 = io_setup_async_rw(req, iovec, s, true);
4216 io = req->async_data;
4219 * Now use our persistent iterator and state, if we aren't already.
4220 * We've restored and mapped the iter to match.
4225 * We end up here because of a partial read, either from
4226 * above or inside this loop. Advance the iter by the bytes
4227 * that were consumed.
4229 iov_iter_advance(&s->iter, ret);
4230 if (!iov_iter_count(&s->iter))
4232 io->bytes_done += ret;
4233 iov_iter_save_state(&s->iter, &s->iter_state);
4235 /* if we can retry, do so with the callbacks armed */
4236 if (!io_rw_should_retry(req)) {
4237 kiocb->ki_flags &= ~IOCB_WAITQ;
4242 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4243 * we get -EIOCBQUEUED, then we'll get a notification when the
4244 * desired page gets unlocked. We can also get a partial read
4245 * here, and if we do, then just retry at the new offset.
4247 ret = io_iter_do_read(rw, &s->iter);
4248 if (ret == -EIOCBQUEUED)
4250 /* we got some bytes, but not all. retry. */
4251 kiocb->ki_flags &= ~IOCB_WAITQ;
4252 iov_iter_restore(&s->iter, &s->iter_state);
4255 kiocb_done(req, ret, issue_flags);
4257 /* it's faster to check here then delegate to kfree */
4263 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4265 struct io_rw *rw = io_kiocb_to_cmd(req);
4266 struct io_rw_state __s, *s = &__s;
4267 struct iovec *iovec;
4268 struct kiocb *kiocb = &rw->kiocb;
4269 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4273 if (!req_has_async_data(req)) {
4274 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4275 if (unlikely(ret < 0))
4278 struct io_async_rw *io = req->async_data;
4281 iov_iter_restore(&s->iter, &s->iter_state);
4284 ret = io_rw_init_file(req, FMODE_WRITE);
4285 if (unlikely(ret)) {
4289 req->cqe.res = iov_iter_count(&s->iter);
4291 if (force_nonblock) {
4292 /* If the file doesn't support async, just async punt */
4293 if (unlikely(!io_file_supports_nowait(req)))
4296 /* file path doesn't support NOWAIT for non-direct_IO */
4297 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4298 (req->flags & REQ_F_ISREG))
4301 kiocb->ki_flags |= IOCB_NOWAIT;
4303 /* Ensure we clear previously set non-block flag */
4304 kiocb->ki_flags &= ~IOCB_NOWAIT;
4307 ppos = io_kiocb_update_pos(req);
4309 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4314 * Open-code file_start_write here to grab freeze protection,
4315 * which will be released by another thread in
4316 * io_complete_rw(). Fool lockdep by telling it the lock got
4317 * released so that it doesn't complain about the held lock when
4318 * we return to userspace.
4320 if (req->flags & REQ_F_ISREG) {
4321 sb_start_write(file_inode(req->file)->i_sb);
4322 __sb_writers_release(file_inode(req->file)->i_sb,
4325 kiocb->ki_flags |= IOCB_WRITE;
4327 if (likely(req->file->f_op->write_iter))
4328 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4329 else if (req->file->f_op->write)
4330 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
4334 if (req->flags & REQ_F_REISSUE) {
4335 req->flags &= ~REQ_F_REISSUE;
4340 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4341 * retry them without IOCB_NOWAIT.
4343 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4345 /* no retry on NONBLOCK nor RWF_NOWAIT */
4346 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4348 if (!force_nonblock || ret2 != -EAGAIN) {
4349 /* IOPOLL retry should happen for io-wq threads */
4350 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4353 kiocb_done(req, ret2, issue_flags);
4356 iov_iter_restore(&s->iter, &s->iter_state);
4357 ret = io_setup_async_rw(req, iovec, s, false);
4358 return ret ?: -EAGAIN;
4361 /* it's reportedly faster than delegating the null check to kfree() */
4367 static int io_renameat_prep(struct io_kiocb *req,
4368 const struct io_uring_sqe *sqe)
4370 struct io_rename *ren = &req->rename;
4371 const char __user *oldf, *newf;
4373 if (sqe->buf_index || sqe->splice_fd_in)
4375 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4378 ren->old_dfd = READ_ONCE(sqe->fd);
4379 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4380 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4381 ren->new_dfd = READ_ONCE(sqe->len);
4382 ren->flags = READ_ONCE(sqe->rename_flags);
4384 ren->oldpath = getname(oldf);
4385 if (IS_ERR(ren->oldpath))
4386 return PTR_ERR(ren->oldpath);
4388 ren->newpath = getname(newf);
4389 if (IS_ERR(ren->newpath)) {
4390 putname(ren->oldpath);
4391 return PTR_ERR(ren->newpath);
4394 req->flags |= REQ_F_NEED_CLEANUP;
4398 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4400 struct io_rename *ren = &req->rename;
4403 if (issue_flags & IO_URING_F_NONBLOCK)
4406 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4407 ren->newpath, ren->flags);
4409 req->flags &= ~REQ_F_NEED_CLEANUP;
4410 io_req_complete(req, ret);
4414 static inline void __io_xattr_finish(struct io_kiocb *req)
4416 struct io_xattr *ix = &req->xattr;
4419 putname(ix->filename);
4421 kfree(ix->ctx.kname);
4422 kvfree(ix->ctx.kvalue);
4425 static void io_xattr_finish(struct io_kiocb *req, int ret)
4427 req->flags &= ~REQ_F_NEED_CLEANUP;
4429 __io_xattr_finish(req);
4430 io_req_complete(req, ret);
4433 static int __io_getxattr_prep(struct io_kiocb *req,
4434 const struct io_uring_sqe *sqe)
4436 struct io_xattr *ix = &req->xattr;
4437 const char __user *name;
4440 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4443 ix->filename = NULL;
4444 ix->ctx.kvalue = NULL;
4445 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4446 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4447 ix->ctx.size = READ_ONCE(sqe->len);
4448 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4453 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4457 ret = strncpy_from_user(ix->ctx.kname->name, name,
4458 sizeof(ix->ctx.kname->name));
4459 if (!ret || ret == sizeof(ix->ctx.kname->name))
4462 kfree(ix->ctx.kname);
4466 req->flags |= REQ_F_NEED_CLEANUP;
4470 static int io_fgetxattr_prep(struct io_kiocb *req,
4471 const struct io_uring_sqe *sqe)
4473 return __io_getxattr_prep(req, sqe);
4476 static int io_getxattr_prep(struct io_kiocb *req,
4477 const struct io_uring_sqe *sqe)
4479 struct io_xattr *ix = &req->xattr;
4480 const char __user *path;
4483 ret = __io_getxattr_prep(req, sqe);
4487 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4489 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4490 if (IS_ERR(ix->filename)) {
4491 ret = PTR_ERR(ix->filename);
4492 ix->filename = NULL;
4498 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4500 struct io_xattr *ix = &req->xattr;
4503 if (issue_flags & IO_URING_F_NONBLOCK)
4506 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4507 req->file->f_path.dentry,
4510 io_xattr_finish(req, ret);
4514 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4516 struct io_xattr *ix = &req->xattr;
4517 unsigned int lookup_flags = LOOKUP_FOLLOW;
4521 if (issue_flags & IO_URING_F_NONBLOCK)
4525 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4527 ret = do_getxattr(mnt_user_ns(path.mnt),
4532 if (retry_estale(ret, lookup_flags)) {
4533 lookup_flags |= LOOKUP_REVAL;
4538 io_xattr_finish(req, ret);
4542 static int __io_setxattr_prep(struct io_kiocb *req,
4543 const struct io_uring_sqe *sqe)
4545 struct io_xattr *ix = &req->xattr;
4546 const char __user *name;
4549 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4552 ix->filename = NULL;
4553 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4554 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4555 ix->ctx.kvalue = NULL;
4556 ix->ctx.size = READ_ONCE(sqe->len);
4557 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4559 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4563 ret = setxattr_copy(name, &ix->ctx);
4565 kfree(ix->ctx.kname);
4569 req->flags |= REQ_F_NEED_CLEANUP;
4573 static int io_setxattr_prep(struct io_kiocb *req,
4574 const struct io_uring_sqe *sqe)
4576 struct io_xattr *ix = &req->xattr;
4577 const char __user *path;
4580 ret = __io_setxattr_prep(req, sqe);
4584 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4586 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4587 if (IS_ERR(ix->filename)) {
4588 ret = PTR_ERR(ix->filename);
4589 ix->filename = NULL;
4595 static int io_fsetxattr_prep(struct io_kiocb *req,
4596 const struct io_uring_sqe *sqe)
4598 return __io_setxattr_prep(req, sqe);
4601 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4604 struct io_xattr *ix = &req->xattr;
4607 ret = mnt_want_write(path->mnt);
4609 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4610 mnt_drop_write(path->mnt);
4616 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4620 if (issue_flags & IO_URING_F_NONBLOCK)
4623 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4624 io_xattr_finish(req, ret);
4629 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4631 struct io_xattr *ix = &req->xattr;
4632 unsigned int lookup_flags = LOOKUP_FOLLOW;
4636 if (issue_flags & IO_URING_F_NONBLOCK)
4640 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4642 ret = __io_setxattr(req, issue_flags, &path);
4644 if (retry_estale(ret, lookup_flags)) {
4645 lookup_flags |= LOOKUP_REVAL;
4650 io_xattr_finish(req, ret);
4654 static int io_unlinkat_prep(struct io_kiocb *req,
4655 const struct io_uring_sqe *sqe)
4657 struct io_unlink *un = &req->unlink;
4658 const char __user *fname;
4660 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4662 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4665 un->dfd = READ_ONCE(sqe->fd);
4667 un->flags = READ_ONCE(sqe->unlink_flags);
4668 if (un->flags & ~AT_REMOVEDIR)
4671 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4672 un->filename = getname(fname);
4673 if (IS_ERR(un->filename))
4674 return PTR_ERR(un->filename);
4676 req->flags |= REQ_F_NEED_CLEANUP;
4680 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4682 struct io_unlink *un = &req->unlink;
4685 if (issue_flags & IO_URING_F_NONBLOCK)
4688 if (un->flags & AT_REMOVEDIR)
4689 ret = do_rmdir(un->dfd, un->filename);
4691 ret = do_unlinkat(un->dfd, un->filename);
4693 req->flags &= ~REQ_F_NEED_CLEANUP;
4694 io_req_complete(req, ret);
4698 static int io_mkdirat_prep(struct io_kiocb *req,
4699 const struct io_uring_sqe *sqe)
4701 struct io_mkdir *mkd = &req->mkdir;
4702 const char __user *fname;
4704 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4706 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4709 mkd->dfd = READ_ONCE(sqe->fd);
4710 mkd->mode = READ_ONCE(sqe->len);
4712 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4713 mkd->filename = getname(fname);
4714 if (IS_ERR(mkd->filename))
4715 return PTR_ERR(mkd->filename);
4717 req->flags |= REQ_F_NEED_CLEANUP;
4721 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4723 struct io_mkdir *mkd = &req->mkdir;
4726 if (issue_flags & IO_URING_F_NONBLOCK)
4729 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4731 req->flags &= ~REQ_F_NEED_CLEANUP;
4732 io_req_complete(req, ret);
4736 static int io_symlinkat_prep(struct io_kiocb *req,
4737 const struct io_uring_sqe *sqe)
4739 struct io_symlink *sl = &req->symlink;
4740 const char __user *oldpath, *newpath;
4742 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4744 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4747 sl->new_dfd = READ_ONCE(sqe->fd);
4748 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4749 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4751 sl->oldpath = getname(oldpath);
4752 if (IS_ERR(sl->oldpath))
4753 return PTR_ERR(sl->oldpath);
4755 sl->newpath = getname(newpath);
4756 if (IS_ERR(sl->newpath)) {
4757 putname(sl->oldpath);
4758 return PTR_ERR(sl->newpath);
4761 req->flags |= REQ_F_NEED_CLEANUP;
4765 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4767 struct io_symlink *sl = &req->symlink;
4770 if (issue_flags & IO_URING_F_NONBLOCK)
4773 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4775 req->flags &= ~REQ_F_NEED_CLEANUP;
4776 io_req_complete(req, ret);
4780 static int io_linkat_prep(struct io_kiocb *req,
4781 const struct io_uring_sqe *sqe)
4783 struct io_hardlink *lnk = &req->hardlink;
4784 const char __user *oldf, *newf;
4786 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4788 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4791 lnk->old_dfd = READ_ONCE(sqe->fd);
4792 lnk->new_dfd = READ_ONCE(sqe->len);
4793 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4794 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4795 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4797 lnk->oldpath = getname(oldf);
4798 if (IS_ERR(lnk->oldpath))
4799 return PTR_ERR(lnk->oldpath);
4801 lnk->newpath = getname(newf);
4802 if (IS_ERR(lnk->newpath)) {
4803 putname(lnk->oldpath);
4804 return PTR_ERR(lnk->newpath);
4807 req->flags |= REQ_F_NEED_CLEANUP;
4811 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4813 struct io_hardlink *lnk = &req->hardlink;
4816 if (issue_flags & IO_URING_F_NONBLOCK)
4819 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4820 lnk->newpath, lnk->flags);
4822 req->flags &= ~REQ_F_NEED_CLEANUP;
4823 io_req_complete(req, ret);
4827 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
4829 req->uring_cmd.task_work_cb(&req->uring_cmd);
4832 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
4833 void (*task_work_cb)(struct io_uring_cmd *))
4835 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4837 req->uring_cmd.task_work_cb = task_work_cb;
4838 req->io_task_work.func = io_uring_cmd_work;
4839 io_req_task_work_add(req);
4841 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
4843 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
4844 u64 extra1, u64 extra2)
4846 req->extra1 = extra1;
4847 req->extra2 = extra2;
4848 req->flags |= REQ_F_CQE32_INIT;
4852 * Called by consumers of io_uring_cmd, if they originally returned
4853 * -EIOCBQUEUED upon receiving the command.
4855 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
4857 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4862 if (req->ctx->flags & IORING_SETUP_CQE32)
4863 io_req_set_cqe32_extra(req, res2, 0);
4864 io_req_complete(req, ret);
4866 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
4868 static int io_uring_cmd_prep_async(struct io_kiocb *req)
4872 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
4874 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
4878 static int io_uring_cmd_prep(struct io_kiocb *req,
4879 const struct io_uring_sqe *sqe)
4881 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4883 if (sqe->rw_flags || sqe->__pad1)
4885 ioucmd->cmd = sqe->cmd;
4886 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
4890 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
4892 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4893 struct io_ring_ctx *ctx = req->ctx;
4894 struct file *file = req->file;
4897 if (!req->file->f_op->uring_cmd)
4900 if (ctx->flags & IORING_SETUP_SQE128)
4901 issue_flags |= IO_URING_F_SQE128;
4902 if (ctx->flags & IORING_SETUP_CQE32)
4903 issue_flags |= IO_URING_F_CQE32;
4904 if (ctx->flags & IORING_SETUP_IOPOLL)
4905 issue_flags |= IO_URING_F_IOPOLL;
4907 if (req_has_async_data(req))
4908 ioucmd->cmd = req->async_data;
4910 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
4911 if (ret == -EAGAIN) {
4912 if (!req_has_async_data(req)) {
4913 if (io_alloc_async_data(req))
4915 io_uring_cmd_prep_async(req);
4920 if (ret != -EIOCBQUEUED)
4921 io_uring_cmd_done(ioucmd, ret, 0);
4925 static int __io_splice_prep(struct io_kiocb *req,
4926 const struct io_uring_sqe *sqe)
4928 struct io_splice *sp = &req->splice;
4929 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4931 sp->len = READ_ONCE(sqe->len);
4932 sp->flags = READ_ONCE(sqe->splice_flags);
4933 if (unlikely(sp->flags & ~valid_flags))
4935 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4939 static int io_tee_prep(struct io_kiocb *req,
4940 const struct io_uring_sqe *sqe)
4942 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4944 return __io_splice_prep(req, sqe);
4947 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4949 struct io_splice *sp = &req->splice;
4950 struct file *out = sp->file_out;
4951 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4955 if (issue_flags & IO_URING_F_NONBLOCK)
4958 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4959 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4961 in = io_file_get_normal(req, sp->splice_fd_in);
4968 ret = do_tee(in, out, sp->len, flags);
4970 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4975 __io_req_complete(req, 0, ret, 0);
4979 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4981 struct io_splice *sp = &req->splice;
4983 sp->off_in = READ_ONCE(sqe->splice_off_in);
4984 sp->off_out = READ_ONCE(sqe->off);
4985 return __io_splice_prep(req, sqe);
4988 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4990 struct io_splice *sp = &req->splice;
4991 struct file *out = sp->file_out;
4992 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4993 loff_t *poff_in, *poff_out;
4997 if (issue_flags & IO_URING_F_NONBLOCK)
5000 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5001 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5003 in = io_file_get_normal(req, sp->splice_fd_in);
5009 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5010 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5013 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5015 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5020 __io_req_complete(req, 0, ret, 0);
5024 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5030 * IORING_OP_NOP just posts a completion event, nothing else.
5032 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5034 __io_req_complete(req, issue_flags, 0, 0);
5038 static int io_msg_ring_prep(struct io_kiocb *req,
5039 const struct io_uring_sqe *sqe)
5041 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5042 sqe->buf_index || sqe->personality))
5045 req->msg.user_data = READ_ONCE(sqe->off);
5046 req->msg.len = READ_ONCE(sqe->len);
5050 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5052 struct io_ring_ctx *target_ctx;
5053 struct io_msg *msg = &req->msg;
5058 if (req->file->f_op != &io_uring_fops)
5062 target_ctx = req->file->private_data;
5064 spin_lock(&target_ctx->completion_lock);
5065 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5066 io_commit_cqring(target_ctx);
5067 spin_unlock(&target_ctx->completion_lock);
5070 io_cqring_ev_posted(target_ctx);
5077 __io_req_complete(req, issue_flags, ret, 0);
5078 /* put file to avoid an attempt to IOPOLL the req */
5079 io_put_file(req->file);
5084 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5086 struct io_sync *sync = io_kiocb_to_cmd(req);
5088 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5091 sync->flags = READ_ONCE(sqe->fsync_flags);
5092 if (unlikely(sync->flags & ~IORING_FSYNC_DATASYNC))
5095 sync->off = READ_ONCE(sqe->off);
5096 sync->len = READ_ONCE(sqe->len);
5100 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5102 struct io_sync *sync = io_kiocb_to_cmd(req);
5103 loff_t end = sync->off + sync->len;
5106 /* fsync always requires a blocking context */
5107 if (issue_flags & IO_URING_F_NONBLOCK)
5110 ret = vfs_fsync_range(req->file, sync->off, end > 0 ? end : LLONG_MAX,
5111 sync->flags & IORING_FSYNC_DATASYNC);
5112 io_req_complete(req, ret);
5116 static int io_fallocate_prep(struct io_kiocb *req,
5117 const struct io_uring_sqe *sqe)
5119 struct io_sync *sync = io_kiocb_to_cmd(req);
5121 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5124 sync->off = READ_ONCE(sqe->off);
5125 sync->len = READ_ONCE(sqe->addr);
5126 sync->mode = READ_ONCE(sqe->len);
5130 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5132 struct io_sync *sync = io_kiocb_to_cmd(req);
5135 /* fallocate always requiring blocking context */
5136 if (issue_flags & IO_URING_F_NONBLOCK)
5138 ret = vfs_fallocate(req->file, sync->mode, sync->off, sync->len);
5140 fsnotify_modify(req->file);
5141 io_req_complete(req, ret);
5145 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5147 const char __user *fname;
5150 if (unlikely(sqe->buf_index))
5152 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5155 /* open.how should be already initialised */
5156 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5157 req->open.how.flags |= O_LARGEFILE;
5159 req->open.dfd = READ_ONCE(sqe->fd);
5160 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5161 req->open.filename = getname(fname);
5162 if (IS_ERR(req->open.filename)) {
5163 ret = PTR_ERR(req->open.filename);
5164 req->open.filename = NULL;
5168 req->open.file_slot = READ_ONCE(sqe->file_index);
5169 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5172 req->open.nofile = rlimit(RLIMIT_NOFILE);
5173 req->flags |= REQ_F_NEED_CLEANUP;
5177 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5179 u64 mode = READ_ONCE(sqe->len);
5180 u64 flags = READ_ONCE(sqe->open_flags);
5182 req->open.how = build_open_how(flags, mode);
5183 return __io_openat_prep(req, sqe);
5186 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5188 struct open_how __user *how;
5192 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5193 len = READ_ONCE(sqe->len);
5194 if (len < OPEN_HOW_SIZE_VER0)
5197 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5202 return __io_openat_prep(req, sqe);
5205 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5207 struct io_file_table *table = &ctx->file_table;
5208 unsigned long nr = ctx->nr_user_files;
5212 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5216 if (!table->alloc_hint)
5219 nr = table->alloc_hint;
5220 table->alloc_hint = 0;
5227 * Note when io_fixed_fd_install() returns error value, it will ensure
5228 * fput() is called correspondingly.
5230 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5231 struct file *file, unsigned int file_slot)
5233 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5234 struct io_ring_ctx *ctx = req->ctx;
5237 io_ring_submit_lock(ctx, issue_flags);
5240 ret = io_file_bitmap_get(ctx);
5241 if (unlikely(ret < 0))
5248 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5249 if (!ret && alloc_slot)
5252 io_ring_submit_unlock(ctx, issue_flags);
5253 if (unlikely(ret < 0))
5258 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5260 struct open_flags op;
5262 bool resolve_nonblock, nonblock_set;
5263 bool fixed = !!req->open.file_slot;
5266 ret = build_open_flags(&req->open.how, &op);
5269 nonblock_set = op.open_flag & O_NONBLOCK;
5270 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5271 if (issue_flags & IO_URING_F_NONBLOCK) {
5273 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5274 * it'll always -EAGAIN
5276 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5278 op.lookup_flags |= LOOKUP_CACHED;
5279 op.open_flag |= O_NONBLOCK;
5283 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5288 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5291 * We could hang on to this 'fd' on retrying, but seems like
5292 * marginal gain for something that is now known to be a slower
5293 * path. So just put it, and we'll get a new one when we retry.
5298 ret = PTR_ERR(file);
5299 /* only retry if RESOLVE_CACHED wasn't already set by application */
5300 if (ret == -EAGAIN &&
5301 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5306 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5307 file->f_flags &= ~O_NONBLOCK;
5308 fsnotify_open(file);
5311 fd_install(ret, file);
5313 ret = io_fixed_fd_install(req, issue_flags, file,
5314 req->open.file_slot);
5316 putname(req->open.filename);
5317 req->flags &= ~REQ_F_NEED_CLEANUP;
5320 __io_req_complete(req, issue_flags, ret, 0);
5324 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5326 return io_openat2(req, issue_flags);
5329 static int io_remove_buffers_prep(struct io_kiocb *req,
5330 const struct io_uring_sqe *sqe)
5332 struct io_provide_buf *p = &req->pbuf;
5335 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5339 tmp = READ_ONCE(sqe->fd);
5340 if (!tmp || tmp > USHRT_MAX)
5343 memset(p, 0, sizeof(*p));
5345 p->bgid = READ_ONCE(sqe->buf_group);
5349 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5350 struct io_buffer_list *bl, unsigned nbufs)
5354 /* shouldn't happen */
5358 if (bl->buf_nr_pages) {
5361 i = bl->buf_ring->tail - bl->head;
5362 for (j = 0; j < bl->buf_nr_pages; j++)
5363 unpin_user_page(bl->buf_pages[j]);
5364 kvfree(bl->buf_pages);
5365 bl->buf_pages = NULL;
5366 bl->buf_nr_pages = 0;
5367 /* make sure it's seen as empty */
5368 INIT_LIST_HEAD(&bl->buf_list);
5372 /* the head kbuf is the list itself */
5373 while (!list_empty(&bl->buf_list)) {
5374 struct io_buffer *nxt;
5376 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5377 list_del(&nxt->list);
5387 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5389 struct io_provide_buf *p = &req->pbuf;
5390 struct io_ring_ctx *ctx = req->ctx;
5391 struct io_buffer_list *bl;
5394 io_ring_submit_lock(ctx, issue_flags);
5397 bl = io_buffer_get_list(ctx, p->bgid);
5400 /* can't use provide/remove buffers command on mapped buffers */
5401 if (!bl->buf_nr_pages)
5402 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5407 /* complete before unlock, IOPOLL may need the lock */
5408 __io_req_complete(req, issue_flags, ret, 0);
5409 io_ring_submit_unlock(ctx, issue_flags);
5413 static int io_provide_buffers_prep(struct io_kiocb *req,
5414 const struct io_uring_sqe *sqe)
5416 unsigned long size, tmp_check;
5417 struct io_provide_buf *p = &req->pbuf;
5420 if (sqe->rw_flags || sqe->splice_fd_in)
5423 tmp = READ_ONCE(sqe->fd);
5424 if (!tmp || tmp > USHRT_MAX)
5427 p->addr = READ_ONCE(sqe->addr);
5428 p->len = READ_ONCE(sqe->len);
5430 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5433 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5436 size = (unsigned long)p->len * p->nbufs;
5437 if (!access_ok(u64_to_user_ptr(p->addr), size))
5440 p->bgid = READ_ONCE(sqe->buf_group);
5441 tmp = READ_ONCE(sqe->off);
5442 if (tmp > USHRT_MAX)
5448 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5450 struct io_buffer *buf;
5455 * Completions that don't happen inline (eg not under uring_lock) will
5456 * add to ->io_buffers_comp. If we don't have any free buffers, check
5457 * the completion list and splice those entries first.
5459 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5460 spin_lock(&ctx->completion_lock);
5461 if (!list_empty(&ctx->io_buffers_comp)) {
5462 list_splice_init(&ctx->io_buffers_comp,
5463 &ctx->io_buffers_cache);
5464 spin_unlock(&ctx->completion_lock);
5467 spin_unlock(&ctx->completion_lock);
5471 * No free buffers and no completion entries either. Allocate a new
5472 * page worth of buffer entries and add those to our freelist.
5474 page = alloc_page(GFP_KERNEL_ACCOUNT);
5478 list_add(&page->lru, &ctx->io_buffers_pages);
5480 buf = page_address(page);
5481 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5482 while (bufs_in_page) {
5483 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5491 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5492 struct io_buffer_list *bl)
5494 struct io_buffer *buf;
5495 u64 addr = pbuf->addr;
5496 int i, bid = pbuf->bid;
5498 for (i = 0; i < pbuf->nbufs; i++) {
5499 if (list_empty(&ctx->io_buffers_cache) &&
5500 io_refill_buffer_cache(ctx))
5502 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5504 list_move_tail(&buf->list, &bl->buf_list);
5506 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5508 buf->bgid = pbuf->bgid;
5514 return i ? 0 : -ENOMEM;
5517 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5521 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5526 for (i = 0; i < BGID_ARRAY; i++) {
5527 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5528 ctx->io_bl[i].bgid = i;
5534 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5536 struct io_provide_buf *p = &req->pbuf;
5537 struct io_ring_ctx *ctx = req->ctx;
5538 struct io_buffer_list *bl;
5541 io_ring_submit_lock(ctx, issue_flags);
5543 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5544 ret = io_init_bl_list(ctx);
5549 bl = io_buffer_get_list(ctx, p->bgid);
5550 if (unlikely(!bl)) {
5551 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5556 INIT_LIST_HEAD(&bl->buf_list);
5557 ret = io_buffer_add_list(ctx, bl, p->bgid);
5563 /* can't add buffers via this command for a mapped buffer ring */
5564 if (bl->buf_nr_pages) {
5569 ret = io_add_buffers(ctx, p, bl);
5573 /* complete before unlock, IOPOLL may need the lock */
5574 __io_req_complete(req, issue_flags, ret, 0);
5575 io_ring_submit_unlock(ctx, issue_flags);
5579 static int io_epoll_ctl_prep(struct io_kiocb *req,
5580 const struct io_uring_sqe *sqe)
5582 #if defined(CONFIG_EPOLL)
5583 if (sqe->buf_index || sqe->splice_fd_in)
5586 req->epoll.epfd = READ_ONCE(sqe->fd);
5587 req->epoll.op = READ_ONCE(sqe->len);
5588 req->epoll.fd = READ_ONCE(sqe->off);
5590 if (ep_op_has_event(req->epoll.op)) {
5591 struct epoll_event __user *ev;
5593 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5594 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5604 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5606 #if defined(CONFIG_EPOLL)
5607 struct io_epoll *ie = &req->epoll;
5609 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5611 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5612 if (force_nonblock && ret == -EAGAIN)
5617 __io_req_complete(req, issue_flags, ret, 0);
5624 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5626 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5627 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5630 req->madvise.addr = READ_ONCE(sqe->addr);
5631 req->madvise.len = READ_ONCE(sqe->len);
5632 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5639 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5641 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5642 struct io_madvise *ma = &req->madvise;
5645 if (issue_flags & IO_URING_F_NONBLOCK)
5648 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5649 io_req_complete(req, ret);
5656 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5658 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5661 req->fadvise.offset = READ_ONCE(sqe->off);
5662 req->fadvise.len = READ_ONCE(sqe->len);
5663 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5667 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5669 struct io_fadvise *fa = &req->fadvise;
5672 if (issue_flags & IO_URING_F_NONBLOCK) {
5673 switch (fa->advice) {
5674 case POSIX_FADV_NORMAL:
5675 case POSIX_FADV_RANDOM:
5676 case POSIX_FADV_SEQUENTIAL:
5683 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5686 __io_req_complete(req, issue_flags, ret, 0);
5690 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5692 const char __user *path;
5694 if (sqe->buf_index || sqe->splice_fd_in)
5696 if (req->flags & REQ_F_FIXED_FILE)
5699 req->statx.dfd = READ_ONCE(sqe->fd);
5700 req->statx.mask = READ_ONCE(sqe->len);
5701 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5702 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5703 req->statx.flags = READ_ONCE(sqe->statx_flags);
5705 req->statx.filename = getname_flags(path,
5706 getname_statx_lookup_flags(req->statx.flags),
5709 if (IS_ERR(req->statx.filename)) {
5710 int ret = PTR_ERR(req->statx.filename);
5712 req->statx.filename = NULL;
5716 req->flags |= REQ_F_NEED_CLEANUP;
5720 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5722 struct io_statx *ctx = &req->statx;
5725 if (issue_flags & IO_URING_F_NONBLOCK)
5728 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5730 io_req_complete(req, ret);
5734 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5736 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5738 if (req->flags & REQ_F_FIXED_FILE)
5741 req->close.fd = READ_ONCE(sqe->fd);
5742 req->close.file_slot = READ_ONCE(sqe->file_index);
5743 if (req->close.file_slot && req->close.fd)
5749 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5751 struct files_struct *files = current->files;
5752 struct io_close *close = &req->close;
5753 struct fdtable *fdt;
5757 if (req->close.file_slot) {
5758 ret = io_close_fixed(req, issue_flags);
5762 spin_lock(&files->file_lock);
5763 fdt = files_fdtable(files);
5764 if (close->fd >= fdt->max_fds) {
5765 spin_unlock(&files->file_lock);
5768 file = rcu_dereference_protected(fdt->fd[close->fd],
5769 lockdep_is_held(&files->file_lock));
5770 if (!file || file->f_op == &io_uring_fops) {
5771 spin_unlock(&files->file_lock);
5775 /* if the file has a flush method, be safe and punt to async */
5776 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5777 spin_unlock(&files->file_lock);
5781 file = __close_fd_get_file(close->fd);
5782 spin_unlock(&files->file_lock);
5786 /* No ->flush() or already async, safely close from here */
5787 ret = filp_close(file, current->files);
5791 __io_req_complete(req, issue_flags, ret, 0);
5795 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5797 struct io_sync *sync = io_kiocb_to_cmd(req);
5799 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5802 sync->off = READ_ONCE(sqe->off);
5803 sync->len = READ_ONCE(sqe->len);
5804 sync->flags = READ_ONCE(sqe->sync_range_flags);
5808 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5810 struct io_sync *sync = io_kiocb_to_cmd(req);
5813 /* sync_file_range always requires a blocking context */
5814 if (issue_flags & IO_URING_F_NONBLOCK)
5817 ret = sync_file_range(req->file, sync->off, sync->len, sync->flags);
5818 io_req_complete(req, ret);
5822 #if defined(CONFIG_NET)
5823 static int io_shutdown_prep(struct io_kiocb *req,
5824 const struct io_uring_sqe *sqe)
5826 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
5828 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
5829 sqe->buf_index || sqe->splice_fd_in))
5832 shutdown->how = READ_ONCE(sqe->len);
5836 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
5838 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
5839 struct socket *sock;
5842 if (issue_flags & IO_URING_F_NONBLOCK)
5845 sock = sock_from_file(req->file);
5846 if (unlikely(!sock))
5849 ret = __sys_shutdown_sock(sock, shutdown->how);
5850 io_req_complete(req, ret);
5854 static bool io_net_retry(struct socket *sock, int flags)
5856 if (!(flags & MSG_WAITALL))
5858 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5861 static int io_setup_async_msg(struct io_kiocb *req,
5862 struct io_async_msghdr *kmsg)
5864 struct io_async_msghdr *async_msg = req->async_data;
5868 if (io_alloc_async_data(req)) {
5869 kfree(kmsg->free_iov);
5872 async_msg = req->async_data;
5873 req->flags |= REQ_F_NEED_CLEANUP;
5874 memcpy(async_msg, kmsg, sizeof(*kmsg));
5875 async_msg->msg.msg_name = &async_msg->addr;
5876 /* if were using fast_iov, set it to the new one */
5877 if (!async_msg->free_iov)
5878 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5883 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5884 struct io_async_msghdr *iomsg)
5886 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5888 iomsg->msg.msg_name = &iomsg->addr;
5889 iomsg->free_iov = iomsg->fast_iov;
5890 return sendmsg_copy_msghdr(&iomsg->msg, sr->umsg, sr->msg_flags,
5894 static int io_sendmsg_prep_async(struct io_kiocb *req)
5898 ret = io_sendmsg_copy_hdr(req, req->async_data);
5900 req->flags |= REQ_F_NEED_CLEANUP;
5904 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5906 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5908 if (unlikely(sqe->file_index || sqe->addr2))
5911 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5912 sr->len = READ_ONCE(sqe->len);
5913 sr->flags = READ_ONCE(sqe->ioprio);
5914 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5916 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5917 if (sr->msg_flags & MSG_DONTWAIT)
5918 req->flags |= REQ_F_NOWAIT;
5920 #ifdef CONFIG_COMPAT
5921 if (req->ctx->compat)
5922 sr->msg_flags |= MSG_CMSG_COMPAT;
5928 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5930 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5931 struct io_async_msghdr iomsg, *kmsg;
5932 struct socket *sock;
5937 sock = sock_from_file(req->file);
5938 if (unlikely(!sock))
5941 if (req_has_async_data(req)) {
5942 kmsg = req->async_data;
5944 ret = io_sendmsg_copy_hdr(req, &iomsg);
5950 if (!(req->flags & REQ_F_POLLED) &&
5951 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5952 return io_setup_async_msg(req, kmsg);
5954 flags = sr->msg_flags;
5955 if (issue_flags & IO_URING_F_NONBLOCK)
5956 flags |= MSG_DONTWAIT;
5957 if (flags & MSG_WAITALL)
5958 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5960 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5962 if (ret < min_ret) {
5963 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5964 return io_setup_async_msg(req, kmsg);
5965 if (ret == -ERESTARTSYS)
5967 if (ret > 0 && io_net_retry(sock, flags)) {
5969 req->flags |= REQ_F_PARTIAL_IO;
5970 return io_setup_async_msg(req, kmsg);
5974 /* fast path, check for non-NULL to avoid function call */
5976 kfree(kmsg->free_iov);
5977 req->flags &= ~REQ_F_NEED_CLEANUP;
5980 else if (sr->done_io)
5982 __io_req_complete(req, issue_flags, ret, 0);
5986 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5988 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
5991 struct socket *sock;
5996 if (!(req->flags & REQ_F_POLLED) &&
5997 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6000 sock = sock_from_file(req->file);
6001 if (unlikely(!sock))
6004 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6008 msg.msg_name = NULL;
6009 msg.msg_control = NULL;
6010 msg.msg_controllen = 0;
6011 msg.msg_namelen = 0;
6013 flags = sr->msg_flags;
6014 if (issue_flags & IO_URING_F_NONBLOCK)
6015 flags |= MSG_DONTWAIT;
6016 if (flags & MSG_WAITALL)
6017 min_ret = iov_iter_count(&msg.msg_iter);
6019 msg.msg_flags = flags;
6020 ret = sock_sendmsg(sock, &msg);
6021 if (ret < min_ret) {
6022 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6024 if (ret == -ERESTARTSYS)
6026 if (ret > 0 && io_net_retry(sock, flags)) {
6030 req->flags |= REQ_F_PARTIAL_IO;
6037 else if (sr->done_io)
6039 __io_req_complete(req, issue_flags, ret, 0);
6043 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6044 struct io_async_msghdr *iomsg)
6046 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6047 struct iovec __user *uiov;
6051 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6052 &iomsg->uaddr, &uiov, &iov_len);
6056 if (req->flags & REQ_F_BUFFER_SELECT) {
6059 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6061 sr->len = iomsg->fast_iov[0].iov_len;
6062 iomsg->free_iov = NULL;
6064 iomsg->free_iov = iomsg->fast_iov;
6065 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6066 &iomsg->free_iov, &iomsg->msg.msg_iter,
6075 #ifdef CONFIG_COMPAT
6076 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6077 struct io_async_msghdr *iomsg)
6079 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6080 struct compat_iovec __user *uiov;
6085 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6090 uiov = compat_ptr(ptr);
6091 if (req->flags & REQ_F_BUFFER_SELECT) {
6092 compat_ssize_t clen;
6096 if (!access_ok(uiov, sizeof(*uiov)))
6098 if (__get_user(clen, &uiov->iov_len))
6103 iomsg->free_iov = NULL;
6105 iomsg->free_iov = iomsg->fast_iov;
6106 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6107 UIO_FASTIOV, &iomsg->free_iov,
6108 &iomsg->msg.msg_iter, true);
6117 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6118 struct io_async_msghdr *iomsg)
6120 iomsg->msg.msg_name = &iomsg->addr;
6122 #ifdef CONFIG_COMPAT
6123 if (req->ctx->compat)
6124 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6127 return __io_recvmsg_copy_hdr(req, iomsg);
6130 static int io_recvmsg_prep_async(struct io_kiocb *req)
6134 ret = io_recvmsg_copy_hdr(req, req->async_data);
6136 req->flags |= REQ_F_NEED_CLEANUP;
6140 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6142 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6144 if (unlikely(sqe->file_index || sqe->addr2))
6147 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6148 sr->len = READ_ONCE(sqe->len);
6149 sr->flags = READ_ONCE(sqe->ioprio);
6150 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6152 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6153 if (sr->msg_flags & MSG_DONTWAIT)
6154 req->flags |= REQ_F_NOWAIT;
6155 if (sr->msg_flags & MSG_ERRQUEUE)
6156 req->flags |= REQ_F_CLEAR_POLLIN;
6158 #ifdef CONFIG_COMPAT
6159 if (req->ctx->compat)
6160 sr->msg_flags |= MSG_CMSG_COMPAT;
6166 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6168 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6169 struct io_async_msghdr iomsg, *kmsg;
6170 struct socket *sock;
6171 unsigned int cflags;
6173 int ret, min_ret = 0;
6174 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6176 sock = sock_from_file(req->file);
6177 if (unlikely(!sock))
6180 if (req_has_async_data(req)) {
6181 kmsg = req->async_data;
6183 ret = io_recvmsg_copy_hdr(req, &iomsg);
6189 if (!(req->flags & REQ_F_POLLED) &&
6190 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6191 return io_setup_async_msg(req, kmsg);
6193 if (io_do_buffer_select(req)) {
6196 buf = io_buffer_select(req, &sr->len, issue_flags);
6199 kmsg->fast_iov[0].iov_base = buf;
6200 kmsg->fast_iov[0].iov_len = sr->len;
6201 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6205 flags = sr->msg_flags;
6207 flags |= MSG_DONTWAIT;
6208 if (flags & MSG_WAITALL)
6209 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6211 kmsg->msg.msg_get_inq = 1;
6212 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6213 if (ret < min_ret) {
6214 if (ret == -EAGAIN && force_nonblock)
6215 return io_setup_async_msg(req, kmsg);
6216 if (ret == -ERESTARTSYS)
6218 if (ret > 0 && io_net_retry(sock, flags)) {
6220 req->flags |= REQ_F_PARTIAL_IO;
6221 return io_setup_async_msg(req, kmsg);
6224 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6228 /* fast path, check for non-NULL to avoid function call */
6230 kfree(kmsg->free_iov);
6231 req->flags &= ~REQ_F_NEED_CLEANUP;
6234 else if (sr->done_io)
6236 cflags = io_put_kbuf(req, issue_flags);
6237 if (kmsg->msg.msg_inq)
6238 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6239 __io_req_complete(req, issue_flags, ret, cflags);
6243 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6245 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
6247 struct socket *sock;
6249 unsigned int cflags;
6251 int ret, min_ret = 0;
6252 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6254 if (!(req->flags & REQ_F_POLLED) &&
6255 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6258 sock = sock_from_file(req->file);
6259 if (unlikely(!sock))
6262 if (io_do_buffer_select(req)) {
6265 buf = io_buffer_select(req, &sr->len, issue_flags);
6271 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6275 msg.msg_name = NULL;
6276 msg.msg_namelen = 0;
6277 msg.msg_control = NULL;
6278 msg.msg_get_inq = 1;
6280 msg.msg_controllen = 0;
6281 msg.msg_iocb = NULL;
6283 flags = sr->msg_flags;
6285 flags |= MSG_DONTWAIT;
6286 if (flags & MSG_WAITALL)
6287 min_ret = iov_iter_count(&msg.msg_iter);
6289 ret = sock_recvmsg(sock, &msg, flags);
6290 if (ret < min_ret) {
6291 if (ret == -EAGAIN && force_nonblock)
6293 if (ret == -ERESTARTSYS)
6295 if (ret > 0 && io_net_retry(sock, flags)) {
6299 req->flags |= REQ_F_PARTIAL_IO;
6303 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6310 else if (sr->done_io)
6312 cflags = io_put_kbuf(req, issue_flags);
6314 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6315 __io_req_complete(req, issue_flags, ret, cflags);
6319 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6321 struct io_accept *accept = io_kiocb_to_cmd(req);
6324 if (sqe->len || sqe->buf_index)
6327 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6328 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6329 accept->flags = READ_ONCE(sqe->accept_flags);
6330 accept->nofile = rlimit(RLIMIT_NOFILE);
6331 flags = READ_ONCE(sqe->ioprio);
6332 if (flags & ~IORING_ACCEPT_MULTISHOT)
6335 accept->file_slot = READ_ONCE(sqe->file_index);
6336 if (accept->file_slot) {
6337 if (accept->flags & SOCK_CLOEXEC)
6339 if (flags & IORING_ACCEPT_MULTISHOT &&
6340 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6343 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6345 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6346 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6347 if (flags & IORING_ACCEPT_MULTISHOT)
6348 req->flags |= REQ_F_APOLL_MULTISHOT;
6352 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6354 struct io_ring_ctx *ctx = req->ctx;
6355 struct io_accept *accept = io_kiocb_to_cmd(req);
6356 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6357 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6358 bool fixed = !!accept->file_slot;
6364 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6365 if (unlikely(fd < 0))
6368 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6373 ret = PTR_ERR(file);
6374 if (ret == -EAGAIN && force_nonblock) {
6376 * if it's multishot and polled, we don't need to
6377 * return EAGAIN to arm the poll infra since it
6378 * has already been done
6380 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6381 IO_APOLL_MULTI_POLLED)
6385 if (ret == -ERESTARTSYS)
6388 } else if (!fixed) {
6389 fd_install(fd, file);
6392 ret = io_fixed_fd_install(req, issue_flags, file,
6396 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6397 __io_req_complete(req, issue_flags, ret, 0);
6403 spin_lock(&ctx->completion_lock);
6404 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6406 io_commit_cqring(ctx);
6407 spin_unlock(&ctx->completion_lock);
6409 io_cqring_ev_posted(ctx);
6418 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6420 struct io_socket *sock = io_kiocb_to_cmd(req);
6422 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6425 sock->domain = READ_ONCE(sqe->fd);
6426 sock->type = READ_ONCE(sqe->off);
6427 sock->protocol = READ_ONCE(sqe->len);
6428 sock->file_slot = READ_ONCE(sqe->file_index);
6429 sock->nofile = rlimit(RLIMIT_NOFILE);
6431 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6432 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6434 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6439 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6441 struct io_socket *sock = io_kiocb_to_cmd(req);
6442 bool fixed = !!sock->file_slot;
6447 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6448 if (unlikely(fd < 0))
6451 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6455 ret = PTR_ERR(file);
6456 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6458 if (ret == -ERESTARTSYS)
6461 } else if (!fixed) {
6462 fd_install(fd, file);
6465 ret = io_fixed_fd_install(req, issue_flags, file,
6468 __io_req_complete(req, issue_flags, ret, 0);
6472 static int io_connect_prep_async(struct io_kiocb *req)
6474 struct io_async_connect *io = req->async_data;
6475 struct io_connect *conn = io_kiocb_to_cmd(req);
6477 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6480 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6482 struct io_connect *conn = io_kiocb_to_cmd(req);
6484 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6487 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6488 conn->addr_len = READ_ONCE(sqe->addr2);
6492 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6494 struct io_connect *connect = io_kiocb_to_cmd(req);
6495 struct io_async_connect __io, *io;
6496 unsigned file_flags;
6498 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6500 if (req_has_async_data(req)) {
6501 io = req->async_data;
6503 ret = move_addr_to_kernel(connect->addr,
6511 file_flags = force_nonblock ? O_NONBLOCK : 0;
6513 ret = __sys_connect_file(req->file, &io->address,
6514 connect->addr_len, file_flags);
6515 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6516 if (req_has_async_data(req))
6518 if (io_alloc_async_data(req)) {
6522 memcpy(req->async_data, &__io, sizeof(__io));
6525 if (ret == -ERESTARTSYS)
6530 __io_req_complete(req, issue_flags, ret, 0);
6533 #else /* !CONFIG_NET */
6534 #define IO_NETOP_FN(op) \
6535 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6537 return -EOPNOTSUPP; \
6540 #define IO_NETOP_PREP(op) \
6542 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6544 return -EOPNOTSUPP; \
6547 #define IO_NETOP_PREP_ASYNC(op) \
6549 static int io_##op##_prep_async(struct io_kiocb *req) \
6551 return -EOPNOTSUPP; \
6554 IO_NETOP_PREP_ASYNC(sendmsg);
6555 IO_NETOP_PREP_ASYNC(recvmsg);
6556 IO_NETOP_PREP_ASYNC(connect);
6557 IO_NETOP_PREP(accept);
6558 IO_NETOP_PREP(socket);
6559 IO_NETOP_PREP(shutdown);
6562 #endif /* CONFIG_NET */
6564 struct io_poll_table {
6565 struct poll_table_struct pt;
6566 struct io_kiocb *req;
6571 #define IO_POLL_CANCEL_FLAG BIT(31)
6572 #define IO_POLL_REF_MASK GENMASK(30, 0)
6575 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6576 * bump it and acquire ownership. It's disallowed to modify requests while not
6577 * owning it, that prevents from races for enqueueing task_work's and b/w
6578 * arming poll and wakeups.
6580 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6582 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6585 static void io_poll_mark_cancelled(struct io_kiocb *req)
6587 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6590 static struct io_poll *io_poll_get_double(struct io_kiocb *req)
6592 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6593 if (req->opcode == IORING_OP_POLL_ADD)
6594 return req->async_data;
6595 return req->apoll->double_poll;
6598 static struct io_poll *io_poll_get_single(struct io_kiocb *req)
6600 if (req->opcode == IORING_OP_POLL_ADD)
6601 return io_kiocb_to_cmd(req);
6602 return &req->apoll->poll;
6605 static void io_poll_req_insert(struct io_kiocb *req)
6607 struct io_ring_ctx *ctx = req->ctx;
6608 struct hlist_head *list;
6610 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6611 hlist_add_head(&req->hash_node, list);
6614 static void io_init_poll_iocb(struct io_poll *poll, __poll_t events,
6615 wait_queue_func_t wake_func)
6618 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6619 /* mask in events that we always want/need */
6620 poll->events = events | IO_POLL_UNMASK;
6621 INIT_LIST_HEAD(&poll->wait.entry);
6622 init_waitqueue_func_entry(&poll->wait, wake_func);
6625 static inline void io_poll_remove_entry(struct io_poll *poll)
6627 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6630 spin_lock_irq(&head->lock);
6631 list_del_init(&poll->wait.entry);
6633 spin_unlock_irq(&head->lock);
6637 static void io_poll_remove_entries(struct io_kiocb *req)
6640 * Nothing to do if neither of those flags are set. Avoid dipping
6641 * into the poll/apoll/double cachelines if we can.
6643 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6647 * While we hold the waitqueue lock and the waitqueue is nonempty,
6648 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6649 * lock in the first place can race with the waitqueue being freed.
6651 * We solve this as eventpoll does: by taking advantage of the fact that
6652 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6653 * we enter rcu_read_lock() and see that the pointer to the queue is
6654 * non-NULL, we can then lock it without the memory being freed out from
6657 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6658 * case the caller deletes the entry from the queue, leaving it empty.
6659 * In that case, only RCU prevents the queue memory from being freed.
6662 if (req->flags & REQ_F_SINGLE_POLL)
6663 io_poll_remove_entry(io_poll_get_single(req));
6664 if (req->flags & REQ_F_DOUBLE_POLL)
6665 io_poll_remove_entry(io_poll_get_double(req));
6669 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6671 * All poll tw should go through this. Checks for poll events, manages
6672 * references, does rewait, etc.
6674 * Returns a negative error on failure. >0 when no action require, which is
6675 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6676 * the request, then the mask is stored in req->cqe.res.
6678 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6680 struct io_ring_ctx *ctx = req->ctx;
6683 /* req->task == current here, checking PF_EXITING is safe */
6684 if (unlikely(req->task->flags & PF_EXITING))
6688 v = atomic_read(&req->poll_refs);
6690 /* tw handler should be the owner, and so have some references */
6691 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6693 if (v & IO_POLL_CANCEL_FLAG)
6696 if (!req->cqe.res) {
6697 struct poll_table_struct pt = { ._key = req->apoll_events };
6698 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6701 if ((unlikely(!req->cqe.res)))
6703 if (req->apoll_events & EPOLLONESHOT)
6706 /* multishot, just fill a CQE and proceed */
6707 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6708 __poll_t mask = mangle_poll(req->cqe.res &
6712 spin_lock(&ctx->completion_lock);
6713 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6714 mask, IORING_CQE_F_MORE);
6715 io_commit_cqring(ctx);
6716 spin_unlock(&ctx->completion_lock);
6718 io_cqring_ev_posted(ctx);
6724 io_tw_lock(req->ctx, locked);
6725 if (unlikely(req->task->flags & PF_EXITING))
6727 ret = io_issue_sqe(req,
6728 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6733 * Release all references, retry if someone tried to restart
6734 * task_work while we were executing it.
6736 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6741 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6743 struct io_ring_ctx *ctx = req->ctx;
6746 ret = io_poll_check_events(req, locked);
6751 struct io_poll *poll = io_kiocb_to_cmd(req);
6753 req->cqe.res = mangle_poll(req->cqe.res & poll->events);
6759 io_poll_remove_entries(req);
6760 spin_lock(&ctx->completion_lock);
6761 hash_del(&req->hash_node);
6762 __io_req_complete_post(req, req->cqe.res, 0);
6763 io_commit_cqring(ctx);
6764 spin_unlock(&ctx->completion_lock);
6765 io_cqring_ev_posted(ctx);
6768 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6770 struct io_ring_ctx *ctx = req->ctx;
6773 ret = io_poll_check_events(req, locked);
6777 io_poll_remove_entries(req);
6778 spin_lock(&ctx->completion_lock);
6779 hash_del(&req->hash_node);
6780 spin_unlock(&ctx->completion_lock);
6783 io_req_task_submit(req, locked);
6785 io_req_complete_failed(req, ret);
6788 static void __io_poll_execute(struct io_kiocb *req, int mask,
6789 __poll_t __maybe_unused events)
6791 req->cqe.res = mask;
6793 * This is useful for poll that is armed on behalf of another
6794 * request, and where the wakeup path could be on a different
6795 * CPU. We want to avoid pulling in req->apoll->events for that
6798 if (req->opcode == IORING_OP_POLL_ADD)
6799 req->io_task_work.func = io_poll_task_func;
6801 req->io_task_work.func = io_apoll_task_func;
6803 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6804 io_req_task_work_add(req);
6807 static inline void io_poll_execute(struct io_kiocb *req, int res,
6810 if (io_poll_get_ownership(req))
6811 __io_poll_execute(req, res, events);
6814 static void io_poll_cancel_req(struct io_kiocb *req)
6816 io_poll_mark_cancelled(req);
6817 /* kick tw, which should complete the request */
6818 io_poll_execute(req, 0, 0);
6821 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6822 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6823 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
6825 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6828 struct io_kiocb *req = wqe_to_req(wait);
6829 struct io_poll *poll = container_of(wait, struct io_poll, wait);
6830 __poll_t mask = key_to_poll(key);
6832 if (unlikely(mask & POLLFREE)) {
6833 io_poll_mark_cancelled(req);
6834 /* we have to kick tw in case it's not already */
6835 io_poll_execute(req, 0, poll->events);
6838 * If the waitqueue is being freed early but someone is already
6839 * holds ownership over it, we have to tear down the request as
6840 * best we can. That means immediately removing the request from
6841 * its waitqueue and preventing all further accesses to the
6842 * waitqueue via the request.
6844 list_del_init(&poll->wait.entry);
6847 * Careful: this *must* be the last step, since as soon
6848 * as req->head is NULL'ed out, the request can be
6849 * completed and freed, since aio_poll_complete_work()
6850 * will no longer need to take the waitqueue lock.
6852 smp_store_release(&poll->head, NULL);
6856 /* for instances that support it check for an event match first */
6857 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
6860 if (io_poll_get_ownership(req)) {
6861 /* optional, saves extra locking for removal in tw handler */
6862 if (mask && poll->events & EPOLLONESHOT) {
6863 list_del_init(&poll->wait.entry);
6865 if (wqe_is_double(wait))
6866 req->flags &= ~REQ_F_DOUBLE_POLL;
6868 req->flags &= ~REQ_F_SINGLE_POLL;
6870 __io_poll_execute(req, mask, poll->events);
6875 static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt,
6876 struct wait_queue_head *head,
6877 struct io_poll **poll_ptr)
6879 struct io_kiocb *req = pt->req;
6880 unsigned long wqe_private = (unsigned long) req;
6883 * The file being polled uses multiple waitqueues for poll handling
6884 * (e.g. one for read, one for write). Setup a separate io_poll
6887 if (unlikely(pt->nr_entries)) {
6888 struct io_poll *first = poll;
6890 /* double add on the same waitqueue head, ignore */
6891 if (first->head == head)
6893 /* already have a 2nd entry, fail a third attempt */
6895 if ((*poll_ptr)->head == head)
6897 pt->error = -EINVAL;
6901 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6903 pt->error = -ENOMEM;
6906 /* mark as double wq entry */
6908 req->flags |= REQ_F_DOUBLE_POLL;
6909 io_init_poll_iocb(poll, first->events, first->wait.func);
6911 if (req->opcode == IORING_OP_POLL_ADD)
6912 req->flags |= REQ_F_ASYNC_DATA;
6915 req->flags |= REQ_F_SINGLE_POLL;
6918 poll->wait.private = (void *) wqe_private;
6920 if (poll->events & EPOLLEXCLUSIVE)
6921 add_wait_queue_exclusive(head, &poll->wait);
6923 add_wait_queue(head, &poll->wait);
6926 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6927 struct poll_table_struct *p)
6929 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6930 struct io_poll *poll = io_kiocb_to_cmd(pt->req);
6932 __io_queue_proc(poll, pt, head,
6933 (struct io_poll **) &pt->req->async_data);
6936 static int __io_arm_poll_handler(struct io_kiocb *req,
6937 struct io_poll *poll,
6938 struct io_poll_table *ipt, __poll_t mask)
6940 struct io_ring_ctx *ctx = req->ctx;
6943 INIT_HLIST_NODE(&req->hash_node);
6944 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
6945 io_init_poll_iocb(poll, mask, io_poll_wake);
6946 poll->file = req->file;
6948 req->apoll_events = poll->events;
6950 ipt->pt._key = mask;
6953 ipt->nr_entries = 0;
6956 * Take the ownership to delay any tw execution up until we're done
6957 * with poll arming. see io_poll_get_ownership().
6959 atomic_set(&req->poll_refs, 1);
6960 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6962 if (mask && (poll->events & EPOLLONESHOT)) {
6963 io_poll_remove_entries(req);
6964 /* no one else has access to the req, forget about the ref */
6967 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6968 io_poll_remove_entries(req);
6970 ipt->error = -EINVAL;
6974 spin_lock(&ctx->completion_lock);
6975 io_poll_req_insert(req);
6976 spin_unlock(&ctx->completion_lock);
6979 /* can't multishot if failed, just queue the event we've got */
6980 if (unlikely(ipt->error || !ipt->nr_entries)) {
6981 poll->events |= EPOLLONESHOT;
6982 req->apoll_events |= EPOLLONESHOT;
6985 __io_poll_execute(req, mask, poll->events);
6990 * Release ownership. If someone tried to queue a tw while it was
6991 * locked, kick it off for them.
6993 v = atomic_dec_return(&req->poll_refs);
6994 if (unlikely(v & IO_POLL_REF_MASK))
6995 __io_poll_execute(req, 0, poll->events);
6999 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7000 struct poll_table_struct *p)
7002 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7003 struct async_poll *apoll = pt->req->apoll;
7005 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7014 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7016 const struct io_op_def *def = &io_op_defs[req->opcode];
7017 struct io_ring_ctx *ctx = req->ctx;
7018 struct async_poll *apoll;
7019 struct io_poll_table ipt;
7020 __poll_t mask = POLLPRI | POLLERR;
7023 if (!def->pollin && !def->pollout)
7024 return IO_APOLL_ABORTED;
7025 if (!file_can_poll(req->file))
7026 return IO_APOLL_ABORTED;
7027 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7028 return IO_APOLL_ABORTED;
7029 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7030 mask |= EPOLLONESHOT;
7033 mask |= EPOLLIN | EPOLLRDNORM;
7035 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7036 if (req->flags & REQ_F_CLEAR_POLLIN)
7039 mask |= EPOLLOUT | EPOLLWRNORM;
7041 if (def->poll_exclusive)
7042 mask |= EPOLLEXCLUSIVE;
7043 if (req->flags & REQ_F_POLLED) {
7045 kfree(apoll->double_poll);
7046 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7047 !list_empty(&ctx->apoll_cache)) {
7048 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7050 list_del_init(&apoll->poll.wait.entry);
7052 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7053 if (unlikely(!apoll))
7054 return IO_APOLL_ABORTED;
7056 apoll->double_poll = NULL;
7058 req->flags |= REQ_F_POLLED;
7059 ipt.pt._qproc = io_async_queue_proc;
7061 io_kbuf_recycle(req, issue_flags);
7063 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7064 if (ret || ipt.error)
7065 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7067 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7068 mask, apoll->poll.events);
7073 * Returns true if we found and killed one or more poll requests
7075 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7076 struct task_struct *tsk, bool cancel_all)
7078 struct hlist_node *tmp;
7079 struct io_kiocb *req;
7083 spin_lock(&ctx->completion_lock);
7084 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7085 struct hlist_head *list;
7087 list = &ctx->cancel_hash[i];
7088 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7089 if (io_match_task_safe(req, tsk, cancel_all)) {
7090 hlist_del_init(&req->hash_node);
7091 io_poll_cancel_req(req);
7096 spin_unlock(&ctx->completion_lock);
7100 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7101 struct io_cancel_data *cd)
7102 __must_hold(&ctx->completion_lock)
7104 struct hlist_head *list;
7105 struct io_kiocb *req;
7107 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7108 hlist_for_each_entry(req, list, hash_node) {
7109 if (cd->data != req->cqe.user_data)
7111 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7113 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7114 if (cd->seq == req->work.cancel_seq)
7116 req->work.cancel_seq = cd->seq;
7123 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7124 struct io_cancel_data *cd)
7125 __must_hold(&ctx->completion_lock)
7127 struct io_kiocb *req;
7130 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7131 struct hlist_head *list;
7133 list = &ctx->cancel_hash[i];
7134 hlist_for_each_entry(req, list, hash_node) {
7135 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7136 req->file != cd->file)
7138 if (cd->seq == req->work.cancel_seq)
7140 req->work.cancel_seq = cd->seq;
7147 static bool io_poll_disarm(struct io_kiocb *req)
7148 __must_hold(&ctx->completion_lock)
7150 if (!io_poll_get_ownership(req))
7152 io_poll_remove_entries(req);
7153 hash_del(&req->hash_node);
7157 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7158 __must_hold(&ctx->completion_lock)
7160 struct io_kiocb *req;
7162 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7163 req = io_poll_file_find(ctx, cd);
7165 req = io_poll_find(ctx, false, cd);
7168 io_poll_cancel_req(req);
7172 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7177 events = READ_ONCE(sqe->poll32_events);
7179 events = swahw32(events);
7181 if (!(flags & IORING_POLL_ADD_MULTI))
7182 events |= EPOLLONESHOT;
7183 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7186 static int io_poll_remove_prep(struct io_kiocb *req,
7187 const struct io_uring_sqe *sqe)
7189 struct io_poll_update *upd = io_kiocb_to_cmd(req);
7192 if (sqe->buf_index || sqe->splice_fd_in)
7194 flags = READ_ONCE(sqe->len);
7195 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7196 IORING_POLL_ADD_MULTI))
7198 /* meaningless without update */
7199 if (flags == IORING_POLL_ADD_MULTI)
7202 upd->old_user_data = READ_ONCE(sqe->addr);
7203 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7204 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7206 upd->new_user_data = READ_ONCE(sqe->off);
7207 if (!upd->update_user_data && upd->new_user_data)
7209 if (upd->update_events)
7210 upd->events = io_poll_parse_events(sqe, flags);
7211 else if (sqe->poll32_events)
7217 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7219 struct io_poll *poll = io_kiocb_to_cmd(req);
7222 if (sqe->buf_index || sqe->off || sqe->addr)
7224 flags = READ_ONCE(sqe->len);
7225 if (flags & ~IORING_POLL_ADD_MULTI)
7227 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7230 io_req_set_refcount(req);
7231 poll->events = io_poll_parse_events(sqe, flags);
7235 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7237 struct io_poll *poll = io_kiocb_to_cmd(req);
7238 struct io_poll_table ipt;
7241 ipt.pt._qproc = io_poll_queue_proc;
7243 ret = __io_arm_poll_handler(req, poll, &ipt, poll->events);
7244 if (!ret && ipt.error)
7246 ret = ret ?: ipt.error;
7248 __io_req_complete(req, issue_flags, ret, 0);
7252 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7254 struct io_poll_update *poll_update = io_kiocb_to_cmd(req);
7255 struct io_cancel_data cd = { .data = poll_update->old_user_data, };
7256 struct io_ring_ctx *ctx = req->ctx;
7257 struct io_kiocb *preq;
7261 spin_lock(&ctx->completion_lock);
7262 preq = io_poll_find(ctx, true, &cd);
7263 if (!preq || !io_poll_disarm(preq)) {
7264 spin_unlock(&ctx->completion_lock);
7265 ret = preq ? -EALREADY : -ENOENT;
7268 spin_unlock(&ctx->completion_lock);
7270 if (poll_update->update_events || poll_update->update_user_data) {
7271 /* only mask one event flags, keep behavior flags */
7272 if (poll_update->update_events) {
7273 struct io_poll *poll = io_kiocb_to_cmd(preq);
7275 poll->events &= ~0xffff;
7276 poll->events |= poll_update->events & 0xffff;
7277 poll->events |= IO_POLL_UNMASK;
7279 if (poll_update->update_user_data)
7280 preq->cqe.user_data = poll_update->new_user_data;
7282 ret2 = io_poll_add(preq, issue_flags);
7283 /* successfully updated, don't complete poll request */
7289 preq->cqe.res = -ECANCELED;
7290 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7291 io_req_task_complete(preq, &locked);
7295 /* complete update request, we're done with it */
7296 __io_req_complete(req, issue_flags, ret, 0);
7300 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7302 struct io_timeout_data *data = container_of(timer,
7303 struct io_timeout_data, timer);
7304 struct io_kiocb *req = data->req;
7305 struct io_ring_ctx *ctx = req->ctx;
7306 unsigned long flags;
7308 spin_lock_irqsave(&ctx->timeout_lock, flags);
7309 list_del_init(&req->timeout.list);
7310 atomic_set(&req->ctx->cq_timeouts,
7311 atomic_read(&req->ctx->cq_timeouts) + 1);
7312 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7314 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7317 req->cqe.res = -ETIME;
7318 req->io_task_work.func = io_req_task_complete;
7319 io_req_task_work_add(req);
7320 return HRTIMER_NORESTART;
7323 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7324 struct io_cancel_data *cd)
7325 __must_hold(&ctx->timeout_lock)
7327 struct io_timeout_data *io;
7328 struct io_kiocb *req;
7331 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7332 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7333 cd->data != req->cqe.user_data)
7335 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7336 if (cd->seq == req->work.cancel_seq)
7338 req->work.cancel_seq = cd->seq;
7344 return ERR_PTR(-ENOENT);
7346 io = req->async_data;
7347 if (hrtimer_try_to_cancel(&io->timer) == -1)
7348 return ERR_PTR(-EALREADY);
7349 list_del_init(&req->timeout.list);
7353 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7354 __must_hold(&ctx->completion_lock)
7356 struct io_kiocb *req;
7358 spin_lock_irq(&ctx->timeout_lock);
7359 req = io_timeout_extract(ctx, cd);
7360 spin_unlock_irq(&ctx->timeout_lock);
7363 return PTR_ERR(req);
7364 io_req_task_queue_fail(req, -ECANCELED);
7368 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7370 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7371 case IORING_TIMEOUT_BOOTTIME:
7372 return CLOCK_BOOTTIME;
7373 case IORING_TIMEOUT_REALTIME:
7374 return CLOCK_REALTIME;
7376 /* can't happen, vetted at prep time */
7380 return CLOCK_MONOTONIC;
7384 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7385 struct timespec64 *ts, enum hrtimer_mode mode)
7386 __must_hold(&ctx->timeout_lock)
7388 struct io_timeout_data *io;
7389 struct io_kiocb *req;
7392 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7393 found = user_data == req->cqe.user_data;
7400 io = req->async_data;
7401 if (hrtimer_try_to_cancel(&io->timer) == -1)
7403 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7404 io->timer.function = io_link_timeout_fn;
7405 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7409 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7410 struct timespec64 *ts, enum hrtimer_mode mode)
7411 __must_hold(&ctx->timeout_lock)
7413 struct io_cancel_data cd = { .data = user_data, };
7414 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7415 struct io_timeout_data *data;
7418 return PTR_ERR(req);
7420 req->timeout.off = 0; /* noseq */
7421 data = req->async_data;
7422 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7423 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7424 data->timer.function = io_timeout_fn;
7425 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7429 static int io_timeout_remove_prep(struct io_kiocb *req,
7430 const struct io_uring_sqe *sqe)
7432 struct io_timeout_rem *tr = &req->timeout_rem;
7434 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7436 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7439 tr->ltimeout = false;
7440 tr->addr = READ_ONCE(sqe->addr);
7441 tr->flags = READ_ONCE(sqe->timeout_flags);
7442 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7443 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7445 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7446 tr->ltimeout = true;
7447 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7449 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7451 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7453 } else if (tr->flags) {
7454 /* timeout removal doesn't support flags */
7461 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7463 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7468 * Remove or update an existing timeout command
7470 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7472 struct io_timeout_rem *tr = &req->timeout_rem;
7473 struct io_ring_ctx *ctx = req->ctx;
7476 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7477 struct io_cancel_data cd = { .data = tr->addr, };
7479 spin_lock(&ctx->completion_lock);
7480 ret = io_timeout_cancel(ctx, &cd);
7481 spin_unlock(&ctx->completion_lock);
7483 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7485 spin_lock_irq(&ctx->timeout_lock);
7487 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7489 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7490 spin_unlock_irq(&ctx->timeout_lock);
7495 io_req_complete_post(req, ret, 0);
7499 static int __io_timeout_prep(struct io_kiocb *req,
7500 const struct io_uring_sqe *sqe,
7501 bool is_timeout_link)
7503 struct io_timeout_data *data;
7505 u32 off = READ_ONCE(sqe->off);
7507 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7509 if (off && is_timeout_link)
7511 flags = READ_ONCE(sqe->timeout_flags);
7512 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7513 IORING_TIMEOUT_ETIME_SUCCESS))
7515 /* more than one clock specified is invalid, obviously */
7516 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7519 INIT_LIST_HEAD(&req->timeout.list);
7520 req->timeout.off = off;
7521 if (unlikely(off && !req->ctx->off_timeout_used))
7522 req->ctx->off_timeout_used = true;
7524 if (WARN_ON_ONCE(req_has_async_data(req)))
7526 if (io_alloc_async_data(req))
7529 data = req->async_data;
7531 data->flags = flags;
7533 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7536 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7539 INIT_LIST_HEAD(&req->timeout.list);
7540 data->mode = io_translate_timeout_mode(flags);
7541 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7543 if (is_timeout_link) {
7544 struct io_submit_link *link = &req->ctx->submit_state.link;
7548 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7550 req->timeout.head = link->last;
7551 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7556 static int io_timeout_prep(struct io_kiocb *req,
7557 const struct io_uring_sqe *sqe)
7559 return __io_timeout_prep(req, sqe, false);
7562 static int io_link_timeout_prep(struct io_kiocb *req,
7563 const struct io_uring_sqe *sqe)
7565 return __io_timeout_prep(req, sqe, true);
7568 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7570 struct io_ring_ctx *ctx = req->ctx;
7571 struct io_timeout_data *data = req->async_data;
7572 struct list_head *entry;
7573 u32 tail, off = req->timeout.off;
7575 spin_lock_irq(&ctx->timeout_lock);
7578 * sqe->off holds how many events that need to occur for this
7579 * timeout event to be satisfied. If it isn't set, then this is
7580 * a pure timeout request, sequence isn't used.
7582 if (io_is_timeout_noseq(req)) {
7583 entry = ctx->timeout_list.prev;
7587 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7588 req->timeout.target_seq = tail + off;
7590 /* Update the last seq here in case io_flush_timeouts() hasn't.
7591 * This is safe because ->completion_lock is held, and submissions
7592 * and completions are never mixed in the same ->completion_lock section.
7594 ctx->cq_last_tm_flush = tail;
7597 * Insertion sort, ensuring the first entry in the list is always
7598 * the one we need first.
7600 list_for_each_prev(entry, &ctx->timeout_list) {
7601 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7604 if (io_is_timeout_noseq(nxt))
7606 /* nxt.seq is behind @tail, otherwise would've been completed */
7607 if (off >= nxt->timeout.target_seq - tail)
7611 list_add(&req->timeout.list, entry);
7612 data->timer.function = io_timeout_fn;
7613 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7614 spin_unlock_irq(&ctx->timeout_lock);
7618 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7620 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7621 struct io_cancel_data *cd = data;
7623 if (req->ctx != cd->ctx)
7625 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7627 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7628 if (req->file != cd->file)
7631 if (req->cqe.user_data != cd->data)
7634 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7635 if (cd->seq == req->work.cancel_seq)
7637 req->work.cancel_seq = cd->seq;
7642 static int io_async_cancel_one(struct io_uring_task *tctx,
7643 struct io_cancel_data *cd)
7645 enum io_wq_cancel cancel_ret;
7649 if (!tctx || !tctx->io_wq)
7652 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7653 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7654 switch (cancel_ret) {
7655 case IO_WQ_CANCEL_OK:
7658 case IO_WQ_CANCEL_RUNNING:
7661 case IO_WQ_CANCEL_NOTFOUND:
7669 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7671 struct io_ring_ctx *ctx = req->ctx;
7674 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7676 ret = io_async_cancel_one(req->task->io_uring, cd);
7678 * Fall-through even for -EALREADY, as we may have poll armed
7679 * that need unarming.
7684 spin_lock(&ctx->completion_lock);
7685 ret = io_poll_cancel(ctx, cd);
7688 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7689 ret = io_timeout_cancel(ctx, cd);
7691 spin_unlock(&ctx->completion_lock);
7695 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7696 IORING_ASYNC_CANCEL_ANY)
7698 static int io_async_cancel_prep(struct io_kiocb *req,
7699 const struct io_uring_sqe *sqe)
7701 struct io_cancel *cancel = io_kiocb_to_cmd(req);
7703 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7705 if (sqe->off || sqe->len || sqe->splice_fd_in)
7708 cancel->addr = READ_ONCE(sqe->addr);
7709 cancel->flags = READ_ONCE(sqe->cancel_flags);
7710 if (cancel->flags & ~CANCEL_FLAGS)
7712 if (cancel->flags & IORING_ASYNC_CANCEL_FD) {
7713 if (cancel->flags & IORING_ASYNC_CANCEL_ANY)
7715 cancel->fd = READ_ONCE(sqe->fd);
7721 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7722 unsigned int issue_flags)
7724 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7725 struct io_ring_ctx *ctx = cd->ctx;
7726 struct io_tctx_node *node;
7730 ret = io_try_cancel(req, cd);
7738 /* slow path, try all io-wq's */
7739 io_ring_submit_lock(ctx, issue_flags);
7741 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7742 struct io_uring_task *tctx = node->task->io_uring;
7744 ret = io_async_cancel_one(tctx, cd);
7745 if (ret != -ENOENT) {
7751 io_ring_submit_unlock(ctx, issue_flags);
7752 return all ? nr : ret;
7755 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7757 struct io_cancel *cancel = io_kiocb_to_cmd(req);
7758 struct io_cancel_data cd = {
7760 .data = cancel->addr,
7761 .flags = cancel->flags,
7762 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7766 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7767 if (req->flags & REQ_F_FIXED_FILE)
7768 req->file = io_file_get_fixed(req, cancel->fd,
7771 req->file = io_file_get_normal(req, cancel->fd);
7776 cd.file = req->file;
7779 ret = __io_async_cancel(&cd, req, issue_flags);
7783 io_req_complete_post(req, ret, 0);
7787 static int io_files_update_prep(struct io_kiocb *req,
7788 const struct io_uring_sqe *sqe)
7790 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7792 if (sqe->rw_flags || sqe->splice_fd_in)
7795 req->rsrc_update.offset = READ_ONCE(sqe->off);
7796 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7797 if (!req->rsrc_update.nr_args)
7799 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7803 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7804 unsigned int issue_flags)
7806 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7811 if (!req->ctx->file_data)
7814 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7815 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7825 ret = io_fixed_fd_install(req, issue_flags, file,
7826 IORING_FILE_INDEX_ALLOC);
7829 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
7830 __io_close_fixed(req, issue_flags, ret);
7841 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7843 struct io_ring_ctx *ctx = req->ctx;
7844 struct io_uring_rsrc_update2 up;
7847 up.offset = req->rsrc_update.offset;
7848 up.data = req->rsrc_update.arg;
7854 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
7855 ret = io_files_update_with_index_alloc(req, issue_flags);
7857 io_ring_submit_lock(ctx, issue_flags);
7858 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
7859 &up, req->rsrc_update.nr_args);
7860 io_ring_submit_unlock(ctx, issue_flags);
7865 __io_req_complete(req, issue_flags, ret, 0);
7869 static int io_req_prep_async(struct io_kiocb *req)
7871 const struct io_op_def *def = &io_op_defs[req->opcode];
7873 /* assign early for deferred execution for non-fixed file */
7874 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
7875 req->file = io_file_get_normal(req, req->cqe.fd);
7876 if (!def->prep_async)
7878 if (WARN_ON_ONCE(req_has_async_data(req)))
7880 if (io_alloc_async_data(req))
7883 return def->prep_async(req);
7886 static u32 io_get_sequence(struct io_kiocb *req)
7888 u32 seq = req->ctx->cached_sq_head;
7889 struct io_kiocb *cur;
7891 /* need original cached_sq_head, but it was increased for each req */
7892 io_for_each_link(cur, req)
7897 static __cold void io_drain_req(struct io_kiocb *req)
7899 struct io_ring_ctx *ctx = req->ctx;
7900 struct io_defer_entry *de;
7902 u32 seq = io_get_sequence(req);
7904 /* Still need defer if there is pending req in defer list. */
7905 spin_lock(&ctx->completion_lock);
7906 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7907 spin_unlock(&ctx->completion_lock);
7909 ctx->drain_active = false;
7910 io_req_task_queue(req);
7913 spin_unlock(&ctx->completion_lock);
7915 ret = io_req_prep_async(req);
7918 io_req_complete_failed(req, ret);
7921 io_prep_async_link(req);
7922 de = kmalloc(sizeof(*de), GFP_KERNEL);
7928 spin_lock(&ctx->completion_lock);
7929 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7930 spin_unlock(&ctx->completion_lock);
7935 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7938 list_add_tail(&de->list, &ctx->defer_list);
7939 spin_unlock(&ctx->completion_lock);
7942 static void io_clean_op(struct io_kiocb *req)
7944 if (req->flags & REQ_F_BUFFER_SELECTED) {
7945 spin_lock(&req->ctx->completion_lock);
7946 io_put_kbuf_comp(req);
7947 spin_unlock(&req->ctx->completion_lock);
7950 if (req->flags & REQ_F_NEED_CLEANUP) {
7951 switch (req->opcode) {
7952 case IORING_OP_READV:
7953 case IORING_OP_READ_FIXED:
7954 case IORING_OP_READ:
7955 case IORING_OP_WRITEV:
7956 case IORING_OP_WRITE_FIXED:
7957 case IORING_OP_WRITE: {
7958 struct io_async_rw *io = req->async_data;
7960 kfree(io->free_iovec);
7963 case IORING_OP_RECVMSG:
7964 case IORING_OP_SENDMSG: {
7965 struct io_async_msghdr *io = req->async_data;
7967 kfree(io->free_iov);
7970 case IORING_OP_OPENAT:
7971 case IORING_OP_OPENAT2:
7972 if (req->open.filename)
7973 putname(req->open.filename);
7975 case IORING_OP_RENAMEAT:
7976 putname(req->rename.oldpath);
7977 putname(req->rename.newpath);
7979 case IORING_OP_UNLINKAT:
7980 putname(req->unlink.filename);
7982 case IORING_OP_MKDIRAT:
7983 putname(req->mkdir.filename);
7985 case IORING_OP_SYMLINKAT:
7986 putname(req->symlink.oldpath);
7987 putname(req->symlink.newpath);
7989 case IORING_OP_LINKAT:
7990 putname(req->hardlink.oldpath);
7991 putname(req->hardlink.newpath);
7993 case IORING_OP_STATX:
7994 if (req->statx.filename)
7995 putname(req->statx.filename);
7997 case IORING_OP_SETXATTR:
7998 case IORING_OP_FSETXATTR:
7999 case IORING_OP_GETXATTR:
8000 case IORING_OP_FGETXATTR:
8001 __io_xattr_finish(req);
8005 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8006 kfree(req->apoll->double_poll);
8010 if (req->flags & REQ_F_INFLIGHT) {
8011 struct io_uring_task *tctx = req->task->io_uring;
8013 atomic_dec(&tctx->inflight_tracked);
8015 if (req->flags & REQ_F_CREDS)
8016 put_cred(req->creds);
8017 if (req->flags & REQ_F_ASYNC_DATA) {
8018 kfree(req->async_data);
8019 req->async_data = NULL;
8021 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8024 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8026 if (req->file || !io_op_defs[req->opcode].needs_file)
8029 if (req->flags & REQ_F_FIXED_FILE)
8030 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8032 req->file = io_file_get_normal(req, req->cqe.fd);
8037 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8039 const struct io_op_def *def = &io_op_defs[req->opcode];
8040 const struct cred *creds = NULL;
8043 if (unlikely(!io_assign_file(req, issue_flags)))
8046 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8047 creds = override_creds(req->creds);
8049 if (!def->audit_skip)
8050 audit_uring_entry(req->opcode);
8052 ret = def->issue(req, issue_flags);
8054 if (!def->audit_skip)
8055 audit_uring_exit(!ret, ret);
8058 revert_creds(creds);
8061 /* If the op doesn't have a file, we're not polling for it */
8062 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8063 io_iopoll_req_issued(req, issue_flags);
8068 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8070 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8072 req = io_put_req_find_next(req);
8073 return req ? &req->work : NULL;
8076 static void io_wq_submit_work(struct io_wq_work *work)
8078 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8079 const struct io_op_def *def = &io_op_defs[req->opcode];
8080 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8081 bool needs_poll = false;
8082 int ret = 0, err = -ECANCELED;
8084 /* one will be dropped by ->io_free_work() after returning to io-wq */
8085 if (!(req->flags & REQ_F_REFCOUNT))
8086 __io_req_set_refcount(req, 2);
8090 io_arm_ltimeout(req);
8092 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8093 if (work->flags & IO_WQ_WORK_CANCEL) {
8095 io_req_task_queue_fail(req, err);
8098 if (!io_assign_file(req, issue_flags)) {
8100 work->flags |= IO_WQ_WORK_CANCEL;
8104 if (req->flags & REQ_F_FORCE_ASYNC) {
8105 bool opcode_poll = def->pollin || def->pollout;
8107 if (opcode_poll && file_can_poll(req->file)) {
8109 issue_flags |= IO_URING_F_NONBLOCK;
8114 ret = io_issue_sqe(req, issue_flags);
8118 * We can get EAGAIN for iopolled IO even though we're
8119 * forcing a sync submission from here, since we can't
8120 * wait for request slots on the block side.
8123 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8129 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8131 /* aborted or ready, in either case retry blocking */
8133 issue_flags &= ~IO_URING_F_NONBLOCK;
8136 /* avoid locking problems by failing it from a clean context */
8138 io_req_task_queue_fail(req, ret);
8141 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8144 return &table->files[i];
8147 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8150 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8152 return (struct file *) (slot->file_ptr & FFS_MASK);
8155 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8157 unsigned long file_ptr = (unsigned long) file;
8159 file_ptr |= io_file_get_flags(file);
8160 file_slot->file_ptr = file_ptr;
8163 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8164 unsigned int issue_flags)
8166 struct io_ring_ctx *ctx = req->ctx;
8167 struct file *file = NULL;
8168 unsigned long file_ptr;
8170 io_ring_submit_lock(ctx, issue_flags);
8172 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8174 fd = array_index_nospec(fd, ctx->nr_user_files);
8175 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8176 file = (struct file *) (file_ptr & FFS_MASK);
8177 file_ptr &= ~FFS_MASK;
8178 /* mask in overlapping REQ_F and FFS bits */
8179 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8180 io_req_set_rsrc_node(req, ctx, 0);
8181 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8183 io_ring_submit_unlock(ctx, issue_flags);
8187 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8189 struct file *file = fget(fd);
8191 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8193 /* we don't allow fixed io_uring files */
8194 if (file && file->f_op == &io_uring_fops)
8195 io_req_track_inflight(req);
8199 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8201 struct io_kiocb *prev = req->timeout.prev;
8205 if (!(req->task->flags & PF_EXITING)) {
8206 struct io_cancel_data cd = {
8208 .data = prev->cqe.user_data,
8211 ret = io_try_cancel(req, &cd);
8213 io_req_complete_post(req, ret ?: -ETIME, 0);
8216 io_req_complete_post(req, -ETIME, 0);
8220 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8222 struct io_timeout_data *data = container_of(timer,
8223 struct io_timeout_data, timer);
8224 struct io_kiocb *prev, *req = data->req;
8225 struct io_ring_ctx *ctx = req->ctx;
8226 unsigned long flags;
8228 spin_lock_irqsave(&ctx->timeout_lock, flags);
8229 prev = req->timeout.head;
8230 req->timeout.head = NULL;
8233 * We don't expect the list to be empty, that will only happen if we
8234 * race with the completion of the linked work.
8237 io_remove_next_linked(prev);
8238 if (!req_ref_inc_not_zero(prev))
8241 list_del(&req->timeout.list);
8242 req->timeout.prev = prev;
8243 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8245 req->io_task_work.func = io_req_task_link_timeout;
8246 io_req_task_work_add(req);
8247 return HRTIMER_NORESTART;
8250 static void io_queue_linked_timeout(struct io_kiocb *req)
8252 struct io_ring_ctx *ctx = req->ctx;
8254 spin_lock_irq(&ctx->timeout_lock);
8256 * If the back reference is NULL, then our linked request finished
8257 * before we got a chance to setup the timer
8259 if (req->timeout.head) {
8260 struct io_timeout_data *data = req->async_data;
8262 data->timer.function = io_link_timeout_fn;
8263 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8265 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8267 spin_unlock_irq(&ctx->timeout_lock);
8268 /* drop submission reference */
8272 static void io_queue_async(struct io_kiocb *req, int ret)
8273 __must_hold(&req->ctx->uring_lock)
8275 struct io_kiocb *linked_timeout;
8277 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8278 io_req_complete_failed(req, ret);
8282 linked_timeout = io_prep_linked_timeout(req);
8284 switch (io_arm_poll_handler(req, 0)) {
8285 case IO_APOLL_READY:
8286 io_req_task_queue(req);
8288 case IO_APOLL_ABORTED:
8290 * Queued up for async execution, worker will release
8291 * submit reference when the iocb is actually submitted.
8293 io_kbuf_recycle(req, 0);
8294 io_queue_iowq(req, NULL);
8301 io_queue_linked_timeout(linked_timeout);
8304 static inline void io_queue_sqe(struct io_kiocb *req)
8305 __must_hold(&req->ctx->uring_lock)
8309 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8311 if (req->flags & REQ_F_COMPLETE_INLINE) {
8312 io_req_add_compl_list(req);
8316 * We async punt it if the file wasn't marked NOWAIT, or if the file
8317 * doesn't support non-blocking read/write attempts
8320 io_arm_ltimeout(req);
8322 io_queue_async(req, ret);
8325 static void io_queue_sqe_fallback(struct io_kiocb *req)
8326 __must_hold(&req->ctx->uring_lock)
8328 if (unlikely(req->flags & REQ_F_FAIL)) {
8330 * We don't submit, fail them all, for that replace hardlinks
8331 * with normal links. Extra REQ_F_LINK is tolerated.
8333 req->flags &= ~REQ_F_HARDLINK;
8334 req->flags |= REQ_F_LINK;
8335 io_req_complete_failed(req, req->cqe.res);
8336 } else if (unlikely(req->ctx->drain_active)) {
8339 int ret = io_req_prep_async(req);
8342 io_req_complete_failed(req, ret);
8344 io_queue_iowq(req, NULL);
8349 * Check SQE restrictions (opcode and flags).
8351 * Returns 'true' if SQE is allowed, 'false' otherwise.
8353 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8354 struct io_kiocb *req,
8355 unsigned int sqe_flags)
8357 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8360 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8361 ctx->restrictions.sqe_flags_required)
8364 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8365 ctx->restrictions.sqe_flags_required))
8371 static void io_init_req_drain(struct io_kiocb *req)
8373 struct io_ring_ctx *ctx = req->ctx;
8374 struct io_kiocb *head = ctx->submit_state.link.head;
8376 ctx->drain_active = true;
8379 * If we need to drain a request in the middle of a link, drain
8380 * the head request and the next request/link after the current
8381 * link. Considering sequential execution of links,
8382 * REQ_F_IO_DRAIN will be maintained for every request of our
8385 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8386 ctx->drain_next = true;
8390 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8391 const struct io_uring_sqe *sqe)
8392 __must_hold(&ctx->uring_lock)
8394 const struct io_op_def *def;
8395 unsigned int sqe_flags;
8399 /* req is partially pre-initialised, see io_preinit_req() */
8400 req->opcode = opcode = READ_ONCE(sqe->opcode);
8401 /* same numerical values with corresponding REQ_F_*, safe to copy */
8402 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8403 req->cqe.user_data = READ_ONCE(sqe->user_data);
8405 req->rsrc_node = NULL;
8406 req->task = current;
8408 if (unlikely(opcode >= IORING_OP_LAST)) {
8412 def = &io_op_defs[opcode];
8413 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8414 /* enforce forwards compatibility on users */
8415 if (sqe_flags & ~SQE_VALID_FLAGS)
8417 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8418 if (!def->buffer_select)
8420 req->buf_index = READ_ONCE(sqe->buf_group);
8422 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8423 ctx->drain_disabled = true;
8424 if (sqe_flags & IOSQE_IO_DRAIN) {
8425 if (ctx->drain_disabled)
8427 io_init_req_drain(req);
8430 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8431 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8433 /* knock it to the slow queue path, will be drained there */
8434 if (ctx->drain_active)
8435 req->flags |= REQ_F_FORCE_ASYNC;
8436 /* if there is no link, we're at "next" request and need to drain */
8437 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8438 ctx->drain_next = false;
8439 ctx->drain_active = true;
8440 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8444 if (!def->ioprio && sqe->ioprio)
8446 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8449 if (def->needs_file) {
8450 struct io_submit_state *state = &ctx->submit_state;
8452 req->cqe.fd = READ_ONCE(sqe->fd);
8455 * Plug now if we have more than 2 IO left after this, and the
8456 * target is potentially a read/write to block based storage.
8458 if (state->need_plug && def->plug) {
8459 state->plug_started = true;
8460 state->need_plug = false;
8461 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8465 personality = READ_ONCE(sqe->personality);
8469 req->creds = xa_load(&ctx->personalities, personality);
8472 get_cred(req->creds);
8473 ret = security_uring_override_creds(req->creds);
8475 put_cred(req->creds);
8478 req->flags |= REQ_F_CREDS;
8481 return def->prep(req, sqe);
8484 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8485 struct io_kiocb *req, int ret)
8487 struct io_ring_ctx *ctx = req->ctx;
8488 struct io_submit_link *link = &ctx->submit_state.link;
8489 struct io_kiocb *head = link->head;
8491 trace_io_uring_req_failed(sqe, ctx, req, ret);
8494 * Avoid breaking links in the middle as it renders links with SQPOLL
8495 * unusable. Instead of failing eagerly, continue assembling the link if
8496 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8497 * should find the flag and handle the rest.
8499 req_fail_link_node(req, ret);
8500 if (head && !(head->flags & REQ_F_FAIL))
8501 req_fail_link_node(head, -ECANCELED);
8503 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8505 link->last->link = req;
8509 io_queue_sqe_fallback(req);
8514 link->last->link = req;
8521 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8522 const struct io_uring_sqe *sqe)
8523 __must_hold(&ctx->uring_lock)
8525 struct io_submit_link *link = &ctx->submit_state.link;
8528 ret = io_init_req(ctx, req, sqe);
8530 return io_submit_fail_init(sqe, req, ret);
8532 /* don't need @sqe from now on */
8533 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8535 ctx->flags & IORING_SETUP_SQPOLL);
8538 * If we already have a head request, queue this one for async
8539 * submittal once the head completes. If we don't have a head but
8540 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8541 * submitted sync once the chain is complete. If none of those
8542 * conditions are true (normal request), then just queue it.
8544 if (unlikely(link->head)) {
8545 ret = io_req_prep_async(req);
8547 return io_submit_fail_init(sqe, req, ret);
8549 trace_io_uring_link(ctx, req, link->head);
8550 link->last->link = req;
8553 if (req->flags & IO_REQ_LINK_FLAGS)
8555 /* last request of the link, flush it */
8558 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8561 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8562 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8563 if (req->flags & IO_REQ_LINK_FLAGS) {
8568 io_queue_sqe_fallback(req);
8578 * Batched submission is done, ensure local IO is flushed out.
8580 static void io_submit_state_end(struct io_ring_ctx *ctx)
8582 struct io_submit_state *state = &ctx->submit_state;
8584 if (unlikely(state->link.head))
8585 io_queue_sqe_fallback(state->link.head);
8586 /* flush only after queuing links as they can generate completions */
8587 io_submit_flush_completions(ctx);
8588 if (state->plug_started)
8589 blk_finish_plug(&state->plug);
8593 * Start submission side cache.
8595 static void io_submit_state_start(struct io_submit_state *state,
8596 unsigned int max_ios)
8598 state->plug_started = false;
8599 state->need_plug = max_ios > 2;
8600 state->submit_nr = max_ios;
8601 /* set only head, no need to init link_last in advance */
8602 state->link.head = NULL;
8605 static void io_commit_sqring(struct io_ring_ctx *ctx)
8607 struct io_rings *rings = ctx->rings;
8610 * Ensure any loads from the SQEs are done at this point,
8611 * since once we write the new head, the application could
8612 * write new data to them.
8614 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
8618 * Fetch an sqe, if one is available. Note this returns a pointer to memory
8619 * that is mapped by userspace. This means that care needs to be taken to
8620 * ensure that reads are stable, as we cannot rely on userspace always
8621 * being a good citizen. If members of the sqe are validated and then later
8622 * used, it's important that those reads are done through READ_ONCE() to
8623 * prevent a re-load down the line.
8625 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
8627 unsigned head, mask = ctx->sq_entries - 1;
8628 unsigned sq_idx = ctx->cached_sq_head++ & mask;
8631 * The cached sq head (or cq tail) serves two purposes:
8633 * 1) allows us to batch the cost of updating the user visible
8635 * 2) allows the kernel side to track the head on its own, even
8636 * though the application is the one updating it.
8638 head = READ_ONCE(ctx->sq_array[sq_idx]);
8639 if (likely(head < ctx->sq_entries)) {
8640 /* double index for 128-byte SQEs, twice as long */
8641 if (ctx->flags & IORING_SETUP_SQE128)
8643 return &ctx->sq_sqes[head];
8646 /* drop invalid entries */
8648 WRITE_ONCE(ctx->rings->sq_dropped,
8649 READ_ONCE(ctx->rings->sq_dropped) + 1);
8653 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
8654 __must_hold(&ctx->uring_lock)
8656 unsigned int entries = io_sqring_entries(ctx);
8660 if (unlikely(!entries))
8662 /* make sure SQ entry isn't read before tail */
8663 ret = left = min3(nr, ctx->sq_entries, entries);
8664 io_get_task_refs(left);
8665 io_submit_state_start(&ctx->submit_state, left);
8668 const struct io_uring_sqe *sqe;
8669 struct io_kiocb *req;
8671 if (unlikely(!io_alloc_req_refill(ctx)))
8673 req = io_alloc_req(ctx);
8674 sqe = io_get_sqe(ctx);
8675 if (unlikely(!sqe)) {
8676 io_req_add_to_cache(req, ctx);
8681 * Continue submitting even for sqe failure if the
8682 * ring was setup with IORING_SETUP_SUBMIT_ALL
8684 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
8685 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
8691 if (unlikely(left)) {
8693 /* try again if it submitted nothing and can't allocate a req */
8694 if (!ret && io_req_cache_empty(ctx))
8696 current->io_uring->cached_refs += left;
8699 io_submit_state_end(ctx);
8700 /* Commit SQ ring head once we've consumed and submitted all SQEs */
8701 io_commit_sqring(ctx);
8705 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
8707 return READ_ONCE(sqd->state);
8710 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
8712 unsigned int to_submit;
8715 to_submit = io_sqring_entries(ctx);
8716 /* if we're handling multiple rings, cap submit size for fairness */
8717 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
8718 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
8720 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
8721 const struct cred *creds = NULL;
8723 if (ctx->sq_creds != current_cred())
8724 creds = override_creds(ctx->sq_creds);
8726 mutex_lock(&ctx->uring_lock);
8727 if (!wq_list_empty(&ctx->iopoll_list))
8728 io_do_iopoll(ctx, true);
8731 * Don't submit if refs are dying, good for io_uring_register(),
8732 * but also it is relied upon by io_ring_exit_work()
8734 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
8735 !(ctx->flags & IORING_SETUP_R_DISABLED))
8736 ret = io_submit_sqes(ctx, to_submit);
8737 mutex_unlock(&ctx->uring_lock);
8739 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8740 wake_up(&ctx->sqo_sq_wait);
8742 revert_creds(creds);
8748 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8750 struct io_ring_ctx *ctx;
8751 unsigned sq_thread_idle = 0;
8753 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8754 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8755 sqd->sq_thread_idle = sq_thread_idle;
8758 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8760 bool did_sig = false;
8761 struct ksignal ksig;
8763 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8764 signal_pending(current)) {
8765 mutex_unlock(&sqd->lock);
8766 if (signal_pending(current))
8767 did_sig = get_signal(&ksig);
8769 mutex_lock(&sqd->lock);
8771 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8774 static int io_sq_thread(void *data)
8776 struct io_sq_data *sqd = data;
8777 struct io_ring_ctx *ctx;
8778 unsigned long timeout = 0;
8779 char buf[TASK_COMM_LEN];
8782 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8783 set_task_comm(current, buf);
8785 if (sqd->sq_cpu != -1)
8786 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8788 set_cpus_allowed_ptr(current, cpu_online_mask);
8789 current->flags |= PF_NO_SETAFFINITY;
8791 audit_alloc_kernel(current);
8793 mutex_lock(&sqd->lock);
8795 bool cap_entries, sqt_spin = false;
8797 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8798 if (io_sqd_handle_event(sqd))
8800 timeout = jiffies + sqd->sq_thread_idle;
8803 cap_entries = !list_is_singular(&sqd->ctx_list);
8804 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8805 int ret = __io_sq_thread(ctx, cap_entries);
8807 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8810 if (io_run_task_work())
8813 if (sqt_spin || !time_after(jiffies, timeout)) {
8816 timeout = jiffies + sqd->sq_thread_idle;
8820 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8821 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8822 bool needs_sched = true;
8824 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8825 atomic_or(IORING_SQ_NEED_WAKEUP,
8826 &ctx->rings->sq_flags);
8827 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8828 !wq_list_empty(&ctx->iopoll_list)) {
8829 needs_sched = false;
8834 * Ensure the store of the wakeup flag is not
8835 * reordered with the load of the SQ tail
8837 smp_mb__after_atomic();
8839 if (io_sqring_entries(ctx)) {
8840 needs_sched = false;
8846 mutex_unlock(&sqd->lock);
8848 mutex_lock(&sqd->lock);
8850 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8851 atomic_andnot(IORING_SQ_NEED_WAKEUP,
8852 &ctx->rings->sq_flags);
8855 finish_wait(&sqd->wait, &wait);
8856 timeout = jiffies + sqd->sq_thread_idle;
8859 io_uring_cancel_generic(true, sqd);
8861 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8862 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
8864 mutex_unlock(&sqd->lock);
8866 audit_free(current);
8868 complete(&sqd->exited);
8872 struct io_wait_queue {
8873 struct wait_queue_entry wq;
8874 struct io_ring_ctx *ctx;
8876 unsigned nr_timeouts;
8879 static inline bool io_should_wake(struct io_wait_queue *iowq)
8881 struct io_ring_ctx *ctx = iowq->ctx;
8882 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8885 * Wake up if we have enough events, or if a timeout occurred since we
8886 * started waiting. For timeouts, we always want to return to userspace,
8887 * regardless of event count.
8889 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8892 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8893 int wake_flags, void *key)
8895 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8899 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8900 * the task, and the next invocation will do it.
8902 if (io_should_wake(iowq) ||
8903 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
8904 return autoremove_wake_function(curr, mode, wake_flags, key);
8908 static int io_run_task_work_sig(void)
8910 if (io_run_task_work())
8912 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8913 return -ERESTARTSYS;
8914 if (task_sigpending(current))
8919 /* when returns >0, the caller should retry */
8920 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8921 struct io_wait_queue *iowq,
8925 unsigned long check_cq;
8927 /* make sure we run task_work before checking for signals */
8928 ret = io_run_task_work_sig();
8929 if (ret || io_should_wake(iowq))
8931 check_cq = READ_ONCE(ctx->check_cq);
8932 /* let the caller flush overflows, retry */
8933 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
8935 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
8937 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8943 * Wait until events become available, if we don't already have some. The
8944 * application must reap them itself, as they reside on the shared cq ring.
8946 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8947 const sigset_t __user *sig, size_t sigsz,
8948 struct __kernel_timespec __user *uts)
8950 struct io_wait_queue iowq;
8951 struct io_rings *rings = ctx->rings;
8952 ktime_t timeout = KTIME_MAX;
8956 io_cqring_overflow_flush(ctx);
8957 if (io_cqring_events(ctx) >= min_events)
8959 if (!io_run_task_work())
8964 #ifdef CONFIG_COMPAT
8965 if (in_compat_syscall())
8966 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8970 ret = set_user_sigmask(sig, sigsz);
8977 struct timespec64 ts;
8979 if (get_timespec64(&ts, uts))
8981 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8984 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8985 iowq.wq.private = current;
8986 INIT_LIST_HEAD(&iowq.wq.entry);
8988 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8989 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8991 trace_io_uring_cqring_wait(ctx, min_events);
8993 /* if we can't even flush overflow, don't wait for more */
8994 if (!io_cqring_overflow_flush(ctx)) {
8998 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8999 TASK_INTERRUPTIBLE);
9000 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9004 finish_wait(&ctx->cq_wait, &iowq.wq);
9005 restore_saved_sigmask_unless(ret == -EINTR);
9007 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9010 static void io_free_page_table(void **table, size_t size)
9012 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9014 for (i = 0; i < nr_tables; i++)
9019 static __cold void **io_alloc_page_table(size_t size)
9021 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9022 size_t init_size = size;
9025 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9029 for (i = 0; i < nr_tables; i++) {
9030 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9032 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9034 io_free_page_table(table, init_size);
9042 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9044 percpu_ref_exit(&ref_node->refs);
9048 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9050 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9051 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9052 unsigned long flags;
9053 bool first_add = false;
9054 unsigned long delay = HZ;
9056 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9059 /* if we are mid-quiesce then do not delay */
9060 if (node->rsrc_data->quiesce)
9063 while (!list_empty(&ctx->rsrc_ref_list)) {
9064 node = list_first_entry(&ctx->rsrc_ref_list,
9065 struct io_rsrc_node, node);
9066 /* recycle ref nodes in order */
9069 list_del(&node->node);
9070 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9072 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9075 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9078 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9080 struct io_rsrc_node *ref_node;
9082 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9086 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9091 INIT_LIST_HEAD(&ref_node->node);
9092 INIT_LIST_HEAD(&ref_node->rsrc_list);
9093 ref_node->done = false;
9097 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9098 struct io_rsrc_data *data_to_kill)
9099 __must_hold(&ctx->uring_lock)
9101 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9102 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9104 io_rsrc_refs_drop(ctx);
9107 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9109 rsrc_node->rsrc_data = data_to_kill;
9110 spin_lock_irq(&ctx->rsrc_ref_lock);
9111 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9112 spin_unlock_irq(&ctx->rsrc_ref_lock);
9114 atomic_inc(&data_to_kill->refs);
9115 percpu_ref_kill(&rsrc_node->refs);
9116 ctx->rsrc_node = NULL;
9119 if (!ctx->rsrc_node) {
9120 ctx->rsrc_node = ctx->rsrc_backup_node;
9121 ctx->rsrc_backup_node = NULL;
9125 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9127 if (ctx->rsrc_backup_node)
9129 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9130 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9133 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9134 struct io_ring_ctx *ctx)
9138 /* As we may drop ->uring_lock, other task may have started quiesce */
9142 data->quiesce = true;
9144 ret = io_rsrc_node_switch_start(ctx);
9147 io_rsrc_node_switch(ctx, data);
9149 /* kill initial ref, already quiesced if zero */
9150 if (atomic_dec_and_test(&data->refs))
9152 mutex_unlock(&ctx->uring_lock);
9153 flush_delayed_work(&ctx->rsrc_put_work);
9154 ret = wait_for_completion_interruptible(&data->done);
9156 mutex_lock(&ctx->uring_lock);
9157 if (atomic_read(&data->refs) > 0) {
9159 * it has been revived by another thread while
9162 mutex_unlock(&ctx->uring_lock);
9168 atomic_inc(&data->refs);
9169 /* wait for all works potentially completing data->done */
9170 flush_delayed_work(&ctx->rsrc_put_work);
9171 reinit_completion(&data->done);
9173 ret = io_run_task_work_sig();
9174 mutex_lock(&ctx->uring_lock);
9176 data->quiesce = false;
9181 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9183 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9184 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9186 return &data->tags[table_idx][off];
9189 static void io_rsrc_data_free(struct io_rsrc_data *data)
9191 size_t size = data->nr * sizeof(data->tags[0][0]);
9194 io_free_page_table((void **)data->tags, size);
9198 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9199 u64 __user *utags, unsigned nr,
9200 struct io_rsrc_data **pdata)
9202 struct io_rsrc_data *data;
9206 data = kzalloc(sizeof(*data), GFP_KERNEL);
9209 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9217 data->do_put = do_put;
9220 for (i = 0; i < nr; i++) {
9221 u64 *tag_slot = io_get_tag_slot(data, i);
9223 if (copy_from_user(tag_slot, &utags[i],
9229 atomic_set(&data->refs, 1);
9230 init_completion(&data->done);
9234 io_rsrc_data_free(data);
9238 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9240 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9241 GFP_KERNEL_ACCOUNT);
9242 if (unlikely(!table->files))
9245 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9246 if (unlikely(!table->bitmap)) {
9247 kvfree(table->files);
9254 static void io_free_file_tables(struct io_file_table *table)
9256 kvfree(table->files);
9257 bitmap_free(table->bitmap);
9258 table->files = NULL;
9259 table->bitmap = NULL;
9262 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9264 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9265 __set_bit(bit, table->bitmap);
9266 table->alloc_hint = bit + 1;
9269 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9271 __clear_bit(bit, table->bitmap);
9272 table->alloc_hint = bit;
9275 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9277 #if !defined(IO_URING_SCM_ALL)
9280 for (i = 0; i < ctx->nr_user_files; i++) {
9281 struct file *file = io_file_from_index(ctx, i);
9285 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9287 io_file_bitmap_clear(&ctx->file_table, i);
9292 #if defined(CONFIG_UNIX)
9293 if (ctx->ring_sock) {
9294 struct sock *sock = ctx->ring_sock->sk;
9295 struct sk_buff *skb;
9297 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9301 io_free_file_tables(&ctx->file_table);
9302 io_rsrc_data_free(ctx->file_data);
9303 ctx->file_data = NULL;
9304 ctx->nr_user_files = 0;
9307 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9309 unsigned nr = ctx->nr_user_files;
9312 if (!ctx->file_data)
9316 * Quiesce may unlock ->uring_lock, and while it's not held
9317 * prevent new requests using the table.
9319 ctx->nr_user_files = 0;
9320 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9321 ctx->nr_user_files = nr;
9323 __io_sqe_files_unregister(ctx);
9327 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9328 __releases(&sqd->lock)
9330 WARN_ON_ONCE(sqd->thread == current);
9333 * Do the dance but not conditional clear_bit() because it'd race with
9334 * other threads incrementing park_pending and setting the bit.
9336 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9337 if (atomic_dec_return(&sqd->park_pending))
9338 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9339 mutex_unlock(&sqd->lock);
9342 static void io_sq_thread_park(struct io_sq_data *sqd)
9343 __acquires(&sqd->lock)
9345 WARN_ON_ONCE(sqd->thread == current);
9347 atomic_inc(&sqd->park_pending);
9348 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9349 mutex_lock(&sqd->lock);
9351 wake_up_process(sqd->thread);
9354 static void io_sq_thread_stop(struct io_sq_data *sqd)
9356 WARN_ON_ONCE(sqd->thread == current);
9357 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9359 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9360 mutex_lock(&sqd->lock);
9362 wake_up_process(sqd->thread);
9363 mutex_unlock(&sqd->lock);
9364 wait_for_completion(&sqd->exited);
9367 static void io_put_sq_data(struct io_sq_data *sqd)
9369 if (refcount_dec_and_test(&sqd->refs)) {
9370 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9372 io_sq_thread_stop(sqd);
9377 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9379 struct io_sq_data *sqd = ctx->sq_data;
9382 io_sq_thread_park(sqd);
9383 list_del_init(&ctx->sqd_list);
9384 io_sqd_update_thread_idle(sqd);
9385 io_sq_thread_unpark(sqd);
9387 io_put_sq_data(sqd);
9388 ctx->sq_data = NULL;
9392 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9394 struct io_ring_ctx *ctx_attach;
9395 struct io_sq_data *sqd;
9398 f = fdget(p->wq_fd);
9400 return ERR_PTR(-ENXIO);
9401 if (f.file->f_op != &io_uring_fops) {
9403 return ERR_PTR(-EINVAL);
9406 ctx_attach = f.file->private_data;
9407 sqd = ctx_attach->sq_data;
9410 return ERR_PTR(-EINVAL);
9412 if (sqd->task_tgid != current->tgid) {
9414 return ERR_PTR(-EPERM);
9417 refcount_inc(&sqd->refs);
9422 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9425 struct io_sq_data *sqd;
9428 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9429 sqd = io_attach_sq_data(p);
9434 /* fall through for EPERM case, setup new sqd/task */
9435 if (PTR_ERR(sqd) != -EPERM)
9439 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9441 return ERR_PTR(-ENOMEM);
9443 atomic_set(&sqd->park_pending, 0);
9444 refcount_set(&sqd->refs, 1);
9445 INIT_LIST_HEAD(&sqd->ctx_list);
9446 mutex_init(&sqd->lock);
9447 init_waitqueue_head(&sqd->wait);
9448 init_completion(&sqd->exited);
9453 * Ensure the UNIX gc is aware of our file set, so we are certain that
9454 * the io_uring can be safely unregistered on process exit, even if we have
9455 * loops in the file referencing. We account only files that can hold other
9456 * files because otherwise they can't form a loop and so are not interesting
9459 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9461 #if defined(CONFIG_UNIX)
9462 struct sock *sk = ctx->ring_sock->sk;
9463 struct sk_buff_head *head = &sk->sk_receive_queue;
9464 struct scm_fp_list *fpl;
9465 struct sk_buff *skb;
9467 if (likely(!io_file_need_scm(file)))
9471 * See if we can merge this file into an existing skb SCM_RIGHTS
9472 * file set. If there's no room, fall back to allocating a new skb
9473 * and filling it in.
9475 spin_lock_irq(&head->lock);
9476 skb = skb_peek(head);
9477 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9478 __skb_unlink(skb, head);
9481 spin_unlock_irq(&head->lock);
9484 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9488 skb = alloc_skb(0, GFP_KERNEL);
9494 fpl->user = get_uid(current_user());
9495 fpl->max = SCM_MAX_FD;
9498 UNIXCB(skb).fp = fpl;
9500 skb->destructor = unix_destruct_scm;
9501 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9504 fpl = UNIXCB(skb).fp;
9505 fpl->fp[fpl->count++] = get_file(file);
9506 unix_inflight(fpl->user, file);
9507 skb_queue_head(head, skb);
9513 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9515 struct file *file = prsrc->file;
9516 #if defined(CONFIG_UNIX)
9517 struct sock *sock = ctx->ring_sock->sk;
9518 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9519 struct sk_buff *skb;
9522 if (!io_file_need_scm(file)) {
9527 __skb_queue_head_init(&list);
9530 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9531 * remove this entry and rearrange the file array.
9533 skb = skb_dequeue(head);
9535 struct scm_fp_list *fp;
9537 fp = UNIXCB(skb).fp;
9538 for (i = 0; i < fp->count; i++) {
9541 if (fp->fp[i] != file)
9544 unix_notinflight(fp->user, fp->fp[i]);
9545 left = fp->count - 1 - i;
9547 memmove(&fp->fp[i], &fp->fp[i + 1],
9548 left * sizeof(struct file *));
9555 __skb_queue_tail(&list, skb);
9565 __skb_queue_tail(&list, skb);
9567 skb = skb_dequeue(head);
9570 if (skb_peek(&list)) {
9571 spin_lock_irq(&head->lock);
9572 while ((skb = __skb_dequeue(&list)) != NULL)
9573 __skb_queue_tail(head, skb);
9574 spin_unlock_irq(&head->lock);
9581 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9583 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9584 struct io_ring_ctx *ctx = rsrc_data->ctx;
9585 struct io_rsrc_put *prsrc, *tmp;
9587 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9588 list_del(&prsrc->list);
9591 if (ctx->flags & IORING_SETUP_IOPOLL)
9592 mutex_lock(&ctx->uring_lock);
9594 spin_lock(&ctx->completion_lock);
9595 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9596 io_commit_cqring(ctx);
9597 spin_unlock(&ctx->completion_lock);
9598 io_cqring_ev_posted(ctx);
9600 if (ctx->flags & IORING_SETUP_IOPOLL)
9601 mutex_unlock(&ctx->uring_lock);
9604 rsrc_data->do_put(ctx, prsrc);
9608 io_rsrc_node_destroy(ref_node);
9609 if (atomic_dec_and_test(&rsrc_data->refs))
9610 complete(&rsrc_data->done);
9613 static void io_rsrc_put_work(struct work_struct *work)
9615 struct io_ring_ctx *ctx;
9616 struct llist_node *node;
9618 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
9619 node = llist_del_all(&ctx->rsrc_put_llist);
9622 struct io_rsrc_node *ref_node;
9623 struct llist_node *next = node->next;
9625 ref_node = llist_entry(node, struct io_rsrc_node, llist);
9626 __io_rsrc_put_work(ref_node);
9631 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
9632 unsigned nr_args, u64 __user *tags)
9634 __s32 __user *fds = (__s32 __user *) arg;
9643 if (nr_args > IORING_MAX_FIXED_FILES)
9645 if (nr_args > rlimit(RLIMIT_NOFILE))
9647 ret = io_rsrc_node_switch_start(ctx);
9650 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9655 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
9656 io_rsrc_data_free(ctx->file_data);
9657 ctx->file_data = NULL;
9661 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9662 struct io_fixed_file *file_slot;
9664 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
9668 /* allow sparse sets */
9669 if (!fds || fd == -1) {
9671 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9678 if (unlikely(!file))
9682 * Don't allow io_uring instances to be registered. If UNIX
9683 * isn't enabled, then this causes a reference cycle and this
9684 * instance can never get freed. If UNIX is enabled we'll
9685 * handle it just fine, but there's still no point in allowing
9686 * a ring fd as it doesn't support regular read/write anyway.
9688 if (file->f_op == &io_uring_fops) {
9692 ret = io_scm_file_account(ctx, file);
9697 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9698 io_fixed_file_set(file_slot, file);
9699 io_file_bitmap_set(&ctx->file_table, i);
9702 io_rsrc_node_switch(ctx, NULL);
9705 __io_sqe_files_unregister(ctx);
9709 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9710 struct io_rsrc_node *node, void *rsrc)
9712 u64 *tag_slot = io_get_tag_slot(data, idx);
9713 struct io_rsrc_put *prsrc;
9715 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9719 prsrc->tag = *tag_slot;
9722 list_add(&prsrc->list, &node->rsrc_list);
9726 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9727 unsigned int issue_flags, u32 slot_index)
9728 __must_hold(&req->ctx->uring_lock)
9730 struct io_ring_ctx *ctx = req->ctx;
9731 bool needs_switch = false;
9732 struct io_fixed_file *file_slot;
9735 if (file->f_op == &io_uring_fops)
9737 if (!ctx->file_data)
9739 if (slot_index >= ctx->nr_user_files)
9742 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9743 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9745 if (file_slot->file_ptr) {
9746 struct file *old_file;
9748 ret = io_rsrc_node_switch_start(ctx);
9752 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9753 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9754 ctx->rsrc_node, old_file);
9757 file_slot->file_ptr = 0;
9758 io_file_bitmap_clear(&ctx->file_table, slot_index);
9759 needs_switch = true;
9762 ret = io_scm_file_account(ctx, file);
9764 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9765 io_fixed_file_set(file_slot, file);
9766 io_file_bitmap_set(&ctx->file_table, slot_index);
9770 io_rsrc_node_switch(ctx, ctx->file_data);
9776 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
9777 unsigned int offset)
9779 struct io_ring_ctx *ctx = req->ctx;
9780 struct io_fixed_file *file_slot;
9784 io_ring_submit_lock(ctx, issue_flags);
9786 if (unlikely(!ctx->file_data))
9789 if (offset >= ctx->nr_user_files)
9791 ret = io_rsrc_node_switch_start(ctx);
9795 offset = array_index_nospec(offset, ctx->nr_user_files);
9796 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9798 if (!file_slot->file_ptr)
9801 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9802 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9806 file_slot->file_ptr = 0;
9807 io_file_bitmap_clear(&ctx->file_table, offset);
9808 io_rsrc_node_switch(ctx, ctx->file_data);
9811 io_ring_submit_unlock(ctx, issue_flags);
9815 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9817 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
9820 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9821 struct io_uring_rsrc_update2 *up,
9824 u64 __user *tags = u64_to_user_ptr(up->tags);
9825 __s32 __user *fds = u64_to_user_ptr(up->data);
9826 struct io_rsrc_data *data = ctx->file_data;
9827 struct io_fixed_file *file_slot;
9831 bool needs_switch = false;
9833 if (!ctx->file_data)
9835 if (up->offset + nr_args > ctx->nr_user_files)
9838 for (done = 0; done < nr_args; done++) {
9841 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9842 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9846 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9850 if (fd == IORING_REGISTER_FILES_SKIP)
9853 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9854 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9856 if (file_slot->file_ptr) {
9857 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9858 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9861 file_slot->file_ptr = 0;
9862 io_file_bitmap_clear(&ctx->file_table, i);
9863 needs_switch = true;
9872 * Don't allow io_uring instances to be registered. If
9873 * UNIX isn't enabled, then this causes a reference
9874 * cycle and this instance can never get freed. If UNIX
9875 * is enabled we'll handle it just fine, but there's
9876 * still no point in allowing a ring fd as it doesn't
9877 * support regular read/write anyway.
9879 if (file->f_op == &io_uring_fops) {
9884 err = io_scm_file_account(ctx, file);
9889 *io_get_tag_slot(data, i) = tag;
9890 io_fixed_file_set(file_slot, file);
9891 io_file_bitmap_set(&ctx->file_table, i);
9896 io_rsrc_node_switch(ctx, data);
9897 return done ? done : err;
9900 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9901 struct task_struct *task)
9903 struct io_wq_hash *hash;
9904 struct io_wq_data data;
9905 unsigned int concurrency;
9907 mutex_lock(&ctx->uring_lock);
9908 hash = ctx->hash_map;
9910 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9912 mutex_unlock(&ctx->uring_lock);
9913 return ERR_PTR(-ENOMEM);
9915 refcount_set(&hash->refs, 1);
9916 init_waitqueue_head(&hash->wait);
9917 ctx->hash_map = hash;
9919 mutex_unlock(&ctx->uring_lock);
9923 data.free_work = io_wq_free_work;
9924 data.do_work = io_wq_submit_work;
9926 /* Do QD, or 4 * CPUS, whatever is smallest */
9927 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9929 return io_wq_create(concurrency, &data);
9932 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9933 struct io_ring_ctx *ctx)
9935 struct io_uring_task *tctx;
9938 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9939 if (unlikely(!tctx))
9942 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9943 sizeof(struct file *), GFP_KERNEL);
9944 if (unlikely(!tctx->registered_rings)) {
9949 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9950 if (unlikely(ret)) {
9951 kfree(tctx->registered_rings);
9956 tctx->io_wq = io_init_wq_offload(ctx, task);
9957 if (IS_ERR(tctx->io_wq)) {
9958 ret = PTR_ERR(tctx->io_wq);
9959 percpu_counter_destroy(&tctx->inflight);
9960 kfree(tctx->registered_rings);
9966 init_waitqueue_head(&tctx->wait);
9967 atomic_set(&tctx->in_idle, 0);
9968 atomic_set(&tctx->inflight_tracked, 0);
9969 task->io_uring = tctx;
9970 spin_lock_init(&tctx->task_lock);
9971 INIT_WQ_LIST(&tctx->task_list);
9972 INIT_WQ_LIST(&tctx->prio_task_list);
9973 init_task_work(&tctx->task_work, tctx_task_work);
9977 void __io_uring_free(struct task_struct *tsk)
9979 struct io_uring_task *tctx = tsk->io_uring;
9981 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9982 WARN_ON_ONCE(tctx->io_wq);
9983 WARN_ON_ONCE(tctx->cached_refs);
9985 kfree(tctx->registered_rings);
9986 percpu_counter_destroy(&tctx->inflight);
9988 tsk->io_uring = NULL;
9991 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9992 struct io_uring_params *p)
9996 /* Retain compatibility with failing for an invalid attach attempt */
9997 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9998 IORING_SETUP_ATTACH_WQ) {
10001 f = fdget(p->wq_fd);
10004 if (f.file->f_op != &io_uring_fops) {
10010 if (ctx->flags & IORING_SETUP_SQPOLL) {
10011 struct task_struct *tsk;
10012 struct io_sq_data *sqd;
10015 ret = security_uring_sqpoll();
10019 sqd = io_get_sq_data(p, &attached);
10021 ret = PTR_ERR(sqd);
10025 ctx->sq_creds = get_current_cred();
10026 ctx->sq_data = sqd;
10027 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10028 if (!ctx->sq_thread_idle)
10029 ctx->sq_thread_idle = HZ;
10031 io_sq_thread_park(sqd);
10032 list_add(&ctx->sqd_list, &sqd->ctx_list);
10033 io_sqd_update_thread_idle(sqd);
10034 /* don't attach to a dying SQPOLL thread, would be racy */
10035 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10036 io_sq_thread_unpark(sqd);
10043 if (p->flags & IORING_SETUP_SQ_AFF) {
10044 int cpu = p->sq_thread_cpu;
10047 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10054 sqd->task_pid = current->pid;
10055 sqd->task_tgid = current->tgid;
10056 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10058 ret = PTR_ERR(tsk);
10063 ret = io_uring_alloc_task_context(tsk, ctx);
10064 wake_up_new_task(tsk);
10067 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10068 /* Can't have SQ_AFF without SQPOLL */
10075 complete(&ctx->sq_data->exited);
10077 io_sq_thread_finish(ctx);
10081 static inline void __io_unaccount_mem(struct user_struct *user,
10082 unsigned long nr_pages)
10084 atomic_long_sub(nr_pages, &user->locked_vm);
10087 static inline int __io_account_mem(struct user_struct *user,
10088 unsigned long nr_pages)
10090 unsigned long page_limit, cur_pages, new_pages;
10092 /* Don't allow more pages than we can safely lock */
10093 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10096 cur_pages = atomic_long_read(&user->locked_vm);
10097 new_pages = cur_pages + nr_pages;
10098 if (new_pages > page_limit)
10100 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10101 new_pages) != cur_pages);
10106 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10109 __io_unaccount_mem(ctx->user, nr_pages);
10111 if (ctx->mm_account)
10112 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10115 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10120 ret = __io_account_mem(ctx->user, nr_pages);
10125 if (ctx->mm_account)
10126 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10131 static void io_mem_free(void *ptr)
10138 page = virt_to_head_page(ptr);
10139 if (put_page_testzero(page))
10140 free_compound_page(page);
10143 static void *io_mem_alloc(size_t size)
10145 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10147 return (void *) __get_free_pages(gfp, get_order(size));
10150 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10151 unsigned int cq_entries, size_t *sq_offset)
10153 struct io_rings *rings;
10154 size_t off, sq_array_size;
10156 off = struct_size(rings, cqes, cq_entries);
10157 if (off == SIZE_MAX)
10159 if (ctx->flags & IORING_SETUP_CQE32) {
10160 if (check_shl_overflow(off, 1, &off))
10165 off = ALIGN(off, SMP_CACHE_BYTES);
10173 sq_array_size = array_size(sizeof(u32), sq_entries);
10174 if (sq_array_size == SIZE_MAX)
10177 if (check_add_overflow(off, sq_array_size, &off))
10183 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10185 struct io_mapped_ubuf *imu = *slot;
10188 if (imu != ctx->dummy_ubuf) {
10189 for (i = 0; i < imu->nr_bvecs; i++)
10190 unpin_user_page(imu->bvec[i].bv_page);
10191 if (imu->acct_pages)
10192 io_unaccount_mem(ctx, imu->acct_pages);
10198 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10200 io_buffer_unmap(ctx, &prsrc->buf);
10204 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10208 for (i = 0; i < ctx->nr_user_bufs; i++)
10209 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10210 kfree(ctx->user_bufs);
10211 io_rsrc_data_free(ctx->buf_data);
10212 ctx->user_bufs = NULL;
10213 ctx->buf_data = NULL;
10214 ctx->nr_user_bufs = 0;
10217 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10219 unsigned nr = ctx->nr_user_bufs;
10222 if (!ctx->buf_data)
10226 * Quiesce may unlock ->uring_lock, and while it's not held
10227 * prevent new requests using the table.
10229 ctx->nr_user_bufs = 0;
10230 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10231 ctx->nr_user_bufs = nr;
10233 __io_sqe_buffers_unregister(ctx);
10237 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10238 void __user *arg, unsigned index)
10240 struct iovec __user *src;
10242 #ifdef CONFIG_COMPAT
10244 struct compat_iovec __user *ciovs;
10245 struct compat_iovec ciov;
10247 ciovs = (struct compat_iovec __user *) arg;
10248 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10251 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10252 dst->iov_len = ciov.iov_len;
10256 src = (struct iovec __user *) arg;
10257 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10263 * Not super efficient, but this is just a registration time. And we do cache
10264 * the last compound head, so generally we'll only do a full search if we don't
10267 * We check if the given compound head page has already been accounted, to
10268 * avoid double accounting it. This allows us to account the full size of the
10269 * page, not just the constituent pages of a huge page.
10271 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10272 int nr_pages, struct page *hpage)
10276 /* check current page array */
10277 for (i = 0; i < nr_pages; i++) {
10278 if (!PageCompound(pages[i]))
10280 if (compound_head(pages[i]) == hpage)
10284 /* check previously registered pages */
10285 for (i = 0; i < ctx->nr_user_bufs; i++) {
10286 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10288 for (j = 0; j < imu->nr_bvecs; j++) {
10289 if (!PageCompound(imu->bvec[j].bv_page))
10291 if (compound_head(imu->bvec[j].bv_page) == hpage)
10299 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10300 int nr_pages, struct io_mapped_ubuf *imu,
10301 struct page **last_hpage)
10305 imu->acct_pages = 0;
10306 for (i = 0; i < nr_pages; i++) {
10307 if (!PageCompound(pages[i])) {
10310 struct page *hpage;
10312 hpage = compound_head(pages[i]);
10313 if (hpage == *last_hpage)
10315 *last_hpage = hpage;
10316 if (headpage_already_acct(ctx, pages, i, hpage))
10318 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10322 if (!imu->acct_pages)
10325 ret = io_account_mem(ctx, imu->acct_pages);
10327 imu->acct_pages = 0;
10331 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10334 unsigned long start, end, nr_pages;
10335 struct vm_area_struct **vmas = NULL;
10336 struct page **pages = NULL;
10337 int i, pret, ret = -ENOMEM;
10339 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10340 start = ubuf >> PAGE_SHIFT;
10341 nr_pages = end - start;
10343 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10347 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10353 mmap_read_lock(current->mm);
10354 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10356 if (pret == nr_pages) {
10357 /* don't support file backed memory */
10358 for (i = 0; i < nr_pages; i++) {
10359 struct vm_area_struct *vma = vmas[i];
10361 if (vma_is_shmem(vma))
10363 if (vma->vm_file &&
10364 !is_file_hugepages(vma->vm_file)) {
10369 *npages = nr_pages;
10371 ret = pret < 0 ? pret : -EFAULT;
10373 mmap_read_unlock(current->mm);
10376 * if we did partial map, or found file backed vmas,
10377 * release any pages we did get
10380 unpin_user_pages(pages, pret);
10388 pages = ERR_PTR(ret);
10393 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10394 struct io_mapped_ubuf **pimu,
10395 struct page **last_hpage)
10397 struct io_mapped_ubuf *imu = NULL;
10398 struct page **pages = NULL;
10401 int ret, nr_pages, i;
10403 if (!iov->iov_base) {
10404 *pimu = ctx->dummy_ubuf;
10411 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10413 if (IS_ERR(pages)) {
10414 ret = PTR_ERR(pages);
10419 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10423 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10425 unpin_user_pages(pages, nr_pages);
10429 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10430 size = iov->iov_len;
10431 for (i = 0; i < nr_pages; i++) {
10434 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10435 imu->bvec[i].bv_page = pages[i];
10436 imu->bvec[i].bv_len = vec_len;
10437 imu->bvec[i].bv_offset = off;
10441 /* store original address for later verification */
10442 imu->ubuf = (unsigned long) iov->iov_base;
10443 imu->ubuf_end = imu->ubuf + iov->iov_len;
10444 imu->nr_bvecs = nr_pages;
10454 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10456 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10457 return ctx->user_bufs ? 0 : -ENOMEM;
10460 static int io_buffer_validate(struct iovec *iov)
10462 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10465 * Don't impose further limits on the size and buffer
10466 * constraints here, we'll -EINVAL later when IO is
10467 * submitted if they are wrong.
10469 if (!iov->iov_base)
10470 return iov->iov_len ? -EFAULT : 0;
10474 /* arbitrary limit, but we need something */
10475 if (iov->iov_len > SZ_1G)
10478 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10484 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10485 unsigned int nr_args, u64 __user *tags)
10487 struct page *last_hpage = NULL;
10488 struct io_rsrc_data *data;
10492 if (ctx->user_bufs)
10494 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10496 ret = io_rsrc_node_switch_start(ctx);
10499 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10502 ret = io_buffers_map_alloc(ctx, nr_args);
10504 io_rsrc_data_free(data);
10508 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10510 ret = io_copy_iov(ctx, &iov, arg, i);
10513 ret = io_buffer_validate(&iov);
10517 memset(&iov, 0, sizeof(iov));
10520 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10525 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10531 WARN_ON_ONCE(ctx->buf_data);
10533 ctx->buf_data = data;
10535 __io_sqe_buffers_unregister(ctx);
10537 io_rsrc_node_switch(ctx, NULL);
10541 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10542 struct io_uring_rsrc_update2 *up,
10543 unsigned int nr_args)
10545 u64 __user *tags = u64_to_user_ptr(up->tags);
10546 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10547 struct page *last_hpage = NULL;
10548 bool needs_switch = false;
10552 if (!ctx->buf_data)
10554 if (up->offset + nr_args > ctx->nr_user_bufs)
10557 for (done = 0; done < nr_args; done++) {
10558 struct io_mapped_ubuf *imu;
10559 int offset = up->offset + done;
10562 err = io_copy_iov(ctx, &iov, iovs, done);
10565 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10569 err = io_buffer_validate(&iov);
10572 if (!iov.iov_base && tag) {
10576 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10580 i = array_index_nospec(offset, ctx->nr_user_bufs);
10581 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10582 err = io_queue_rsrc_removal(ctx->buf_data, i,
10583 ctx->rsrc_node, ctx->user_bufs[i]);
10584 if (unlikely(err)) {
10585 io_buffer_unmap(ctx, &imu);
10588 ctx->user_bufs[i] = NULL;
10589 needs_switch = true;
10592 ctx->user_bufs[i] = imu;
10593 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10597 io_rsrc_node_switch(ctx, ctx->buf_data);
10598 return done ? done : err;
10601 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10602 unsigned int eventfd_async)
10604 struct io_ev_fd *ev_fd;
10605 __s32 __user *fds = arg;
10608 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10609 lockdep_is_held(&ctx->uring_lock));
10613 if (copy_from_user(&fd, fds, sizeof(*fds)))
10616 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10620 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10621 if (IS_ERR(ev_fd->cq_ev_fd)) {
10622 int ret = PTR_ERR(ev_fd->cq_ev_fd);
10626 ev_fd->eventfd_async = eventfd_async;
10627 ctx->has_evfd = true;
10628 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10632 static void io_eventfd_put(struct rcu_head *rcu)
10634 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10636 eventfd_ctx_put(ev_fd->cq_ev_fd);
10640 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10642 struct io_ev_fd *ev_fd;
10644 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10645 lockdep_is_held(&ctx->uring_lock));
10647 ctx->has_evfd = false;
10648 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10649 call_rcu(&ev_fd->rcu, io_eventfd_put);
10656 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10658 struct io_buffer_list *bl;
10659 unsigned long index;
10662 for (i = 0; i < BGID_ARRAY; i++) {
10665 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
10668 xa_for_each(&ctx->io_bl_xa, index, bl) {
10669 xa_erase(&ctx->io_bl_xa, bl->bgid);
10670 __io_remove_buffers(ctx, bl, -1U);
10674 while (!list_empty(&ctx->io_buffers_pages)) {
10677 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10678 list_del_init(&page->lru);
10683 static void io_req_caches_free(struct io_ring_ctx *ctx)
10685 struct io_submit_state *state = &ctx->submit_state;
10688 mutex_lock(&ctx->uring_lock);
10689 io_flush_cached_locked_reqs(ctx, state);
10691 while (!io_req_cache_empty(ctx)) {
10692 struct io_wq_work_node *node;
10693 struct io_kiocb *req;
10695 node = wq_stack_extract(&state->free_list);
10696 req = container_of(node, struct io_kiocb, comp_list);
10697 kmem_cache_free(req_cachep, req);
10701 percpu_ref_put_many(&ctx->refs, nr);
10702 mutex_unlock(&ctx->uring_lock);
10705 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10707 if (data && !atomic_dec_and_test(&data->refs))
10708 wait_for_completion(&data->done);
10711 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10713 struct async_poll *apoll;
10715 while (!list_empty(&ctx->apoll_cache)) {
10716 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10718 list_del(&apoll->poll.wait.entry);
10723 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10725 io_sq_thread_finish(ctx);
10727 if (ctx->mm_account) {
10728 mmdrop(ctx->mm_account);
10729 ctx->mm_account = NULL;
10732 io_rsrc_refs_drop(ctx);
10733 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10734 io_wait_rsrc_data(ctx->buf_data);
10735 io_wait_rsrc_data(ctx->file_data);
10737 mutex_lock(&ctx->uring_lock);
10739 __io_sqe_buffers_unregister(ctx);
10740 if (ctx->file_data)
10741 __io_sqe_files_unregister(ctx);
10743 __io_cqring_overflow_flush(ctx, true);
10744 io_eventfd_unregister(ctx);
10745 io_flush_apoll_cache(ctx);
10746 mutex_unlock(&ctx->uring_lock);
10747 io_destroy_buffers(ctx);
10749 put_cred(ctx->sq_creds);
10751 /* there are no registered resources left, nobody uses it */
10752 if (ctx->rsrc_node)
10753 io_rsrc_node_destroy(ctx->rsrc_node);
10754 if (ctx->rsrc_backup_node)
10755 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10756 flush_delayed_work(&ctx->rsrc_put_work);
10757 flush_delayed_work(&ctx->fallback_work);
10759 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10760 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10762 #if defined(CONFIG_UNIX)
10763 if (ctx->ring_sock) {
10764 ctx->ring_sock->file = NULL; /* so that iput() is called */
10765 sock_release(ctx->ring_sock);
10768 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10770 io_mem_free(ctx->rings);
10771 io_mem_free(ctx->sq_sqes);
10773 percpu_ref_exit(&ctx->refs);
10774 free_uid(ctx->user);
10775 io_req_caches_free(ctx);
10777 io_wq_put_hash(ctx->hash_map);
10778 kfree(ctx->cancel_hash);
10779 kfree(ctx->dummy_ubuf);
10781 xa_destroy(&ctx->io_bl_xa);
10785 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10787 struct io_ring_ctx *ctx = file->private_data;
10790 poll_wait(file, &ctx->cq_wait, wait);
10792 * synchronizes with barrier from wq_has_sleeper call in
10796 if (!io_sqring_full(ctx))
10797 mask |= EPOLLOUT | EPOLLWRNORM;
10800 * Don't flush cqring overflow list here, just do a simple check.
10801 * Otherwise there could possible be ABBA deadlock:
10804 * lock(&ctx->uring_lock);
10806 * lock(&ctx->uring_lock);
10809 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10810 * pushs them to do the flush.
10812 if (io_cqring_events(ctx) ||
10813 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
10814 mask |= EPOLLIN | EPOLLRDNORM;
10819 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10821 const struct cred *creds;
10823 creds = xa_erase(&ctx->personalities, id);
10832 struct io_tctx_exit {
10833 struct callback_head task_work;
10834 struct completion completion;
10835 struct io_ring_ctx *ctx;
10838 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10840 struct io_uring_task *tctx = current->io_uring;
10841 struct io_tctx_exit *work;
10843 work = container_of(cb, struct io_tctx_exit, task_work);
10845 * When @in_idle, we're in cancellation and it's racy to remove the
10846 * node. It'll be removed by the end of cancellation, just ignore it.
10848 if (!atomic_read(&tctx->in_idle))
10849 io_uring_del_tctx_node((unsigned long)work->ctx);
10850 complete(&work->completion);
10853 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10855 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10857 return req->ctx == data;
10860 static __cold void io_ring_exit_work(struct work_struct *work)
10862 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10863 unsigned long timeout = jiffies + HZ * 60 * 5;
10864 unsigned long interval = HZ / 20;
10865 struct io_tctx_exit exit;
10866 struct io_tctx_node *node;
10870 * If we're doing polled IO and end up having requests being
10871 * submitted async (out-of-line), then completions can come in while
10872 * we're waiting for refs to drop. We need to reap these manually,
10873 * as nobody else will be looking for them.
10876 io_uring_try_cancel_requests(ctx, NULL, true);
10877 if (ctx->sq_data) {
10878 struct io_sq_data *sqd = ctx->sq_data;
10879 struct task_struct *tsk;
10881 io_sq_thread_park(sqd);
10883 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10884 io_wq_cancel_cb(tsk->io_uring->io_wq,
10885 io_cancel_ctx_cb, ctx, true);
10886 io_sq_thread_unpark(sqd);
10889 io_req_caches_free(ctx);
10891 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10892 /* there is little hope left, don't run it too often */
10893 interval = HZ * 60;
10895 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10897 init_completion(&exit.completion);
10898 init_task_work(&exit.task_work, io_tctx_exit_cb);
10901 * Some may use context even when all refs and requests have been put,
10902 * and they are free to do so while still holding uring_lock or
10903 * completion_lock, see io_req_task_submit(). Apart from other work,
10904 * this lock/unlock section also waits them to finish.
10906 mutex_lock(&ctx->uring_lock);
10907 while (!list_empty(&ctx->tctx_list)) {
10908 WARN_ON_ONCE(time_after(jiffies, timeout));
10910 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10912 /* don't spin on a single task if cancellation failed */
10913 list_rotate_left(&ctx->tctx_list);
10914 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10915 if (WARN_ON_ONCE(ret))
10918 mutex_unlock(&ctx->uring_lock);
10919 wait_for_completion(&exit.completion);
10920 mutex_lock(&ctx->uring_lock);
10922 mutex_unlock(&ctx->uring_lock);
10923 spin_lock(&ctx->completion_lock);
10924 spin_unlock(&ctx->completion_lock);
10926 io_ring_ctx_free(ctx);
10929 /* Returns true if we found and killed one or more timeouts */
10930 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10931 struct task_struct *tsk, bool cancel_all)
10933 struct io_kiocb *req, *tmp;
10936 spin_lock(&ctx->completion_lock);
10937 spin_lock_irq(&ctx->timeout_lock);
10938 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10939 if (io_match_task(req, tsk, cancel_all)) {
10940 io_kill_timeout(req, -ECANCELED);
10944 spin_unlock_irq(&ctx->timeout_lock);
10945 io_commit_cqring(ctx);
10946 spin_unlock(&ctx->completion_lock);
10948 io_cqring_ev_posted(ctx);
10949 return canceled != 0;
10952 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10954 unsigned long index;
10955 struct creds *creds;
10957 mutex_lock(&ctx->uring_lock);
10958 percpu_ref_kill(&ctx->refs);
10960 __io_cqring_overflow_flush(ctx, true);
10961 xa_for_each(&ctx->personalities, index, creds)
10962 io_unregister_personality(ctx, index);
10963 mutex_unlock(&ctx->uring_lock);
10965 /* failed during ring init, it couldn't have issued any requests */
10967 io_kill_timeouts(ctx, NULL, true);
10968 io_poll_remove_all(ctx, NULL, true);
10969 /* if we failed setting up the ctx, we might not have any rings */
10970 io_iopoll_try_reap_events(ctx);
10973 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10975 * Use system_unbound_wq to avoid spawning tons of event kworkers
10976 * if we're exiting a ton of rings at the same time. It just adds
10977 * noise and overhead, there's no discernable change in runtime
10978 * over using system_wq.
10980 queue_work(system_unbound_wq, &ctx->exit_work);
10983 static int io_uring_release(struct inode *inode, struct file *file)
10985 struct io_ring_ctx *ctx = file->private_data;
10987 file->private_data = NULL;
10988 io_ring_ctx_wait_and_kill(ctx);
10992 struct io_task_cancel {
10993 struct task_struct *task;
10997 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10999 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11000 struct io_task_cancel *cancel = data;
11002 return io_match_task_safe(req, cancel->task, cancel->all);
11005 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11006 struct task_struct *task,
11009 struct io_defer_entry *de;
11012 spin_lock(&ctx->completion_lock);
11013 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11014 if (io_match_task_safe(de->req, task, cancel_all)) {
11015 list_cut_position(&list, &ctx->defer_list, &de->list);
11019 spin_unlock(&ctx->completion_lock);
11020 if (list_empty(&list))
11023 while (!list_empty(&list)) {
11024 de = list_first_entry(&list, struct io_defer_entry, list);
11025 list_del_init(&de->list);
11026 io_req_complete_failed(de->req, -ECANCELED);
11032 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11034 struct io_tctx_node *node;
11035 enum io_wq_cancel cret;
11038 mutex_lock(&ctx->uring_lock);
11039 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11040 struct io_uring_task *tctx = node->task->io_uring;
11043 * io_wq will stay alive while we hold uring_lock, because it's
11044 * killed after ctx nodes, which requires to take the lock.
11046 if (!tctx || !tctx->io_wq)
11048 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11049 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11051 mutex_unlock(&ctx->uring_lock);
11056 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11057 struct task_struct *task,
11060 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11061 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11063 /* failed during ring init, it couldn't have issued any requests */
11068 enum io_wq_cancel cret;
11072 ret |= io_uring_try_cancel_iowq(ctx);
11073 } else if (tctx && tctx->io_wq) {
11075 * Cancels requests of all rings, not only @ctx, but
11076 * it's fine as the task is in exit/exec.
11078 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11080 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11083 /* SQPOLL thread does its own polling */
11084 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11085 (ctx->sq_data && ctx->sq_data->thread == current)) {
11086 while (!wq_list_empty(&ctx->iopoll_list)) {
11087 io_iopoll_try_reap_events(ctx);
11092 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11093 ret |= io_poll_remove_all(ctx, task, cancel_all);
11094 ret |= io_kill_timeouts(ctx, task, cancel_all);
11096 ret |= io_run_task_work();
11103 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11105 struct io_uring_task *tctx = current->io_uring;
11106 struct io_tctx_node *node;
11109 if (unlikely(!tctx)) {
11110 ret = io_uring_alloc_task_context(current, ctx);
11114 tctx = current->io_uring;
11115 if (ctx->iowq_limits_set) {
11116 unsigned int limits[2] = { ctx->iowq_limits[0],
11117 ctx->iowq_limits[1], };
11119 ret = io_wq_max_workers(tctx->io_wq, limits);
11124 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11125 node = kmalloc(sizeof(*node), GFP_KERNEL);
11129 node->task = current;
11131 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11132 node, GFP_KERNEL));
11138 mutex_lock(&ctx->uring_lock);
11139 list_add(&node->ctx_node, &ctx->tctx_list);
11140 mutex_unlock(&ctx->uring_lock);
11147 * Note that this task has used io_uring. We use it for cancelation purposes.
11149 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11151 struct io_uring_task *tctx = current->io_uring;
11153 if (likely(tctx && tctx->last == ctx))
11155 return __io_uring_add_tctx_node(ctx);
11159 * Remove this io_uring_file -> task mapping.
11161 static __cold void io_uring_del_tctx_node(unsigned long index)
11163 struct io_uring_task *tctx = current->io_uring;
11164 struct io_tctx_node *node;
11168 node = xa_erase(&tctx->xa, index);
11172 WARN_ON_ONCE(current != node->task);
11173 WARN_ON_ONCE(list_empty(&node->ctx_node));
11175 mutex_lock(&node->ctx->uring_lock);
11176 list_del(&node->ctx_node);
11177 mutex_unlock(&node->ctx->uring_lock);
11179 if (tctx->last == node->ctx)
11184 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11186 struct io_wq *wq = tctx->io_wq;
11187 struct io_tctx_node *node;
11188 unsigned long index;
11190 xa_for_each(&tctx->xa, index, node) {
11191 io_uring_del_tctx_node(index);
11196 * Must be after io_uring_del_tctx_node() (removes nodes under
11197 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11199 io_wq_put_and_exit(wq);
11200 tctx->io_wq = NULL;
11204 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11207 return atomic_read(&tctx->inflight_tracked);
11208 return percpu_counter_sum(&tctx->inflight);
11212 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11213 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11215 static __cold void io_uring_cancel_generic(bool cancel_all,
11216 struct io_sq_data *sqd)
11218 struct io_uring_task *tctx = current->io_uring;
11219 struct io_ring_ctx *ctx;
11223 WARN_ON_ONCE(sqd && sqd->thread != current);
11225 if (!current->io_uring)
11228 io_wq_exit_start(tctx->io_wq);
11230 atomic_inc(&tctx->in_idle);
11232 io_uring_drop_tctx_refs(current);
11233 /* read completions before cancelations */
11234 inflight = tctx_inflight(tctx, !cancel_all);
11239 struct io_tctx_node *node;
11240 unsigned long index;
11242 xa_for_each(&tctx->xa, index, node) {
11243 /* sqpoll task will cancel all its requests */
11244 if (node->ctx->sq_data)
11246 io_uring_try_cancel_requests(node->ctx, current,
11250 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11251 io_uring_try_cancel_requests(ctx, current,
11255 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11256 io_run_task_work();
11257 io_uring_drop_tctx_refs(current);
11260 * If we've seen completions, retry without waiting. This
11261 * avoids a race where a completion comes in before we did
11262 * prepare_to_wait().
11264 if (inflight == tctx_inflight(tctx, !cancel_all))
11266 finish_wait(&tctx->wait, &wait);
11269 io_uring_clean_tctx(tctx);
11272 * We shouldn't run task_works after cancel, so just leave
11273 * ->in_idle set for normal exit.
11275 atomic_dec(&tctx->in_idle);
11276 /* for exec all current's requests should be gone, kill tctx */
11277 __io_uring_free(current);
11281 void __io_uring_cancel(bool cancel_all)
11283 io_uring_cancel_generic(cancel_all, NULL);
11286 void io_uring_unreg_ringfd(void)
11288 struct io_uring_task *tctx = current->io_uring;
11291 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11292 if (tctx->registered_rings[i]) {
11293 fput(tctx->registered_rings[i]);
11294 tctx->registered_rings[i] = NULL;
11299 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11300 int start, int end)
11305 for (offset = start; offset < end; offset++) {
11306 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11307 if (tctx->registered_rings[offset])
11313 } else if (file->f_op != &io_uring_fops) {
11315 return -EOPNOTSUPP;
11317 tctx->registered_rings[offset] = file;
11325 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11326 * invocation. User passes in an array of struct io_uring_rsrc_update
11327 * with ->data set to the ring_fd, and ->offset given for the desired
11328 * index. If no index is desired, application may set ->offset == -1U
11329 * and we'll find an available index. Returns number of entries
11330 * successfully processed, or < 0 on error if none were processed.
11332 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11335 struct io_uring_rsrc_update __user *arg = __arg;
11336 struct io_uring_rsrc_update reg;
11337 struct io_uring_task *tctx;
11340 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11343 mutex_unlock(&ctx->uring_lock);
11344 ret = io_uring_add_tctx_node(ctx);
11345 mutex_lock(&ctx->uring_lock);
11349 tctx = current->io_uring;
11350 for (i = 0; i < nr_args; i++) {
11353 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11363 if (reg.offset == -1U) {
11365 end = IO_RINGFD_REG_MAX;
11367 if (reg.offset >= IO_RINGFD_REG_MAX) {
11371 start = reg.offset;
11375 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11380 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11381 fput(tctx->registered_rings[reg.offset]);
11382 tctx->registered_rings[reg.offset] = NULL;
11388 return i ? i : ret;
11391 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11394 struct io_uring_rsrc_update __user *arg = __arg;
11395 struct io_uring_task *tctx = current->io_uring;
11396 struct io_uring_rsrc_update reg;
11399 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11404 for (i = 0; i < nr_args; i++) {
11405 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11409 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11414 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11415 if (tctx->registered_rings[reg.offset]) {
11416 fput(tctx->registered_rings[reg.offset]);
11417 tctx->registered_rings[reg.offset] = NULL;
11421 return i ? i : ret;
11424 static void *io_uring_validate_mmap_request(struct file *file,
11425 loff_t pgoff, size_t sz)
11427 struct io_ring_ctx *ctx = file->private_data;
11428 loff_t offset = pgoff << PAGE_SHIFT;
11433 case IORING_OFF_SQ_RING:
11434 case IORING_OFF_CQ_RING:
11437 case IORING_OFF_SQES:
11438 ptr = ctx->sq_sqes;
11441 return ERR_PTR(-EINVAL);
11444 page = virt_to_head_page(ptr);
11445 if (sz > page_size(page))
11446 return ERR_PTR(-EINVAL);
11453 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11455 size_t sz = vma->vm_end - vma->vm_start;
11459 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11461 return PTR_ERR(ptr);
11463 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11464 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11467 #else /* !CONFIG_MMU */
11469 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11471 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11474 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11476 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11479 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11480 unsigned long addr, unsigned long len,
11481 unsigned long pgoff, unsigned long flags)
11485 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11487 return PTR_ERR(ptr);
11489 return (unsigned long) ptr;
11492 #endif /* !CONFIG_MMU */
11494 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11499 if (!io_sqring_full(ctx))
11501 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11503 if (!io_sqring_full(ctx))
11506 } while (!signal_pending(current));
11508 finish_wait(&ctx->sqo_sq_wait, &wait);
11512 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11514 if (flags & IORING_ENTER_EXT_ARG) {
11515 struct io_uring_getevents_arg arg;
11517 if (argsz != sizeof(arg))
11519 if (copy_from_user(&arg, argp, sizeof(arg)))
11525 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11526 struct __kernel_timespec __user **ts,
11527 const sigset_t __user **sig)
11529 struct io_uring_getevents_arg arg;
11532 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11533 * is just a pointer to the sigset_t.
11535 if (!(flags & IORING_ENTER_EXT_ARG)) {
11536 *sig = (const sigset_t __user *) argp;
11542 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11543 * timespec and sigset_t pointers if good.
11545 if (*argsz != sizeof(arg))
11547 if (copy_from_user(&arg, argp, sizeof(arg)))
11551 *sig = u64_to_user_ptr(arg.sigmask);
11552 *argsz = arg.sigmask_sz;
11553 *ts = u64_to_user_ptr(arg.ts);
11557 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11558 u32, min_complete, u32, flags, const void __user *, argp,
11561 struct io_ring_ctx *ctx;
11565 io_run_task_work();
11567 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11568 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11569 IORING_ENTER_REGISTERED_RING)))
11573 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11574 * need only dereference our task private array to find it.
11576 if (flags & IORING_ENTER_REGISTERED_RING) {
11577 struct io_uring_task *tctx = current->io_uring;
11579 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11581 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11582 f.file = tctx->registered_rings[fd];
11588 if (unlikely(!f.file))
11592 if (unlikely(f.file->f_op != &io_uring_fops))
11596 ctx = f.file->private_data;
11597 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11601 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11605 * For SQ polling, the thread will do all submissions and completions.
11606 * Just return the requested submit count, and wake the thread if
11607 * we were asked to.
11610 if (ctx->flags & IORING_SETUP_SQPOLL) {
11611 io_cqring_overflow_flush(ctx);
11613 if (unlikely(ctx->sq_data->thread == NULL)) {
11617 if (flags & IORING_ENTER_SQ_WAKEUP)
11618 wake_up(&ctx->sq_data->wait);
11619 if (flags & IORING_ENTER_SQ_WAIT) {
11620 ret = io_sqpoll_wait_sq(ctx);
11625 } else if (to_submit) {
11626 ret = io_uring_add_tctx_node(ctx);
11630 mutex_lock(&ctx->uring_lock);
11631 ret = io_submit_sqes(ctx, to_submit);
11632 if (ret != to_submit) {
11633 mutex_unlock(&ctx->uring_lock);
11636 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
11637 goto iopoll_locked;
11638 mutex_unlock(&ctx->uring_lock);
11640 if (flags & IORING_ENTER_GETEVENTS) {
11642 if (ctx->syscall_iopoll) {
11644 * We disallow the app entering submit/complete with
11645 * polling, but we still need to lock the ring to
11646 * prevent racing with polled issue that got punted to
11649 mutex_lock(&ctx->uring_lock);
11651 ret2 = io_validate_ext_arg(flags, argp, argsz);
11652 if (likely(!ret2)) {
11653 min_complete = min(min_complete,
11655 ret2 = io_iopoll_check(ctx, min_complete);
11657 mutex_unlock(&ctx->uring_lock);
11659 const sigset_t __user *sig;
11660 struct __kernel_timespec __user *ts;
11662 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
11663 if (likely(!ret2)) {
11664 min_complete = min(min_complete,
11666 ret2 = io_cqring_wait(ctx, min_complete, sig,
11675 * EBADR indicates that one or more CQE were dropped.
11676 * Once the user has been informed we can clear the bit
11677 * as they are obviously ok with those drops.
11679 if (unlikely(ret2 == -EBADR))
11680 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
11686 percpu_ref_put(&ctx->refs);
11692 #ifdef CONFIG_PROC_FS
11693 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11694 const struct cred *cred)
11696 struct user_namespace *uns = seq_user_ns(m);
11697 struct group_info *gi;
11702 seq_printf(m, "%5d\n", id);
11703 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11704 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11705 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11706 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11707 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11708 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11709 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11710 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11711 seq_puts(m, "\n\tGroups:\t");
11712 gi = cred->group_info;
11713 for (g = 0; g < gi->ngroups; g++) {
11714 seq_put_decimal_ull(m, g ? " " : "",
11715 from_kgid_munged(uns, gi->gid[g]));
11717 seq_puts(m, "\n\tCapEff:\t");
11718 cap = cred->cap_effective;
11719 CAP_FOR_EACH_U32(__capi)
11720 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11725 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11726 struct seq_file *m)
11728 struct io_sq_data *sq = NULL;
11729 struct io_overflow_cqe *ocqe;
11730 struct io_rings *r = ctx->rings;
11731 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11732 unsigned int sq_head = READ_ONCE(r->sq.head);
11733 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11734 unsigned int cq_head = READ_ONCE(r->cq.head);
11735 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11736 unsigned int cq_shift = 0;
11737 unsigned int sq_entries, cq_entries;
11739 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
11746 * we may get imprecise sqe and cqe info if uring is actively running
11747 * since we get cached_sq_head and cached_cq_tail without uring_lock
11748 * and sq_tail and cq_head are changed by userspace. But it's ok since
11749 * we usually use these info when it is stuck.
11751 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11752 seq_printf(m, "SqHead:\t%u\n", sq_head);
11753 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11754 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11755 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11756 seq_printf(m, "CqHead:\t%u\n", cq_head);
11757 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11758 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11759 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11760 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11761 for (i = 0; i < sq_entries; i++) {
11762 unsigned int entry = i + sq_head;
11763 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11764 struct io_uring_sqe *sqe;
11766 if (sq_idx > sq_mask)
11768 sqe = &ctx->sq_sqes[sq_idx];
11769 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11770 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11773 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11774 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11775 for (i = 0; i < cq_entries; i++) {
11776 unsigned int entry = i + cq_head;
11777 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
11780 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11781 entry & cq_mask, cqe->user_data, cqe->res,
11784 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
11785 "extra1:%llu, extra2:%llu\n",
11786 entry & cq_mask, cqe->user_data, cqe->res,
11787 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
11792 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11793 * since fdinfo case grabs it in the opposite direction of normal use
11794 * cases. If we fail to get the lock, we just don't iterate any
11795 * structures that could be going away outside the io_uring mutex.
11797 has_lock = mutex_trylock(&ctx->uring_lock);
11799 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11805 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11806 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11807 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11808 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11809 struct file *f = io_file_from_index(ctx, i);
11812 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11814 seq_printf(m, "%5u: <none>\n", i);
11816 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11817 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11818 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11819 unsigned int len = buf->ubuf_end - buf->ubuf;
11821 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11823 if (has_lock && !xa_empty(&ctx->personalities)) {
11824 unsigned long index;
11825 const struct cred *cred;
11827 seq_printf(m, "Personalities:\n");
11828 xa_for_each(&ctx->personalities, index, cred)
11829 io_uring_show_cred(m, index, cred);
11832 mutex_unlock(&ctx->uring_lock);
11834 seq_puts(m, "PollList:\n");
11835 spin_lock(&ctx->completion_lock);
11836 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11837 struct hlist_head *list = &ctx->cancel_hash[i];
11838 struct io_kiocb *req;
11840 hlist_for_each_entry(req, list, hash_node)
11841 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11842 task_work_pending(req->task));
11845 seq_puts(m, "CqOverflowList:\n");
11846 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11847 struct io_uring_cqe *cqe = &ocqe->cqe;
11849 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11850 cqe->user_data, cqe->res, cqe->flags);
11854 spin_unlock(&ctx->completion_lock);
11857 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11859 struct io_ring_ctx *ctx = f->private_data;
11861 if (percpu_ref_tryget(&ctx->refs)) {
11862 __io_uring_show_fdinfo(ctx, m);
11863 percpu_ref_put(&ctx->refs);
11868 static const struct file_operations io_uring_fops = {
11869 .release = io_uring_release,
11870 .mmap = io_uring_mmap,
11872 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11873 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11875 .poll = io_uring_poll,
11876 #ifdef CONFIG_PROC_FS
11877 .show_fdinfo = io_uring_show_fdinfo,
11881 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11882 struct io_uring_params *p)
11884 struct io_rings *rings;
11885 size_t size, sq_array_offset;
11887 /* make sure these are sane, as we already accounted them */
11888 ctx->sq_entries = p->sq_entries;
11889 ctx->cq_entries = p->cq_entries;
11891 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
11892 if (size == SIZE_MAX)
11895 rings = io_mem_alloc(size);
11899 ctx->rings = rings;
11900 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11901 rings->sq_ring_mask = p->sq_entries - 1;
11902 rings->cq_ring_mask = p->cq_entries - 1;
11903 rings->sq_ring_entries = p->sq_entries;
11904 rings->cq_ring_entries = p->cq_entries;
11906 if (p->flags & IORING_SETUP_SQE128)
11907 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
11909 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11910 if (size == SIZE_MAX) {
11911 io_mem_free(ctx->rings);
11916 ctx->sq_sqes = io_mem_alloc(size);
11917 if (!ctx->sq_sqes) {
11918 io_mem_free(ctx->rings);
11926 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11930 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11934 ret = io_uring_add_tctx_node(ctx);
11939 fd_install(fd, file);
11944 * Allocate an anonymous fd, this is what constitutes the application
11945 * visible backing of an io_uring instance. The application mmaps this
11946 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11947 * we have to tie this fd to a socket for file garbage collection purposes.
11949 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11952 #if defined(CONFIG_UNIX)
11955 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11958 return ERR_PTR(ret);
11961 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11962 O_RDWR | O_CLOEXEC, NULL);
11963 #if defined(CONFIG_UNIX)
11964 if (IS_ERR(file)) {
11965 sock_release(ctx->ring_sock);
11966 ctx->ring_sock = NULL;
11968 ctx->ring_sock->file = file;
11974 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11975 struct io_uring_params __user *params)
11977 struct io_ring_ctx *ctx;
11983 if (entries > IORING_MAX_ENTRIES) {
11984 if (!(p->flags & IORING_SETUP_CLAMP))
11986 entries = IORING_MAX_ENTRIES;
11990 * Use twice as many entries for the CQ ring. It's possible for the
11991 * application to drive a higher depth than the size of the SQ ring,
11992 * since the sqes are only used at submission time. This allows for
11993 * some flexibility in overcommitting a bit. If the application has
11994 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11995 * of CQ ring entries manually.
11997 p->sq_entries = roundup_pow_of_two(entries);
11998 if (p->flags & IORING_SETUP_CQSIZE) {
12000 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12001 * to a power-of-two, if it isn't already. We do NOT impose
12002 * any cq vs sq ring sizing.
12004 if (!p->cq_entries)
12006 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12007 if (!(p->flags & IORING_SETUP_CLAMP))
12009 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12011 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12012 if (p->cq_entries < p->sq_entries)
12015 p->cq_entries = 2 * p->sq_entries;
12018 ctx = io_ring_ctx_alloc(p);
12023 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12024 * space applications don't need to do io completion events
12025 * polling again, they can rely on io_sq_thread to do polling
12026 * work, which can reduce cpu usage and uring_lock contention.
12028 if (ctx->flags & IORING_SETUP_IOPOLL &&
12029 !(ctx->flags & IORING_SETUP_SQPOLL))
12030 ctx->syscall_iopoll = 1;
12032 ctx->compat = in_compat_syscall();
12033 if (!capable(CAP_IPC_LOCK))
12034 ctx->user = get_uid(current_user());
12037 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12038 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12041 if (ctx->flags & IORING_SETUP_SQPOLL) {
12042 /* IPI related flags don't make sense with SQPOLL */
12043 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12044 IORING_SETUP_TASKRUN_FLAG))
12046 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12047 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12048 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12050 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12052 ctx->notify_method = TWA_SIGNAL;
12056 * This is just grabbed for accounting purposes. When a process exits,
12057 * the mm is exited and dropped before the files, hence we need to hang
12058 * on to this mm purely for the purposes of being able to unaccount
12059 * memory (locked/pinned vm). It's not used for anything else.
12061 mmgrab(current->mm);
12062 ctx->mm_account = current->mm;
12064 ret = io_allocate_scq_urings(ctx, p);
12068 ret = io_sq_offload_create(ctx, p);
12071 /* always set a rsrc node */
12072 ret = io_rsrc_node_switch_start(ctx);
12075 io_rsrc_node_switch(ctx, NULL);
12077 memset(&p->sq_off, 0, sizeof(p->sq_off));
12078 p->sq_off.head = offsetof(struct io_rings, sq.head);
12079 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12080 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12081 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12082 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12083 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12084 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12086 memset(&p->cq_off, 0, sizeof(p->cq_off));
12087 p->cq_off.head = offsetof(struct io_rings, cq.head);
12088 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12089 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12090 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12091 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12092 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12093 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12095 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12096 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12097 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12098 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12099 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12100 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12101 IORING_FEAT_LINKED_FILE;
12103 if (copy_to_user(params, p, sizeof(*p))) {
12108 file = io_uring_get_file(ctx);
12109 if (IS_ERR(file)) {
12110 ret = PTR_ERR(file);
12115 * Install ring fd as the very last thing, so we don't risk someone
12116 * having closed it before we finish setup
12118 ret = io_uring_install_fd(ctx, file);
12120 /* fput will clean it up */
12125 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12128 io_ring_ctx_wait_and_kill(ctx);
12133 * Sets up an aio uring context, and returns the fd. Applications asks for a
12134 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12135 * params structure passed in.
12137 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12139 struct io_uring_params p;
12142 if (copy_from_user(&p, params, sizeof(p)))
12144 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12149 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12150 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12151 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12152 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12153 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12154 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12157 return io_uring_create(entries, &p, params);
12160 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12161 struct io_uring_params __user *, params)
12163 return io_uring_setup(entries, params);
12166 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12169 struct io_uring_probe *p;
12173 size = struct_size(p, ops, nr_args);
12174 if (size == SIZE_MAX)
12176 p = kzalloc(size, GFP_KERNEL);
12181 if (copy_from_user(p, arg, size))
12184 if (memchr_inv(p, 0, size))
12187 p->last_op = IORING_OP_LAST - 1;
12188 if (nr_args > IORING_OP_LAST)
12189 nr_args = IORING_OP_LAST;
12191 for (i = 0; i < nr_args; i++) {
12193 if (!io_op_defs[i].not_supported)
12194 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12199 if (copy_to_user(arg, p, size))
12206 static int io_register_personality(struct io_ring_ctx *ctx)
12208 const struct cred *creds;
12212 creds = get_current_cred();
12214 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12215 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12223 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12224 void __user *arg, unsigned int nr_args)
12226 struct io_uring_restriction *res;
12230 /* Restrictions allowed only if rings started disabled */
12231 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12234 /* We allow only a single restrictions registration */
12235 if (ctx->restrictions.registered)
12238 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12241 size = array_size(nr_args, sizeof(*res));
12242 if (size == SIZE_MAX)
12245 res = memdup_user(arg, size);
12247 return PTR_ERR(res);
12251 for (i = 0; i < nr_args; i++) {
12252 switch (res[i].opcode) {
12253 case IORING_RESTRICTION_REGISTER_OP:
12254 if (res[i].register_op >= IORING_REGISTER_LAST) {
12259 __set_bit(res[i].register_op,
12260 ctx->restrictions.register_op);
12262 case IORING_RESTRICTION_SQE_OP:
12263 if (res[i].sqe_op >= IORING_OP_LAST) {
12268 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12270 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12271 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12273 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12274 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12283 /* Reset all restrictions if an error happened */
12285 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12287 ctx->restrictions.registered = true;
12293 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12295 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12298 if (ctx->restrictions.registered)
12299 ctx->restricted = 1;
12301 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12302 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12303 wake_up(&ctx->sq_data->wait);
12307 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12308 struct io_uring_rsrc_update2 *up,
12314 if (check_add_overflow(up->offset, nr_args, &tmp))
12316 err = io_rsrc_node_switch_start(ctx);
12321 case IORING_RSRC_FILE:
12322 return __io_sqe_files_update(ctx, up, nr_args);
12323 case IORING_RSRC_BUFFER:
12324 return __io_sqe_buffers_update(ctx, up, nr_args);
12329 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12332 struct io_uring_rsrc_update2 up;
12336 memset(&up, 0, sizeof(up));
12337 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12339 if (up.resv || up.resv2)
12341 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12344 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12345 unsigned size, unsigned type)
12347 struct io_uring_rsrc_update2 up;
12349 if (size != sizeof(up))
12351 if (copy_from_user(&up, arg, sizeof(up)))
12353 if (!up.nr || up.resv || up.resv2)
12355 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12358 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12359 unsigned int size, unsigned int type)
12361 struct io_uring_rsrc_register rr;
12363 /* keep it extendible */
12364 if (size != sizeof(rr))
12367 memset(&rr, 0, sizeof(rr));
12368 if (copy_from_user(&rr, arg, size))
12370 if (!rr.nr || rr.resv2)
12372 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12376 case IORING_RSRC_FILE:
12377 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12379 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12380 rr.nr, u64_to_user_ptr(rr.tags));
12381 case IORING_RSRC_BUFFER:
12382 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12384 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12385 rr.nr, u64_to_user_ptr(rr.tags));
12390 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12391 void __user *arg, unsigned len)
12393 struct io_uring_task *tctx = current->io_uring;
12394 cpumask_var_t new_mask;
12397 if (!tctx || !tctx->io_wq)
12400 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12403 cpumask_clear(new_mask);
12404 if (len > cpumask_size())
12405 len = cpumask_size();
12407 if (in_compat_syscall()) {
12408 ret = compat_get_bitmap(cpumask_bits(new_mask),
12409 (const compat_ulong_t __user *)arg,
12410 len * 8 /* CHAR_BIT */);
12412 ret = copy_from_user(new_mask, arg, len);
12416 free_cpumask_var(new_mask);
12420 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12421 free_cpumask_var(new_mask);
12425 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12427 struct io_uring_task *tctx = current->io_uring;
12429 if (!tctx || !tctx->io_wq)
12432 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12435 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12437 __must_hold(&ctx->uring_lock)
12439 struct io_tctx_node *node;
12440 struct io_uring_task *tctx = NULL;
12441 struct io_sq_data *sqd = NULL;
12442 __u32 new_count[2];
12445 if (copy_from_user(new_count, arg, sizeof(new_count)))
12447 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12448 if (new_count[i] > INT_MAX)
12451 if (ctx->flags & IORING_SETUP_SQPOLL) {
12452 sqd = ctx->sq_data;
12455 * Observe the correct sqd->lock -> ctx->uring_lock
12456 * ordering. Fine to drop uring_lock here, we hold
12457 * a ref to the ctx.
12459 refcount_inc(&sqd->refs);
12460 mutex_unlock(&ctx->uring_lock);
12461 mutex_lock(&sqd->lock);
12462 mutex_lock(&ctx->uring_lock);
12464 tctx = sqd->thread->io_uring;
12467 tctx = current->io_uring;
12470 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12472 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12474 ctx->iowq_limits[i] = new_count[i];
12475 ctx->iowq_limits_set = true;
12477 if (tctx && tctx->io_wq) {
12478 ret = io_wq_max_workers(tctx->io_wq, new_count);
12482 memset(new_count, 0, sizeof(new_count));
12486 mutex_unlock(&sqd->lock);
12487 io_put_sq_data(sqd);
12490 if (copy_to_user(arg, new_count, sizeof(new_count)))
12493 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12497 /* now propagate the restriction to all registered users */
12498 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12499 struct io_uring_task *tctx = node->task->io_uring;
12501 if (WARN_ON_ONCE(!tctx->io_wq))
12504 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12505 new_count[i] = ctx->iowq_limits[i];
12506 /* ignore errors, it always returns zero anyway */
12507 (void)io_wq_max_workers(tctx->io_wq, new_count);
12512 mutex_unlock(&sqd->lock);
12513 io_put_sq_data(sqd);
12518 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12520 struct io_uring_buf_ring *br;
12521 struct io_uring_buf_reg reg;
12522 struct io_buffer_list *bl, *free_bl = NULL;
12523 struct page **pages;
12526 if (copy_from_user(®, arg, sizeof(reg)))
12529 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12531 if (!reg.ring_addr)
12533 if (reg.ring_addr & ~PAGE_MASK)
12535 if (!is_power_of_2(reg.ring_entries))
12538 /* cannot disambiguate full vs empty due to head/tail size */
12539 if (reg.ring_entries >= 65536)
12542 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12543 int ret = io_init_bl_list(ctx);
12548 bl = io_buffer_get_list(ctx, reg.bgid);
12550 /* if mapped buffer ring OR classic exists, don't allow */
12551 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12554 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12559 pages = io_pin_pages(reg.ring_addr,
12560 struct_size(br, bufs, reg.ring_entries),
12562 if (IS_ERR(pages)) {
12564 return PTR_ERR(pages);
12567 br = page_address(pages[0]);
12568 bl->buf_pages = pages;
12569 bl->buf_nr_pages = nr_pages;
12570 bl->nr_entries = reg.ring_entries;
12572 bl->mask = reg.ring_entries - 1;
12573 io_buffer_add_list(ctx, bl, reg.bgid);
12577 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12579 struct io_uring_buf_reg reg;
12580 struct io_buffer_list *bl;
12582 if (copy_from_user(®, arg, sizeof(reg)))
12584 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12587 bl = io_buffer_get_list(ctx, reg.bgid);
12590 if (!bl->buf_nr_pages)
12593 __io_remove_buffers(ctx, bl, -1U);
12594 if (bl->bgid >= BGID_ARRAY) {
12595 xa_erase(&ctx->io_bl_xa, bl->bgid);
12601 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12602 void __user *arg, unsigned nr_args)
12603 __releases(ctx->uring_lock)
12604 __acquires(ctx->uring_lock)
12609 * We're inside the ring mutex, if the ref is already dying, then
12610 * someone else killed the ctx or is already going through
12611 * io_uring_register().
12613 if (percpu_ref_is_dying(&ctx->refs))
12616 if (ctx->restricted) {
12617 if (opcode >= IORING_REGISTER_LAST)
12619 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12620 if (!test_bit(opcode, ctx->restrictions.register_op))
12625 case IORING_REGISTER_BUFFERS:
12629 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
12631 case IORING_UNREGISTER_BUFFERS:
12633 if (arg || nr_args)
12635 ret = io_sqe_buffers_unregister(ctx);
12637 case IORING_REGISTER_FILES:
12641 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
12643 case IORING_UNREGISTER_FILES:
12645 if (arg || nr_args)
12647 ret = io_sqe_files_unregister(ctx);
12649 case IORING_REGISTER_FILES_UPDATE:
12650 ret = io_register_files_update(ctx, arg, nr_args);
12652 case IORING_REGISTER_EVENTFD:
12656 ret = io_eventfd_register(ctx, arg, 0);
12658 case IORING_REGISTER_EVENTFD_ASYNC:
12662 ret = io_eventfd_register(ctx, arg, 1);
12664 case IORING_UNREGISTER_EVENTFD:
12666 if (arg || nr_args)
12668 ret = io_eventfd_unregister(ctx);
12670 case IORING_REGISTER_PROBE:
12672 if (!arg || nr_args > 256)
12674 ret = io_probe(ctx, arg, nr_args);
12676 case IORING_REGISTER_PERSONALITY:
12678 if (arg || nr_args)
12680 ret = io_register_personality(ctx);
12682 case IORING_UNREGISTER_PERSONALITY:
12686 ret = io_unregister_personality(ctx, nr_args);
12688 case IORING_REGISTER_ENABLE_RINGS:
12690 if (arg || nr_args)
12692 ret = io_register_enable_rings(ctx);
12694 case IORING_REGISTER_RESTRICTIONS:
12695 ret = io_register_restrictions(ctx, arg, nr_args);
12697 case IORING_REGISTER_FILES2:
12698 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
12700 case IORING_REGISTER_FILES_UPDATE2:
12701 ret = io_register_rsrc_update(ctx, arg, nr_args,
12704 case IORING_REGISTER_BUFFERS2:
12705 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
12707 case IORING_REGISTER_BUFFERS_UPDATE:
12708 ret = io_register_rsrc_update(ctx, arg, nr_args,
12709 IORING_RSRC_BUFFER);
12711 case IORING_REGISTER_IOWQ_AFF:
12713 if (!arg || !nr_args)
12715 ret = io_register_iowq_aff(ctx, arg, nr_args);
12717 case IORING_UNREGISTER_IOWQ_AFF:
12719 if (arg || nr_args)
12721 ret = io_unregister_iowq_aff(ctx);
12723 case IORING_REGISTER_IOWQ_MAX_WORKERS:
12725 if (!arg || nr_args != 2)
12727 ret = io_register_iowq_max_workers(ctx, arg);
12729 case IORING_REGISTER_RING_FDS:
12730 ret = io_ringfd_register(ctx, arg, nr_args);
12732 case IORING_UNREGISTER_RING_FDS:
12733 ret = io_ringfd_unregister(ctx, arg, nr_args);
12735 case IORING_REGISTER_PBUF_RING:
12737 if (!arg || nr_args != 1)
12739 ret = io_register_pbuf_ring(ctx, arg);
12741 case IORING_UNREGISTER_PBUF_RING:
12743 if (!arg || nr_args != 1)
12745 ret = io_unregister_pbuf_ring(ctx, arg);
12755 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
12756 void __user *, arg, unsigned int, nr_args)
12758 struct io_ring_ctx *ctx;
12767 if (f.file->f_op != &io_uring_fops)
12770 ctx = f.file->private_data;
12772 io_run_task_work();
12774 mutex_lock(&ctx->uring_lock);
12775 ret = __io_uring_register(ctx, opcode, arg, nr_args);
12776 mutex_unlock(&ctx->uring_lock);
12777 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
12783 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
12789 static const struct io_op_def io_op_defs[] = {
12790 [IORING_OP_NOP] = {
12793 .prep = io_nop_prep,
12796 [IORING_OP_READV] = {
12798 .unbound_nonreg_file = 1,
12800 .buffer_select = 1,
12805 .async_size = sizeof(struct io_async_rw),
12806 .prep = io_prep_rw,
12808 .prep_async = io_readv_prep_async,
12810 [IORING_OP_WRITEV] = {
12812 .hash_reg_file = 1,
12813 .unbound_nonreg_file = 1,
12819 .async_size = sizeof(struct io_async_rw),
12820 .prep = io_prep_rw,
12822 .prep_async = io_writev_prep_async,
12824 [IORING_OP_FSYNC] = {
12827 .prep = io_fsync_prep,
12830 [IORING_OP_READ_FIXED] = {
12832 .unbound_nonreg_file = 1,
12838 .async_size = sizeof(struct io_async_rw),
12839 .prep = io_prep_rw,
12842 [IORING_OP_WRITE_FIXED] = {
12844 .hash_reg_file = 1,
12845 .unbound_nonreg_file = 1,
12851 .async_size = sizeof(struct io_async_rw),
12852 .prep = io_prep_rw,
12855 [IORING_OP_POLL_ADD] = {
12857 .unbound_nonreg_file = 1,
12859 .prep = io_poll_add_prep,
12860 .issue = io_poll_add,
12862 [IORING_OP_POLL_REMOVE] = {
12864 .prep = io_poll_remove_prep,
12865 .issue = io_poll_remove,
12867 [IORING_OP_SYNC_FILE_RANGE] = {
12870 .prep = io_sfr_prep,
12871 .issue = io_sync_file_range,
12873 [IORING_OP_SENDMSG] = {
12875 .unbound_nonreg_file = 1,
12878 .async_size = sizeof(struct io_async_msghdr),
12879 .prep = io_sendmsg_prep,
12880 .issue = io_sendmsg,
12881 .prep_async = io_sendmsg_prep_async,
12883 [IORING_OP_RECVMSG] = {
12885 .unbound_nonreg_file = 1,
12887 .buffer_select = 1,
12889 .async_size = sizeof(struct io_async_msghdr),
12890 .prep = io_recvmsg_prep,
12891 .issue = io_recvmsg,
12892 .prep_async = io_recvmsg_prep_async,
12894 [IORING_OP_TIMEOUT] = {
12896 .async_size = sizeof(struct io_timeout_data),
12897 .prep = io_timeout_prep,
12898 .issue = io_timeout,
12900 [IORING_OP_TIMEOUT_REMOVE] = {
12901 /* used by timeout updates' prep() */
12903 .prep = io_timeout_remove_prep,
12904 .issue = io_timeout_remove,
12906 [IORING_OP_ACCEPT] = {
12908 .unbound_nonreg_file = 1,
12910 .poll_exclusive = 1,
12911 .ioprio = 1, /* used for flags */
12912 .prep = io_accept_prep,
12913 .issue = io_accept,
12915 [IORING_OP_ASYNC_CANCEL] = {
12917 .prep = io_async_cancel_prep,
12918 .issue = io_async_cancel,
12920 [IORING_OP_LINK_TIMEOUT] = {
12922 .async_size = sizeof(struct io_timeout_data),
12923 .prep = io_link_timeout_prep,
12924 .issue = io_no_issue,
12926 [IORING_OP_CONNECT] = {
12928 .unbound_nonreg_file = 1,
12930 .async_size = sizeof(struct io_async_connect),
12931 .prep = io_connect_prep,
12932 .issue = io_connect,
12933 .prep_async = io_connect_prep_async,
12935 [IORING_OP_FALLOCATE] = {
12937 .prep = io_fallocate_prep,
12938 .issue = io_fallocate,
12940 [IORING_OP_OPENAT] = {
12941 .prep = io_openat_prep,
12942 .issue = io_openat,
12944 [IORING_OP_CLOSE] = {
12945 .prep = io_close_prep,
12948 [IORING_OP_FILES_UPDATE] = {
12951 .prep = io_files_update_prep,
12952 .issue = io_files_update,
12954 [IORING_OP_STATX] = {
12956 .prep = io_statx_prep,
12959 [IORING_OP_READ] = {
12961 .unbound_nonreg_file = 1,
12963 .buffer_select = 1,
12968 .async_size = sizeof(struct io_async_rw),
12969 .prep = io_prep_rw,
12972 [IORING_OP_WRITE] = {
12974 .hash_reg_file = 1,
12975 .unbound_nonreg_file = 1,
12981 .async_size = sizeof(struct io_async_rw),
12982 .prep = io_prep_rw,
12985 [IORING_OP_FADVISE] = {
12988 .prep = io_fadvise_prep,
12989 .issue = io_fadvise,
12991 [IORING_OP_MADVISE] = {
12992 .prep = io_madvise_prep,
12993 .issue = io_madvise,
12995 [IORING_OP_SEND] = {
12997 .unbound_nonreg_file = 1,
13001 .prep = io_sendmsg_prep,
13004 [IORING_OP_RECV] = {
13006 .unbound_nonreg_file = 1,
13008 .buffer_select = 1,
13011 .prep = io_recvmsg_prep,
13014 [IORING_OP_OPENAT2] = {
13015 .prep = io_openat2_prep,
13016 .issue = io_openat2,
13018 [IORING_OP_EPOLL_CTL] = {
13019 .unbound_nonreg_file = 1,
13021 .prep = io_epoll_ctl_prep,
13022 .issue = io_epoll_ctl,
13024 [IORING_OP_SPLICE] = {
13026 .hash_reg_file = 1,
13027 .unbound_nonreg_file = 1,
13029 .prep = io_splice_prep,
13030 .issue = io_splice,
13032 [IORING_OP_PROVIDE_BUFFERS] = {
13035 .prep = io_provide_buffers_prep,
13036 .issue = io_provide_buffers,
13038 [IORING_OP_REMOVE_BUFFERS] = {
13041 .prep = io_remove_buffers_prep,
13042 .issue = io_remove_buffers,
13044 [IORING_OP_TEE] = {
13046 .hash_reg_file = 1,
13047 .unbound_nonreg_file = 1,
13049 .prep = io_tee_prep,
13052 [IORING_OP_SHUTDOWN] = {
13054 .prep = io_shutdown_prep,
13055 .issue = io_shutdown,
13057 [IORING_OP_RENAMEAT] = {
13058 .prep = io_renameat_prep,
13059 .issue = io_renameat,
13061 [IORING_OP_UNLINKAT] = {
13062 .prep = io_unlinkat_prep,
13063 .issue = io_unlinkat,
13065 [IORING_OP_MKDIRAT] = {
13066 .prep = io_mkdirat_prep,
13067 .issue = io_mkdirat,
13069 [IORING_OP_SYMLINKAT] = {
13070 .prep = io_symlinkat_prep,
13071 .issue = io_symlinkat,
13073 [IORING_OP_LINKAT] = {
13074 .prep = io_linkat_prep,
13075 .issue = io_linkat,
13077 [IORING_OP_MSG_RING] = {
13080 .prep = io_msg_ring_prep,
13081 .issue = io_msg_ring,
13083 [IORING_OP_FSETXATTR] = {
13085 .prep = io_fsetxattr_prep,
13086 .issue = io_fsetxattr,
13088 [IORING_OP_SETXATTR] = {
13089 .prep = io_setxattr_prep,
13090 .issue = io_setxattr,
13092 [IORING_OP_FGETXATTR] = {
13094 .prep = io_fgetxattr_prep,
13095 .issue = io_fgetxattr,
13097 [IORING_OP_GETXATTR] = {
13098 .prep = io_getxattr_prep,
13099 .issue = io_getxattr,
13101 [IORING_OP_SOCKET] = {
13103 .prep = io_socket_prep,
13104 .issue = io_socket,
13106 [IORING_OP_URING_CMD] = {
13109 .async_size = uring_cmd_pdu_size(1),
13110 .prep = io_uring_cmd_prep,
13111 .issue = io_uring_cmd,
13112 .prep_async = io_uring_cmd_prep_async,
13116 static int __init io_uring_init(void)
13120 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13121 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13122 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13125 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13126 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13127 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13128 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13129 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13130 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13131 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13132 BUILD_BUG_SQE_ELEM(8, __u64, off);
13133 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13134 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13135 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13136 BUILD_BUG_SQE_ELEM(24, __u32, len);
13137 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13138 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13139 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13140 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13141 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13142 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13143 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13144 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13145 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13146 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13147 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13148 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13149 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13150 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13151 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13152 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13153 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13154 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13155 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13156 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13157 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13158 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13160 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13161 sizeof(struct io_uring_rsrc_update));
13162 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13163 sizeof(struct io_uring_rsrc_update2));
13165 /* ->buf_index is u16 */
13166 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13167 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13168 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13169 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13170 offsetof(struct io_uring_buf_ring, tail));
13172 /* should fit into one byte */
13173 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13174 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13175 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13177 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13178 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13180 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13182 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13184 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
13185 BUG_ON(!io_op_defs[i].prep);
13186 BUG_ON(!io_op_defs[i].issue);
13189 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13193 __initcall(io_uring_init);