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))
4322 * Safe and required to re-import if we're using provided
4323 * buffers, as we dropped the selected one before retry.
4325 if (req->flags & REQ_F_BUFFER_SELECT) {
4326 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4327 if (unlikely(ret < 0))
4331 rw = req->async_data;
4334 * We come here from an earlier attempt, restore our state to
4335 * match in case it doesn't. It's cheap enough that we don't
4336 * need to make this conditional.
4338 iov_iter_restore(&s->iter, &s->iter_state);
4341 ret = io_rw_init_file(req, FMODE_READ);
4342 if (unlikely(ret)) {
4346 req->cqe.res = iov_iter_count(&s->iter);
4348 if (force_nonblock) {
4349 /* If the file doesn't support async, just async punt */
4350 if (unlikely(!io_file_supports_nowait(req))) {
4351 ret = io_setup_async_rw(req, iovec, s, true);
4352 return ret ?: -EAGAIN;
4354 kiocb->ki_flags |= IOCB_NOWAIT;
4356 /* Ensure we clear previously set non-block flag */
4357 kiocb->ki_flags &= ~IOCB_NOWAIT;
4360 ppos = io_kiocb_update_pos(req);
4362 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4363 if (unlikely(ret)) {
4368 ret = io_iter_do_read(req, &s->iter);
4370 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4371 req->flags &= ~REQ_F_REISSUE;
4372 /* if we can poll, just do that */
4373 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4375 /* IOPOLL retry should happen for io-wq threads */
4376 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4378 /* no retry on NONBLOCK nor RWF_NOWAIT */
4379 if (req->flags & REQ_F_NOWAIT)
4382 } else if (ret == -EIOCBQUEUED) {
4384 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4385 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4386 /* read all, failed, already did sync or don't want to retry */
4391 * Don't depend on the iter state matching what was consumed, or being
4392 * untouched in case of error. Restore it and we'll advance it
4393 * manually if we need to.
4395 iov_iter_restore(&s->iter, &s->iter_state);
4397 ret2 = io_setup_async_rw(req, iovec, s, true);
4402 rw = req->async_data;
4405 * Now use our persistent iterator and state, if we aren't already.
4406 * We've restored and mapped the iter to match.
4411 * We end up here because of a partial read, either from
4412 * above or inside this loop. Advance the iter by the bytes
4413 * that were consumed.
4415 iov_iter_advance(&s->iter, ret);
4416 if (!iov_iter_count(&s->iter))
4418 rw->bytes_done += ret;
4419 iov_iter_save_state(&s->iter, &s->iter_state);
4421 /* if we can retry, do so with the callbacks armed */
4422 if (!io_rw_should_retry(req)) {
4423 kiocb->ki_flags &= ~IOCB_WAITQ;
4428 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4429 * we get -EIOCBQUEUED, then we'll get a notification when the
4430 * desired page gets unlocked. We can also get a partial read
4431 * here, and if we do, then just retry at the new offset.
4433 ret = io_iter_do_read(req, &s->iter);
4434 if (ret == -EIOCBQUEUED)
4436 /* we got some bytes, but not all. retry. */
4437 kiocb->ki_flags &= ~IOCB_WAITQ;
4438 iov_iter_restore(&s->iter, &s->iter_state);
4441 kiocb_done(req, ret, issue_flags);
4443 /* it's faster to check here then delegate to kfree */
4449 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4451 struct io_rw_state __s, *s = &__s;
4452 struct iovec *iovec;
4453 struct kiocb *kiocb = &req->rw.kiocb;
4454 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4458 if (!req_has_async_data(req)) {
4459 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4460 if (unlikely(ret < 0))
4463 struct io_async_rw *rw = req->async_data;
4466 iov_iter_restore(&s->iter, &s->iter_state);
4469 ret = io_rw_init_file(req, FMODE_WRITE);
4470 if (unlikely(ret)) {
4474 req->cqe.res = iov_iter_count(&s->iter);
4476 if (force_nonblock) {
4477 /* If the file doesn't support async, just async punt */
4478 if (unlikely(!io_file_supports_nowait(req)))
4481 /* file path doesn't support NOWAIT for non-direct_IO */
4482 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4483 (req->flags & REQ_F_ISREG))
4486 kiocb->ki_flags |= IOCB_NOWAIT;
4488 /* Ensure we clear previously set non-block flag */
4489 kiocb->ki_flags &= ~IOCB_NOWAIT;
4492 ppos = io_kiocb_update_pos(req);
4494 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4499 * Open-code file_start_write here to grab freeze protection,
4500 * which will be released by another thread in
4501 * io_complete_rw(). Fool lockdep by telling it the lock got
4502 * released so that it doesn't complain about the held lock when
4503 * we return to userspace.
4505 if (req->flags & REQ_F_ISREG) {
4506 sb_start_write(file_inode(req->file)->i_sb);
4507 __sb_writers_release(file_inode(req->file)->i_sb,
4510 kiocb->ki_flags |= IOCB_WRITE;
4512 if (likely(req->file->f_op->write_iter))
4513 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4514 else if (req->file->f_op->write)
4515 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4519 if (req->flags & REQ_F_REISSUE) {
4520 req->flags &= ~REQ_F_REISSUE;
4525 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4526 * retry them without IOCB_NOWAIT.
4528 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4530 /* no retry on NONBLOCK nor RWF_NOWAIT */
4531 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4533 if (!force_nonblock || ret2 != -EAGAIN) {
4534 /* IOPOLL retry should happen for io-wq threads */
4535 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4538 kiocb_done(req, ret2, issue_flags);
4541 iov_iter_restore(&s->iter, &s->iter_state);
4542 ret = io_setup_async_rw(req, iovec, s, false);
4543 return ret ?: -EAGAIN;
4546 /* it's reportedly faster than delegating the null check to kfree() */
4552 static int io_renameat_prep(struct io_kiocb *req,
4553 const struct io_uring_sqe *sqe)
4555 struct io_rename *ren = &req->rename;
4556 const char __user *oldf, *newf;
4558 if (sqe->buf_index || sqe->splice_fd_in)
4560 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4563 ren->old_dfd = READ_ONCE(sqe->fd);
4564 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4565 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4566 ren->new_dfd = READ_ONCE(sqe->len);
4567 ren->flags = READ_ONCE(sqe->rename_flags);
4569 ren->oldpath = getname(oldf);
4570 if (IS_ERR(ren->oldpath))
4571 return PTR_ERR(ren->oldpath);
4573 ren->newpath = getname(newf);
4574 if (IS_ERR(ren->newpath)) {
4575 putname(ren->oldpath);
4576 return PTR_ERR(ren->newpath);
4579 req->flags |= REQ_F_NEED_CLEANUP;
4583 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4585 struct io_rename *ren = &req->rename;
4588 if (issue_flags & IO_URING_F_NONBLOCK)
4591 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4592 ren->newpath, ren->flags);
4594 req->flags &= ~REQ_F_NEED_CLEANUP;
4595 io_req_complete(req, ret);
4599 static inline void __io_xattr_finish(struct io_kiocb *req)
4601 struct io_xattr *ix = &req->xattr;
4604 putname(ix->filename);
4606 kfree(ix->ctx.kname);
4607 kvfree(ix->ctx.kvalue);
4610 static void io_xattr_finish(struct io_kiocb *req, int ret)
4612 req->flags &= ~REQ_F_NEED_CLEANUP;
4614 __io_xattr_finish(req);
4615 io_req_complete(req, ret);
4618 static int __io_getxattr_prep(struct io_kiocb *req,
4619 const struct io_uring_sqe *sqe)
4621 struct io_xattr *ix = &req->xattr;
4622 const char __user *name;
4625 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4628 ix->filename = NULL;
4629 ix->ctx.kvalue = NULL;
4630 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4631 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4632 ix->ctx.size = READ_ONCE(sqe->len);
4633 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4638 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4642 ret = strncpy_from_user(ix->ctx.kname->name, name,
4643 sizeof(ix->ctx.kname->name));
4644 if (!ret || ret == sizeof(ix->ctx.kname->name))
4647 kfree(ix->ctx.kname);
4651 req->flags |= REQ_F_NEED_CLEANUP;
4655 static int io_fgetxattr_prep(struct io_kiocb *req,
4656 const struct io_uring_sqe *sqe)
4658 return __io_getxattr_prep(req, sqe);
4661 static int io_getxattr_prep(struct io_kiocb *req,
4662 const struct io_uring_sqe *sqe)
4664 struct io_xattr *ix = &req->xattr;
4665 const char __user *path;
4668 ret = __io_getxattr_prep(req, sqe);
4672 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4674 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4675 if (IS_ERR(ix->filename)) {
4676 ret = PTR_ERR(ix->filename);
4677 ix->filename = NULL;
4683 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4685 struct io_xattr *ix = &req->xattr;
4688 if (issue_flags & IO_URING_F_NONBLOCK)
4691 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4692 req->file->f_path.dentry,
4695 io_xattr_finish(req, ret);
4699 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4701 struct io_xattr *ix = &req->xattr;
4702 unsigned int lookup_flags = LOOKUP_FOLLOW;
4706 if (issue_flags & IO_URING_F_NONBLOCK)
4710 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4712 ret = do_getxattr(mnt_user_ns(path.mnt),
4717 if (retry_estale(ret, lookup_flags)) {
4718 lookup_flags |= LOOKUP_REVAL;
4723 io_xattr_finish(req, ret);
4727 static int __io_setxattr_prep(struct io_kiocb *req,
4728 const struct io_uring_sqe *sqe)
4730 struct io_xattr *ix = &req->xattr;
4731 const char __user *name;
4734 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4737 ix->filename = NULL;
4738 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4739 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4740 ix->ctx.kvalue = NULL;
4741 ix->ctx.size = READ_ONCE(sqe->len);
4742 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4744 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4748 ret = setxattr_copy(name, &ix->ctx);
4750 kfree(ix->ctx.kname);
4754 req->flags |= REQ_F_NEED_CLEANUP;
4758 static int io_setxattr_prep(struct io_kiocb *req,
4759 const struct io_uring_sqe *sqe)
4761 struct io_xattr *ix = &req->xattr;
4762 const char __user *path;
4765 ret = __io_setxattr_prep(req, sqe);
4769 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4771 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4772 if (IS_ERR(ix->filename)) {
4773 ret = PTR_ERR(ix->filename);
4774 ix->filename = NULL;
4780 static int io_fsetxattr_prep(struct io_kiocb *req,
4781 const struct io_uring_sqe *sqe)
4783 return __io_setxattr_prep(req, sqe);
4786 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4789 struct io_xattr *ix = &req->xattr;
4792 ret = mnt_want_write(path->mnt);
4794 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4795 mnt_drop_write(path->mnt);
4801 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4805 if (issue_flags & IO_URING_F_NONBLOCK)
4808 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4809 io_xattr_finish(req, ret);
4814 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4816 struct io_xattr *ix = &req->xattr;
4817 unsigned int lookup_flags = LOOKUP_FOLLOW;
4821 if (issue_flags & IO_URING_F_NONBLOCK)
4825 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4827 ret = __io_setxattr(req, issue_flags, &path);
4829 if (retry_estale(ret, lookup_flags)) {
4830 lookup_flags |= LOOKUP_REVAL;
4835 io_xattr_finish(req, ret);
4839 static int io_unlinkat_prep(struct io_kiocb *req,
4840 const struct io_uring_sqe *sqe)
4842 struct io_unlink *un = &req->unlink;
4843 const char __user *fname;
4845 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4847 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4850 un->dfd = READ_ONCE(sqe->fd);
4852 un->flags = READ_ONCE(sqe->unlink_flags);
4853 if (un->flags & ~AT_REMOVEDIR)
4856 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4857 un->filename = getname(fname);
4858 if (IS_ERR(un->filename))
4859 return PTR_ERR(un->filename);
4861 req->flags |= REQ_F_NEED_CLEANUP;
4865 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4867 struct io_unlink *un = &req->unlink;
4870 if (issue_flags & IO_URING_F_NONBLOCK)
4873 if (un->flags & AT_REMOVEDIR)
4874 ret = do_rmdir(un->dfd, un->filename);
4876 ret = do_unlinkat(un->dfd, un->filename);
4878 req->flags &= ~REQ_F_NEED_CLEANUP;
4879 io_req_complete(req, ret);
4883 static int io_mkdirat_prep(struct io_kiocb *req,
4884 const struct io_uring_sqe *sqe)
4886 struct io_mkdir *mkd = &req->mkdir;
4887 const char __user *fname;
4889 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4891 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4894 mkd->dfd = READ_ONCE(sqe->fd);
4895 mkd->mode = READ_ONCE(sqe->len);
4897 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4898 mkd->filename = getname(fname);
4899 if (IS_ERR(mkd->filename))
4900 return PTR_ERR(mkd->filename);
4902 req->flags |= REQ_F_NEED_CLEANUP;
4906 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4908 struct io_mkdir *mkd = &req->mkdir;
4911 if (issue_flags & IO_URING_F_NONBLOCK)
4914 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4916 req->flags &= ~REQ_F_NEED_CLEANUP;
4917 io_req_complete(req, ret);
4921 static int io_symlinkat_prep(struct io_kiocb *req,
4922 const struct io_uring_sqe *sqe)
4924 struct io_symlink *sl = &req->symlink;
4925 const char __user *oldpath, *newpath;
4927 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4929 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4932 sl->new_dfd = READ_ONCE(sqe->fd);
4933 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4934 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4936 sl->oldpath = getname(oldpath);
4937 if (IS_ERR(sl->oldpath))
4938 return PTR_ERR(sl->oldpath);
4940 sl->newpath = getname(newpath);
4941 if (IS_ERR(sl->newpath)) {
4942 putname(sl->oldpath);
4943 return PTR_ERR(sl->newpath);
4946 req->flags |= REQ_F_NEED_CLEANUP;
4950 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4952 struct io_symlink *sl = &req->symlink;
4955 if (issue_flags & IO_URING_F_NONBLOCK)
4958 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4960 req->flags &= ~REQ_F_NEED_CLEANUP;
4961 io_req_complete(req, ret);
4965 static int io_linkat_prep(struct io_kiocb *req,
4966 const struct io_uring_sqe *sqe)
4968 struct io_hardlink *lnk = &req->hardlink;
4969 const char __user *oldf, *newf;
4971 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4973 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4976 lnk->old_dfd = READ_ONCE(sqe->fd);
4977 lnk->new_dfd = READ_ONCE(sqe->len);
4978 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4979 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4980 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4982 lnk->oldpath = getname(oldf);
4983 if (IS_ERR(lnk->oldpath))
4984 return PTR_ERR(lnk->oldpath);
4986 lnk->newpath = getname(newf);
4987 if (IS_ERR(lnk->newpath)) {
4988 putname(lnk->oldpath);
4989 return PTR_ERR(lnk->newpath);
4992 req->flags |= REQ_F_NEED_CLEANUP;
4996 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4998 struct io_hardlink *lnk = &req->hardlink;
5001 if (issue_flags & IO_URING_F_NONBLOCK)
5004 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
5005 lnk->newpath, lnk->flags);
5007 req->flags &= ~REQ_F_NEED_CLEANUP;
5008 io_req_complete(req, ret);
5012 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
5014 req->uring_cmd.task_work_cb(&req->uring_cmd);
5017 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
5018 void (*task_work_cb)(struct io_uring_cmd *))
5020 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5022 req->uring_cmd.task_work_cb = task_work_cb;
5023 req->io_task_work.func = io_uring_cmd_work;
5024 io_req_task_work_add(req);
5026 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
5028 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
5029 u64 extra1, u64 extra2)
5031 req->extra1 = extra1;
5032 req->extra2 = extra2;
5033 req->flags |= REQ_F_CQE32_INIT;
5037 * Called by consumers of io_uring_cmd, if they originally returned
5038 * -EIOCBQUEUED upon receiving the command.
5040 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
5042 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5047 if (req->ctx->flags & IORING_SETUP_CQE32)
5048 io_req_set_cqe32_extra(req, res2, 0);
5049 io_req_complete(req, ret);
5051 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
5053 static int io_uring_cmd_prep_async(struct io_kiocb *req)
5057 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
5059 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
5063 static int io_uring_cmd_prep(struct io_kiocb *req,
5064 const struct io_uring_sqe *sqe)
5066 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5070 ioucmd->cmd = sqe->cmd;
5071 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
5075 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
5077 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5078 struct io_ring_ctx *ctx = req->ctx;
5079 struct file *file = req->file;
5082 if (!req->file->f_op->uring_cmd)
5085 if (ctx->flags & IORING_SETUP_SQE128)
5086 issue_flags |= IO_URING_F_SQE128;
5087 if (ctx->flags & IORING_SETUP_CQE32)
5088 issue_flags |= IO_URING_F_CQE32;
5089 if (ctx->flags & IORING_SETUP_IOPOLL)
5090 issue_flags |= IO_URING_F_IOPOLL;
5092 if (req_has_async_data(req))
5093 ioucmd->cmd = req->async_data;
5095 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
5096 if (ret == -EAGAIN) {
5097 if (!req_has_async_data(req)) {
5098 if (io_alloc_async_data(req))
5100 io_uring_cmd_prep_async(req);
5105 if (ret != -EIOCBQUEUED)
5106 io_uring_cmd_done(ioucmd, ret, 0);
5110 static int __io_splice_prep(struct io_kiocb *req,
5111 const struct io_uring_sqe *sqe)
5113 struct io_splice *sp = &req->splice;
5114 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
5116 sp->len = READ_ONCE(sqe->len);
5117 sp->flags = READ_ONCE(sqe->splice_flags);
5118 if (unlikely(sp->flags & ~valid_flags))
5120 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
5124 static int io_tee_prep(struct io_kiocb *req,
5125 const struct io_uring_sqe *sqe)
5127 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
5129 return __io_splice_prep(req, sqe);
5132 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
5134 struct io_splice *sp = &req->splice;
5135 struct file *out = sp->file_out;
5136 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5140 if (issue_flags & IO_URING_F_NONBLOCK)
5143 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5144 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5146 in = io_file_get_normal(req, sp->splice_fd_in);
5153 ret = do_tee(in, out, sp->len, flags);
5155 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5160 __io_req_complete(req, 0, ret, 0);
5164 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5166 struct io_splice *sp = &req->splice;
5168 sp->off_in = READ_ONCE(sqe->splice_off_in);
5169 sp->off_out = READ_ONCE(sqe->off);
5170 return __io_splice_prep(req, sqe);
5173 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5175 struct io_splice *sp = &req->splice;
5176 struct file *out = sp->file_out;
5177 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5178 loff_t *poff_in, *poff_out;
5182 if (issue_flags & IO_URING_F_NONBLOCK)
5185 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5186 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5188 in = io_file_get_normal(req, sp->splice_fd_in);
5194 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5195 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5198 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5200 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5205 __io_req_complete(req, 0, ret, 0);
5209 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5215 * IORING_OP_NOP just posts a completion event, nothing else.
5217 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5219 __io_req_complete(req, issue_flags, 0, 0);
5223 static int io_msg_ring_prep(struct io_kiocb *req,
5224 const struct io_uring_sqe *sqe)
5226 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5227 sqe->buf_index || sqe->personality))
5230 req->msg.user_data = READ_ONCE(sqe->off);
5231 req->msg.len = READ_ONCE(sqe->len);
5235 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5237 struct io_ring_ctx *target_ctx;
5238 struct io_msg *msg = &req->msg;
5243 if (req->file->f_op != &io_uring_fops)
5247 target_ctx = req->file->private_data;
5249 spin_lock(&target_ctx->completion_lock);
5250 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5251 io_commit_cqring(target_ctx);
5252 spin_unlock(&target_ctx->completion_lock);
5255 io_cqring_ev_posted(target_ctx);
5262 __io_req_complete(req, issue_flags, ret, 0);
5263 /* put file to avoid an attempt to IOPOLL the req */
5264 io_put_file(req->file);
5269 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5271 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5274 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5275 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5278 req->sync.off = READ_ONCE(sqe->off);
5279 req->sync.len = READ_ONCE(sqe->len);
5283 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5285 loff_t end = req->sync.off + req->sync.len;
5288 /* fsync always requires a blocking context */
5289 if (issue_flags & IO_URING_F_NONBLOCK)
5292 ret = vfs_fsync_range(req->file, req->sync.off,
5293 end > 0 ? end : LLONG_MAX,
5294 req->sync.flags & IORING_FSYNC_DATASYNC);
5295 io_req_complete(req, ret);
5299 static int io_fallocate_prep(struct io_kiocb *req,
5300 const struct io_uring_sqe *sqe)
5302 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5305 req->sync.off = READ_ONCE(sqe->off);
5306 req->sync.len = READ_ONCE(sqe->addr);
5307 req->sync.mode = READ_ONCE(sqe->len);
5311 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5315 /* fallocate always requiring blocking context */
5316 if (issue_flags & IO_URING_F_NONBLOCK)
5318 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5321 fsnotify_modify(req->file);
5322 io_req_complete(req, ret);
5326 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5328 const char __user *fname;
5331 if (unlikely(sqe->buf_index))
5333 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5336 /* open.how should be already initialised */
5337 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5338 req->open.how.flags |= O_LARGEFILE;
5340 req->open.dfd = READ_ONCE(sqe->fd);
5341 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5342 req->open.filename = getname(fname);
5343 if (IS_ERR(req->open.filename)) {
5344 ret = PTR_ERR(req->open.filename);
5345 req->open.filename = NULL;
5349 req->open.file_slot = READ_ONCE(sqe->file_index);
5350 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5353 req->open.nofile = rlimit(RLIMIT_NOFILE);
5354 req->flags |= REQ_F_NEED_CLEANUP;
5358 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5360 u64 mode = READ_ONCE(sqe->len);
5361 u64 flags = READ_ONCE(sqe->open_flags);
5363 req->open.how = build_open_how(flags, mode);
5364 return __io_openat_prep(req, sqe);
5367 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5369 struct open_how __user *how;
5373 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5374 len = READ_ONCE(sqe->len);
5375 if (len < OPEN_HOW_SIZE_VER0)
5378 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5383 return __io_openat_prep(req, sqe);
5386 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5388 struct io_file_table *table = &ctx->file_table;
5389 unsigned long nr = ctx->nr_user_files;
5393 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5397 if (!table->alloc_hint)
5400 nr = table->alloc_hint;
5401 table->alloc_hint = 0;
5408 * Note when io_fixed_fd_install() returns error value, it will ensure
5409 * fput() is called correspondingly.
5411 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5412 struct file *file, unsigned int file_slot)
5414 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5415 struct io_ring_ctx *ctx = req->ctx;
5418 io_ring_submit_lock(ctx, issue_flags);
5421 ret = io_file_bitmap_get(ctx);
5422 if (unlikely(ret < 0))
5429 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5430 if (!ret && alloc_slot)
5433 io_ring_submit_unlock(ctx, issue_flags);
5434 if (unlikely(ret < 0))
5439 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5441 struct open_flags op;
5443 bool resolve_nonblock, nonblock_set;
5444 bool fixed = !!req->open.file_slot;
5447 ret = build_open_flags(&req->open.how, &op);
5450 nonblock_set = op.open_flag & O_NONBLOCK;
5451 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5452 if (issue_flags & IO_URING_F_NONBLOCK) {
5454 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5455 * it'll always -EAGAIN
5457 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5459 op.lookup_flags |= LOOKUP_CACHED;
5460 op.open_flag |= O_NONBLOCK;
5464 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5469 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5472 * We could hang on to this 'fd' on retrying, but seems like
5473 * marginal gain for something that is now known to be a slower
5474 * path. So just put it, and we'll get a new one when we retry.
5479 ret = PTR_ERR(file);
5480 /* only retry if RESOLVE_CACHED wasn't already set by application */
5481 if (ret == -EAGAIN &&
5482 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5487 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5488 file->f_flags &= ~O_NONBLOCK;
5489 fsnotify_open(file);
5492 fd_install(ret, file);
5494 ret = io_fixed_fd_install(req, issue_flags, file,
5495 req->open.file_slot);
5497 putname(req->open.filename);
5498 req->flags &= ~REQ_F_NEED_CLEANUP;
5501 __io_req_complete(req, issue_flags, ret, 0);
5505 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5507 return io_openat2(req, issue_flags);
5510 static int io_remove_buffers_prep(struct io_kiocb *req,
5511 const struct io_uring_sqe *sqe)
5513 struct io_provide_buf *p = &req->pbuf;
5516 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5520 tmp = READ_ONCE(sqe->fd);
5521 if (!tmp || tmp > USHRT_MAX)
5524 memset(p, 0, sizeof(*p));
5526 p->bgid = READ_ONCE(sqe->buf_group);
5530 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5531 struct io_buffer_list *bl, unsigned nbufs)
5535 /* shouldn't happen */
5539 if (bl->buf_nr_pages) {
5542 i = bl->buf_ring->tail - bl->head;
5543 for (j = 0; j < bl->buf_nr_pages; j++)
5544 unpin_user_page(bl->buf_pages[j]);
5545 kvfree(bl->buf_pages);
5546 bl->buf_pages = NULL;
5547 bl->buf_nr_pages = 0;
5548 /* make sure it's seen as empty */
5549 INIT_LIST_HEAD(&bl->buf_list);
5553 /* the head kbuf is the list itself */
5554 while (!list_empty(&bl->buf_list)) {
5555 struct io_buffer *nxt;
5557 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5558 list_del(&nxt->list);
5568 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5570 struct io_provide_buf *p = &req->pbuf;
5571 struct io_ring_ctx *ctx = req->ctx;
5572 struct io_buffer_list *bl;
5575 io_ring_submit_lock(ctx, issue_flags);
5578 bl = io_buffer_get_list(ctx, p->bgid);
5581 /* can't use provide/remove buffers command on mapped buffers */
5582 if (!bl->buf_nr_pages)
5583 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5588 /* complete before unlock, IOPOLL may need the lock */
5589 __io_req_complete(req, issue_flags, ret, 0);
5590 io_ring_submit_unlock(ctx, issue_flags);
5594 static int io_provide_buffers_prep(struct io_kiocb *req,
5595 const struct io_uring_sqe *sqe)
5597 unsigned long size, tmp_check;
5598 struct io_provide_buf *p = &req->pbuf;
5601 if (sqe->rw_flags || sqe->splice_fd_in)
5604 tmp = READ_ONCE(sqe->fd);
5605 if (!tmp || tmp > USHRT_MAX)
5608 p->addr = READ_ONCE(sqe->addr);
5609 p->len = READ_ONCE(sqe->len);
5611 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5614 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5617 size = (unsigned long)p->len * p->nbufs;
5618 if (!access_ok(u64_to_user_ptr(p->addr), size))
5621 p->bgid = READ_ONCE(sqe->buf_group);
5622 tmp = READ_ONCE(sqe->off);
5623 if (tmp > USHRT_MAX)
5629 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5631 struct io_buffer *buf;
5636 * Completions that don't happen inline (eg not under uring_lock) will
5637 * add to ->io_buffers_comp. If we don't have any free buffers, check
5638 * the completion list and splice those entries first.
5640 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5641 spin_lock(&ctx->completion_lock);
5642 if (!list_empty(&ctx->io_buffers_comp)) {
5643 list_splice_init(&ctx->io_buffers_comp,
5644 &ctx->io_buffers_cache);
5645 spin_unlock(&ctx->completion_lock);
5648 spin_unlock(&ctx->completion_lock);
5652 * No free buffers and no completion entries either. Allocate a new
5653 * page worth of buffer entries and add those to our freelist.
5655 page = alloc_page(GFP_KERNEL_ACCOUNT);
5659 list_add(&page->lru, &ctx->io_buffers_pages);
5661 buf = page_address(page);
5662 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5663 while (bufs_in_page) {
5664 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5672 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5673 struct io_buffer_list *bl)
5675 struct io_buffer *buf;
5676 u64 addr = pbuf->addr;
5677 int i, bid = pbuf->bid;
5679 for (i = 0; i < pbuf->nbufs; i++) {
5680 if (list_empty(&ctx->io_buffers_cache) &&
5681 io_refill_buffer_cache(ctx))
5683 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5685 list_move_tail(&buf->list, &bl->buf_list);
5687 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5689 buf->bgid = pbuf->bgid;
5695 return i ? 0 : -ENOMEM;
5698 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5702 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5707 for (i = 0; i < BGID_ARRAY; i++) {
5708 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5709 ctx->io_bl[i].bgid = i;
5715 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5717 struct io_provide_buf *p = &req->pbuf;
5718 struct io_ring_ctx *ctx = req->ctx;
5719 struct io_buffer_list *bl;
5722 io_ring_submit_lock(ctx, issue_flags);
5724 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5725 ret = io_init_bl_list(ctx);
5730 bl = io_buffer_get_list(ctx, p->bgid);
5731 if (unlikely(!bl)) {
5732 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5737 INIT_LIST_HEAD(&bl->buf_list);
5738 ret = io_buffer_add_list(ctx, bl, p->bgid);
5744 /* can't add buffers via this command for a mapped buffer ring */
5745 if (bl->buf_nr_pages) {
5750 ret = io_add_buffers(ctx, p, bl);
5754 /* complete before unlock, IOPOLL may need the lock */
5755 __io_req_complete(req, issue_flags, ret, 0);
5756 io_ring_submit_unlock(ctx, issue_flags);
5760 static int io_epoll_ctl_prep(struct io_kiocb *req,
5761 const struct io_uring_sqe *sqe)
5763 #if defined(CONFIG_EPOLL)
5764 if (sqe->buf_index || sqe->splice_fd_in)
5767 req->epoll.epfd = READ_ONCE(sqe->fd);
5768 req->epoll.op = READ_ONCE(sqe->len);
5769 req->epoll.fd = READ_ONCE(sqe->off);
5771 if (ep_op_has_event(req->epoll.op)) {
5772 struct epoll_event __user *ev;
5774 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5775 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5785 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5787 #if defined(CONFIG_EPOLL)
5788 struct io_epoll *ie = &req->epoll;
5790 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5792 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5793 if (force_nonblock && ret == -EAGAIN)
5798 __io_req_complete(req, issue_flags, ret, 0);
5805 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5807 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5808 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5811 req->madvise.addr = READ_ONCE(sqe->addr);
5812 req->madvise.len = READ_ONCE(sqe->len);
5813 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5820 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5822 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5823 struct io_madvise *ma = &req->madvise;
5826 if (issue_flags & IO_URING_F_NONBLOCK)
5829 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5830 io_req_complete(req, ret);
5837 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5839 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5842 req->fadvise.offset = READ_ONCE(sqe->off);
5843 req->fadvise.len = READ_ONCE(sqe->len);
5844 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5848 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5850 struct io_fadvise *fa = &req->fadvise;
5853 if (issue_flags & IO_URING_F_NONBLOCK) {
5854 switch (fa->advice) {
5855 case POSIX_FADV_NORMAL:
5856 case POSIX_FADV_RANDOM:
5857 case POSIX_FADV_SEQUENTIAL:
5864 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5867 __io_req_complete(req, issue_flags, ret, 0);
5871 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5873 const char __user *path;
5875 if (sqe->buf_index || sqe->splice_fd_in)
5877 if (req->flags & REQ_F_FIXED_FILE)
5880 req->statx.dfd = READ_ONCE(sqe->fd);
5881 req->statx.mask = READ_ONCE(sqe->len);
5882 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5883 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5884 req->statx.flags = READ_ONCE(sqe->statx_flags);
5886 req->statx.filename = getname_flags(path,
5887 getname_statx_lookup_flags(req->statx.flags),
5890 if (IS_ERR(req->statx.filename)) {
5891 int ret = PTR_ERR(req->statx.filename);
5893 req->statx.filename = NULL;
5897 req->flags |= REQ_F_NEED_CLEANUP;
5901 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5903 struct io_statx *ctx = &req->statx;
5906 if (issue_flags & IO_URING_F_NONBLOCK)
5909 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5911 io_req_complete(req, ret);
5915 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5917 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5919 if (req->flags & REQ_F_FIXED_FILE)
5922 req->close.fd = READ_ONCE(sqe->fd);
5923 req->close.file_slot = READ_ONCE(sqe->file_index);
5924 if (req->close.file_slot && req->close.fd)
5930 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5932 struct files_struct *files = current->files;
5933 struct io_close *close = &req->close;
5934 struct fdtable *fdt;
5938 if (req->close.file_slot) {
5939 ret = io_close_fixed(req, issue_flags);
5943 spin_lock(&files->file_lock);
5944 fdt = files_fdtable(files);
5945 if (close->fd >= fdt->max_fds) {
5946 spin_unlock(&files->file_lock);
5949 file = rcu_dereference_protected(fdt->fd[close->fd],
5950 lockdep_is_held(&files->file_lock));
5951 if (!file || file->f_op == &io_uring_fops) {
5952 spin_unlock(&files->file_lock);
5956 /* if the file has a flush method, be safe and punt to async */
5957 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5958 spin_unlock(&files->file_lock);
5962 file = __close_fd_get_file(close->fd);
5963 spin_unlock(&files->file_lock);
5967 /* No ->flush() or already async, safely close from here */
5968 ret = filp_close(file, current->files);
5972 __io_req_complete(req, issue_flags, ret, 0);
5976 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5978 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5981 req->sync.off = READ_ONCE(sqe->off);
5982 req->sync.len = READ_ONCE(sqe->len);
5983 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5987 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5991 /* sync_file_range always requires a blocking context */
5992 if (issue_flags & IO_URING_F_NONBLOCK)
5995 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5997 io_req_complete(req, ret);
6001 #if defined(CONFIG_NET)
6002 static int io_shutdown_prep(struct io_kiocb *req,
6003 const struct io_uring_sqe *sqe)
6005 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
6006 sqe->buf_index || sqe->splice_fd_in))
6009 req->shutdown.how = READ_ONCE(sqe->len);
6013 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
6015 struct socket *sock;
6018 if (issue_flags & IO_URING_F_NONBLOCK)
6021 sock = sock_from_file(req->file);
6022 if (unlikely(!sock))
6025 ret = __sys_shutdown_sock(sock, req->shutdown.how);
6026 io_req_complete(req, ret);
6030 static bool io_net_retry(struct socket *sock, int flags)
6032 if (!(flags & MSG_WAITALL))
6034 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
6037 static int io_setup_async_msg(struct io_kiocb *req,
6038 struct io_async_msghdr *kmsg)
6040 struct io_async_msghdr *async_msg = req->async_data;
6044 if (io_alloc_async_data(req)) {
6045 kfree(kmsg->free_iov);
6048 async_msg = req->async_data;
6049 req->flags |= REQ_F_NEED_CLEANUP;
6050 memcpy(async_msg, kmsg, sizeof(*kmsg));
6051 async_msg->msg.msg_name = &async_msg->addr;
6052 /* if were using fast_iov, set it to the new one */
6053 if (!async_msg->free_iov)
6054 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
6059 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
6060 struct io_async_msghdr *iomsg)
6062 iomsg->msg.msg_name = &iomsg->addr;
6063 iomsg->free_iov = iomsg->fast_iov;
6064 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
6065 req->sr_msg.msg_flags, &iomsg->free_iov);
6068 static int io_sendmsg_prep_async(struct io_kiocb *req)
6072 ret = io_sendmsg_copy_hdr(req, req->async_data);
6074 req->flags |= REQ_F_NEED_CLEANUP;
6078 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6080 struct io_sr_msg *sr = &req->sr_msg;
6082 if (unlikely(sqe->file_index || sqe->addr2))
6085 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6086 sr->len = READ_ONCE(sqe->len);
6087 sr->flags = READ_ONCE(sqe->ioprio);
6088 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6090 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6091 if (sr->msg_flags & MSG_DONTWAIT)
6092 req->flags |= REQ_F_NOWAIT;
6094 #ifdef CONFIG_COMPAT
6095 if (req->ctx->compat)
6096 sr->msg_flags |= MSG_CMSG_COMPAT;
6102 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
6104 struct io_async_msghdr iomsg, *kmsg;
6105 struct io_sr_msg *sr = &req->sr_msg;
6106 struct socket *sock;
6111 sock = sock_from_file(req->file);
6112 if (unlikely(!sock))
6115 if (req_has_async_data(req)) {
6116 kmsg = req->async_data;
6118 ret = io_sendmsg_copy_hdr(req, &iomsg);
6124 if (!(req->flags & REQ_F_POLLED) &&
6125 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6126 return io_setup_async_msg(req, kmsg);
6128 flags = sr->msg_flags;
6129 if (issue_flags & IO_URING_F_NONBLOCK)
6130 flags |= MSG_DONTWAIT;
6131 if (flags & MSG_WAITALL)
6132 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6134 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
6136 if (ret < min_ret) {
6137 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6138 return io_setup_async_msg(req, kmsg);
6139 if (ret == -ERESTARTSYS)
6141 if (ret > 0 && io_net_retry(sock, flags)) {
6143 req->flags |= REQ_F_PARTIAL_IO;
6144 return io_setup_async_msg(req, kmsg);
6148 /* fast path, check for non-NULL to avoid function call */
6150 kfree(kmsg->free_iov);
6151 req->flags &= ~REQ_F_NEED_CLEANUP;
6154 else if (sr->done_io)
6156 __io_req_complete(req, issue_flags, ret, 0);
6160 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6162 struct io_sr_msg *sr = &req->sr_msg;
6165 struct socket *sock;
6170 if (!(req->flags & REQ_F_POLLED) &&
6171 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6174 sock = sock_from_file(req->file);
6175 if (unlikely(!sock))
6178 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6182 msg.msg_name = NULL;
6183 msg.msg_control = NULL;
6184 msg.msg_controllen = 0;
6185 msg.msg_namelen = 0;
6187 flags = sr->msg_flags;
6188 if (issue_flags & IO_URING_F_NONBLOCK)
6189 flags |= MSG_DONTWAIT;
6190 if (flags & MSG_WAITALL)
6191 min_ret = iov_iter_count(&msg.msg_iter);
6193 msg.msg_flags = flags;
6194 ret = sock_sendmsg(sock, &msg);
6195 if (ret < min_ret) {
6196 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6198 if (ret == -ERESTARTSYS)
6200 if (ret > 0 && io_net_retry(sock, flags)) {
6204 req->flags |= REQ_F_PARTIAL_IO;
6211 else if (sr->done_io)
6213 __io_req_complete(req, issue_flags, ret, 0);
6217 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6218 struct io_async_msghdr *iomsg)
6220 struct io_sr_msg *sr = &req->sr_msg;
6221 struct iovec __user *uiov;
6225 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6226 &iomsg->uaddr, &uiov, &iov_len);
6230 if (req->flags & REQ_F_BUFFER_SELECT) {
6233 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6235 sr->len = iomsg->fast_iov[0].iov_len;
6236 iomsg->free_iov = NULL;
6238 iomsg->free_iov = iomsg->fast_iov;
6239 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6240 &iomsg->free_iov, &iomsg->msg.msg_iter,
6249 #ifdef CONFIG_COMPAT
6250 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6251 struct io_async_msghdr *iomsg)
6253 struct io_sr_msg *sr = &req->sr_msg;
6254 struct compat_iovec __user *uiov;
6259 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6264 uiov = compat_ptr(ptr);
6265 if (req->flags & REQ_F_BUFFER_SELECT) {
6266 compat_ssize_t clen;
6270 if (!access_ok(uiov, sizeof(*uiov)))
6272 if (__get_user(clen, &uiov->iov_len))
6277 iomsg->free_iov = NULL;
6279 iomsg->free_iov = iomsg->fast_iov;
6280 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6281 UIO_FASTIOV, &iomsg->free_iov,
6282 &iomsg->msg.msg_iter, true);
6291 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6292 struct io_async_msghdr *iomsg)
6294 iomsg->msg.msg_name = &iomsg->addr;
6296 #ifdef CONFIG_COMPAT
6297 if (req->ctx->compat)
6298 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6301 return __io_recvmsg_copy_hdr(req, iomsg);
6304 static int io_recvmsg_prep_async(struct io_kiocb *req)
6308 ret = io_recvmsg_copy_hdr(req, req->async_data);
6310 req->flags |= REQ_F_NEED_CLEANUP;
6314 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6316 struct io_sr_msg *sr = &req->sr_msg;
6318 if (unlikely(sqe->file_index || sqe->addr2))
6321 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6322 sr->len = READ_ONCE(sqe->len);
6323 sr->flags = READ_ONCE(sqe->ioprio);
6324 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6326 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6327 if (sr->msg_flags & MSG_DONTWAIT)
6328 req->flags |= REQ_F_NOWAIT;
6330 #ifdef CONFIG_COMPAT
6331 if (req->ctx->compat)
6332 sr->msg_flags |= MSG_CMSG_COMPAT;
6338 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6340 struct io_async_msghdr iomsg, *kmsg;
6341 struct io_sr_msg *sr = &req->sr_msg;
6342 struct socket *sock;
6343 unsigned int cflags;
6345 int ret, min_ret = 0;
6346 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6348 sock = sock_from_file(req->file);
6349 if (unlikely(!sock))
6352 if (req_has_async_data(req)) {
6353 kmsg = req->async_data;
6355 ret = io_recvmsg_copy_hdr(req, &iomsg);
6361 if (!(req->flags & REQ_F_POLLED) &&
6362 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6363 return io_setup_async_msg(req, kmsg);
6365 if (io_do_buffer_select(req)) {
6368 buf = io_buffer_select(req, &sr->len, issue_flags);
6371 kmsg->fast_iov[0].iov_base = buf;
6372 kmsg->fast_iov[0].iov_len = sr->len;
6373 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6377 flags = sr->msg_flags;
6379 flags |= MSG_DONTWAIT;
6380 if (flags & MSG_WAITALL)
6381 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6383 kmsg->msg.msg_get_inq = 1;
6384 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6385 if (ret < min_ret) {
6386 if (ret == -EAGAIN && force_nonblock)
6387 return io_setup_async_msg(req, kmsg);
6388 if (ret == -ERESTARTSYS)
6390 if (ret > 0 && io_net_retry(sock, flags)) {
6392 req->flags |= REQ_F_PARTIAL_IO;
6393 return io_setup_async_msg(req, kmsg);
6396 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6400 /* fast path, check for non-NULL to avoid function call */
6402 kfree(kmsg->free_iov);
6403 req->flags &= ~REQ_F_NEED_CLEANUP;
6406 else if (sr->done_io)
6408 cflags = io_put_kbuf(req, issue_flags);
6409 if (kmsg->msg.msg_inq)
6410 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6411 __io_req_complete(req, issue_flags, ret, cflags);
6415 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6417 struct io_sr_msg *sr = &req->sr_msg;
6419 struct socket *sock;
6421 unsigned int cflags;
6423 int ret, min_ret = 0;
6424 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6426 if (!(req->flags & REQ_F_POLLED) &&
6427 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6430 sock = sock_from_file(req->file);
6431 if (unlikely(!sock))
6434 if (io_do_buffer_select(req)) {
6437 buf = io_buffer_select(req, &sr->len, issue_flags);
6443 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6447 msg.msg_name = NULL;
6448 msg.msg_namelen = 0;
6449 msg.msg_control = NULL;
6450 msg.msg_get_inq = 1;
6452 msg.msg_controllen = 0;
6453 msg.msg_iocb = NULL;
6455 flags = sr->msg_flags;
6457 flags |= MSG_DONTWAIT;
6458 if (flags & MSG_WAITALL)
6459 min_ret = iov_iter_count(&msg.msg_iter);
6461 ret = sock_recvmsg(sock, &msg, flags);
6462 if (ret < min_ret) {
6463 if (ret == -EAGAIN && force_nonblock)
6465 if (ret == -ERESTARTSYS)
6467 if (ret > 0 && io_net_retry(sock, flags)) {
6471 req->flags |= REQ_F_PARTIAL_IO;
6475 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6482 else if (sr->done_io)
6484 cflags = io_put_kbuf(req, issue_flags);
6486 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6487 __io_req_complete(req, issue_flags, ret, cflags);
6491 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6493 struct io_accept *accept = &req->accept;
6496 if (sqe->len || sqe->buf_index)
6499 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6500 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6501 accept->flags = READ_ONCE(sqe->accept_flags);
6502 accept->nofile = rlimit(RLIMIT_NOFILE);
6503 flags = READ_ONCE(sqe->ioprio);
6504 if (flags & ~IORING_ACCEPT_MULTISHOT)
6507 accept->file_slot = READ_ONCE(sqe->file_index);
6508 if (accept->file_slot) {
6509 if (accept->flags & SOCK_CLOEXEC)
6511 if (flags & IORING_ACCEPT_MULTISHOT &&
6512 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6515 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6517 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6518 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6519 if (flags & IORING_ACCEPT_MULTISHOT)
6520 req->flags |= REQ_F_APOLL_MULTISHOT;
6524 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6526 struct io_ring_ctx *ctx = req->ctx;
6527 struct io_accept *accept = &req->accept;
6528 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6529 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6530 bool fixed = !!accept->file_slot;
6536 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6537 if (unlikely(fd < 0))
6540 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6545 ret = PTR_ERR(file);
6546 if (ret == -EAGAIN && force_nonblock) {
6548 * if it's multishot and polled, we don't need to
6549 * return EAGAIN to arm the poll infra since it
6550 * has already been done
6552 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6553 IO_APOLL_MULTI_POLLED)
6557 if (ret == -ERESTARTSYS)
6560 } else if (!fixed) {
6561 fd_install(fd, file);
6564 ret = io_fixed_fd_install(req, issue_flags, file,
6568 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6569 __io_req_complete(req, issue_flags, ret, 0);
6575 spin_lock(&ctx->completion_lock);
6576 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6578 io_commit_cqring(ctx);
6579 spin_unlock(&ctx->completion_lock);
6581 io_cqring_ev_posted(ctx);
6590 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6592 struct io_socket *sock = &req->sock;
6594 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6597 sock->domain = READ_ONCE(sqe->fd);
6598 sock->type = READ_ONCE(sqe->off);
6599 sock->protocol = READ_ONCE(sqe->len);
6600 sock->file_slot = READ_ONCE(sqe->file_index);
6601 sock->nofile = rlimit(RLIMIT_NOFILE);
6603 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6604 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6606 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6611 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6613 struct io_socket *sock = &req->sock;
6614 bool fixed = !!sock->file_slot;
6619 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6620 if (unlikely(fd < 0))
6623 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6627 ret = PTR_ERR(file);
6628 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6630 if (ret == -ERESTARTSYS)
6633 } else if (!fixed) {
6634 fd_install(fd, file);
6637 ret = io_fixed_fd_install(req, issue_flags, file,
6640 __io_req_complete(req, issue_flags, ret, 0);
6644 static int io_connect_prep_async(struct io_kiocb *req)
6646 struct io_async_connect *io = req->async_data;
6647 struct io_connect *conn = &req->connect;
6649 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6652 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6654 struct io_connect *conn = &req->connect;
6656 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6659 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6660 conn->addr_len = READ_ONCE(sqe->addr2);
6664 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6666 struct io_async_connect __io, *io;
6667 unsigned file_flags;
6669 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6671 if (req_has_async_data(req)) {
6672 io = req->async_data;
6674 ret = move_addr_to_kernel(req->connect.addr,
6675 req->connect.addr_len,
6682 file_flags = force_nonblock ? O_NONBLOCK : 0;
6684 ret = __sys_connect_file(req->file, &io->address,
6685 req->connect.addr_len, file_flags);
6686 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6687 if (req_has_async_data(req))
6689 if (io_alloc_async_data(req)) {
6693 memcpy(req->async_data, &__io, sizeof(__io));
6696 if (ret == -ERESTARTSYS)
6701 __io_req_complete(req, issue_flags, ret, 0);
6704 #else /* !CONFIG_NET */
6705 #define IO_NETOP_FN(op) \
6706 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6708 return -EOPNOTSUPP; \
6711 #define IO_NETOP_PREP(op) \
6713 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6715 return -EOPNOTSUPP; \
6718 #define IO_NETOP_PREP_ASYNC(op) \
6720 static int io_##op##_prep_async(struct io_kiocb *req) \
6722 return -EOPNOTSUPP; \
6725 IO_NETOP_PREP_ASYNC(sendmsg);
6726 IO_NETOP_PREP_ASYNC(recvmsg);
6727 IO_NETOP_PREP_ASYNC(connect);
6728 IO_NETOP_PREP(accept);
6729 IO_NETOP_PREP(socket);
6730 IO_NETOP_PREP(shutdown);
6733 #endif /* CONFIG_NET */
6735 struct io_poll_table {
6736 struct poll_table_struct pt;
6737 struct io_kiocb *req;
6742 #define IO_POLL_CANCEL_FLAG BIT(31)
6743 #define IO_POLL_REF_MASK GENMASK(30, 0)
6746 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6747 * bump it and acquire ownership. It's disallowed to modify requests while not
6748 * owning it, that prevents from races for enqueueing task_work's and b/w
6749 * arming poll and wakeups.
6751 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6753 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6756 static void io_poll_mark_cancelled(struct io_kiocb *req)
6758 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6761 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6763 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6764 if (req->opcode == IORING_OP_POLL_ADD)
6765 return req->async_data;
6766 return req->apoll->double_poll;
6769 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6771 if (req->opcode == IORING_OP_POLL_ADD)
6773 return &req->apoll->poll;
6776 static void io_poll_req_insert(struct io_kiocb *req)
6778 struct io_ring_ctx *ctx = req->ctx;
6779 struct hlist_head *list;
6781 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6782 hlist_add_head(&req->hash_node, list);
6785 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6786 wait_queue_func_t wake_func)
6789 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6790 /* mask in events that we always want/need */
6791 poll->events = events | IO_POLL_UNMASK;
6792 INIT_LIST_HEAD(&poll->wait.entry);
6793 init_waitqueue_func_entry(&poll->wait, wake_func);
6796 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6798 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6801 spin_lock_irq(&head->lock);
6802 list_del_init(&poll->wait.entry);
6804 spin_unlock_irq(&head->lock);
6808 static void io_poll_remove_entries(struct io_kiocb *req)
6811 * Nothing to do if neither of those flags are set. Avoid dipping
6812 * into the poll/apoll/double cachelines if we can.
6814 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6818 * While we hold the waitqueue lock and the waitqueue is nonempty,
6819 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6820 * lock in the first place can race with the waitqueue being freed.
6822 * We solve this as eventpoll does: by taking advantage of the fact that
6823 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6824 * we enter rcu_read_lock() and see that the pointer to the queue is
6825 * non-NULL, we can then lock it without the memory being freed out from
6828 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6829 * case the caller deletes the entry from the queue, leaving it empty.
6830 * In that case, only RCU prevents the queue memory from being freed.
6833 if (req->flags & REQ_F_SINGLE_POLL)
6834 io_poll_remove_entry(io_poll_get_single(req));
6835 if (req->flags & REQ_F_DOUBLE_POLL)
6836 io_poll_remove_entry(io_poll_get_double(req));
6840 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6842 * All poll tw should go through this. Checks for poll events, manages
6843 * references, does rewait, etc.
6845 * Returns a negative error on failure. >0 when no action require, which is
6846 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6847 * the request, then the mask is stored in req->cqe.res.
6849 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6851 struct io_ring_ctx *ctx = req->ctx;
6854 /* req->task == current here, checking PF_EXITING is safe */
6855 if (unlikely(req->task->flags & PF_EXITING))
6859 v = atomic_read(&req->poll_refs);
6861 /* tw handler should be the owner, and so have some references */
6862 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6864 if (v & IO_POLL_CANCEL_FLAG)
6867 if (!req->cqe.res) {
6868 struct poll_table_struct pt = { ._key = req->apoll_events };
6869 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6872 if ((unlikely(!req->cqe.res)))
6874 if (req->apoll_events & EPOLLONESHOT)
6877 /* multishot, just fill a CQE and proceed */
6878 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6879 __poll_t mask = mangle_poll(req->cqe.res &
6883 spin_lock(&ctx->completion_lock);
6884 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6885 mask, IORING_CQE_F_MORE);
6886 io_commit_cqring(ctx);
6887 spin_unlock(&ctx->completion_lock);
6889 io_cqring_ev_posted(ctx);
6895 io_tw_lock(req->ctx, locked);
6896 if (unlikely(req->task->flags & PF_EXITING))
6898 ret = io_issue_sqe(req,
6899 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6904 * Release all references, retry if someone tried to restart
6905 * task_work while we were executing it.
6907 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6912 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6914 struct io_ring_ctx *ctx = req->ctx;
6917 ret = io_poll_check_events(req, locked);
6922 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6928 io_poll_remove_entries(req);
6929 spin_lock(&ctx->completion_lock);
6930 hash_del(&req->hash_node);
6931 __io_req_complete_post(req, req->cqe.res, 0);
6932 io_commit_cqring(ctx);
6933 spin_unlock(&ctx->completion_lock);
6934 io_cqring_ev_posted(ctx);
6937 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6939 struct io_ring_ctx *ctx = req->ctx;
6942 ret = io_poll_check_events(req, locked);
6946 io_poll_remove_entries(req);
6947 spin_lock(&ctx->completion_lock);
6948 hash_del(&req->hash_node);
6949 spin_unlock(&ctx->completion_lock);
6952 io_req_task_submit(req, locked);
6954 io_req_complete_failed(req, ret);
6957 static void __io_poll_execute(struct io_kiocb *req, int mask,
6958 __poll_t __maybe_unused events)
6960 req->cqe.res = mask;
6962 * This is useful for poll that is armed on behalf of another
6963 * request, and where the wakeup path could be on a different
6964 * CPU. We want to avoid pulling in req->apoll->events for that
6967 if (req->opcode == IORING_OP_POLL_ADD)
6968 req->io_task_work.func = io_poll_task_func;
6970 req->io_task_work.func = io_apoll_task_func;
6972 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6973 io_req_task_work_add(req);
6976 static inline void io_poll_execute(struct io_kiocb *req, int res,
6979 if (io_poll_get_ownership(req))
6980 __io_poll_execute(req, res, events);
6983 static void io_poll_cancel_req(struct io_kiocb *req)
6985 io_poll_mark_cancelled(req);
6986 /* kick tw, which should complete the request */
6987 io_poll_execute(req, 0, 0);
6990 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6991 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6992 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
6994 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6997 struct io_kiocb *req = wqe_to_req(wait);
6998 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
7000 __poll_t mask = key_to_poll(key);
7002 if (unlikely(mask & POLLFREE)) {
7003 io_poll_mark_cancelled(req);
7004 /* we have to kick tw in case it's not already */
7005 io_poll_execute(req, 0, poll->events);
7008 * If the waitqueue is being freed early but someone is already
7009 * holds ownership over it, we have to tear down the request as
7010 * best we can. That means immediately removing the request from
7011 * its waitqueue and preventing all further accesses to the
7012 * waitqueue via the request.
7014 list_del_init(&poll->wait.entry);
7017 * Careful: this *must* be the last step, since as soon
7018 * as req->head is NULL'ed out, the request can be
7019 * completed and freed, since aio_poll_complete_work()
7020 * will no longer need to take the waitqueue lock.
7022 smp_store_release(&poll->head, NULL);
7026 /* for instances that support it check for an event match first */
7027 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
7030 if (io_poll_get_ownership(req)) {
7031 /* optional, saves extra locking for removal in tw handler */
7032 if (mask && poll->events & EPOLLONESHOT) {
7033 list_del_init(&poll->wait.entry);
7035 if (wqe_is_double(wait))
7036 req->flags &= ~REQ_F_DOUBLE_POLL;
7038 req->flags &= ~REQ_F_SINGLE_POLL;
7040 __io_poll_execute(req, mask, poll->events);
7045 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
7046 struct wait_queue_head *head,
7047 struct io_poll_iocb **poll_ptr)
7049 struct io_kiocb *req = pt->req;
7050 unsigned long wqe_private = (unsigned long) req;
7053 * The file being polled uses multiple waitqueues for poll handling
7054 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
7057 if (unlikely(pt->nr_entries)) {
7058 struct io_poll_iocb *first = poll;
7060 /* double add on the same waitqueue head, ignore */
7061 if (first->head == head)
7063 /* already have a 2nd entry, fail a third attempt */
7065 if ((*poll_ptr)->head == head)
7067 pt->error = -EINVAL;
7071 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
7073 pt->error = -ENOMEM;
7076 /* mark as double wq entry */
7078 req->flags |= REQ_F_DOUBLE_POLL;
7079 io_init_poll_iocb(poll, first->events, first->wait.func);
7081 if (req->opcode == IORING_OP_POLL_ADD)
7082 req->flags |= REQ_F_ASYNC_DATA;
7085 req->flags |= REQ_F_SINGLE_POLL;
7088 poll->wait.private = (void *) wqe_private;
7090 if (poll->events & EPOLLEXCLUSIVE)
7091 add_wait_queue_exclusive(head, &poll->wait);
7093 add_wait_queue(head, &poll->wait);
7096 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
7097 struct poll_table_struct *p)
7099 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7101 __io_queue_proc(&pt->req->poll, pt, head,
7102 (struct io_poll_iocb **) &pt->req->async_data);
7105 static int __io_arm_poll_handler(struct io_kiocb *req,
7106 struct io_poll_iocb *poll,
7107 struct io_poll_table *ipt, __poll_t mask)
7109 struct io_ring_ctx *ctx = req->ctx;
7112 INIT_HLIST_NODE(&req->hash_node);
7113 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
7114 io_init_poll_iocb(poll, mask, io_poll_wake);
7115 poll->file = req->file;
7117 req->apoll_events = poll->events;
7119 ipt->pt._key = mask;
7122 ipt->nr_entries = 0;
7125 * Take the ownership to delay any tw execution up until we're done
7126 * with poll arming. see io_poll_get_ownership().
7128 atomic_set(&req->poll_refs, 1);
7129 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
7131 if (mask && (poll->events & EPOLLONESHOT)) {
7132 io_poll_remove_entries(req);
7133 /* no one else has access to the req, forget about the ref */
7136 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
7137 io_poll_remove_entries(req);
7139 ipt->error = -EINVAL;
7143 spin_lock(&ctx->completion_lock);
7144 io_poll_req_insert(req);
7145 spin_unlock(&ctx->completion_lock);
7148 /* can't multishot if failed, just queue the event we've got */
7149 if (unlikely(ipt->error || !ipt->nr_entries)) {
7150 poll->events |= EPOLLONESHOT;
7151 req->apoll_events |= EPOLLONESHOT;
7154 __io_poll_execute(req, mask, poll->events);
7159 * Release ownership. If someone tried to queue a tw while it was
7160 * locked, kick it off for them.
7162 v = atomic_dec_return(&req->poll_refs);
7163 if (unlikely(v & IO_POLL_REF_MASK))
7164 __io_poll_execute(req, 0, poll->events);
7168 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7169 struct poll_table_struct *p)
7171 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7172 struct async_poll *apoll = pt->req->apoll;
7174 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7183 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7185 const struct io_op_def *def = &io_op_defs[req->opcode];
7186 struct io_ring_ctx *ctx = req->ctx;
7187 struct async_poll *apoll;
7188 struct io_poll_table ipt;
7189 __poll_t mask = POLLPRI | POLLERR;
7192 if (!def->pollin && !def->pollout)
7193 return IO_APOLL_ABORTED;
7194 if (!file_can_poll(req->file))
7195 return IO_APOLL_ABORTED;
7196 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7197 return IO_APOLL_ABORTED;
7198 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7199 mask |= EPOLLONESHOT;
7202 mask |= EPOLLIN | EPOLLRDNORM;
7204 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7205 if ((req->opcode == IORING_OP_RECVMSG) &&
7206 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7209 mask |= EPOLLOUT | EPOLLWRNORM;
7211 if (def->poll_exclusive)
7212 mask |= EPOLLEXCLUSIVE;
7213 if (req->flags & REQ_F_POLLED) {
7215 kfree(apoll->double_poll);
7216 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7217 !list_empty(&ctx->apoll_cache)) {
7218 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7220 list_del_init(&apoll->poll.wait.entry);
7222 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7223 if (unlikely(!apoll))
7224 return IO_APOLL_ABORTED;
7226 apoll->double_poll = NULL;
7228 req->flags |= REQ_F_POLLED;
7229 ipt.pt._qproc = io_async_queue_proc;
7231 io_kbuf_recycle(req, issue_flags);
7233 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7234 if (ret || ipt.error)
7235 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7237 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7238 mask, apoll->poll.events);
7243 * Returns true if we found and killed one or more poll requests
7245 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7246 struct task_struct *tsk, bool cancel_all)
7248 struct hlist_node *tmp;
7249 struct io_kiocb *req;
7253 spin_lock(&ctx->completion_lock);
7254 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7255 struct hlist_head *list;
7257 list = &ctx->cancel_hash[i];
7258 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7259 if (io_match_task_safe(req, tsk, cancel_all)) {
7260 hlist_del_init(&req->hash_node);
7261 io_poll_cancel_req(req);
7266 spin_unlock(&ctx->completion_lock);
7270 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7271 struct io_cancel_data *cd)
7272 __must_hold(&ctx->completion_lock)
7274 struct hlist_head *list;
7275 struct io_kiocb *req;
7277 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7278 hlist_for_each_entry(req, list, hash_node) {
7279 if (cd->data != req->cqe.user_data)
7281 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7283 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7284 if (cd->seq == req->work.cancel_seq)
7286 req->work.cancel_seq = cd->seq;
7293 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7294 struct io_cancel_data *cd)
7295 __must_hold(&ctx->completion_lock)
7297 struct io_kiocb *req;
7300 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7301 struct hlist_head *list;
7303 list = &ctx->cancel_hash[i];
7304 hlist_for_each_entry(req, list, hash_node) {
7305 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7306 req->file != cd->file)
7308 if (cd->seq == req->work.cancel_seq)
7310 req->work.cancel_seq = cd->seq;
7317 static bool io_poll_disarm(struct io_kiocb *req)
7318 __must_hold(&ctx->completion_lock)
7320 if (!io_poll_get_ownership(req))
7322 io_poll_remove_entries(req);
7323 hash_del(&req->hash_node);
7327 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7328 __must_hold(&ctx->completion_lock)
7330 struct io_kiocb *req;
7332 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7333 req = io_poll_file_find(ctx, cd);
7335 req = io_poll_find(ctx, false, cd);
7338 io_poll_cancel_req(req);
7342 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7347 events = READ_ONCE(sqe->poll32_events);
7349 events = swahw32(events);
7351 if (!(flags & IORING_POLL_ADD_MULTI))
7352 events |= EPOLLONESHOT;
7353 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7356 static int io_poll_remove_prep(struct io_kiocb *req,
7357 const struct io_uring_sqe *sqe)
7359 struct io_poll_update *upd = &req->poll_update;
7362 if (sqe->buf_index || sqe->splice_fd_in)
7364 flags = READ_ONCE(sqe->len);
7365 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7366 IORING_POLL_ADD_MULTI))
7368 /* meaningless without update */
7369 if (flags == IORING_POLL_ADD_MULTI)
7372 upd->old_user_data = READ_ONCE(sqe->addr);
7373 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7374 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7376 upd->new_user_data = READ_ONCE(sqe->off);
7377 if (!upd->update_user_data && upd->new_user_data)
7379 if (upd->update_events)
7380 upd->events = io_poll_parse_events(sqe, flags);
7381 else if (sqe->poll32_events)
7387 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7389 struct io_poll_iocb *poll = &req->poll;
7392 if (sqe->buf_index || sqe->off || sqe->addr)
7394 flags = READ_ONCE(sqe->len);
7395 if (flags & ~IORING_POLL_ADD_MULTI)
7397 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7400 io_req_set_refcount(req);
7401 poll->events = io_poll_parse_events(sqe, flags);
7405 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7407 struct io_poll_iocb *poll = &req->poll;
7408 struct io_poll_table ipt;
7411 ipt.pt._qproc = io_poll_queue_proc;
7413 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7414 if (!ret && ipt.error)
7416 ret = ret ?: ipt.error;
7418 __io_req_complete(req, issue_flags, ret, 0);
7422 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7424 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7425 struct io_ring_ctx *ctx = req->ctx;
7426 struct io_kiocb *preq;
7430 spin_lock(&ctx->completion_lock);
7431 preq = io_poll_find(ctx, true, &cd);
7432 if (!preq || !io_poll_disarm(preq)) {
7433 spin_unlock(&ctx->completion_lock);
7434 ret = preq ? -EALREADY : -ENOENT;
7437 spin_unlock(&ctx->completion_lock);
7439 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7440 /* only mask one event flags, keep behavior flags */
7441 if (req->poll_update.update_events) {
7442 preq->poll.events &= ~0xffff;
7443 preq->poll.events |= req->poll_update.events & 0xffff;
7444 preq->poll.events |= IO_POLL_UNMASK;
7446 if (req->poll_update.update_user_data)
7447 preq->cqe.user_data = req->poll_update.new_user_data;
7449 ret2 = io_poll_add(preq, issue_flags);
7450 /* successfully updated, don't complete poll request */
7456 preq->cqe.res = -ECANCELED;
7457 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7458 io_req_task_complete(preq, &locked);
7462 /* complete update request, we're done with it */
7463 __io_req_complete(req, issue_flags, ret, 0);
7467 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7469 struct io_timeout_data *data = container_of(timer,
7470 struct io_timeout_data, timer);
7471 struct io_kiocb *req = data->req;
7472 struct io_ring_ctx *ctx = req->ctx;
7473 unsigned long flags;
7475 spin_lock_irqsave(&ctx->timeout_lock, flags);
7476 list_del_init(&req->timeout.list);
7477 atomic_set(&req->ctx->cq_timeouts,
7478 atomic_read(&req->ctx->cq_timeouts) + 1);
7479 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7481 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7484 req->cqe.res = -ETIME;
7485 req->io_task_work.func = io_req_task_complete;
7486 io_req_task_work_add(req);
7487 return HRTIMER_NORESTART;
7490 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7491 struct io_cancel_data *cd)
7492 __must_hold(&ctx->timeout_lock)
7494 struct io_timeout_data *io;
7495 struct io_kiocb *req;
7498 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7499 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7500 cd->data != req->cqe.user_data)
7502 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7503 if (cd->seq == req->work.cancel_seq)
7505 req->work.cancel_seq = cd->seq;
7511 return ERR_PTR(-ENOENT);
7513 io = req->async_data;
7514 if (hrtimer_try_to_cancel(&io->timer) == -1)
7515 return ERR_PTR(-EALREADY);
7516 list_del_init(&req->timeout.list);
7520 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7521 __must_hold(&ctx->completion_lock)
7523 struct io_kiocb *req;
7525 spin_lock_irq(&ctx->timeout_lock);
7526 req = io_timeout_extract(ctx, cd);
7527 spin_unlock_irq(&ctx->timeout_lock);
7530 return PTR_ERR(req);
7531 io_req_task_queue_fail(req, -ECANCELED);
7535 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7537 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7538 case IORING_TIMEOUT_BOOTTIME:
7539 return CLOCK_BOOTTIME;
7540 case IORING_TIMEOUT_REALTIME:
7541 return CLOCK_REALTIME;
7543 /* can't happen, vetted at prep time */
7547 return CLOCK_MONOTONIC;
7551 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7552 struct timespec64 *ts, enum hrtimer_mode mode)
7553 __must_hold(&ctx->timeout_lock)
7555 struct io_timeout_data *io;
7556 struct io_kiocb *req;
7559 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7560 found = user_data == req->cqe.user_data;
7567 io = req->async_data;
7568 if (hrtimer_try_to_cancel(&io->timer) == -1)
7570 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7571 io->timer.function = io_link_timeout_fn;
7572 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7576 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7577 struct timespec64 *ts, enum hrtimer_mode mode)
7578 __must_hold(&ctx->timeout_lock)
7580 struct io_cancel_data cd = { .data = user_data, };
7581 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7582 struct io_timeout_data *data;
7585 return PTR_ERR(req);
7587 req->timeout.off = 0; /* noseq */
7588 data = req->async_data;
7589 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7590 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7591 data->timer.function = io_timeout_fn;
7592 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7596 static int io_timeout_remove_prep(struct io_kiocb *req,
7597 const struct io_uring_sqe *sqe)
7599 struct io_timeout_rem *tr = &req->timeout_rem;
7601 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7603 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7606 tr->ltimeout = false;
7607 tr->addr = READ_ONCE(sqe->addr);
7608 tr->flags = READ_ONCE(sqe->timeout_flags);
7609 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7610 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7612 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7613 tr->ltimeout = true;
7614 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7616 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7618 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7620 } else if (tr->flags) {
7621 /* timeout removal doesn't support flags */
7628 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7630 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7635 * Remove or update an existing timeout command
7637 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7639 struct io_timeout_rem *tr = &req->timeout_rem;
7640 struct io_ring_ctx *ctx = req->ctx;
7643 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7644 struct io_cancel_data cd = { .data = tr->addr, };
7646 spin_lock(&ctx->completion_lock);
7647 ret = io_timeout_cancel(ctx, &cd);
7648 spin_unlock(&ctx->completion_lock);
7650 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7652 spin_lock_irq(&ctx->timeout_lock);
7654 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7656 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7657 spin_unlock_irq(&ctx->timeout_lock);
7662 io_req_complete_post(req, ret, 0);
7666 static int __io_timeout_prep(struct io_kiocb *req,
7667 const struct io_uring_sqe *sqe,
7668 bool is_timeout_link)
7670 struct io_timeout_data *data;
7672 u32 off = READ_ONCE(sqe->off);
7674 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7676 if (off && is_timeout_link)
7678 flags = READ_ONCE(sqe->timeout_flags);
7679 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7680 IORING_TIMEOUT_ETIME_SUCCESS))
7682 /* more than one clock specified is invalid, obviously */
7683 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7686 INIT_LIST_HEAD(&req->timeout.list);
7687 req->timeout.off = off;
7688 if (unlikely(off && !req->ctx->off_timeout_used))
7689 req->ctx->off_timeout_used = true;
7691 if (WARN_ON_ONCE(req_has_async_data(req)))
7693 if (io_alloc_async_data(req))
7696 data = req->async_data;
7698 data->flags = flags;
7700 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7703 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7706 INIT_LIST_HEAD(&req->timeout.list);
7707 data->mode = io_translate_timeout_mode(flags);
7708 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7710 if (is_timeout_link) {
7711 struct io_submit_link *link = &req->ctx->submit_state.link;
7715 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7717 req->timeout.head = link->last;
7718 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7723 static int io_timeout_prep(struct io_kiocb *req,
7724 const struct io_uring_sqe *sqe)
7726 return __io_timeout_prep(req, sqe, false);
7729 static int io_link_timeout_prep(struct io_kiocb *req,
7730 const struct io_uring_sqe *sqe)
7732 return __io_timeout_prep(req, sqe, true);
7735 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7737 struct io_ring_ctx *ctx = req->ctx;
7738 struct io_timeout_data *data = req->async_data;
7739 struct list_head *entry;
7740 u32 tail, off = req->timeout.off;
7742 spin_lock_irq(&ctx->timeout_lock);
7745 * sqe->off holds how many events that need to occur for this
7746 * timeout event to be satisfied. If it isn't set, then this is
7747 * a pure timeout request, sequence isn't used.
7749 if (io_is_timeout_noseq(req)) {
7750 entry = ctx->timeout_list.prev;
7754 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7755 req->timeout.target_seq = tail + off;
7757 /* Update the last seq here in case io_flush_timeouts() hasn't.
7758 * This is safe because ->completion_lock is held, and submissions
7759 * and completions are never mixed in the same ->completion_lock section.
7761 ctx->cq_last_tm_flush = tail;
7764 * Insertion sort, ensuring the first entry in the list is always
7765 * the one we need first.
7767 list_for_each_prev(entry, &ctx->timeout_list) {
7768 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7771 if (io_is_timeout_noseq(nxt))
7773 /* nxt.seq is behind @tail, otherwise would've been completed */
7774 if (off >= nxt->timeout.target_seq - tail)
7778 list_add(&req->timeout.list, entry);
7779 data->timer.function = io_timeout_fn;
7780 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7781 spin_unlock_irq(&ctx->timeout_lock);
7785 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7787 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7788 struct io_cancel_data *cd = data;
7790 if (req->ctx != cd->ctx)
7792 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7794 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7795 if (req->file != cd->file)
7798 if (req->cqe.user_data != cd->data)
7801 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7802 if (cd->seq == req->work.cancel_seq)
7804 req->work.cancel_seq = cd->seq;
7809 static int io_async_cancel_one(struct io_uring_task *tctx,
7810 struct io_cancel_data *cd)
7812 enum io_wq_cancel cancel_ret;
7816 if (!tctx || !tctx->io_wq)
7819 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7820 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7821 switch (cancel_ret) {
7822 case IO_WQ_CANCEL_OK:
7825 case IO_WQ_CANCEL_RUNNING:
7828 case IO_WQ_CANCEL_NOTFOUND:
7836 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7838 struct io_ring_ctx *ctx = req->ctx;
7841 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7843 ret = io_async_cancel_one(req->task->io_uring, cd);
7845 * Fall-through even for -EALREADY, as we may have poll armed
7846 * that need unarming.
7851 spin_lock(&ctx->completion_lock);
7852 ret = io_poll_cancel(ctx, cd);
7855 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7856 ret = io_timeout_cancel(ctx, cd);
7858 spin_unlock(&ctx->completion_lock);
7862 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7863 IORING_ASYNC_CANCEL_ANY)
7865 static int io_async_cancel_prep(struct io_kiocb *req,
7866 const struct io_uring_sqe *sqe)
7868 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7870 if (sqe->off || sqe->len || sqe->splice_fd_in)
7873 req->cancel.addr = READ_ONCE(sqe->addr);
7874 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7875 if (req->cancel.flags & ~CANCEL_FLAGS)
7877 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7878 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7880 req->cancel.fd = READ_ONCE(sqe->fd);
7886 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7887 unsigned int issue_flags)
7889 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7890 struct io_ring_ctx *ctx = cd->ctx;
7891 struct io_tctx_node *node;
7895 ret = io_try_cancel(req, cd);
7903 /* slow path, try all io-wq's */
7904 io_ring_submit_lock(ctx, issue_flags);
7906 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7907 struct io_uring_task *tctx = node->task->io_uring;
7909 ret = io_async_cancel_one(tctx, cd);
7910 if (ret != -ENOENT) {
7916 io_ring_submit_unlock(ctx, issue_flags);
7917 return all ? nr : ret;
7920 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7922 struct io_cancel_data cd = {
7924 .data = req->cancel.addr,
7925 .flags = req->cancel.flags,
7926 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7930 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7931 if (req->flags & REQ_F_FIXED_FILE)
7932 req->file = io_file_get_fixed(req, req->cancel.fd,
7935 req->file = io_file_get_normal(req, req->cancel.fd);
7940 cd.file = req->file;
7943 ret = __io_async_cancel(&cd, req, issue_flags);
7947 io_req_complete_post(req, ret, 0);
7951 static int io_files_update_prep(struct io_kiocb *req,
7952 const struct io_uring_sqe *sqe)
7954 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7956 if (sqe->rw_flags || sqe->splice_fd_in)
7959 req->rsrc_update.offset = READ_ONCE(sqe->off);
7960 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7961 if (!req->rsrc_update.nr_args)
7963 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7967 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7968 unsigned int issue_flags)
7970 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7975 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7976 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7986 ret = io_fixed_fd_install(req, issue_flags, file,
7987 IORING_FILE_INDEX_ALLOC);
7990 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
7991 __io_close_fixed(req, issue_flags, ret);
8002 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
8004 struct io_ring_ctx *ctx = req->ctx;
8005 struct io_uring_rsrc_update2 up;
8008 up.offset = req->rsrc_update.offset;
8009 up.data = req->rsrc_update.arg;
8015 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
8016 ret = io_files_update_with_index_alloc(req, issue_flags);
8018 io_ring_submit_lock(ctx, issue_flags);
8019 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
8020 &up, req->rsrc_update.nr_args);
8021 io_ring_submit_unlock(ctx, issue_flags);
8026 __io_req_complete(req, issue_flags, ret, 0);
8030 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
8032 switch (req->opcode) {
8034 return io_nop_prep(req, sqe);
8035 case IORING_OP_READV:
8036 case IORING_OP_READ_FIXED:
8037 case IORING_OP_READ:
8038 case IORING_OP_WRITEV:
8039 case IORING_OP_WRITE_FIXED:
8040 case IORING_OP_WRITE:
8041 return io_prep_rw(req, sqe);
8042 case IORING_OP_POLL_ADD:
8043 return io_poll_add_prep(req, sqe);
8044 case IORING_OP_POLL_REMOVE:
8045 return io_poll_remove_prep(req, sqe);
8046 case IORING_OP_FSYNC:
8047 return io_fsync_prep(req, sqe);
8048 case IORING_OP_SYNC_FILE_RANGE:
8049 return io_sfr_prep(req, sqe);
8050 case IORING_OP_SENDMSG:
8051 case IORING_OP_SEND:
8052 return io_sendmsg_prep(req, sqe);
8053 case IORING_OP_RECVMSG:
8054 case IORING_OP_RECV:
8055 return io_recvmsg_prep(req, sqe);
8056 case IORING_OP_CONNECT:
8057 return io_connect_prep(req, sqe);
8058 case IORING_OP_TIMEOUT:
8059 return io_timeout_prep(req, sqe);
8060 case IORING_OP_TIMEOUT_REMOVE:
8061 return io_timeout_remove_prep(req, sqe);
8062 case IORING_OP_ASYNC_CANCEL:
8063 return io_async_cancel_prep(req, sqe);
8064 case IORING_OP_LINK_TIMEOUT:
8065 return io_link_timeout_prep(req, sqe);
8066 case IORING_OP_ACCEPT:
8067 return io_accept_prep(req, sqe);
8068 case IORING_OP_FALLOCATE:
8069 return io_fallocate_prep(req, sqe);
8070 case IORING_OP_OPENAT:
8071 return io_openat_prep(req, sqe);
8072 case IORING_OP_CLOSE:
8073 return io_close_prep(req, sqe);
8074 case IORING_OP_FILES_UPDATE:
8075 return io_files_update_prep(req, sqe);
8076 case IORING_OP_STATX:
8077 return io_statx_prep(req, sqe);
8078 case IORING_OP_FADVISE:
8079 return io_fadvise_prep(req, sqe);
8080 case IORING_OP_MADVISE:
8081 return io_madvise_prep(req, sqe);
8082 case IORING_OP_OPENAT2:
8083 return io_openat2_prep(req, sqe);
8084 case IORING_OP_EPOLL_CTL:
8085 return io_epoll_ctl_prep(req, sqe);
8086 case IORING_OP_SPLICE:
8087 return io_splice_prep(req, sqe);
8088 case IORING_OP_PROVIDE_BUFFERS:
8089 return io_provide_buffers_prep(req, sqe);
8090 case IORING_OP_REMOVE_BUFFERS:
8091 return io_remove_buffers_prep(req, sqe);
8093 return io_tee_prep(req, sqe);
8094 case IORING_OP_SHUTDOWN:
8095 return io_shutdown_prep(req, sqe);
8096 case IORING_OP_RENAMEAT:
8097 return io_renameat_prep(req, sqe);
8098 case IORING_OP_UNLINKAT:
8099 return io_unlinkat_prep(req, sqe);
8100 case IORING_OP_MKDIRAT:
8101 return io_mkdirat_prep(req, sqe);
8102 case IORING_OP_SYMLINKAT:
8103 return io_symlinkat_prep(req, sqe);
8104 case IORING_OP_LINKAT:
8105 return io_linkat_prep(req, sqe);
8106 case IORING_OP_MSG_RING:
8107 return io_msg_ring_prep(req, sqe);
8108 case IORING_OP_FSETXATTR:
8109 return io_fsetxattr_prep(req, sqe);
8110 case IORING_OP_SETXATTR:
8111 return io_setxattr_prep(req, sqe);
8112 case IORING_OP_FGETXATTR:
8113 return io_fgetxattr_prep(req, sqe);
8114 case IORING_OP_GETXATTR:
8115 return io_getxattr_prep(req, sqe);
8116 case IORING_OP_SOCKET:
8117 return io_socket_prep(req, sqe);
8118 case IORING_OP_URING_CMD:
8119 return io_uring_cmd_prep(req, sqe);
8122 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
8127 static int io_req_prep_async(struct io_kiocb *req)
8129 const struct io_op_def *def = &io_op_defs[req->opcode];
8131 /* assign early for deferred execution for non-fixed file */
8132 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
8133 req->file = io_file_get_normal(req, req->cqe.fd);
8134 if (!def->needs_async_setup)
8136 if (WARN_ON_ONCE(req_has_async_data(req)))
8138 if (io_alloc_async_data(req))
8141 switch (req->opcode) {
8142 case IORING_OP_READV:
8143 return io_readv_prep_async(req);
8144 case IORING_OP_WRITEV:
8145 return io_writev_prep_async(req);
8146 case IORING_OP_SENDMSG:
8147 return io_sendmsg_prep_async(req);
8148 case IORING_OP_RECVMSG:
8149 return io_recvmsg_prep_async(req);
8150 case IORING_OP_CONNECT:
8151 return io_connect_prep_async(req);
8152 case IORING_OP_URING_CMD:
8153 return io_uring_cmd_prep_async(req);
8155 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
8160 static u32 io_get_sequence(struct io_kiocb *req)
8162 u32 seq = req->ctx->cached_sq_head;
8163 struct io_kiocb *cur;
8165 /* need original cached_sq_head, but it was increased for each req */
8166 io_for_each_link(cur, req)
8171 static __cold void io_drain_req(struct io_kiocb *req)
8173 struct io_ring_ctx *ctx = req->ctx;
8174 struct io_defer_entry *de;
8176 u32 seq = io_get_sequence(req);
8178 /* Still need defer if there is pending req in defer list. */
8179 spin_lock(&ctx->completion_lock);
8180 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
8181 spin_unlock(&ctx->completion_lock);
8183 ctx->drain_active = false;
8184 io_req_task_queue(req);
8187 spin_unlock(&ctx->completion_lock);
8189 ret = io_req_prep_async(req);
8192 io_req_complete_failed(req, ret);
8195 io_prep_async_link(req);
8196 de = kmalloc(sizeof(*de), GFP_KERNEL);
8202 spin_lock(&ctx->completion_lock);
8203 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
8204 spin_unlock(&ctx->completion_lock);
8209 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
8212 list_add_tail(&de->list, &ctx->defer_list);
8213 spin_unlock(&ctx->completion_lock);
8216 static void io_clean_op(struct io_kiocb *req)
8218 if (req->flags & REQ_F_BUFFER_SELECTED) {
8219 spin_lock(&req->ctx->completion_lock);
8220 io_put_kbuf_comp(req);
8221 spin_unlock(&req->ctx->completion_lock);
8224 if (req->flags & REQ_F_NEED_CLEANUP) {
8225 switch (req->opcode) {
8226 case IORING_OP_READV:
8227 case IORING_OP_READ_FIXED:
8228 case IORING_OP_READ:
8229 case IORING_OP_WRITEV:
8230 case IORING_OP_WRITE_FIXED:
8231 case IORING_OP_WRITE: {
8232 struct io_async_rw *io = req->async_data;
8234 kfree(io->free_iovec);
8237 case IORING_OP_RECVMSG:
8238 case IORING_OP_SENDMSG: {
8239 struct io_async_msghdr *io = req->async_data;
8241 kfree(io->free_iov);
8244 case IORING_OP_OPENAT:
8245 case IORING_OP_OPENAT2:
8246 if (req->open.filename)
8247 putname(req->open.filename);
8249 case IORING_OP_RENAMEAT:
8250 putname(req->rename.oldpath);
8251 putname(req->rename.newpath);
8253 case IORING_OP_UNLINKAT:
8254 putname(req->unlink.filename);
8256 case IORING_OP_MKDIRAT:
8257 putname(req->mkdir.filename);
8259 case IORING_OP_SYMLINKAT:
8260 putname(req->symlink.oldpath);
8261 putname(req->symlink.newpath);
8263 case IORING_OP_LINKAT:
8264 putname(req->hardlink.oldpath);
8265 putname(req->hardlink.newpath);
8267 case IORING_OP_STATX:
8268 if (req->statx.filename)
8269 putname(req->statx.filename);
8271 case IORING_OP_SETXATTR:
8272 case IORING_OP_FSETXATTR:
8273 case IORING_OP_GETXATTR:
8274 case IORING_OP_FGETXATTR:
8275 __io_xattr_finish(req);
8279 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8280 kfree(req->apoll->double_poll);
8284 if (req->flags & REQ_F_INFLIGHT) {
8285 struct io_uring_task *tctx = req->task->io_uring;
8287 atomic_dec(&tctx->inflight_tracked);
8289 if (req->flags & REQ_F_CREDS)
8290 put_cred(req->creds);
8291 if (req->flags & REQ_F_ASYNC_DATA) {
8292 kfree(req->async_data);
8293 req->async_data = NULL;
8295 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8298 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8300 if (req->file || !io_op_defs[req->opcode].needs_file)
8303 if (req->flags & REQ_F_FIXED_FILE)
8304 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8306 req->file = io_file_get_normal(req, req->cqe.fd);
8311 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8313 const struct io_op_def *def = &io_op_defs[req->opcode];
8314 const struct cred *creds = NULL;
8317 if (unlikely(!io_assign_file(req, issue_flags)))
8320 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8321 creds = override_creds(req->creds);
8323 if (!def->audit_skip)
8324 audit_uring_entry(req->opcode);
8326 switch (req->opcode) {
8328 ret = io_nop(req, issue_flags);
8330 case IORING_OP_READV:
8331 case IORING_OP_READ_FIXED:
8332 case IORING_OP_READ:
8333 ret = io_read(req, issue_flags);
8335 case IORING_OP_WRITEV:
8336 case IORING_OP_WRITE_FIXED:
8337 case IORING_OP_WRITE:
8338 ret = io_write(req, issue_flags);
8340 case IORING_OP_FSYNC:
8341 ret = io_fsync(req, issue_flags);
8343 case IORING_OP_POLL_ADD:
8344 ret = io_poll_add(req, issue_flags);
8346 case IORING_OP_POLL_REMOVE:
8347 ret = io_poll_remove(req, issue_flags);
8349 case IORING_OP_SYNC_FILE_RANGE:
8350 ret = io_sync_file_range(req, issue_flags);
8352 case IORING_OP_SENDMSG:
8353 ret = io_sendmsg(req, issue_flags);
8355 case IORING_OP_SEND:
8356 ret = io_send(req, issue_flags);
8358 case IORING_OP_RECVMSG:
8359 ret = io_recvmsg(req, issue_flags);
8361 case IORING_OP_RECV:
8362 ret = io_recv(req, issue_flags);
8364 case IORING_OP_TIMEOUT:
8365 ret = io_timeout(req, issue_flags);
8367 case IORING_OP_TIMEOUT_REMOVE:
8368 ret = io_timeout_remove(req, issue_flags);
8370 case IORING_OP_ACCEPT:
8371 ret = io_accept(req, issue_flags);
8373 case IORING_OP_CONNECT:
8374 ret = io_connect(req, issue_flags);
8376 case IORING_OP_ASYNC_CANCEL:
8377 ret = io_async_cancel(req, issue_flags);
8379 case IORING_OP_FALLOCATE:
8380 ret = io_fallocate(req, issue_flags);
8382 case IORING_OP_OPENAT:
8383 ret = io_openat(req, issue_flags);
8385 case IORING_OP_CLOSE:
8386 ret = io_close(req, issue_flags);
8388 case IORING_OP_FILES_UPDATE:
8389 ret = io_files_update(req, issue_flags);
8391 case IORING_OP_STATX:
8392 ret = io_statx(req, issue_flags);
8394 case IORING_OP_FADVISE:
8395 ret = io_fadvise(req, issue_flags);
8397 case IORING_OP_MADVISE:
8398 ret = io_madvise(req, issue_flags);
8400 case IORING_OP_OPENAT2:
8401 ret = io_openat2(req, issue_flags);
8403 case IORING_OP_EPOLL_CTL:
8404 ret = io_epoll_ctl(req, issue_flags);
8406 case IORING_OP_SPLICE:
8407 ret = io_splice(req, issue_flags);
8409 case IORING_OP_PROVIDE_BUFFERS:
8410 ret = io_provide_buffers(req, issue_flags);
8412 case IORING_OP_REMOVE_BUFFERS:
8413 ret = io_remove_buffers(req, issue_flags);
8416 ret = io_tee(req, issue_flags);
8418 case IORING_OP_SHUTDOWN:
8419 ret = io_shutdown(req, issue_flags);
8421 case IORING_OP_RENAMEAT:
8422 ret = io_renameat(req, issue_flags);
8424 case IORING_OP_UNLINKAT:
8425 ret = io_unlinkat(req, issue_flags);
8427 case IORING_OP_MKDIRAT:
8428 ret = io_mkdirat(req, issue_flags);
8430 case IORING_OP_SYMLINKAT:
8431 ret = io_symlinkat(req, issue_flags);
8433 case IORING_OP_LINKAT:
8434 ret = io_linkat(req, issue_flags);
8436 case IORING_OP_MSG_RING:
8437 ret = io_msg_ring(req, issue_flags);
8439 case IORING_OP_FSETXATTR:
8440 ret = io_fsetxattr(req, issue_flags);
8442 case IORING_OP_SETXATTR:
8443 ret = io_setxattr(req, issue_flags);
8445 case IORING_OP_FGETXATTR:
8446 ret = io_fgetxattr(req, issue_flags);
8448 case IORING_OP_GETXATTR:
8449 ret = io_getxattr(req, issue_flags);
8451 case IORING_OP_SOCKET:
8452 ret = io_socket(req, issue_flags);
8454 case IORING_OP_URING_CMD:
8455 ret = io_uring_cmd(req, issue_flags);
8462 if (!def->audit_skip)
8463 audit_uring_exit(!ret, ret);
8466 revert_creds(creds);
8469 /* If the op doesn't have a file, we're not polling for it */
8470 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8471 io_iopoll_req_issued(req, issue_flags);
8476 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8478 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8480 req = io_put_req_find_next(req);
8481 return req ? &req->work : NULL;
8484 static void io_wq_submit_work(struct io_wq_work *work)
8486 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8487 const struct io_op_def *def = &io_op_defs[req->opcode];
8488 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8489 bool needs_poll = false;
8490 int ret = 0, err = -ECANCELED;
8492 /* one will be dropped by ->io_free_work() after returning to io-wq */
8493 if (!(req->flags & REQ_F_REFCOUNT))
8494 __io_req_set_refcount(req, 2);
8498 io_arm_ltimeout(req);
8500 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8501 if (work->flags & IO_WQ_WORK_CANCEL) {
8503 io_req_task_queue_fail(req, err);
8506 if (!io_assign_file(req, issue_flags)) {
8508 work->flags |= IO_WQ_WORK_CANCEL;
8512 if (req->flags & REQ_F_FORCE_ASYNC) {
8513 bool opcode_poll = def->pollin || def->pollout;
8515 if (opcode_poll && file_can_poll(req->file)) {
8517 issue_flags |= IO_URING_F_NONBLOCK;
8522 ret = io_issue_sqe(req, issue_flags);
8526 * We can get EAGAIN for iopolled IO even though we're
8527 * forcing a sync submission from here, since we can't
8528 * wait for request slots on the block side.
8531 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8537 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8539 /* aborted or ready, in either case retry blocking */
8541 issue_flags &= ~IO_URING_F_NONBLOCK;
8544 /* avoid locking problems by failing it from a clean context */
8546 io_req_task_queue_fail(req, ret);
8549 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8552 return &table->files[i];
8555 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8558 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8560 return (struct file *) (slot->file_ptr & FFS_MASK);
8563 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8565 unsigned long file_ptr = (unsigned long) file;
8567 file_ptr |= io_file_get_flags(file);
8568 file_slot->file_ptr = file_ptr;
8571 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8572 unsigned int issue_flags)
8574 struct io_ring_ctx *ctx = req->ctx;
8575 struct file *file = NULL;
8576 unsigned long file_ptr;
8578 io_ring_submit_lock(ctx, issue_flags);
8580 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8582 fd = array_index_nospec(fd, ctx->nr_user_files);
8583 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8584 file = (struct file *) (file_ptr & FFS_MASK);
8585 file_ptr &= ~FFS_MASK;
8586 /* mask in overlapping REQ_F and FFS bits */
8587 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8588 io_req_set_rsrc_node(req, ctx, 0);
8589 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8591 io_ring_submit_unlock(ctx, issue_flags);
8595 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8597 struct file *file = fget(fd);
8599 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8601 /* we don't allow fixed io_uring files */
8602 if (file && file->f_op == &io_uring_fops)
8603 io_req_track_inflight(req);
8607 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8609 struct io_kiocb *prev = req->timeout.prev;
8613 if (!(req->task->flags & PF_EXITING)) {
8614 struct io_cancel_data cd = {
8616 .data = prev->cqe.user_data,
8619 ret = io_try_cancel(req, &cd);
8621 io_req_complete_post(req, ret ?: -ETIME, 0);
8624 io_req_complete_post(req, -ETIME, 0);
8628 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8630 struct io_timeout_data *data = container_of(timer,
8631 struct io_timeout_data, timer);
8632 struct io_kiocb *prev, *req = data->req;
8633 struct io_ring_ctx *ctx = req->ctx;
8634 unsigned long flags;
8636 spin_lock_irqsave(&ctx->timeout_lock, flags);
8637 prev = req->timeout.head;
8638 req->timeout.head = NULL;
8641 * We don't expect the list to be empty, that will only happen if we
8642 * race with the completion of the linked work.
8645 io_remove_next_linked(prev);
8646 if (!req_ref_inc_not_zero(prev))
8649 list_del(&req->timeout.list);
8650 req->timeout.prev = prev;
8651 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8653 req->io_task_work.func = io_req_task_link_timeout;
8654 io_req_task_work_add(req);
8655 return HRTIMER_NORESTART;
8658 static void io_queue_linked_timeout(struct io_kiocb *req)
8660 struct io_ring_ctx *ctx = req->ctx;
8662 spin_lock_irq(&ctx->timeout_lock);
8664 * If the back reference is NULL, then our linked request finished
8665 * before we got a chance to setup the timer
8667 if (req->timeout.head) {
8668 struct io_timeout_data *data = req->async_data;
8670 data->timer.function = io_link_timeout_fn;
8671 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8673 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8675 spin_unlock_irq(&ctx->timeout_lock);
8676 /* drop submission reference */
8680 static void io_queue_async(struct io_kiocb *req, int ret)
8681 __must_hold(&req->ctx->uring_lock)
8683 struct io_kiocb *linked_timeout;
8685 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8686 io_req_complete_failed(req, ret);
8690 linked_timeout = io_prep_linked_timeout(req);
8692 switch (io_arm_poll_handler(req, 0)) {
8693 case IO_APOLL_READY:
8694 io_req_task_queue(req);
8696 case IO_APOLL_ABORTED:
8698 * Queued up for async execution, worker will release
8699 * submit reference when the iocb is actually submitted.
8701 io_kbuf_recycle(req, 0);
8702 io_queue_iowq(req, NULL);
8709 io_queue_linked_timeout(linked_timeout);
8712 static inline void io_queue_sqe(struct io_kiocb *req)
8713 __must_hold(&req->ctx->uring_lock)
8717 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8719 if (req->flags & REQ_F_COMPLETE_INLINE) {
8720 io_req_add_compl_list(req);
8724 * We async punt it if the file wasn't marked NOWAIT, or if the file
8725 * doesn't support non-blocking read/write attempts
8728 io_arm_ltimeout(req);
8730 io_queue_async(req, ret);
8733 static void io_queue_sqe_fallback(struct io_kiocb *req)
8734 __must_hold(&req->ctx->uring_lock)
8736 if (unlikely(req->flags & REQ_F_FAIL)) {
8738 * We don't submit, fail them all, for that replace hardlinks
8739 * with normal links. Extra REQ_F_LINK is tolerated.
8741 req->flags &= ~REQ_F_HARDLINK;
8742 req->flags |= REQ_F_LINK;
8743 io_req_complete_failed(req, req->cqe.res);
8744 } else if (unlikely(req->ctx->drain_active)) {
8747 int ret = io_req_prep_async(req);
8750 io_req_complete_failed(req, ret);
8752 io_queue_iowq(req, NULL);
8757 * Check SQE restrictions (opcode and flags).
8759 * Returns 'true' if SQE is allowed, 'false' otherwise.
8761 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8762 struct io_kiocb *req,
8763 unsigned int sqe_flags)
8765 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8768 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8769 ctx->restrictions.sqe_flags_required)
8772 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8773 ctx->restrictions.sqe_flags_required))
8779 static void io_init_req_drain(struct io_kiocb *req)
8781 struct io_ring_ctx *ctx = req->ctx;
8782 struct io_kiocb *head = ctx->submit_state.link.head;
8784 ctx->drain_active = true;
8787 * If we need to drain a request in the middle of a link, drain
8788 * the head request and the next request/link after the current
8789 * link. Considering sequential execution of links,
8790 * REQ_F_IO_DRAIN will be maintained for every request of our
8793 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8794 ctx->drain_next = true;
8798 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8799 const struct io_uring_sqe *sqe)
8800 __must_hold(&ctx->uring_lock)
8802 const struct io_op_def *def;
8803 unsigned int sqe_flags;
8807 /* req is partially pre-initialised, see io_preinit_req() */
8808 req->opcode = opcode = READ_ONCE(sqe->opcode);
8809 /* same numerical values with corresponding REQ_F_*, safe to copy */
8810 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8811 req->cqe.user_data = READ_ONCE(sqe->user_data);
8813 req->rsrc_node = NULL;
8814 req->task = current;
8816 if (unlikely(opcode >= IORING_OP_LAST)) {
8820 def = &io_op_defs[opcode];
8821 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8822 /* enforce forwards compatibility on users */
8823 if (sqe_flags & ~SQE_VALID_FLAGS)
8825 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8826 if (!def->buffer_select)
8828 req->buf_index = READ_ONCE(sqe->buf_group);
8830 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8831 ctx->drain_disabled = true;
8832 if (sqe_flags & IOSQE_IO_DRAIN) {
8833 if (ctx->drain_disabled)
8835 io_init_req_drain(req);
8838 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8839 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8841 /* knock it to the slow queue path, will be drained there */
8842 if (ctx->drain_active)
8843 req->flags |= REQ_F_FORCE_ASYNC;
8844 /* if there is no link, we're at "next" request and need to drain */
8845 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8846 ctx->drain_next = false;
8847 ctx->drain_active = true;
8848 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8852 if (!def->ioprio && sqe->ioprio)
8854 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8857 if (def->needs_file) {
8858 struct io_submit_state *state = &ctx->submit_state;
8860 req->cqe.fd = READ_ONCE(sqe->fd);
8863 * Plug now if we have more than 2 IO left after this, and the
8864 * target is potentially a read/write to block based storage.
8866 if (state->need_plug && def->plug) {
8867 state->plug_started = true;
8868 state->need_plug = false;
8869 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8873 personality = READ_ONCE(sqe->personality);
8877 req->creds = xa_load(&ctx->personalities, personality);
8880 get_cred(req->creds);
8881 ret = security_uring_override_creds(req->creds);
8883 put_cred(req->creds);
8886 req->flags |= REQ_F_CREDS;
8889 return io_req_prep(req, sqe);
8892 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8893 struct io_kiocb *req, int ret)
8895 struct io_ring_ctx *ctx = req->ctx;
8896 struct io_submit_link *link = &ctx->submit_state.link;
8897 struct io_kiocb *head = link->head;
8899 trace_io_uring_req_failed(sqe, ctx, req, ret);
8902 * Avoid breaking links in the middle as it renders links with SQPOLL
8903 * unusable. Instead of failing eagerly, continue assembling the link if
8904 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8905 * should find the flag and handle the rest.
8907 req_fail_link_node(req, ret);
8908 if (head && !(head->flags & REQ_F_FAIL))
8909 req_fail_link_node(head, -ECANCELED);
8911 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8913 link->last->link = req;
8917 io_queue_sqe_fallback(req);
8922 link->last->link = req;
8929 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8930 const struct io_uring_sqe *sqe)
8931 __must_hold(&ctx->uring_lock)
8933 struct io_submit_link *link = &ctx->submit_state.link;
8936 ret = io_init_req(ctx, req, sqe);
8938 return io_submit_fail_init(sqe, req, ret);
8940 /* don't need @sqe from now on */
8941 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8943 ctx->flags & IORING_SETUP_SQPOLL);
8946 * If we already have a head request, queue this one for async
8947 * submittal once the head completes. If we don't have a head but
8948 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8949 * submitted sync once the chain is complete. If none of those
8950 * conditions are true (normal request), then just queue it.
8952 if (unlikely(link->head)) {
8953 ret = io_req_prep_async(req);
8955 return io_submit_fail_init(sqe, req, ret);
8957 trace_io_uring_link(ctx, req, link->head);
8958 link->last->link = req;
8961 if (req->flags & IO_REQ_LINK_FLAGS)
8963 /* last request of the link, flush it */
8966 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8969 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8970 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8971 if (req->flags & IO_REQ_LINK_FLAGS) {
8976 io_queue_sqe_fallback(req);
8986 * Batched submission is done, ensure local IO is flushed out.
8988 static void io_submit_state_end(struct io_ring_ctx *ctx)
8990 struct io_submit_state *state = &ctx->submit_state;
8992 if (unlikely(state->link.head))
8993 io_queue_sqe_fallback(state->link.head);
8994 /* flush only after queuing links as they can generate completions */
8995 io_submit_flush_completions(ctx);
8996 if (state->plug_started)
8997 blk_finish_plug(&state->plug);
9001 * Start submission side cache.
9003 static void io_submit_state_start(struct io_submit_state *state,
9004 unsigned int max_ios)
9006 state->plug_started = false;
9007 state->need_plug = max_ios > 2;
9008 state->submit_nr = max_ios;
9009 /* set only head, no need to init link_last in advance */
9010 state->link.head = NULL;
9013 static void io_commit_sqring(struct io_ring_ctx *ctx)
9015 struct io_rings *rings = ctx->rings;
9018 * Ensure any loads from the SQEs are done at this point,
9019 * since once we write the new head, the application could
9020 * write new data to them.
9022 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
9026 * Fetch an sqe, if one is available. Note this returns a pointer to memory
9027 * that is mapped by userspace. This means that care needs to be taken to
9028 * ensure that reads are stable, as we cannot rely on userspace always
9029 * being a good citizen. If members of the sqe are validated and then later
9030 * used, it's important that those reads are done through READ_ONCE() to
9031 * prevent a re-load down the line.
9033 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
9035 unsigned head, mask = ctx->sq_entries - 1;
9036 unsigned sq_idx = ctx->cached_sq_head++ & mask;
9039 * The cached sq head (or cq tail) serves two purposes:
9041 * 1) allows us to batch the cost of updating the user visible
9043 * 2) allows the kernel side to track the head on its own, even
9044 * though the application is the one updating it.
9046 head = READ_ONCE(ctx->sq_array[sq_idx]);
9047 if (likely(head < ctx->sq_entries)) {
9048 /* double index for 128-byte SQEs, twice as long */
9049 if (ctx->flags & IORING_SETUP_SQE128)
9051 return &ctx->sq_sqes[head];
9054 /* drop invalid entries */
9056 WRITE_ONCE(ctx->rings->sq_dropped,
9057 READ_ONCE(ctx->rings->sq_dropped) + 1);
9061 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
9062 __must_hold(&ctx->uring_lock)
9064 unsigned int entries = io_sqring_entries(ctx);
9068 if (unlikely(!entries))
9070 /* make sure SQ entry isn't read before tail */
9071 ret = left = min3(nr, ctx->sq_entries, entries);
9072 io_get_task_refs(left);
9073 io_submit_state_start(&ctx->submit_state, left);
9076 const struct io_uring_sqe *sqe;
9077 struct io_kiocb *req;
9079 if (unlikely(!io_alloc_req_refill(ctx)))
9081 req = io_alloc_req(ctx);
9082 sqe = io_get_sqe(ctx);
9083 if (unlikely(!sqe)) {
9084 io_req_add_to_cache(req, ctx);
9089 * Continue submitting even for sqe failure if the
9090 * ring was setup with IORING_SETUP_SUBMIT_ALL
9092 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
9093 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
9099 if (unlikely(left)) {
9101 /* try again if it submitted nothing and can't allocate a req */
9102 if (!ret && io_req_cache_empty(ctx))
9104 current->io_uring->cached_refs += left;
9107 io_submit_state_end(ctx);
9108 /* Commit SQ ring head once we've consumed and submitted all SQEs */
9109 io_commit_sqring(ctx);
9113 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
9115 return READ_ONCE(sqd->state);
9118 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
9120 unsigned int to_submit;
9123 to_submit = io_sqring_entries(ctx);
9124 /* if we're handling multiple rings, cap submit size for fairness */
9125 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
9126 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
9128 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
9129 const struct cred *creds = NULL;
9131 if (ctx->sq_creds != current_cred())
9132 creds = override_creds(ctx->sq_creds);
9134 mutex_lock(&ctx->uring_lock);
9135 if (!wq_list_empty(&ctx->iopoll_list))
9136 io_do_iopoll(ctx, true);
9139 * Don't submit if refs are dying, good for io_uring_register(),
9140 * but also it is relied upon by io_ring_exit_work()
9142 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
9143 !(ctx->flags & IORING_SETUP_R_DISABLED))
9144 ret = io_submit_sqes(ctx, to_submit);
9145 mutex_unlock(&ctx->uring_lock);
9147 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
9148 wake_up(&ctx->sqo_sq_wait);
9150 revert_creds(creds);
9156 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
9158 struct io_ring_ctx *ctx;
9159 unsigned sq_thread_idle = 0;
9161 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9162 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
9163 sqd->sq_thread_idle = sq_thread_idle;
9166 static bool io_sqd_handle_event(struct io_sq_data *sqd)
9168 bool did_sig = false;
9169 struct ksignal ksig;
9171 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
9172 signal_pending(current)) {
9173 mutex_unlock(&sqd->lock);
9174 if (signal_pending(current))
9175 did_sig = get_signal(&ksig);
9177 mutex_lock(&sqd->lock);
9179 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9182 static int io_sq_thread(void *data)
9184 struct io_sq_data *sqd = data;
9185 struct io_ring_ctx *ctx;
9186 unsigned long timeout = 0;
9187 char buf[TASK_COMM_LEN];
9190 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
9191 set_task_comm(current, buf);
9193 if (sqd->sq_cpu != -1)
9194 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
9196 set_cpus_allowed_ptr(current, cpu_online_mask);
9197 current->flags |= PF_NO_SETAFFINITY;
9199 audit_alloc_kernel(current);
9201 mutex_lock(&sqd->lock);
9203 bool cap_entries, sqt_spin = false;
9205 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
9206 if (io_sqd_handle_event(sqd))
9208 timeout = jiffies + sqd->sq_thread_idle;
9211 cap_entries = !list_is_singular(&sqd->ctx_list);
9212 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9213 int ret = __io_sq_thread(ctx, cap_entries);
9215 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
9218 if (io_run_task_work())
9221 if (sqt_spin || !time_after(jiffies, timeout)) {
9224 timeout = jiffies + sqd->sq_thread_idle;
9228 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
9229 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
9230 bool needs_sched = true;
9232 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9233 atomic_or(IORING_SQ_NEED_WAKEUP,
9234 &ctx->rings->sq_flags);
9235 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
9236 !wq_list_empty(&ctx->iopoll_list)) {
9237 needs_sched = false;
9242 * Ensure the store of the wakeup flag is not
9243 * reordered with the load of the SQ tail
9245 smp_mb__after_atomic();
9247 if (io_sqring_entries(ctx)) {
9248 needs_sched = false;
9254 mutex_unlock(&sqd->lock);
9256 mutex_lock(&sqd->lock);
9258 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9259 atomic_andnot(IORING_SQ_NEED_WAKEUP,
9260 &ctx->rings->sq_flags);
9263 finish_wait(&sqd->wait, &wait);
9264 timeout = jiffies + sqd->sq_thread_idle;
9267 io_uring_cancel_generic(true, sqd);
9269 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9270 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9272 mutex_unlock(&sqd->lock);
9274 audit_free(current);
9276 complete(&sqd->exited);
9280 struct io_wait_queue {
9281 struct wait_queue_entry wq;
9282 struct io_ring_ctx *ctx;
9284 unsigned nr_timeouts;
9287 static inline bool io_should_wake(struct io_wait_queue *iowq)
9289 struct io_ring_ctx *ctx = iowq->ctx;
9290 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9293 * Wake up if we have enough events, or if a timeout occurred since we
9294 * started waiting. For timeouts, we always want to return to userspace,
9295 * regardless of event count.
9297 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9300 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9301 int wake_flags, void *key)
9303 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9307 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9308 * the task, and the next invocation will do it.
9310 if (io_should_wake(iowq) ||
9311 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9312 return autoremove_wake_function(curr, mode, wake_flags, key);
9316 static int io_run_task_work_sig(void)
9318 if (io_run_task_work())
9320 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9321 return -ERESTARTSYS;
9322 if (task_sigpending(current))
9327 /* when returns >0, the caller should retry */
9328 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9329 struct io_wait_queue *iowq,
9333 unsigned long check_cq;
9335 /* make sure we run task_work before checking for signals */
9336 ret = io_run_task_work_sig();
9337 if (ret || io_should_wake(iowq))
9339 check_cq = READ_ONCE(ctx->check_cq);
9340 /* let the caller flush overflows, retry */
9341 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9343 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9345 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9351 * Wait until events become available, if we don't already have some. The
9352 * application must reap them itself, as they reside on the shared cq ring.
9354 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9355 const sigset_t __user *sig, size_t sigsz,
9356 struct __kernel_timespec __user *uts)
9358 struct io_wait_queue iowq;
9359 struct io_rings *rings = ctx->rings;
9360 ktime_t timeout = KTIME_MAX;
9364 io_cqring_overflow_flush(ctx);
9365 if (io_cqring_events(ctx) >= min_events)
9367 if (!io_run_task_work())
9372 #ifdef CONFIG_COMPAT
9373 if (in_compat_syscall())
9374 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9378 ret = set_user_sigmask(sig, sigsz);
9385 struct timespec64 ts;
9387 if (get_timespec64(&ts, uts))
9389 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9392 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9393 iowq.wq.private = current;
9394 INIT_LIST_HEAD(&iowq.wq.entry);
9396 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9397 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9399 trace_io_uring_cqring_wait(ctx, min_events);
9401 /* if we can't even flush overflow, don't wait for more */
9402 if (!io_cqring_overflow_flush(ctx)) {
9406 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9407 TASK_INTERRUPTIBLE);
9408 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9412 finish_wait(&ctx->cq_wait, &iowq.wq);
9413 restore_saved_sigmask_unless(ret == -EINTR);
9415 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9418 static void io_free_page_table(void **table, size_t size)
9420 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9422 for (i = 0; i < nr_tables; i++)
9427 static __cold void **io_alloc_page_table(size_t size)
9429 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9430 size_t init_size = size;
9433 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9437 for (i = 0; i < nr_tables; i++) {
9438 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9440 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9442 io_free_page_table(table, init_size);
9450 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9452 percpu_ref_exit(&ref_node->refs);
9456 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9458 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9459 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9460 unsigned long flags;
9461 bool first_add = false;
9462 unsigned long delay = HZ;
9464 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9467 /* if we are mid-quiesce then do not delay */
9468 if (node->rsrc_data->quiesce)
9471 while (!list_empty(&ctx->rsrc_ref_list)) {
9472 node = list_first_entry(&ctx->rsrc_ref_list,
9473 struct io_rsrc_node, node);
9474 /* recycle ref nodes in order */
9477 list_del(&node->node);
9478 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9480 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9483 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9486 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9488 struct io_rsrc_node *ref_node;
9490 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9494 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9499 INIT_LIST_HEAD(&ref_node->node);
9500 INIT_LIST_HEAD(&ref_node->rsrc_list);
9501 ref_node->done = false;
9505 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9506 struct io_rsrc_data *data_to_kill)
9507 __must_hold(&ctx->uring_lock)
9509 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9510 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9512 io_rsrc_refs_drop(ctx);
9515 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9517 rsrc_node->rsrc_data = data_to_kill;
9518 spin_lock_irq(&ctx->rsrc_ref_lock);
9519 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9520 spin_unlock_irq(&ctx->rsrc_ref_lock);
9522 atomic_inc(&data_to_kill->refs);
9523 percpu_ref_kill(&rsrc_node->refs);
9524 ctx->rsrc_node = NULL;
9527 if (!ctx->rsrc_node) {
9528 ctx->rsrc_node = ctx->rsrc_backup_node;
9529 ctx->rsrc_backup_node = NULL;
9533 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9535 if (ctx->rsrc_backup_node)
9537 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9538 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9541 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9542 struct io_ring_ctx *ctx)
9546 /* As we may drop ->uring_lock, other task may have started quiesce */
9550 data->quiesce = true;
9552 ret = io_rsrc_node_switch_start(ctx);
9555 io_rsrc_node_switch(ctx, data);
9557 /* kill initial ref, already quiesced if zero */
9558 if (atomic_dec_and_test(&data->refs))
9560 mutex_unlock(&ctx->uring_lock);
9561 flush_delayed_work(&ctx->rsrc_put_work);
9562 ret = wait_for_completion_interruptible(&data->done);
9564 mutex_lock(&ctx->uring_lock);
9565 if (atomic_read(&data->refs) > 0) {
9567 * it has been revived by another thread while
9570 mutex_unlock(&ctx->uring_lock);
9576 atomic_inc(&data->refs);
9577 /* wait for all works potentially completing data->done */
9578 flush_delayed_work(&ctx->rsrc_put_work);
9579 reinit_completion(&data->done);
9581 ret = io_run_task_work_sig();
9582 mutex_lock(&ctx->uring_lock);
9584 data->quiesce = false;
9589 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9591 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9592 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9594 return &data->tags[table_idx][off];
9597 static void io_rsrc_data_free(struct io_rsrc_data *data)
9599 size_t size = data->nr * sizeof(data->tags[0][0]);
9602 io_free_page_table((void **)data->tags, size);
9606 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9607 u64 __user *utags, unsigned nr,
9608 struct io_rsrc_data **pdata)
9610 struct io_rsrc_data *data;
9614 data = kzalloc(sizeof(*data), GFP_KERNEL);
9617 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9625 data->do_put = do_put;
9628 for (i = 0; i < nr; i++) {
9629 u64 *tag_slot = io_get_tag_slot(data, i);
9631 if (copy_from_user(tag_slot, &utags[i],
9637 atomic_set(&data->refs, 1);
9638 init_completion(&data->done);
9642 io_rsrc_data_free(data);
9646 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9648 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9649 GFP_KERNEL_ACCOUNT);
9650 if (unlikely(!table->files))
9653 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9654 if (unlikely(!table->bitmap)) {
9655 kvfree(table->files);
9662 static void io_free_file_tables(struct io_file_table *table)
9664 kvfree(table->files);
9665 bitmap_free(table->bitmap);
9666 table->files = NULL;
9667 table->bitmap = NULL;
9670 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9672 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9673 __set_bit(bit, table->bitmap);
9674 table->alloc_hint = bit + 1;
9677 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9679 __clear_bit(bit, table->bitmap);
9680 table->alloc_hint = bit;
9683 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9685 #if !defined(IO_URING_SCM_ALL)
9688 for (i = 0; i < ctx->nr_user_files; i++) {
9689 struct file *file = io_file_from_index(ctx, i);
9693 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9695 io_file_bitmap_clear(&ctx->file_table, i);
9700 #if defined(CONFIG_UNIX)
9701 if (ctx->ring_sock) {
9702 struct sock *sock = ctx->ring_sock->sk;
9703 struct sk_buff *skb;
9705 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9709 io_free_file_tables(&ctx->file_table);
9710 io_rsrc_data_free(ctx->file_data);
9711 ctx->file_data = NULL;
9712 ctx->nr_user_files = 0;
9715 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9717 unsigned nr = ctx->nr_user_files;
9720 if (!ctx->file_data)
9724 * Quiesce may unlock ->uring_lock, and while it's not held
9725 * prevent new requests using the table.
9727 ctx->nr_user_files = 0;
9728 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9729 ctx->nr_user_files = nr;
9731 __io_sqe_files_unregister(ctx);
9735 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9736 __releases(&sqd->lock)
9738 WARN_ON_ONCE(sqd->thread == current);
9741 * Do the dance but not conditional clear_bit() because it'd race with
9742 * other threads incrementing park_pending and setting the bit.
9744 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9745 if (atomic_dec_return(&sqd->park_pending))
9746 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9747 mutex_unlock(&sqd->lock);
9750 static void io_sq_thread_park(struct io_sq_data *sqd)
9751 __acquires(&sqd->lock)
9753 WARN_ON_ONCE(sqd->thread == current);
9755 atomic_inc(&sqd->park_pending);
9756 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9757 mutex_lock(&sqd->lock);
9759 wake_up_process(sqd->thread);
9762 static void io_sq_thread_stop(struct io_sq_data *sqd)
9764 WARN_ON_ONCE(sqd->thread == current);
9765 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9767 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9768 mutex_lock(&sqd->lock);
9770 wake_up_process(sqd->thread);
9771 mutex_unlock(&sqd->lock);
9772 wait_for_completion(&sqd->exited);
9775 static void io_put_sq_data(struct io_sq_data *sqd)
9777 if (refcount_dec_and_test(&sqd->refs)) {
9778 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9780 io_sq_thread_stop(sqd);
9785 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9787 struct io_sq_data *sqd = ctx->sq_data;
9790 io_sq_thread_park(sqd);
9791 list_del_init(&ctx->sqd_list);
9792 io_sqd_update_thread_idle(sqd);
9793 io_sq_thread_unpark(sqd);
9795 io_put_sq_data(sqd);
9796 ctx->sq_data = NULL;
9800 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9802 struct io_ring_ctx *ctx_attach;
9803 struct io_sq_data *sqd;
9806 f = fdget(p->wq_fd);
9808 return ERR_PTR(-ENXIO);
9809 if (f.file->f_op != &io_uring_fops) {
9811 return ERR_PTR(-EINVAL);
9814 ctx_attach = f.file->private_data;
9815 sqd = ctx_attach->sq_data;
9818 return ERR_PTR(-EINVAL);
9820 if (sqd->task_tgid != current->tgid) {
9822 return ERR_PTR(-EPERM);
9825 refcount_inc(&sqd->refs);
9830 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9833 struct io_sq_data *sqd;
9836 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9837 sqd = io_attach_sq_data(p);
9842 /* fall through for EPERM case, setup new sqd/task */
9843 if (PTR_ERR(sqd) != -EPERM)
9847 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9849 return ERR_PTR(-ENOMEM);
9851 atomic_set(&sqd->park_pending, 0);
9852 refcount_set(&sqd->refs, 1);
9853 INIT_LIST_HEAD(&sqd->ctx_list);
9854 mutex_init(&sqd->lock);
9855 init_waitqueue_head(&sqd->wait);
9856 init_completion(&sqd->exited);
9861 * Ensure the UNIX gc is aware of our file set, so we are certain that
9862 * the io_uring can be safely unregistered on process exit, even if we have
9863 * loops in the file referencing. We account only files that can hold other
9864 * files because otherwise they can't form a loop and so are not interesting
9867 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9869 #if defined(CONFIG_UNIX)
9870 struct sock *sk = ctx->ring_sock->sk;
9871 struct sk_buff_head *head = &sk->sk_receive_queue;
9872 struct scm_fp_list *fpl;
9873 struct sk_buff *skb;
9875 if (likely(!io_file_need_scm(file)))
9879 * See if we can merge this file into an existing skb SCM_RIGHTS
9880 * file set. If there's no room, fall back to allocating a new skb
9881 * and filling it in.
9883 spin_lock_irq(&head->lock);
9884 skb = skb_peek(head);
9885 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9886 __skb_unlink(skb, head);
9889 spin_unlock_irq(&head->lock);
9892 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9896 skb = alloc_skb(0, GFP_KERNEL);
9902 fpl->user = get_uid(current_user());
9903 fpl->max = SCM_MAX_FD;
9906 UNIXCB(skb).fp = fpl;
9908 skb->destructor = unix_destruct_scm;
9909 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9912 fpl = UNIXCB(skb).fp;
9913 fpl->fp[fpl->count++] = get_file(file);
9914 unix_inflight(fpl->user, file);
9915 skb_queue_head(head, skb);
9921 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9923 struct file *file = prsrc->file;
9924 #if defined(CONFIG_UNIX)
9925 struct sock *sock = ctx->ring_sock->sk;
9926 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9927 struct sk_buff *skb;
9930 if (!io_file_need_scm(file)) {
9935 __skb_queue_head_init(&list);
9938 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9939 * remove this entry and rearrange the file array.
9941 skb = skb_dequeue(head);
9943 struct scm_fp_list *fp;
9945 fp = UNIXCB(skb).fp;
9946 for (i = 0; i < fp->count; i++) {
9949 if (fp->fp[i] != file)
9952 unix_notinflight(fp->user, fp->fp[i]);
9953 left = fp->count - 1 - i;
9955 memmove(&fp->fp[i], &fp->fp[i + 1],
9956 left * sizeof(struct file *));
9963 __skb_queue_tail(&list, skb);
9973 __skb_queue_tail(&list, skb);
9975 skb = skb_dequeue(head);
9978 if (skb_peek(&list)) {
9979 spin_lock_irq(&head->lock);
9980 while ((skb = __skb_dequeue(&list)) != NULL)
9981 __skb_queue_tail(head, skb);
9982 spin_unlock_irq(&head->lock);
9989 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9991 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9992 struct io_ring_ctx *ctx = rsrc_data->ctx;
9993 struct io_rsrc_put *prsrc, *tmp;
9995 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9996 list_del(&prsrc->list);
9999 if (ctx->flags & IORING_SETUP_IOPOLL)
10000 mutex_lock(&ctx->uring_lock);
10002 spin_lock(&ctx->completion_lock);
10003 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
10004 io_commit_cqring(ctx);
10005 spin_unlock(&ctx->completion_lock);
10006 io_cqring_ev_posted(ctx);
10008 if (ctx->flags & IORING_SETUP_IOPOLL)
10009 mutex_unlock(&ctx->uring_lock);
10012 rsrc_data->do_put(ctx, prsrc);
10016 io_rsrc_node_destroy(ref_node);
10017 if (atomic_dec_and_test(&rsrc_data->refs))
10018 complete(&rsrc_data->done);
10021 static void io_rsrc_put_work(struct work_struct *work)
10023 struct io_ring_ctx *ctx;
10024 struct llist_node *node;
10026 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
10027 node = llist_del_all(&ctx->rsrc_put_llist);
10030 struct io_rsrc_node *ref_node;
10031 struct llist_node *next = node->next;
10033 ref_node = llist_entry(node, struct io_rsrc_node, llist);
10034 __io_rsrc_put_work(ref_node);
10039 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
10040 unsigned nr_args, u64 __user *tags)
10042 __s32 __user *fds = (__s32 __user *) arg;
10047 if (ctx->file_data)
10051 if (nr_args > IORING_MAX_FIXED_FILES)
10053 if (nr_args > rlimit(RLIMIT_NOFILE))
10055 ret = io_rsrc_node_switch_start(ctx);
10058 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
10063 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
10064 io_rsrc_data_free(ctx->file_data);
10065 ctx->file_data = NULL;
10069 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
10070 struct io_fixed_file *file_slot;
10072 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
10076 /* allow sparse sets */
10077 if (!fds || fd == -1) {
10079 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
10086 if (unlikely(!file))
10090 * Don't allow io_uring instances to be registered. If UNIX
10091 * isn't enabled, then this causes a reference cycle and this
10092 * instance can never get freed. If UNIX is enabled we'll
10093 * handle it just fine, but there's still no point in allowing
10094 * a ring fd as it doesn't support regular read/write anyway.
10096 if (file->f_op == &io_uring_fops) {
10100 ret = io_scm_file_account(ctx, file);
10105 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10106 io_fixed_file_set(file_slot, file);
10107 io_file_bitmap_set(&ctx->file_table, i);
10110 io_rsrc_node_switch(ctx, NULL);
10113 __io_sqe_files_unregister(ctx);
10117 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
10118 struct io_rsrc_node *node, void *rsrc)
10120 u64 *tag_slot = io_get_tag_slot(data, idx);
10121 struct io_rsrc_put *prsrc;
10123 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
10127 prsrc->tag = *tag_slot;
10129 prsrc->rsrc = rsrc;
10130 list_add(&prsrc->list, &node->rsrc_list);
10134 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
10135 unsigned int issue_flags, u32 slot_index)
10136 __must_hold(&req->ctx->uring_lock)
10138 struct io_ring_ctx *ctx = req->ctx;
10139 bool needs_switch = false;
10140 struct io_fixed_file *file_slot;
10143 if (file->f_op == &io_uring_fops)
10145 if (!ctx->file_data)
10147 if (slot_index >= ctx->nr_user_files)
10150 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
10151 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
10153 if (file_slot->file_ptr) {
10154 struct file *old_file;
10156 ret = io_rsrc_node_switch_start(ctx);
10160 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10161 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
10162 ctx->rsrc_node, old_file);
10165 file_slot->file_ptr = 0;
10166 io_file_bitmap_clear(&ctx->file_table, slot_index);
10167 needs_switch = true;
10170 ret = io_scm_file_account(ctx, file);
10172 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
10173 io_fixed_file_set(file_slot, file);
10174 io_file_bitmap_set(&ctx->file_table, slot_index);
10178 io_rsrc_node_switch(ctx, ctx->file_data);
10184 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
10185 unsigned int offset)
10187 struct io_ring_ctx *ctx = req->ctx;
10188 struct io_fixed_file *file_slot;
10192 io_ring_submit_lock(ctx, issue_flags);
10194 if (unlikely(!ctx->file_data))
10197 if (offset >= ctx->nr_user_files)
10199 ret = io_rsrc_node_switch_start(ctx);
10203 offset = array_index_nospec(offset, ctx->nr_user_files);
10204 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
10206 if (!file_slot->file_ptr)
10209 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10210 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
10214 file_slot->file_ptr = 0;
10215 io_file_bitmap_clear(&ctx->file_table, offset);
10216 io_rsrc_node_switch(ctx, ctx->file_data);
10219 io_ring_submit_unlock(ctx, issue_flags);
10223 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
10225 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
10228 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
10229 struct io_uring_rsrc_update2 *up,
10232 u64 __user *tags = u64_to_user_ptr(up->tags);
10233 __s32 __user *fds = u64_to_user_ptr(up->data);
10234 struct io_rsrc_data *data = ctx->file_data;
10235 struct io_fixed_file *file_slot;
10237 int fd, i, err = 0;
10239 bool needs_switch = false;
10241 if (!ctx->file_data)
10243 if (up->offset + nr_args > ctx->nr_user_files)
10246 for (done = 0; done < nr_args; done++) {
10249 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
10250 copy_from_user(&fd, &fds[done], sizeof(fd))) {
10254 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
10258 if (fd == IORING_REGISTER_FILES_SKIP)
10261 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
10262 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10264 if (file_slot->file_ptr) {
10265 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10266 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
10269 file_slot->file_ptr = 0;
10270 io_file_bitmap_clear(&ctx->file_table, i);
10271 needs_switch = true;
10280 * Don't allow io_uring instances to be registered. If
10281 * UNIX isn't enabled, then this causes a reference
10282 * cycle and this instance can never get freed. If UNIX
10283 * is enabled we'll handle it just fine, but there's
10284 * still no point in allowing a ring fd as it doesn't
10285 * support regular read/write anyway.
10287 if (file->f_op == &io_uring_fops) {
10292 err = io_scm_file_account(ctx, file);
10297 *io_get_tag_slot(data, i) = tag;
10298 io_fixed_file_set(file_slot, file);
10299 io_file_bitmap_set(&ctx->file_table, i);
10304 io_rsrc_node_switch(ctx, data);
10305 return done ? done : err;
10308 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
10309 struct task_struct *task)
10311 struct io_wq_hash *hash;
10312 struct io_wq_data data;
10313 unsigned int concurrency;
10315 mutex_lock(&ctx->uring_lock);
10316 hash = ctx->hash_map;
10318 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10320 mutex_unlock(&ctx->uring_lock);
10321 return ERR_PTR(-ENOMEM);
10323 refcount_set(&hash->refs, 1);
10324 init_waitqueue_head(&hash->wait);
10325 ctx->hash_map = hash;
10327 mutex_unlock(&ctx->uring_lock);
10331 data.free_work = io_wq_free_work;
10332 data.do_work = io_wq_submit_work;
10334 /* Do QD, or 4 * CPUS, whatever is smallest */
10335 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10337 return io_wq_create(concurrency, &data);
10340 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10341 struct io_ring_ctx *ctx)
10343 struct io_uring_task *tctx;
10346 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10347 if (unlikely(!tctx))
10350 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10351 sizeof(struct file *), GFP_KERNEL);
10352 if (unlikely(!tctx->registered_rings)) {
10357 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10358 if (unlikely(ret)) {
10359 kfree(tctx->registered_rings);
10364 tctx->io_wq = io_init_wq_offload(ctx, task);
10365 if (IS_ERR(tctx->io_wq)) {
10366 ret = PTR_ERR(tctx->io_wq);
10367 percpu_counter_destroy(&tctx->inflight);
10368 kfree(tctx->registered_rings);
10373 xa_init(&tctx->xa);
10374 init_waitqueue_head(&tctx->wait);
10375 atomic_set(&tctx->in_idle, 0);
10376 atomic_set(&tctx->inflight_tracked, 0);
10377 task->io_uring = tctx;
10378 spin_lock_init(&tctx->task_lock);
10379 INIT_WQ_LIST(&tctx->task_list);
10380 INIT_WQ_LIST(&tctx->prio_task_list);
10381 init_task_work(&tctx->task_work, tctx_task_work);
10385 void __io_uring_free(struct task_struct *tsk)
10387 struct io_uring_task *tctx = tsk->io_uring;
10389 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10390 WARN_ON_ONCE(tctx->io_wq);
10391 WARN_ON_ONCE(tctx->cached_refs);
10393 kfree(tctx->registered_rings);
10394 percpu_counter_destroy(&tctx->inflight);
10396 tsk->io_uring = NULL;
10399 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10400 struct io_uring_params *p)
10404 /* Retain compatibility with failing for an invalid attach attempt */
10405 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10406 IORING_SETUP_ATTACH_WQ) {
10409 f = fdget(p->wq_fd);
10412 if (f.file->f_op != &io_uring_fops) {
10418 if (ctx->flags & IORING_SETUP_SQPOLL) {
10419 struct task_struct *tsk;
10420 struct io_sq_data *sqd;
10423 ret = security_uring_sqpoll();
10427 sqd = io_get_sq_data(p, &attached);
10429 ret = PTR_ERR(sqd);
10433 ctx->sq_creds = get_current_cred();
10434 ctx->sq_data = sqd;
10435 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10436 if (!ctx->sq_thread_idle)
10437 ctx->sq_thread_idle = HZ;
10439 io_sq_thread_park(sqd);
10440 list_add(&ctx->sqd_list, &sqd->ctx_list);
10441 io_sqd_update_thread_idle(sqd);
10442 /* don't attach to a dying SQPOLL thread, would be racy */
10443 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10444 io_sq_thread_unpark(sqd);
10451 if (p->flags & IORING_SETUP_SQ_AFF) {
10452 int cpu = p->sq_thread_cpu;
10455 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10462 sqd->task_pid = current->pid;
10463 sqd->task_tgid = current->tgid;
10464 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10466 ret = PTR_ERR(tsk);
10471 ret = io_uring_alloc_task_context(tsk, ctx);
10472 wake_up_new_task(tsk);
10475 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10476 /* Can't have SQ_AFF without SQPOLL */
10483 complete(&ctx->sq_data->exited);
10485 io_sq_thread_finish(ctx);
10489 static inline void __io_unaccount_mem(struct user_struct *user,
10490 unsigned long nr_pages)
10492 atomic_long_sub(nr_pages, &user->locked_vm);
10495 static inline int __io_account_mem(struct user_struct *user,
10496 unsigned long nr_pages)
10498 unsigned long page_limit, cur_pages, new_pages;
10500 /* Don't allow more pages than we can safely lock */
10501 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10504 cur_pages = atomic_long_read(&user->locked_vm);
10505 new_pages = cur_pages + nr_pages;
10506 if (new_pages > page_limit)
10508 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10509 new_pages) != cur_pages);
10514 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10517 __io_unaccount_mem(ctx->user, nr_pages);
10519 if (ctx->mm_account)
10520 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10523 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10528 ret = __io_account_mem(ctx->user, nr_pages);
10533 if (ctx->mm_account)
10534 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10539 static void io_mem_free(void *ptr)
10546 page = virt_to_head_page(ptr);
10547 if (put_page_testzero(page))
10548 free_compound_page(page);
10551 static void *io_mem_alloc(size_t size)
10553 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10555 return (void *) __get_free_pages(gfp, get_order(size));
10558 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10559 unsigned int cq_entries, size_t *sq_offset)
10561 struct io_rings *rings;
10562 size_t off, sq_array_size;
10564 off = struct_size(rings, cqes, cq_entries);
10565 if (off == SIZE_MAX)
10567 if (ctx->flags & IORING_SETUP_CQE32) {
10568 if (check_shl_overflow(off, 1, &off))
10573 off = ALIGN(off, SMP_CACHE_BYTES);
10581 sq_array_size = array_size(sizeof(u32), sq_entries);
10582 if (sq_array_size == SIZE_MAX)
10585 if (check_add_overflow(off, sq_array_size, &off))
10591 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10593 struct io_mapped_ubuf *imu = *slot;
10596 if (imu != ctx->dummy_ubuf) {
10597 for (i = 0; i < imu->nr_bvecs; i++)
10598 unpin_user_page(imu->bvec[i].bv_page);
10599 if (imu->acct_pages)
10600 io_unaccount_mem(ctx, imu->acct_pages);
10606 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10608 io_buffer_unmap(ctx, &prsrc->buf);
10612 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10616 for (i = 0; i < ctx->nr_user_bufs; i++)
10617 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10618 kfree(ctx->user_bufs);
10619 io_rsrc_data_free(ctx->buf_data);
10620 ctx->user_bufs = NULL;
10621 ctx->buf_data = NULL;
10622 ctx->nr_user_bufs = 0;
10625 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10627 unsigned nr = ctx->nr_user_bufs;
10630 if (!ctx->buf_data)
10634 * Quiesce may unlock ->uring_lock, and while it's not held
10635 * prevent new requests using the table.
10637 ctx->nr_user_bufs = 0;
10638 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10639 ctx->nr_user_bufs = nr;
10641 __io_sqe_buffers_unregister(ctx);
10645 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10646 void __user *arg, unsigned index)
10648 struct iovec __user *src;
10650 #ifdef CONFIG_COMPAT
10652 struct compat_iovec __user *ciovs;
10653 struct compat_iovec ciov;
10655 ciovs = (struct compat_iovec __user *) arg;
10656 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10659 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10660 dst->iov_len = ciov.iov_len;
10664 src = (struct iovec __user *) arg;
10665 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10671 * Not super efficient, but this is just a registration time. And we do cache
10672 * the last compound head, so generally we'll only do a full search if we don't
10675 * We check if the given compound head page has already been accounted, to
10676 * avoid double accounting it. This allows us to account the full size of the
10677 * page, not just the constituent pages of a huge page.
10679 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10680 int nr_pages, struct page *hpage)
10684 /* check current page array */
10685 for (i = 0; i < nr_pages; i++) {
10686 if (!PageCompound(pages[i]))
10688 if (compound_head(pages[i]) == hpage)
10692 /* check previously registered pages */
10693 for (i = 0; i < ctx->nr_user_bufs; i++) {
10694 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10696 for (j = 0; j < imu->nr_bvecs; j++) {
10697 if (!PageCompound(imu->bvec[j].bv_page))
10699 if (compound_head(imu->bvec[j].bv_page) == hpage)
10707 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10708 int nr_pages, struct io_mapped_ubuf *imu,
10709 struct page **last_hpage)
10713 imu->acct_pages = 0;
10714 for (i = 0; i < nr_pages; i++) {
10715 if (!PageCompound(pages[i])) {
10718 struct page *hpage;
10720 hpage = compound_head(pages[i]);
10721 if (hpage == *last_hpage)
10723 *last_hpage = hpage;
10724 if (headpage_already_acct(ctx, pages, i, hpage))
10726 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10730 if (!imu->acct_pages)
10733 ret = io_account_mem(ctx, imu->acct_pages);
10735 imu->acct_pages = 0;
10739 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10742 unsigned long start, end, nr_pages;
10743 struct vm_area_struct **vmas = NULL;
10744 struct page **pages = NULL;
10745 int i, pret, ret = -ENOMEM;
10747 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10748 start = ubuf >> PAGE_SHIFT;
10749 nr_pages = end - start;
10751 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10755 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10761 mmap_read_lock(current->mm);
10762 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10764 if (pret == nr_pages) {
10765 /* don't support file backed memory */
10766 for (i = 0; i < nr_pages; i++) {
10767 struct vm_area_struct *vma = vmas[i];
10769 if (vma_is_shmem(vma))
10771 if (vma->vm_file &&
10772 !is_file_hugepages(vma->vm_file)) {
10777 *npages = nr_pages;
10779 ret = pret < 0 ? pret : -EFAULT;
10781 mmap_read_unlock(current->mm);
10784 * if we did partial map, or found file backed vmas,
10785 * release any pages we did get
10788 unpin_user_pages(pages, pret);
10796 pages = ERR_PTR(ret);
10801 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10802 struct io_mapped_ubuf **pimu,
10803 struct page **last_hpage)
10805 struct io_mapped_ubuf *imu = NULL;
10806 struct page **pages = NULL;
10809 int ret, nr_pages, i;
10811 if (!iov->iov_base) {
10812 *pimu = ctx->dummy_ubuf;
10819 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10821 if (IS_ERR(pages)) {
10822 ret = PTR_ERR(pages);
10827 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10831 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10833 unpin_user_pages(pages, nr_pages);
10837 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10838 size = iov->iov_len;
10839 for (i = 0; i < nr_pages; i++) {
10842 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10843 imu->bvec[i].bv_page = pages[i];
10844 imu->bvec[i].bv_len = vec_len;
10845 imu->bvec[i].bv_offset = off;
10849 /* store original address for later verification */
10850 imu->ubuf = (unsigned long) iov->iov_base;
10851 imu->ubuf_end = imu->ubuf + iov->iov_len;
10852 imu->nr_bvecs = nr_pages;
10862 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10864 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10865 return ctx->user_bufs ? 0 : -ENOMEM;
10868 static int io_buffer_validate(struct iovec *iov)
10870 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10873 * Don't impose further limits on the size and buffer
10874 * constraints here, we'll -EINVAL later when IO is
10875 * submitted if they are wrong.
10877 if (!iov->iov_base)
10878 return iov->iov_len ? -EFAULT : 0;
10882 /* arbitrary limit, but we need something */
10883 if (iov->iov_len > SZ_1G)
10886 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10892 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10893 unsigned int nr_args, u64 __user *tags)
10895 struct page *last_hpage = NULL;
10896 struct io_rsrc_data *data;
10900 if (ctx->user_bufs)
10902 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10904 ret = io_rsrc_node_switch_start(ctx);
10907 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10910 ret = io_buffers_map_alloc(ctx, nr_args);
10912 io_rsrc_data_free(data);
10916 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10918 ret = io_copy_iov(ctx, &iov, arg, i);
10921 ret = io_buffer_validate(&iov);
10925 memset(&iov, 0, sizeof(iov));
10928 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10933 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10939 WARN_ON_ONCE(ctx->buf_data);
10941 ctx->buf_data = data;
10943 __io_sqe_buffers_unregister(ctx);
10945 io_rsrc_node_switch(ctx, NULL);
10949 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10950 struct io_uring_rsrc_update2 *up,
10951 unsigned int nr_args)
10953 u64 __user *tags = u64_to_user_ptr(up->tags);
10954 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10955 struct page *last_hpage = NULL;
10956 bool needs_switch = false;
10960 if (!ctx->buf_data)
10962 if (up->offset + nr_args > ctx->nr_user_bufs)
10965 for (done = 0; done < nr_args; done++) {
10966 struct io_mapped_ubuf *imu;
10967 int offset = up->offset + done;
10970 err = io_copy_iov(ctx, &iov, iovs, done);
10973 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10977 err = io_buffer_validate(&iov);
10980 if (!iov.iov_base && tag) {
10984 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10988 i = array_index_nospec(offset, ctx->nr_user_bufs);
10989 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10990 err = io_queue_rsrc_removal(ctx->buf_data, i,
10991 ctx->rsrc_node, ctx->user_bufs[i]);
10992 if (unlikely(err)) {
10993 io_buffer_unmap(ctx, &imu);
10996 ctx->user_bufs[i] = NULL;
10997 needs_switch = true;
11000 ctx->user_bufs[i] = imu;
11001 *io_get_tag_slot(ctx->buf_data, offset) = tag;
11005 io_rsrc_node_switch(ctx, ctx->buf_data);
11006 return done ? done : err;
11009 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
11010 unsigned int eventfd_async)
11012 struct io_ev_fd *ev_fd;
11013 __s32 __user *fds = arg;
11016 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11017 lockdep_is_held(&ctx->uring_lock));
11021 if (copy_from_user(&fd, fds, sizeof(*fds)))
11024 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
11028 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
11029 if (IS_ERR(ev_fd->cq_ev_fd)) {
11030 int ret = PTR_ERR(ev_fd->cq_ev_fd);
11034 ev_fd->eventfd_async = eventfd_async;
11035 ctx->has_evfd = true;
11036 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
11040 static void io_eventfd_put(struct rcu_head *rcu)
11042 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
11044 eventfd_ctx_put(ev_fd->cq_ev_fd);
11048 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
11050 struct io_ev_fd *ev_fd;
11052 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11053 lockdep_is_held(&ctx->uring_lock));
11055 ctx->has_evfd = false;
11056 rcu_assign_pointer(ctx->io_ev_fd, NULL);
11057 call_rcu(&ev_fd->rcu, io_eventfd_put);
11064 static void io_destroy_buffers(struct io_ring_ctx *ctx)
11066 struct io_buffer_list *bl;
11067 unsigned long index;
11070 for (i = 0; i < BGID_ARRAY; i++) {
11073 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
11076 xa_for_each(&ctx->io_bl_xa, index, bl) {
11077 xa_erase(&ctx->io_bl_xa, bl->bgid);
11078 __io_remove_buffers(ctx, bl, -1U);
11082 while (!list_empty(&ctx->io_buffers_pages)) {
11085 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
11086 list_del_init(&page->lru);
11091 static void io_req_caches_free(struct io_ring_ctx *ctx)
11093 struct io_submit_state *state = &ctx->submit_state;
11096 mutex_lock(&ctx->uring_lock);
11097 io_flush_cached_locked_reqs(ctx, state);
11099 while (!io_req_cache_empty(ctx)) {
11100 struct io_wq_work_node *node;
11101 struct io_kiocb *req;
11103 node = wq_stack_extract(&state->free_list);
11104 req = container_of(node, struct io_kiocb, comp_list);
11105 kmem_cache_free(req_cachep, req);
11109 percpu_ref_put_many(&ctx->refs, nr);
11110 mutex_unlock(&ctx->uring_lock);
11113 static void io_wait_rsrc_data(struct io_rsrc_data *data)
11115 if (data && !atomic_dec_and_test(&data->refs))
11116 wait_for_completion(&data->done);
11119 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
11121 struct async_poll *apoll;
11123 while (!list_empty(&ctx->apoll_cache)) {
11124 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
11126 list_del(&apoll->poll.wait.entry);
11131 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
11133 io_sq_thread_finish(ctx);
11135 if (ctx->mm_account) {
11136 mmdrop(ctx->mm_account);
11137 ctx->mm_account = NULL;
11140 io_rsrc_refs_drop(ctx);
11141 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
11142 io_wait_rsrc_data(ctx->buf_data);
11143 io_wait_rsrc_data(ctx->file_data);
11145 mutex_lock(&ctx->uring_lock);
11147 __io_sqe_buffers_unregister(ctx);
11148 if (ctx->file_data)
11149 __io_sqe_files_unregister(ctx);
11151 __io_cqring_overflow_flush(ctx, true);
11152 io_eventfd_unregister(ctx);
11153 io_flush_apoll_cache(ctx);
11154 mutex_unlock(&ctx->uring_lock);
11155 io_destroy_buffers(ctx);
11157 put_cred(ctx->sq_creds);
11159 /* there are no registered resources left, nobody uses it */
11160 if (ctx->rsrc_node)
11161 io_rsrc_node_destroy(ctx->rsrc_node);
11162 if (ctx->rsrc_backup_node)
11163 io_rsrc_node_destroy(ctx->rsrc_backup_node);
11164 flush_delayed_work(&ctx->rsrc_put_work);
11165 flush_delayed_work(&ctx->fallback_work);
11167 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
11168 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
11170 #if defined(CONFIG_UNIX)
11171 if (ctx->ring_sock) {
11172 ctx->ring_sock->file = NULL; /* so that iput() is called */
11173 sock_release(ctx->ring_sock);
11176 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
11178 io_mem_free(ctx->rings);
11179 io_mem_free(ctx->sq_sqes);
11181 percpu_ref_exit(&ctx->refs);
11182 free_uid(ctx->user);
11183 io_req_caches_free(ctx);
11185 io_wq_put_hash(ctx->hash_map);
11186 kfree(ctx->cancel_hash);
11187 kfree(ctx->dummy_ubuf);
11189 xa_destroy(&ctx->io_bl_xa);
11193 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
11195 struct io_ring_ctx *ctx = file->private_data;
11198 poll_wait(file, &ctx->cq_wait, wait);
11200 * synchronizes with barrier from wq_has_sleeper call in
11204 if (!io_sqring_full(ctx))
11205 mask |= EPOLLOUT | EPOLLWRNORM;
11208 * Don't flush cqring overflow list here, just do a simple check.
11209 * Otherwise there could possible be ABBA deadlock:
11212 * lock(&ctx->uring_lock);
11214 * lock(&ctx->uring_lock);
11217 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
11218 * pushs them to do the flush.
11220 if (io_cqring_events(ctx) ||
11221 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
11222 mask |= EPOLLIN | EPOLLRDNORM;
11227 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
11229 const struct cred *creds;
11231 creds = xa_erase(&ctx->personalities, id);
11240 struct io_tctx_exit {
11241 struct callback_head task_work;
11242 struct completion completion;
11243 struct io_ring_ctx *ctx;
11246 static __cold void io_tctx_exit_cb(struct callback_head *cb)
11248 struct io_uring_task *tctx = current->io_uring;
11249 struct io_tctx_exit *work;
11251 work = container_of(cb, struct io_tctx_exit, task_work);
11253 * When @in_idle, we're in cancellation and it's racy to remove the
11254 * node. It'll be removed by the end of cancellation, just ignore it.
11256 if (!atomic_read(&tctx->in_idle))
11257 io_uring_del_tctx_node((unsigned long)work->ctx);
11258 complete(&work->completion);
11261 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
11263 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11265 return req->ctx == data;
11268 static __cold void io_ring_exit_work(struct work_struct *work)
11270 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
11271 unsigned long timeout = jiffies + HZ * 60 * 5;
11272 unsigned long interval = HZ / 20;
11273 struct io_tctx_exit exit;
11274 struct io_tctx_node *node;
11278 * If we're doing polled IO and end up having requests being
11279 * submitted async (out-of-line), then completions can come in while
11280 * we're waiting for refs to drop. We need to reap these manually,
11281 * as nobody else will be looking for them.
11284 io_uring_try_cancel_requests(ctx, NULL, true);
11285 if (ctx->sq_data) {
11286 struct io_sq_data *sqd = ctx->sq_data;
11287 struct task_struct *tsk;
11289 io_sq_thread_park(sqd);
11291 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
11292 io_wq_cancel_cb(tsk->io_uring->io_wq,
11293 io_cancel_ctx_cb, ctx, true);
11294 io_sq_thread_unpark(sqd);
11297 io_req_caches_free(ctx);
11299 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
11300 /* there is little hope left, don't run it too often */
11301 interval = HZ * 60;
11303 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
11305 init_completion(&exit.completion);
11306 init_task_work(&exit.task_work, io_tctx_exit_cb);
11309 * Some may use context even when all refs and requests have been put,
11310 * and they are free to do so while still holding uring_lock or
11311 * completion_lock, see io_req_task_submit(). Apart from other work,
11312 * this lock/unlock section also waits them to finish.
11314 mutex_lock(&ctx->uring_lock);
11315 while (!list_empty(&ctx->tctx_list)) {
11316 WARN_ON_ONCE(time_after(jiffies, timeout));
11318 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
11320 /* don't spin on a single task if cancellation failed */
11321 list_rotate_left(&ctx->tctx_list);
11322 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
11323 if (WARN_ON_ONCE(ret))
11326 mutex_unlock(&ctx->uring_lock);
11327 wait_for_completion(&exit.completion);
11328 mutex_lock(&ctx->uring_lock);
11330 mutex_unlock(&ctx->uring_lock);
11331 spin_lock(&ctx->completion_lock);
11332 spin_unlock(&ctx->completion_lock);
11334 io_ring_ctx_free(ctx);
11337 /* Returns true if we found and killed one or more timeouts */
11338 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
11339 struct task_struct *tsk, bool cancel_all)
11341 struct io_kiocb *req, *tmp;
11344 spin_lock(&ctx->completion_lock);
11345 spin_lock_irq(&ctx->timeout_lock);
11346 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11347 if (io_match_task(req, tsk, cancel_all)) {
11348 io_kill_timeout(req, -ECANCELED);
11352 spin_unlock_irq(&ctx->timeout_lock);
11353 io_commit_cqring(ctx);
11354 spin_unlock(&ctx->completion_lock);
11356 io_cqring_ev_posted(ctx);
11357 return canceled != 0;
11360 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11362 unsigned long index;
11363 struct creds *creds;
11365 mutex_lock(&ctx->uring_lock);
11366 percpu_ref_kill(&ctx->refs);
11368 __io_cqring_overflow_flush(ctx, true);
11369 xa_for_each(&ctx->personalities, index, creds)
11370 io_unregister_personality(ctx, index);
11371 mutex_unlock(&ctx->uring_lock);
11373 /* failed during ring init, it couldn't have issued any requests */
11375 io_kill_timeouts(ctx, NULL, true);
11376 io_poll_remove_all(ctx, NULL, true);
11377 /* if we failed setting up the ctx, we might not have any rings */
11378 io_iopoll_try_reap_events(ctx);
11381 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11383 * Use system_unbound_wq to avoid spawning tons of event kworkers
11384 * if we're exiting a ton of rings at the same time. It just adds
11385 * noise and overhead, there's no discernable change in runtime
11386 * over using system_wq.
11388 queue_work(system_unbound_wq, &ctx->exit_work);
11391 static int io_uring_release(struct inode *inode, struct file *file)
11393 struct io_ring_ctx *ctx = file->private_data;
11395 file->private_data = NULL;
11396 io_ring_ctx_wait_and_kill(ctx);
11400 struct io_task_cancel {
11401 struct task_struct *task;
11405 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11407 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11408 struct io_task_cancel *cancel = data;
11410 return io_match_task_safe(req, cancel->task, cancel->all);
11413 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11414 struct task_struct *task,
11417 struct io_defer_entry *de;
11420 spin_lock(&ctx->completion_lock);
11421 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11422 if (io_match_task_safe(de->req, task, cancel_all)) {
11423 list_cut_position(&list, &ctx->defer_list, &de->list);
11427 spin_unlock(&ctx->completion_lock);
11428 if (list_empty(&list))
11431 while (!list_empty(&list)) {
11432 de = list_first_entry(&list, struct io_defer_entry, list);
11433 list_del_init(&de->list);
11434 io_req_complete_failed(de->req, -ECANCELED);
11440 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11442 struct io_tctx_node *node;
11443 enum io_wq_cancel cret;
11446 mutex_lock(&ctx->uring_lock);
11447 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11448 struct io_uring_task *tctx = node->task->io_uring;
11451 * io_wq will stay alive while we hold uring_lock, because it's
11452 * killed after ctx nodes, which requires to take the lock.
11454 if (!tctx || !tctx->io_wq)
11456 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11457 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11459 mutex_unlock(&ctx->uring_lock);
11464 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11465 struct task_struct *task,
11468 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11469 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11471 /* failed during ring init, it couldn't have issued any requests */
11476 enum io_wq_cancel cret;
11480 ret |= io_uring_try_cancel_iowq(ctx);
11481 } else if (tctx && tctx->io_wq) {
11483 * Cancels requests of all rings, not only @ctx, but
11484 * it's fine as the task is in exit/exec.
11486 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11488 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11491 /* SQPOLL thread does its own polling */
11492 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11493 (ctx->sq_data && ctx->sq_data->thread == current)) {
11494 while (!wq_list_empty(&ctx->iopoll_list)) {
11495 io_iopoll_try_reap_events(ctx);
11500 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11501 ret |= io_poll_remove_all(ctx, task, cancel_all);
11502 ret |= io_kill_timeouts(ctx, task, cancel_all);
11504 ret |= io_run_task_work();
11511 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11513 struct io_uring_task *tctx = current->io_uring;
11514 struct io_tctx_node *node;
11517 if (unlikely(!tctx)) {
11518 ret = io_uring_alloc_task_context(current, ctx);
11522 tctx = current->io_uring;
11523 if (ctx->iowq_limits_set) {
11524 unsigned int limits[2] = { ctx->iowq_limits[0],
11525 ctx->iowq_limits[1], };
11527 ret = io_wq_max_workers(tctx->io_wq, limits);
11532 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11533 node = kmalloc(sizeof(*node), GFP_KERNEL);
11537 node->task = current;
11539 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11540 node, GFP_KERNEL));
11546 mutex_lock(&ctx->uring_lock);
11547 list_add(&node->ctx_node, &ctx->tctx_list);
11548 mutex_unlock(&ctx->uring_lock);
11555 * Note that this task has used io_uring. We use it for cancelation purposes.
11557 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11559 struct io_uring_task *tctx = current->io_uring;
11561 if (likely(tctx && tctx->last == ctx))
11563 return __io_uring_add_tctx_node(ctx);
11567 * Remove this io_uring_file -> task mapping.
11569 static __cold void io_uring_del_tctx_node(unsigned long index)
11571 struct io_uring_task *tctx = current->io_uring;
11572 struct io_tctx_node *node;
11576 node = xa_erase(&tctx->xa, index);
11580 WARN_ON_ONCE(current != node->task);
11581 WARN_ON_ONCE(list_empty(&node->ctx_node));
11583 mutex_lock(&node->ctx->uring_lock);
11584 list_del(&node->ctx_node);
11585 mutex_unlock(&node->ctx->uring_lock);
11587 if (tctx->last == node->ctx)
11592 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11594 struct io_wq *wq = tctx->io_wq;
11595 struct io_tctx_node *node;
11596 unsigned long index;
11598 xa_for_each(&tctx->xa, index, node) {
11599 io_uring_del_tctx_node(index);
11604 * Must be after io_uring_del_tctx_node() (removes nodes under
11605 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11607 io_wq_put_and_exit(wq);
11608 tctx->io_wq = NULL;
11612 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11615 return atomic_read(&tctx->inflight_tracked);
11616 return percpu_counter_sum(&tctx->inflight);
11620 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11621 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11623 static __cold void io_uring_cancel_generic(bool cancel_all,
11624 struct io_sq_data *sqd)
11626 struct io_uring_task *tctx = current->io_uring;
11627 struct io_ring_ctx *ctx;
11631 WARN_ON_ONCE(sqd && sqd->thread != current);
11633 if (!current->io_uring)
11636 io_wq_exit_start(tctx->io_wq);
11638 atomic_inc(&tctx->in_idle);
11640 io_uring_drop_tctx_refs(current);
11641 /* read completions before cancelations */
11642 inflight = tctx_inflight(tctx, !cancel_all);
11647 struct io_tctx_node *node;
11648 unsigned long index;
11650 xa_for_each(&tctx->xa, index, node) {
11651 /* sqpoll task will cancel all its requests */
11652 if (node->ctx->sq_data)
11654 io_uring_try_cancel_requests(node->ctx, current,
11658 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11659 io_uring_try_cancel_requests(ctx, current,
11663 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11664 io_run_task_work();
11665 io_uring_drop_tctx_refs(current);
11668 * If we've seen completions, retry without waiting. This
11669 * avoids a race where a completion comes in before we did
11670 * prepare_to_wait().
11672 if (inflight == tctx_inflight(tctx, !cancel_all))
11674 finish_wait(&tctx->wait, &wait);
11677 io_uring_clean_tctx(tctx);
11680 * We shouldn't run task_works after cancel, so just leave
11681 * ->in_idle set for normal exit.
11683 atomic_dec(&tctx->in_idle);
11684 /* for exec all current's requests should be gone, kill tctx */
11685 __io_uring_free(current);
11689 void __io_uring_cancel(bool cancel_all)
11691 io_uring_cancel_generic(cancel_all, NULL);
11694 void io_uring_unreg_ringfd(void)
11696 struct io_uring_task *tctx = current->io_uring;
11699 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11700 if (tctx->registered_rings[i]) {
11701 fput(tctx->registered_rings[i]);
11702 tctx->registered_rings[i] = NULL;
11707 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11708 int start, int end)
11713 for (offset = start; offset < end; offset++) {
11714 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11715 if (tctx->registered_rings[offset])
11721 } else if (file->f_op != &io_uring_fops) {
11723 return -EOPNOTSUPP;
11725 tctx->registered_rings[offset] = file;
11733 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11734 * invocation. User passes in an array of struct io_uring_rsrc_update
11735 * with ->data set to the ring_fd, and ->offset given for the desired
11736 * index. If no index is desired, application may set ->offset == -1U
11737 * and we'll find an available index. Returns number of entries
11738 * successfully processed, or < 0 on error if none were processed.
11740 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11743 struct io_uring_rsrc_update __user *arg = __arg;
11744 struct io_uring_rsrc_update reg;
11745 struct io_uring_task *tctx;
11748 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11751 mutex_unlock(&ctx->uring_lock);
11752 ret = io_uring_add_tctx_node(ctx);
11753 mutex_lock(&ctx->uring_lock);
11757 tctx = current->io_uring;
11758 for (i = 0; i < nr_args; i++) {
11761 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11771 if (reg.offset == -1U) {
11773 end = IO_RINGFD_REG_MAX;
11775 if (reg.offset >= IO_RINGFD_REG_MAX) {
11779 start = reg.offset;
11783 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11788 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11789 fput(tctx->registered_rings[reg.offset]);
11790 tctx->registered_rings[reg.offset] = NULL;
11796 return i ? i : ret;
11799 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11802 struct io_uring_rsrc_update __user *arg = __arg;
11803 struct io_uring_task *tctx = current->io_uring;
11804 struct io_uring_rsrc_update reg;
11807 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11812 for (i = 0; i < nr_args; i++) {
11813 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11817 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11822 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11823 if (tctx->registered_rings[reg.offset]) {
11824 fput(tctx->registered_rings[reg.offset]);
11825 tctx->registered_rings[reg.offset] = NULL;
11829 return i ? i : ret;
11832 static void *io_uring_validate_mmap_request(struct file *file,
11833 loff_t pgoff, size_t sz)
11835 struct io_ring_ctx *ctx = file->private_data;
11836 loff_t offset = pgoff << PAGE_SHIFT;
11841 case IORING_OFF_SQ_RING:
11842 case IORING_OFF_CQ_RING:
11845 case IORING_OFF_SQES:
11846 ptr = ctx->sq_sqes;
11849 return ERR_PTR(-EINVAL);
11852 page = virt_to_head_page(ptr);
11853 if (sz > page_size(page))
11854 return ERR_PTR(-EINVAL);
11861 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11863 size_t sz = vma->vm_end - vma->vm_start;
11867 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11869 return PTR_ERR(ptr);
11871 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11872 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11875 #else /* !CONFIG_MMU */
11877 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11879 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11882 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11884 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11887 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11888 unsigned long addr, unsigned long len,
11889 unsigned long pgoff, unsigned long flags)
11893 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11895 return PTR_ERR(ptr);
11897 return (unsigned long) ptr;
11900 #endif /* !CONFIG_MMU */
11902 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11907 if (!io_sqring_full(ctx))
11909 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11911 if (!io_sqring_full(ctx))
11914 } while (!signal_pending(current));
11916 finish_wait(&ctx->sqo_sq_wait, &wait);
11920 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11922 if (flags & IORING_ENTER_EXT_ARG) {
11923 struct io_uring_getevents_arg arg;
11925 if (argsz != sizeof(arg))
11927 if (copy_from_user(&arg, argp, sizeof(arg)))
11933 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11934 struct __kernel_timespec __user **ts,
11935 const sigset_t __user **sig)
11937 struct io_uring_getevents_arg arg;
11940 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11941 * is just a pointer to the sigset_t.
11943 if (!(flags & IORING_ENTER_EXT_ARG)) {
11944 *sig = (const sigset_t __user *) argp;
11950 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11951 * timespec and sigset_t pointers if good.
11953 if (*argsz != sizeof(arg))
11955 if (copy_from_user(&arg, argp, sizeof(arg)))
11959 *sig = u64_to_user_ptr(arg.sigmask);
11960 *argsz = arg.sigmask_sz;
11961 *ts = u64_to_user_ptr(arg.ts);
11965 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11966 u32, min_complete, u32, flags, const void __user *, argp,
11969 struct io_ring_ctx *ctx;
11973 io_run_task_work();
11975 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11976 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11977 IORING_ENTER_REGISTERED_RING)))
11981 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11982 * need only dereference our task private array to find it.
11984 if (flags & IORING_ENTER_REGISTERED_RING) {
11985 struct io_uring_task *tctx = current->io_uring;
11987 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11989 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11990 f.file = tctx->registered_rings[fd];
11996 if (unlikely(!f.file))
12000 if (unlikely(f.file->f_op != &io_uring_fops))
12004 ctx = f.file->private_data;
12005 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
12009 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
12013 * For SQ polling, the thread will do all submissions and completions.
12014 * Just return the requested submit count, and wake the thread if
12015 * we were asked to.
12018 if (ctx->flags & IORING_SETUP_SQPOLL) {
12019 io_cqring_overflow_flush(ctx);
12021 if (unlikely(ctx->sq_data->thread == NULL)) {
12025 if (flags & IORING_ENTER_SQ_WAKEUP)
12026 wake_up(&ctx->sq_data->wait);
12027 if (flags & IORING_ENTER_SQ_WAIT) {
12028 ret = io_sqpoll_wait_sq(ctx);
12033 } else if (to_submit) {
12034 ret = io_uring_add_tctx_node(ctx);
12038 mutex_lock(&ctx->uring_lock);
12039 ret = io_submit_sqes(ctx, to_submit);
12040 if (ret != to_submit) {
12041 mutex_unlock(&ctx->uring_lock);
12044 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
12045 goto iopoll_locked;
12046 mutex_unlock(&ctx->uring_lock);
12048 if (flags & IORING_ENTER_GETEVENTS) {
12050 if (ctx->syscall_iopoll) {
12052 * We disallow the app entering submit/complete with
12053 * polling, but we still need to lock the ring to
12054 * prevent racing with polled issue that got punted to
12057 mutex_lock(&ctx->uring_lock);
12059 ret2 = io_validate_ext_arg(flags, argp, argsz);
12060 if (likely(!ret2)) {
12061 min_complete = min(min_complete,
12063 ret2 = io_iopoll_check(ctx, min_complete);
12065 mutex_unlock(&ctx->uring_lock);
12067 const sigset_t __user *sig;
12068 struct __kernel_timespec __user *ts;
12070 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
12071 if (likely(!ret2)) {
12072 min_complete = min(min_complete,
12074 ret2 = io_cqring_wait(ctx, min_complete, sig,
12083 * EBADR indicates that one or more CQE were dropped.
12084 * Once the user has been informed we can clear the bit
12085 * as they are obviously ok with those drops.
12087 if (unlikely(ret2 == -EBADR))
12088 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
12094 percpu_ref_put(&ctx->refs);
12100 #ifdef CONFIG_PROC_FS
12101 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
12102 const struct cred *cred)
12104 struct user_namespace *uns = seq_user_ns(m);
12105 struct group_info *gi;
12110 seq_printf(m, "%5d\n", id);
12111 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
12112 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
12113 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
12114 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
12115 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
12116 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
12117 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
12118 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
12119 seq_puts(m, "\n\tGroups:\t");
12120 gi = cred->group_info;
12121 for (g = 0; g < gi->ngroups; g++) {
12122 seq_put_decimal_ull(m, g ? " " : "",
12123 from_kgid_munged(uns, gi->gid[g]));
12125 seq_puts(m, "\n\tCapEff:\t");
12126 cap = cred->cap_effective;
12127 CAP_FOR_EACH_U32(__capi)
12128 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
12133 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
12134 struct seq_file *m)
12136 struct io_sq_data *sq = NULL;
12137 struct io_overflow_cqe *ocqe;
12138 struct io_rings *r = ctx->rings;
12139 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
12140 unsigned int sq_head = READ_ONCE(r->sq.head);
12141 unsigned int sq_tail = READ_ONCE(r->sq.tail);
12142 unsigned int cq_head = READ_ONCE(r->cq.head);
12143 unsigned int cq_tail = READ_ONCE(r->cq.tail);
12144 unsigned int cq_shift = 0;
12145 unsigned int sq_entries, cq_entries;
12147 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
12154 * we may get imprecise sqe and cqe info if uring is actively running
12155 * since we get cached_sq_head and cached_cq_tail without uring_lock
12156 * and sq_tail and cq_head are changed by userspace. But it's ok since
12157 * we usually use these info when it is stuck.
12159 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
12160 seq_printf(m, "SqHead:\t%u\n", sq_head);
12161 seq_printf(m, "SqTail:\t%u\n", sq_tail);
12162 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
12163 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
12164 seq_printf(m, "CqHead:\t%u\n", cq_head);
12165 seq_printf(m, "CqTail:\t%u\n", cq_tail);
12166 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
12167 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
12168 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
12169 for (i = 0; i < sq_entries; i++) {
12170 unsigned int entry = i + sq_head;
12171 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
12172 struct io_uring_sqe *sqe;
12174 if (sq_idx > sq_mask)
12176 sqe = &ctx->sq_sqes[sq_idx];
12177 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
12178 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
12181 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
12182 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
12183 for (i = 0; i < cq_entries; i++) {
12184 unsigned int entry = i + cq_head;
12185 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
12188 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
12189 entry & cq_mask, cqe->user_data, cqe->res,
12192 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
12193 "extra1:%llu, extra2:%llu\n",
12194 entry & cq_mask, cqe->user_data, cqe->res,
12195 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
12200 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
12201 * since fdinfo case grabs it in the opposite direction of normal use
12202 * cases. If we fail to get the lock, we just don't iterate any
12203 * structures that could be going away outside the io_uring mutex.
12205 has_lock = mutex_trylock(&ctx->uring_lock);
12207 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
12213 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
12214 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
12215 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
12216 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
12217 struct file *f = io_file_from_index(ctx, i);
12220 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
12222 seq_printf(m, "%5u: <none>\n", i);
12224 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
12225 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
12226 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
12227 unsigned int len = buf->ubuf_end - buf->ubuf;
12229 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
12231 if (has_lock && !xa_empty(&ctx->personalities)) {
12232 unsigned long index;
12233 const struct cred *cred;
12235 seq_printf(m, "Personalities:\n");
12236 xa_for_each(&ctx->personalities, index, cred)
12237 io_uring_show_cred(m, index, cred);
12240 mutex_unlock(&ctx->uring_lock);
12242 seq_puts(m, "PollList:\n");
12243 spin_lock(&ctx->completion_lock);
12244 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
12245 struct hlist_head *list = &ctx->cancel_hash[i];
12246 struct io_kiocb *req;
12248 hlist_for_each_entry(req, list, hash_node)
12249 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
12250 task_work_pending(req->task));
12253 seq_puts(m, "CqOverflowList:\n");
12254 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
12255 struct io_uring_cqe *cqe = &ocqe->cqe;
12257 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
12258 cqe->user_data, cqe->res, cqe->flags);
12262 spin_unlock(&ctx->completion_lock);
12265 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
12267 struct io_ring_ctx *ctx = f->private_data;
12269 if (percpu_ref_tryget(&ctx->refs)) {
12270 __io_uring_show_fdinfo(ctx, m);
12271 percpu_ref_put(&ctx->refs);
12276 static const struct file_operations io_uring_fops = {
12277 .release = io_uring_release,
12278 .mmap = io_uring_mmap,
12280 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
12281 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
12283 .poll = io_uring_poll,
12284 #ifdef CONFIG_PROC_FS
12285 .show_fdinfo = io_uring_show_fdinfo,
12289 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
12290 struct io_uring_params *p)
12292 struct io_rings *rings;
12293 size_t size, sq_array_offset;
12295 /* make sure these are sane, as we already accounted them */
12296 ctx->sq_entries = p->sq_entries;
12297 ctx->cq_entries = p->cq_entries;
12299 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
12300 if (size == SIZE_MAX)
12303 rings = io_mem_alloc(size);
12307 ctx->rings = rings;
12308 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
12309 rings->sq_ring_mask = p->sq_entries - 1;
12310 rings->cq_ring_mask = p->cq_entries - 1;
12311 rings->sq_ring_entries = p->sq_entries;
12312 rings->cq_ring_entries = p->cq_entries;
12314 if (p->flags & IORING_SETUP_SQE128)
12315 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
12317 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
12318 if (size == SIZE_MAX) {
12319 io_mem_free(ctx->rings);
12324 ctx->sq_sqes = io_mem_alloc(size);
12325 if (!ctx->sq_sqes) {
12326 io_mem_free(ctx->rings);
12334 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
12338 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
12342 ret = io_uring_add_tctx_node(ctx);
12347 fd_install(fd, file);
12352 * Allocate an anonymous fd, this is what constitutes the application
12353 * visible backing of an io_uring instance. The application mmaps this
12354 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12355 * we have to tie this fd to a socket for file garbage collection purposes.
12357 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12360 #if defined(CONFIG_UNIX)
12363 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12366 return ERR_PTR(ret);
12369 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12370 O_RDWR | O_CLOEXEC, NULL);
12371 #if defined(CONFIG_UNIX)
12372 if (IS_ERR(file)) {
12373 sock_release(ctx->ring_sock);
12374 ctx->ring_sock = NULL;
12376 ctx->ring_sock->file = file;
12382 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12383 struct io_uring_params __user *params)
12385 struct io_ring_ctx *ctx;
12391 if (entries > IORING_MAX_ENTRIES) {
12392 if (!(p->flags & IORING_SETUP_CLAMP))
12394 entries = IORING_MAX_ENTRIES;
12398 * Use twice as many entries for the CQ ring. It's possible for the
12399 * application to drive a higher depth than the size of the SQ ring,
12400 * since the sqes are only used at submission time. This allows for
12401 * some flexibility in overcommitting a bit. If the application has
12402 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12403 * of CQ ring entries manually.
12405 p->sq_entries = roundup_pow_of_two(entries);
12406 if (p->flags & IORING_SETUP_CQSIZE) {
12408 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12409 * to a power-of-two, if it isn't already. We do NOT impose
12410 * any cq vs sq ring sizing.
12412 if (!p->cq_entries)
12414 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12415 if (!(p->flags & IORING_SETUP_CLAMP))
12417 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12419 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12420 if (p->cq_entries < p->sq_entries)
12423 p->cq_entries = 2 * p->sq_entries;
12426 ctx = io_ring_ctx_alloc(p);
12431 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12432 * space applications don't need to do io completion events
12433 * polling again, they can rely on io_sq_thread to do polling
12434 * work, which can reduce cpu usage and uring_lock contention.
12436 if (ctx->flags & IORING_SETUP_IOPOLL &&
12437 !(ctx->flags & IORING_SETUP_SQPOLL))
12438 ctx->syscall_iopoll = 1;
12440 ctx->compat = in_compat_syscall();
12441 if (!capable(CAP_IPC_LOCK))
12442 ctx->user = get_uid(current_user());
12445 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12446 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12449 if (ctx->flags & IORING_SETUP_SQPOLL) {
12450 /* IPI related flags don't make sense with SQPOLL */
12451 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12452 IORING_SETUP_TASKRUN_FLAG))
12454 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12455 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12456 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12458 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12460 ctx->notify_method = TWA_SIGNAL;
12464 * This is just grabbed for accounting purposes. When a process exits,
12465 * the mm is exited and dropped before the files, hence we need to hang
12466 * on to this mm purely for the purposes of being able to unaccount
12467 * memory (locked/pinned vm). It's not used for anything else.
12469 mmgrab(current->mm);
12470 ctx->mm_account = current->mm;
12472 ret = io_allocate_scq_urings(ctx, p);
12476 ret = io_sq_offload_create(ctx, p);
12479 /* always set a rsrc node */
12480 ret = io_rsrc_node_switch_start(ctx);
12483 io_rsrc_node_switch(ctx, NULL);
12485 memset(&p->sq_off, 0, sizeof(p->sq_off));
12486 p->sq_off.head = offsetof(struct io_rings, sq.head);
12487 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12488 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12489 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12490 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12491 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12492 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12494 memset(&p->cq_off, 0, sizeof(p->cq_off));
12495 p->cq_off.head = offsetof(struct io_rings, cq.head);
12496 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12497 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12498 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12499 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12500 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12501 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12503 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12504 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12505 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12506 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12507 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12508 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12509 IORING_FEAT_LINKED_FILE;
12511 if (copy_to_user(params, p, sizeof(*p))) {
12516 file = io_uring_get_file(ctx);
12517 if (IS_ERR(file)) {
12518 ret = PTR_ERR(file);
12523 * Install ring fd as the very last thing, so we don't risk someone
12524 * having closed it before we finish setup
12526 ret = io_uring_install_fd(ctx, file);
12528 /* fput will clean it up */
12533 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12536 io_ring_ctx_wait_and_kill(ctx);
12541 * Sets up an aio uring context, and returns the fd. Applications asks for a
12542 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12543 * params structure passed in.
12545 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12547 struct io_uring_params p;
12550 if (copy_from_user(&p, params, sizeof(p)))
12552 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12557 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12558 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12559 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12560 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12561 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12562 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12565 return io_uring_create(entries, &p, params);
12568 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12569 struct io_uring_params __user *, params)
12571 return io_uring_setup(entries, params);
12574 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12577 struct io_uring_probe *p;
12581 size = struct_size(p, ops, nr_args);
12582 if (size == SIZE_MAX)
12584 p = kzalloc(size, GFP_KERNEL);
12589 if (copy_from_user(p, arg, size))
12592 if (memchr_inv(p, 0, size))
12595 p->last_op = IORING_OP_LAST - 1;
12596 if (nr_args > IORING_OP_LAST)
12597 nr_args = IORING_OP_LAST;
12599 for (i = 0; i < nr_args; i++) {
12601 if (!io_op_defs[i].not_supported)
12602 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12607 if (copy_to_user(arg, p, size))
12614 static int io_register_personality(struct io_ring_ctx *ctx)
12616 const struct cred *creds;
12620 creds = get_current_cred();
12622 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12623 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12631 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12632 void __user *arg, unsigned int nr_args)
12634 struct io_uring_restriction *res;
12638 /* Restrictions allowed only if rings started disabled */
12639 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12642 /* We allow only a single restrictions registration */
12643 if (ctx->restrictions.registered)
12646 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12649 size = array_size(nr_args, sizeof(*res));
12650 if (size == SIZE_MAX)
12653 res = memdup_user(arg, size);
12655 return PTR_ERR(res);
12659 for (i = 0; i < nr_args; i++) {
12660 switch (res[i].opcode) {
12661 case IORING_RESTRICTION_REGISTER_OP:
12662 if (res[i].register_op >= IORING_REGISTER_LAST) {
12667 __set_bit(res[i].register_op,
12668 ctx->restrictions.register_op);
12670 case IORING_RESTRICTION_SQE_OP:
12671 if (res[i].sqe_op >= IORING_OP_LAST) {
12676 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12678 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12679 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12681 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12682 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12691 /* Reset all restrictions if an error happened */
12693 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12695 ctx->restrictions.registered = true;
12701 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12703 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12706 if (ctx->restrictions.registered)
12707 ctx->restricted = 1;
12709 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12710 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12711 wake_up(&ctx->sq_data->wait);
12715 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12716 struct io_uring_rsrc_update2 *up,
12722 if (check_add_overflow(up->offset, nr_args, &tmp))
12724 err = io_rsrc_node_switch_start(ctx);
12729 case IORING_RSRC_FILE:
12730 return __io_sqe_files_update(ctx, up, nr_args);
12731 case IORING_RSRC_BUFFER:
12732 return __io_sqe_buffers_update(ctx, up, nr_args);
12737 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12740 struct io_uring_rsrc_update2 up;
12744 memset(&up, 0, sizeof(up));
12745 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12747 if (up.resv || up.resv2)
12749 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12752 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12753 unsigned size, unsigned type)
12755 struct io_uring_rsrc_update2 up;
12757 if (size != sizeof(up))
12759 if (copy_from_user(&up, arg, sizeof(up)))
12761 if (!up.nr || up.resv || up.resv2)
12763 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12766 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12767 unsigned int size, unsigned int type)
12769 struct io_uring_rsrc_register rr;
12771 /* keep it extendible */
12772 if (size != sizeof(rr))
12775 memset(&rr, 0, sizeof(rr));
12776 if (copy_from_user(&rr, arg, size))
12778 if (!rr.nr || rr.resv2)
12780 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12784 case IORING_RSRC_FILE:
12785 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12787 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12788 rr.nr, u64_to_user_ptr(rr.tags));
12789 case IORING_RSRC_BUFFER:
12790 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12792 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12793 rr.nr, u64_to_user_ptr(rr.tags));
12798 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12799 void __user *arg, unsigned len)
12801 struct io_uring_task *tctx = current->io_uring;
12802 cpumask_var_t new_mask;
12805 if (!tctx || !tctx->io_wq)
12808 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12811 cpumask_clear(new_mask);
12812 if (len > cpumask_size())
12813 len = cpumask_size();
12815 if (in_compat_syscall()) {
12816 ret = compat_get_bitmap(cpumask_bits(new_mask),
12817 (const compat_ulong_t __user *)arg,
12818 len * 8 /* CHAR_BIT */);
12820 ret = copy_from_user(new_mask, arg, len);
12824 free_cpumask_var(new_mask);
12828 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12829 free_cpumask_var(new_mask);
12833 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12835 struct io_uring_task *tctx = current->io_uring;
12837 if (!tctx || !tctx->io_wq)
12840 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12843 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12845 __must_hold(&ctx->uring_lock)
12847 struct io_tctx_node *node;
12848 struct io_uring_task *tctx = NULL;
12849 struct io_sq_data *sqd = NULL;
12850 __u32 new_count[2];
12853 if (copy_from_user(new_count, arg, sizeof(new_count)))
12855 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12856 if (new_count[i] > INT_MAX)
12859 if (ctx->flags & IORING_SETUP_SQPOLL) {
12860 sqd = ctx->sq_data;
12863 * Observe the correct sqd->lock -> ctx->uring_lock
12864 * ordering. Fine to drop uring_lock here, we hold
12865 * a ref to the ctx.
12867 refcount_inc(&sqd->refs);
12868 mutex_unlock(&ctx->uring_lock);
12869 mutex_lock(&sqd->lock);
12870 mutex_lock(&ctx->uring_lock);
12872 tctx = sqd->thread->io_uring;
12875 tctx = current->io_uring;
12878 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12880 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12882 ctx->iowq_limits[i] = new_count[i];
12883 ctx->iowq_limits_set = true;
12885 if (tctx && tctx->io_wq) {
12886 ret = io_wq_max_workers(tctx->io_wq, new_count);
12890 memset(new_count, 0, sizeof(new_count));
12894 mutex_unlock(&sqd->lock);
12895 io_put_sq_data(sqd);
12898 if (copy_to_user(arg, new_count, sizeof(new_count)))
12901 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12905 /* now propagate the restriction to all registered users */
12906 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12907 struct io_uring_task *tctx = node->task->io_uring;
12909 if (WARN_ON_ONCE(!tctx->io_wq))
12912 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12913 new_count[i] = ctx->iowq_limits[i];
12914 /* ignore errors, it always returns zero anyway */
12915 (void)io_wq_max_workers(tctx->io_wq, new_count);
12920 mutex_unlock(&sqd->lock);
12921 io_put_sq_data(sqd);
12926 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12928 struct io_uring_buf_ring *br;
12929 struct io_uring_buf_reg reg;
12930 struct io_buffer_list *bl;
12931 struct page **pages;
12934 if (copy_from_user(®, arg, sizeof(reg)))
12937 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12939 if (!reg.ring_addr)
12941 if (reg.ring_addr & ~PAGE_MASK)
12943 if (!is_power_of_2(reg.ring_entries))
12946 /* cannot disambiguate full vs empty due to head/tail size */
12947 if (reg.ring_entries >= 65536)
12950 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12951 int ret = io_init_bl_list(ctx);
12956 bl = io_buffer_get_list(ctx, reg.bgid);
12958 /* if mapped buffer ring OR classic exists, don't allow */
12959 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12962 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12967 pages = io_pin_pages(reg.ring_addr,
12968 struct_size(br, bufs, reg.ring_entries),
12970 if (IS_ERR(pages)) {
12972 return PTR_ERR(pages);
12975 br = page_address(pages[0]);
12976 bl->buf_pages = pages;
12977 bl->buf_nr_pages = nr_pages;
12978 bl->nr_entries = reg.ring_entries;
12980 bl->mask = reg.ring_entries - 1;
12981 io_buffer_add_list(ctx, bl, reg.bgid);
12985 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12987 struct io_uring_buf_reg reg;
12988 struct io_buffer_list *bl;
12990 if (copy_from_user(®, arg, sizeof(reg)))
12992 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12995 bl = io_buffer_get_list(ctx, reg.bgid);
12998 if (!bl->buf_nr_pages)
13001 __io_remove_buffers(ctx, bl, -1U);
13002 if (bl->bgid >= BGID_ARRAY) {
13003 xa_erase(&ctx->io_bl_xa, bl->bgid);
13009 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
13010 void __user *arg, unsigned nr_args)
13011 __releases(ctx->uring_lock)
13012 __acquires(ctx->uring_lock)
13017 * We're inside the ring mutex, if the ref is already dying, then
13018 * someone else killed the ctx or is already going through
13019 * io_uring_register().
13021 if (percpu_ref_is_dying(&ctx->refs))
13024 if (ctx->restricted) {
13025 if (opcode >= IORING_REGISTER_LAST)
13027 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
13028 if (!test_bit(opcode, ctx->restrictions.register_op))
13033 case IORING_REGISTER_BUFFERS:
13037 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
13039 case IORING_UNREGISTER_BUFFERS:
13041 if (arg || nr_args)
13043 ret = io_sqe_buffers_unregister(ctx);
13045 case IORING_REGISTER_FILES:
13049 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
13051 case IORING_UNREGISTER_FILES:
13053 if (arg || nr_args)
13055 ret = io_sqe_files_unregister(ctx);
13057 case IORING_REGISTER_FILES_UPDATE:
13058 ret = io_register_files_update(ctx, arg, nr_args);
13060 case IORING_REGISTER_EVENTFD:
13064 ret = io_eventfd_register(ctx, arg, 0);
13066 case IORING_REGISTER_EVENTFD_ASYNC:
13070 ret = io_eventfd_register(ctx, arg, 1);
13072 case IORING_UNREGISTER_EVENTFD:
13074 if (arg || nr_args)
13076 ret = io_eventfd_unregister(ctx);
13078 case IORING_REGISTER_PROBE:
13080 if (!arg || nr_args > 256)
13082 ret = io_probe(ctx, arg, nr_args);
13084 case IORING_REGISTER_PERSONALITY:
13086 if (arg || nr_args)
13088 ret = io_register_personality(ctx);
13090 case IORING_UNREGISTER_PERSONALITY:
13094 ret = io_unregister_personality(ctx, nr_args);
13096 case IORING_REGISTER_ENABLE_RINGS:
13098 if (arg || nr_args)
13100 ret = io_register_enable_rings(ctx);
13102 case IORING_REGISTER_RESTRICTIONS:
13103 ret = io_register_restrictions(ctx, arg, nr_args);
13105 case IORING_REGISTER_FILES2:
13106 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
13108 case IORING_REGISTER_FILES_UPDATE2:
13109 ret = io_register_rsrc_update(ctx, arg, nr_args,
13112 case IORING_REGISTER_BUFFERS2:
13113 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
13115 case IORING_REGISTER_BUFFERS_UPDATE:
13116 ret = io_register_rsrc_update(ctx, arg, nr_args,
13117 IORING_RSRC_BUFFER);
13119 case IORING_REGISTER_IOWQ_AFF:
13121 if (!arg || !nr_args)
13123 ret = io_register_iowq_aff(ctx, arg, nr_args);
13125 case IORING_UNREGISTER_IOWQ_AFF:
13127 if (arg || nr_args)
13129 ret = io_unregister_iowq_aff(ctx);
13131 case IORING_REGISTER_IOWQ_MAX_WORKERS:
13133 if (!arg || nr_args != 2)
13135 ret = io_register_iowq_max_workers(ctx, arg);
13137 case IORING_REGISTER_RING_FDS:
13138 ret = io_ringfd_register(ctx, arg, nr_args);
13140 case IORING_UNREGISTER_RING_FDS:
13141 ret = io_ringfd_unregister(ctx, arg, nr_args);
13143 case IORING_REGISTER_PBUF_RING:
13145 if (!arg || nr_args != 1)
13147 ret = io_register_pbuf_ring(ctx, arg);
13149 case IORING_UNREGISTER_PBUF_RING:
13151 if (!arg || nr_args != 1)
13153 ret = io_unregister_pbuf_ring(ctx, arg);
13163 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
13164 void __user *, arg, unsigned int, nr_args)
13166 struct io_ring_ctx *ctx;
13175 if (f.file->f_op != &io_uring_fops)
13178 ctx = f.file->private_data;
13180 io_run_task_work();
13182 mutex_lock(&ctx->uring_lock);
13183 ret = __io_uring_register(ctx, opcode, arg, nr_args);
13184 mutex_unlock(&ctx->uring_lock);
13185 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
13191 static int __init io_uring_init(void)
13193 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13194 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13195 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13198 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13199 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13200 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13201 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13202 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13203 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13204 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13205 BUILD_BUG_SQE_ELEM(8, __u64, off);
13206 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13207 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13208 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13209 BUILD_BUG_SQE_ELEM(24, __u32, len);
13210 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13211 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13212 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13213 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13214 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13215 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13216 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13217 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13218 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13219 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13220 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13221 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13222 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13223 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13224 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13225 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13226 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13227 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13228 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13229 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13230 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13231 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13233 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13234 sizeof(struct io_uring_rsrc_update));
13235 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13236 sizeof(struct io_uring_rsrc_update2));
13238 /* ->buf_index is u16 */
13239 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13240 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13241 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13242 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13243 offsetof(struct io_uring_buf_ring, tail));
13245 /* should fit into one byte */
13246 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13247 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13248 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13250 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13251 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13253 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13255 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13257 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13261 __initcall(io_uring_init);