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>
559 struct io_poll_iocb {
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 /* keep async read/write and isreg together and in order */
850 REQ_F_SUPPORT_NOWAIT_BIT,
853 /* not a real bit, just to check we're not overflowing the space */
859 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
860 /* drain existing IO first */
861 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
863 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
864 /* doesn't sever on completion < 0 */
865 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
867 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
868 /* IOSQE_BUFFER_SELECT */
869 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
870 /* IOSQE_CQE_SKIP_SUCCESS */
871 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
873 /* fail rest of links */
874 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
875 /* on inflight list, should be cancelled and waited on exit reliably */
876 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
877 /* read/write uses file position */
878 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
879 /* must not punt to workers */
880 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
881 /* has or had linked timeout */
882 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
884 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
885 /* already went through poll handler */
886 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
887 /* buffer already selected */
888 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
889 /* buffer selected from ring, needs commit */
890 REQ_F_BUFFER_RING = BIT(REQ_F_BUFFER_RING_BIT),
891 /* completion is deferred through io_comp_state */
892 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
893 /* caller should reissue async */
894 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
895 /* supports async reads/writes */
896 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
898 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
899 /* has creds assigned */
900 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
901 /* skip refcounting if not set */
902 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
903 /* there is a linked timeout that has to be armed */
904 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
905 /* ->async_data allocated */
906 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
907 /* don't post CQEs while failing linked requests */
908 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
909 /* single poll may be active */
910 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
911 /* double poll may active */
912 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
913 /* request has already done partial IO */
914 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
915 /* fast poll multishot mode */
916 REQ_F_APOLL_MULTISHOT = BIT(REQ_F_APOLL_MULTISHOT_BIT),
917 /* ->extra1 and ->extra2 are initialised */
918 REQ_F_CQE32_INIT = BIT(REQ_F_CQE32_INIT_BIT),
922 struct io_poll_iocb poll;
923 struct io_poll_iocb *double_poll;
926 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
928 struct io_task_work {
930 struct io_wq_work_node node;
931 struct llist_node fallback_node;
933 io_req_tw_func_t func;
937 IORING_RSRC_FILE = 0,
938 IORING_RSRC_BUFFER = 1,
944 /* fd initially, then cflags for completion */
952 IO_CHECK_CQ_OVERFLOW_BIT,
953 IO_CHECK_CQ_DROPPED_BIT,
957 * NOTE! Each of the iocb union members has the file pointer
958 * as the first entry in their struct definition. So you can
959 * access the file pointer through any of the sub-structs,
960 * or directly as just 'file' in this struct.
966 struct io_poll_iocb poll;
967 struct io_poll_update poll_update;
968 struct io_accept accept;
970 struct io_cancel cancel;
971 struct io_timeout timeout;
972 struct io_timeout_rem timeout_rem;
973 struct io_connect connect;
974 struct io_sr_msg sr_msg;
976 struct io_close close;
977 struct io_rsrc_update rsrc_update;
978 struct io_fadvise fadvise;
979 struct io_madvise madvise;
980 struct io_epoll epoll;
981 struct io_splice splice;
982 struct io_provide_buf pbuf;
983 struct io_statx statx;
984 struct io_shutdown shutdown;
985 struct io_rename rename;
986 struct io_unlink unlink;
987 struct io_mkdir mkdir;
988 struct io_symlink symlink;
989 struct io_hardlink hardlink;
991 struct io_xattr xattr;
992 struct io_socket sock;
993 struct io_uring_cmd uring_cmd;
997 /* polled IO has completed */
1000 * Can be either a fixed buffer index, or used with provided buffers.
1001 * For the latter, before issue it points to the buffer group ID,
1002 * and after selection it points to the buffer ID itself.
1009 struct io_ring_ctx *ctx;
1010 struct task_struct *task;
1012 struct io_rsrc_node *rsrc_node;
1015 /* store used ubuf, so we can prevent reloading */
1016 struct io_mapped_ubuf *imu;
1018 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
1019 struct io_buffer *kbuf;
1022 * stores buffer ID for ring provided buffers, valid IFF
1023 * REQ_F_BUFFER_RING is set.
1025 struct io_buffer_list *buf_list;
1029 /* used by request caches, completion batching and iopoll */
1030 struct io_wq_work_node comp_list;
1031 /* cache ->apoll->events */
1032 __poll_t apoll_events;
1036 struct io_task_work io_task_work;
1037 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1039 struct hlist_node hash_node;
1045 /* internal polling, see IORING_FEAT_FAST_POLL */
1046 struct async_poll *apoll;
1047 /* opcode allocated if it needs to store data for async defer */
1049 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1050 struct io_kiocb *link;
1051 /* custom credentials, valid IFF REQ_F_CREDS is set */
1052 const struct cred *creds;
1053 struct io_wq_work work;
1056 struct io_tctx_node {
1057 struct list_head ctx_node;
1058 struct task_struct *task;
1059 struct io_ring_ctx *ctx;
1062 struct io_defer_entry {
1063 struct list_head list;
1064 struct io_kiocb *req;
1068 struct io_cancel_data {
1069 struct io_ring_ctx *ctx;
1079 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
1080 * the following sqe if SQE128 is used.
1082 #define uring_cmd_pdu_size(is_sqe128) \
1083 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
1084 offsetof(struct io_uring_sqe, cmd))
1087 /* needs req->file assigned */
1088 unsigned needs_file : 1;
1089 /* should block plug */
1091 /* hash wq insertion if file is a regular file */
1092 unsigned hash_reg_file : 1;
1093 /* unbound wq insertion if file is a non-regular file */
1094 unsigned unbound_nonreg_file : 1;
1095 /* set if opcode supports polled "wait" */
1096 unsigned pollin : 1;
1097 unsigned pollout : 1;
1098 unsigned poll_exclusive : 1;
1099 /* op supports buffer selection */
1100 unsigned buffer_select : 1;
1101 /* do prep async if is going to be punted */
1102 unsigned needs_async_setup : 1;
1103 /* opcode is not supported by this kernel */
1104 unsigned not_supported : 1;
1106 unsigned audit_skip : 1;
1107 /* supports ioprio */
1108 unsigned ioprio : 1;
1109 /* supports iopoll */
1110 unsigned iopoll : 1;
1111 /* size of async data needed, if any */
1112 unsigned short async_size;
1114 int (*prep)(struct io_kiocb *, const struct io_uring_sqe *);
1115 int (*issue)(struct io_kiocb *, unsigned int);
1118 static const struct io_op_def io_op_defs[];
1120 /* requests with any of those set should undergo io_disarm_next() */
1121 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1122 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1124 static bool io_disarm_next(struct io_kiocb *req);
1125 static void io_uring_del_tctx_node(unsigned long index);
1126 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1127 struct task_struct *task,
1129 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1131 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1132 static void io_dismantle_req(struct io_kiocb *req);
1133 static void io_queue_linked_timeout(struct io_kiocb *req);
1134 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1135 struct io_uring_rsrc_update2 *up,
1137 static void io_clean_op(struct io_kiocb *req);
1138 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1139 unsigned issue_flags);
1140 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1141 static void io_queue_sqe(struct io_kiocb *req);
1142 static void io_rsrc_put_work(struct work_struct *work);
1144 static void io_req_task_queue(struct io_kiocb *req);
1145 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1146 static int io_req_prep_async(struct io_kiocb *req);
1148 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1149 unsigned int issue_flags, u32 slot_index);
1150 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
1151 unsigned int offset);
1152 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1154 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1155 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1156 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1158 static struct kmem_cache *req_cachep;
1160 static const struct file_operations io_uring_fops;
1162 const char *io_uring_get_opcode(u8 opcode)
1164 switch ((enum io_uring_op)opcode) {
1167 case IORING_OP_READV:
1169 case IORING_OP_WRITEV:
1171 case IORING_OP_FSYNC:
1173 case IORING_OP_READ_FIXED:
1174 return "READ_FIXED";
1175 case IORING_OP_WRITE_FIXED:
1176 return "WRITE_FIXED";
1177 case IORING_OP_POLL_ADD:
1179 case IORING_OP_POLL_REMOVE:
1180 return "POLL_REMOVE";
1181 case IORING_OP_SYNC_FILE_RANGE:
1182 return "SYNC_FILE_RANGE";
1183 case IORING_OP_SENDMSG:
1185 case IORING_OP_RECVMSG:
1187 case IORING_OP_TIMEOUT:
1189 case IORING_OP_TIMEOUT_REMOVE:
1190 return "TIMEOUT_REMOVE";
1191 case IORING_OP_ACCEPT:
1193 case IORING_OP_ASYNC_CANCEL:
1194 return "ASYNC_CANCEL";
1195 case IORING_OP_LINK_TIMEOUT:
1196 return "LINK_TIMEOUT";
1197 case IORING_OP_CONNECT:
1199 case IORING_OP_FALLOCATE:
1201 case IORING_OP_OPENAT:
1203 case IORING_OP_CLOSE:
1205 case IORING_OP_FILES_UPDATE:
1206 return "FILES_UPDATE";
1207 case IORING_OP_STATX:
1209 case IORING_OP_READ:
1211 case IORING_OP_WRITE:
1213 case IORING_OP_FADVISE:
1215 case IORING_OP_MADVISE:
1217 case IORING_OP_SEND:
1219 case IORING_OP_RECV:
1221 case IORING_OP_OPENAT2:
1223 case IORING_OP_EPOLL_CTL:
1225 case IORING_OP_SPLICE:
1227 case IORING_OP_PROVIDE_BUFFERS:
1228 return "PROVIDE_BUFFERS";
1229 case IORING_OP_REMOVE_BUFFERS:
1230 return "REMOVE_BUFFERS";
1233 case IORING_OP_SHUTDOWN:
1235 case IORING_OP_RENAMEAT:
1237 case IORING_OP_UNLINKAT:
1239 case IORING_OP_MKDIRAT:
1241 case IORING_OP_SYMLINKAT:
1243 case IORING_OP_LINKAT:
1245 case IORING_OP_MSG_RING:
1247 case IORING_OP_FSETXATTR:
1249 case IORING_OP_SETXATTR:
1251 case IORING_OP_FGETXATTR:
1253 case IORING_OP_GETXATTR:
1255 case IORING_OP_SOCKET:
1257 case IORING_OP_URING_CMD:
1259 case IORING_OP_LAST:
1265 struct sock *io_uring_get_socket(struct file *file)
1267 #if defined(CONFIG_UNIX)
1268 if (file->f_op == &io_uring_fops) {
1269 struct io_ring_ctx *ctx = file->private_data;
1271 return ctx->ring_sock->sk;
1276 EXPORT_SYMBOL(io_uring_get_socket);
1278 #if defined(CONFIG_UNIX)
1279 static inline bool io_file_need_scm(struct file *filp)
1281 #if defined(IO_URING_SCM_ALL)
1284 return !!unix_get_socket(filp);
1288 static inline bool io_file_need_scm(struct file *filp)
1294 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1296 lockdep_assert_held(&ctx->uring_lock);
1297 if (issue_flags & IO_URING_F_UNLOCKED)
1298 mutex_unlock(&ctx->uring_lock);
1301 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1304 * "Normal" inline submissions always hold the uring_lock, since we
1305 * grab it from the system call. Same is true for the SQPOLL offload.
1306 * The only exception is when we've detached the request and issue it
1307 * from an async worker thread, grab the lock for that case.
1309 if (issue_flags & IO_URING_F_UNLOCKED)
1310 mutex_lock(&ctx->uring_lock);
1311 lockdep_assert_held(&ctx->uring_lock);
1314 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1317 mutex_lock(&ctx->uring_lock);
1322 #define io_for_each_link(pos, head) \
1323 for (pos = (head); pos; pos = pos->link)
1326 * Shamelessly stolen from the mm implementation of page reference checking,
1327 * see commit f958d7b528b1 for details.
1329 #define req_ref_zero_or_close_to_overflow(req) \
1330 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1332 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1334 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1335 return atomic_inc_not_zero(&req->refs);
1338 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1340 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1343 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1344 return atomic_dec_and_test(&req->refs);
1347 static inline void req_ref_get(struct io_kiocb *req)
1349 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1350 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1351 atomic_inc(&req->refs);
1354 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1356 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1357 __io_submit_flush_completions(ctx);
1360 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1362 if (!(req->flags & REQ_F_REFCOUNT)) {
1363 req->flags |= REQ_F_REFCOUNT;
1364 atomic_set(&req->refs, nr);
1368 static inline void io_req_set_refcount(struct io_kiocb *req)
1370 __io_req_set_refcount(req, 1);
1373 #define IO_RSRC_REF_BATCH 100
1375 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1377 percpu_ref_put_many(&node->refs, nr);
1380 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1381 struct io_ring_ctx *ctx)
1382 __must_hold(&ctx->uring_lock)
1384 struct io_rsrc_node *node = req->rsrc_node;
1387 if (node == ctx->rsrc_node)
1388 ctx->rsrc_cached_refs++;
1390 io_rsrc_put_node(node, 1);
1394 static inline void io_req_put_rsrc(struct io_kiocb *req)
1397 io_rsrc_put_node(req->rsrc_node, 1);
1400 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1401 __must_hold(&ctx->uring_lock)
1403 if (ctx->rsrc_cached_refs) {
1404 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1405 ctx->rsrc_cached_refs = 0;
1409 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1410 __must_hold(&ctx->uring_lock)
1412 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1413 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1416 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1417 struct io_ring_ctx *ctx,
1418 unsigned int issue_flags)
1420 if (!req->rsrc_node) {
1421 req->rsrc_node = ctx->rsrc_node;
1423 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1424 lockdep_assert_held(&ctx->uring_lock);
1425 ctx->rsrc_cached_refs--;
1426 if (unlikely(ctx->rsrc_cached_refs < 0))
1427 io_rsrc_refs_refill(ctx);
1429 percpu_ref_get(&req->rsrc_node->refs);
1434 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1436 if (req->flags & REQ_F_BUFFER_RING) {
1438 req->buf_list->head++;
1439 req->flags &= ~REQ_F_BUFFER_RING;
1441 list_add(&req->kbuf->list, list);
1442 req->flags &= ~REQ_F_BUFFER_SELECTED;
1445 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1448 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1450 lockdep_assert_held(&req->ctx->completion_lock);
1452 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1454 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1457 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1458 unsigned issue_flags)
1460 unsigned int cflags;
1462 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1466 * We can add this buffer back to two lists:
1468 * 1) The io_buffers_cache list. This one is protected by the
1469 * ctx->uring_lock. If we already hold this lock, add back to this
1470 * list as we can grab it from issue as well.
1471 * 2) The io_buffers_comp list. This one is protected by the
1472 * ctx->completion_lock.
1474 * We migrate buffers from the comp_list to the issue cache list
1477 if (req->flags & REQ_F_BUFFER_RING) {
1478 /* no buffers to recycle for this case */
1479 cflags = __io_put_kbuf(req, NULL);
1480 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1481 struct io_ring_ctx *ctx = req->ctx;
1483 spin_lock(&ctx->completion_lock);
1484 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1485 spin_unlock(&ctx->completion_lock);
1487 lockdep_assert_held(&req->ctx->uring_lock);
1489 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1495 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1498 if (ctx->io_bl && bgid < BGID_ARRAY)
1499 return &ctx->io_bl[bgid];
1501 return xa_load(&ctx->io_bl_xa, bgid);
1504 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1506 struct io_ring_ctx *ctx = req->ctx;
1507 struct io_buffer_list *bl;
1508 struct io_buffer *buf;
1510 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1513 * For legacy provided buffer mode, don't recycle if we already did
1514 * IO to this buffer. For ring-mapped provided buffer mode, we should
1515 * increment ring->head to explicitly monopolize the buffer to avoid
1518 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
1519 (req->flags & REQ_F_PARTIAL_IO))
1523 * READV uses fields in `struct io_rw` (len/addr) to stash the selected
1524 * buffer data. However if that buffer is recycled the original request
1525 * data stored in addr is lost. Therefore forbid recycling for now.
1527 if (req->opcode == IORING_OP_READV)
1531 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1532 * the flag and hence ensure that bl->head doesn't get incremented.
1533 * If the tail has already been incremented, hang on to it.
1535 if (req->flags & REQ_F_BUFFER_RING) {
1536 if (req->buf_list) {
1537 if (req->flags & REQ_F_PARTIAL_IO) {
1538 req->buf_list->head++;
1539 req->buf_list = NULL;
1541 req->buf_index = req->buf_list->bgid;
1542 req->flags &= ~REQ_F_BUFFER_RING;
1548 io_ring_submit_lock(ctx, issue_flags);
1551 bl = io_buffer_get_list(ctx, buf->bgid);
1552 list_add(&buf->list, &bl->buf_list);
1553 req->flags &= ~REQ_F_BUFFER_SELECTED;
1554 req->buf_index = buf->bgid;
1556 io_ring_submit_unlock(ctx, issue_flags);
1559 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1561 __must_hold(&req->ctx->timeout_lock)
1563 struct io_kiocb *req;
1565 if (task && head->task != task)
1570 io_for_each_link(req, head) {
1571 if (req->flags & REQ_F_INFLIGHT)
1577 static bool io_match_linked(struct io_kiocb *head)
1579 struct io_kiocb *req;
1581 io_for_each_link(req, head) {
1582 if (req->flags & REQ_F_INFLIGHT)
1589 * As io_match_task() but protected against racing with linked timeouts.
1590 * User must not hold timeout_lock.
1592 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1597 if (task && head->task != task)
1602 if (head->flags & REQ_F_LINK_TIMEOUT) {
1603 struct io_ring_ctx *ctx = head->ctx;
1605 /* protect against races with linked timeouts */
1606 spin_lock_irq(&ctx->timeout_lock);
1607 matched = io_match_linked(head);
1608 spin_unlock_irq(&ctx->timeout_lock);
1610 matched = io_match_linked(head);
1615 static inline bool req_has_async_data(struct io_kiocb *req)
1617 return req->flags & REQ_F_ASYNC_DATA;
1620 static inline void req_set_fail(struct io_kiocb *req)
1622 req->flags |= REQ_F_FAIL;
1623 if (req->flags & REQ_F_CQE_SKIP) {
1624 req->flags &= ~REQ_F_CQE_SKIP;
1625 req->flags |= REQ_F_SKIP_LINK_CQES;
1629 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1635 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1637 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1640 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1642 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1644 complete(&ctx->ref_comp);
1647 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1649 return !req->timeout.off;
1652 static __cold void io_fallback_req_func(struct work_struct *work)
1654 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1655 fallback_work.work);
1656 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1657 struct io_kiocb *req, *tmp;
1658 bool locked = false;
1660 percpu_ref_get(&ctx->refs);
1661 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1662 req->io_task_work.func(req, &locked);
1665 io_submit_flush_completions(ctx);
1666 mutex_unlock(&ctx->uring_lock);
1668 percpu_ref_put(&ctx->refs);
1671 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1673 struct io_ring_ctx *ctx;
1676 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1680 xa_init(&ctx->io_bl_xa);
1683 * Use 5 bits less than the max cq entries, that should give us around
1684 * 32 entries per hash list if totally full and uniformly spread.
1686 hash_bits = ilog2(p->cq_entries);
1690 ctx->cancel_hash_bits = hash_bits;
1691 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1693 if (!ctx->cancel_hash)
1695 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1697 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1698 if (!ctx->dummy_ubuf)
1700 /* set invalid range, so io_import_fixed() fails meeting it */
1701 ctx->dummy_ubuf->ubuf = -1UL;
1703 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1707 ctx->flags = p->flags;
1708 init_waitqueue_head(&ctx->sqo_sq_wait);
1709 INIT_LIST_HEAD(&ctx->sqd_list);
1710 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1711 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1712 INIT_LIST_HEAD(&ctx->apoll_cache);
1713 init_completion(&ctx->ref_comp);
1714 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1715 mutex_init(&ctx->uring_lock);
1716 init_waitqueue_head(&ctx->cq_wait);
1717 spin_lock_init(&ctx->completion_lock);
1718 spin_lock_init(&ctx->timeout_lock);
1719 INIT_WQ_LIST(&ctx->iopoll_list);
1720 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1721 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1722 INIT_LIST_HEAD(&ctx->defer_list);
1723 INIT_LIST_HEAD(&ctx->timeout_list);
1724 INIT_LIST_HEAD(&ctx->ltimeout_list);
1725 spin_lock_init(&ctx->rsrc_ref_lock);
1726 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1727 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1728 init_llist_head(&ctx->rsrc_put_llist);
1729 INIT_LIST_HEAD(&ctx->tctx_list);
1730 ctx->submit_state.free_list.next = NULL;
1731 INIT_WQ_LIST(&ctx->locked_free_list);
1732 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1733 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1736 kfree(ctx->dummy_ubuf);
1737 kfree(ctx->cancel_hash);
1739 xa_destroy(&ctx->io_bl_xa);
1744 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1746 struct io_rings *r = ctx->rings;
1748 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1752 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1754 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1755 struct io_ring_ctx *ctx = req->ctx;
1757 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1763 static inline bool io_req_ffs_set(struct io_kiocb *req)
1765 return req->flags & REQ_F_FIXED_FILE;
1768 static inline void io_req_track_inflight(struct io_kiocb *req)
1770 if (!(req->flags & REQ_F_INFLIGHT)) {
1771 req->flags |= REQ_F_INFLIGHT;
1772 atomic_inc(&req->task->io_uring->inflight_tracked);
1776 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1778 if (WARN_ON_ONCE(!req->link))
1781 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1782 req->flags |= REQ_F_LINK_TIMEOUT;
1784 /* linked timeouts should have two refs once prep'ed */
1785 io_req_set_refcount(req);
1786 __io_req_set_refcount(req->link, 2);
1790 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1792 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1794 return __io_prep_linked_timeout(req);
1797 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1799 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1802 static inline void io_arm_ltimeout(struct io_kiocb *req)
1804 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1805 __io_arm_ltimeout(req);
1808 static void io_prep_async_work(struct io_kiocb *req)
1810 const struct io_op_def *def = &io_op_defs[req->opcode];
1811 struct io_ring_ctx *ctx = req->ctx;
1813 if (!(req->flags & REQ_F_CREDS)) {
1814 req->flags |= REQ_F_CREDS;
1815 req->creds = get_current_cred();
1818 req->work.list.next = NULL;
1819 req->work.flags = 0;
1820 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1821 if (req->flags & REQ_F_FORCE_ASYNC)
1822 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1824 if (req->flags & REQ_F_ISREG) {
1825 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1826 io_wq_hash_work(&req->work, file_inode(req->file));
1827 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1828 if (def->unbound_nonreg_file)
1829 req->work.flags |= IO_WQ_WORK_UNBOUND;
1833 static void io_prep_async_link(struct io_kiocb *req)
1835 struct io_kiocb *cur;
1837 if (req->flags & REQ_F_LINK_TIMEOUT) {
1838 struct io_ring_ctx *ctx = req->ctx;
1840 spin_lock_irq(&ctx->timeout_lock);
1841 io_for_each_link(cur, req)
1842 io_prep_async_work(cur);
1843 spin_unlock_irq(&ctx->timeout_lock);
1845 io_for_each_link(cur, req)
1846 io_prep_async_work(cur);
1850 static inline void io_req_add_compl_list(struct io_kiocb *req)
1852 struct io_submit_state *state = &req->ctx->submit_state;
1854 if (!(req->flags & REQ_F_CQE_SKIP))
1855 state->flush_cqes = true;
1856 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1859 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1861 struct io_kiocb *link = io_prep_linked_timeout(req);
1862 struct io_uring_task *tctx = req->task->io_uring;
1865 BUG_ON(!tctx->io_wq);
1867 /* init ->work of the whole link before punting */
1868 io_prep_async_link(req);
1871 * Not expected to happen, but if we do have a bug where this _can_
1872 * happen, catch it here and ensure the request is marked as
1873 * canceled. That will make io-wq go through the usual work cancel
1874 * procedure rather than attempt to run this request (or create a new
1877 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1878 req->work.flags |= IO_WQ_WORK_CANCEL;
1880 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1881 req->opcode, req->flags, &req->work,
1882 io_wq_is_hashed(&req->work));
1883 io_wq_enqueue(tctx->io_wq, &req->work);
1885 io_queue_linked_timeout(link);
1888 static void io_kill_timeout(struct io_kiocb *req, int status)
1889 __must_hold(&req->ctx->completion_lock)
1890 __must_hold(&req->ctx->timeout_lock)
1892 struct io_timeout_data *io = req->async_data;
1894 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1897 atomic_set(&req->ctx->cq_timeouts,
1898 atomic_read(&req->ctx->cq_timeouts) + 1);
1899 list_del_init(&req->timeout.list);
1900 io_req_tw_post_queue(req, status, 0);
1904 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1906 while (!list_empty(&ctx->defer_list)) {
1907 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1908 struct io_defer_entry, list);
1910 if (req_need_defer(de->req, de->seq))
1912 list_del_init(&de->list);
1913 io_req_task_queue(de->req);
1918 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1919 __must_hold(&ctx->completion_lock)
1921 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1922 struct io_kiocb *req, *tmp;
1924 spin_lock_irq(&ctx->timeout_lock);
1925 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1926 u32 events_needed, events_got;
1928 if (io_is_timeout_noseq(req))
1932 * Since seq can easily wrap around over time, subtract
1933 * the last seq at which timeouts were flushed before comparing.
1934 * Assuming not more than 2^31-1 events have happened since,
1935 * these subtractions won't have wrapped, so we can check if
1936 * target is in [last_seq, current_seq] by comparing the two.
1938 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1939 events_got = seq - ctx->cq_last_tm_flush;
1940 if (events_got < events_needed)
1943 io_kill_timeout(req, 0);
1945 ctx->cq_last_tm_flush = seq;
1946 spin_unlock_irq(&ctx->timeout_lock);
1949 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1951 /* order cqe stores with ring update */
1952 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1955 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1957 if (ctx->off_timeout_used || ctx->drain_active) {
1958 spin_lock(&ctx->completion_lock);
1959 if (ctx->off_timeout_used)
1960 io_flush_timeouts(ctx);
1961 if (ctx->drain_active)
1962 io_queue_deferred(ctx);
1963 io_commit_cqring(ctx);
1964 spin_unlock(&ctx->completion_lock);
1967 io_eventfd_signal(ctx);
1970 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1972 struct io_rings *r = ctx->rings;
1974 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1977 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1979 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1983 * writes to the cq entry need to come after reading head; the
1984 * control dependency is enough as we're using WRITE_ONCE to
1987 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1989 struct io_rings *rings = ctx->rings;
1990 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1991 unsigned int shift = 0;
1992 unsigned int free, queued, len;
1994 if (ctx->flags & IORING_SETUP_CQE32)
1997 /* userspace may cheat modifying the tail, be safe and do min */
1998 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
1999 free = ctx->cq_entries - queued;
2000 /* we need a contiguous range, limit based on the current array offset */
2001 len = min(free, ctx->cq_entries - off);
2005 ctx->cached_cq_tail++;
2006 ctx->cqe_cached = &rings->cqes[off];
2007 ctx->cqe_sentinel = ctx->cqe_cached + len;
2009 return &rings->cqes[off << shift];
2012 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2014 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2015 struct io_uring_cqe *cqe = ctx->cqe_cached;
2017 if (ctx->flags & IORING_SETUP_CQE32) {
2018 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2023 ctx->cached_cq_tail++;
2028 return __io_get_cqe(ctx);
2031 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2033 struct io_ev_fd *ev_fd;
2037 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2038 * and eventfd_signal
2040 ev_fd = rcu_dereference(ctx->io_ev_fd);
2043 * Check again if ev_fd exists incase an io_eventfd_unregister call
2044 * completed between the NULL check of ctx->io_ev_fd at the start of
2045 * the function and rcu_read_lock.
2047 if (unlikely(!ev_fd))
2049 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2052 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2053 eventfd_signal(ev_fd->cq_ev_fd, 1);
2058 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2061 * wake_up_all() may seem excessive, but io_wake_function() and
2062 * io_should_wake() handle the termination of the loop and only
2063 * wake as many waiters as we need to.
2065 if (wq_has_sleeper(&ctx->cq_wait))
2066 wake_up_all(&ctx->cq_wait);
2070 * This should only get called when at least one event has been posted.
2071 * Some applications rely on the eventfd notification count only changing
2072 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2073 * 1:1 relationship between how many times this function is called (and
2074 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2076 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2078 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2080 __io_commit_cqring_flush(ctx);
2082 io_cqring_wake(ctx);
2085 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2087 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2089 __io_commit_cqring_flush(ctx);
2091 if (ctx->flags & IORING_SETUP_SQPOLL)
2092 io_cqring_wake(ctx);
2095 /* Returns true if there are no backlogged entries after the flush */
2096 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2098 bool all_flushed, posted;
2099 size_t cqe_size = sizeof(struct io_uring_cqe);
2101 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2104 if (ctx->flags & IORING_SETUP_CQE32)
2108 spin_lock(&ctx->completion_lock);
2109 while (!list_empty(&ctx->cq_overflow_list)) {
2110 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2111 struct io_overflow_cqe *ocqe;
2115 ocqe = list_first_entry(&ctx->cq_overflow_list,
2116 struct io_overflow_cqe, list);
2118 memcpy(cqe, &ocqe->cqe, cqe_size);
2120 io_account_cq_overflow(ctx);
2123 list_del(&ocqe->list);
2127 all_flushed = list_empty(&ctx->cq_overflow_list);
2129 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2130 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2133 io_commit_cqring(ctx);
2134 spin_unlock(&ctx->completion_lock);
2136 io_cqring_ev_posted(ctx);
2140 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2144 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2145 /* iopoll syncs against uring_lock, not completion_lock */
2146 if (ctx->flags & IORING_SETUP_IOPOLL)
2147 mutex_lock(&ctx->uring_lock);
2148 ret = __io_cqring_overflow_flush(ctx, false);
2149 if (ctx->flags & IORING_SETUP_IOPOLL)
2150 mutex_unlock(&ctx->uring_lock);
2156 static void __io_put_task(struct task_struct *task, int nr)
2158 struct io_uring_task *tctx = task->io_uring;
2160 percpu_counter_sub(&tctx->inflight, nr);
2161 if (unlikely(atomic_read(&tctx->in_idle)))
2162 wake_up(&tctx->wait);
2163 put_task_struct_many(task, nr);
2166 /* must to be called somewhat shortly after putting a request */
2167 static inline void io_put_task(struct task_struct *task, int nr)
2169 if (likely(task == current))
2170 task->io_uring->cached_refs += nr;
2172 __io_put_task(task, nr);
2175 static void io_task_refs_refill(struct io_uring_task *tctx)
2177 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2179 percpu_counter_add(&tctx->inflight, refill);
2180 refcount_add(refill, ¤t->usage);
2181 tctx->cached_refs += refill;
2184 static inline void io_get_task_refs(int nr)
2186 struct io_uring_task *tctx = current->io_uring;
2188 tctx->cached_refs -= nr;
2189 if (unlikely(tctx->cached_refs < 0))
2190 io_task_refs_refill(tctx);
2193 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2195 struct io_uring_task *tctx = task->io_uring;
2196 unsigned int refs = tctx->cached_refs;
2199 tctx->cached_refs = 0;
2200 percpu_counter_sub(&tctx->inflight, refs);
2201 put_task_struct_many(task, refs);
2205 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2206 s32 res, u32 cflags, u64 extra1,
2209 struct io_overflow_cqe *ocqe;
2210 size_t ocq_size = sizeof(struct io_overflow_cqe);
2211 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2214 ocq_size += sizeof(struct io_uring_cqe);
2216 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2217 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2220 * If we're in ring overflow flush mode, or in task cancel mode,
2221 * or cannot allocate an overflow entry, then we need to drop it
2224 io_account_cq_overflow(ctx);
2225 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2228 if (list_empty(&ctx->cq_overflow_list)) {
2229 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2230 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2233 ocqe->cqe.user_data = user_data;
2234 ocqe->cqe.res = res;
2235 ocqe->cqe.flags = cflags;
2237 ocqe->cqe.big_cqe[0] = extra1;
2238 ocqe->cqe.big_cqe[1] = extra2;
2240 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2244 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
2245 struct io_kiocb *req)
2247 struct io_uring_cqe *cqe;
2249 if (!(ctx->flags & IORING_SETUP_CQE32)) {
2250 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2251 req->cqe.res, req->cqe.flags, 0, 0);
2254 * If we can't get a cq entry, userspace overflowed the
2255 * submission (by quite a lot). Increment the overflow count in
2258 cqe = io_get_cqe(ctx);
2260 memcpy(cqe, &req->cqe, sizeof(*cqe));
2264 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2265 req->cqe.res, req->cqe.flags,
2268 u64 extra1 = 0, extra2 = 0;
2270 if (req->flags & REQ_F_CQE32_INIT) {
2271 extra1 = req->extra1;
2272 extra2 = req->extra2;
2275 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2276 req->cqe.res, req->cqe.flags, extra1, extra2);
2279 * If we can't get a cq entry, userspace overflowed the
2280 * submission (by quite a lot). Increment the overflow count in
2283 cqe = io_get_cqe(ctx);
2285 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2286 WRITE_ONCE(cqe->big_cqe[0], extra1);
2287 WRITE_ONCE(cqe->big_cqe[1], extra2);
2291 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2292 req->cqe.res, req->cqe.flags,
2297 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2298 s32 res, u32 cflags)
2300 struct io_uring_cqe *cqe;
2303 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2306 * If we can't get a cq entry, userspace overflowed the
2307 * submission (by quite a lot). Increment the overflow count in
2310 cqe = io_get_cqe(ctx);
2312 WRITE_ONCE(cqe->user_data, user_data);
2313 WRITE_ONCE(cqe->res, res);
2314 WRITE_ONCE(cqe->flags, cflags);
2316 if (ctx->flags & IORING_SETUP_CQE32) {
2317 WRITE_ONCE(cqe->big_cqe[0], 0);
2318 WRITE_ONCE(cqe->big_cqe[1], 0);
2322 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2325 static void __io_req_complete_put(struct io_kiocb *req)
2328 * If we're the last reference to this request, add to our locked
2331 if (req_ref_put_and_test(req)) {
2332 struct io_ring_ctx *ctx = req->ctx;
2334 if (req->flags & IO_REQ_LINK_FLAGS) {
2335 if (req->flags & IO_DISARM_MASK)
2336 io_disarm_next(req);
2338 io_req_task_queue(req->link);
2342 io_req_put_rsrc(req);
2344 * Selected buffer deallocation in io_clean_op() assumes that
2345 * we don't hold ->completion_lock. Clean them here to avoid
2348 io_put_kbuf_comp(req);
2349 io_dismantle_req(req);
2350 io_put_task(req->task, 1);
2351 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2352 ctx->locked_free_nr++;
2356 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2359 if (!(req->flags & REQ_F_CQE_SKIP)) {
2361 req->cqe.flags = cflags;
2362 __io_fill_cqe_req(req->ctx, req);
2364 __io_req_complete_put(req);
2367 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2369 struct io_ring_ctx *ctx = req->ctx;
2371 spin_lock(&ctx->completion_lock);
2372 __io_req_complete_post(req, res, cflags);
2373 io_commit_cqring(ctx);
2374 spin_unlock(&ctx->completion_lock);
2375 io_cqring_ev_posted(ctx);
2378 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2382 req->cqe.flags = cflags;
2383 req->flags |= REQ_F_COMPLETE_INLINE;
2386 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2387 s32 res, u32 cflags)
2389 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2390 io_req_complete_state(req, res, cflags);
2392 io_req_complete_post(req, res, cflags);
2395 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2399 __io_req_complete(req, 0, res, 0);
2402 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2405 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2409 * Don't initialise the fields below on every allocation, but do that in
2410 * advance and keep them valid across allocations.
2412 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2416 req->async_data = NULL;
2417 /* not necessary, but safer to zero */
2421 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2422 struct io_submit_state *state)
2424 spin_lock(&ctx->completion_lock);
2425 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2426 ctx->locked_free_nr = 0;
2427 spin_unlock(&ctx->completion_lock);
2430 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2432 return !ctx->submit_state.free_list.next;
2436 * A request might get retired back into the request caches even before opcode
2437 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2438 * Because of that, io_alloc_req() should be called only under ->uring_lock
2439 * and with extra caution to not get a request that is still worked on.
2441 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2442 __must_hold(&ctx->uring_lock)
2444 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2445 void *reqs[IO_REQ_ALLOC_BATCH];
2449 * If we have more than a batch's worth of requests in our IRQ side
2450 * locked cache, grab the lock and move them over to our submission
2453 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2454 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2455 if (!io_req_cache_empty(ctx))
2459 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2462 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2463 * retry single alloc to be on the safe side.
2465 if (unlikely(ret <= 0)) {
2466 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2472 percpu_ref_get_many(&ctx->refs, ret);
2473 for (i = 0; i < ret; i++) {
2474 struct io_kiocb *req = reqs[i];
2476 io_preinit_req(req, ctx);
2477 io_req_add_to_cache(req, ctx);
2482 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2484 if (unlikely(io_req_cache_empty(ctx)))
2485 return __io_alloc_req_refill(ctx);
2489 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2491 struct io_wq_work_node *node;
2493 node = wq_stack_extract(&ctx->submit_state.free_list);
2494 return container_of(node, struct io_kiocb, comp_list);
2497 static inline void io_put_file(struct file *file)
2503 static inline void io_dismantle_req(struct io_kiocb *req)
2505 unsigned int flags = req->flags;
2507 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2509 if (!(flags & REQ_F_FIXED_FILE))
2510 io_put_file(req->file);
2513 static __cold void io_free_req(struct io_kiocb *req)
2515 struct io_ring_ctx *ctx = req->ctx;
2517 io_req_put_rsrc(req);
2518 io_dismantle_req(req);
2519 io_put_task(req->task, 1);
2521 spin_lock(&ctx->completion_lock);
2522 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2523 ctx->locked_free_nr++;
2524 spin_unlock(&ctx->completion_lock);
2527 static inline void io_remove_next_linked(struct io_kiocb *req)
2529 struct io_kiocb *nxt = req->link;
2531 req->link = nxt->link;
2535 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2536 __must_hold(&req->ctx->completion_lock)
2537 __must_hold(&req->ctx->timeout_lock)
2539 struct io_kiocb *link = req->link;
2541 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2542 struct io_timeout_data *io = link->async_data;
2544 io_remove_next_linked(req);
2545 link->timeout.head = NULL;
2546 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2547 list_del(&link->timeout.list);
2554 static void io_fail_links(struct io_kiocb *req)
2555 __must_hold(&req->ctx->completion_lock)
2557 struct io_kiocb *nxt, *link = req->link;
2558 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2562 long res = -ECANCELED;
2564 if (link->flags & REQ_F_FAIL)
2565 res = link->cqe.res;
2570 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2574 link->flags |= REQ_F_CQE_SKIP;
2576 link->flags &= ~REQ_F_CQE_SKIP;
2577 __io_req_complete_post(link, res, 0);
2582 static bool io_disarm_next(struct io_kiocb *req)
2583 __must_hold(&req->ctx->completion_lock)
2585 struct io_kiocb *link = NULL;
2586 bool posted = false;
2588 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2590 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2591 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2592 io_remove_next_linked(req);
2593 io_req_tw_post_queue(link, -ECANCELED, 0);
2596 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2597 struct io_ring_ctx *ctx = req->ctx;
2599 spin_lock_irq(&ctx->timeout_lock);
2600 link = io_disarm_linked_timeout(req);
2601 spin_unlock_irq(&ctx->timeout_lock);
2604 io_req_tw_post_queue(link, -ECANCELED, 0);
2607 if (unlikely((req->flags & REQ_F_FAIL) &&
2608 !(req->flags & REQ_F_HARDLINK))) {
2609 posted |= (req->link != NULL);
2615 static void __io_req_find_next_prep(struct io_kiocb *req)
2617 struct io_ring_ctx *ctx = req->ctx;
2620 spin_lock(&ctx->completion_lock);
2621 posted = io_disarm_next(req);
2622 io_commit_cqring(ctx);
2623 spin_unlock(&ctx->completion_lock);
2625 io_cqring_ev_posted(ctx);
2628 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2630 struct io_kiocb *nxt;
2633 * If LINK is set, we have dependent requests in this chain. If we
2634 * didn't fail this request, queue the first one up, moving any other
2635 * dependencies to the next request. In case of failure, fail the rest
2638 if (unlikely(req->flags & IO_DISARM_MASK))
2639 __io_req_find_next_prep(req);
2645 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2649 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2650 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2652 io_submit_flush_completions(ctx);
2653 mutex_unlock(&ctx->uring_lock);
2656 percpu_ref_put(&ctx->refs);
2659 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2661 io_commit_cqring(ctx);
2662 spin_unlock(&ctx->completion_lock);
2663 io_cqring_ev_posted(ctx);
2666 static void handle_prev_tw_list(struct io_wq_work_node *node,
2667 struct io_ring_ctx **ctx, bool *uring_locked)
2669 if (*ctx && !*uring_locked)
2670 spin_lock(&(*ctx)->completion_lock);
2673 struct io_wq_work_node *next = node->next;
2674 struct io_kiocb *req = container_of(node, struct io_kiocb,
2677 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2679 if (req->ctx != *ctx) {
2680 if (unlikely(!*uring_locked && *ctx))
2681 ctx_commit_and_unlock(*ctx);
2683 ctx_flush_and_put(*ctx, uring_locked);
2685 /* if not contended, grab and improve batching */
2686 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2687 percpu_ref_get(&(*ctx)->refs);
2688 if (unlikely(!*uring_locked))
2689 spin_lock(&(*ctx)->completion_lock);
2691 if (likely(*uring_locked))
2692 req->io_task_work.func(req, uring_locked);
2694 __io_req_complete_post(req, req->cqe.res,
2695 io_put_kbuf_comp(req));
2699 if (unlikely(!*uring_locked))
2700 ctx_commit_and_unlock(*ctx);
2703 static void handle_tw_list(struct io_wq_work_node *node,
2704 struct io_ring_ctx **ctx, bool *locked)
2707 struct io_wq_work_node *next = node->next;
2708 struct io_kiocb *req = container_of(node, struct io_kiocb,
2711 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2713 if (req->ctx != *ctx) {
2714 ctx_flush_and_put(*ctx, locked);
2716 /* if not contended, grab and improve batching */
2717 *locked = mutex_trylock(&(*ctx)->uring_lock);
2718 percpu_ref_get(&(*ctx)->refs);
2720 req->io_task_work.func(req, locked);
2725 static void tctx_task_work(struct callback_head *cb)
2727 bool uring_locked = false;
2728 struct io_ring_ctx *ctx = NULL;
2729 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2733 struct io_wq_work_node *node1, *node2;
2735 spin_lock_irq(&tctx->task_lock);
2736 node1 = tctx->prio_task_list.first;
2737 node2 = tctx->task_list.first;
2738 INIT_WQ_LIST(&tctx->task_list);
2739 INIT_WQ_LIST(&tctx->prio_task_list);
2740 if (!node2 && !node1)
2741 tctx->task_running = false;
2742 spin_unlock_irq(&tctx->task_lock);
2743 if (!node2 && !node1)
2747 handle_prev_tw_list(node1, &ctx, &uring_locked);
2749 handle_tw_list(node2, &ctx, &uring_locked);
2752 if (data_race(!tctx->task_list.first) &&
2753 data_race(!tctx->prio_task_list.first) && uring_locked)
2754 io_submit_flush_completions(ctx);
2757 ctx_flush_and_put(ctx, &uring_locked);
2759 /* relaxed read is enough as only the task itself sets ->in_idle */
2760 if (unlikely(atomic_read(&tctx->in_idle)))
2761 io_uring_drop_tctx_refs(current);
2764 static void __io_req_task_work_add(struct io_kiocb *req,
2765 struct io_uring_task *tctx,
2766 struct io_wq_work_list *list)
2768 struct io_ring_ctx *ctx = req->ctx;
2769 struct io_wq_work_node *node;
2770 unsigned long flags;
2773 spin_lock_irqsave(&tctx->task_lock, flags);
2774 wq_list_add_tail(&req->io_task_work.node, list);
2775 running = tctx->task_running;
2777 tctx->task_running = true;
2778 spin_unlock_irqrestore(&tctx->task_lock, flags);
2780 /* task_work already pending, we're done */
2784 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2785 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2787 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2790 spin_lock_irqsave(&tctx->task_lock, flags);
2791 tctx->task_running = false;
2792 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2793 spin_unlock_irqrestore(&tctx->task_lock, flags);
2796 req = container_of(node, struct io_kiocb, io_task_work.node);
2798 if (llist_add(&req->io_task_work.fallback_node,
2799 &req->ctx->fallback_llist))
2800 schedule_delayed_work(&req->ctx->fallback_work, 1);
2804 static void io_req_task_work_add(struct io_kiocb *req)
2806 struct io_uring_task *tctx = req->task->io_uring;
2808 __io_req_task_work_add(req, tctx, &tctx->task_list);
2811 static void io_req_task_prio_work_add(struct io_kiocb *req)
2813 struct io_uring_task *tctx = req->task->io_uring;
2815 if (req->ctx->flags & IORING_SETUP_SQPOLL)
2816 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
2818 __io_req_task_work_add(req, tctx, &tctx->task_list);
2821 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2823 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2826 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2829 req->cqe.flags = cflags;
2830 req->io_task_work.func = io_req_tw_post;
2831 io_req_task_work_add(req);
2834 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2836 /* not needed for normal modes, but SQPOLL depends on it */
2837 io_tw_lock(req->ctx, locked);
2838 io_req_complete_failed(req, req->cqe.res);
2841 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2843 io_tw_lock(req->ctx, locked);
2844 /* req->task == current here, checking PF_EXITING is safe */
2845 if (likely(!(req->task->flags & PF_EXITING)))
2848 io_req_complete_failed(req, -EFAULT);
2851 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2854 req->io_task_work.func = io_req_task_cancel;
2855 io_req_task_work_add(req);
2858 static void io_req_task_queue(struct io_kiocb *req)
2860 req->io_task_work.func = io_req_task_submit;
2861 io_req_task_work_add(req);
2864 static void io_req_task_queue_reissue(struct io_kiocb *req)
2866 req->io_task_work.func = io_queue_iowq;
2867 io_req_task_work_add(req);
2870 static void io_queue_next(struct io_kiocb *req)
2872 struct io_kiocb *nxt = io_req_find_next(req);
2875 io_req_task_queue(nxt);
2878 static void io_free_batch_list(struct io_ring_ctx *ctx,
2879 struct io_wq_work_node *node)
2880 __must_hold(&ctx->uring_lock)
2882 struct task_struct *task = NULL;
2886 struct io_kiocb *req = container_of(node, struct io_kiocb,
2889 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2890 if (req->flags & REQ_F_REFCOUNT) {
2891 node = req->comp_list.next;
2892 if (!req_ref_put_and_test(req))
2895 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2896 struct async_poll *apoll = req->apoll;
2898 if (apoll->double_poll)
2899 kfree(apoll->double_poll);
2900 list_add(&apoll->poll.wait.entry,
2902 req->flags &= ~REQ_F_POLLED;
2904 if (req->flags & IO_REQ_LINK_FLAGS)
2906 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2909 if (!(req->flags & REQ_F_FIXED_FILE))
2910 io_put_file(req->file);
2912 io_req_put_rsrc_locked(req, ctx);
2914 if (req->task != task) {
2916 io_put_task(task, task_refs);
2921 node = req->comp_list.next;
2922 io_req_add_to_cache(req, ctx);
2926 io_put_task(task, task_refs);
2929 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2930 __must_hold(&ctx->uring_lock)
2932 struct io_wq_work_node *node, *prev;
2933 struct io_submit_state *state = &ctx->submit_state;
2935 if (state->flush_cqes) {
2936 spin_lock(&ctx->completion_lock);
2937 wq_list_for_each(node, prev, &state->compl_reqs) {
2938 struct io_kiocb *req = container_of(node, struct io_kiocb,
2941 if (!(req->flags & REQ_F_CQE_SKIP))
2942 __io_fill_cqe_req(ctx, req);
2945 io_commit_cqring(ctx);
2946 spin_unlock(&ctx->completion_lock);
2947 io_cqring_ev_posted(ctx);
2948 state->flush_cqes = false;
2951 io_free_batch_list(ctx, state->compl_reqs.first);
2952 INIT_WQ_LIST(&state->compl_reqs);
2956 * Drop reference to request, return next in chain (if there is one) if this
2957 * was the last reference to this request.
2959 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2961 struct io_kiocb *nxt = NULL;
2963 if (req_ref_put_and_test(req)) {
2964 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2965 nxt = io_req_find_next(req);
2971 static inline void io_put_req(struct io_kiocb *req)
2973 if (req_ref_put_and_test(req)) {
2979 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2981 /* See comment at the top of this file */
2983 return __io_cqring_events(ctx);
2986 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2988 struct io_rings *rings = ctx->rings;
2990 /* make sure SQ entry isn't read before tail */
2991 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2994 static inline bool io_run_task_work(void)
2996 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2997 __set_current_state(TASK_RUNNING);
2998 clear_notify_signal();
2999 if (task_work_pending(current))
3007 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3009 struct io_wq_work_node *pos, *start, *prev;
3010 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3011 DEFINE_IO_COMP_BATCH(iob);
3015 * Only spin for completions if we don't have multiple devices hanging
3016 * off our complete list.
3018 if (ctx->poll_multi_queue || force_nonspin)
3019 poll_flags |= BLK_POLL_ONESHOT;
3021 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3022 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3023 struct kiocb *kiocb = &req->rw.kiocb;
3027 * Move completed and retryable entries to our local lists.
3028 * If we find a request that requires polling, break out
3029 * and complete those lists first, if we have entries there.
3031 if (READ_ONCE(req->iopoll_completed))
3034 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3035 if (unlikely(ret < 0))
3038 poll_flags |= BLK_POLL_ONESHOT;
3040 /* iopoll may have completed current req */
3041 if (!rq_list_empty(iob.req_list) ||
3042 READ_ONCE(req->iopoll_completed))
3046 if (!rq_list_empty(iob.req_list))
3052 wq_list_for_each_resume(pos, prev) {
3053 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3055 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3056 if (!smp_load_acquire(&req->iopoll_completed))
3059 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3062 req->cqe.flags = io_put_kbuf(req, 0);
3063 __io_fill_cqe_req(req->ctx, req);
3066 if (unlikely(!nr_events))
3069 io_commit_cqring(ctx);
3070 io_cqring_ev_posted_iopoll(ctx);
3071 pos = start ? start->next : ctx->iopoll_list.first;
3072 wq_list_cut(&ctx->iopoll_list, prev, start);
3073 io_free_batch_list(ctx, pos);
3078 * We can't just wait for polled events to come to us, we have to actively
3079 * find and complete them.
3081 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3083 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3086 mutex_lock(&ctx->uring_lock);
3087 while (!wq_list_empty(&ctx->iopoll_list)) {
3088 /* let it sleep and repeat later if can't complete a request */
3089 if (io_do_iopoll(ctx, true) == 0)
3092 * Ensure we allow local-to-the-cpu processing to take place,
3093 * in this case we need to ensure that we reap all events.
3094 * Also let task_work, etc. to progress by releasing the mutex
3096 if (need_resched()) {
3097 mutex_unlock(&ctx->uring_lock);
3099 mutex_lock(&ctx->uring_lock);
3102 mutex_unlock(&ctx->uring_lock);
3105 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3107 unsigned int nr_events = 0;
3109 unsigned long check_cq;
3112 * Don't enter poll loop if we already have events pending.
3113 * If we do, we can potentially be spinning for commands that
3114 * already triggered a CQE (eg in error).
3116 check_cq = READ_ONCE(ctx->check_cq);
3117 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3118 __io_cqring_overflow_flush(ctx, false);
3119 if (io_cqring_events(ctx))
3123 * Similarly do not spin if we have not informed the user of any
3126 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3131 * If a submit got punted to a workqueue, we can have the
3132 * application entering polling for a command before it gets
3133 * issued. That app will hold the uring_lock for the duration
3134 * of the poll right here, so we need to take a breather every
3135 * now and then to ensure that the issue has a chance to add
3136 * the poll to the issued list. Otherwise we can spin here
3137 * forever, while the workqueue is stuck trying to acquire the
3140 if (wq_list_empty(&ctx->iopoll_list)) {
3141 u32 tail = ctx->cached_cq_tail;
3143 mutex_unlock(&ctx->uring_lock);
3145 mutex_lock(&ctx->uring_lock);
3147 /* some requests don't go through iopoll_list */
3148 if (tail != ctx->cached_cq_tail ||
3149 wq_list_empty(&ctx->iopoll_list))
3152 ret = io_do_iopoll(ctx, !min);
3157 } while (nr_events < min && !need_resched());
3162 static void kiocb_end_write(struct io_kiocb *req)
3165 * Tell lockdep we inherited freeze protection from submission
3168 if (req->flags & REQ_F_ISREG) {
3169 struct super_block *sb = file_inode(req->file)->i_sb;
3171 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3177 static bool io_resubmit_prep(struct io_kiocb *req)
3179 struct io_async_rw *rw = req->async_data;
3181 if (!req_has_async_data(req))
3182 return !io_req_prep_async(req);
3183 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3187 static bool io_rw_should_reissue(struct io_kiocb *req)
3189 umode_t mode = file_inode(req->file)->i_mode;
3190 struct io_ring_ctx *ctx = req->ctx;
3192 if (!S_ISBLK(mode) && !S_ISREG(mode))
3194 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3195 !(ctx->flags & IORING_SETUP_IOPOLL)))
3198 * If ref is dying, we might be running poll reap from the exit work.
3199 * Don't attempt to reissue from that path, just let it fail with
3202 if (percpu_ref_is_dying(&ctx->refs))
3205 * Play it safe and assume not safe to re-import and reissue if we're
3206 * not in the original thread group (or in task context).
3208 if (!same_thread_group(req->task, current) || !in_task())
3213 static bool io_resubmit_prep(struct io_kiocb *req)
3217 static bool io_rw_should_reissue(struct io_kiocb *req)
3223 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3225 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3226 kiocb_end_write(req);
3227 fsnotify_modify(req->file);
3229 fsnotify_access(req->file);
3231 if (unlikely(res != req->cqe.res)) {
3232 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3233 io_rw_should_reissue(req)) {
3234 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3243 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3245 int res = req->cqe.res;
3248 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3249 io_req_add_compl_list(req);
3251 io_req_complete_post(req, res,
3252 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3256 static void __io_complete_rw(struct io_kiocb *req, long res,
3257 unsigned int issue_flags)
3259 if (__io_complete_rw_common(req, res))
3261 __io_req_complete(req, issue_flags, req->cqe.res,
3262 io_put_kbuf(req, issue_flags));
3265 static void io_complete_rw(struct kiocb *kiocb, long res)
3267 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3269 if (__io_complete_rw_common(req, res))
3272 req->io_task_work.func = io_req_task_complete;
3273 io_req_task_prio_work_add(req);
3276 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3278 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3280 if (kiocb->ki_flags & IOCB_WRITE)
3281 kiocb_end_write(req);
3282 if (unlikely(res != req->cqe.res)) {
3283 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3284 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3290 /* order with io_iopoll_complete() checking ->iopoll_completed */
3291 smp_store_release(&req->iopoll_completed, 1);
3295 * After the iocb has been issued, it's safe to be found on the poll list.
3296 * Adding the kiocb to the list AFTER submission ensures that we don't
3297 * find it from a io_do_iopoll() thread before the issuer is done
3298 * accessing the kiocb cookie.
3300 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3302 struct io_ring_ctx *ctx = req->ctx;
3303 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3305 /* workqueue context doesn't hold uring_lock, grab it now */
3306 if (unlikely(needs_lock))
3307 mutex_lock(&ctx->uring_lock);
3310 * Track whether we have multiple files in our lists. This will impact
3311 * how we do polling eventually, not spinning if we're on potentially
3312 * different devices.
3314 if (wq_list_empty(&ctx->iopoll_list)) {
3315 ctx->poll_multi_queue = false;
3316 } else if (!ctx->poll_multi_queue) {
3317 struct io_kiocb *list_req;
3319 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3321 if (list_req->file != req->file)
3322 ctx->poll_multi_queue = true;
3326 * For fast devices, IO may have already completed. If it has, add
3327 * it to the front so we find it first.
3329 if (READ_ONCE(req->iopoll_completed))
3330 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3332 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3334 if (unlikely(needs_lock)) {
3336 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3337 * in sq thread task context or in io worker task context. If
3338 * current task context is sq thread, we don't need to check
3339 * whether should wake up sq thread.
3341 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3342 wq_has_sleeper(&ctx->sq_data->wait))
3343 wake_up(&ctx->sq_data->wait);
3345 mutex_unlock(&ctx->uring_lock);
3349 static bool io_bdev_nowait(struct block_device *bdev)
3351 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3355 * If we tracked the file through the SCM inflight mechanism, we could support
3356 * any file. For now, just ensure that anything potentially problematic is done
3359 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3361 if (S_ISBLK(mode)) {
3362 if (IS_ENABLED(CONFIG_BLOCK) &&
3363 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3369 if (S_ISREG(mode)) {
3370 if (IS_ENABLED(CONFIG_BLOCK) &&
3371 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3372 file->f_op != &io_uring_fops)
3377 /* any ->read/write should understand O_NONBLOCK */
3378 if (file->f_flags & O_NONBLOCK)
3380 return file->f_mode & FMODE_NOWAIT;
3384 * If we tracked the file through the SCM inflight mechanism, we could support
3385 * any file. For now, just ensure that anything potentially problematic is done
3388 static unsigned int io_file_get_flags(struct file *file)
3390 umode_t mode = file_inode(file)->i_mode;
3391 unsigned int res = 0;
3395 if (__io_file_supports_nowait(file, mode))
3397 if (io_file_need_scm(file))
3402 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3404 return req->flags & REQ_F_SUPPORT_NOWAIT;
3407 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3409 struct kiocb *kiocb = &req->rw.kiocb;
3413 kiocb->ki_pos = READ_ONCE(sqe->off);
3414 /* used for fixed read/write too - just read unconditionally */
3415 req->buf_index = READ_ONCE(sqe->buf_index);
3417 if (req->opcode == IORING_OP_READ_FIXED ||
3418 req->opcode == IORING_OP_WRITE_FIXED) {
3419 struct io_ring_ctx *ctx = req->ctx;
3422 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3424 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3425 req->imu = ctx->user_bufs[index];
3426 io_req_set_rsrc_node(req, ctx, 0);
3429 ioprio = READ_ONCE(sqe->ioprio);
3431 ret = ioprio_check_cap(ioprio);
3435 kiocb->ki_ioprio = ioprio;
3437 kiocb->ki_ioprio = get_current_ioprio();
3440 req->rw.addr = READ_ONCE(sqe->addr);
3441 req->rw.len = READ_ONCE(sqe->len);
3442 req->rw.flags = READ_ONCE(sqe->rw_flags);
3446 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3452 case -ERESTARTNOINTR:
3453 case -ERESTARTNOHAND:
3454 case -ERESTART_RESTARTBLOCK:
3456 * We can't just restart the syscall, since previously
3457 * submitted sqes may already be in progress. Just fail this
3463 kiocb->ki_complete(kiocb, ret);
3467 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3469 struct kiocb *kiocb = &req->rw.kiocb;
3471 if (kiocb->ki_pos != -1)
3472 return &kiocb->ki_pos;
3474 if (!(req->file->f_mode & FMODE_STREAM)) {
3475 req->flags |= REQ_F_CUR_POS;
3476 kiocb->ki_pos = req->file->f_pos;
3477 return &kiocb->ki_pos;
3484 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3485 unsigned int issue_flags)
3487 struct io_async_rw *io = req->async_data;
3489 /* add previously done IO, if any */
3490 if (req_has_async_data(req) && io->bytes_done > 0) {
3492 ret = io->bytes_done;
3494 ret += io->bytes_done;
3497 if (req->flags & REQ_F_CUR_POS)
3498 req->file->f_pos = req->rw.kiocb.ki_pos;
3499 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3500 __io_complete_rw(req, ret, issue_flags);
3502 io_rw_done(&req->rw.kiocb, ret);
3504 if (req->flags & REQ_F_REISSUE) {
3505 req->flags &= ~REQ_F_REISSUE;
3506 if (io_resubmit_prep(req))
3507 io_req_task_queue_reissue(req);
3509 io_req_task_queue_fail(req, ret);
3513 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3514 struct io_mapped_ubuf *imu)
3516 size_t len = req->rw.len;
3517 u64 buf_end, buf_addr = req->rw.addr;
3520 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3522 /* not inside the mapped region */
3523 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3527 * May not be a start of buffer, set size appropriately
3528 * and advance us to the beginning.
3530 offset = buf_addr - imu->ubuf;
3531 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3535 * Don't use iov_iter_advance() here, as it's really slow for
3536 * using the latter parts of a big fixed buffer - it iterates
3537 * over each segment manually. We can cheat a bit here, because
3540 * 1) it's a BVEC iter, we set it up
3541 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3542 * first and last bvec
3544 * So just find our index, and adjust the iterator afterwards.
3545 * If the offset is within the first bvec (or the whole first
3546 * bvec, just use iov_iter_advance(). This makes it easier
3547 * since we can just skip the first segment, which may not
3548 * be PAGE_SIZE aligned.
3550 const struct bio_vec *bvec = imu->bvec;
3552 if (offset <= bvec->bv_len) {
3553 iov_iter_advance(iter, offset);
3555 unsigned long seg_skip;
3557 /* skip first vec */
3558 offset -= bvec->bv_len;
3559 seg_skip = 1 + (offset >> PAGE_SHIFT);
3561 iter->bvec = bvec + seg_skip;
3562 iter->nr_segs -= seg_skip;
3563 iter->count -= bvec->bv_len + offset;
3564 iter->iov_offset = offset & ~PAGE_MASK;
3571 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3572 unsigned int issue_flags)
3574 if (WARN_ON_ONCE(!req->imu))
3576 return __io_import_fixed(req, rw, iter, req->imu);
3579 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3580 struct io_buffer_list *bl, unsigned int bgid)
3583 if (bgid < BGID_ARRAY)
3586 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3589 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3590 struct io_buffer_list *bl)
3592 if (!list_empty(&bl->buf_list)) {
3593 struct io_buffer *kbuf;
3595 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3596 list_del(&kbuf->list);
3597 if (*len > kbuf->len)
3599 req->flags |= REQ_F_BUFFER_SELECTED;
3601 req->buf_index = kbuf->bid;
3602 return u64_to_user_ptr(kbuf->addr);
3607 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3608 struct io_buffer_list *bl,
3609 unsigned int issue_flags)
3611 struct io_uring_buf_ring *br = bl->buf_ring;
3612 struct io_uring_buf *buf;
3613 __u16 head = bl->head;
3615 if (unlikely(smp_load_acquire(&br->tail) == head))
3619 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3620 buf = &br->bufs[head];
3622 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3623 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3624 buf = page_address(bl->buf_pages[index]);
3627 if (*len > buf->len)
3629 req->flags |= REQ_F_BUFFER_RING;
3631 req->buf_index = buf->bid;
3633 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3635 * If we came in unlocked, we have no choice but to consume the
3636 * buffer here. This does mean it'll be pinned until the IO
3637 * completes. But coming in unlocked means we're in io-wq
3638 * context, hence there should be no further retry. For the
3639 * locked case, the caller must ensure to call the commit when
3640 * the transfer completes (or if we get -EAGAIN and must poll
3643 req->buf_list = NULL;
3646 return u64_to_user_ptr(buf->addr);
3649 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3650 unsigned int issue_flags)
3652 struct io_ring_ctx *ctx = req->ctx;
3653 struct io_buffer_list *bl;
3654 void __user *ret = NULL;
3656 io_ring_submit_lock(req->ctx, issue_flags);
3658 bl = io_buffer_get_list(ctx, req->buf_index);
3660 if (bl->buf_nr_pages)
3661 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3663 ret = io_provided_buffer_select(req, len, bl);
3665 io_ring_submit_unlock(req->ctx, issue_flags);
3669 #ifdef CONFIG_COMPAT
3670 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3671 unsigned int issue_flags)
3673 struct compat_iovec __user *uiov;
3674 compat_ssize_t clen;
3678 uiov = u64_to_user_ptr(req->rw.addr);
3679 if (!access_ok(uiov, sizeof(*uiov)))
3681 if (__get_user(clen, &uiov->iov_len))
3687 buf = io_buffer_select(req, &len, issue_flags);
3690 req->rw.addr = (unsigned long) buf;
3691 iov[0].iov_base = buf;
3692 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3697 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3698 unsigned int issue_flags)
3700 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3704 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3707 len = iov[0].iov_len;
3710 buf = io_buffer_select(req, &len, issue_flags);
3713 req->rw.addr = (unsigned long) buf;
3714 iov[0].iov_base = buf;
3715 req->rw.len = iov[0].iov_len = len;
3719 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3720 unsigned int issue_flags)
3722 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3723 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3724 iov[0].iov_len = req->rw.len;
3727 if (req->rw.len != 1)
3730 #ifdef CONFIG_COMPAT
3731 if (req->ctx->compat)
3732 return io_compat_import(req, iov, issue_flags);
3735 return __io_iov_buffer_select(req, iov, issue_flags);
3738 static inline bool io_do_buffer_select(struct io_kiocb *req)
3740 if (!(req->flags & REQ_F_BUFFER_SELECT))
3742 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3745 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3746 struct io_rw_state *s,
3747 unsigned int issue_flags)
3749 struct iov_iter *iter = &s->iter;
3750 u8 opcode = req->opcode;
3751 struct iovec *iovec;
3756 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3757 ret = io_import_fixed(req, rw, iter, issue_flags);
3759 return ERR_PTR(ret);
3763 buf = u64_to_user_ptr(req->rw.addr);
3764 sqe_len = req->rw.len;
3766 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3767 if (io_do_buffer_select(req)) {
3768 buf = io_buffer_select(req, &sqe_len, issue_flags);
3770 return ERR_PTR(-ENOBUFS);
3771 req->rw.addr = (unsigned long) buf;
3772 req->rw.len = sqe_len;
3775 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3777 return ERR_PTR(ret);
3781 iovec = s->fast_iov;
3782 if (req->flags & REQ_F_BUFFER_SELECT) {
3783 ret = io_iov_buffer_select(req, iovec, issue_flags);
3785 return ERR_PTR(ret);
3786 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3790 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3792 if (unlikely(ret < 0))
3793 return ERR_PTR(ret);
3797 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3798 struct iovec **iovec, struct io_rw_state *s,
3799 unsigned int issue_flags)
3801 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3802 if (unlikely(IS_ERR(*iovec)))
3803 return PTR_ERR(*iovec);
3805 iov_iter_save_state(&s->iter, &s->iter_state);
3809 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3811 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3815 * For files that don't have ->read_iter() and ->write_iter(), handle them
3816 * by looping over ->read() or ->write() manually.
3818 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3820 struct kiocb *kiocb = &req->rw.kiocb;
3821 struct file *file = req->file;
3826 * Don't support polled IO through this interface, and we can't
3827 * support non-blocking either. For the latter, this just causes
3828 * the kiocb to be handled from an async context.
3830 if (kiocb->ki_flags & IOCB_HIPRI)
3832 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3833 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3836 ppos = io_kiocb_ppos(kiocb);
3838 while (iov_iter_count(iter)) {
3842 if (!iov_iter_is_bvec(iter)) {
3843 iovec = iov_iter_iovec(iter);
3845 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3846 iovec.iov_len = req->rw.len;
3850 nr = file->f_op->read(file, iovec.iov_base,
3851 iovec.iov_len, ppos);
3853 nr = file->f_op->write(file, iovec.iov_base,
3854 iovec.iov_len, ppos);
3863 if (!iov_iter_is_bvec(iter)) {
3864 iov_iter_advance(iter, nr);
3871 if (nr != iovec.iov_len)
3878 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3879 const struct iovec *fast_iov, struct iov_iter *iter)
3881 struct io_async_rw *rw = req->async_data;
3883 memcpy(&rw->s.iter, iter, sizeof(*iter));
3884 rw->free_iovec = iovec;
3886 /* can only be fixed buffers, no need to do anything */
3887 if (iov_iter_is_bvec(iter))
3890 unsigned iov_off = 0;
3892 rw->s.iter.iov = rw->s.fast_iov;
3893 if (iter->iov != fast_iov) {
3894 iov_off = iter->iov - fast_iov;
3895 rw->s.iter.iov += iov_off;
3897 if (rw->s.fast_iov != fast_iov)
3898 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3899 sizeof(struct iovec) * iter->nr_segs);
3901 req->flags |= REQ_F_NEED_CLEANUP;
3905 static inline bool io_alloc_async_data(struct io_kiocb *req)
3907 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3908 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3909 if (req->async_data) {
3910 req->flags |= REQ_F_ASYNC_DATA;
3916 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3917 struct io_rw_state *s, bool force)
3919 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3921 if (!req_has_async_data(req)) {
3922 struct io_async_rw *iorw;
3924 if (io_alloc_async_data(req)) {
3929 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3930 iorw = req->async_data;
3931 /* we've copied and mapped the iter, ensure state is saved */
3932 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3937 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3939 struct io_async_rw *iorw = req->async_data;
3943 /* submission path, ->uring_lock should already be taken */
3944 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3945 if (unlikely(ret < 0))
3948 iorw->bytes_done = 0;
3949 iorw->free_iovec = iov;
3951 req->flags |= REQ_F_NEED_CLEANUP;
3955 static int io_readv_prep_async(struct io_kiocb *req)
3957 return io_rw_prep_async(req, READ);
3960 static int io_writev_prep_async(struct io_kiocb *req)
3962 return io_rw_prep_async(req, WRITE);
3966 * This is our waitqueue callback handler, registered through __folio_lock_async()
3967 * when we initially tried to do the IO with the iocb armed our waitqueue.
3968 * This gets called when the page is unlocked, and we generally expect that to
3969 * happen when the page IO is completed and the page is now uptodate. This will
3970 * queue a task_work based retry of the operation, attempting to copy the data
3971 * again. If the latter fails because the page was NOT uptodate, then we will
3972 * do a thread based blocking retry of the operation. That's the unexpected
3975 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3976 int sync, void *arg)
3978 struct wait_page_queue *wpq;
3979 struct io_kiocb *req = wait->private;
3980 struct wait_page_key *key = arg;
3982 wpq = container_of(wait, struct wait_page_queue, wait);
3984 if (!wake_page_match(wpq, key))
3987 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3988 list_del_init(&wait->entry);
3989 io_req_task_queue(req);
3994 * This controls whether a given IO request should be armed for async page
3995 * based retry. If we return false here, the request is handed to the async
3996 * worker threads for retry. If we're doing buffered reads on a regular file,
3997 * we prepare a private wait_page_queue entry and retry the operation. This
3998 * will either succeed because the page is now uptodate and unlocked, or it
3999 * will register a callback when the page is unlocked at IO completion. Through
4000 * that callback, io_uring uses task_work to setup a retry of the operation.
4001 * That retry will attempt the buffered read again. The retry will generally
4002 * succeed, or in rare cases where it fails, we then fall back to using the
4003 * async worker threads for a blocking retry.
4005 static bool io_rw_should_retry(struct io_kiocb *req)
4007 struct io_async_rw *rw = req->async_data;
4008 struct wait_page_queue *wait = &rw->wpq;
4009 struct kiocb *kiocb = &req->rw.kiocb;
4011 /* never retry for NOWAIT, we just complete with -EAGAIN */
4012 if (req->flags & REQ_F_NOWAIT)
4015 /* Only for buffered IO */
4016 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4020 * just use poll if we can, and don't attempt if the fs doesn't
4021 * support callback based unlocks
4023 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4026 wait->wait.func = io_async_buf_func;
4027 wait->wait.private = req;
4028 wait->wait.flags = 0;
4029 INIT_LIST_HEAD(&wait->wait.entry);
4030 kiocb->ki_flags |= IOCB_WAITQ;
4031 kiocb->ki_flags &= ~IOCB_NOWAIT;
4032 kiocb->ki_waitq = wait;
4036 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4038 if (likely(req->file->f_op->read_iter))
4039 return call_read_iter(req->file, &req->rw.kiocb, iter);
4040 else if (req->file->f_op->read)
4041 return loop_rw_iter(READ, req, iter);
4046 static bool need_read_all(struct io_kiocb *req)
4048 return req->flags & REQ_F_ISREG ||
4049 S_ISBLK(file_inode(req->file)->i_mode);
4052 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4054 struct kiocb *kiocb = &req->rw.kiocb;
4055 struct io_ring_ctx *ctx = req->ctx;
4056 struct file *file = req->file;
4059 if (unlikely(!file || !(file->f_mode & mode)))
4062 if (!io_req_ffs_set(req))
4063 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4065 kiocb->ki_flags = iocb_flags(file);
4066 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4071 * If the file is marked O_NONBLOCK, still allow retry for it if it
4072 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4073 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4075 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4076 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4077 req->flags |= REQ_F_NOWAIT;
4079 if (ctx->flags & IORING_SETUP_IOPOLL) {
4080 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4083 kiocb->private = NULL;
4084 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4085 kiocb->ki_complete = io_complete_rw_iopoll;
4086 req->iopoll_completed = 0;
4088 if (kiocb->ki_flags & IOCB_HIPRI)
4090 kiocb->ki_complete = io_complete_rw;
4096 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4098 struct io_rw_state __s, *s = &__s;
4099 struct iovec *iovec;
4100 struct kiocb *kiocb = &req->rw.kiocb;
4101 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4102 struct io_async_rw *rw;
4106 if (!req_has_async_data(req)) {
4107 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4108 if (unlikely(ret < 0))
4111 rw = req->async_data;
4115 * Safe and required to re-import if we're using provided
4116 * buffers, as we dropped the selected one before retry.
4118 if (io_do_buffer_select(req)) {
4119 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4120 if (unlikely(ret < 0))
4125 * We come here from an earlier attempt, restore our state to
4126 * match in case it doesn't. It's cheap enough that we don't
4127 * need to make this conditional.
4129 iov_iter_restore(&s->iter, &s->iter_state);
4132 ret = io_rw_init_file(req, FMODE_READ);
4133 if (unlikely(ret)) {
4137 req->cqe.res = iov_iter_count(&s->iter);
4139 if (force_nonblock) {
4140 /* If the file doesn't support async, just async punt */
4141 if (unlikely(!io_file_supports_nowait(req))) {
4142 ret = io_setup_async_rw(req, iovec, s, true);
4143 return ret ?: -EAGAIN;
4145 kiocb->ki_flags |= IOCB_NOWAIT;
4147 /* Ensure we clear previously set non-block flag */
4148 kiocb->ki_flags &= ~IOCB_NOWAIT;
4151 ppos = io_kiocb_update_pos(req);
4153 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4154 if (unlikely(ret)) {
4159 ret = io_iter_do_read(req, &s->iter);
4161 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4162 req->flags &= ~REQ_F_REISSUE;
4163 /* if we can poll, just do that */
4164 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4166 /* IOPOLL retry should happen for io-wq threads */
4167 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4169 /* no retry on NONBLOCK nor RWF_NOWAIT */
4170 if (req->flags & REQ_F_NOWAIT)
4173 } else if (ret == -EIOCBQUEUED) {
4175 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4176 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4177 /* read all, failed, already did sync or don't want to retry */
4182 * Don't depend on the iter state matching what was consumed, or being
4183 * untouched in case of error. Restore it and we'll advance it
4184 * manually if we need to.
4186 iov_iter_restore(&s->iter, &s->iter_state);
4188 ret2 = io_setup_async_rw(req, iovec, s, true);
4193 rw = req->async_data;
4196 * Now use our persistent iterator and state, if we aren't already.
4197 * We've restored and mapped the iter to match.
4202 * We end up here because of a partial read, either from
4203 * above or inside this loop. Advance the iter by the bytes
4204 * that were consumed.
4206 iov_iter_advance(&s->iter, ret);
4207 if (!iov_iter_count(&s->iter))
4209 rw->bytes_done += ret;
4210 iov_iter_save_state(&s->iter, &s->iter_state);
4212 /* if we can retry, do so with the callbacks armed */
4213 if (!io_rw_should_retry(req)) {
4214 kiocb->ki_flags &= ~IOCB_WAITQ;
4219 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4220 * we get -EIOCBQUEUED, then we'll get a notification when the
4221 * desired page gets unlocked. We can also get a partial read
4222 * here, and if we do, then just retry at the new offset.
4224 ret = io_iter_do_read(req, &s->iter);
4225 if (ret == -EIOCBQUEUED)
4227 /* we got some bytes, but not all. retry. */
4228 kiocb->ki_flags &= ~IOCB_WAITQ;
4229 iov_iter_restore(&s->iter, &s->iter_state);
4232 kiocb_done(req, ret, issue_flags);
4234 /* it's faster to check here then delegate to kfree */
4240 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4242 struct io_rw_state __s, *s = &__s;
4243 struct iovec *iovec;
4244 struct kiocb *kiocb = &req->rw.kiocb;
4245 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4249 if (!req_has_async_data(req)) {
4250 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4251 if (unlikely(ret < 0))
4254 struct io_async_rw *rw = req->async_data;
4257 iov_iter_restore(&s->iter, &s->iter_state);
4260 ret = io_rw_init_file(req, FMODE_WRITE);
4261 if (unlikely(ret)) {
4265 req->cqe.res = iov_iter_count(&s->iter);
4267 if (force_nonblock) {
4268 /* If the file doesn't support async, just async punt */
4269 if (unlikely(!io_file_supports_nowait(req)))
4272 /* file path doesn't support NOWAIT for non-direct_IO */
4273 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4274 (req->flags & REQ_F_ISREG))
4277 kiocb->ki_flags |= IOCB_NOWAIT;
4279 /* Ensure we clear previously set non-block flag */
4280 kiocb->ki_flags &= ~IOCB_NOWAIT;
4283 ppos = io_kiocb_update_pos(req);
4285 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4290 * Open-code file_start_write here to grab freeze protection,
4291 * which will be released by another thread in
4292 * io_complete_rw(). Fool lockdep by telling it the lock got
4293 * released so that it doesn't complain about the held lock when
4294 * we return to userspace.
4296 if (req->flags & REQ_F_ISREG) {
4297 sb_start_write(file_inode(req->file)->i_sb);
4298 __sb_writers_release(file_inode(req->file)->i_sb,
4301 kiocb->ki_flags |= IOCB_WRITE;
4303 if (likely(req->file->f_op->write_iter))
4304 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4305 else if (req->file->f_op->write)
4306 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4310 if (req->flags & REQ_F_REISSUE) {
4311 req->flags &= ~REQ_F_REISSUE;
4316 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4317 * retry them without IOCB_NOWAIT.
4319 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4321 /* no retry on NONBLOCK nor RWF_NOWAIT */
4322 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4324 if (!force_nonblock || ret2 != -EAGAIN) {
4325 /* IOPOLL retry should happen for io-wq threads */
4326 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4329 kiocb_done(req, ret2, issue_flags);
4332 iov_iter_restore(&s->iter, &s->iter_state);
4333 ret = io_setup_async_rw(req, iovec, s, false);
4335 if (kiocb->ki_flags & IOCB_WRITE)
4336 kiocb_end_write(req);
4342 /* it's reportedly faster than delegating the null check to kfree() */
4348 static int io_renameat_prep(struct io_kiocb *req,
4349 const struct io_uring_sqe *sqe)
4351 struct io_rename *ren = &req->rename;
4352 const char __user *oldf, *newf;
4354 if (sqe->buf_index || sqe->splice_fd_in)
4356 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4359 ren->old_dfd = READ_ONCE(sqe->fd);
4360 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4361 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4362 ren->new_dfd = READ_ONCE(sqe->len);
4363 ren->flags = READ_ONCE(sqe->rename_flags);
4365 ren->oldpath = getname(oldf);
4366 if (IS_ERR(ren->oldpath))
4367 return PTR_ERR(ren->oldpath);
4369 ren->newpath = getname(newf);
4370 if (IS_ERR(ren->newpath)) {
4371 putname(ren->oldpath);
4372 return PTR_ERR(ren->newpath);
4375 req->flags |= REQ_F_NEED_CLEANUP;
4379 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4381 struct io_rename *ren = &req->rename;
4384 if (issue_flags & IO_URING_F_NONBLOCK)
4387 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4388 ren->newpath, ren->flags);
4390 req->flags &= ~REQ_F_NEED_CLEANUP;
4391 io_req_complete(req, ret);
4395 static inline void __io_xattr_finish(struct io_kiocb *req)
4397 struct io_xattr *ix = &req->xattr;
4400 putname(ix->filename);
4402 kfree(ix->ctx.kname);
4403 kvfree(ix->ctx.kvalue);
4406 static void io_xattr_finish(struct io_kiocb *req, int ret)
4408 req->flags &= ~REQ_F_NEED_CLEANUP;
4410 __io_xattr_finish(req);
4411 io_req_complete(req, ret);
4414 static int __io_getxattr_prep(struct io_kiocb *req,
4415 const struct io_uring_sqe *sqe)
4417 struct io_xattr *ix = &req->xattr;
4418 const char __user *name;
4421 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4424 ix->filename = NULL;
4425 ix->ctx.kvalue = NULL;
4426 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4427 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4428 ix->ctx.size = READ_ONCE(sqe->len);
4429 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4434 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4438 ret = strncpy_from_user(ix->ctx.kname->name, name,
4439 sizeof(ix->ctx.kname->name));
4440 if (!ret || ret == sizeof(ix->ctx.kname->name))
4443 kfree(ix->ctx.kname);
4447 req->flags |= REQ_F_NEED_CLEANUP;
4451 static int io_fgetxattr_prep(struct io_kiocb *req,
4452 const struct io_uring_sqe *sqe)
4454 return __io_getxattr_prep(req, sqe);
4457 static int io_getxattr_prep(struct io_kiocb *req,
4458 const struct io_uring_sqe *sqe)
4460 struct io_xattr *ix = &req->xattr;
4461 const char __user *path;
4464 ret = __io_getxattr_prep(req, sqe);
4468 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4470 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4471 if (IS_ERR(ix->filename)) {
4472 ret = PTR_ERR(ix->filename);
4473 ix->filename = NULL;
4479 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4481 struct io_xattr *ix = &req->xattr;
4484 if (issue_flags & IO_URING_F_NONBLOCK)
4487 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4488 req->file->f_path.dentry,
4491 io_xattr_finish(req, ret);
4495 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4497 struct io_xattr *ix = &req->xattr;
4498 unsigned int lookup_flags = LOOKUP_FOLLOW;
4502 if (issue_flags & IO_URING_F_NONBLOCK)
4506 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4508 ret = do_getxattr(mnt_user_ns(path.mnt),
4513 if (retry_estale(ret, lookup_flags)) {
4514 lookup_flags |= LOOKUP_REVAL;
4519 io_xattr_finish(req, ret);
4523 static int __io_setxattr_prep(struct io_kiocb *req,
4524 const struct io_uring_sqe *sqe)
4526 struct io_xattr *ix = &req->xattr;
4527 const char __user *name;
4530 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4533 ix->filename = NULL;
4534 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4535 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4536 ix->ctx.kvalue = NULL;
4537 ix->ctx.size = READ_ONCE(sqe->len);
4538 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4540 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4544 ret = setxattr_copy(name, &ix->ctx);
4546 kfree(ix->ctx.kname);
4550 req->flags |= REQ_F_NEED_CLEANUP;
4554 static int io_setxattr_prep(struct io_kiocb *req,
4555 const struct io_uring_sqe *sqe)
4557 struct io_xattr *ix = &req->xattr;
4558 const char __user *path;
4561 ret = __io_setxattr_prep(req, sqe);
4565 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4567 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4568 if (IS_ERR(ix->filename)) {
4569 ret = PTR_ERR(ix->filename);
4570 ix->filename = NULL;
4576 static int io_fsetxattr_prep(struct io_kiocb *req,
4577 const struct io_uring_sqe *sqe)
4579 return __io_setxattr_prep(req, sqe);
4582 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4585 struct io_xattr *ix = &req->xattr;
4588 ret = mnt_want_write(path->mnt);
4590 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4591 mnt_drop_write(path->mnt);
4597 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4601 if (issue_flags & IO_URING_F_NONBLOCK)
4604 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4605 io_xattr_finish(req, ret);
4610 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4612 struct io_xattr *ix = &req->xattr;
4613 unsigned int lookup_flags = LOOKUP_FOLLOW;
4617 if (issue_flags & IO_URING_F_NONBLOCK)
4621 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4623 ret = __io_setxattr(req, issue_flags, &path);
4625 if (retry_estale(ret, lookup_flags)) {
4626 lookup_flags |= LOOKUP_REVAL;
4631 io_xattr_finish(req, ret);
4635 static int io_unlinkat_prep(struct io_kiocb *req,
4636 const struct io_uring_sqe *sqe)
4638 struct io_unlink *un = &req->unlink;
4639 const char __user *fname;
4641 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4643 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4646 un->dfd = READ_ONCE(sqe->fd);
4648 un->flags = READ_ONCE(sqe->unlink_flags);
4649 if (un->flags & ~AT_REMOVEDIR)
4652 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4653 un->filename = getname(fname);
4654 if (IS_ERR(un->filename))
4655 return PTR_ERR(un->filename);
4657 req->flags |= REQ_F_NEED_CLEANUP;
4661 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4663 struct io_unlink *un = &req->unlink;
4666 if (issue_flags & IO_URING_F_NONBLOCK)
4669 if (un->flags & AT_REMOVEDIR)
4670 ret = do_rmdir(un->dfd, un->filename);
4672 ret = do_unlinkat(un->dfd, un->filename);
4674 req->flags &= ~REQ_F_NEED_CLEANUP;
4675 io_req_complete(req, ret);
4679 static int io_mkdirat_prep(struct io_kiocb *req,
4680 const struct io_uring_sqe *sqe)
4682 struct io_mkdir *mkd = &req->mkdir;
4683 const char __user *fname;
4685 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4687 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4690 mkd->dfd = READ_ONCE(sqe->fd);
4691 mkd->mode = READ_ONCE(sqe->len);
4693 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4694 mkd->filename = getname(fname);
4695 if (IS_ERR(mkd->filename))
4696 return PTR_ERR(mkd->filename);
4698 req->flags |= REQ_F_NEED_CLEANUP;
4702 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4704 struct io_mkdir *mkd = &req->mkdir;
4707 if (issue_flags & IO_URING_F_NONBLOCK)
4710 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4712 req->flags &= ~REQ_F_NEED_CLEANUP;
4713 io_req_complete(req, ret);
4717 static int io_symlinkat_prep(struct io_kiocb *req,
4718 const struct io_uring_sqe *sqe)
4720 struct io_symlink *sl = &req->symlink;
4721 const char __user *oldpath, *newpath;
4723 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4725 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4728 sl->new_dfd = READ_ONCE(sqe->fd);
4729 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4730 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4732 sl->oldpath = getname(oldpath);
4733 if (IS_ERR(sl->oldpath))
4734 return PTR_ERR(sl->oldpath);
4736 sl->newpath = getname(newpath);
4737 if (IS_ERR(sl->newpath)) {
4738 putname(sl->oldpath);
4739 return PTR_ERR(sl->newpath);
4742 req->flags |= REQ_F_NEED_CLEANUP;
4746 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4748 struct io_symlink *sl = &req->symlink;
4751 if (issue_flags & IO_URING_F_NONBLOCK)
4754 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4756 req->flags &= ~REQ_F_NEED_CLEANUP;
4757 io_req_complete(req, ret);
4761 static int io_linkat_prep(struct io_kiocb *req,
4762 const struct io_uring_sqe *sqe)
4764 struct io_hardlink *lnk = &req->hardlink;
4765 const char __user *oldf, *newf;
4767 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4769 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4772 lnk->old_dfd = READ_ONCE(sqe->fd);
4773 lnk->new_dfd = READ_ONCE(sqe->len);
4774 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4775 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4776 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4778 lnk->oldpath = getname(oldf);
4779 if (IS_ERR(lnk->oldpath))
4780 return PTR_ERR(lnk->oldpath);
4782 lnk->newpath = getname(newf);
4783 if (IS_ERR(lnk->newpath)) {
4784 putname(lnk->oldpath);
4785 return PTR_ERR(lnk->newpath);
4788 req->flags |= REQ_F_NEED_CLEANUP;
4792 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4794 struct io_hardlink *lnk = &req->hardlink;
4797 if (issue_flags & IO_URING_F_NONBLOCK)
4800 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4801 lnk->newpath, lnk->flags);
4803 req->flags &= ~REQ_F_NEED_CLEANUP;
4804 io_req_complete(req, ret);
4808 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
4810 req->uring_cmd.task_work_cb(&req->uring_cmd);
4813 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
4814 void (*task_work_cb)(struct io_uring_cmd *))
4816 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4818 req->uring_cmd.task_work_cb = task_work_cb;
4819 req->io_task_work.func = io_uring_cmd_work;
4820 io_req_task_work_add(req);
4822 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
4824 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
4825 u64 extra1, u64 extra2)
4827 req->extra1 = extra1;
4828 req->extra2 = extra2;
4829 req->flags |= REQ_F_CQE32_INIT;
4833 * Called by consumers of io_uring_cmd, if they originally returned
4834 * -EIOCBQUEUED upon receiving the command.
4836 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
4838 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4843 if (req->ctx->flags & IORING_SETUP_CQE32)
4844 io_req_set_cqe32_extra(req, res2, 0);
4845 io_req_complete(req, ret);
4847 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
4849 static int io_uring_cmd_prep_async(struct io_kiocb *req)
4853 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
4855 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
4859 static int io_uring_cmd_prep(struct io_kiocb *req,
4860 const struct io_uring_sqe *sqe)
4862 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4864 if (sqe->rw_flags || sqe->__pad1)
4866 ioucmd->cmd = sqe->cmd;
4867 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
4871 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
4873 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4874 struct io_ring_ctx *ctx = req->ctx;
4875 struct file *file = req->file;
4878 if (!req->file->f_op->uring_cmd)
4881 ret = security_uring_cmd(ioucmd);
4885 if (ctx->flags & IORING_SETUP_SQE128)
4886 issue_flags |= IO_URING_F_SQE128;
4887 if (ctx->flags & IORING_SETUP_CQE32)
4888 issue_flags |= IO_URING_F_CQE32;
4889 if (ctx->flags & IORING_SETUP_IOPOLL)
4890 issue_flags |= IO_URING_F_IOPOLL;
4892 if (req_has_async_data(req))
4893 ioucmd->cmd = req->async_data;
4895 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
4896 if (ret == -EAGAIN) {
4897 if (!req_has_async_data(req)) {
4898 if (io_alloc_async_data(req))
4900 io_uring_cmd_prep_async(req);
4905 if (ret != -EIOCBQUEUED)
4906 io_uring_cmd_done(ioucmd, ret, 0);
4910 static int __io_splice_prep(struct io_kiocb *req,
4911 const struct io_uring_sqe *sqe)
4913 struct io_splice *sp = &req->splice;
4914 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4916 sp->len = READ_ONCE(sqe->len);
4917 sp->flags = READ_ONCE(sqe->splice_flags);
4918 if (unlikely(sp->flags & ~valid_flags))
4920 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4924 static int io_tee_prep(struct io_kiocb *req,
4925 const struct io_uring_sqe *sqe)
4927 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4929 return __io_splice_prep(req, sqe);
4932 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4934 struct io_splice *sp = &req->splice;
4935 struct file *out = sp->file_out;
4936 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4940 if (issue_flags & IO_URING_F_NONBLOCK)
4943 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4944 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4946 in = io_file_get_normal(req, sp->splice_fd_in);
4953 ret = do_tee(in, out, sp->len, flags);
4955 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4960 __io_req_complete(req, 0, ret, 0);
4964 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4966 struct io_splice *sp = &req->splice;
4968 sp->off_in = READ_ONCE(sqe->splice_off_in);
4969 sp->off_out = READ_ONCE(sqe->off);
4970 return __io_splice_prep(req, sqe);
4973 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4975 struct io_splice *sp = &req->splice;
4976 struct file *out = sp->file_out;
4977 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4978 loff_t *poff_in, *poff_out;
4982 if (issue_flags & IO_URING_F_NONBLOCK)
4985 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4986 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4988 in = io_file_get_normal(req, sp->splice_fd_in);
4994 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4995 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4998 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5000 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5005 __io_req_complete(req, 0, ret, 0);
5009 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5015 * IORING_OP_NOP just posts a completion event, nothing else.
5017 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5019 __io_req_complete(req, issue_flags, 0, 0);
5023 static int io_msg_ring_prep(struct io_kiocb *req,
5024 const struct io_uring_sqe *sqe)
5026 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5027 sqe->buf_index || sqe->personality))
5030 req->msg.user_data = READ_ONCE(sqe->off);
5031 req->msg.len = READ_ONCE(sqe->len);
5035 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5037 struct io_ring_ctx *target_ctx;
5038 struct io_msg *msg = &req->msg;
5043 if (req->file->f_op != &io_uring_fops)
5047 target_ctx = req->file->private_data;
5049 spin_lock(&target_ctx->completion_lock);
5050 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5051 io_commit_cqring(target_ctx);
5052 spin_unlock(&target_ctx->completion_lock);
5055 io_cqring_ev_posted(target_ctx);
5062 __io_req_complete(req, issue_flags, ret, 0);
5063 /* put file to avoid an attempt to IOPOLL the req */
5064 if (!(req->flags & REQ_F_FIXED_FILE))
5065 io_put_file(req->file);
5070 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5072 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5075 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5076 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5079 req->sync.off = READ_ONCE(sqe->off);
5080 req->sync.len = READ_ONCE(sqe->len);
5084 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5086 loff_t end = req->sync.off + req->sync.len;
5089 /* fsync always requires a blocking context */
5090 if (issue_flags & IO_URING_F_NONBLOCK)
5093 ret = vfs_fsync_range(req->file, req->sync.off,
5094 end > 0 ? end : LLONG_MAX,
5095 req->sync.flags & IORING_FSYNC_DATASYNC);
5096 io_req_complete(req, ret);
5100 static int io_fallocate_prep(struct io_kiocb *req,
5101 const struct io_uring_sqe *sqe)
5103 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5106 req->sync.off = READ_ONCE(sqe->off);
5107 req->sync.len = READ_ONCE(sqe->addr);
5108 req->sync.mode = READ_ONCE(sqe->len);
5112 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5116 /* fallocate always requiring blocking context */
5117 if (issue_flags & IO_URING_F_NONBLOCK)
5119 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5122 fsnotify_modify(req->file);
5123 io_req_complete(req, ret);
5127 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5129 const char __user *fname;
5132 if (unlikely(sqe->buf_index))
5134 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5137 /* open.how should be already initialised */
5138 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5139 req->open.how.flags |= O_LARGEFILE;
5141 req->open.dfd = READ_ONCE(sqe->fd);
5142 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5143 req->open.filename = getname(fname);
5144 if (IS_ERR(req->open.filename)) {
5145 ret = PTR_ERR(req->open.filename);
5146 req->open.filename = NULL;
5150 req->open.file_slot = READ_ONCE(sqe->file_index);
5151 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5154 req->open.nofile = rlimit(RLIMIT_NOFILE);
5155 req->flags |= REQ_F_NEED_CLEANUP;
5159 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5161 u64 mode = READ_ONCE(sqe->len);
5162 u64 flags = READ_ONCE(sqe->open_flags);
5164 req->open.how = build_open_how(flags, mode);
5165 return __io_openat_prep(req, sqe);
5168 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5170 struct open_how __user *how;
5174 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5175 len = READ_ONCE(sqe->len);
5176 if (len < OPEN_HOW_SIZE_VER0)
5179 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5184 return __io_openat_prep(req, sqe);
5187 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5189 struct io_file_table *table = &ctx->file_table;
5190 unsigned long nr = ctx->nr_user_files;
5194 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5198 if (!table->alloc_hint)
5201 nr = table->alloc_hint;
5202 table->alloc_hint = 0;
5209 * Note when io_fixed_fd_install() returns error value, it will ensure
5210 * fput() is called correspondingly.
5212 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5213 struct file *file, unsigned int file_slot)
5215 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5216 struct io_ring_ctx *ctx = req->ctx;
5219 io_ring_submit_lock(ctx, issue_flags);
5222 ret = io_file_bitmap_get(ctx);
5223 if (unlikely(ret < 0))
5230 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5231 if (!ret && alloc_slot)
5234 io_ring_submit_unlock(ctx, issue_flags);
5235 if (unlikely(ret < 0))
5240 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5242 struct open_flags op;
5244 bool resolve_nonblock, nonblock_set;
5245 bool fixed = !!req->open.file_slot;
5248 ret = build_open_flags(&req->open.how, &op);
5251 nonblock_set = op.open_flag & O_NONBLOCK;
5252 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5253 if (issue_flags & IO_URING_F_NONBLOCK) {
5255 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5256 * it'll always -EAGAIN
5258 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5260 op.lookup_flags |= LOOKUP_CACHED;
5261 op.open_flag |= O_NONBLOCK;
5265 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5270 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5273 * We could hang on to this 'fd' on retrying, but seems like
5274 * marginal gain for something that is now known to be a slower
5275 * path. So just put it, and we'll get a new one when we retry.
5280 ret = PTR_ERR(file);
5281 /* only retry if RESOLVE_CACHED wasn't already set by application */
5282 if (ret == -EAGAIN &&
5283 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5288 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5289 file->f_flags &= ~O_NONBLOCK;
5290 fsnotify_open(file);
5293 fd_install(ret, file);
5295 ret = io_fixed_fd_install(req, issue_flags, file,
5296 req->open.file_slot);
5298 putname(req->open.filename);
5299 req->flags &= ~REQ_F_NEED_CLEANUP;
5302 __io_req_complete(req, issue_flags, ret, 0);
5306 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5308 return io_openat2(req, issue_flags);
5311 static int io_remove_buffers_prep(struct io_kiocb *req,
5312 const struct io_uring_sqe *sqe)
5314 struct io_provide_buf *p = &req->pbuf;
5317 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5321 tmp = READ_ONCE(sqe->fd);
5322 if (!tmp || tmp > USHRT_MAX)
5325 memset(p, 0, sizeof(*p));
5327 p->bgid = READ_ONCE(sqe->buf_group);
5331 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5332 struct io_buffer_list *bl, unsigned nbufs)
5336 /* shouldn't happen */
5340 if (bl->buf_nr_pages) {
5343 i = bl->buf_ring->tail - bl->head;
5344 for (j = 0; j < bl->buf_nr_pages; j++)
5345 unpin_user_page(bl->buf_pages[j]);
5346 kvfree(bl->buf_pages);
5347 bl->buf_pages = NULL;
5348 bl->buf_nr_pages = 0;
5349 /* make sure it's seen as empty */
5350 INIT_LIST_HEAD(&bl->buf_list);
5354 /* the head kbuf is the list itself */
5355 while (!list_empty(&bl->buf_list)) {
5356 struct io_buffer *nxt;
5358 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5359 list_del(&nxt->list);
5369 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5371 struct io_provide_buf *p = &req->pbuf;
5372 struct io_ring_ctx *ctx = req->ctx;
5373 struct io_buffer_list *bl;
5376 io_ring_submit_lock(ctx, issue_flags);
5379 bl = io_buffer_get_list(ctx, p->bgid);
5382 /* can't use provide/remove buffers command on mapped buffers */
5383 if (!bl->buf_nr_pages)
5384 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5389 /* complete before unlock, IOPOLL may need the lock */
5390 __io_req_complete(req, issue_flags, ret, 0);
5391 io_ring_submit_unlock(ctx, issue_flags);
5395 static int io_provide_buffers_prep(struct io_kiocb *req,
5396 const struct io_uring_sqe *sqe)
5398 unsigned long size, tmp_check;
5399 struct io_provide_buf *p = &req->pbuf;
5402 if (sqe->rw_flags || sqe->splice_fd_in)
5405 tmp = READ_ONCE(sqe->fd);
5406 if (!tmp || tmp > USHRT_MAX)
5409 p->addr = READ_ONCE(sqe->addr);
5410 p->len = READ_ONCE(sqe->len);
5412 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5415 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5418 size = (unsigned long)p->len * p->nbufs;
5419 if (!access_ok(u64_to_user_ptr(p->addr), size))
5422 p->bgid = READ_ONCE(sqe->buf_group);
5423 tmp = READ_ONCE(sqe->off);
5424 if (tmp > USHRT_MAX)
5430 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5432 struct io_buffer *buf;
5437 * Completions that don't happen inline (eg not under uring_lock) will
5438 * add to ->io_buffers_comp. If we don't have any free buffers, check
5439 * the completion list and splice those entries first.
5441 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5442 spin_lock(&ctx->completion_lock);
5443 if (!list_empty(&ctx->io_buffers_comp)) {
5444 list_splice_init(&ctx->io_buffers_comp,
5445 &ctx->io_buffers_cache);
5446 spin_unlock(&ctx->completion_lock);
5449 spin_unlock(&ctx->completion_lock);
5453 * No free buffers and no completion entries either. Allocate a new
5454 * page worth of buffer entries and add those to our freelist.
5456 page = alloc_page(GFP_KERNEL_ACCOUNT);
5460 list_add(&page->lru, &ctx->io_buffers_pages);
5462 buf = page_address(page);
5463 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5464 while (bufs_in_page) {
5465 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5473 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5474 struct io_buffer_list *bl)
5476 struct io_buffer *buf;
5477 u64 addr = pbuf->addr;
5478 int i, bid = pbuf->bid;
5480 for (i = 0; i < pbuf->nbufs; i++) {
5481 if (list_empty(&ctx->io_buffers_cache) &&
5482 io_refill_buffer_cache(ctx))
5484 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5486 list_move_tail(&buf->list, &bl->buf_list);
5488 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5490 buf->bgid = pbuf->bgid;
5496 return i ? 0 : -ENOMEM;
5499 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5503 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5508 for (i = 0; i < BGID_ARRAY; i++) {
5509 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5510 ctx->io_bl[i].bgid = i;
5516 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5518 struct io_provide_buf *p = &req->pbuf;
5519 struct io_ring_ctx *ctx = req->ctx;
5520 struct io_buffer_list *bl;
5523 io_ring_submit_lock(ctx, issue_flags);
5525 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5526 ret = io_init_bl_list(ctx);
5531 bl = io_buffer_get_list(ctx, p->bgid);
5532 if (unlikely(!bl)) {
5533 bl = kzalloc(sizeof(*bl), GFP_KERNEL_ACCOUNT);
5538 INIT_LIST_HEAD(&bl->buf_list);
5539 ret = io_buffer_add_list(ctx, bl, p->bgid);
5545 /* can't add buffers via this command for a mapped buffer ring */
5546 if (bl->buf_nr_pages) {
5551 ret = io_add_buffers(ctx, p, bl);
5555 /* complete before unlock, IOPOLL may need the lock */
5556 __io_req_complete(req, issue_flags, ret, 0);
5557 io_ring_submit_unlock(ctx, issue_flags);
5561 static int io_epoll_ctl_prep(struct io_kiocb *req,
5562 const struct io_uring_sqe *sqe)
5564 #if defined(CONFIG_EPOLL)
5565 if (sqe->buf_index || sqe->splice_fd_in)
5568 req->epoll.epfd = READ_ONCE(sqe->fd);
5569 req->epoll.op = READ_ONCE(sqe->len);
5570 req->epoll.fd = READ_ONCE(sqe->off);
5572 if (ep_op_has_event(req->epoll.op)) {
5573 struct epoll_event __user *ev;
5575 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5576 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5586 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5588 #if defined(CONFIG_EPOLL)
5589 struct io_epoll *ie = &req->epoll;
5591 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5593 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5594 if (force_nonblock && ret == -EAGAIN)
5599 __io_req_complete(req, issue_flags, ret, 0);
5606 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5608 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5609 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5612 req->madvise.addr = READ_ONCE(sqe->addr);
5613 req->madvise.len = READ_ONCE(sqe->len);
5614 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5621 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5623 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5624 struct io_madvise *ma = &req->madvise;
5627 if (issue_flags & IO_URING_F_NONBLOCK)
5630 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5631 io_req_complete(req, ret);
5638 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5640 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5643 req->fadvise.offset = READ_ONCE(sqe->off);
5644 req->fadvise.len = READ_ONCE(sqe->len);
5645 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5649 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5651 struct io_fadvise *fa = &req->fadvise;
5654 if (issue_flags & IO_URING_F_NONBLOCK) {
5655 switch (fa->advice) {
5656 case POSIX_FADV_NORMAL:
5657 case POSIX_FADV_RANDOM:
5658 case POSIX_FADV_SEQUENTIAL:
5665 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5668 __io_req_complete(req, issue_flags, ret, 0);
5672 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5674 const char __user *path;
5676 if (sqe->buf_index || sqe->splice_fd_in)
5678 if (req->flags & REQ_F_FIXED_FILE)
5681 req->statx.dfd = READ_ONCE(sqe->fd);
5682 req->statx.mask = READ_ONCE(sqe->len);
5683 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5684 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5685 req->statx.flags = READ_ONCE(sqe->statx_flags);
5687 req->statx.filename = getname_flags(path,
5688 getname_statx_lookup_flags(req->statx.flags),
5691 if (IS_ERR(req->statx.filename)) {
5692 int ret = PTR_ERR(req->statx.filename);
5694 req->statx.filename = NULL;
5698 req->flags |= REQ_F_NEED_CLEANUP;
5702 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5704 struct io_statx *ctx = &req->statx;
5707 if (issue_flags & IO_URING_F_NONBLOCK)
5710 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5712 io_req_complete(req, ret);
5716 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5718 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5720 if (req->flags & REQ_F_FIXED_FILE)
5723 req->close.fd = READ_ONCE(sqe->fd);
5724 req->close.file_slot = READ_ONCE(sqe->file_index);
5725 if (req->close.file_slot && req->close.fd)
5731 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5733 struct files_struct *files = current->files;
5734 struct io_close *close = &req->close;
5735 struct fdtable *fdt;
5739 if (req->close.file_slot) {
5740 ret = io_close_fixed(req, issue_flags);
5744 spin_lock(&files->file_lock);
5745 fdt = files_fdtable(files);
5746 if (close->fd >= fdt->max_fds) {
5747 spin_unlock(&files->file_lock);
5750 file = rcu_dereference_protected(fdt->fd[close->fd],
5751 lockdep_is_held(&files->file_lock));
5752 if (!file || file->f_op == &io_uring_fops) {
5753 spin_unlock(&files->file_lock);
5757 /* if the file has a flush method, be safe and punt to async */
5758 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5759 spin_unlock(&files->file_lock);
5763 file = __close_fd_get_file(close->fd);
5764 spin_unlock(&files->file_lock);
5768 /* No ->flush() or already async, safely close from here */
5769 ret = filp_close(file, current->files);
5773 __io_req_complete(req, issue_flags, ret, 0);
5777 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5779 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5782 req->sync.off = READ_ONCE(sqe->off);
5783 req->sync.len = READ_ONCE(sqe->len);
5784 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5788 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5792 /* sync_file_range always requires a blocking context */
5793 if (issue_flags & IO_URING_F_NONBLOCK)
5796 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5798 io_req_complete(req, ret);
5802 #if defined(CONFIG_NET)
5803 static int io_shutdown_prep(struct io_kiocb *req,
5804 const struct io_uring_sqe *sqe)
5806 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
5807 sqe->buf_index || sqe->splice_fd_in))
5810 req->shutdown.how = READ_ONCE(sqe->len);
5814 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
5816 struct socket *sock;
5819 if (issue_flags & IO_URING_F_NONBLOCK)
5822 sock = sock_from_file(req->file);
5823 if (unlikely(!sock))
5826 ret = __sys_shutdown_sock(sock, req->shutdown.how);
5827 io_req_complete(req, ret);
5831 static bool io_net_retry(struct socket *sock, int flags)
5833 if (!(flags & MSG_WAITALL))
5835 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5838 static int io_setup_async_msg(struct io_kiocb *req,
5839 struct io_async_msghdr *kmsg)
5841 struct io_async_msghdr *async_msg = req->async_data;
5845 if (io_alloc_async_data(req)) {
5846 kfree(kmsg->free_iov);
5849 async_msg = req->async_data;
5850 req->flags |= REQ_F_NEED_CLEANUP;
5851 memcpy(async_msg, kmsg, sizeof(*kmsg));
5852 async_msg->msg.msg_name = &async_msg->addr;
5853 /* if were using fast_iov, set it to the new one */
5854 if (!async_msg->free_iov)
5855 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5860 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5861 struct io_async_msghdr *iomsg)
5863 iomsg->msg.msg_name = &iomsg->addr;
5864 iomsg->free_iov = iomsg->fast_iov;
5865 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5866 req->sr_msg.msg_flags, &iomsg->free_iov);
5869 static int io_sendmsg_prep_async(struct io_kiocb *req)
5873 ret = io_sendmsg_copy_hdr(req, req->async_data);
5875 req->flags |= REQ_F_NEED_CLEANUP;
5879 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5881 struct io_sr_msg *sr = &req->sr_msg;
5883 if (unlikely(sqe->file_index || sqe->addr2))
5886 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5887 sr->len = READ_ONCE(sqe->len);
5888 sr->flags = READ_ONCE(sqe->ioprio);
5889 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5891 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5892 if (sr->msg_flags & MSG_DONTWAIT)
5893 req->flags |= REQ_F_NOWAIT;
5895 #ifdef CONFIG_COMPAT
5896 if (req->ctx->compat)
5897 sr->msg_flags |= MSG_CMSG_COMPAT;
5903 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5905 struct io_async_msghdr iomsg, *kmsg;
5906 struct io_sr_msg *sr = &req->sr_msg;
5907 struct socket *sock;
5912 sock = sock_from_file(req->file);
5913 if (unlikely(!sock))
5916 if (req_has_async_data(req)) {
5917 kmsg = req->async_data;
5919 ret = io_sendmsg_copy_hdr(req, &iomsg);
5925 if (!(req->flags & REQ_F_POLLED) &&
5926 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5927 return io_setup_async_msg(req, kmsg);
5929 flags = sr->msg_flags;
5930 if (issue_flags & IO_URING_F_NONBLOCK)
5931 flags |= MSG_DONTWAIT;
5932 if (flags & MSG_WAITALL)
5933 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5935 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5937 if (ret < min_ret) {
5938 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5939 return io_setup_async_msg(req, kmsg);
5940 if (ret == -ERESTARTSYS)
5942 if (ret > 0 && io_net_retry(sock, flags)) {
5944 req->flags |= REQ_F_PARTIAL_IO;
5945 return io_setup_async_msg(req, kmsg);
5949 /* fast path, check for non-NULL to avoid function call */
5951 kfree(kmsg->free_iov);
5952 req->flags &= ~REQ_F_NEED_CLEANUP;
5955 else if (sr->done_io)
5957 __io_req_complete(req, issue_flags, ret, 0);
5961 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5963 struct io_sr_msg *sr = &req->sr_msg;
5966 struct socket *sock;
5971 if (!(req->flags & REQ_F_POLLED) &&
5972 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5975 sock = sock_from_file(req->file);
5976 if (unlikely(!sock))
5979 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5983 msg.msg_name = NULL;
5984 msg.msg_control = NULL;
5985 msg.msg_controllen = 0;
5986 msg.msg_namelen = 0;
5988 flags = sr->msg_flags;
5989 if (issue_flags & IO_URING_F_NONBLOCK)
5990 flags |= MSG_DONTWAIT;
5991 if (flags & MSG_WAITALL)
5992 min_ret = iov_iter_count(&msg.msg_iter);
5994 msg.msg_flags = flags;
5995 ret = sock_sendmsg(sock, &msg);
5996 if (ret < min_ret) {
5997 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5999 if (ret == -ERESTARTSYS)
6001 if (ret > 0 && io_net_retry(sock, flags)) {
6005 req->flags |= REQ_F_PARTIAL_IO;
6012 else if (sr->done_io)
6014 __io_req_complete(req, issue_flags, ret, 0);
6018 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6019 struct io_async_msghdr *iomsg)
6021 struct io_sr_msg *sr = &req->sr_msg;
6022 struct iovec __user *uiov;
6026 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6027 &iomsg->uaddr, &uiov, &iov_len);
6031 if (req->flags & REQ_F_BUFFER_SELECT) {
6034 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6036 sr->len = iomsg->fast_iov[0].iov_len;
6037 iomsg->free_iov = NULL;
6039 iomsg->free_iov = iomsg->fast_iov;
6040 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6041 &iomsg->free_iov, &iomsg->msg.msg_iter,
6050 #ifdef CONFIG_COMPAT
6051 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6052 struct io_async_msghdr *iomsg)
6054 struct io_sr_msg *sr = &req->sr_msg;
6055 struct compat_iovec __user *uiov;
6060 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6065 uiov = compat_ptr(ptr);
6066 if (req->flags & REQ_F_BUFFER_SELECT) {
6067 compat_ssize_t clen;
6071 if (!access_ok(uiov, sizeof(*uiov)))
6073 if (__get_user(clen, &uiov->iov_len))
6078 iomsg->free_iov = NULL;
6080 iomsg->free_iov = iomsg->fast_iov;
6081 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6082 UIO_FASTIOV, &iomsg->free_iov,
6083 &iomsg->msg.msg_iter, true);
6092 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6093 struct io_async_msghdr *iomsg)
6095 iomsg->msg.msg_name = &iomsg->addr;
6097 #ifdef CONFIG_COMPAT
6098 if (req->ctx->compat)
6099 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6102 return __io_recvmsg_copy_hdr(req, iomsg);
6105 static int io_recvmsg_prep_async(struct io_kiocb *req)
6109 ret = io_recvmsg_copy_hdr(req, req->async_data);
6111 req->flags |= REQ_F_NEED_CLEANUP;
6115 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6117 struct io_sr_msg *sr = &req->sr_msg;
6119 if (unlikely(sqe->file_index || sqe->addr2))
6122 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6123 sr->len = READ_ONCE(sqe->len);
6124 sr->flags = READ_ONCE(sqe->ioprio);
6125 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6127 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6128 if (sr->msg_flags & MSG_DONTWAIT)
6129 req->flags |= REQ_F_NOWAIT;
6131 #ifdef CONFIG_COMPAT
6132 if (req->ctx->compat)
6133 sr->msg_flags |= MSG_CMSG_COMPAT;
6139 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6141 struct io_async_msghdr iomsg, *kmsg;
6142 struct io_sr_msg *sr = &req->sr_msg;
6143 struct socket *sock;
6144 unsigned int cflags;
6146 int ret, min_ret = 0;
6147 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6149 sock = sock_from_file(req->file);
6150 if (unlikely(!sock))
6153 if (req_has_async_data(req)) {
6154 kmsg = req->async_data;
6156 ret = io_recvmsg_copy_hdr(req, &iomsg);
6162 if (!(req->flags & REQ_F_POLLED) &&
6163 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6164 return io_setup_async_msg(req, kmsg);
6166 if (io_do_buffer_select(req)) {
6169 buf = io_buffer_select(req, &sr->len, issue_flags);
6172 kmsg->fast_iov[0].iov_base = buf;
6173 kmsg->fast_iov[0].iov_len = sr->len;
6174 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6178 flags = sr->msg_flags;
6180 flags |= MSG_DONTWAIT;
6181 if (flags & MSG_WAITALL)
6182 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6184 kmsg->msg.msg_get_inq = 1;
6185 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6186 if (ret < min_ret) {
6187 if (ret == -EAGAIN && force_nonblock)
6188 return io_setup_async_msg(req, kmsg);
6189 if (ret == -ERESTARTSYS)
6191 if (ret > 0 && io_net_retry(sock, flags)) {
6193 req->flags |= REQ_F_PARTIAL_IO;
6194 return io_setup_async_msg(req, kmsg);
6197 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6201 /* fast path, check for non-NULL to avoid function call */
6203 kfree(kmsg->free_iov);
6204 req->flags &= ~REQ_F_NEED_CLEANUP;
6207 else if (sr->done_io)
6209 cflags = io_put_kbuf(req, issue_flags);
6210 if (kmsg->msg.msg_inq)
6211 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6212 __io_req_complete(req, issue_flags, ret, cflags);
6216 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6218 struct io_sr_msg *sr = &req->sr_msg;
6220 struct socket *sock;
6222 unsigned int cflags;
6224 int ret, min_ret = 0;
6225 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6227 if (!(req->flags & REQ_F_POLLED) &&
6228 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6231 sock = sock_from_file(req->file);
6232 if (unlikely(!sock))
6235 if (io_do_buffer_select(req)) {
6238 buf = io_buffer_select(req, &sr->len, issue_flags);
6244 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6248 msg.msg_name = NULL;
6249 msg.msg_namelen = 0;
6250 msg.msg_control = NULL;
6251 msg.msg_get_inq = 1;
6253 msg.msg_controllen = 0;
6254 msg.msg_iocb = NULL;
6256 flags = sr->msg_flags;
6258 flags |= MSG_DONTWAIT;
6259 if (flags & MSG_WAITALL)
6260 min_ret = iov_iter_count(&msg.msg_iter);
6262 ret = sock_recvmsg(sock, &msg, flags);
6263 if (ret < min_ret) {
6264 if (ret == -EAGAIN && force_nonblock)
6266 if (ret == -ERESTARTSYS)
6268 if (ret > 0 && io_net_retry(sock, flags)) {
6272 req->flags |= REQ_F_PARTIAL_IO;
6276 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6283 else if (sr->done_io)
6285 cflags = io_put_kbuf(req, issue_flags);
6287 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6288 __io_req_complete(req, issue_flags, ret, cflags);
6292 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6294 struct io_accept *accept = &req->accept;
6297 if (sqe->len || sqe->buf_index)
6300 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6301 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6302 accept->flags = READ_ONCE(sqe->accept_flags);
6303 accept->nofile = rlimit(RLIMIT_NOFILE);
6304 flags = READ_ONCE(sqe->ioprio);
6305 if (flags & ~IORING_ACCEPT_MULTISHOT)
6308 accept->file_slot = READ_ONCE(sqe->file_index);
6309 if (accept->file_slot) {
6310 if (accept->flags & SOCK_CLOEXEC)
6312 if (flags & IORING_ACCEPT_MULTISHOT &&
6313 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6316 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6318 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6319 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6320 if (flags & IORING_ACCEPT_MULTISHOT)
6321 req->flags |= REQ_F_APOLL_MULTISHOT;
6325 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6327 struct io_ring_ctx *ctx = req->ctx;
6328 struct io_accept *accept = &req->accept;
6329 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6330 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6331 bool fixed = !!accept->file_slot;
6337 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6338 if (unlikely(fd < 0))
6341 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6346 ret = PTR_ERR(file);
6347 if (ret == -EAGAIN && force_nonblock) {
6349 * if it's multishot and polled, we don't need to
6350 * return EAGAIN to arm the poll infra since it
6351 * has already been done
6353 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6354 IO_APOLL_MULTI_POLLED)
6358 if (ret == -ERESTARTSYS)
6361 } else if (!fixed) {
6362 fd_install(fd, file);
6365 ret = io_fixed_fd_install(req, issue_flags, file,
6369 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6370 __io_req_complete(req, issue_flags, ret, 0);
6376 spin_lock(&ctx->completion_lock);
6377 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6379 io_commit_cqring(ctx);
6380 spin_unlock(&ctx->completion_lock);
6382 io_cqring_ev_posted(ctx);
6391 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6393 struct io_socket *sock = &req->sock;
6395 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6398 sock->domain = READ_ONCE(sqe->fd);
6399 sock->type = READ_ONCE(sqe->off);
6400 sock->protocol = READ_ONCE(sqe->len);
6401 sock->file_slot = READ_ONCE(sqe->file_index);
6402 sock->nofile = rlimit(RLIMIT_NOFILE);
6404 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6405 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6407 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6412 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6414 struct io_socket *sock = &req->sock;
6415 bool fixed = !!sock->file_slot;
6420 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6421 if (unlikely(fd < 0))
6424 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6428 ret = PTR_ERR(file);
6429 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6431 if (ret == -ERESTARTSYS)
6434 } else if (!fixed) {
6435 fd_install(fd, file);
6438 ret = io_fixed_fd_install(req, issue_flags, file,
6441 __io_req_complete(req, issue_flags, ret, 0);
6445 static int io_connect_prep_async(struct io_kiocb *req)
6447 struct io_async_connect *io = req->async_data;
6448 struct io_connect *conn = &req->connect;
6450 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6453 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6455 struct io_connect *conn = &req->connect;
6457 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6460 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6461 conn->addr_len = READ_ONCE(sqe->addr2);
6465 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6467 struct io_async_connect __io, *io;
6468 unsigned file_flags;
6470 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6472 if (req_has_async_data(req)) {
6473 io = req->async_data;
6475 ret = move_addr_to_kernel(req->connect.addr,
6476 req->connect.addr_len,
6483 file_flags = force_nonblock ? O_NONBLOCK : 0;
6485 ret = __sys_connect_file(req->file, &io->address,
6486 req->connect.addr_len, file_flags);
6487 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6488 if (req_has_async_data(req))
6490 if (io_alloc_async_data(req)) {
6494 memcpy(req->async_data, &__io, sizeof(__io));
6497 if (ret == -ERESTARTSYS)
6502 __io_req_complete(req, issue_flags, ret, 0);
6505 #else /* !CONFIG_NET */
6506 #define IO_NETOP_FN(op) \
6507 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6509 return -EOPNOTSUPP; \
6512 #define IO_NETOP_PREP(op) \
6514 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6516 return -EOPNOTSUPP; \
6519 #define IO_NETOP_PREP_ASYNC(op) \
6521 static int io_##op##_prep_async(struct io_kiocb *req) \
6523 return -EOPNOTSUPP; \
6526 IO_NETOP_PREP_ASYNC(sendmsg);
6527 IO_NETOP_PREP_ASYNC(recvmsg);
6528 IO_NETOP_PREP_ASYNC(connect);
6529 IO_NETOP_PREP(accept);
6530 IO_NETOP_PREP(socket);
6531 IO_NETOP_PREP(shutdown);
6534 #endif /* CONFIG_NET */
6536 struct io_poll_table {
6537 struct poll_table_struct pt;
6538 struct io_kiocb *req;
6543 #define IO_POLL_CANCEL_FLAG BIT(31)
6544 #define IO_POLL_REF_MASK GENMASK(30, 0)
6547 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6548 * bump it and acquire ownership. It's disallowed to modify requests while not
6549 * owning it, that prevents from races for enqueueing task_work's and b/w
6550 * arming poll and wakeups.
6552 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6554 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6557 static void io_poll_mark_cancelled(struct io_kiocb *req)
6559 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6562 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6564 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6565 if (req->opcode == IORING_OP_POLL_ADD)
6566 return req->async_data;
6567 return req->apoll->double_poll;
6570 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6572 if (req->opcode == IORING_OP_POLL_ADD)
6574 return &req->apoll->poll;
6577 static void io_poll_req_insert(struct io_kiocb *req)
6579 struct io_ring_ctx *ctx = req->ctx;
6580 struct hlist_head *list;
6582 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6583 hlist_add_head(&req->hash_node, list);
6586 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6587 wait_queue_func_t wake_func)
6590 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6591 /* mask in events that we always want/need */
6592 poll->events = events | IO_POLL_UNMASK;
6593 INIT_LIST_HEAD(&poll->wait.entry);
6594 init_waitqueue_func_entry(&poll->wait, wake_func);
6597 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6599 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6602 spin_lock_irq(&head->lock);
6603 list_del_init(&poll->wait.entry);
6605 spin_unlock_irq(&head->lock);
6609 static void io_poll_remove_entries(struct io_kiocb *req)
6612 * Nothing to do if neither of those flags are set. Avoid dipping
6613 * into the poll/apoll/double cachelines if we can.
6615 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6619 * While we hold the waitqueue lock and the waitqueue is nonempty,
6620 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6621 * lock in the first place can race with the waitqueue being freed.
6623 * We solve this as eventpoll does: by taking advantage of the fact that
6624 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6625 * we enter rcu_read_lock() and see that the pointer to the queue is
6626 * non-NULL, we can then lock it without the memory being freed out from
6629 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6630 * case the caller deletes the entry from the queue, leaving it empty.
6631 * In that case, only RCU prevents the queue memory from being freed.
6634 if (req->flags & REQ_F_SINGLE_POLL)
6635 io_poll_remove_entry(io_poll_get_single(req));
6636 if (req->flags & REQ_F_DOUBLE_POLL)
6637 io_poll_remove_entry(io_poll_get_double(req));
6641 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6643 * All poll tw should go through this. Checks for poll events, manages
6644 * references, does rewait, etc.
6646 * Returns a negative error on failure. >0 when no action require, which is
6647 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6648 * the request, then the mask is stored in req->cqe.res.
6650 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6652 struct io_ring_ctx *ctx = req->ctx;
6655 /* req->task == current here, checking PF_EXITING is safe */
6656 if (unlikely(req->task->flags & PF_EXITING))
6660 v = atomic_read(&req->poll_refs);
6662 /* tw handler should be the owner, and so have some references */
6663 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6665 if (v & IO_POLL_CANCEL_FLAG)
6668 if (!req->cqe.res) {
6669 struct poll_table_struct pt = { ._key = req->apoll_events };
6670 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6673 if ((unlikely(!req->cqe.res)))
6675 if (req->apoll_events & EPOLLONESHOT)
6678 /* multishot, just fill a CQE and proceed */
6679 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6680 __poll_t mask = mangle_poll(req->cqe.res &
6684 spin_lock(&ctx->completion_lock);
6685 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6686 mask, IORING_CQE_F_MORE);
6687 io_commit_cqring(ctx);
6688 spin_unlock(&ctx->completion_lock);
6690 io_cqring_ev_posted(ctx);
6696 io_tw_lock(req->ctx, locked);
6697 if (unlikely(req->task->flags & PF_EXITING))
6699 ret = io_issue_sqe(req,
6700 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6705 * Release all references, retry if someone tried to restart
6706 * task_work while we were executing it.
6708 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6713 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6715 struct io_ring_ctx *ctx = req->ctx;
6718 ret = io_poll_check_events(req, locked);
6723 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6729 io_poll_remove_entries(req);
6730 spin_lock(&ctx->completion_lock);
6731 hash_del(&req->hash_node);
6732 __io_req_complete_post(req, req->cqe.res, 0);
6733 io_commit_cqring(ctx);
6734 spin_unlock(&ctx->completion_lock);
6735 io_cqring_ev_posted(ctx);
6738 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6740 struct io_ring_ctx *ctx = req->ctx;
6743 ret = io_poll_check_events(req, locked);
6747 io_poll_remove_entries(req);
6748 spin_lock(&ctx->completion_lock);
6749 hash_del(&req->hash_node);
6750 spin_unlock(&ctx->completion_lock);
6753 io_req_task_submit(req, locked);
6755 io_req_complete_failed(req, ret);
6758 static void __io_poll_execute(struct io_kiocb *req, int mask,
6759 __poll_t __maybe_unused events)
6761 req->cqe.res = mask;
6763 * This is useful for poll that is armed on behalf of another
6764 * request, and where the wakeup path could be on a different
6765 * CPU. We want to avoid pulling in req->apoll->events for that
6768 if (req->opcode == IORING_OP_POLL_ADD)
6769 req->io_task_work.func = io_poll_task_func;
6771 req->io_task_work.func = io_apoll_task_func;
6773 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6774 io_req_task_work_add(req);
6777 static inline void io_poll_execute(struct io_kiocb *req, int res,
6780 if (io_poll_get_ownership(req))
6781 __io_poll_execute(req, res, events);
6784 static void io_poll_cancel_req(struct io_kiocb *req)
6786 io_poll_mark_cancelled(req);
6787 /* kick tw, which should complete the request */
6788 io_poll_execute(req, 0, 0);
6791 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6792 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6793 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
6795 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6798 struct io_kiocb *req = wqe_to_req(wait);
6799 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6801 __poll_t mask = key_to_poll(key);
6803 if (unlikely(mask & POLLFREE)) {
6804 io_poll_mark_cancelled(req);
6805 /* we have to kick tw in case it's not already */
6806 io_poll_execute(req, 0, poll->events);
6809 * If the waitqueue is being freed early but someone is already
6810 * holds ownership over it, we have to tear down the request as
6811 * best we can. That means immediately removing the request from
6812 * its waitqueue and preventing all further accesses to the
6813 * waitqueue via the request.
6815 list_del_init(&poll->wait.entry);
6818 * Careful: this *must* be the last step, since as soon
6819 * as req->head is NULL'ed out, the request can be
6820 * completed and freed, since aio_poll_complete_work()
6821 * will no longer need to take the waitqueue lock.
6823 smp_store_release(&poll->head, NULL);
6827 /* for instances that support it check for an event match first */
6828 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
6831 if (io_poll_get_ownership(req)) {
6832 /* optional, saves extra locking for removal in tw handler */
6833 if (mask && poll->events & EPOLLONESHOT) {
6834 list_del_init(&poll->wait.entry);
6836 if (wqe_is_double(wait))
6837 req->flags &= ~REQ_F_DOUBLE_POLL;
6839 req->flags &= ~REQ_F_SINGLE_POLL;
6841 __io_poll_execute(req, mask, poll->events);
6846 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6847 struct wait_queue_head *head,
6848 struct io_poll_iocb **poll_ptr)
6850 struct io_kiocb *req = pt->req;
6851 unsigned long wqe_private = (unsigned long) req;
6854 * The file being polled uses multiple waitqueues for poll handling
6855 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6858 if (unlikely(pt->nr_entries)) {
6859 struct io_poll_iocb *first = poll;
6861 /* double add on the same waitqueue head, ignore */
6862 if (first->head == head)
6864 /* already have a 2nd entry, fail a third attempt */
6866 if ((*poll_ptr)->head == head)
6868 pt->error = -EINVAL;
6872 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6874 pt->error = -ENOMEM;
6877 /* mark as double wq entry */
6879 req->flags |= REQ_F_DOUBLE_POLL;
6880 io_init_poll_iocb(poll, first->events, first->wait.func);
6882 if (req->opcode == IORING_OP_POLL_ADD)
6883 req->flags |= REQ_F_ASYNC_DATA;
6886 req->flags |= REQ_F_SINGLE_POLL;
6889 poll->wait.private = (void *) wqe_private;
6891 if (poll->events & EPOLLEXCLUSIVE)
6892 add_wait_queue_exclusive(head, &poll->wait);
6894 add_wait_queue(head, &poll->wait);
6897 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6898 struct poll_table_struct *p)
6900 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6902 __io_queue_proc(&pt->req->poll, pt, head,
6903 (struct io_poll_iocb **) &pt->req->async_data);
6906 static int __io_arm_poll_handler(struct io_kiocb *req,
6907 struct io_poll_iocb *poll,
6908 struct io_poll_table *ipt, __poll_t mask)
6910 struct io_ring_ctx *ctx = req->ctx;
6913 INIT_HLIST_NODE(&req->hash_node);
6914 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
6915 io_init_poll_iocb(poll, mask, io_poll_wake);
6916 poll->file = req->file;
6918 req->apoll_events = poll->events;
6920 ipt->pt._key = mask;
6923 ipt->nr_entries = 0;
6926 * Take the ownership to delay any tw execution up until we're done
6927 * with poll arming. see io_poll_get_ownership().
6929 atomic_set(&req->poll_refs, 1);
6930 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6932 if (mask && (poll->events & EPOLLONESHOT)) {
6933 io_poll_remove_entries(req);
6934 /* no one else has access to the req, forget about the ref */
6937 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6938 io_poll_remove_entries(req);
6940 ipt->error = -EINVAL;
6944 spin_lock(&ctx->completion_lock);
6945 io_poll_req_insert(req);
6946 spin_unlock(&ctx->completion_lock);
6949 /* can't multishot if failed, just queue the event we've got */
6950 if (unlikely(ipt->error || !ipt->nr_entries)) {
6951 poll->events |= EPOLLONESHOT;
6952 req->apoll_events |= EPOLLONESHOT;
6955 __io_poll_execute(req, mask, poll->events);
6960 * Release ownership. If someone tried to queue a tw while it was
6961 * locked, kick it off for them.
6963 v = atomic_dec_return(&req->poll_refs);
6964 if (unlikely(v & IO_POLL_REF_MASK))
6965 __io_poll_execute(req, 0, poll->events);
6969 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6970 struct poll_table_struct *p)
6972 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6973 struct async_poll *apoll = pt->req->apoll;
6975 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6984 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6986 const struct io_op_def *def = &io_op_defs[req->opcode];
6987 struct io_ring_ctx *ctx = req->ctx;
6988 struct async_poll *apoll;
6989 struct io_poll_table ipt;
6990 __poll_t mask = POLLPRI | POLLERR;
6993 if (!def->pollin && !def->pollout)
6994 return IO_APOLL_ABORTED;
6995 if (!file_can_poll(req->file))
6996 return IO_APOLL_ABORTED;
6997 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
6998 return IO_APOLL_ABORTED;
6999 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7000 mask |= EPOLLONESHOT;
7003 mask |= EPOLLIN | EPOLLRDNORM;
7005 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7006 if ((req->opcode == IORING_OP_RECVMSG) &&
7007 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7010 mask |= EPOLLOUT | EPOLLWRNORM;
7012 if (def->poll_exclusive)
7013 mask |= EPOLLEXCLUSIVE;
7014 if (req->flags & REQ_F_POLLED) {
7016 kfree(apoll->double_poll);
7017 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7018 !list_empty(&ctx->apoll_cache)) {
7019 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7021 list_del_init(&apoll->poll.wait.entry);
7023 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7024 if (unlikely(!apoll))
7025 return IO_APOLL_ABORTED;
7027 apoll->double_poll = NULL;
7029 req->flags |= REQ_F_POLLED;
7030 ipt.pt._qproc = io_async_queue_proc;
7032 io_kbuf_recycle(req, issue_flags);
7034 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7035 if (ret || ipt.error)
7036 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7038 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7039 mask, apoll->poll.events);
7044 * Returns true if we found and killed one or more poll requests
7046 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7047 struct task_struct *tsk, bool cancel_all)
7049 struct hlist_node *tmp;
7050 struct io_kiocb *req;
7054 spin_lock(&ctx->completion_lock);
7055 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7056 struct hlist_head *list;
7058 list = &ctx->cancel_hash[i];
7059 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7060 if (io_match_task_safe(req, tsk, cancel_all)) {
7061 hlist_del_init(&req->hash_node);
7062 io_poll_cancel_req(req);
7067 spin_unlock(&ctx->completion_lock);
7071 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7072 struct io_cancel_data *cd)
7073 __must_hold(&ctx->completion_lock)
7075 struct hlist_head *list;
7076 struct io_kiocb *req;
7078 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7079 hlist_for_each_entry(req, list, hash_node) {
7080 if (cd->data != req->cqe.user_data)
7082 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7084 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7085 if (cd->seq == req->work.cancel_seq)
7087 req->work.cancel_seq = cd->seq;
7094 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7095 struct io_cancel_data *cd)
7096 __must_hold(&ctx->completion_lock)
7098 struct io_kiocb *req;
7101 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7102 struct hlist_head *list;
7104 list = &ctx->cancel_hash[i];
7105 hlist_for_each_entry(req, list, hash_node) {
7106 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7107 req->file != cd->file)
7109 if (cd->seq == req->work.cancel_seq)
7111 req->work.cancel_seq = cd->seq;
7118 static bool io_poll_disarm(struct io_kiocb *req)
7119 __must_hold(&ctx->completion_lock)
7121 if (!io_poll_get_ownership(req))
7123 io_poll_remove_entries(req);
7124 hash_del(&req->hash_node);
7128 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7129 __must_hold(&ctx->completion_lock)
7131 struct io_kiocb *req;
7133 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7134 req = io_poll_file_find(ctx, cd);
7136 req = io_poll_find(ctx, false, cd);
7139 io_poll_cancel_req(req);
7143 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7148 events = READ_ONCE(sqe->poll32_events);
7150 events = swahw32(events);
7152 if (!(flags & IORING_POLL_ADD_MULTI))
7153 events |= EPOLLONESHOT;
7154 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7157 static int io_poll_remove_prep(struct io_kiocb *req,
7158 const struct io_uring_sqe *sqe)
7160 struct io_poll_update *upd = &req->poll_update;
7163 if (sqe->buf_index || sqe->splice_fd_in)
7165 flags = READ_ONCE(sqe->len);
7166 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7167 IORING_POLL_ADD_MULTI))
7169 /* meaningless without update */
7170 if (flags == IORING_POLL_ADD_MULTI)
7173 upd->old_user_data = READ_ONCE(sqe->addr);
7174 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7175 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7177 upd->new_user_data = READ_ONCE(sqe->off);
7178 if (!upd->update_user_data && upd->new_user_data)
7180 if (upd->update_events)
7181 upd->events = io_poll_parse_events(sqe, flags);
7182 else if (sqe->poll32_events)
7188 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7190 struct io_poll_iocb *poll = &req->poll;
7193 if (sqe->buf_index || sqe->off || sqe->addr)
7195 flags = READ_ONCE(sqe->len);
7196 if (flags & ~IORING_POLL_ADD_MULTI)
7198 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7201 io_req_set_refcount(req);
7202 poll->events = io_poll_parse_events(sqe, flags);
7206 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7208 struct io_poll_iocb *poll = &req->poll;
7209 struct io_poll_table ipt;
7212 ipt.pt._qproc = io_poll_queue_proc;
7214 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7215 if (!ret && ipt.error)
7217 ret = ret ?: ipt.error;
7219 __io_req_complete(req, issue_flags, ret, 0);
7223 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7225 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7226 struct io_ring_ctx *ctx = req->ctx;
7227 struct io_kiocb *preq;
7231 spin_lock(&ctx->completion_lock);
7232 preq = io_poll_find(ctx, true, &cd);
7233 if (!preq || !io_poll_disarm(preq)) {
7234 spin_unlock(&ctx->completion_lock);
7235 ret = preq ? -EALREADY : -ENOENT;
7238 spin_unlock(&ctx->completion_lock);
7240 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7241 /* only mask one event flags, keep behavior flags */
7242 if (req->poll_update.update_events) {
7243 preq->poll.events &= ~0xffff;
7244 preq->poll.events |= req->poll_update.events & 0xffff;
7245 preq->poll.events |= IO_POLL_UNMASK;
7247 if (req->poll_update.update_user_data)
7248 preq->cqe.user_data = req->poll_update.new_user_data;
7250 ret2 = io_poll_add(preq, issue_flags);
7251 /* successfully updated, don't complete poll request */
7257 preq->cqe.res = -ECANCELED;
7258 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7259 io_req_task_complete(preq, &locked);
7263 /* complete update request, we're done with it */
7264 __io_req_complete(req, issue_flags, ret, 0);
7268 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7270 struct io_timeout_data *data = container_of(timer,
7271 struct io_timeout_data, timer);
7272 struct io_kiocb *req = data->req;
7273 struct io_ring_ctx *ctx = req->ctx;
7274 unsigned long flags;
7276 spin_lock_irqsave(&ctx->timeout_lock, flags);
7277 list_del_init(&req->timeout.list);
7278 atomic_set(&req->ctx->cq_timeouts,
7279 atomic_read(&req->ctx->cq_timeouts) + 1);
7280 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7282 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7285 req->cqe.res = -ETIME;
7286 req->io_task_work.func = io_req_task_complete;
7287 io_req_task_work_add(req);
7288 return HRTIMER_NORESTART;
7291 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7292 struct io_cancel_data *cd)
7293 __must_hold(&ctx->timeout_lock)
7295 struct io_timeout_data *io;
7296 struct io_kiocb *req;
7299 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7300 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7301 cd->data != req->cqe.user_data)
7303 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7304 if (cd->seq == req->work.cancel_seq)
7306 req->work.cancel_seq = cd->seq;
7312 return ERR_PTR(-ENOENT);
7314 io = req->async_data;
7315 if (hrtimer_try_to_cancel(&io->timer) == -1)
7316 return ERR_PTR(-EALREADY);
7317 list_del_init(&req->timeout.list);
7321 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7322 __must_hold(&ctx->completion_lock)
7324 struct io_kiocb *req;
7326 spin_lock_irq(&ctx->timeout_lock);
7327 req = io_timeout_extract(ctx, cd);
7328 spin_unlock_irq(&ctx->timeout_lock);
7331 return PTR_ERR(req);
7332 io_req_task_queue_fail(req, -ECANCELED);
7336 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7338 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7339 case IORING_TIMEOUT_BOOTTIME:
7340 return CLOCK_BOOTTIME;
7341 case IORING_TIMEOUT_REALTIME:
7342 return CLOCK_REALTIME;
7344 /* can't happen, vetted at prep time */
7348 return CLOCK_MONOTONIC;
7352 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7353 struct timespec64 *ts, enum hrtimer_mode mode)
7354 __must_hold(&ctx->timeout_lock)
7356 struct io_timeout_data *io;
7357 struct io_kiocb *req;
7360 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7361 found = user_data == req->cqe.user_data;
7368 io = req->async_data;
7369 if (hrtimer_try_to_cancel(&io->timer) == -1)
7371 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7372 io->timer.function = io_link_timeout_fn;
7373 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7377 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7378 struct timespec64 *ts, enum hrtimer_mode mode)
7379 __must_hold(&ctx->timeout_lock)
7381 struct io_cancel_data cd = { .data = user_data, };
7382 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7383 struct io_timeout_data *data;
7386 return PTR_ERR(req);
7388 req->timeout.off = 0; /* noseq */
7389 data = req->async_data;
7390 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7391 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7392 data->timer.function = io_timeout_fn;
7393 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7397 static int io_timeout_remove_prep(struct io_kiocb *req,
7398 const struct io_uring_sqe *sqe)
7400 struct io_timeout_rem *tr = &req->timeout_rem;
7402 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7404 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7407 tr->ltimeout = false;
7408 tr->addr = READ_ONCE(sqe->addr);
7409 tr->flags = READ_ONCE(sqe->timeout_flags);
7410 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7411 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7413 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7414 tr->ltimeout = true;
7415 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7417 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7419 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7421 } else if (tr->flags) {
7422 /* timeout removal doesn't support flags */
7429 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7431 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7436 * Remove or update an existing timeout command
7438 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7440 struct io_timeout_rem *tr = &req->timeout_rem;
7441 struct io_ring_ctx *ctx = req->ctx;
7444 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7445 struct io_cancel_data cd = { .data = tr->addr, };
7447 spin_lock(&ctx->completion_lock);
7448 ret = io_timeout_cancel(ctx, &cd);
7449 spin_unlock(&ctx->completion_lock);
7451 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7453 spin_lock_irq(&ctx->timeout_lock);
7455 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7457 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7458 spin_unlock_irq(&ctx->timeout_lock);
7463 io_req_complete_post(req, ret, 0);
7467 static int __io_timeout_prep(struct io_kiocb *req,
7468 const struct io_uring_sqe *sqe,
7469 bool is_timeout_link)
7471 struct io_timeout_data *data;
7473 u32 off = READ_ONCE(sqe->off);
7475 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7477 if (off && is_timeout_link)
7479 flags = READ_ONCE(sqe->timeout_flags);
7480 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7481 IORING_TIMEOUT_ETIME_SUCCESS))
7483 /* more than one clock specified is invalid, obviously */
7484 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7487 INIT_LIST_HEAD(&req->timeout.list);
7488 req->timeout.off = off;
7489 if (unlikely(off && !req->ctx->off_timeout_used))
7490 req->ctx->off_timeout_used = true;
7492 if (WARN_ON_ONCE(req_has_async_data(req)))
7494 if (io_alloc_async_data(req))
7497 data = req->async_data;
7499 data->flags = flags;
7501 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7504 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7507 INIT_LIST_HEAD(&req->timeout.list);
7508 data->mode = io_translate_timeout_mode(flags);
7509 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7511 if (is_timeout_link) {
7512 struct io_submit_link *link = &req->ctx->submit_state.link;
7516 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7518 req->timeout.head = link->last;
7519 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7524 static int io_timeout_prep(struct io_kiocb *req,
7525 const struct io_uring_sqe *sqe)
7527 return __io_timeout_prep(req, sqe, false);
7530 static int io_link_timeout_prep(struct io_kiocb *req,
7531 const struct io_uring_sqe *sqe)
7533 return __io_timeout_prep(req, sqe, true);
7536 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7538 struct io_ring_ctx *ctx = req->ctx;
7539 struct io_timeout_data *data = req->async_data;
7540 struct list_head *entry;
7541 u32 tail, off = req->timeout.off;
7543 spin_lock_irq(&ctx->timeout_lock);
7546 * sqe->off holds how many events that need to occur for this
7547 * timeout event to be satisfied. If it isn't set, then this is
7548 * a pure timeout request, sequence isn't used.
7550 if (io_is_timeout_noseq(req)) {
7551 entry = ctx->timeout_list.prev;
7555 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7556 req->timeout.target_seq = tail + off;
7558 /* Update the last seq here in case io_flush_timeouts() hasn't.
7559 * This is safe because ->completion_lock is held, and submissions
7560 * and completions are never mixed in the same ->completion_lock section.
7562 ctx->cq_last_tm_flush = tail;
7565 * Insertion sort, ensuring the first entry in the list is always
7566 * the one we need first.
7568 list_for_each_prev(entry, &ctx->timeout_list) {
7569 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7572 if (io_is_timeout_noseq(nxt))
7574 /* nxt.seq is behind @tail, otherwise would've been completed */
7575 if (off >= nxt->timeout.target_seq - tail)
7579 list_add(&req->timeout.list, entry);
7580 data->timer.function = io_timeout_fn;
7581 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7582 spin_unlock_irq(&ctx->timeout_lock);
7586 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7588 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7589 struct io_cancel_data *cd = data;
7591 if (req->ctx != cd->ctx)
7593 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7595 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7596 if (req->file != cd->file)
7599 if (req->cqe.user_data != cd->data)
7602 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7603 if (cd->seq == req->work.cancel_seq)
7605 req->work.cancel_seq = cd->seq;
7610 static int io_async_cancel_one(struct io_uring_task *tctx,
7611 struct io_cancel_data *cd)
7613 enum io_wq_cancel cancel_ret;
7617 if (!tctx || !tctx->io_wq)
7620 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7621 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7622 switch (cancel_ret) {
7623 case IO_WQ_CANCEL_OK:
7626 case IO_WQ_CANCEL_RUNNING:
7629 case IO_WQ_CANCEL_NOTFOUND:
7637 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7639 struct io_ring_ctx *ctx = req->ctx;
7642 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7644 ret = io_async_cancel_one(req->task->io_uring, cd);
7646 * Fall-through even for -EALREADY, as we may have poll armed
7647 * that need unarming.
7652 spin_lock(&ctx->completion_lock);
7653 ret = io_poll_cancel(ctx, cd);
7656 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7657 ret = io_timeout_cancel(ctx, cd);
7659 spin_unlock(&ctx->completion_lock);
7663 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7664 IORING_ASYNC_CANCEL_ANY)
7666 static int io_async_cancel_prep(struct io_kiocb *req,
7667 const struct io_uring_sqe *sqe)
7669 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7671 if (sqe->off || sqe->len || sqe->splice_fd_in)
7674 req->cancel.addr = READ_ONCE(sqe->addr);
7675 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7676 if (req->cancel.flags & ~CANCEL_FLAGS)
7678 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7679 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7681 req->cancel.fd = READ_ONCE(sqe->fd);
7687 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7688 unsigned int issue_flags)
7690 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7691 struct io_ring_ctx *ctx = cd->ctx;
7692 struct io_tctx_node *node;
7696 ret = io_try_cancel(req, cd);
7704 /* slow path, try all io-wq's */
7705 io_ring_submit_lock(ctx, issue_flags);
7707 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7708 struct io_uring_task *tctx = node->task->io_uring;
7710 ret = io_async_cancel_one(tctx, cd);
7711 if (ret != -ENOENT) {
7717 io_ring_submit_unlock(ctx, issue_flags);
7718 return all ? nr : ret;
7721 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7723 struct io_cancel_data cd = {
7725 .data = req->cancel.addr,
7726 .flags = req->cancel.flags,
7727 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7731 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7732 if (req->flags & REQ_F_FIXED_FILE)
7733 req->file = io_file_get_fixed(req, req->cancel.fd,
7736 req->file = io_file_get_normal(req, req->cancel.fd);
7741 cd.file = req->file;
7744 ret = __io_async_cancel(&cd, req, issue_flags);
7748 io_req_complete_post(req, ret, 0);
7752 static int io_files_update_prep(struct io_kiocb *req,
7753 const struct io_uring_sqe *sqe)
7755 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7757 if (sqe->rw_flags || sqe->splice_fd_in)
7760 req->rsrc_update.offset = READ_ONCE(sqe->off);
7761 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7762 if (!req->rsrc_update.nr_args)
7764 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7768 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7769 unsigned int issue_flags)
7771 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7776 if (!req->ctx->file_data)
7779 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7780 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7790 ret = io_fixed_fd_install(req, issue_flags, file,
7791 IORING_FILE_INDEX_ALLOC);
7794 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
7795 __io_close_fixed(req, issue_flags, ret);
7806 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7808 struct io_ring_ctx *ctx = req->ctx;
7809 struct io_uring_rsrc_update2 up;
7812 up.offset = req->rsrc_update.offset;
7813 up.data = req->rsrc_update.arg;
7819 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
7820 ret = io_files_update_with_index_alloc(req, issue_flags);
7822 io_ring_submit_lock(ctx, issue_flags);
7823 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
7824 &up, req->rsrc_update.nr_args);
7825 io_ring_submit_unlock(ctx, issue_flags);
7830 __io_req_complete(req, issue_flags, ret, 0);
7834 static int io_req_prep_async(struct io_kiocb *req)
7836 const struct io_op_def *def = &io_op_defs[req->opcode];
7838 /* assign early for deferred execution for non-fixed file */
7839 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
7840 req->file = io_file_get_normal(req, req->cqe.fd);
7841 if (!def->needs_async_setup)
7843 if (WARN_ON_ONCE(req_has_async_data(req)))
7845 if (io_alloc_async_data(req))
7848 switch (req->opcode) {
7849 case IORING_OP_READV:
7850 return io_readv_prep_async(req);
7851 case IORING_OP_WRITEV:
7852 return io_writev_prep_async(req);
7853 case IORING_OP_SENDMSG:
7854 return io_sendmsg_prep_async(req);
7855 case IORING_OP_RECVMSG:
7856 return io_recvmsg_prep_async(req);
7857 case IORING_OP_CONNECT:
7858 return io_connect_prep_async(req);
7859 case IORING_OP_URING_CMD:
7860 return io_uring_cmd_prep_async(req);
7863 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
7868 static u32 io_get_sequence(struct io_kiocb *req)
7870 u32 seq = req->ctx->cached_sq_head;
7871 struct io_kiocb *cur;
7873 /* need original cached_sq_head, but it was increased for each req */
7874 io_for_each_link(cur, req)
7879 static __cold void io_drain_req(struct io_kiocb *req)
7881 struct io_ring_ctx *ctx = req->ctx;
7882 struct io_defer_entry *de;
7884 u32 seq = io_get_sequence(req);
7886 /* Still need defer if there is pending req in defer list. */
7887 spin_lock(&ctx->completion_lock);
7888 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7889 spin_unlock(&ctx->completion_lock);
7891 ctx->drain_active = false;
7892 io_req_task_queue(req);
7895 spin_unlock(&ctx->completion_lock);
7897 ret = io_req_prep_async(req);
7900 io_req_complete_failed(req, ret);
7903 io_prep_async_link(req);
7904 de = kmalloc(sizeof(*de), GFP_KERNEL);
7910 spin_lock(&ctx->completion_lock);
7911 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7912 spin_unlock(&ctx->completion_lock);
7917 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7920 list_add_tail(&de->list, &ctx->defer_list);
7921 spin_unlock(&ctx->completion_lock);
7924 static void io_clean_op(struct io_kiocb *req)
7926 if (req->flags & REQ_F_BUFFER_SELECTED) {
7927 spin_lock(&req->ctx->completion_lock);
7928 io_put_kbuf_comp(req);
7929 spin_unlock(&req->ctx->completion_lock);
7932 if (req->flags & REQ_F_NEED_CLEANUP) {
7933 switch (req->opcode) {
7934 case IORING_OP_READV:
7935 case IORING_OP_READ_FIXED:
7936 case IORING_OP_READ:
7937 case IORING_OP_WRITEV:
7938 case IORING_OP_WRITE_FIXED:
7939 case IORING_OP_WRITE: {
7940 struct io_async_rw *io = req->async_data;
7942 kfree(io->free_iovec);
7945 case IORING_OP_RECVMSG:
7946 case IORING_OP_SENDMSG: {
7947 struct io_async_msghdr *io = req->async_data;
7949 kfree(io->free_iov);
7952 case IORING_OP_OPENAT:
7953 case IORING_OP_OPENAT2:
7954 if (req->open.filename)
7955 putname(req->open.filename);
7957 case IORING_OP_RENAMEAT:
7958 putname(req->rename.oldpath);
7959 putname(req->rename.newpath);
7961 case IORING_OP_UNLINKAT:
7962 putname(req->unlink.filename);
7964 case IORING_OP_MKDIRAT:
7965 putname(req->mkdir.filename);
7967 case IORING_OP_SYMLINKAT:
7968 putname(req->symlink.oldpath);
7969 putname(req->symlink.newpath);
7971 case IORING_OP_LINKAT:
7972 putname(req->hardlink.oldpath);
7973 putname(req->hardlink.newpath);
7975 case IORING_OP_STATX:
7976 if (req->statx.filename)
7977 putname(req->statx.filename);
7979 case IORING_OP_SETXATTR:
7980 case IORING_OP_FSETXATTR:
7981 case IORING_OP_GETXATTR:
7982 case IORING_OP_FGETXATTR:
7983 __io_xattr_finish(req);
7987 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7988 kfree(req->apoll->double_poll);
7992 if (req->flags & REQ_F_INFLIGHT) {
7993 struct io_uring_task *tctx = req->task->io_uring;
7995 atomic_dec(&tctx->inflight_tracked);
7997 if (req->flags & REQ_F_CREDS)
7998 put_cred(req->creds);
7999 if (req->flags & REQ_F_ASYNC_DATA) {
8000 kfree(req->async_data);
8001 req->async_data = NULL;
8003 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8006 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8008 if (req->file || !io_op_defs[req->opcode].needs_file)
8011 if (req->flags & REQ_F_FIXED_FILE)
8012 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8014 req->file = io_file_get_normal(req, req->cqe.fd);
8019 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8021 const struct io_op_def *def = &io_op_defs[req->opcode];
8022 const struct cred *creds = NULL;
8025 if (unlikely(!io_assign_file(req, issue_flags)))
8028 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8029 creds = override_creds(req->creds);
8031 if (!def->audit_skip)
8032 audit_uring_entry(req->opcode);
8034 ret = def->issue(req, issue_flags);
8036 if (!def->audit_skip)
8037 audit_uring_exit(!ret, ret);
8040 revert_creds(creds);
8043 /* If the op doesn't have a file, we're not polling for it */
8044 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8045 io_iopoll_req_issued(req, issue_flags);
8050 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8052 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8054 req = io_put_req_find_next(req);
8055 return req ? &req->work : NULL;
8058 static void io_wq_submit_work(struct io_wq_work *work)
8060 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8061 const struct io_op_def *def = &io_op_defs[req->opcode];
8062 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8063 bool needs_poll = false;
8064 int ret = 0, err = -ECANCELED;
8066 /* one will be dropped by ->io_free_work() after returning to io-wq */
8067 if (!(req->flags & REQ_F_REFCOUNT))
8068 __io_req_set_refcount(req, 2);
8072 io_arm_ltimeout(req);
8074 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8075 if (work->flags & IO_WQ_WORK_CANCEL) {
8077 io_req_task_queue_fail(req, err);
8080 if (!io_assign_file(req, issue_flags)) {
8082 work->flags |= IO_WQ_WORK_CANCEL;
8086 if (req->flags & REQ_F_FORCE_ASYNC) {
8087 bool opcode_poll = def->pollin || def->pollout;
8089 if (opcode_poll && file_can_poll(req->file)) {
8091 issue_flags |= IO_URING_F_NONBLOCK;
8096 ret = io_issue_sqe(req, issue_flags);
8100 * We can get EAGAIN for iopolled IO even though we're
8101 * forcing a sync submission from here, since we can't
8102 * wait for request slots on the block side.
8105 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8111 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8113 /* aborted or ready, in either case retry blocking */
8115 issue_flags &= ~IO_URING_F_NONBLOCK;
8118 /* avoid locking problems by failing it from a clean context */
8120 io_req_task_queue_fail(req, ret);
8123 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8126 return &table->files[i];
8129 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8132 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8134 return (struct file *) (slot->file_ptr & FFS_MASK);
8137 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8139 unsigned long file_ptr = (unsigned long) file;
8141 file_ptr |= io_file_get_flags(file);
8142 file_slot->file_ptr = file_ptr;
8145 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8146 unsigned int issue_flags)
8148 struct io_ring_ctx *ctx = req->ctx;
8149 struct file *file = NULL;
8150 unsigned long file_ptr;
8152 io_ring_submit_lock(ctx, issue_flags);
8154 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8156 fd = array_index_nospec(fd, ctx->nr_user_files);
8157 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8158 file = (struct file *) (file_ptr & FFS_MASK);
8159 file_ptr &= ~FFS_MASK;
8160 /* mask in overlapping REQ_F and FFS bits */
8161 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8162 io_req_set_rsrc_node(req, ctx, 0);
8163 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8165 io_ring_submit_unlock(ctx, issue_flags);
8169 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8171 struct file *file = fget(fd);
8173 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8175 /* we don't allow fixed io_uring files */
8176 if (file && file->f_op == &io_uring_fops)
8177 io_req_track_inflight(req);
8181 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8183 struct io_kiocb *prev = req->timeout.prev;
8187 if (!(req->task->flags & PF_EXITING)) {
8188 struct io_cancel_data cd = {
8190 .data = prev->cqe.user_data,
8193 ret = io_try_cancel(req, &cd);
8195 io_req_complete_post(req, ret ?: -ETIME, 0);
8198 io_req_complete_post(req, -ETIME, 0);
8202 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8204 struct io_timeout_data *data = container_of(timer,
8205 struct io_timeout_data, timer);
8206 struct io_kiocb *prev, *req = data->req;
8207 struct io_ring_ctx *ctx = req->ctx;
8208 unsigned long flags;
8210 spin_lock_irqsave(&ctx->timeout_lock, flags);
8211 prev = req->timeout.head;
8212 req->timeout.head = NULL;
8215 * We don't expect the list to be empty, that will only happen if we
8216 * race with the completion of the linked work.
8219 io_remove_next_linked(prev);
8220 if (!req_ref_inc_not_zero(prev))
8223 list_del(&req->timeout.list);
8224 req->timeout.prev = prev;
8225 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8227 req->io_task_work.func = io_req_task_link_timeout;
8228 io_req_task_work_add(req);
8229 return HRTIMER_NORESTART;
8232 static void io_queue_linked_timeout(struct io_kiocb *req)
8234 struct io_ring_ctx *ctx = req->ctx;
8236 spin_lock_irq(&ctx->timeout_lock);
8238 * If the back reference is NULL, then our linked request finished
8239 * before we got a chance to setup the timer
8241 if (req->timeout.head) {
8242 struct io_timeout_data *data = req->async_data;
8244 data->timer.function = io_link_timeout_fn;
8245 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8247 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8249 spin_unlock_irq(&ctx->timeout_lock);
8250 /* drop submission reference */
8254 static void io_queue_async(struct io_kiocb *req, int ret)
8255 __must_hold(&req->ctx->uring_lock)
8257 struct io_kiocb *linked_timeout;
8259 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8260 io_req_complete_failed(req, ret);
8264 linked_timeout = io_prep_linked_timeout(req);
8266 switch (io_arm_poll_handler(req, 0)) {
8267 case IO_APOLL_READY:
8268 io_kbuf_recycle(req, 0);
8269 io_req_task_queue(req);
8271 case IO_APOLL_ABORTED:
8273 * Queued up for async execution, worker will release
8274 * submit reference when the iocb is actually submitted.
8276 io_kbuf_recycle(req, 0);
8277 io_queue_iowq(req, NULL);
8284 io_queue_linked_timeout(linked_timeout);
8287 static inline void io_queue_sqe(struct io_kiocb *req)
8288 __must_hold(&req->ctx->uring_lock)
8292 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8294 if (req->flags & REQ_F_COMPLETE_INLINE) {
8295 io_req_add_compl_list(req);
8299 * We async punt it if the file wasn't marked NOWAIT, or if the file
8300 * doesn't support non-blocking read/write attempts
8303 io_arm_ltimeout(req);
8305 io_queue_async(req, ret);
8308 static void io_queue_sqe_fallback(struct io_kiocb *req)
8309 __must_hold(&req->ctx->uring_lock)
8311 if (unlikely(req->flags & REQ_F_FAIL)) {
8313 * We don't submit, fail them all, for that replace hardlinks
8314 * with normal links. Extra REQ_F_LINK is tolerated.
8316 req->flags &= ~REQ_F_HARDLINK;
8317 req->flags |= REQ_F_LINK;
8318 io_req_complete_failed(req, req->cqe.res);
8319 } else if (unlikely(req->ctx->drain_active)) {
8322 int ret = io_req_prep_async(req);
8325 io_req_complete_failed(req, ret);
8327 io_queue_iowq(req, NULL);
8332 * Check SQE restrictions (opcode and flags).
8334 * Returns 'true' if SQE is allowed, 'false' otherwise.
8336 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8337 struct io_kiocb *req,
8338 unsigned int sqe_flags)
8340 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8343 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8344 ctx->restrictions.sqe_flags_required)
8347 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8348 ctx->restrictions.sqe_flags_required))
8354 static void io_init_req_drain(struct io_kiocb *req)
8356 struct io_ring_ctx *ctx = req->ctx;
8357 struct io_kiocb *head = ctx->submit_state.link.head;
8359 ctx->drain_active = true;
8362 * If we need to drain a request in the middle of a link, drain
8363 * the head request and the next request/link after the current
8364 * link. Considering sequential execution of links,
8365 * REQ_F_IO_DRAIN will be maintained for every request of our
8368 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8369 ctx->drain_next = true;
8373 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8374 const struct io_uring_sqe *sqe)
8375 __must_hold(&ctx->uring_lock)
8377 const struct io_op_def *def;
8378 unsigned int sqe_flags;
8382 /* req is partially pre-initialised, see io_preinit_req() */
8383 req->opcode = opcode = READ_ONCE(sqe->opcode);
8384 /* same numerical values with corresponding REQ_F_*, safe to copy */
8385 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8386 req->cqe.user_data = READ_ONCE(sqe->user_data);
8388 req->rsrc_node = NULL;
8389 req->task = current;
8391 if (unlikely(opcode >= IORING_OP_LAST)) {
8395 def = &io_op_defs[opcode];
8396 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8397 /* enforce forwards compatibility on users */
8398 if (sqe_flags & ~SQE_VALID_FLAGS)
8400 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8401 if (!def->buffer_select)
8403 req->buf_index = READ_ONCE(sqe->buf_group);
8405 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8406 ctx->drain_disabled = true;
8407 if (sqe_flags & IOSQE_IO_DRAIN) {
8408 if (ctx->drain_disabled)
8410 io_init_req_drain(req);
8413 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8414 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8416 /* knock it to the slow queue path, will be drained there */
8417 if (ctx->drain_active)
8418 req->flags |= REQ_F_FORCE_ASYNC;
8419 /* if there is no link, we're at "next" request and need to drain */
8420 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8421 ctx->drain_next = false;
8422 ctx->drain_active = true;
8423 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8427 if (!def->ioprio && sqe->ioprio)
8429 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8432 if (def->needs_file) {
8433 struct io_submit_state *state = &ctx->submit_state;
8435 req->cqe.fd = READ_ONCE(sqe->fd);
8438 * Plug now if we have more than 2 IO left after this, and the
8439 * target is potentially a read/write to block based storage.
8441 if (state->need_plug && def->plug) {
8442 state->plug_started = true;
8443 state->need_plug = false;
8444 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8448 personality = READ_ONCE(sqe->personality);
8452 req->creds = xa_load(&ctx->personalities, personality);
8455 get_cred(req->creds);
8456 ret = security_uring_override_creds(req->creds);
8458 put_cred(req->creds);
8461 req->flags |= REQ_F_CREDS;
8464 return def->prep(req, sqe);
8467 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8468 struct io_kiocb *req, int ret)
8470 struct io_ring_ctx *ctx = req->ctx;
8471 struct io_submit_link *link = &ctx->submit_state.link;
8472 struct io_kiocb *head = link->head;
8474 trace_io_uring_req_failed(sqe, ctx, req, ret);
8477 * Avoid breaking links in the middle as it renders links with SQPOLL
8478 * unusable. Instead of failing eagerly, continue assembling the link if
8479 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8480 * should find the flag and handle the rest.
8482 req_fail_link_node(req, ret);
8483 if (head && !(head->flags & REQ_F_FAIL))
8484 req_fail_link_node(head, -ECANCELED);
8486 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8488 link->last->link = req;
8492 io_queue_sqe_fallback(req);
8497 link->last->link = req;
8504 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8505 const struct io_uring_sqe *sqe)
8506 __must_hold(&ctx->uring_lock)
8508 struct io_submit_link *link = &ctx->submit_state.link;
8511 ret = io_init_req(ctx, req, sqe);
8513 return io_submit_fail_init(sqe, req, ret);
8515 /* don't need @sqe from now on */
8516 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8518 ctx->flags & IORING_SETUP_SQPOLL);
8521 * If we already have a head request, queue this one for async
8522 * submittal once the head completes. If we don't have a head but
8523 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8524 * submitted sync once the chain is complete. If none of those
8525 * conditions are true (normal request), then just queue it.
8527 if (unlikely(link->head)) {
8528 ret = io_req_prep_async(req);
8530 return io_submit_fail_init(sqe, req, ret);
8532 trace_io_uring_link(ctx, req, link->head);
8533 link->last->link = req;
8536 if (req->flags & IO_REQ_LINK_FLAGS)
8538 /* last request of the link, flush it */
8541 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8544 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8545 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8546 if (req->flags & IO_REQ_LINK_FLAGS) {
8551 io_queue_sqe_fallback(req);
8561 * Batched submission is done, ensure local IO is flushed out.
8563 static void io_submit_state_end(struct io_ring_ctx *ctx)
8565 struct io_submit_state *state = &ctx->submit_state;
8567 if (unlikely(state->link.head))
8568 io_queue_sqe_fallback(state->link.head);
8569 /* flush only after queuing links as they can generate completions */
8570 io_submit_flush_completions(ctx);
8571 if (state->plug_started)
8572 blk_finish_plug(&state->plug);
8576 * Start submission side cache.
8578 static void io_submit_state_start(struct io_submit_state *state,
8579 unsigned int max_ios)
8581 state->plug_started = false;
8582 state->need_plug = max_ios > 2;
8583 state->submit_nr = max_ios;
8584 /* set only head, no need to init link_last in advance */
8585 state->link.head = NULL;
8588 static void io_commit_sqring(struct io_ring_ctx *ctx)
8590 struct io_rings *rings = ctx->rings;
8593 * Ensure any loads from the SQEs are done at this point,
8594 * since once we write the new head, the application could
8595 * write new data to them.
8597 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
8601 * Fetch an sqe, if one is available. Note this returns a pointer to memory
8602 * that is mapped by userspace. This means that care needs to be taken to
8603 * ensure that reads are stable, as we cannot rely on userspace always
8604 * being a good citizen. If members of the sqe are validated and then later
8605 * used, it's important that those reads are done through READ_ONCE() to
8606 * prevent a re-load down the line.
8608 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
8610 unsigned head, mask = ctx->sq_entries - 1;
8611 unsigned sq_idx = ctx->cached_sq_head++ & mask;
8614 * The cached sq head (or cq tail) serves two purposes:
8616 * 1) allows us to batch the cost of updating the user visible
8618 * 2) allows the kernel side to track the head on its own, even
8619 * though the application is the one updating it.
8621 head = READ_ONCE(ctx->sq_array[sq_idx]);
8622 if (likely(head < ctx->sq_entries)) {
8623 /* double index for 128-byte SQEs, twice as long */
8624 if (ctx->flags & IORING_SETUP_SQE128)
8626 return &ctx->sq_sqes[head];
8629 /* drop invalid entries */
8631 WRITE_ONCE(ctx->rings->sq_dropped,
8632 READ_ONCE(ctx->rings->sq_dropped) + 1);
8636 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
8637 __must_hold(&ctx->uring_lock)
8639 unsigned int entries = io_sqring_entries(ctx);
8643 if (unlikely(!entries))
8645 /* make sure SQ entry isn't read before tail */
8646 ret = left = min3(nr, ctx->sq_entries, entries);
8647 io_get_task_refs(left);
8648 io_submit_state_start(&ctx->submit_state, left);
8651 const struct io_uring_sqe *sqe;
8652 struct io_kiocb *req;
8654 if (unlikely(!io_alloc_req_refill(ctx)))
8656 req = io_alloc_req(ctx);
8657 sqe = io_get_sqe(ctx);
8658 if (unlikely(!sqe)) {
8659 io_req_add_to_cache(req, ctx);
8664 * Continue submitting even for sqe failure if the
8665 * ring was setup with IORING_SETUP_SUBMIT_ALL
8667 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
8668 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
8674 if (unlikely(left)) {
8676 /* try again if it submitted nothing and can't allocate a req */
8677 if (!ret && io_req_cache_empty(ctx))
8679 current->io_uring->cached_refs += left;
8682 io_submit_state_end(ctx);
8683 /* Commit SQ ring head once we've consumed and submitted all SQEs */
8684 io_commit_sqring(ctx);
8688 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
8690 return READ_ONCE(sqd->state);
8693 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
8695 unsigned int to_submit;
8698 to_submit = io_sqring_entries(ctx);
8699 /* if we're handling multiple rings, cap submit size for fairness */
8700 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
8701 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
8703 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
8704 const struct cred *creds = NULL;
8706 if (ctx->sq_creds != current_cred())
8707 creds = override_creds(ctx->sq_creds);
8709 mutex_lock(&ctx->uring_lock);
8710 if (!wq_list_empty(&ctx->iopoll_list))
8711 io_do_iopoll(ctx, true);
8714 * Don't submit if refs are dying, good for io_uring_register(),
8715 * but also it is relied upon by io_ring_exit_work()
8717 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
8718 !(ctx->flags & IORING_SETUP_R_DISABLED))
8719 ret = io_submit_sqes(ctx, to_submit);
8720 mutex_unlock(&ctx->uring_lock);
8722 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8723 wake_up(&ctx->sqo_sq_wait);
8725 revert_creds(creds);
8731 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8733 struct io_ring_ctx *ctx;
8734 unsigned sq_thread_idle = 0;
8736 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8737 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8738 sqd->sq_thread_idle = sq_thread_idle;
8741 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8743 bool did_sig = false;
8744 struct ksignal ksig;
8746 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8747 signal_pending(current)) {
8748 mutex_unlock(&sqd->lock);
8749 if (signal_pending(current))
8750 did_sig = get_signal(&ksig);
8752 mutex_lock(&sqd->lock);
8754 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8757 static int io_sq_thread(void *data)
8759 struct io_sq_data *sqd = data;
8760 struct io_ring_ctx *ctx;
8761 unsigned long timeout = 0;
8762 char buf[TASK_COMM_LEN];
8765 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8766 set_task_comm(current, buf);
8768 if (sqd->sq_cpu != -1)
8769 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8771 set_cpus_allowed_ptr(current, cpu_online_mask);
8772 current->flags |= PF_NO_SETAFFINITY;
8774 audit_alloc_kernel(current);
8776 mutex_lock(&sqd->lock);
8778 bool cap_entries, sqt_spin = false;
8780 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8781 if (io_sqd_handle_event(sqd))
8783 timeout = jiffies + sqd->sq_thread_idle;
8786 cap_entries = !list_is_singular(&sqd->ctx_list);
8787 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8788 int ret = __io_sq_thread(ctx, cap_entries);
8790 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8793 if (io_run_task_work())
8796 if (sqt_spin || !time_after(jiffies, timeout)) {
8799 timeout = jiffies + sqd->sq_thread_idle;
8803 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8804 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8805 bool needs_sched = true;
8807 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8808 atomic_or(IORING_SQ_NEED_WAKEUP,
8809 &ctx->rings->sq_flags);
8810 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8811 !wq_list_empty(&ctx->iopoll_list)) {
8812 needs_sched = false;
8817 * Ensure the store of the wakeup flag is not
8818 * reordered with the load of the SQ tail
8820 smp_mb__after_atomic();
8822 if (io_sqring_entries(ctx)) {
8823 needs_sched = false;
8829 mutex_unlock(&sqd->lock);
8831 mutex_lock(&sqd->lock);
8833 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8834 atomic_andnot(IORING_SQ_NEED_WAKEUP,
8835 &ctx->rings->sq_flags);
8838 finish_wait(&sqd->wait, &wait);
8839 timeout = jiffies + sqd->sq_thread_idle;
8842 io_uring_cancel_generic(true, sqd);
8844 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8845 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
8847 mutex_unlock(&sqd->lock);
8849 audit_free(current);
8851 complete(&sqd->exited);
8855 struct io_wait_queue {
8856 struct wait_queue_entry wq;
8857 struct io_ring_ctx *ctx;
8859 unsigned nr_timeouts;
8862 static inline bool io_should_wake(struct io_wait_queue *iowq)
8864 struct io_ring_ctx *ctx = iowq->ctx;
8865 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8868 * Wake up if we have enough events, or if a timeout occurred since we
8869 * started waiting. For timeouts, we always want to return to userspace,
8870 * regardless of event count.
8872 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8875 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8876 int wake_flags, void *key)
8878 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8882 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8883 * the task, and the next invocation will do it.
8885 if (io_should_wake(iowq) ||
8886 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
8887 return autoremove_wake_function(curr, mode, wake_flags, key);
8891 static int io_run_task_work_sig(void)
8893 if (io_run_task_work())
8895 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8896 return -ERESTARTSYS;
8897 if (task_sigpending(current))
8902 /* when returns >0, the caller should retry */
8903 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8904 struct io_wait_queue *iowq,
8908 unsigned long check_cq;
8910 /* make sure we run task_work before checking for signals */
8911 ret = io_run_task_work_sig();
8912 if (ret || io_should_wake(iowq))
8914 check_cq = READ_ONCE(ctx->check_cq);
8915 /* let the caller flush overflows, retry */
8916 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
8918 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
8920 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8926 * Wait until events become available, if we don't already have some. The
8927 * application must reap them itself, as they reside on the shared cq ring.
8929 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8930 const sigset_t __user *sig, size_t sigsz,
8931 struct __kernel_timespec __user *uts)
8933 struct io_wait_queue iowq;
8934 struct io_rings *rings = ctx->rings;
8935 ktime_t timeout = KTIME_MAX;
8939 io_cqring_overflow_flush(ctx);
8940 if (io_cqring_events(ctx) >= min_events)
8942 if (!io_run_task_work())
8947 #ifdef CONFIG_COMPAT
8948 if (in_compat_syscall())
8949 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8953 ret = set_user_sigmask(sig, sigsz);
8960 struct timespec64 ts;
8962 if (get_timespec64(&ts, uts))
8964 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8967 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8968 iowq.wq.private = current;
8969 INIT_LIST_HEAD(&iowq.wq.entry);
8971 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8972 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8974 trace_io_uring_cqring_wait(ctx, min_events);
8976 /* if we can't even flush overflow, don't wait for more */
8977 if (!io_cqring_overflow_flush(ctx)) {
8981 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8982 TASK_INTERRUPTIBLE);
8983 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8987 finish_wait(&ctx->cq_wait, &iowq.wq);
8988 restore_saved_sigmask_unless(ret == -EINTR);
8990 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8993 static void io_free_page_table(void **table, size_t size)
8995 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8997 for (i = 0; i < nr_tables; i++)
9002 static __cold void **io_alloc_page_table(size_t size)
9004 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9005 size_t init_size = size;
9008 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9012 for (i = 0; i < nr_tables; i++) {
9013 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9015 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9017 io_free_page_table(table, init_size);
9025 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9027 percpu_ref_exit(&ref_node->refs);
9031 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9033 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9034 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9035 unsigned long flags;
9036 bool first_add = false;
9037 unsigned long delay = HZ;
9039 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9042 /* if we are mid-quiesce then do not delay */
9043 if (node->rsrc_data->quiesce)
9046 while (!list_empty(&ctx->rsrc_ref_list)) {
9047 node = list_first_entry(&ctx->rsrc_ref_list,
9048 struct io_rsrc_node, node);
9049 /* recycle ref nodes in order */
9052 list_del(&node->node);
9053 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9055 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9058 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9061 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9063 struct io_rsrc_node *ref_node;
9065 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9069 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9074 INIT_LIST_HEAD(&ref_node->node);
9075 INIT_LIST_HEAD(&ref_node->rsrc_list);
9076 ref_node->done = false;
9080 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9081 struct io_rsrc_data *data_to_kill)
9082 __must_hold(&ctx->uring_lock)
9084 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9085 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9087 io_rsrc_refs_drop(ctx);
9090 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9092 rsrc_node->rsrc_data = data_to_kill;
9093 spin_lock_irq(&ctx->rsrc_ref_lock);
9094 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9095 spin_unlock_irq(&ctx->rsrc_ref_lock);
9097 atomic_inc(&data_to_kill->refs);
9098 percpu_ref_kill(&rsrc_node->refs);
9099 ctx->rsrc_node = NULL;
9102 if (!ctx->rsrc_node) {
9103 ctx->rsrc_node = ctx->rsrc_backup_node;
9104 ctx->rsrc_backup_node = NULL;
9108 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9110 if (ctx->rsrc_backup_node)
9112 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9113 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9116 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9117 struct io_ring_ctx *ctx)
9121 /* As we may drop ->uring_lock, other task may have started quiesce */
9125 data->quiesce = true;
9127 ret = io_rsrc_node_switch_start(ctx);
9130 io_rsrc_node_switch(ctx, data);
9132 /* kill initial ref, already quiesced if zero */
9133 if (atomic_dec_and_test(&data->refs))
9135 mutex_unlock(&ctx->uring_lock);
9136 flush_delayed_work(&ctx->rsrc_put_work);
9137 ret = wait_for_completion_interruptible(&data->done);
9139 mutex_lock(&ctx->uring_lock);
9140 if (atomic_read(&data->refs) > 0) {
9142 * it has been revived by another thread while
9145 mutex_unlock(&ctx->uring_lock);
9151 atomic_inc(&data->refs);
9152 /* wait for all works potentially completing data->done */
9153 flush_delayed_work(&ctx->rsrc_put_work);
9154 reinit_completion(&data->done);
9156 ret = io_run_task_work_sig();
9157 mutex_lock(&ctx->uring_lock);
9159 data->quiesce = false;
9164 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9166 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9167 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9169 return &data->tags[table_idx][off];
9172 static void io_rsrc_data_free(struct io_rsrc_data *data)
9174 size_t size = data->nr * sizeof(data->tags[0][0]);
9177 io_free_page_table((void **)data->tags, size);
9181 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9182 u64 __user *utags, unsigned nr,
9183 struct io_rsrc_data **pdata)
9185 struct io_rsrc_data *data;
9189 data = kzalloc(sizeof(*data), GFP_KERNEL);
9192 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9200 data->do_put = do_put;
9203 for (i = 0; i < nr; i++) {
9204 u64 *tag_slot = io_get_tag_slot(data, i);
9206 if (copy_from_user(tag_slot, &utags[i],
9212 atomic_set(&data->refs, 1);
9213 init_completion(&data->done);
9217 io_rsrc_data_free(data);
9221 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9223 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9224 GFP_KERNEL_ACCOUNT);
9225 if (unlikely(!table->files))
9228 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9229 if (unlikely(!table->bitmap)) {
9230 kvfree(table->files);
9237 static void io_free_file_tables(struct io_file_table *table)
9239 kvfree(table->files);
9240 bitmap_free(table->bitmap);
9241 table->files = NULL;
9242 table->bitmap = NULL;
9245 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9247 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9248 __set_bit(bit, table->bitmap);
9249 table->alloc_hint = bit + 1;
9252 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9254 __clear_bit(bit, table->bitmap);
9255 table->alloc_hint = bit;
9258 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9260 #if !defined(IO_URING_SCM_ALL)
9263 for (i = 0; i < ctx->nr_user_files; i++) {
9264 struct file *file = io_file_from_index(ctx, i);
9268 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9270 io_file_bitmap_clear(&ctx->file_table, i);
9275 #if defined(CONFIG_UNIX)
9276 if (ctx->ring_sock) {
9277 struct sock *sock = ctx->ring_sock->sk;
9278 struct sk_buff *skb;
9280 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9284 io_free_file_tables(&ctx->file_table);
9285 io_rsrc_data_free(ctx->file_data);
9286 ctx->file_data = NULL;
9287 ctx->nr_user_files = 0;
9290 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9292 unsigned nr = ctx->nr_user_files;
9295 if (!ctx->file_data)
9299 * Quiesce may unlock ->uring_lock, and while it's not held
9300 * prevent new requests using the table.
9302 ctx->nr_user_files = 0;
9303 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9304 ctx->nr_user_files = nr;
9306 __io_sqe_files_unregister(ctx);
9310 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9311 __releases(&sqd->lock)
9313 WARN_ON_ONCE(sqd->thread == current);
9316 * Do the dance but not conditional clear_bit() because it'd race with
9317 * other threads incrementing park_pending and setting the bit.
9319 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9320 if (atomic_dec_return(&sqd->park_pending))
9321 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9322 mutex_unlock(&sqd->lock);
9325 static void io_sq_thread_park(struct io_sq_data *sqd)
9326 __acquires(&sqd->lock)
9328 WARN_ON_ONCE(sqd->thread == current);
9330 atomic_inc(&sqd->park_pending);
9331 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9332 mutex_lock(&sqd->lock);
9334 wake_up_process(sqd->thread);
9337 static void io_sq_thread_stop(struct io_sq_data *sqd)
9339 WARN_ON_ONCE(sqd->thread == current);
9340 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9342 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9343 mutex_lock(&sqd->lock);
9345 wake_up_process(sqd->thread);
9346 mutex_unlock(&sqd->lock);
9347 wait_for_completion(&sqd->exited);
9350 static void io_put_sq_data(struct io_sq_data *sqd)
9352 if (refcount_dec_and_test(&sqd->refs)) {
9353 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9355 io_sq_thread_stop(sqd);
9360 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9362 struct io_sq_data *sqd = ctx->sq_data;
9365 io_sq_thread_park(sqd);
9366 list_del_init(&ctx->sqd_list);
9367 io_sqd_update_thread_idle(sqd);
9368 io_sq_thread_unpark(sqd);
9370 io_put_sq_data(sqd);
9371 ctx->sq_data = NULL;
9375 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9377 struct io_ring_ctx *ctx_attach;
9378 struct io_sq_data *sqd;
9381 f = fdget(p->wq_fd);
9383 return ERR_PTR(-ENXIO);
9384 if (f.file->f_op != &io_uring_fops) {
9386 return ERR_PTR(-EINVAL);
9389 ctx_attach = f.file->private_data;
9390 sqd = ctx_attach->sq_data;
9393 return ERR_PTR(-EINVAL);
9395 if (sqd->task_tgid != current->tgid) {
9397 return ERR_PTR(-EPERM);
9400 refcount_inc(&sqd->refs);
9405 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9408 struct io_sq_data *sqd;
9411 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9412 sqd = io_attach_sq_data(p);
9417 /* fall through for EPERM case, setup new sqd/task */
9418 if (PTR_ERR(sqd) != -EPERM)
9422 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9424 return ERR_PTR(-ENOMEM);
9426 atomic_set(&sqd->park_pending, 0);
9427 refcount_set(&sqd->refs, 1);
9428 INIT_LIST_HEAD(&sqd->ctx_list);
9429 mutex_init(&sqd->lock);
9430 init_waitqueue_head(&sqd->wait);
9431 init_completion(&sqd->exited);
9436 * Ensure the UNIX gc is aware of our file set, so we are certain that
9437 * the io_uring can be safely unregistered on process exit, even if we have
9438 * loops in the file referencing. We account only files that can hold other
9439 * files because otherwise they can't form a loop and so are not interesting
9442 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9444 #if defined(CONFIG_UNIX)
9445 struct sock *sk = ctx->ring_sock->sk;
9446 struct sk_buff_head *head = &sk->sk_receive_queue;
9447 struct scm_fp_list *fpl;
9448 struct sk_buff *skb;
9450 if (likely(!io_file_need_scm(file)))
9454 * See if we can merge this file into an existing skb SCM_RIGHTS
9455 * file set. If there's no room, fall back to allocating a new skb
9456 * and filling it in.
9458 spin_lock_irq(&head->lock);
9459 skb = skb_peek(head);
9460 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9461 __skb_unlink(skb, head);
9464 spin_unlock_irq(&head->lock);
9467 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9471 skb = alloc_skb(0, GFP_KERNEL);
9477 fpl->user = get_uid(current_user());
9478 fpl->max = SCM_MAX_FD;
9481 UNIXCB(skb).fp = fpl;
9483 skb->destructor = unix_destruct_scm;
9484 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9487 fpl = UNIXCB(skb).fp;
9488 fpl->fp[fpl->count++] = get_file(file);
9489 unix_inflight(fpl->user, file);
9490 skb_queue_head(head, skb);
9496 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9498 struct file *file = prsrc->file;
9499 #if defined(CONFIG_UNIX)
9500 struct sock *sock = ctx->ring_sock->sk;
9501 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9502 struct sk_buff *skb;
9505 if (!io_file_need_scm(file)) {
9510 __skb_queue_head_init(&list);
9513 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9514 * remove this entry and rearrange the file array.
9516 skb = skb_dequeue(head);
9518 struct scm_fp_list *fp;
9520 fp = UNIXCB(skb).fp;
9521 for (i = 0; i < fp->count; i++) {
9524 if (fp->fp[i] != file)
9527 unix_notinflight(fp->user, fp->fp[i]);
9528 left = fp->count - 1 - i;
9530 memmove(&fp->fp[i], &fp->fp[i + 1],
9531 left * sizeof(struct file *));
9538 __skb_queue_tail(&list, skb);
9548 __skb_queue_tail(&list, skb);
9550 skb = skb_dequeue(head);
9553 if (skb_peek(&list)) {
9554 spin_lock_irq(&head->lock);
9555 while ((skb = __skb_dequeue(&list)) != NULL)
9556 __skb_queue_tail(head, skb);
9557 spin_unlock_irq(&head->lock);
9564 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9566 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9567 struct io_ring_ctx *ctx = rsrc_data->ctx;
9568 struct io_rsrc_put *prsrc, *tmp;
9570 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9571 list_del(&prsrc->list);
9574 if (ctx->flags & IORING_SETUP_IOPOLL)
9575 mutex_lock(&ctx->uring_lock);
9577 spin_lock(&ctx->completion_lock);
9578 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9579 io_commit_cqring(ctx);
9580 spin_unlock(&ctx->completion_lock);
9581 io_cqring_ev_posted(ctx);
9583 if (ctx->flags & IORING_SETUP_IOPOLL)
9584 mutex_unlock(&ctx->uring_lock);
9587 rsrc_data->do_put(ctx, prsrc);
9591 io_rsrc_node_destroy(ref_node);
9592 if (atomic_dec_and_test(&rsrc_data->refs))
9593 complete(&rsrc_data->done);
9596 static void io_rsrc_put_work(struct work_struct *work)
9598 struct io_ring_ctx *ctx;
9599 struct llist_node *node;
9601 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
9602 node = llist_del_all(&ctx->rsrc_put_llist);
9605 struct io_rsrc_node *ref_node;
9606 struct llist_node *next = node->next;
9608 ref_node = llist_entry(node, struct io_rsrc_node, llist);
9609 __io_rsrc_put_work(ref_node);
9614 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
9615 unsigned nr_args, u64 __user *tags)
9617 __s32 __user *fds = (__s32 __user *) arg;
9626 if (nr_args > IORING_MAX_FIXED_FILES)
9628 if (nr_args > rlimit(RLIMIT_NOFILE))
9630 ret = io_rsrc_node_switch_start(ctx);
9633 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9638 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
9639 io_rsrc_data_free(ctx->file_data);
9640 ctx->file_data = NULL;
9644 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9645 struct io_fixed_file *file_slot;
9647 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
9651 /* allow sparse sets */
9652 if (!fds || fd == -1) {
9654 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9661 if (unlikely(!file))
9665 * Don't allow io_uring instances to be registered. If UNIX
9666 * isn't enabled, then this causes a reference cycle and this
9667 * instance can never get freed. If UNIX is enabled we'll
9668 * handle it just fine, but there's still no point in allowing
9669 * a ring fd as it doesn't support regular read/write anyway.
9671 if (file->f_op == &io_uring_fops) {
9675 ret = io_scm_file_account(ctx, file);
9680 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9681 io_fixed_file_set(file_slot, file);
9682 io_file_bitmap_set(&ctx->file_table, i);
9685 io_rsrc_node_switch(ctx, NULL);
9688 __io_sqe_files_unregister(ctx);
9692 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9693 struct io_rsrc_node *node, void *rsrc)
9695 u64 *tag_slot = io_get_tag_slot(data, idx);
9696 struct io_rsrc_put *prsrc;
9698 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9702 prsrc->tag = *tag_slot;
9705 list_add(&prsrc->list, &node->rsrc_list);
9709 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9710 unsigned int issue_flags, u32 slot_index)
9711 __must_hold(&req->ctx->uring_lock)
9713 struct io_ring_ctx *ctx = req->ctx;
9714 bool needs_switch = false;
9715 struct io_fixed_file *file_slot;
9718 if (file->f_op == &io_uring_fops)
9720 if (!ctx->file_data)
9722 if (slot_index >= ctx->nr_user_files)
9725 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9726 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9728 if (file_slot->file_ptr) {
9729 struct file *old_file;
9731 ret = io_rsrc_node_switch_start(ctx);
9735 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9736 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9737 ctx->rsrc_node, old_file);
9740 file_slot->file_ptr = 0;
9741 io_file_bitmap_clear(&ctx->file_table, slot_index);
9742 needs_switch = true;
9745 ret = io_scm_file_account(ctx, file);
9747 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9748 io_fixed_file_set(file_slot, file);
9749 io_file_bitmap_set(&ctx->file_table, slot_index);
9753 io_rsrc_node_switch(ctx, ctx->file_data);
9759 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
9760 unsigned int offset)
9762 struct io_ring_ctx *ctx = req->ctx;
9763 struct io_fixed_file *file_slot;
9767 io_ring_submit_lock(ctx, issue_flags);
9769 if (unlikely(!ctx->file_data))
9772 if (offset >= ctx->nr_user_files)
9774 ret = io_rsrc_node_switch_start(ctx);
9778 offset = array_index_nospec(offset, ctx->nr_user_files);
9779 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9781 if (!file_slot->file_ptr)
9784 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9785 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9789 file_slot->file_ptr = 0;
9790 io_file_bitmap_clear(&ctx->file_table, offset);
9791 io_rsrc_node_switch(ctx, ctx->file_data);
9794 io_ring_submit_unlock(ctx, issue_flags);
9798 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9800 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
9803 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9804 struct io_uring_rsrc_update2 *up,
9807 u64 __user *tags = u64_to_user_ptr(up->tags);
9808 __s32 __user *fds = u64_to_user_ptr(up->data);
9809 struct io_rsrc_data *data = ctx->file_data;
9810 struct io_fixed_file *file_slot;
9814 bool needs_switch = false;
9816 if (!ctx->file_data)
9818 if (up->offset + nr_args > ctx->nr_user_files)
9821 for (done = 0; done < nr_args; done++) {
9824 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9825 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9829 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9833 if (fd == IORING_REGISTER_FILES_SKIP)
9836 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9837 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9839 if (file_slot->file_ptr) {
9840 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9841 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9844 file_slot->file_ptr = 0;
9845 io_file_bitmap_clear(&ctx->file_table, i);
9846 needs_switch = true;
9855 * Don't allow io_uring instances to be registered. If
9856 * UNIX isn't enabled, then this causes a reference
9857 * cycle and this instance can never get freed. If UNIX
9858 * is enabled we'll handle it just fine, but there's
9859 * still no point in allowing a ring fd as it doesn't
9860 * support regular read/write anyway.
9862 if (file->f_op == &io_uring_fops) {
9867 err = io_scm_file_account(ctx, file);
9872 *io_get_tag_slot(data, i) = tag;
9873 io_fixed_file_set(file_slot, file);
9874 io_file_bitmap_set(&ctx->file_table, i);
9879 io_rsrc_node_switch(ctx, data);
9880 return done ? done : err;
9883 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9884 struct task_struct *task)
9886 struct io_wq_hash *hash;
9887 struct io_wq_data data;
9888 unsigned int concurrency;
9890 mutex_lock(&ctx->uring_lock);
9891 hash = ctx->hash_map;
9893 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9895 mutex_unlock(&ctx->uring_lock);
9896 return ERR_PTR(-ENOMEM);
9898 refcount_set(&hash->refs, 1);
9899 init_waitqueue_head(&hash->wait);
9900 ctx->hash_map = hash;
9902 mutex_unlock(&ctx->uring_lock);
9906 data.free_work = io_wq_free_work;
9907 data.do_work = io_wq_submit_work;
9909 /* Do QD, or 4 * CPUS, whatever is smallest */
9910 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9912 return io_wq_create(concurrency, &data);
9915 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9916 struct io_ring_ctx *ctx)
9918 struct io_uring_task *tctx;
9921 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9922 if (unlikely(!tctx))
9925 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9926 sizeof(struct file *), GFP_KERNEL);
9927 if (unlikely(!tctx->registered_rings)) {
9932 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9933 if (unlikely(ret)) {
9934 kfree(tctx->registered_rings);
9939 tctx->io_wq = io_init_wq_offload(ctx, task);
9940 if (IS_ERR(tctx->io_wq)) {
9941 ret = PTR_ERR(tctx->io_wq);
9942 percpu_counter_destroy(&tctx->inflight);
9943 kfree(tctx->registered_rings);
9949 init_waitqueue_head(&tctx->wait);
9950 atomic_set(&tctx->in_idle, 0);
9951 atomic_set(&tctx->inflight_tracked, 0);
9952 task->io_uring = tctx;
9953 spin_lock_init(&tctx->task_lock);
9954 INIT_WQ_LIST(&tctx->task_list);
9955 INIT_WQ_LIST(&tctx->prio_task_list);
9956 init_task_work(&tctx->task_work, tctx_task_work);
9960 void __io_uring_free(struct task_struct *tsk)
9962 struct io_uring_task *tctx = tsk->io_uring;
9964 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9965 WARN_ON_ONCE(tctx->io_wq);
9966 WARN_ON_ONCE(tctx->cached_refs);
9968 kfree(tctx->registered_rings);
9969 percpu_counter_destroy(&tctx->inflight);
9971 tsk->io_uring = NULL;
9974 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9975 struct io_uring_params *p)
9979 /* Retain compatibility with failing for an invalid attach attempt */
9980 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9981 IORING_SETUP_ATTACH_WQ) {
9984 f = fdget(p->wq_fd);
9987 if (f.file->f_op != &io_uring_fops) {
9993 if (ctx->flags & IORING_SETUP_SQPOLL) {
9994 struct task_struct *tsk;
9995 struct io_sq_data *sqd;
9998 ret = security_uring_sqpoll();
10002 sqd = io_get_sq_data(p, &attached);
10004 ret = PTR_ERR(sqd);
10008 ctx->sq_creds = get_current_cred();
10009 ctx->sq_data = sqd;
10010 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10011 if (!ctx->sq_thread_idle)
10012 ctx->sq_thread_idle = HZ;
10014 io_sq_thread_park(sqd);
10015 list_add(&ctx->sqd_list, &sqd->ctx_list);
10016 io_sqd_update_thread_idle(sqd);
10017 /* don't attach to a dying SQPOLL thread, would be racy */
10018 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10019 io_sq_thread_unpark(sqd);
10026 if (p->flags & IORING_SETUP_SQ_AFF) {
10027 int cpu = p->sq_thread_cpu;
10030 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10037 sqd->task_pid = current->pid;
10038 sqd->task_tgid = current->tgid;
10039 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10041 ret = PTR_ERR(tsk);
10046 ret = io_uring_alloc_task_context(tsk, ctx);
10047 wake_up_new_task(tsk);
10050 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10051 /* Can't have SQ_AFF without SQPOLL */
10058 complete(&ctx->sq_data->exited);
10060 io_sq_thread_finish(ctx);
10064 static inline void __io_unaccount_mem(struct user_struct *user,
10065 unsigned long nr_pages)
10067 atomic_long_sub(nr_pages, &user->locked_vm);
10070 static inline int __io_account_mem(struct user_struct *user,
10071 unsigned long nr_pages)
10073 unsigned long page_limit, cur_pages, new_pages;
10075 /* Don't allow more pages than we can safely lock */
10076 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10079 cur_pages = atomic_long_read(&user->locked_vm);
10080 new_pages = cur_pages + nr_pages;
10081 if (new_pages > page_limit)
10083 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10084 new_pages) != cur_pages);
10089 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10092 __io_unaccount_mem(ctx->user, nr_pages);
10094 if (ctx->mm_account)
10095 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10098 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10103 ret = __io_account_mem(ctx->user, nr_pages);
10108 if (ctx->mm_account)
10109 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10114 static void io_mem_free(void *ptr)
10121 page = virt_to_head_page(ptr);
10122 if (put_page_testzero(page))
10123 free_compound_page(page);
10126 static void *io_mem_alloc(size_t size)
10128 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10130 return (void *) __get_free_pages(gfp, get_order(size));
10133 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10134 unsigned int cq_entries, size_t *sq_offset)
10136 struct io_rings *rings;
10137 size_t off, sq_array_size;
10139 off = struct_size(rings, cqes, cq_entries);
10140 if (off == SIZE_MAX)
10142 if (ctx->flags & IORING_SETUP_CQE32) {
10143 if (check_shl_overflow(off, 1, &off))
10148 off = ALIGN(off, SMP_CACHE_BYTES);
10156 sq_array_size = array_size(sizeof(u32), sq_entries);
10157 if (sq_array_size == SIZE_MAX)
10160 if (check_add_overflow(off, sq_array_size, &off))
10166 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10168 struct io_mapped_ubuf *imu = *slot;
10171 if (imu != ctx->dummy_ubuf) {
10172 for (i = 0; i < imu->nr_bvecs; i++)
10173 unpin_user_page(imu->bvec[i].bv_page);
10174 if (imu->acct_pages)
10175 io_unaccount_mem(ctx, imu->acct_pages);
10181 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10183 io_buffer_unmap(ctx, &prsrc->buf);
10187 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10191 for (i = 0; i < ctx->nr_user_bufs; i++)
10192 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10193 kfree(ctx->user_bufs);
10194 io_rsrc_data_free(ctx->buf_data);
10195 ctx->user_bufs = NULL;
10196 ctx->buf_data = NULL;
10197 ctx->nr_user_bufs = 0;
10200 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10202 unsigned nr = ctx->nr_user_bufs;
10205 if (!ctx->buf_data)
10209 * Quiesce may unlock ->uring_lock, and while it's not held
10210 * prevent new requests using the table.
10212 ctx->nr_user_bufs = 0;
10213 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10214 ctx->nr_user_bufs = nr;
10216 __io_sqe_buffers_unregister(ctx);
10220 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10221 void __user *arg, unsigned index)
10223 struct iovec __user *src;
10225 #ifdef CONFIG_COMPAT
10227 struct compat_iovec __user *ciovs;
10228 struct compat_iovec ciov;
10230 ciovs = (struct compat_iovec __user *) arg;
10231 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10234 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10235 dst->iov_len = ciov.iov_len;
10239 src = (struct iovec __user *) arg;
10240 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10246 * Not super efficient, but this is just a registration time. And we do cache
10247 * the last compound head, so generally we'll only do a full search if we don't
10250 * We check if the given compound head page has already been accounted, to
10251 * avoid double accounting it. This allows us to account the full size of the
10252 * page, not just the constituent pages of a huge page.
10254 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10255 int nr_pages, struct page *hpage)
10259 /* check current page array */
10260 for (i = 0; i < nr_pages; i++) {
10261 if (!PageCompound(pages[i]))
10263 if (compound_head(pages[i]) == hpage)
10267 /* check previously registered pages */
10268 for (i = 0; i < ctx->nr_user_bufs; i++) {
10269 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10271 for (j = 0; j < imu->nr_bvecs; j++) {
10272 if (!PageCompound(imu->bvec[j].bv_page))
10274 if (compound_head(imu->bvec[j].bv_page) == hpage)
10282 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10283 int nr_pages, struct io_mapped_ubuf *imu,
10284 struct page **last_hpage)
10288 imu->acct_pages = 0;
10289 for (i = 0; i < nr_pages; i++) {
10290 if (!PageCompound(pages[i])) {
10293 struct page *hpage;
10295 hpage = compound_head(pages[i]);
10296 if (hpage == *last_hpage)
10298 *last_hpage = hpage;
10299 if (headpage_already_acct(ctx, pages, i, hpage))
10301 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10305 if (!imu->acct_pages)
10308 ret = io_account_mem(ctx, imu->acct_pages);
10310 imu->acct_pages = 0;
10314 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10317 unsigned long start, end, nr_pages;
10318 struct vm_area_struct **vmas = NULL;
10319 struct page **pages = NULL;
10320 int i, pret, ret = -ENOMEM;
10322 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10323 start = ubuf >> PAGE_SHIFT;
10324 nr_pages = end - start;
10326 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10330 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10336 mmap_read_lock(current->mm);
10337 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10339 if (pret == nr_pages) {
10340 /* don't support file backed memory */
10341 for (i = 0; i < nr_pages; i++) {
10342 struct vm_area_struct *vma = vmas[i];
10344 if (vma_is_shmem(vma))
10346 if (vma->vm_file &&
10347 !is_file_hugepages(vma->vm_file)) {
10352 *npages = nr_pages;
10354 ret = pret < 0 ? pret : -EFAULT;
10356 mmap_read_unlock(current->mm);
10359 * if we did partial map, or found file backed vmas,
10360 * release any pages we did get
10363 unpin_user_pages(pages, pret);
10371 pages = ERR_PTR(ret);
10376 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10377 struct io_mapped_ubuf **pimu,
10378 struct page **last_hpage)
10380 struct io_mapped_ubuf *imu = NULL;
10381 struct page **pages = NULL;
10384 int ret, nr_pages, i;
10386 if (!iov->iov_base) {
10387 *pimu = ctx->dummy_ubuf;
10394 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10396 if (IS_ERR(pages)) {
10397 ret = PTR_ERR(pages);
10402 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10406 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10408 unpin_user_pages(pages, nr_pages);
10412 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10413 size = iov->iov_len;
10414 for (i = 0; i < nr_pages; i++) {
10417 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10418 imu->bvec[i].bv_page = pages[i];
10419 imu->bvec[i].bv_len = vec_len;
10420 imu->bvec[i].bv_offset = off;
10424 /* store original address for later verification */
10425 imu->ubuf = (unsigned long) iov->iov_base;
10426 imu->ubuf_end = imu->ubuf + iov->iov_len;
10427 imu->nr_bvecs = nr_pages;
10437 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10439 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10440 return ctx->user_bufs ? 0 : -ENOMEM;
10443 static int io_buffer_validate(struct iovec *iov)
10445 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10448 * Don't impose further limits on the size and buffer
10449 * constraints here, we'll -EINVAL later when IO is
10450 * submitted if they are wrong.
10452 if (!iov->iov_base)
10453 return iov->iov_len ? -EFAULT : 0;
10457 /* arbitrary limit, but we need something */
10458 if (iov->iov_len > SZ_1G)
10461 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10467 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10468 unsigned int nr_args, u64 __user *tags)
10470 struct page *last_hpage = NULL;
10471 struct io_rsrc_data *data;
10475 if (ctx->user_bufs)
10477 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10479 ret = io_rsrc_node_switch_start(ctx);
10482 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10485 ret = io_buffers_map_alloc(ctx, nr_args);
10487 io_rsrc_data_free(data);
10491 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10493 ret = io_copy_iov(ctx, &iov, arg, i);
10496 ret = io_buffer_validate(&iov);
10500 memset(&iov, 0, sizeof(iov));
10503 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10508 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10514 WARN_ON_ONCE(ctx->buf_data);
10516 ctx->buf_data = data;
10518 __io_sqe_buffers_unregister(ctx);
10520 io_rsrc_node_switch(ctx, NULL);
10524 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10525 struct io_uring_rsrc_update2 *up,
10526 unsigned int nr_args)
10528 u64 __user *tags = u64_to_user_ptr(up->tags);
10529 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10530 struct page *last_hpage = NULL;
10531 bool needs_switch = false;
10535 if (!ctx->buf_data)
10537 if (up->offset + nr_args > ctx->nr_user_bufs)
10540 for (done = 0; done < nr_args; done++) {
10541 struct io_mapped_ubuf *imu;
10542 int offset = up->offset + done;
10545 err = io_copy_iov(ctx, &iov, iovs, done);
10548 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10552 err = io_buffer_validate(&iov);
10555 if (!iov.iov_base && tag) {
10559 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10563 i = array_index_nospec(offset, ctx->nr_user_bufs);
10564 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10565 err = io_queue_rsrc_removal(ctx->buf_data, i,
10566 ctx->rsrc_node, ctx->user_bufs[i]);
10567 if (unlikely(err)) {
10568 io_buffer_unmap(ctx, &imu);
10571 ctx->user_bufs[i] = NULL;
10572 needs_switch = true;
10575 ctx->user_bufs[i] = imu;
10576 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10580 io_rsrc_node_switch(ctx, ctx->buf_data);
10581 return done ? done : err;
10584 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10585 unsigned int eventfd_async)
10587 struct io_ev_fd *ev_fd;
10588 __s32 __user *fds = arg;
10591 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10592 lockdep_is_held(&ctx->uring_lock));
10596 if (copy_from_user(&fd, fds, sizeof(*fds)))
10599 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10603 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10604 if (IS_ERR(ev_fd->cq_ev_fd)) {
10605 int ret = PTR_ERR(ev_fd->cq_ev_fd);
10609 ev_fd->eventfd_async = eventfd_async;
10610 ctx->has_evfd = true;
10611 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10615 static void io_eventfd_put(struct rcu_head *rcu)
10617 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10619 eventfd_ctx_put(ev_fd->cq_ev_fd);
10623 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10625 struct io_ev_fd *ev_fd;
10627 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10628 lockdep_is_held(&ctx->uring_lock));
10630 ctx->has_evfd = false;
10631 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10632 call_rcu(&ev_fd->rcu, io_eventfd_put);
10639 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10641 struct io_buffer_list *bl;
10642 unsigned long index;
10645 for (i = 0; i < BGID_ARRAY; i++) {
10648 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
10651 xa_for_each(&ctx->io_bl_xa, index, bl) {
10652 xa_erase(&ctx->io_bl_xa, bl->bgid);
10653 __io_remove_buffers(ctx, bl, -1U);
10657 while (!list_empty(&ctx->io_buffers_pages)) {
10660 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10661 list_del_init(&page->lru);
10666 static void io_req_caches_free(struct io_ring_ctx *ctx)
10668 struct io_submit_state *state = &ctx->submit_state;
10671 mutex_lock(&ctx->uring_lock);
10672 io_flush_cached_locked_reqs(ctx, state);
10674 while (!io_req_cache_empty(ctx)) {
10675 struct io_wq_work_node *node;
10676 struct io_kiocb *req;
10678 node = wq_stack_extract(&state->free_list);
10679 req = container_of(node, struct io_kiocb, comp_list);
10680 kmem_cache_free(req_cachep, req);
10684 percpu_ref_put_many(&ctx->refs, nr);
10685 mutex_unlock(&ctx->uring_lock);
10688 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10690 if (data && !atomic_dec_and_test(&data->refs))
10691 wait_for_completion(&data->done);
10694 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10696 struct async_poll *apoll;
10698 while (!list_empty(&ctx->apoll_cache)) {
10699 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10701 list_del(&apoll->poll.wait.entry);
10706 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10708 io_sq_thread_finish(ctx);
10710 if (ctx->mm_account) {
10711 mmdrop(ctx->mm_account);
10712 ctx->mm_account = NULL;
10715 io_rsrc_refs_drop(ctx);
10716 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10717 io_wait_rsrc_data(ctx->buf_data);
10718 io_wait_rsrc_data(ctx->file_data);
10720 mutex_lock(&ctx->uring_lock);
10722 __io_sqe_buffers_unregister(ctx);
10723 if (ctx->file_data)
10724 __io_sqe_files_unregister(ctx);
10726 __io_cqring_overflow_flush(ctx, true);
10727 io_eventfd_unregister(ctx);
10728 io_flush_apoll_cache(ctx);
10729 mutex_unlock(&ctx->uring_lock);
10730 io_destroy_buffers(ctx);
10732 put_cred(ctx->sq_creds);
10734 /* there are no registered resources left, nobody uses it */
10735 if (ctx->rsrc_node)
10736 io_rsrc_node_destroy(ctx->rsrc_node);
10737 if (ctx->rsrc_backup_node)
10738 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10739 flush_delayed_work(&ctx->rsrc_put_work);
10740 flush_delayed_work(&ctx->fallback_work);
10742 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10743 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10745 #if defined(CONFIG_UNIX)
10746 if (ctx->ring_sock) {
10747 ctx->ring_sock->file = NULL; /* so that iput() is called */
10748 sock_release(ctx->ring_sock);
10751 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10753 io_mem_free(ctx->rings);
10754 io_mem_free(ctx->sq_sqes);
10756 percpu_ref_exit(&ctx->refs);
10757 free_uid(ctx->user);
10758 io_req_caches_free(ctx);
10760 io_wq_put_hash(ctx->hash_map);
10761 kfree(ctx->cancel_hash);
10762 kfree(ctx->dummy_ubuf);
10764 xa_destroy(&ctx->io_bl_xa);
10768 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10770 struct io_ring_ctx *ctx = file->private_data;
10773 poll_wait(file, &ctx->cq_wait, wait);
10775 * synchronizes with barrier from wq_has_sleeper call in
10779 if (!io_sqring_full(ctx))
10780 mask |= EPOLLOUT | EPOLLWRNORM;
10783 * Don't flush cqring overflow list here, just do a simple check.
10784 * Otherwise there could possible be ABBA deadlock:
10787 * lock(&ctx->uring_lock);
10789 * lock(&ctx->uring_lock);
10792 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10793 * pushs them to do the flush.
10795 if (io_cqring_events(ctx) ||
10796 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
10797 mask |= EPOLLIN | EPOLLRDNORM;
10802 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10804 const struct cred *creds;
10806 creds = xa_erase(&ctx->personalities, id);
10815 struct io_tctx_exit {
10816 struct callback_head task_work;
10817 struct completion completion;
10818 struct io_ring_ctx *ctx;
10821 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10823 struct io_uring_task *tctx = current->io_uring;
10824 struct io_tctx_exit *work;
10826 work = container_of(cb, struct io_tctx_exit, task_work);
10828 * When @in_idle, we're in cancellation and it's racy to remove the
10829 * node. It'll be removed by the end of cancellation, just ignore it.
10831 if (!atomic_read(&tctx->in_idle))
10832 io_uring_del_tctx_node((unsigned long)work->ctx);
10833 complete(&work->completion);
10836 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10838 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10840 return req->ctx == data;
10843 static __cold void io_ring_exit_work(struct work_struct *work)
10845 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10846 unsigned long timeout = jiffies + HZ * 60 * 5;
10847 unsigned long interval = HZ / 20;
10848 struct io_tctx_exit exit;
10849 struct io_tctx_node *node;
10853 * If we're doing polled IO and end up having requests being
10854 * submitted async (out-of-line), then completions can come in while
10855 * we're waiting for refs to drop. We need to reap these manually,
10856 * as nobody else will be looking for them.
10859 io_uring_try_cancel_requests(ctx, NULL, true);
10860 if (ctx->sq_data) {
10861 struct io_sq_data *sqd = ctx->sq_data;
10862 struct task_struct *tsk;
10864 io_sq_thread_park(sqd);
10866 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10867 io_wq_cancel_cb(tsk->io_uring->io_wq,
10868 io_cancel_ctx_cb, ctx, true);
10869 io_sq_thread_unpark(sqd);
10872 io_req_caches_free(ctx);
10874 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10875 /* there is little hope left, don't run it too often */
10876 interval = HZ * 60;
10878 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10880 init_completion(&exit.completion);
10881 init_task_work(&exit.task_work, io_tctx_exit_cb);
10884 * Some may use context even when all refs and requests have been put,
10885 * and they are free to do so while still holding uring_lock or
10886 * completion_lock, see io_req_task_submit(). Apart from other work,
10887 * this lock/unlock section also waits them to finish.
10889 mutex_lock(&ctx->uring_lock);
10890 while (!list_empty(&ctx->tctx_list)) {
10891 WARN_ON_ONCE(time_after(jiffies, timeout));
10893 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10895 /* don't spin on a single task if cancellation failed */
10896 list_rotate_left(&ctx->tctx_list);
10897 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10898 if (WARN_ON_ONCE(ret))
10901 mutex_unlock(&ctx->uring_lock);
10902 wait_for_completion(&exit.completion);
10903 mutex_lock(&ctx->uring_lock);
10905 mutex_unlock(&ctx->uring_lock);
10906 spin_lock(&ctx->completion_lock);
10907 spin_unlock(&ctx->completion_lock);
10909 io_ring_ctx_free(ctx);
10912 /* Returns true if we found and killed one or more timeouts */
10913 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10914 struct task_struct *tsk, bool cancel_all)
10916 struct io_kiocb *req, *tmp;
10919 spin_lock(&ctx->completion_lock);
10920 spin_lock_irq(&ctx->timeout_lock);
10921 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10922 if (io_match_task(req, tsk, cancel_all)) {
10923 io_kill_timeout(req, -ECANCELED);
10927 spin_unlock_irq(&ctx->timeout_lock);
10928 io_commit_cqring(ctx);
10929 spin_unlock(&ctx->completion_lock);
10931 io_cqring_ev_posted(ctx);
10932 return canceled != 0;
10935 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10937 unsigned long index;
10938 struct creds *creds;
10940 mutex_lock(&ctx->uring_lock);
10941 percpu_ref_kill(&ctx->refs);
10943 __io_cqring_overflow_flush(ctx, true);
10944 xa_for_each(&ctx->personalities, index, creds)
10945 io_unregister_personality(ctx, index);
10946 mutex_unlock(&ctx->uring_lock);
10948 /* failed during ring init, it couldn't have issued any requests */
10950 io_kill_timeouts(ctx, NULL, true);
10951 io_poll_remove_all(ctx, NULL, true);
10952 /* if we failed setting up the ctx, we might not have any rings */
10953 io_iopoll_try_reap_events(ctx);
10954 /* drop cached put refs after potentially doing completions */
10955 if (current->io_uring)
10956 io_uring_drop_tctx_refs(current);
10959 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10961 * Use system_unbound_wq to avoid spawning tons of event kworkers
10962 * if we're exiting a ton of rings at the same time. It just adds
10963 * noise and overhead, there's no discernable change in runtime
10964 * over using system_wq.
10966 queue_work(system_unbound_wq, &ctx->exit_work);
10969 static int io_uring_release(struct inode *inode, struct file *file)
10971 struct io_ring_ctx *ctx = file->private_data;
10973 file->private_data = NULL;
10974 io_ring_ctx_wait_and_kill(ctx);
10978 struct io_task_cancel {
10979 struct task_struct *task;
10983 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10985 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10986 struct io_task_cancel *cancel = data;
10988 return io_match_task_safe(req, cancel->task, cancel->all);
10991 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10992 struct task_struct *task,
10995 struct io_defer_entry *de;
10998 spin_lock(&ctx->completion_lock);
10999 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11000 if (io_match_task_safe(de->req, task, cancel_all)) {
11001 list_cut_position(&list, &ctx->defer_list, &de->list);
11005 spin_unlock(&ctx->completion_lock);
11006 if (list_empty(&list))
11009 while (!list_empty(&list)) {
11010 de = list_first_entry(&list, struct io_defer_entry, list);
11011 list_del_init(&de->list);
11012 io_req_complete_failed(de->req, -ECANCELED);
11018 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11020 struct io_tctx_node *node;
11021 enum io_wq_cancel cret;
11024 mutex_lock(&ctx->uring_lock);
11025 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11026 struct io_uring_task *tctx = node->task->io_uring;
11029 * io_wq will stay alive while we hold uring_lock, because it's
11030 * killed after ctx nodes, which requires to take the lock.
11032 if (!tctx || !tctx->io_wq)
11034 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11035 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11037 mutex_unlock(&ctx->uring_lock);
11042 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11043 struct task_struct *task,
11046 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11047 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11049 /* failed during ring init, it couldn't have issued any requests */
11054 enum io_wq_cancel cret;
11058 ret |= io_uring_try_cancel_iowq(ctx);
11059 } else if (tctx && tctx->io_wq) {
11061 * Cancels requests of all rings, not only @ctx, but
11062 * it's fine as the task is in exit/exec.
11064 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11066 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11069 /* SQPOLL thread does its own polling */
11070 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11071 (ctx->sq_data && ctx->sq_data->thread == current)) {
11072 while (!wq_list_empty(&ctx->iopoll_list)) {
11073 io_iopoll_try_reap_events(ctx);
11078 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11079 ret |= io_poll_remove_all(ctx, task, cancel_all);
11080 ret |= io_kill_timeouts(ctx, task, cancel_all);
11082 ret |= io_run_task_work();
11089 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11091 struct io_uring_task *tctx = current->io_uring;
11092 struct io_tctx_node *node;
11095 if (unlikely(!tctx)) {
11096 ret = io_uring_alloc_task_context(current, ctx);
11100 tctx = current->io_uring;
11101 if (ctx->iowq_limits_set) {
11102 unsigned int limits[2] = { ctx->iowq_limits[0],
11103 ctx->iowq_limits[1], };
11105 ret = io_wq_max_workers(tctx->io_wq, limits);
11110 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11111 node = kmalloc(sizeof(*node), GFP_KERNEL);
11115 node->task = current;
11117 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11118 node, GFP_KERNEL));
11124 mutex_lock(&ctx->uring_lock);
11125 list_add(&node->ctx_node, &ctx->tctx_list);
11126 mutex_unlock(&ctx->uring_lock);
11133 * Note that this task has used io_uring. We use it for cancelation purposes.
11135 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11137 struct io_uring_task *tctx = current->io_uring;
11139 if (likely(tctx && tctx->last == ctx))
11141 return __io_uring_add_tctx_node(ctx);
11145 * Remove this io_uring_file -> task mapping.
11147 static __cold void io_uring_del_tctx_node(unsigned long index)
11149 struct io_uring_task *tctx = current->io_uring;
11150 struct io_tctx_node *node;
11154 node = xa_erase(&tctx->xa, index);
11158 WARN_ON_ONCE(current != node->task);
11159 WARN_ON_ONCE(list_empty(&node->ctx_node));
11161 mutex_lock(&node->ctx->uring_lock);
11162 list_del(&node->ctx_node);
11163 mutex_unlock(&node->ctx->uring_lock);
11165 if (tctx->last == node->ctx)
11170 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11172 struct io_wq *wq = tctx->io_wq;
11173 struct io_tctx_node *node;
11174 unsigned long index;
11176 xa_for_each(&tctx->xa, index, node) {
11177 io_uring_del_tctx_node(index);
11182 * Must be after io_uring_del_tctx_node() (removes nodes under
11183 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11185 io_wq_put_and_exit(wq);
11186 tctx->io_wq = NULL;
11190 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11193 return atomic_read(&tctx->inflight_tracked);
11194 return percpu_counter_sum(&tctx->inflight);
11198 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11199 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11201 static __cold void io_uring_cancel_generic(bool cancel_all,
11202 struct io_sq_data *sqd)
11204 struct io_uring_task *tctx = current->io_uring;
11205 struct io_ring_ctx *ctx;
11209 WARN_ON_ONCE(sqd && sqd->thread != current);
11211 if (!current->io_uring)
11214 io_wq_exit_start(tctx->io_wq);
11216 atomic_inc(&tctx->in_idle);
11218 io_uring_drop_tctx_refs(current);
11219 /* read completions before cancelations */
11220 inflight = tctx_inflight(tctx, !cancel_all);
11225 struct io_tctx_node *node;
11226 unsigned long index;
11228 xa_for_each(&tctx->xa, index, node) {
11229 /* sqpoll task will cancel all its requests */
11230 if (node->ctx->sq_data)
11232 io_uring_try_cancel_requests(node->ctx, current,
11236 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11237 io_uring_try_cancel_requests(ctx, current,
11241 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11242 io_run_task_work();
11243 io_uring_drop_tctx_refs(current);
11246 * If we've seen completions, retry without waiting. This
11247 * avoids a race where a completion comes in before we did
11248 * prepare_to_wait().
11250 if (inflight == tctx_inflight(tctx, !cancel_all))
11252 finish_wait(&tctx->wait, &wait);
11255 io_uring_clean_tctx(tctx);
11258 * We shouldn't run task_works after cancel, so just leave
11259 * ->in_idle set for normal exit.
11261 atomic_dec(&tctx->in_idle);
11262 /* for exec all current's requests should be gone, kill tctx */
11263 __io_uring_free(current);
11267 void __io_uring_cancel(bool cancel_all)
11269 io_uring_cancel_generic(cancel_all, NULL);
11272 void io_uring_unreg_ringfd(void)
11274 struct io_uring_task *tctx = current->io_uring;
11277 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11278 if (tctx->registered_rings[i]) {
11279 fput(tctx->registered_rings[i]);
11280 tctx->registered_rings[i] = NULL;
11285 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11286 int start, int end)
11291 for (offset = start; offset < end; offset++) {
11292 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11293 if (tctx->registered_rings[offset])
11299 } else if (file->f_op != &io_uring_fops) {
11301 return -EOPNOTSUPP;
11303 tctx->registered_rings[offset] = file;
11311 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11312 * invocation. User passes in an array of struct io_uring_rsrc_update
11313 * with ->data set to the ring_fd, and ->offset given for the desired
11314 * index. If no index is desired, application may set ->offset == -1U
11315 * and we'll find an available index. Returns number of entries
11316 * successfully processed, or < 0 on error if none were processed.
11318 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11321 struct io_uring_rsrc_update __user *arg = __arg;
11322 struct io_uring_rsrc_update reg;
11323 struct io_uring_task *tctx;
11326 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11329 mutex_unlock(&ctx->uring_lock);
11330 ret = io_uring_add_tctx_node(ctx);
11331 mutex_lock(&ctx->uring_lock);
11335 tctx = current->io_uring;
11336 for (i = 0; i < nr_args; i++) {
11339 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11349 if (reg.offset == -1U) {
11351 end = IO_RINGFD_REG_MAX;
11353 if (reg.offset >= IO_RINGFD_REG_MAX) {
11357 start = reg.offset;
11361 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11366 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11367 fput(tctx->registered_rings[reg.offset]);
11368 tctx->registered_rings[reg.offset] = NULL;
11374 return i ? i : ret;
11377 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11380 struct io_uring_rsrc_update __user *arg = __arg;
11381 struct io_uring_task *tctx = current->io_uring;
11382 struct io_uring_rsrc_update reg;
11385 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11390 for (i = 0; i < nr_args; i++) {
11391 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11395 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11400 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11401 if (tctx->registered_rings[reg.offset]) {
11402 fput(tctx->registered_rings[reg.offset]);
11403 tctx->registered_rings[reg.offset] = NULL;
11407 return i ? i : ret;
11410 static void *io_uring_validate_mmap_request(struct file *file,
11411 loff_t pgoff, size_t sz)
11413 struct io_ring_ctx *ctx = file->private_data;
11414 loff_t offset = pgoff << PAGE_SHIFT;
11419 case IORING_OFF_SQ_RING:
11420 case IORING_OFF_CQ_RING:
11423 case IORING_OFF_SQES:
11424 ptr = ctx->sq_sqes;
11427 return ERR_PTR(-EINVAL);
11430 page = virt_to_head_page(ptr);
11431 if (sz > page_size(page))
11432 return ERR_PTR(-EINVAL);
11439 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11441 size_t sz = vma->vm_end - vma->vm_start;
11445 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11447 return PTR_ERR(ptr);
11449 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11450 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11453 #else /* !CONFIG_MMU */
11455 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11457 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11460 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11462 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11465 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11466 unsigned long addr, unsigned long len,
11467 unsigned long pgoff, unsigned long flags)
11471 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11473 return PTR_ERR(ptr);
11475 return (unsigned long) ptr;
11478 #endif /* !CONFIG_MMU */
11480 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11485 if (!io_sqring_full(ctx))
11487 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11489 if (!io_sqring_full(ctx))
11492 } while (!signal_pending(current));
11494 finish_wait(&ctx->sqo_sq_wait, &wait);
11498 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11500 if (flags & IORING_ENTER_EXT_ARG) {
11501 struct io_uring_getevents_arg arg;
11503 if (argsz != sizeof(arg))
11505 if (copy_from_user(&arg, argp, sizeof(arg)))
11511 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11512 struct __kernel_timespec __user **ts,
11513 const sigset_t __user **sig)
11515 struct io_uring_getevents_arg arg;
11518 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11519 * is just a pointer to the sigset_t.
11521 if (!(flags & IORING_ENTER_EXT_ARG)) {
11522 *sig = (const sigset_t __user *) argp;
11528 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11529 * timespec and sigset_t pointers if good.
11531 if (*argsz != sizeof(arg))
11533 if (copy_from_user(&arg, argp, sizeof(arg)))
11537 *sig = u64_to_user_ptr(arg.sigmask);
11538 *argsz = arg.sigmask_sz;
11539 *ts = u64_to_user_ptr(arg.ts);
11543 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11544 u32, min_complete, u32, flags, const void __user *, argp,
11547 struct io_ring_ctx *ctx;
11551 io_run_task_work();
11553 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11554 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11555 IORING_ENTER_REGISTERED_RING)))
11559 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11560 * need only dereference our task private array to find it.
11562 if (flags & IORING_ENTER_REGISTERED_RING) {
11563 struct io_uring_task *tctx = current->io_uring;
11565 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11567 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11568 f.file = tctx->registered_rings[fd];
11574 if (unlikely(!f.file))
11578 if (unlikely(f.file->f_op != &io_uring_fops))
11582 ctx = f.file->private_data;
11583 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11587 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11591 * For SQ polling, the thread will do all submissions and completions.
11592 * Just return the requested submit count, and wake the thread if
11593 * we were asked to.
11596 if (ctx->flags & IORING_SETUP_SQPOLL) {
11597 io_cqring_overflow_flush(ctx);
11599 if (unlikely(ctx->sq_data->thread == NULL)) {
11603 if (flags & IORING_ENTER_SQ_WAKEUP)
11604 wake_up(&ctx->sq_data->wait);
11605 if (flags & IORING_ENTER_SQ_WAIT) {
11606 ret = io_sqpoll_wait_sq(ctx);
11611 } else if (to_submit) {
11612 ret = io_uring_add_tctx_node(ctx);
11616 mutex_lock(&ctx->uring_lock);
11617 ret = io_submit_sqes(ctx, to_submit);
11618 if (ret != to_submit) {
11619 mutex_unlock(&ctx->uring_lock);
11622 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
11623 goto iopoll_locked;
11624 mutex_unlock(&ctx->uring_lock);
11626 if (flags & IORING_ENTER_GETEVENTS) {
11628 if (ctx->syscall_iopoll) {
11630 * We disallow the app entering submit/complete with
11631 * polling, but we still need to lock the ring to
11632 * prevent racing with polled issue that got punted to
11635 mutex_lock(&ctx->uring_lock);
11637 ret2 = io_validate_ext_arg(flags, argp, argsz);
11638 if (likely(!ret2)) {
11639 min_complete = min(min_complete,
11641 ret2 = io_iopoll_check(ctx, min_complete);
11643 mutex_unlock(&ctx->uring_lock);
11645 const sigset_t __user *sig;
11646 struct __kernel_timespec __user *ts;
11648 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
11649 if (likely(!ret2)) {
11650 min_complete = min(min_complete,
11652 ret2 = io_cqring_wait(ctx, min_complete, sig,
11661 * EBADR indicates that one or more CQE were dropped.
11662 * Once the user has been informed we can clear the bit
11663 * as they are obviously ok with those drops.
11665 if (unlikely(ret2 == -EBADR))
11666 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
11672 percpu_ref_put(&ctx->refs);
11678 #ifdef CONFIG_PROC_FS
11679 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11680 const struct cred *cred)
11682 struct user_namespace *uns = seq_user_ns(m);
11683 struct group_info *gi;
11688 seq_printf(m, "%5d\n", id);
11689 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11690 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11691 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11692 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11693 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11694 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11695 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11696 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11697 seq_puts(m, "\n\tGroups:\t");
11698 gi = cred->group_info;
11699 for (g = 0; g < gi->ngroups; g++) {
11700 seq_put_decimal_ull(m, g ? " " : "",
11701 from_kgid_munged(uns, gi->gid[g]));
11703 seq_puts(m, "\n\tCapEff:\t");
11704 cap = cred->cap_effective;
11705 CAP_FOR_EACH_U32(__capi)
11706 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11711 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11712 struct seq_file *m)
11714 struct io_sq_data *sq = NULL;
11715 struct io_overflow_cqe *ocqe;
11716 struct io_rings *r = ctx->rings;
11717 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11718 unsigned int sq_head = READ_ONCE(r->sq.head);
11719 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11720 unsigned int cq_head = READ_ONCE(r->cq.head);
11721 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11722 unsigned int cq_shift = 0;
11723 unsigned int sq_entries, cq_entries;
11725 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
11732 * we may get imprecise sqe and cqe info if uring is actively running
11733 * since we get cached_sq_head and cached_cq_tail without uring_lock
11734 * and sq_tail and cq_head are changed by userspace. But it's ok since
11735 * we usually use these info when it is stuck.
11737 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11738 seq_printf(m, "SqHead:\t%u\n", sq_head);
11739 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11740 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11741 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11742 seq_printf(m, "CqHead:\t%u\n", cq_head);
11743 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11744 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11745 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11746 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11747 for (i = 0; i < sq_entries; i++) {
11748 unsigned int entry = i + sq_head;
11749 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11750 struct io_uring_sqe *sqe;
11752 if (sq_idx > sq_mask)
11754 sqe = &ctx->sq_sqes[sq_idx];
11755 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11756 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11759 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11760 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11761 for (i = 0; i < cq_entries; i++) {
11762 unsigned int entry = i + cq_head;
11763 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
11766 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11767 entry & cq_mask, cqe->user_data, cqe->res,
11770 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
11771 "extra1:%llu, extra2:%llu\n",
11772 entry & cq_mask, cqe->user_data, cqe->res,
11773 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
11778 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11779 * since fdinfo case grabs it in the opposite direction of normal use
11780 * cases. If we fail to get the lock, we just don't iterate any
11781 * structures that could be going away outside the io_uring mutex.
11783 has_lock = mutex_trylock(&ctx->uring_lock);
11785 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11791 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11792 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11793 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11794 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11795 struct file *f = io_file_from_index(ctx, i);
11798 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11800 seq_printf(m, "%5u: <none>\n", i);
11802 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11803 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11804 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11805 unsigned int len = buf->ubuf_end - buf->ubuf;
11807 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11809 if (has_lock && !xa_empty(&ctx->personalities)) {
11810 unsigned long index;
11811 const struct cred *cred;
11813 seq_printf(m, "Personalities:\n");
11814 xa_for_each(&ctx->personalities, index, cred)
11815 io_uring_show_cred(m, index, cred);
11818 mutex_unlock(&ctx->uring_lock);
11820 seq_puts(m, "PollList:\n");
11821 spin_lock(&ctx->completion_lock);
11822 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11823 struct hlist_head *list = &ctx->cancel_hash[i];
11824 struct io_kiocb *req;
11826 hlist_for_each_entry(req, list, hash_node)
11827 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11828 task_work_pending(req->task));
11831 seq_puts(m, "CqOverflowList:\n");
11832 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11833 struct io_uring_cqe *cqe = &ocqe->cqe;
11835 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11836 cqe->user_data, cqe->res, cqe->flags);
11840 spin_unlock(&ctx->completion_lock);
11843 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11845 struct io_ring_ctx *ctx = f->private_data;
11847 if (percpu_ref_tryget(&ctx->refs)) {
11848 __io_uring_show_fdinfo(ctx, m);
11849 percpu_ref_put(&ctx->refs);
11854 static const struct file_operations io_uring_fops = {
11855 .release = io_uring_release,
11856 .mmap = io_uring_mmap,
11858 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11859 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11861 .poll = io_uring_poll,
11862 #ifdef CONFIG_PROC_FS
11863 .show_fdinfo = io_uring_show_fdinfo,
11867 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11868 struct io_uring_params *p)
11870 struct io_rings *rings;
11871 size_t size, sq_array_offset;
11873 /* make sure these are sane, as we already accounted them */
11874 ctx->sq_entries = p->sq_entries;
11875 ctx->cq_entries = p->cq_entries;
11877 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
11878 if (size == SIZE_MAX)
11881 rings = io_mem_alloc(size);
11885 ctx->rings = rings;
11886 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11887 rings->sq_ring_mask = p->sq_entries - 1;
11888 rings->cq_ring_mask = p->cq_entries - 1;
11889 rings->sq_ring_entries = p->sq_entries;
11890 rings->cq_ring_entries = p->cq_entries;
11892 if (p->flags & IORING_SETUP_SQE128)
11893 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
11895 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11896 if (size == SIZE_MAX) {
11897 io_mem_free(ctx->rings);
11902 ctx->sq_sqes = io_mem_alloc(size);
11903 if (!ctx->sq_sqes) {
11904 io_mem_free(ctx->rings);
11912 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11916 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11920 ret = io_uring_add_tctx_node(ctx);
11925 fd_install(fd, file);
11930 * Allocate an anonymous fd, this is what constitutes the application
11931 * visible backing of an io_uring instance. The application mmaps this
11932 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11933 * we have to tie this fd to a socket for file garbage collection purposes.
11935 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11938 #if defined(CONFIG_UNIX)
11941 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11944 return ERR_PTR(ret);
11947 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11948 O_RDWR | O_CLOEXEC, NULL);
11949 #if defined(CONFIG_UNIX)
11950 if (IS_ERR(file)) {
11951 sock_release(ctx->ring_sock);
11952 ctx->ring_sock = NULL;
11954 ctx->ring_sock->file = file;
11960 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11961 struct io_uring_params __user *params)
11963 struct io_ring_ctx *ctx;
11969 if (entries > IORING_MAX_ENTRIES) {
11970 if (!(p->flags & IORING_SETUP_CLAMP))
11972 entries = IORING_MAX_ENTRIES;
11976 * Use twice as many entries for the CQ ring. It's possible for the
11977 * application to drive a higher depth than the size of the SQ ring,
11978 * since the sqes are only used at submission time. This allows for
11979 * some flexibility in overcommitting a bit. If the application has
11980 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11981 * of CQ ring entries manually.
11983 p->sq_entries = roundup_pow_of_two(entries);
11984 if (p->flags & IORING_SETUP_CQSIZE) {
11986 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11987 * to a power-of-two, if it isn't already. We do NOT impose
11988 * any cq vs sq ring sizing.
11990 if (!p->cq_entries)
11992 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11993 if (!(p->flags & IORING_SETUP_CLAMP))
11995 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11997 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11998 if (p->cq_entries < p->sq_entries)
12001 p->cq_entries = 2 * p->sq_entries;
12004 ctx = io_ring_ctx_alloc(p);
12009 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12010 * space applications don't need to do io completion events
12011 * polling again, they can rely on io_sq_thread to do polling
12012 * work, which can reduce cpu usage and uring_lock contention.
12014 if (ctx->flags & IORING_SETUP_IOPOLL &&
12015 !(ctx->flags & IORING_SETUP_SQPOLL))
12016 ctx->syscall_iopoll = 1;
12018 ctx->compat = in_compat_syscall();
12019 if (!capable(CAP_IPC_LOCK))
12020 ctx->user = get_uid(current_user());
12023 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12024 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12027 if (ctx->flags & IORING_SETUP_SQPOLL) {
12028 /* IPI related flags don't make sense with SQPOLL */
12029 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12030 IORING_SETUP_TASKRUN_FLAG))
12032 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12033 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12034 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12036 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12038 ctx->notify_method = TWA_SIGNAL;
12042 * This is just grabbed for accounting purposes. When a process exits,
12043 * the mm is exited and dropped before the files, hence we need to hang
12044 * on to this mm purely for the purposes of being able to unaccount
12045 * memory (locked/pinned vm). It's not used for anything else.
12047 mmgrab(current->mm);
12048 ctx->mm_account = current->mm;
12050 ret = io_allocate_scq_urings(ctx, p);
12054 ret = io_sq_offload_create(ctx, p);
12057 /* always set a rsrc node */
12058 ret = io_rsrc_node_switch_start(ctx);
12061 io_rsrc_node_switch(ctx, NULL);
12063 memset(&p->sq_off, 0, sizeof(p->sq_off));
12064 p->sq_off.head = offsetof(struct io_rings, sq.head);
12065 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12066 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12067 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12068 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12069 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12070 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12072 memset(&p->cq_off, 0, sizeof(p->cq_off));
12073 p->cq_off.head = offsetof(struct io_rings, cq.head);
12074 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12075 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12076 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12077 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12078 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12079 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12081 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12082 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12083 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12084 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12085 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12086 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12087 IORING_FEAT_LINKED_FILE;
12089 if (copy_to_user(params, p, sizeof(*p))) {
12094 file = io_uring_get_file(ctx);
12095 if (IS_ERR(file)) {
12096 ret = PTR_ERR(file);
12101 * Install ring fd as the very last thing, so we don't risk someone
12102 * having closed it before we finish setup
12104 ret = io_uring_install_fd(ctx, file);
12106 /* fput will clean it up */
12111 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12114 io_ring_ctx_wait_and_kill(ctx);
12119 * Sets up an aio uring context, and returns the fd. Applications asks for a
12120 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12121 * params structure passed in.
12123 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12125 struct io_uring_params p;
12128 if (copy_from_user(&p, params, sizeof(p)))
12130 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12135 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12136 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12137 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12138 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12139 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12140 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12143 return io_uring_create(entries, &p, params);
12146 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12147 struct io_uring_params __user *, params)
12149 return io_uring_setup(entries, params);
12152 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12155 struct io_uring_probe *p;
12159 size = struct_size(p, ops, nr_args);
12160 if (size == SIZE_MAX)
12162 p = kzalloc(size, GFP_KERNEL);
12167 if (copy_from_user(p, arg, size))
12170 if (memchr_inv(p, 0, size))
12173 p->last_op = IORING_OP_LAST - 1;
12174 if (nr_args > IORING_OP_LAST)
12175 nr_args = IORING_OP_LAST;
12177 for (i = 0; i < nr_args; i++) {
12179 if (!io_op_defs[i].not_supported)
12180 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12185 if (copy_to_user(arg, p, size))
12192 static int io_register_personality(struct io_ring_ctx *ctx)
12194 const struct cred *creds;
12198 creds = get_current_cred();
12200 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12201 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12209 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12210 void __user *arg, unsigned int nr_args)
12212 struct io_uring_restriction *res;
12216 /* Restrictions allowed only if rings started disabled */
12217 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12220 /* We allow only a single restrictions registration */
12221 if (ctx->restrictions.registered)
12224 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12227 size = array_size(nr_args, sizeof(*res));
12228 if (size == SIZE_MAX)
12231 res = memdup_user(arg, size);
12233 return PTR_ERR(res);
12237 for (i = 0; i < nr_args; i++) {
12238 switch (res[i].opcode) {
12239 case IORING_RESTRICTION_REGISTER_OP:
12240 if (res[i].register_op >= IORING_REGISTER_LAST) {
12245 __set_bit(res[i].register_op,
12246 ctx->restrictions.register_op);
12248 case IORING_RESTRICTION_SQE_OP:
12249 if (res[i].sqe_op >= IORING_OP_LAST) {
12254 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12256 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12257 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12259 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12260 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12269 /* Reset all restrictions if an error happened */
12271 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12273 ctx->restrictions.registered = true;
12279 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12281 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12284 if (ctx->restrictions.registered)
12285 ctx->restricted = 1;
12287 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12288 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12289 wake_up(&ctx->sq_data->wait);
12293 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12294 struct io_uring_rsrc_update2 *up,
12300 if (check_add_overflow(up->offset, nr_args, &tmp))
12302 err = io_rsrc_node_switch_start(ctx);
12307 case IORING_RSRC_FILE:
12308 return __io_sqe_files_update(ctx, up, nr_args);
12309 case IORING_RSRC_BUFFER:
12310 return __io_sqe_buffers_update(ctx, up, nr_args);
12315 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12318 struct io_uring_rsrc_update2 up;
12322 memset(&up, 0, sizeof(up));
12323 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12325 if (up.resv || up.resv2)
12327 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12330 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12331 unsigned size, unsigned type)
12333 struct io_uring_rsrc_update2 up;
12335 if (size != sizeof(up))
12337 if (copy_from_user(&up, arg, sizeof(up)))
12339 if (!up.nr || up.resv || up.resv2)
12341 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12344 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12345 unsigned int size, unsigned int type)
12347 struct io_uring_rsrc_register rr;
12349 /* keep it extendible */
12350 if (size != sizeof(rr))
12353 memset(&rr, 0, sizeof(rr));
12354 if (copy_from_user(&rr, arg, size))
12356 if (!rr.nr || rr.resv2)
12358 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12362 case IORING_RSRC_FILE:
12363 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12365 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12366 rr.nr, u64_to_user_ptr(rr.tags));
12367 case IORING_RSRC_BUFFER:
12368 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12370 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12371 rr.nr, u64_to_user_ptr(rr.tags));
12376 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12377 void __user *arg, unsigned len)
12379 struct io_uring_task *tctx = current->io_uring;
12380 cpumask_var_t new_mask;
12383 if (!tctx || !tctx->io_wq)
12386 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12389 cpumask_clear(new_mask);
12390 if (len > cpumask_size())
12391 len = cpumask_size();
12393 if (in_compat_syscall()) {
12394 ret = compat_get_bitmap(cpumask_bits(new_mask),
12395 (const compat_ulong_t __user *)arg,
12396 len * 8 /* CHAR_BIT */);
12398 ret = copy_from_user(new_mask, arg, len);
12402 free_cpumask_var(new_mask);
12406 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12407 free_cpumask_var(new_mask);
12411 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12413 struct io_uring_task *tctx = current->io_uring;
12415 if (!tctx || !tctx->io_wq)
12418 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12421 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12423 __must_hold(&ctx->uring_lock)
12425 struct io_tctx_node *node;
12426 struct io_uring_task *tctx = NULL;
12427 struct io_sq_data *sqd = NULL;
12428 __u32 new_count[2];
12431 if (copy_from_user(new_count, arg, sizeof(new_count)))
12433 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12434 if (new_count[i] > INT_MAX)
12437 if (ctx->flags & IORING_SETUP_SQPOLL) {
12438 sqd = ctx->sq_data;
12441 * Observe the correct sqd->lock -> ctx->uring_lock
12442 * ordering. Fine to drop uring_lock here, we hold
12443 * a ref to the ctx.
12445 refcount_inc(&sqd->refs);
12446 mutex_unlock(&ctx->uring_lock);
12447 mutex_lock(&sqd->lock);
12448 mutex_lock(&ctx->uring_lock);
12450 tctx = sqd->thread->io_uring;
12453 tctx = current->io_uring;
12456 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12458 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12460 ctx->iowq_limits[i] = new_count[i];
12461 ctx->iowq_limits_set = true;
12463 if (tctx && tctx->io_wq) {
12464 ret = io_wq_max_workers(tctx->io_wq, new_count);
12468 memset(new_count, 0, sizeof(new_count));
12472 mutex_unlock(&sqd->lock);
12473 io_put_sq_data(sqd);
12476 if (copy_to_user(arg, new_count, sizeof(new_count)))
12479 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12483 /* now propagate the restriction to all registered users */
12484 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12485 struct io_uring_task *tctx = node->task->io_uring;
12487 if (WARN_ON_ONCE(!tctx->io_wq))
12490 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12491 new_count[i] = ctx->iowq_limits[i];
12492 /* ignore errors, it always returns zero anyway */
12493 (void)io_wq_max_workers(tctx->io_wq, new_count);
12498 mutex_unlock(&sqd->lock);
12499 io_put_sq_data(sqd);
12504 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12506 struct io_uring_buf_ring *br;
12507 struct io_uring_buf_reg reg;
12508 struct io_buffer_list *bl, *free_bl = NULL;
12509 struct page **pages;
12512 if (copy_from_user(®, arg, sizeof(reg)))
12515 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12517 if (!reg.ring_addr)
12519 if (reg.ring_addr & ~PAGE_MASK)
12521 if (!is_power_of_2(reg.ring_entries))
12524 /* cannot disambiguate full vs empty due to head/tail size */
12525 if (reg.ring_entries >= 65536)
12528 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12529 int ret = io_init_bl_list(ctx);
12534 bl = io_buffer_get_list(ctx, reg.bgid);
12536 /* if mapped buffer ring OR classic exists, don't allow */
12537 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12540 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12545 pages = io_pin_pages(reg.ring_addr,
12546 struct_size(br, bufs, reg.ring_entries),
12548 if (IS_ERR(pages)) {
12550 return PTR_ERR(pages);
12553 br = page_address(pages[0]);
12554 bl->buf_pages = pages;
12555 bl->buf_nr_pages = nr_pages;
12556 bl->nr_entries = reg.ring_entries;
12558 bl->mask = reg.ring_entries - 1;
12559 io_buffer_add_list(ctx, bl, reg.bgid);
12563 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12565 struct io_uring_buf_reg reg;
12566 struct io_buffer_list *bl;
12568 if (copy_from_user(®, arg, sizeof(reg)))
12570 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12573 bl = io_buffer_get_list(ctx, reg.bgid);
12576 if (!bl->buf_nr_pages)
12579 __io_remove_buffers(ctx, bl, -1U);
12580 if (bl->bgid >= BGID_ARRAY) {
12581 xa_erase(&ctx->io_bl_xa, bl->bgid);
12587 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12588 void __user *arg, unsigned nr_args)
12589 __releases(ctx->uring_lock)
12590 __acquires(ctx->uring_lock)
12595 * We're inside the ring mutex, if the ref is already dying, then
12596 * someone else killed the ctx or is already going through
12597 * io_uring_register().
12599 if (percpu_ref_is_dying(&ctx->refs))
12602 if (ctx->restricted) {
12603 if (opcode >= IORING_REGISTER_LAST)
12605 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12606 if (!test_bit(opcode, ctx->restrictions.register_op))
12611 case IORING_REGISTER_BUFFERS:
12615 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
12617 case IORING_UNREGISTER_BUFFERS:
12619 if (arg || nr_args)
12621 ret = io_sqe_buffers_unregister(ctx);
12623 case IORING_REGISTER_FILES:
12627 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
12629 case IORING_UNREGISTER_FILES:
12631 if (arg || nr_args)
12633 ret = io_sqe_files_unregister(ctx);
12635 case IORING_REGISTER_FILES_UPDATE:
12636 ret = io_register_files_update(ctx, arg, nr_args);
12638 case IORING_REGISTER_EVENTFD:
12642 ret = io_eventfd_register(ctx, arg, 0);
12644 case IORING_REGISTER_EVENTFD_ASYNC:
12648 ret = io_eventfd_register(ctx, arg, 1);
12650 case IORING_UNREGISTER_EVENTFD:
12652 if (arg || nr_args)
12654 ret = io_eventfd_unregister(ctx);
12656 case IORING_REGISTER_PROBE:
12658 if (!arg || nr_args > 256)
12660 ret = io_probe(ctx, arg, nr_args);
12662 case IORING_REGISTER_PERSONALITY:
12664 if (arg || nr_args)
12666 ret = io_register_personality(ctx);
12668 case IORING_UNREGISTER_PERSONALITY:
12672 ret = io_unregister_personality(ctx, nr_args);
12674 case IORING_REGISTER_ENABLE_RINGS:
12676 if (arg || nr_args)
12678 ret = io_register_enable_rings(ctx);
12680 case IORING_REGISTER_RESTRICTIONS:
12681 ret = io_register_restrictions(ctx, arg, nr_args);
12683 case IORING_REGISTER_FILES2:
12684 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
12686 case IORING_REGISTER_FILES_UPDATE2:
12687 ret = io_register_rsrc_update(ctx, arg, nr_args,
12690 case IORING_REGISTER_BUFFERS2:
12691 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
12693 case IORING_REGISTER_BUFFERS_UPDATE:
12694 ret = io_register_rsrc_update(ctx, arg, nr_args,
12695 IORING_RSRC_BUFFER);
12697 case IORING_REGISTER_IOWQ_AFF:
12699 if (!arg || !nr_args)
12701 ret = io_register_iowq_aff(ctx, arg, nr_args);
12703 case IORING_UNREGISTER_IOWQ_AFF:
12705 if (arg || nr_args)
12707 ret = io_unregister_iowq_aff(ctx);
12709 case IORING_REGISTER_IOWQ_MAX_WORKERS:
12711 if (!arg || nr_args != 2)
12713 ret = io_register_iowq_max_workers(ctx, arg);
12715 case IORING_REGISTER_RING_FDS:
12716 ret = io_ringfd_register(ctx, arg, nr_args);
12718 case IORING_UNREGISTER_RING_FDS:
12719 ret = io_ringfd_unregister(ctx, arg, nr_args);
12721 case IORING_REGISTER_PBUF_RING:
12723 if (!arg || nr_args != 1)
12725 ret = io_register_pbuf_ring(ctx, arg);
12727 case IORING_UNREGISTER_PBUF_RING:
12729 if (!arg || nr_args != 1)
12731 ret = io_unregister_pbuf_ring(ctx, arg);
12741 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
12742 void __user *, arg, unsigned int, nr_args)
12744 struct io_ring_ctx *ctx;
12753 if (f.file->f_op != &io_uring_fops)
12756 ctx = f.file->private_data;
12758 io_run_task_work();
12760 mutex_lock(&ctx->uring_lock);
12761 ret = __io_uring_register(ctx, opcode, arg, nr_args);
12762 mutex_unlock(&ctx->uring_lock);
12763 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
12769 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
12775 static const struct io_op_def io_op_defs[] = {
12776 [IORING_OP_NOP] = {
12779 .prep = io_nop_prep,
12782 [IORING_OP_READV] = {
12784 .unbound_nonreg_file = 1,
12786 .buffer_select = 1,
12787 .needs_async_setup = 1,
12792 .async_size = sizeof(struct io_async_rw),
12793 .prep = io_prep_rw,
12796 [IORING_OP_WRITEV] = {
12798 .hash_reg_file = 1,
12799 .unbound_nonreg_file = 1,
12801 .needs_async_setup = 1,
12806 .async_size = sizeof(struct io_async_rw),
12807 .prep = io_prep_rw,
12810 [IORING_OP_FSYNC] = {
12813 .prep = io_fsync_prep,
12816 [IORING_OP_READ_FIXED] = {
12818 .unbound_nonreg_file = 1,
12824 .async_size = sizeof(struct io_async_rw),
12825 .prep = io_prep_rw,
12828 [IORING_OP_WRITE_FIXED] = {
12830 .hash_reg_file = 1,
12831 .unbound_nonreg_file = 1,
12837 .async_size = sizeof(struct io_async_rw),
12838 .prep = io_prep_rw,
12841 [IORING_OP_POLL_ADD] = {
12843 .unbound_nonreg_file = 1,
12845 .prep = io_poll_add_prep,
12846 .issue = io_poll_add,
12848 [IORING_OP_POLL_REMOVE] = {
12850 .prep = io_poll_remove_prep,
12851 .issue = io_poll_remove,
12853 [IORING_OP_SYNC_FILE_RANGE] = {
12856 .prep = io_sfr_prep,
12857 .issue = io_sync_file_range,
12859 [IORING_OP_SENDMSG] = {
12861 .unbound_nonreg_file = 1,
12863 .needs_async_setup = 1,
12865 .async_size = sizeof(struct io_async_msghdr),
12866 .prep = io_sendmsg_prep,
12867 .issue = io_sendmsg,
12869 [IORING_OP_RECVMSG] = {
12871 .unbound_nonreg_file = 1,
12873 .buffer_select = 1,
12874 .needs_async_setup = 1,
12876 .async_size = sizeof(struct io_async_msghdr),
12877 .prep = io_recvmsg_prep,
12878 .issue = io_recvmsg,
12880 [IORING_OP_TIMEOUT] = {
12882 .async_size = sizeof(struct io_timeout_data),
12883 .prep = io_timeout_prep,
12884 .issue = io_timeout,
12886 [IORING_OP_TIMEOUT_REMOVE] = {
12887 /* used by timeout updates' prep() */
12889 .prep = io_timeout_remove_prep,
12890 .issue = io_timeout_remove,
12892 [IORING_OP_ACCEPT] = {
12894 .unbound_nonreg_file = 1,
12896 .poll_exclusive = 1,
12897 .ioprio = 1, /* used for flags */
12898 .prep = io_accept_prep,
12899 .issue = io_accept,
12901 [IORING_OP_ASYNC_CANCEL] = {
12903 .prep = io_async_cancel_prep,
12904 .issue = io_async_cancel,
12906 [IORING_OP_LINK_TIMEOUT] = {
12908 .async_size = sizeof(struct io_timeout_data),
12909 .prep = io_link_timeout_prep,
12910 .issue = io_no_issue,
12912 [IORING_OP_CONNECT] = {
12914 .unbound_nonreg_file = 1,
12916 .needs_async_setup = 1,
12917 .async_size = sizeof(struct io_async_connect),
12918 .prep = io_connect_prep,
12919 .issue = io_connect,
12921 [IORING_OP_FALLOCATE] = {
12923 .prep = io_fallocate_prep,
12924 .issue = io_fallocate,
12926 [IORING_OP_OPENAT] = {
12927 .prep = io_openat_prep,
12928 .issue = io_openat,
12930 [IORING_OP_CLOSE] = {
12931 .prep = io_close_prep,
12934 [IORING_OP_FILES_UPDATE] = {
12937 .prep = io_files_update_prep,
12938 .issue = io_files_update,
12940 [IORING_OP_STATX] = {
12942 .prep = io_statx_prep,
12945 [IORING_OP_READ] = {
12947 .unbound_nonreg_file = 1,
12949 .buffer_select = 1,
12954 .async_size = sizeof(struct io_async_rw),
12955 .prep = io_prep_rw,
12958 [IORING_OP_WRITE] = {
12960 .hash_reg_file = 1,
12961 .unbound_nonreg_file = 1,
12967 .async_size = sizeof(struct io_async_rw),
12968 .prep = io_prep_rw,
12971 [IORING_OP_FADVISE] = {
12974 .prep = io_fadvise_prep,
12975 .issue = io_fadvise,
12977 [IORING_OP_MADVISE] = {
12978 .prep = io_madvise_prep,
12979 .issue = io_madvise,
12981 [IORING_OP_SEND] = {
12983 .unbound_nonreg_file = 1,
12987 .prep = io_sendmsg_prep,
12990 [IORING_OP_RECV] = {
12992 .unbound_nonreg_file = 1,
12994 .buffer_select = 1,
12997 .prep = io_recvmsg_prep,
13000 [IORING_OP_OPENAT2] = {
13001 .prep = io_openat2_prep,
13002 .issue = io_openat2,
13004 [IORING_OP_EPOLL_CTL] = {
13005 .unbound_nonreg_file = 1,
13007 .prep = io_epoll_ctl_prep,
13008 .issue = io_epoll_ctl,
13010 [IORING_OP_SPLICE] = {
13012 .hash_reg_file = 1,
13013 .unbound_nonreg_file = 1,
13015 .prep = io_splice_prep,
13016 .issue = io_splice,
13018 [IORING_OP_PROVIDE_BUFFERS] = {
13021 .prep = io_provide_buffers_prep,
13022 .issue = io_provide_buffers,
13024 [IORING_OP_REMOVE_BUFFERS] = {
13027 .prep = io_remove_buffers_prep,
13028 .issue = io_remove_buffers,
13030 [IORING_OP_TEE] = {
13032 .hash_reg_file = 1,
13033 .unbound_nonreg_file = 1,
13035 .prep = io_tee_prep,
13038 [IORING_OP_SHUTDOWN] = {
13040 .prep = io_shutdown_prep,
13041 .issue = io_shutdown,
13043 [IORING_OP_RENAMEAT] = {
13044 .prep = io_renameat_prep,
13045 .issue = io_renameat,
13047 [IORING_OP_UNLINKAT] = {
13048 .prep = io_unlinkat_prep,
13049 .issue = io_unlinkat,
13051 [IORING_OP_MKDIRAT] = {
13052 .prep = io_mkdirat_prep,
13053 .issue = io_mkdirat,
13055 [IORING_OP_SYMLINKAT] = {
13056 .prep = io_symlinkat_prep,
13057 .issue = io_symlinkat,
13059 [IORING_OP_LINKAT] = {
13060 .prep = io_linkat_prep,
13061 .issue = io_linkat,
13063 [IORING_OP_MSG_RING] = {
13066 .prep = io_msg_ring_prep,
13067 .issue = io_msg_ring,
13069 [IORING_OP_FSETXATTR] = {
13071 .prep = io_fsetxattr_prep,
13072 .issue = io_fsetxattr,
13074 [IORING_OP_SETXATTR] = {
13075 .prep = io_setxattr_prep,
13076 .issue = io_setxattr,
13078 [IORING_OP_FGETXATTR] = {
13080 .prep = io_fgetxattr_prep,
13081 .issue = io_fgetxattr,
13083 [IORING_OP_GETXATTR] = {
13084 .prep = io_getxattr_prep,
13085 .issue = io_getxattr,
13087 [IORING_OP_SOCKET] = {
13089 .prep = io_socket_prep,
13090 .issue = io_socket,
13092 [IORING_OP_URING_CMD] = {
13095 .needs_async_setup = 1,
13096 .async_size = uring_cmd_pdu_size(1),
13097 .prep = io_uring_cmd_prep,
13098 .issue = io_uring_cmd,
13102 static int __init io_uring_init(void)
13106 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13107 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13108 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13111 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13112 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13113 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13114 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13115 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13116 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13117 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13118 BUILD_BUG_SQE_ELEM(8, __u64, off);
13119 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13120 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13121 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13122 BUILD_BUG_SQE_ELEM(24, __u32, len);
13123 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13124 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13125 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13126 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13127 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13128 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13129 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13130 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13131 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13132 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13133 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13134 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13135 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13136 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13137 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13138 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13139 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13140 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13141 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13142 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13143 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13144 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13146 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13147 sizeof(struct io_uring_rsrc_update));
13148 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13149 sizeof(struct io_uring_rsrc_update2));
13151 /* ->buf_index is u16 */
13152 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13153 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13154 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13155 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13156 offsetof(struct io_uring_buf_ring, tail));
13158 /* should fit into one byte */
13159 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13160 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13161 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13163 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13164 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13166 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13168 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13170 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
13171 BUG_ON(!io_op_defs[i].prep);
13172 BUG_ON(!io_op_defs[i].issue);
13175 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13179 __initcall(io_uring_init);