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 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1742 * the flag and hence ensure that bl->head doesn't get incremented.
1743 * If the tail has already been incremented, hang on to it.
1745 if (req->flags & REQ_F_BUFFER_RING) {
1746 if (req->buf_list) {
1747 if (req->flags & REQ_F_PARTIAL_IO) {
1748 req->buf_list->head++;
1749 req->buf_list = NULL;
1751 req->buf_index = req->buf_list->bgid;
1752 req->flags &= ~REQ_F_BUFFER_RING;
1758 io_ring_submit_lock(ctx, issue_flags);
1761 bl = io_buffer_get_list(ctx, buf->bgid);
1762 list_add(&buf->list, &bl->buf_list);
1763 req->flags &= ~REQ_F_BUFFER_SELECTED;
1764 req->buf_index = buf->bgid;
1766 io_ring_submit_unlock(ctx, issue_flags);
1769 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1771 __must_hold(&req->ctx->timeout_lock)
1773 struct io_kiocb *req;
1775 if (task && head->task != task)
1780 io_for_each_link(req, head) {
1781 if (req->flags & REQ_F_INFLIGHT)
1787 static bool io_match_linked(struct io_kiocb *head)
1789 struct io_kiocb *req;
1791 io_for_each_link(req, head) {
1792 if (req->flags & REQ_F_INFLIGHT)
1799 * As io_match_task() but protected against racing with linked timeouts.
1800 * User must not hold timeout_lock.
1802 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1807 if (task && head->task != task)
1812 if (head->flags & REQ_F_LINK_TIMEOUT) {
1813 struct io_ring_ctx *ctx = head->ctx;
1815 /* protect against races with linked timeouts */
1816 spin_lock_irq(&ctx->timeout_lock);
1817 matched = io_match_linked(head);
1818 spin_unlock_irq(&ctx->timeout_lock);
1820 matched = io_match_linked(head);
1825 static inline bool req_has_async_data(struct io_kiocb *req)
1827 return req->flags & REQ_F_ASYNC_DATA;
1830 static inline void req_set_fail(struct io_kiocb *req)
1832 req->flags |= REQ_F_FAIL;
1833 if (req->flags & REQ_F_CQE_SKIP) {
1834 req->flags &= ~REQ_F_CQE_SKIP;
1835 req->flags |= REQ_F_SKIP_LINK_CQES;
1839 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1845 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1847 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1850 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1852 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1854 complete(&ctx->ref_comp);
1857 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1859 return !req->timeout.off;
1862 static __cold void io_fallback_req_func(struct work_struct *work)
1864 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1865 fallback_work.work);
1866 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1867 struct io_kiocb *req, *tmp;
1868 bool locked = false;
1870 percpu_ref_get(&ctx->refs);
1871 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1872 req->io_task_work.func(req, &locked);
1875 io_submit_flush_completions(ctx);
1876 mutex_unlock(&ctx->uring_lock);
1878 percpu_ref_put(&ctx->refs);
1881 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1883 struct io_ring_ctx *ctx;
1886 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1890 xa_init(&ctx->io_bl_xa);
1893 * Use 5 bits less than the max cq entries, that should give us around
1894 * 32 entries per hash list if totally full and uniformly spread.
1896 hash_bits = ilog2(p->cq_entries);
1900 ctx->cancel_hash_bits = hash_bits;
1901 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1903 if (!ctx->cancel_hash)
1905 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1907 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1908 if (!ctx->dummy_ubuf)
1910 /* set invalid range, so io_import_fixed() fails meeting it */
1911 ctx->dummy_ubuf->ubuf = -1UL;
1913 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1914 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1917 ctx->flags = p->flags;
1918 init_waitqueue_head(&ctx->sqo_sq_wait);
1919 INIT_LIST_HEAD(&ctx->sqd_list);
1920 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1921 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1922 INIT_LIST_HEAD(&ctx->apoll_cache);
1923 init_completion(&ctx->ref_comp);
1924 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1925 mutex_init(&ctx->uring_lock);
1926 init_waitqueue_head(&ctx->cq_wait);
1927 spin_lock_init(&ctx->completion_lock);
1928 spin_lock_init(&ctx->timeout_lock);
1929 INIT_WQ_LIST(&ctx->iopoll_list);
1930 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1931 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1932 INIT_LIST_HEAD(&ctx->defer_list);
1933 INIT_LIST_HEAD(&ctx->timeout_list);
1934 INIT_LIST_HEAD(&ctx->ltimeout_list);
1935 spin_lock_init(&ctx->rsrc_ref_lock);
1936 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1937 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1938 init_llist_head(&ctx->rsrc_put_llist);
1939 INIT_LIST_HEAD(&ctx->tctx_list);
1940 ctx->submit_state.free_list.next = NULL;
1941 INIT_WQ_LIST(&ctx->locked_free_list);
1942 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1943 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1946 kfree(ctx->dummy_ubuf);
1947 kfree(ctx->cancel_hash);
1949 xa_destroy(&ctx->io_bl_xa);
1954 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1956 struct io_rings *r = ctx->rings;
1958 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1962 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1964 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1965 struct io_ring_ctx *ctx = req->ctx;
1967 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1973 static inline bool io_req_ffs_set(struct io_kiocb *req)
1975 return req->flags & REQ_F_FIXED_FILE;
1978 static inline void io_req_track_inflight(struct io_kiocb *req)
1980 if (!(req->flags & REQ_F_INFLIGHT)) {
1981 req->flags |= REQ_F_INFLIGHT;
1982 atomic_inc(&req->task->io_uring->inflight_tracked);
1986 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1988 if (WARN_ON_ONCE(!req->link))
1991 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1992 req->flags |= REQ_F_LINK_TIMEOUT;
1994 /* linked timeouts should have two refs once prep'ed */
1995 io_req_set_refcount(req);
1996 __io_req_set_refcount(req->link, 2);
2000 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2002 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
2004 return __io_prep_linked_timeout(req);
2007 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
2009 io_queue_linked_timeout(__io_prep_linked_timeout(req));
2012 static inline void io_arm_ltimeout(struct io_kiocb *req)
2014 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
2015 __io_arm_ltimeout(req);
2018 static void io_prep_async_work(struct io_kiocb *req)
2020 const struct io_op_def *def = &io_op_defs[req->opcode];
2021 struct io_ring_ctx *ctx = req->ctx;
2023 if (!(req->flags & REQ_F_CREDS)) {
2024 req->flags |= REQ_F_CREDS;
2025 req->creds = get_current_cred();
2028 req->work.list.next = NULL;
2029 req->work.flags = 0;
2030 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
2031 if (req->flags & REQ_F_FORCE_ASYNC)
2032 req->work.flags |= IO_WQ_WORK_CONCURRENT;
2034 if (req->flags & REQ_F_ISREG) {
2035 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
2036 io_wq_hash_work(&req->work, file_inode(req->file));
2037 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
2038 if (def->unbound_nonreg_file)
2039 req->work.flags |= IO_WQ_WORK_UNBOUND;
2043 static void io_prep_async_link(struct io_kiocb *req)
2045 struct io_kiocb *cur;
2047 if (req->flags & REQ_F_LINK_TIMEOUT) {
2048 struct io_ring_ctx *ctx = req->ctx;
2050 spin_lock_irq(&ctx->timeout_lock);
2051 io_for_each_link(cur, req)
2052 io_prep_async_work(cur);
2053 spin_unlock_irq(&ctx->timeout_lock);
2055 io_for_each_link(cur, req)
2056 io_prep_async_work(cur);
2060 static inline void io_req_add_compl_list(struct io_kiocb *req)
2062 struct io_submit_state *state = &req->ctx->submit_state;
2064 if (!(req->flags & REQ_F_CQE_SKIP))
2065 state->flush_cqes = true;
2066 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
2069 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
2071 struct io_kiocb *link = io_prep_linked_timeout(req);
2072 struct io_uring_task *tctx = req->task->io_uring;
2075 BUG_ON(!tctx->io_wq);
2077 /* init ->work of the whole link before punting */
2078 io_prep_async_link(req);
2081 * Not expected to happen, but if we do have a bug where this _can_
2082 * happen, catch it here and ensure the request is marked as
2083 * canceled. That will make io-wq go through the usual work cancel
2084 * procedure rather than attempt to run this request (or create a new
2087 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
2088 req->work.flags |= IO_WQ_WORK_CANCEL;
2090 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
2091 req->opcode, req->flags, &req->work,
2092 io_wq_is_hashed(&req->work));
2093 io_wq_enqueue(tctx->io_wq, &req->work);
2095 io_queue_linked_timeout(link);
2098 static void io_kill_timeout(struct io_kiocb *req, int status)
2099 __must_hold(&req->ctx->completion_lock)
2100 __must_hold(&req->ctx->timeout_lock)
2102 struct io_timeout_data *io = req->async_data;
2104 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2107 atomic_set(&req->ctx->cq_timeouts,
2108 atomic_read(&req->ctx->cq_timeouts) + 1);
2109 list_del_init(&req->timeout.list);
2110 io_req_tw_post_queue(req, status, 0);
2114 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
2116 while (!list_empty(&ctx->defer_list)) {
2117 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
2118 struct io_defer_entry, list);
2120 if (req_need_defer(de->req, de->seq))
2122 list_del_init(&de->list);
2123 io_req_task_queue(de->req);
2128 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
2129 __must_hold(&ctx->completion_lock)
2131 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
2132 struct io_kiocb *req, *tmp;
2134 spin_lock_irq(&ctx->timeout_lock);
2135 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
2136 u32 events_needed, events_got;
2138 if (io_is_timeout_noseq(req))
2142 * Since seq can easily wrap around over time, subtract
2143 * the last seq at which timeouts were flushed before comparing.
2144 * Assuming not more than 2^31-1 events have happened since,
2145 * these subtractions won't have wrapped, so we can check if
2146 * target is in [last_seq, current_seq] by comparing the two.
2148 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
2149 events_got = seq - ctx->cq_last_tm_flush;
2150 if (events_got < events_needed)
2153 io_kill_timeout(req, 0);
2155 ctx->cq_last_tm_flush = seq;
2156 spin_unlock_irq(&ctx->timeout_lock);
2159 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
2161 /* order cqe stores with ring update */
2162 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
2165 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
2167 if (ctx->off_timeout_used || ctx->drain_active) {
2168 spin_lock(&ctx->completion_lock);
2169 if (ctx->off_timeout_used)
2170 io_flush_timeouts(ctx);
2171 if (ctx->drain_active)
2172 io_queue_deferred(ctx);
2173 io_commit_cqring(ctx);
2174 spin_unlock(&ctx->completion_lock);
2177 io_eventfd_signal(ctx);
2180 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
2182 struct io_rings *r = ctx->rings;
2184 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
2187 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
2189 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
2193 * writes to the cq entry need to come after reading head; the
2194 * control dependency is enough as we're using WRITE_ONCE to
2197 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
2199 struct io_rings *rings = ctx->rings;
2200 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
2201 unsigned int shift = 0;
2202 unsigned int free, queued, len;
2204 if (ctx->flags & IORING_SETUP_CQE32)
2207 /* userspace may cheat modifying the tail, be safe and do min */
2208 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2209 free = ctx->cq_entries - queued;
2210 /* we need a contiguous range, limit based on the current array offset */
2211 len = min(free, ctx->cq_entries - off);
2215 ctx->cached_cq_tail++;
2216 ctx->cqe_cached = &rings->cqes[off];
2217 ctx->cqe_sentinel = ctx->cqe_cached + len;
2219 return &rings->cqes[off << shift];
2222 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2224 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2225 struct io_uring_cqe *cqe = ctx->cqe_cached;
2227 if (ctx->flags & IORING_SETUP_CQE32) {
2228 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2233 ctx->cached_cq_tail++;
2238 return __io_get_cqe(ctx);
2241 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2243 struct io_ev_fd *ev_fd;
2247 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2248 * and eventfd_signal
2250 ev_fd = rcu_dereference(ctx->io_ev_fd);
2253 * Check again if ev_fd exists incase an io_eventfd_unregister call
2254 * completed between the NULL check of ctx->io_ev_fd at the start of
2255 * the function and rcu_read_lock.
2257 if (unlikely(!ev_fd))
2259 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2262 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2263 eventfd_signal(ev_fd->cq_ev_fd, 1);
2268 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2271 * wake_up_all() may seem excessive, but io_wake_function() and
2272 * io_should_wake() handle the termination of the loop and only
2273 * wake as many waiters as we need to.
2275 if (wq_has_sleeper(&ctx->cq_wait))
2276 wake_up_all(&ctx->cq_wait);
2280 * This should only get called when at least one event has been posted.
2281 * Some applications rely on the eventfd notification count only changing
2282 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2283 * 1:1 relationship between how many times this function is called (and
2284 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2286 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2288 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2290 __io_commit_cqring_flush(ctx);
2292 io_cqring_wake(ctx);
2295 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2297 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2299 __io_commit_cqring_flush(ctx);
2301 if (ctx->flags & IORING_SETUP_SQPOLL)
2302 io_cqring_wake(ctx);
2305 /* Returns true if there are no backlogged entries after the flush */
2306 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2308 bool all_flushed, posted;
2309 size_t cqe_size = sizeof(struct io_uring_cqe);
2311 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2314 if (ctx->flags & IORING_SETUP_CQE32)
2318 spin_lock(&ctx->completion_lock);
2319 while (!list_empty(&ctx->cq_overflow_list)) {
2320 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2321 struct io_overflow_cqe *ocqe;
2325 ocqe = list_first_entry(&ctx->cq_overflow_list,
2326 struct io_overflow_cqe, list);
2328 memcpy(cqe, &ocqe->cqe, cqe_size);
2330 io_account_cq_overflow(ctx);
2333 list_del(&ocqe->list);
2337 all_flushed = list_empty(&ctx->cq_overflow_list);
2339 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2340 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2343 io_commit_cqring(ctx);
2344 spin_unlock(&ctx->completion_lock);
2346 io_cqring_ev_posted(ctx);
2350 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2354 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2355 /* iopoll syncs against uring_lock, not completion_lock */
2356 if (ctx->flags & IORING_SETUP_IOPOLL)
2357 mutex_lock(&ctx->uring_lock);
2358 ret = __io_cqring_overflow_flush(ctx, false);
2359 if (ctx->flags & IORING_SETUP_IOPOLL)
2360 mutex_unlock(&ctx->uring_lock);
2366 static void __io_put_task(struct task_struct *task, int nr)
2368 struct io_uring_task *tctx = task->io_uring;
2370 percpu_counter_sub(&tctx->inflight, nr);
2371 if (unlikely(atomic_read(&tctx->in_idle)))
2372 wake_up(&tctx->wait);
2373 put_task_struct_many(task, nr);
2376 /* must to be called somewhat shortly after putting a request */
2377 static inline void io_put_task(struct task_struct *task, int nr)
2379 if (likely(task == current))
2380 task->io_uring->cached_refs += nr;
2382 __io_put_task(task, nr);
2385 static void io_task_refs_refill(struct io_uring_task *tctx)
2387 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2389 percpu_counter_add(&tctx->inflight, refill);
2390 refcount_add(refill, ¤t->usage);
2391 tctx->cached_refs += refill;
2394 static inline void io_get_task_refs(int nr)
2396 struct io_uring_task *tctx = current->io_uring;
2398 tctx->cached_refs -= nr;
2399 if (unlikely(tctx->cached_refs < 0))
2400 io_task_refs_refill(tctx);
2403 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2405 struct io_uring_task *tctx = task->io_uring;
2406 unsigned int refs = tctx->cached_refs;
2409 tctx->cached_refs = 0;
2410 percpu_counter_sub(&tctx->inflight, refs);
2411 put_task_struct_many(task, refs);
2415 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2416 s32 res, u32 cflags, u64 extra1,
2419 struct io_overflow_cqe *ocqe;
2420 size_t ocq_size = sizeof(struct io_overflow_cqe);
2421 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2424 ocq_size += sizeof(struct io_uring_cqe);
2426 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2427 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2430 * If we're in ring overflow flush mode, or in task cancel mode,
2431 * or cannot allocate an overflow entry, then we need to drop it
2434 io_account_cq_overflow(ctx);
2435 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2438 if (list_empty(&ctx->cq_overflow_list)) {
2439 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2440 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2443 ocqe->cqe.user_data = user_data;
2444 ocqe->cqe.res = res;
2445 ocqe->cqe.flags = cflags;
2447 ocqe->cqe.big_cqe[0] = extra1;
2448 ocqe->cqe.big_cqe[1] = extra2;
2450 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2454 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
2455 struct io_kiocb *req)
2457 struct io_uring_cqe *cqe;
2459 if (!(ctx->flags & IORING_SETUP_CQE32)) {
2460 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2461 req->cqe.res, req->cqe.flags, 0, 0);
2464 * If we can't get a cq entry, userspace overflowed the
2465 * submission (by quite a lot). Increment the overflow count in
2468 cqe = io_get_cqe(ctx);
2470 memcpy(cqe, &req->cqe, sizeof(*cqe));
2474 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2475 req->cqe.res, req->cqe.flags,
2478 u64 extra1 = 0, extra2 = 0;
2480 if (req->flags & REQ_F_CQE32_INIT) {
2481 extra1 = req->extra1;
2482 extra2 = req->extra2;
2485 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2486 req->cqe.res, req->cqe.flags, extra1, extra2);
2489 * If we can't get a cq entry, userspace overflowed the
2490 * submission (by quite a lot). Increment the overflow count in
2493 cqe = io_get_cqe(ctx);
2495 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2496 WRITE_ONCE(cqe->big_cqe[0], extra1);
2497 WRITE_ONCE(cqe->big_cqe[1], extra2);
2501 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2502 req->cqe.res, req->cqe.flags,
2507 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2508 s32 res, u32 cflags)
2510 struct io_uring_cqe *cqe;
2513 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2516 * If we can't get a cq entry, userspace overflowed the
2517 * submission (by quite a lot). Increment the overflow count in
2520 cqe = io_get_cqe(ctx);
2522 WRITE_ONCE(cqe->user_data, user_data);
2523 WRITE_ONCE(cqe->res, res);
2524 WRITE_ONCE(cqe->flags, cflags);
2526 if (ctx->flags & IORING_SETUP_CQE32) {
2527 WRITE_ONCE(cqe->big_cqe[0], 0);
2528 WRITE_ONCE(cqe->big_cqe[1], 0);
2532 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2535 static void __io_req_complete_put(struct io_kiocb *req)
2538 * If we're the last reference to this request, add to our locked
2541 if (req_ref_put_and_test(req)) {
2542 struct io_ring_ctx *ctx = req->ctx;
2544 if (req->flags & IO_REQ_LINK_FLAGS) {
2545 if (req->flags & IO_DISARM_MASK)
2546 io_disarm_next(req);
2548 io_req_task_queue(req->link);
2552 io_req_put_rsrc(req);
2554 * Selected buffer deallocation in io_clean_op() assumes that
2555 * we don't hold ->completion_lock. Clean them here to avoid
2558 io_put_kbuf_comp(req);
2559 io_dismantle_req(req);
2560 io_put_task(req->task, 1);
2561 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2562 ctx->locked_free_nr++;
2566 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2569 if (!(req->flags & REQ_F_CQE_SKIP)) {
2571 req->cqe.flags = cflags;
2572 __io_fill_cqe_req(req->ctx, req);
2574 __io_req_complete_put(req);
2577 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2579 struct io_ring_ctx *ctx = req->ctx;
2581 spin_lock(&ctx->completion_lock);
2582 __io_req_complete_post(req, res, cflags);
2583 io_commit_cqring(ctx);
2584 spin_unlock(&ctx->completion_lock);
2585 io_cqring_ev_posted(ctx);
2588 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2592 req->cqe.flags = cflags;
2593 req->flags |= REQ_F_COMPLETE_INLINE;
2596 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2597 s32 res, u32 cflags)
2599 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2600 io_req_complete_state(req, res, cflags);
2602 io_req_complete_post(req, res, cflags);
2605 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2609 __io_req_complete(req, 0, res, 0);
2612 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2615 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2619 * Don't initialise the fields below on every allocation, but do that in
2620 * advance and keep them valid across allocations.
2622 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2626 req->async_data = NULL;
2627 /* not necessary, but safer to zero */
2631 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2632 struct io_submit_state *state)
2634 spin_lock(&ctx->completion_lock);
2635 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2636 ctx->locked_free_nr = 0;
2637 spin_unlock(&ctx->completion_lock);
2640 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2642 return !ctx->submit_state.free_list.next;
2646 * A request might get retired back into the request caches even before opcode
2647 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2648 * Because of that, io_alloc_req() should be called only under ->uring_lock
2649 * and with extra caution to not get a request that is still worked on.
2651 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2652 __must_hold(&ctx->uring_lock)
2654 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2655 void *reqs[IO_REQ_ALLOC_BATCH];
2659 * If we have more than a batch's worth of requests in our IRQ side
2660 * locked cache, grab the lock and move them over to our submission
2663 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2664 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2665 if (!io_req_cache_empty(ctx))
2669 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2672 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2673 * retry single alloc to be on the safe side.
2675 if (unlikely(ret <= 0)) {
2676 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2682 percpu_ref_get_many(&ctx->refs, ret);
2683 for (i = 0; i < ret; i++) {
2684 struct io_kiocb *req = reqs[i];
2686 io_preinit_req(req, ctx);
2687 io_req_add_to_cache(req, ctx);
2692 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2694 if (unlikely(io_req_cache_empty(ctx)))
2695 return __io_alloc_req_refill(ctx);
2699 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2701 struct io_wq_work_node *node;
2703 node = wq_stack_extract(&ctx->submit_state.free_list);
2704 return container_of(node, struct io_kiocb, comp_list);
2707 static inline void io_put_file(struct file *file)
2713 static inline void io_dismantle_req(struct io_kiocb *req)
2715 unsigned int flags = req->flags;
2717 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2719 if (!(flags & REQ_F_FIXED_FILE))
2720 io_put_file(req->file);
2723 static __cold void io_free_req(struct io_kiocb *req)
2725 struct io_ring_ctx *ctx = req->ctx;
2727 io_req_put_rsrc(req);
2728 io_dismantle_req(req);
2729 io_put_task(req->task, 1);
2731 spin_lock(&ctx->completion_lock);
2732 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2733 ctx->locked_free_nr++;
2734 spin_unlock(&ctx->completion_lock);
2737 static inline void io_remove_next_linked(struct io_kiocb *req)
2739 struct io_kiocb *nxt = req->link;
2741 req->link = nxt->link;
2745 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2746 __must_hold(&req->ctx->completion_lock)
2747 __must_hold(&req->ctx->timeout_lock)
2749 struct io_kiocb *link = req->link;
2751 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2752 struct io_timeout_data *io = link->async_data;
2754 io_remove_next_linked(req);
2755 link->timeout.head = NULL;
2756 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2757 list_del(&link->timeout.list);
2764 static void io_fail_links(struct io_kiocb *req)
2765 __must_hold(&req->ctx->completion_lock)
2767 struct io_kiocb *nxt, *link = req->link;
2768 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2772 long res = -ECANCELED;
2774 if (link->flags & REQ_F_FAIL)
2775 res = link->cqe.res;
2780 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2784 link->flags |= REQ_F_CQE_SKIP;
2786 link->flags &= ~REQ_F_CQE_SKIP;
2787 __io_req_complete_post(link, res, 0);
2792 static bool io_disarm_next(struct io_kiocb *req)
2793 __must_hold(&req->ctx->completion_lock)
2795 struct io_kiocb *link = NULL;
2796 bool posted = false;
2798 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2800 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2801 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2802 io_remove_next_linked(req);
2803 io_req_tw_post_queue(link, -ECANCELED, 0);
2806 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2807 struct io_ring_ctx *ctx = req->ctx;
2809 spin_lock_irq(&ctx->timeout_lock);
2810 link = io_disarm_linked_timeout(req);
2811 spin_unlock_irq(&ctx->timeout_lock);
2814 io_req_tw_post_queue(link, -ECANCELED, 0);
2817 if (unlikely((req->flags & REQ_F_FAIL) &&
2818 !(req->flags & REQ_F_HARDLINK))) {
2819 posted |= (req->link != NULL);
2825 static void __io_req_find_next_prep(struct io_kiocb *req)
2827 struct io_ring_ctx *ctx = req->ctx;
2830 spin_lock(&ctx->completion_lock);
2831 posted = io_disarm_next(req);
2832 io_commit_cqring(ctx);
2833 spin_unlock(&ctx->completion_lock);
2835 io_cqring_ev_posted(ctx);
2838 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2840 struct io_kiocb *nxt;
2843 * If LINK is set, we have dependent requests in this chain. If we
2844 * didn't fail this request, queue the first one up, moving any other
2845 * dependencies to the next request. In case of failure, fail the rest
2848 if (unlikely(req->flags & IO_DISARM_MASK))
2849 __io_req_find_next_prep(req);
2855 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2859 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2860 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2862 io_submit_flush_completions(ctx);
2863 mutex_unlock(&ctx->uring_lock);
2866 percpu_ref_put(&ctx->refs);
2869 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2871 io_commit_cqring(ctx);
2872 spin_unlock(&ctx->completion_lock);
2873 io_cqring_ev_posted(ctx);
2876 static void handle_prev_tw_list(struct io_wq_work_node *node,
2877 struct io_ring_ctx **ctx, bool *uring_locked)
2879 if (*ctx && !*uring_locked)
2880 spin_lock(&(*ctx)->completion_lock);
2883 struct io_wq_work_node *next = node->next;
2884 struct io_kiocb *req = container_of(node, struct io_kiocb,
2887 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2889 if (req->ctx != *ctx) {
2890 if (unlikely(!*uring_locked && *ctx))
2891 ctx_commit_and_unlock(*ctx);
2893 ctx_flush_and_put(*ctx, uring_locked);
2895 /* if not contended, grab and improve batching */
2896 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2897 percpu_ref_get(&(*ctx)->refs);
2898 if (unlikely(!*uring_locked))
2899 spin_lock(&(*ctx)->completion_lock);
2901 if (likely(*uring_locked))
2902 req->io_task_work.func(req, uring_locked);
2904 __io_req_complete_post(req, req->cqe.res,
2905 io_put_kbuf_comp(req));
2909 if (unlikely(!*uring_locked))
2910 ctx_commit_and_unlock(*ctx);
2913 static void handle_tw_list(struct io_wq_work_node *node,
2914 struct io_ring_ctx **ctx, bool *locked)
2917 struct io_wq_work_node *next = node->next;
2918 struct io_kiocb *req = container_of(node, struct io_kiocb,
2921 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2923 if (req->ctx != *ctx) {
2924 ctx_flush_and_put(*ctx, locked);
2926 /* if not contended, grab and improve batching */
2927 *locked = mutex_trylock(&(*ctx)->uring_lock);
2928 percpu_ref_get(&(*ctx)->refs);
2930 req->io_task_work.func(req, locked);
2935 static void tctx_task_work(struct callback_head *cb)
2937 bool uring_locked = false;
2938 struct io_ring_ctx *ctx = NULL;
2939 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2943 struct io_wq_work_node *node1, *node2;
2945 spin_lock_irq(&tctx->task_lock);
2946 node1 = tctx->prio_task_list.first;
2947 node2 = tctx->task_list.first;
2948 INIT_WQ_LIST(&tctx->task_list);
2949 INIT_WQ_LIST(&tctx->prio_task_list);
2950 if (!node2 && !node1)
2951 tctx->task_running = false;
2952 spin_unlock_irq(&tctx->task_lock);
2953 if (!node2 && !node1)
2957 handle_prev_tw_list(node1, &ctx, &uring_locked);
2959 handle_tw_list(node2, &ctx, &uring_locked);
2962 if (data_race(!tctx->task_list.first) &&
2963 data_race(!tctx->prio_task_list.first) && uring_locked)
2964 io_submit_flush_completions(ctx);
2967 ctx_flush_and_put(ctx, &uring_locked);
2969 /* relaxed read is enough as only the task itself sets ->in_idle */
2970 if (unlikely(atomic_read(&tctx->in_idle)))
2971 io_uring_drop_tctx_refs(current);
2974 static void __io_req_task_work_add(struct io_kiocb *req,
2975 struct io_uring_task *tctx,
2976 struct io_wq_work_list *list)
2978 struct io_ring_ctx *ctx = req->ctx;
2979 struct io_wq_work_node *node;
2980 unsigned long flags;
2983 spin_lock_irqsave(&tctx->task_lock, flags);
2984 wq_list_add_tail(&req->io_task_work.node, list);
2985 running = tctx->task_running;
2987 tctx->task_running = true;
2988 spin_unlock_irqrestore(&tctx->task_lock, flags);
2990 /* task_work already pending, we're done */
2994 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2995 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2997 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
3000 spin_lock_irqsave(&tctx->task_lock, flags);
3001 tctx->task_running = false;
3002 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
3003 spin_unlock_irqrestore(&tctx->task_lock, flags);
3006 req = container_of(node, struct io_kiocb, io_task_work.node);
3008 if (llist_add(&req->io_task_work.fallback_node,
3009 &req->ctx->fallback_llist))
3010 schedule_delayed_work(&req->ctx->fallback_work, 1);
3014 static void io_req_task_work_add(struct io_kiocb *req)
3016 struct io_uring_task *tctx = req->task->io_uring;
3018 __io_req_task_work_add(req, tctx, &tctx->task_list);
3021 static void io_req_task_prio_work_add(struct io_kiocb *req)
3023 struct io_uring_task *tctx = req->task->io_uring;
3025 if (req->ctx->flags & IORING_SETUP_SQPOLL)
3026 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
3028 __io_req_task_work_add(req, tctx, &tctx->task_list);
3031 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
3033 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
3036 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
3039 req->cqe.flags = cflags;
3040 req->io_task_work.func = io_req_tw_post;
3041 io_req_task_work_add(req);
3044 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
3046 /* not needed for normal modes, but SQPOLL depends on it */
3047 io_tw_lock(req->ctx, locked);
3048 io_req_complete_failed(req, req->cqe.res);
3051 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
3053 io_tw_lock(req->ctx, locked);
3054 /* req->task == current here, checking PF_EXITING is safe */
3055 if (likely(!(req->task->flags & PF_EXITING)))
3058 io_req_complete_failed(req, -EFAULT);
3061 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
3064 req->io_task_work.func = io_req_task_cancel;
3065 io_req_task_work_add(req);
3068 static void io_req_task_queue(struct io_kiocb *req)
3070 req->io_task_work.func = io_req_task_submit;
3071 io_req_task_work_add(req);
3074 static void io_req_task_queue_reissue(struct io_kiocb *req)
3076 req->io_task_work.func = io_queue_iowq;
3077 io_req_task_work_add(req);
3080 static void io_queue_next(struct io_kiocb *req)
3082 struct io_kiocb *nxt = io_req_find_next(req);
3085 io_req_task_queue(nxt);
3088 static void io_free_batch_list(struct io_ring_ctx *ctx,
3089 struct io_wq_work_node *node)
3090 __must_hold(&ctx->uring_lock)
3092 struct task_struct *task = NULL;
3096 struct io_kiocb *req = container_of(node, struct io_kiocb,
3099 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
3100 if (req->flags & REQ_F_REFCOUNT) {
3101 node = req->comp_list.next;
3102 if (!req_ref_put_and_test(req))
3105 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3106 struct async_poll *apoll = req->apoll;
3108 if (apoll->double_poll)
3109 kfree(apoll->double_poll);
3110 list_add(&apoll->poll.wait.entry,
3112 req->flags &= ~REQ_F_POLLED;
3114 if (req->flags & IO_REQ_LINK_FLAGS)
3116 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
3119 if (!(req->flags & REQ_F_FIXED_FILE))
3120 io_put_file(req->file);
3122 io_req_put_rsrc_locked(req, ctx);
3124 if (req->task != task) {
3126 io_put_task(task, task_refs);
3131 node = req->comp_list.next;
3132 io_req_add_to_cache(req, ctx);
3136 io_put_task(task, task_refs);
3139 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
3140 __must_hold(&ctx->uring_lock)
3142 struct io_wq_work_node *node, *prev;
3143 struct io_submit_state *state = &ctx->submit_state;
3145 if (state->flush_cqes) {
3146 spin_lock(&ctx->completion_lock);
3147 wq_list_for_each(node, prev, &state->compl_reqs) {
3148 struct io_kiocb *req = container_of(node, struct io_kiocb,
3151 if (!(req->flags & REQ_F_CQE_SKIP))
3152 __io_fill_cqe_req(ctx, req);
3155 io_commit_cqring(ctx);
3156 spin_unlock(&ctx->completion_lock);
3157 io_cqring_ev_posted(ctx);
3158 state->flush_cqes = false;
3161 io_free_batch_list(ctx, state->compl_reqs.first);
3162 INIT_WQ_LIST(&state->compl_reqs);
3166 * Drop reference to request, return next in chain (if there is one) if this
3167 * was the last reference to this request.
3169 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
3171 struct io_kiocb *nxt = NULL;
3173 if (req_ref_put_and_test(req)) {
3174 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
3175 nxt = io_req_find_next(req);
3181 static inline void io_put_req(struct io_kiocb *req)
3183 if (req_ref_put_and_test(req)) {
3189 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
3191 /* See comment at the top of this file */
3193 return __io_cqring_events(ctx);
3196 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
3198 struct io_rings *rings = ctx->rings;
3200 /* make sure SQ entry isn't read before tail */
3201 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3204 static inline bool io_run_task_work(void)
3206 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3207 __set_current_state(TASK_RUNNING);
3208 clear_notify_signal();
3209 if (task_work_pending(current))
3217 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3219 struct io_wq_work_node *pos, *start, *prev;
3220 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3221 DEFINE_IO_COMP_BATCH(iob);
3225 * Only spin for completions if we don't have multiple devices hanging
3226 * off our complete list.
3228 if (ctx->poll_multi_queue || force_nonspin)
3229 poll_flags |= BLK_POLL_ONESHOT;
3231 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3232 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3233 struct kiocb *kiocb = &req->rw.kiocb;
3237 * Move completed and retryable entries to our local lists.
3238 * If we find a request that requires polling, break out
3239 * and complete those lists first, if we have entries there.
3241 if (READ_ONCE(req->iopoll_completed))
3244 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3245 if (unlikely(ret < 0))
3248 poll_flags |= BLK_POLL_ONESHOT;
3250 /* iopoll may have completed current req */
3251 if (!rq_list_empty(iob.req_list) ||
3252 READ_ONCE(req->iopoll_completed))
3256 if (!rq_list_empty(iob.req_list))
3262 wq_list_for_each_resume(pos, prev) {
3263 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3265 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3266 if (!smp_load_acquire(&req->iopoll_completed))
3269 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3272 req->cqe.flags = io_put_kbuf(req, 0);
3273 __io_fill_cqe_req(req->ctx, req);
3276 if (unlikely(!nr_events))
3279 io_commit_cqring(ctx);
3280 io_cqring_ev_posted_iopoll(ctx);
3281 pos = start ? start->next : ctx->iopoll_list.first;
3282 wq_list_cut(&ctx->iopoll_list, prev, start);
3283 io_free_batch_list(ctx, pos);
3288 * We can't just wait for polled events to come to us, we have to actively
3289 * find and complete them.
3291 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3293 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3296 mutex_lock(&ctx->uring_lock);
3297 while (!wq_list_empty(&ctx->iopoll_list)) {
3298 /* let it sleep and repeat later if can't complete a request */
3299 if (io_do_iopoll(ctx, true) == 0)
3302 * Ensure we allow local-to-the-cpu processing to take place,
3303 * in this case we need to ensure that we reap all events.
3304 * Also let task_work, etc. to progress by releasing the mutex
3306 if (need_resched()) {
3307 mutex_unlock(&ctx->uring_lock);
3309 mutex_lock(&ctx->uring_lock);
3312 mutex_unlock(&ctx->uring_lock);
3315 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3317 unsigned int nr_events = 0;
3319 unsigned long check_cq;
3322 * Don't enter poll loop if we already have events pending.
3323 * If we do, we can potentially be spinning for commands that
3324 * already triggered a CQE (eg in error).
3326 check_cq = READ_ONCE(ctx->check_cq);
3327 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3328 __io_cqring_overflow_flush(ctx, false);
3329 if (io_cqring_events(ctx))
3333 * Similarly do not spin if we have not informed the user of any
3336 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3341 * If a submit got punted to a workqueue, we can have the
3342 * application entering polling for a command before it gets
3343 * issued. That app will hold the uring_lock for the duration
3344 * of the poll right here, so we need to take a breather every
3345 * now and then to ensure that the issue has a chance to add
3346 * the poll to the issued list. Otherwise we can spin here
3347 * forever, while the workqueue is stuck trying to acquire the
3350 if (wq_list_empty(&ctx->iopoll_list)) {
3351 u32 tail = ctx->cached_cq_tail;
3353 mutex_unlock(&ctx->uring_lock);
3355 mutex_lock(&ctx->uring_lock);
3357 /* some requests don't go through iopoll_list */
3358 if (tail != ctx->cached_cq_tail ||
3359 wq_list_empty(&ctx->iopoll_list))
3362 ret = io_do_iopoll(ctx, !min);
3367 } while (nr_events < min && !need_resched());
3372 static void kiocb_end_write(struct io_kiocb *req)
3375 * Tell lockdep we inherited freeze protection from submission
3378 if (req->flags & REQ_F_ISREG) {
3379 struct super_block *sb = file_inode(req->file)->i_sb;
3381 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3387 static bool io_resubmit_prep(struct io_kiocb *req)
3389 struct io_async_rw *rw = req->async_data;
3391 if (!req_has_async_data(req))
3392 return !io_req_prep_async(req);
3393 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3397 static bool io_rw_should_reissue(struct io_kiocb *req)
3399 umode_t mode = file_inode(req->file)->i_mode;
3400 struct io_ring_ctx *ctx = req->ctx;
3402 if (!S_ISBLK(mode) && !S_ISREG(mode))
3404 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3405 !(ctx->flags & IORING_SETUP_IOPOLL)))
3408 * If ref is dying, we might be running poll reap from the exit work.
3409 * Don't attempt to reissue from that path, just let it fail with
3412 if (percpu_ref_is_dying(&ctx->refs))
3415 * Play it safe and assume not safe to re-import and reissue if we're
3416 * not in the original thread group (or in task context).
3418 if (!same_thread_group(req->task, current) || !in_task())
3423 static bool io_resubmit_prep(struct io_kiocb *req)
3427 static bool io_rw_should_reissue(struct io_kiocb *req)
3433 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3435 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3436 kiocb_end_write(req);
3437 fsnotify_modify(req->file);
3439 fsnotify_access(req->file);
3441 if (unlikely(res != req->cqe.res)) {
3442 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3443 io_rw_should_reissue(req)) {
3444 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3453 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3455 int res = req->cqe.res;
3458 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3459 io_req_add_compl_list(req);
3461 io_req_complete_post(req, res,
3462 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3466 static void __io_complete_rw(struct io_kiocb *req, long res,
3467 unsigned int issue_flags)
3469 if (__io_complete_rw_common(req, res))
3471 __io_req_complete(req, issue_flags, req->cqe.res,
3472 io_put_kbuf(req, issue_flags));
3475 static void io_complete_rw(struct kiocb *kiocb, long res)
3477 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3479 if (__io_complete_rw_common(req, res))
3482 req->io_task_work.func = io_req_task_complete;
3483 io_req_task_prio_work_add(req);
3486 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3488 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3490 if (kiocb->ki_flags & IOCB_WRITE)
3491 kiocb_end_write(req);
3492 if (unlikely(res != req->cqe.res)) {
3493 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3494 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3500 /* order with io_iopoll_complete() checking ->iopoll_completed */
3501 smp_store_release(&req->iopoll_completed, 1);
3505 * After the iocb has been issued, it's safe to be found on the poll list.
3506 * Adding the kiocb to the list AFTER submission ensures that we don't
3507 * find it from a io_do_iopoll() thread before the issuer is done
3508 * accessing the kiocb cookie.
3510 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3512 struct io_ring_ctx *ctx = req->ctx;
3513 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3515 /* workqueue context doesn't hold uring_lock, grab it now */
3516 if (unlikely(needs_lock))
3517 mutex_lock(&ctx->uring_lock);
3520 * Track whether we have multiple files in our lists. This will impact
3521 * how we do polling eventually, not spinning if we're on potentially
3522 * different devices.
3524 if (wq_list_empty(&ctx->iopoll_list)) {
3525 ctx->poll_multi_queue = false;
3526 } else if (!ctx->poll_multi_queue) {
3527 struct io_kiocb *list_req;
3529 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3531 if (list_req->file != req->file)
3532 ctx->poll_multi_queue = true;
3536 * For fast devices, IO may have already completed. If it has, add
3537 * it to the front so we find it first.
3539 if (READ_ONCE(req->iopoll_completed))
3540 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3542 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3544 if (unlikely(needs_lock)) {
3546 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3547 * in sq thread task context or in io worker task context. If
3548 * current task context is sq thread, we don't need to check
3549 * whether should wake up sq thread.
3551 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3552 wq_has_sleeper(&ctx->sq_data->wait))
3553 wake_up(&ctx->sq_data->wait);
3555 mutex_unlock(&ctx->uring_lock);
3559 static bool io_bdev_nowait(struct block_device *bdev)
3561 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3565 * If we tracked the file through the SCM inflight mechanism, we could support
3566 * any file. For now, just ensure that anything potentially problematic is done
3569 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3571 if (S_ISBLK(mode)) {
3572 if (IS_ENABLED(CONFIG_BLOCK) &&
3573 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3579 if (S_ISREG(mode)) {
3580 if (IS_ENABLED(CONFIG_BLOCK) &&
3581 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3582 file->f_op != &io_uring_fops)
3587 /* any ->read/write should understand O_NONBLOCK */
3588 if (file->f_flags & O_NONBLOCK)
3590 return file->f_mode & FMODE_NOWAIT;
3594 * If we tracked the file through the SCM inflight mechanism, we could support
3595 * any file. For now, just ensure that anything potentially problematic is done
3598 static unsigned int io_file_get_flags(struct file *file)
3600 umode_t mode = file_inode(file)->i_mode;
3601 unsigned int res = 0;
3605 if (__io_file_supports_nowait(file, mode))
3607 if (io_file_need_scm(file))
3612 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3614 return req->flags & REQ_F_SUPPORT_NOWAIT;
3617 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3619 struct kiocb *kiocb = &req->rw.kiocb;
3623 kiocb->ki_pos = READ_ONCE(sqe->off);
3624 /* used for fixed read/write too - just read unconditionally */
3625 req->buf_index = READ_ONCE(sqe->buf_index);
3627 if (req->opcode == IORING_OP_READ_FIXED ||
3628 req->opcode == IORING_OP_WRITE_FIXED) {
3629 struct io_ring_ctx *ctx = req->ctx;
3632 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3634 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3635 req->imu = ctx->user_bufs[index];
3636 io_req_set_rsrc_node(req, ctx, 0);
3639 ioprio = READ_ONCE(sqe->ioprio);
3641 ret = ioprio_check_cap(ioprio);
3645 kiocb->ki_ioprio = ioprio;
3647 kiocb->ki_ioprio = get_current_ioprio();
3650 req->rw.addr = READ_ONCE(sqe->addr);
3651 req->rw.len = READ_ONCE(sqe->len);
3652 req->rw.flags = READ_ONCE(sqe->rw_flags);
3656 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3662 case -ERESTARTNOINTR:
3663 case -ERESTARTNOHAND:
3664 case -ERESTART_RESTARTBLOCK:
3666 * We can't just restart the syscall, since previously
3667 * submitted sqes may already be in progress. Just fail this
3673 kiocb->ki_complete(kiocb, ret);
3677 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3679 struct kiocb *kiocb = &req->rw.kiocb;
3681 if (kiocb->ki_pos != -1)
3682 return &kiocb->ki_pos;
3684 if (!(req->file->f_mode & FMODE_STREAM)) {
3685 req->flags |= REQ_F_CUR_POS;
3686 kiocb->ki_pos = req->file->f_pos;
3687 return &kiocb->ki_pos;
3694 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3695 unsigned int issue_flags)
3697 struct io_async_rw *io = req->async_data;
3699 /* add previously done IO, if any */
3700 if (req_has_async_data(req) && io->bytes_done > 0) {
3702 ret = io->bytes_done;
3704 ret += io->bytes_done;
3707 if (req->flags & REQ_F_CUR_POS)
3708 req->file->f_pos = req->rw.kiocb.ki_pos;
3709 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3710 __io_complete_rw(req, ret, issue_flags);
3712 io_rw_done(&req->rw.kiocb, ret);
3714 if (req->flags & REQ_F_REISSUE) {
3715 req->flags &= ~REQ_F_REISSUE;
3716 if (io_resubmit_prep(req))
3717 io_req_task_queue_reissue(req);
3719 io_req_task_queue_fail(req, ret);
3723 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3724 struct io_mapped_ubuf *imu)
3726 size_t len = req->rw.len;
3727 u64 buf_end, buf_addr = req->rw.addr;
3730 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3732 /* not inside the mapped region */
3733 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3737 * May not be a start of buffer, set size appropriately
3738 * and advance us to the beginning.
3740 offset = buf_addr - imu->ubuf;
3741 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3745 * Don't use iov_iter_advance() here, as it's really slow for
3746 * using the latter parts of a big fixed buffer - it iterates
3747 * over each segment manually. We can cheat a bit here, because
3750 * 1) it's a BVEC iter, we set it up
3751 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3752 * first and last bvec
3754 * So just find our index, and adjust the iterator afterwards.
3755 * If the offset is within the first bvec (or the whole first
3756 * bvec, just use iov_iter_advance(). This makes it easier
3757 * since we can just skip the first segment, which may not
3758 * be PAGE_SIZE aligned.
3760 const struct bio_vec *bvec = imu->bvec;
3762 if (offset <= bvec->bv_len) {
3763 iov_iter_advance(iter, offset);
3765 unsigned long seg_skip;
3767 /* skip first vec */
3768 offset -= bvec->bv_len;
3769 seg_skip = 1 + (offset >> PAGE_SHIFT);
3771 iter->bvec = bvec + seg_skip;
3772 iter->nr_segs -= seg_skip;
3773 iter->count -= bvec->bv_len + offset;
3774 iter->iov_offset = offset & ~PAGE_MASK;
3781 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3782 unsigned int issue_flags)
3784 if (WARN_ON_ONCE(!req->imu))
3786 return __io_import_fixed(req, rw, iter, req->imu);
3789 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3790 struct io_buffer_list *bl, unsigned int bgid)
3793 if (bgid < BGID_ARRAY)
3796 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3799 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3800 struct io_buffer_list *bl)
3802 if (!list_empty(&bl->buf_list)) {
3803 struct io_buffer *kbuf;
3805 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3806 list_del(&kbuf->list);
3807 if (*len > kbuf->len)
3809 req->flags |= REQ_F_BUFFER_SELECTED;
3811 req->buf_index = kbuf->bid;
3812 return u64_to_user_ptr(kbuf->addr);
3817 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3818 struct io_buffer_list *bl,
3819 unsigned int issue_flags)
3821 struct io_uring_buf_ring *br = bl->buf_ring;
3822 struct io_uring_buf *buf;
3823 __u16 head = bl->head;
3825 if (unlikely(smp_load_acquire(&br->tail) == head))
3829 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3830 buf = &br->bufs[head];
3832 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3833 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3834 buf = page_address(bl->buf_pages[index]);
3837 if (*len > buf->len)
3839 req->flags |= REQ_F_BUFFER_RING;
3841 req->buf_index = buf->bid;
3843 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3845 * If we came in unlocked, we have no choice but to consume the
3846 * buffer here. This does mean it'll be pinned until the IO
3847 * completes. But coming in unlocked means we're in io-wq
3848 * context, hence there should be no further retry. For the
3849 * locked case, the caller must ensure to call the commit when
3850 * the transfer completes (or if we get -EAGAIN and must poll
3853 req->buf_list = NULL;
3856 return u64_to_user_ptr(buf->addr);
3859 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3860 unsigned int issue_flags)
3862 struct io_ring_ctx *ctx = req->ctx;
3863 struct io_buffer_list *bl;
3864 void __user *ret = NULL;
3866 io_ring_submit_lock(req->ctx, issue_flags);
3868 bl = io_buffer_get_list(ctx, req->buf_index);
3870 if (bl->buf_nr_pages)
3871 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3873 ret = io_provided_buffer_select(req, len, bl);
3875 io_ring_submit_unlock(req->ctx, issue_flags);
3879 #ifdef CONFIG_COMPAT
3880 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3881 unsigned int issue_flags)
3883 struct compat_iovec __user *uiov;
3884 compat_ssize_t clen;
3888 uiov = u64_to_user_ptr(req->rw.addr);
3889 if (!access_ok(uiov, sizeof(*uiov)))
3891 if (__get_user(clen, &uiov->iov_len))
3897 buf = io_buffer_select(req, &len, issue_flags);
3900 req->rw.addr = (unsigned long) buf;
3901 iov[0].iov_base = buf;
3902 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3907 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3908 unsigned int issue_flags)
3910 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3914 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3917 len = iov[0].iov_len;
3920 buf = io_buffer_select(req, &len, issue_flags);
3923 req->rw.addr = (unsigned long) buf;
3924 iov[0].iov_base = buf;
3925 req->rw.len = iov[0].iov_len = len;
3929 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3930 unsigned int issue_flags)
3932 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3933 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3934 iov[0].iov_len = req->rw.len;
3937 if (req->rw.len != 1)
3940 #ifdef CONFIG_COMPAT
3941 if (req->ctx->compat)
3942 return io_compat_import(req, iov, issue_flags);
3945 return __io_iov_buffer_select(req, iov, issue_flags);
3948 static inline bool io_do_buffer_select(struct io_kiocb *req)
3950 if (!(req->flags & REQ_F_BUFFER_SELECT))
3952 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3955 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3956 struct io_rw_state *s,
3957 unsigned int issue_flags)
3959 struct iov_iter *iter = &s->iter;
3960 u8 opcode = req->opcode;
3961 struct iovec *iovec;
3966 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3967 ret = io_import_fixed(req, rw, iter, issue_flags);
3969 return ERR_PTR(ret);
3973 buf = u64_to_user_ptr(req->rw.addr);
3974 sqe_len = req->rw.len;
3976 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3977 if (io_do_buffer_select(req)) {
3978 buf = io_buffer_select(req, &sqe_len, issue_flags);
3980 return ERR_PTR(-ENOBUFS);
3981 req->rw.addr = (unsigned long) buf;
3982 req->rw.len = sqe_len;
3985 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3987 return ERR_PTR(ret);
3991 iovec = s->fast_iov;
3992 if (req->flags & REQ_F_BUFFER_SELECT) {
3993 ret = io_iov_buffer_select(req, iovec, issue_flags);
3995 return ERR_PTR(ret);
3996 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
4000 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
4002 if (unlikely(ret < 0))
4003 return ERR_PTR(ret);
4007 static inline int io_import_iovec(int rw, struct io_kiocb *req,
4008 struct iovec **iovec, struct io_rw_state *s,
4009 unsigned int issue_flags)
4011 *iovec = __io_import_iovec(rw, req, s, issue_flags);
4012 if (unlikely(IS_ERR(*iovec)))
4013 return PTR_ERR(*iovec);
4015 iov_iter_save_state(&s->iter, &s->iter_state);
4019 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
4021 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
4025 * For files that don't have ->read_iter() and ->write_iter(), handle them
4026 * by looping over ->read() or ->write() manually.
4028 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
4030 struct kiocb *kiocb = &req->rw.kiocb;
4031 struct file *file = req->file;
4036 * Don't support polled IO through this interface, and we can't
4037 * support non-blocking either. For the latter, this just causes
4038 * the kiocb to be handled from an async context.
4040 if (kiocb->ki_flags & IOCB_HIPRI)
4042 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
4043 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
4046 ppos = io_kiocb_ppos(kiocb);
4048 while (iov_iter_count(iter)) {
4052 if (!iov_iter_is_bvec(iter)) {
4053 iovec = iov_iter_iovec(iter);
4055 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
4056 iovec.iov_len = req->rw.len;
4060 nr = file->f_op->read(file, iovec.iov_base,
4061 iovec.iov_len, ppos);
4063 nr = file->f_op->write(file, iovec.iov_base,
4064 iovec.iov_len, ppos);
4073 if (!iov_iter_is_bvec(iter)) {
4074 iov_iter_advance(iter, nr);
4081 if (nr != iovec.iov_len)
4088 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
4089 const struct iovec *fast_iov, struct iov_iter *iter)
4091 struct io_async_rw *rw = req->async_data;
4093 memcpy(&rw->s.iter, iter, sizeof(*iter));
4094 rw->free_iovec = iovec;
4096 /* can only be fixed buffers, no need to do anything */
4097 if (iov_iter_is_bvec(iter))
4100 unsigned iov_off = 0;
4102 rw->s.iter.iov = rw->s.fast_iov;
4103 if (iter->iov != fast_iov) {
4104 iov_off = iter->iov - fast_iov;
4105 rw->s.iter.iov += iov_off;
4107 if (rw->s.fast_iov != fast_iov)
4108 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
4109 sizeof(struct iovec) * iter->nr_segs);
4111 req->flags |= REQ_F_NEED_CLEANUP;
4115 static inline bool io_alloc_async_data(struct io_kiocb *req)
4117 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
4118 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
4119 if (req->async_data) {
4120 req->flags |= REQ_F_ASYNC_DATA;
4126 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
4127 struct io_rw_state *s, bool force)
4129 if (!force && !io_op_defs[req->opcode].needs_async_setup)
4131 if (!req_has_async_data(req)) {
4132 struct io_async_rw *iorw;
4134 if (io_alloc_async_data(req)) {
4139 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
4140 iorw = req->async_data;
4141 /* we've copied and mapped the iter, ensure state is saved */
4142 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
4147 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
4149 struct io_async_rw *iorw = req->async_data;
4153 /* submission path, ->uring_lock should already be taken */
4154 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
4155 if (unlikely(ret < 0))
4158 iorw->bytes_done = 0;
4159 iorw->free_iovec = iov;
4161 req->flags |= REQ_F_NEED_CLEANUP;
4165 static int io_readv_prep_async(struct io_kiocb *req)
4167 return io_rw_prep_async(req, READ);
4170 static int io_writev_prep_async(struct io_kiocb *req)
4172 return io_rw_prep_async(req, WRITE);
4176 * This is our waitqueue callback handler, registered through __folio_lock_async()
4177 * when we initially tried to do the IO with the iocb armed our waitqueue.
4178 * This gets called when the page is unlocked, and we generally expect that to
4179 * happen when the page IO is completed and the page is now uptodate. This will
4180 * queue a task_work based retry of the operation, attempting to copy the data
4181 * again. If the latter fails because the page was NOT uptodate, then we will
4182 * do a thread based blocking retry of the operation. That's the unexpected
4185 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
4186 int sync, void *arg)
4188 struct wait_page_queue *wpq;
4189 struct io_kiocb *req = wait->private;
4190 struct wait_page_key *key = arg;
4192 wpq = container_of(wait, struct wait_page_queue, wait);
4194 if (!wake_page_match(wpq, key))
4197 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
4198 list_del_init(&wait->entry);
4199 io_req_task_queue(req);
4204 * This controls whether a given IO request should be armed for async page
4205 * based retry. If we return false here, the request is handed to the async
4206 * worker threads for retry. If we're doing buffered reads on a regular file,
4207 * we prepare a private wait_page_queue entry and retry the operation. This
4208 * will either succeed because the page is now uptodate and unlocked, or it
4209 * will register a callback when the page is unlocked at IO completion. Through
4210 * that callback, io_uring uses task_work to setup a retry of the operation.
4211 * That retry will attempt the buffered read again. The retry will generally
4212 * succeed, or in rare cases where it fails, we then fall back to using the
4213 * async worker threads for a blocking retry.
4215 static bool io_rw_should_retry(struct io_kiocb *req)
4217 struct io_async_rw *rw = req->async_data;
4218 struct wait_page_queue *wait = &rw->wpq;
4219 struct kiocb *kiocb = &req->rw.kiocb;
4221 /* never retry for NOWAIT, we just complete with -EAGAIN */
4222 if (req->flags & REQ_F_NOWAIT)
4225 /* Only for buffered IO */
4226 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4230 * just use poll if we can, and don't attempt if the fs doesn't
4231 * support callback based unlocks
4233 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4236 wait->wait.func = io_async_buf_func;
4237 wait->wait.private = req;
4238 wait->wait.flags = 0;
4239 INIT_LIST_HEAD(&wait->wait.entry);
4240 kiocb->ki_flags |= IOCB_WAITQ;
4241 kiocb->ki_flags &= ~IOCB_NOWAIT;
4242 kiocb->ki_waitq = wait;
4246 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4248 if (likely(req->file->f_op->read_iter))
4249 return call_read_iter(req->file, &req->rw.kiocb, iter);
4250 else if (req->file->f_op->read)
4251 return loop_rw_iter(READ, req, iter);
4256 static bool need_read_all(struct io_kiocb *req)
4258 return req->flags & REQ_F_ISREG ||
4259 S_ISBLK(file_inode(req->file)->i_mode);
4262 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4264 struct kiocb *kiocb = &req->rw.kiocb;
4265 struct io_ring_ctx *ctx = req->ctx;
4266 struct file *file = req->file;
4269 if (unlikely(!file || !(file->f_mode & mode)))
4272 if (!io_req_ffs_set(req))
4273 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4275 kiocb->ki_flags = iocb_flags(file);
4276 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4281 * If the file is marked O_NONBLOCK, still allow retry for it if it
4282 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4283 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4285 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4286 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4287 req->flags |= REQ_F_NOWAIT;
4289 if (ctx->flags & IORING_SETUP_IOPOLL) {
4290 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4293 kiocb->private = NULL;
4294 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4295 kiocb->ki_complete = io_complete_rw_iopoll;
4296 req->iopoll_completed = 0;
4298 if (kiocb->ki_flags & IOCB_HIPRI)
4300 kiocb->ki_complete = io_complete_rw;
4306 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4308 struct io_rw_state __s, *s = &__s;
4309 struct iovec *iovec;
4310 struct kiocb *kiocb = &req->rw.kiocb;
4311 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4312 struct io_async_rw *rw;
4316 if (!req_has_async_data(req)) {
4317 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4318 if (unlikely(ret < 0))
4321 rw = req->async_data;
4325 * Safe and required to re-import if we're using provided
4326 * buffers, as we dropped the selected one before retry.
4328 if (io_do_buffer_select(req)) {
4329 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4330 if (unlikely(ret < 0))
4335 * We come here from an earlier attempt, restore our state to
4336 * match in case it doesn't. It's cheap enough that we don't
4337 * need to make this conditional.
4339 iov_iter_restore(&s->iter, &s->iter_state);
4342 ret = io_rw_init_file(req, FMODE_READ);
4343 if (unlikely(ret)) {
4347 req->cqe.res = iov_iter_count(&s->iter);
4349 if (force_nonblock) {
4350 /* If the file doesn't support async, just async punt */
4351 if (unlikely(!io_file_supports_nowait(req))) {
4352 ret = io_setup_async_rw(req, iovec, s, true);
4353 return ret ?: -EAGAIN;
4355 kiocb->ki_flags |= IOCB_NOWAIT;
4357 /* Ensure we clear previously set non-block flag */
4358 kiocb->ki_flags &= ~IOCB_NOWAIT;
4361 ppos = io_kiocb_update_pos(req);
4363 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4364 if (unlikely(ret)) {
4369 ret = io_iter_do_read(req, &s->iter);
4371 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4372 req->flags &= ~REQ_F_REISSUE;
4373 /* if we can poll, just do that */
4374 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4376 /* IOPOLL retry should happen for io-wq threads */
4377 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4379 /* no retry on NONBLOCK nor RWF_NOWAIT */
4380 if (req->flags & REQ_F_NOWAIT)
4383 } else if (ret == -EIOCBQUEUED) {
4385 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4386 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4387 /* read all, failed, already did sync or don't want to retry */
4392 * Don't depend on the iter state matching what was consumed, or being
4393 * untouched in case of error. Restore it and we'll advance it
4394 * manually if we need to.
4396 iov_iter_restore(&s->iter, &s->iter_state);
4398 ret2 = io_setup_async_rw(req, iovec, s, true);
4403 rw = req->async_data;
4406 * Now use our persistent iterator and state, if we aren't already.
4407 * We've restored and mapped the iter to match.
4412 * We end up here because of a partial read, either from
4413 * above or inside this loop. Advance the iter by the bytes
4414 * that were consumed.
4416 iov_iter_advance(&s->iter, ret);
4417 if (!iov_iter_count(&s->iter))
4419 rw->bytes_done += ret;
4420 iov_iter_save_state(&s->iter, &s->iter_state);
4422 /* if we can retry, do so with the callbacks armed */
4423 if (!io_rw_should_retry(req)) {
4424 kiocb->ki_flags &= ~IOCB_WAITQ;
4429 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4430 * we get -EIOCBQUEUED, then we'll get a notification when the
4431 * desired page gets unlocked. We can also get a partial read
4432 * here, and if we do, then just retry at the new offset.
4434 ret = io_iter_do_read(req, &s->iter);
4435 if (ret == -EIOCBQUEUED)
4437 /* we got some bytes, but not all. retry. */
4438 kiocb->ki_flags &= ~IOCB_WAITQ;
4439 iov_iter_restore(&s->iter, &s->iter_state);
4442 kiocb_done(req, ret, issue_flags);
4444 /* it's faster to check here then delegate to kfree */
4450 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4452 struct io_rw_state __s, *s = &__s;
4453 struct iovec *iovec;
4454 struct kiocb *kiocb = &req->rw.kiocb;
4455 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4459 if (!req_has_async_data(req)) {
4460 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4461 if (unlikely(ret < 0))
4464 struct io_async_rw *rw = req->async_data;
4467 iov_iter_restore(&s->iter, &s->iter_state);
4470 ret = io_rw_init_file(req, FMODE_WRITE);
4471 if (unlikely(ret)) {
4475 req->cqe.res = iov_iter_count(&s->iter);
4477 if (force_nonblock) {
4478 /* If the file doesn't support async, just async punt */
4479 if (unlikely(!io_file_supports_nowait(req)))
4482 /* file path doesn't support NOWAIT for non-direct_IO */
4483 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4484 (req->flags & REQ_F_ISREG))
4487 kiocb->ki_flags |= IOCB_NOWAIT;
4489 /* Ensure we clear previously set non-block flag */
4490 kiocb->ki_flags &= ~IOCB_NOWAIT;
4493 ppos = io_kiocb_update_pos(req);
4495 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4500 * Open-code file_start_write here to grab freeze protection,
4501 * which will be released by another thread in
4502 * io_complete_rw(). Fool lockdep by telling it the lock got
4503 * released so that it doesn't complain about the held lock when
4504 * we return to userspace.
4506 if (req->flags & REQ_F_ISREG) {
4507 sb_start_write(file_inode(req->file)->i_sb);
4508 __sb_writers_release(file_inode(req->file)->i_sb,
4511 kiocb->ki_flags |= IOCB_WRITE;
4513 if (likely(req->file->f_op->write_iter))
4514 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4515 else if (req->file->f_op->write)
4516 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4520 if (req->flags & REQ_F_REISSUE) {
4521 req->flags &= ~REQ_F_REISSUE;
4526 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4527 * retry them without IOCB_NOWAIT.
4529 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4531 /* no retry on NONBLOCK nor RWF_NOWAIT */
4532 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4534 if (!force_nonblock || ret2 != -EAGAIN) {
4535 /* IOPOLL retry should happen for io-wq threads */
4536 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4539 kiocb_done(req, ret2, issue_flags);
4542 iov_iter_restore(&s->iter, &s->iter_state);
4543 ret = io_setup_async_rw(req, iovec, s, false);
4544 return ret ?: -EAGAIN;
4547 /* it's reportedly faster than delegating the null check to kfree() */
4553 static int io_renameat_prep(struct io_kiocb *req,
4554 const struct io_uring_sqe *sqe)
4556 struct io_rename *ren = &req->rename;
4557 const char __user *oldf, *newf;
4559 if (sqe->buf_index || sqe->splice_fd_in)
4561 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4564 ren->old_dfd = READ_ONCE(sqe->fd);
4565 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4566 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4567 ren->new_dfd = READ_ONCE(sqe->len);
4568 ren->flags = READ_ONCE(sqe->rename_flags);
4570 ren->oldpath = getname(oldf);
4571 if (IS_ERR(ren->oldpath))
4572 return PTR_ERR(ren->oldpath);
4574 ren->newpath = getname(newf);
4575 if (IS_ERR(ren->newpath)) {
4576 putname(ren->oldpath);
4577 return PTR_ERR(ren->newpath);
4580 req->flags |= REQ_F_NEED_CLEANUP;
4584 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4586 struct io_rename *ren = &req->rename;
4589 if (issue_flags & IO_URING_F_NONBLOCK)
4592 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4593 ren->newpath, ren->flags);
4595 req->flags &= ~REQ_F_NEED_CLEANUP;
4596 io_req_complete(req, ret);
4600 static inline void __io_xattr_finish(struct io_kiocb *req)
4602 struct io_xattr *ix = &req->xattr;
4605 putname(ix->filename);
4607 kfree(ix->ctx.kname);
4608 kvfree(ix->ctx.kvalue);
4611 static void io_xattr_finish(struct io_kiocb *req, int ret)
4613 req->flags &= ~REQ_F_NEED_CLEANUP;
4615 __io_xattr_finish(req);
4616 io_req_complete(req, ret);
4619 static int __io_getxattr_prep(struct io_kiocb *req,
4620 const struct io_uring_sqe *sqe)
4622 struct io_xattr *ix = &req->xattr;
4623 const char __user *name;
4626 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4629 ix->filename = NULL;
4630 ix->ctx.kvalue = NULL;
4631 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4632 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4633 ix->ctx.size = READ_ONCE(sqe->len);
4634 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4639 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4643 ret = strncpy_from_user(ix->ctx.kname->name, name,
4644 sizeof(ix->ctx.kname->name));
4645 if (!ret || ret == sizeof(ix->ctx.kname->name))
4648 kfree(ix->ctx.kname);
4652 req->flags |= REQ_F_NEED_CLEANUP;
4656 static int io_fgetxattr_prep(struct io_kiocb *req,
4657 const struct io_uring_sqe *sqe)
4659 return __io_getxattr_prep(req, sqe);
4662 static int io_getxattr_prep(struct io_kiocb *req,
4663 const struct io_uring_sqe *sqe)
4665 struct io_xattr *ix = &req->xattr;
4666 const char __user *path;
4669 ret = __io_getxattr_prep(req, sqe);
4673 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4675 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4676 if (IS_ERR(ix->filename)) {
4677 ret = PTR_ERR(ix->filename);
4678 ix->filename = NULL;
4684 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4686 struct io_xattr *ix = &req->xattr;
4689 if (issue_flags & IO_URING_F_NONBLOCK)
4692 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4693 req->file->f_path.dentry,
4696 io_xattr_finish(req, ret);
4700 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4702 struct io_xattr *ix = &req->xattr;
4703 unsigned int lookup_flags = LOOKUP_FOLLOW;
4707 if (issue_flags & IO_URING_F_NONBLOCK)
4711 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4713 ret = do_getxattr(mnt_user_ns(path.mnt),
4718 if (retry_estale(ret, lookup_flags)) {
4719 lookup_flags |= LOOKUP_REVAL;
4724 io_xattr_finish(req, ret);
4728 static int __io_setxattr_prep(struct io_kiocb *req,
4729 const struct io_uring_sqe *sqe)
4731 struct io_xattr *ix = &req->xattr;
4732 const char __user *name;
4735 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4738 ix->filename = NULL;
4739 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4740 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4741 ix->ctx.kvalue = NULL;
4742 ix->ctx.size = READ_ONCE(sqe->len);
4743 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4745 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4749 ret = setxattr_copy(name, &ix->ctx);
4751 kfree(ix->ctx.kname);
4755 req->flags |= REQ_F_NEED_CLEANUP;
4759 static int io_setxattr_prep(struct io_kiocb *req,
4760 const struct io_uring_sqe *sqe)
4762 struct io_xattr *ix = &req->xattr;
4763 const char __user *path;
4766 ret = __io_setxattr_prep(req, sqe);
4770 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4772 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4773 if (IS_ERR(ix->filename)) {
4774 ret = PTR_ERR(ix->filename);
4775 ix->filename = NULL;
4781 static int io_fsetxattr_prep(struct io_kiocb *req,
4782 const struct io_uring_sqe *sqe)
4784 return __io_setxattr_prep(req, sqe);
4787 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4790 struct io_xattr *ix = &req->xattr;
4793 ret = mnt_want_write(path->mnt);
4795 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4796 mnt_drop_write(path->mnt);
4802 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4806 if (issue_flags & IO_URING_F_NONBLOCK)
4809 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4810 io_xattr_finish(req, ret);
4815 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4817 struct io_xattr *ix = &req->xattr;
4818 unsigned int lookup_flags = LOOKUP_FOLLOW;
4822 if (issue_flags & IO_URING_F_NONBLOCK)
4826 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4828 ret = __io_setxattr(req, issue_flags, &path);
4830 if (retry_estale(ret, lookup_flags)) {
4831 lookup_flags |= LOOKUP_REVAL;
4836 io_xattr_finish(req, ret);
4840 static int io_unlinkat_prep(struct io_kiocb *req,
4841 const struct io_uring_sqe *sqe)
4843 struct io_unlink *un = &req->unlink;
4844 const char __user *fname;
4846 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4848 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4851 un->dfd = READ_ONCE(sqe->fd);
4853 un->flags = READ_ONCE(sqe->unlink_flags);
4854 if (un->flags & ~AT_REMOVEDIR)
4857 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4858 un->filename = getname(fname);
4859 if (IS_ERR(un->filename))
4860 return PTR_ERR(un->filename);
4862 req->flags |= REQ_F_NEED_CLEANUP;
4866 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4868 struct io_unlink *un = &req->unlink;
4871 if (issue_flags & IO_URING_F_NONBLOCK)
4874 if (un->flags & AT_REMOVEDIR)
4875 ret = do_rmdir(un->dfd, un->filename);
4877 ret = do_unlinkat(un->dfd, un->filename);
4879 req->flags &= ~REQ_F_NEED_CLEANUP;
4880 io_req_complete(req, ret);
4884 static int io_mkdirat_prep(struct io_kiocb *req,
4885 const struct io_uring_sqe *sqe)
4887 struct io_mkdir *mkd = &req->mkdir;
4888 const char __user *fname;
4890 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4892 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4895 mkd->dfd = READ_ONCE(sqe->fd);
4896 mkd->mode = READ_ONCE(sqe->len);
4898 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4899 mkd->filename = getname(fname);
4900 if (IS_ERR(mkd->filename))
4901 return PTR_ERR(mkd->filename);
4903 req->flags |= REQ_F_NEED_CLEANUP;
4907 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4909 struct io_mkdir *mkd = &req->mkdir;
4912 if (issue_flags & IO_URING_F_NONBLOCK)
4915 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4917 req->flags &= ~REQ_F_NEED_CLEANUP;
4918 io_req_complete(req, ret);
4922 static int io_symlinkat_prep(struct io_kiocb *req,
4923 const struct io_uring_sqe *sqe)
4925 struct io_symlink *sl = &req->symlink;
4926 const char __user *oldpath, *newpath;
4928 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4930 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4933 sl->new_dfd = READ_ONCE(sqe->fd);
4934 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4935 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4937 sl->oldpath = getname(oldpath);
4938 if (IS_ERR(sl->oldpath))
4939 return PTR_ERR(sl->oldpath);
4941 sl->newpath = getname(newpath);
4942 if (IS_ERR(sl->newpath)) {
4943 putname(sl->oldpath);
4944 return PTR_ERR(sl->newpath);
4947 req->flags |= REQ_F_NEED_CLEANUP;
4951 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4953 struct io_symlink *sl = &req->symlink;
4956 if (issue_flags & IO_URING_F_NONBLOCK)
4959 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4961 req->flags &= ~REQ_F_NEED_CLEANUP;
4962 io_req_complete(req, ret);
4966 static int io_linkat_prep(struct io_kiocb *req,
4967 const struct io_uring_sqe *sqe)
4969 struct io_hardlink *lnk = &req->hardlink;
4970 const char __user *oldf, *newf;
4972 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4974 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4977 lnk->old_dfd = READ_ONCE(sqe->fd);
4978 lnk->new_dfd = READ_ONCE(sqe->len);
4979 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4980 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4981 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4983 lnk->oldpath = getname(oldf);
4984 if (IS_ERR(lnk->oldpath))
4985 return PTR_ERR(lnk->oldpath);
4987 lnk->newpath = getname(newf);
4988 if (IS_ERR(lnk->newpath)) {
4989 putname(lnk->oldpath);
4990 return PTR_ERR(lnk->newpath);
4993 req->flags |= REQ_F_NEED_CLEANUP;
4997 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4999 struct io_hardlink *lnk = &req->hardlink;
5002 if (issue_flags & IO_URING_F_NONBLOCK)
5005 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
5006 lnk->newpath, lnk->flags);
5008 req->flags &= ~REQ_F_NEED_CLEANUP;
5009 io_req_complete(req, ret);
5013 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
5015 req->uring_cmd.task_work_cb(&req->uring_cmd);
5018 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
5019 void (*task_work_cb)(struct io_uring_cmd *))
5021 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5023 req->uring_cmd.task_work_cb = task_work_cb;
5024 req->io_task_work.func = io_uring_cmd_work;
5025 io_req_task_work_add(req);
5027 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
5029 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
5030 u64 extra1, u64 extra2)
5032 req->extra1 = extra1;
5033 req->extra2 = extra2;
5034 req->flags |= REQ_F_CQE32_INIT;
5038 * Called by consumers of io_uring_cmd, if they originally returned
5039 * -EIOCBQUEUED upon receiving the command.
5041 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
5043 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5048 if (req->ctx->flags & IORING_SETUP_CQE32)
5049 io_req_set_cqe32_extra(req, res2, 0);
5050 io_req_complete(req, ret);
5052 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
5054 static int io_uring_cmd_prep_async(struct io_kiocb *req)
5058 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
5060 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
5064 static int io_uring_cmd_prep(struct io_kiocb *req,
5065 const struct io_uring_sqe *sqe)
5067 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5069 if (sqe->rw_flags || sqe->__pad1)
5071 ioucmd->cmd = sqe->cmd;
5072 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
5076 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
5078 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5079 struct io_ring_ctx *ctx = req->ctx;
5080 struct file *file = req->file;
5083 if (!req->file->f_op->uring_cmd)
5086 if (ctx->flags & IORING_SETUP_SQE128)
5087 issue_flags |= IO_URING_F_SQE128;
5088 if (ctx->flags & IORING_SETUP_CQE32)
5089 issue_flags |= IO_URING_F_CQE32;
5090 if (ctx->flags & IORING_SETUP_IOPOLL)
5091 issue_flags |= IO_URING_F_IOPOLL;
5093 if (req_has_async_data(req))
5094 ioucmd->cmd = req->async_data;
5096 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
5097 if (ret == -EAGAIN) {
5098 if (!req_has_async_data(req)) {
5099 if (io_alloc_async_data(req))
5101 io_uring_cmd_prep_async(req);
5106 if (ret != -EIOCBQUEUED)
5107 io_uring_cmd_done(ioucmd, ret, 0);
5111 static int __io_splice_prep(struct io_kiocb *req,
5112 const struct io_uring_sqe *sqe)
5114 struct io_splice *sp = &req->splice;
5115 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
5117 sp->len = READ_ONCE(sqe->len);
5118 sp->flags = READ_ONCE(sqe->splice_flags);
5119 if (unlikely(sp->flags & ~valid_flags))
5121 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
5125 static int io_tee_prep(struct io_kiocb *req,
5126 const struct io_uring_sqe *sqe)
5128 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
5130 return __io_splice_prep(req, sqe);
5133 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
5135 struct io_splice *sp = &req->splice;
5136 struct file *out = sp->file_out;
5137 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5141 if (issue_flags & IO_URING_F_NONBLOCK)
5144 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5145 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5147 in = io_file_get_normal(req, sp->splice_fd_in);
5154 ret = do_tee(in, out, sp->len, flags);
5156 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5161 __io_req_complete(req, 0, ret, 0);
5165 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5167 struct io_splice *sp = &req->splice;
5169 sp->off_in = READ_ONCE(sqe->splice_off_in);
5170 sp->off_out = READ_ONCE(sqe->off);
5171 return __io_splice_prep(req, sqe);
5174 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5176 struct io_splice *sp = &req->splice;
5177 struct file *out = sp->file_out;
5178 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5179 loff_t *poff_in, *poff_out;
5183 if (issue_flags & IO_URING_F_NONBLOCK)
5186 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5187 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5189 in = io_file_get_normal(req, sp->splice_fd_in);
5195 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5196 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5199 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5201 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5206 __io_req_complete(req, 0, ret, 0);
5210 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5216 * IORING_OP_NOP just posts a completion event, nothing else.
5218 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5220 __io_req_complete(req, issue_flags, 0, 0);
5224 static int io_msg_ring_prep(struct io_kiocb *req,
5225 const struct io_uring_sqe *sqe)
5227 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5228 sqe->buf_index || sqe->personality))
5231 req->msg.user_data = READ_ONCE(sqe->off);
5232 req->msg.len = READ_ONCE(sqe->len);
5236 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5238 struct io_ring_ctx *target_ctx;
5239 struct io_msg *msg = &req->msg;
5244 if (req->file->f_op != &io_uring_fops)
5248 target_ctx = req->file->private_data;
5250 spin_lock(&target_ctx->completion_lock);
5251 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5252 io_commit_cqring(target_ctx);
5253 spin_unlock(&target_ctx->completion_lock);
5256 io_cqring_ev_posted(target_ctx);
5263 __io_req_complete(req, issue_flags, ret, 0);
5264 /* put file to avoid an attempt to IOPOLL the req */
5265 io_put_file(req->file);
5270 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5272 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5275 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5276 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5279 req->sync.off = READ_ONCE(sqe->off);
5280 req->sync.len = READ_ONCE(sqe->len);
5284 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5286 loff_t end = req->sync.off + req->sync.len;
5289 /* fsync always requires a blocking context */
5290 if (issue_flags & IO_URING_F_NONBLOCK)
5293 ret = vfs_fsync_range(req->file, req->sync.off,
5294 end > 0 ? end : LLONG_MAX,
5295 req->sync.flags & IORING_FSYNC_DATASYNC);
5296 io_req_complete(req, ret);
5300 static int io_fallocate_prep(struct io_kiocb *req,
5301 const struct io_uring_sqe *sqe)
5303 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5306 req->sync.off = READ_ONCE(sqe->off);
5307 req->sync.len = READ_ONCE(sqe->addr);
5308 req->sync.mode = READ_ONCE(sqe->len);
5312 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5316 /* fallocate always requiring blocking context */
5317 if (issue_flags & IO_URING_F_NONBLOCK)
5319 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5322 fsnotify_modify(req->file);
5323 io_req_complete(req, ret);
5327 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5329 const char __user *fname;
5332 if (unlikely(sqe->buf_index))
5334 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5337 /* open.how should be already initialised */
5338 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5339 req->open.how.flags |= O_LARGEFILE;
5341 req->open.dfd = READ_ONCE(sqe->fd);
5342 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5343 req->open.filename = getname(fname);
5344 if (IS_ERR(req->open.filename)) {
5345 ret = PTR_ERR(req->open.filename);
5346 req->open.filename = NULL;
5350 req->open.file_slot = READ_ONCE(sqe->file_index);
5351 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5354 req->open.nofile = rlimit(RLIMIT_NOFILE);
5355 req->flags |= REQ_F_NEED_CLEANUP;
5359 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5361 u64 mode = READ_ONCE(sqe->len);
5362 u64 flags = READ_ONCE(sqe->open_flags);
5364 req->open.how = build_open_how(flags, mode);
5365 return __io_openat_prep(req, sqe);
5368 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5370 struct open_how __user *how;
5374 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5375 len = READ_ONCE(sqe->len);
5376 if (len < OPEN_HOW_SIZE_VER0)
5379 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5384 return __io_openat_prep(req, sqe);
5387 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5389 struct io_file_table *table = &ctx->file_table;
5390 unsigned long nr = ctx->nr_user_files;
5394 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5398 if (!table->alloc_hint)
5401 nr = table->alloc_hint;
5402 table->alloc_hint = 0;
5409 * Note when io_fixed_fd_install() returns error value, it will ensure
5410 * fput() is called correspondingly.
5412 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5413 struct file *file, unsigned int file_slot)
5415 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5416 struct io_ring_ctx *ctx = req->ctx;
5419 io_ring_submit_lock(ctx, issue_flags);
5422 ret = io_file_bitmap_get(ctx);
5423 if (unlikely(ret < 0))
5430 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5431 if (!ret && alloc_slot)
5434 io_ring_submit_unlock(ctx, issue_flags);
5435 if (unlikely(ret < 0))
5440 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5442 struct open_flags op;
5444 bool resolve_nonblock, nonblock_set;
5445 bool fixed = !!req->open.file_slot;
5448 ret = build_open_flags(&req->open.how, &op);
5451 nonblock_set = op.open_flag & O_NONBLOCK;
5452 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5453 if (issue_flags & IO_URING_F_NONBLOCK) {
5455 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5456 * it'll always -EAGAIN
5458 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5460 op.lookup_flags |= LOOKUP_CACHED;
5461 op.open_flag |= O_NONBLOCK;
5465 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5470 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5473 * We could hang on to this 'fd' on retrying, but seems like
5474 * marginal gain for something that is now known to be a slower
5475 * path. So just put it, and we'll get a new one when we retry.
5480 ret = PTR_ERR(file);
5481 /* only retry if RESOLVE_CACHED wasn't already set by application */
5482 if (ret == -EAGAIN &&
5483 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5488 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5489 file->f_flags &= ~O_NONBLOCK;
5490 fsnotify_open(file);
5493 fd_install(ret, file);
5495 ret = io_fixed_fd_install(req, issue_flags, file,
5496 req->open.file_slot);
5498 putname(req->open.filename);
5499 req->flags &= ~REQ_F_NEED_CLEANUP;
5502 __io_req_complete(req, issue_flags, ret, 0);
5506 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5508 return io_openat2(req, issue_flags);
5511 static int io_remove_buffers_prep(struct io_kiocb *req,
5512 const struct io_uring_sqe *sqe)
5514 struct io_provide_buf *p = &req->pbuf;
5517 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5521 tmp = READ_ONCE(sqe->fd);
5522 if (!tmp || tmp > USHRT_MAX)
5525 memset(p, 0, sizeof(*p));
5527 p->bgid = READ_ONCE(sqe->buf_group);
5531 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5532 struct io_buffer_list *bl, unsigned nbufs)
5536 /* shouldn't happen */
5540 if (bl->buf_nr_pages) {
5543 i = bl->buf_ring->tail - bl->head;
5544 for (j = 0; j < bl->buf_nr_pages; j++)
5545 unpin_user_page(bl->buf_pages[j]);
5546 kvfree(bl->buf_pages);
5547 bl->buf_pages = NULL;
5548 bl->buf_nr_pages = 0;
5549 /* make sure it's seen as empty */
5550 INIT_LIST_HEAD(&bl->buf_list);
5554 /* the head kbuf is the list itself */
5555 while (!list_empty(&bl->buf_list)) {
5556 struct io_buffer *nxt;
5558 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5559 list_del(&nxt->list);
5569 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5571 struct io_provide_buf *p = &req->pbuf;
5572 struct io_ring_ctx *ctx = req->ctx;
5573 struct io_buffer_list *bl;
5576 io_ring_submit_lock(ctx, issue_flags);
5579 bl = io_buffer_get_list(ctx, p->bgid);
5582 /* can't use provide/remove buffers command on mapped buffers */
5583 if (!bl->buf_nr_pages)
5584 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5589 /* complete before unlock, IOPOLL may need the lock */
5590 __io_req_complete(req, issue_flags, ret, 0);
5591 io_ring_submit_unlock(ctx, issue_flags);
5595 static int io_provide_buffers_prep(struct io_kiocb *req,
5596 const struct io_uring_sqe *sqe)
5598 unsigned long size, tmp_check;
5599 struct io_provide_buf *p = &req->pbuf;
5602 if (sqe->rw_flags || sqe->splice_fd_in)
5605 tmp = READ_ONCE(sqe->fd);
5606 if (!tmp || tmp > USHRT_MAX)
5609 p->addr = READ_ONCE(sqe->addr);
5610 p->len = READ_ONCE(sqe->len);
5612 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5615 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5618 size = (unsigned long)p->len * p->nbufs;
5619 if (!access_ok(u64_to_user_ptr(p->addr), size))
5622 p->bgid = READ_ONCE(sqe->buf_group);
5623 tmp = READ_ONCE(sqe->off);
5624 if (tmp > USHRT_MAX)
5630 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5632 struct io_buffer *buf;
5637 * Completions that don't happen inline (eg not under uring_lock) will
5638 * add to ->io_buffers_comp. If we don't have any free buffers, check
5639 * the completion list and splice those entries first.
5641 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5642 spin_lock(&ctx->completion_lock);
5643 if (!list_empty(&ctx->io_buffers_comp)) {
5644 list_splice_init(&ctx->io_buffers_comp,
5645 &ctx->io_buffers_cache);
5646 spin_unlock(&ctx->completion_lock);
5649 spin_unlock(&ctx->completion_lock);
5653 * No free buffers and no completion entries either. Allocate a new
5654 * page worth of buffer entries and add those to our freelist.
5656 page = alloc_page(GFP_KERNEL_ACCOUNT);
5660 list_add(&page->lru, &ctx->io_buffers_pages);
5662 buf = page_address(page);
5663 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5664 while (bufs_in_page) {
5665 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5673 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5674 struct io_buffer_list *bl)
5676 struct io_buffer *buf;
5677 u64 addr = pbuf->addr;
5678 int i, bid = pbuf->bid;
5680 for (i = 0; i < pbuf->nbufs; i++) {
5681 if (list_empty(&ctx->io_buffers_cache) &&
5682 io_refill_buffer_cache(ctx))
5684 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5686 list_move_tail(&buf->list, &bl->buf_list);
5688 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5690 buf->bgid = pbuf->bgid;
5696 return i ? 0 : -ENOMEM;
5699 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5703 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5708 for (i = 0; i < BGID_ARRAY; i++) {
5709 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5710 ctx->io_bl[i].bgid = i;
5716 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5718 struct io_provide_buf *p = &req->pbuf;
5719 struct io_ring_ctx *ctx = req->ctx;
5720 struct io_buffer_list *bl;
5723 io_ring_submit_lock(ctx, issue_flags);
5725 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5726 ret = io_init_bl_list(ctx);
5731 bl = io_buffer_get_list(ctx, p->bgid);
5732 if (unlikely(!bl)) {
5733 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5738 INIT_LIST_HEAD(&bl->buf_list);
5739 ret = io_buffer_add_list(ctx, bl, p->bgid);
5745 /* can't add buffers via this command for a mapped buffer ring */
5746 if (bl->buf_nr_pages) {
5751 ret = io_add_buffers(ctx, p, bl);
5755 /* complete before unlock, IOPOLL may need the lock */
5756 __io_req_complete(req, issue_flags, ret, 0);
5757 io_ring_submit_unlock(ctx, issue_flags);
5761 static int io_epoll_ctl_prep(struct io_kiocb *req,
5762 const struct io_uring_sqe *sqe)
5764 #if defined(CONFIG_EPOLL)
5765 if (sqe->buf_index || sqe->splice_fd_in)
5768 req->epoll.epfd = READ_ONCE(sqe->fd);
5769 req->epoll.op = READ_ONCE(sqe->len);
5770 req->epoll.fd = READ_ONCE(sqe->off);
5772 if (ep_op_has_event(req->epoll.op)) {
5773 struct epoll_event __user *ev;
5775 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5776 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5786 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5788 #if defined(CONFIG_EPOLL)
5789 struct io_epoll *ie = &req->epoll;
5791 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5793 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5794 if (force_nonblock && ret == -EAGAIN)
5799 __io_req_complete(req, issue_flags, ret, 0);
5806 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5808 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5809 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5812 req->madvise.addr = READ_ONCE(sqe->addr);
5813 req->madvise.len = READ_ONCE(sqe->len);
5814 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5821 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5823 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5824 struct io_madvise *ma = &req->madvise;
5827 if (issue_flags & IO_URING_F_NONBLOCK)
5830 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5831 io_req_complete(req, ret);
5838 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5840 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5843 req->fadvise.offset = READ_ONCE(sqe->off);
5844 req->fadvise.len = READ_ONCE(sqe->len);
5845 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5849 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5851 struct io_fadvise *fa = &req->fadvise;
5854 if (issue_flags & IO_URING_F_NONBLOCK) {
5855 switch (fa->advice) {
5856 case POSIX_FADV_NORMAL:
5857 case POSIX_FADV_RANDOM:
5858 case POSIX_FADV_SEQUENTIAL:
5865 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5868 __io_req_complete(req, issue_flags, ret, 0);
5872 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5874 const char __user *path;
5876 if (sqe->buf_index || sqe->splice_fd_in)
5878 if (req->flags & REQ_F_FIXED_FILE)
5881 req->statx.dfd = READ_ONCE(sqe->fd);
5882 req->statx.mask = READ_ONCE(sqe->len);
5883 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5884 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5885 req->statx.flags = READ_ONCE(sqe->statx_flags);
5887 req->statx.filename = getname_flags(path,
5888 getname_statx_lookup_flags(req->statx.flags),
5891 if (IS_ERR(req->statx.filename)) {
5892 int ret = PTR_ERR(req->statx.filename);
5894 req->statx.filename = NULL;
5898 req->flags |= REQ_F_NEED_CLEANUP;
5902 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5904 struct io_statx *ctx = &req->statx;
5907 if (issue_flags & IO_URING_F_NONBLOCK)
5910 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5912 io_req_complete(req, ret);
5916 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5918 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5920 if (req->flags & REQ_F_FIXED_FILE)
5923 req->close.fd = READ_ONCE(sqe->fd);
5924 req->close.file_slot = READ_ONCE(sqe->file_index);
5925 if (req->close.file_slot && req->close.fd)
5931 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5933 struct files_struct *files = current->files;
5934 struct io_close *close = &req->close;
5935 struct fdtable *fdt;
5939 if (req->close.file_slot) {
5940 ret = io_close_fixed(req, issue_flags);
5944 spin_lock(&files->file_lock);
5945 fdt = files_fdtable(files);
5946 if (close->fd >= fdt->max_fds) {
5947 spin_unlock(&files->file_lock);
5950 file = rcu_dereference_protected(fdt->fd[close->fd],
5951 lockdep_is_held(&files->file_lock));
5952 if (!file || file->f_op == &io_uring_fops) {
5953 spin_unlock(&files->file_lock);
5957 /* if the file has a flush method, be safe and punt to async */
5958 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5959 spin_unlock(&files->file_lock);
5963 file = __close_fd_get_file(close->fd);
5964 spin_unlock(&files->file_lock);
5968 /* No ->flush() or already async, safely close from here */
5969 ret = filp_close(file, current->files);
5973 __io_req_complete(req, issue_flags, ret, 0);
5977 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5979 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5982 req->sync.off = READ_ONCE(sqe->off);
5983 req->sync.len = READ_ONCE(sqe->len);
5984 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5988 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5992 /* sync_file_range always requires a blocking context */
5993 if (issue_flags & IO_URING_F_NONBLOCK)
5996 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5998 io_req_complete(req, ret);
6002 #if defined(CONFIG_NET)
6003 static int io_shutdown_prep(struct io_kiocb *req,
6004 const struct io_uring_sqe *sqe)
6006 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
6007 sqe->buf_index || sqe->splice_fd_in))
6010 req->shutdown.how = READ_ONCE(sqe->len);
6014 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
6016 struct socket *sock;
6019 if (issue_flags & IO_URING_F_NONBLOCK)
6022 sock = sock_from_file(req->file);
6023 if (unlikely(!sock))
6026 ret = __sys_shutdown_sock(sock, req->shutdown.how);
6027 io_req_complete(req, ret);
6031 static bool io_net_retry(struct socket *sock, int flags)
6033 if (!(flags & MSG_WAITALL))
6035 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
6038 static int io_setup_async_msg(struct io_kiocb *req,
6039 struct io_async_msghdr *kmsg)
6041 struct io_async_msghdr *async_msg = req->async_data;
6045 if (io_alloc_async_data(req)) {
6046 kfree(kmsg->free_iov);
6049 async_msg = req->async_data;
6050 req->flags |= REQ_F_NEED_CLEANUP;
6051 memcpy(async_msg, kmsg, sizeof(*kmsg));
6052 async_msg->msg.msg_name = &async_msg->addr;
6053 /* if were using fast_iov, set it to the new one */
6054 if (!async_msg->free_iov)
6055 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
6060 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
6061 struct io_async_msghdr *iomsg)
6063 iomsg->msg.msg_name = &iomsg->addr;
6064 iomsg->free_iov = iomsg->fast_iov;
6065 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
6066 req->sr_msg.msg_flags, &iomsg->free_iov);
6069 static int io_sendmsg_prep_async(struct io_kiocb *req)
6073 ret = io_sendmsg_copy_hdr(req, req->async_data);
6075 req->flags |= REQ_F_NEED_CLEANUP;
6079 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6081 struct io_sr_msg *sr = &req->sr_msg;
6083 if (unlikely(sqe->file_index || sqe->addr2))
6086 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6087 sr->len = READ_ONCE(sqe->len);
6088 sr->flags = READ_ONCE(sqe->ioprio);
6089 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6091 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6092 if (sr->msg_flags & MSG_DONTWAIT)
6093 req->flags |= REQ_F_NOWAIT;
6095 #ifdef CONFIG_COMPAT
6096 if (req->ctx->compat)
6097 sr->msg_flags |= MSG_CMSG_COMPAT;
6103 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
6105 struct io_async_msghdr iomsg, *kmsg;
6106 struct io_sr_msg *sr = &req->sr_msg;
6107 struct socket *sock;
6112 sock = sock_from_file(req->file);
6113 if (unlikely(!sock))
6116 if (req_has_async_data(req)) {
6117 kmsg = req->async_data;
6119 ret = io_sendmsg_copy_hdr(req, &iomsg);
6125 if (!(req->flags & REQ_F_POLLED) &&
6126 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6127 return io_setup_async_msg(req, kmsg);
6129 flags = sr->msg_flags;
6130 if (issue_flags & IO_URING_F_NONBLOCK)
6131 flags |= MSG_DONTWAIT;
6132 if (flags & MSG_WAITALL)
6133 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6135 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
6137 if (ret < min_ret) {
6138 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6139 return io_setup_async_msg(req, kmsg);
6140 if (ret == -ERESTARTSYS)
6142 if (ret > 0 && io_net_retry(sock, flags)) {
6144 req->flags |= REQ_F_PARTIAL_IO;
6145 return io_setup_async_msg(req, kmsg);
6149 /* fast path, check for non-NULL to avoid function call */
6151 kfree(kmsg->free_iov);
6152 req->flags &= ~REQ_F_NEED_CLEANUP;
6155 else if (sr->done_io)
6157 __io_req_complete(req, issue_flags, ret, 0);
6161 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6163 struct io_sr_msg *sr = &req->sr_msg;
6166 struct socket *sock;
6171 if (!(req->flags & REQ_F_POLLED) &&
6172 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6175 sock = sock_from_file(req->file);
6176 if (unlikely(!sock))
6179 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6183 msg.msg_name = NULL;
6184 msg.msg_control = NULL;
6185 msg.msg_controllen = 0;
6186 msg.msg_namelen = 0;
6188 flags = sr->msg_flags;
6189 if (issue_flags & IO_URING_F_NONBLOCK)
6190 flags |= MSG_DONTWAIT;
6191 if (flags & MSG_WAITALL)
6192 min_ret = iov_iter_count(&msg.msg_iter);
6194 msg.msg_flags = flags;
6195 ret = sock_sendmsg(sock, &msg);
6196 if (ret < min_ret) {
6197 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6199 if (ret == -ERESTARTSYS)
6201 if (ret > 0 && io_net_retry(sock, flags)) {
6205 req->flags |= REQ_F_PARTIAL_IO;
6212 else if (sr->done_io)
6214 __io_req_complete(req, issue_flags, ret, 0);
6218 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6219 struct io_async_msghdr *iomsg)
6221 struct io_sr_msg *sr = &req->sr_msg;
6222 struct iovec __user *uiov;
6226 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6227 &iomsg->uaddr, &uiov, &iov_len);
6231 if (req->flags & REQ_F_BUFFER_SELECT) {
6234 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6236 sr->len = iomsg->fast_iov[0].iov_len;
6237 iomsg->free_iov = NULL;
6239 iomsg->free_iov = iomsg->fast_iov;
6240 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6241 &iomsg->free_iov, &iomsg->msg.msg_iter,
6250 #ifdef CONFIG_COMPAT
6251 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6252 struct io_async_msghdr *iomsg)
6254 struct io_sr_msg *sr = &req->sr_msg;
6255 struct compat_iovec __user *uiov;
6260 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6265 uiov = compat_ptr(ptr);
6266 if (req->flags & REQ_F_BUFFER_SELECT) {
6267 compat_ssize_t clen;
6271 if (!access_ok(uiov, sizeof(*uiov)))
6273 if (__get_user(clen, &uiov->iov_len))
6278 iomsg->free_iov = NULL;
6280 iomsg->free_iov = iomsg->fast_iov;
6281 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6282 UIO_FASTIOV, &iomsg->free_iov,
6283 &iomsg->msg.msg_iter, true);
6292 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6293 struct io_async_msghdr *iomsg)
6295 iomsg->msg.msg_name = &iomsg->addr;
6297 #ifdef CONFIG_COMPAT
6298 if (req->ctx->compat)
6299 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6302 return __io_recvmsg_copy_hdr(req, iomsg);
6305 static int io_recvmsg_prep_async(struct io_kiocb *req)
6309 ret = io_recvmsg_copy_hdr(req, req->async_data);
6311 req->flags |= REQ_F_NEED_CLEANUP;
6315 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6317 struct io_sr_msg *sr = &req->sr_msg;
6319 if (unlikely(sqe->file_index || sqe->addr2))
6322 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6323 sr->len = READ_ONCE(sqe->len);
6324 sr->flags = READ_ONCE(sqe->ioprio);
6325 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6327 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6328 if (sr->msg_flags & MSG_DONTWAIT)
6329 req->flags |= REQ_F_NOWAIT;
6331 #ifdef CONFIG_COMPAT
6332 if (req->ctx->compat)
6333 sr->msg_flags |= MSG_CMSG_COMPAT;
6339 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6341 struct io_async_msghdr iomsg, *kmsg;
6342 struct io_sr_msg *sr = &req->sr_msg;
6343 struct socket *sock;
6344 unsigned int cflags;
6346 int ret, min_ret = 0;
6347 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6349 sock = sock_from_file(req->file);
6350 if (unlikely(!sock))
6353 if (req_has_async_data(req)) {
6354 kmsg = req->async_data;
6356 ret = io_recvmsg_copy_hdr(req, &iomsg);
6362 if (!(req->flags & REQ_F_POLLED) &&
6363 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6364 return io_setup_async_msg(req, kmsg);
6366 if (io_do_buffer_select(req)) {
6369 buf = io_buffer_select(req, &sr->len, issue_flags);
6372 kmsg->fast_iov[0].iov_base = buf;
6373 kmsg->fast_iov[0].iov_len = sr->len;
6374 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6378 flags = sr->msg_flags;
6380 flags |= MSG_DONTWAIT;
6381 if (flags & MSG_WAITALL)
6382 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6384 kmsg->msg.msg_get_inq = 1;
6385 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6386 if (ret < min_ret) {
6387 if (ret == -EAGAIN && force_nonblock)
6388 return io_setup_async_msg(req, kmsg);
6389 if (ret == -ERESTARTSYS)
6391 if (ret > 0 && io_net_retry(sock, flags)) {
6393 req->flags |= REQ_F_PARTIAL_IO;
6394 return io_setup_async_msg(req, kmsg);
6397 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6401 /* fast path, check for non-NULL to avoid function call */
6403 kfree(kmsg->free_iov);
6404 req->flags &= ~REQ_F_NEED_CLEANUP;
6407 else if (sr->done_io)
6409 cflags = io_put_kbuf(req, issue_flags);
6410 if (kmsg->msg.msg_inq)
6411 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6412 __io_req_complete(req, issue_flags, ret, cflags);
6416 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6418 struct io_sr_msg *sr = &req->sr_msg;
6420 struct socket *sock;
6422 unsigned int cflags;
6424 int ret, min_ret = 0;
6425 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6427 if (!(req->flags & REQ_F_POLLED) &&
6428 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6431 sock = sock_from_file(req->file);
6432 if (unlikely(!sock))
6435 if (io_do_buffer_select(req)) {
6438 buf = io_buffer_select(req, &sr->len, issue_flags);
6444 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6448 msg.msg_name = NULL;
6449 msg.msg_namelen = 0;
6450 msg.msg_control = NULL;
6451 msg.msg_get_inq = 1;
6453 msg.msg_controllen = 0;
6454 msg.msg_iocb = NULL;
6456 flags = sr->msg_flags;
6458 flags |= MSG_DONTWAIT;
6459 if (flags & MSG_WAITALL)
6460 min_ret = iov_iter_count(&msg.msg_iter);
6462 ret = sock_recvmsg(sock, &msg, flags);
6463 if (ret < min_ret) {
6464 if (ret == -EAGAIN && force_nonblock)
6466 if (ret == -ERESTARTSYS)
6468 if (ret > 0 && io_net_retry(sock, flags)) {
6472 req->flags |= REQ_F_PARTIAL_IO;
6476 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6483 else if (sr->done_io)
6485 cflags = io_put_kbuf(req, issue_flags);
6487 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6488 __io_req_complete(req, issue_flags, ret, cflags);
6492 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6494 struct io_accept *accept = &req->accept;
6497 if (sqe->len || sqe->buf_index)
6500 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6501 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6502 accept->flags = READ_ONCE(sqe->accept_flags);
6503 accept->nofile = rlimit(RLIMIT_NOFILE);
6504 flags = READ_ONCE(sqe->ioprio);
6505 if (flags & ~IORING_ACCEPT_MULTISHOT)
6508 accept->file_slot = READ_ONCE(sqe->file_index);
6509 if (accept->file_slot) {
6510 if (accept->flags & SOCK_CLOEXEC)
6512 if (flags & IORING_ACCEPT_MULTISHOT &&
6513 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6516 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6518 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6519 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6520 if (flags & IORING_ACCEPT_MULTISHOT)
6521 req->flags |= REQ_F_APOLL_MULTISHOT;
6525 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6527 struct io_ring_ctx *ctx = req->ctx;
6528 struct io_accept *accept = &req->accept;
6529 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6530 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6531 bool fixed = !!accept->file_slot;
6537 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6538 if (unlikely(fd < 0))
6541 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6546 ret = PTR_ERR(file);
6547 if (ret == -EAGAIN && force_nonblock) {
6549 * if it's multishot and polled, we don't need to
6550 * return EAGAIN to arm the poll infra since it
6551 * has already been done
6553 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6554 IO_APOLL_MULTI_POLLED)
6558 if (ret == -ERESTARTSYS)
6561 } else if (!fixed) {
6562 fd_install(fd, file);
6565 ret = io_fixed_fd_install(req, issue_flags, file,
6569 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6570 __io_req_complete(req, issue_flags, ret, 0);
6576 spin_lock(&ctx->completion_lock);
6577 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6579 io_commit_cqring(ctx);
6580 spin_unlock(&ctx->completion_lock);
6582 io_cqring_ev_posted(ctx);
6591 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6593 struct io_socket *sock = &req->sock;
6595 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6598 sock->domain = READ_ONCE(sqe->fd);
6599 sock->type = READ_ONCE(sqe->off);
6600 sock->protocol = READ_ONCE(sqe->len);
6601 sock->file_slot = READ_ONCE(sqe->file_index);
6602 sock->nofile = rlimit(RLIMIT_NOFILE);
6604 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6605 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6607 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6612 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6614 struct io_socket *sock = &req->sock;
6615 bool fixed = !!sock->file_slot;
6620 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6621 if (unlikely(fd < 0))
6624 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6628 ret = PTR_ERR(file);
6629 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6631 if (ret == -ERESTARTSYS)
6634 } else if (!fixed) {
6635 fd_install(fd, file);
6638 ret = io_fixed_fd_install(req, issue_flags, file,
6641 __io_req_complete(req, issue_flags, ret, 0);
6645 static int io_connect_prep_async(struct io_kiocb *req)
6647 struct io_async_connect *io = req->async_data;
6648 struct io_connect *conn = &req->connect;
6650 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6653 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6655 struct io_connect *conn = &req->connect;
6657 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6660 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6661 conn->addr_len = READ_ONCE(sqe->addr2);
6665 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6667 struct io_async_connect __io, *io;
6668 unsigned file_flags;
6670 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6672 if (req_has_async_data(req)) {
6673 io = req->async_data;
6675 ret = move_addr_to_kernel(req->connect.addr,
6676 req->connect.addr_len,
6683 file_flags = force_nonblock ? O_NONBLOCK : 0;
6685 ret = __sys_connect_file(req->file, &io->address,
6686 req->connect.addr_len, file_flags);
6687 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6688 if (req_has_async_data(req))
6690 if (io_alloc_async_data(req)) {
6694 memcpy(req->async_data, &__io, sizeof(__io));
6697 if (ret == -ERESTARTSYS)
6702 __io_req_complete(req, issue_flags, ret, 0);
6705 #else /* !CONFIG_NET */
6706 #define IO_NETOP_FN(op) \
6707 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6709 return -EOPNOTSUPP; \
6712 #define IO_NETOP_PREP(op) \
6714 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6716 return -EOPNOTSUPP; \
6719 #define IO_NETOP_PREP_ASYNC(op) \
6721 static int io_##op##_prep_async(struct io_kiocb *req) \
6723 return -EOPNOTSUPP; \
6726 IO_NETOP_PREP_ASYNC(sendmsg);
6727 IO_NETOP_PREP_ASYNC(recvmsg);
6728 IO_NETOP_PREP_ASYNC(connect);
6729 IO_NETOP_PREP(accept);
6730 IO_NETOP_PREP(socket);
6731 IO_NETOP_PREP(shutdown);
6734 #endif /* CONFIG_NET */
6736 struct io_poll_table {
6737 struct poll_table_struct pt;
6738 struct io_kiocb *req;
6743 #define IO_POLL_CANCEL_FLAG BIT(31)
6744 #define IO_POLL_REF_MASK GENMASK(30, 0)
6747 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6748 * bump it and acquire ownership. It's disallowed to modify requests while not
6749 * owning it, that prevents from races for enqueueing task_work's and b/w
6750 * arming poll and wakeups.
6752 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6754 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6757 static void io_poll_mark_cancelled(struct io_kiocb *req)
6759 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6762 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6764 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6765 if (req->opcode == IORING_OP_POLL_ADD)
6766 return req->async_data;
6767 return req->apoll->double_poll;
6770 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6772 if (req->opcode == IORING_OP_POLL_ADD)
6774 return &req->apoll->poll;
6777 static void io_poll_req_insert(struct io_kiocb *req)
6779 struct io_ring_ctx *ctx = req->ctx;
6780 struct hlist_head *list;
6782 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6783 hlist_add_head(&req->hash_node, list);
6786 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6787 wait_queue_func_t wake_func)
6790 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6791 /* mask in events that we always want/need */
6792 poll->events = events | IO_POLL_UNMASK;
6793 INIT_LIST_HEAD(&poll->wait.entry);
6794 init_waitqueue_func_entry(&poll->wait, wake_func);
6797 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6799 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6802 spin_lock_irq(&head->lock);
6803 list_del_init(&poll->wait.entry);
6805 spin_unlock_irq(&head->lock);
6809 static void io_poll_remove_entries(struct io_kiocb *req)
6812 * Nothing to do if neither of those flags are set. Avoid dipping
6813 * into the poll/apoll/double cachelines if we can.
6815 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6819 * While we hold the waitqueue lock and the waitqueue is nonempty,
6820 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6821 * lock in the first place can race with the waitqueue being freed.
6823 * We solve this as eventpoll does: by taking advantage of the fact that
6824 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6825 * we enter rcu_read_lock() and see that the pointer to the queue is
6826 * non-NULL, we can then lock it without the memory being freed out from
6829 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6830 * case the caller deletes the entry from the queue, leaving it empty.
6831 * In that case, only RCU prevents the queue memory from being freed.
6834 if (req->flags & REQ_F_SINGLE_POLL)
6835 io_poll_remove_entry(io_poll_get_single(req));
6836 if (req->flags & REQ_F_DOUBLE_POLL)
6837 io_poll_remove_entry(io_poll_get_double(req));
6841 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6843 * All poll tw should go through this. Checks for poll events, manages
6844 * references, does rewait, etc.
6846 * Returns a negative error on failure. >0 when no action require, which is
6847 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6848 * the request, then the mask is stored in req->cqe.res.
6850 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6852 struct io_ring_ctx *ctx = req->ctx;
6855 /* req->task == current here, checking PF_EXITING is safe */
6856 if (unlikely(req->task->flags & PF_EXITING))
6860 v = atomic_read(&req->poll_refs);
6862 /* tw handler should be the owner, and so have some references */
6863 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6865 if (v & IO_POLL_CANCEL_FLAG)
6868 if (!req->cqe.res) {
6869 struct poll_table_struct pt = { ._key = req->apoll_events };
6870 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6873 if ((unlikely(!req->cqe.res)))
6875 if (req->apoll_events & EPOLLONESHOT)
6878 /* multishot, just fill a CQE and proceed */
6879 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6880 __poll_t mask = mangle_poll(req->cqe.res &
6884 spin_lock(&ctx->completion_lock);
6885 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6886 mask, IORING_CQE_F_MORE);
6887 io_commit_cqring(ctx);
6888 spin_unlock(&ctx->completion_lock);
6890 io_cqring_ev_posted(ctx);
6896 io_tw_lock(req->ctx, locked);
6897 if (unlikely(req->task->flags & PF_EXITING))
6899 ret = io_issue_sqe(req,
6900 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6905 * Release all references, retry if someone tried to restart
6906 * task_work while we were executing it.
6908 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6913 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6915 struct io_ring_ctx *ctx = req->ctx;
6918 ret = io_poll_check_events(req, locked);
6923 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6929 io_poll_remove_entries(req);
6930 spin_lock(&ctx->completion_lock);
6931 hash_del(&req->hash_node);
6932 __io_req_complete_post(req, req->cqe.res, 0);
6933 io_commit_cqring(ctx);
6934 spin_unlock(&ctx->completion_lock);
6935 io_cqring_ev_posted(ctx);
6938 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6940 struct io_ring_ctx *ctx = req->ctx;
6943 ret = io_poll_check_events(req, locked);
6947 io_poll_remove_entries(req);
6948 spin_lock(&ctx->completion_lock);
6949 hash_del(&req->hash_node);
6950 spin_unlock(&ctx->completion_lock);
6953 io_req_task_submit(req, locked);
6955 io_req_complete_failed(req, ret);
6958 static void __io_poll_execute(struct io_kiocb *req, int mask,
6959 __poll_t __maybe_unused events)
6961 req->cqe.res = mask;
6963 * This is useful for poll that is armed on behalf of another
6964 * request, and where the wakeup path could be on a different
6965 * CPU. We want to avoid pulling in req->apoll->events for that
6968 if (req->opcode == IORING_OP_POLL_ADD)
6969 req->io_task_work.func = io_poll_task_func;
6971 req->io_task_work.func = io_apoll_task_func;
6973 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6974 io_req_task_work_add(req);
6977 static inline void io_poll_execute(struct io_kiocb *req, int res,
6980 if (io_poll_get_ownership(req))
6981 __io_poll_execute(req, res, events);
6984 static void io_poll_cancel_req(struct io_kiocb *req)
6986 io_poll_mark_cancelled(req);
6987 /* kick tw, which should complete the request */
6988 io_poll_execute(req, 0, 0);
6991 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6992 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6993 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
6995 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6998 struct io_kiocb *req = wqe_to_req(wait);
6999 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
7001 __poll_t mask = key_to_poll(key);
7003 if (unlikely(mask & POLLFREE)) {
7004 io_poll_mark_cancelled(req);
7005 /* we have to kick tw in case it's not already */
7006 io_poll_execute(req, 0, poll->events);
7009 * If the waitqueue is being freed early but someone is already
7010 * holds ownership over it, we have to tear down the request as
7011 * best we can. That means immediately removing the request from
7012 * its waitqueue and preventing all further accesses to the
7013 * waitqueue via the request.
7015 list_del_init(&poll->wait.entry);
7018 * Careful: this *must* be the last step, since as soon
7019 * as req->head is NULL'ed out, the request can be
7020 * completed and freed, since aio_poll_complete_work()
7021 * will no longer need to take the waitqueue lock.
7023 smp_store_release(&poll->head, NULL);
7027 /* for instances that support it check for an event match first */
7028 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
7031 if (io_poll_get_ownership(req)) {
7032 /* optional, saves extra locking for removal in tw handler */
7033 if (mask && poll->events & EPOLLONESHOT) {
7034 list_del_init(&poll->wait.entry);
7036 if (wqe_is_double(wait))
7037 req->flags &= ~REQ_F_DOUBLE_POLL;
7039 req->flags &= ~REQ_F_SINGLE_POLL;
7041 __io_poll_execute(req, mask, poll->events);
7046 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
7047 struct wait_queue_head *head,
7048 struct io_poll_iocb **poll_ptr)
7050 struct io_kiocb *req = pt->req;
7051 unsigned long wqe_private = (unsigned long) req;
7054 * The file being polled uses multiple waitqueues for poll handling
7055 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
7058 if (unlikely(pt->nr_entries)) {
7059 struct io_poll_iocb *first = poll;
7061 /* double add on the same waitqueue head, ignore */
7062 if (first->head == head)
7064 /* already have a 2nd entry, fail a third attempt */
7066 if ((*poll_ptr)->head == head)
7068 pt->error = -EINVAL;
7072 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
7074 pt->error = -ENOMEM;
7077 /* mark as double wq entry */
7079 req->flags |= REQ_F_DOUBLE_POLL;
7080 io_init_poll_iocb(poll, first->events, first->wait.func);
7082 if (req->opcode == IORING_OP_POLL_ADD)
7083 req->flags |= REQ_F_ASYNC_DATA;
7086 req->flags |= REQ_F_SINGLE_POLL;
7089 poll->wait.private = (void *) wqe_private;
7091 if (poll->events & EPOLLEXCLUSIVE)
7092 add_wait_queue_exclusive(head, &poll->wait);
7094 add_wait_queue(head, &poll->wait);
7097 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
7098 struct poll_table_struct *p)
7100 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7102 __io_queue_proc(&pt->req->poll, pt, head,
7103 (struct io_poll_iocb **) &pt->req->async_data);
7106 static int __io_arm_poll_handler(struct io_kiocb *req,
7107 struct io_poll_iocb *poll,
7108 struct io_poll_table *ipt, __poll_t mask)
7110 struct io_ring_ctx *ctx = req->ctx;
7113 INIT_HLIST_NODE(&req->hash_node);
7114 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
7115 io_init_poll_iocb(poll, mask, io_poll_wake);
7116 poll->file = req->file;
7118 req->apoll_events = poll->events;
7120 ipt->pt._key = mask;
7123 ipt->nr_entries = 0;
7126 * Take the ownership to delay any tw execution up until we're done
7127 * with poll arming. see io_poll_get_ownership().
7129 atomic_set(&req->poll_refs, 1);
7130 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
7132 if (mask && (poll->events & EPOLLONESHOT)) {
7133 io_poll_remove_entries(req);
7134 /* no one else has access to the req, forget about the ref */
7137 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
7138 io_poll_remove_entries(req);
7140 ipt->error = -EINVAL;
7144 spin_lock(&ctx->completion_lock);
7145 io_poll_req_insert(req);
7146 spin_unlock(&ctx->completion_lock);
7149 /* can't multishot if failed, just queue the event we've got */
7150 if (unlikely(ipt->error || !ipt->nr_entries)) {
7151 poll->events |= EPOLLONESHOT;
7152 req->apoll_events |= EPOLLONESHOT;
7155 __io_poll_execute(req, mask, poll->events);
7160 * Release ownership. If someone tried to queue a tw while it was
7161 * locked, kick it off for them.
7163 v = atomic_dec_return(&req->poll_refs);
7164 if (unlikely(v & IO_POLL_REF_MASK))
7165 __io_poll_execute(req, 0, poll->events);
7169 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7170 struct poll_table_struct *p)
7172 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7173 struct async_poll *apoll = pt->req->apoll;
7175 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7184 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7186 const struct io_op_def *def = &io_op_defs[req->opcode];
7187 struct io_ring_ctx *ctx = req->ctx;
7188 struct async_poll *apoll;
7189 struct io_poll_table ipt;
7190 __poll_t mask = POLLPRI | POLLERR;
7193 if (!def->pollin && !def->pollout)
7194 return IO_APOLL_ABORTED;
7195 if (!file_can_poll(req->file))
7196 return IO_APOLL_ABORTED;
7197 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7198 return IO_APOLL_ABORTED;
7199 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7200 mask |= EPOLLONESHOT;
7203 mask |= EPOLLIN | EPOLLRDNORM;
7205 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7206 if ((req->opcode == IORING_OP_RECVMSG) &&
7207 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7210 mask |= EPOLLOUT | EPOLLWRNORM;
7212 if (def->poll_exclusive)
7213 mask |= EPOLLEXCLUSIVE;
7214 if (req->flags & REQ_F_POLLED) {
7216 kfree(apoll->double_poll);
7217 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7218 !list_empty(&ctx->apoll_cache)) {
7219 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7221 list_del_init(&apoll->poll.wait.entry);
7223 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7224 if (unlikely(!apoll))
7225 return IO_APOLL_ABORTED;
7227 apoll->double_poll = NULL;
7229 req->flags |= REQ_F_POLLED;
7230 ipt.pt._qproc = io_async_queue_proc;
7232 io_kbuf_recycle(req, issue_flags);
7234 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7235 if (ret || ipt.error)
7236 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7238 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7239 mask, apoll->poll.events);
7244 * Returns true if we found and killed one or more poll requests
7246 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7247 struct task_struct *tsk, bool cancel_all)
7249 struct hlist_node *tmp;
7250 struct io_kiocb *req;
7254 spin_lock(&ctx->completion_lock);
7255 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7256 struct hlist_head *list;
7258 list = &ctx->cancel_hash[i];
7259 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7260 if (io_match_task_safe(req, tsk, cancel_all)) {
7261 hlist_del_init(&req->hash_node);
7262 io_poll_cancel_req(req);
7267 spin_unlock(&ctx->completion_lock);
7271 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7272 struct io_cancel_data *cd)
7273 __must_hold(&ctx->completion_lock)
7275 struct hlist_head *list;
7276 struct io_kiocb *req;
7278 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7279 hlist_for_each_entry(req, list, hash_node) {
7280 if (cd->data != req->cqe.user_data)
7282 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7284 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7285 if (cd->seq == req->work.cancel_seq)
7287 req->work.cancel_seq = cd->seq;
7294 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7295 struct io_cancel_data *cd)
7296 __must_hold(&ctx->completion_lock)
7298 struct io_kiocb *req;
7301 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7302 struct hlist_head *list;
7304 list = &ctx->cancel_hash[i];
7305 hlist_for_each_entry(req, list, hash_node) {
7306 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7307 req->file != cd->file)
7309 if (cd->seq == req->work.cancel_seq)
7311 req->work.cancel_seq = cd->seq;
7318 static bool io_poll_disarm(struct io_kiocb *req)
7319 __must_hold(&ctx->completion_lock)
7321 if (!io_poll_get_ownership(req))
7323 io_poll_remove_entries(req);
7324 hash_del(&req->hash_node);
7328 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7329 __must_hold(&ctx->completion_lock)
7331 struct io_kiocb *req;
7333 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7334 req = io_poll_file_find(ctx, cd);
7336 req = io_poll_find(ctx, false, cd);
7339 io_poll_cancel_req(req);
7343 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7348 events = READ_ONCE(sqe->poll32_events);
7350 events = swahw32(events);
7352 if (!(flags & IORING_POLL_ADD_MULTI))
7353 events |= EPOLLONESHOT;
7354 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7357 static int io_poll_remove_prep(struct io_kiocb *req,
7358 const struct io_uring_sqe *sqe)
7360 struct io_poll_update *upd = &req->poll_update;
7363 if (sqe->buf_index || sqe->splice_fd_in)
7365 flags = READ_ONCE(sqe->len);
7366 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7367 IORING_POLL_ADD_MULTI))
7369 /* meaningless without update */
7370 if (flags == IORING_POLL_ADD_MULTI)
7373 upd->old_user_data = READ_ONCE(sqe->addr);
7374 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7375 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7377 upd->new_user_data = READ_ONCE(sqe->off);
7378 if (!upd->update_user_data && upd->new_user_data)
7380 if (upd->update_events)
7381 upd->events = io_poll_parse_events(sqe, flags);
7382 else if (sqe->poll32_events)
7388 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7390 struct io_poll_iocb *poll = &req->poll;
7393 if (sqe->buf_index || sqe->off || sqe->addr)
7395 flags = READ_ONCE(sqe->len);
7396 if (flags & ~IORING_POLL_ADD_MULTI)
7398 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7401 io_req_set_refcount(req);
7402 poll->events = io_poll_parse_events(sqe, flags);
7406 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7408 struct io_poll_iocb *poll = &req->poll;
7409 struct io_poll_table ipt;
7412 ipt.pt._qproc = io_poll_queue_proc;
7414 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7415 if (!ret && ipt.error)
7417 ret = ret ?: ipt.error;
7419 __io_req_complete(req, issue_flags, ret, 0);
7423 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7425 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7426 struct io_ring_ctx *ctx = req->ctx;
7427 struct io_kiocb *preq;
7431 spin_lock(&ctx->completion_lock);
7432 preq = io_poll_find(ctx, true, &cd);
7433 if (!preq || !io_poll_disarm(preq)) {
7434 spin_unlock(&ctx->completion_lock);
7435 ret = preq ? -EALREADY : -ENOENT;
7438 spin_unlock(&ctx->completion_lock);
7440 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7441 /* only mask one event flags, keep behavior flags */
7442 if (req->poll_update.update_events) {
7443 preq->poll.events &= ~0xffff;
7444 preq->poll.events |= req->poll_update.events & 0xffff;
7445 preq->poll.events |= IO_POLL_UNMASK;
7447 if (req->poll_update.update_user_data)
7448 preq->cqe.user_data = req->poll_update.new_user_data;
7450 ret2 = io_poll_add(preq, issue_flags);
7451 /* successfully updated, don't complete poll request */
7457 preq->cqe.res = -ECANCELED;
7458 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7459 io_req_task_complete(preq, &locked);
7463 /* complete update request, we're done with it */
7464 __io_req_complete(req, issue_flags, ret, 0);
7468 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7470 struct io_timeout_data *data = container_of(timer,
7471 struct io_timeout_data, timer);
7472 struct io_kiocb *req = data->req;
7473 struct io_ring_ctx *ctx = req->ctx;
7474 unsigned long flags;
7476 spin_lock_irqsave(&ctx->timeout_lock, flags);
7477 list_del_init(&req->timeout.list);
7478 atomic_set(&req->ctx->cq_timeouts,
7479 atomic_read(&req->ctx->cq_timeouts) + 1);
7480 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7482 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7485 req->cqe.res = -ETIME;
7486 req->io_task_work.func = io_req_task_complete;
7487 io_req_task_work_add(req);
7488 return HRTIMER_NORESTART;
7491 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7492 struct io_cancel_data *cd)
7493 __must_hold(&ctx->timeout_lock)
7495 struct io_timeout_data *io;
7496 struct io_kiocb *req;
7499 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7500 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7501 cd->data != req->cqe.user_data)
7503 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7504 if (cd->seq == req->work.cancel_seq)
7506 req->work.cancel_seq = cd->seq;
7512 return ERR_PTR(-ENOENT);
7514 io = req->async_data;
7515 if (hrtimer_try_to_cancel(&io->timer) == -1)
7516 return ERR_PTR(-EALREADY);
7517 list_del_init(&req->timeout.list);
7521 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7522 __must_hold(&ctx->completion_lock)
7524 struct io_kiocb *req;
7526 spin_lock_irq(&ctx->timeout_lock);
7527 req = io_timeout_extract(ctx, cd);
7528 spin_unlock_irq(&ctx->timeout_lock);
7531 return PTR_ERR(req);
7532 io_req_task_queue_fail(req, -ECANCELED);
7536 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7538 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7539 case IORING_TIMEOUT_BOOTTIME:
7540 return CLOCK_BOOTTIME;
7541 case IORING_TIMEOUT_REALTIME:
7542 return CLOCK_REALTIME;
7544 /* can't happen, vetted at prep time */
7548 return CLOCK_MONOTONIC;
7552 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7553 struct timespec64 *ts, enum hrtimer_mode mode)
7554 __must_hold(&ctx->timeout_lock)
7556 struct io_timeout_data *io;
7557 struct io_kiocb *req;
7560 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7561 found = user_data == req->cqe.user_data;
7568 io = req->async_data;
7569 if (hrtimer_try_to_cancel(&io->timer) == -1)
7571 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7572 io->timer.function = io_link_timeout_fn;
7573 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7577 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7578 struct timespec64 *ts, enum hrtimer_mode mode)
7579 __must_hold(&ctx->timeout_lock)
7581 struct io_cancel_data cd = { .data = user_data, };
7582 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7583 struct io_timeout_data *data;
7586 return PTR_ERR(req);
7588 req->timeout.off = 0; /* noseq */
7589 data = req->async_data;
7590 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7591 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7592 data->timer.function = io_timeout_fn;
7593 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7597 static int io_timeout_remove_prep(struct io_kiocb *req,
7598 const struct io_uring_sqe *sqe)
7600 struct io_timeout_rem *tr = &req->timeout_rem;
7602 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7604 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7607 tr->ltimeout = false;
7608 tr->addr = READ_ONCE(sqe->addr);
7609 tr->flags = READ_ONCE(sqe->timeout_flags);
7610 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7611 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7613 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7614 tr->ltimeout = true;
7615 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7617 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7619 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7621 } else if (tr->flags) {
7622 /* timeout removal doesn't support flags */
7629 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7631 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7636 * Remove or update an existing timeout command
7638 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7640 struct io_timeout_rem *tr = &req->timeout_rem;
7641 struct io_ring_ctx *ctx = req->ctx;
7644 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7645 struct io_cancel_data cd = { .data = tr->addr, };
7647 spin_lock(&ctx->completion_lock);
7648 ret = io_timeout_cancel(ctx, &cd);
7649 spin_unlock(&ctx->completion_lock);
7651 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7653 spin_lock_irq(&ctx->timeout_lock);
7655 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7657 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7658 spin_unlock_irq(&ctx->timeout_lock);
7663 io_req_complete_post(req, ret, 0);
7667 static int __io_timeout_prep(struct io_kiocb *req,
7668 const struct io_uring_sqe *sqe,
7669 bool is_timeout_link)
7671 struct io_timeout_data *data;
7673 u32 off = READ_ONCE(sqe->off);
7675 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7677 if (off && is_timeout_link)
7679 flags = READ_ONCE(sqe->timeout_flags);
7680 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7681 IORING_TIMEOUT_ETIME_SUCCESS))
7683 /* more than one clock specified is invalid, obviously */
7684 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7687 INIT_LIST_HEAD(&req->timeout.list);
7688 req->timeout.off = off;
7689 if (unlikely(off && !req->ctx->off_timeout_used))
7690 req->ctx->off_timeout_used = true;
7692 if (WARN_ON_ONCE(req_has_async_data(req)))
7694 if (io_alloc_async_data(req))
7697 data = req->async_data;
7699 data->flags = flags;
7701 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7704 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7707 INIT_LIST_HEAD(&req->timeout.list);
7708 data->mode = io_translate_timeout_mode(flags);
7709 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7711 if (is_timeout_link) {
7712 struct io_submit_link *link = &req->ctx->submit_state.link;
7716 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7718 req->timeout.head = link->last;
7719 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7724 static int io_timeout_prep(struct io_kiocb *req,
7725 const struct io_uring_sqe *sqe)
7727 return __io_timeout_prep(req, sqe, false);
7730 static int io_link_timeout_prep(struct io_kiocb *req,
7731 const struct io_uring_sqe *sqe)
7733 return __io_timeout_prep(req, sqe, true);
7736 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7738 struct io_ring_ctx *ctx = req->ctx;
7739 struct io_timeout_data *data = req->async_data;
7740 struct list_head *entry;
7741 u32 tail, off = req->timeout.off;
7743 spin_lock_irq(&ctx->timeout_lock);
7746 * sqe->off holds how many events that need to occur for this
7747 * timeout event to be satisfied. If it isn't set, then this is
7748 * a pure timeout request, sequence isn't used.
7750 if (io_is_timeout_noseq(req)) {
7751 entry = ctx->timeout_list.prev;
7755 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7756 req->timeout.target_seq = tail + off;
7758 /* Update the last seq here in case io_flush_timeouts() hasn't.
7759 * This is safe because ->completion_lock is held, and submissions
7760 * and completions are never mixed in the same ->completion_lock section.
7762 ctx->cq_last_tm_flush = tail;
7765 * Insertion sort, ensuring the first entry in the list is always
7766 * the one we need first.
7768 list_for_each_prev(entry, &ctx->timeout_list) {
7769 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7772 if (io_is_timeout_noseq(nxt))
7774 /* nxt.seq is behind @tail, otherwise would've been completed */
7775 if (off >= nxt->timeout.target_seq - tail)
7779 list_add(&req->timeout.list, entry);
7780 data->timer.function = io_timeout_fn;
7781 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7782 spin_unlock_irq(&ctx->timeout_lock);
7786 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7788 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7789 struct io_cancel_data *cd = data;
7791 if (req->ctx != cd->ctx)
7793 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7795 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7796 if (req->file != cd->file)
7799 if (req->cqe.user_data != cd->data)
7802 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7803 if (cd->seq == req->work.cancel_seq)
7805 req->work.cancel_seq = cd->seq;
7810 static int io_async_cancel_one(struct io_uring_task *tctx,
7811 struct io_cancel_data *cd)
7813 enum io_wq_cancel cancel_ret;
7817 if (!tctx || !tctx->io_wq)
7820 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7821 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7822 switch (cancel_ret) {
7823 case IO_WQ_CANCEL_OK:
7826 case IO_WQ_CANCEL_RUNNING:
7829 case IO_WQ_CANCEL_NOTFOUND:
7837 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7839 struct io_ring_ctx *ctx = req->ctx;
7842 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7844 ret = io_async_cancel_one(req->task->io_uring, cd);
7846 * Fall-through even for -EALREADY, as we may have poll armed
7847 * that need unarming.
7852 spin_lock(&ctx->completion_lock);
7853 ret = io_poll_cancel(ctx, cd);
7856 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7857 ret = io_timeout_cancel(ctx, cd);
7859 spin_unlock(&ctx->completion_lock);
7863 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7864 IORING_ASYNC_CANCEL_ANY)
7866 static int io_async_cancel_prep(struct io_kiocb *req,
7867 const struct io_uring_sqe *sqe)
7869 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7871 if (sqe->off || sqe->len || sqe->splice_fd_in)
7874 req->cancel.addr = READ_ONCE(sqe->addr);
7875 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7876 if (req->cancel.flags & ~CANCEL_FLAGS)
7878 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7879 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7881 req->cancel.fd = READ_ONCE(sqe->fd);
7887 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7888 unsigned int issue_flags)
7890 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7891 struct io_ring_ctx *ctx = cd->ctx;
7892 struct io_tctx_node *node;
7896 ret = io_try_cancel(req, cd);
7904 /* slow path, try all io-wq's */
7905 io_ring_submit_lock(ctx, issue_flags);
7907 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7908 struct io_uring_task *tctx = node->task->io_uring;
7910 ret = io_async_cancel_one(tctx, cd);
7911 if (ret != -ENOENT) {
7917 io_ring_submit_unlock(ctx, issue_flags);
7918 return all ? nr : ret;
7921 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7923 struct io_cancel_data cd = {
7925 .data = req->cancel.addr,
7926 .flags = req->cancel.flags,
7927 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7931 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7932 if (req->flags & REQ_F_FIXED_FILE)
7933 req->file = io_file_get_fixed(req, req->cancel.fd,
7936 req->file = io_file_get_normal(req, req->cancel.fd);
7941 cd.file = req->file;
7944 ret = __io_async_cancel(&cd, req, issue_flags);
7948 io_req_complete_post(req, ret, 0);
7952 static int io_files_update_prep(struct io_kiocb *req,
7953 const struct io_uring_sqe *sqe)
7955 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7957 if (sqe->rw_flags || sqe->splice_fd_in)
7960 req->rsrc_update.offset = READ_ONCE(sqe->off);
7961 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7962 if (!req->rsrc_update.nr_args)
7964 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7968 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7969 unsigned int issue_flags)
7971 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7976 if (!req->ctx->file_data)
7979 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7980 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7990 ret = io_fixed_fd_install(req, issue_flags, file,
7991 IORING_FILE_INDEX_ALLOC);
7994 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
7995 __io_close_fixed(req, issue_flags, ret);
8006 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
8008 struct io_ring_ctx *ctx = req->ctx;
8009 struct io_uring_rsrc_update2 up;
8012 up.offset = req->rsrc_update.offset;
8013 up.data = req->rsrc_update.arg;
8019 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
8020 ret = io_files_update_with_index_alloc(req, issue_flags);
8022 io_ring_submit_lock(ctx, issue_flags);
8023 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
8024 &up, req->rsrc_update.nr_args);
8025 io_ring_submit_unlock(ctx, issue_flags);
8030 __io_req_complete(req, issue_flags, ret, 0);
8034 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
8036 switch (req->opcode) {
8038 return io_nop_prep(req, sqe);
8039 case IORING_OP_READV:
8040 case IORING_OP_READ_FIXED:
8041 case IORING_OP_READ:
8042 case IORING_OP_WRITEV:
8043 case IORING_OP_WRITE_FIXED:
8044 case IORING_OP_WRITE:
8045 return io_prep_rw(req, sqe);
8046 case IORING_OP_POLL_ADD:
8047 return io_poll_add_prep(req, sqe);
8048 case IORING_OP_POLL_REMOVE:
8049 return io_poll_remove_prep(req, sqe);
8050 case IORING_OP_FSYNC:
8051 return io_fsync_prep(req, sqe);
8052 case IORING_OP_SYNC_FILE_RANGE:
8053 return io_sfr_prep(req, sqe);
8054 case IORING_OP_SENDMSG:
8055 case IORING_OP_SEND:
8056 return io_sendmsg_prep(req, sqe);
8057 case IORING_OP_RECVMSG:
8058 case IORING_OP_RECV:
8059 return io_recvmsg_prep(req, sqe);
8060 case IORING_OP_CONNECT:
8061 return io_connect_prep(req, sqe);
8062 case IORING_OP_TIMEOUT:
8063 return io_timeout_prep(req, sqe);
8064 case IORING_OP_TIMEOUT_REMOVE:
8065 return io_timeout_remove_prep(req, sqe);
8066 case IORING_OP_ASYNC_CANCEL:
8067 return io_async_cancel_prep(req, sqe);
8068 case IORING_OP_LINK_TIMEOUT:
8069 return io_link_timeout_prep(req, sqe);
8070 case IORING_OP_ACCEPT:
8071 return io_accept_prep(req, sqe);
8072 case IORING_OP_FALLOCATE:
8073 return io_fallocate_prep(req, sqe);
8074 case IORING_OP_OPENAT:
8075 return io_openat_prep(req, sqe);
8076 case IORING_OP_CLOSE:
8077 return io_close_prep(req, sqe);
8078 case IORING_OP_FILES_UPDATE:
8079 return io_files_update_prep(req, sqe);
8080 case IORING_OP_STATX:
8081 return io_statx_prep(req, sqe);
8082 case IORING_OP_FADVISE:
8083 return io_fadvise_prep(req, sqe);
8084 case IORING_OP_MADVISE:
8085 return io_madvise_prep(req, sqe);
8086 case IORING_OP_OPENAT2:
8087 return io_openat2_prep(req, sqe);
8088 case IORING_OP_EPOLL_CTL:
8089 return io_epoll_ctl_prep(req, sqe);
8090 case IORING_OP_SPLICE:
8091 return io_splice_prep(req, sqe);
8092 case IORING_OP_PROVIDE_BUFFERS:
8093 return io_provide_buffers_prep(req, sqe);
8094 case IORING_OP_REMOVE_BUFFERS:
8095 return io_remove_buffers_prep(req, sqe);
8097 return io_tee_prep(req, sqe);
8098 case IORING_OP_SHUTDOWN:
8099 return io_shutdown_prep(req, sqe);
8100 case IORING_OP_RENAMEAT:
8101 return io_renameat_prep(req, sqe);
8102 case IORING_OP_UNLINKAT:
8103 return io_unlinkat_prep(req, sqe);
8104 case IORING_OP_MKDIRAT:
8105 return io_mkdirat_prep(req, sqe);
8106 case IORING_OP_SYMLINKAT:
8107 return io_symlinkat_prep(req, sqe);
8108 case IORING_OP_LINKAT:
8109 return io_linkat_prep(req, sqe);
8110 case IORING_OP_MSG_RING:
8111 return io_msg_ring_prep(req, sqe);
8112 case IORING_OP_FSETXATTR:
8113 return io_fsetxattr_prep(req, sqe);
8114 case IORING_OP_SETXATTR:
8115 return io_setxattr_prep(req, sqe);
8116 case IORING_OP_FGETXATTR:
8117 return io_fgetxattr_prep(req, sqe);
8118 case IORING_OP_GETXATTR:
8119 return io_getxattr_prep(req, sqe);
8120 case IORING_OP_SOCKET:
8121 return io_socket_prep(req, sqe);
8122 case IORING_OP_URING_CMD:
8123 return io_uring_cmd_prep(req, sqe);
8126 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
8131 static int io_req_prep_async(struct io_kiocb *req)
8133 const struct io_op_def *def = &io_op_defs[req->opcode];
8135 /* assign early for deferred execution for non-fixed file */
8136 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
8137 req->file = io_file_get_normal(req, req->cqe.fd);
8138 if (!def->needs_async_setup)
8140 if (WARN_ON_ONCE(req_has_async_data(req)))
8142 if (io_alloc_async_data(req))
8145 switch (req->opcode) {
8146 case IORING_OP_READV:
8147 return io_readv_prep_async(req);
8148 case IORING_OP_WRITEV:
8149 return io_writev_prep_async(req);
8150 case IORING_OP_SENDMSG:
8151 return io_sendmsg_prep_async(req);
8152 case IORING_OP_RECVMSG:
8153 return io_recvmsg_prep_async(req);
8154 case IORING_OP_CONNECT:
8155 return io_connect_prep_async(req);
8156 case IORING_OP_URING_CMD:
8157 return io_uring_cmd_prep_async(req);
8159 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
8164 static u32 io_get_sequence(struct io_kiocb *req)
8166 u32 seq = req->ctx->cached_sq_head;
8167 struct io_kiocb *cur;
8169 /* need original cached_sq_head, but it was increased for each req */
8170 io_for_each_link(cur, req)
8175 static __cold void io_drain_req(struct io_kiocb *req)
8177 struct io_ring_ctx *ctx = req->ctx;
8178 struct io_defer_entry *de;
8180 u32 seq = io_get_sequence(req);
8182 /* Still need defer if there is pending req in defer list. */
8183 spin_lock(&ctx->completion_lock);
8184 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
8185 spin_unlock(&ctx->completion_lock);
8187 ctx->drain_active = false;
8188 io_req_task_queue(req);
8191 spin_unlock(&ctx->completion_lock);
8193 ret = io_req_prep_async(req);
8196 io_req_complete_failed(req, ret);
8199 io_prep_async_link(req);
8200 de = kmalloc(sizeof(*de), GFP_KERNEL);
8206 spin_lock(&ctx->completion_lock);
8207 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
8208 spin_unlock(&ctx->completion_lock);
8213 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
8216 list_add_tail(&de->list, &ctx->defer_list);
8217 spin_unlock(&ctx->completion_lock);
8220 static void io_clean_op(struct io_kiocb *req)
8222 if (req->flags & REQ_F_BUFFER_SELECTED) {
8223 spin_lock(&req->ctx->completion_lock);
8224 io_put_kbuf_comp(req);
8225 spin_unlock(&req->ctx->completion_lock);
8228 if (req->flags & REQ_F_NEED_CLEANUP) {
8229 switch (req->opcode) {
8230 case IORING_OP_READV:
8231 case IORING_OP_READ_FIXED:
8232 case IORING_OP_READ:
8233 case IORING_OP_WRITEV:
8234 case IORING_OP_WRITE_FIXED:
8235 case IORING_OP_WRITE: {
8236 struct io_async_rw *io = req->async_data;
8238 kfree(io->free_iovec);
8241 case IORING_OP_RECVMSG:
8242 case IORING_OP_SENDMSG: {
8243 struct io_async_msghdr *io = req->async_data;
8245 kfree(io->free_iov);
8248 case IORING_OP_OPENAT:
8249 case IORING_OP_OPENAT2:
8250 if (req->open.filename)
8251 putname(req->open.filename);
8253 case IORING_OP_RENAMEAT:
8254 putname(req->rename.oldpath);
8255 putname(req->rename.newpath);
8257 case IORING_OP_UNLINKAT:
8258 putname(req->unlink.filename);
8260 case IORING_OP_MKDIRAT:
8261 putname(req->mkdir.filename);
8263 case IORING_OP_SYMLINKAT:
8264 putname(req->symlink.oldpath);
8265 putname(req->symlink.newpath);
8267 case IORING_OP_LINKAT:
8268 putname(req->hardlink.oldpath);
8269 putname(req->hardlink.newpath);
8271 case IORING_OP_STATX:
8272 if (req->statx.filename)
8273 putname(req->statx.filename);
8275 case IORING_OP_SETXATTR:
8276 case IORING_OP_FSETXATTR:
8277 case IORING_OP_GETXATTR:
8278 case IORING_OP_FGETXATTR:
8279 __io_xattr_finish(req);
8283 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8284 kfree(req->apoll->double_poll);
8288 if (req->flags & REQ_F_INFLIGHT) {
8289 struct io_uring_task *tctx = req->task->io_uring;
8291 atomic_dec(&tctx->inflight_tracked);
8293 if (req->flags & REQ_F_CREDS)
8294 put_cred(req->creds);
8295 if (req->flags & REQ_F_ASYNC_DATA) {
8296 kfree(req->async_data);
8297 req->async_data = NULL;
8299 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8302 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8304 if (req->file || !io_op_defs[req->opcode].needs_file)
8307 if (req->flags & REQ_F_FIXED_FILE)
8308 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8310 req->file = io_file_get_normal(req, req->cqe.fd);
8315 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8317 const struct io_op_def *def = &io_op_defs[req->opcode];
8318 const struct cred *creds = NULL;
8321 if (unlikely(!io_assign_file(req, issue_flags)))
8324 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8325 creds = override_creds(req->creds);
8327 if (!def->audit_skip)
8328 audit_uring_entry(req->opcode);
8330 switch (req->opcode) {
8332 ret = io_nop(req, issue_flags);
8334 case IORING_OP_READV:
8335 case IORING_OP_READ_FIXED:
8336 case IORING_OP_READ:
8337 ret = io_read(req, issue_flags);
8339 case IORING_OP_WRITEV:
8340 case IORING_OP_WRITE_FIXED:
8341 case IORING_OP_WRITE:
8342 ret = io_write(req, issue_flags);
8344 case IORING_OP_FSYNC:
8345 ret = io_fsync(req, issue_flags);
8347 case IORING_OP_POLL_ADD:
8348 ret = io_poll_add(req, issue_flags);
8350 case IORING_OP_POLL_REMOVE:
8351 ret = io_poll_remove(req, issue_flags);
8353 case IORING_OP_SYNC_FILE_RANGE:
8354 ret = io_sync_file_range(req, issue_flags);
8356 case IORING_OP_SENDMSG:
8357 ret = io_sendmsg(req, issue_flags);
8359 case IORING_OP_SEND:
8360 ret = io_send(req, issue_flags);
8362 case IORING_OP_RECVMSG:
8363 ret = io_recvmsg(req, issue_flags);
8365 case IORING_OP_RECV:
8366 ret = io_recv(req, issue_flags);
8368 case IORING_OP_TIMEOUT:
8369 ret = io_timeout(req, issue_flags);
8371 case IORING_OP_TIMEOUT_REMOVE:
8372 ret = io_timeout_remove(req, issue_flags);
8374 case IORING_OP_ACCEPT:
8375 ret = io_accept(req, issue_flags);
8377 case IORING_OP_CONNECT:
8378 ret = io_connect(req, issue_flags);
8380 case IORING_OP_ASYNC_CANCEL:
8381 ret = io_async_cancel(req, issue_flags);
8383 case IORING_OP_FALLOCATE:
8384 ret = io_fallocate(req, issue_flags);
8386 case IORING_OP_OPENAT:
8387 ret = io_openat(req, issue_flags);
8389 case IORING_OP_CLOSE:
8390 ret = io_close(req, issue_flags);
8392 case IORING_OP_FILES_UPDATE:
8393 ret = io_files_update(req, issue_flags);
8395 case IORING_OP_STATX:
8396 ret = io_statx(req, issue_flags);
8398 case IORING_OP_FADVISE:
8399 ret = io_fadvise(req, issue_flags);
8401 case IORING_OP_MADVISE:
8402 ret = io_madvise(req, issue_flags);
8404 case IORING_OP_OPENAT2:
8405 ret = io_openat2(req, issue_flags);
8407 case IORING_OP_EPOLL_CTL:
8408 ret = io_epoll_ctl(req, issue_flags);
8410 case IORING_OP_SPLICE:
8411 ret = io_splice(req, issue_flags);
8413 case IORING_OP_PROVIDE_BUFFERS:
8414 ret = io_provide_buffers(req, issue_flags);
8416 case IORING_OP_REMOVE_BUFFERS:
8417 ret = io_remove_buffers(req, issue_flags);
8420 ret = io_tee(req, issue_flags);
8422 case IORING_OP_SHUTDOWN:
8423 ret = io_shutdown(req, issue_flags);
8425 case IORING_OP_RENAMEAT:
8426 ret = io_renameat(req, issue_flags);
8428 case IORING_OP_UNLINKAT:
8429 ret = io_unlinkat(req, issue_flags);
8431 case IORING_OP_MKDIRAT:
8432 ret = io_mkdirat(req, issue_flags);
8434 case IORING_OP_SYMLINKAT:
8435 ret = io_symlinkat(req, issue_flags);
8437 case IORING_OP_LINKAT:
8438 ret = io_linkat(req, issue_flags);
8440 case IORING_OP_MSG_RING:
8441 ret = io_msg_ring(req, issue_flags);
8443 case IORING_OP_FSETXATTR:
8444 ret = io_fsetxattr(req, issue_flags);
8446 case IORING_OP_SETXATTR:
8447 ret = io_setxattr(req, issue_flags);
8449 case IORING_OP_FGETXATTR:
8450 ret = io_fgetxattr(req, issue_flags);
8452 case IORING_OP_GETXATTR:
8453 ret = io_getxattr(req, issue_flags);
8455 case IORING_OP_SOCKET:
8456 ret = io_socket(req, issue_flags);
8458 case IORING_OP_URING_CMD:
8459 ret = io_uring_cmd(req, issue_flags);
8466 if (!def->audit_skip)
8467 audit_uring_exit(!ret, ret);
8470 revert_creds(creds);
8473 /* If the op doesn't have a file, we're not polling for it */
8474 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8475 io_iopoll_req_issued(req, issue_flags);
8480 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8482 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8484 req = io_put_req_find_next(req);
8485 return req ? &req->work : NULL;
8488 static void io_wq_submit_work(struct io_wq_work *work)
8490 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8491 const struct io_op_def *def = &io_op_defs[req->opcode];
8492 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8493 bool needs_poll = false;
8494 int ret = 0, err = -ECANCELED;
8496 /* one will be dropped by ->io_free_work() after returning to io-wq */
8497 if (!(req->flags & REQ_F_REFCOUNT))
8498 __io_req_set_refcount(req, 2);
8502 io_arm_ltimeout(req);
8504 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8505 if (work->flags & IO_WQ_WORK_CANCEL) {
8507 io_req_task_queue_fail(req, err);
8510 if (!io_assign_file(req, issue_flags)) {
8512 work->flags |= IO_WQ_WORK_CANCEL;
8516 if (req->flags & REQ_F_FORCE_ASYNC) {
8517 bool opcode_poll = def->pollin || def->pollout;
8519 if (opcode_poll && file_can_poll(req->file)) {
8521 issue_flags |= IO_URING_F_NONBLOCK;
8526 ret = io_issue_sqe(req, issue_flags);
8530 * We can get EAGAIN for iopolled IO even though we're
8531 * forcing a sync submission from here, since we can't
8532 * wait for request slots on the block side.
8535 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8541 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8543 /* aborted or ready, in either case retry blocking */
8545 issue_flags &= ~IO_URING_F_NONBLOCK;
8548 /* avoid locking problems by failing it from a clean context */
8550 io_req_task_queue_fail(req, ret);
8553 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8556 return &table->files[i];
8559 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8562 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8564 return (struct file *) (slot->file_ptr & FFS_MASK);
8567 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8569 unsigned long file_ptr = (unsigned long) file;
8571 file_ptr |= io_file_get_flags(file);
8572 file_slot->file_ptr = file_ptr;
8575 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8576 unsigned int issue_flags)
8578 struct io_ring_ctx *ctx = req->ctx;
8579 struct file *file = NULL;
8580 unsigned long file_ptr;
8582 io_ring_submit_lock(ctx, issue_flags);
8584 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8586 fd = array_index_nospec(fd, ctx->nr_user_files);
8587 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8588 file = (struct file *) (file_ptr & FFS_MASK);
8589 file_ptr &= ~FFS_MASK;
8590 /* mask in overlapping REQ_F and FFS bits */
8591 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8592 io_req_set_rsrc_node(req, ctx, 0);
8593 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8595 io_ring_submit_unlock(ctx, issue_flags);
8599 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8601 struct file *file = fget(fd);
8603 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8605 /* we don't allow fixed io_uring files */
8606 if (file && file->f_op == &io_uring_fops)
8607 io_req_track_inflight(req);
8611 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8613 struct io_kiocb *prev = req->timeout.prev;
8617 if (!(req->task->flags & PF_EXITING)) {
8618 struct io_cancel_data cd = {
8620 .data = prev->cqe.user_data,
8623 ret = io_try_cancel(req, &cd);
8625 io_req_complete_post(req, ret ?: -ETIME, 0);
8628 io_req_complete_post(req, -ETIME, 0);
8632 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8634 struct io_timeout_data *data = container_of(timer,
8635 struct io_timeout_data, timer);
8636 struct io_kiocb *prev, *req = data->req;
8637 struct io_ring_ctx *ctx = req->ctx;
8638 unsigned long flags;
8640 spin_lock_irqsave(&ctx->timeout_lock, flags);
8641 prev = req->timeout.head;
8642 req->timeout.head = NULL;
8645 * We don't expect the list to be empty, that will only happen if we
8646 * race with the completion of the linked work.
8649 io_remove_next_linked(prev);
8650 if (!req_ref_inc_not_zero(prev))
8653 list_del(&req->timeout.list);
8654 req->timeout.prev = prev;
8655 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8657 req->io_task_work.func = io_req_task_link_timeout;
8658 io_req_task_work_add(req);
8659 return HRTIMER_NORESTART;
8662 static void io_queue_linked_timeout(struct io_kiocb *req)
8664 struct io_ring_ctx *ctx = req->ctx;
8666 spin_lock_irq(&ctx->timeout_lock);
8668 * If the back reference is NULL, then our linked request finished
8669 * before we got a chance to setup the timer
8671 if (req->timeout.head) {
8672 struct io_timeout_data *data = req->async_data;
8674 data->timer.function = io_link_timeout_fn;
8675 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8677 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8679 spin_unlock_irq(&ctx->timeout_lock);
8680 /* drop submission reference */
8684 static void io_queue_async(struct io_kiocb *req, int ret)
8685 __must_hold(&req->ctx->uring_lock)
8687 struct io_kiocb *linked_timeout;
8689 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8690 io_req_complete_failed(req, ret);
8694 linked_timeout = io_prep_linked_timeout(req);
8696 switch (io_arm_poll_handler(req, 0)) {
8697 case IO_APOLL_READY:
8698 io_req_task_queue(req);
8700 case IO_APOLL_ABORTED:
8702 * Queued up for async execution, worker will release
8703 * submit reference when the iocb is actually submitted.
8705 io_kbuf_recycle(req, 0);
8706 io_queue_iowq(req, NULL);
8713 io_queue_linked_timeout(linked_timeout);
8716 static inline void io_queue_sqe(struct io_kiocb *req)
8717 __must_hold(&req->ctx->uring_lock)
8721 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8723 if (req->flags & REQ_F_COMPLETE_INLINE) {
8724 io_req_add_compl_list(req);
8728 * We async punt it if the file wasn't marked NOWAIT, or if the file
8729 * doesn't support non-blocking read/write attempts
8732 io_arm_ltimeout(req);
8734 io_queue_async(req, ret);
8737 static void io_queue_sqe_fallback(struct io_kiocb *req)
8738 __must_hold(&req->ctx->uring_lock)
8740 if (unlikely(req->flags & REQ_F_FAIL)) {
8742 * We don't submit, fail them all, for that replace hardlinks
8743 * with normal links. Extra REQ_F_LINK is tolerated.
8745 req->flags &= ~REQ_F_HARDLINK;
8746 req->flags |= REQ_F_LINK;
8747 io_req_complete_failed(req, req->cqe.res);
8748 } else if (unlikely(req->ctx->drain_active)) {
8751 int ret = io_req_prep_async(req);
8754 io_req_complete_failed(req, ret);
8756 io_queue_iowq(req, NULL);
8761 * Check SQE restrictions (opcode and flags).
8763 * Returns 'true' if SQE is allowed, 'false' otherwise.
8765 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8766 struct io_kiocb *req,
8767 unsigned int sqe_flags)
8769 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8772 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8773 ctx->restrictions.sqe_flags_required)
8776 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8777 ctx->restrictions.sqe_flags_required))
8783 static void io_init_req_drain(struct io_kiocb *req)
8785 struct io_ring_ctx *ctx = req->ctx;
8786 struct io_kiocb *head = ctx->submit_state.link.head;
8788 ctx->drain_active = true;
8791 * If we need to drain a request in the middle of a link, drain
8792 * the head request and the next request/link after the current
8793 * link. Considering sequential execution of links,
8794 * REQ_F_IO_DRAIN will be maintained for every request of our
8797 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8798 ctx->drain_next = true;
8802 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8803 const struct io_uring_sqe *sqe)
8804 __must_hold(&ctx->uring_lock)
8806 const struct io_op_def *def;
8807 unsigned int sqe_flags;
8811 /* req is partially pre-initialised, see io_preinit_req() */
8812 req->opcode = opcode = READ_ONCE(sqe->opcode);
8813 /* same numerical values with corresponding REQ_F_*, safe to copy */
8814 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8815 req->cqe.user_data = READ_ONCE(sqe->user_data);
8817 req->rsrc_node = NULL;
8818 req->task = current;
8820 if (unlikely(opcode >= IORING_OP_LAST)) {
8824 def = &io_op_defs[opcode];
8825 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8826 /* enforce forwards compatibility on users */
8827 if (sqe_flags & ~SQE_VALID_FLAGS)
8829 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8830 if (!def->buffer_select)
8832 req->buf_index = READ_ONCE(sqe->buf_group);
8834 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8835 ctx->drain_disabled = true;
8836 if (sqe_flags & IOSQE_IO_DRAIN) {
8837 if (ctx->drain_disabled)
8839 io_init_req_drain(req);
8842 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8843 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8845 /* knock it to the slow queue path, will be drained there */
8846 if (ctx->drain_active)
8847 req->flags |= REQ_F_FORCE_ASYNC;
8848 /* if there is no link, we're at "next" request and need to drain */
8849 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8850 ctx->drain_next = false;
8851 ctx->drain_active = true;
8852 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8856 if (!def->ioprio && sqe->ioprio)
8858 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8861 if (def->needs_file) {
8862 struct io_submit_state *state = &ctx->submit_state;
8864 req->cqe.fd = READ_ONCE(sqe->fd);
8867 * Plug now if we have more than 2 IO left after this, and the
8868 * target is potentially a read/write to block based storage.
8870 if (state->need_plug && def->plug) {
8871 state->plug_started = true;
8872 state->need_plug = false;
8873 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8877 personality = READ_ONCE(sqe->personality);
8881 req->creds = xa_load(&ctx->personalities, personality);
8884 get_cred(req->creds);
8885 ret = security_uring_override_creds(req->creds);
8887 put_cred(req->creds);
8890 req->flags |= REQ_F_CREDS;
8893 return io_req_prep(req, sqe);
8896 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8897 struct io_kiocb *req, int ret)
8899 struct io_ring_ctx *ctx = req->ctx;
8900 struct io_submit_link *link = &ctx->submit_state.link;
8901 struct io_kiocb *head = link->head;
8903 trace_io_uring_req_failed(sqe, ctx, req, ret);
8906 * Avoid breaking links in the middle as it renders links with SQPOLL
8907 * unusable. Instead of failing eagerly, continue assembling the link if
8908 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8909 * should find the flag and handle the rest.
8911 req_fail_link_node(req, ret);
8912 if (head && !(head->flags & REQ_F_FAIL))
8913 req_fail_link_node(head, -ECANCELED);
8915 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8917 link->last->link = req;
8921 io_queue_sqe_fallback(req);
8926 link->last->link = req;
8933 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8934 const struct io_uring_sqe *sqe)
8935 __must_hold(&ctx->uring_lock)
8937 struct io_submit_link *link = &ctx->submit_state.link;
8940 ret = io_init_req(ctx, req, sqe);
8942 return io_submit_fail_init(sqe, req, ret);
8944 /* don't need @sqe from now on */
8945 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8947 ctx->flags & IORING_SETUP_SQPOLL);
8950 * If we already have a head request, queue this one for async
8951 * submittal once the head completes. If we don't have a head but
8952 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8953 * submitted sync once the chain is complete. If none of those
8954 * conditions are true (normal request), then just queue it.
8956 if (unlikely(link->head)) {
8957 ret = io_req_prep_async(req);
8959 return io_submit_fail_init(sqe, req, ret);
8961 trace_io_uring_link(ctx, req, link->head);
8962 link->last->link = req;
8965 if (req->flags & IO_REQ_LINK_FLAGS)
8967 /* last request of the link, flush it */
8970 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8973 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8974 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8975 if (req->flags & IO_REQ_LINK_FLAGS) {
8980 io_queue_sqe_fallback(req);
8990 * Batched submission is done, ensure local IO is flushed out.
8992 static void io_submit_state_end(struct io_ring_ctx *ctx)
8994 struct io_submit_state *state = &ctx->submit_state;
8996 if (unlikely(state->link.head))
8997 io_queue_sqe_fallback(state->link.head);
8998 /* flush only after queuing links as they can generate completions */
8999 io_submit_flush_completions(ctx);
9000 if (state->plug_started)
9001 blk_finish_plug(&state->plug);
9005 * Start submission side cache.
9007 static void io_submit_state_start(struct io_submit_state *state,
9008 unsigned int max_ios)
9010 state->plug_started = false;
9011 state->need_plug = max_ios > 2;
9012 state->submit_nr = max_ios;
9013 /* set only head, no need to init link_last in advance */
9014 state->link.head = NULL;
9017 static void io_commit_sqring(struct io_ring_ctx *ctx)
9019 struct io_rings *rings = ctx->rings;
9022 * Ensure any loads from the SQEs are done at this point,
9023 * since once we write the new head, the application could
9024 * write new data to them.
9026 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
9030 * Fetch an sqe, if one is available. Note this returns a pointer to memory
9031 * that is mapped by userspace. This means that care needs to be taken to
9032 * ensure that reads are stable, as we cannot rely on userspace always
9033 * being a good citizen. If members of the sqe are validated and then later
9034 * used, it's important that those reads are done through READ_ONCE() to
9035 * prevent a re-load down the line.
9037 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
9039 unsigned head, mask = ctx->sq_entries - 1;
9040 unsigned sq_idx = ctx->cached_sq_head++ & mask;
9043 * The cached sq head (or cq tail) serves two purposes:
9045 * 1) allows us to batch the cost of updating the user visible
9047 * 2) allows the kernel side to track the head on its own, even
9048 * though the application is the one updating it.
9050 head = READ_ONCE(ctx->sq_array[sq_idx]);
9051 if (likely(head < ctx->sq_entries)) {
9052 /* double index for 128-byte SQEs, twice as long */
9053 if (ctx->flags & IORING_SETUP_SQE128)
9055 return &ctx->sq_sqes[head];
9058 /* drop invalid entries */
9060 WRITE_ONCE(ctx->rings->sq_dropped,
9061 READ_ONCE(ctx->rings->sq_dropped) + 1);
9065 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
9066 __must_hold(&ctx->uring_lock)
9068 unsigned int entries = io_sqring_entries(ctx);
9072 if (unlikely(!entries))
9074 /* make sure SQ entry isn't read before tail */
9075 ret = left = min3(nr, ctx->sq_entries, entries);
9076 io_get_task_refs(left);
9077 io_submit_state_start(&ctx->submit_state, left);
9080 const struct io_uring_sqe *sqe;
9081 struct io_kiocb *req;
9083 if (unlikely(!io_alloc_req_refill(ctx)))
9085 req = io_alloc_req(ctx);
9086 sqe = io_get_sqe(ctx);
9087 if (unlikely(!sqe)) {
9088 io_req_add_to_cache(req, ctx);
9093 * Continue submitting even for sqe failure if the
9094 * ring was setup with IORING_SETUP_SUBMIT_ALL
9096 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
9097 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
9103 if (unlikely(left)) {
9105 /* try again if it submitted nothing and can't allocate a req */
9106 if (!ret && io_req_cache_empty(ctx))
9108 current->io_uring->cached_refs += left;
9111 io_submit_state_end(ctx);
9112 /* Commit SQ ring head once we've consumed and submitted all SQEs */
9113 io_commit_sqring(ctx);
9117 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
9119 return READ_ONCE(sqd->state);
9122 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
9124 unsigned int to_submit;
9127 to_submit = io_sqring_entries(ctx);
9128 /* if we're handling multiple rings, cap submit size for fairness */
9129 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
9130 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
9132 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
9133 const struct cred *creds = NULL;
9135 if (ctx->sq_creds != current_cred())
9136 creds = override_creds(ctx->sq_creds);
9138 mutex_lock(&ctx->uring_lock);
9139 if (!wq_list_empty(&ctx->iopoll_list))
9140 io_do_iopoll(ctx, true);
9143 * Don't submit if refs are dying, good for io_uring_register(),
9144 * but also it is relied upon by io_ring_exit_work()
9146 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
9147 !(ctx->flags & IORING_SETUP_R_DISABLED))
9148 ret = io_submit_sqes(ctx, to_submit);
9149 mutex_unlock(&ctx->uring_lock);
9151 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
9152 wake_up(&ctx->sqo_sq_wait);
9154 revert_creds(creds);
9160 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
9162 struct io_ring_ctx *ctx;
9163 unsigned sq_thread_idle = 0;
9165 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9166 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
9167 sqd->sq_thread_idle = sq_thread_idle;
9170 static bool io_sqd_handle_event(struct io_sq_data *sqd)
9172 bool did_sig = false;
9173 struct ksignal ksig;
9175 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
9176 signal_pending(current)) {
9177 mutex_unlock(&sqd->lock);
9178 if (signal_pending(current))
9179 did_sig = get_signal(&ksig);
9181 mutex_lock(&sqd->lock);
9183 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9186 static int io_sq_thread(void *data)
9188 struct io_sq_data *sqd = data;
9189 struct io_ring_ctx *ctx;
9190 unsigned long timeout = 0;
9191 char buf[TASK_COMM_LEN];
9194 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
9195 set_task_comm(current, buf);
9197 if (sqd->sq_cpu != -1)
9198 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
9200 set_cpus_allowed_ptr(current, cpu_online_mask);
9201 current->flags |= PF_NO_SETAFFINITY;
9203 audit_alloc_kernel(current);
9205 mutex_lock(&sqd->lock);
9207 bool cap_entries, sqt_spin = false;
9209 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
9210 if (io_sqd_handle_event(sqd))
9212 timeout = jiffies + sqd->sq_thread_idle;
9215 cap_entries = !list_is_singular(&sqd->ctx_list);
9216 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9217 int ret = __io_sq_thread(ctx, cap_entries);
9219 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
9222 if (io_run_task_work())
9225 if (sqt_spin || !time_after(jiffies, timeout)) {
9228 timeout = jiffies + sqd->sq_thread_idle;
9232 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
9233 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
9234 bool needs_sched = true;
9236 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9237 atomic_or(IORING_SQ_NEED_WAKEUP,
9238 &ctx->rings->sq_flags);
9239 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
9240 !wq_list_empty(&ctx->iopoll_list)) {
9241 needs_sched = false;
9246 * Ensure the store of the wakeup flag is not
9247 * reordered with the load of the SQ tail
9249 smp_mb__after_atomic();
9251 if (io_sqring_entries(ctx)) {
9252 needs_sched = false;
9258 mutex_unlock(&sqd->lock);
9260 mutex_lock(&sqd->lock);
9262 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9263 atomic_andnot(IORING_SQ_NEED_WAKEUP,
9264 &ctx->rings->sq_flags);
9267 finish_wait(&sqd->wait, &wait);
9268 timeout = jiffies + sqd->sq_thread_idle;
9271 io_uring_cancel_generic(true, sqd);
9273 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9274 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9276 mutex_unlock(&sqd->lock);
9278 audit_free(current);
9280 complete(&sqd->exited);
9284 struct io_wait_queue {
9285 struct wait_queue_entry wq;
9286 struct io_ring_ctx *ctx;
9288 unsigned nr_timeouts;
9291 static inline bool io_should_wake(struct io_wait_queue *iowq)
9293 struct io_ring_ctx *ctx = iowq->ctx;
9294 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9297 * Wake up if we have enough events, or if a timeout occurred since we
9298 * started waiting. For timeouts, we always want to return to userspace,
9299 * regardless of event count.
9301 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9304 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9305 int wake_flags, void *key)
9307 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9311 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9312 * the task, and the next invocation will do it.
9314 if (io_should_wake(iowq) ||
9315 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9316 return autoremove_wake_function(curr, mode, wake_flags, key);
9320 static int io_run_task_work_sig(void)
9322 if (io_run_task_work())
9324 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9325 return -ERESTARTSYS;
9326 if (task_sigpending(current))
9331 /* when returns >0, the caller should retry */
9332 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9333 struct io_wait_queue *iowq,
9337 unsigned long check_cq;
9339 /* make sure we run task_work before checking for signals */
9340 ret = io_run_task_work_sig();
9341 if (ret || io_should_wake(iowq))
9343 check_cq = READ_ONCE(ctx->check_cq);
9344 /* let the caller flush overflows, retry */
9345 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9347 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9349 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9355 * Wait until events become available, if we don't already have some. The
9356 * application must reap them itself, as they reside on the shared cq ring.
9358 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9359 const sigset_t __user *sig, size_t sigsz,
9360 struct __kernel_timespec __user *uts)
9362 struct io_wait_queue iowq;
9363 struct io_rings *rings = ctx->rings;
9364 ktime_t timeout = KTIME_MAX;
9368 io_cqring_overflow_flush(ctx);
9369 if (io_cqring_events(ctx) >= min_events)
9371 if (!io_run_task_work())
9376 #ifdef CONFIG_COMPAT
9377 if (in_compat_syscall())
9378 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9382 ret = set_user_sigmask(sig, sigsz);
9389 struct timespec64 ts;
9391 if (get_timespec64(&ts, uts))
9393 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9396 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9397 iowq.wq.private = current;
9398 INIT_LIST_HEAD(&iowq.wq.entry);
9400 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9401 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9403 trace_io_uring_cqring_wait(ctx, min_events);
9405 /* if we can't even flush overflow, don't wait for more */
9406 if (!io_cqring_overflow_flush(ctx)) {
9410 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9411 TASK_INTERRUPTIBLE);
9412 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9416 finish_wait(&ctx->cq_wait, &iowq.wq);
9417 restore_saved_sigmask_unless(ret == -EINTR);
9419 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9422 static void io_free_page_table(void **table, size_t size)
9424 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9426 for (i = 0; i < nr_tables; i++)
9431 static __cold void **io_alloc_page_table(size_t size)
9433 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9434 size_t init_size = size;
9437 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9441 for (i = 0; i < nr_tables; i++) {
9442 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9444 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9446 io_free_page_table(table, init_size);
9454 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9456 percpu_ref_exit(&ref_node->refs);
9460 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9462 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9463 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9464 unsigned long flags;
9465 bool first_add = false;
9466 unsigned long delay = HZ;
9468 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9471 /* if we are mid-quiesce then do not delay */
9472 if (node->rsrc_data->quiesce)
9475 while (!list_empty(&ctx->rsrc_ref_list)) {
9476 node = list_first_entry(&ctx->rsrc_ref_list,
9477 struct io_rsrc_node, node);
9478 /* recycle ref nodes in order */
9481 list_del(&node->node);
9482 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9484 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9487 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9490 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9492 struct io_rsrc_node *ref_node;
9494 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9498 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9503 INIT_LIST_HEAD(&ref_node->node);
9504 INIT_LIST_HEAD(&ref_node->rsrc_list);
9505 ref_node->done = false;
9509 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9510 struct io_rsrc_data *data_to_kill)
9511 __must_hold(&ctx->uring_lock)
9513 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9514 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9516 io_rsrc_refs_drop(ctx);
9519 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9521 rsrc_node->rsrc_data = data_to_kill;
9522 spin_lock_irq(&ctx->rsrc_ref_lock);
9523 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9524 spin_unlock_irq(&ctx->rsrc_ref_lock);
9526 atomic_inc(&data_to_kill->refs);
9527 percpu_ref_kill(&rsrc_node->refs);
9528 ctx->rsrc_node = NULL;
9531 if (!ctx->rsrc_node) {
9532 ctx->rsrc_node = ctx->rsrc_backup_node;
9533 ctx->rsrc_backup_node = NULL;
9537 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9539 if (ctx->rsrc_backup_node)
9541 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9542 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9545 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9546 struct io_ring_ctx *ctx)
9550 /* As we may drop ->uring_lock, other task may have started quiesce */
9554 data->quiesce = true;
9556 ret = io_rsrc_node_switch_start(ctx);
9559 io_rsrc_node_switch(ctx, data);
9561 /* kill initial ref, already quiesced if zero */
9562 if (atomic_dec_and_test(&data->refs))
9564 mutex_unlock(&ctx->uring_lock);
9565 flush_delayed_work(&ctx->rsrc_put_work);
9566 ret = wait_for_completion_interruptible(&data->done);
9568 mutex_lock(&ctx->uring_lock);
9569 if (atomic_read(&data->refs) > 0) {
9571 * it has been revived by another thread while
9574 mutex_unlock(&ctx->uring_lock);
9580 atomic_inc(&data->refs);
9581 /* wait for all works potentially completing data->done */
9582 flush_delayed_work(&ctx->rsrc_put_work);
9583 reinit_completion(&data->done);
9585 ret = io_run_task_work_sig();
9586 mutex_lock(&ctx->uring_lock);
9588 data->quiesce = false;
9593 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9595 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9596 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9598 return &data->tags[table_idx][off];
9601 static void io_rsrc_data_free(struct io_rsrc_data *data)
9603 size_t size = data->nr * sizeof(data->tags[0][0]);
9606 io_free_page_table((void **)data->tags, size);
9610 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9611 u64 __user *utags, unsigned nr,
9612 struct io_rsrc_data **pdata)
9614 struct io_rsrc_data *data;
9618 data = kzalloc(sizeof(*data), GFP_KERNEL);
9621 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9629 data->do_put = do_put;
9632 for (i = 0; i < nr; i++) {
9633 u64 *tag_slot = io_get_tag_slot(data, i);
9635 if (copy_from_user(tag_slot, &utags[i],
9641 atomic_set(&data->refs, 1);
9642 init_completion(&data->done);
9646 io_rsrc_data_free(data);
9650 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9652 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9653 GFP_KERNEL_ACCOUNT);
9654 if (unlikely(!table->files))
9657 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9658 if (unlikely(!table->bitmap)) {
9659 kvfree(table->files);
9666 static void io_free_file_tables(struct io_file_table *table)
9668 kvfree(table->files);
9669 bitmap_free(table->bitmap);
9670 table->files = NULL;
9671 table->bitmap = NULL;
9674 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9676 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9677 __set_bit(bit, table->bitmap);
9678 table->alloc_hint = bit + 1;
9681 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9683 __clear_bit(bit, table->bitmap);
9684 table->alloc_hint = bit;
9687 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9689 #if !defined(IO_URING_SCM_ALL)
9692 for (i = 0; i < ctx->nr_user_files; i++) {
9693 struct file *file = io_file_from_index(ctx, i);
9697 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9699 io_file_bitmap_clear(&ctx->file_table, i);
9704 #if defined(CONFIG_UNIX)
9705 if (ctx->ring_sock) {
9706 struct sock *sock = ctx->ring_sock->sk;
9707 struct sk_buff *skb;
9709 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9713 io_free_file_tables(&ctx->file_table);
9714 io_rsrc_data_free(ctx->file_data);
9715 ctx->file_data = NULL;
9716 ctx->nr_user_files = 0;
9719 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9721 unsigned nr = ctx->nr_user_files;
9724 if (!ctx->file_data)
9728 * Quiesce may unlock ->uring_lock, and while it's not held
9729 * prevent new requests using the table.
9731 ctx->nr_user_files = 0;
9732 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9733 ctx->nr_user_files = nr;
9735 __io_sqe_files_unregister(ctx);
9739 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9740 __releases(&sqd->lock)
9742 WARN_ON_ONCE(sqd->thread == current);
9745 * Do the dance but not conditional clear_bit() because it'd race with
9746 * other threads incrementing park_pending and setting the bit.
9748 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9749 if (atomic_dec_return(&sqd->park_pending))
9750 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9751 mutex_unlock(&sqd->lock);
9754 static void io_sq_thread_park(struct io_sq_data *sqd)
9755 __acquires(&sqd->lock)
9757 WARN_ON_ONCE(sqd->thread == current);
9759 atomic_inc(&sqd->park_pending);
9760 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9761 mutex_lock(&sqd->lock);
9763 wake_up_process(sqd->thread);
9766 static void io_sq_thread_stop(struct io_sq_data *sqd)
9768 WARN_ON_ONCE(sqd->thread == current);
9769 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9771 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9772 mutex_lock(&sqd->lock);
9774 wake_up_process(sqd->thread);
9775 mutex_unlock(&sqd->lock);
9776 wait_for_completion(&sqd->exited);
9779 static void io_put_sq_data(struct io_sq_data *sqd)
9781 if (refcount_dec_and_test(&sqd->refs)) {
9782 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9784 io_sq_thread_stop(sqd);
9789 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9791 struct io_sq_data *sqd = ctx->sq_data;
9794 io_sq_thread_park(sqd);
9795 list_del_init(&ctx->sqd_list);
9796 io_sqd_update_thread_idle(sqd);
9797 io_sq_thread_unpark(sqd);
9799 io_put_sq_data(sqd);
9800 ctx->sq_data = NULL;
9804 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9806 struct io_ring_ctx *ctx_attach;
9807 struct io_sq_data *sqd;
9810 f = fdget(p->wq_fd);
9812 return ERR_PTR(-ENXIO);
9813 if (f.file->f_op != &io_uring_fops) {
9815 return ERR_PTR(-EINVAL);
9818 ctx_attach = f.file->private_data;
9819 sqd = ctx_attach->sq_data;
9822 return ERR_PTR(-EINVAL);
9824 if (sqd->task_tgid != current->tgid) {
9826 return ERR_PTR(-EPERM);
9829 refcount_inc(&sqd->refs);
9834 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9837 struct io_sq_data *sqd;
9840 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9841 sqd = io_attach_sq_data(p);
9846 /* fall through for EPERM case, setup new sqd/task */
9847 if (PTR_ERR(sqd) != -EPERM)
9851 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9853 return ERR_PTR(-ENOMEM);
9855 atomic_set(&sqd->park_pending, 0);
9856 refcount_set(&sqd->refs, 1);
9857 INIT_LIST_HEAD(&sqd->ctx_list);
9858 mutex_init(&sqd->lock);
9859 init_waitqueue_head(&sqd->wait);
9860 init_completion(&sqd->exited);
9865 * Ensure the UNIX gc is aware of our file set, so we are certain that
9866 * the io_uring can be safely unregistered on process exit, even if we have
9867 * loops in the file referencing. We account only files that can hold other
9868 * files because otherwise they can't form a loop and so are not interesting
9871 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9873 #if defined(CONFIG_UNIX)
9874 struct sock *sk = ctx->ring_sock->sk;
9875 struct sk_buff_head *head = &sk->sk_receive_queue;
9876 struct scm_fp_list *fpl;
9877 struct sk_buff *skb;
9879 if (likely(!io_file_need_scm(file)))
9883 * See if we can merge this file into an existing skb SCM_RIGHTS
9884 * file set. If there's no room, fall back to allocating a new skb
9885 * and filling it in.
9887 spin_lock_irq(&head->lock);
9888 skb = skb_peek(head);
9889 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9890 __skb_unlink(skb, head);
9893 spin_unlock_irq(&head->lock);
9896 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9900 skb = alloc_skb(0, GFP_KERNEL);
9906 fpl->user = get_uid(current_user());
9907 fpl->max = SCM_MAX_FD;
9910 UNIXCB(skb).fp = fpl;
9912 skb->destructor = unix_destruct_scm;
9913 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9916 fpl = UNIXCB(skb).fp;
9917 fpl->fp[fpl->count++] = get_file(file);
9918 unix_inflight(fpl->user, file);
9919 skb_queue_head(head, skb);
9925 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9927 struct file *file = prsrc->file;
9928 #if defined(CONFIG_UNIX)
9929 struct sock *sock = ctx->ring_sock->sk;
9930 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9931 struct sk_buff *skb;
9934 if (!io_file_need_scm(file)) {
9939 __skb_queue_head_init(&list);
9942 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9943 * remove this entry and rearrange the file array.
9945 skb = skb_dequeue(head);
9947 struct scm_fp_list *fp;
9949 fp = UNIXCB(skb).fp;
9950 for (i = 0; i < fp->count; i++) {
9953 if (fp->fp[i] != file)
9956 unix_notinflight(fp->user, fp->fp[i]);
9957 left = fp->count - 1 - i;
9959 memmove(&fp->fp[i], &fp->fp[i + 1],
9960 left * sizeof(struct file *));
9967 __skb_queue_tail(&list, skb);
9977 __skb_queue_tail(&list, skb);
9979 skb = skb_dequeue(head);
9982 if (skb_peek(&list)) {
9983 spin_lock_irq(&head->lock);
9984 while ((skb = __skb_dequeue(&list)) != NULL)
9985 __skb_queue_tail(head, skb);
9986 spin_unlock_irq(&head->lock);
9993 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9995 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9996 struct io_ring_ctx *ctx = rsrc_data->ctx;
9997 struct io_rsrc_put *prsrc, *tmp;
9999 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
10000 list_del(&prsrc->list);
10003 if (ctx->flags & IORING_SETUP_IOPOLL)
10004 mutex_lock(&ctx->uring_lock);
10006 spin_lock(&ctx->completion_lock);
10007 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
10008 io_commit_cqring(ctx);
10009 spin_unlock(&ctx->completion_lock);
10010 io_cqring_ev_posted(ctx);
10012 if (ctx->flags & IORING_SETUP_IOPOLL)
10013 mutex_unlock(&ctx->uring_lock);
10016 rsrc_data->do_put(ctx, prsrc);
10020 io_rsrc_node_destroy(ref_node);
10021 if (atomic_dec_and_test(&rsrc_data->refs))
10022 complete(&rsrc_data->done);
10025 static void io_rsrc_put_work(struct work_struct *work)
10027 struct io_ring_ctx *ctx;
10028 struct llist_node *node;
10030 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
10031 node = llist_del_all(&ctx->rsrc_put_llist);
10034 struct io_rsrc_node *ref_node;
10035 struct llist_node *next = node->next;
10037 ref_node = llist_entry(node, struct io_rsrc_node, llist);
10038 __io_rsrc_put_work(ref_node);
10043 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
10044 unsigned nr_args, u64 __user *tags)
10046 __s32 __user *fds = (__s32 __user *) arg;
10051 if (ctx->file_data)
10055 if (nr_args > IORING_MAX_FIXED_FILES)
10057 if (nr_args > rlimit(RLIMIT_NOFILE))
10059 ret = io_rsrc_node_switch_start(ctx);
10062 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
10067 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
10068 io_rsrc_data_free(ctx->file_data);
10069 ctx->file_data = NULL;
10073 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
10074 struct io_fixed_file *file_slot;
10076 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
10080 /* allow sparse sets */
10081 if (!fds || fd == -1) {
10083 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
10090 if (unlikely(!file))
10094 * Don't allow io_uring instances to be registered. If UNIX
10095 * isn't enabled, then this causes a reference cycle and this
10096 * instance can never get freed. If UNIX is enabled we'll
10097 * handle it just fine, but there's still no point in allowing
10098 * a ring fd as it doesn't support regular read/write anyway.
10100 if (file->f_op == &io_uring_fops) {
10104 ret = io_scm_file_account(ctx, file);
10109 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10110 io_fixed_file_set(file_slot, file);
10111 io_file_bitmap_set(&ctx->file_table, i);
10114 io_rsrc_node_switch(ctx, NULL);
10117 __io_sqe_files_unregister(ctx);
10121 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
10122 struct io_rsrc_node *node, void *rsrc)
10124 u64 *tag_slot = io_get_tag_slot(data, idx);
10125 struct io_rsrc_put *prsrc;
10127 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
10131 prsrc->tag = *tag_slot;
10133 prsrc->rsrc = rsrc;
10134 list_add(&prsrc->list, &node->rsrc_list);
10138 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
10139 unsigned int issue_flags, u32 slot_index)
10140 __must_hold(&req->ctx->uring_lock)
10142 struct io_ring_ctx *ctx = req->ctx;
10143 bool needs_switch = false;
10144 struct io_fixed_file *file_slot;
10147 if (file->f_op == &io_uring_fops)
10149 if (!ctx->file_data)
10151 if (slot_index >= ctx->nr_user_files)
10154 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
10155 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
10157 if (file_slot->file_ptr) {
10158 struct file *old_file;
10160 ret = io_rsrc_node_switch_start(ctx);
10164 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10165 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
10166 ctx->rsrc_node, old_file);
10169 file_slot->file_ptr = 0;
10170 io_file_bitmap_clear(&ctx->file_table, slot_index);
10171 needs_switch = true;
10174 ret = io_scm_file_account(ctx, file);
10176 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
10177 io_fixed_file_set(file_slot, file);
10178 io_file_bitmap_set(&ctx->file_table, slot_index);
10182 io_rsrc_node_switch(ctx, ctx->file_data);
10188 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
10189 unsigned int offset)
10191 struct io_ring_ctx *ctx = req->ctx;
10192 struct io_fixed_file *file_slot;
10196 io_ring_submit_lock(ctx, issue_flags);
10198 if (unlikely(!ctx->file_data))
10201 if (offset >= ctx->nr_user_files)
10203 ret = io_rsrc_node_switch_start(ctx);
10207 offset = array_index_nospec(offset, ctx->nr_user_files);
10208 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
10210 if (!file_slot->file_ptr)
10213 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10214 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
10218 file_slot->file_ptr = 0;
10219 io_file_bitmap_clear(&ctx->file_table, offset);
10220 io_rsrc_node_switch(ctx, ctx->file_data);
10223 io_ring_submit_unlock(ctx, issue_flags);
10227 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
10229 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
10232 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
10233 struct io_uring_rsrc_update2 *up,
10236 u64 __user *tags = u64_to_user_ptr(up->tags);
10237 __s32 __user *fds = u64_to_user_ptr(up->data);
10238 struct io_rsrc_data *data = ctx->file_data;
10239 struct io_fixed_file *file_slot;
10241 int fd, i, err = 0;
10243 bool needs_switch = false;
10245 if (!ctx->file_data)
10247 if (up->offset + nr_args > ctx->nr_user_files)
10250 for (done = 0; done < nr_args; done++) {
10253 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
10254 copy_from_user(&fd, &fds[done], sizeof(fd))) {
10258 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
10262 if (fd == IORING_REGISTER_FILES_SKIP)
10265 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
10266 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10268 if (file_slot->file_ptr) {
10269 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10270 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
10273 file_slot->file_ptr = 0;
10274 io_file_bitmap_clear(&ctx->file_table, i);
10275 needs_switch = true;
10284 * Don't allow io_uring instances to be registered. If
10285 * UNIX isn't enabled, then this causes a reference
10286 * cycle and this instance can never get freed. If UNIX
10287 * is enabled we'll handle it just fine, but there's
10288 * still no point in allowing a ring fd as it doesn't
10289 * support regular read/write anyway.
10291 if (file->f_op == &io_uring_fops) {
10296 err = io_scm_file_account(ctx, file);
10301 *io_get_tag_slot(data, i) = tag;
10302 io_fixed_file_set(file_slot, file);
10303 io_file_bitmap_set(&ctx->file_table, i);
10308 io_rsrc_node_switch(ctx, data);
10309 return done ? done : err;
10312 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
10313 struct task_struct *task)
10315 struct io_wq_hash *hash;
10316 struct io_wq_data data;
10317 unsigned int concurrency;
10319 mutex_lock(&ctx->uring_lock);
10320 hash = ctx->hash_map;
10322 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10324 mutex_unlock(&ctx->uring_lock);
10325 return ERR_PTR(-ENOMEM);
10327 refcount_set(&hash->refs, 1);
10328 init_waitqueue_head(&hash->wait);
10329 ctx->hash_map = hash;
10331 mutex_unlock(&ctx->uring_lock);
10335 data.free_work = io_wq_free_work;
10336 data.do_work = io_wq_submit_work;
10338 /* Do QD, or 4 * CPUS, whatever is smallest */
10339 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10341 return io_wq_create(concurrency, &data);
10344 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10345 struct io_ring_ctx *ctx)
10347 struct io_uring_task *tctx;
10350 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10351 if (unlikely(!tctx))
10354 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10355 sizeof(struct file *), GFP_KERNEL);
10356 if (unlikely(!tctx->registered_rings)) {
10361 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10362 if (unlikely(ret)) {
10363 kfree(tctx->registered_rings);
10368 tctx->io_wq = io_init_wq_offload(ctx, task);
10369 if (IS_ERR(tctx->io_wq)) {
10370 ret = PTR_ERR(tctx->io_wq);
10371 percpu_counter_destroy(&tctx->inflight);
10372 kfree(tctx->registered_rings);
10377 xa_init(&tctx->xa);
10378 init_waitqueue_head(&tctx->wait);
10379 atomic_set(&tctx->in_idle, 0);
10380 atomic_set(&tctx->inflight_tracked, 0);
10381 task->io_uring = tctx;
10382 spin_lock_init(&tctx->task_lock);
10383 INIT_WQ_LIST(&tctx->task_list);
10384 INIT_WQ_LIST(&tctx->prio_task_list);
10385 init_task_work(&tctx->task_work, tctx_task_work);
10389 void __io_uring_free(struct task_struct *tsk)
10391 struct io_uring_task *tctx = tsk->io_uring;
10393 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10394 WARN_ON_ONCE(tctx->io_wq);
10395 WARN_ON_ONCE(tctx->cached_refs);
10397 kfree(tctx->registered_rings);
10398 percpu_counter_destroy(&tctx->inflight);
10400 tsk->io_uring = NULL;
10403 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10404 struct io_uring_params *p)
10408 /* Retain compatibility with failing for an invalid attach attempt */
10409 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10410 IORING_SETUP_ATTACH_WQ) {
10413 f = fdget(p->wq_fd);
10416 if (f.file->f_op != &io_uring_fops) {
10422 if (ctx->flags & IORING_SETUP_SQPOLL) {
10423 struct task_struct *tsk;
10424 struct io_sq_data *sqd;
10427 ret = security_uring_sqpoll();
10431 sqd = io_get_sq_data(p, &attached);
10433 ret = PTR_ERR(sqd);
10437 ctx->sq_creds = get_current_cred();
10438 ctx->sq_data = sqd;
10439 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10440 if (!ctx->sq_thread_idle)
10441 ctx->sq_thread_idle = HZ;
10443 io_sq_thread_park(sqd);
10444 list_add(&ctx->sqd_list, &sqd->ctx_list);
10445 io_sqd_update_thread_idle(sqd);
10446 /* don't attach to a dying SQPOLL thread, would be racy */
10447 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10448 io_sq_thread_unpark(sqd);
10455 if (p->flags & IORING_SETUP_SQ_AFF) {
10456 int cpu = p->sq_thread_cpu;
10459 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10466 sqd->task_pid = current->pid;
10467 sqd->task_tgid = current->tgid;
10468 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10470 ret = PTR_ERR(tsk);
10475 ret = io_uring_alloc_task_context(tsk, ctx);
10476 wake_up_new_task(tsk);
10479 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10480 /* Can't have SQ_AFF without SQPOLL */
10487 complete(&ctx->sq_data->exited);
10489 io_sq_thread_finish(ctx);
10493 static inline void __io_unaccount_mem(struct user_struct *user,
10494 unsigned long nr_pages)
10496 atomic_long_sub(nr_pages, &user->locked_vm);
10499 static inline int __io_account_mem(struct user_struct *user,
10500 unsigned long nr_pages)
10502 unsigned long page_limit, cur_pages, new_pages;
10504 /* Don't allow more pages than we can safely lock */
10505 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10508 cur_pages = atomic_long_read(&user->locked_vm);
10509 new_pages = cur_pages + nr_pages;
10510 if (new_pages > page_limit)
10512 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10513 new_pages) != cur_pages);
10518 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10521 __io_unaccount_mem(ctx->user, nr_pages);
10523 if (ctx->mm_account)
10524 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10527 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10532 ret = __io_account_mem(ctx->user, nr_pages);
10537 if (ctx->mm_account)
10538 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10543 static void io_mem_free(void *ptr)
10550 page = virt_to_head_page(ptr);
10551 if (put_page_testzero(page))
10552 free_compound_page(page);
10555 static void *io_mem_alloc(size_t size)
10557 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10559 return (void *) __get_free_pages(gfp, get_order(size));
10562 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10563 unsigned int cq_entries, size_t *sq_offset)
10565 struct io_rings *rings;
10566 size_t off, sq_array_size;
10568 off = struct_size(rings, cqes, cq_entries);
10569 if (off == SIZE_MAX)
10571 if (ctx->flags & IORING_SETUP_CQE32) {
10572 if (check_shl_overflow(off, 1, &off))
10577 off = ALIGN(off, SMP_CACHE_BYTES);
10585 sq_array_size = array_size(sizeof(u32), sq_entries);
10586 if (sq_array_size == SIZE_MAX)
10589 if (check_add_overflow(off, sq_array_size, &off))
10595 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10597 struct io_mapped_ubuf *imu = *slot;
10600 if (imu != ctx->dummy_ubuf) {
10601 for (i = 0; i < imu->nr_bvecs; i++)
10602 unpin_user_page(imu->bvec[i].bv_page);
10603 if (imu->acct_pages)
10604 io_unaccount_mem(ctx, imu->acct_pages);
10610 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10612 io_buffer_unmap(ctx, &prsrc->buf);
10616 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10620 for (i = 0; i < ctx->nr_user_bufs; i++)
10621 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10622 kfree(ctx->user_bufs);
10623 io_rsrc_data_free(ctx->buf_data);
10624 ctx->user_bufs = NULL;
10625 ctx->buf_data = NULL;
10626 ctx->nr_user_bufs = 0;
10629 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10631 unsigned nr = ctx->nr_user_bufs;
10634 if (!ctx->buf_data)
10638 * Quiesce may unlock ->uring_lock, and while it's not held
10639 * prevent new requests using the table.
10641 ctx->nr_user_bufs = 0;
10642 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10643 ctx->nr_user_bufs = nr;
10645 __io_sqe_buffers_unregister(ctx);
10649 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10650 void __user *arg, unsigned index)
10652 struct iovec __user *src;
10654 #ifdef CONFIG_COMPAT
10656 struct compat_iovec __user *ciovs;
10657 struct compat_iovec ciov;
10659 ciovs = (struct compat_iovec __user *) arg;
10660 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10663 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10664 dst->iov_len = ciov.iov_len;
10668 src = (struct iovec __user *) arg;
10669 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10675 * Not super efficient, but this is just a registration time. And we do cache
10676 * the last compound head, so generally we'll only do a full search if we don't
10679 * We check if the given compound head page has already been accounted, to
10680 * avoid double accounting it. This allows us to account the full size of the
10681 * page, not just the constituent pages of a huge page.
10683 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10684 int nr_pages, struct page *hpage)
10688 /* check current page array */
10689 for (i = 0; i < nr_pages; i++) {
10690 if (!PageCompound(pages[i]))
10692 if (compound_head(pages[i]) == hpage)
10696 /* check previously registered pages */
10697 for (i = 0; i < ctx->nr_user_bufs; i++) {
10698 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10700 for (j = 0; j < imu->nr_bvecs; j++) {
10701 if (!PageCompound(imu->bvec[j].bv_page))
10703 if (compound_head(imu->bvec[j].bv_page) == hpage)
10711 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10712 int nr_pages, struct io_mapped_ubuf *imu,
10713 struct page **last_hpage)
10717 imu->acct_pages = 0;
10718 for (i = 0; i < nr_pages; i++) {
10719 if (!PageCompound(pages[i])) {
10722 struct page *hpage;
10724 hpage = compound_head(pages[i]);
10725 if (hpage == *last_hpage)
10727 *last_hpage = hpage;
10728 if (headpage_already_acct(ctx, pages, i, hpage))
10730 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10734 if (!imu->acct_pages)
10737 ret = io_account_mem(ctx, imu->acct_pages);
10739 imu->acct_pages = 0;
10743 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10746 unsigned long start, end, nr_pages;
10747 struct vm_area_struct **vmas = NULL;
10748 struct page **pages = NULL;
10749 int i, pret, ret = -ENOMEM;
10751 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10752 start = ubuf >> PAGE_SHIFT;
10753 nr_pages = end - start;
10755 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10759 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10765 mmap_read_lock(current->mm);
10766 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10768 if (pret == nr_pages) {
10769 /* don't support file backed memory */
10770 for (i = 0; i < nr_pages; i++) {
10771 struct vm_area_struct *vma = vmas[i];
10773 if (vma_is_shmem(vma))
10775 if (vma->vm_file &&
10776 !is_file_hugepages(vma->vm_file)) {
10781 *npages = nr_pages;
10783 ret = pret < 0 ? pret : -EFAULT;
10785 mmap_read_unlock(current->mm);
10788 * if we did partial map, or found file backed vmas,
10789 * release any pages we did get
10792 unpin_user_pages(pages, pret);
10800 pages = ERR_PTR(ret);
10805 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10806 struct io_mapped_ubuf **pimu,
10807 struct page **last_hpage)
10809 struct io_mapped_ubuf *imu = NULL;
10810 struct page **pages = NULL;
10813 int ret, nr_pages, i;
10815 if (!iov->iov_base) {
10816 *pimu = ctx->dummy_ubuf;
10823 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10825 if (IS_ERR(pages)) {
10826 ret = PTR_ERR(pages);
10831 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10835 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10837 unpin_user_pages(pages, nr_pages);
10841 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10842 size = iov->iov_len;
10843 for (i = 0; i < nr_pages; i++) {
10846 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10847 imu->bvec[i].bv_page = pages[i];
10848 imu->bvec[i].bv_len = vec_len;
10849 imu->bvec[i].bv_offset = off;
10853 /* store original address for later verification */
10854 imu->ubuf = (unsigned long) iov->iov_base;
10855 imu->ubuf_end = imu->ubuf + iov->iov_len;
10856 imu->nr_bvecs = nr_pages;
10866 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10868 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10869 return ctx->user_bufs ? 0 : -ENOMEM;
10872 static int io_buffer_validate(struct iovec *iov)
10874 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10877 * Don't impose further limits on the size and buffer
10878 * constraints here, we'll -EINVAL later when IO is
10879 * submitted if they are wrong.
10881 if (!iov->iov_base)
10882 return iov->iov_len ? -EFAULT : 0;
10886 /* arbitrary limit, but we need something */
10887 if (iov->iov_len > SZ_1G)
10890 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10896 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10897 unsigned int nr_args, u64 __user *tags)
10899 struct page *last_hpage = NULL;
10900 struct io_rsrc_data *data;
10904 if (ctx->user_bufs)
10906 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10908 ret = io_rsrc_node_switch_start(ctx);
10911 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10914 ret = io_buffers_map_alloc(ctx, nr_args);
10916 io_rsrc_data_free(data);
10920 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10922 ret = io_copy_iov(ctx, &iov, arg, i);
10925 ret = io_buffer_validate(&iov);
10929 memset(&iov, 0, sizeof(iov));
10932 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10937 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10943 WARN_ON_ONCE(ctx->buf_data);
10945 ctx->buf_data = data;
10947 __io_sqe_buffers_unregister(ctx);
10949 io_rsrc_node_switch(ctx, NULL);
10953 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10954 struct io_uring_rsrc_update2 *up,
10955 unsigned int nr_args)
10957 u64 __user *tags = u64_to_user_ptr(up->tags);
10958 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10959 struct page *last_hpage = NULL;
10960 bool needs_switch = false;
10964 if (!ctx->buf_data)
10966 if (up->offset + nr_args > ctx->nr_user_bufs)
10969 for (done = 0; done < nr_args; done++) {
10970 struct io_mapped_ubuf *imu;
10971 int offset = up->offset + done;
10974 err = io_copy_iov(ctx, &iov, iovs, done);
10977 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10981 err = io_buffer_validate(&iov);
10984 if (!iov.iov_base && tag) {
10988 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10992 i = array_index_nospec(offset, ctx->nr_user_bufs);
10993 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10994 err = io_queue_rsrc_removal(ctx->buf_data, i,
10995 ctx->rsrc_node, ctx->user_bufs[i]);
10996 if (unlikely(err)) {
10997 io_buffer_unmap(ctx, &imu);
11000 ctx->user_bufs[i] = NULL;
11001 needs_switch = true;
11004 ctx->user_bufs[i] = imu;
11005 *io_get_tag_slot(ctx->buf_data, offset) = tag;
11009 io_rsrc_node_switch(ctx, ctx->buf_data);
11010 return done ? done : err;
11013 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
11014 unsigned int eventfd_async)
11016 struct io_ev_fd *ev_fd;
11017 __s32 __user *fds = arg;
11020 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11021 lockdep_is_held(&ctx->uring_lock));
11025 if (copy_from_user(&fd, fds, sizeof(*fds)))
11028 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
11032 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
11033 if (IS_ERR(ev_fd->cq_ev_fd)) {
11034 int ret = PTR_ERR(ev_fd->cq_ev_fd);
11038 ev_fd->eventfd_async = eventfd_async;
11039 ctx->has_evfd = true;
11040 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
11044 static void io_eventfd_put(struct rcu_head *rcu)
11046 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
11048 eventfd_ctx_put(ev_fd->cq_ev_fd);
11052 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
11054 struct io_ev_fd *ev_fd;
11056 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11057 lockdep_is_held(&ctx->uring_lock));
11059 ctx->has_evfd = false;
11060 rcu_assign_pointer(ctx->io_ev_fd, NULL);
11061 call_rcu(&ev_fd->rcu, io_eventfd_put);
11068 static void io_destroy_buffers(struct io_ring_ctx *ctx)
11070 struct io_buffer_list *bl;
11071 unsigned long index;
11074 for (i = 0; i < BGID_ARRAY; i++) {
11077 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
11080 xa_for_each(&ctx->io_bl_xa, index, bl) {
11081 xa_erase(&ctx->io_bl_xa, bl->bgid);
11082 __io_remove_buffers(ctx, bl, -1U);
11086 while (!list_empty(&ctx->io_buffers_pages)) {
11089 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
11090 list_del_init(&page->lru);
11095 static void io_req_caches_free(struct io_ring_ctx *ctx)
11097 struct io_submit_state *state = &ctx->submit_state;
11100 mutex_lock(&ctx->uring_lock);
11101 io_flush_cached_locked_reqs(ctx, state);
11103 while (!io_req_cache_empty(ctx)) {
11104 struct io_wq_work_node *node;
11105 struct io_kiocb *req;
11107 node = wq_stack_extract(&state->free_list);
11108 req = container_of(node, struct io_kiocb, comp_list);
11109 kmem_cache_free(req_cachep, req);
11113 percpu_ref_put_many(&ctx->refs, nr);
11114 mutex_unlock(&ctx->uring_lock);
11117 static void io_wait_rsrc_data(struct io_rsrc_data *data)
11119 if (data && !atomic_dec_and_test(&data->refs))
11120 wait_for_completion(&data->done);
11123 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
11125 struct async_poll *apoll;
11127 while (!list_empty(&ctx->apoll_cache)) {
11128 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
11130 list_del(&apoll->poll.wait.entry);
11135 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
11137 io_sq_thread_finish(ctx);
11139 if (ctx->mm_account) {
11140 mmdrop(ctx->mm_account);
11141 ctx->mm_account = NULL;
11144 io_rsrc_refs_drop(ctx);
11145 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
11146 io_wait_rsrc_data(ctx->buf_data);
11147 io_wait_rsrc_data(ctx->file_data);
11149 mutex_lock(&ctx->uring_lock);
11151 __io_sqe_buffers_unregister(ctx);
11152 if (ctx->file_data)
11153 __io_sqe_files_unregister(ctx);
11155 __io_cqring_overflow_flush(ctx, true);
11156 io_eventfd_unregister(ctx);
11157 io_flush_apoll_cache(ctx);
11158 mutex_unlock(&ctx->uring_lock);
11159 io_destroy_buffers(ctx);
11161 put_cred(ctx->sq_creds);
11163 /* there are no registered resources left, nobody uses it */
11164 if (ctx->rsrc_node)
11165 io_rsrc_node_destroy(ctx->rsrc_node);
11166 if (ctx->rsrc_backup_node)
11167 io_rsrc_node_destroy(ctx->rsrc_backup_node);
11168 flush_delayed_work(&ctx->rsrc_put_work);
11169 flush_delayed_work(&ctx->fallback_work);
11171 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
11172 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
11174 #if defined(CONFIG_UNIX)
11175 if (ctx->ring_sock) {
11176 ctx->ring_sock->file = NULL; /* so that iput() is called */
11177 sock_release(ctx->ring_sock);
11180 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
11182 io_mem_free(ctx->rings);
11183 io_mem_free(ctx->sq_sqes);
11185 percpu_ref_exit(&ctx->refs);
11186 free_uid(ctx->user);
11187 io_req_caches_free(ctx);
11189 io_wq_put_hash(ctx->hash_map);
11190 kfree(ctx->cancel_hash);
11191 kfree(ctx->dummy_ubuf);
11193 xa_destroy(&ctx->io_bl_xa);
11197 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
11199 struct io_ring_ctx *ctx = file->private_data;
11202 poll_wait(file, &ctx->cq_wait, wait);
11204 * synchronizes with barrier from wq_has_sleeper call in
11208 if (!io_sqring_full(ctx))
11209 mask |= EPOLLOUT | EPOLLWRNORM;
11212 * Don't flush cqring overflow list here, just do a simple check.
11213 * Otherwise there could possible be ABBA deadlock:
11216 * lock(&ctx->uring_lock);
11218 * lock(&ctx->uring_lock);
11221 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
11222 * pushs them to do the flush.
11224 if (io_cqring_events(ctx) ||
11225 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
11226 mask |= EPOLLIN | EPOLLRDNORM;
11231 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
11233 const struct cred *creds;
11235 creds = xa_erase(&ctx->personalities, id);
11244 struct io_tctx_exit {
11245 struct callback_head task_work;
11246 struct completion completion;
11247 struct io_ring_ctx *ctx;
11250 static __cold void io_tctx_exit_cb(struct callback_head *cb)
11252 struct io_uring_task *tctx = current->io_uring;
11253 struct io_tctx_exit *work;
11255 work = container_of(cb, struct io_tctx_exit, task_work);
11257 * When @in_idle, we're in cancellation and it's racy to remove the
11258 * node. It'll be removed by the end of cancellation, just ignore it.
11260 if (!atomic_read(&tctx->in_idle))
11261 io_uring_del_tctx_node((unsigned long)work->ctx);
11262 complete(&work->completion);
11265 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
11267 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11269 return req->ctx == data;
11272 static __cold void io_ring_exit_work(struct work_struct *work)
11274 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
11275 unsigned long timeout = jiffies + HZ * 60 * 5;
11276 unsigned long interval = HZ / 20;
11277 struct io_tctx_exit exit;
11278 struct io_tctx_node *node;
11282 * If we're doing polled IO and end up having requests being
11283 * submitted async (out-of-line), then completions can come in while
11284 * we're waiting for refs to drop. We need to reap these manually,
11285 * as nobody else will be looking for them.
11288 io_uring_try_cancel_requests(ctx, NULL, true);
11289 if (ctx->sq_data) {
11290 struct io_sq_data *sqd = ctx->sq_data;
11291 struct task_struct *tsk;
11293 io_sq_thread_park(sqd);
11295 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
11296 io_wq_cancel_cb(tsk->io_uring->io_wq,
11297 io_cancel_ctx_cb, ctx, true);
11298 io_sq_thread_unpark(sqd);
11301 io_req_caches_free(ctx);
11303 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
11304 /* there is little hope left, don't run it too often */
11305 interval = HZ * 60;
11307 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
11309 init_completion(&exit.completion);
11310 init_task_work(&exit.task_work, io_tctx_exit_cb);
11313 * Some may use context even when all refs and requests have been put,
11314 * and they are free to do so while still holding uring_lock or
11315 * completion_lock, see io_req_task_submit(). Apart from other work,
11316 * this lock/unlock section also waits them to finish.
11318 mutex_lock(&ctx->uring_lock);
11319 while (!list_empty(&ctx->tctx_list)) {
11320 WARN_ON_ONCE(time_after(jiffies, timeout));
11322 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
11324 /* don't spin on a single task if cancellation failed */
11325 list_rotate_left(&ctx->tctx_list);
11326 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
11327 if (WARN_ON_ONCE(ret))
11330 mutex_unlock(&ctx->uring_lock);
11331 wait_for_completion(&exit.completion);
11332 mutex_lock(&ctx->uring_lock);
11334 mutex_unlock(&ctx->uring_lock);
11335 spin_lock(&ctx->completion_lock);
11336 spin_unlock(&ctx->completion_lock);
11338 io_ring_ctx_free(ctx);
11341 /* Returns true if we found and killed one or more timeouts */
11342 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
11343 struct task_struct *tsk, bool cancel_all)
11345 struct io_kiocb *req, *tmp;
11348 spin_lock(&ctx->completion_lock);
11349 spin_lock_irq(&ctx->timeout_lock);
11350 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11351 if (io_match_task(req, tsk, cancel_all)) {
11352 io_kill_timeout(req, -ECANCELED);
11356 spin_unlock_irq(&ctx->timeout_lock);
11357 io_commit_cqring(ctx);
11358 spin_unlock(&ctx->completion_lock);
11360 io_cqring_ev_posted(ctx);
11361 return canceled != 0;
11364 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11366 unsigned long index;
11367 struct creds *creds;
11369 mutex_lock(&ctx->uring_lock);
11370 percpu_ref_kill(&ctx->refs);
11372 __io_cqring_overflow_flush(ctx, true);
11373 xa_for_each(&ctx->personalities, index, creds)
11374 io_unregister_personality(ctx, index);
11375 mutex_unlock(&ctx->uring_lock);
11377 /* failed during ring init, it couldn't have issued any requests */
11379 io_kill_timeouts(ctx, NULL, true);
11380 io_poll_remove_all(ctx, NULL, true);
11381 /* if we failed setting up the ctx, we might not have any rings */
11382 io_iopoll_try_reap_events(ctx);
11385 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11387 * Use system_unbound_wq to avoid spawning tons of event kworkers
11388 * if we're exiting a ton of rings at the same time. It just adds
11389 * noise and overhead, there's no discernable change in runtime
11390 * over using system_wq.
11392 queue_work(system_unbound_wq, &ctx->exit_work);
11395 static int io_uring_release(struct inode *inode, struct file *file)
11397 struct io_ring_ctx *ctx = file->private_data;
11399 file->private_data = NULL;
11400 io_ring_ctx_wait_and_kill(ctx);
11404 struct io_task_cancel {
11405 struct task_struct *task;
11409 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11411 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11412 struct io_task_cancel *cancel = data;
11414 return io_match_task_safe(req, cancel->task, cancel->all);
11417 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11418 struct task_struct *task,
11421 struct io_defer_entry *de;
11424 spin_lock(&ctx->completion_lock);
11425 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11426 if (io_match_task_safe(de->req, task, cancel_all)) {
11427 list_cut_position(&list, &ctx->defer_list, &de->list);
11431 spin_unlock(&ctx->completion_lock);
11432 if (list_empty(&list))
11435 while (!list_empty(&list)) {
11436 de = list_first_entry(&list, struct io_defer_entry, list);
11437 list_del_init(&de->list);
11438 io_req_complete_failed(de->req, -ECANCELED);
11444 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11446 struct io_tctx_node *node;
11447 enum io_wq_cancel cret;
11450 mutex_lock(&ctx->uring_lock);
11451 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11452 struct io_uring_task *tctx = node->task->io_uring;
11455 * io_wq will stay alive while we hold uring_lock, because it's
11456 * killed after ctx nodes, which requires to take the lock.
11458 if (!tctx || !tctx->io_wq)
11460 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11461 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11463 mutex_unlock(&ctx->uring_lock);
11468 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11469 struct task_struct *task,
11472 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11473 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11475 /* failed during ring init, it couldn't have issued any requests */
11480 enum io_wq_cancel cret;
11484 ret |= io_uring_try_cancel_iowq(ctx);
11485 } else if (tctx && tctx->io_wq) {
11487 * Cancels requests of all rings, not only @ctx, but
11488 * it's fine as the task is in exit/exec.
11490 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11492 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11495 /* SQPOLL thread does its own polling */
11496 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11497 (ctx->sq_data && ctx->sq_data->thread == current)) {
11498 while (!wq_list_empty(&ctx->iopoll_list)) {
11499 io_iopoll_try_reap_events(ctx);
11504 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11505 ret |= io_poll_remove_all(ctx, task, cancel_all);
11506 ret |= io_kill_timeouts(ctx, task, cancel_all);
11508 ret |= io_run_task_work();
11515 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11517 struct io_uring_task *tctx = current->io_uring;
11518 struct io_tctx_node *node;
11521 if (unlikely(!tctx)) {
11522 ret = io_uring_alloc_task_context(current, ctx);
11526 tctx = current->io_uring;
11527 if (ctx->iowq_limits_set) {
11528 unsigned int limits[2] = { ctx->iowq_limits[0],
11529 ctx->iowq_limits[1], };
11531 ret = io_wq_max_workers(tctx->io_wq, limits);
11536 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11537 node = kmalloc(sizeof(*node), GFP_KERNEL);
11541 node->task = current;
11543 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11544 node, GFP_KERNEL));
11550 mutex_lock(&ctx->uring_lock);
11551 list_add(&node->ctx_node, &ctx->tctx_list);
11552 mutex_unlock(&ctx->uring_lock);
11559 * Note that this task has used io_uring. We use it for cancelation purposes.
11561 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11563 struct io_uring_task *tctx = current->io_uring;
11565 if (likely(tctx && tctx->last == ctx))
11567 return __io_uring_add_tctx_node(ctx);
11571 * Remove this io_uring_file -> task mapping.
11573 static __cold void io_uring_del_tctx_node(unsigned long index)
11575 struct io_uring_task *tctx = current->io_uring;
11576 struct io_tctx_node *node;
11580 node = xa_erase(&tctx->xa, index);
11584 WARN_ON_ONCE(current != node->task);
11585 WARN_ON_ONCE(list_empty(&node->ctx_node));
11587 mutex_lock(&node->ctx->uring_lock);
11588 list_del(&node->ctx_node);
11589 mutex_unlock(&node->ctx->uring_lock);
11591 if (tctx->last == node->ctx)
11596 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11598 struct io_wq *wq = tctx->io_wq;
11599 struct io_tctx_node *node;
11600 unsigned long index;
11602 xa_for_each(&tctx->xa, index, node) {
11603 io_uring_del_tctx_node(index);
11608 * Must be after io_uring_del_tctx_node() (removes nodes under
11609 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11611 io_wq_put_and_exit(wq);
11612 tctx->io_wq = NULL;
11616 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11619 return atomic_read(&tctx->inflight_tracked);
11620 return percpu_counter_sum(&tctx->inflight);
11624 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11625 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11627 static __cold void io_uring_cancel_generic(bool cancel_all,
11628 struct io_sq_data *sqd)
11630 struct io_uring_task *tctx = current->io_uring;
11631 struct io_ring_ctx *ctx;
11635 WARN_ON_ONCE(sqd && sqd->thread != current);
11637 if (!current->io_uring)
11640 io_wq_exit_start(tctx->io_wq);
11642 atomic_inc(&tctx->in_idle);
11644 io_uring_drop_tctx_refs(current);
11645 /* read completions before cancelations */
11646 inflight = tctx_inflight(tctx, !cancel_all);
11651 struct io_tctx_node *node;
11652 unsigned long index;
11654 xa_for_each(&tctx->xa, index, node) {
11655 /* sqpoll task will cancel all its requests */
11656 if (node->ctx->sq_data)
11658 io_uring_try_cancel_requests(node->ctx, current,
11662 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11663 io_uring_try_cancel_requests(ctx, current,
11667 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11668 io_run_task_work();
11669 io_uring_drop_tctx_refs(current);
11672 * If we've seen completions, retry without waiting. This
11673 * avoids a race where a completion comes in before we did
11674 * prepare_to_wait().
11676 if (inflight == tctx_inflight(tctx, !cancel_all))
11678 finish_wait(&tctx->wait, &wait);
11681 io_uring_clean_tctx(tctx);
11684 * We shouldn't run task_works after cancel, so just leave
11685 * ->in_idle set for normal exit.
11687 atomic_dec(&tctx->in_idle);
11688 /* for exec all current's requests should be gone, kill tctx */
11689 __io_uring_free(current);
11693 void __io_uring_cancel(bool cancel_all)
11695 io_uring_cancel_generic(cancel_all, NULL);
11698 void io_uring_unreg_ringfd(void)
11700 struct io_uring_task *tctx = current->io_uring;
11703 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11704 if (tctx->registered_rings[i]) {
11705 fput(tctx->registered_rings[i]);
11706 tctx->registered_rings[i] = NULL;
11711 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11712 int start, int end)
11717 for (offset = start; offset < end; offset++) {
11718 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11719 if (tctx->registered_rings[offset])
11725 } else if (file->f_op != &io_uring_fops) {
11727 return -EOPNOTSUPP;
11729 tctx->registered_rings[offset] = file;
11737 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11738 * invocation. User passes in an array of struct io_uring_rsrc_update
11739 * with ->data set to the ring_fd, and ->offset given for the desired
11740 * index. If no index is desired, application may set ->offset == -1U
11741 * and we'll find an available index. Returns number of entries
11742 * successfully processed, or < 0 on error if none were processed.
11744 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11747 struct io_uring_rsrc_update __user *arg = __arg;
11748 struct io_uring_rsrc_update reg;
11749 struct io_uring_task *tctx;
11752 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11755 mutex_unlock(&ctx->uring_lock);
11756 ret = io_uring_add_tctx_node(ctx);
11757 mutex_lock(&ctx->uring_lock);
11761 tctx = current->io_uring;
11762 for (i = 0; i < nr_args; i++) {
11765 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11775 if (reg.offset == -1U) {
11777 end = IO_RINGFD_REG_MAX;
11779 if (reg.offset >= IO_RINGFD_REG_MAX) {
11783 start = reg.offset;
11787 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11792 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11793 fput(tctx->registered_rings[reg.offset]);
11794 tctx->registered_rings[reg.offset] = NULL;
11800 return i ? i : ret;
11803 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11806 struct io_uring_rsrc_update __user *arg = __arg;
11807 struct io_uring_task *tctx = current->io_uring;
11808 struct io_uring_rsrc_update reg;
11811 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11816 for (i = 0; i < nr_args; i++) {
11817 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11821 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11826 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11827 if (tctx->registered_rings[reg.offset]) {
11828 fput(tctx->registered_rings[reg.offset]);
11829 tctx->registered_rings[reg.offset] = NULL;
11833 return i ? i : ret;
11836 static void *io_uring_validate_mmap_request(struct file *file,
11837 loff_t pgoff, size_t sz)
11839 struct io_ring_ctx *ctx = file->private_data;
11840 loff_t offset = pgoff << PAGE_SHIFT;
11845 case IORING_OFF_SQ_RING:
11846 case IORING_OFF_CQ_RING:
11849 case IORING_OFF_SQES:
11850 ptr = ctx->sq_sqes;
11853 return ERR_PTR(-EINVAL);
11856 page = virt_to_head_page(ptr);
11857 if (sz > page_size(page))
11858 return ERR_PTR(-EINVAL);
11865 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11867 size_t sz = vma->vm_end - vma->vm_start;
11871 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11873 return PTR_ERR(ptr);
11875 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11876 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11879 #else /* !CONFIG_MMU */
11881 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11883 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11886 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11888 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11891 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11892 unsigned long addr, unsigned long len,
11893 unsigned long pgoff, unsigned long flags)
11897 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11899 return PTR_ERR(ptr);
11901 return (unsigned long) ptr;
11904 #endif /* !CONFIG_MMU */
11906 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11911 if (!io_sqring_full(ctx))
11913 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11915 if (!io_sqring_full(ctx))
11918 } while (!signal_pending(current));
11920 finish_wait(&ctx->sqo_sq_wait, &wait);
11924 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11926 if (flags & IORING_ENTER_EXT_ARG) {
11927 struct io_uring_getevents_arg arg;
11929 if (argsz != sizeof(arg))
11931 if (copy_from_user(&arg, argp, sizeof(arg)))
11937 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11938 struct __kernel_timespec __user **ts,
11939 const sigset_t __user **sig)
11941 struct io_uring_getevents_arg arg;
11944 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11945 * is just a pointer to the sigset_t.
11947 if (!(flags & IORING_ENTER_EXT_ARG)) {
11948 *sig = (const sigset_t __user *) argp;
11954 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11955 * timespec and sigset_t pointers if good.
11957 if (*argsz != sizeof(arg))
11959 if (copy_from_user(&arg, argp, sizeof(arg)))
11963 *sig = u64_to_user_ptr(arg.sigmask);
11964 *argsz = arg.sigmask_sz;
11965 *ts = u64_to_user_ptr(arg.ts);
11969 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11970 u32, min_complete, u32, flags, const void __user *, argp,
11973 struct io_ring_ctx *ctx;
11977 io_run_task_work();
11979 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11980 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11981 IORING_ENTER_REGISTERED_RING)))
11985 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11986 * need only dereference our task private array to find it.
11988 if (flags & IORING_ENTER_REGISTERED_RING) {
11989 struct io_uring_task *tctx = current->io_uring;
11991 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11993 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11994 f.file = tctx->registered_rings[fd];
12000 if (unlikely(!f.file))
12004 if (unlikely(f.file->f_op != &io_uring_fops))
12008 ctx = f.file->private_data;
12009 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
12013 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
12017 * For SQ polling, the thread will do all submissions and completions.
12018 * Just return the requested submit count, and wake the thread if
12019 * we were asked to.
12022 if (ctx->flags & IORING_SETUP_SQPOLL) {
12023 io_cqring_overflow_flush(ctx);
12025 if (unlikely(ctx->sq_data->thread == NULL)) {
12029 if (flags & IORING_ENTER_SQ_WAKEUP)
12030 wake_up(&ctx->sq_data->wait);
12031 if (flags & IORING_ENTER_SQ_WAIT) {
12032 ret = io_sqpoll_wait_sq(ctx);
12037 } else if (to_submit) {
12038 ret = io_uring_add_tctx_node(ctx);
12042 mutex_lock(&ctx->uring_lock);
12043 ret = io_submit_sqes(ctx, to_submit);
12044 if (ret != to_submit) {
12045 mutex_unlock(&ctx->uring_lock);
12048 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
12049 goto iopoll_locked;
12050 mutex_unlock(&ctx->uring_lock);
12052 if (flags & IORING_ENTER_GETEVENTS) {
12054 if (ctx->syscall_iopoll) {
12056 * We disallow the app entering submit/complete with
12057 * polling, but we still need to lock the ring to
12058 * prevent racing with polled issue that got punted to
12061 mutex_lock(&ctx->uring_lock);
12063 ret2 = io_validate_ext_arg(flags, argp, argsz);
12064 if (likely(!ret2)) {
12065 min_complete = min(min_complete,
12067 ret2 = io_iopoll_check(ctx, min_complete);
12069 mutex_unlock(&ctx->uring_lock);
12071 const sigset_t __user *sig;
12072 struct __kernel_timespec __user *ts;
12074 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
12075 if (likely(!ret2)) {
12076 min_complete = min(min_complete,
12078 ret2 = io_cqring_wait(ctx, min_complete, sig,
12087 * EBADR indicates that one or more CQE were dropped.
12088 * Once the user has been informed we can clear the bit
12089 * as they are obviously ok with those drops.
12091 if (unlikely(ret2 == -EBADR))
12092 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
12098 percpu_ref_put(&ctx->refs);
12104 #ifdef CONFIG_PROC_FS
12105 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
12106 const struct cred *cred)
12108 struct user_namespace *uns = seq_user_ns(m);
12109 struct group_info *gi;
12114 seq_printf(m, "%5d\n", id);
12115 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
12116 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
12117 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
12118 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
12119 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
12120 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
12121 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
12122 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
12123 seq_puts(m, "\n\tGroups:\t");
12124 gi = cred->group_info;
12125 for (g = 0; g < gi->ngroups; g++) {
12126 seq_put_decimal_ull(m, g ? " " : "",
12127 from_kgid_munged(uns, gi->gid[g]));
12129 seq_puts(m, "\n\tCapEff:\t");
12130 cap = cred->cap_effective;
12131 CAP_FOR_EACH_U32(__capi)
12132 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
12137 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
12138 struct seq_file *m)
12140 struct io_sq_data *sq = NULL;
12141 struct io_overflow_cqe *ocqe;
12142 struct io_rings *r = ctx->rings;
12143 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
12144 unsigned int sq_head = READ_ONCE(r->sq.head);
12145 unsigned int sq_tail = READ_ONCE(r->sq.tail);
12146 unsigned int cq_head = READ_ONCE(r->cq.head);
12147 unsigned int cq_tail = READ_ONCE(r->cq.tail);
12148 unsigned int cq_shift = 0;
12149 unsigned int sq_entries, cq_entries;
12151 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
12158 * we may get imprecise sqe and cqe info if uring is actively running
12159 * since we get cached_sq_head and cached_cq_tail without uring_lock
12160 * and sq_tail and cq_head are changed by userspace. But it's ok since
12161 * we usually use these info when it is stuck.
12163 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
12164 seq_printf(m, "SqHead:\t%u\n", sq_head);
12165 seq_printf(m, "SqTail:\t%u\n", sq_tail);
12166 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
12167 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
12168 seq_printf(m, "CqHead:\t%u\n", cq_head);
12169 seq_printf(m, "CqTail:\t%u\n", cq_tail);
12170 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
12171 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
12172 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
12173 for (i = 0; i < sq_entries; i++) {
12174 unsigned int entry = i + sq_head;
12175 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
12176 struct io_uring_sqe *sqe;
12178 if (sq_idx > sq_mask)
12180 sqe = &ctx->sq_sqes[sq_idx];
12181 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
12182 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
12185 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
12186 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
12187 for (i = 0; i < cq_entries; i++) {
12188 unsigned int entry = i + cq_head;
12189 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
12192 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
12193 entry & cq_mask, cqe->user_data, cqe->res,
12196 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
12197 "extra1:%llu, extra2:%llu\n",
12198 entry & cq_mask, cqe->user_data, cqe->res,
12199 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
12204 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
12205 * since fdinfo case grabs it in the opposite direction of normal use
12206 * cases. If we fail to get the lock, we just don't iterate any
12207 * structures that could be going away outside the io_uring mutex.
12209 has_lock = mutex_trylock(&ctx->uring_lock);
12211 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
12217 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
12218 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
12219 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
12220 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
12221 struct file *f = io_file_from_index(ctx, i);
12224 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
12226 seq_printf(m, "%5u: <none>\n", i);
12228 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
12229 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
12230 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
12231 unsigned int len = buf->ubuf_end - buf->ubuf;
12233 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
12235 if (has_lock && !xa_empty(&ctx->personalities)) {
12236 unsigned long index;
12237 const struct cred *cred;
12239 seq_printf(m, "Personalities:\n");
12240 xa_for_each(&ctx->personalities, index, cred)
12241 io_uring_show_cred(m, index, cred);
12244 mutex_unlock(&ctx->uring_lock);
12246 seq_puts(m, "PollList:\n");
12247 spin_lock(&ctx->completion_lock);
12248 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
12249 struct hlist_head *list = &ctx->cancel_hash[i];
12250 struct io_kiocb *req;
12252 hlist_for_each_entry(req, list, hash_node)
12253 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
12254 task_work_pending(req->task));
12257 seq_puts(m, "CqOverflowList:\n");
12258 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
12259 struct io_uring_cqe *cqe = &ocqe->cqe;
12261 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
12262 cqe->user_data, cqe->res, cqe->flags);
12266 spin_unlock(&ctx->completion_lock);
12269 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
12271 struct io_ring_ctx *ctx = f->private_data;
12273 if (percpu_ref_tryget(&ctx->refs)) {
12274 __io_uring_show_fdinfo(ctx, m);
12275 percpu_ref_put(&ctx->refs);
12280 static const struct file_operations io_uring_fops = {
12281 .release = io_uring_release,
12282 .mmap = io_uring_mmap,
12284 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
12285 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
12287 .poll = io_uring_poll,
12288 #ifdef CONFIG_PROC_FS
12289 .show_fdinfo = io_uring_show_fdinfo,
12293 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
12294 struct io_uring_params *p)
12296 struct io_rings *rings;
12297 size_t size, sq_array_offset;
12299 /* make sure these are sane, as we already accounted them */
12300 ctx->sq_entries = p->sq_entries;
12301 ctx->cq_entries = p->cq_entries;
12303 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
12304 if (size == SIZE_MAX)
12307 rings = io_mem_alloc(size);
12311 ctx->rings = rings;
12312 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
12313 rings->sq_ring_mask = p->sq_entries - 1;
12314 rings->cq_ring_mask = p->cq_entries - 1;
12315 rings->sq_ring_entries = p->sq_entries;
12316 rings->cq_ring_entries = p->cq_entries;
12318 if (p->flags & IORING_SETUP_SQE128)
12319 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
12321 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
12322 if (size == SIZE_MAX) {
12323 io_mem_free(ctx->rings);
12328 ctx->sq_sqes = io_mem_alloc(size);
12329 if (!ctx->sq_sqes) {
12330 io_mem_free(ctx->rings);
12338 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
12342 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
12346 ret = io_uring_add_tctx_node(ctx);
12351 fd_install(fd, file);
12356 * Allocate an anonymous fd, this is what constitutes the application
12357 * visible backing of an io_uring instance. The application mmaps this
12358 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12359 * we have to tie this fd to a socket for file garbage collection purposes.
12361 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12364 #if defined(CONFIG_UNIX)
12367 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12370 return ERR_PTR(ret);
12373 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12374 O_RDWR | O_CLOEXEC, NULL);
12375 #if defined(CONFIG_UNIX)
12376 if (IS_ERR(file)) {
12377 sock_release(ctx->ring_sock);
12378 ctx->ring_sock = NULL;
12380 ctx->ring_sock->file = file;
12386 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12387 struct io_uring_params __user *params)
12389 struct io_ring_ctx *ctx;
12395 if (entries > IORING_MAX_ENTRIES) {
12396 if (!(p->flags & IORING_SETUP_CLAMP))
12398 entries = IORING_MAX_ENTRIES;
12402 * Use twice as many entries for the CQ ring. It's possible for the
12403 * application to drive a higher depth than the size of the SQ ring,
12404 * since the sqes are only used at submission time. This allows for
12405 * some flexibility in overcommitting a bit. If the application has
12406 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12407 * of CQ ring entries manually.
12409 p->sq_entries = roundup_pow_of_two(entries);
12410 if (p->flags & IORING_SETUP_CQSIZE) {
12412 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12413 * to a power-of-two, if it isn't already. We do NOT impose
12414 * any cq vs sq ring sizing.
12416 if (!p->cq_entries)
12418 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12419 if (!(p->flags & IORING_SETUP_CLAMP))
12421 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12423 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12424 if (p->cq_entries < p->sq_entries)
12427 p->cq_entries = 2 * p->sq_entries;
12430 ctx = io_ring_ctx_alloc(p);
12435 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12436 * space applications don't need to do io completion events
12437 * polling again, they can rely on io_sq_thread to do polling
12438 * work, which can reduce cpu usage and uring_lock contention.
12440 if (ctx->flags & IORING_SETUP_IOPOLL &&
12441 !(ctx->flags & IORING_SETUP_SQPOLL))
12442 ctx->syscall_iopoll = 1;
12444 ctx->compat = in_compat_syscall();
12445 if (!capable(CAP_IPC_LOCK))
12446 ctx->user = get_uid(current_user());
12449 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12450 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12453 if (ctx->flags & IORING_SETUP_SQPOLL) {
12454 /* IPI related flags don't make sense with SQPOLL */
12455 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12456 IORING_SETUP_TASKRUN_FLAG))
12458 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12459 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12460 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12462 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12464 ctx->notify_method = TWA_SIGNAL;
12468 * This is just grabbed for accounting purposes. When a process exits,
12469 * the mm is exited and dropped before the files, hence we need to hang
12470 * on to this mm purely for the purposes of being able to unaccount
12471 * memory (locked/pinned vm). It's not used for anything else.
12473 mmgrab(current->mm);
12474 ctx->mm_account = current->mm;
12476 ret = io_allocate_scq_urings(ctx, p);
12480 ret = io_sq_offload_create(ctx, p);
12483 /* always set a rsrc node */
12484 ret = io_rsrc_node_switch_start(ctx);
12487 io_rsrc_node_switch(ctx, NULL);
12489 memset(&p->sq_off, 0, sizeof(p->sq_off));
12490 p->sq_off.head = offsetof(struct io_rings, sq.head);
12491 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12492 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12493 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12494 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12495 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12496 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12498 memset(&p->cq_off, 0, sizeof(p->cq_off));
12499 p->cq_off.head = offsetof(struct io_rings, cq.head);
12500 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12501 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12502 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12503 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12504 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12505 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12507 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12508 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12509 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12510 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12511 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12512 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12513 IORING_FEAT_LINKED_FILE;
12515 if (copy_to_user(params, p, sizeof(*p))) {
12520 file = io_uring_get_file(ctx);
12521 if (IS_ERR(file)) {
12522 ret = PTR_ERR(file);
12527 * Install ring fd as the very last thing, so we don't risk someone
12528 * having closed it before we finish setup
12530 ret = io_uring_install_fd(ctx, file);
12532 /* fput will clean it up */
12537 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12540 io_ring_ctx_wait_and_kill(ctx);
12545 * Sets up an aio uring context, and returns the fd. Applications asks for a
12546 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12547 * params structure passed in.
12549 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12551 struct io_uring_params p;
12554 if (copy_from_user(&p, params, sizeof(p)))
12556 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12561 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12562 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12563 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12564 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12565 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12566 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12569 return io_uring_create(entries, &p, params);
12572 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12573 struct io_uring_params __user *, params)
12575 return io_uring_setup(entries, params);
12578 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12581 struct io_uring_probe *p;
12585 size = struct_size(p, ops, nr_args);
12586 if (size == SIZE_MAX)
12588 p = kzalloc(size, GFP_KERNEL);
12593 if (copy_from_user(p, arg, size))
12596 if (memchr_inv(p, 0, size))
12599 p->last_op = IORING_OP_LAST - 1;
12600 if (nr_args > IORING_OP_LAST)
12601 nr_args = IORING_OP_LAST;
12603 for (i = 0; i < nr_args; i++) {
12605 if (!io_op_defs[i].not_supported)
12606 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12611 if (copy_to_user(arg, p, size))
12618 static int io_register_personality(struct io_ring_ctx *ctx)
12620 const struct cred *creds;
12624 creds = get_current_cred();
12626 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12627 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12635 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12636 void __user *arg, unsigned int nr_args)
12638 struct io_uring_restriction *res;
12642 /* Restrictions allowed only if rings started disabled */
12643 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12646 /* We allow only a single restrictions registration */
12647 if (ctx->restrictions.registered)
12650 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12653 size = array_size(nr_args, sizeof(*res));
12654 if (size == SIZE_MAX)
12657 res = memdup_user(arg, size);
12659 return PTR_ERR(res);
12663 for (i = 0; i < nr_args; i++) {
12664 switch (res[i].opcode) {
12665 case IORING_RESTRICTION_REGISTER_OP:
12666 if (res[i].register_op >= IORING_REGISTER_LAST) {
12671 __set_bit(res[i].register_op,
12672 ctx->restrictions.register_op);
12674 case IORING_RESTRICTION_SQE_OP:
12675 if (res[i].sqe_op >= IORING_OP_LAST) {
12680 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12682 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12683 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12685 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12686 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12695 /* Reset all restrictions if an error happened */
12697 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12699 ctx->restrictions.registered = true;
12705 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12707 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12710 if (ctx->restrictions.registered)
12711 ctx->restricted = 1;
12713 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12714 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12715 wake_up(&ctx->sq_data->wait);
12719 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12720 struct io_uring_rsrc_update2 *up,
12726 if (check_add_overflow(up->offset, nr_args, &tmp))
12728 err = io_rsrc_node_switch_start(ctx);
12733 case IORING_RSRC_FILE:
12734 return __io_sqe_files_update(ctx, up, nr_args);
12735 case IORING_RSRC_BUFFER:
12736 return __io_sqe_buffers_update(ctx, up, nr_args);
12741 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12744 struct io_uring_rsrc_update2 up;
12748 memset(&up, 0, sizeof(up));
12749 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12751 if (up.resv || up.resv2)
12753 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12756 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12757 unsigned size, unsigned type)
12759 struct io_uring_rsrc_update2 up;
12761 if (size != sizeof(up))
12763 if (copy_from_user(&up, arg, sizeof(up)))
12765 if (!up.nr || up.resv || up.resv2)
12767 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12770 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12771 unsigned int size, unsigned int type)
12773 struct io_uring_rsrc_register rr;
12775 /* keep it extendible */
12776 if (size != sizeof(rr))
12779 memset(&rr, 0, sizeof(rr));
12780 if (copy_from_user(&rr, arg, size))
12782 if (!rr.nr || rr.resv2)
12784 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12788 case IORING_RSRC_FILE:
12789 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12791 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12792 rr.nr, u64_to_user_ptr(rr.tags));
12793 case IORING_RSRC_BUFFER:
12794 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12796 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12797 rr.nr, u64_to_user_ptr(rr.tags));
12802 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12803 void __user *arg, unsigned len)
12805 struct io_uring_task *tctx = current->io_uring;
12806 cpumask_var_t new_mask;
12809 if (!tctx || !tctx->io_wq)
12812 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12815 cpumask_clear(new_mask);
12816 if (len > cpumask_size())
12817 len = cpumask_size();
12819 if (in_compat_syscall()) {
12820 ret = compat_get_bitmap(cpumask_bits(new_mask),
12821 (const compat_ulong_t __user *)arg,
12822 len * 8 /* CHAR_BIT */);
12824 ret = copy_from_user(new_mask, arg, len);
12828 free_cpumask_var(new_mask);
12832 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12833 free_cpumask_var(new_mask);
12837 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12839 struct io_uring_task *tctx = current->io_uring;
12841 if (!tctx || !tctx->io_wq)
12844 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12847 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12849 __must_hold(&ctx->uring_lock)
12851 struct io_tctx_node *node;
12852 struct io_uring_task *tctx = NULL;
12853 struct io_sq_data *sqd = NULL;
12854 __u32 new_count[2];
12857 if (copy_from_user(new_count, arg, sizeof(new_count)))
12859 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12860 if (new_count[i] > INT_MAX)
12863 if (ctx->flags & IORING_SETUP_SQPOLL) {
12864 sqd = ctx->sq_data;
12867 * Observe the correct sqd->lock -> ctx->uring_lock
12868 * ordering. Fine to drop uring_lock here, we hold
12869 * a ref to the ctx.
12871 refcount_inc(&sqd->refs);
12872 mutex_unlock(&ctx->uring_lock);
12873 mutex_lock(&sqd->lock);
12874 mutex_lock(&ctx->uring_lock);
12876 tctx = sqd->thread->io_uring;
12879 tctx = current->io_uring;
12882 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12884 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12886 ctx->iowq_limits[i] = new_count[i];
12887 ctx->iowq_limits_set = true;
12889 if (tctx && tctx->io_wq) {
12890 ret = io_wq_max_workers(tctx->io_wq, new_count);
12894 memset(new_count, 0, sizeof(new_count));
12898 mutex_unlock(&sqd->lock);
12899 io_put_sq_data(sqd);
12902 if (copy_to_user(arg, new_count, sizeof(new_count)))
12905 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12909 /* now propagate the restriction to all registered users */
12910 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12911 struct io_uring_task *tctx = node->task->io_uring;
12913 if (WARN_ON_ONCE(!tctx->io_wq))
12916 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12917 new_count[i] = ctx->iowq_limits[i];
12918 /* ignore errors, it always returns zero anyway */
12919 (void)io_wq_max_workers(tctx->io_wq, new_count);
12924 mutex_unlock(&sqd->lock);
12925 io_put_sq_data(sqd);
12930 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12932 struct io_uring_buf_ring *br;
12933 struct io_uring_buf_reg reg;
12934 struct io_buffer_list *bl;
12935 struct page **pages;
12938 if (copy_from_user(®, arg, sizeof(reg)))
12941 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12943 if (!reg.ring_addr)
12945 if (reg.ring_addr & ~PAGE_MASK)
12947 if (!is_power_of_2(reg.ring_entries))
12950 /* cannot disambiguate full vs empty due to head/tail size */
12951 if (reg.ring_entries >= 65536)
12954 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12955 int ret = io_init_bl_list(ctx);
12960 bl = io_buffer_get_list(ctx, reg.bgid);
12962 /* if mapped buffer ring OR classic exists, don't allow */
12963 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12966 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12971 pages = io_pin_pages(reg.ring_addr,
12972 struct_size(br, bufs, reg.ring_entries),
12974 if (IS_ERR(pages)) {
12976 return PTR_ERR(pages);
12979 br = page_address(pages[0]);
12980 bl->buf_pages = pages;
12981 bl->buf_nr_pages = nr_pages;
12982 bl->nr_entries = reg.ring_entries;
12984 bl->mask = reg.ring_entries - 1;
12985 io_buffer_add_list(ctx, bl, reg.bgid);
12989 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12991 struct io_uring_buf_reg reg;
12992 struct io_buffer_list *bl;
12994 if (copy_from_user(®, arg, sizeof(reg)))
12996 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12999 bl = io_buffer_get_list(ctx, reg.bgid);
13002 if (!bl->buf_nr_pages)
13005 __io_remove_buffers(ctx, bl, -1U);
13006 if (bl->bgid >= BGID_ARRAY) {
13007 xa_erase(&ctx->io_bl_xa, bl->bgid);
13013 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
13014 void __user *arg, unsigned nr_args)
13015 __releases(ctx->uring_lock)
13016 __acquires(ctx->uring_lock)
13021 * We're inside the ring mutex, if the ref is already dying, then
13022 * someone else killed the ctx or is already going through
13023 * io_uring_register().
13025 if (percpu_ref_is_dying(&ctx->refs))
13028 if (ctx->restricted) {
13029 if (opcode >= IORING_REGISTER_LAST)
13031 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
13032 if (!test_bit(opcode, ctx->restrictions.register_op))
13037 case IORING_REGISTER_BUFFERS:
13041 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
13043 case IORING_UNREGISTER_BUFFERS:
13045 if (arg || nr_args)
13047 ret = io_sqe_buffers_unregister(ctx);
13049 case IORING_REGISTER_FILES:
13053 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
13055 case IORING_UNREGISTER_FILES:
13057 if (arg || nr_args)
13059 ret = io_sqe_files_unregister(ctx);
13061 case IORING_REGISTER_FILES_UPDATE:
13062 ret = io_register_files_update(ctx, arg, nr_args);
13064 case IORING_REGISTER_EVENTFD:
13068 ret = io_eventfd_register(ctx, arg, 0);
13070 case IORING_REGISTER_EVENTFD_ASYNC:
13074 ret = io_eventfd_register(ctx, arg, 1);
13076 case IORING_UNREGISTER_EVENTFD:
13078 if (arg || nr_args)
13080 ret = io_eventfd_unregister(ctx);
13082 case IORING_REGISTER_PROBE:
13084 if (!arg || nr_args > 256)
13086 ret = io_probe(ctx, arg, nr_args);
13088 case IORING_REGISTER_PERSONALITY:
13090 if (arg || nr_args)
13092 ret = io_register_personality(ctx);
13094 case IORING_UNREGISTER_PERSONALITY:
13098 ret = io_unregister_personality(ctx, nr_args);
13100 case IORING_REGISTER_ENABLE_RINGS:
13102 if (arg || nr_args)
13104 ret = io_register_enable_rings(ctx);
13106 case IORING_REGISTER_RESTRICTIONS:
13107 ret = io_register_restrictions(ctx, arg, nr_args);
13109 case IORING_REGISTER_FILES2:
13110 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
13112 case IORING_REGISTER_FILES_UPDATE2:
13113 ret = io_register_rsrc_update(ctx, arg, nr_args,
13116 case IORING_REGISTER_BUFFERS2:
13117 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
13119 case IORING_REGISTER_BUFFERS_UPDATE:
13120 ret = io_register_rsrc_update(ctx, arg, nr_args,
13121 IORING_RSRC_BUFFER);
13123 case IORING_REGISTER_IOWQ_AFF:
13125 if (!arg || !nr_args)
13127 ret = io_register_iowq_aff(ctx, arg, nr_args);
13129 case IORING_UNREGISTER_IOWQ_AFF:
13131 if (arg || nr_args)
13133 ret = io_unregister_iowq_aff(ctx);
13135 case IORING_REGISTER_IOWQ_MAX_WORKERS:
13137 if (!arg || nr_args != 2)
13139 ret = io_register_iowq_max_workers(ctx, arg);
13141 case IORING_REGISTER_RING_FDS:
13142 ret = io_ringfd_register(ctx, arg, nr_args);
13144 case IORING_UNREGISTER_RING_FDS:
13145 ret = io_ringfd_unregister(ctx, arg, nr_args);
13147 case IORING_REGISTER_PBUF_RING:
13149 if (!arg || nr_args != 1)
13151 ret = io_register_pbuf_ring(ctx, arg);
13153 case IORING_UNREGISTER_PBUF_RING:
13155 if (!arg || nr_args != 1)
13157 ret = io_unregister_pbuf_ring(ctx, arg);
13167 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
13168 void __user *, arg, unsigned int, nr_args)
13170 struct io_ring_ctx *ctx;
13179 if (f.file->f_op != &io_uring_fops)
13182 ctx = f.file->private_data;
13184 io_run_task_work();
13186 mutex_lock(&ctx->uring_lock);
13187 ret = __io_uring_register(ctx, opcode, arg, nr_args);
13188 mutex_unlock(&ctx->uring_lock);
13189 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
13195 static int __init io_uring_init(void)
13197 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13198 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13199 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13202 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13203 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13204 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13205 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13206 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13207 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13208 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13209 BUILD_BUG_SQE_ELEM(8, __u64, off);
13210 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13211 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13212 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13213 BUILD_BUG_SQE_ELEM(24, __u32, len);
13214 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13215 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13216 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13217 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13218 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13219 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13220 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13221 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13222 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13223 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13224 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13225 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13226 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13227 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13228 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13229 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13230 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13231 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13232 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13233 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13234 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13235 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13237 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13238 sizeof(struct io_uring_rsrc_update));
13239 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13240 sizeof(struct io_uring_rsrc_update2));
13242 /* ->buf_index is u16 */
13243 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13244 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13245 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13246 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13247 offsetof(struct io_uring_buf_ring, tail));
13249 /* should fit into one byte */
13250 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13251 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13252 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13254 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13255 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13257 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13259 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13261 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13265 __initcall(io_uring_init);