1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/audit.h>
82 #include <linux/security.h>
83 #include <linux/xattr.h>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
98 #define IORING_MAX_FIXED_FILES (1U << 20)
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100 IORING_REGISTER_LAST + IORING_OP_LAST)
102 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
103 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
104 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
106 #define IORING_MAX_REG_BUFFERS (1U << 14)
108 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
111 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
114 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
115 REQ_F_POLLED | REQ_F_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;
1115 static const struct io_op_def io_op_defs[] = {
1120 [IORING_OP_READV] = {
1122 .unbound_nonreg_file = 1,
1125 .needs_async_setup = 1,
1130 .async_size = sizeof(struct io_async_rw),
1132 [IORING_OP_WRITEV] = {
1135 .unbound_nonreg_file = 1,
1137 .needs_async_setup = 1,
1142 .async_size = sizeof(struct io_async_rw),
1144 [IORING_OP_FSYNC] = {
1148 [IORING_OP_READ_FIXED] = {
1150 .unbound_nonreg_file = 1,
1156 .async_size = sizeof(struct io_async_rw),
1158 [IORING_OP_WRITE_FIXED] = {
1161 .unbound_nonreg_file = 1,
1167 .async_size = sizeof(struct io_async_rw),
1169 [IORING_OP_POLL_ADD] = {
1171 .unbound_nonreg_file = 1,
1174 [IORING_OP_POLL_REMOVE] = {
1177 [IORING_OP_SYNC_FILE_RANGE] = {
1181 [IORING_OP_SENDMSG] = {
1183 .unbound_nonreg_file = 1,
1185 .needs_async_setup = 1,
1187 .async_size = sizeof(struct io_async_msghdr),
1189 [IORING_OP_RECVMSG] = {
1191 .unbound_nonreg_file = 1,
1194 .needs_async_setup = 1,
1196 .async_size = sizeof(struct io_async_msghdr),
1198 [IORING_OP_TIMEOUT] = {
1200 .async_size = sizeof(struct io_timeout_data),
1202 [IORING_OP_TIMEOUT_REMOVE] = {
1203 /* used by timeout updates' prep() */
1206 [IORING_OP_ACCEPT] = {
1208 .unbound_nonreg_file = 1,
1210 .poll_exclusive = 1,
1211 .ioprio = 1, /* used for flags */
1213 [IORING_OP_ASYNC_CANCEL] = {
1216 [IORING_OP_LINK_TIMEOUT] = {
1218 .async_size = sizeof(struct io_timeout_data),
1220 [IORING_OP_CONNECT] = {
1222 .unbound_nonreg_file = 1,
1224 .needs_async_setup = 1,
1225 .async_size = sizeof(struct io_async_connect),
1227 [IORING_OP_FALLOCATE] = {
1230 [IORING_OP_OPENAT] = {},
1231 [IORING_OP_CLOSE] = {},
1232 [IORING_OP_FILES_UPDATE] = {
1236 [IORING_OP_STATX] = {
1239 [IORING_OP_READ] = {
1241 .unbound_nonreg_file = 1,
1248 .async_size = sizeof(struct io_async_rw),
1250 [IORING_OP_WRITE] = {
1253 .unbound_nonreg_file = 1,
1259 .async_size = sizeof(struct io_async_rw),
1261 [IORING_OP_FADVISE] = {
1265 [IORING_OP_MADVISE] = {},
1266 [IORING_OP_SEND] = {
1268 .unbound_nonreg_file = 1,
1273 [IORING_OP_RECV] = {
1275 .unbound_nonreg_file = 1,
1281 [IORING_OP_OPENAT2] = {
1283 [IORING_OP_EPOLL_CTL] = {
1284 .unbound_nonreg_file = 1,
1287 [IORING_OP_SPLICE] = {
1290 .unbound_nonreg_file = 1,
1293 [IORING_OP_PROVIDE_BUFFERS] = {
1297 [IORING_OP_REMOVE_BUFFERS] = {
1304 .unbound_nonreg_file = 1,
1307 [IORING_OP_SHUTDOWN] = {
1310 [IORING_OP_RENAMEAT] = {},
1311 [IORING_OP_UNLINKAT] = {},
1312 [IORING_OP_MKDIRAT] = {},
1313 [IORING_OP_SYMLINKAT] = {},
1314 [IORING_OP_LINKAT] = {},
1315 [IORING_OP_MSG_RING] = {
1319 [IORING_OP_FSETXATTR] = {
1322 [IORING_OP_SETXATTR] = {},
1323 [IORING_OP_FGETXATTR] = {
1326 [IORING_OP_GETXATTR] = {},
1327 [IORING_OP_SOCKET] = {
1330 [IORING_OP_URING_CMD] = {
1333 .needs_async_setup = 1,
1334 .async_size = uring_cmd_pdu_size(1),
1338 /* requests with any of those set should undergo io_disarm_next() */
1339 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1340 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1342 static bool io_disarm_next(struct io_kiocb *req);
1343 static void io_uring_del_tctx_node(unsigned long index);
1344 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1345 struct task_struct *task,
1347 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1349 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1350 static void io_dismantle_req(struct io_kiocb *req);
1351 static void io_queue_linked_timeout(struct io_kiocb *req);
1352 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1353 struct io_uring_rsrc_update2 *up,
1355 static void io_clean_op(struct io_kiocb *req);
1356 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1357 unsigned issue_flags);
1358 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1359 static void io_queue_sqe(struct io_kiocb *req);
1360 static void io_rsrc_put_work(struct work_struct *work);
1362 static void io_req_task_queue(struct io_kiocb *req);
1363 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1364 static int io_req_prep_async(struct io_kiocb *req);
1366 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1367 unsigned int issue_flags, u32 slot_index);
1368 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
1369 unsigned int offset);
1370 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1372 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1373 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1374 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1376 static struct kmem_cache *req_cachep;
1378 static const struct file_operations io_uring_fops;
1380 const char *io_uring_get_opcode(u8 opcode)
1382 switch ((enum io_uring_op)opcode) {
1385 case IORING_OP_READV:
1387 case IORING_OP_WRITEV:
1389 case IORING_OP_FSYNC:
1391 case IORING_OP_READ_FIXED:
1392 return "READ_FIXED";
1393 case IORING_OP_WRITE_FIXED:
1394 return "WRITE_FIXED";
1395 case IORING_OP_POLL_ADD:
1397 case IORING_OP_POLL_REMOVE:
1398 return "POLL_REMOVE";
1399 case IORING_OP_SYNC_FILE_RANGE:
1400 return "SYNC_FILE_RANGE";
1401 case IORING_OP_SENDMSG:
1403 case IORING_OP_RECVMSG:
1405 case IORING_OP_TIMEOUT:
1407 case IORING_OP_TIMEOUT_REMOVE:
1408 return "TIMEOUT_REMOVE";
1409 case IORING_OP_ACCEPT:
1411 case IORING_OP_ASYNC_CANCEL:
1412 return "ASYNC_CANCEL";
1413 case IORING_OP_LINK_TIMEOUT:
1414 return "LINK_TIMEOUT";
1415 case IORING_OP_CONNECT:
1417 case IORING_OP_FALLOCATE:
1419 case IORING_OP_OPENAT:
1421 case IORING_OP_CLOSE:
1423 case IORING_OP_FILES_UPDATE:
1424 return "FILES_UPDATE";
1425 case IORING_OP_STATX:
1427 case IORING_OP_READ:
1429 case IORING_OP_WRITE:
1431 case IORING_OP_FADVISE:
1433 case IORING_OP_MADVISE:
1435 case IORING_OP_SEND:
1437 case IORING_OP_RECV:
1439 case IORING_OP_OPENAT2:
1441 case IORING_OP_EPOLL_CTL:
1443 case IORING_OP_SPLICE:
1445 case IORING_OP_PROVIDE_BUFFERS:
1446 return "PROVIDE_BUFFERS";
1447 case IORING_OP_REMOVE_BUFFERS:
1448 return "REMOVE_BUFFERS";
1451 case IORING_OP_SHUTDOWN:
1453 case IORING_OP_RENAMEAT:
1455 case IORING_OP_UNLINKAT:
1457 case IORING_OP_MKDIRAT:
1459 case IORING_OP_SYMLINKAT:
1461 case IORING_OP_LINKAT:
1463 case IORING_OP_MSG_RING:
1465 case IORING_OP_FSETXATTR:
1467 case IORING_OP_SETXATTR:
1469 case IORING_OP_FGETXATTR:
1471 case IORING_OP_GETXATTR:
1473 case IORING_OP_SOCKET:
1475 case IORING_OP_URING_CMD:
1477 case IORING_OP_LAST:
1483 struct sock *io_uring_get_socket(struct file *file)
1485 #if defined(CONFIG_UNIX)
1486 if (file->f_op == &io_uring_fops) {
1487 struct io_ring_ctx *ctx = file->private_data;
1489 return ctx->ring_sock->sk;
1494 EXPORT_SYMBOL(io_uring_get_socket);
1496 #if defined(CONFIG_UNIX)
1497 static inline bool io_file_need_scm(struct file *filp)
1499 #if defined(IO_URING_SCM_ALL)
1502 return !!unix_get_socket(filp);
1506 static inline bool io_file_need_scm(struct file *filp)
1512 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1514 lockdep_assert_held(&ctx->uring_lock);
1515 if (issue_flags & IO_URING_F_UNLOCKED)
1516 mutex_unlock(&ctx->uring_lock);
1519 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1522 * "Normal" inline submissions always hold the uring_lock, since we
1523 * grab it from the system call. Same is true for the SQPOLL offload.
1524 * The only exception is when we've detached the request and issue it
1525 * from an async worker thread, grab the lock for that case.
1527 if (issue_flags & IO_URING_F_UNLOCKED)
1528 mutex_lock(&ctx->uring_lock);
1529 lockdep_assert_held(&ctx->uring_lock);
1532 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1535 mutex_lock(&ctx->uring_lock);
1540 #define io_for_each_link(pos, head) \
1541 for (pos = (head); pos; pos = pos->link)
1544 * Shamelessly stolen from the mm implementation of page reference checking,
1545 * see commit f958d7b528b1 for details.
1547 #define req_ref_zero_or_close_to_overflow(req) \
1548 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1550 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1552 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1553 return atomic_inc_not_zero(&req->refs);
1556 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1558 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1561 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1562 return atomic_dec_and_test(&req->refs);
1565 static inline void req_ref_get(struct io_kiocb *req)
1567 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1568 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1569 atomic_inc(&req->refs);
1572 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1574 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1575 __io_submit_flush_completions(ctx);
1578 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1580 if (!(req->flags & REQ_F_REFCOUNT)) {
1581 req->flags |= REQ_F_REFCOUNT;
1582 atomic_set(&req->refs, nr);
1586 static inline void io_req_set_refcount(struct io_kiocb *req)
1588 __io_req_set_refcount(req, 1);
1591 #define IO_RSRC_REF_BATCH 100
1593 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1595 percpu_ref_put_many(&node->refs, nr);
1598 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1599 struct io_ring_ctx *ctx)
1600 __must_hold(&ctx->uring_lock)
1602 struct io_rsrc_node *node = req->rsrc_node;
1605 if (node == ctx->rsrc_node)
1606 ctx->rsrc_cached_refs++;
1608 io_rsrc_put_node(node, 1);
1612 static inline void io_req_put_rsrc(struct io_kiocb *req)
1615 io_rsrc_put_node(req->rsrc_node, 1);
1618 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1619 __must_hold(&ctx->uring_lock)
1621 if (ctx->rsrc_cached_refs) {
1622 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1623 ctx->rsrc_cached_refs = 0;
1627 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1628 __must_hold(&ctx->uring_lock)
1630 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1631 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1634 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1635 struct io_ring_ctx *ctx,
1636 unsigned int issue_flags)
1638 if (!req->rsrc_node) {
1639 req->rsrc_node = ctx->rsrc_node;
1641 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1642 lockdep_assert_held(&ctx->uring_lock);
1643 ctx->rsrc_cached_refs--;
1644 if (unlikely(ctx->rsrc_cached_refs < 0))
1645 io_rsrc_refs_refill(ctx);
1647 percpu_ref_get(&req->rsrc_node->refs);
1652 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1654 if (req->flags & REQ_F_BUFFER_RING) {
1656 req->buf_list->head++;
1657 req->flags &= ~REQ_F_BUFFER_RING;
1659 list_add(&req->kbuf->list, list);
1660 req->flags &= ~REQ_F_BUFFER_SELECTED;
1663 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1666 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1668 lockdep_assert_held(&req->ctx->completion_lock);
1670 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1672 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1675 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1676 unsigned issue_flags)
1678 unsigned int cflags;
1680 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1684 * We can add this buffer back to two lists:
1686 * 1) The io_buffers_cache list. This one is protected by the
1687 * ctx->uring_lock. If we already hold this lock, add back to this
1688 * list as we can grab it from issue as well.
1689 * 2) The io_buffers_comp list. This one is protected by the
1690 * ctx->completion_lock.
1692 * We migrate buffers from the comp_list to the issue cache list
1695 if (req->flags & REQ_F_BUFFER_RING) {
1696 /* no buffers to recycle for this case */
1697 cflags = __io_put_kbuf(req, NULL);
1698 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1699 struct io_ring_ctx *ctx = req->ctx;
1701 spin_lock(&ctx->completion_lock);
1702 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1703 spin_unlock(&ctx->completion_lock);
1705 lockdep_assert_held(&req->ctx->uring_lock);
1707 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1713 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1716 if (ctx->io_bl && bgid < BGID_ARRAY)
1717 return &ctx->io_bl[bgid];
1719 return xa_load(&ctx->io_bl_xa, bgid);
1722 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1724 struct io_ring_ctx *ctx = req->ctx;
1725 struct io_buffer_list *bl;
1726 struct io_buffer *buf;
1728 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1731 * For legacy provided buffer mode, don't recycle if we already did
1732 * IO to this buffer. For ring-mapped provided buffer mode, we should
1733 * increment ring->head to explicitly monopolize the buffer to avoid
1736 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
1737 (req->flags & REQ_F_PARTIAL_IO))
1741 * READV uses fields in `struct io_rw` (len/addr) to stash the selected
1742 * buffer data. However if that buffer is recycled the original request
1743 * data stored in addr is lost. Therefore forbid recycling for now.
1745 if (req->opcode == IORING_OP_READV)
1749 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1750 * the flag and hence ensure that bl->head doesn't get incremented.
1751 * If the tail has already been incremented, hang on to it.
1753 if (req->flags & REQ_F_BUFFER_RING) {
1754 if (req->buf_list) {
1755 if (req->flags & REQ_F_PARTIAL_IO) {
1756 req->buf_list->head++;
1757 req->buf_list = NULL;
1759 req->buf_index = req->buf_list->bgid;
1760 req->flags &= ~REQ_F_BUFFER_RING;
1766 io_ring_submit_lock(ctx, issue_flags);
1769 bl = io_buffer_get_list(ctx, buf->bgid);
1770 list_add(&buf->list, &bl->buf_list);
1771 req->flags &= ~REQ_F_BUFFER_SELECTED;
1772 req->buf_index = buf->bgid;
1774 io_ring_submit_unlock(ctx, issue_flags);
1777 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1779 __must_hold(&req->ctx->timeout_lock)
1781 struct io_kiocb *req;
1783 if (task && head->task != task)
1788 io_for_each_link(req, head) {
1789 if (req->flags & REQ_F_INFLIGHT)
1795 static bool io_match_linked(struct io_kiocb *head)
1797 struct io_kiocb *req;
1799 io_for_each_link(req, head) {
1800 if (req->flags & REQ_F_INFLIGHT)
1807 * As io_match_task() but protected against racing with linked timeouts.
1808 * User must not hold timeout_lock.
1810 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1815 if (task && head->task != task)
1820 if (head->flags & REQ_F_LINK_TIMEOUT) {
1821 struct io_ring_ctx *ctx = head->ctx;
1823 /* protect against races with linked timeouts */
1824 spin_lock_irq(&ctx->timeout_lock);
1825 matched = io_match_linked(head);
1826 spin_unlock_irq(&ctx->timeout_lock);
1828 matched = io_match_linked(head);
1833 static inline bool req_has_async_data(struct io_kiocb *req)
1835 return req->flags & REQ_F_ASYNC_DATA;
1838 static inline void req_set_fail(struct io_kiocb *req)
1840 req->flags |= REQ_F_FAIL;
1841 if (req->flags & REQ_F_CQE_SKIP) {
1842 req->flags &= ~REQ_F_CQE_SKIP;
1843 req->flags |= REQ_F_SKIP_LINK_CQES;
1847 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1853 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1855 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1858 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1860 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1862 complete(&ctx->ref_comp);
1865 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1867 return !req->timeout.off;
1870 static __cold void io_fallback_req_func(struct work_struct *work)
1872 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1873 fallback_work.work);
1874 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1875 struct io_kiocb *req, *tmp;
1876 bool locked = false;
1878 percpu_ref_get(&ctx->refs);
1879 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1880 req->io_task_work.func(req, &locked);
1883 io_submit_flush_completions(ctx);
1884 mutex_unlock(&ctx->uring_lock);
1886 percpu_ref_put(&ctx->refs);
1889 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1891 struct io_ring_ctx *ctx;
1894 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1898 xa_init(&ctx->io_bl_xa);
1901 * Use 5 bits less than the max cq entries, that should give us around
1902 * 32 entries per hash list if totally full and uniformly spread.
1904 hash_bits = ilog2(p->cq_entries);
1908 ctx->cancel_hash_bits = hash_bits;
1909 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1911 if (!ctx->cancel_hash)
1913 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1915 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1916 if (!ctx->dummy_ubuf)
1918 /* set invalid range, so io_import_fixed() fails meeting it */
1919 ctx->dummy_ubuf->ubuf = -1UL;
1921 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1922 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1925 ctx->flags = p->flags;
1926 init_waitqueue_head(&ctx->sqo_sq_wait);
1927 INIT_LIST_HEAD(&ctx->sqd_list);
1928 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1929 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1930 INIT_LIST_HEAD(&ctx->apoll_cache);
1931 init_completion(&ctx->ref_comp);
1932 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1933 mutex_init(&ctx->uring_lock);
1934 init_waitqueue_head(&ctx->cq_wait);
1935 spin_lock_init(&ctx->completion_lock);
1936 spin_lock_init(&ctx->timeout_lock);
1937 INIT_WQ_LIST(&ctx->iopoll_list);
1938 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1939 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1940 INIT_LIST_HEAD(&ctx->defer_list);
1941 INIT_LIST_HEAD(&ctx->timeout_list);
1942 INIT_LIST_HEAD(&ctx->ltimeout_list);
1943 spin_lock_init(&ctx->rsrc_ref_lock);
1944 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1945 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1946 init_llist_head(&ctx->rsrc_put_llist);
1947 INIT_LIST_HEAD(&ctx->tctx_list);
1948 ctx->submit_state.free_list.next = NULL;
1949 INIT_WQ_LIST(&ctx->locked_free_list);
1950 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1951 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1954 kfree(ctx->dummy_ubuf);
1955 kfree(ctx->cancel_hash);
1957 xa_destroy(&ctx->io_bl_xa);
1962 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1964 struct io_rings *r = ctx->rings;
1966 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1970 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1972 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1973 struct io_ring_ctx *ctx = req->ctx;
1975 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1981 static inline bool io_req_ffs_set(struct io_kiocb *req)
1983 return req->flags & REQ_F_FIXED_FILE;
1986 static inline void io_req_track_inflight(struct io_kiocb *req)
1988 if (!(req->flags & REQ_F_INFLIGHT)) {
1989 req->flags |= REQ_F_INFLIGHT;
1990 atomic_inc(&req->task->io_uring->inflight_tracked);
1994 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1996 if (WARN_ON_ONCE(!req->link))
1999 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2000 req->flags |= REQ_F_LINK_TIMEOUT;
2002 /* linked timeouts should have two refs once prep'ed */
2003 io_req_set_refcount(req);
2004 __io_req_set_refcount(req->link, 2);
2008 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2010 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
2012 return __io_prep_linked_timeout(req);
2015 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
2017 io_queue_linked_timeout(__io_prep_linked_timeout(req));
2020 static inline void io_arm_ltimeout(struct io_kiocb *req)
2022 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
2023 __io_arm_ltimeout(req);
2026 static void io_prep_async_work(struct io_kiocb *req)
2028 const struct io_op_def *def = &io_op_defs[req->opcode];
2029 struct io_ring_ctx *ctx = req->ctx;
2031 if (!(req->flags & REQ_F_CREDS)) {
2032 req->flags |= REQ_F_CREDS;
2033 req->creds = get_current_cred();
2036 req->work.list.next = NULL;
2037 req->work.flags = 0;
2038 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
2039 if (req->flags & REQ_F_FORCE_ASYNC)
2040 req->work.flags |= IO_WQ_WORK_CONCURRENT;
2042 if (req->flags & REQ_F_ISREG) {
2043 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
2044 io_wq_hash_work(&req->work, file_inode(req->file));
2045 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
2046 if (def->unbound_nonreg_file)
2047 req->work.flags |= IO_WQ_WORK_UNBOUND;
2051 static void io_prep_async_link(struct io_kiocb *req)
2053 struct io_kiocb *cur;
2055 if (req->flags & REQ_F_LINK_TIMEOUT) {
2056 struct io_ring_ctx *ctx = req->ctx;
2058 spin_lock_irq(&ctx->timeout_lock);
2059 io_for_each_link(cur, req)
2060 io_prep_async_work(cur);
2061 spin_unlock_irq(&ctx->timeout_lock);
2063 io_for_each_link(cur, req)
2064 io_prep_async_work(cur);
2068 static inline void io_req_add_compl_list(struct io_kiocb *req)
2070 struct io_submit_state *state = &req->ctx->submit_state;
2072 if (!(req->flags & REQ_F_CQE_SKIP))
2073 state->flush_cqes = true;
2074 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
2077 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
2079 struct io_kiocb *link = io_prep_linked_timeout(req);
2080 struct io_uring_task *tctx = req->task->io_uring;
2083 BUG_ON(!tctx->io_wq);
2085 /* init ->work of the whole link before punting */
2086 io_prep_async_link(req);
2089 * Not expected to happen, but if we do have a bug where this _can_
2090 * happen, catch it here and ensure the request is marked as
2091 * canceled. That will make io-wq go through the usual work cancel
2092 * procedure rather than attempt to run this request (or create a new
2095 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
2096 req->work.flags |= IO_WQ_WORK_CANCEL;
2098 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
2099 req->opcode, req->flags, &req->work,
2100 io_wq_is_hashed(&req->work));
2101 io_wq_enqueue(tctx->io_wq, &req->work);
2103 io_queue_linked_timeout(link);
2106 static void io_kill_timeout(struct io_kiocb *req, int status)
2107 __must_hold(&req->ctx->completion_lock)
2108 __must_hold(&req->ctx->timeout_lock)
2110 struct io_timeout_data *io = req->async_data;
2112 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2115 atomic_set(&req->ctx->cq_timeouts,
2116 atomic_read(&req->ctx->cq_timeouts) + 1);
2117 list_del_init(&req->timeout.list);
2118 io_req_tw_post_queue(req, status, 0);
2122 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
2124 while (!list_empty(&ctx->defer_list)) {
2125 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
2126 struct io_defer_entry, list);
2128 if (req_need_defer(de->req, de->seq))
2130 list_del_init(&de->list);
2131 io_req_task_queue(de->req);
2136 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
2137 __must_hold(&ctx->completion_lock)
2139 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
2140 struct io_kiocb *req, *tmp;
2142 spin_lock_irq(&ctx->timeout_lock);
2143 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
2144 u32 events_needed, events_got;
2146 if (io_is_timeout_noseq(req))
2150 * Since seq can easily wrap around over time, subtract
2151 * the last seq at which timeouts were flushed before comparing.
2152 * Assuming not more than 2^31-1 events have happened since,
2153 * these subtractions won't have wrapped, so we can check if
2154 * target is in [last_seq, current_seq] by comparing the two.
2156 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
2157 events_got = seq - ctx->cq_last_tm_flush;
2158 if (events_got < events_needed)
2161 io_kill_timeout(req, 0);
2163 ctx->cq_last_tm_flush = seq;
2164 spin_unlock_irq(&ctx->timeout_lock);
2167 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
2169 /* order cqe stores with ring update */
2170 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
2173 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
2175 if (ctx->off_timeout_used || ctx->drain_active) {
2176 spin_lock(&ctx->completion_lock);
2177 if (ctx->off_timeout_used)
2178 io_flush_timeouts(ctx);
2179 if (ctx->drain_active)
2180 io_queue_deferred(ctx);
2181 io_commit_cqring(ctx);
2182 spin_unlock(&ctx->completion_lock);
2185 io_eventfd_signal(ctx);
2188 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
2190 struct io_rings *r = ctx->rings;
2192 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
2195 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
2197 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
2201 * writes to the cq entry need to come after reading head; the
2202 * control dependency is enough as we're using WRITE_ONCE to
2205 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
2207 struct io_rings *rings = ctx->rings;
2208 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
2209 unsigned int shift = 0;
2210 unsigned int free, queued, len;
2212 if (ctx->flags & IORING_SETUP_CQE32)
2215 /* userspace may cheat modifying the tail, be safe and do min */
2216 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2217 free = ctx->cq_entries - queued;
2218 /* we need a contiguous range, limit based on the current array offset */
2219 len = min(free, ctx->cq_entries - off);
2223 ctx->cached_cq_tail++;
2224 ctx->cqe_cached = &rings->cqes[off];
2225 ctx->cqe_sentinel = ctx->cqe_cached + len;
2227 return &rings->cqes[off << shift];
2230 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2232 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2233 struct io_uring_cqe *cqe = ctx->cqe_cached;
2235 if (ctx->flags & IORING_SETUP_CQE32) {
2236 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2241 ctx->cached_cq_tail++;
2246 return __io_get_cqe(ctx);
2249 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2251 struct io_ev_fd *ev_fd;
2255 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2256 * and eventfd_signal
2258 ev_fd = rcu_dereference(ctx->io_ev_fd);
2261 * Check again if ev_fd exists incase an io_eventfd_unregister call
2262 * completed between the NULL check of ctx->io_ev_fd at the start of
2263 * the function and rcu_read_lock.
2265 if (unlikely(!ev_fd))
2267 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2270 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2271 eventfd_signal(ev_fd->cq_ev_fd, 1);
2276 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2279 * wake_up_all() may seem excessive, but io_wake_function() and
2280 * io_should_wake() handle the termination of the loop and only
2281 * wake as many waiters as we need to.
2283 if (wq_has_sleeper(&ctx->cq_wait))
2284 wake_up_all(&ctx->cq_wait);
2288 * This should only get called when at least one event has been posted.
2289 * Some applications rely on the eventfd notification count only changing
2290 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2291 * 1:1 relationship between how many times this function is called (and
2292 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2294 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2296 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2298 __io_commit_cqring_flush(ctx);
2300 io_cqring_wake(ctx);
2303 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2305 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2307 __io_commit_cqring_flush(ctx);
2309 if (ctx->flags & IORING_SETUP_SQPOLL)
2310 io_cqring_wake(ctx);
2313 /* Returns true if there are no backlogged entries after the flush */
2314 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2316 bool all_flushed, posted;
2317 size_t cqe_size = sizeof(struct io_uring_cqe);
2319 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2322 if (ctx->flags & IORING_SETUP_CQE32)
2326 spin_lock(&ctx->completion_lock);
2327 while (!list_empty(&ctx->cq_overflow_list)) {
2328 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2329 struct io_overflow_cqe *ocqe;
2333 ocqe = list_first_entry(&ctx->cq_overflow_list,
2334 struct io_overflow_cqe, list);
2336 memcpy(cqe, &ocqe->cqe, cqe_size);
2338 io_account_cq_overflow(ctx);
2341 list_del(&ocqe->list);
2345 all_flushed = list_empty(&ctx->cq_overflow_list);
2347 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2348 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2351 io_commit_cqring(ctx);
2352 spin_unlock(&ctx->completion_lock);
2354 io_cqring_ev_posted(ctx);
2358 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2362 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2363 /* iopoll syncs against uring_lock, not completion_lock */
2364 if (ctx->flags & IORING_SETUP_IOPOLL)
2365 mutex_lock(&ctx->uring_lock);
2366 ret = __io_cqring_overflow_flush(ctx, false);
2367 if (ctx->flags & IORING_SETUP_IOPOLL)
2368 mutex_unlock(&ctx->uring_lock);
2374 static void __io_put_task(struct task_struct *task, int nr)
2376 struct io_uring_task *tctx = task->io_uring;
2378 percpu_counter_sub(&tctx->inflight, nr);
2379 if (unlikely(atomic_read(&tctx->in_idle)))
2380 wake_up(&tctx->wait);
2381 put_task_struct_many(task, nr);
2384 /* must to be called somewhat shortly after putting a request */
2385 static inline void io_put_task(struct task_struct *task, int nr)
2387 if (likely(task == current))
2388 task->io_uring->cached_refs += nr;
2390 __io_put_task(task, nr);
2393 static void io_task_refs_refill(struct io_uring_task *tctx)
2395 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2397 percpu_counter_add(&tctx->inflight, refill);
2398 refcount_add(refill, ¤t->usage);
2399 tctx->cached_refs += refill;
2402 static inline void io_get_task_refs(int nr)
2404 struct io_uring_task *tctx = current->io_uring;
2406 tctx->cached_refs -= nr;
2407 if (unlikely(tctx->cached_refs < 0))
2408 io_task_refs_refill(tctx);
2411 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2413 struct io_uring_task *tctx = task->io_uring;
2414 unsigned int refs = tctx->cached_refs;
2417 tctx->cached_refs = 0;
2418 percpu_counter_sub(&tctx->inflight, refs);
2419 put_task_struct_many(task, refs);
2423 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2424 s32 res, u32 cflags, u64 extra1,
2427 struct io_overflow_cqe *ocqe;
2428 size_t ocq_size = sizeof(struct io_overflow_cqe);
2429 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2432 ocq_size += sizeof(struct io_uring_cqe);
2434 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2435 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2438 * If we're in ring overflow flush mode, or in task cancel mode,
2439 * or cannot allocate an overflow entry, then we need to drop it
2442 io_account_cq_overflow(ctx);
2443 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2446 if (list_empty(&ctx->cq_overflow_list)) {
2447 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2448 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2451 ocqe->cqe.user_data = user_data;
2452 ocqe->cqe.res = res;
2453 ocqe->cqe.flags = cflags;
2455 ocqe->cqe.big_cqe[0] = extra1;
2456 ocqe->cqe.big_cqe[1] = extra2;
2458 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2462 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
2463 struct io_kiocb *req)
2465 struct io_uring_cqe *cqe;
2467 if (!(ctx->flags & IORING_SETUP_CQE32)) {
2468 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2469 req->cqe.res, req->cqe.flags, 0, 0);
2472 * If we can't get a cq entry, userspace overflowed the
2473 * submission (by quite a lot). Increment the overflow count in
2476 cqe = io_get_cqe(ctx);
2478 memcpy(cqe, &req->cqe, sizeof(*cqe));
2482 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2483 req->cqe.res, req->cqe.flags,
2486 u64 extra1 = 0, extra2 = 0;
2488 if (req->flags & REQ_F_CQE32_INIT) {
2489 extra1 = req->extra1;
2490 extra2 = req->extra2;
2493 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2494 req->cqe.res, req->cqe.flags, extra1, extra2);
2497 * If we can't get a cq entry, userspace overflowed the
2498 * submission (by quite a lot). Increment the overflow count in
2501 cqe = io_get_cqe(ctx);
2503 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2504 WRITE_ONCE(cqe->big_cqe[0], extra1);
2505 WRITE_ONCE(cqe->big_cqe[1], extra2);
2509 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2510 req->cqe.res, req->cqe.flags,
2515 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2516 s32 res, u32 cflags)
2518 struct io_uring_cqe *cqe;
2521 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2524 * If we can't get a cq entry, userspace overflowed the
2525 * submission (by quite a lot). Increment the overflow count in
2528 cqe = io_get_cqe(ctx);
2530 WRITE_ONCE(cqe->user_data, user_data);
2531 WRITE_ONCE(cqe->res, res);
2532 WRITE_ONCE(cqe->flags, cflags);
2534 if (ctx->flags & IORING_SETUP_CQE32) {
2535 WRITE_ONCE(cqe->big_cqe[0], 0);
2536 WRITE_ONCE(cqe->big_cqe[1], 0);
2540 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2543 static void __io_req_complete_put(struct io_kiocb *req)
2546 * If we're the last reference to this request, add to our locked
2549 if (req_ref_put_and_test(req)) {
2550 struct io_ring_ctx *ctx = req->ctx;
2552 if (req->flags & IO_REQ_LINK_FLAGS) {
2553 if (req->flags & IO_DISARM_MASK)
2554 io_disarm_next(req);
2556 io_req_task_queue(req->link);
2560 io_req_put_rsrc(req);
2562 * Selected buffer deallocation in io_clean_op() assumes that
2563 * we don't hold ->completion_lock. Clean them here to avoid
2566 io_put_kbuf_comp(req);
2567 io_dismantle_req(req);
2568 io_put_task(req->task, 1);
2569 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2570 ctx->locked_free_nr++;
2574 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2577 if (!(req->flags & REQ_F_CQE_SKIP)) {
2579 req->cqe.flags = cflags;
2580 __io_fill_cqe_req(req->ctx, req);
2582 __io_req_complete_put(req);
2585 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2587 struct io_ring_ctx *ctx = req->ctx;
2589 spin_lock(&ctx->completion_lock);
2590 __io_req_complete_post(req, res, cflags);
2591 io_commit_cqring(ctx);
2592 spin_unlock(&ctx->completion_lock);
2593 io_cqring_ev_posted(ctx);
2596 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2600 req->cqe.flags = cflags;
2601 req->flags |= REQ_F_COMPLETE_INLINE;
2604 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2605 s32 res, u32 cflags)
2607 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2608 io_req_complete_state(req, res, cflags);
2610 io_req_complete_post(req, res, cflags);
2613 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2617 __io_req_complete(req, 0, res, 0);
2620 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2623 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2627 * Don't initialise the fields below on every allocation, but do that in
2628 * advance and keep them valid across allocations.
2630 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2634 req->async_data = NULL;
2635 /* not necessary, but safer to zero */
2639 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2640 struct io_submit_state *state)
2642 spin_lock(&ctx->completion_lock);
2643 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2644 ctx->locked_free_nr = 0;
2645 spin_unlock(&ctx->completion_lock);
2648 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2650 return !ctx->submit_state.free_list.next;
2654 * A request might get retired back into the request caches even before opcode
2655 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2656 * Because of that, io_alloc_req() should be called only under ->uring_lock
2657 * and with extra caution to not get a request that is still worked on.
2659 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2660 __must_hold(&ctx->uring_lock)
2662 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2663 void *reqs[IO_REQ_ALLOC_BATCH];
2667 * If we have more than a batch's worth of requests in our IRQ side
2668 * locked cache, grab the lock and move them over to our submission
2671 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2672 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2673 if (!io_req_cache_empty(ctx))
2677 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2680 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2681 * retry single alloc to be on the safe side.
2683 if (unlikely(ret <= 0)) {
2684 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2690 percpu_ref_get_many(&ctx->refs, ret);
2691 for (i = 0; i < ret; i++) {
2692 struct io_kiocb *req = reqs[i];
2694 io_preinit_req(req, ctx);
2695 io_req_add_to_cache(req, ctx);
2700 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2702 if (unlikely(io_req_cache_empty(ctx)))
2703 return __io_alloc_req_refill(ctx);
2707 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2709 struct io_wq_work_node *node;
2711 node = wq_stack_extract(&ctx->submit_state.free_list);
2712 return container_of(node, struct io_kiocb, comp_list);
2715 static inline void io_put_file(struct file *file)
2721 static inline void io_dismantle_req(struct io_kiocb *req)
2723 unsigned int flags = req->flags;
2725 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2727 if (!(flags & REQ_F_FIXED_FILE))
2728 io_put_file(req->file);
2731 static __cold void io_free_req(struct io_kiocb *req)
2733 struct io_ring_ctx *ctx = req->ctx;
2735 io_req_put_rsrc(req);
2736 io_dismantle_req(req);
2737 io_put_task(req->task, 1);
2739 spin_lock(&ctx->completion_lock);
2740 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2741 ctx->locked_free_nr++;
2742 spin_unlock(&ctx->completion_lock);
2745 static inline void io_remove_next_linked(struct io_kiocb *req)
2747 struct io_kiocb *nxt = req->link;
2749 req->link = nxt->link;
2753 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2754 __must_hold(&req->ctx->completion_lock)
2755 __must_hold(&req->ctx->timeout_lock)
2757 struct io_kiocb *link = req->link;
2759 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2760 struct io_timeout_data *io = link->async_data;
2762 io_remove_next_linked(req);
2763 link->timeout.head = NULL;
2764 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2765 list_del(&link->timeout.list);
2772 static void io_fail_links(struct io_kiocb *req)
2773 __must_hold(&req->ctx->completion_lock)
2775 struct io_kiocb *nxt, *link = req->link;
2776 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2780 long res = -ECANCELED;
2782 if (link->flags & REQ_F_FAIL)
2783 res = link->cqe.res;
2788 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2792 link->flags |= REQ_F_CQE_SKIP;
2794 link->flags &= ~REQ_F_CQE_SKIP;
2795 __io_req_complete_post(link, res, 0);
2800 static bool io_disarm_next(struct io_kiocb *req)
2801 __must_hold(&req->ctx->completion_lock)
2803 struct io_kiocb *link = NULL;
2804 bool posted = false;
2806 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2808 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2809 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2810 io_remove_next_linked(req);
2811 io_req_tw_post_queue(link, -ECANCELED, 0);
2814 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2815 struct io_ring_ctx *ctx = req->ctx;
2817 spin_lock_irq(&ctx->timeout_lock);
2818 link = io_disarm_linked_timeout(req);
2819 spin_unlock_irq(&ctx->timeout_lock);
2822 io_req_tw_post_queue(link, -ECANCELED, 0);
2825 if (unlikely((req->flags & REQ_F_FAIL) &&
2826 !(req->flags & REQ_F_HARDLINK))) {
2827 posted |= (req->link != NULL);
2833 static void __io_req_find_next_prep(struct io_kiocb *req)
2835 struct io_ring_ctx *ctx = req->ctx;
2838 spin_lock(&ctx->completion_lock);
2839 posted = io_disarm_next(req);
2840 io_commit_cqring(ctx);
2841 spin_unlock(&ctx->completion_lock);
2843 io_cqring_ev_posted(ctx);
2846 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2848 struct io_kiocb *nxt;
2851 * If LINK is set, we have dependent requests in this chain. If we
2852 * didn't fail this request, queue the first one up, moving any other
2853 * dependencies to the next request. In case of failure, fail the rest
2856 if (unlikely(req->flags & IO_DISARM_MASK))
2857 __io_req_find_next_prep(req);
2863 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2867 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2868 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2870 io_submit_flush_completions(ctx);
2871 mutex_unlock(&ctx->uring_lock);
2874 percpu_ref_put(&ctx->refs);
2877 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2879 io_commit_cqring(ctx);
2880 spin_unlock(&ctx->completion_lock);
2881 io_cqring_ev_posted(ctx);
2884 static void handle_prev_tw_list(struct io_wq_work_node *node,
2885 struct io_ring_ctx **ctx, bool *uring_locked)
2887 if (*ctx && !*uring_locked)
2888 spin_lock(&(*ctx)->completion_lock);
2891 struct io_wq_work_node *next = node->next;
2892 struct io_kiocb *req = container_of(node, struct io_kiocb,
2895 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2897 if (req->ctx != *ctx) {
2898 if (unlikely(!*uring_locked && *ctx))
2899 ctx_commit_and_unlock(*ctx);
2901 ctx_flush_and_put(*ctx, uring_locked);
2903 /* if not contended, grab and improve batching */
2904 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2905 percpu_ref_get(&(*ctx)->refs);
2906 if (unlikely(!*uring_locked))
2907 spin_lock(&(*ctx)->completion_lock);
2909 if (likely(*uring_locked))
2910 req->io_task_work.func(req, uring_locked);
2912 __io_req_complete_post(req, req->cqe.res,
2913 io_put_kbuf_comp(req));
2917 if (unlikely(!*uring_locked))
2918 ctx_commit_and_unlock(*ctx);
2921 static void handle_tw_list(struct io_wq_work_node *node,
2922 struct io_ring_ctx **ctx, bool *locked)
2925 struct io_wq_work_node *next = node->next;
2926 struct io_kiocb *req = container_of(node, struct io_kiocb,
2929 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2931 if (req->ctx != *ctx) {
2932 ctx_flush_and_put(*ctx, locked);
2934 /* if not contended, grab and improve batching */
2935 *locked = mutex_trylock(&(*ctx)->uring_lock);
2936 percpu_ref_get(&(*ctx)->refs);
2938 req->io_task_work.func(req, locked);
2943 static void tctx_task_work(struct callback_head *cb)
2945 bool uring_locked = false;
2946 struct io_ring_ctx *ctx = NULL;
2947 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2951 struct io_wq_work_node *node1, *node2;
2953 spin_lock_irq(&tctx->task_lock);
2954 node1 = tctx->prio_task_list.first;
2955 node2 = tctx->task_list.first;
2956 INIT_WQ_LIST(&tctx->task_list);
2957 INIT_WQ_LIST(&tctx->prio_task_list);
2958 if (!node2 && !node1)
2959 tctx->task_running = false;
2960 spin_unlock_irq(&tctx->task_lock);
2961 if (!node2 && !node1)
2965 handle_prev_tw_list(node1, &ctx, &uring_locked);
2967 handle_tw_list(node2, &ctx, &uring_locked);
2970 if (data_race(!tctx->task_list.first) &&
2971 data_race(!tctx->prio_task_list.first) && uring_locked)
2972 io_submit_flush_completions(ctx);
2975 ctx_flush_and_put(ctx, &uring_locked);
2977 /* relaxed read is enough as only the task itself sets ->in_idle */
2978 if (unlikely(atomic_read(&tctx->in_idle)))
2979 io_uring_drop_tctx_refs(current);
2982 static void __io_req_task_work_add(struct io_kiocb *req,
2983 struct io_uring_task *tctx,
2984 struct io_wq_work_list *list)
2986 struct io_ring_ctx *ctx = req->ctx;
2987 struct io_wq_work_node *node;
2988 unsigned long flags;
2991 spin_lock_irqsave(&tctx->task_lock, flags);
2992 wq_list_add_tail(&req->io_task_work.node, list);
2993 running = tctx->task_running;
2995 tctx->task_running = true;
2996 spin_unlock_irqrestore(&tctx->task_lock, flags);
2998 /* task_work already pending, we're done */
3002 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
3003 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
3005 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
3008 spin_lock_irqsave(&tctx->task_lock, flags);
3009 tctx->task_running = false;
3010 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
3011 spin_unlock_irqrestore(&tctx->task_lock, flags);
3014 req = container_of(node, struct io_kiocb, io_task_work.node);
3016 if (llist_add(&req->io_task_work.fallback_node,
3017 &req->ctx->fallback_llist))
3018 schedule_delayed_work(&req->ctx->fallback_work, 1);
3022 static void io_req_task_work_add(struct io_kiocb *req)
3024 struct io_uring_task *tctx = req->task->io_uring;
3026 __io_req_task_work_add(req, tctx, &tctx->task_list);
3029 static void io_req_task_prio_work_add(struct io_kiocb *req)
3031 struct io_uring_task *tctx = req->task->io_uring;
3033 if (req->ctx->flags & IORING_SETUP_SQPOLL)
3034 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
3036 __io_req_task_work_add(req, tctx, &tctx->task_list);
3039 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
3041 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
3044 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
3047 req->cqe.flags = cflags;
3048 req->io_task_work.func = io_req_tw_post;
3049 io_req_task_work_add(req);
3052 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
3054 /* not needed for normal modes, but SQPOLL depends on it */
3055 io_tw_lock(req->ctx, locked);
3056 io_req_complete_failed(req, req->cqe.res);
3059 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
3061 io_tw_lock(req->ctx, locked);
3062 /* req->task == current here, checking PF_EXITING is safe */
3063 if (likely(!(req->task->flags & PF_EXITING)))
3066 io_req_complete_failed(req, -EFAULT);
3069 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
3072 req->io_task_work.func = io_req_task_cancel;
3073 io_req_task_work_add(req);
3076 static void io_req_task_queue(struct io_kiocb *req)
3078 req->io_task_work.func = io_req_task_submit;
3079 io_req_task_work_add(req);
3082 static void io_req_task_queue_reissue(struct io_kiocb *req)
3084 req->io_task_work.func = io_queue_iowq;
3085 io_req_task_work_add(req);
3088 static void io_queue_next(struct io_kiocb *req)
3090 struct io_kiocb *nxt = io_req_find_next(req);
3093 io_req_task_queue(nxt);
3096 static void io_free_batch_list(struct io_ring_ctx *ctx,
3097 struct io_wq_work_node *node)
3098 __must_hold(&ctx->uring_lock)
3100 struct task_struct *task = NULL;
3104 struct io_kiocb *req = container_of(node, struct io_kiocb,
3107 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
3108 if (req->flags & REQ_F_REFCOUNT) {
3109 node = req->comp_list.next;
3110 if (!req_ref_put_and_test(req))
3113 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3114 struct async_poll *apoll = req->apoll;
3116 if (apoll->double_poll)
3117 kfree(apoll->double_poll);
3118 list_add(&apoll->poll.wait.entry,
3120 req->flags &= ~REQ_F_POLLED;
3122 if (req->flags & IO_REQ_LINK_FLAGS)
3124 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
3127 if (!(req->flags & REQ_F_FIXED_FILE))
3128 io_put_file(req->file);
3130 io_req_put_rsrc_locked(req, ctx);
3132 if (req->task != task) {
3134 io_put_task(task, task_refs);
3139 node = req->comp_list.next;
3140 io_req_add_to_cache(req, ctx);
3144 io_put_task(task, task_refs);
3147 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
3148 __must_hold(&ctx->uring_lock)
3150 struct io_wq_work_node *node, *prev;
3151 struct io_submit_state *state = &ctx->submit_state;
3153 if (state->flush_cqes) {
3154 spin_lock(&ctx->completion_lock);
3155 wq_list_for_each(node, prev, &state->compl_reqs) {
3156 struct io_kiocb *req = container_of(node, struct io_kiocb,
3159 if (!(req->flags & REQ_F_CQE_SKIP))
3160 __io_fill_cqe_req(ctx, req);
3163 io_commit_cqring(ctx);
3164 spin_unlock(&ctx->completion_lock);
3165 io_cqring_ev_posted(ctx);
3166 state->flush_cqes = false;
3169 io_free_batch_list(ctx, state->compl_reqs.first);
3170 INIT_WQ_LIST(&state->compl_reqs);
3174 * Drop reference to request, return next in chain (if there is one) if this
3175 * was the last reference to this request.
3177 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
3179 struct io_kiocb *nxt = NULL;
3181 if (req_ref_put_and_test(req)) {
3182 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
3183 nxt = io_req_find_next(req);
3189 static inline void io_put_req(struct io_kiocb *req)
3191 if (req_ref_put_and_test(req)) {
3197 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
3199 /* See comment at the top of this file */
3201 return __io_cqring_events(ctx);
3204 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
3206 struct io_rings *rings = ctx->rings;
3208 /* make sure SQ entry isn't read before tail */
3209 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3212 static inline bool io_run_task_work(void)
3214 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3215 __set_current_state(TASK_RUNNING);
3216 clear_notify_signal();
3217 if (task_work_pending(current))
3225 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3227 struct io_wq_work_node *pos, *start, *prev;
3228 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3229 DEFINE_IO_COMP_BATCH(iob);
3233 * Only spin for completions if we don't have multiple devices hanging
3234 * off our complete list.
3236 if (ctx->poll_multi_queue || force_nonspin)
3237 poll_flags |= BLK_POLL_ONESHOT;
3239 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3240 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3241 struct kiocb *kiocb = &req->rw.kiocb;
3245 * Move completed and retryable entries to our local lists.
3246 * If we find a request that requires polling, break out
3247 * and complete those lists first, if we have entries there.
3249 if (READ_ONCE(req->iopoll_completed))
3252 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3253 if (unlikely(ret < 0))
3256 poll_flags |= BLK_POLL_ONESHOT;
3258 /* iopoll may have completed current req */
3259 if (!rq_list_empty(iob.req_list) ||
3260 READ_ONCE(req->iopoll_completed))
3264 if (!rq_list_empty(iob.req_list))
3270 wq_list_for_each_resume(pos, prev) {
3271 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3273 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3274 if (!smp_load_acquire(&req->iopoll_completed))
3277 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3280 req->cqe.flags = io_put_kbuf(req, 0);
3281 __io_fill_cqe_req(req->ctx, req);
3284 if (unlikely(!nr_events))
3287 io_commit_cqring(ctx);
3288 io_cqring_ev_posted_iopoll(ctx);
3289 pos = start ? start->next : ctx->iopoll_list.first;
3290 wq_list_cut(&ctx->iopoll_list, prev, start);
3291 io_free_batch_list(ctx, pos);
3296 * We can't just wait for polled events to come to us, we have to actively
3297 * find and complete them.
3299 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3301 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3304 mutex_lock(&ctx->uring_lock);
3305 while (!wq_list_empty(&ctx->iopoll_list)) {
3306 /* let it sleep and repeat later if can't complete a request */
3307 if (io_do_iopoll(ctx, true) == 0)
3310 * Ensure we allow local-to-the-cpu processing to take place,
3311 * in this case we need to ensure that we reap all events.
3312 * Also let task_work, etc. to progress by releasing the mutex
3314 if (need_resched()) {
3315 mutex_unlock(&ctx->uring_lock);
3317 mutex_lock(&ctx->uring_lock);
3320 mutex_unlock(&ctx->uring_lock);
3323 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3325 unsigned int nr_events = 0;
3327 unsigned long check_cq;
3330 * Don't enter poll loop if we already have events pending.
3331 * If we do, we can potentially be spinning for commands that
3332 * already triggered a CQE (eg in error).
3334 check_cq = READ_ONCE(ctx->check_cq);
3335 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3336 __io_cqring_overflow_flush(ctx, false);
3337 if (io_cqring_events(ctx))
3341 * Similarly do not spin if we have not informed the user of any
3344 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3349 * If a submit got punted to a workqueue, we can have the
3350 * application entering polling for a command before it gets
3351 * issued. That app will hold the uring_lock for the duration
3352 * of the poll right here, so we need to take a breather every
3353 * now and then to ensure that the issue has a chance to add
3354 * the poll to the issued list. Otherwise we can spin here
3355 * forever, while the workqueue is stuck trying to acquire the
3358 if (wq_list_empty(&ctx->iopoll_list)) {
3359 u32 tail = ctx->cached_cq_tail;
3361 mutex_unlock(&ctx->uring_lock);
3363 mutex_lock(&ctx->uring_lock);
3365 /* some requests don't go through iopoll_list */
3366 if (tail != ctx->cached_cq_tail ||
3367 wq_list_empty(&ctx->iopoll_list))
3370 ret = io_do_iopoll(ctx, !min);
3375 } while (nr_events < min && !need_resched());
3380 static void kiocb_end_write(struct io_kiocb *req)
3383 * Tell lockdep we inherited freeze protection from submission
3386 if (req->flags & REQ_F_ISREG) {
3387 struct super_block *sb = file_inode(req->file)->i_sb;
3389 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3395 static bool io_resubmit_prep(struct io_kiocb *req)
3397 struct io_async_rw *rw = req->async_data;
3399 if (!req_has_async_data(req))
3400 return !io_req_prep_async(req);
3401 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3405 static bool io_rw_should_reissue(struct io_kiocb *req)
3407 umode_t mode = file_inode(req->file)->i_mode;
3408 struct io_ring_ctx *ctx = req->ctx;
3410 if (!S_ISBLK(mode) && !S_ISREG(mode))
3412 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3413 !(ctx->flags & IORING_SETUP_IOPOLL)))
3416 * If ref is dying, we might be running poll reap from the exit work.
3417 * Don't attempt to reissue from that path, just let it fail with
3420 if (percpu_ref_is_dying(&ctx->refs))
3423 * Play it safe and assume not safe to re-import and reissue if we're
3424 * not in the original thread group (or in task context).
3426 if (!same_thread_group(req->task, current) || !in_task())
3431 static bool io_resubmit_prep(struct io_kiocb *req)
3435 static bool io_rw_should_reissue(struct io_kiocb *req)
3441 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3443 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3444 kiocb_end_write(req);
3445 fsnotify_modify(req->file);
3447 fsnotify_access(req->file);
3449 if (unlikely(res != req->cqe.res)) {
3450 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3451 io_rw_should_reissue(req)) {
3452 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3461 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3463 int res = req->cqe.res;
3466 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3467 io_req_add_compl_list(req);
3469 io_req_complete_post(req, res,
3470 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3474 static void __io_complete_rw(struct io_kiocb *req, long res,
3475 unsigned int issue_flags)
3477 if (__io_complete_rw_common(req, res))
3479 __io_req_complete(req, issue_flags, req->cqe.res,
3480 io_put_kbuf(req, issue_flags));
3483 static void io_complete_rw(struct kiocb *kiocb, long res)
3485 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3487 if (__io_complete_rw_common(req, res))
3490 req->io_task_work.func = io_req_task_complete;
3491 io_req_task_prio_work_add(req);
3494 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3496 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3498 if (kiocb->ki_flags & IOCB_WRITE)
3499 kiocb_end_write(req);
3500 if (unlikely(res != req->cqe.res)) {
3501 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3502 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3508 /* order with io_iopoll_complete() checking ->iopoll_completed */
3509 smp_store_release(&req->iopoll_completed, 1);
3513 * After the iocb has been issued, it's safe to be found on the poll list.
3514 * Adding the kiocb to the list AFTER submission ensures that we don't
3515 * find it from a io_do_iopoll() thread before the issuer is done
3516 * accessing the kiocb cookie.
3518 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3520 struct io_ring_ctx *ctx = req->ctx;
3521 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3523 /* workqueue context doesn't hold uring_lock, grab it now */
3524 if (unlikely(needs_lock))
3525 mutex_lock(&ctx->uring_lock);
3528 * Track whether we have multiple files in our lists. This will impact
3529 * how we do polling eventually, not spinning if we're on potentially
3530 * different devices.
3532 if (wq_list_empty(&ctx->iopoll_list)) {
3533 ctx->poll_multi_queue = false;
3534 } else if (!ctx->poll_multi_queue) {
3535 struct io_kiocb *list_req;
3537 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3539 if (list_req->file != req->file)
3540 ctx->poll_multi_queue = true;
3544 * For fast devices, IO may have already completed. If it has, add
3545 * it to the front so we find it first.
3547 if (READ_ONCE(req->iopoll_completed))
3548 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3550 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3552 if (unlikely(needs_lock)) {
3554 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3555 * in sq thread task context or in io worker task context. If
3556 * current task context is sq thread, we don't need to check
3557 * whether should wake up sq thread.
3559 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3560 wq_has_sleeper(&ctx->sq_data->wait))
3561 wake_up(&ctx->sq_data->wait);
3563 mutex_unlock(&ctx->uring_lock);
3567 static bool io_bdev_nowait(struct block_device *bdev)
3569 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3573 * If we tracked the file through the SCM inflight mechanism, we could support
3574 * any file. For now, just ensure that anything potentially problematic is done
3577 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3579 if (S_ISBLK(mode)) {
3580 if (IS_ENABLED(CONFIG_BLOCK) &&
3581 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3587 if (S_ISREG(mode)) {
3588 if (IS_ENABLED(CONFIG_BLOCK) &&
3589 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3590 file->f_op != &io_uring_fops)
3595 /* any ->read/write should understand O_NONBLOCK */
3596 if (file->f_flags & O_NONBLOCK)
3598 return file->f_mode & FMODE_NOWAIT;
3602 * If we tracked the file through the SCM inflight mechanism, we could support
3603 * any file. For now, just ensure that anything potentially problematic is done
3606 static unsigned int io_file_get_flags(struct file *file)
3608 umode_t mode = file_inode(file)->i_mode;
3609 unsigned int res = 0;
3613 if (__io_file_supports_nowait(file, mode))
3615 if (io_file_need_scm(file))
3620 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3622 return req->flags & REQ_F_SUPPORT_NOWAIT;
3625 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3627 struct kiocb *kiocb = &req->rw.kiocb;
3631 kiocb->ki_pos = READ_ONCE(sqe->off);
3632 /* used for fixed read/write too - just read unconditionally */
3633 req->buf_index = READ_ONCE(sqe->buf_index);
3635 if (req->opcode == IORING_OP_READ_FIXED ||
3636 req->opcode == IORING_OP_WRITE_FIXED) {
3637 struct io_ring_ctx *ctx = req->ctx;
3640 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3642 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3643 req->imu = ctx->user_bufs[index];
3644 io_req_set_rsrc_node(req, ctx, 0);
3647 ioprio = READ_ONCE(sqe->ioprio);
3649 ret = ioprio_check_cap(ioprio);
3653 kiocb->ki_ioprio = ioprio;
3655 kiocb->ki_ioprio = get_current_ioprio();
3658 req->rw.addr = READ_ONCE(sqe->addr);
3659 req->rw.len = READ_ONCE(sqe->len);
3660 req->rw.flags = READ_ONCE(sqe->rw_flags);
3664 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3670 case -ERESTARTNOINTR:
3671 case -ERESTARTNOHAND:
3672 case -ERESTART_RESTARTBLOCK:
3674 * We can't just restart the syscall, since previously
3675 * submitted sqes may already be in progress. Just fail this
3681 kiocb->ki_complete(kiocb, ret);
3685 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3687 struct kiocb *kiocb = &req->rw.kiocb;
3689 if (kiocb->ki_pos != -1)
3690 return &kiocb->ki_pos;
3692 if (!(req->file->f_mode & FMODE_STREAM)) {
3693 req->flags |= REQ_F_CUR_POS;
3694 kiocb->ki_pos = req->file->f_pos;
3695 return &kiocb->ki_pos;
3702 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3703 unsigned int issue_flags)
3705 struct io_async_rw *io = req->async_data;
3707 /* add previously done IO, if any */
3708 if (req_has_async_data(req) && io->bytes_done > 0) {
3710 ret = io->bytes_done;
3712 ret += io->bytes_done;
3715 if (req->flags & REQ_F_CUR_POS)
3716 req->file->f_pos = req->rw.kiocb.ki_pos;
3717 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3718 __io_complete_rw(req, ret, issue_flags);
3720 io_rw_done(&req->rw.kiocb, ret);
3722 if (req->flags & REQ_F_REISSUE) {
3723 req->flags &= ~REQ_F_REISSUE;
3724 if (io_resubmit_prep(req))
3725 io_req_task_queue_reissue(req);
3727 io_req_task_queue_fail(req, ret);
3731 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3732 struct io_mapped_ubuf *imu)
3734 size_t len = req->rw.len;
3735 u64 buf_end, buf_addr = req->rw.addr;
3738 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3740 /* not inside the mapped region */
3741 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3745 * May not be a start of buffer, set size appropriately
3746 * and advance us to the beginning.
3748 offset = buf_addr - imu->ubuf;
3749 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3753 * Don't use iov_iter_advance() here, as it's really slow for
3754 * using the latter parts of a big fixed buffer - it iterates
3755 * over each segment manually. We can cheat a bit here, because
3758 * 1) it's a BVEC iter, we set it up
3759 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3760 * first and last bvec
3762 * So just find our index, and adjust the iterator afterwards.
3763 * If the offset is within the first bvec (or the whole first
3764 * bvec, just use iov_iter_advance(). This makes it easier
3765 * since we can just skip the first segment, which may not
3766 * be PAGE_SIZE aligned.
3768 const struct bio_vec *bvec = imu->bvec;
3770 if (offset <= bvec->bv_len) {
3771 iov_iter_advance(iter, offset);
3773 unsigned long seg_skip;
3775 /* skip first vec */
3776 offset -= bvec->bv_len;
3777 seg_skip = 1 + (offset >> PAGE_SHIFT);
3779 iter->bvec = bvec + seg_skip;
3780 iter->nr_segs -= seg_skip;
3781 iter->count -= bvec->bv_len + offset;
3782 iter->iov_offset = offset & ~PAGE_MASK;
3789 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3790 unsigned int issue_flags)
3792 if (WARN_ON_ONCE(!req->imu))
3794 return __io_import_fixed(req, rw, iter, req->imu);
3797 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3798 struct io_buffer_list *bl, unsigned int bgid)
3801 if (bgid < BGID_ARRAY)
3804 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3807 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3808 struct io_buffer_list *bl)
3810 if (!list_empty(&bl->buf_list)) {
3811 struct io_buffer *kbuf;
3813 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3814 list_del(&kbuf->list);
3815 if (*len > kbuf->len)
3817 req->flags |= REQ_F_BUFFER_SELECTED;
3819 req->buf_index = kbuf->bid;
3820 return u64_to_user_ptr(kbuf->addr);
3825 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3826 struct io_buffer_list *bl,
3827 unsigned int issue_flags)
3829 struct io_uring_buf_ring *br = bl->buf_ring;
3830 struct io_uring_buf *buf;
3831 __u16 head = bl->head;
3833 if (unlikely(smp_load_acquire(&br->tail) == head))
3837 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3838 buf = &br->bufs[head];
3840 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3841 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3842 buf = page_address(bl->buf_pages[index]);
3845 if (*len > buf->len)
3847 req->flags |= REQ_F_BUFFER_RING;
3849 req->buf_index = buf->bid;
3851 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3853 * If we came in unlocked, we have no choice but to consume the
3854 * buffer here. This does mean it'll be pinned until the IO
3855 * completes. But coming in unlocked means we're in io-wq
3856 * context, hence there should be no further retry. For the
3857 * locked case, the caller must ensure to call the commit when
3858 * the transfer completes (or if we get -EAGAIN and must poll
3861 req->buf_list = NULL;
3864 return u64_to_user_ptr(buf->addr);
3867 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3868 unsigned int issue_flags)
3870 struct io_ring_ctx *ctx = req->ctx;
3871 struct io_buffer_list *bl;
3872 void __user *ret = NULL;
3874 io_ring_submit_lock(req->ctx, issue_flags);
3876 bl = io_buffer_get_list(ctx, req->buf_index);
3878 if (bl->buf_nr_pages)
3879 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3881 ret = io_provided_buffer_select(req, len, bl);
3883 io_ring_submit_unlock(req->ctx, issue_flags);
3887 #ifdef CONFIG_COMPAT
3888 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3889 unsigned int issue_flags)
3891 struct compat_iovec __user *uiov;
3892 compat_ssize_t clen;
3896 uiov = u64_to_user_ptr(req->rw.addr);
3897 if (!access_ok(uiov, sizeof(*uiov)))
3899 if (__get_user(clen, &uiov->iov_len))
3905 buf = io_buffer_select(req, &len, issue_flags);
3908 req->rw.addr = (unsigned long) buf;
3909 iov[0].iov_base = buf;
3910 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3915 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3916 unsigned int issue_flags)
3918 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3922 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3925 len = iov[0].iov_len;
3928 buf = io_buffer_select(req, &len, issue_flags);
3931 req->rw.addr = (unsigned long) buf;
3932 iov[0].iov_base = buf;
3933 req->rw.len = iov[0].iov_len = len;
3937 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3938 unsigned int issue_flags)
3940 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3941 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3942 iov[0].iov_len = req->rw.len;
3945 if (req->rw.len != 1)
3948 #ifdef CONFIG_COMPAT
3949 if (req->ctx->compat)
3950 return io_compat_import(req, iov, issue_flags);
3953 return __io_iov_buffer_select(req, iov, issue_flags);
3956 static inline bool io_do_buffer_select(struct io_kiocb *req)
3958 if (!(req->flags & REQ_F_BUFFER_SELECT))
3960 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3963 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3964 struct io_rw_state *s,
3965 unsigned int issue_flags)
3967 struct iov_iter *iter = &s->iter;
3968 u8 opcode = req->opcode;
3969 struct iovec *iovec;
3974 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3975 ret = io_import_fixed(req, rw, iter, issue_flags);
3977 return ERR_PTR(ret);
3981 buf = u64_to_user_ptr(req->rw.addr);
3982 sqe_len = req->rw.len;
3984 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3985 if (io_do_buffer_select(req)) {
3986 buf = io_buffer_select(req, &sqe_len, issue_flags);
3988 return ERR_PTR(-ENOBUFS);
3989 req->rw.addr = (unsigned long) buf;
3990 req->rw.len = sqe_len;
3993 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3995 return ERR_PTR(ret);
3999 iovec = s->fast_iov;
4000 if (req->flags & REQ_F_BUFFER_SELECT) {
4001 ret = io_iov_buffer_select(req, iovec, issue_flags);
4003 return ERR_PTR(ret);
4004 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
4008 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
4010 if (unlikely(ret < 0))
4011 return ERR_PTR(ret);
4015 static inline int io_import_iovec(int rw, struct io_kiocb *req,
4016 struct iovec **iovec, struct io_rw_state *s,
4017 unsigned int issue_flags)
4019 *iovec = __io_import_iovec(rw, req, s, issue_flags);
4020 if (unlikely(IS_ERR(*iovec)))
4021 return PTR_ERR(*iovec);
4023 iov_iter_save_state(&s->iter, &s->iter_state);
4027 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
4029 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
4033 * For files that don't have ->read_iter() and ->write_iter(), handle them
4034 * by looping over ->read() or ->write() manually.
4036 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
4038 struct kiocb *kiocb = &req->rw.kiocb;
4039 struct file *file = req->file;
4044 * Don't support polled IO through this interface, and we can't
4045 * support non-blocking either. For the latter, this just causes
4046 * the kiocb to be handled from an async context.
4048 if (kiocb->ki_flags & IOCB_HIPRI)
4050 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
4051 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
4054 ppos = io_kiocb_ppos(kiocb);
4056 while (iov_iter_count(iter)) {
4060 if (!iov_iter_is_bvec(iter)) {
4061 iovec = iov_iter_iovec(iter);
4063 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
4064 iovec.iov_len = req->rw.len;
4068 nr = file->f_op->read(file, iovec.iov_base,
4069 iovec.iov_len, ppos);
4071 nr = file->f_op->write(file, iovec.iov_base,
4072 iovec.iov_len, ppos);
4081 if (!iov_iter_is_bvec(iter)) {
4082 iov_iter_advance(iter, nr);
4089 if (nr != iovec.iov_len)
4096 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
4097 const struct iovec *fast_iov, struct iov_iter *iter)
4099 struct io_async_rw *rw = req->async_data;
4101 memcpy(&rw->s.iter, iter, sizeof(*iter));
4102 rw->free_iovec = iovec;
4104 /* can only be fixed buffers, no need to do anything */
4105 if (iov_iter_is_bvec(iter))
4108 unsigned iov_off = 0;
4110 rw->s.iter.iov = rw->s.fast_iov;
4111 if (iter->iov != fast_iov) {
4112 iov_off = iter->iov - fast_iov;
4113 rw->s.iter.iov += iov_off;
4115 if (rw->s.fast_iov != fast_iov)
4116 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
4117 sizeof(struct iovec) * iter->nr_segs);
4119 req->flags |= REQ_F_NEED_CLEANUP;
4123 static inline bool io_alloc_async_data(struct io_kiocb *req)
4125 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
4126 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
4127 if (req->async_data) {
4128 req->flags |= REQ_F_ASYNC_DATA;
4134 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
4135 struct io_rw_state *s, bool force)
4137 if (!force && !io_op_defs[req->opcode].needs_async_setup)
4139 if (!req_has_async_data(req)) {
4140 struct io_async_rw *iorw;
4142 if (io_alloc_async_data(req)) {
4147 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
4148 iorw = req->async_data;
4149 /* we've copied and mapped the iter, ensure state is saved */
4150 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
4155 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
4157 struct io_async_rw *iorw = req->async_data;
4161 /* submission path, ->uring_lock should already be taken */
4162 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
4163 if (unlikely(ret < 0))
4166 iorw->bytes_done = 0;
4167 iorw->free_iovec = iov;
4169 req->flags |= REQ_F_NEED_CLEANUP;
4173 static int io_readv_prep_async(struct io_kiocb *req)
4175 return io_rw_prep_async(req, READ);
4178 static int io_writev_prep_async(struct io_kiocb *req)
4180 return io_rw_prep_async(req, WRITE);
4184 * This is our waitqueue callback handler, registered through __folio_lock_async()
4185 * when we initially tried to do the IO with the iocb armed our waitqueue.
4186 * This gets called when the page is unlocked, and we generally expect that to
4187 * happen when the page IO is completed and the page is now uptodate. This will
4188 * queue a task_work based retry of the operation, attempting to copy the data
4189 * again. If the latter fails because the page was NOT uptodate, then we will
4190 * do a thread based blocking retry of the operation. That's the unexpected
4193 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
4194 int sync, void *arg)
4196 struct wait_page_queue *wpq;
4197 struct io_kiocb *req = wait->private;
4198 struct wait_page_key *key = arg;
4200 wpq = container_of(wait, struct wait_page_queue, wait);
4202 if (!wake_page_match(wpq, key))
4205 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
4206 list_del_init(&wait->entry);
4207 io_req_task_queue(req);
4212 * This controls whether a given IO request should be armed for async page
4213 * based retry. If we return false here, the request is handed to the async
4214 * worker threads for retry. If we're doing buffered reads on a regular file,
4215 * we prepare a private wait_page_queue entry and retry the operation. This
4216 * will either succeed because the page is now uptodate and unlocked, or it
4217 * will register a callback when the page is unlocked at IO completion. Through
4218 * that callback, io_uring uses task_work to setup a retry of the operation.
4219 * That retry will attempt the buffered read again. The retry will generally
4220 * succeed, or in rare cases where it fails, we then fall back to using the
4221 * async worker threads for a blocking retry.
4223 static bool io_rw_should_retry(struct io_kiocb *req)
4225 struct io_async_rw *rw = req->async_data;
4226 struct wait_page_queue *wait = &rw->wpq;
4227 struct kiocb *kiocb = &req->rw.kiocb;
4229 /* never retry for NOWAIT, we just complete with -EAGAIN */
4230 if (req->flags & REQ_F_NOWAIT)
4233 /* Only for buffered IO */
4234 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4238 * just use poll if we can, and don't attempt if the fs doesn't
4239 * support callback based unlocks
4241 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4244 wait->wait.func = io_async_buf_func;
4245 wait->wait.private = req;
4246 wait->wait.flags = 0;
4247 INIT_LIST_HEAD(&wait->wait.entry);
4248 kiocb->ki_flags |= IOCB_WAITQ;
4249 kiocb->ki_flags &= ~IOCB_NOWAIT;
4250 kiocb->ki_waitq = wait;
4254 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4256 if (likely(req->file->f_op->read_iter))
4257 return call_read_iter(req->file, &req->rw.kiocb, iter);
4258 else if (req->file->f_op->read)
4259 return loop_rw_iter(READ, req, iter);
4264 static bool need_read_all(struct io_kiocb *req)
4266 return req->flags & REQ_F_ISREG ||
4267 S_ISBLK(file_inode(req->file)->i_mode);
4270 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4272 struct kiocb *kiocb = &req->rw.kiocb;
4273 struct io_ring_ctx *ctx = req->ctx;
4274 struct file *file = req->file;
4277 if (unlikely(!file || !(file->f_mode & mode)))
4280 if (!io_req_ffs_set(req))
4281 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4283 kiocb->ki_flags = iocb_flags(file);
4284 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4289 * If the file is marked O_NONBLOCK, still allow retry for it if it
4290 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4291 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4293 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4294 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4295 req->flags |= REQ_F_NOWAIT;
4297 if (ctx->flags & IORING_SETUP_IOPOLL) {
4298 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4301 kiocb->private = NULL;
4302 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4303 kiocb->ki_complete = io_complete_rw_iopoll;
4304 req->iopoll_completed = 0;
4306 if (kiocb->ki_flags & IOCB_HIPRI)
4308 kiocb->ki_complete = io_complete_rw;
4314 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4316 struct io_rw_state __s, *s = &__s;
4317 struct iovec *iovec;
4318 struct kiocb *kiocb = &req->rw.kiocb;
4319 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4320 struct io_async_rw *rw;
4324 if (!req_has_async_data(req)) {
4325 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4326 if (unlikely(ret < 0))
4329 rw = req->async_data;
4333 * Safe and required to re-import if we're using provided
4334 * buffers, as we dropped the selected one before retry.
4336 if (io_do_buffer_select(req)) {
4337 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4338 if (unlikely(ret < 0))
4343 * We come here from an earlier attempt, restore our state to
4344 * match in case it doesn't. It's cheap enough that we don't
4345 * need to make this conditional.
4347 iov_iter_restore(&s->iter, &s->iter_state);
4350 ret = io_rw_init_file(req, FMODE_READ);
4351 if (unlikely(ret)) {
4355 req->cqe.res = iov_iter_count(&s->iter);
4357 if (force_nonblock) {
4358 /* If the file doesn't support async, just async punt */
4359 if (unlikely(!io_file_supports_nowait(req))) {
4360 ret = io_setup_async_rw(req, iovec, s, true);
4361 return ret ?: -EAGAIN;
4363 kiocb->ki_flags |= IOCB_NOWAIT;
4365 /* Ensure we clear previously set non-block flag */
4366 kiocb->ki_flags &= ~IOCB_NOWAIT;
4369 ppos = io_kiocb_update_pos(req);
4371 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4372 if (unlikely(ret)) {
4377 ret = io_iter_do_read(req, &s->iter);
4379 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4380 req->flags &= ~REQ_F_REISSUE;
4381 /* if we can poll, just do that */
4382 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4384 /* IOPOLL retry should happen for io-wq threads */
4385 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4387 /* no retry on NONBLOCK nor RWF_NOWAIT */
4388 if (req->flags & REQ_F_NOWAIT)
4391 } else if (ret == -EIOCBQUEUED) {
4393 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4394 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4395 /* read all, failed, already did sync or don't want to retry */
4400 * Don't depend on the iter state matching what was consumed, or being
4401 * untouched in case of error. Restore it and we'll advance it
4402 * manually if we need to.
4404 iov_iter_restore(&s->iter, &s->iter_state);
4406 ret2 = io_setup_async_rw(req, iovec, s, true);
4411 rw = req->async_data;
4414 * Now use our persistent iterator and state, if we aren't already.
4415 * We've restored and mapped the iter to match.
4420 * We end up here because of a partial read, either from
4421 * above or inside this loop. Advance the iter by the bytes
4422 * that were consumed.
4424 iov_iter_advance(&s->iter, ret);
4425 if (!iov_iter_count(&s->iter))
4427 rw->bytes_done += ret;
4428 iov_iter_save_state(&s->iter, &s->iter_state);
4430 /* if we can retry, do so with the callbacks armed */
4431 if (!io_rw_should_retry(req)) {
4432 kiocb->ki_flags &= ~IOCB_WAITQ;
4437 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4438 * we get -EIOCBQUEUED, then we'll get a notification when the
4439 * desired page gets unlocked. We can also get a partial read
4440 * here, and if we do, then just retry at the new offset.
4442 ret = io_iter_do_read(req, &s->iter);
4443 if (ret == -EIOCBQUEUED)
4445 /* we got some bytes, but not all. retry. */
4446 kiocb->ki_flags &= ~IOCB_WAITQ;
4447 iov_iter_restore(&s->iter, &s->iter_state);
4450 kiocb_done(req, ret, issue_flags);
4452 /* it's faster to check here then delegate to kfree */
4458 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4460 struct io_rw_state __s, *s = &__s;
4461 struct iovec *iovec;
4462 struct kiocb *kiocb = &req->rw.kiocb;
4463 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4467 if (!req_has_async_data(req)) {
4468 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4469 if (unlikely(ret < 0))
4472 struct io_async_rw *rw = req->async_data;
4475 iov_iter_restore(&s->iter, &s->iter_state);
4478 ret = io_rw_init_file(req, FMODE_WRITE);
4479 if (unlikely(ret)) {
4483 req->cqe.res = iov_iter_count(&s->iter);
4485 if (force_nonblock) {
4486 /* If the file doesn't support async, just async punt */
4487 if (unlikely(!io_file_supports_nowait(req)))
4490 /* file path doesn't support NOWAIT for non-direct_IO */
4491 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4492 (req->flags & REQ_F_ISREG))
4495 kiocb->ki_flags |= IOCB_NOWAIT;
4497 /* Ensure we clear previously set non-block flag */
4498 kiocb->ki_flags &= ~IOCB_NOWAIT;
4501 ppos = io_kiocb_update_pos(req);
4503 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4508 * Open-code file_start_write here to grab freeze protection,
4509 * which will be released by another thread in
4510 * io_complete_rw(). Fool lockdep by telling it the lock got
4511 * released so that it doesn't complain about the held lock when
4512 * we return to userspace.
4514 if (req->flags & REQ_F_ISREG) {
4515 sb_start_write(file_inode(req->file)->i_sb);
4516 __sb_writers_release(file_inode(req->file)->i_sb,
4519 kiocb->ki_flags |= IOCB_WRITE;
4521 if (likely(req->file->f_op->write_iter))
4522 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4523 else if (req->file->f_op->write)
4524 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4528 if (req->flags & REQ_F_REISSUE) {
4529 req->flags &= ~REQ_F_REISSUE;
4534 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4535 * retry them without IOCB_NOWAIT.
4537 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4539 /* no retry on NONBLOCK nor RWF_NOWAIT */
4540 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4542 if (!force_nonblock || ret2 != -EAGAIN) {
4543 /* IOPOLL retry should happen for io-wq threads */
4544 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4547 kiocb_done(req, ret2, issue_flags);
4550 iov_iter_restore(&s->iter, &s->iter_state);
4551 ret = io_setup_async_rw(req, iovec, s, false);
4552 return ret ?: -EAGAIN;
4555 /* it's reportedly faster than delegating the null check to kfree() */
4561 static int io_renameat_prep(struct io_kiocb *req,
4562 const struct io_uring_sqe *sqe)
4564 struct io_rename *ren = &req->rename;
4565 const char __user *oldf, *newf;
4567 if (sqe->buf_index || sqe->splice_fd_in)
4569 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4572 ren->old_dfd = READ_ONCE(sqe->fd);
4573 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4574 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4575 ren->new_dfd = READ_ONCE(sqe->len);
4576 ren->flags = READ_ONCE(sqe->rename_flags);
4578 ren->oldpath = getname(oldf);
4579 if (IS_ERR(ren->oldpath))
4580 return PTR_ERR(ren->oldpath);
4582 ren->newpath = getname(newf);
4583 if (IS_ERR(ren->newpath)) {
4584 putname(ren->oldpath);
4585 return PTR_ERR(ren->newpath);
4588 req->flags |= REQ_F_NEED_CLEANUP;
4592 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4594 struct io_rename *ren = &req->rename;
4597 if (issue_flags & IO_URING_F_NONBLOCK)
4600 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4601 ren->newpath, ren->flags);
4603 req->flags &= ~REQ_F_NEED_CLEANUP;
4604 io_req_complete(req, ret);
4608 static inline void __io_xattr_finish(struct io_kiocb *req)
4610 struct io_xattr *ix = &req->xattr;
4613 putname(ix->filename);
4615 kfree(ix->ctx.kname);
4616 kvfree(ix->ctx.kvalue);
4619 static void io_xattr_finish(struct io_kiocb *req, int ret)
4621 req->flags &= ~REQ_F_NEED_CLEANUP;
4623 __io_xattr_finish(req);
4624 io_req_complete(req, ret);
4627 static int __io_getxattr_prep(struct io_kiocb *req,
4628 const struct io_uring_sqe *sqe)
4630 struct io_xattr *ix = &req->xattr;
4631 const char __user *name;
4634 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4637 ix->filename = NULL;
4638 ix->ctx.kvalue = NULL;
4639 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4640 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4641 ix->ctx.size = READ_ONCE(sqe->len);
4642 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4647 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4651 ret = strncpy_from_user(ix->ctx.kname->name, name,
4652 sizeof(ix->ctx.kname->name));
4653 if (!ret || ret == sizeof(ix->ctx.kname->name))
4656 kfree(ix->ctx.kname);
4660 req->flags |= REQ_F_NEED_CLEANUP;
4664 static int io_fgetxattr_prep(struct io_kiocb *req,
4665 const struct io_uring_sqe *sqe)
4667 return __io_getxattr_prep(req, sqe);
4670 static int io_getxattr_prep(struct io_kiocb *req,
4671 const struct io_uring_sqe *sqe)
4673 struct io_xattr *ix = &req->xattr;
4674 const char __user *path;
4677 ret = __io_getxattr_prep(req, sqe);
4681 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4683 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4684 if (IS_ERR(ix->filename)) {
4685 ret = PTR_ERR(ix->filename);
4686 ix->filename = NULL;
4692 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4694 struct io_xattr *ix = &req->xattr;
4697 if (issue_flags & IO_URING_F_NONBLOCK)
4700 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4701 req->file->f_path.dentry,
4704 io_xattr_finish(req, ret);
4708 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4710 struct io_xattr *ix = &req->xattr;
4711 unsigned int lookup_flags = LOOKUP_FOLLOW;
4715 if (issue_flags & IO_URING_F_NONBLOCK)
4719 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4721 ret = do_getxattr(mnt_user_ns(path.mnt),
4726 if (retry_estale(ret, lookup_flags)) {
4727 lookup_flags |= LOOKUP_REVAL;
4732 io_xattr_finish(req, ret);
4736 static int __io_setxattr_prep(struct io_kiocb *req,
4737 const struct io_uring_sqe *sqe)
4739 struct io_xattr *ix = &req->xattr;
4740 const char __user *name;
4743 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4746 ix->filename = NULL;
4747 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4748 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4749 ix->ctx.kvalue = NULL;
4750 ix->ctx.size = READ_ONCE(sqe->len);
4751 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4753 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4757 ret = setxattr_copy(name, &ix->ctx);
4759 kfree(ix->ctx.kname);
4763 req->flags |= REQ_F_NEED_CLEANUP;
4767 static int io_setxattr_prep(struct io_kiocb *req,
4768 const struct io_uring_sqe *sqe)
4770 struct io_xattr *ix = &req->xattr;
4771 const char __user *path;
4774 ret = __io_setxattr_prep(req, sqe);
4778 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4780 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4781 if (IS_ERR(ix->filename)) {
4782 ret = PTR_ERR(ix->filename);
4783 ix->filename = NULL;
4789 static int io_fsetxattr_prep(struct io_kiocb *req,
4790 const struct io_uring_sqe *sqe)
4792 return __io_setxattr_prep(req, sqe);
4795 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4798 struct io_xattr *ix = &req->xattr;
4801 ret = mnt_want_write(path->mnt);
4803 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4804 mnt_drop_write(path->mnt);
4810 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4814 if (issue_flags & IO_URING_F_NONBLOCK)
4817 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4818 io_xattr_finish(req, ret);
4823 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4825 struct io_xattr *ix = &req->xattr;
4826 unsigned int lookup_flags = LOOKUP_FOLLOW;
4830 if (issue_flags & IO_URING_F_NONBLOCK)
4834 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4836 ret = __io_setxattr(req, issue_flags, &path);
4838 if (retry_estale(ret, lookup_flags)) {
4839 lookup_flags |= LOOKUP_REVAL;
4844 io_xattr_finish(req, ret);
4848 static int io_unlinkat_prep(struct io_kiocb *req,
4849 const struct io_uring_sqe *sqe)
4851 struct io_unlink *un = &req->unlink;
4852 const char __user *fname;
4854 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4856 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4859 un->dfd = READ_ONCE(sqe->fd);
4861 un->flags = READ_ONCE(sqe->unlink_flags);
4862 if (un->flags & ~AT_REMOVEDIR)
4865 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4866 un->filename = getname(fname);
4867 if (IS_ERR(un->filename))
4868 return PTR_ERR(un->filename);
4870 req->flags |= REQ_F_NEED_CLEANUP;
4874 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4876 struct io_unlink *un = &req->unlink;
4879 if (issue_flags & IO_URING_F_NONBLOCK)
4882 if (un->flags & AT_REMOVEDIR)
4883 ret = do_rmdir(un->dfd, un->filename);
4885 ret = do_unlinkat(un->dfd, un->filename);
4887 req->flags &= ~REQ_F_NEED_CLEANUP;
4888 io_req_complete(req, ret);
4892 static int io_mkdirat_prep(struct io_kiocb *req,
4893 const struct io_uring_sqe *sqe)
4895 struct io_mkdir *mkd = &req->mkdir;
4896 const char __user *fname;
4898 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4900 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4903 mkd->dfd = READ_ONCE(sqe->fd);
4904 mkd->mode = READ_ONCE(sqe->len);
4906 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4907 mkd->filename = getname(fname);
4908 if (IS_ERR(mkd->filename))
4909 return PTR_ERR(mkd->filename);
4911 req->flags |= REQ_F_NEED_CLEANUP;
4915 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4917 struct io_mkdir *mkd = &req->mkdir;
4920 if (issue_flags & IO_URING_F_NONBLOCK)
4923 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4925 req->flags &= ~REQ_F_NEED_CLEANUP;
4926 io_req_complete(req, ret);
4930 static int io_symlinkat_prep(struct io_kiocb *req,
4931 const struct io_uring_sqe *sqe)
4933 struct io_symlink *sl = &req->symlink;
4934 const char __user *oldpath, *newpath;
4936 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4938 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4941 sl->new_dfd = READ_ONCE(sqe->fd);
4942 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4943 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4945 sl->oldpath = getname(oldpath);
4946 if (IS_ERR(sl->oldpath))
4947 return PTR_ERR(sl->oldpath);
4949 sl->newpath = getname(newpath);
4950 if (IS_ERR(sl->newpath)) {
4951 putname(sl->oldpath);
4952 return PTR_ERR(sl->newpath);
4955 req->flags |= REQ_F_NEED_CLEANUP;
4959 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4961 struct io_symlink *sl = &req->symlink;
4964 if (issue_flags & IO_URING_F_NONBLOCK)
4967 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4969 req->flags &= ~REQ_F_NEED_CLEANUP;
4970 io_req_complete(req, ret);
4974 static int io_linkat_prep(struct io_kiocb *req,
4975 const struct io_uring_sqe *sqe)
4977 struct io_hardlink *lnk = &req->hardlink;
4978 const char __user *oldf, *newf;
4980 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4982 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4985 lnk->old_dfd = READ_ONCE(sqe->fd);
4986 lnk->new_dfd = READ_ONCE(sqe->len);
4987 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4988 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4989 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4991 lnk->oldpath = getname(oldf);
4992 if (IS_ERR(lnk->oldpath))
4993 return PTR_ERR(lnk->oldpath);
4995 lnk->newpath = getname(newf);
4996 if (IS_ERR(lnk->newpath)) {
4997 putname(lnk->oldpath);
4998 return PTR_ERR(lnk->newpath);
5001 req->flags |= REQ_F_NEED_CLEANUP;
5005 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
5007 struct io_hardlink *lnk = &req->hardlink;
5010 if (issue_flags & IO_URING_F_NONBLOCK)
5013 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
5014 lnk->newpath, lnk->flags);
5016 req->flags &= ~REQ_F_NEED_CLEANUP;
5017 io_req_complete(req, ret);
5021 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
5023 req->uring_cmd.task_work_cb(&req->uring_cmd);
5026 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
5027 void (*task_work_cb)(struct io_uring_cmd *))
5029 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5031 req->uring_cmd.task_work_cb = task_work_cb;
5032 req->io_task_work.func = io_uring_cmd_work;
5033 io_req_task_work_add(req);
5035 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
5037 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
5038 u64 extra1, u64 extra2)
5040 req->extra1 = extra1;
5041 req->extra2 = extra2;
5042 req->flags |= REQ_F_CQE32_INIT;
5046 * Called by consumers of io_uring_cmd, if they originally returned
5047 * -EIOCBQUEUED upon receiving the command.
5049 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
5051 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5056 if (req->ctx->flags & IORING_SETUP_CQE32)
5057 io_req_set_cqe32_extra(req, res2, 0);
5058 io_req_complete(req, ret);
5060 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
5062 static int io_uring_cmd_prep_async(struct io_kiocb *req)
5066 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
5068 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
5072 static int io_uring_cmd_prep(struct io_kiocb *req,
5073 const struct io_uring_sqe *sqe)
5075 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5077 if (sqe->rw_flags || sqe->__pad1)
5079 ioucmd->cmd = sqe->cmd;
5080 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
5084 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
5086 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5087 struct io_ring_ctx *ctx = req->ctx;
5088 struct file *file = req->file;
5091 if (!req->file->f_op->uring_cmd)
5094 if (ctx->flags & IORING_SETUP_SQE128)
5095 issue_flags |= IO_URING_F_SQE128;
5096 if (ctx->flags & IORING_SETUP_CQE32)
5097 issue_flags |= IO_URING_F_CQE32;
5098 if (ctx->flags & IORING_SETUP_IOPOLL)
5099 issue_flags |= IO_URING_F_IOPOLL;
5101 if (req_has_async_data(req))
5102 ioucmd->cmd = req->async_data;
5104 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
5105 if (ret == -EAGAIN) {
5106 if (!req_has_async_data(req)) {
5107 if (io_alloc_async_data(req))
5109 io_uring_cmd_prep_async(req);
5114 if (ret != -EIOCBQUEUED)
5115 io_uring_cmd_done(ioucmd, ret, 0);
5119 static int __io_splice_prep(struct io_kiocb *req,
5120 const struct io_uring_sqe *sqe)
5122 struct io_splice *sp = &req->splice;
5123 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
5125 sp->len = READ_ONCE(sqe->len);
5126 sp->flags = READ_ONCE(sqe->splice_flags);
5127 if (unlikely(sp->flags & ~valid_flags))
5129 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
5133 static int io_tee_prep(struct io_kiocb *req,
5134 const struct io_uring_sqe *sqe)
5136 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
5138 return __io_splice_prep(req, sqe);
5141 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
5143 struct io_splice *sp = &req->splice;
5144 struct file *out = sp->file_out;
5145 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5149 if (issue_flags & IO_URING_F_NONBLOCK)
5152 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5153 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5155 in = io_file_get_normal(req, sp->splice_fd_in);
5162 ret = do_tee(in, out, sp->len, flags);
5164 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5169 __io_req_complete(req, 0, ret, 0);
5173 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5175 struct io_splice *sp = &req->splice;
5177 sp->off_in = READ_ONCE(sqe->splice_off_in);
5178 sp->off_out = READ_ONCE(sqe->off);
5179 return __io_splice_prep(req, sqe);
5182 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5184 struct io_splice *sp = &req->splice;
5185 struct file *out = sp->file_out;
5186 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5187 loff_t *poff_in, *poff_out;
5191 if (issue_flags & IO_URING_F_NONBLOCK)
5194 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5195 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5197 in = io_file_get_normal(req, sp->splice_fd_in);
5203 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5204 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5207 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5209 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5214 __io_req_complete(req, 0, ret, 0);
5218 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5224 * IORING_OP_NOP just posts a completion event, nothing else.
5226 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5228 __io_req_complete(req, issue_flags, 0, 0);
5232 static int io_msg_ring_prep(struct io_kiocb *req,
5233 const struct io_uring_sqe *sqe)
5235 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5236 sqe->buf_index || sqe->personality))
5239 req->msg.user_data = READ_ONCE(sqe->off);
5240 req->msg.len = READ_ONCE(sqe->len);
5244 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5246 struct io_ring_ctx *target_ctx;
5247 struct io_msg *msg = &req->msg;
5252 if (req->file->f_op != &io_uring_fops)
5256 target_ctx = req->file->private_data;
5258 spin_lock(&target_ctx->completion_lock);
5259 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5260 io_commit_cqring(target_ctx);
5261 spin_unlock(&target_ctx->completion_lock);
5264 io_cqring_ev_posted(target_ctx);
5271 __io_req_complete(req, issue_flags, ret, 0);
5272 /* put file to avoid an attempt to IOPOLL the req */
5273 io_put_file(req->file);
5278 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5280 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5283 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5284 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5287 req->sync.off = READ_ONCE(sqe->off);
5288 req->sync.len = READ_ONCE(sqe->len);
5292 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5294 loff_t end = req->sync.off + req->sync.len;
5297 /* fsync always requires a blocking context */
5298 if (issue_flags & IO_URING_F_NONBLOCK)
5301 ret = vfs_fsync_range(req->file, req->sync.off,
5302 end > 0 ? end : LLONG_MAX,
5303 req->sync.flags & IORING_FSYNC_DATASYNC);
5304 io_req_complete(req, ret);
5308 static int io_fallocate_prep(struct io_kiocb *req,
5309 const struct io_uring_sqe *sqe)
5311 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5314 req->sync.off = READ_ONCE(sqe->off);
5315 req->sync.len = READ_ONCE(sqe->addr);
5316 req->sync.mode = READ_ONCE(sqe->len);
5320 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5324 /* fallocate always requiring blocking context */
5325 if (issue_flags & IO_URING_F_NONBLOCK)
5327 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5330 fsnotify_modify(req->file);
5331 io_req_complete(req, ret);
5335 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5337 const char __user *fname;
5340 if (unlikely(sqe->buf_index))
5342 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5345 /* open.how should be already initialised */
5346 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5347 req->open.how.flags |= O_LARGEFILE;
5349 req->open.dfd = READ_ONCE(sqe->fd);
5350 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5351 req->open.filename = getname(fname);
5352 if (IS_ERR(req->open.filename)) {
5353 ret = PTR_ERR(req->open.filename);
5354 req->open.filename = NULL;
5358 req->open.file_slot = READ_ONCE(sqe->file_index);
5359 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5362 req->open.nofile = rlimit(RLIMIT_NOFILE);
5363 req->flags |= REQ_F_NEED_CLEANUP;
5367 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5369 u64 mode = READ_ONCE(sqe->len);
5370 u64 flags = READ_ONCE(sqe->open_flags);
5372 req->open.how = build_open_how(flags, mode);
5373 return __io_openat_prep(req, sqe);
5376 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5378 struct open_how __user *how;
5382 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5383 len = READ_ONCE(sqe->len);
5384 if (len < OPEN_HOW_SIZE_VER0)
5387 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5392 return __io_openat_prep(req, sqe);
5395 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5397 struct io_file_table *table = &ctx->file_table;
5398 unsigned long nr = ctx->nr_user_files;
5402 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5406 if (!table->alloc_hint)
5409 nr = table->alloc_hint;
5410 table->alloc_hint = 0;
5417 * Note when io_fixed_fd_install() returns error value, it will ensure
5418 * fput() is called correspondingly.
5420 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5421 struct file *file, unsigned int file_slot)
5423 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5424 struct io_ring_ctx *ctx = req->ctx;
5427 io_ring_submit_lock(ctx, issue_flags);
5430 ret = io_file_bitmap_get(ctx);
5431 if (unlikely(ret < 0))
5438 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5439 if (!ret && alloc_slot)
5442 io_ring_submit_unlock(ctx, issue_flags);
5443 if (unlikely(ret < 0))
5448 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5450 struct open_flags op;
5452 bool resolve_nonblock, nonblock_set;
5453 bool fixed = !!req->open.file_slot;
5456 ret = build_open_flags(&req->open.how, &op);
5459 nonblock_set = op.open_flag & O_NONBLOCK;
5460 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5461 if (issue_flags & IO_URING_F_NONBLOCK) {
5463 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5464 * it'll always -EAGAIN
5466 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5468 op.lookup_flags |= LOOKUP_CACHED;
5469 op.open_flag |= O_NONBLOCK;
5473 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5478 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5481 * We could hang on to this 'fd' on retrying, but seems like
5482 * marginal gain for something that is now known to be a slower
5483 * path. So just put it, and we'll get a new one when we retry.
5488 ret = PTR_ERR(file);
5489 /* only retry if RESOLVE_CACHED wasn't already set by application */
5490 if (ret == -EAGAIN &&
5491 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5496 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5497 file->f_flags &= ~O_NONBLOCK;
5498 fsnotify_open(file);
5501 fd_install(ret, file);
5503 ret = io_fixed_fd_install(req, issue_flags, file,
5504 req->open.file_slot);
5506 putname(req->open.filename);
5507 req->flags &= ~REQ_F_NEED_CLEANUP;
5510 __io_req_complete(req, issue_flags, ret, 0);
5514 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5516 return io_openat2(req, issue_flags);
5519 static int io_remove_buffers_prep(struct io_kiocb *req,
5520 const struct io_uring_sqe *sqe)
5522 struct io_provide_buf *p = &req->pbuf;
5525 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5529 tmp = READ_ONCE(sqe->fd);
5530 if (!tmp || tmp > USHRT_MAX)
5533 memset(p, 0, sizeof(*p));
5535 p->bgid = READ_ONCE(sqe->buf_group);
5539 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5540 struct io_buffer_list *bl, unsigned nbufs)
5544 /* shouldn't happen */
5548 if (bl->buf_nr_pages) {
5551 i = bl->buf_ring->tail - bl->head;
5552 for (j = 0; j < bl->buf_nr_pages; j++)
5553 unpin_user_page(bl->buf_pages[j]);
5554 kvfree(bl->buf_pages);
5555 bl->buf_pages = NULL;
5556 bl->buf_nr_pages = 0;
5557 /* make sure it's seen as empty */
5558 INIT_LIST_HEAD(&bl->buf_list);
5562 /* the head kbuf is the list itself */
5563 while (!list_empty(&bl->buf_list)) {
5564 struct io_buffer *nxt;
5566 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5567 list_del(&nxt->list);
5577 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5579 struct io_provide_buf *p = &req->pbuf;
5580 struct io_ring_ctx *ctx = req->ctx;
5581 struct io_buffer_list *bl;
5584 io_ring_submit_lock(ctx, issue_flags);
5587 bl = io_buffer_get_list(ctx, p->bgid);
5590 /* can't use provide/remove buffers command on mapped buffers */
5591 if (!bl->buf_nr_pages)
5592 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5597 /* complete before unlock, IOPOLL may need the lock */
5598 __io_req_complete(req, issue_flags, ret, 0);
5599 io_ring_submit_unlock(ctx, issue_flags);
5603 static int io_provide_buffers_prep(struct io_kiocb *req,
5604 const struct io_uring_sqe *sqe)
5606 unsigned long size, tmp_check;
5607 struct io_provide_buf *p = &req->pbuf;
5610 if (sqe->rw_flags || sqe->splice_fd_in)
5613 tmp = READ_ONCE(sqe->fd);
5614 if (!tmp || tmp > USHRT_MAX)
5617 p->addr = READ_ONCE(sqe->addr);
5618 p->len = READ_ONCE(sqe->len);
5620 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5623 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5626 size = (unsigned long)p->len * p->nbufs;
5627 if (!access_ok(u64_to_user_ptr(p->addr), size))
5630 p->bgid = READ_ONCE(sqe->buf_group);
5631 tmp = READ_ONCE(sqe->off);
5632 if (tmp > USHRT_MAX)
5638 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5640 struct io_buffer *buf;
5645 * Completions that don't happen inline (eg not under uring_lock) will
5646 * add to ->io_buffers_comp. If we don't have any free buffers, check
5647 * the completion list and splice those entries first.
5649 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5650 spin_lock(&ctx->completion_lock);
5651 if (!list_empty(&ctx->io_buffers_comp)) {
5652 list_splice_init(&ctx->io_buffers_comp,
5653 &ctx->io_buffers_cache);
5654 spin_unlock(&ctx->completion_lock);
5657 spin_unlock(&ctx->completion_lock);
5661 * No free buffers and no completion entries either. Allocate a new
5662 * page worth of buffer entries and add those to our freelist.
5664 page = alloc_page(GFP_KERNEL_ACCOUNT);
5668 list_add(&page->lru, &ctx->io_buffers_pages);
5670 buf = page_address(page);
5671 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5672 while (bufs_in_page) {
5673 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5681 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5682 struct io_buffer_list *bl)
5684 struct io_buffer *buf;
5685 u64 addr = pbuf->addr;
5686 int i, bid = pbuf->bid;
5688 for (i = 0; i < pbuf->nbufs; i++) {
5689 if (list_empty(&ctx->io_buffers_cache) &&
5690 io_refill_buffer_cache(ctx))
5692 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5694 list_move_tail(&buf->list, &bl->buf_list);
5696 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5698 buf->bgid = pbuf->bgid;
5704 return i ? 0 : -ENOMEM;
5707 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5711 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5716 for (i = 0; i < BGID_ARRAY; i++) {
5717 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5718 ctx->io_bl[i].bgid = i;
5724 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5726 struct io_provide_buf *p = &req->pbuf;
5727 struct io_ring_ctx *ctx = req->ctx;
5728 struct io_buffer_list *bl;
5731 io_ring_submit_lock(ctx, issue_flags);
5733 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5734 ret = io_init_bl_list(ctx);
5739 bl = io_buffer_get_list(ctx, p->bgid);
5740 if (unlikely(!bl)) {
5741 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5746 INIT_LIST_HEAD(&bl->buf_list);
5747 ret = io_buffer_add_list(ctx, bl, p->bgid);
5753 /* can't add buffers via this command for a mapped buffer ring */
5754 if (bl->buf_nr_pages) {
5759 ret = io_add_buffers(ctx, p, bl);
5763 /* complete before unlock, IOPOLL may need the lock */
5764 __io_req_complete(req, issue_flags, ret, 0);
5765 io_ring_submit_unlock(ctx, issue_flags);
5769 static int io_epoll_ctl_prep(struct io_kiocb *req,
5770 const struct io_uring_sqe *sqe)
5772 #if defined(CONFIG_EPOLL)
5773 if (sqe->buf_index || sqe->splice_fd_in)
5776 req->epoll.epfd = READ_ONCE(sqe->fd);
5777 req->epoll.op = READ_ONCE(sqe->len);
5778 req->epoll.fd = READ_ONCE(sqe->off);
5780 if (ep_op_has_event(req->epoll.op)) {
5781 struct epoll_event __user *ev;
5783 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5784 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5794 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5796 #if defined(CONFIG_EPOLL)
5797 struct io_epoll *ie = &req->epoll;
5799 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5801 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5802 if (force_nonblock && ret == -EAGAIN)
5807 __io_req_complete(req, issue_flags, ret, 0);
5814 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5816 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5817 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5820 req->madvise.addr = READ_ONCE(sqe->addr);
5821 req->madvise.len = READ_ONCE(sqe->len);
5822 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5829 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5831 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5832 struct io_madvise *ma = &req->madvise;
5835 if (issue_flags & IO_URING_F_NONBLOCK)
5838 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5839 io_req_complete(req, ret);
5846 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5848 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5851 req->fadvise.offset = READ_ONCE(sqe->off);
5852 req->fadvise.len = READ_ONCE(sqe->len);
5853 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5857 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5859 struct io_fadvise *fa = &req->fadvise;
5862 if (issue_flags & IO_URING_F_NONBLOCK) {
5863 switch (fa->advice) {
5864 case POSIX_FADV_NORMAL:
5865 case POSIX_FADV_RANDOM:
5866 case POSIX_FADV_SEQUENTIAL:
5873 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5876 __io_req_complete(req, issue_flags, ret, 0);
5880 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5882 const char __user *path;
5884 if (sqe->buf_index || sqe->splice_fd_in)
5886 if (req->flags & REQ_F_FIXED_FILE)
5889 req->statx.dfd = READ_ONCE(sqe->fd);
5890 req->statx.mask = READ_ONCE(sqe->len);
5891 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5892 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5893 req->statx.flags = READ_ONCE(sqe->statx_flags);
5895 req->statx.filename = getname_flags(path,
5896 getname_statx_lookup_flags(req->statx.flags),
5899 if (IS_ERR(req->statx.filename)) {
5900 int ret = PTR_ERR(req->statx.filename);
5902 req->statx.filename = NULL;
5906 req->flags |= REQ_F_NEED_CLEANUP;
5910 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5912 struct io_statx *ctx = &req->statx;
5915 if (issue_flags & IO_URING_F_NONBLOCK)
5918 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5920 io_req_complete(req, ret);
5924 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5926 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5928 if (req->flags & REQ_F_FIXED_FILE)
5931 req->close.fd = READ_ONCE(sqe->fd);
5932 req->close.file_slot = READ_ONCE(sqe->file_index);
5933 if (req->close.file_slot && req->close.fd)
5939 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5941 struct files_struct *files = current->files;
5942 struct io_close *close = &req->close;
5943 struct fdtable *fdt;
5947 if (req->close.file_slot) {
5948 ret = io_close_fixed(req, issue_flags);
5952 spin_lock(&files->file_lock);
5953 fdt = files_fdtable(files);
5954 if (close->fd >= fdt->max_fds) {
5955 spin_unlock(&files->file_lock);
5958 file = rcu_dereference_protected(fdt->fd[close->fd],
5959 lockdep_is_held(&files->file_lock));
5960 if (!file || file->f_op == &io_uring_fops) {
5961 spin_unlock(&files->file_lock);
5965 /* if the file has a flush method, be safe and punt to async */
5966 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5967 spin_unlock(&files->file_lock);
5971 file = __close_fd_get_file(close->fd);
5972 spin_unlock(&files->file_lock);
5976 /* No ->flush() or already async, safely close from here */
5977 ret = filp_close(file, current->files);
5981 __io_req_complete(req, issue_flags, ret, 0);
5985 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5987 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5990 req->sync.off = READ_ONCE(sqe->off);
5991 req->sync.len = READ_ONCE(sqe->len);
5992 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5996 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
6000 /* sync_file_range always requires a blocking context */
6001 if (issue_flags & IO_URING_F_NONBLOCK)
6004 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
6006 io_req_complete(req, ret);
6010 #if defined(CONFIG_NET)
6011 static int io_shutdown_prep(struct io_kiocb *req,
6012 const struct io_uring_sqe *sqe)
6014 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
6015 sqe->buf_index || sqe->splice_fd_in))
6018 req->shutdown.how = READ_ONCE(sqe->len);
6022 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
6024 struct socket *sock;
6027 if (issue_flags & IO_URING_F_NONBLOCK)
6030 sock = sock_from_file(req->file);
6031 if (unlikely(!sock))
6034 ret = __sys_shutdown_sock(sock, req->shutdown.how);
6035 io_req_complete(req, ret);
6039 static bool io_net_retry(struct socket *sock, int flags)
6041 if (!(flags & MSG_WAITALL))
6043 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
6046 static int io_setup_async_msg(struct io_kiocb *req,
6047 struct io_async_msghdr *kmsg)
6049 struct io_async_msghdr *async_msg = req->async_data;
6053 if (io_alloc_async_data(req)) {
6054 kfree(kmsg->free_iov);
6057 async_msg = req->async_data;
6058 req->flags |= REQ_F_NEED_CLEANUP;
6059 memcpy(async_msg, kmsg, sizeof(*kmsg));
6060 async_msg->msg.msg_name = &async_msg->addr;
6061 /* if were using fast_iov, set it to the new one */
6062 if (!async_msg->free_iov)
6063 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
6068 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
6069 struct io_async_msghdr *iomsg)
6071 iomsg->msg.msg_name = &iomsg->addr;
6072 iomsg->free_iov = iomsg->fast_iov;
6073 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
6074 req->sr_msg.msg_flags, &iomsg->free_iov);
6077 static int io_sendmsg_prep_async(struct io_kiocb *req)
6081 ret = io_sendmsg_copy_hdr(req, req->async_data);
6083 req->flags |= REQ_F_NEED_CLEANUP;
6087 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6089 struct io_sr_msg *sr = &req->sr_msg;
6091 if (unlikely(sqe->file_index || sqe->addr2))
6094 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6095 sr->len = READ_ONCE(sqe->len);
6096 sr->flags = READ_ONCE(sqe->ioprio);
6097 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6099 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6100 if (sr->msg_flags & MSG_DONTWAIT)
6101 req->flags |= REQ_F_NOWAIT;
6103 #ifdef CONFIG_COMPAT
6104 if (req->ctx->compat)
6105 sr->msg_flags |= MSG_CMSG_COMPAT;
6111 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
6113 struct io_async_msghdr iomsg, *kmsg;
6114 struct io_sr_msg *sr = &req->sr_msg;
6115 struct socket *sock;
6120 sock = sock_from_file(req->file);
6121 if (unlikely(!sock))
6124 if (req_has_async_data(req)) {
6125 kmsg = req->async_data;
6127 ret = io_sendmsg_copy_hdr(req, &iomsg);
6133 if (!(req->flags & REQ_F_POLLED) &&
6134 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6135 return io_setup_async_msg(req, kmsg);
6137 flags = sr->msg_flags;
6138 if (issue_flags & IO_URING_F_NONBLOCK)
6139 flags |= MSG_DONTWAIT;
6140 if (flags & MSG_WAITALL)
6141 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6143 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
6145 if (ret < min_ret) {
6146 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6147 return io_setup_async_msg(req, kmsg);
6148 if (ret == -ERESTARTSYS)
6150 if (ret > 0 && io_net_retry(sock, flags)) {
6152 req->flags |= REQ_F_PARTIAL_IO;
6153 return io_setup_async_msg(req, kmsg);
6157 /* fast path, check for non-NULL to avoid function call */
6159 kfree(kmsg->free_iov);
6160 req->flags &= ~REQ_F_NEED_CLEANUP;
6163 else if (sr->done_io)
6165 __io_req_complete(req, issue_flags, ret, 0);
6169 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6171 struct io_sr_msg *sr = &req->sr_msg;
6174 struct socket *sock;
6179 if (!(req->flags & REQ_F_POLLED) &&
6180 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6183 sock = sock_from_file(req->file);
6184 if (unlikely(!sock))
6187 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6191 msg.msg_name = NULL;
6192 msg.msg_control = NULL;
6193 msg.msg_controllen = 0;
6194 msg.msg_namelen = 0;
6196 flags = sr->msg_flags;
6197 if (issue_flags & IO_URING_F_NONBLOCK)
6198 flags |= MSG_DONTWAIT;
6199 if (flags & MSG_WAITALL)
6200 min_ret = iov_iter_count(&msg.msg_iter);
6202 msg.msg_flags = flags;
6203 ret = sock_sendmsg(sock, &msg);
6204 if (ret < min_ret) {
6205 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6207 if (ret == -ERESTARTSYS)
6209 if (ret > 0 && io_net_retry(sock, flags)) {
6213 req->flags |= REQ_F_PARTIAL_IO;
6220 else if (sr->done_io)
6222 __io_req_complete(req, issue_flags, ret, 0);
6226 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6227 struct io_async_msghdr *iomsg)
6229 struct io_sr_msg *sr = &req->sr_msg;
6230 struct iovec __user *uiov;
6234 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6235 &iomsg->uaddr, &uiov, &iov_len);
6239 if (req->flags & REQ_F_BUFFER_SELECT) {
6242 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6244 sr->len = iomsg->fast_iov[0].iov_len;
6245 iomsg->free_iov = NULL;
6247 iomsg->free_iov = iomsg->fast_iov;
6248 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6249 &iomsg->free_iov, &iomsg->msg.msg_iter,
6258 #ifdef CONFIG_COMPAT
6259 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6260 struct io_async_msghdr *iomsg)
6262 struct io_sr_msg *sr = &req->sr_msg;
6263 struct compat_iovec __user *uiov;
6268 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6273 uiov = compat_ptr(ptr);
6274 if (req->flags & REQ_F_BUFFER_SELECT) {
6275 compat_ssize_t clen;
6279 if (!access_ok(uiov, sizeof(*uiov)))
6281 if (__get_user(clen, &uiov->iov_len))
6286 iomsg->free_iov = NULL;
6288 iomsg->free_iov = iomsg->fast_iov;
6289 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6290 UIO_FASTIOV, &iomsg->free_iov,
6291 &iomsg->msg.msg_iter, true);
6300 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6301 struct io_async_msghdr *iomsg)
6303 iomsg->msg.msg_name = &iomsg->addr;
6305 #ifdef CONFIG_COMPAT
6306 if (req->ctx->compat)
6307 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6310 return __io_recvmsg_copy_hdr(req, iomsg);
6313 static int io_recvmsg_prep_async(struct io_kiocb *req)
6317 ret = io_recvmsg_copy_hdr(req, req->async_data);
6319 req->flags |= REQ_F_NEED_CLEANUP;
6323 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6325 struct io_sr_msg *sr = &req->sr_msg;
6327 if (unlikely(sqe->file_index || sqe->addr2))
6330 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6331 sr->len = READ_ONCE(sqe->len);
6332 sr->flags = READ_ONCE(sqe->ioprio);
6333 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6335 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6336 if (sr->msg_flags & MSG_DONTWAIT)
6337 req->flags |= REQ_F_NOWAIT;
6339 #ifdef CONFIG_COMPAT
6340 if (req->ctx->compat)
6341 sr->msg_flags |= MSG_CMSG_COMPAT;
6347 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6349 struct io_async_msghdr iomsg, *kmsg;
6350 struct io_sr_msg *sr = &req->sr_msg;
6351 struct socket *sock;
6352 unsigned int cflags;
6354 int ret, min_ret = 0;
6355 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6357 sock = sock_from_file(req->file);
6358 if (unlikely(!sock))
6361 if (req_has_async_data(req)) {
6362 kmsg = req->async_data;
6364 ret = io_recvmsg_copy_hdr(req, &iomsg);
6370 if (!(req->flags & REQ_F_POLLED) &&
6371 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6372 return io_setup_async_msg(req, kmsg);
6374 if (io_do_buffer_select(req)) {
6377 buf = io_buffer_select(req, &sr->len, issue_flags);
6380 kmsg->fast_iov[0].iov_base = buf;
6381 kmsg->fast_iov[0].iov_len = sr->len;
6382 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6386 flags = sr->msg_flags;
6388 flags |= MSG_DONTWAIT;
6389 if (flags & MSG_WAITALL)
6390 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6392 kmsg->msg.msg_get_inq = 1;
6393 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6394 if (ret < min_ret) {
6395 if (ret == -EAGAIN && force_nonblock)
6396 return io_setup_async_msg(req, kmsg);
6397 if (ret == -ERESTARTSYS)
6399 if (ret > 0 && io_net_retry(sock, flags)) {
6401 req->flags |= REQ_F_PARTIAL_IO;
6402 return io_setup_async_msg(req, kmsg);
6405 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6409 /* fast path, check for non-NULL to avoid function call */
6411 kfree(kmsg->free_iov);
6412 req->flags &= ~REQ_F_NEED_CLEANUP;
6415 else if (sr->done_io)
6417 cflags = io_put_kbuf(req, issue_flags);
6418 if (kmsg->msg.msg_inq)
6419 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6420 __io_req_complete(req, issue_flags, ret, cflags);
6424 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6426 struct io_sr_msg *sr = &req->sr_msg;
6428 struct socket *sock;
6430 unsigned int cflags;
6432 int ret, min_ret = 0;
6433 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6435 if (!(req->flags & REQ_F_POLLED) &&
6436 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6439 sock = sock_from_file(req->file);
6440 if (unlikely(!sock))
6443 if (io_do_buffer_select(req)) {
6446 buf = io_buffer_select(req, &sr->len, issue_flags);
6452 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6456 msg.msg_name = NULL;
6457 msg.msg_namelen = 0;
6458 msg.msg_control = NULL;
6459 msg.msg_get_inq = 1;
6461 msg.msg_controllen = 0;
6462 msg.msg_iocb = NULL;
6464 flags = sr->msg_flags;
6466 flags |= MSG_DONTWAIT;
6467 if (flags & MSG_WAITALL)
6468 min_ret = iov_iter_count(&msg.msg_iter);
6470 ret = sock_recvmsg(sock, &msg, flags);
6471 if (ret < min_ret) {
6472 if (ret == -EAGAIN && force_nonblock)
6474 if (ret == -ERESTARTSYS)
6476 if (ret > 0 && io_net_retry(sock, flags)) {
6480 req->flags |= REQ_F_PARTIAL_IO;
6484 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6491 else if (sr->done_io)
6493 cflags = io_put_kbuf(req, issue_flags);
6495 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6496 __io_req_complete(req, issue_flags, ret, cflags);
6500 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6502 struct io_accept *accept = &req->accept;
6505 if (sqe->len || sqe->buf_index)
6508 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6509 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6510 accept->flags = READ_ONCE(sqe->accept_flags);
6511 accept->nofile = rlimit(RLIMIT_NOFILE);
6512 flags = READ_ONCE(sqe->ioprio);
6513 if (flags & ~IORING_ACCEPT_MULTISHOT)
6516 accept->file_slot = READ_ONCE(sqe->file_index);
6517 if (accept->file_slot) {
6518 if (accept->flags & SOCK_CLOEXEC)
6520 if (flags & IORING_ACCEPT_MULTISHOT &&
6521 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6524 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6526 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6527 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6528 if (flags & IORING_ACCEPT_MULTISHOT)
6529 req->flags |= REQ_F_APOLL_MULTISHOT;
6533 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6535 struct io_ring_ctx *ctx = req->ctx;
6536 struct io_accept *accept = &req->accept;
6537 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6538 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6539 bool fixed = !!accept->file_slot;
6545 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6546 if (unlikely(fd < 0))
6549 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6554 ret = PTR_ERR(file);
6555 if (ret == -EAGAIN && force_nonblock) {
6557 * if it's multishot and polled, we don't need to
6558 * return EAGAIN to arm the poll infra since it
6559 * has already been done
6561 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6562 IO_APOLL_MULTI_POLLED)
6566 if (ret == -ERESTARTSYS)
6569 } else if (!fixed) {
6570 fd_install(fd, file);
6573 ret = io_fixed_fd_install(req, issue_flags, file,
6577 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6578 __io_req_complete(req, issue_flags, ret, 0);
6584 spin_lock(&ctx->completion_lock);
6585 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6587 io_commit_cqring(ctx);
6588 spin_unlock(&ctx->completion_lock);
6590 io_cqring_ev_posted(ctx);
6599 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6601 struct io_socket *sock = &req->sock;
6603 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6606 sock->domain = READ_ONCE(sqe->fd);
6607 sock->type = READ_ONCE(sqe->off);
6608 sock->protocol = READ_ONCE(sqe->len);
6609 sock->file_slot = READ_ONCE(sqe->file_index);
6610 sock->nofile = rlimit(RLIMIT_NOFILE);
6612 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6613 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6615 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6620 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6622 struct io_socket *sock = &req->sock;
6623 bool fixed = !!sock->file_slot;
6628 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6629 if (unlikely(fd < 0))
6632 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6636 ret = PTR_ERR(file);
6637 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6639 if (ret == -ERESTARTSYS)
6642 } else if (!fixed) {
6643 fd_install(fd, file);
6646 ret = io_fixed_fd_install(req, issue_flags, file,
6649 __io_req_complete(req, issue_flags, ret, 0);
6653 static int io_connect_prep_async(struct io_kiocb *req)
6655 struct io_async_connect *io = req->async_data;
6656 struct io_connect *conn = &req->connect;
6658 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6661 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6663 struct io_connect *conn = &req->connect;
6665 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6668 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6669 conn->addr_len = READ_ONCE(sqe->addr2);
6673 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6675 struct io_async_connect __io, *io;
6676 unsigned file_flags;
6678 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6680 if (req_has_async_data(req)) {
6681 io = req->async_data;
6683 ret = move_addr_to_kernel(req->connect.addr,
6684 req->connect.addr_len,
6691 file_flags = force_nonblock ? O_NONBLOCK : 0;
6693 ret = __sys_connect_file(req->file, &io->address,
6694 req->connect.addr_len, file_flags);
6695 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6696 if (req_has_async_data(req))
6698 if (io_alloc_async_data(req)) {
6702 memcpy(req->async_data, &__io, sizeof(__io));
6705 if (ret == -ERESTARTSYS)
6710 __io_req_complete(req, issue_flags, ret, 0);
6713 #else /* !CONFIG_NET */
6714 #define IO_NETOP_FN(op) \
6715 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6717 return -EOPNOTSUPP; \
6720 #define IO_NETOP_PREP(op) \
6722 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6724 return -EOPNOTSUPP; \
6727 #define IO_NETOP_PREP_ASYNC(op) \
6729 static int io_##op##_prep_async(struct io_kiocb *req) \
6731 return -EOPNOTSUPP; \
6734 IO_NETOP_PREP_ASYNC(sendmsg);
6735 IO_NETOP_PREP_ASYNC(recvmsg);
6736 IO_NETOP_PREP_ASYNC(connect);
6737 IO_NETOP_PREP(accept);
6738 IO_NETOP_PREP(socket);
6739 IO_NETOP_PREP(shutdown);
6742 #endif /* CONFIG_NET */
6744 struct io_poll_table {
6745 struct poll_table_struct pt;
6746 struct io_kiocb *req;
6751 #define IO_POLL_CANCEL_FLAG BIT(31)
6752 #define IO_POLL_REF_MASK GENMASK(30, 0)
6755 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6756 * bump it and acquire ownership. It's disallowed to modify requests while not
6757 * owning it, that prevents from races for enqueueing task_work's and b/w
6758 * arming poll and wakeups.
6760 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6762 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6765 static void io_poll_mark_cancelled(struct io_kiocb *req)
6767 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6770 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6772 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6773 if (req->opcode == IORING_OP_POLL_ADD)
6774 return req->async_data;
6775 return req->apoll->double_poll;
6778 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6780 if (req->opcode == IORING_OP_POLL_ADD)
6782 return &req->apoll->poll;
6785 static void io_poll_req_insert(struct io_kiocb *req)
6787 struct io_ring_ctx *ctx = req->ctx;
6788 struct hlist_head *list;
6790 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6791 hlist_add_head(&req->hash_node, list);
6794 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6795 wait_queue_func_t wake_func)
6798 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6799 /* mask in events that we always want/need */
6800 poll->events = events | IO_POLL_UNMASK;
6801 INIT_LIST_HEAD(&poll->wait.entry);
6802 init_waitqueue_func_entry(&poll->wait, wake_func);
6805 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6807 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6810 spin_lock_irq(&head->lock);
6811 list_del_init(&poll->wait.entry);
6813 spin_unlock_irq(&head->lock);
6817 static void io_poll_remove_entries(struct io_kiocb *req)
6820 * Nothing to do if neither of those flags are set. Avoid dipping
6821 * into the poll/apoll/double cachelines if we can.
6823 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6827 * While we hold the waitqueue lock and the waitqueue is nonempty,
6828 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6829 * lock in the first place can race with the waitqueue being freed.
6831 * We solve this as eventpoll does: by taking advantage of the fact that
6832 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6833 * we enter rcu_read_lock() and see that the pointer to the queue is
6834 * non-NULL, we can then lock it without the memory being freed out from
6837 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6838 * case the caller deletes the entry from the queue, leaving it empty.
6839 * In that case, only RCU prevents the queue memory from being freed.
6842 if (req->flags & REQ_F_SINGLE_POLL)
6843 io_poll_remove_entry(io_poll_get_single(req));
6844 if (req->flags & REQ_F_DOUBLE_POLL)
6845 io_poll_remove_entry(io_poll_get_double(req));
6849 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6851 * All poll tw should go through this. Checks for poll events, manages
6852 * references, does rewait, etc.
6854 * Returns a negative error on failure. >0 when no action require, which is
6855 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6856 * the request, then the mask is stored in req->cqe.res.
6858 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6860 struct io_ring_ctx *ctx = req->ctx;
6863 /* req->task == current here, checking PF_EXITING is safe */
6864 if (unlikely(req->task->flags & PF_EXITING))
6868 v = atomic_read(&req->poll_refs);
6870 /* tw handler should be the owner, and so have some references */
6871 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6873 if (v & IO_POLL_CANCEL_FLAG)
6876 if (!req->cqe.res) {
6877 struct poll_table_struct pt = { ._key = req->apoll_events };
6878 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6881 if ((unlikely(!req->cqe.res)))
6883 if (req->apoll_events & EPOLLONESHOT)
6886 /* multishot, just fill a CQE and proceed */
6887 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6888 __poll_t mask = mangle_poll(req->cqe.res &
6892 spin_lock(&ctx->completion_lock);
6893 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6894 mask, IORING_CQE_F_MORE);
6895 io_commit_cqring(ctx);
6896 spin_unlock(&ctx->completion_lock);
6898 io_cqring_ev_posted(ctx);
6904 io_tw_lock(req->ctx, locked);
6905 if (unlikely(req->task->flags & PF_EXITING))
6907 ret = io_issue_sqe(req,
6908 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6913 * Release all references, retry if someone tried to restart
6914 * task_work while we were executing it.
6916 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6921 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6923 struct io_ring_ctx *ctx = req->ctx;
6926 ret = io_poll_check_events(req, locked);
6931 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6937 io_poll_remove_entries(req);
6938 spin_lock(&ctx->completion_lock);
6939 hash_del(&req->hash_node);
6940 __io_req_complete_post(req, req->cqe.res, 0);
6941 io_commit_cqring(ctx);
6942 spin_unlock(&ctx->completion_lock);
6943 io_cqring_ev_posted(ctx);
6946 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6948 struct io_ring_ctx *ctx = req->ctx;
6951 ret = io_poll_check_events(req, locked);
6955 io_poll_remove_entries(req);
6956 spin_lock(&ctx->completion_lock);
6957 hash_del(&req->hash_node);
6958 spin_unlock(&ctx->completion_lock);
6961 io_req_task_submit(req, locked);
6963 io_req_complete_failed(req, ret);
6966 static void __io_poll_execute(struct io_kiocb *req, int mask,
6967 __poll_t __maybe_unused events)
6969 req->cqe.res = mask;
6971 * This is useful for poll that is armed on behalf of another
6972 * request, and where the wakeup path could be on a different
6973 * CPU. We want to avoid pulling in req->apoll->events for that
6976 if (req->opcode == IORING_OP_POLL_ADD)
6977 req->io_task_work.func = io_poll_task_func;
6979 req->io_task_work.func = io_apoll_task_func;
6981 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6982 io_req_task_work_add(req);
6985 static inline void io_poll_execute(struct io_kiocb *req, int res,
6988 if (io_poll_get_ownership(req))
6989 __io_poll_execute(req, res, events);
6992 static void io_poll_cancel_req(struct io_kiocb *req)
6994 io_poll_mark_cancelled(req);
6995 /* kick tw, which should complete the request */
6996 io_poll_execute(req, 0, 0);
6999 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
7000 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
7001 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
7003 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
7006 struct io_kiocb *req = wqe_to_req(wait);
7007 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
7009 __poll_t mask = key_to_poll(key);
7011 if (unlikely(mask & POLLFREE)) {
7012 io_poll_mark_cancelled(req);
7013 /* we have to kick tw in case it's not already */
7014 io_poll_execute(req, 0, poll->events);
7017 * If the waitqueue is being freed early but someone is already
7018 * holds ownership over it, we have to tear down the request as
7019 * best we can. That means immediately removing the request from
7020 * its waitqueue and preventing all further accesses to the
7021 * waitqueue via the request.
7023 list_del_init(&poll->wait.entry);
7026 * Careful: this *must* be the last step, since as soon
7027 * as req->head is NULL'ed out, the request can be
7028 * completed and freed, since aio_poll_complete_work()
7029 * will no longer need to take the waitqueue lock.
7031 smp_store_release(&poll->head, NULL);
7035 /* for instances that support it check for an event match first */
7036 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
7039 if (io_poll_get_ownership(req)) {
7040 /* optional, saves extra locking for removal in tw handler */
7041 if (mask && poll->events & EPOLLONESHOT) {
7042 list_del_init(&poll->wait.entry);
7044 if (wqe_is_double(wait))
7045 req->flags &= ~REQ_F_DOUBLE_POLL;
7047 req->flags &= ~REQ_F_SINGLE_POLL;
7049 __io_poll_execute(req, mask, poll->events);
7054 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
7055 struct wait_queue_head *head,
7056 struct io_poll_iocb **poll_ptr)
7058 struct io_kiocb *req = pt->req;
7059 unsigned long wqe_private = (unsigned long) req;
7062 * The file being polled uses multiple waitqueues for poll handling
7063 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
7066 if (unlikely(pt->nr_entries)) {
7067 struct io_poll_iocb *first = poll;
7069 /* double add on the same waitqueue head, ignore */
7070 if (first->head == head)
7072 /* already have a 2nd entry, fail a third attempt */
7074 if ((*poll_ptr)->head == head)
7076 pt->error = -EINVAL;
7080 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
7082 pt->error = -ENOMEM;
7085 /* mark as double wq entry */
7087 req->flags |= REQ_F_DOUBLE_POLL;
7088 io_init_poll_iocb(poll, first->events, first->wait.func);
7090 if (req->opcode == IORING_OP_POLL_ADD)
7091 req->flags |= REQ_F_ASYNC_DATA;
7094 req->flags |= REQ_F_SINGLE_POLL;
7097 poll->wait.private = (void *) wqe_private;
7099 if (poll->events & EPOLLEXCLUSIVE)
7100 add_wait_queue_exclusive(head, &poll->wait);
7102 add_wait_queue(head, &poll->wait);
7105 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
7106 struct poll_table_struct *p)
7108 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7110 __io_queue_proc(&pt->req->poll, pt, head,
7111 (struct io_poll_iocb **) &pt->req->async_data);
7114 static int __io_arm_poll_handler(struct io_kiocb *req,
7115 struct io_poll_iocb *poll,
7116 struct io_poll_table *ipt, __poll_t mask)
7118 struct io_ring_ctx *ctx = req->ctx;
7121 INIT_HLIST_NODE(&req->hash_node);
7122 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
7123 io_init_poll_iocb(poll, mask, io_poll_wake);
7124 poll->file = req->file;
7126 req->apoll_events = poll->events;
7128 ipt->pt._key = mask;
7131 ipt->nr_entries = 0;
7134 * Take the ownership to delay any tw execution up until we're done
7135 * with poll arming. see io_poll_get_ownership().
7137 atomic_set(&req->poll_refs, 1);
7138 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
7140 if (mask && (poll->events & EPOLLONESHOT)) {
7141 io_poll_remove_entries(req);
7142 /* no one else has access to the req, forget about the ref */
7145 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
7146 io_poll_remove_entries(req);
7148 ipt->error = -EINVAL;
7152 spin_lock(&ctx->completion_lock);
7153 io_poll_req_insert(req);
7154 spin_unlock(&ctx->completion_lock);
7157 /* can't multishot if failed, just queue the event we've got */
7158 if (unlikely(ipt->error || !ipt->nr_entries)) {
7159 poll->events |= EPOLLONESHOT;
7160 req->apoll_events |= EPOLLONESHOT;
7163 __io_poll_execute(req, mask, poll->events);
7168 * Release ownership. If someone tried to queue a tw while it was
7169 * locked, kick it off for them.
7171 v = atomic_dec_return(&req->poll_refs);
7172 if (unlikely(v & IO_POLL_REF_MASK))
7173 __io_poll_execute(req, 0, poll->events);
7177 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7178 struct poll_table_struct *p)
7180 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7181 struct async_poll *apoll = pt->req->apoll;
7183 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7192 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7194 const struct io_op_def *def = &io_op_defs[req->opcode];
7195 struct io_ring_ctx *ctx = req->ctx;
7196 struct async_poll *apoll;
7197 struct io_poll_table ipt;
7198 __poll_t mask = POLLPRI | POLLERR;
7201 if (!def->pollin && !def->pollout)
7202 return IO_APOLL_ABORTED;
7203 if (!file_can_poll(req->file))
7204 return IO_APOLL_ABORTED;
7205 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7206 return IO_APOLL_ABORTED;
7207 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7208 mask |= EPOLLONESHOT;
7211 mask |= EPOLLIN | EPOLLRDNORM;
7213 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7214 if ((req->opcode == IORING_OP_RECVMSG) &&
7215 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7218 mask |= EPOLLOUT | EPOLLWRNORM;
7220 if (def->poll_exclusive)
7221 mask |= EPOLLEXCLUSIVE;
7222 if (req->flags & REQ_F_POLLED) {
7224 kfree(apoll->double_poll);
7225 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7226 !list_empty(&ctx->apoll_cache)) {
7227 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7229 list_del_init(&apoll->poll.wait.entry);
7231 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7232 if (unlikely(!apoll))
7233 return IO_APOLL_ABORTED;
7235 apoll->double_poll = NULL;
7237 req->flags |= REQ_F_POLLED;
7238 ipt.pt._qproc = io_async_queue_proc;
7240 io_kbuf_recycle(req, issue_flags);
7242 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7243 if (ret || ipt.error)
7244 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7246 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7247 mask, apoll->poll.events);
7252 * Returns true if we found and killed one or more poll requests
7254 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7255 struct task_struct *tsk, bool cancel_all)
7257 struct hlist_node *tmp;
7258 struct io_kiocb *req;
7262 spin_lock(&ctx->completion_lock);
7263 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7264 struct hlist_head *list;
7266 list = &ctx->cancel_hash[i];
7267 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7268 if (io_match_task_safe(req, tsk, cancel_all)) {
7269 hlist_del_init(&req->hash_node);
7270 io_poll_cancel_req(req);
7275 spin_unlock(&ctx->completion_lock);
7279 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7280 struct io_cancel_data *cd)
7281 __must_hold(&ctx->completion_lock)
7283 struct hlist_head *list;
7284 struct io_kiocb *req;
7286 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7287 hlist_for_each_entry(req, list, hash_node) {
7288 if (cd->data != req->cqe.user_data)
7290 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7292 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7293 if (cd->seq == req->work.cancel_seq)
7295 req->work.cancel_seq = cd->seq;
7302 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7303 struct io_cancel_data *cd)
7304 __must_hold(&ctx->completion_lock)
7306 struct io_kiocb *req;
7309 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7310 struct hlist_head *list;
7312 list = &ctx->cancel_hash[i];
7313 hlist_for_each_entry(req, list, hash_node) {
7314 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7315 req->file != cd->file)
7317 if (cd->seq == req->work.cancel_seq)
7319 req->work.cancel_seq = cd->seq;
7326 static bool io_poll_disarm(struct io_kiocb *req)
7327 __must_hold(&ctx->completion_lock)
7329 if (!io_poll_get_ownership(req))
7331 io_poll_remove_entries(req);
7332 hash_del(&req->hash_node);
7336 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7337 __must_hold(&ctx->completion_lock)
7339 struct io_kiocb *req;
7341 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7342 req = io_poll_file_find(ctx, cd);
7344 req = io_poll_find(ctx, false, cd);
7347 io_poll_cancel_req(req);
7351 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7356 events = READ_ONCE(sqe->poll32_events);
7358 events = swahw32(events);
7360 if (!(flags & IORING_POLL_ADD_MULTI))
7361 events |= EPOLLONESHOT;
7362 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7365 static int io_poll_remove_prep(struct io_kiocb *req,
7366 const struct io_uring_sqe *sqe)
7368 struct io_poll_update *upd = &req->poll_update;
7371 if (sqe->buf_index || sqe->splice_fd_in)
7373 flags = READ_ONCE(sqe->len);
7374 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7375 IORING_POLL_ADD_MULTI))
7377 /* meaningless without update */
7378 if (flags == IORING_POLL_ADD_MULTI)
7381 upd->old_user_data = READ_ONCE(sqe->addr);
7382 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7383 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7385 upd->new_user_data = READ_ONCE(sqe->off);
7386 if (!upd->update_user_data && upd->new_user_data)
7388 if (upd->update_events)
7389 upd->events = io_poll_parse_events(sqe, flags);
7390 else if (sqe->poll32_events)
7396 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7398 struct io_poll_iocb *poll = &req->poll;
7401 if (sqe->buf_index || sqe->off || sqe->addr)
7403 flags = READ_ONCE(sqe->len);
7404 if (flags & ~IORING_POLL_ADD_MULTI)
7406 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7409 io_req_set_refcount(req);
7410 poll->events = io_poll_parse_events(sqe, flags);
7414 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7416 struct io_poll_iocb *poll = &req->poll;
7417 struct io_poll_table ipt;
7420 ipt.pt._qproc = io_poll_queue_proc;
7422 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7423 if (!ret && ipt.error)
7425 ret = ret ?: ipt.error;
7427 __io_req_complete(req, issue_flags, ret, 0);
7431 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7433 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7434 struct io_ring_ctx *ctx = req->ctx;
7435 struct io_kiocb *preq;
7439 spin_lock(&ctx->completion_lock);
7440 preq = io_poll_find(ctx, true, &cd);
7441 if (!preq || !io_poll_disarm(preq)) {
7442 spin_unlock(&ctx->completion_lock);
7443 ret = preq ? -EALREADY : -ENOENT;
7446 spin_unlock(&ctx->completion_lock);
7448 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7449 /* only mask one event flags, keep behavior flags */
7450 if (req->poll_update.update_events) {
7451 preq->poll.events &= ~0xffff;
7452 preq->poll.events |= req->poll_update.events & 0xffff;
7453 preq->poll.events |= IO_POLL_UNMASK;
7455 if (req->poll_update.update_user_data)
7456 preq->cqe.user_data = req->poll_update.new_user_data;
7458 ret2 = io_poll_add(preq, issue_flags);
7459 /* successfully updated, don't complete poll request */
7465 preq->cqe.res = -ECANCELED;
7466 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7467 io_req_task_complete(preq, &locked);
7471 /* complete update request, we're done with it */
7472 __io_req_complete(req, issue_flags, ret, 0);
7476 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7478 struct io_timeout_data *data = container_of(timer,
7479 struct io_timeout_data, timer);
7480 struct io_kiocb *req = data->req;
7481 struct io_ring_ctx *ctx = req->ctx;
7482 unsigned long flags;
7484 spin_lock_irqsave(&ctx->timeout_lock, flags);
7485 list_del_init(&req->timeout.list);
7486 atomic_set(&req->ctx->cq_timeouts,
7487 atomic_read(&req->ctx->cq_timeouts) + 1);
7488 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7490 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7493 req->cqe.res = -ETIME;
7494 req->io_task_work.func = io_req_task_complete;
7495 io_req_task_work_add(req);
7496 return HRTIMER_NORESTART;
7499 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7500 struct io_cancel_data *cd)
7501 __must_hold(&ctx->timeout_lock)
7503 struct io_timeout_data *io;
7504 struct io_kiocb *req;
7507 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7508 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7509 cd->data != req->cqe.user_data)
7511 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7512 if (cd->seq == req->work.cancel_seq)
7514 req->work.cancel_seq = cd->seq;
7520 return ERR_PTR(-ENOENT);
7522 io = req->async_data;
7523 if (hrtimer_try_to_cancel(&io->timer) == -1)
7524 return ERR_PTR(-EALREADY);
7525 list_del_init(&req->timeout.list);
7529 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7530 __must_hold(&ctx->completion_lock)
7532 struct io_kiocb *req;
7534 spin_lock_irq(&ctx->timeout_lock);
7535 req = io_timeout_extract(ctx, cd);
7536 spin_unlock_irq(&ctx->timeout_lock);
7539 return PTR_ERR(req);
7540 io_req_task_queue_fail(req, -ECANCELED);
7544 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7546 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7547 case IORING_TIMEOUT_BOOTTIME:
7548 return CLOCK_BOOTTIME;
7549 case IORING_TIMEOUT_REALTIME:
7550 return CLOCK_REALTIME;
7552 /* can't happen, vetted at prep time */
7556 return CLOCK_MONOTONIC;
7560 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7561 struct timespec64 *ts, enum hrtimer_mode mode)
7562 __must_hold(&ctx->timeout_lock)
7564 struct io_timeout_data *io;
7565 struct io_kiocb *req;
7568 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7569 found = user_data == req->cqe.user_data;
7576 io = req->async_data;
7577 if (hrtimer_try_to_cancel(&io->timer) == -1)
7579 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7580 io->timer.function = io_link_timeout_fn;
7581 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7585 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7586 struct timespec64 *ts, enum hrtimer_mode mode)
7587 __must_hold(&ctx->timeout_lock)
7589 struct io_cancel_data cd = { .data = user_data, };
7590 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7591 struct io_timeout_data *data;
7594 return PTR_ERR(req);
7596 req->timeout.off = 0; /* noseq */
7597 data = req->async_data;
7598 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7599 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7600 data->timer.function = io_timeout_fn;
7601 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7605 static int io_timeout_remove_prep(struct io_kiocb *req,
7606 const struct io_uring_sqe *sqe)
7608 struct io_timeout_rem *tr = &req->timeout_rem;
7610 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7612 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7615 tr->ltimeout = false;
7616 tr->addr = READ_ONCE(sqe->addr);
7617 tr->flags = READ_ONCE(sqe->timeout_flags);
7618 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7619 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7621 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7622 tr->ltimeout = true;
7623 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7625 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7627 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7629 } else if (tr->flags) {
7630 /* timeout removal doesn't support flags */
7637 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7639 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7644 * Remove or update an existing timeout command
7646 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7648 struct io_timeout_rem *tr = &req->timeout_rem;
7649 struct io_ring_ctx *ctx = req->ctx;
7652 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7653 struct io_cancel_data cd = { .data = tr->addr, };
7655 spin_lock(&ctx->completion_lock);
7656 ret = io_timeout_cancel(ctx, &cd);
7657 spin_unlock(&ctx->completion_lock);
7659 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7661 spin_lock_irq(&ctx->timeout_lock);
7663 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7665 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7666 spin_unlock_irq(&ctx->timeout_lock);
7671 io_req_complete_post(req, ret, 0);
7675 static int __io_timeout_prep(struct io_kiocb *req,
7676 const struct io_uring_sqe *sqe,
7677 bool is_timeout_link)
7679 struct io_timeout_data *data;
7681 u32 off = READ_ONCE(sqe->off);
7683 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7685 if (off && is_timeout_link)
7687 flags = READ_ONCE(sqe->timeout_flags);
7688 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7689 IORING_TIMEOUT_ETIME_SUCCESS))
7691 /* more than one clock specified is invalid, obviously */
7692 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7695 INIT_LIST_HEAD(&req->timeout.list);
7696 req->timeout.off = off;
7697 if (unlikely(off && !req->ctx->off_timeout_used))
7698 req->ctx->off_timeout_used = true;
7700 if (WARN_ON_ONCE(req_has_async_data(req)))
7702 if (io_alloc_async_data(req))
7705 data = req->async_data;
7707 data->flags = flags;
7709 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7712 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7715 INIT_LIST_HEAD(&req->timeout.list);
7716 data->mode = io_translate_timeout_mode(flags);
7717 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7719 if (is_timeout_link) {
7720 struct io_submit_link *link = &req->ctx->submit_state.link;
7724 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7726 req->timeout.head = link->last;
7727 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7732 static int io_timeout_prep(struct io_kiocb *req,
7733 const struct io_uring_sqe *sqe)
7735 return __io_timeout_prep(req, sqe, false);
7738 static int io_link_timeout_prep(struct io_kiocb *req,
7739 const struct io_uring_sqe *sqe)
7741 return __io_timeout_prep(req, sqe, true);
7744 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7746 struct io_ring_ctx *ctx = req->ctx;
7747 struct io_timeout_data *data = req->async_data;
7748 struct list_head *entry;
7749 u32 tail, off = req->timeout.off;
7751 spin_lock_irq(&ctx->timeout_lock);
7754 * sqe->off holds how many events that need to occur for this
7755 * timeout event to be satisfied. If it isn't set, then this is
7756 * a pure timeout request, sequence isn't used.
7758 if (io_is_timeout_noseq(req)) {
7759 entry = ctx->timeout_list.prev;
7763 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7764 req->timeout.target_seq = tail + off;
7766 /* Update the last seq here in case io_flush_timeouts() hasn't.
7767 * This is safe because ->completion_lock is held, and submissions
7768 * and completions are never mixed in the same ->completion_lock section.
7770 ctx->cq_last_tm_flush = tail;
7773 * Insertion sort, ensuring the first entry in the list is always
7774 * the one we need first.
7776 list_for_each_prev(entry, &ctx->timeout_list) {
7777 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7780 if (io_is_timeout_noseq(nxt))
7782 /* nxt.seq is behind @tail, otherwise would've been completed */
7783 if (off >= nxt->timeout.target_seq - tail)
7787 list_add(&req->timeout.list, entry);
7788 data->timer.function = io_timeout_fn;
7789 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7790 spin_unlock_irq(&ctx->timeout_lock);
7794 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7796 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7797 struct io_cancel_data *cd = data;
7799 if (req->ctx != cd->ctx)
7801 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7803 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7804 if (req->file != cd->file)
7807 if (req->cqe.user_data != cd->data)
7810 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7811 if (cd->seq == req->work.cancel_seq)
7813 req->work.cancel_seq = cd->seq;
7818 static int io_async_cancel_one(struct io_uring_task *tctx,
7819 struct io_cancel_data *cd)
7821 enum io_wq_cancel cancel_ret;
7825 if (!tctx || !tctx->io_wq)
7828 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7829 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7830 switch (cancel_ret) {
7831 case IO_WQ_CANCEL_OK:
7834 case IO_WQ_CANCEL_RUNNING:
7837 case IO_WQ_CANCEL_NOTFOUND:
7845 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7847 struct io_ring_ctx *ctx = req->ctx;
7850 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7852 ret = io_async_cancel_one(req->task->io_uring, cd);
7854 * Fall-through even for -EALREADY, as we may have poll armed
7855 * that need unarming.
7860 spin_lock(&ctx->completion_lock);
7861 ret = io_poll_cancel(ctx, cd);
7864 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7865 ret = io_timeout_cancel(ctx, cd);
7867 spin_unlock(&ctx->completion_lock);
7871 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7872 IORING_ASYNC_CANCEL_ANY)
7874 static int io_async_cancel_prep(struct io_kiocb *req,
7875 const struct io_uring_sqe *sqe)
7877 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7879 if (sqe->off || sqe->len || sqe->splice_fd_in)
7882 req->cancel.addr = READ_ONCE(sqe->addr);
7883 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7884 if (req->cancel.flags & ~CANCEL_FLAGS)
7886 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7887 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7889 req->cancel.fd = READ_ONCE(sqe->fd);
7895 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7896 unsigned int issue_flags)
7898 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7899 struct io_ring_ctx *ctx = cd->ctx;
7900 struct io_tctx_node *node;
7904 ret = io_try_cancel(req, cd);
7912 /* slow path, try all io-wq's */
7913 io_ring_submit_lock(ctx, issue_flags);
7915 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7916 struct io_uring_task *tctx = node->task->io_uring;
7918 ret = io_async_cancel_one(tctx, cd);
7919 if (ret != -ENOENT) {
7925 io_ring_submit_unlock(ctx, issue_flags);
7926 return all ? nr : ret;
7929 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7931 struct io_cancel_data cd = {
7933 .data = req->cancel.addr,
7934 .flags = req->cancel.flags,
7935 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7939 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7940 if (req->flags & REQ_F_FIXED_FILE)
7941 req->file = io_file_get_fixed(req, req->cancel.fd,
7944 req->file = io_file_get_normal(req, req->cancel.fd);
7949 cd.file = req->file;
7952 ret = __io_async_cancel(&cd, req, issue_flags);
7956 io_req_complete_post(req, ret, 0);
7960 static int io_files_update_prep(struct io_kiocb *req,
7961 const struct io_uring_sqe *sqe)
7963 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7965 if (sqe->rw_flags || sqe->splice_fd_in)
7968 req->rsrc_update.offset = READ_ONCE(sqe->off);
7969 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7970 if (!req->rsrc_update.nr_args)
7972 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7976 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7977 unsigned int issue_flags)
7979 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7984 if (!req->ctx->file_data)
7987 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7988 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7998 ret = io_fixed_fd_install(req, issue_flags, file,
7999 IORING_FILE_INDEX_ALLOC);
8002 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
8003 __io_close_fixed(req, issue_flags, ret);
8014 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
8016 struct io_ring_ctx *ctx = req->ctx;
8017 struct io_uring_rsrc_update2 up;
8020 up.offset = req->rsrc_update.offset;
8021 up.data = req->rsrc_update.arg;
8027 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
8028 ret = io_files_update_with_index_alloc(req, issue_flags);
8030 io_ring_submit_lock(ctx, issue_flags);
8031 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
8032 &up, req->rsrc_update.nr_args);
8033 io_ring_submit_unlock(ctx, issue_flags);
8038 __io_req_complete(req, issue_flags, ret, 0);
8042 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
8044 switch (req->opcode) {
8046 return io_nop_prep(req, sqe);
8047 case IORING_OP_READV:
8048 case IORING_OP_READ_FIXED:
8049 case IORING_OP_READ:
8050 case IORING_OP_WRITEV:
8051 case IORING_OP_WRITE_FIXED:
8052 case IORING_OP_WRITE:
8053 return io_prep_rw(req, sqe);
8054 case IORING_OP_POLL_ADD:
8055 return io_poll_add_prep(req, sqe);
8056 case IORING_OP_POLL_REMOVE:
8057 return io_poll_remove_prep(req, sqe);
8058 case IORING_OP_FSYNC:
8059 return io_fsync_prep(req, sqe);
8060 case IORING_OP_SYNC_FILE_RANGE:
8061 return io_sfr_prep(req, sqe);
8062 case IORING_OP_SENDMSG:
8063 case IORING_OP_SEND:
8064 return io_sendmsg_prep(req, sqe);
8065 case IORING_OP_RECVMSG:
8066 case IORING_OP_RECV:
8067 return io_recvmsg_prep(req, sqe);
8068 case IORING_OP_CONNECT:
8069 return io_connect_prep(req, sqe);
8070 case IORING_OP_TIMEOUT:
8071 return io_timeout_prep(req, sqe);
8072 case IORING_OP_TIMEOUT_REMOVE:
8073 return io_timeout_remove_prep(req, sqe);
8074 case IORING_OP_ASYNC_CANCEL:
8075 return io_async_cancel_prep(req, sqe);
8076 case IORING_OP_LINK_TIMEOUT:
8077 return io_link_timeout_prep(req, sqe);
8078 case IORING_OP_ACCEPT:
8079 return io_accept_prep(req, sqe);
8080 case IORING_OP_FALLOCATE:
8081 return io_fallocate_prep(req, sqe);
8082 case IORING_OP_OPENAT:
8083 return io_openat_prep(req, sqe);
8084 case IORING_OP_CLOSE:
8085 return io_close_prep(req, sqe);
8086 case IORING_OP_FILES_UPDATE:
8087 return io_files_update_prep(req, sqe);
8088 case IORING_OP_STATX:
8089 return io_statx_prep(req, sqe);
8090 case IORING_OP_FADVISE:
8091 return io_fadvise_prep(req, sqe);
8092 case IORING_OP_MADVISE:
8093 return io_madvise_prep(req, sqe);
8094 case IORING_OP_OPENAT2:
8095 return io_openat2_prep(req, sqe);
8096 case IORING_OP_EPOLL_CTL:
8097 return io_epoll_ctl_prep(req, sqe);
8098 case IORING_OP_SPLICE:
8099 return io_splice_prep(req, sqe);
8100 case IORING_OP_PROVIDE_BUFFERS:
8101 return io_provide_buffers_prep(req, sqe);
8102 case IORING_OP_REMOVE_BUFFERS:
8103 return io_remove_buffers_prep(req, sqe);
8105 return io_tee_prep(req, sqe);
8106 case IORING_OP_SHUTDOWN:
8107 return io_shutdown_prep(req, sqe);
8108 case IORING_OP_RENAMEAT:
8109 return io_renameat_prep(req, sqe);
8110 case IORING_OP_UNLINKAT:
8111 return io_unlinkat_prep(req, sqe);
8112 case IORING_OP_MKDIRAT:
8113 return io_mkdirat_prep(req, sqe);
8114 case IORING_OP_SYMLINKAT:
8115 return io_symlinkat_prep(req, sqe);
8116 case IORING_OP_LINKAT:
8117 return io_linkat_prep(req, sqe);
8118 case IORING_OP_MSG_RING:
8119 return io_msg_ring_prep(req, sqe);
8120 case IORING_OP_FSETXATTR:
8121 return io_fsetxattr_prep(req, sqe);
8122 case IORING_OP_SETXATTR:
8123 return io_setxattr_prep(req, sqe);
8124 case IORING_OP_FGETXATTR:
8125 return io_fgetxattr_prep(req, sqe);
8126 case IORING_OP_GETXATTR:
8127 return io_getxattr_prep(req, sqe);
8128 case IORING_OP_SOCKET:
8129 return io_socket_prep(req, sqe);
8130 case IORING_OP_URING_CMD:
8131 return io_uring_cmd_prep(req, sqe);
8134 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
8139 static int io_req_prep_async(struct io_kiocb *req)
8141 const struct io_op_def *def = &io_op_defs[req->opcode];
8143 /* assign early for deferred execution for non-fixed file */
8144 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
8145 req->file = io_file_get_normal(req, req->cqe.fd);
8146 if (!def->needs_async_setup)
8148 if (WARN_ON_ONCE(req_has_async_data(req)))
8150 if (io_alloc_async_data(req))
8153 switch (req->opcode) {
8154 case IORING_OP_READV:
8155 return io_readv_prep_async(req);
8156 case IORING_OP_WRITEV:
8157 return io_writev_prep_async(req);
8158 case IORING_OP_SENDMSG:
8159 return io_sendmsg_prep_async(req);
8160 case IORING_OP_RECVMSG:
8161 return io_recvmsg_prep_async(req);
8162 case IORING_OP_CONNECT:
8163 return io_connect_prep_async(req);
8164 case IORING_OP_URING_CMD:
8165 return io_uring_cmd_prep_async(req);
8167 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
8172 static u32 io_get_sequence(struct io_kiocb *req)
8174 u32 seq = req->ctx->cached_sq_head;
8175 struct io_kiocb *cur;
8177 /* need original cached_sq_head, but it was increased for each req */
8178 io_for_each_link(cur, req)
8183 static __cold void io_drain_req(struct io_kiocb *req)
8185 struct io_ring_ctx *ctx = req->ctx;
8186 struct io_defer_entry *de;
8188 u32 seq = io_get_sequence(req);
8190 /* Still need defer if there is pending req in defer list. */
8191 spin_lock(&ctx->completion_lock);
8192 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
8193 spin_unlock(&ctx->completion_lock);
8195 ctx->drain_active = false;
8196 io_req_task_queue(req);
8199 spin_unlock(&ctx->completion_lock);
8201 ret = io_req_prep_async(req);
8204 io_req_complete_failed(req, ret);
8207 io_prep_async_link(req);
8208 de = kmalloc(sizeof(*de), GFP_KERNEL);
8214 spin_lock(&ctx->completion_lock);
8215 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
8216 spin_unlock(&ctx->completion_lock);
8221 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
8224 list_add_tail(&de->list, &ctx->defer_list);
8225 spin_unlock(&ctx->completion_lock);
8228 static void io_clean_op(struct io_kiocb *req)
8230 if (req->flags & REQ_F_BUFFER_SELECTED) {
8231 spin_lock(&req->ctx->completion_lock);
8232 io_put_kbuf_comp(req);
8233 spin_unlock(&req->ctx->completion_lock);
8236 if (req->flags & REQ_F_NEED_CLEANUP) {
8237 switch (req->opcode) {
8238 case IORING_OP_READV:
8239 case IORING_OP_READ_FIXED:
8240 case IORING_OP_READ:
8241 case IORING_OP_WRITEV:
8242 case IORING_OP_WRITE_FIXED:
8243 case IORING_OP_WRITE: {
8244 struct io_async_rw *io = req->async_data;
8246 kfree(io->free_iovec);
8249 case IORING_OP_RECVMSG:
8250 case IORING_OP_SENDMSG: {
8251 struct io_async_msghdr *io = req->async_data;
8253 kfree(io->free_iov);
8256 case IORING_OP_OPENAT:
8257 case IORING_OP_OPENAT2:
8258 if (req->open.filename)
8259 putname(req->open.filename);
8261 case IORING_OP_RENAMEAT:
8262 putname(req->rename.oldpath);
8263 putname(req->rename.newpath);
8265 case IORING_OP_UNLINKAT:
8266 putname(req->unlink.filename);
8268 case IORING_OP_MKDIRAT:
8269 putname(req->mkdir.filename);
8271 case IORING_OP_SYMLINKAT:
8272 putname(req->symlink.oldpath);
8273 putname(req->symlink.newpath);
8275 case IORING_OP_LINKAT:
8276 putname(req->hardlink.oldpath);
8277 putname(req->hardlink.newpath);
8279 case IORING_OP_STATX:
8280 if (req->statx.filename)
8281 putname(req->statx.filename);
8283 case IORING_OP_SETXATTR:
8284 case IORING_OP_FSETXATTR:
8285 case IORING_OP_GETXATTR:
8286 case IORING_OP_FGETXATTR:
8287 __io_xattr_finish(req);
8291 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8292 kfree(req->apoll->double_poll);
8296 if (req->flags & REQ_F_INFLIGHT) {
8297 struct io_uring_task *tctx = req->task->io_uring;
8299 atomic_dec(&tctx->inflight_tracked);
8301 if (req->flags & REQ_F_CREDS)
8302 put_cred(req->creds);
8303 if (req->flags & REQ_F_ASYNC_DATA) {
8304 kfree(req->async_data);
8305 req->async_data = NULL;
8307 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8310 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8312 if (req->file || !io_op_defs[req->opcode].needs_file)
8315 if (req->flags & REQ_F_FIXED_FILE)
8316 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8318 req->file = io_file_get_normal(req, req->cqe.fd);
8323 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8325 const struct io_op_def *def = &io_op_defs[req->opcode];
8326 const struct cred *creds = NULL;
8329 if (unlikely(!io_assign_file(req, issue_flags)))
8332 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8333 creds = override_creds(req->creds);
8335 if (!def->audit_skip)
8336 audit_uring_entry(req->opcode);
8338 switch (req->opcode) {
8340 ret = io_nop(req, issue_flags);
8342 case IORING_OP_READV:
8343 case IORING_OP_READ_FIXED:
8344 case IORING_OP_READ:
8345 ret = io_read(req, issue_flags);
8347 case IORING_OP_WRITEV:
8348 case IORING_OP_WRITE_FIXED:
8349 case IORING_OP_WRITE:
8350 ret = io_write(req, issue_flags);
8352 case IORING_OP_FSYNC:
8353 ret = io_fsync(req, issue_flags);
8355 case IORING_OP_POLL_ADD:
8356 ret = io_poll_add(req, issue_flags);
8358 case IORING_OP_POLL_REMOVE:
8359 ret = io_poll_remove(req, issue_flags);
8361 case IORING_OP_SYNC_FILE_RANGE:
8362 ret = io_sync_file_range(req, issue_flags);
8364 case IORING_OP_SENDMSG:
8365 ret = io_sendmsg(req, issue_flags);
8367 case IORING_OP_SEND:
8368 ret = io_send(req, issue_flags);
8370 case IORING_OP_RECVMSG:
8371 ret = io_recvmsg(req, issue_flags);
8373 case IORING_OP_RECV:
8374 ret = io_recv(req, issue_flags);
8376 case IORING_OP_TIMEOUT:
8377 ret = io_timeout(req, issue_flags);
8379 case IORING_OP_TIMEOUT_REMOVE:
8380 ret = io_timeout_remove(req, issue_flags);
8382 case IORING_OP_ACCEPT:
8383 ret = io_accept(req, issue_flags);
8385 case IORING_OP_CONNECT:
8386 ret = io_connect(req, issue_flags);
8388 case IORING_OP_ASYNC_CANCEL:
8389 ret = io_async_cancel(req, issue_flags);
8391 case IORING_OP_FALLOCATE:
8392 ret = io_fallocate(req, issue_flags);
8394 case IORING_OP_OPENAT:
8395 ret = io_openat(req, issue_flags);
8397 case IORING_OP_CLOSE:
8398 ret = io_close(req, issue_flags);
8400 case IORING_OP_FILES_UPDATE:
8401 ret = io_files_update(req, issue_flags);
8403 case IORING_OP_STATX:
8404 ret = io_statx(req, issue_flags);
8406 case IORING_OP_FADVISE:
8407 ret = io_fadvise(req, issue_flags);
8409 case IORING_OP_MADVISE:
8410 ret = io_madvise(req, issue_flags);
8412 case IORING_OP_OPENAT2:
8413 ret = io_openat2(req, issue_flags);
8415 case IORING_OP_EPOLL_CTL:
8416 ret = io_epoll_ctl(req, issue_flags);
8418 case IORING_OP_SPLICE:
8419 ret = io_splice(req, issue_flags);
8421 case IORING_OP_PROVIDE_BUFFERS:
8422 ret = io_provide_buffers(req, issue_flags);
8424 case IORING_OP_REMOVE_BUFFERS:
8425 ret = io_remove_buffers(req, issue_flags);
8428 ret = io_tee(req, issue_flags);
8430 case IORING_OP_SHUTDOWN:
8431 ret = io_shutdown(req, issue_flags);
8433 case IORING_OP_RENAMEAT:
8434 ret = io_renameat(req, issue_flags);
8436 case IORING_OP_UNLINKAT:
8437 ret = io_unlinkat(req, issue_flags);
8439 case IORING_OP_MKDIRAT:
8440 ret = io_mkdirat(req, issue_flags);
8442 case IORING_OP_SYMLINKAT:
8443 ret = io_symlinkat(req, issue_flags);
8445 case IORING_OP_LINKAT:
8446 ret = io_linkat(req, issue_flags);
8448 case IORING_OP_MSG_RING:
8449 ret = io_msg_ring(req, issue_flags);
8451 case IORING_OP_FSETXATTR:
8452 ret = io_fsetxattr(req, issue_flags);
8454 case IORING_OP_SETXATTR:
8455 ret = io_setxattr(req, issue_flags);
8457 case IORING_OP_FGETXATTR:
8458 ret = io_fgetxattr(req, issue_flags);
8460 case IORING_OP_GETXATTR:
8461 ret = io_getxattr(req, issue_flags);
8463 case IORING_OP_SOCKET:
8464 ret = io_socket(req, issue_flags);
8466 case IORING_OP_URING_CMD:
8467 ret = io_uring_cmd(req, issue_flags);
8474 if (!def->audit_skip)
8475 audit_uring_exit(!ret, ret);
8478 revert_creds(creds);
8481 /* If the op doesn't have a file, we're not polling for it */
8482 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8483 io_iopoll_req_issued(req, issue_flags);
8488 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8490 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8492 req = io_put_req_find_next(req);
8493 return req ? &req->work : NULL;
8496 static void io_wq_submit_work(struct io_wq_work *work)
8498 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8499 const struct io_op_def *def = &io_op_defs[req->opcode];
8500 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8501 bool needs_poll = false;
8502 int ret = 0, err = -ECANCELED;
8504 /* one will be dropped by ->io_free_work() after returning to io-wq */
8505 if (!(req->flags & REQ_F_REFCOUNT))
8506 __io_req_set_refcount(req, 2);
8510 io_arm_ltimeout(req);
8512 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8513 if (work->flags & IO_WQ_WORK_CANCEL) {
8515 io_req_task_queue_fail(req, err);
8518 if (!io_assign_file(req, issue_flags)) {
8520 work->flags |= IO_WQ_WORK_CANCEL;
8524 if (req->flags & REQ_F_FORCE_ASYNC) {
8525 bool opcode_poll = def->pollin || def->pollout;
8527 if (opcode_poll && file_can_poll(req->file)) {
8529 issue_flags |= IO_URING_F_NONBLOCK;
8534 ret = io_issue_sqe(req, issue_flags);
8538 * We can get EAGAIN for iopolled IO even though we're
8539 * forcing a sync submission from here, since we can't
8540 * wait for request slots on the block side.
8543 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8549 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8551 /* aborted or ready, in either case retry blocking */
8553 issue_flags &= ~IO_URING_F_NONBLOCK;
8556 /* avoid locking problems by failing it from a clean context */
8558 io_req_task_queue_fail(req, ret);
8561 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8564 return &table->files[i];
8567 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8570 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8572 return (struct file *) (slot->file_ptr & FFS_MASK);
8575 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8577 unsigned long file_ptr = (unsigned long) file;
8579 file_ptr |= io_file_get_flags(file);
8580 file_slot->file_ptr = file_ptr;
8583 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8584 unsigned int issue_flags)
8586 struct io_ring_ctx *ctx = req->ctx;
8587 struct file *file = NULL;
8588 unsigned long file_ptr;
8590 io_ring_submit_lock(ctx, issue_flags);
8592 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8594 fd = array_index_nospec(fd, ctx->nr_user_files);
8595 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8596 file = (struct file *) (file_ptr & FFS_MASK);
8597 file_ptr &= ~FFS_MASK;
8598 /* mask in overlapping REQ_F and FFS bits */
8599 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8600 io_req_set_rsrc_node(req, ctx, 0);
8601 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8603 io_ring_submit_unlock(ctx, issue_flags);
8607 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8609 struct file *file = fget(fd);
8611 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8613 /* we don't allow fixed io_uring files */
8614 if (file && file->f_op == &io_uring_fops)
8615 io_req_track_inflight(req);
8619 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8621 struct io_kiocb *prev = req->timeout.prev;
8625 if (!(req->task->flags & PF_EXITING)) {
8626 struct io_cancel_data cd = {
8628 .data = prev->cqe.user_data,
8631 ret = io_try_cancel(req, &cd);
8633 io_req_complete_post(req, ret ?: -ETIME, 0);
8636 io_req_complete_post(req, -ETIME, 0);
8640 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8642 struct io_timeout_data *data = container_of(timer,
8643 struct io_timeout_data, timer);
8644 struct io_kiocb *prev, *req = data->req;
8645 struct io_ring_ctx *ctx = req->ctx;
8646 unsigned long flags;
8648 spin_lock_irqsave(&ctx->timeout_lock, flags);
8649 prev = req->timeout.head;
8650 req->timeout.head = NULL;
8653 * We don't expect the list to be empty, that will only happen if we
8654 * race with the completion of the linked work.
8657 io_remove_next_linked(prev);
8658 if (!req_ref_inc_not_zero(prev))
8661 list_del(&req->timeout.list);
8662 req->timeout.prev = prev;
8663 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8665 req->io_task_work.func = io_req_task_link_timeout;
8666 io_req_task_work_add(req);
8667 return HRTIMER_NORESTART;
8670 static void io_queue_linked_timeout(struct io_kiocb *req)
8672 struct io_ring_ctx *ctx = req->ctx;
8674 spin_lock_irq(&ctx->timeout_lock);
8676 * If the back reference is NULL, then our linked request finished
8677 * before we got a chance to setup the timer
8679 if (req->timeout.head) {
8680 struct io_timeout_data *data = req->async_data;
8682 data->timer.function = io_link_timeout_fn;
8683 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8685 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8687 spin_unlock_irq(&ctx->timeout_lock);
8688 /* drop submission reference */
8692 static void io_queue_async(struct io_kiocb *req, int ret)
8693 __must_hold(&req->ctx->uring_lock)
8695 struct io_kiocb *linked_timeout;
8697 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8698 io_req_complete_failed(req, ret);
8702 linked_timeout = io_prep_linked_timeout(req);
8704 switch (io_arm_poll_handler(req, 0)) {
8705 case IO_APOLL_READY:
8706 io_req_task_queue(req);
8708 case IO_APOLL_ABORTED:
8710 * Queued up for async execution, worker will release
8711 * submit reference when the iocb is actually submitted.
8713 io_kbuf_recycle(req, 0);
8714 io_queue_iowq(req, NULL);
8721 io_queue_linked_timeout(linked_timeout);
8724 static inline void io_queue_sqe(struct io_kiocb *req)
8725 __must_hold(&req->ctx->uring_lock)
8729 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8731 if (req->flags & REQ_F_COMPLETE_INLINE) {
8732 io_req_add_compl_list(req);
8736 * We async punt it if the file wasn't marked NOWAIT, or if the file
8737 * doesn't support non-blocking read/write attempts
8740 io_arm_ltimeout(req);
8742 io_queue_async(req, ret);
8745 static void io_queue_sqe_fallback(struct io_kiocb *req)
8746 __must_hold(&req->ctx->uring_lock)
8748 if (unlikely(req->flags & REQ_F_FAIL)) {
8750 * We don't submit, fail them all, for that replace hardlinks
8751 * with normal links. Extra REQ_F_LINK is tolerated.
8753 req->flags &= ~REQ_F_HARDLINK;
8754 req->flags |= REQ_F_LINK;
8755 io_req_complete_failed(req, req->cqe.res);
8756 } else if (unlikely(req->ctx->drain_active)) {
8759 int ret = io_req_prep_async(req);
8762 io_req_complete_failed(req, ret);
8764 io_queue_iowq(req, NULL);
8769 * Check SQE restrictions (opcode and flags).
8771 * Returns 'true' if SQE is allowed, 'false' otherwise.
8773 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8774 struct io_kiocb *req,
8775 unsigned int sqe_flags)
8777 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8780 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8781 ctx->restrictions.sqe_flags_required)
8784 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8785 ctx->restrictions.sqe_flags_required))
8791 static void io_init_req_drain(struct io_kiocb *req)
8793 struct io_ring_ctx *ctx = req->ctx;
8794 struct io_kiocb *head = ctx->submit_state.link.head;
8796 ctx->drain_active = true;
8799 * If we need to drain a request in the middle of a link, drain
8800 * the head request and the next request/link after the current
8801 * link. Considering sequential execution of links,
8802 * REQ_F_IO_DRAIN will be maintained for every request of our
8805 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8806 ctx->drain_next = true;
8810 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8811 const struct io_uring_sqe *sqe)
8812 __must_hold(&ctx->uring_lock)
8814 const struct io_op_def *def;
8815 unsigned int sqe_flags;
8819 /* req is partially pre-initialised, see io_preinit_req() */
8820 req->opcode = opcode = READ_ONCE(sqe->opcode);
8821 /* same numerical values with corresponding REQ_F_*, safe to copy */
8822 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8823 req->cqe.user_data = READ_ONCE(sqe->user_data);
8825 req->rsrc_node = NULL;
8826 req->task = current;
8828 if (unlikely(opcode >= IORING_OP_LAST)) {
8832 def = &io_op_defs[opcode];
8833 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8834 /* enforce forwards compatibility on users */
8835 if (sqe_flags & ~SQE_VALID_FLAGS)
8837 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8838 if (!def->buffer_select)
8840 req->buf_index = READ_ONCE(sqe->buf_group);
8842 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8843 ctx->drain_disabled = true;
8844 if (sqe_flags & IOSQE_IO_DRAIN) {
8845 if (ctx->drain_disabled)
8847 io_init_req_drain(req);
8850 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8851 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8853 /* knock it to the slow queue path, will be drained there */
8854 if (ctx->drain_active)
8855 req->flags |= REQ_F_FORCE_ASYNC;
8856 /* if there is no link, we're at "next" request and need to drain */
8857 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8858 ctx->drain_next = false;
8859 ctx->drain_active = true;
8860 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8864 if (!def->ioprio && sqe->ioprio)
8866 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8869 if (def->needs_file) {
8870 struct io_submit_state *state = &ctx->submit_state;
8872 req->cqe.fd = READ_ONCE(sqe->fd);
8875 * Plug now if we have more than 2 IO left after this, and the
8876 * target is potentially a read/write to block based storage.
8878 if (state->need_plug && def->plug) {
8879 state->plug_started = true;
8880 state->need_plug = false;
8881 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8885 personality = READ_ONCE(sqe->personality);
8889 req->creds = xa_load(&ctx->personalities, personality);
8892 get_cred(req->creds);
8893 ret = security_uring_override_creds(req->creds);
8895 put_cred(req->creds);
8898 req->flags |= REQ_F_CREDS;
8901 return io_req_prep(req, sqe);
8904 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8905 struct io_kiocb *req, int ret)
8907 struct io_ring_ctx *ctx = req->ctx;
8908 struct io_submit_link *link = &ctx->submit_state.link;
8909 struct io_kiocb *head = link->head;
8911 trace_io_uring_req_failed(sqe, ctx, req, ret);
8914 * Avoid breaking links in the middle as it renders links with SQPOLL
8915 * unusable. Instead of failing eagerly, continue assembling the link if
8916 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8917 * should find the flag and handle the rest.
8919 req_fail_link_node(req, ret);
8920 if (head && !(head->flags & REQ_F_FAIL))
8921 req_fail_link_node(head, -ECANCELED);
8923 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8925 link->last->link = req;
8929 io_queue_sqe_fallback(req);
8934 link->last->link = req;
8941 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8942 const struct io_uring_sqe *sqe)
8943 __must_hold(&ctx->uring_lock)
8945 struct io_submit_link *link = &ctx->submit_state.link;
8948 ret = io_init_req(ctx, req, sqe);
8950 return io_submit_fail_init(sqe, req, ret);
8952 /* don't need @sqe from now on */
8953 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8955 ctx->flags & IORING_SETUP_SQPOLL);
8958 * If we already have a head request, queue this one for async
8959 * submittal once the head completes. If we don't have a head but
8960 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8961 * submitted sync once the chain is complete. If none of those
8962 * conditions are true (normal request), then just queue it.
8964 if (unlikely(link->head)) {
8965 ret = io_req_prep_async(req);
8967 return io_submit_fail_init(sqe, req, ret);
8969 trace_io_uring_link(ctx, req, link->head);
8970 link->last->link = req;
8973 if (req->flags & IO_REQ_LINK_FLAGS)
8975 /* last request of the link, flush it */
8978 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8981 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8982 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8983 if (req->flags & IO_REQ_LINK_FLAGS) {
8988 io_queue_sqe_fallback(req);
8998 * Batched submission is done, ensure local IO is flushed out.
9000 static void io_submit_state_end(struct io_ring_ctx *ctx)
9002 struct io_submit_state *state = &ctx->submit_state;
9004 if (unlikely(state->link.head))
9005 io_queue_sqe_fallback(state->link.head);
9006 /* flush only after queuing links as they can generate completions */
9007 io_submit_flush_completions(ctx);
9008 if (state->plug_started)
9009 blk_finish_plug(&state->plug);
9013 * Start submission side cache.
9015 static void io_submit_state_start(struct io_submit_state *state,
9016 unsigned int max_ios)
9018 state->plug_started = false;
9019 state->need_plug = max_ios > 2;
9020 state->submit_nr = max_ios;
9021 /* set only head, no need to init link_last in advance */
9022 state->link.head = NULL;
9025 static void io_commit_sqring(struct io_ring_ctx *ctx)
9027 struct io_rings *rings = ctx->rings;
9030 * Ensure any loads from the SQEs are done at this point,
9031 * since once we write the new head, the application could
9032 * write new data to them.
9034 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
9038 * Fetch an sqe, if one is available. Note this returns a pointer to memory
9039 * that is mapped by userspace. This means that care needs to be taken to
9040 * ensure that reads are stable, as we cannot rely on userspace always
9041 * being a good citizen. If members of the sqe are validated and then later
9042 * used, it's important that those reads are done through READ_ONCE() to
9043 * prevent a re-load down the line.
9045 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
9047 unsigned head, mask = ctx->sq_entries - 1;
9048 unsigned sq_idx = ctx->cached_sq_head++ & mask;
9051 * The cached sq head (or cq tail) serves two purposes:
9053 * 1) allows us to batch the cost of updating the user visible
9055 * 2) allows the kernel side to track the head on its own, even
9056 * though the application is the one updating it.
9058 head = READ_ONCE(ctx->sq_array[sq_idx]);
9059 if (likely(head < ctx->sq_entries)) {
9060 /* double index for 128-byte SQEs, twice as long */
9061 if (ctx->flags & IORING_SETUP_SQE128)
9063 return &ctx->sq_sqes[head];
9066 /* drop invalid entries */
9068 WRITE_ONCE(ctx->rings->sq_dropped,
9069 READ_ONCE(ctx->rings->sq_dropped) + 1);
9073 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
9074 __must_hold(&ctx->uring_lock)
9076 unsigned int entries = io_sqring_entries(ctx);
9080 if (unlikely(!entries))
9082 /* make sure SQ entry isn't read before tail */
9083 ret = left = min3(nr, ctx->sq_entries, entries);
9084 io_get_task_refs(left);
9085 io_submit_state_start(&ctx->submit_state, left);
9088 const struct io_uring_sqe *sqe;
9089 struct io_kiocb *req;
9091 if (unlikely(!io_alloc_req_refill(ctx)))
9093 req = io_alloc_req(ctx);
9094 sqe = io_get_sqe(ctx);
9095 if (unlikely(!sqe)) {
9096 io_req_add_to_cache(req, ctx);
9101 * Continue submitting even for sqe failure if the
9102 * ring was setup with IORING_SETUP_SUBMIT_ALL
9104 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
9105 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
9111 if (unlikely(left)) {
9113 /* try again if it submitted nothing and can't allocate a req */
9114 if (!ret && io_req_cache_empty(ctx))
9116 current->io_uring->cached_refs += left;
9119 io_submit_state_end(ctx);
9120 /* Commit SQ ring head once we've consumed and submitted all SQEs */
9121 io_commit_sqring(ctx);
9125 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
9127 return READ_ONCE(sqd->state);
9130 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
9132 unsigned int to_submit;
9135 to_submit = io_sqring_entries(ctx);
9136 /* if we're handling multiple rings, cap submit size for fairness */
9137 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
9138 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
9140 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
9141 const struct cred *creds = NULL;
9143 if (ctx->sq_creds != current_cred())
9144 creds = override_creds(ctx->sq_creds);
9146 mutex_lock(&ctx->uring_lock);
9147 if (!wq_list_empty(&ctx->iopoll_list))
9148 io_do_iopoll(ctx, true);
9151 * Don't submit if refs are dying, good for io_uring_register(),
9152 * but also it is relied upon by io_ring_exit_work()
9154 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
9155 !(ctx->flags & IORING_SETUP_R_DISABLED))
9156 ret = io_submit_sqes(ctx, to_submit);
9157 mutex_unlock(&ctx->uring_lock);
9159 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
9160 wake_up(&ctx->sqo_sq_wait);
9162 revert_creds(creds);
9168 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
9170 struct io_ring_ctx *ctx;
9171 unsigned sq_thread_idle = 0;
9173 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9174 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
9175 sqd->sq_thread_idle = sq_thread_idle;
9178 static bool io_sqd_handle_event(struct io_sq_data *sqd)
9180 bool did_sig = false;
9181 struct ksignal ksig;
9183 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
9184 signal_pending(current)) {
9185 mutex_unlock(&sqd->lock);
9186 if (signal_pending(current))
9187 did_sig = get_signal(&ksig);
9189 mutex_lock(&sqd->lock);
9191 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9194 static int io_sq_thread(void *data)
9196 struct io_sq_data *sqd = data;
9197 struct io_ring_ctx *ctx;
9198 unsigned long timeout = 0;
9199 char buf[TASK_COMM_LEN];
9202 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
9203 set_task_comm(current, buf);
9205 if (sqd->sq_cpu != -1)
9206 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
9208 set_cpus_allowed_ptr(current, cpu_online_mask);
9209 current->flags |= PF_NO_SETAFFINITY;
9211 audit_alloc_kernel(current);
9213 mutex_lock(&sqd->lock);
9215 bool cap_entries, sqt_spin = false;
9217 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
9218 if (io_sqd_handle_event(sqd))
9220 timeout = jiffies + sqd->sq_thread_idle;
9223 cap_entries = !list_is_singular(&sqd->ctx_list);
9224 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9225 int ret = __io_sq_thread(ctx, cap_entries);
9227 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
9230 if (io_run_task_work())
9233 if (sqt_spin || !time_after(jiffies, timeout)) {
9236 timeout = jiffies + sqd->sq_thread_idle;
9240 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
9241 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
9242 bool needs_sched = true;
9244 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9245 atomic_or(IORING_SQ_NEED_WAKEUP,
9246 &ctx->rings->sq_flags);
9247 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
9248 !wq_list_empty(&ctx->iopoll_list)) {
9249 needs_sched = false;
9254 * Ensure the store of the wakeup flag is not
9255 * reordered with the load of the SQ tail
9257 smp_mb__after_atomic();
9259 if (io_sqring_entries(ctx)) {
9260 needs_sched = false;
9266 mutex_unlock(&sqd->lock);
9268 mutex_lock(&sqd->lock);
9270 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9271 atomic_andnot(IORING_SQ_NEED_WAKEUP,
9272 &ctx->rings->sq_flags);
9275 finish_wait(&sqd->wait, &wait);
9276 timeout = jiffies + sqd->sq_thread_idle;
9279 io_uring_cancel_generic(true, sqd);
9281 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9282 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9284 mutex_unlock(&sqd->lock);
9286 audit_free(current);
9288 complete(&sqd->exited);
9292 struct io_wait_queue {
9293 struct wait_queue_entry wq;
9294 struct io_ring_ctx *ctx;
9296 unsigned nr_timeouts;
9299 static inline bool io_should_wake(struct io_wait_queue *iowq)
9301 struct io_ring_ctx *ctx = iowq->ctx;
9302 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9305 * Wake up if we have enough events, or if a timeout occurred since we
9306 * started waiting. For timeouts, we always want to return to userspace,
9307 * regardless of event count.
9309 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9312 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9313 int wake_flags, void *key)
9315 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9319 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9320 * the task, and the next invocation will do it.
9322 if (io_should_wake(iowq) ||
9323 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9324 return autoremove_wake_function(curr, mode, wake_flags, key);
9328 static int io_run_task_work_sig(void)
9330 if (io_run_task_work())
9332 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9333 return -ERESTARTSYS;
9334 if (task_sigpending(current))
9339 /* when returns >0, the caller should retry */
9340 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9341 struct io_wait_queue *iowq,
9345 unsigned long check_cq;
9347 /* make sure we run task_work before checking for signals */
9348 ret = io_run_task_work_sig();
9349 if (ret || io_should_wake(iowq))
9351 check_cq = READ_ONCE(ctx->check_cq);
9352 /* let the caller flush overflows, retry */
9353 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9355 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9357 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9363 * Wait until events become available, if we don't already have some. The
9364 * application must reap them itself, as they reside on the shared cq ring.
9366 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9367 const sigset_t __user *sig, size_t sigsz,
9368 struct __kernel_timespec __user *uts)
9370 struct io_wait_queue iowq;
9371 struct io_rings *rings = ctx->rings;
9372 ktime_t timeout = KTIME_MAX;
9376 io_cqring_overflow_flush(ctx);
9377 if (io_cqring_events(ctx) >= min_events)
9379 if (!io_run_task_work())
9384 #ifdef CONFIG_COMPAT
9385 if (in_compat_syscall())
9386 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9390 ret = set_user_sigmask(sig, sigsz);
9397 struct timespec64 ts;
9399 if (get_timespec64(&ts, uts))
9401 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9404 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9405 iowq.wq.private = current;
9406 INIT_LIST_HEAD(&iowq.wq.entry);
9408 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9409 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9411 trace_io_uring_cqring_wait(ctx, min_events);
9413 /* if we can't even flush overflow, don't wait for more */
9414 if (!io_cqring_overflow_flush(ctx)) {
9418 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9419 TASK_INTERRUPTIBLE);
9420 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9424 finish_wait(&ctx->cq_wait, &iowq.wq);
9425 restore_saved_sigmask_unless(ret == -EINTR);
9427 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9430 static void io_free_page_table(void **table, size_t size)
9432 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9434 for (i = 0; i < nr_tables; i++)
9439 static __cold void **io_alloc_page_table(size_t size)
9441 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9442 size_t init_size = size;
9445 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9449 for (i = 0; i < nr_tables; i++) {
9450 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9452 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9454 io_free_page_table(table, init_size);
9462 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9464 percpu_ref_exit(&ref_node->refs);
9468 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9470 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9471 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9472 unsigned long flags;
9473 bool first_add = false;
9474 unsigned long delay = HZ;
9476 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9479 /* if we are mid-quiesce then do not delay */
9480 if (node->rsrc_data->quiesce)
9483 while (!list_empty(&ctx->rsrc_ref_list)) {
9484 node = list_first_entry(&ctx->rsrc_ref_list,
9485 struct io_rsrc_node, node);
9486 /* recycle ref nodes in order */
9489 list_del(&node->node);
9490 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9492 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9495 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9498 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9500 struct io_rsrc_node *ref_node;
9502 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9506 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9511 INIT_LIST_HEAD(&ref_node->node);
9512 INIT_LIST_HEAD(&ref_node->rsrc_list);
9513 ref_node->done = false;
9517 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9518 struct io_rsrc_data *data_to_kill)
9519 __must_hold(&ctx->uring_lock)
9521 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9522 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9524 io_rsrc_refs_drop(ctx);
9527 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9529 rsrc_node->rsrc_data = data_to_kill;
9530 spin_lock_irq(&ctx->rsrc_ref_lock);
9531 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9532 spin_unlock_irq(&ctx->rsrc_ref_lock);
9534 atomic_inc(&data_to_kill->refs);
9535 percpu_ref_kill(&rsrc_node->refs);
9536 ctx->rsrc_node = NULL;
9539 if (!ctx->rsrc_node) {
9540 ctx->rsrc_node = ctx->rsrc_backup_node;
9541 ctx->rsrc_backup_node = NULL;
9545 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9547 if (ctx->rsrc_backup_node)
9549 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9550 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9553 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9554 struct io_ring_ctx *ctx)
9558 /* As we may drop ->uring_lock, other task may have started quiesce */
9562 data->quiesce = true;
9564 ret = io_rsrc_node_switch_start(ctx);
9567 io_rsrc_node_switch(ctx, data);
9569 /* kill initial ref, already quiesced if zero */
9570 if (atomic_dec_and_test(&data->refs))
9572 mutex_unlock(&ctx->uring_lock);
9573 flush_delayed_work(&ctx->rsrc_put_work);
9574 ret = wait_for_completion_interruptible(&data->done);
9576 mutex_lock(&ctx->uring_lock);
9577 if (atomic_read(&data->refs) > 0) {
9579 * it has been revived by another thread while
9582 mutex_unlock(&ctx->uring_lock);
9588 atomic_inc(&data->refs);
9589 /* wait for all works potentially completing data->done */
9590 flush_delayed_work(&ctx->rsrc_put_work);
9591 reinit_completion(&data->done);
9593 ret = io_run_task_work_sig();
9594 mutex_lock(&ctx->uring_lock);
9596 data->quiesce = false;
9601 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9603 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9604 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9606 return &data->tags[table_idx][off];
9609 static void io_rsrc_data_free(struct io_rsrc_data *data)
9611 size_t size = data->nr * sizeof(data->tags[0][0]);
9614 io_free_page_table((void **)data->tags, size);
9618 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9619 u64 __user *utags, unsigned nr,
9620 struct io_rsrc_data **pdata)
9622 struct io_rsrc_data *data;
9626 data = kzalloc(sizeof(*data), GFP_KERNEL);
9629 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9637 data->do_put = do_put;
9640 for (i = 0; i < nr; i++) {
9641 u64 *tag_slot = io_get_tag_slot(data, i);
9643 if (copy_from_user(tag_slot, &utags[i],
9649 atomic_set(&data->refs, 1);
9650 init_completion(&data->done);
9654 io_rsrc_data_free(data);
9658 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9660 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9661 GFP_KERNEL_ACCOUNT);
9662 if (unlikely(!table->files))
9665 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9666 if (unlikely(!table->bitmap)) {
9667 kvfree(table->files);
9674 static void io_free_file_tables(struct io_file_table *table)
9676 kvfree(table->files);
9677 bitmap_free(table->bitmap);
9678 table->files = NULL;
9679 table->bitmap = NULL;
9682 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9684 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9685 __set_bit(bit, table->bitmap);
9686 table->alloc_hint = bit + 1;
9689 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9691 __clear_bit(bit, table->bitmap);
9692 table->alloc_hint = bit;
9695 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9697 #if !defined(IO_URING_SCM_ALL)
9700 for (i = 0; i < ctx->nr_user_files; i++) {
9701 struct file *file = io_file_from_index(ctx, i);
9705 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9707 io_file_bitmap_clear(&ctx->file_table, i);
9712 #if defined(CONFIG_UNIX)
9713 if (ctx->ring_sock) {
9714 struct sock *sock = ctx->ring_sock->sk;
9715 struct sk_buff *skb;
9717 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9721 io_free_file_tables(&ctx->file_table);
9722 io_rsrc_data_free(ctx->file_data);
9723 ctx->file_data = NULL;
9724 ctx->nr_user_files = 0;
9727 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9729 unsigned nr = ctx->nr_user_files;
9732 if (!ctx->file_data)
9736 * Quiesce may unlock ->uring_lock, and while it's not held
9737 * prevent new requests using the table.
9739 ctx->nr_user_files = 0;
9740 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9741 ctx->nr_user_files = nr;
9743 __io_sqe_files_unregister(ctx);
9747 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9748 __releases(&sqd->lock)
9750 WARN_ON_ONCE(sqd->thread == current);
9753 * Do the dance but not conditional clear_bit() because it'd race with
9754 * other threads incrementing park_pending and setting the bit.
9756 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9757 if (atomic_dec_return(&sqd->park_pending))
9758 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9759 mutex_unlock(&sqd->lock);
9762 static void io_sq_thread_park(struct io_sq_data *sqd)
9763 __acquires(&sqd->lock)
9765 WARN_ON_ONCE(sqd->thread == current);
9767 atomic_inc(&sqd->park_pending);
9768 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9769 mutex_lock(&sqd->lock);
9771 wake_up_process(sqd->thread);
9774 static void io_sq_thread_stop(struct io_sq_data *sqd)
9776 WARN_ON_ONCE(sqd->thread == current);
9777 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9779 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9780 mutex_lock(&sqd->lock);
9782 wake_up_process(sqd->thread);
9783 mutex_unlock(&sqd->lock);
9784 wait_for_completion(&sqd->exited);
9787 static void io_put_sq_data(struct io_sq_data *sqd)
9789 if (refcount_dec_and_test(&sqd->refs)) {
9790 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9792 io_sq_thread_stop(sqd);
9797 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9799 struct io_sq_data *sqd = ctx->sq_data;
9802 io_sq_thread_park(sqd);
9803 list_del_init(&ctx->sqd_list);
9804 io_sqd_update_thread_idle(sqd);
9805 io_sq_thread_unpark(sqd);
9807 io_put_sq_data(sqd);
9808 ctx->sq_data = NULL;
9812 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9814 struct io_ring_ctx *ctx_attach;
9815 struct io_sq_data *sqd;
9818 f = fdget(p->wq_fd);
9820 return ERR_PTR(-ENXIO);
9821 if (f.file->f_op != &io_uring_fops) {
9823 return ERR_PTR(-EINVAL);
9826 ctx_attach = f.file->private_data;
9827 sqd = ctx_attach->sq_data;
9830 return ERR_PTR(-EINVAL);
9832 if (sqd->task_tgid != current->tgid) {
9834 return ERR_PTR(-EPERM);
9837 refcount_inc(&sqd->refs);
9842 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9845 struct io_sq_data *sqd;
9848 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9849 sqd = io_attach_sq_data(p);
9854 /* fall through for EPERM case, setup new sqd/task */
9855 if (PTR_ERR(sqd) != -EPERM)
9859 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9861 return ERR_PTR(-ENOMEM);
9863 atomic_set(&sqd->park_pending, 0);
9864 refcount_set(&sqd->refs, 1);
9865 INIT_LIST_HEAD(&sqd->ctx_list);
9866 mutex_init(&sqd->lock);
9867 init_waitqueue_head(&sqd->wait);
9868 init_completion(&sqd->exited);
9873 * Ensure the UNIX gc is aware of our file set, so we are certain that
9874 * the io_uring can be safely unregistered on process exit, even if we have
9875 * loops in the file referencing. We account only files that can hold other
9876 * files because otherwise they can't form a loop and so are not interesting
9879 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9881 #if defined(CONFIG_UNIX)
9882 struct sock *sk = ctx->ring_sock->sk;
9883 struct sk_buff_head *head = &sk->sk_receive_queue;
9884 struct scm_fp_list *fpl;
9885 struct sk_buff *skb;
9887 if (likely(!io_file_need_scm(file)))
9891 * See if we can merge this file into an existing skb SCM_RIGHTS
9892 * file set. If there's no room, fall back to allocating a new skb
9893 * and filling it in.
9895 spin_lock_irq(&head->lock);
9896 skb = skb_peek(head);
9897 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9898 __skb_unlink(skb, head);
9901 spin_unlock_irq(&head->lock);
9904 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9908 skb = alloc_skb(0, GFP_KERNEL);
9914 fpl->user = get_uid(current_user());
9915 fpl->max = SCM_MAX_FD;
9918 UNIXCB(skb).fp = fpl;
9920 skb->destructor = unix_destruct_scm;
9921 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9924 fpl = UNIXCB(skb).fp;
9925 fpl->fp[fpl->count++] = get_file(file);
9926 unix_inflight(fpl->user, file);
9927 skb_queue_head(head, skb);
9933 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9935 struct file *file = prsrc->file;
9936 #if defined(CONFIG_UNIX)
9937 struct sock *sock = ctx->ring_sock->sk;
9938 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9939 struct sk_buff *skb;
9942 if (!io_file_need_scm(file)) {
9947 __skb_queue_head_init(&list);
9950 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9951 * remove this entry and rearrange the file array.
9953 skb = skb_dequeue(head);
9955 struct scm_fp_list *fp;
9957 fp = UNIXCB(skb).fp;
9958 for (i = 0; i < fp->count; i++) {
9961 if (fp->fp[i] != file)
9964 unix_notinflight(fp->user, fp->fp[i]);
9965 left = fp->count - 1 - i;
9967 memmove(&fp->fp[i], &fp->fp[i + 1],
9968 left * sizeof(struct file *));
9975 __skb_queue_tail(&list, skb);
9985 __skb_queue_tail(&list, skb);
9987 skb = skb_dequeue(head);
9990 if (skb_peek(&list)) {
9991 spin_lock_irq(&head->lock);
9992 while ((skb = __skb_dequeue(&list)) != NULL)
9993 __skb_queue_tail(head, skb);
9994 spin_unlock_irq(&head->lock);
10001 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
10003 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
10004 struct io_ring_ctx *ctx = rsrc_data->ctx;
10005 struct io_rsrc_put *prsrc, *tmp;
10007 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
10008 list_del(&prsrc->list);
10011 if (ctx->flags & IORING_SETUP_IOPOLL)
10012 mutex_lock(&ctx->uring_lock);
10014 spin_lock(&ctx->completion_lock);
10015 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
10016 io_commit_cqring(ctx);
10017 spin_unlock(&ctx->completion_lock);
10018 io_cqring_ev_posted(ctx);
10020 if (ctx->flags & IORING_SETUP_IOPOLL)
10021 mutex_unlock(&ctx->uring_lock);
10024 rsrc_data->do_put(ctx, prsrc);
10028 io_rsrc_node_destroy(ref_node);
10029 if (atomic_dec_and_test(&rsrc_data->refs))
10030 complete(&rsrc_data->done);
10033 static void io_rsrc_put_work(struct work_struct *work)
10035 struct io_ring_ctx *ctx;
10036 struct llist_node *node;
10038 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
10039 node = llist_del_all(&ctx->rsrc_put_llist);
10042 struct io_rsrc_node *ref_node;
10043 struct llist_node *next = node->next;
10045 ref_node = llist_entry(node, struct io_rsrc_node, llist);
10046 __io_rsrc_put_work(ref_node);
10051 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
10052 unsigned nr_args, u64 __user *tags)
10054 __s32 __user *fds = (__s32 __user *) arg;
10059 if (ctx->file_data)
10063 if (nr_args > IORING_MAX_FIXED_FILES)
10065 if (nr_args > rlimit(RLIMIT_NOFILE))
10067 ret = io_rsrc_node_switch_start(ctx);
10070 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
10075 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
10076 io_rsrc_data_free(ctx->file_data);
10077 ctx->file_data = NULL;
10081 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
10082 struct io_fixed_file *file_slot;
10084 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
10088 /* allow sparse sets */
10089 if (!fds || fd == -1) {
10091 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
10098 if (unlikely(!file))
10102 * Don't allow io_uring instances to be registered. If UNIX
10103 * isn't enabled, then this causes a reference cycle and this
10104 * instance can never get freed. If UNIX is enabled we'll
10105 * handle it just fine, but there's still no point in allowing
10106 * a ring fd as it doesn't support regular read/write anyway.
10108 if (file->f_op == &io_uring_fops) {
10112 ret = io_scm_file_account(ctx, file);
10117 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10118 io_fixed_file_set(file_slot, file);
10119 io_file_bitmap_set(&ctx->file_table, i);
10122 io_rsrc_node_switch(ctx, NULL);
10125 __io_sqe_files_unregister(ctx);
10129 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
10130 struct io_rsrc_node *node, void *rsrc)
10132 u64 *tag_slot = io_get_tag_slot(data, idx);
10133 struct io_rsrc_put *prsrc;
10135 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
10139 prsrc->tag = *tag_slot;
10141 prsrc->rsrc = rsrc;
10142 list_add(&prsrc->list, &node->rsrc_list);
10146 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
10147 unsigned int issue_flags, u32 slot_index)
10148 __must_hold(&req->ctx->uring_lock)
10150 struct io_ring_ctx *ctx = req->ctx;
10151 bool needs_switch = false;
10152 struct io_fixed_file *file_slot;
10155 if (file->f_op == &io_uring_fops)
10157 if (!ctx->file_data)
10159 if (slot_index >= ctx->nr_user_files)
10162 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
10163 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
10165 if (file_slot->file_ptr) {
10166 struct file *old_file;
10168 ret = io_rsrc_node_switch_start(ctx);
10172 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10173 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
10174 ctx->rsrc_node, old_file);
10177 file_slot->file_ptr = 0;
10178 io_file_bitmap_clear(&ctx->file_table, slot_index);
10179 needs_switch = true;
10182 ret = io_scm_file_account(ctx, file);
10184 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
10185 io_fixed_file_set(file_slot, file);
10186 io_file_bitmap_set(&ctx->file_table, slot_index);
10190 io_rsrc_node_switch(ctx, ctx->file_data);
10196 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
10197 unsigned int offset)
10199 struct io_ring_ctx *ctx = req->ctx;
10200 struct io_fixed_file *file_slot;
10204 io_ring_submit_lock(ctx, issue_flags);
10206 if (unlikely(!ctx->file_data))
10209 if (offset >= ctx->nr_user_files)
10211 ret = io_rsrc_node_switch_start(ctx);
10215 offset = array_index_nospec(offset, ctx->nr_user_files);
10216 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
10218 if (!file_slot->file_ptr)
10221 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10222 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
10226 file_slot->file_ptr = 0;
10227 io_file_bitmap_clear(&ctx->file_table, offset);
10228 io_rsrc_node_switch(ctx, ctx->file_data);
10231 io_ring_submit_unlock(ctx, issue_flags);
10235 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
10237 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
10240 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
10241 struct io_uring_rsrc_update2 *up,
10244 u64 __user *tags = u64_to_user_ptr(up->tags);
10245 __s32 __user *fds = u64_to_user_ptr(up->data);
10246 struct io_rsrc_data *data = ctx->file_data;
10247 struct io_fixed_file *file_slot;
10249 int fd, i, err = 0;
10251 bool needs_switch = false;
10253 if (!ctx->file_data)
10255 if (up->offset + nr_args > ctx->nr_user_files)
10258 for (done = 0; done < nr_args; done++) {
10261 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
10262 copy_from_user(&fd, &fds[done], sizeof(fd))) {
10266 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
10270 if (fd == IORING_REGISTER_FILES_SKIP)
10273 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
10274 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10276 if (file_slot->file_ptr) {
10277 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10278 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
10281 file_slot->file_ptr = 0;
10282 io_file_bitmap_clear(&ctx->file_table, i);
10283 needs_switch = true;
10292 * Don't allow io_uring instances to be registered. If
10293 * UNIX isn't enabled, then this causes a reference
10294 * cycle and this instance can never get freed. If UNIX
10295 * is enabled we'll handle it just fine, but there's
10296 * still no point in allowing a ring fd as it doesn't
10297 * support regular read/write anyway.
10299 if (file->f_op == &io_uring_fops) {
10304 err = io_scm_file_account(ctx, file);
10309 *io_get_tag_slot(data, i) = tag;
10310 io_fixed_file_set(file_slot, file);
10311 io_file_bitmap_set(&ctx->file_table, i);
10316 io_rsrc_node_switch(ctx, data);
10317 return done ? done : err;
10320 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
10321 struct task_struct *task)
10323 struct io_wq_hash *hash;
10324 struct io_wq_data data;
10325 unsigned int concurrency;
10327 mutex_lock(&ctx->uring_lock);
10328 hash = ctx->hash_map;
10330 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10332 mutex_unlock(&ctx->uring_lock);
10333 return ERR_PTR(-ENOMEM);
10335 refcount_set(&hash->refs, 1);
10336 init_waitqueue_head(&hash->wait);
10337 ctx->hash_map = hash;
10339 mutex_unlock(&ctx->uring_lock);
10343 data.free_work = io_wq_free_work;
10344 data.do_work = io_wq_submit_work;
10346 /* Do QD, or 4 * CPUS, whatever is smallest */
10347 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10349 return io_wq_create(concurrency, &data);
10352 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10353 struct io_ring_ctx *ctx)
10355 struct io_uring_task *tctx;
10358 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10359 if (unlikely(!tctx))
10362 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10363 sizeof(struct file *), GFP_KERNEL);
10364 if (unlikely(!tctx->registered_rings)) {
10369 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10370 if (unlikely(ret)) {
10371 kfree(tctx->registered_rings);
10376 tctx->io_wq = io_init_wq_offload(ctx, task);
10377 if (IS_ERR(tctx->io_wq)) {
10378 ret = PTR_ERR(tctx->io_wq);
10379 percpu_counter_destroy(&tctx->inflight);
10380 kfree(tctx->registered_rings);
10385 xa_init(&tctx->xa);
10386 init_waitqueue_head(&tctx->wait);
10387 atomic_set(&tctx->in_idle, 0);
10388 atomic_set(&tctx->inflight_tracked, 0);
10389 task->io_uring = tctx;
10390 spin_lock_init(&tctx->task_lock);
10391 INIT_WQ_LIST(&tctx->task_list);
10392 INIT_WQ_LIST(&tctx->prio_task_list);
10393 init_task_work(&tctx->task_work, tctx_task_work);
10397 void __io_uring_free(struct task_struct *tsk)
10399 struct io_uring_task *tctx = tsk->io_uring;
10401 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10402 WARN_ON_ONCE(tctx->io_wq);
10403 WARN_ON_ONCE(tctx->cached_refs);
10405 kfree(tctx->registered_rings);
10406 percpu_counter_destroy(&tctx->inflight);
10408 tsk->io_uring = NULL;
10411 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10412 struct io_uring_params *p)
10416 /* Retain compatibility with failing for an invalid attach attempt */
10417 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10418 IORING_SETUP_ATTACH_WQ) {
10421 f = fdget(p->wq_fd);
10424 if (f.file->f_op != &io_uring_fops) {
10430 if (ctx->flags & IORING_SETUP_SQPOLL) {
10431 struct task_struct *tsk;
10432 struct io_sq_data *sqd;
10435 ret = security_uring_sqpoll();
10439 sqd = io_get_sq_data(p, &attached);
10441 ret = PTR_ERR(sqd);
10445 ctx->sq_creds = get_current_cred();
10446 ctx->sq_data = sqd;
10447 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10448 if (!ctx->sq_thread_idle)
10449 ctx->sq_thread_idle = HZ;
10451 io_sq_thread_park(sqd);
10452 list_add(&ctx->sqd_list, &sqd->ctx_list);
10453 io_sqd_update_thread_idle(sqd);
10454 /* don't attach to a dying SQPOLL thread, would be racy */
10455 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10456 io_sq_thread_unpark(sqd);
10463 if (p->flags & IORING_SETUP_SQ_AFF) {
10464 int cpu = p->sq_thread_cpu;
10467 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10474 sqd->task_pid = current->pid;
10475 sqd->task_tgid = current->tgid;
10476 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10478 ret = PTR_ERR(tsk);
10483 ret = io_uring_alloc_task_context(tsk, ctx);
10484 wake_up_new_task(tsk);
10487 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10488 /* Can't have SQ_AFF without SQPOLL */
10495 complete(&ctx->sq_data->exited);
10497 io_sq_thread_finish(ctx);
10501 static inline void __io_unaccount_mem(struct user_struct *user,
10502 unsigned long nr_pages)
10504 atomic_long_sub(nr_pages, &user->locked_vm);
10507 static inline int __io_account_mem(struct user_struct *user,
10508 unsigned long nr_pages)
10510 unsigned long page_limit, cur_pages, new_pages;
10512 /* Don't allow more pages than we can safely lock */
10513 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10516 cur_pages = atomic_long_read(&user->locked_vm);
10517 new_pages = cur_pages + nr_pages;
10518 if (new_pages > page_limit)
10520 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10521 new_pages) != cur_pages);
10526 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10529 __io_unaccount_mem(ctx->user, nr_pages);
10531 if (ctx->mm_account)
10532 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10535 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10540 ret = __io_account_mem(ctx->user, nr_pages);
10545 if (ctx->mm_account)
10546 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10551 static void io_mem_free(void *ptr)
10558 page = virt_to_head_page(ptr);
10559 if (put_page_testzero(page))
10560 free_compound_page(page);
10563 static void *io_mem_alloc(size_t size)
10565 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10567 return (void *) __get_free_pages(gfp, get_order(size));
10570 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10571 unsigned int cq_entries, size_t *sq_offset)
10573 struct io_rings *rings;
10574 size_t off, sq_array_size;
10576 off = struct_size(rings, cqes, cq_entries);
10577 if (off == SIZE_MAX)
10579 if (ctx->flags & IORING_SETUP_CQE32) {
10580 if (check_shl_overflow(off, 1, &off))
10585 off = ALIGN(off, SMP_CACHE_BYTES);
10593 sq_array_size = array_size(sizeof(u32), sq_entries);
10594 if (sq_array_size == SIZE_MAX)
10597 if (check_add_overflow(off, sq_array_size, &off))
10603 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10605 struct io_mapped_ubuf *imu = *slot;
10608 if (imu != ctx->dummy_ubuf) {
10609 for (i = 0; i < imu->nr_bvecs; i++)
10610 unpin_user_page(imu->bvec[i].bv_page);
10611 if (imu->acct_pages)
10612 io_unaccount_mem(ctx, imu->acct_pages);
10618 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10620 io_buffer_unmap(ctx, &prsrc->buf);
10624 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10628 for (i = 0; i < ctx->nr_user_bufs; i++)
10629 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10630 kfree(ctx->user_bufs);
10631 io_rsrc_data_free(ctx->buf_data);
10632 ctx->user_bufs = NULL;
10633 ctx->buf_data = NULL;
10634 ctx->nr_user_bufs = 0;
10637 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10639 unsigned nr = ctx->nr_user_bufs;
10642 if (!ctx->buf_data)
10646 * Quiesce may unlock ->uring_lock, and while it's not held
10647 * prevent new requests using the table.
10649 ctx->nr_user_bufs = 0;
10650 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10651 ctx->nr_user_bufs = nr;
10653 __io_sqe_buffers_unregister(ctx);
10657 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10658 void __user *arg, unsigned index)
10660 struct iovec __user *src;
10662 #ifdef CONFIG_COMPAT
10664 struct compat_iovec __user *ciovs;
10665 struct compat_iovec ciov;
10667 ciovs = (struct compat_iovec __user *) arg;
10668 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10671 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10672 dst->iov_len = ciov.iov_len;
10676 src = (struct iovec __user *) arg;
10677 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10683 * Not super efficient, but this is just a registration time. And we do cache
10684 * the last compound head, so generally we'll only do a full search if we don't
10687 * We check if the given compound head page has already been accounted, to
10688 * avoid double accounting it. This allows us to account the full size of the
10689 * page, not just the constituent pages of a huge page.
10691 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10692 int nr_pages, struct page *hpage)
10696 /* check current page array */
10697 for (i = 0; i < nr_pages; i++) {
10698 if (!PageCompound(pages[i]))
10700 if (compound_head(pages[i]) == hpage)
10704 /* check previously registered pages */
10705 for (i = 0; i < ctx->nr_user_bufs; i++) {
10706 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10708 for (j = 0; j < imu->nr_bvecs; j++) {
10709 if (!PageCompound(imu->bvec[j].bv_page))
10711 if (compound_head(imu->bvec[j].bv_page) == hpage)
10719 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10720 int nr_pages, struct io_mapped_ubuf *imu,
10721 struct page **last_hpage)
10725 imu->acct_pages = 0;
10726 for (i = 0; i < nr_pages; i++) {
10727 if (!PageCompound(pages[i])) {
10730 struct page *hpage;
10732 hpage = compound_head(pages[i]);
10733 if (hpage == *last_hpage)
10735 *last_hpage = hpage;
10736 if (headpage_already_acct(ctx, pages, i, hpage))
10738 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10742 if (!imu->acct_pages)
10745 ret = io_account_mem(ctx, imu->acct_pages);
10747 imu->acct_pages = 0;
10751 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10754 unsigned long start, end, nr_pages;
10755 struct vm_area_struct **vmas = NULL;
10756 struct page **pages = NULL;
10757 int i, pret, ret = -ENOMEM;
10759 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10760 start = ubuf >> PAGE_SHIFT;
10761 nr_pages = end - start;
10763 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10767 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10773 mmap_read_lock(current->mm);
10774 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10776 if (pret == nr_pages) {
10777 /* don't support file backed memory */
10778 for (i = 0; i < nr_pages; i++) {
10779 struct vm_area_struct *vma = vmas[i];
10781 if (vma_is_shmem(vma))
10783 if (vma->vm_file &&
10784 !is_file_hugepages(vma->vm_file)) {
10789 *npages = nr_pages;
10791 ret = pret < 0 ? pret : -EFAULT;
10793 mmap_read_unlock(current->mm);
10796 * if we did partial map, or found file backed vmas,
10797 * release any pages we did get
10800 unpin_user_pages(pages, pret);
10808 pages = ERR_PTR(ret);
10813 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10814 struct io_mapped_ubuf **pimu,
10815 struct page **last_hpage)
10817 struct io_mapped_ubuf *imu = NULL;
10818 struct page **pages = NULL;
10821 int ret, nr_pages, i;
10823 if (!iov->iov_base) {
10824 *pimu = ctx->dummy_ubuf;
10831 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10833 if (IS_ERR(pages)) {
10834 ret = PTR_ERR(pages);
10839 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10843 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10845 unpin_user_pages(pages, nr_pages);
10849 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10850 size = iov->iov_len;
10851 for (i = 0; i < nr_pages; i++) {
10854 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10855 imu->bvec[i].bv_page = pages[i];
10856 imu->bvec[i].bv_len = vec_len;
10857 imu->bvec[i].bv_offset = off;
10861 /* store original address for later verification */
10862 imu->ubuf = (unsigned long) iov->iov_base;
10863 imu->ubuf_end = imu->ubuf + iov->iov_len;
10864 imu->nr_bvecs = nr_pages;
10874 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10876 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10877 return ctx->user_bufs ? 0 : -ENOMEM;
10880 static int io_buffer_validate(struct iovec *iov)
10882 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10885 * Don't impose further limits on the size and buffer
10886 * constraints here, we'll -EINVAL later when IO is
10887 * submitted if they are wrong.
10889 if (!iov->iov_base)
10890 return iov->iov_len ? -EFAULT : 0;
10894 /* arbitrary limit, but we need something */
10895 if (iov->iov_len > SZ_1G)
10898 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10904 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10905 unsigned int nr_args, u64 __user *tags)
10907 struct page *last_hpage = NULL;
10908 struct io_rsrc_data *data;
10912 if (ctx->user_bufs)
10914 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10916 ret = io_rsrc_node_switch_start(ctx);
10919 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10922 ret = io_buffers_map_alloc(ctx, nr_args);
10924 io_rsrc_data_free(data);
10928 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10930 ret = io_copy_iov(ctx, &iov, arg, i);
10933 ret = io_buffer_validate(&iov);
10937 memset(&iov, 0, sizeof(iov));
10940 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10945 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10951 WARN_ON_ONCE(ctx->buf_data);
10953 ctx->buf_data = data;
10955 __io_sqe_buffers_unregister(ctx);
10957 io_rsrc_node_switch(ctx, NULL);
10961 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10962 struct io_uring_rsrc_update2 *up,
10963 unsigned int nr_args)
10965 u64 __user *tags = u64_to_user_ptr(up->tags);
10966 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10967 struct page *last_hpage = NULL;
10968 bool needs_switch = false;
10972 if (!ctx->buf_data)
10974 if (up->offset + nr_args > ctx->nr_user_bufs)
10977 for (done = 0; done < nr_args; done++) {
10978 struct io_mapped_ubuf *imu;
10979 int offset = up->offset + done;
10982 err = io_copy_iov(ctx, &iov, iovs, done);
10985 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10989 err = io_buffer_validate(&iov);
10992 if (!iov.iov_base && tag) {
10996 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
11000 i = array_index_nospec(offset, ctx->nr_user_bufs);
11001 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
11002 err = io_queue_rsrc_removal(ctx->buf_data, i,
11003 ctx->rsrc_node, ctx->user_bufs[i]);
11004 if (unlikely(err)) {
11005 io_buffer_unmap(ctx, &imu);
11008 ctx->user_bufs[i] = NULL;
11009 needs_switch = true;
11012 ctx->user_bufs[i] = imu;
11013 *io_get_tag_slot(ctx->buf_data, offset) = tag;
11017 io_rsrc_node_switch(ctx, ctx->buf_data);
11018 return done ? done : err;
11021 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
11022 unsigned int eventfd_async)
11024 struct io_ev_fd *ev_fd;
11025 __s32 __user *fds = arg;
11028 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11029 lockdep_is_held(&ctx->uring_lock));
11033 if (copy_from_user(&fd, fds, sizeof(*fds)))
11036 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
11040 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
11041 if (IS_ERR(ev_fd->cq_ev_fd)) {
11042 int ret = PTR_ERR(ev_fd->cq_ev_fd);
11046 ev_fd->eventfd_async = eventfd_async;
11047 ctx->has_evfd = true;
11048 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
11052 static void io_eventfd_put(struct rcu_head *rcu)
11054 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
11056 eventfd_ctx_put(ev_fd->cq_ev_fd);
11060 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
11062 struct io_ev_fd *ev_fd;
11064 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11065 lockdep_is_held(&ctx->uring_lock));
11067 ctx->has_evfd = false;
11068 rcu_assign_pointer(ctx->io_ev_fd, NULL);
11069 call_rcu(&ev_fd->rcu, io_eventfd_put);
11076 static void io_destroy_buffers(struct io_ring_ctx *ctx)
11078 struct io_buffer_list *bl;
11079 unsigned long index;
11082 for (i = 0; i < BGID_ARRAY; i++) {
11085 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
11088 xa_for_each(&ctx->io_bl_xa, index, bl) {
11089 xa_erase(&ctx->io_bl_xa, bl->bgid);
11090 __io_remove_buffers(ctx, bl, -1U);
11094 while (!list_empty(&ctx->io_buffers_pages)) {
11097 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
11098 list_del_init(&page->lru);
11103 static void io_req_caches_free(struct io_ring_ctx *ctx)
11105 struct io_submit_state *state = &ctx->submit_state;
11108 mutex_lock(&ctx->uring_lock);
11109 io_flush_cached_locked_reqs(ctx, state);
11111 while (!io_req_cache_empty(ctx)) {
11112 struct io_wq_work_node *node;
11113 struct io_kiocb *req;
11115 node = wq_stack_extract(&state->free_list);
11116 req = container_of(node, struct io_kiocb, comp_list);
11117 kmem_cache_free(req_cachep, req);
11121 percpu_ref_put_many(&ctx->refs, nr);
11122 mutex_unlock(&ctx->uring_lock);
11125 static void io_wait_rsrc_data(struct io_rsrc_data *data)
11127 if (data && !atomic_dec_and_test(&data->refs))
11128 wait_for_completion(&data->done);
11131 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
11133 struct async_poll *apoll;
11135 while (!list_empty(&ctx->apoll_cache)) {
11136 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
11138 list_del(&apoll->poll.wait.entry);
11143 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
11145 io_sq_thread_finish(ctx);
11147 if (ctx->mm_account) {
11148 mmdrop(ctx->mm_account);
11149 ctx->mm_account = NULL;
11152 io_rsrc_refs_drop(ctx);
11153 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
11154 io_wait_rsrc_data(ctx->buf_data);
11155 io_wait_rsrc_data(ctx->file_data);
11157 mutex_lock(&ctx->uring_lock);
11159 __io_sqe_buffers_unregister(ctx);
11160 if (ctx->file_data)
11161 __io_sqe_files_unregister(ctx);
11163 __io_cqring_overflow_flush(ctx, true);
11164 io_eventfd_unregister(ctx);
11165 io_flush_apoll_cache(ctx);
11166 mutex_unlock(&ctx->uring_lock);
11167 io_destroy_buffers(ctx);
11169 put_cred(ctx->sq_creds);
11171 /* there are no registered resources left, nobody uses it */
11172 if (ctx->rsrc_node)
11173 io_rsrc_node_destroy(ctx->rsrc_node);
11174 if (ctx->rsrc_backup_node)
11175 io_rsrc_node_destroy(ctx->rsrc_backup_node);
11176 flush_delayed_work(&ctx->rsrc_put_work);
11177 flush_delayed_work(&ctx->fallback_work);
11179 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
11180 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
11182 #if defined(CONFIG_UNIX)
11183 if (ctx->ring_sock) {
11184 ctx->ring_sock->file = NULL; /* so that iput() is called */
11185 sock_release(ctx->ring_sock);
11188 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
11190 io_mem_free(ctx->rings);
11191 io_mem_free(ctx->sq_sqes);
11193 percpu_ref_exit(&ctx->refs);
11194 free_uid(ctx->user);
11195 io_req_caches_free(ctx);
11197 io_wq_put_hash(ctx->hash_map);
11198 kfree(ctx->cancel_hash);
11199 kfree(ctx->dummy_ubuf);
11201 xa_destroy(&ctx->io_bl_xa);
11205 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
11207 struct io_ring_ctx *ctx = file->private_data;
11210 poll_wait(file, &ctx->cq_wait, wait);
11212 * synchronizes with barrier from wq_has_sleeper call in
11216 if (!io_sqring_full(ctx))
11217 mask |= EPOLLOUT | EPOLLWRNORM;
11220 * Don't flush cqring overflow list here, just do a simple check.
11221 * Otherwise there could possible be ABBA deadlock:
11224 * lock(&ctx->uring_lock);
11226 * lock(&ctx->uring_lock);
11229 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
11230 * pushs them to do the flush.
11232 if (io_cqring_events(ctx) ||
11233 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
11234 mask |= EPOLLIN | EPOLLRDNORM;
11239 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
11241 const struct cred *creds;
11243 creds = xa_erase(&ctx->personalities, id);
11252 struct io_tctx_exit {
11253 struct callback_head task_work;
11254 struct completion completion;
11255 struct io_ring_ctx *ctx;
11258 static __cold void io_tctx_exit_cb(struct callback_head *cb)
11260 struct io_uring_task *tctx = current->io_uring;
11261 struct io_tctx_exit *work;
11263 work = container_of(cb, struct io_tctx_exit, task_work);
11265 * When @in_idle, we're in cancellation and it's racy to remove the
11266 * node. It'll be removed by the end of cancellation, just ignore it.
11268 if (!atomic_read(&tctx->in_idle))
11269 io_uring_del_tctx_node((unsigned long)work->ctx);
11270 complete(&work->completion);
11273 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
11275 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11277 return req->ctx == data;
11280 static __cold void io_ring_exit_work(struct work_struct *work)
11282 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
11283 unsigned long timeout = jiffies + HZ * 60 * 5;
11284 unsigned long interval = HZ / 20;
11285 struct io_tctx_exit exit;
11286 struct io_tctx_node *node;
11290 * If we're doing polled IO and end up having requests being
11291 * submitted async (out-of-line), then completions can come in while
11292 * we're waiting for refs to drop. We need to reap these manually,
11293 * as nobody else will be looking for them.
11296 io_uring_try_cancel_requests(ctx, NULL, true);
11297 if (ctx->sq_data) {
11298 struct io_sq_data *sqd = ctx->sq_data;
11299 struct task_struct *tsk;
11301 io_sq_thread_park(sqd);
11303 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
11304 io_wq_cancel_cb(tsk->io_uring->io_wq,
11305 io_cancel_ctx_cb, ctx, true);
11306 io_sq_thread_unpark(sqd);
11309 io_req_caches_free(ctx);
11311 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
11312 /* there is little hope left, don't run it too often */
11313 interval = HZ * 60;
11315 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
11317 init_completion(&exit.completion);
11318 init_task_work(&exit.task_work, io_tctx_exit_cb);
11321 * Some may use context even when all refs and requests have been put,
11322 * and they are free to do so while still holding uring_lock or
11323 * completion_lock, see io_req_task_submit(). Apart from other work,
11324 * this lock/unlock section also waits them to finish.
11326 mutex_lock(&ctx->uring_lock);
11327 while (!list_empty(&ctx->tctx_list)) {
11328 WARN_ON_ONCE(time_after(jiffies, timeout));
11330 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
11332 /* don't spin on a single task if cancellation failed */
11333 list_rotate_left(&ctx->tctx_list);
11334 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
11335 if (WARN_ON_ONCE(ret))
11338 mutex_unlock(&ctx->uring_lock);
11339 wait_for_completion(&exit.completion);
11340 mutex_lock(&ctx->uring_lock);
11342 mutex_unlock(&ctx->uring_lock);
11343 spin_lock(&ctx->completion_lock);
11344 spin_unlock(&ctx->completion_lock);
11346 io_ring_ctx_free(ctx);
11349 /* Returns true if we found and killed one or more timeouts */
11350 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
11351 struct task_struct *tsk, bool cancel_all)
11353 struct io_kiocb *req, *tmp;
11356 spin_lock(&ctx->completion_lock);
11357 spin_lock_irq(&ctx->timeout_lock);
11358 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11359 if (io_match_task(req, tsk, cancel_all)) {
11360 io_kill_timeout(req, -ECANCELED);
11364 spin_unlock_irq(&ctx->timeout_lock);
11365 io_commit_cqring(ctx);
11366 spin_unlock(&ctx->completion_lock);
11368 io_cqring_ev_posted(ctx);
11369 return canceled != 0;
11372 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11374 unsigned long index;
11375 struct creds *creds;
11377 mutex_lock(&ctx->uring_lock);
11378 percpu_ref_kill(&ctx->refs);
11380 __io_cqring_overflow_flush(ctx, true);
11381 xa_for_each(&ctx->personalities, index, creds)
11382 io_unregister_personality(ctx, index);
11383 mutex_unlock(&ctx->uring_lock);
11385 /* failed during ring init, it couldn't have issued any requests */
11387 io_kill_timeouts(ctx, NULL, true);
11388 io_poll_remove_all(ctx, NULL, true);
11389 /* if we failed setting up the ctx, we might not have any rings */
11390 io_iopoll_try_reap_events(ctx);
11393 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11395 * Use system_unbound_wq to avoid spawning tons of event kworkers
11396 * if we're exiting a ton of rings at the same time. It just adds
11397 * noise and overhead, there's no discernable change in runtime
11398 * over using system_wq.
11400 queue_work(system_unbound_wq, &ctx->exit_work);
11403 static int io_uring_release(struct inode *inode, struct file *file)
11405 struct io_ring_ctx *ctx = file->private_data;
11407 file->private_data = NULL;
11408 io_ring_ctx_wait_and_kill(ctx);
11412 struct io_task_cancel {
11413 struct task_struct *task;
11417 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11419 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11420 struct io_task_cancel *cancel = data;
11422 return io_match_task_safe(req, cancel->task, cancel->all);
11425 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11426 struct task_struct *task,
11429 struct io_defer_entry *de;
11432 spin_lock(&ctx->completion_lock);
11433 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11434 if (io_match_task_safe(de->req, task, cancel_all)) {
11435 list_cut_position(&list, &ctx->defer_list, &de->list);
11439 spin_unlock(&ctx->completion_lock);
11440 if (list_empty(&list))
11443 while (!list_empty(&list)) {
11444 de = list_first_entry(&list, struct io_defer_entry, list);
11445 list_del_init(&de->list);
11446 io_req_complete_failed(de->req, -ECANCELED);
11452 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11454 struct io_tctx_node *node;
11455 enum io_wq_cancel cret;
11458 mutex_lock(&ctx->uring_lock);
11459 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11460 struct io_uring_task *tctx = node->task->io_uring;
11463 * io_wq will stay alive while we hold uring_lock, because it's
11464 * killed after ctx nodes, which requires to take the lock.
11466 if (!tctx || !tctx->io_wq)
11468 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11469 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11471 mutex_unlock(&ctx->uring_lock);
11476 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11477 struct task_struct *task,
11480 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11481 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11483 /* failed during ring init, it couldn't have issued any requests */
11488 enum io_wq_cancel cret;
11492 ret |= io_uring_try_cancel_iowq(ctx);
11493 } else if (tctx && tctx->io_wq) {
11495 * Cancels requests of all rings, not only @ctx, but
11496 * it's fine as the task is in exit/exec.
11498 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11500 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11503 /* SQPOLL thread does its own polling */
11504 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11505 (ctx->sq_data && ctx->sq_data->thread == current)) {
11506 while (!wq_list_empty(&ctx->iopoll_list)) {
11507 io_iopoll_try_reap_events(ctx);
11512 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11513 ret |= io_poll_remove_all(ctx, task, cancel_all);
11514 ret |= io_kill_timeouts(ctx, task, cancel_all);
11516 ret |= io_run_task_work();
11523 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11525 struct io_uring_task *tctx = current->io_uring;
11526 struct io_tctx_node *node;
11529 if (unlikely(!tctx)) {
11530 ret = io_uring_alloc_task_context(current, ctx);
11534 tctx = current->io_uring;
11535 if (ctx->iowq_limits_set) {
11536 unsigned int limits[2] = { ctx->iowq_limits[0],
11537 ctx->iowq_limits[1], };
11539 ret = io_wq_max_workers(tctx->io_wq, limits);
11544 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11545 node = kmalloc(sizeof(*node), GFP_KERNEL);
11549 node->task = current;
11551 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11552 node, GFP_KERNEL));
11558 mutex_lock(&ctx->uring_lock);
11559 list_add(&node->ctx_node, &ctx->tctx_list);
11560 mutex_unlock(&ctx->uring_lock);
11567 * Note that this task has used io_uring. We use it for cancelation purposes.
11569 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11571 struct io_uring_task *tctx = current->io_uring;
11573 if (likely(tctx && tctx->last == ctx))
11575 return __io_uring_add_tctx_node(ctx);
11579 * Remove this io_uring_file -> task mapping.
11581 static __cold void io_uring_del_tctx_node(unsigned long index)
11583 struct io_uring_task *tctx = current->io_uring;
11584 struct io_tctx_node *node;
11588 node = xa_erase(&tctx->xa, index);
11592 WARN_ON_ONCE(current != node->task);
11593 WARN_ON_ONCE(list_empty(&node->ctx_node));
11595 mutex_lock(&node->ctx->uring_lock);
11596 list_del(&node->ctx_node);
11597 mutex_unlock(&node->ctx->uring_lock);
11599 if (tctx->last == node->ctx)
11604 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11606 struct io_wq *wq = tctx->io_wq;
11607 struct io_tctx_node *node;
11608 unsigned long index;
11610 xa_for_each(&tctx->xa, index, node) {
11611 io_uring_del_tctx_node(index);
11616 * Must be after io_uring_del_tctx_node() (removes nodes under
11617 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11619 io_wq_put_and_exit(wq);
11620 tctx->io_wq = NULL;
11624 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11627 return atomic_read(&tctx->inflight_tracked);
11628 return percpu_counter_sum(&tctx->inflight);
11632 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11633 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11635 static __cold void io_uring_cancel_generic(bool cancel_all,
11636 struct io_sq_data *sqd)
11638 struct io_uring_task *tctx = current->io_uring;
11639 struct io_ring_ctx *ctx;
11643 WARN_ON_ONCE(sqd && sqd->thread != current);
11645 if (!current->io_uring)
11648 io_wq_exit_start(tctx->io_wq);
11650 atomic_inc(&tctx->in_idle);
11652 io_uring_drop_tctx_refs(current);
11653 /* read completions before cancelations */
11654 inflight = tctx_inflight(tctx, !cancel_all);
11659 struct io_tctx_node *node;
11660 unsigned long index;
11662 xa_for_each(&tctx->xa, index, node) {
11663 /* sqpoll task will cancel all its requests */
11664 if (node->ctx->sq_data)
11666 io_uring_try_cancel_requests(node->ctx, current,
11670 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11671 io_uring_try_cancel_requests(ctx, current,
11675 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11676 io_run_task_work();
11677 io_uring_drop_tctx_refs(current);
11680 * If we've seen completions, retry without waiting. This
11681 * avoids a race where a completion comes in before we did
11682 * prepare_to_wait().
11684 if (inflight == tctx_inflight(tctx, !cancel_all))
11686 finish_wait(&tctx->wait, &wait);
11689 io_uring_clean_tctx(tctx);
11692 * We shouldn't run task_works after cancel, so just leave
11693 * ->in_idle set for normal exit.
11695 atomic_dec(&tctx->in_idle);
11696 /* for exec all current's requests should be gone, kill tctx */
11697 __io_uring_free(current);
11701 void __io_uring_cancel(bool cancel_all)
11703 io_uring_cancel_generic(cancel_all, NULL);
11706 void io_uring_unreg_ringfd(void)
11708 struct io_uring_task *tctx = current->io_uring;
11711 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11712 if (tctx->registered_rings[i]) {
11713 fput(tctx->registered_rings[i]);
11714 tctx->registered_rings[i] = NULL;
11719 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11720 int start, int end)
11725 for (offset = start; offset < end; offset++) {
11726 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11727 if (tctx->registered_rings[offset])
11733 } else if (file->f_op != &io_uring_fops) {
11735 return -EOPNOTSUPP;
11737 tctx->registered_rings[offset] = file;
11745 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11746 * invocation. User passes in an array of struct io_uring_rsrc_update
11747 * with ->data set to the ring_fd, and ->offset given for the desired
11748 * index. If no index is desired, application may set ->offset == -1U
11749 * and we'll find an available index. Returns number of entries
11750 * successfully processed, or < 0 on error if none were processed.
11752 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11755 struct io_uring_rsrc_update __user *arg = __arg;
11756 struct io_uring_rsrc_update reg;
11757 struct io_uring_task *tctx;
11760 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11763 mutex_unlock(&ctx->uring_lock);
11764 ret = io_uring_add_tctx_node(ctx);
11765 mutex_lock(&ctx->uring_lock);
11769 tctx = current->io_uring;
11770 for (i = 0; i < nr_args; i++) {
11773 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11783 if (reg.offset == -1U) {
11785 end = IO_RINGFD_REG_MAX;
11787 if (reg.offset >= IO_RINGFD_REG_MAX) {
11791 start = reg.offset;
11795 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11800 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11801 fput(tctx->registered_rings[reg.offset]);
11802 tctx->registered_rings[reg.offset] = NULL;
11808 return i ? i : ret;
11811 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11814 struct io_uring_rsrc_update __user *arg = __arg;
11815 struct io_uring_task *tctx = current->io_uring;
11816 struct io_uring_rsrc_update reg;
11819 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11824 for (i = 0; i < nr_args; i++) {
11825 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11829 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11834 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11835 if (tctx->registered_rings[reg.offset]) {
11836 fput(tctx->registered_rings[reg.offset]);
11837 tctx->registered_rings[reg.offset] = NULL;
11841 return i ? i : ret;
11844 static void *io_uring_validate_mmap_request(struct file *file,
11845 loff_t pgoff, size_t sz)
11847 struct io_ring_ctx *ctx = file->private_data;
11848 loff_t offset = pgoff << PAGE_SHIFT;
11853 case IORING_OFF_SQ_RING:
11854 case IORING_OFF_CQ_RING:
11857 case IORING_OFF_SQES:
11858 ptr = ctx->sq_sqes;
11861 return ERR_PTR(-EINVAL);
11864 page = virt_to_head_page(ptr);
11865 if (sz > page_size(page))
11866 return ERR_PTR(-EINVAL);
11873 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11875 size_t sz = vma->vm_end - vma->vm_start;
11879 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11881 return PTR_ERR(ptr);
11883 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11884 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11887 #else /* !CONFIG_MMU */
11889 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11891 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11894 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11896 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11899 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11900 unsigned long addr, unsigned long len,
11901 unsigned long pgoff, unsigned long flags)
11905 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11907 return PTR_ERR(ptr);
11909 return (unsigned long) ptr;
11912 #endif /* !CONFIG_MMU */
11914 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11919 if (!io_sqring_full(ctx))
11921 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11923 if (!io_sqring_full(ctx))
11926 } while (!signal_pending(current));
11928 finish_wait(&ctx->sqo_sq_wait, &wait);
11932 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11934 if (flags & IORING_ENTER_EXT_ARG) {
11935 struct io_uring_getevents_arg arg;
11937 if (argsz != sizeof(arg))
11939 if (copy_from_user(&arg, argp, sizeof(arg)))
11945 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11946 struct __kernel_timespec __user **ts,
11947 const sigset_t __user **sig)
11949 struct io_uring_getevents_arg arg;
11952 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11953 * is just a pointer to the sigset_t.
11955 if (!(flags & IORING_ENTER_EXT_ARG)) {
11956 *sig = (const sigset_t __user *) argp;
11962 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11963 * timespec and sigset_t pointers if good.
11965 if (*argsz != sizeof(arg))
11967 if (copy_from_user(&arg, argp, sizeof(arg)))
11971 *sig = u64_to_user_ptr(arg.sigmask);
11972 *argsz = arg.sigmask_sz;
11973 *ts = u64_to_user_ptr(arg.ts);
11977 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11978 u32, min_complete, u32, flags, const void __user *, argp,
11981 struct io_ring_ctx *ctx;
11985 io_run_task_work();
11987 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11988 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11989 IORING_ENTER_REGISTERED_RING)))
11993 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11994 * need only dereference our task private array to find it.
11996 if (flags & IORING_ENTER_REGISTERED_RING) {
11997 struct io_uring_task *tctx = current->io_uring;
11999 if (!tctx || fd >= IO_RINGFD_REG_MAX)
12001 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
12002 f.file = tctx->registered_rings[fd];
12008 if (unlikely(!f.file))
12012 if (unlikely(f.file->f_op != &io_uring_fops))
12016 ctx = f.file->private_data;
12017 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
12021 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
12025 * For SQ polling, the thread will do all submissions and completions.
12026 * Just return the requested submit count, and wake the thread if
12027 * we were asked to.
12030 if (ctx->flags & IORING_SETUP_SQPOLL) {
12031 io_cqring_overflow_flush(ctx);
12033 if (unlikely(ctx->sq_data->thread == NULL)) {
12037 if (flags & IORING_ENTER_SQ_WAKEUP)
12038 wake_up(&ctx->sq_data->wait);
12039 if (flags & IORING_ENTER_SQ_WAIT) {
12040 ret = io_sqpoll_wait_sq(ctx);
12045 } else if (to_submit) {
12046 ret = io_uring_add_tctx_node(ctx);
12050 mutex_lock(&ctx->uring_lock);
12051 ret = io_submit_sqes(ctx, to_submit);
12052 if (ret != to_submit) {
12053 mutex_unlock(&ctx->uring_lock);
12056 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
12057 goto iopoll_locked;
12058 mutex_unlock(&ctx->uring_lock);
12060 if (flags & IORING_ENTER_GETEVENTS) {
12062 if (ctx->syscall_iopoll) {
12064 * We disallow the app entering submit/complete with
12065 * polling, but we still need to lock the ring to
12066 * prevent racing with polled issue that got punted to
12069 mutex_lock(&ctx->uring_lock);
12071 ret2 = io_validate_ext_arg(flags, argp, argsz);
12072 if (likely(!ret2)) {
12073 min_complete = min(min_complete,
12075 ret2 = io_iopoll_check(ctx, min_complete);
12077 mutex_unlock(&ctx->uring_lock);
12079 const sigset_t __user *sig;
12080 struct __kernel_timespec __user *ts;
12082 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
12083 if (likely(!ret2)) {
12084 min_complete = min(min_complete,
12086 ret2 = io_cqring_wait(ctx, min_complete, sig,
12095 * EBADR indicates that one or more CQE were dropped.
12096 * Once the user has been informed we can clear the bit
12097 * as they are obviously ok with those drops.
12099 if (unlikely(ret2 == -EBADR))
12100 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
12106 percpu_ref_put(&ctx->refs);
12112 #ifdef CONFIG_PROC_FS
12113 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
12114 const struct cred *cred)
12116 struct user_namespace *uns = seq_user_ns(m);
12117 struct group_info *gi;
12122 seq_printf(m, "%5d\n", id);
12123 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
12124 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
12125 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
12126 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
12127 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
12128 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
12129 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
12130 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
12131 seq_puts(m, "\n\tGroups:\t");
12132 gi = cred->group_info;
12133 for (g = 0; g < gi->ngroups; g++) {
12134 seq_put_decimal_ull(m, g ? " " : "",
12135 from_kgid_munged(uns, gi->gid[g]));
12137 seq_puts(m, "\n\tCapEff:\t");
12138 cap = cred->cap_effective;
12139 CAP_FOR_EACH_U32(__capi)
12140 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
12145 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
12146 struct seq_file *m)
12148 struct io_sq_data *sq = NULL;
12149 struct io_overflow_cqe *ocqe;
12150 struct io_rings *r = ctx->rings;
12151 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
12152 unsigned int sq_head = READ_ONCE(r->sq.head);
12153 unsigned int sq_tail = READ_ONCE(r->sq.tail);
12154 unsigned int cq_head = READ_ONCE(r->cq.head);
12155 unsigned int cq_tail = READ_ONCE(r->cq.tail);
12156 unsigned int cq_shift = 0;
12157 unsigned int sq_entries, cq_entries;
12159 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
12166 * we may get imprecise sqe and cqe info if uring is actively running
12167 * since we get cached_sq_head and cached_cq_tail without uring_lock
12168 * and sq_tail and cq_head are changed by userspace. But it's ok since
12169 * we usually use these info when it is stuck.
12171 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
12172 seq_printf(m, "SqHead:\t%u\n", sq_head);
12173 seq_printf(m, "SqTail:\t%u\n", sq_tail);
12174 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
12175 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
12176 seq_printf(m, "CqHead:\t%u\n", cq_head);
12177 seq_printf(m, "CqTail:\t%u\n", cq_tail);
12178 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
12179 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
12180 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
12181 for (i = 0; i < sq_entries; i++) {
12182 unsigned int entry = i + sq_head;
12183 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
12184 struct io_uring_sqe *sqe;
12186 if (sq_idx > sq_mask)
12188 sqe = &ctx->sq_sqes[sq_idx];
12189 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
12190 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
12193 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
12194 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
12195 for (i = 0; i < cq_entries; i++) {
12196 unsigned int entry = i + cq_head;
12197 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
12200 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
12201 entry & cq_mask, cqe->user_data, cqe->res,
12204 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
12205 "extra1:%llu, extra2:%llu\n",
12206 entry & cq_mask, cqe->user_data, cqe->res,
12207 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
12212 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
12213 * since fdinfo case grabs it in the opposite direction of normal use
12214 * cases. If we fail to get the lock, we just don't iterate any
12215 * structures that could be going away outside the io_uring mutex.
12217 has_lock = mutex_trylock(&ctx->uring_lock);
12219 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
12225 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
12226 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
12227 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
12228 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
12229 struct file *f = io_file_from_index(ctx, i);
12232 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
12234 seq_printf(m, "%5u: <none>\n", i);
12236 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
12237 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
12238 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
12239 unsigned int len = buf->ubuf_end - buf->ubuf;
12241 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
12243 if (has_lock && !xa_empty(&ctx->personalities)) {
12244 unsigned long index;
12245 const struct cred *cred;
12247 seq_printf(m, "Personalities:\n");
12248 xa_for_each(&ctx->personalities, index, cred)
12249 io_uring_show_cred(m, index, cred);
12252 mutex_unlock(&ctx->uring_lock);
12254 seq_puts(m, "PollList:\n");
12255 spin_lock(&ctx->completion_lock);
12256 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
12257 struct hlist_head *list = &ctx->cancel_hash[i];
12258 struct io_kiocb *req;
12260 hlist_for_each_entry(req, list, hash_node)
12261 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
12262 task_work_pending(req->task));
12265 seq_puts(m, "CqOverflowList:\n");
12266 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
12267 struct io_uring_cqe *cqe = &ocqe->cqe;
12269 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
12270 cqe->user_data, cqe->res, cqe->flags);
12274 spin_unlock(&ctx->completion_lock);
12277 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
12279 struct io_ring_ctx *ctx = f->private_data;
12281 if (percpu_ref_tryget(&ctx->refs)) {
12282 __io_uring_show_fdinfo(ctx, m);
12283 percpu_ref_put(&ctx->refs);
12288 static const struct file_operations io_uring_fops = {
12289 .release = io_uring_release,
12290 .mmap = io_uring_mmap,
12292 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
12293 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
12295 .poll = io_uring_poll,
12296 #ifdef CONFIG_PROC_FS
12297 .show_fdinfo = io_uring_show_fdinfo,
12301 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
12302 struct io_uring_params *p)
12304 struct io_rings *rings;
12305 size_t size, sq_array_offset;
12307 /* make sure these are sane, as we already accounted them */
12308 ctx->sq_entries = p->sq_entries;
12309 ctx->cq_entries = p->cq_entries;
12311 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
12312 if (size == SIZE_MAX)
12315 rings = io_mem_alloc(size);
12319 ctx->rings = rings;
12320 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
12321 rings->sq_ring_mask = p->sq_entries - 1;
12322 rings->cq_ring_mask = p->cq_entries - 1;
12323 rings->sq_ring_entries = p->sq_entries;
12324 rings->cq_ring_entries = p->cq_entries;
12326 if (p->flags & IORING_SETUP_SQE128)
12327 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
12329 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
12330 if (size == SIZE_MAX) {
12331 io_mem_free(ctx->rings);
12336 ctx->sq_sqes = io_mem_alloc(size);
12337 if (!ctx->sq_sqes) {
12338 io_mem_free(ctx->rings);
12346 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
12350 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
12354 ret = io_uring_add_tctx_node(ctx);
12359 fd_install(fd, file);
12364 * Allocate an anonymous fd, this is what constitutes the application
12365 * visible backing of an io_uring instance. The application mmaps this
12366 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12367 * we have to tie this fd to a socket for file garbage collection purposes.
12369 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12372 #if defined(CONFIG_UNIX)
12375 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12378 return ERR_PTR(ret);
12381 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12382 O_RDWR | O_CLOEXEC, NULL);
12383 #if defined(CONFIG_UNIX)
12384 if (IS_ERR(file)) {
12385 sock_release(ctx->ring_sock);
12386 ctx->ring_sock = NULL;
12388 ctx->ring_sock->file = file;
12394 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12395 struct io_uring_params __user *params)
12397 struct io_ring_ctx *ctx;
12403 if (entries > IORING_MAX_ENTRIES) {
12404 if (!(p->flags & IORING_SETUP_CLAMP))
12406 entries = IORING_MAX_ENTRIES;
12410 * Use twice as many entries for the CQ ring. It's possible for the
12411 * application to drive a higher depth than the size of the SQ ring,
12412 * since the sqes are only used at submission time. This allows for
12413 * some flexibility in overcommitting a bit. If the application has
12414 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12415 * of CQ ring entries manually.
12417 p->sq_entries = roundup_pow_of_two(entries);
12418 if (p->flags & IORING_SETUP_CQSIZE) {
12420 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12421 * to a power-of-two, if it isn't already. We do NOT impose
12422 * any cq vs sq ring sizing.
12424 if (!p->cq_entries)
12426 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12427 if (!(p->flags & IORING_SETUP_CLAMP))
12429 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12431 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12432 if (p->cq_entries < p->sq_entries)
12435 p->cq_entries = 2 * p->sq_entries;
12438 ctx = io_ring_ctx_alloc(p);
12443 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12444 * space applications don't need to do io completion events
12445 * polling again, they can rely on io_sq_thread to do polling
12446 * work, which can reduce cpu usage and uring_lock contention.
12448 if (ctx->flags & IORING_SETUP_IOPOLL &&
12449 !(ctx->flags & IORING_SETUP_SQPOLL))
12450 ctx->syscall_iopoll = 1;
12452 ctx->compat = in_compat_syscall();
12453 if (!capable(CAP_IPC_LOCK))
12454 ctx->user = get_uid(current_user());
12457 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12458 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12461 if (ctx->flags & IORING_SETUP_SQPOLL) {
12462 /* IPI related flags don't make sense with SQPOLL */
12463 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12464 IORING_SETUP_TASKRUN_FLAG))
12466 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12467 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12468 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12470 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12472 ctx->notify_method = TWA_SIGNAL;
12476 * This is just grabbed for accounting purposes. When a process exits,
12477 * the mm is exited and dropped before the files, hence we need to hang
12478 * on to this mm purely for the purposes of being able to unaccount
12479 * memory (locked/pinned vm). It's not used for anything else.
12481 mmgrab(current->mm);
12482 ctx->mm_account = current->mm;
12484 ret = io_allocate_scq_urings(ctx, p);
12488 ret = io_sq_offload_create(ctx, p);
12491 /* always set a rsrc node */
12492 ret = io_rsrc_node_switch_start(ctx);
12495 io_rsrc_node_switch(ctx, NULL);
12497 memset(&p->sq_off, 0, sizeof(p->sq_off));
12498 p->sq_off.head = offsetof(struct io_rings, sq.head);
12499 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12500 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12501 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12502 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12503 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12504 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12506 memset(&p->cq_off, 0, sizeof(p->cq_off));
12507 p->cq_off.head = offsetof(struct io_rings, cq.head);
12508 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12509 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12510 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12511 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12512 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12513 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12515 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12516 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12517 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12518 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12519 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12520 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12521 IORING_FEAT_LINKED_FILE;
12523 if (copy_to_user(params, p, sizeof(*p))) {
12528 file = io_uring_get_file(ctx);
12529 if (IS_ERR(file)) {
12530 ret = PTR_ERR(file);
12535 * Install ring fd as the very last thing, so we don't risk someone
12536 * having closed it before we finish setup
12538 ret = io_uring_install_fd(ctx, file);
12540 /* fput will clean it up */
12545 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12548 io_ring_ctx_wait_and_kill(ctx);
12553 * Sets up an aio uring context, and returns the fd. Applications asks for a
12554 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12555 * params structure passed in.
12557 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12559 struct io_uring_params p;
12562 if (copy_from_user(&p, params, sizeof(p)))
12564 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12569 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12570 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12571 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12572 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12573 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12574 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12577 return io_uring_create(entries, &p, params);
12580 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12581 struct io_uring_params __user *, params)
12583 return io_uring_setup(entries, params);
12586 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12589 struct io_uring_probe *p;
12593 size = struct_size(p, ops, nr_args);
12594 if (size == SIZE_MAX)
12596 p = kzalloc(size, GFP_KERNEL);
12601 if (copy_from_user(p, arg, size))
12604 if (memchr_inv(p, 0, size))
12607 p->last_op = IORING_OP_LAST - 1;
12608 if (nr_args > IORING_OP_LAST)
12609 nr_args = IORING_OP_LAST;
12611 for (i = 0; i < nr_args; i++) {
12613 if (!io_op_defs[i].not_supported)
12614 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12619 if (copy_to_user(arg, p, size))
12626 static int io_register_personality(struct io_ring_ctx *ctx)
12628 const struct cred *creds;
12632 creds = get_current_cred();
12634 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12635 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12643 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12644 void __user *arg, unsigned int nr_args)
12646 struct io_uring_restriction *res;
12650 /* Restrictions allowed only if rings started disabled */
12651 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12654 /* We allow only a single restrictions registration */
12655 if (ctx->restrictions.registered)
12658 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12661 size = array_size(nr_args, sizeof(*res));
12662 if (size == SIZE_MAX)
12665 res = memdup_user(arg, size);
12667 return PTR_ERR(res);
12671 for (i = 0; i < nr_args; i++) {
12672 switch (res[i].opcode) {
12673 case IORING_RESTRICTION_REGISTER_OP:
12674 if (res[i].register_op >= IORING_REGISTER_LAST) {
12679 __set_bit(res[i].register_op,
12680 ctx->restrictions.register_op);
12682 case IORING_RESTRICTION_SQE_OP:
12683 if (res[i].sqe_op >= IORING_OP_LAST) {
12688 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12690 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12691 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12693 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12694 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12703 /* Reset all restrictions if an error happened */
12705 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12707 ctx->restrictions.registered = true;
12713 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12715 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12718 if (ctx->restrictions.registered)
12719 ctx->restricted = 1;
12721 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12722 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12723 wake_up(&ctx->sq_data->wait);
12727 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12728 struct io_uring_rsrc_update2 *up,
12734 if (check_add_overflow(up->offset, nr_args, &tmp))
12736 err = io_rsrc_node_switch_start(ctx);
12741 case IORING_RSRC_FILE:
12742 return __io_sqe_files_update(ctx, up, nr_args);
12743 case IORING_RSRC_BUFFER:
12744 return __io_sqe_buffers_update(ctx, up, nr_args);
12749 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12752 struct io_uring_rsrc_update2 up;
12756 memset(&up, 0, sizeof(up));
12757 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12759 if (up.resv || up.resv2)
12761 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12764 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12765 unsigned size, unsigned type)
12767 struct io_uring_rsrc_update2 up;
12769 if (size != sizeof(up))
12771 if (copy_from_user(&up, arg, sizeof(up)))
12773 if (!up.nr || up.resv || up.resv2)
12775 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12778 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12779 unsigned int size, unsigned int type)
12781 struct io_uring_rsrc_register rr;
12783 /* keep it extendible */
12784 if (size != sizeof(rr))
12787 memset(&rr, 0, sizeof(rr));
12788 if (copy_from_user(&rr, arg, size))
12790 if (!rr.nr || rr.resv2)
12792 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12796 case IORING_RSRC_FILE:
12797 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12799 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12800 rr.nr, u64_to_user_ptr(rr.tags));
12801 case IORING_RSRC_BUFFER:
12802 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12804 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12805 rr.nr, u64_to_user_ptr(rr.tags));
12810 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12811 void __user *arg, unsigned len)
12813 struct io_uring_task *tctx = current->io_uring;
12814 cpumask_var_t new_mask;
12817 if (!tctx || !tctx->io_wq)
12820 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12823 cpumask_clear(new_mask);
12824 if (len > cpumask_size())
12825 len = cpumask_size();
12827 if (in_compat_syscall()) {
12828 ret = compat_get_bitmap(cpumask_bits(new_mask),
12829 (const compat_ulong_t __user *)arg,
12830 len * 8 /* CHAR_BIT */);
12832 ret = copy_from_user(new_mask, arg, len);
12836 free_cpumask_var(new_mask);
12840 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12841 free_cpumask_var(new_mask);
12845 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12847 struct io_uring_task *tctx = current->io_uring;
12849 if (!tctx || !tctx->io_wq)
12852 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12855 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12857 __must_hold(&ctx->uring_lock)
12859 struct io_tctx_node *node;
12860 struct io_uring_task *tctx = NULL;
12861 struct io_sq_data *sqd = NULL;
12862 __u32 new_count[2];
12865 if (copy_from_user(new_count, arg, sizeof(new_count)))
12867 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12868 if (new_count[i] > INT_MAX)
12871 if (ctx->flags & IORING_SETUP_SQPOLL) {
12872 sqd = ctx->sq_data;
12875 * Observe the correct sqd->lock -> ctx->uring_lock
12876 * ordering. Fine to drop uring_lock here, we hold
12877 * a ref to the ctx.
12879 refcount_inc(&sqd->refs);
12880 mutex_unlock(&ctx->uring_lock);
12881 mutex_lock(&sqd->lock);
12882 mutex_lock(&ctx->uring_lock);
12884 tctx = sqd->thread->io_uring;
12887 tctx = current->io_uring;
12890 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12892 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12894 ctx->iowq_limits[i] = new_count[i];
12895 ctx->iowq_limits_set = true;
12897 if (tctx && tctx->io_wq) {
12898 ret = io_wq_max_workers(tctx->io_wq, new_count);
12902 memset(new_count, 0, sizeof(new_count));
12906 mutex_unlock(&sqd->lock);
12907 io_put_sq_data(sqd);
12910 if (copy_to_user(arg, new_count, sizeof(new_count)))
12913 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12917 /* now propagate the restriction to all registered users */
12918 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12919 struct io_uring_task *tctx = node->task->io_uring;
12921 if (WARN_ON_ONCE(!tctx->io_wq))
12924 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12925 new_count[i] = ctx->iowq_limits[i];
12926 /* ignore errors, it always returns zero anyway */
12927 (void)io_wq_max_workers(tctx->io_wq, new_count);
12932 mutex_unlock(&sqd->lock);
12933 io_put_sq_data(sqd);
12938 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12940 struct io_uring_buf_ring *br;
12941 struct io_uring_buf_reg reg;
12942 struct io_buffer_list *bl, *free_bl = NULL;
12943 struct page **pages;
12946 if (copy_from_user(®, arg, sizeof(reg)))
12949 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12951 if (!reg.ring_addr)
12953 if (reg.ring_addr & ~PAGE_MASK)
12955 if (!is_power_of_2(reg.ring_entries))
12958 /* cannot disambiguate full vs empty due to head/tail size */
12959 if (reg.ring_entries >= 65536)
12962 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12963 int ret = io_init_bl_list(ctx);
12968 bl = io_buffer_get_list(ctx, reg.bgid);
12970 /* if mapped buffer ring OR classic exists, don't allow */
12971 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12974 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12979 pages = io_pin_pages(reg.ring_addr,
12980 struct_size(br, bufs, reg.ring_entries),
12982 if (IS_ERR(pages)) {
12984 return PTR_ERR(pages);
12987 br = page_address(pages[0]);
12988 bl->buf_pages = pages;
12989 bl->buf_nr_pages = nr_pages;
12990 bl->nr_entries = reg.ring_entries;
12992 bl->mask = reg.ring_entries - 1;
12993 io_buffer_add_list(ctx, bl, reg.bgid);
12997 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12999 struct io_uring_buf_reg reg;
13000 struct io_buffer_list *bl;
13002 if (copy_from_user(®, arg, sizeof(reg)))
13004 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
13007 bl = io_buffer_get_list(ctx, reg.bgid);
13010 if (!bl->buf_nr_pages)
13013 __io_remove_buffers(ctx, bl, -1U);
13014 if (bl->bgid >= BGID_ARRAY) {
13015 xa_erase(&ctx->io_bl_xa, bl->bgid);
13021 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
13022 void __user *arg, unsigned nr_args)
13023 __releases(ctx->uring_lock)
13024 __acquires(ctx->uring_lock)
13029 * We're inside the ring mutex, if the ref is already dying, then
13030 * someone else killed the ctx or is already going through
13031 * io_uring_register().
13033 if (percpu_ref_is_dying(&ctx->refs))
13036 if (ctx->restricted) {
13037 if (opcode >= IORING_REGISTER_LAST)
13039 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
13040 if (!test_bit(opcode, ctx->restrictions.register_op))
13045 case IORING_REGISTER_BUFFERS:
13049 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
13051 case IORING_UNREGISTER_BUFFERS:
13053 if (arg || nr_args)
13055 ret = io_sqe_buffers_unregister(ctx);
13057 case IORING_REGISTER_FILES:
13061 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
13063 case IORING_UNREGISTER_FILES:
13065 if (arg || nr_args)
13067 ret = io_sqe_files_unregister(ctx);
13069 case IORING_REGISTER_FILES_UPDATE:
13070 ret = io_register_files_update(ctx, arg, nr_args);
13072 case IORING_REGISTER_EVENTFD:
13076 ret = io_eventfd_register(ctx, arg, 0);
13078 case IORING_REGISTER_EVENTFD_ASYNC:
13082 ret = io_eventfd_register(ctx, arg, 1);
13084 case IORING_UNREGISTER_EVENTFD:
13086 if (arg || nr_args)
13088 ret = io_eventfd_unregister(ctx);
13090 case IORING_REGISTER_PROBE:
13092 if (!arg || nr_args > 256)
13094 ret = io_probe(ctx, arg, nr_args);
13096 case IORING_REGISTER_PERSONALITY:
13098 if (arg || nr_args)
13100 ret = io_register_personality(ctx);
13102 case IORING_UNREGISTER_PERSONALITY:
13106 ret = io_unregister_personality(ctx, nr_args);
13108 case IORING_REGISTER_ENABLE_RINGS:
13110 if (arg || nr_args)
13112 ret = io_register_enable_rings(ctx);
13114 case IORING_REGISTER_RESTRICTIONS:
13115 ret = io_register_restrictions(ctx, arg, nr_args);
13117 case IORING_REGISTER_FILES2:
13118 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
13120 case IORING_REGISTER_FILES_UPDATE2:
13121 ret = io_register_rsrc_update(ctx, arg, nr_args,
13124 case IORING_REGISTER_BUFFERS2:
13125 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
13127 case IORING_REGISTER_BUFFERS_UPDATE:
13128 ret = io_register_rsrc_update(ctx, arg, nr_args,
13129 IORING_RSRC_BUFFER);
13131 case IORING_REGISTER_IOWQ_AFF:
13133 if (!arg || !nr_args)
13135 ret = io_register_iowq_aff(ctx, arg, nr_args);
13137 case IORING_UNREGISTER_IOWQ_AFF:
13139 if (arg || nr_args)
13141 ret = io_unregister_iowq_aff(ctx);
13143 case IORING_REGISTER_IOWQ_MAX_WORKERS:
13145 if (!arg || nr_args != 2)
13147 ret = io_register_iowq_max_workers(ctx, arg);
13149 case IORING_REGISTER_RING_FDS:
13150 ret = io_ringfd_register(ctx, arg, nr_args);
13152 case IORING_UNREGISTER_RING_FDS:
13153 ret = io_ringfd_unregister(ctx, arg, nr_args);
13155 case IORING_REGISTER_PBUF_RING:
13157 if (!arg || nr_args != 1)
13159 ret = io_register_pbuf_ring(ctx, arg);
13161 case IORING_UNREGISTER_PBUF_RING:
13163 if (!arg || nr_args != 1)
13165 ret = io_unregister_pbuf_ring(ctx, arg);
13175 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
13176 void __user *, arg, unsigned int, nr_args)
13178 struct io_ring_ctx *ctx;
13187 if (f.file->f_op != &io_uring_fops)
13190 ctx = f.file->private_data;
13192 io_run_task_work();
13194 mutex_lock(&ctx->uring_lock);
13195 ret = __io_uring_register(ctx, opcode, arg, nr_args);
13196 mutex_unlock(&ctx->uring_lock);
13197 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
13203 static int __init io_uring_init(void)
13205 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13206 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13207 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13210 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13211 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13212 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13213 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13214 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13215 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13216 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13217 BUILD_BUG_SQE_ELEM(8, __u64, off);
13218 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13219 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13220 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13221 BUILD_BUG_SQE_ELEM(24, __u32, len);
13222 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13223 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13224 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13225 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13226 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13227 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13228 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13229 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13230 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13231 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13232 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13233 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13234 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13235 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13236 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13237 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13238 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13239 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13240 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13241 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13242 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13243 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13245 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13246 sizeof(struct io_uring_rsrc_update));
13247 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13248 sizeof(struct io_uring_rsrc_update2));
13250 /* ->buf_index is u16 */
13251 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13252 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13253 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13254 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13255 offsetof(struct io_uring_buf_ring, tail));
13257 /* should fit into one byte */
13258 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13259 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13260 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13262 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13263 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13265 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13267 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13269 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13273 __initcall(io_uring_init);