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,
1186 .async_size = sizeof(struct io_async_msghdr),
1188 [IORING_OP_RECVMSG] = {
1190 .unbound_nonreg_file = 1,
1193 .needs_async_setup = 1,
1194 .async_size = sizeof(struct io_async_msghdr),
1196 [IORING_OP_TIMEOUT] = {
1198 .async_size = sizeof(struct io_timeout_data),
1200 [IORING_OP_TIMEOUT_REMOVE] = {
1201 /* used by timeout updates' prep() */
1204 [IORING_OP_ACCEPT] = {
1206 .unbound_nonreg_file = 1,
1208 .poll_exclusive = 1,
1209 .ioprio = 1, /* used for flags */
1211 [IORING_OP_ASYNC_CANCEL] = {
1214 [IORING_OP_LINK_TIMEOUT] = {
1216 .async_size = sizeof(struct io_timeout_data),
1218 [IORING_OP_CONNECT] = {
1220 .unbound_nonreg_file = 1,
1222 .needs_async_setup = 1,
1223 .async_size = sizeof(struct io_async_connect),
1225 [IORING_OP_FALLOCATE] = {
1228 [IORING_OP_OPENAT] = {},
1229 [IORING_OP_CLOSE] = {},
1230 [IORING_OP_FILES_UPDATE] = {
1234 [IORING_OP_STATX] = {
1237 [IORING_OP_READ] = {
1239 .unbound_nonreg_file = 1,
1246 .async_size = sizeof(struct io_async_rw),
1248 [IORING_OP_WRITE] = {
1251 .unbound_nonreg_file = 1,
1257 .async_size = sizeof(struct io_async_rw),
1259 [IORING_OP_FADVISE] = {
1263 [IORING_OP_MADVISE] = {},
1264 [IORING_OP_SEND] = {
1266 .unbound_nonreg_file = 1,
1270 [IORING_OP_RECV] = {
1272 .unbound_nonreg_file = 1,
1277 [IORING_OP_OPENAT2] = {
1279 [IORING_OP_EPOLL_CTL] = {
1280 .unbound_nonreg_file = 1,
1283 [IORING_OP_SPLICE] = {
1286 .unbound_nonreg_file = 1,
1289 [IORING_OP_PROVIDE_BUFFERS] = {
1293 [IORING_OP_REMOVE_BUFFERS] = {
1300 .unbound_nonreg_file = 1,
1303 [IORING_OP_SHUTDOWN] = {
1306 [IORING_OP_RENAMEAT] = {},
1307 [IORING_OP_UNLINKAT] = {},
1308 [IORING_OP_MKDIRAT] = {},
1309 [IORING_OP_SYMLINKAT] = {},
1310 [IORING_OP_LINKAT] = {},
1311 [IORING_OP_MSG_RING] = {
1315 [IORING_OP_FSETXATTR] = {
1318 [IORING_OP_SETXATTR] = {},
1319 [IORING_OP_FGETXATTR] = {
1322 [IORING_OP_GETXATTR] = {},
1323 [IORING_OP_SOCKET] = {
1326 [IORING_OP_URING_CMD] = {
1329 .needs_async_setup = 1,
1330 .async_size = uring_cmd_pdu_size(1),
1334 /* requests with any of those set should undergo io_disarm_next() */
1335 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1336 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1338 static bool io_disarm_next(struct io_kiocb *req);
1339 static void io_uring_del_tctx_node(unsigned long index);
1340 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1341 struct task_struct *task,
1343 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1345 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1346 static void io_dismantle_req(struct io_kiocb *req);
1347 static void io_queue_linked_timeout(struct io_kiocb *req);
1348 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1349 struct io_uring_rsrc_update2 *up,
1351 static void io_clean_op(struct io_kiocb *req);
1352 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1353 unsigned issue_flags);
1354 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1355 static void io_queue_sqe(struct io_kiocb *req);
1356 static void io_rsrc_put_work(struct work_struct *work);
1358 static void io_req_task_queue(struct io_kiocb *req);
1359 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1360 static int io_req_prep_async(struct io_kiocb *req);
1362 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1363 unsigned int issue_flags, u32 slot_index);
1364 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
1365 unsigned int offset);
1366 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1368 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1369 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1370 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1372 static struct kmem_cache *req_cachep;
1374 static const struct file_operations io_uring_fops;
1376 const char *io_uring_get_opcode(u8 opcode)
1378 switch ((enum io_uring_op)opcode) {
1381 case IORING_OP_READV:
1383 case IORING_OP_WRITEV:
1385 case IORING_OP_FSYNC:
1387 case IORING_OP_READ_FIXED:
1388 return "READ_FIXED";
1389 case IORING_OP_WRITE_FIXED:
1390 return "WRITE_FIXED";
1391 case IORING_OP_POLL_ADD:
1393 case IORING_OP_POLL_REMOVE:
1394 return "POLL_REMOVE";
1395 case IORING_OP_SYNC_FILE_RANGE:
1396 return "SYNC_FILE_RANGE";
1397 case IORING_OP_SENDMSG:
1399 case IORING_OP_RECVMSG:
1401 case IORING_OP_TIMEOUT:
1403 case IORING_OP_TIMEOUT_REMOVE:
1404 return "TIMEOUT_REMOVE";
1405 case IORING_OP_ACCEPT:
1407 case IORING_OP_ASYNC_CANCEL:
1408 return "ASYNC_CANCEL";
1409 case IORING_OP_LINK_TIMEOUT:
1410 return "LINK_TIMEOUT";
1411 case IORING_OP_CONNECT:
1413 case IORING_OP_FALLOCATE:
1415 case IORING_OP_OPENAT:
1417 case IORING_OP_CLOSE:
1419 case IORING_OP_FILES_UPDATE:
1420 return "FILES_UPDATE";
1421 case IORING_OP_STATX:
1423 case IORING_OP_READ:
1425 case IORING_OP_WRITE:
1427 case IORING_OP_FADVISE:
1429 case IORING_OP_MADVISE:
1431 case IORING_OP_SEND:
1433 case IORING_OP_RECV:
1435 case IORING_OP_OPENAT2:
1437 case IORING_OP_EPOLL_CTL:
1439 case IORING_OP_SPLICE:
1441 case IORING_OP_PROVIDE_BUFFERS:
1442 return "PROVIDE_BUFFERS";
1443 case IORING_OP_REMOVE_BUFFERS:
1444 return "REMOVE_BUFFERS";
1447 case IORING_OP_SHUTDOWN:
1449 case IORING_OP_RENAMEAT:
1451 case IORING_OP_UNLINKAT:
1453 case IORING_OP_MKDIRAT:
1455 case IORING_OP_SYMLINKAT:
1457 case IORING_OP_LINKAT:
1459 case IORING_OP_MSG_RING:
1461 case IORING_OP_FSETXATTR:
1463 case IORING_OP_SETXATTR:
1465 case IORING_OP_FGETXATTR:
1467 case IORING_OP_GETXATTR:
1469 case IORING_OP_SOCKET:
1471 case IORING_OP_URING_CMD:
1473 case IORING_OP_LAST:
1479 struct sock *io_uring_get_socket(struct file *file)
1481 #if defined(CONFIG_UNIX)
1482 if (file->f_op == &io_uring_fops) {
1483 struct io_ring_ctx *ctx = file->private_data;
1485 return ctx->ring_sock->sk;
1490 EXPORT_SYMBOL(io_uring_get_socket);
1492 #if defined(CONFIG_UNIX)
1493 static inline bool io_file_need_scm(struct file *filp)
1495 #if defined(IO_URING_SCM_ALL)
1498 return !!unix_get_socket(filp);
1502 static inline bool io_file_need_scm(struct file *filp)
1508 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1510 lockdep_assert_held(&ctx->uring_lock);
1511 if (issue_flags & IO_URING_F_UNLOCKED)
1512 mutex_unlock(&ctx->uring_lock);
1515 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1518 * "Normal" inline submissions always hold the uring_lock, since we
1519 * grab it from the system call. Same is true for the SQPOLL offload.
1520 * The only exception is when we've detached the request and issue it
1521 * from an async worker thread, grab the lock for that case.
1523 if (issue_flags & IO_URING_F_UNLOCKED)
1524 mutex_lock(&ctx->uring_lock);
1525 lockdep_assert_held(&ctx->uring_lock);
1528 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1531 mutex_lock(&ctx->uring_lock);
1536 #define io_for_each_link(pos, head) \
1537 for (pos = (head); pos; pos = pos->link)
1540 * Shamelessly stolen from the mm implementation of page reference checking,
1541 * see commit f958d7b528b1 for details.
1543 #define req_ref_zero_or_close_to_overflow(req) \
1544 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1546 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1548 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1549 return atomic_inc_not_zero(&req->refs);
1552 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1554 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1557 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1558 return atomic_dec_and_test(&req->refs);
1561 static inline void req_ref_get(struct io_kiocb *req)
1563 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1564 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1565 atomic_inc(&req->refs);
1568 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1570 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1571 __io_submit_flush_completions(ctx);
1574 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1576 if (!(req->flags & REQ_F_REFCOUNT)) {
1577 req->flags |= REQ_F_REFCOUNT;
1578 atomic_set(&req->refs, nr);
1582 static inline void io_req_set_refcount(struct io_kiocb *req)
1584 __io_req_set_refcount(req, 1);
1587 #define IO_RSRC_REF_BATCH 100
1589 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1591 percpu_ref_put_many(&node->refs, nr);
1594 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1595 struct io_ring_ctx *ctx)
1596 __must_hold(&ctx->uring_lock)
1598 struct io_rsrc_node *node = req->rsrc_node;
1601 if (node == ctx->rsrc_node)
1602 ctx->rsrc_cached_refs++;
1604 io_rsrc_put_node(node, 1);
1608 static inline void io_req_put_rsrc(struct io_kiocb *req)
1611 io_rsrc_put_node(req->rsrc_node, 1);
1614 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1615 __must_hold(&ctx->uring_lock)
1617 if (ctx->rsrc_cached_refs) {
1618 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1619 ctx->rsrc_cached_refs = 0;
1623 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1624 __must_hold(&ctx->uring_lock)
1626 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1627 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1630 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1631 struct io_ring_ctx *ctx,
1632 unsigned int issue_flags)
1634 if (!req->rsrc_node) {
1635 req->rsrc_node = ctx->rsrc_node;
1637 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1638 lockdep_assert_held(&ctx->uring_lock);
1639 ctx->rsrc_cached_refs--;
1640 if (unlikely(ctx->rsrc_cached_refs < 0))
1641 io_rsrc_refs_refill(ctx);
1643 percpu_ref_get(&req->rsrc_node->refs);
1648 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1650 if (req->flags & REQ_F_BUFFER_RING) {
1652 req->buf_list->head++;
1653 req->flags &= ~REQ_F_BUFFER_RING;
1655 list_add(&req->kbuf->list, list);
1656 req->flags &= ~REQ_F_BUFFER_SELECTED;
1659 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1662 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1664 lockdep_assert_held(&req->ctx->completion_lock);
1666 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1668 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1671 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1672 unsigned issue_flags)
1674 unsigned int cflags;
1676 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1680 * We can add this buffer back to two lists:
1682 * 1) The io_buffers_cache list. This one is protected by the
1683 * ctx->uring_lock. If we already hold this lock, add back to this
1684 * list as we can grab it from issue as well.
1685 * 2) The io_buffers_comp list. This one is protected by the
1686 * ctx->completion_lock.
1688 * We migrate buffers from the comp_list to the issue cache list
1691 if (req->flags & REQ_F_BUFFER_RING) {
1692 /* no buffers to recycle for this case */
1693 cflags = __io_put_kbuf(req, NULL);
1694 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1695 struct io_ring_ctx *ctx = req->ctx;
1697 spin_lock(&ctx->completion_lock);
1698 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1699 spin_unlock(&ctx->completion_lock);
1701 lockdep_assert_held(&req->ctx->uring_lock);
1703 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1709 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1712 if (ctx->io_bl && bgid < BGID_ARRAY)
1713 return &ctx->io_bl[bgid];
1715 return xa_load(&ctx->io_bl_xa, bgid);
1718 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1720 struct io_ring_ctx *ctx = req->ctx;
1721 struct io_buffer_list *bl;
1722 struct io_buffer *buf;
1724 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1727 * For legacy provided buffer mode, don't recycle if we already did
1728 * IO to this buffer. For ring-mapped provided buffer mode, we should
1729 * increment ring->head to explicitly monopolize the buffer to avoid
1732 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
1733 (req->flags & REQ_F_PARTIAL_IO))
1737 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1738 * the flag and hence ensure that bl->head doesn't get incremented.
1739 * If the tail has already been incremented, hang on to it.
1741 if (req->flags & REQ_F_BUFFER_RING) {
1742 if (req->buf_list) {
1743 if (req->flags & REQ_F_PARTIAL_IO) {
1744 req->buf_list->head++;
1745 req->buf_list = NULL;
1747 req->buf_index = req->buf_list->bgid;
1748 req->flags &= ~REQ_F_BUFFER_RING;
1754 io_ring_submit_lock(ctx, issue_flags);
1757 bl = io_buffer_get_list(ctx, buf->bgid);
1758 list_add(&buf->list, &bl->buf_list);
1759 req->flags &= ~REQ_F_BUFFER_SELECTED;
1760 req->buf_index = buf->bgid;
1762 io_ring_submit_unlock(ctx, issue_flags);
1765 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1767 __must_hold(&req->ctx->timeout_lock)
1769 struct io_kiocb *req;
1771 if (task && head->task != task)
1776 io_for_each_link(req, head) {
1777 if (req->flags & REQ_F_INFLIGHT)
1783 static bool io_match_linked(struct io_kiocb *head)
1785 struct io_kiocb *req;
1787 io_for_each_link(req, head) {
1788 if (req->flags & REQ_F_INFLIGHT)
1795 * As io_match_task() but protected against racing with linked timeouts.
1796 * User must not hold timeout_lock.
1798 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1803 if (task && head->task != task)
1808 if (head->flags & REQ_F_LINK_TIMEOUT) {
1809 struct io_ring_ctx *ctx = head->ctx;
1811 /* protect against races with linked timeouts */
1812 spin_lock_irq(&ctx->timeout_lock);
1813 matched = io_match_linked(head);
1814 spin_unlock_irq(&ctx->timeout_lock);
1816 matched = io_match_linked(head);
1821 static inline bool req_has_async_data(struct io_kiocb *req)
1823 return req->flags & REQ_F_ASYNC_DATA;
1826 static inline void req_set_fail(struct io_kiocb *req)
1828 req->flags |= REQ_F_FAIL;
1829 if (req->flags & REQ_F_CQE_SKIP) {
1830 req->flags &= ~REQ_F_CQE_SKIP;
1831 req->flags |= REQ_F_SKIP_LINK_CQES;
1835 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1841 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1843 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1846 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1848 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1850 complete(&ctx->ref_comp);
1853 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1855 return !req->timeout.off;
1858 static __cold void io_fallback_req_func(struct work_struct *work)
1860 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1861 fallback_work.work);
1862 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1863 struct io_kiocb *req, *tmp;
1864 bool locked = false;
1866 percpu_ref_get(&ctx->refs);
1867 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1868 req->io_task_work.func(req, &locked);
1871 io_submit_flush_completions(ctx);
1872 mutex_unlock(&ctx->uring_lock);
1874 percpu_ref_put(&ctx->refs);
1877 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1879 struct io_ring_ctx *ctx;
1882 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1886 xa_init(&ctx->io_bl_xa);
1889 * Use 5 bits less than the max cq entries, that should give us around
1890 * 32 entries per hash list if totally full and uniformly spread.
1892 hash_bits = ilog2(p->cq_entries);
1896 ctx->cancel_hash_bits = hash_bits;
1897 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1899 if (!ctx->cancel_hash)
1901 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1903 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1904 if (!ctx->dummy_ubuf)
1906 /* set invalid range, so io_import_fixed() fails meeting it */
1907 ctx->dummy_ubuf->ubuf = -1UL;
1909 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1910 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1913 ctx->flags = p->flags;
1914 init_waitqueue_head(&ctx->sqo_sq_wait);
1915 INIT_LIST_HEAD(&ctx->sqd_list);
1916 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1917 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1918 INIT_LIST_HEAD(&ctx->apoll_cache);
1919 init_completion(&ctx->ref_comp);
1920 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1921 mutex_init(&ctx->uring_lock);
1922 init_waitqueue_head(&ctx->cq_wait);
1923 spin_lock_init(&ctx->completion_lock);
1924 spin_lock_init(&ctx->timeout_lock);
1925 INIT_WQ_LIST(&ctx->iopoll_list);
1926 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1927 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1928 INIT_LIST_HEAD(&ctx->defer_list);
1929 INIT_LIST_HEAD(&ctx->timeout_list);
1930 INIT_LIST_HEAD(&ctx->ltimeout_list);
1931 spin_lock_init(&ctx->rsrc_ref_lock);
1932 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1933 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1934 init_llist_head(&ctx->rsrc_put_llist);
1935 INIT_LIST_HEAD(&ctx->tctx_list);
1936 ctx->submit_state.free_list.next = NULL;
1937 INIT_WQ_LIST(&ctx->locked_free_list);
1938 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1939 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1942 kfree(ctx->dummy_ubuf);
1943 kfree(ctx->cancel_hash);
1945 xa_destroy(&ctx->io_bl_xa);
1950 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1952 struct io_rings *r = ctx->rings;
1954 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1958 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1960 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1961 struct io_ring_ctx *ctx = req->ctx;
1963 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1969 static inline bool io_req_ffs_set(struct io_kiocb *req)
1971 return req->flags & REQ_F_FIXED_FILE;
1974 static inline void io_req_track_inflight(struct io_kiocb *req)
1976 if (!(req->flags & REQ_F_INFLIGHT)) {
1977 req->flags |= REQ_F_INFLIGHT;
1978 atomic_inc(¤t->io_uring->inflight_tracked);
1982 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1984 if (WARN_ON_ONCE(!req->link))
1987 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1988 req->flags |= REQ_F_LINK_TIMEOUT;
1990 /* linked timeouts should have two refs once prep'ed */
1991 io_req_set_refcount(req);
1992 __io_req_set_refcount(req->link, 2);
1996 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1998 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
2000 return __io_prep_linked_timeout(req);
2003 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
2005 io_queue_linked_timeout(__io_prep_linked_timeout(req));
2008 static inline void io_arm_ltimeout(struct io_kiocb *req)
2010 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
2011 __io_arm_ltimeout(req);
2014 static void io_prep_async_work(struct io_kiocb *req)
2016 const struct io_op_def *def = &io_op_defs[req->opcode];
2017 struct io_ring_ctx *ctx = req->ctx;
2019 if (!(req->flags & REQ_F_CREDS)) {
2020 req->flags |= REQ_F_CREDS;
2021 req->creds = get_current_cred();
2024 req->work.list.next = NULL;
2025 req->work.flags = 0;
2026 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
2027 if (req->flags & REQ_F_FORCE_ASYNC)
2028 req->work.flags |= IO_WQ_WORK_CONCURRENT;
2030 if (req->flags & REQ_F_ISREG) {
2031 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
2032 io_wq_hash_work(&req->work, file_inode(req->file));
2033 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
2034 if (def->unbound_nonreg_file)
2035 req->work.flags |= IO_WQ_WORK_UNBOUND;
2039 static void io_prep_async_link(struct io_kiocb *req)
2041 struct io_kiocb *cur;
2043 if (req->flags & REQ_F_LINK_TIMEOUT) {
2044 struct io_ring_ctx *ctx = req->ctx;
2046 spin_lock_irq(&ctx->timeout_lock);
2047 io_for_each_link(cur, req)
2048 io_prep_async_work(cur);
2049 spin_unlock_irq(&ctx->timeout_lock);
2051 io_for_each_link(cur, req)
2052 io_prep_async_work(cur);
2056 static inline void io_req_add_compl_list(struct io_kiocb *req)
2058 struct io_submit_state *state = &req->ctx->submit_state;
2060 if (!(req->flags & REQ_F_CQE_SKIP))
2061 state->flush_cqes = true;
2062 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
2065 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
2067 struct io_kiocb *link = io_prep_linked_timeout(req);
2068 struct io_uring_task *tctx = req->task->io_uring;
2071 BUG_ON(!tctx->io_wq);
2073 /* init ->work of the whole link before punting */
2074 io_prep_async_link(req);
2077 * Not expected to happen, but if we do have a bug where this _can_
2078 * happen, catch it here and ensure the request is marked as
2079 * canceled. That will make io-wq go through the usual work cancel
2080 * procedure rather than attempt to run this request (or create a new
2083 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
2084 req->work.flags |= IO_WQ_WORK_CANCEL;
2086 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
2087 req->opcode, req->flags, &req->work,
2088 io_wq_is_hashed(&req->work));
2089 io_wq_enqueue(tctx->io_wq, &req->work);
2091 io_queue_linked_timeout(link);
2094 static void io_kill_timeout(struct io_kiocb *req, int status)
2095 __must_hold(&req->ctx->completion_lock)
2096 __must_hold(&req->ctx->timeout_lock)
2098 struct io_timeout_data *io = req->async_data;
2100 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2103 atomic_set(&req->ctx->cq_timeouts,
2104 atomic_read(&req->ctx->cq_timeouts) + 1);
2105 list_del_init(&req->timeout.list);
2106 io_req_tw_post_queue(req, status, 0);
2110 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
2112 while (!list_empty(&ctx->defer_list)) {
2113 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
2114 struct io_defer_entry, list);
2116 if (req_need_defer(de->req, de->seq))
2118 list_del_init(&de->list);
2119 io_req_task_queue(de->req);
2124 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
2125 __must_hold(&ctx->completion_lock)
2127 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
2128 struct io_kiocb *req, *tmp;
2130 spin_lock_irq(&ctx->timeout_lock);
2131 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
2132 u32 events_needed, events_got;
2134 if (io_is_timeout_noseq(req))
2138 * Since seq can easily wrap around over time, subtract
2139 * the last seq at which timeouts were flushed before comparing.
2140 * Assuming not more than 2^31-1 events have happened since,
2141 * these subtractions won't have wrapped, so we can check if
2142 * target is in [last_seq, current_seq] by comparing the two.
2144 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
2145 events_got = seq - ctx->cq_last_tm_flush;
2146 if (events_got < events_needed)
2149 io_kill_timeout(req, 0);
2151 ctx->cq_last_tm_flush = seq;
2152 spin_unlock_irq(&ctx->timeout_lock);
2155 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
2157 /* order cqe stores with ring update */
2158 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
2161 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
2163 if (ctx->off_timeout_used || ctx->drain_active) {
2164 spin_lock(&ctx->completion_lock);
2165 if (ctx->off_timeout_used)
2166 io_flush_timeouts(ctx);
2167 if (ctx->drain_active)
2168 io_queue_deferred(ctx);
2169 io_commit_cqring(ctx);
2170 spin_unlock(&ctx->completion_lock);
2173 io_eventfd_signal(ctx);
2176 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
2178 struct io_rings *r = ctx->rings;
2180 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
2183 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
2185 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
2189 * writes to the cq entry need to come after reading head; the
2190 * control dependency is enough as we're using WRITE_ONCE to
2193 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
2195 struct io_rings *rings = ctx->rings;
2196 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
2197 unsigned int shift = 0;
2198 unsigned int free, queued, len;
2200 if (ctx->flags & IORING_SETUP_CQE32)
2203 /* userspace may cheat modifying the tail, be safe and do min */
2204 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2205 free = ctx->cq_entries - queued;
2206 /* we need a contiguous range, limit based on the current array offset */
2207 len = min(free, ctx->cq_entries - off);
2211 ctx->cached_cq_tail++;
2212 ctx->cqe_cached = &rings->cqes[off];
2213 ctx->cqe_sentinel = ctx->cqe_cached + len;
2215 return &rings->cqes[off << shift];
2218 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2220 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2221 struct io_uring_cqe *cqe = ctx->cqe_cached;
2223 if (ctx->flags & IORING_SETUP_CQE32) {
2224 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2229 ctx->cached_cq_tail++;
2234 return __io_get_cqe(ctx);
2237 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2239 struct io_ev_fd *ev_fd;
2243 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2244 * and eventfd_signal
2246 ev_fd = rcu_dereference(ctx->io_ev_fd);
2249 * Check again if ev_fd exists incase an io_eventfd_unregister call
2250 * completed between the NULL check of ctx->io_ev_fd at the start of
2251 * the function and rcu_read_lock.
2253 if (unlikely(!ev_fd))
2255 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2258 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2259 eventfd_signal(ev_fd->cq_ev_fd, 1);
2264 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2267 * wake_up_all() may seem excessive, but io_wake_function() and
2268 * io_should_wake() handle the termination of the loop and only
2269 * wake as many waiters as we need to.
2271 if (wq_has_sleeper(&ctx->cq_wait))
2272 wake_up_all(&ctx->cq_wait);
2276 * This should only get called when at least one event has been posted.
2277 * Some applications rely on the eventfd notification count only changing
2278 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2279 * 1:1 relationship between how many times this function is called (and
2280 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2282 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2284 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2286 __io_commit_cqring_flush(ctx);
2288 io_cqring_wake(ctx);
2291 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2293 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2295 __io_commit_cqring_flush(ctx);
2297 if (ctx->flags & IORING_SETUP_SQPOLL)
2298 io_cqring_wake(ctx);
2301 /* Returns true if there are no backlogged entries after the flush */
2302 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2304 bool all_flushed, posted;
2305 size_t cqe_size = sizeof(struct io_uring_cqe);
2307 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2310 if (ctx->flags & IORING_SETUP_CQE32)
2314 spin_lock(&ctx->completion_lock);
2315 while (!list_empty(&ctx->cq_overflow_list)) {
2316 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2317 struct io_overflow_cqe *ocqe;
2321 ocqe = list_first_entry(&ctx->cq_overflow_list,
2322 struct io_overflow_cqe, list);
2324 memcpy(cqe, &ocqe->cqe, cqe_size);
2326 io_account_cq_overflow(ctx);
2329 list_del(&ocqe->list);
2333 all_flushed = list_empty(&ctx->cq_overflow_list);
2335 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2336 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2339 io_commit_cqring(ctx);
2340 spin_unlock(&ctx->completion_lock);
2342 io_cqring_ev_posted(ctx);
2346 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2350 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2351 /* iopoll syncs against uring_lock, not completion_lock */
2352 if (ctx->flags & IORING_SETUP_IOPOLL)
2353 mutex_lock(&ctx->uring_lock);
2354 ret = __io_cqring_overflow_flush(ctx, false);
2355 if (ctx->flags & IORING_SETUP_IOPOLL)
2356 mutex_unlock(&ctx->uring_lock);
2362 static void __io_put_task(struct task_struct *task, int nr)
2364 struct io_uring_task *tctx = task->io_uring;
2366 percpu_counter_sub(&tctx->inflight, nr);
2367 if (unlikely(atomic_read(&tctx->in_idle)))
2368 wake_up(&tctx->wait);
2369 put_task_struct_many(task, nr);
2372 /* must to be called somewhat shortly after putting a request */
2373 static inline void io_put_task(struct task_struct *task, int nr)
2375 if (likely(task == current))
2376 task->io_uring->cached_refs += nr;
2378 __io_put_task(task, nr);
2381 static void io_task_refs_refill(struct io_uring_task *tctx)
2383 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2385 percpu_counter_add(&tctx->inflight, refill);
2386 refcount_add(refill, ¤t->usage);
2387 tctx->cached_refs += refill;
2390 static inline void io_get_task_refs(int nr)
2392 struct io_uring_task *tctx = current->io_uring;
2394 tctx->cached_refs -= nr;
2395 if (unlikely(tctx->cached_refs < 0))
2396 io_task_refs_refill(tctx);
2399 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2401 struct io_uring_task *tctx = task->io_uring;
2402 unsigned int refs = tctx->cached_refs;
2405 tctx->cached_refs = 0;
2406 percpu_counter_sub(&tctx->inflight, refs);
2407 put_task_struct_many(task, refs);
2411 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2412 s32 res, u32 cflags, u64 extra1,
2415 struct io_overflow_cqe *ocqe;
2416 size_t ocq_size = sizeof(struct io_overflow_cqe);
2417 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2420 ocq_size += sizeof(struct io_uring_cqe);
2422 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2423 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2426 * If we're in ring overflow flush mode, or in task cancel mode,
2427 * or cannot allocate an overflow entry, then we need to drop it
2430 io_account_cq_overflow(ctx);
2431 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2434 if (list_empty(&ctx->cq_overflow_list)) {
2435 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2436 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2439 ocqe->cqe.user_data = user_data;
2440 ocqe->cqe.res = res;
2441 ocqe->cqe.flags = cflags;
2443 ocqe->cqe.big_cqe[0] = extra1;
2444 ocqe->cqe.big_cqe[1] = extra2;
2446 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2450 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
2451 struct io_kiocb *req)
2453 struct io_uring_cqe *cqe;
2455 if (!(ctx->flags & IORING_SETUP_CQE32)) {
2456 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2457 req->cqe.res, req->cqe.flags, 0, 0);
2460 * If we can't get a cq entry, userspace overflowed the
2461 * submission (by quite a lot). Increment the overflow count in
2464 cqe = io_get_cqe(ctx);
2466 memcpy(cqe, &req->cqe, sizeof(*cqe));
2470 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2471 req->cqe.res, req->cqe.flags,
2474 u64 extra1 = 0, extra2 = 0;
2476 if (req->flags & REQ_F_CQE32_INIT) {
2477 extra1 = req->extra1;
2478 extra2 = req->extra2;
2481 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2482 req->cqe.res, req->cqe.flags, extra1, extra2);
2485 * If we can't get a cq entry, userspace overflowed the
2486 * submission (by quite a lot). Increment the overflow count in
2489 cqe = io_get_cqe(ctx);
2491 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2492 WRITE_ONCE(cqe->big_cqe[0], extra1);
2493 WRITE_ONCE(cqe->big_cqe[1], extra2);
2497 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2498 req->cqe.res, req->cqe.flags,
2503 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2504 s32 res, u32 cflags)
2506 struct io_uring_cqe *cqe;
2509 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2512 * If we can't get a cq entry, userspace overflowed the
2513 * submission (by quite a lot). Increment the overflow count in
2516 cqe = io_get_cqe(ctx);
2518 WRITE_ONCE(cqe->user_data, user_data);
2519 WRITE_ONCE(cqe->res, res);
2520 WRITE_ONCE(cqe->flags, cflags);
2522 if (ctx->flags & IORING_SETUP_CQE32) {
2523 WRITE_ONCE(cqe->big_cqe[0], 0);
2524 WRITE_ONCE(cqe->big_cqe[1], 0);
2528 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2531 static void __io_req_complete_put(struct io_kiocb *req)
2534 * If we're the last reference to this request, add to our locked
2537 if (req_ref_put_and_test(req)) {
2538 struct io_ring_ctx *ctx = req->ctx;
2540 if (req->flags & IO_REQ_LINK_FLAGS) {
2541 if (req->flags & IO_DISARM_MASK)
2542 io_disarm_next(req);
2544 io_req_task_queue(req->link);
2548 io_req_put_rsrc(req);
2550 * Selected buffer deallocation in io_clean_op() assumes that
2551 * we don't hold ->completion_lock. Clean them here to avoid
2554 io_put_kbuf_comp(req);
2555 io_dismantle_req(req);
2556 io_put_task(req->task, 1);
2557 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2558 ctx->locked_free_nr++;
2562 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2565 if (!(req->flags & REQ_F_CQE_SKIP)) {
2567 req->cqe.flags = cflags;
2568 __io_fill_cqe_req(req->ctx, req);
2570 __io_req_complete_put(req);
2573 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2575 struct io_ring_ctx *ctx = req->ctx;
2577 spin_lock(&ctx->completion_lock);
2578 __io_req_complete_post(req, res, cflags);
2579 io_commit_cqring(ctx);
2580 spin_unlock(&ctx->completion_lock);
2581 io_cqring_ev_posted(ctx);
2584 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2588 req->cqe.flags = cflags;
2589 req->flags |= REQ_F_COMPLETE_INLINE;
2592 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2593 s32 res, u32 cflags)
2595 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2596 io_req_complete_state(req, res, cflags);
2598 io_req_complete_post(req, res, cflags);
2601 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2605 __io_req_complete(req, 0, res, 0);
2608 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2611 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2615 * Don't initialise the fields below on every allocation, but do that in
2616 * advance and keep them valid across allocations.
2618 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2622 req->async_data = NULL;
2623 /* not necessary, but safer to zero */
2627 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2628 struct io_submit_state *state)
2630 spin_lock(&ctx->completion_lock);
2631 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2632 ctx->locked_free_nr = 0;
2633 spin_unlock(&ctx->completion_lock);
2636 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2638 return !ctx->submit_state.free_list.next;
2642 * A request might get retired back into the request caches even before opcode
2643 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2644 * Because of that, io_alloc_req() should be called only under ->uring_lock
2645 * and with extra caution to not get a request that is still worked on.
2647 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2648 __must_hold(&ctx->uring_lock)
2650 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2651 void *reqs[IO_REQ_ALLOC_BATCH];
2655 * If we have more than a batch's worth of requests in our IRQ side
2656 * locked cache, grab the lock and move them over to our submission
2659 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2660 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2661 if (!io_req_cache_empty(ctx))
2665 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2668 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2669 * retry single alloc to be on the safe side.
2671 if (unlikely(ret <= 0)) {
2672 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2678 percpu_ref_get_many(&ctx->refs, ret);
2679 for (i = 0; i < ret; i++) {
2680 struct io_kiocb *req = reqs[i];
2682 io_preinit_req(req, ctx);
2683 io_req_add_to_cache(req, ctx);
2688 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2690 if (unlikely(io_req_cache_empty(ctx)))
2691 return __io_alloc_req_refill(ctx);
2695 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2697 struct io_wq_work_node *node;
2699 node = wq_stack_extract(&ctx->submit_state.free_list);
2700 return container_of(node, struct io_kiocb, comp_list);
2703 static inline void io_put_file(struct file *file)
2709 static inline void io_dismantle_req(struct io_kiocb *req)
2711 unsigned int flags = req->flags;
2713 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2715 if (!(flags & REQ_F_FIXED_FILE))
2716 io_put_file(req->file);
2719 static __cold void io_free_req(struct io_kiocb *req)
2721 struct io_ring_ctx *ctx = req->ctx;
2723 io_req_put_rsrc(req);
2724 io_dismantle_req(req);
2725 io_put_task(req->task, 1);
2727 spin_lock(&ctx->completion_lock);
2728 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2729 ctx->locked_free_nr++;
2730 spin_unlock(&ctx->completion_lock);
2733 static inline void io_remove_next_linked(struct io_kiocb *req)
2735 struct io_kiocb *nxt = req->link;
2737 req->link = nxt->link;
2741 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2742 __must_hold(&req->ctx->completion_lock)
2743 __must_hold(&req->ctx->timeout_lock)
2745 struct io_kiocb *link = req->link;
2747 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2748 struct io_timeout_data *io = link->async_data;
2750 io_remove_next_linked(req);
2751 link->timeout.head = NULL;
2752 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2753 list_del(&link->timeout.list);
2760 static void io_fail_links(struct io_kiocb *req)
2761 __must_hold(&req->ctx->completion_lock)
2763 struct io_kiocb *nxt, *link = req->link;
2764 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2768 long res = -ECANCELED;
2770 if (link->flags & REQ_F_FAIL)
2771 res = link->cqe.res;
2776 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2780 link->flags |= REQ_F_CQE_SKIP;
2782 link->flags &= ~REQ_F_CQE_SKIP;
2783 __io_req_complete_post(link, res, 0);
2788 static bool io_disarm_next(struct io_kiocb *req)
2789 __must_hold(&req->ctx->completion_lock)
2791 struct io_kiocb *link = NULL;
2792 bool posted = false;
2794 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2796 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2797 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2798 io_remove_next_linked(req);
2799 io_req_tw_post_queue(link, -ECANCELED, 0);
2802 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2803 struct io_ring_ctx *ctx = req->ctx;
2805 spin_lock_irq(&ctx->timeout_lock);
2806 link = io_disarm_linked_timeout(req);
2807 spin_unlock_irq(&ctx->timeout_lock);
2810 io_req_tw_post_queue(link, -ECANCELED, 0);
2813 if (unlikely((req->flags & REQ_F_FAIL) &&
2814 !(req->flags & REQ_F_HARDLINK))) {
2815 posted |= (req->link != NULL);
2821 static void __io_req_find_next_prep(struct io_kiocb *req)
2823 struct io_ring_ctx *ctx = req->ctx;
2826 spin_lock(&ctx->completion_lock);
2827 posted = io_disarm_next(req);
2828 io_commit_cqring(ctx);
2829 spin_unlock(&ctx->completion_lock);
2831 io_cqring_ev_posted(ctx);
2834 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2836 struct io_kiocb *nxt;
2839 * If LINK is set, we have dependent requests in this chain. If we
2840 * didn't fail this request, queue the first one up, moving any other
2841 * dependencies to the next request. In case of failure, fail the rest
2844 if (unlikely(req->flags & IO_DISARM_MASK))
2845 __io_req_find_next_prep(req);
2851 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2855 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2856 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2858 io_submit_flush_completions(ctx);
2859 mutex_unlock(&ctx->uring_lock);
2862 percpu_ref_put(&ctx->refs);
2865 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2867 io_commit_cqring(ctx);
2868 spin_unlock(&ctx->completion_lock);
2869 io_cqring_ev_posted(ctx);
2872 static void handle_prev_tw_list(struct io_wq_work_node *node,
2873 struct io_ring_ctx **ctx, bool *uring_locked)
2875 if (*ctx && !*uring_locked)
2876 spin_lock(&(*ctx)->completion_lock);
2879 struct io_wq_work_node *next = node->next;
2880 struct io_kiocb *req = container_of(node, struct io_kiocb,
2883 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2885 if (req->ctx != *ctx) {
2886 if (unlikely(!*uring_locked && *ctx))
2887 ctx_commit_and_unlock(*ctx);
2889 ctx_flush_and_put(*ctx, uring_locked);
2891 /* if not contended, grab and improve batching */
2892 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2893 percpu_ref_get(&(*ctx)->refs);
2894 if (unlikely(!*uring_locked))
2895 spin_lock(&(*ctx)->completion_lock);
2897 if (likely(*uring_locked))
2898 req->io_task_work.func(req, uring_locked);
2900 __io_req_complete_post(req, req->cqe.res,
2901 io_put_kbuf_comp(req));
2905 if (unlikely(!*uring_locked))
2906 ctx_commit_and_unlock(*ctx);
2909 static void handle_tw_list(struct io_wq_work_node *node,
2910 struct io_ring_ctx **ctx, bool *locked)
2913 struct io_wq_work_node *next = node->next;
2914 struct io_kiocb *req = container_of(node, struct io_kiocb,
2917 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2919 if (req->ctx != *ctx) {
2920 ctx_flush_and_put(*ctx, locked);
2922 /* if not contended, grab and improve batching */
2923 *locked = mutex_trylock(&(*ctx)->uring_lock);
2924 percpu_ref_get(&(*ctx)->refs);
2926 req->io_task_work.func(req, locked);
2931 static void tctx_task_work(struct callback_head *cb)
2933 bool uring_locked = false;
2934 struct io_ring_ctx *ctx = NULL;
2935 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2939 struct io_wq_work_node *node1, *node2;
2941 spin_lock_irq(&tctx->task_lock);
2942 node1 = tctx->prio_task_list.first;
2943 node2 = tctx->task_list.first;
2944 INIT_WQ_LIST(&tctx->task_list);
2945 INIT_WQ_LIST(&tctx->prio_task_list);
2946 if (!node2 && !node1)
2947 tctx->task_running = false;
2948 spin_unlock_irq(&tctx->task_lock);
2949 if (!node2 && !node1)
2953 handle_prev_tw_list(node1, &ctx, &uring_locked);
2955 handle_tw_list(node2, &ctx, &uring_locked);
2958 if (data_race(!tctx->task_list.first) &&
2959 data_race(!tctx->prio_task_list.first) && uring_locked)
2960 io_submit_flush_completions(ctx);
2963 ctx_flush_and_put(ctx, &uring_locked);
2965 /* relaxed read is enough as only the task itself sets ->in_idle */
2966 if (unlikely(atomic_read(&tctx->in_idle)))
2967 io_uring_drop_tctx_refs(current);
2970 static void __io_req_task_work_add(struct io_kiocb *req,
2971 struct io_uring_task *tctx,
2972 struct io_wq_work_list *list)
2974 struct io_ring_ctx *ctx = req->ctx;
2975 struct io_wq_work_node *node;
2976 unsigned long flags;
2979 spin_lock_irqsave(&tctx->task_lock, flags);
2980 wq_list_add_tail(&req->io_task_work.node, list);
2981 running = tctx->task_running;
2983 tctx->task_running = true;
2984 spin_unlock_irqrestore(&tctx->task_lock, flags);
2986 /* task_work already pending, we're done */
2990 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2991 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2993 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2996 spin_lock_irqsave(&tctx->task_lock, flags);
2997 tctx->task_running = false;
2998 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2999 spin_unlock_irqrestore(&tctx->task_lock, flags);
3002 req = container_of(node, struct io_kiocb, io_task_work.node);
3004 if (llist_add(&req->io_task_work.fallback_node,
3005 &req->ctx->fallback_llist))
3006 schedule_delayed_work(&req->ctx->fallback_work, 1);
3010 static void io_req_task_work_add(struct io_kiocb *req)
3012 struct io_uring_task *tctx = req->task->io_uring;
3014 __io_req_task_work_add(req, tctx, &tctx->task_list);
3017 static void io_req_task_prio_work_add(struct io_kiocb *req)
3019 struct io_uring_task *tctx = req->task->io_uring;
3021 if (req->ctx->flags & IORING_SETUP_SQPOLL)
3022 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
3024 __io_req_task_work_add(req, tctx, &tctx->task_list);
3027 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
3029 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
3032 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
3035 req->cqe.flags = cflags;
3036 req->io_task_work.func = io_req_tw_post;
3037 io_req_task_work_add(req);
3040 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
3042 /* not needed for normal modes, but SQPOLL depends on it */
3043 io_tw_lock(req->ctx, locked);
3044 io_req_complete_failed(req, req->cqe.res);
3047 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
3049 io_tw_lock(req->ctx, locked);
3050 /* req->task == current here, checking PF_EXITING is safe */
3051 if (likely(!(req->task->flags & PF_EXITING)))
3054 io_req_complete_failed(req, -EFAULT);
3057 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
3060 req->io_task_work.func = io_req_task_cancel;
3061 io_req_task_work_add(req);
3064 static void io_req_task_queue(struct io_kiocb *req)
3066 req->io_task_work.func = io_req_task_submit;
3067 io_req_task_work_add(req);
3070 static void io_req_task_queue_reissue(struct io_kiocb *req)
3072 req->io_task_work.func = io_queue_iowq;
3073 io_req_task_work_add(req);
3076 static void io_queue_next(struct io_kiocb *req)
3078 struct io_kiocb *nxt = io_req_find_next(req);
3081 io_req_task_queue(nxt);
3084 static void io_free_batch_list(struct io_ring_ctx *ctx,
3085 struct io_wq_work_node *node)
3086 __must_hold(&ctx->uring_lock)
3088 struct task_struct *task = NULL;
3092 struct io_kiocb *req = container_of(node, struct io_kiocb,
3095 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
3096 if (req->flags & REQ_F_REFCOUNT) {
3097 node = req->comp_list.next;
3098 if (!req_ref_put_and_test(req))
3101 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3102 struct async_poll *apoll = req->apoll;
3104 if (apoll->double_poll)
3105 kfree(apoll->double_poll);
3106 list_add(&apoll->poll.wait.entry,
3108 req->flags &= ~REQ_F_POLLED;
3110 if (req->flags & IO_REQ_LINK_FLAGS)
3112 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
3115 if (!(req->flags & REQ_F_FIXED_FILE))
3116 io_put_file(req->file);
3118 io_req_put_rsrc_locked(req, ctx);
3120 if (req->task != task) {
3122 io_put_task(task, task_refs);
3127 node = req->comp_list.next;
3128 io_req_add_to_cache(req, ctx);
3132 io_put_task(task, task_refs);
3135 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
3136 __must_hold(&ctx->uring_lock)
3138 struct io_wq_work_node *node, *prev;
3139 struct io_submit_state *state = &ctx->submit_state;
3141 if (state->flush_cqes) {
3142 spin_lock(&ctx->completion_lock);
3143 wq_list_for_each(node, prev, &state->compl_reqs) {
3144 struct io_kiocb *req = container_of(node, struct io_kiocb,
3147 if (!(req->flags & REQ_F_CQE_SKIP))
3148 __io_fill_cqe_req(ctx, req);
3151 io_commit_cqring(ctx);
3152 spin_unlock(&ctx->completion_lock);
3153 io_cqring_ev_posted(ctx);
3154 state->flush_cqes = false;
3157 io_free_batch_list(ctx, state->compl_reqs.first);
3158 INIT_WQ_LIST(&state->compl_reqs);
3162 * Drop reference to request, return next in chain (if there is one) if this
3163 * was the last reference to this request.
3165 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
3167 struct io_kiocb *nxt = NULL;
3169 if (req_ref_put_and_test(req)) {
3170 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
3171 nxt = io_req_find_next(req);
3177 static inline void io_put_req(struct io_kiocb *req)
3179 if (req_ref_put_and_test(req)) {
3185 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
3187 /* See comment at the top of this file */
3189 return __io_cqring_events(ctx);
3192 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
3194 struct io_rings *rings = ctx->rings;
3196 /* make sure SQ entry isn't read before tail */
3197 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3200 static inline bool io_run_task_work(void)
3202 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3203 __set_current_state(TASK_RUNNING);
3204 clear_notify_signal();
3205 if (task_work_pending(current))
3213 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3215 struct io_wq_work_node *pos, *start, *prev;
3216 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3217 DEFINE_IO_COMP_BATCH(iob);
3221 * Only spin for completions if we don't have multiple devices hanging
3222 * off our complete list.
3224 if (ctx->poll_multi_queue || force_nonspin)
3225 poll_flags |= BLK_POLL_ONESHOT;
3227 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3228 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3229 struct kiocb *kiocb = &req->rw.kiocb;
3233 * Move completed and retryable entries to our local lists.
3234 * If we find a request that requires polling, break out
3235 * and complete those lists first, if we have entries there.
3237 if (READ_ONCE(req->iopoll_completed))
3240 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3241 if (unlikely(ret < 0))
3244 poll_flags |= BLK_POLL_ONESHOT;
3246 /* iopoll may have completed current req */
3247 if (!rq_list_empty(iob.req_list) ||
3248 READ_ONCE(req->iopoll_completed))
3252 if (!rq_list_empty(iob.req_list))
3258 wq_list_for_each_resume(pos, prev) {
3259 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3261 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3262 if (!smp_load_acquire(&req->iopoll_completed))
3265 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3268 req->cqe.flags = io_put_kbuf(req, 0);
3269 __io_fill_cqe_req(req->ctx, req);
3272 if (unlikely(!nr_events))
3275 io_commit_cqring(ctx);
3276 io_cqring_ev_posted_iopoll(ctx);
3277 pos = start ? start->next : ctx->iopoll_list.first;
3278 wq_list_cut(&ctx->iopoll_list, prev, start);
3279 io_free_batch_list(ctx, pos);
3284 * We can't just wait for polled events to come to us, we have to actively
3285 * find and complete them.
3287 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3289 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3292 mutex_lock(&ctx->uring_lock);
3293 while (!wq_list_empty(&ctx->iopoll_list)) {
3294 /* let it sleep and repeat later if can't complete a request */
3295 if (io_do_iopoll(ctx, true) == 0)
3298 * Ensure we allow local-to-the-cpu processing to take place,
3299 * in this case we need to ensure that we reap all events.
3300 * Also let task_work, etc. to progress by releasing the mutex
3302 if (need_resched()) {
3303 mutex_unlock(&ctx->uring_lock);
3305 mutex_lock(&ctx->uring_lock);
3308 mutex_unlock(&ctx->uring_lock);
3311 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3313 unsigned int nr_events = 0;
3315 unsigned long check_cq;
3318 * Don't enter poll loop if we already have events pending.
3319 * If we do, we can potentially be spinning for commands that
3320 * already triggered a CQE (eg in error).
3322 check_cq = READ_ONCE(ctx->check_cq);
3323 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3324 __io_cqring_overflow_flush(ctx, false);
3325 if (io_cqring_events(ctx))
3329 * Similarly do not spin if we have not informed the user of any
3332 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3337 * If a submit got punted to a workqueue, we can have the
3338 * application entering polling for a command before it gets
3339 * issued. That app will hold the uring_lock for the duration
3340 * of the poll right here, so we need to take a breather every
3341 * now and then to ensure that the issue has a chance to add
3342 * the poll to the issued list. Otherwise we can spin here
3343 * forever, while the workqueue is stuck trying to acquire the
3346 if (wq_list_empty(&ctx->iopoll_list)) {
3347 u32 tail = ctx->cached_cq_tail;
3349 mutex_unlock(&ctx->uring_lock);
3351 mutex_lock(&ctx->uring_lock);
3353 /* some requests don't go through iopoll_list */
3354 if (tail != ctx->cached_cq_tail ||
3355 wq_list_empty(&ctx->iopoll_list))
3358 ret = io_do_iopoll(ctx, !min);
3363 } while (nr_events < min && !need_resched());
3368 static void kiocb_end_write(struct io_kiocb *req)
3371 * Tell lockdep we inherited freeze protection from submission
3374 if (req->flags & REQ_F_ISREG) {
3375 struct super_block *sb = file_inode(req->file)->i_sb;
3377 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3383 static bool io_resubmit_prep(struct io_kiocb *req)
3385 struct io_async_rw *rw = req->async_data;
3387 if (!req_has_async_data(req))
3388 return !io_req_prep_async(req);
3389 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3393 static bool io_rw_should_reissue(struct io_kiocb *req)
3395 umode_t mode = file_inode(req->file)->i_mode;
3396 struct io_ring_ctx *ctx = req->ctx;
3398 if (!S_ISBLK(mode) && !S_ISREG(mode))
3400 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3401 !(ctx->flags & IORING_SETUP_IOPOLL)))
3404 * If ref is dying, we might be running poll reap from the exit work.
3405 * Don't attempt to reissue from that path, just let it fail with
3408 if (percpu_ref_is_dying(&ctx->refs))
3411 * Play it safe and assume not safe to re-import and reissue if we're
3412 * not in the original thread group (or in task context).
3414 if (!same_thread_group(req->task, current) || !in_task())
3419 static bool io_resubmit_prep(struct io_kiocb *req)
3423 static bool io_rw_should_reissue(struct io_kiocb *req)
3429 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3431 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3432 kiocb_end_write(req);
3433 fsnotify_modify(req->file);
3435 fsnotify_access(req->file);
3437 if (unlikely(res != req->cqe.res)) {
3438 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3439 io_rw_should_reissue(req)) {
3440 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3449 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3451 int res = req->cqe.res;
3454 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3455 io_req_add_compl_list(req);
3457 io_req_complete_post(req, res,
3458 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3462 static void __io_complete_rw(struct io_kiocb *req, long res,
3463 unsigned int issue_flags)
3465 if (__io_complete_rw_common(req, res))
3467 __io_req_complete(req, issue_flags, req->cqe.res,
3468 io_put_kbuf(req, issue_flags));
3471 static void io_complete_rw(struct kiocb *kiocb, long res)
3473 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3475 if (__io_complete_rw_common(req, res))
3478 req->io_task_work.func = io_req_task_complete;
3479 io_req_task_prio_work_add(req);
3482 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3484 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3486 if (kiocb->ki_flags & IOCB_WRITE)
3487 kiocb_end_write(req);
3488 if (unlikely(res != req->cqe.res)) {
3489 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3490 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3496 /* order with io_iopoll_complete() checking ->iopoll_completed */
3497 smp_store_release(&req->iopoll_completed, 1);
3501 * After the iocb has been issued, it's safe to be found on the poll list.
3502 * Adding the kiocb to the list AFTER submission ensures that we don't
3503 * find it from a io_do_iopoll() thread before the issuer is done
3504 * accessing the kiocb cookie.
3506 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3508 struct io_ring_ctx *ctx = req->ctx;
3509 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3511 /* workqueue context doesn't hold uring_lock, grab it now */
3512 if (unlikely(needs_lock))
3513 mutex_lock(&ctx->uring_lock);
3516 * Track whether we have multiple files in our lists. This will impact
3517 * how we do polling eventually, not spinning if we're on potentially
3518 * different devices.
3520 if (wq_list_empty(&ctx->iopoll_list)) {
3521 ctx->poll_multi_queue = false;
3522 } else if (!ctx->poll_multi_queue) {
3523 struct io_kiocb *list_req;
3525 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3527 if (list_req->file != req->file)
3528 ctx->poll_multi_queue = true;
3532 * For fast devices, IO may have already completed. If it has, add
3533 * it to the front so we find it first.
3535 if (READ_ONCE(req->iopoll_completed))
3536 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3538 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3540 if (unlikely(needs_lock)) {
3542 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3543 * in sq thread task context or in io worker task context. If
3544 * current task context is sq thread, we don't need to check
3545 * whether should wake up sq thread.
3547 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3548 wq_has_sleeper(&ctx->sq_data->wait))
3549 wake_up(&ctx->sq_data->wait);
3551 mutex_unlock(&ctx->uring_lock);
3555 static bool io_bdev_nowait(struct block_device *bdev)
3557 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3561 * If we tracked the file through the SCM inflight mechanism, we could support
3562 * any file. For now, just ensure that anything potentially problematic is done
3565 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3567 if (S_ISBLK(mode)) {
3568 if (IS_ENABLED(CONFIG_BLOCK) &&
3569 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3575 if (S_ISREG(mode)) {
3576 if (IS_ENABLED(CONFIG_BLOCK) &&
3577 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3578 file->f_op != &io_uring_fops)
3583 /* any ->read/write should understand O_NONBLOCK */
3584 if (file->f_flags & O_NONBLOCK)
3586 return file->f_mode & FMODE_NOWAIT;
3590 * If we tracked the file through the SCM inflight mechanism, we could support
3591 * any file. For now, just ensure that anything potentially problematic is done
3594 static unsigned int io_file_get_flags(struct file *file)
3596 umode_t mode = file_inode(file)->i_mode;
3597 unsigned int res = 0;
3601 if (__io_file_supports_nowait(file, mode))
3603 if (io_file_need_scm(file))
3608 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3610 return req->flags & REQ_F_SUPPORT_NOWAIT;
3613 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3615 struct kiocb *kiocb = &req->rw.kiocb;
3619 kiocb->ki_pos = READ_ONCE(sqe->off);
3620 /* used for fixed read/write too - just read unconditionally */
3621 req->buf_index = READ_ONCE(sqe->buf_index);
3623 if (req->opcode == IORING_OP_READ_FIXED ||
3624 req->opcode == IORING_OP_WRITE_FIXED) {
3625 struct io_ring_ctx *ctx = req->ctx;
3628 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3630 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3631 req->imu = ctx->user_bufs[index];
3632 io_req_set_rsrc_node(req, ctx, 0);
3635 ioprio = READ_ONCE(sqe->ioprio);
3637 ret = ioprio_check_cap(ioprio);
3641 kiocb->ki_ioprio = ioprio;
3643 kiocb->ki_ioprio = get_current_ioprio();
3646 req->rw.addr = READ_ONCE(sqe->addr);
3647 req->rw.len = READ_ONCE(sqe->len);
3648 req->rw.flags = READ_ONCE(sqe->rw_flags);
3652 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3658 case -ERESTARTNOINTR:
3659 case -ERESTARTNOHAND:
3660 case -ERESTART_RESTARTBLOCK:
3662 * We can't just restart the syscall, since previously
3663 * submitted sqes may already be in progress. Just fail this
3669 kiocb->ki_complete(kiocb, ret);
3673 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3675 struct kiocb *kiocb = &req->rw.kiocb;
3677 if (kiocb->ki_pos != -1)
3678 return &kiocb->ki_pos;
3680 if (!(req->file->f_mode & FMODE_STREAM)) {
3681 req->flags |= REQ_F_CUR_POS;
3682 kiocb->ki_pos = req->file->f_pos;
3683 return &kiocb->ki_pos;
3690 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3691 unsigned int issue_flags)
3693 struct io_async_rw *io = req->async_data;
3695 /* add previously done IO, if any */
3696 if (req_has_async_data(req) && io->bytes_done > 0) {
3698 ret = io->bytes_done;
3700 ret += io->bytes_done;
3703 if (req->flags & REQ_F_CUR_POS)
3704 req->file->f_pos = req->rw.kiocb.ki_pos;
3705 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3706 __io_complete_rw(req, ret, issue_flags);
3708 io_rw_done(&req->rw.kiocb, ret);
3710 if (req->flags & REQ_F_REISSUE) {
3711 req->flags &= ~REQ_F_REISSUE;
3712 if (io_resubmit_prep(req))
3713 io_req_task_queue_reissue(req);
3715 io_req_task_queue_fail(req, ret);
3719 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3720 struct io_mapped_ubuf *imu)
3722 size_t len = req->rw.len;
3723 u64 buf_end, buf_addr = req->rw.addr;
3726 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3728 /* not inside the mapped region */
3729 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3733 * May not be a start of buffer, set size appropriately
3734 * and advance us to the beginning.
3736 offset = buf_addr - imu->ubuf;
3737 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3741 * Don't use iov_iter_advance() here, as it's really slow for
3742 * using the latter parts of a big fixed buffer - it iterates
3743 * over each segment manually. We can cheat a bit here, because
3746 * 1) it's a BVEC iter, we set it up
3747 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3748 * first and last bvec
3750 * So just find our index, and adjust the iterator afterwards.
3751 * If the offset is within the first bvec (or the whole first
3752 * bvec, just use iov_iter_advance(). This makes it easier
3753 * since we can just skip the first segment, which may not
3754 * be PAGE_SIZE aligned.
3756 const struct bio_vec *bvec = imu->bvec;
3758 if (offset <= bvec->bv_len) {
3759 iov_iter_advance(iter, offset);
3761 unsigned long seg_skip;
3763 /* skip first vec */
3764 offset -= bvec->bv_len;
3765 seg_skip = 1 + (offset >> PAGE_SHIFT);
3767 iter->bvec = bvec + seg_skip;
3768 iter->nr_segs -= seg_skip;
3769 iter->count -= bvec->bv_len + offset;
3770 iter->iov_offset = offset & ~PAGE_MASK;
3777 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3778 unsigned int issue_flags)
3780 if (WARN_ON_ONCE(!req->imu))
3782 return __io_import_fixed(req, rw, iter, req->imu);
3785 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3786 struct io_buffer_list *bl, unsigned int bgid)
3789 if (bgid < BGID_ARRAY)
3792 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3795 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3796 struct io_buffer_list *bl)
3798 if (!list_empty(&bl->buf_list)) {
3799 struct io_buffer *kbuf;
3801 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3802 list_del(&kbuf->list);
3803 if (*len > kbuf->len)
3805 req->flags |= REQ_F_BUFFER_SELECTED;
3807 req->buf_index = kbuf->bid;
3808 return u64_to_user_ptr(kbuf->addr);
3813 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3814 struct io_buffer_list *bl,
3815 unsigned int issue_flags)
3817 struct io_uring_buf_ring *br = bl->buf_ring;
3818 struct io_uring_buf *buf;
3819 __u16 head = bl->head;
3821 if (unlikely(smp_load_acquire(&br->tail) == head))
3825 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3826 buf = &br->bufs[head];
3828 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3829 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3830 buf = page_address(bl->buf_pages[index]);
3833 if (*len > buf->len)
3835 req->flags |= REQ_F_BUFFER_RING;
3837 req->buf_index = buf->bid;
3839 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3841 * If we came in unlocked, we have no choice but to consume the
3842 * buffer here. This does mean it'll be pinned until the IO
3843 * completes. But coming in unlocked means we're in io-wq
3844 * context, hence there should be no further retry. For the
3845 * locked case, the caller must ensure to call the commit when
3846 * the transfer completes (or if we get -EAGAIN and must poll
3849 req->buf_list = NULL;
3852 return u64_to_user_ptr(buf->addr);
3855 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3856 unsigned int issue_flags)
3858 struct io_ring_ctx *ctx = req->ctx;
3859 struct io_buffer_list *bl;
3860 void __user *ret = NULL;
3862 io_ring_submit_lock(req->ctx, issue_flags);
3864 bl = io_buffer_get_list(ctx, req->buf_index);
3866 if (bl->buf_nr_pages)
3867 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3869 ret = io_provided_buffer_select(req, len, bl);
3871 io_ring_submit_unlock(req->ctx, issue_flags);
3875 #ifdef CONFIG_COMPAT
3876 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3877 unsigned int issue_flags)
3879 struct compat_iovec __user *uiov;
3880 compat_ssize_t clen;
3884 uiov = u64_to_user_ptr(req->rw.addr);
3885 if (!access_ok(uiov, sizeof(*uiov)))
3887 if (__get_user(clen, &uiov->iov_len))
3893 buf = io_buffer_select(req, &len, issue_flags);
3896 req->rw.addr = (unsigned long) buf;
3897 iov[0].iov_base = buf;
3898 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3903 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3904 unsigned int issue_flags)
3906 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3910 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3913 len = iov[0].iov_len;
3916 buf = io_buffer_select(req, &len, issue_flags);
3919 req->rw.addr = (unsigned long) buf;
3920 iov[0].iov_base = buf;
3921 req->rw.len = iov[0].iov_len = len;
3925 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3926 unsigned int issue_flags)
3928 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3929 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3930 iov[0].iov_len = req->rw.len;
3933 if (req->rw.len != 1)
3936 #ifdef CONFIG_COMPAT
3937 if (req->ctx->compat)
3938 return io_compat_import(req, iov, issue_flags);
3941 return __io_iov_buffer_select(req, iov, issue_flags);
3944 static inline bool io_do_buffer_select(struct io_kiocb *req)
3946 if (!(req->flags & REQ_F_BUFFER_SELECT))
3948 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3951 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3952 struct io_rw_state *s,
3953 unsigned int issue_flags)
3955 struct iov_iter *iter = &s->iter;
3956 u8 opcode = req->opcode;
3957 struct iovec *iovec;
3962 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3963 ret = io_import_fixed(req, rw, iter, issue_flags);
3965 return ERR_PTR(ret);
3969 buf = u64_to_user_ptr(req->rw.addr);
3970 sqe_len = req->rw.len;
3972 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3973 if (io_do_buffer_select(req)) {
3974 buf = io_buffer_select(req, &sqe_len, issue_flags);
3976 return ERR_PTR(-ENOBUFS);
3977 req->rw.addr = (unsigned long) buf;
3978 req->rw.len = sqe_len;
3981 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3983 return ERR_PTR(ret);
3987 iovec = s->fast_iov;
3988 if (req->flags & REQ_F_BUFFER_SELECT) {
3989 ret = io_iov_buffer_select(req, iovec, issue_flags);
3991 return ERR_PTR(ret);
3992 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3996 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3998 if (unlikely(ret < 0))
3999 return ERR_PTR(ret);
4003 static inline int io_import_iovec(int rw, struct io_kiocb *req,
4004 struct iovec **iovec, struct io_rw_state *s,
4005 unsigned int issue_flags)
4007 *iovec = __io_import_iovec(rw, req, s, issue_flags);
4008 if (unlikely(IS_ERR(*iovec)))
4009 return PTR_ERR(*iovec);
4011 iov_iter_save_state(&s->iter, &s->iter_state);
4015 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
4017 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
4021 * For files that don't have ->read_iter() and ->write_iter(), handle them
4022 * by looping over ->read() or ->write() manually.
4024 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
4026 struct kiocb *kiocb = &req->rw.kiocb;
4027 struct file *file = req->file;
4032 * Don't support polled IO through this interface, and we can't
4033 * support non-blocking either. For the latter, this just causes
4034 * the kiocb to be handled from an async context.
4036 if (kiocb->ki_flags & IOCB_HIPRI)
4038 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
4039 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
4042 ppos = io_kiocb_ppos(kiocb);
4044 while (iov_iter_count(iter)) {
4048 if (!iov_iter_is_bvec(iter)) {
4049 iovec = iov_iter_iovec(iter);
4051 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
4052 iovec.iov_len = req->rw.len;
4056 nr = file->f_op->read(file, iovec.iov_base,
4057 iovec.iov_len, ppos);
4059 nr = file->f_op->write(file, iovec.iov_base,
4060 iovec.iov_len, ppos);
4069 if (!iov_iter_is_bvec(iter)) {
4070 iov_iter_advance(iter, nr);
4077 if (nr != iovec.iov_len)
4084 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
4085 const struct iovec *fast_iov, struct iov_iter *iter)
4087 struct io_async_rw *rw = req->async_data;
4089 memcpy(&rw->s.iter, iter, sizeof(*iter));
4090 rw->free_iovec = iovec;
4092 /* can only be fixed buffers, no need to do anything */
4093 if (iov_iter_is_bvec(iter))
4096 unsigned iov_off = 0;
4098 rw->s.iter.iov = rw->s.fast_iov;
4099 if (iter->iov != fast_iov) {
4100 iov_off = iter->iov - fast_iov;
4101 rw->s.iter.iov += iov_off;
4103 if (rw->s.fast_iov != fast_iov)
4104 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
4105 sizeof(struct iovec) * iter->nr_segs);
4107 req->flags |= REQ_F_NEED_CLEANUP;
4111 static inline bool io_alloc_async_data(struct io_kiocb *req)
4113 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
4114 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
4115 if (req->async_data) {
4116 req->flags |= REQ_F_ASYNC_DATA;
4122 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
4123 struct io_rw_state *s, bool force)
4125 if (!force && !io_op_defs[req->opcode].needs_async_setup)
4127 if (!req_has_async_data(req)) {
4128 struct io_async_rw *iorw;
4130 if (io_alloc_async_data(req)) {
4135 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
4136 iorw = req->async_data;
4137 /* we've copied and mapped the iter, ensure state is saved */
4138 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
4143 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
4145 struct io_async_rw *iorw = req->async_data;
4149 /* submission path, ->uring_lock should already be taken */
4150 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
4151 if (unlikely(ret < 0))
4154 iorw->bytes_done = 0;
4155 iorw->free_iovec = iov;
4157 req->flags |= REQ_F_NEED_CLEANUP;
4161 static int io_readv_prep_async(struct io_kiocb *req)
4163 return io_rw_prep_async(req, READ);
4166 static int io_writev_prep_async(struct io_kiocb *req)
4168 return io_rw_prep_async(req, WRITE);
4172 * This is our waitqueue callback handler, registered through __folio_lock_async()
4173 * when we initially tried to do the IO with the iocb armed our waitqueue.
4174 * This gets called when the page is unlocked, and we generally expect that to
4175 * happen when the page IO is completed and the page is now uptodate. This will
4176 * queue a task_work based retry of the operation, attempting to copy the data
4177 * again. If the latter fails because the page was NOT uptodate, then we will
4178 * do a thread based blocking retry of the operation. That's the unexpected
4181 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
4182 int sync, void *arg)
4184 struct wait_page_queue *wpq;
4185 struct io_kiocb *req = wait->private;
4186 struct wait_page_key *key = arg;
4188 wpq = container_of(wait, struct wait_page_queue, wait);
4190 if (!wake_page_match(wpq, key))
4193 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
4194 list_del_init(&wait->entry);
4195 io_req_task_queue(req);
4200 * This controls whether a given IO request should be armed for async page
4201 * based retry. If we return false here, the request is handed to the async
4202 * worker threads for retry. If we're doing buffered reads on a regular file,
4203 * we prepare a private wait_page_queue entry and retry the operation. This
4204 * will either succeed because the page is now uptodate and unlocked, or it
4205 * will register a callback when the page is unlocked at IO completion. Through
4206 * that callback, io_uring uses task_work to setup a retry of the operation.
4207 * That retry will attempt the buffered read again. The retry will generally
4208 * succeed, or in rare cases where it fails, we then fall back to using the
4209 * async worker threads for a blocking retry.
4211 static bool io_rw_should_retry(struct io_kiocb *req)
4213 struct io_async_rw *rw = req->async_data;
4214 struct wait_page_queue *wait = &rw->wpq;
4215 struct kiocb *kiocb = &req->rw.kiocb;
4217 /* never retry for NOWAIT, we just complete with -EAGAIN */
4218 if (req->flags & REQ_F_NOWAIT)
4221 /* Only for buffered IO */
4222 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4226 * just use poll if we can, and don't attempt if the fs doesn't
4227 * support callback based unlocks
4229 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4232 wait->wait.func = io_async_buf_func;
4233 wait->wait.private = req;
4234 wait->wait.flags = 0;
4235 INIT_LIST_HEAD(&wait->wait.entry);
4236 kiocb->ki_flags |= IOCB_WAITQ;
4237 kiocb->ki_flags &= ~IOCB_NOWAIT;
4238 kiocb->ki_waitq = wait;
4242 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4244 if (likely(req->file->f_op->read_iter))
4245 return call_read_iter(req->file, &req->rw.kiocb, iter);
4246 else if (req->file->f_op->read)
4247 return loop_rw_iter(READ, req, iter);
4252 static bool need_read_all(struct io_kiocb *req)
4254 return req->flags & REQ_F_ISREG ||
4255 S_ISBLK(file_inode(req->file)->i_mode);
4258 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4260 struct kiocb *kiocb = &req->rw.kiocb;
4261 struct io_ring_ctx *ctx = req->ctx;
4262 struct file *file = req->file;
4265 if (unlikely(!file || !(file->f_mode & mode)))
4268 if (!io_req_ffs_set(req))
4269 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4271 kiocb->ki_flags = iocb_flags(file);
4272 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4277 * If the file is marked O_NONBLOCK, still allow retry for it if it
4278 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4279 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4281 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4282 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4283 req->flags |= REQ_F_NOWAIT;
4285 if (ctx->flags & IORING_SETUP_IOPOLL) {
4286 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4289 kiocb->private = NULL;
4290 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4291 kiocb->ki_complete = io_complete_rw_iopoll;
4292 req->iopoll_completed = 0;
4294 if (kiocb->ki_flags & IOCB_HIPRI)
4296 kiocb->ki_complete = io_complete_rw;
4302 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4304 struct io_rw_state __s, *s = &__s;
4305 struct iovec *iovec;
4306 struct kiocb *kiocb = &req->rw.kiocb;
4307 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4308 struct io_async_rw *rw;
4312 if (!req_has_async_data(req)) {
4313 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4314 if (unlikely(ret < 0))
4318 * Safe and required to re-import if we're using provided
4319 * buffers, as we dropped the selected one before retry.
4321 if (req->flags & REQ_F_BUFFER_SELECT) {
4322 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4323 if (unlikely(ret < 0))
4327 rw = req->async_data;
4330 * We come here from an earlier attempt, restore our state to
4331 * match in case it doesn't. It's cheap enough that we don't
4332 * need to make this conditional.
4334 iov_iter_restore(&s->iter, &s->iter_state);
4337 ret = io_rw_init_file(req, FMODE_READ);
4338 if (unlikely(ret)) {
4342 req->cqe.res = iov_iter_count(&s->iter);
4344 if (force_nonblock) {
4345 /* If the file doesn't support async, just async punt */
4346 if (unlikely(!io_file_supports_nowait(req))) {
4347 ret = io_setup_async_rw(req, iovec, s, true);
4348 return ret ?: -EAGAIN;
4350 kiocb->ki_flags |= IOCB_NOWAIT;
4352 /* Ensure we clear previously set non-block flag */
4353 kiocb->ki_flags &= ~IOCB_NOWAIT;
4356 ppos = io_kiocb_update_pos(req);
4358 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4359 if (unlikely(ret)) {
4364 ret = io_iter_do_read(req, &s->iter);
4366 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4367 req->flags &= ~REQ_F_REISSUE;
4368 /* if we can poll, just do that */
4369 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4371 /* IOPOLL retry should happen for io-wq threads */
4372 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4374 /* no retry on NONBLOCK nor RWF_NOWAIT */
4375 if (req->flags & REQ_F_NOWAIT)
4378 } else if (ret == -EIOCBQUEUED) {
4380 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4381 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4382 /* read all, failed, already did sync or don't want to retry */
4387 * Don't depend on the iter state matching what was consumed, or being
4388 * untouched in case of error. Restore it and we'll advance it
4389 * manually if we need to.
4391 iov_iter_restore(&s->iter, &s->iter_state);
4393 ret2 = io_setup_async_rw(req, iovec, s, true);
4398 rw = req->async_data;
4401 * Now use our persistent iterator and state, if we aren't already.
4402 * We've restored and mapped the iter to match.
4407 * We end up here because of a partial read, either from
4408 * above or inside this loop. Advance the iter by the bytes
4409 * that were consumed.
4411 iov_iter_advance(&s->iter, ret);
4412 if (!iov_iter_count(&s->iter))
4414 rw->bytes_done += ret;
4415 iov_iter_save_state(&s->iter, &s->iter_state);
4417 /* if we can retry, do so with the callbacks armed */
4418 if (!io_rw_should_retry(req)) {
4419 kiocb->ki_flags &= ~IOCB_WAITQ;
4424 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4425 * we get -EIOCBQUEUED, then we'll get a notification when the
4426 * desired page gets unlocked. We can also get a partial read
4427 * here, and if we do, then just retry at the new offset.
4429 ret = io_iter_do_read(req, &s->iter);
4430 if (ret == -EIOCBQUEUED)
4432 /* we got some bytes, but not all. retry. */
4433 kiocb->ki_flags &= ~IOCB_WAITQ;
4434 iov_iter_restore(&s->iter, &s->iter_state);
4437 kiocb_done(req, ret, issue_flags);
4439 /* it's faster to check here then delegate to kfree */
4445 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4447 struct io_rw_state __s, *s = &__s;
4448 struct iovec *iovec;
4449 struct kiocb *kiocb = &req->rw.kiocb;
4450 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4454 if (!req_has_async_data(req)) {
4455 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4456 if (unlikely(ret < 0))
4459 struct io_async_rw *rw = req->async_data;
4462 iov_iter_restore(&s->iter, &s->iter_state);
4465 ret = io_rw_init_file(req, FMODE_WRITE);
4466 if (unlikely(ret)) {
4470 req->cqe.res = iov_iter_count(&s->iter);
4472 if (force_nonblock) {
4473 /* If the file doesn't support async, just async punt */
4474 if (unlikely(!io_file_supports_nowait(req)))
4477 /* file path doesn't support NOWAIT for non-direct_IO */
4478 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4479 (req->flags & REQ_F_ISREG))
4482 kiocb->ki_flags |= IOCB_NOWAIT;
4484 /* Ensure we clear previously set non-block flag */
4485 kiocb->ki_flags &= ~IOCB_NOWAIT;
4488 ppos = io_kiocb_update_pos(req);
4490 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4495 * Open-code file_start_write here to grab freeze protection,
4496 * which will be released by another thread in
4497 * io_complete_rw(). Fool lockdep by telling it the lock got
4498 * released so that it doesn't complain about the held lock when
4499 * we return to userspace.
4501 if (req->flags & REQ_F_ISREG) {
4502 sb_start_write(file_inode(req->file)->i_sb);
4503 __sb_writers_release(file_inode(req->file)->i_sb,
4506 kiocb->ki_flags |= IOCB_WRITE;
4508 if (likely(req->file->f_op->write_iter))
4509 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4510 else if (req->file->f_op->write)
4511 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4515 if (req->flags & REQ_F_REISSUE) {
4516 req->flags &= ~REQ_F_REISSUE;
4521 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4522 * retry them without IOCB_NOWAIT.
4524 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4526 /* no retry on NONBLOCK nor RWF_NOWAIT */
4527 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4529 if (!force_nonblock || ret2 != -EAGAIN) {
4530 /* IOPOLL retry should happen for io-wq threads */
4531 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4534 kiocb_done(req, ret2, issue_flags);
4537 iov_iter_restore(&s->iter, &s->iter_state);
4538 ret = io_setup_async_rw(req, iovec, s, false);
4539 return ret ?: -EAGAIN;
4542 /* it's reportedly faster than delegating the null check to kfree() */
4548 static int io_renameat_prep(struct io_kiocb *req,
4549 const struct io_uring_sqe *sqe)
4551 struct io_rename *ren = &req->rename;
4552 const char __user *oldf, *newf;
4554 if (sqe->buf_index || sqe->splice_fd_in)
4556 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4559 ren->old_dfd = READ_ONCE(sqe->fd);
4560 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4561 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4562 ren->new_dfd = READ_ONCE(sqe->len);
4563 ren->flags = READ_ONCE(sqe->rename_flags);
4565 ren->oldpath = getname(oldf);
4566 if (IS_ERR(ren->oldpath))
4567 return PTR_ERR(ren->oldpath);
4569 ren->newpath = getname(newf);
4570 if (IS_ERR(ren->newpath)) {
4571 putname(ren->oldpath);
4572 return PTR_ERR(ren->newpath);
4575 req->flags |= REQ_F_NEED_CLEANUP;
4579 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4581 struct io_rename *ren = &req->rename;
4584 if (issue_flags & IO_URING_F_NONBLOCK)
4587 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4588 ren->newpath, ren->flags);
4590 req->flags &= ~REQ_F_NEED_CLEANUP;
4591 io_req_complete(req, ret);
4595 static inline void __io_xattr_finish(struct io_kiocb *req)
4597 struct io_xattr *ix = &req->xattr;
4600 putname(ix->filename);
4602 kfree(ix->ctx.kname);
4603 kvfree(ix->ctx.kvalue);
4606 static void io_xattr_finish(struct io_kiocb *req, int ret)
4608 req->flags &= ~REQ_F_NEED_CLEANUP;
4610 __io_xattr_finish(req);
4611 io_req_complete(req, ret);
4614 static int __io_getxattr_prep(struct io_kiocb *req,
4615 const struct io_uring_sqe *sqe)
4617 struct io_xattr *ix = &req->xattr;
4618 const char __user *name;
4621 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4624 ix->filename = NULL;
4625 ix->ctx.kvalue = NULL;
4626 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4627 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4628 ix->ctx.size = READ_ONCE(sqe->len);
4629 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4634 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4638 ret = strncpy_from_user(ix->ctx.kname->name, name,
4639 sizeof(ix->ctx.kname->name));
4640 if (!ret || ret == sizeof(ix->ctx.kname->name))
4643 kfree(ix->ctx.kname);
4647 req->flags |= REQ_F_NEED_CLEANUP;
4651 static int io_fgetxattr_prep(struct io_kiocb *req,
4652 const struct io_uring_sqe *sqe)
4654 return __io_getxattr_prep(req, sqe);
4657 static int io_getxattr_prep(struct io_kiocb *req,
4658 const struct io_uring_sqe *sqe)
4660 struct io_xattr *ix = &req->xattr;
4661 const char __user *path;
4664 ret = __io_getxattr_prep(req, sqe);
4668 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4670 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4671 if (IS_ERR(ix->filename)) {
4672 ret = PTR_ERR(ix->filename);
4673 ix->filename = NULL;
4679 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4681 struct io_xattr *ix = &req->xattr;
4684 if (issue_flags & IO_URING_F_NONBLOCK)
4687 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4688 req->file->f_path.dentry,
4691 io_xattr_finish(req, ret);
4695 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4697 struct io_xattr *ix = &req->xattr;
4698 unsigned int lookup_flags = LOOKUP_FOLLOW;
4702 if (issue_flags & IO_URING_F_NONBLOCK)
4706 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4708 ret = do_getxattr(mnt_user_ns(path.mnt),
4713 if (retry_estale(ret, lookup_flags)) {
4714 lookup_flags |= LOOKUP_REVAL;
4719 io_xattr_finish(req, ret);
4723 static int __io_setxattr_prep(struct io_kiocb *req,
4724 const struct io_uring_sqe *sqe)
4726 struct io_xattr *ix = &req->xattr;
4727 const char __user *name;
4730 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4733 ix->filename = NULL;
4734 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4735 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4736 ix->ctx.kvalue = NULL;
4737 ix->ctx.size = READ_ONCE(sqe->len);
4738 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4740 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4744 ret = setxattr_copy(name, &ix->ctx);
4746 kfree(ix->ctx.kname);
4750 req->flags |= REQ_F_NEED_CLEANUP;
4754 static int io_setxattr_prep(struct io_kiocb *req,
4755 const struct io_uring_sqe *sqe)
4757 struct io_xattr *ix = &req->xattr;
4758 const char __user *path;
4761 ret = __io_setxattr_prep(req, sqe);
4765 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4767 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4768 if (IS_ERR(ix->filename)) {
4769 ret = PTR_ERR(ix->filename);
4770 ix->filename = NULL;
4776 static int io_fsetxattr_prep(struct io_kiocb *req,
4777 const struct io_uring_sqe *sqe)
4779 return __io_setxattr_prep(req, sqe);
4782 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4785 struct io_xattr *ix = &req->xattr;
4788 ret = mnt_want_write(path->mnt);
4790 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4791 mnt_drop_write(path->mnt);
4797 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4801 if (issue_flags & IO_URING_F_NONBLOCK)
4804 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4805 io_xattr_finish(req, ret);
4810 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4812 struct io_xattr *ix = &req->xattr;
4813 unsigned int lookup_flags = LOOKUP_FOLLOW;
4817 if (issue_flags & IO_URING_F_NONBLOCK)
4821 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4823 ret = __io_setxattr(req, issue_flags, &path);
4825 if (retry_estale(ret, lookup_flags)) {
4826 lookup_flags |= LOOKUP_REVAL;
4831 io_xattr_finish(req, ret);
4835 static int io_unlinkat_prep(struct io_kiocb *req,
4836 const struct io_uring_sqe *sqe)
4838 struct io_unlink *un = &req->unlink;
4839 const char __user *fname;
4841 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4843 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4846 un->dfd = READ_ONCE(sqe->fd);
4848 un->flags = READ_ONCE(sqe->unlink_flags);
4849 if (un->flags & ~AT_REMOVEDIR)
4852 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4853 un->filename = getname(fname);
4854 if (IS_ERR(un->filename))
4855 return PTR_ERR(un->filename);
4857 req->flags |= REQ_F_NEED_CLEANUP;
4861 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4863 struct io_unlink *un = &req->unlink;
4866 if (issue_flags & IO_URING_F_NONBLOCK)
4869 if (un->flags & AT_REMOVEDIR)
4870 ret = do_rmdir(un->dfd, un->filename);
4872 ret = do_unlinkat(un->dfd, un->filename);
4874 req->flags &= ~REQ_F_NEED_CLEANUP;
4875 io_req_complete(req, ret);
4879 static int io_mkdirat_prep(struct io_kiocb *req,
4880 const struct io_uring_sqe *sqe)
4882 struct io_mkdir *mkd = &req->mkdir;
4883 const char __user *fname;
4885 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4887 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4890 mkd->dfd = READ_ONCE(sqe->fd);
4891 mkd->mode = READ_ONCE(sqe->len);
4893 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4894 mkd->filename = getname(fname);
4895 if (IS_ERR(mkd->filename))
4896 return PTR_ERR(mkd->filename);
4898 req->flags |= REQ_F_NEED_CLEANUP;
4902 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4904 struct io_mkdir *mkd = &req->mkdir;
4907 if (issue_flags & IO_URING_F_NONBLOCK)
4910 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4912 req->flags &= ~REQ_F_NEED_CLEANUP;
4913 io_req_complete(req, ret);
4917 static int io_symlinkat_prep(struct io_kiocb *req,
4918 const struct io_uring_sqe *sqe)
4920 struct io_symlink *sl = &req->symlink;
4921 const char __user *oldpath, *newpath;
4923 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4925 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4928 sl->new_dfd = READ_ONCE(sqe->fd);
4929 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4930 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4932 sl->oldpath = getname(oldpath);
4933 if (IS_ERR(sl->oldpath))
4934 return PTR_ERR(sl->oldpath);
4936 sl->newpath = getname(newpath);
4937 if (IS_ERR(sl->newpath)) {
4938 putname(sl->oldpath);
4939 return PTR_ERR(sl->newpath);
4942 req->flags |= REQ_F_NEED_CLEANUP;
4946 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4948 struct io_symlink *sl = &req->symlink;
4951 if (issue_flags & IO_URING_F_NONBLOCK)
4954 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4956 req->flags &= ~REQ_F_NEED_CLEANUP;
4957 io_req_complete(req, ret);
4961 static int io_linkat_prep(struct io_kiocb *req,
4962 const struct io_uring_sqe *sqe)
4964 struct io_hardlink *lnk = &req->hardlink;
4965 const char __user *oldf, *newf;
4967 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4969 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4972 lnk->old_dfd = READ_ONCE(sqe->fd);
4973 lnk->new_dfd = READ_ONCE(sqe->len);
4974 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4975 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4976 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4978 lnk->oldpath = getname(oldf);
4979 if (IS_ERR(lnk->oldpath))
4980 return PTR_ERR(lnk->oldpath);
4982 lnk->newpath = getname(newf);
4983 if (IS_ERR(lnk->newpath)) {
4984 putname(lnk->oldpath);
4985 return PTR_ERR(lnk->newpath);
4988 req->flags |= REQ_F_NEED_CLEANUP;
4992 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4994 struct io_hardlink *lnk = &req->hardlink;
4997 if (issue_flags & IO_URING_F_NONBLOCK)
5000 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
5001 lnk->newpath, lnk->flags);
5003 req->flags &= ~REQ_F_NEED_CLEANUP;
5004 io_req_complete(req, ret);
5008 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
5010 req->uring_cmd.task_work_cb(&req->uring_cmd);
5013 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
5014 void (*task_work_cb)(struct io_uring_cmd *))
5016 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5018 req->uring_cmd.task_work_cb = task_work_cb;
5019 req->io_task_work.func = io_uring_cmd_work;
5020 io_req_task_work_add(req);
5022 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
5024 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
5025 u64 extra1, u64 extra2)
5027 req->extra1 = extra1;
5028 req->extra2 = extra2;
5029 req->flags |= REQ_F_CQE32_INIT;
5033 * Called by consumers of io_uring_cmd, if they originally returned
5034 * -EIOCBQUEUED upon receiving the command.
5036 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
5038 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5043 if (req->ctx->flags & IORING_SETUP_CQE32)
5044 io_req_set_cqe32_extra(req, res2, 0);
5045 io_req_complete(req, ret);
5047 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
5049 static int io_uring_cmd_prep_async(struct io_kiocb *req)
5053 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
5055 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
5059 static int io_uring_cmd_prep(struct io_kiocb *req,
5060 const struct io_uring_sqe *sqe)
5062 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5066 ioucmd->cmd = sqe->cmd;
5067 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
5071 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
5073 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5074 struct io_ring_ctx *ctx = req->ctx;
5075 struct file *file = req->file;
5078 if (!req->file->f_op->uring_cmd)
5081 if (ctx->flags & IORING_SETUP_SQE128)
5082 issue_flags |= IO_URING_F_SQE128;
5083 if (ctx->flags & IORING_SETUP_CQE32)
5084 issue_flags |= IO_URING_F_CQE32;
5085 if (ctx->flags & IORING_SETUP_IOPOLL)
5086 issue_flags |= IO_URING_F_IOPOLL;
5088 if (req_has_async_data(req))
5089 ioucmd->cmd = req->async_data;
5091 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
5092 if (ret == -EAGAIN) {
5093 if (!req_has_async_data(req)) {
5094 if (io_alloc_async_data(req))
5096 io_uring_cmd_prep_async(req);
5101 if (ret != -EIOCBQUEUED)
5102 io_uring_cmd_done(ioucmd, ret, 0);
5106 static int __io_splice_prep(struct io_kiocb *req,
5107 const struct io_uring_sqe *sqe)
5109 struct io_splice *sp = &req->splice;
5110 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
5112 sp->len = READ_ONCE(sqe->len);
5113 sp->flags = READ_ONCE(sqe->splice_flags);
5114 if (unlikely(sp->flags & ~valid_flags))
5116 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
5120 static int io_tee_prep(struct io_kiocb *req,
5121 const struct io_uring_sqe *sqe)
5123 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
5125 return __io_splice_prep(req, sqe);
5128 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
5130 struct io_splice *sp = &req->splice;
5131 struct file *out = sp->file_out;
5132 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5136 if (issue_flags & IO_URING_F_NONBLOCK)
5139 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5140 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5142 in = io_file_get_normal(req, sp->splice_fd_in);
5149 ret = do_tee(in, out, sp->len, flags);
5151 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5156 __io_req_complete(req, 0, ret, 0);
5160 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5162 struct io_splice *sp = &req->splice;
5164 sp->off_in = READ_ONCE(sqe->splice_off_in);
5165 sp->off_out = READ_ONCE(sqe->off);
5166 return __io_splice_prep(req, sqe);
5169 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5171 struct io_splice *sp = &req->splice;
5172 struct file *out = sp->file_out;
5173 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5174 loff_t *poff_in, *poff_out;
5178 if (issue_flags & IO_URING_F_NONBLOCK)
5181 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5182 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5184 in = io_file_get_normal(req, sp->splice_fd_in);
5190 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5191 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5194 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5196 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5201 __io_req_complete(req, 0, ret, 0);
5205 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5211 * IORING_OP_NOP just posts a completion event, nothing else.
5213 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5215 __io_req_complete(req, issue_flags, 0, 0);
5219 static int io_msg_ring_prep(struct io_kiocb *req,
5220 const struct io_uring_sqe *sqe)
5222 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5223 sqe->buf_index || sqe->personality))
5226 req->msg.user_data = READ_ONCE(sqe->off);
5227 req->msg.len = READ_ONCE(sqe->len);
5231 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5233 struct io_ring_ctx *target_ctx;
5234 struct io_msg *msg = &req->msg;
5239 if (req->file->f_op != &io_uring_fops)
5243 target_ctx = req->file->private_data;
5245 spin_lock(&target_ctx->completion_lock);
5246 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5247 io_commit_cqring(target_ctx);
5248 spin_unlock(&target_ctx->completion_lock);
5251 io_cqring_ev_posted(target_ctx);
5258 __io_req_complete(req, issue_flags, ret, 0);
5259 /* put file to avoid an attempt to IOPOLL the req */
5260 io_put_file(req->file);
5265 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5267 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5270 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5271 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5274 req->sync.off = READ_ONCE(sqe->off);
5275 req->sync.len = READ_ONCE(sqe->len);
5279 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5281 loff_t end = req->sync.off + req->sync.len;
5284 /* fsync always requires a blocking context */
5285 if (issue_flags & IO_URING_F_NONBLOCK)
5288 ret = vfs_fsync_range(req->file, req->sync.off,
5289 end > 0 ? end : LLONG_MAX,
5290 req->sync.flags & IORING_FSYNC_DATASYNC);
5291 io_req_complete(req, ret);
5295 static int io_fallocate_prep(struct io_kiocb *req,
5296 const struct io_uring_sqe *sqe)
5298 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5301 req->sync.off = READ_ONCE(sqe->off);
5302 req->sync.len = READ_ONCE(sqe->addr);
5303 req->sync.mode = READ_ONCE(sqe->len);
5307 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5311 /* fallocate always requiring blocking context */
5312 if (issue_flags & IO_URING_F_NONBLOCK)
5314 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5317 fsnotify_modify(req->file);
5318 io_req_complete(req, ret);
5322 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5324 const char __user *fname;
5327 if (unlikely(sqe->buf_index))
5329 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5332 /* open.how should be already initialised */
5333 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5334 req->open.how.flags |= O_LARGEFILE;
5336 req->open.dfd = READ_ONCE(sqe->fd);
5337 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5338 req->open.filename = getname(fname);
5339 if (IS_ERR(req->open.filename)) {
5340 ret = PTR_ERR(req->open.filename);
5341 req->open.filename = NULL;
5345 req->open.file_slot = READ_ONCE(sqe->file_index);
5346 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5349 req->open.nofile = rlimit(RLIMIT_NOFILE);
5350 req->flags |= REQ_F_NEED_CLEANUP;
5354 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5356 u64 mode = READ_ONCE(sqe->len);
5357 u64 flags = READ_ONCE(sqe->open_flags);
5359 req->open.how = build_open_how(flags, mode);
5360 return __io_openat_prep(req, sqe);
5363 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5365 struct open_how __user *how;
5369 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5370 len = READ_ONCE(sqe->len);
5371 if (len < OPEN_HOW_SIZE_VER0)
5374 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5379 return __io_openat_prep(req, sqe);
5382 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5384 struct io_file_table *table = &ctx->file_table;
5385 unsigned long nr = ctx->nr_user_files;
5389 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5393 if (!table->alloc_hint)
5396 nr = table->alloc_hint;
5397 table->alloc_hint = 0;
5404 * Note when io_fixed_fd_install() returns error value, it will ensure
5405 * fput() is called correspondingly.
5407 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5408 struct file *file, unsigned int file_slot)
5410 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5411 struct io_ring_ctx *ctx = req->ctx;
5414 io_ring_submit_lock(ctx, issue_flags);
5417 ret = io_file_bitmap_get(ctx);
5418 if (unlikely(ret < 0))
5425 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5426 if (!ret && alloc_slot)
5429 io_ring_submit_unlock(ctx, issue_flags);
5430 if (unlikely(ret < 0))
5435 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5437 struct open_flags op;
5439 bool resolve_nonblock, nonblock_set;
5440 bool fixed = !!req->open.file_slot;
5443 ret = build_open_flags(&req->open.how, &op);
5446 nonblock_set = op.open_flag & O_NONBLOCK;
5447 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5448 if (issue_flags & IO_URING_F_NONBLOCK) {
5450 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5451 * it'll always -EAGAIN
5453 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5455 op.lookup_flags |= LOOKUP_CACHED;
5456 op.open_flag |= O_NONBLOCK;
5460 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5465 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5468 * We could hang on to this 'fd' on retrying, but seems like
5469 * marginal gain for something that is now known to be a slower
5470 * path. So just put it, and we'll get a new one when we retry.
5475 ret = PTR_ERR(file);
5476 /* only retry if RESOLVE_CACHED wasn't already set by application */
5477 if (ret == -EAGAIN &&
5478 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5483 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5484 file->f_flags &= ~O_NONBLOCK;
5485 fsnotify_open(file);
5488 fd_install(ret, file);
5490 ret = io_fixed_fd_install(req, issue_flags, file,
5491 req->open.file_slot);
5493 putname(req->open.filename);
5494 req->flags &= ~REQ_F_NEED_CLEANUP;
5497 __io_req_complete(req, issue_flags, ret, 0);
5501 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5503 return io_openat2(req, issue_flags);
5506 static int io_remove_buffers_prep(struct io_kiocb *req,
5507 const struct io_uring_sqe *sqe)
5509 struct io_provide_buf *p = &req->pbuf;
5512 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5516 tmp = READ_ONCE(sqe->fd);
5517 if (!tmp || tmp > USHRT_MAX)
5520 memset(p, 0, sizeof(*p));
5522 p->bgid = READ_ONCE(sqe->buf_group);
5526 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5527 struct io_buffer_list *bl, unsigned nbufs)
5531 /* shouldn't happen */
5535 if (bl->buf_nr_pages) {
5538 i = bl->buf_ring->tail - bl->head;
5539 for (j = 0; j < bl->buf_nr_pages; j++)
5540 unpin_user_page(bl->buf_pages[j]);
5541 kvfree(bl->buf_pages);
5542 bl->buf_pages = NULL;
5543 bl->buf_nr_pages = 0;
5544 /* make sure it's seen as empty */
5545 INIT_LIST_HEAD(&bl->buf_list);
5549 /* the head kbuf is the list itself */
5550 while (!list_empty(&bl->buf_list)) {
5551 struct io_buffer *nxt;
5553 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5554 list_del(&nxt->list);
5564 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5566 struct io_provide_buf *p = &req->pbuf;
5567 struct io_ring_ctx *ctx = req->ctx;
5568 struct io_buffer_list *bl;
5571 io_ring_submit_lock(ctx, issue_flags);
5574 bl = io_buffer_get_list(ctx, p->bgid);
5577 /* can't use provide/remove buffers command on mapped buffers */
5578 if (!bl->buf_nr_pages)
5579 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5584 /* complete before unlock, IOPOLL may need the lock */
5585 __io_req_complete(req, issue_flags, ret, 0);
5586 io_ring_submit_unlock(ctx, issue_flags);
5590 static int io_provide_buffers_prep(struct io_kiocb *req,
5591 const struct io_uring_sqe *sqe)
5593 unsigned long size, tmp_check;
5594 struct io_provide_buf *p = &req->pbuf;
5597 if (sqe->rw_flags || sqe->splice_fd_in)
5600 tmp = READ_ONCE(sqe->fd);
5601 if (!tmp || tmp > USHRT_MAX)
5604 p->addr = READ_ONCE(sqe->addr);
5605 p->len = READ_ONCE(sqe->len);
5607 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5610 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5613 size = (unsigned long)p->len * p->nbufs;
5614 if (!access_ok(u64_to_user_ptr(p->addr), size))
5617 p->bgid = READ_ONCE(sqe->buf_group);
5618 tmp = READ_ONCE(sqe->off);
5619 if (tmp > USHRT_MAX)
5625 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5627 struct io_buffer *buf;
5632 * Completions that don't happen inline (eg not under uring_lock) will
5633 * add to ->io_buffers_comp. If we don't have any free buffers, check
5634 * the completion list and splice those entries first.
5636 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5637 spin_lock(&ctx->completion_lock);
5638 if (!list_empty(&ctx->io_buffers_comp)) {
5639 list_splice_init(&ctx->io_buffers_comp,
5640 &ctx->io_buffers_cache);
5641 spin_unlock(&ctx->completion_lock);
5644 spin_unlock(&ctx->completion_lock);
5648 * No free buffers and no completion entries either. Allocate a new
5649 * page worth of buffer entries and add those to our freelist.
5651 page = alloc_page(GFP_KERNEL_ACCOUNT);
5655 list_add(&page->lru, &ctx->io_buffers_pages);
5657 buf = page_address(page);
5658 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5659 while (bufs_in_page) {
5660 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5668 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5669 struct io_buffer_list *bl)
5671 struct io_buffer *buf;
5672 u64 addr = pbuf->addr;
5673 int i, bid = pbuf->bid;
5675 for (i = 0; i < pbuf->nbufs; i++) {
5676 if (list_empty(&ctx->io_buffers_cache) &&
5677 io_refill_buffer_cache(ctx))
5679 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5681 list_move_tail(&buf->list, &bl->buf_list);
5683 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5685 buf->bgid = pbuf->bgid;
5691 return i ? 0 : -ENOMEM;
5694 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5698 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5703 for (i = 0; i < BGID_ARRAY; i++) {
5704 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5705 ctx->io_bl[i].bgid = i;
5711 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5713 struct io_provide_buf *p = &req->pbuf;
5714 struct io_ring_ctx *ctx = req->ctx;
5715 struct io_buffer_list *bl;
5718 io_ring_submit_lock(ctx, issue_flags);
5720 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5721 ret = io_init_bl_list(ctx);
5726 bl = io_buffer_get_list(ctx, p->bgid);
5727 if (unlikely(!bl)) {
5728 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5733 INIT_LIST_HEAD(&bl->buf_list);
5734 ret = io_buffer_add_list(ctx, bl, p->bgid);
5740 /* can't add buffers via this command for a mapped buffer ring */
5741 if (bl->buf_nr_pages) {
5746 ret = io_add_buffers(ctx, p, bl);
5750 /* complete before unlock, IOPOLL may need the lock */
5751 __io_req_complete(req, issue_flags, ret, 0);
5752 io_ring_submit_unlock(ctx, issue_flags);
5756 static int io_epoll_ctl_prep(struct io_kiocb *req,
5757 const struct io_uring_sqe *sqe)
5759 #if defined(CONFIG_EPOLL)
5760 if (sqe->buf_index || sqe->splice_fd_in)
5763 req->epoll.epfd = READ_ONCE(sqe->fd);
5764 req->epoll.op = READ_ONCE(sqe->len);
5765 req->epoll.fd = READ_ONCE(sqe->off);
5767 if (ep_op_has_event(req->epoll.op)) {
5768 struct epoll_event __user *ev;
5770 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5771 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5781 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5783 #if defined(CONFIG_EPOLL)
5784 struct io_epoll *ie = &req->epoll;
5786 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5788 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5789 if (force_nonblock && ret == -EAGAIN)
5794 __io_req_complete(req, issue_flags, ret, 0);
5801 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5803 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5804 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5807 req->madvise.addr = READ_ONCE(sqe->addr);
5808 req->madvise.len = READ_ONCE(sqe->len);
5809 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5816 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5818 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5819 struct io_madvise *ma = &req->madvise;
5822 if (issue_flags & IO_URING_F_NONBLOCK)
5825 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5826 io_req_complete(req, ret);
5833 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5835 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5838 req->fadvise.offset = READ_ONCE(sqe->off);
5839 req->fadvise.len = READ_ONCE(sqe->len);
5840 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5844 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5846 struct io_fadvise *fa = &req->fadvise;
5849 if (issue_flags & IO_URING_F_NONBLOCK) {
5850 switch (fa->advice) {
5851 case POSIX_FADV_NORMAL:
5852 case POSIX_FADV_RANDOM:
5853 case POSIX_FADV_SEQUENTIAL:
5860 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5863 __io_req_complete(req, issue_flags, ret, 0);
5867 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5869 const char __user *path;
5871 if (sqe->buf_index || sqe->splice_fd_in)
5873 if (req->flags & REQ_F_FIXED_FILE)
5876 req->statx.dfd = READ_ONCE(sqe->fd);
5877 req->statx.mask = READ_ONCE(sqe->len);
5878 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5879 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5880 req->statx.flags = READ_ONCE(sqe->statx_flags);
5882 req->statx.filename = getname_flags(path,
5883 getname_statx_lookup_flags(req->statx.flags),
5886 if (IS_ERR(req->statx.filename)) {
5887 int ret = PTR_ERR(req->statx.filename);
5889 req->statx.filename = NULL;
5893 req->flags |= REQ_F_NEED_CLEANUP;
5897 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5899 struct io_statx *ctx = &req->statx;
5902 if (issue_flags & IO_URING_F_NONBLOCK)
5905 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5907 io_req_complete(req, ret);
5911 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5913 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5915 if (req->flags & REQ_F_FIXED_FILE)
5918 req->close.fd = READ_ONCE(sqe->fd);
5919 req->close.file_slot = READ_ONCE(sqe->file_index);
5920 if (req->close.file_slot && req->close.fd)
5926 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5928 struct files_struct *files = current->files;
5929 struct io_close *close = &req->close;
5930 struct fdtable *fdt;
5934 if (req->close.file_slot) {
5935 ret = io_close_fixed(req, issue_flags);
5939 spin_lock(&files->file_lock);
5940 fdt = files_fdtable(files);
5941 if (close->fd >= fdt->max_fds) {
5942 spin_unlock(&files->file_lock);
5945 file = rcu_dereference_protected(fdt->fd[close->fd],
5946 lockdep_is_held(&files->file_lock));
5947 if (!file || file->f_op == &io_uring_fops) {
5948 spin_unlock(&files->file_lock);
5952 /* if the file has a flush method, be safe and punt to async */
5953 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5954 spin_unlock(&files->file_lock);
5958 file = __close_fd_get_file(close->fd);
5959 spin_unlock(&files->file_lock);
5963 /* No ->flush() or already async, safely close from here */
5964 ret = filp_close(file, current->files);
5968 __io_req_complete(req, issue_flags, ret, 0);
5972 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5974 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5977 req->sync.off = READ_ONCE(sqe->off);
5978 req->sync.len = READ_ONCE(sqe->len);
5979 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5983 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5987 /* sync_file_range always requires a blocking context */
5988 if (issue_flags & IO_URING_F_NONBLOCK)
5991 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5993 io_req_complete(req, ret);
5997 #if defined(CONFIG_NET)
5998 static int io_shutdown_prep(struct io_kiocb *req,
5999 const struct io_uring_sqe *sqe)
6001 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
6002 sqe->buf_index || sqe->splice_fd_in))
6005 req->shutdown.how = READ_ONCE(sqe->len);
6009 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
6011 struct socket *sock;
6014 if (issue_flags & IO_URING_F_NONBLOCK)
6017 sock = sock_from_file(req->file);
6018 if (unlikely(!sock))
6021 ret = __sys_shutdown_sock(sock, req->shutdown.how);
6022 io_req_complete(req, ret);
6026 static bool io_net_retry(struct socket *sock, int flags)
6028 if (!(flags & MSG_WAITALL))
6030 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
6033 static int io_setup_async_msg(struct io_kiocb *req,
6034 struct io_async_msghdr *kmsg)
6036 struct io_async_msghdr *async_msg = req->async_data;
6040 if (io_alloc_async_data(req)) {
6041 kfree(kmsg->free_iov);
6044 async_msg = req->async_data;
6045 req->flags |= REQ_F_NEED_CLEANUP;
6046 memcpy(async_msg, kmsg, sizeof(*kmsg));
6047 async_msg->msg.msg_name = &async_msg->addr;
6048 /* if were using fast_iov, set it to the new one */
6049 if (!async_msg->free_iov)
6050 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
6055 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
6056 struct io_async_msghdr *iomsg)
6058 iomsg->msg.msg_name = &iomsg->addr;
6059 iomsg->free_iov = iomsg->fast_iov;
6060 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
6061 req->sr_msg.msg_flags, &iomsg->free_iov);
6064 static int io_sendmsg_prep_async(struct io_kiocb *req)
6068 ret = io_sendmsg_copy_hdr(req, req->async_data);
6070 req->flags |= REQ_F_NEED_CLEANUP;
6074 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6076 struct io_sr_msg *sr = &req->sr_msg;
6078 if (unlikely(sqe->file_index))
6081 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6082 sr->len = READ_ONCE(sqe->len);
6083 sr->flags = READ_ONCE(sqe->addr2);
6084 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6086 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6087 if (sr->msg_flags & MSG_DONTWAIT)
6088 req->flags |= REQ_F_NOWAIT;
6090 #ifdef CONFIG_COMPAT
6091 if (req->ctx->compat)
6092 sr->msg_flags |= MSG_CMSG_COMPAT;
6098 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
6100 struct io_async_msghdr iomsg, *kmsg;
6101 struct io_sr_msg *sr = &req->sr_msg;
6102 struct socket *sock;
6107 sock = sock_from_file(req->file);
6108 if (unlikely(!sock))
6111 if (req_has_async_data(req)) {
6112 kmsg = req->async_data;
6114 ret = io_sendmsg_copy_hdr(req, &iomsg);
6120 if (!(req->flags & REQ_F_POLLED) &&
6121 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6122 return io_setup_async_msg(req, kmsg);
6124 flags = sr->msg_flags;
6125 if (issue_flags & IO_URING_F_NONBLOCK)
6126 flags |= MSG_DONTWAIT;
6127 if (flags & MSG_WAITALL)
6128 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6130 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
6132 if (ret < min_ret) {
6133 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6134 return io_setup_async_msg(req, kmsg);
6135 if (ret == -ERESTARTSYS)
6137 if (ret > 0 && io_net_retry(sock, flags)) {
6139 req->flags |= REQ_F_PARTIAL_IO;
6140 return io_setup_async_msg(req, kmsg);
6144 /* fast path, check for non-NULL to avoid function call */
6146 kfree(kmsg->free_iov);
6147 req->flags &= ~REQ_F_NEED_CLEANUP;
6150 else if (sr->done_io)
6152 __io_req_complete(req, issue_flags, ret, 0);
6156 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6158 struct io_sr_msg *sr = &req->sr_msg;
6161 struct socket *sock;
6166 if (!(req->flags & REQ_F_POLLED) &&
6167 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6170 sock = sock_from_file(req->file);
6171 if (unlikely(!sock))
6174 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6178 msg.msg_name = NULL;
6179 msg.msg_control = NULL;
6180 msg.msg_controllen = 0;
6181 msg.msg_namelen = 0;
6183 flags = sr->msg_flags;
6184 if (issue_flags & IO_URING_F_NONBLOCK)
6185 flags |= MSG_DONTWAIT;
6186 if (flags & MSG_WAITALL)
6187 min_ret = iov_iter_count(&msg.msg_iter);
6189 msg.msg_flags = flags;
6190 ret = sock_sendmsg(sock, &msg);
6191 if (ret < min_ret) {
6192 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6194 if (ret == -ERESTARTSYS)
6196 if (ret > 0 && io_net_retry(sock, flags)) {
6200 req->flags |= REQ_F_PARTIAL_IO;
6207 else if (sr->done_io)
6209 __io_req_complete(req, issue_flags, ret, 0);
6213 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6214 struct io_async_msghdr *iomsg)
6216 struct io_sr_msg *sr = &req->sr_msg;
6217 struct iovec __user *uiov;
6221 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6222 &iomsg->uaddr, &uiov, &iov_len);
6226 if (req->flags & REQ_F_BUFFER_SELECT) {
6229 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6231 sr->len = iomsg->fast_iov[0].iov_len;
6232 iomsg->free_iov = NULL;
6234 iomsg->free_iov = iomsg->fast_iov;
6235 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6236 &iomsg->free_iov, &iomsg->msg.msg_iter,
6245 #ifdef CONFIG_COMPAT
6246 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6247 struct io_async_msghdr *iomsg)
6249 struct io_sr_msg *sr = &req->sr_msg;
6250 struct compat_iovec __user *uiov;
6255 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6260 uiov = compat_ptr(ptr);
6261 if (req->flags & REQ_F_BUFFER_SELECT) {
6262 compat_ssize_t clen;
6266 if (!access_ok(uiov, sizeof(*uiov)))
6268 if (__get_user(clen, &uiov->iov_len))
6273 iomsg->free_iov = NULL;
6275 iomsg->free_iov = iomsg->fast_iov;
6276 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6277 UIO_FASTIOV, &iomsg->free_iov,
6278 &iomsg->msg.msg_iter, true);
6287 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6288 struct io_async_msghdr *iomsg)
6290 iomsg->msg.msg_name = &iomsg->addr;
6292 #ifdef CONFIG_COMPAT
6293 if (req->ctx->compat)
6294 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6297 return __io_recvmsg_copy_hdr(req, iomsg);
6300 static int io_recvmsg_prep_async(struct io_kiocb *req)
6304 ret = io_recvmsg_copy_hdr(req, req->async_data);
6306 req->flags |= REQ_F_NEED_CLEANUP;
6310 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6312 struct io_sr_msg *sr = &req->sr_msg;
6314 if (unlikely(sqe->file_index))
6317 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6318 sr->len = READ_ONCE(sqe->len);
6319 sr->flags = READ_ONCE(sqe->addr2);
6320 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6322 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6323 if (sr->msg_flags & MSG_DONTWAIT)
6324 req->flags |= REQ_F_NOWAIT;
6326 #ifdef CONFIG_COMPAT
6327 if (req->ctx->compat)
6328 sr->msg_flags |= MSG_CMSG_COMPAT;
6334 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6336 struct io_async_msghdr iomsg, *kmsg;
6337 struct io_sr_msg *sr = &req->sr_msg;
6338 struct socket *sock;
6339 unsigned int cflags;
6341 int ret, min_ret = 0;
6342 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6344 sock = sock_from_file(req->file);
6345 if (unlikely(!sock))
6348 if (req_has_async_data(req)) {
6349 kmsg = req->async_data;
6351 ret = io_recvmsg_copy_hdr(req, &iomsg);
6357 if (!(req->flags & REQ_F_POLLED) &&
6358 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6359 return io_setup_async_msg(req, kmsg);
6361 if (io_do_buffer_select(req)) {
6364 buf = io_buffer_select(req, &sr->len, issue_flags);
6367 kmsg->fast_iov[0].iov_base = buf;
6368 kmsg->fast_iov[0].iov_len = sr->len;
6369 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6373 flags = sr->msg_flags;
6375 flags |= MSG_DONTWAIT;
6376 if (flags & MSG_WAITALL)
6377 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6379 kmsg->msg.msg_get_inq = 1;
6380 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6381 if (ret < min_ret) {
6382 if (ret == -EAGAIN && force_nonblock)
6383 return io_setup_async_msg(req, kmsg);
6384 if (ret == -ERESTARTSYS)
6386 if (ret > 0 && io_net_retry(sock, flags)) {
6388 req->flags |= REQ_F_PARTIAL_IO;
6389 return io_setup_async_msg(req, kmsg);
6392 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6396 /* fast path, check for non-NULL to avoid function call */
6398 kfree(kmsg->free_iov);
6399 req->flags &= ~REQ_F_NEED_CLEANUP;
6402 else if (sr->done_io)
6404 cflags = io_put_kbuf(req, issue_flags);
6405 if (kmsg->msg.msg_inq)
6406 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6407 __io_req_complete(req, issue_flags, ret, cflags);
6411 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6413 struct io_sr_msg *sr = &req->sr_msg;
6415 struct socket *sock;
6417 unsigned int cflags;
6419 int ret, min_ret = 0;
6420 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6422 if (!(req->flags & REQ_F_POLLED) &&
6423 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6426 sock = sock_from_file(req->file);
6427 if (unlikely(!sock))
6430 if (io_do_buffer_select(req)) {
6433 buf = io_buffer_select(req, &sr->len, issue_flags);
6439 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6443 msg.msg_name = NULL;
6444 msg.msg_namelen = 0;
6445 msg.msg_control = NULL;
6446 msg.msg_get_inq = 1;
6448 msg.msg_controllen = 0;
6449 msg.msg_iocb = NULL;
6451 flags = sr->msg_flags;
6453 flags |= MSG_DONTWAIT;
6454 if (flags & MSG_WAITALL)
6455 min_ret = iov_iter_count(&msg.msg_iter);
6457 ret = sock_recvmsg(sock, &msg, flags);
6458 if (ret < min_ret) {
6459 if (ret == -EAGAIN && force_nonblock)
6461 if (ret == -ERESTARTSYS)
6463 if (ret > 0 && io_net_retry(sock, flags)) {
6467 req->flags |= REQ_F_PARTIAL_IO;
6471 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6478 else if (sr->done_io)
6480 cflags = io_put_kbuf(req, issue_flags);
6482 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6483 __io_req_complete(req, issue_flags, ret, cflags);
6487 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6489 struct io_accept *accept = &req->accept;
6492 if (sqe->len || sqe->buf_index)
6495 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6496 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6497 accept->flags = READ_ONCE(sqe->accept_flags);
6498 accept->nofile = rlimit(RLIMIT_NOFILE);
6499 flags = READ_ONCE(sqe->ioprio);
6500 if (flags & ~IORING_ACCEPT_MULTISHOT)
6503 accept->file_slot = READ_ONCE(sqe->file_index);
6504 if (accept->file_slot) {
6505 if (accept->flags & SOCK_CLOEXEC)
6507 if (flags & IORING_ACCEPT_MULTISHOT &&
6508 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6511 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6513 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6514 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6515 if (flags & IORING_ACCEPT_MULTISHOT)
6516 req->flags |= REQ_F_APOLL_MULTISHOT;
6520 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6522 struct io_ring_ctx *ctx = req->ctx;
6523 struct io_accept *accept = &req->accept;
6524 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6525 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6526 bool fixed = !!accept->file_slot;
6532 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6533 if (unlikely(fd < 0))
6536 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6541 ret = PTR_ERR(file);
6542 if (ret == -EAGAIN && force_nonblock) {
6544 * if it's multishot and polled, we don't need to
6545 * return EAGAIN to arm the poll infra since it
6546 * has already been done
6548 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6549 IO_APOLL_MULTI_POLLED)
6553 if (ret == -ERESTARTSYS)
6556 } else if (!fixed) {
6557 fd_install(fd, file);
6560 ret = io_fixed_fd_install(req, issue_flags, file,
6564 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6565 __io_req_complete(req, issue_flags, ret, 0);
6571 spin_lock(&ctx->completion_lock);
6572 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6574 io_commit_cqring(ctx);
6575 spin_unlock(&ctx->completion_lock);
6577 io_cqring_ev_posted(ctx);
6586 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6588 struct io_socket *sock = &req->sock;
6590 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6593 sock->domain = READ_ONCE(sqe->fd);
6594 sock->type = READ_ONCE(sqe->off);
6595 sock->protocol = READ_ONCE(sqe->len);
6596 sock->file_slot = READ_ONCE(sqe->file_index);
6597 sock->nofile = rlimit(RLIMIT_NOFILE);
6599 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6600 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6602 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6607 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6609 struct io_socket *sock = &req->sock;
6610 bool fixed = !!sock->file_slot;
6615 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6616 if (unlikely(fd < 0))
6619 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6623 ret = PTR_ERR(file);
6624 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6626 if (ret == -ERESTARTSYS)
6629 } else if (!fixed) {
6630 fd_install(fd, file);
6633 ret = io_fixed_fd_install(req, issue_flags, file,
6636 __io_req_complete(req, issue_flags, ret, 0);
6640 static int io_connect_prep_async(struct io_kiocb *req)
6642 struct io_async_connect *io = req->async_data;
6643 struct io_connect *conn = &req->connect;
6645 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6648 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6650 struct io_connect *conn = &req->connect;
6652 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6655 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6656 conn->addr_len = READ_ONCE(sqe->addr2);
6660 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6662 struct io_async_connect __io, *io;
6663 unsigned file_flags;
6665 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6667 if (req_has_async_data(req)) {
6668 io = req->async_data;
6670 ret = move_addr_to_kernel(req->connect.addr,
6671 req->connect.addr_len,
6678 file_flags = force_nonblock ? O_NONBLOCK : 0;
6680 ret = __sys_connect_file(req->file, &io->address,
6681 req->connect.addr_len, file_flags);
6682 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6683 if (req_has_async_data(req))
6685 if (io_alloc_async_data(req)) {
6689 memcpy(req->async_data, &__io, sizeof(__io));
6692 if (ret == -ERESTARTSYS)
6697 __io_req_complete(req, issue_flags, ret, 0);
6700 #else /* !CONFIG_NET */
6701 #define IO_NETOP_FN(op) \
6702 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6704 return -EOPNOTSUPP; \
6707 #define IO_NETOP_PREP(op) \
6709 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6711 return -EOPNOTSUPP; \
6714 #define IO_NETOP_PREP_ASYNC(op) \
6716 static int io_##op##_prep_async(struct io_kiocb *req) \
6718 return -EOPNOTSUPP; \
6721 IO_NETOP_PREP_ASYNC(sendmsg);
6722 IO_NETOP_PREP_ASYNC(recvmsg);
6723 IO_NETOP_PREP_ASYNC(connect);
6724 IO_NETOP_PREP(accept);
6725 IO_NETOP_PREP(socket);
6726 IO_NETOP_PREP(shutdown);
6729 #endif /* CONFIG_NET */
6731 struct io_poll_table {
6732 struct poll_table_struct pt;
6733 struct io_kiocb *req;
6738 #define IO_POLL_CANCEL_FLAG BIT(31)
6739 #define IO_POLL_REF_MASK GENMASK(30, 0)
6742 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6743 * bump it and acquire ownership. It's disallowed to modify requests while not
6744 * owning it, that prevents from races for enqueueing task_work's and b/w
6745 * arming poll and wakeups.
6747 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6749 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6752 static void io_poll_mark_cancelled(struct io_kiocb *req)
6754 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6757 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6759 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6760 if (req->opcode == IORING_OP_POLL_ADD)
6761 return req->async_data;
6762 return req->apoll->double_poll;
6765 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6767 if (req->opcode == IORING_OP_POLL_ADD)
6769 return &req->apoll->poll;
6772 static void io_poll_req_insert(struct io_kiocb *req)
6774 struct io_ring_ctx *ctx = req->ctx;
6775 struct hlist_head *list;
6777 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6778 hlist_add_head(&req->hash_node, list);
6781 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6782 wait_queue_func_t wake_func)
6785 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6786 /* mask in events that we always want/need */
6787 poll->events = events | IO_POLL_UNMASK;
6788 INIT_LIST_HEAD(&poll->wait.entry);
6789 init_waitqueue_func_entry(&poll->wait, wake_func);
6792 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6794 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6797 spin_lock_irq(&head->lock);
6798 list_del_init(&poll->wait.entry);
6800 spin_unlock_irq(&head->lock);
6804 static void io_poll_remove_entries(struct io_kiocb *req)
6807 * Nothing to do if neither of those flags are set. Avoid dipping
6808 * into the poll/apoll/double cachelines if we can.
6810 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6814 * While we hold the waitqueue lock and the waitqueue is nonempty,
6815 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6816 * lock in the first place can race with the waitqueue being freed.
6818 * We solve this as eventpoll does: by taking advantage of the fact that
6819 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6820 * we enter rcu_read_lock() and see that the pointer to the queue is
6821 * non-NULL, we can then lock it without the memory being freed out from
6824 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6825 * case the caller deletes the entry from the queue, leaving it empty.
6826 * In that case, only RCU prevents the queue memory from being freed.
6829 if (req->flags & REQ_F_SINGLE_POLL)
6830 io_poll_remove_entry(io_poll_get_single(req));
6831 if (req->flags & REQ_F_DOUBLE_POLL)
6832 io_poll_remove_entry(io_poll_get_double(req));
6836 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6838 * All poll tw should go through this. Checks for poll events, manages
6839 * references, does rewait, etc.
6841 * Returns a negative error on failure. >0 when no action require, which is
6842 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6843 * the request, then the mask is stored in req->cqe.res.
6845 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6847 struct io_ring_ctx *ctx = req->ctx;
6850 /* req->task == current here, checking PF_EXITING is safe */
6851 if (unlikely(req->task->flags & PF_EXITING))
6855 v = atomic_read(&req->poll_refs);
6857 /* tw handler should be the owner, and so have some references */
6858 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6860 if (v & IO_POLL_CANCEL_FLAG)
6863 if (!req->cqe.res) {
6864 struct poll_table_struct pt = { ._key = req->apoll_events };
6865 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6868 if ((unlikely(!req->cqe.res)))
6870 if (req->apoll_events & EPOLLONESHOT)
6873 /* multishot, just fill a CQE and proceed */
6874 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6875 __poll_t mask = mangle_poll(req->cqe.res &
6879 spin_lock(&ctx->completion_lock);
6880 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6881 mask, IORING_CQE_F_MORE);
6882 io_commit_cqring(ctx);
6883 spin_unlock(&ctx->completion_lock);
6885 io_cqring_ev_posted(ctx);
6891 io_tw_lock(req->ctx, locked);
6892 if (unlikely(req->task->flags & PF_EXITING))
6894 ret = io_issue_sqe(req,
6895 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6900 * Release all references, retry if someone tried to restart
6901 * task_work while we were executing it.
6903 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6908 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6910 struct io_ring_ctx *ctx = req->ctx;
6913 ret = io_poll_check_events(req, locked);
6918 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6924 io_poll_remove_entries(req);
6925 spin_lock(&ctx->completion_lock);
6926 hash_del(&req->hash_node);
6927 __io_req_complete_post(req, req->cqe.res, 0);
6928 io_commit_cqring(ctx);
6929 spin_unlock(&ctx->completion_lock);
6930 io_cqring_ev_posted(ctx);
6933 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6935 struct io_ring_ctx *ctx = req->ctx;
6938 ret = io_poll_check_events(req, locked);
6942 io_poll_remove_entries(req);
6943 spin_lock(&ctx->completion_lock);
6944 hash_del(&req->hash_node);
6945 spin_unlock(&ctx->completion_lock);
6948 io_req_task_submit(req, locked);
6950 io_req_complete_failed(req, ret);
6953 static void __io_poll_execute(struct io_kiocb *req, int mask,
6954 __poll_t __maybe_unused events)
6956 req->cqe.res = mask;
6958 * This is useful for poll that is armed on behalf of another
6959 * request, and where the wakeup path could be on a different
6960 * CPU. We want to avoid pulling in req->apoll->events for that
6963 if (req->opcode == IORING_OP_POLL_ADD)
6964 req->io_task_work.func = io_poll_task_func;
6966 req->io_task_work.func = io_apoll_task_func;
6968 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6969 io_req_task_work_add(req);
6972 static inline void io_poll_execute(struct io_kiocb *req, int res,
6975 if (io_poll_get_ownership(req))
6976 __io_poll_execute(req, res, events);
6979 static void io_poll_cancel_req(struct io_kiocb *req)
6981 io_poll_mark_cancelled(req);
6982 /* kick tw, which should complete the request */
6983 io_poll_execute(req, 0, 0);
6986 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6987 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6988 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
6990 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6993 struct io_kiocb *req = wqe_to_req(wait);
6994 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6996 __poll_t mask = key_to_poll(key);
6998 if (unlikely(mask & POLLFREE)) {
6999 io_poll_mark_cancelled(req);
7000 /* we have to kick tw in case it's not already */
7001 io_poll_execute(req, 0, poll->events);
7004 * If the waitqueue is being freed early but someone is already
7005 * holds ownership over it, we have to tear down the request as
7006 * best we can. That means immediately removing the request from
7007 * its waitqueue and preventing all further accesses to the
7008 * waitqueue via the request.
7010 list_del_init(&poll->wait.entry);
7013 * Careful: this *must* be the last step, since as soon
7014 * as req->head is NULL'ed out, the request can be
7015 * completed and freed, since aio_poll_complete_work()
7016 * will no longer need to take the waitqueue lock.
7018 smp_store_release(&poll->head, NULL);
7022 /* for instances that support it check for an event match first */
7023 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
7026 if (io_poll_get_ownership(req)) {
7027 /* optional, saves extra locking for removal in tw handler */
7028 if (mask && poll->events & EPOLLONESHOT) {
7029 list_del_init(&poll->wait.entry);
7031 if (wqe_is_double(wait))
7032 req->flags &= ~REQ_F_DOUBLE_POLL;
7034 req->flags &= ~REQ_F_SINGLE_POLL;
7036 __io_poll_execute(req, mask, poll->events);
7041 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
7042 struct wait_queue_head *head,
7043 struct io_poll_iocb **poll_ptr)
7045 struct io_kiocb *req = pt->req;
7046 unsigned long wqe_private = (unsigned long) req;
7049 * The file being polled uses multiple waitqueues for poll handling
7050 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
7053 if (unlikely(pt->nr_entries)) {
7054 struct io_poll_iocb *first = poll;
7056 /* double add on the same waitqueue head, ignore */
7057 if (first->head == head)
7059 /* already have a 2nd entry, fail a third attempt */
7061 if ((*poll_ptr)->head == head)
7063 pt->error = -EINVAL;
7067 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
7069 pt->error = -ENOMEM;
7072 /* mark as double wq entry */
7074 req->flags |= REQ_F_DOUBLE_POLL;
7075 io_init_poll_iocb(poll, first->events, first->wait.func);
7077 if (req->opcode == IORING_OP_POLL_ADD)
7078 req->flags |= REQ_F_ASYNC_DATA;
7081 req->flags |= REQ_F_SINGLE_POLL;
7084 poll->wait.private = (void *) wqe_private;
7086 if (poll->events & EPOLLEXCLUSIVE)
7087 add_wait_queue_exclusive(head, &poll->wait);
7089 add_wait_queue(head, &poll->wait);
7092 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
7093 struct poll_table_struct *p)
7095 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7097 __io_queue_proc(&pt->req->poll, pt, head,
7098 (struct io_poll_iocb **) &pt->req->async_data);
7101 static int __io_arm_poll_handler(struct io_kiocb *req,
7102 struct io_poll_iocb *poll,
7103 struct io_poll_table *ipt, __poll_t mask)
7105 struct io_ring_ctx *ctx = req->ctx;
7108 INIT_HLIST_NODE(&req->hash_node);
7109 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
7110 io_init_poll_iocb(poll, mask, io_poll_wake);
7111 poll->file = req->file;
7113 req->apoll_events = poll->events;
7115 ipt->pt._key = mask;
7118 ipt->nr_entries = 0;
7121 * Take the ownership to delay any tw execution up until we're done
7122 * with poll arming. see io_poll_get_ownership().
7124 atomic_set(&req->poll_refs, 1);
7125 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
7127 if (mask && (poll->events & EPOLLONESHOT)) {
7128 io_poll_remove_entries(req);
7129 /* no one else has access to the req, forget about the ref */
7132 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
7133 io_poll_remove_entries(req);
7135 ipt->error = -EINVAL;
7139 spin_lock(&ctx->completion_lock);
7140 io_poll_req_insert(req);
7141 spin_unlock(&ctx->completion_lock);
7144 /* can't multishot if failed, just queue the event we've got */
7145 if (unlikely(ipt->error || !ipt->nr_entries)) {
7146 poll->events |= EPOLLONESHOT;
7147 req->apoll_events |= EPOLLONESHOT;
7150 __io_poll_execute(req, mask, poll->events);
7155 * Release ownership. If someone tried to queue a tw while it was
7156 * locked, kick it off for them.
7158 v = atomic_dec_return(&req->poll_refs);
7159 if (unlikely(v & IO_POLL_REF_MASK))
7160 __io_poll_execute(req, 0, poll->events);
7164 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7165 struct poll_table_struct *p)
7167 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7168 struct async_poll *apoll = pt->req->apoll;
7170 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7179 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7181 const struct io_op_def *def = &io_op_defs[req->opcode];
7182 struct io_ring_ctx *ctx = req->ctx;
7183 struct async_poll *apoll;
7184 struct io_poll_table ipt;
7185 __poll_t mask = POLLPRI | POLLERR;
7188 if (!def->pollin && !def->pollout)
7189 return IO_APOLL_ABORTED;
7190 if (!file_can_poll(req->file))
7191 return IO_APOLL_ABORTED;
7192 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7193 return IO_APOLL_ABORTED;
7194 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7195 mask |= EPOLLONESHOT;
7198 mask |= EPOLLIN | EPOLLRDNORM;
7200 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7201 if ((req->opcode == IORING_OP_RECVMSG) &&
7202 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7205 mask |= EPOLLOUT | EPOLLWRNORM;
7207 if (def->poll_exclusive)
7208 mask |= EPOLLEXCLUSIVE;
7209 if (req->flags & REQ_F_POLLED) {
7211 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7212 !list_empty(&ctx->apoll_cache)) {
7213 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7215 list_del_init(&apoll->poll.wait.entry);
7217 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7218 if (unlikely(!apoll))
7219 return IO_APOLL_ABORTED;
7221 apoll->double_poll = NULL;
7223 req->flags |= REQ_F_POLLED;
7224 ipt.pt._qproc = io_async_queue_proc;
7226 io_kbuf_recycle(req, issue_flags);
7228 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7229 if (ret || ipt.error)
7230 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7232 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7233 mask, apoll->poll.events);
7238 * Returns true if we found and killed one or more poll requests
7240 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7241 struct task_struct *tsk, bool cancel_all)
7243 struct hlist_node *tmp;
7244 struct io_kiocb *req;
7248 spin_lock(&ctx->completion_lock);
7249 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7250 struct hlist_head *list;
7252 list = &ctx->cancel_hash[i];
7253 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7254 if (io_match_task_safe(req, tsk, cancel_all)) {
7255 hlist_del_init(&req->hash_node);
7256 io_poll_cancel_req(req);
7261 spin_unlock(&ctx->completion_lock);
7265 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7266 struct io_cancel_data *cd)
7267 __must_hold(&ctx->completion_lock)
7269 struct hlist_head *list;
7270 struct io_kiocb *req;
7272 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7273 hlist_for_each_entry(req, list, hash_node) {
7274 if (cd->data != req->cqe.user_data)
7276 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7278 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7279 if (cd->seq == req->work.cancel_seq)
7281 req->work.cancel_seq = cd->seq;
7288 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7289 struct io_cancel_data *cd)
7290 __must_hold(&ctx->completion_lock)
7292 struct io_kiocb *req;
7295 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7296 struct hlist_head *list;
7298 list = &ctx->cancel_hash[i];
7299 hlist_for_each_entry(req, list, hash_node) {
7300 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7301 req->file != cd->file)
7303 if (cd->seq == req->work.cancel_seq)
7305 req->work.cancel_seq = cd->seq;
7312 static bool io_poll_disarm(struct io_kiocb *req)
7313 __must_hold(&ctx->completion_lock)
7315 if (!io_poll_get_ownership(req))
7317 io_poll_remove_entries(req);
7318 hash_del(&req->hash_node);
7322 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7323 __must_hold(&ctx->completion_lock)
7325 struct io_kiocb *req;
7327 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7328 req = io_poll_file_find(ctx, cd);
7330 req = io_poll_find(ctx, false, cd);
7333 io_poll_cancel_req(req);
7337 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7342 events = READ_ONCE(sqe->poll32_events);
7344 events = swahw32(events);
7346 if (!(flags & IORING_POLL_ADD_MULTI))
7347 events |= EPOLLONESHOT;
7348 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7351 static int io_poll_remove_prep(struct io_kiocb *req,
7352 const struct io_uring_sqe *sqe)
7354 struct io_poll_update *upd = &req->poll_update;
7357 if (sqe->buf_index || sqe->splice_fd_in)
7359 flags = READ_ONCE(sqe->len);
7360 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7361 IORING_POLL_ADD_MULTI))
7363 /* meaningless without update */
7364 if (flags == IORING_POLL_ADD_MULTI)
7367 upd->old_user_data = READ_ONCE(sqe->addr);
7368 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7369 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7371 upd->new_user_data = READ_ONCE(sqe->off);
7372 if (!upd->update_user_data && upd->new_user_data)
7374 if (upd->update_events)
7375 upd->events = io_poll_parse_events(sqe, flags);
7376 else if (sqe->poll32_events)
7382 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7384 struct io_poll_iocb *poll = &req->poll;
7387 if (sqe->buf_index || sqe->off || sqe->addr)
7389 flags = READ_ONCE(sqe->len);
7390 if (flags & ~IORING_POLL_ADD_MULTI)
7392 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7395 io_req_set_refcount(req);
7396 poll->events = io_poll_parse_events(sqe, flags);
7400 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7402 struct io_poll_iocb *poll = &req->poll;
7403 struct io_poll_table ipt;
7406 ipt.pt._qproc = io_poll_queue_proc;
7408 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7409 if (!ret && ipt.error)
7411 ret = ret ?: ipt.error;
7413 __io_req_complete(req, issue_flags, ret, 0);
7417 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7419 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7420 struct io_ring_ctx *ctx = req->ctx;
7421 struct io_kiocb *preq;
7425 spin_lock(&ctx->completion_lock);
7426 preq = io_poll_find(ctx, true, &cd);
7427 if (!preq || !io_poll_disarm(preq)) {
7428 spin_unlock(&ctx->completion_lock);
7429 ret = preq ? -EALREADY : -ENOENT;
7432 spin_unlock(&ctx->completion_lock);
7434 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7435 /* only mask one event flags, keep behavior flags */
7436 if (req->poll_update.update_events) {
7437 preq->poll.events &= ~0xffff;
7438 preq->poll.events |= req->poll_update.events & 0xffff;
7439 preq->poll.events |= IO_POLL_UNMASK;
7441 if (req->poll_update.update_user_data)
7442 preq->cqe.user_data = req->poll_update.new_user_data;
7444 ret2 = io_poll_add(preq, issue_flags);
7445 /* successfully updated, don't complete poll request */
7451 preq->cqe.res = -ECANCELED;
7452 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7453 io_req_task_complete(preq, &locked);
7457 /* complete update request, we're done with it */
7458 __io_req_complete(req, issue_flags, ret, 0);
7462 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7464 struct io_timeout_data *data = container_of(timer,
7465 struct io_timeout_data, timer);
7466 struct io_kiocb *req = data->req;
7467 struct io_ring_ctx *ctx = req->ctx;
7468 unsigned long flags;
7470 spin_lock_irqsave(&ctx->timeout_lock, flags);
7471 list_del_init(&req->timeout.list);
7472 atomic_set(&req->ctx->cq_timeouts,
7473 atomic_read(&req->ctx->cq_timeouts) + 1);
7474 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7476 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7479 req->cqe.res = -ETIME;
7480 req->io_task_work.func = io_req_task_complete;
7481 io_req_task_work_add(req);
7482 return HRTIMER_NORESTART;
7485 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7486 struct io_cancel_data *cd)
7487 __must_hold(&ctx->timeout_lock)
7489 struct io_timeout_data *io;
7490 struct io_kiocb *req;
7493 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7494 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7495 cd->data != req->cqe.user_data)
7497 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7498 if (cd->seq == req->work.cancel_seq)
7500 req->work.cancel_seq = cd->seq;
7506 return ERR_PTR(-ENOENT);
7508 io = req->async_data;
7509 if (hrtimer_try_to_cancel(&io->timer) == -1)
7510 return ERR_PTR(-EALREADY);
7511 list_del_init(&req->timeout.list);
7515 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7516 __must_hold(&ctx->completion_lock)
7518 struct io_kiocb *req;
7520 spin_lock_irq(&ctx->timeout_lock);
7521 req = io_timeout_extract(ctx, cd);
7522 spin_unlock_irq(&ctx->timeout_lock);
7525 return PTR_ERR(req);
7526 io_req_task_queue_fail(req, -ECANCELED);
7530 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7532 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7533 case IORING_TIMEOUT_BOOTTIME:
7534 return CLOCK_BOOTTIME;
7535 case IORING_TIMEOUT_REALTIME:
7536 return CLOCK_REALTIME;
7538 /* can't happen, vetted at prep time */
7542 return CLOCK_MONOTONIC;
7546 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7547 struct timespec64 *ts, enum hrtimer_mode mode)
7548 __must_hold(&ctx->timeout_lock)
7550 struct io_timeout_data *io;
7551 struct io_kiocb *req;
7554 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7555 found = user_data == req->cqe.user_data;
7562 io = req->async_data;
7563 if (hrtimer_try_to_cancel(&io->timer) == -1)
7565 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7566 io->timer.function = io_link_timeout_fn;
7567 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7571 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7572 struct timespec64 *ts, enum hrtimer_mode mode)
7573 __must_hold(&ctx->timeout_lock)
7575 struct io_cancel_data cd = { .data = user_data, };
7576 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7577 struct io_timeout_data *data;
7580 return PTR_ERR(req);
7582 req->timeout.off = 0; /* noseq */
7583 data = req->async_data;
7584 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7585 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7586 data->timer.function = io_timeout_fn;
7587 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7591 static int io_timeout_remove_prep(struct io_kiocb *req,
7592 const struct io_uring_sqe *sqe)
7594 struct io_timeout_rem *tr = &req->timeout_rem;
7596 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7598 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7601 tr->ltimeout = false;
7602 tr->addr = READ_ONCE(sqe->addr);
7603 tr->flags = READ_ONCE(sqe->timeout_flags);
7604 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7605 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7607 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7608 tr->ltimeout = true;
7609 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7611 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7613 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7615 } else if (tr->flags) {
7616 /* timeout removal doesn't support flags */
7623 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7625 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7630 * Remove or update an existing timeout command
7632 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7634 struct io_timeout_rem *tr = &req->timeout_rem;
7635 struct io_ring_ctx *ctx = req->ctx;
7638 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7639 struct io_cancel_data cd = { .data = tr->addr, };
7641 spin_lock(&ctx->completion_lock);
7642 ret = io_timeout_cancel(ctx, &cd);
7643 spin_unlock(&ctx->completion_lock);
7645 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7647 spin_lock_irq(&ctx->timeout_lock);
7649 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7651 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7652 spin_unlock_irq(&ctx->timeout_lock);
7657 io_req_complete_post(req, ret, 0);
7661 static int __io_timeout_prep(struct io_kiocb *req,
7662 const struct io_uring_sqe *sqe,
7663 bool is_timeout_link)
7665 struct io_timeout_data *data;
7667 u32 off = READ_ONCE(sqe->off);
7669 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7671 if (off && is_timeout_link)
7673 flags = READ_ONCE(sqe->timeout_flags);
7674 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7675 IORING_TIMEOUT_ETIME_SUCCESS))
7677 /* more than one clock specified is invalid, obviously */
7678 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7681 INIT_LIST_HEAD(&req->timeout.list);
7682 req->timeout.off = off;
7683 if (unlikely(off && !req->ctx->off_timeout_used))
7684 req->ctx->off_timeout_used = true;
7686 if (WARN_ON_ONCE(req_has_async_data(req)))
7688 if (io_alloc_async_data(req))
7691 data = req->async_data;
7693 data->flags = flags;
7695 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7698 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7701 INIT_LIST_HEAD(&req->timeout.list);
7702 data->mode = io_translate_timeout_mode(flags);
7703 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7705 if (is_timeout_link) {
7706 struct io_submit_link *link = &req->ctx->submit_state.link;
7710 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7712 req->timeout.head = link->last;
7713 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7718 static int io_timeout_prep(struct io_kiocb *req,
7719 const struct io_uring_sqe *sqe)
7721 return __io_timeout_prep(req, sqe, false);
7724 static int io_link_timeout_prep(struct io_kiocb *req,
7725 const struct io_uring_sqe *sqe)
7727 return __io_timeout_prep(req, sqe, true);
7730 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7732 struct io_ring_ctx *ctx = req->ctx;
7733 struct io_timeout_data *data = req->async_data;
7734 struct list_head *entry;
7735 u32 tail, off = req->timeout.off;
7737 spin_lock_irq(&ctx->timeout_lock);
7740 * sqe->off holds how many events that need to occur for this
7741 * timeout event to be satisfied. If it isn't set, then this is
7742 * a pure timeout request, sequence isn't used.
7744 if (io_is_timeout_noseq(req)) {
7745 entry = ctx->timeout_list.prev;
7749 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7750 req->timeout.target_seq = tail + off;
7752 /* Update the last seq here in case io_flush_timeouts() hasn't.
7753 * This is safe because ->completion_lock is held, and submissions
7754 * and completions are never mixed in the same ->completion_lock section.
7756 ctx->cq_last_tm_flush = tail;
7759 * Insertion sort, ensuring the first entry in the list is always
7760 * the one we need first.
7762 list_for_each_prev(entry, &ctx->timeout_list) {
7763 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7766 if (io_is_timeout_noseq(nxt))
7768 /* nxt.seq is behind @tail, otherwise would've been completed */
7769 if (off >= nxt->timeout.target_seq - tail)
7773 list_add(&req->timeout.list, entry);
7774 data->timer.function = io_timeout_fn;
7775 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7776 spin_unlock_irq(&ctx->timeout_lock);
7780 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7782 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7783 struct io_cancel_data *cd = data;
7785 if (req->ctx != cd->ctx)
7787 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7789 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7790 if (req->file != cd->file)
7793 if (req->cqe.user_data != cd->data)
7796 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7797 if (cd->seq == req->work.cancel_seq)
7799 req->work.cancel_seq = cd->seq;
7804 static int io_async_cancel_one(struct io_uring_task *tctx,
7805 struct io_cancel_data *cd)
7807 enum io_wq_cancel cancel_ret;
7811 if (!tctx || !tctx->io_wq)
7814 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7815 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7816 switch (cancel_ret) {
7817 case IO_WQ_CANCEL_OK:
7820 case IO_WQ_CANCEL_RUNNING:
7823 case IO_WQ_CANCEL_NOTFOUND:
7831 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7833 struct io_ring_ctx *ctx = req->ctx;
7836 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7838 ret = io_async_cancel_one(req->task->io_uring, cd);
7840 * Fall-through even for -EALREADY, as we may have poll armed
7841 * that need unarming.
7846 spin_lock(&ctx->completion_lock);
7847 ret = io_poll_cancel(ctx, cd);
7850 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7851 ret = io_timeout_cancel(ctx, cd);
7853 spin_unlock(&ctx->completion_lock);
7857 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7858 IORING_ASYNC_CANCEL_ANY)
7860 static int io_async_cancel_prep(struct io_kiocb *req,
7861 const struct io_uring_sqe *sqe)
7863 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7865 if (sqe->off || sqe->len || sqe->splice_fd_in)
7868 req->cancel.addr = READ_ONCE(sqe->addr);
7869 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7870 if (req->cancel.flags & ~CANCEL_FLAGS)
7872 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7873 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7875 req->cancel.fd = READ_ONCE(sqe->fd);
7881 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7882 unsigned int issue_flags)
7884 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7885 struct io_ring_ctx *ctx = cd->ctx;
7886 struct io_tctx_node *node;
7890 ret = io_try_cancel(req, cd);
7898 /* slow path, try all io-wq's */
7899 io_ring_submit_lock(ctx, issue_flags);
7901 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7902 struct io_uring_task *tctx = node->task->io_uring;
7904 ret = io_async_cancel_one(tctx, cd);
7905 if (ret != -ENOENT) {
7911 io_ring_submit_unlock(ctx, issue_flags);
7912 return all ? nr : ret;
7915 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7917 struct io_cancel_data cd = {
7919 .data = req->cancel.addr,
7920 .flags = req->cancel.flags,
7921 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7925 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7926 if (req->flags & REQ_F_FIXED_FILE)
7927 req->file = io_file_get_fixed(req, req->cancel.fd,
7930 req->file = io_file_get_normal(req, req->cancel.fd);
7935 cd.file = req->file;
7938 ret = __io_async_cancel(&cd, req, issue_flags);
7942 io_req_complete_post(req, ret, 0);
7946 static int io_files_update_prep(struct io_kiocb *req,
7947 const struct io_uring_sqe *sqe)
7949 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7951 if (sqe->rw_flags || sqe->splice_fd_in)
7954 req->rsrc_update.offset = READ_ONCE(sqe->off);
7955 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7956 if (!req->rsrc_update.nr_args)
7958 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7962 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7963 unsigned int issue_flags)
7965 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7970 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7971 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7981 ret = io_fixed_fd_install(req, issue_flags, file,
7982 IORING_FILE_INDEX_ALLOC);
7985 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
7986 __io_close_fixed(req, issue_flags, ret);
7997 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7999 struct io_ring_ctx *ctx = req->ctx;
8000 struct io_uring_rsrc_update2 up;
8003 up.offset = req->rsrc_update.offset;
8004 up.data = req->rsrc_update.arg;
8010 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
8011 ret = io_files_update_with_index_alloc(req, issue_flags);
8013 io_ring_submit_lock(ctx, issue_flags);
8014 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
8015 &up, req->rsrc_update.nr_args);
8016 io_ring_submit_unlock(ctx, issue_flags);
8021 __io_req_complete(req, issue_flags, ret, 0);
8025 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
8027 switch (req->opcode) {
8029 return io_nop_prep(req, sqe);
8030 case IORING_OP_READV:
8031 case IORING_OP_READ_FIXED:
8032 case IORING_OP_READ:
8033 case IORING_OP_WRITEV:
8034 case IORING_OP_WRITE_FIXED:
8035 case IORING_OP_WRITE:
8036 return io_prep_rw(req, sqe);
8037 case IORING_OP_POLL_ADD:
8038 return io_poll_add_prep(req, sqe);
8039 case IORING_OP_POLL_REMOVE:
8040 return io_poll_remove_prep(req, sqe);
8041 case IORING_OP_FSYNC:
8042 return io_fsync_prep(req, sqe);
8043 case IORING_OP_SYNC_FILE_RANGE:
8044 return io_sfr_prep(req, sqe);
8045 case IORING_OP_SENDMSG:
8046 case IORING_OP_SEND:
8047 return io_sendmsg_prep(req, sqe);
8048 case IORING_OP_RECVMSG:
8049 case IORING_OP_RECV:
8050 return io_recvmsg_prep(req, sqe);
8051 case IORING_OP_CONNECT:
8052 return io_connect_prep(req, sqe);
8053 case IORING_OP_TIMEOUT:
8054 return io_timeout_prep(req, sqe);
8055 case IORING_OP_TIMEOUT_REMOVE:
8056 return io_timeout_remove_prep(req, sqe);
8057 case IORING_OP_ASYNC_CANCEL:
8058 return io_async_cancel_prep(req, sqe);
8059 case IORING_OP_LINK_TIMEOUT:
8060 return io_link_timeout_prep(req, sqe);
8061 case IORING_OP_ACCEPT:
8062 return io_accept_prep(req, sqe);
8063 case IORING_OP_FALLOCATE:
8064 return io_fallocate_prep(req, sqe);
8065 case IORING_OP_OPENAT:
8066 return io_openat_prep(req, sqe);
8067 case IORING_OP_CLOSE:
8068 return io_close_prep(req, sqe);
8069 case IORING_OP_FILES_UPDATE:
8070 return io_files_update_prep(req, sqe);
8071 case IORING_OP_STATX:
8072 return io_statx_prep(req, sqe);
8073 case IORING_OP_FADVISE:
8074 return io_fadvise_prep(req, sqe);
8075 case IORING_OP_MADVISE:
8076 return io_madvise_prep(req, sqe);
8077 case IORING_OP_OPENAT2:
8078 return io_openat2_prep(req, sqe);
8079 case IORING_OP_EPOLL_CTL:
8080 return io_epoll_ctl_prep(req, sqe);
8081 case IORING_OP_SPLICE:
8082 return io_splice_prep(req, sqe);
8083 case IORING_OP_PROVIDE_BUFFERS:
8084 return io_provide_buffers_prep(req, sqe);
8085 case IORING_OP_REMOVE_BUFFERS:
8086 return io_remove_buffers_prep(req, sqe);
8088 return io_tee_prep(req, sqe);
8089 case IORING_OP_SHUTDOWN:
8090 return io_shutdown_prep(req, sqe);
8091 case IORING_OP_RENAMEAT:
8092 return io_renameat_prep(req, sqe);
8093 case IORING_OP_UNLINKAT:
8094 return io_unlinkat_prep(req, sqe);
8095 case IORING_OP_MKDIRAT:
8096 return io_mkdirat_prep(req, sqe);
8097 case IORING_OP_SYMLINKAT:
8098 return io_symlinkat_prep(req, sqe);
8099 case IORING_OP_LINKAT:
8100 return io_linkat_prep(req, sqe);
8101 case IORING_OP_MSG_RING:
8102 return io_msg_ring_prep(req, sqe);
8103 case IORING_OP_FSETXATTR:
8104 return io_fsetxattr_prep(req, sqe);
8105 case IORING_OP_SETXATTR:
8106 return io_setxattr_prep(req, sqe);
8107 case IORING_OP_FGETXATTR:
8108 return io_fgetxattr_prep(req, sqe);
8109 case IORING_OP_GETXATTR:
8110 return io_getxattr_prep(req, sqe);
8111 case IORING_OP_SOCKET:
8112 return io_socket_prep(req, sqe);
8113 case IORING_OP_URING_CMD:
8114 return io_uring_cmd_prep(req, sqe);
8117 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
8122 static int io_req_prep_async(struct io_kiocb *req)
8124 const struct io_op_def *def = &io_op_defs[req->opcode];
8126 /* assign early for deferred execution for non-fixed file */
8127 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
8128 req->file = io_file_get_normal(req, req->cqe.fd);
8129 if (!def->needs_async_setup)
8131 if (WARN_ON_ONCE(req_has_async_data(req)))
8133 if (io_alloc_async_data(req))
8136 switch (req->opcode) {
8137 case IORING_OP_READV:
8138 return io_readv_prep_async(req);
8139 case IORING_OP_WRITEV:
8140 return io_writev_prep_async(req);
8141 case IORING_OP_SENDMSG:
8142 return io_sendmsg_prep_async(req);
8143 case IORING_OP_RECVMSG:
8144 return io_recvmsg_prep_async(req);
8145 case IORING_OP_CONNECT:
8146 return io_connect_prep_async(req);
8147 case IORING_OP_URING_CMD:
8148 return io_uring_cmd_prep_async(req);
8150 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
8155 static u32 io_get_sequence(struct io_kiocb *req)
8157 u32 seq = req->ctx->cached_sq_head;
8158 struct io_kiocb *cur;
8160 /* need original cached_sq_head, but it was increased for each req */
8161 io_for_each_link(cur, req)
8166 static __cold void io_drain_req(struct io_kiocb *req)
8168 struct io_ring_ctx *ctx = req->ctx;
8169 struct io_defer_entry *de;
8171 u32 seq = io_get_sequence(req);
8173 /* Still need defer if there is pending req in defer list. */
8174 spin_lock(&ctx->completion_lock);
8175 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
8176 spin_unlock(&ctx->completion_lock);
8178 ctx->drain_active = false;
8179 io_req_task_queue(req);
8182 spin_unlock(&ctx->completion_lock);
8184 ret = io_req_prep_async(req);
8187 io_req_complete_failed(req, ret);
8190 io_prep_async_link(req);
8191 de = kmalloc(sizeof(*de), GFP_KERNEL);
8197 spin_lock(&ctx->completion_lock);
8198 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
8199 spin_unlock(&ctx->completion_lock);
8204 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
8207 list_add_tail(&de->list, &ctx->defer_list);
8208 spin_unlock(&ctx->completion_lock);
8211 static void io_clean_op(struct io_kiocb *req)
8213 if (req->flags & REQ_F_BUFFER_SELECTED) {
8214 spin_lock(&req->ctx->completion_lock);
8215 io_put_kbuf_comp(req);
8216 spin_unlock(&req->ctx->completion_lock);
8219 if (req->flags & REQ_F_NEED_CLEANUP) {
8220 switch (req->opcode) {
8221 case IORING_OP_READV:
8222 case IORING_OP_READ_FIXED:
8223 case IORING_OP_READ:
8224 case IORING_OP_WRITEV:
8225 case IORING_OP_WRITE_FIXED:
8226 case IORING_OP_WRITE: {
8227 struct io_async_rw *io = req->async_data;
8229 kfree(io->free_iovec);
8232 case IORING_OP_RECVMSG:
8233 case IORING_OP_SENDMSG: {
8234 struct io_async_msghdr *io = req->async_data;
8236 kfree(io->free_iov);
8239 case IORING_OP_OPENAT:
8240 case IORING_OP_OPENAT2:
8241 if (req->open.filename)
8242 putname(req->open.filename);
8244 case IORING_OP_RENAMEAT:
8245 putname(req->rename.oldpath);
8246 putname(req->rename.newpath);
8248 case IORING_OP_UNLINKAT:
8249 putname(req->unlink.filename);
8251 case IORING_OP_MKDIRAT:
8252 putname(req->mkdir.filename);
8254 case IORING_OP_SYMLINKAT:
8255 putname(req->symlink.oldpath);
8256 putname(req->symlink.newpath);
8258 case IORING_OP_LINKAT:
8259 putname(req->hardlink.oldpath);
8260 putname(req->hardlink.newpath);
8262 case IORING_OP_STATX:
8263 if (req->statx.filename)
8264 putname(req->statx.filename);
8266 case IORING_OP_SETXATTR:
8267 case IORING_OP_FSETXATTR:
8268 case IORING_OP_GETXATTR:
8269 case IORING_OP_FGETXATTR:
8270 __io_xattr_finish(req);
8274 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8275 kfree(req->apoll->double_poll);
8279 if (req->flags & REQ_F_INFLIGHT) {
8280 struct io_uring_task *tctx = req->task->io_uring;
8282 atomic_dec(&tctx->inflight_tracked);
8284 if (req->flags & REQ_F_CREDS)
8285 put_cred(req->creds);
8286 if (req->flags & REQ_F_ASYNC_DATA) {
8287 kfree(req->async_data);
8288 req->async_data = NULL;
8290 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8293 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8295 if (req->file || !io_op_defs[req->opcode].needs_file)
8298 if (req->flags & REQ_F_FIXED_FILE)
8299 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8301 req->file = io_file_get_normal(req, req->cqe.fd);
8306 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8308 const struct io_op_def *def = &io_op_defs[req->opcode];
8309 const struct cred *creds = NULL;
8312 if (unlikely(!io_assign_file(req, issue_flags)))
8315 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8316 creds = override_creds(req->creds);
8318 if (!def->audit_skip)
8319 audit_uring_entry(req->opcode);
8321 switch (req->opcode) {
8323 ret = io_nop(req, issue_flags);
8325 case IORING_OP_READV:
8326 case IORING_OP_READ_FIXED:
8327 case IORING_OP_READ:
8328 ret = io_read(req, issue_flags);
8330 case IORING_OP_WRITEV:
8331 case IORING_OP_WRITE_FIXED:
8332 case IORING_OP_WRITE:
8333 ret = io_write(req, issue_flags);
8335 case IORING_OP_FSYNC:
8336 ret = io_fsync(req, issue_flags);
8338 case IORING_OP_POLL_ADD:
8339 ret = io_poll_add(req, issue_flags);
8341 case IORING_OP_POLL_REMOVE:
8342 ret = io_poll_remove(req, issue_flags);
8344 case IORING_OP_SYNC_FILE_RANGE:
8345 ret = io_sync_file_range(req, issue_flags);
8347 case IORING_OP_SENDMSG:
8348 ret = io_sendmsg(req, issue_flags);
8350 case IORING_OP_SEND:
8351 ret = io_send(req, issue_flags);
8353 case IORING_OP_RECVMSG:
8354 ret = io_recvmsg(req, issue_flags);
8356 case IORING_OP_RECV:
8357 ret = io_recv(req, issue_flags);
8359 case IORING_OP_TIMEOUT:
8360 ret = io_timeout(req, issue_flags);
8362 case IORING_OP_TIMEOUT_REMOVE:
8363 ret = io_timeout_remove(req, issue_flags);
8365 case IORING_OP_ACCEPT:
8366 ret = io_accept(req, issue_flags);
8368 case IORING_OP_CONNECT:
8369 ret = io_connect(req, issue_flags);
8371 case IORING_OP_ASYNC_CANCEL:
8372 ret = io_async_cancel(req, issue_flags);
8374 case IORING_OP_FALLOCATE:
8375 ret = io_fallocate(req, issue_flags);
8377 case IORING_OP_OPENAT:
8378 ret = io_openat(req, issue_flags);
8380 case IORING_OP_CLOSE:
8381 ret = io_close(req, issue_flags);
8383 case IORING_OP_FILES_UPDATE:
8384 ret = io_files_update(req, issue_flags);
8386 case IORING_OP_STATX:
8387 ret = io_statx(req, issue_flags);
8389 case IORING_OP_FADVISE:
8390 ret = io_fadvise(req, issue_flags);
8392 case IORING_OP_MADVISE:
8393 ret = io_madvise(req, issue_flags);
8395 case IORING_OP_OPENAT2:
8396 ret = io_openat2(req, issue_flags);
8398 case IORING_OP_EPOLL_CTL:
8399 ret = io_epoll_ctl(req, issue_flags);
8401 case IORING_OP_SPLICE:
8402 ret = io_splice(req, issue_flags);
8404 case IORING_OP_PROVIDE_BUFFERS:
8405 ret = io_provide_buffers(req, issue_flags);
8407 case IORING_OP_REMOVE_BUFFERS:
8408 ret = io_remove_buffers(req, issue_flags);
8411 ret = io_tee(req, issue_flags);
8413 case IORING_OP_SHUTDOWN:
8414 ret = io_shutdown(req, issue_flags);
8416 case IORING_OP_RENAMEAT:
8417 ret = io_renameat(req, issue_flags);
8419 case IORING_OP_UNLINKAT:
8420 ret = io_unlinkat(req, issue_flags);
8422 case IORING_OP_MKDIRAT:
8423 ret = io_mkdirat(req, issue_flags);
8425 case IORING_OP_SYMLINKAT:
8426 ret = io_symlinkat(req, issue_flags);
8428 case IORING_OP_LINKAT:
8429 ret = io_linkat(req, issue_flags);
8431 case IORING_OP_MSG_RING:
8432 ret = io_msg_ring(req, issue_flags);
8434 case IORING_OP_FSETXATTR:
8435 ret = io_fsetxattr(req, issue_flags);
8437 case IORING_OP_SETXATTR:
8438 ret = io_setxattr(req, issue_flags);
8440 case IORING_OP_FGETXATTR:
8441 ret = io_fgetxattr(req, issue_flags);
8443 case IORING_OP_GETXATTR:
8444 ret = io_getxattr(req, issue_flags);
8446 case IORING_OP_SOCKET:
8447 ret = io_socket(req, issue_flags);
8449 case IORING_OP_URING_CMD:
8450 ret = io_uring_cmd(req, issue_flags);
8457 if (!def->audit_skip)
8458 audit_uring_exit(!ret, ret);
8461 revert_creds(creds);
8464 /* If the op doesn't have a file, we're not polling for it */
8465 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8466 io_iopoll_req_issued(req, issue_flags);
8471 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8473 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8475 req = io_put_req_find_next(req);
8476 return req ? &req->work : NULL;
8479 static void io_wq_submit_work(struct io_wq_work *work)
8481 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8482 const struct io_op_def *def = &io_op_defs[req->opcode];
8483 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8484 bool needs_poll = false;
8485 int ret = 0, err = -ECANCELED;
8487 /* one will be dropped by ->io_free_work() after returning to io-wq */
8488 if (!(req->flags & REQ_F_REFCOUNT))
8489 __io_req_set_refcount(req, 2);
8493 io_arm_ltimeout(req);
8495 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8496 if (work->flags & IO_WQ_WORK_CANCEL) {
8498 io_req_task_queue_fail(req, err);
8501 if (!io_assign_file(req, issue_flags)) {
8503 work->flags |= IO_WQ_WORK_CANCEL;
8507 if (req->flags & REQ_F_FORCE_ASYNC) {
8508 bool opcode_poll = def->pollin || def->pollout;
8510 if (opcode_poll && file_can_poll(req->file)) {
8512 issue_flags |= IO_URING_F_NONBLOCK;
8517 ret = io_issue_sqe(req, issue_flags);
8521 * We can get EAGAIN for iopolled IO even though we're
8522 * forcing a sync submission from here, since we can't
8523 * wait for request slots on the block side.
8526 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8532 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8534 /* aborted or ready, in either case retry blocking */
8536 issue_flags &= ~IO_URING_F_NONBLOCK;
8539 /* avoid locking problems by failing it from a clean context */
8541 io_req_task_queue_fail(req, ret);
8544 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8547 return &table->files[i];
8550 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8553 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8555 return (struct file *) (slot->file_ptr & FFS_MASK);
8558 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8560 unsigned long file_ptr = (unsigned long) file;
8562 file_ptr |= io_file_get_flags(file);
8563 file_slot->file_ptr = file_ptr;
8566 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8567 unsigned int issue_flags)
8569 struct io_ring_ctx *ctx = req->ctx;
8570 struct file *file = NULL;
8571 unsigned long file_ptr;
8573 io_ring_submit_lock(ctx, issue_flags);
8575 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8577 fd = array_index_nospec(fd, ctx->nr_user_files);
8578 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8579 file = (struct file *) (file_ptr & FFS_MASK);
8580 file_ptr &= ~FFS_MASK;
8581 /* mask in overlapping REQ_F and FFS bits */
8582 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8583 io_req_set_rsrc_node(req, ctx, 0);
8584 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8586 io_ring_submit_unlock(ctx, issue_flags);
8590 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8592 struct file *file = fget(fd);
8594 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8596 /* we don't allow fixed io_uring files */
8597 if (file && file->f_op == &io_uring_fops)
8598 io_req_track_inflight(req);
8602 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8604 struct io_kiocb *prev = req->timeout.prev;
8608 if (!(req->task->flags & PF_EXITING)) {
8609 struct io_cancel_data cd = {
8611 .data = prev->cqe.user_data,
8614 ret = io_try_cancel(req, &cd);
8616 io_req_complete_post(req, ret ?: -ETIME, 0);
8619 io_req_complete_post(req, -ETIME, 0);
8623 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8625 struct io_timeout_data *data = container_of(timer,
8626 struct io_timeout_data, timer);
8627 struct io_kiocb *prev, *req = data->req;
8628 struct io_ring_ctx *ctx = req->ctx;
8629 unsigned long flags;
8631 spin_lock_irqsave(&ctx->timeout_lock, flags);
8632 prev = req->timeout.head;
8633 req->timeout.head = NULL;
8636 * We don't expect the list to be empty, that will only happen if we
8637 * race with the completion of the linked work.
8640 io_remove_next_linked(prev);
8641 if (!req_ref_inc_not_zero(prev))
8644 list_del(&req->timeout.list);
8645 req->timeout.prev = prev;
8646 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8648 req->io_task_work.func = io_req_task_link_timeout;
8649 io_req_task_work_add(req);
8650 return HRTIMER_NORESTART;
8653 static void io_queue_linked_timeout(struct io_kiocb *req)
8655 struct io_ring_ctx *ctx = req->ctx;
8657 spin_lock_irq(&ctx->timeout_lock);
8659 * If the back reference is NULL, then our linked request finished
8660 * before we got a chance to setup the timer
8662 if (req->timeout.head) {
8663 struct io_timeout_data *data = req->async_data;
8665 data->timer.function = io_link_timeout_fn;
8666 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8668 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8670 spin_unlock_irq(&ctx->timeout_lock);
8671 /* drop submission reference */
8675 static void io_queue_async(struct io_kiocb *req, int ret)
8676 __must_hold(&req->ctx->uring_lock)
8678 struct io_kiocb *linked_timeout;
8680 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8681 io_req_complete_failed(req, ret);
8685 linked_timeout = io_prep_linked_timeout(req);
8687 switch (io_arm_poll_handler(req, 0)) {
8688 case IO_APOLL_READY:
8689 io_req_task_queue(req);
8691 case IO_APOLL_ABORTED:
8693 * Queued up for async execution, worker will release
8694 * submit reference when the iocb is actually submitted.
8696 io_kbuf_recycle(req, 0);
8697 io_queue_iowq(req, NULL);
8704 io_queue_linked_timeout(linked_timeout);
8707 static inline void io_queue_sqe(struct io_kiocb *req)
8708 __must_hold(&req->ctx->uring_lock)
8712 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8714 if (req->flags & REQ_F_COMPLETE_INLINE) {
8715 io_req_add_compl_list(req);
8719 * We async punt it if the file wasn't marked NOWAIT, or if the file
8720 * doesn't support non-blocking read/write attempts
8723 io_arm_ltimeout(req);
8725 io_queue_async(req, ret);
8728 static void io_queue_sqe_fallback(struct io_kiocb *req)
8729 __must_hold(&req->ctx->uring_lock)
8731 if (unlikely(req->flags & REQ_F_FAIL)) {
8733 * We don't submit, fail them all, for that replace hardlinks
8734 * with normal links. Extra REQ_F_LINK is tolerated.
8736 req->flags &= ~REQ_F_HARDLINK;
8737 req->flags |= REQ_F_LINK;
8738 io_req_complete_failed(req, req->cqe.res);
8739 } else if (unlikely(req->ctx->drain_active)) {
8742 int ret = io_req_prep_async(req);
8745 io_req_complete_failed(req, ret);
8747 io_queue_iowq(req, NULL);
8752 * Check SQE restrictions (opcode and flags).
8754 * Returns 'true' if SQE is allowed, 'false' otherwise.
8756 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8757 struct io_kiocb *req,
8758 unsigned int sqe_flags)
8760 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8763 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8764 ctx->restrictions.sqe_flags_required)
8767 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8768 ctx->restrictions.sqe_flags_required))
8774 static void io_init_req_drain(struct io_kiocb *req)
8776 struct io_ring_ctx *ctx = req->ctx;
8777 struct io_kiocb *head = ctx->submit_state.link.head;
8779 ctx->drain_active = true;
8782 * If we need to drain a request in the middle of a link, drain
8783 * the head request and the next request/link after the current
8784 * link. Considering sequential execution of links,
8785 * REQ_F_IO_DRAIN will be maintained for every request of our
8788 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8789 ctx->drain_next = true;
8793 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8794 const struct io_uring_sqe *sqe)
8795 __must_hold(&ctx->uring_lock)
8797 const struct io_op_def *def;
8798 unsigned int sqe_flags;
8802 /* req is partially pre-initialised, see io_preinit_req() */
8803 req->opcode = opcode = READ_ONCE(sqe->opcode);
8804 /* same numerical values with corresponding REQ_F_*, safe to copy */
8805 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8806 req->cqe.user_data = READ_ONCE(sqe->user_data);
8808 req->rsrc_node = NULL;
8809 req->task = current;
8811 if (unlikely(opcode >= IORING_OP_LAST)) {
8815 def = &io_op_defs[opcode];
8816 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8817 /* enforce forwards compatibility on users */
8818 if (sqe_flags & ~SQE_VALID_FLAGS)
8820 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8821 if (!def->buffer_select)
8823 req->buf_index = READ_ONCE(sqe->buf_group);
8825 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8826 ctx->drain_disabled = true;
8827 if (sqe_flags & IOSQE_IO_DRAIN) {
8828 if (ctx->drain_disabled)
8830 io_init_req_drain(req);
8833 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8834 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8836 /* knock it to the slow queue path, will be drained there */
8837 if (ctx->drain_active)
8838 req->flags |= REQ_F_FORCE_ASYNC;
8839 /* if there is no link, we're at "next" request and need to drain */
8840 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8841 ctx->drain_next = false;
8842 ctx->drain_active = true;
8843 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8847 if (!def->ioprio && sqe->ioprio)
8849 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8852 if (def->needs_file) {
8853 struct io_submit_state *state = &ctx->submit_state;
8855 req->cqe.fd = READ_ONCE(sqe->fd);
8858 * Plug now if we have more than 2 IO left after this, and the
8859 * target is potentially a read/write to block based storage.
8861 if (state->need_plug && def->plug) {
8862 state->plug_started = true;
8863 state->need_plug = false;
8864 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8868 personality = READ_ONCE(sqe->personality);
8872 req->creds = xa_load(&ctx->personalities, personality);
8875 get_cred(req->creds);
8876 ret = security_uring_override_creds(req->creds);
8878 put_cred(req->creds);
8881 req->flags |= REQ_F_CREDS;
8884 return io_req_prep(req, sqe);
8887 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8888 struct io_kiocb *req, int ret)
8890 struct io_ring_ctx *ctx = req->ctx;
8891 struct io_submit_link *link = &ctx->submit_state.link;
8892 struct io_kiocb *head = link->head;
8894 trace_io_uring_req_failed(sqe, ctx, req, ret);
8897 * Avoid breaking links in the middle as it renders links with SQPOLL
8898 * unusable. Instead of failing eagerly, continue assembling the link if
8899 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8900 * should find the flag and handle the rest.
8902 req_fail_link_node(req, ret);
8903 if (head && !(head->flags & REQ_F_FAIL))
8904 req_fail_link_node(head, -ECANCELED);
8906 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8908 link->last->link = req;
8912 io_queue_sqe_fallback(req);
8917 link->last->link = req;
8924 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8925 const struct io_uring_sqe *sqe)
8926 __must_hold(&ctx->uring_lock)
8928 struct io_submit_link *link = &ctx->submit_state.link;
8931 ret = io_init_req(ctx, req, sqe);
8933 return io_submit_fail_init(sqe, req, ret);
8935 /* don't need @sqe from now on */
8936 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8938 ctx->flags & IORING_SETUP_SQPOLL);
8941 * If we already have a head request, queue this one for async
8942 * submittal once the head completes. If we don't have a head but
8943 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8944 * submitted sync once the chain is complete. If none of those
8945 * conditions are true (normal request), then just queue it.
8947 if (unlikely(link->head)) {
8948 ret = io_req_prep_async(req);
8950 return io_submit_fail_init(sqe, req, ret);
8952 trace_io_uring_link(ctx, req, link->head);
8953 link->last->link = req;
8956 if (req->flags & IO_REQ_LINK_FLAGS)
8958 /* last request of the link, flush it */
8961 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8964 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8965 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8966 if (req->flags & IO_REQ_LINK_FLAGS) {
8971 io_queue_sqe_fallback(req);
8981 * Batched submission is done, ensure local IO is flushed out.
8983 static void io_submit_state_end(struct io_ring_ctx *ctx)
8985 struct io_submit_state *state = &ctx->submit_state;
8987 if (unlikely(state->link.head))
8988 io_queue_sqe_fallback(state->link.head);
8989 /* flush only after queuing links as they can generate completions */
8990 io_submit_flush_completions(ctx);
8991 if (state->plug_started)
8992 blk_finish_plug(&state->plug);
8996 * Start submission side cache.
8998 static void io_submit_state_start(struct io_submit_state *state,
8999 unsigned int max_ios)
9001 state->plug_started = false;
9002 state->need_plug = max_ios > 2;
9003 state->submit_nr = max_ios;
9004 /* set only head, no need to init link_last in advance */
9005 state->link.head = NULL;
9008 static void io_commit_sqring(struct io_ring_ctx *ctx)
9010 struct io_rings *rings = ctx->rings;
9013 * Ensure any loads from the SQEs are done at this point,
9014 * since once we write the new head, the application could
9015 * write new data to them.
9017 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
9021 * Fetch an sqe, if one is available. Note this returns a pointer to memory
9022 * that is mapped by userspace. This means that care needs to be taken to
9023 * ensure that reads are stable, as we cannot rely on userspace always
9024 * being a good citizen. If members of the sqe are validated and then later
9025 * used, it's important that those reads are done through READ_ONCE() to
9026 * prevent a re-load down the line.
9028 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
9030 unsigned head, mask = ctx->sq_entries - 1;
9031 unsigned sq_idx = ctx->cached_sq_head++ & mask;
9034 * The cached sq head (or cq tail) serves two purposes:
9036 * 1) allows us to batch the cost of updating the user visible
9038 * 2) allows the kernel side to track the head on its own, even
9039 * though the application is the one updating it.
9041 head = READ_ONCE(ctx->sq_array[sq_idx]);
9042 if (likely(head < ctx->sq_entries)) {
9043 /* double index for 128-byte SQEs, twice as long */
9044 if (ctx->flags & IORING_SETUP_SQE128)
9046 return &ctx->sq_sqes[head];
9049 /* drop invalid entries */
9051 WRITE_ONCE(ctx->rings->sq_dropped,
9052 READ_ONCE(ctx->rings->sq_dropped) + 1);
9056 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
9057 __must_hold(&ctx->uring_lock)
9059 unsigned int entries = io_sqring_entries(ctx);
9063 if (unlikely(!entries))
9065 /* make sure SQ entry isn't read before tail */
9066 ret = left = min3(nr, ctx->sq_entries, entries);
9067 io_get_task_refs(left);
9068 io_submit_state_start(&ctx->submit_state, left);
9071 const struct io_uring_sqe *sqe;
9072 struct io_kiocb *req;
9074 if (unlikely(!io_alloc_req_refill(ctx)))
9076 req = io_alloc_req(ctx);
9077 sqe = io_get_sqe(ctx);
9078 if (unlikely(!sqe)) {
9079 io_req_add_to_cache(req, ctx);
9084 * Continue submitting even for sqe failure if the
9085 * ring was setup with IORING_SETUP_SUBMIT_ALL
9087 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
9088 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
9094 if (unlikely(left)) {
9096 /* try again if it submitted nothing and can't allocate a req */
9097 if (!ret && io_req_cache_empty(ctx))
9099 current->io_uring->cached_refs += left;
9102 io_submit_state_end(ctx);
9103 /* Commit SQ ring head once we've consumed and submitted all SQEs */
9104 io_commit_sqring(ctx);
9108 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
9110 return READ_ONCE(sqd->state);
9113 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
9115 unsigned int to_submit;
9118 to_submit = io_sqring_entries(ctx);
9119 /* if we're handling multiple rings, cap submit size for fairness */
9120 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
9121 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
9123 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
9124 const struct cred *creds = NULL;
9126 if (ctx->sq_creds != current_cred())
9127 creds = override_creds(ctx->sq_creds);
9129 mutex_lock(&ctx->uring_lock);
9130 if (!wq_list_empty(&ctx->iopoll_list))
9131 io_do_iopoll(ctx, true);
9134 * Don't submit if refs are dying, good for io_uring_register(),
9135 * but also it is relied upon by io_ring_exit_work()
9137 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
9138 !(ctx->flags & IORING_SETUP_R_DISABLED))
9139 ret = io_submit_sqes(ctx, to_submit);
9140 mutex_unlock(&ctx->uring_lock);
9142 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
9143 wake_up(&ctx->sqo_sq_wait);
9145 revert_creds(creds);
9151 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
9153 struct io_ring_ctx *ctx;
9154 unsigned sq_thread_idle = 0;
9156 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9157 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
9158 sqd->sq_thread_idle = sq_thread_idle;
9161 static bool io_sqd_handle_event(struct io_sq_data *sqd)
9163 bool did_sig = false;
9164 struct ksignal ksig;
9166 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
9167 signal_pending(current)) {
9168 mutex_unlock(&sqd->lock);
9169 if (signal_pending(current))
9170 did_sig = get_signal(&ksig);
9172 mutex_lock(&sqd->lock);
9174 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9177 static int io_sq_thread(void *data)
9179 struct io_sq_data *sqd = data;
9180 struct io_ring_ctx *ctx;
9181 unsigned long timeout = 0;
9182 char buf[TASK_COMM_LEN];
9185 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
9186 set_task_comm(current, buf);
9188 if (sqd->sq_cpu != -1)
9189 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
9191 set_cpus_allowed_ptr(current, cpu_online_mask);
9192 current->flags |= PF_NO_SETAFFINITY;
9194 audit_alloc_kernel(current);
9196 mutex_lock(&sqd->lock);
9198 bool cap_entries, sqt_spin = false;
9200 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
9201 if (io_sqd_handle_event(sqd))
9203 timeout = jiffies + sqd->sq_thread_idle;
9206 cap_entries = !list_is_singular(&sqd->ctx_list);
9207 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9208 int ret = __io_sq_thread(ctx, cap_entries);
9210 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
9213 if (io_run_task_work())
9216 if (sqt_spin || !time_after(jiffies, timeout)) {
9219 timeout = jiffies + sqd->sq_thread_idle;
9223 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
9224 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
9225 bool needs_sched = true;
9227 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9228 atomic_or(IORING_SQ_NEED_WAKEUP,
9229 &ctx->rings->sq_flags);
9230 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
9231 !wq_list_empty(&ctx->iopoll_list)) {
9232 needs_sched = false;
9237 * Ensure the store of the wakeup flag is not
9238 * reordered with the load of the SQ tail
9240 smp_mb__after_atomic();
9242 if (io_sqring_entries(ctx)) {
9243 needs_sched = false;
9249 mutex_unlock(&sqd->lock);
9251 mutex_lock(&sqd->lock);
9253 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9254 atomic_andnot(IORING_SQ_NEED_WAKEUP,
9255 &ctx->rings->sq_flags);
9258 finish_wait(&sqd->wait, &wait);
9259 timeout = jiffies + sqd->sq_thread_idle;
9262 io_uring_cancel_generic(true, sqd);
9264 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9265 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9267 mutex_unlock(&sqd->lock);
9269 audit_free(current);
9271 complete(&sqd->exited);
9275 struct io_wait_queue {
9276 struct wait_queue_entry wq;
9277 struct io_ring_ctx *ctx;
9279 unsigned nr_timeouts;
9282 static inline bool io_should_wake(struct io_wait_queue *iowq)
9284 struct io_ring_ctx *ctx = iowq->ctx;
9285 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9288 * Wake up if we have enough events, or if a timeout occurred since we
9289 * started waiting. For timeouts, we always want to return to userspace,
9290 * regardless of event count.
9292 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9295 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9296 int wake_flags, void *key)
9298 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9302 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9303 * the task, and the next invocation will do it.
9305 if (io_should_wake(iowq) ||
9306 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9307 return autoremove_wake_function(curr, mode, wake_flags, key);
9311 static int io_run_task_work_sig(void)
9313 if (io_run_task_work())
9315 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9316 return -ERESTARTSYS;
9317 if (task_sigpending(current))
9322 /* when returns >0, the caller should retry */
9323 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9324 struct io_wait_queue *iowq,
9328 unsigned long check_cq;
9330 /* make sure we run task_work before checking for signals */
9331 ret = io_run_task_work_sig();
9332 if (ret || io_should_wake(iowq))
9334 check_cq = READ_ONCE(ctx->check_cq);
9335 /* let the caller flush overflows, retry */
9336 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9338 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9340 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9346 * Wait until events become available, if we don't already have some. The
9347 * application must reap them itself, as they reside on the shared cq ring.
9349 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9350 const sigset_t __user *sig, size_t sigsz,
9351 struct __kernel_timespec __user *uts)
9353 struct io_wait_queue iowq;
9354 struct io_rings *rings = ctx->rings;
9355 ktime_t timeout = KTIME_MAX;
9359 io_cqring_overflow_flush(ctx);
9360 if (io_cqring_events(ctx) >= min_events)
9362 if (!io_run_task_work())
9367 #ifdef CONFIG_COMPAT
9368 if (in_compat_syscall())
9369 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9373 ret = set_user_sigmask(sig, sigsz);
9380 struct timespec64 ts;
9382 if (get_timespec64(&ts, uts))
9384 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9387 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9388 iowq.wq.private = current;
9389 INIT_LIST_HEAD(&iowq.wq.entry);
9391 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9392 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9394 trace_io_uring_cqring_wait(ctx, min_events);
9396 /* if we can't even flush overflow, don't wait for more */
9397 if (!io_cqring_overflow_flush(ctx)) {
9401 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9402 TASK_INTERRUPTIBLE);
9403 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9407 finish_wait(&ctx->cq_wait, &iowq.wq);
9408 restore_saved_sigmask_unless(ret == -EINTR);
9410 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9413 static void io_free_page_table(void **table, size_t size)
9415 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9417 for (i = 0; i < nr_tables; i++)
9422 static __cold void **io_alloc_page_table(size_t size)
9424 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9425 size_t init_size = size;
9428 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9432 for (i = 0; i < nr_tables; i++) {
9433 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9435 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9437 io_free_page_table(table, init_size);
9445 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9447 percpu_ref_exit(&ref_node->refs);
9451 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9453 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9454 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9455 unsigned long flags;
9456 bool first_add = false;
9457 unsigned long delay = HZ;
9459 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9462 /* if we are mid-quiesce then do not delay */
9463 if (node->rsrc_data->quiesce)
9466 while (!list_empty(&ctx->rsrc_ref_list)) {
9467 node = list_first_entry(&ctx->rsrc_ref_list,
9468 struct io_rsrc_node, node);
9469 /* recycle ref nodes in order */
9472 list_del(&node->node);
9473 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9475 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9478 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9481 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9483 struct io_rsrc_node *ref_node;
9485 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9489 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9494 INIT_LIST_HEAD(&ref_node->node);
9495 INIT_LIST_HEAD(&ref_node->rsrc_list);
9496 ref_node->done = false;
9500 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9501 struct io_rsrc_data *data_to_kill)
9502 __must_hold(&ctx->uring_lock)
9504 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9505 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9507 io_rsrc_refs_drop(ctx);
9510 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9512 rsrc_node->rsrc_data = data_to_kill;
9513 spin_lock_irq(&ctx->rsrc_ref_lock);
9514 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9515 spin_unlock_irq(&ctx->rsrc_ref_lock);
9517 atomic_inc(&data_to_kill->refs);
9518 percpu_ref_kill(&rsrc_node->refs);
9519 ctx->rsrc_node = NULL;
9522 if (!ctx->rsrc_node) {
9523 ctx->rsrc_node = ctx->rsrc_backup_node;
9524 ctx->rsrc_backup_node = NULL;
9528 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9530 if (ctx->rsrc_backup_node)
9532 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9533 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9536 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9537 struct io_ring_ctx *ctx)
9541 /* As we may drop ->uring_lock, other task may have started quiesce */
9545 data->quiesce = true;
9547 ret = io_rsrc_node_switch_start(ctx);
9550 io_rsrc_node_switch(ctx, data);
9552 /* kill initial ref, already quiesced if zero */
9553 if (atomic_dec_and_test(&data->refs))
9555 mutex_unlock(&ctx->uring_lock);
9556 flush_delayed_work(&ctx->rsrc_put_work);
9557 ret = wait_for_completion_interruptible(&data->done);
9559 mutex_lock(&ctx->uring_lock);
9560 if (atomic_read(&data->refs) > 0) {
9562 * it has been revived by another thread while
9565 mutex_unlock(&ctx->uring_lock);
9571 atomic_inc(&data->refs);
9572 /* wait for all works potentially completing data->done */
9573 flush_delayed_work(&ctx->rsrc_put_work);
9574 reinit_completion(&data->done);
9576 ret = io_run_task_work_sig();
9577 mutex_lock(&ctx->uring_lock);
9579 data->quiesce = false;
9584 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9586 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9587 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9589 return &data->tags[table_idx][off];
9592 static void io_rsrc_data_free(struct io_rsrc_data *data)
9594 size_t size = data->nr * sizeof(data->tags[0][0]);
9597 io_free_page_table((void **)data->tags, size);
9601 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9602 u64 __user *utags, unsigned nr,
9603 struct io_rsrc_data **pdata)
9605 struct io_rsrc_data *data;
9609 data = kzalloc(sizeof(*data), GFP_KERNEL);
9612 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9620 data->do_put = do_put;
9623 for (i = 0; i < nr; i++) {
9624 u64 *tag_slot = io_get_tag_slot(data, i);
9626 if (copy_from_user(tag_slot, &utags[i],
9632 atomic_set(&data->refs, 1);
9633 init_completion(&data->done);
9637 io_rsrc_data_free(data);
9641 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9643 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9644 GFP_KERNEL_ACCOUNT);
9645 if (unlikely(!table->files))
9648 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9649 if (unlikely(!table->bitmap)) {
9650 kvfree(table->files);
9657 static void io_free_file_tables(struct io_file_table *table)
9659 kvfree(table->files);
9660 bitmap_free(table->bitmap);
9661 table->files = NULL;
9662 table->bitmap = NULL;
9665 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9667 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9668 __set_bit(bit, table->bitmap);
9669 table->alloc_hint = bit + 1;
9672 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9674 __clear_bit(bit, table->bitmap);
9675 table->alloc_hint = bit;
9678 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9680 #if !defined(IO_URING_SCM_ALL)
9683 for (i = 0; i < ctx->nr_user_files; i++) {
9684 struct file *file = io_file_from_index(ctx, i);
9688 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9690 io_file_bitmap_clear(&ctx->file_table, i);
9695 #if defined(CONFIG_UNIX)
9696 if (ctx->ring_sock) {
9697 struct sock *sock = ctx->ring_sock->sk;
9698 struct sk_buff *skb;
9700 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9704 io_free_file_tables(&ctx->file_table);
9705 io_rsrc_data_free(ctx->file_data);
9706 ctx->file_data = NULL;
9707 ctx->nr_user_files = 0;
9710 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9712 unsigned nr = ctx->nr_user_files;
9715 if (!ctx->file_data)
9719 * Quiesce may unlock ->uring_lock, and while it's not held
9720 * prevent new requests using the table.
9722 ctx->nr_user_files = 0;
9723 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9724 ctx->nr_user_files = nr;
9726 __io_sqe_files_unregister(ctx);
9730 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9731 __releases(&sqd->lock)
9733 WARN_ON_ONCE(sqd->thread == current);
9736 * Do the dance but not conditional clear_bit() because it'd race with
9737 * other threads incrementing park_pending and setting the bit.
9739 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9740 if (atomic_dec_return(&sqd->park_pending))
9741 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9742 mutex_unlock(&sqd->lock);
9745 static void io_sq_thread_park(struct io_sq_data *sqd)
9746 __acquires(&sqd->lock)
9748 WARN_ON_ONCE(sqd->thread == current);
9750 atomic_inc(&sqd->park_pending);
9751 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9752 mutex_lock(&sqd->lock);
9754 wake_up_process(sqd->thread);
9757 static void io_sq_thread_stop(struct io_sq_data *sqd)
9759 WARN_ON_ONCE(sqd->thread == current);
9760 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9762 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9763 mutex_lock(&sqd->lock);
9765 wake_up_process(sqd->thread);
9766 mutex_unlock(&sqd->lock);
9767 wait_for_completion(&sqd->exited);
9770 static void io_put_sq_data(struct io_sq_data *sqd)
9772 if (refcount_dec_and_test(&sqd->refs)) {
9773 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9775 io_sq_thread_stop(sqd);
9780 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9782 struct io_sq_data *sqd = ctx->sq_data;
9785 io_sq_thread_park(sqd);
9786 list_del_init(&ctx->sqd_list);
9787 io_sqd_update_thread_idle(sqd);
9788 io_sq_thread_unpark(sqd);
9790 io_put_sq_data(sqd);
9791 ctx->sq_data = NULL;
9795 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9797 struct io_ring_ctx *ctx_attach;
9798 struct io_sq_data *sqd;
9801 f = fdget(p->wq_fd);
9803 return ERR_PTR(-ENXIO);
9804 if (f.file->f_op != &io_uring_fops) {
9806 return ERR_PTR(-EINVAL);
9809 ctx_attach = f.file->private_data;
9810 sqd = ctx_attach->sq_data;
9813 return ERR_PTR(-EINVAL);
9815 if (sqd->task_tgid != current->tgid) {
9817 return ERR_PTR(-EPERM);
9820 refcount_inc(&sqd->refs);
9825 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9828 struct io_sq_data *sqd;
9831 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9832 sqd = io_attach_sq_data(p);
9837 /* fall through for EPERM case, setup new sqd/task */
9838 if (PTR_ERR(sqd) != -EPERM)
9842 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9844 return ERR_PTR(-ENOMEM);
9846 atomic_set(&sqd->park_pending, 0);
9847 refcount_set(&sqd->refs, 1);
9848 INIT_LIST_HEAD(&sqd->ctx_list);
9849 mutex_init(&sqd->lock);
9850 init_waitqueue_head(&sqd->wait);
9851 init_completion(&sqd->exited);
9856 * Ensure the UNIX gc is aware of our file set, so we are certain that
9857 * the io_uring can be safely unregistered on process exit, even if we have
9858 * loops in the file referencing. We account only files that can hold other
9859 * files because otherwise they can't form a loop and so are not interesting
9862 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9864 #if defined(CONFIG_UNIX)
9865 struct sock *sk = ctx->ring_sock->sk;
9866 struct sk_buff_head *head = &sk->sk_receive_queue;
9867 struct scm_fp_list *fpl;
9868 struct sk_buff *skb;
9870 if (likely(!io_file_need_scm(file)))
9874 * See if we can merge this file into an existing skb SCM_RIGHTS
9875 * file set. If there's no room, fall back to allocating a new skb
9876 * and filling it in.
9878 spin_lock_irq(&head->lock);
9879 skb = skb_peek(head);
9880 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9881 __skb_unlink(skb, head);
9884 spin_unlock_irq(&head->lock);
9887 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9891 skb = alloc_skb(0, GFP_KERNEL);
9897 fpl->user = get_uid(current_user());
9898 fpl->max = SCM_MAX_FD;
9901 UNIXCB(skb).fp = fpl;
9903 skb->destructor = unix_destruct_scm;
9904 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9907 fpl = UNIXCB(skb).fp;
9908 fpl->fp[fpl->count++] = get_file(file);
9909 unix_inflight(fpl->user, file);
9910 skb_queue_head(head, skb);
9916 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9918 struct file *file = prsrc->file;
9919 #if defined(CONFIG_UNIX)
9920 struct sock *sock = ctx->ring_sock->sk;
9921 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9922 struct sk_buff *skb;
9925 if (!io_file_need_scm(file)) {
9930 __skb_queue_head_init(&list);
9933 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9934 * remove this entry and rearrange the file array.
9936 skb = skb_dequeue(head);
9938 struct scm_fp_list *fp;
9940 fp = UNIXCB(skb).fp;
9941 for (i = 0; i < fp->count; i++) {
9944 if (fp->fp[i] != file)
9947 unix_notinflight(fp->user, fp->fp[i]);
9948 left = fp->count - 1 - i;
9950 memmove(&fp->fp[i], &fp->fp[i + 1],
9951 left * sizeof(struct file *));
9958 __skb_queue_tail(&list, skb);
9968 __skb_queue_tail(&list, skb);
9970 skb = skb_dequeue(head);
9973 if (skb_peek(&list)) {
9974 spin_lock_irq(&head->lock);
9975 while ((skb = __skb_dequeue(&list)) != NULL)
9976 __skb_queue_tail(head, skb);
9977 spin_unlock_irq(&head->lock);
9984 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9986 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9987 struct io_ring_ctx *ctx = rsrc_data->ctx;
9988 struct io_rsrc_put *prsrc, *tmp;
9990 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9991 list_del(&prsrc->list);
9994 if (ctx->flags & IORING_SETUP_IOPOLL)
9995 mutex_lock(&ctx->uring_lock);
9997 spin_lock(&ctx->completion_lock);
9998 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9999 io_commit_cqring(ctx);
10000 spin_unlock(&ctx->completion_lock);
10001 io_cqring_ev_posted(ctx);
10003 if (ctx->flags & IORING_SETUP_IOPOLL)
10004 mutex_unlock(&ctx->uring_lock);
10007 rsrc_data->do_put(ctx, prsrc);
10011 io_rsrc_node_destroy(ref_node);
10012 if (atomic_dec_and_test(&rsrc_data->refs))
10013 complete(&rsrc_data->done);
10016 static void io_rsrc_put_work(struct work_struct *work)
10018 struct io_ring_ctx *ctx;
10019 struct llist_node *node;
10021 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
10022 node = llist_del_all(&ctx->rsrc_put_llist);
10025 struct io_rsrc_node *ref_node;
10026 struct llist_node *next = node->next;
10028 ref_node = llist_entry(node, struct io_rsrc_node, llist);
10029 __io_rsrc_put_work(ref_node);
10034 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
10035 unsigned nr_args, u64 __user *tags)
10037 __s32 __user *fds = (__s32 __user *) arg;
10042 if (ctx->file_data)
10046 if (nr_args > IORING_MAX_FIXED_FILES)
10048 if (nr_args > rlimit(RLIMIT_NOFILE))
10050 ret = io_rsrc_node_switch_start(ctx);
10053 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
10058 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
10059 io_rsrc_data_free(ctx->file_data);
10060 ctx->file_data = NULL;
10064 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
10065 struct io_fixed_file *file_slot;
10067 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
10071 /* allow sparse sets */
10072 if (!fds || fd == -1) {
10074 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
10081 if (unlikely(!file))
10085 * Don't allow io_uring instances to be registered. If UNIX
10086 * isn't enabled, then this causes a reference cycle and this
10087 * instance can never get freed. If UNIX is enabled we'll
10088 * handle it just fine, but there's still no point in allowing
10089 * a ring fd as it doesn't support regular read/write anyway.
10091 if (file->f_op == &io_uring_fops) {
10095 ret = io_scm_file_account(ctx, file);
10100 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10101 io_fixed_file_set(file_slot, file);
10102 io_file_bitmap_set(&ctx->file_table, i);
10105 io_rsrc_node_switch(ctx, NULL);
10108 __io_sqe_files_unregister(ctx);
10112 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
10113 struct io_rsrc_node *node, void *rsrc)
10115 u64 *tag_slot = io_get_tag_slot(data, idx);
10116 struct io_rsrc_put *prsrc;
10118 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
10122 prsrc->tag = *tag_slot;
10124 prsrc->rsrc = rsrc;
10125 list_add(&prsrc->list, &node->rsrc_list);
10129 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
10130 unsigned int issue_flags, u32 slot_index)
10131 __must_hold(&req->ctx->uring_lock)
10133 struct io_ring_ctx *ctx = req->ctx;
10134 bool needs_switch = false;
10135 struct io_fixed_file *file_slot;
10138 if (file->f_op == &io_uring_fops)
10140 if (!ctx->file_data)
10142 if (slot_index >= ctx->nr_user_files)
10145 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
10146 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
10148 if (file_slot->file_ptr) {
10149 struct file *old_file;
10151 ret = io_rsrc_node_switch_start(ctx);
10155 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10156 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
10157 ctx->rsrc_node, old_file);
10160 file_slot->file_ptr = 0;
10161 io_file_bitmap_clear(&ctx->file_table, slot_index);
10162 needs_switch = true;
10165 ret = io_scm_file_account(ctx, file);
10167 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
10168 io_fixed_file_set(file_slot, file);
10169 io_file_bitmap_set(&ctx->file_table, slot_index);
10173 io_rsrc_node_switch(ctx, ctx->file_data);
10179 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
10180 unsigned int offset)
10182 struct io_ring_ctx *ctx = req->ctx;
10183 struct io_fixed_file *file_slot;
10187 io_ring_submit_lock(ctx, issue_flags);
10189 if (unlikely(!ctx->file_data))
10192 if (offset >= ctx->nr_user_files)
10194 ret = io_rsrc_node_switch_start(ctx);
10198 offset = array_index_nospec(offset, ctx->nr_user_files);
10199 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
10201 if (!file_slot->file_ptr)
10204 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10205 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
10209 file_slot->file_ptr = 0;
10210 io_file_bitmap_clear(&ctx->file_table, offset);
10211 io_rsrc_node_switch(ctx, ctx->file_data);
10214 io_ring_submit_unlock(ctx, issue_flags);
10218 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
10220 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
10223 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
10224 struct io_uring_rsrc_update2 *up,
10227 u64 __user *tags = u64_to_user_ptr(up->tags);
10228 __s32 __user *fds = u64_to_user_ptr(up->data);
10229 struct io_rsrc_data *data = ctx->file_data;
10230 struct io_fixed_file *file_slot;
10232 int fd, i, err = 0;
10234 bool needs_switch = false;
10236 if (!ctx->file_data)
10238 if (up->offset + nr_args > ctx->nr_user_files)
10241 for (done = 0; done < nr_args; done++) {
10244 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
10245 copy_from_user(&fd, &fds[done], sizeof(fd))) {
10249 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
10253 if (fd == IORING_REGISTER_FILES_SKIP)
10256 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
10257 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10259 if (file_slot->file_ptr) {
10260 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10261 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
10264 file_slot->file_ptr = 0;
10265 io_file_bitmap_clear(&ctx->file_table, i);
10266 needs_switch = true;
10275 * Don't allow io_uring instances to be registered. If
10276 * UNIX isn't enabled, then this causes a reference
10277 * cycle and this instance can never get freed. If UNIX
10278 * is enabled we'll handle it just fine, but there's
10279 * still no point in allowing a ring fd as it doesn't
10280 * support regular read/write anyway.
10282 if (file->f_op == &io_uring_fops) {
10287 err = io_scm_file_account(ctx, file);
10292 *io_get_tag_slot(data, i) = tag;
10293 io_fixed_file_set(file_slot, file);
10294 io_file_bitmap_set(&ctx->file_table, i);
10299 io_rsrc_node_switch(ctx, data);
10300 return done ? done : err;
10303 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
10304 struct task_struct *task)
10306 struct io_wq_hash *hash;
10307 struct io_wq_data data;
10308 unsigned int concurrency;
10310 mutex_lock(&ctx->uring_lock);
10311 hash = ctx->hash_map;
10313 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10315 mutex_unlock(&ctx->uring_lock);
10316 return ERR_PTR(-ENOMEM);
10318 refcount_set(&hash->refs, 1);
10319 init_waitqueue_head(&hash->wait);
10320 ctx->hash_map = hash;
10322 mutex_unlock(&ctx->uring_lock);
10326 data.free_work = io_wq_free_work;
10327 data.do_work = io_wq_submit_work;
10329 /* Do QD, or 4 * CPUS, whatever is smallest */
10330 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10332 return io_wq_create(concurrency, &data);
10335 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10336 struct io_ring_ctx *ctx)
10338 struct io_uring_task *tctx;
10341 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10342 if (unlikely(!tctx))
10345 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10346 sizeof(struct file *), GFP_KERNEL);
10347 if (unlikely(!tctx->registered_rings)) {
10352 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10353 if (unlikely(ret)) {
10354 kfree(tctx->registered_rings);
10359 tctx->io_wq = io_init_wq_offload(ctx, task);
10360 if (IS_ERR(tctx->io_wq)) {
10361 ret = PTR_ERR(tctx->io_wq);
10362 percpu_counter_destroy(&tctx->inflight);
10363 kfree(tctx->registered_rings);
10368 xa_init(&tctx->xa);
10369 init_waitqueue_head(&tctx->wait);
10370 atomic_set(&tctx->in_idle, 0);
10371 atomic_set(&tctx->inflight_tracked, 0);
10372 task->io_uring = tctx;
10373 spin_lock_init(&tctx->task_lock);
10374 INIT_WQ_LIST(&tctx->task_list);
10375 INIT_WQ_LIST(&tctx->prio_task_list);
10376 init_task_work(&tctx->task_work, tctx_task_work);
10380 void __io_uring_free(struct task_struct *tsk)
10382 struct io_uring_task *tctx = tsk->io_uring;
10384 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10385 WARN_ON_ONCE(tctx->io_wq);
10386 WARN_ON_ONCE(tctx->cached_refs);
10388 kfree(tctx->registered_rings);
10389 percpu_counter_destroy(&tctx->inflight);
10391 tsk->io_uring = NULL;
10394 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10395 struct io_uring_params *p)
10399 /* Retain compatibility with failing for an invalid attach attempt */
10400 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10401 IORING_SETUP_ATTACH_WQ) {
10404 f = fdget(p->wq_fd);
10407 if (f.file->f_op != &io_uring_fops) {
10413 if (ctx->flags & IORING_SETUP_SQPOLL) {
10414 struct task_struct *tsk;
10415 struct io_sq_data *sqd;
10418 ret = security_uring_sqpoll();
10422 sqd = io_get_sq_data(p, &attached);
10424 ret = PTR_ERR(sqd);
10428 ctx->sq_creds = get_current_cred();
10429 ctx->sq_data = sqd;
10430 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10431 if (!ctx->sq_thread_idle)
10432 ctx->sq_thread_idle = HZ;
10434 io_sq_thread_park(sqd);
10435 list_add(&ctx->sqd_list, &sqd->ctx_list);
10436 io_sqd_update_thread_idle(sqd);
10437 /* don't attach to a dying SQPOLL thread, would be racy */
10438 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10439 io_sq_thread_unpark(sqd);
10446 if (p->flags & IORING_SETUP_SQ_AFF) {
10447 int cpu = p->sq_thread_cpu;
10450 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10457 sqd->task_pid = current->pid;
10458 sqd->task_tgid = current->tgid;
10459 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10461 ret = PTR_ERR(tsk);
10466 ret = io_uring_alloc_task_context(tsk, ctx);
10467 wake_up_new_task(tsk);
10470 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10471 /* Can't have SQ_AFF without SQPOLL */
10478 complete(&ctx->sq_data->exited);
10480 io_sq_thread_finish(ctx);
10484 static inline void __io_unaccount_mem(struct user_struct *user,
10485 unsigned long nr_pages)
10487 atomic_long_sub(nr_pages, &user->locked_vm);
10490 static inline int __io_account_mem(struct user_struct *user,
10491 unsigned long nr_pages)
10493 unsigned long page_limit, cur_pages, new_pages;
10495 /* Don't allow more pages than we can safely lock */
10496 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10499 cur_pages = atomic_long_read(&user->locked_vm);
10500 new_pages = cur_pages + nr_pages;
10501 if (new_pages > page_limit)
10503 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10504 new_pages) != cur_pages);
10509 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10512 __io_unaccount_mem(ctx->user, nr_pages);
10514 if (ctx->mm_account)
10515 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10518 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10523 ret = __io_account_mem(ctx->user, nr_pages);
10528 if (ctx->mm_account)
10529 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10534 static void io_mem_free(void *ptr)
10541 page = virt_to_head_page(ptr);
10542 if (put_page_testzero(page))
10543 free_compound_page(page);
10546 static void *io_mem_alloc(size_t size)
10548 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10550 return (void *) __get_free_pages(gfp, get_order(size));
10553 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10554 unsigned int cq_entries, size_t *sq_offset)
10556 struct io_rings *rings;
10557 size_t off, sq_array_size;
10559 off = struct_size(rings, cqes, cq_entries);
10560 if (off == SIZE_MAX)
10562 if (ctx->flags & IORING_SETUP_CQE32) {
10563 if (check_shl_overflow(off, 1, &off))
10568 off = ALIGN(off, SMP_CACHE_BYTES);
10576 sq_array_size = array_size(sizeof(u32), sq_entries);
10577 if (sq_array_size == SIZE_MAX)
10580 if (check_add_overflow(off, sq_array_size, &off))
10586 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10588 struct io_mapped_ubuf *imu = *slot;
10591 if (imu != ctx->dummy_ubuf) {
10592 for (i = 0; i < imu->nr_bvecs; i++)
10593 unpin_user_page(imu->bvec[i].bv_page);
10594 if (imu->acct_pages)
10595 io_unaccount_mem(ctx, imu->acct_pages);
10601 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10603 io_buffer_unmap(ctx, &prsrc->buf);
10607 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10611 for (i = 0; i < ctx->nr_user_bufs; i++)
10612 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10613 kfree(ctx->user_bufs);
10614 io_rsrc_data_free(ctx->buf_data);
10615 ctx->user_bufs = NULL;
10616 ctx->buf_data = NULL;
10617 ctx->nr_user_bufs = 0;
10620 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10622 unsigned nr = ctx->nr_user_bufs;
10625 if (!ctx->buf_data)
10629 * Quiesce may unlock ->uring_lock, and while it's not held
10630 * prevent new requests using the table.
10632 ctx->nr_user_bufs = 0;
10633 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10634 ctx->nr_user_bufs = nr;
10636 __io_sqe_buffers_unregister(ctx);
10640 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10641 void __user *arg, unsigned index)
10643 struct iovec __user *src;
10645 #ifdef CONFIG_COMPAT
10647 struct compat_iovec __user *ciovs;
10648 struct compat_iovec ciov;
10650 ciovs = (struct compat_iovec __user *) arg;
10651 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10654 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10655 dst->iov_len = ciov.iov_len;
10659 src = (struct iovec __user *) arg;
10660 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10666 * Not super efficient, but this is just a registration time. And we do cache
10667 * the last compound head, so generally we'll only do a full search if we don't
10670 * We check if the given compound head page has already been accounted, to
10671 * avoid double accounting it. This allows us to account the full size of the
10672 * page, not just the constituent pages of a huge page.
10674 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10675 int nr_pages, struct page *hpage)
10679 /* check current page array */
10680 for (i = 0; i < nr_pages; i++) {
10681 if (!PageCompound(pages[i]))
10683 if (compound_head(pages[i]) == hpage)
10687 /* check previously registered pages */
10688 for (i = 0; i < ctx->nr_user_bufs; i++) {
10689 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10691 for (j = 0; j < imu->nr_bvecs; j++) {
10692 if (!PageCompound(imu->bvec[j].bv_page))
10694 if (compound_head(imu->bvec[j].bv_page) == hpage)
10702 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10703 int nr_pages, struct io_mapped_ubuf *imu,
10704 struct page **last_hpage)
10708 imu->acct_pages = 0;
10709 for (i = 0; i < nr_pages; i++) {
10710 if (!PageCompound(pages[i])) {
10713 struct page *hpage;
10715 hpage = compound_head(pages[i]);
10716 if (hpage == *last_hpage)
10718 *last_hpage = hpage;
10719 if (headpage_already_acct(ctx, pages, i, hpage))
10721 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10725 if (!imu->acct_pages)
10728 ret = io_account_mem(ctx, imu->acct_pages);
10730 imu->acct_pages = 0;
10734 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10737 unsigned long start, end, nr_pages;
10738 struct vm_area_struct **vmas = NULL;
10739 struct page **pages = NULL;
10740 int i, pret, ret = -ENOMEM;
10742 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10743 start = ubuf >> PAGE_SHIFT;
10744 nr_pages = end - start;
10746 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10750 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10756 mmap_read_lock(current->mm);
10757 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10759 if (pret == nr_pages) {
10760 /* don't support file backed memory */
10761 for (i = 0; i < nr_pages; i++) {
10762 struct vm_area_struct *vma = vmas[i];
10764 if (vma_is_shmem(vma))
10766 if (vma->vm_file &&
10767 !is_file_hugepages(vma->vm_file)) {
10772 *npages = nr_pages;
10774 ret = pret < 0 ? pret : -EFAULT;
10776 mmap_read_unlock(current->mm);
10779 * if we did partial map, or found file backed vmas,
10780 * release any pages we did get
10783 unpin_user_pages(pages, pret);
10791 pages = ERR_PTR(ret);
10796 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10797 struct io_mapped_ubuf **pimu,
10798 struct page **last_hpage)
10800 struct io_mapped_ubuf *imu = NULL;
10801 struct page **pages = NULL;
10804 int ret, nr_pages, i;
10806 if (!iov->iov_base) {
10807 *pimu = ctx->dummy_ubuf;
10814 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10816 if (IS_ERR(pages)) {
10817 ret = PTR_ERR(pages);
10822 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10826 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10828 unpin_user_pages(pages, nr_pages);
10832 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10833 size = iov->iov_len;
10834 for (i = 0; i < nr_pages; i++) {
10837 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10838 imu->bvec[i].bv_page = pages[i];
10839 imu->bvec[i].bv_len = vec_len;
10840 imu->bvec[i].bv_offset = off;
10844 /* store original address for later verification */
10845 imu->ubuf = (unsigned long) iov->iov_base;
10846 imu->ubuf_end = imu->ubuf + iov->iov_len;
10847 imu->nr_bvecs = nr_pages;
10857 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10859 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10860 return ctx->user_bufs ? 0 : -ENOMEM;
10863 static int io_buffer_validate(struct iovec *iov)
10865 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10868 * Don't impose further limits on the size and buffer
10869 * constraints here, we'll -EINVAL later when IO is
10870 * submitted if they are wrong.
10872 if (!iov->iov_base)
10873 return iov->iov_len ? -EFAULT : 0;
10877 /* arbitrary limit, but we need something */
10878 if (iov->iov_len > SZ_1G)
10881 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10887 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10888 unsigned int nr_args, u64 __user *tags)
10890 struct page *last_hpage = NULL;
10891 struct io_rsrc_data *data;
10895 if (ctx->user_bufs)
10897 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10899 ret = io_rsrc_node_switch_start(ctx);
10902 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10905 ret = io_buffers_map_alloc(ctx, nr_args);
10907 io_rsrc_data_free(data);
10911 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10913 ret = io_copy_iov(ctx, &iov, arg, i);
10916 ret = io_buffer_validate(&iov);
10920 memset(&iov, 0, sizeof(iov));
10923 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10928 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10934 WARN_ON_ONCE(ctx->buf_data);
10936 ctx->buf_data = data;
10938 __io_sqe_buffers_unregister(ctx);
10940 io_rsrc_node_switch(ctx, NULL);
10944 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10945 struct io_uring_rsrc_update2 *up,
10946 unsigned int nr_args)
10948 u64 __user *tags = u64_to_user_ptr(up->tags);
10949 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10950 struct page *last_hpage = NULL;
10951 bool needs_switch = false;
10955 if (!ctx->buf_data)
10957 if (up->offset + nr_args > ctx->nr_user_bufs)
10960 for (done = 0; done < nr_args; done++) {
10961 struct io_mapped_ubuf *imu;
10962 int offset = up->offset + done;
10965 err = io_copy_iov(ctx, &iov, iovs, done);
10968 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10972 err = io_buffer_validate(&iov);
10975 if (!iov.iov_base && tag) {
10979 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10983 i = array_index_nospec(offset, ctx->nr_user_bufs);
10984 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10985 err = io_queue_rsrc_removal(ctx->buf_data, i,
10986 ctx->rsrc_node, ctx->user_bufs[i]);
10987 if (unlikely(err)) {
10988 io_buffer_unmap(ctx, &imu);
10991 ctx->user_bufs[i] = NULL;
10992 needs_switch = true;
10995 ctx->user_bufs[i] = imu;
10996 *io_get_tag_slot(ctx->buf_data, offset) = tag;
11000 io_rsrc_node_switch(ctx, ctx->buf_data);
11001 return done ? done : err;
11004 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
11005 unsigned int eventfd_async)
11007 struct io_ev_fd *ev_fd;
11008 __s32 __user *fds = arg;
11011 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11012 lockdep_is_held(&ctx->uring_lock));
11016 if (copy_from_user(&fd, fds, sizeof(*fds)))
11019 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
11023 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
11024 if (IS_ERR(ev_fd->cq_ev_fd)) {
11025 int ret = PTR_ERR(ev_fd->cq_ev_fd);
11029 ev_fd->eventfd_async = eventfd_async;
11030 ctx->has_evfd = true;
11031 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
11035 static void io_eventfd_put(struct rcu_head *rcu)
11037 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
11039 eventfd_ctx_put(ev_fd->cq_ev_fd);
11043 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
11045 struct io_ev_fd *ev_fd;
11047 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11048 lockdep_is_held(&ctx->uring_lock));
11050 ctx->has_evfd = false;
11051 rcu_assign_pointer(ctx->io_ev_fd, NULL);
11052 call_rcu(&ev_fd->rcu, io_eventfd_put);
11059 static void io_destroy_buffers(struct io_ring_ctx *ctx)
11061 struct io_buffer_list *bl;
11062 unsigned long index;
11065 for (i = 0; i < BGID_ARRAY; i++) {
11068 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
11071 xa_for_each(&ctx->io_bl_xa, index, bl) {
11072 xa_erase(&ctx->io_bl_xa, bl->bgid);
11073 __io_remove_buffers(ctx, bl, -1U);
11077 while (!list_empty(&ctx->io_buffers_pages)) {
11080 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
11081 list_del_init(&page->lru);
11086 static void io_req_caches_free(struct io_ring_ctx *ctx)
11088 struct io_submit_state *state = &ctx->submit_state;
11091 mutex_lock(&ctx->uring_lock);
11092 io_flush_cached_locked_reqs(ctx, state);
11094 while (!io_req_cache_empty(ctx)) {
11095 struct io_wq_work_node *node;
11096 struct io_kiocb *req;
11098 node = wq_stack_extract(&state->free_list);
11099 req = container_of(node, struct io_kiocb, comp_list);
11100 kmem_cache_free(req_cachep, req);
11104 percpu_ref_put_many(&ctx->refs, nr);
11105 mutex_unlock(&ctx->uring_lock);
11108 static void io_wait_rsrc_data(struct io_rsrc_data *data)
11110 if (data && !atomic_dec_and_test(&data->refs))
11111 wait_for_completion(&data->done);
11114 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
11116 struct async_poll *apoll;
11118 while (!list_empty(&ctx->apoll_cache)) {
11119 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
11121 list_del(&apoll->poll.wait.entry);
11126 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
11128 io_sq_thread_finish(ctx);
11130 if (ctx->mm_account) {
11131 mmdrop(ctx->mm_account);
11132 ctx->mm_account = NULL;
11135 io_rsrc_refs_drop(ctx);
11136 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
11137 io_wait_rsrc_data(ctx->buf_data);
11138 io_wait_rsrc_data(ctx->file_data);
11140 mutex_lock(&ctx->uring_lock);
11142 __io_sqe_buffers_unregister(ctx);
11143 if (ctx->file_data)
11144 __io_sqe_files_unregister(ctx);
11146 __io_cqring_overflow_flush(ctx, true);
11147 io_eventfd_unregister(ctx);
11148 io_flush_apoll_cache(ctx);
11149 mutex_unlock(&ctx->uring_lock);
11150 io_destroy_buffers(ctx);
11152 put_cred(ctx->sq_creds);
11154 /* there are no registered resources left, nobody uses it */
11155 if (ctx->rsrc_node)
11156 io_rsrc_node_destroy(ctx->rsrc_node);
11157 if (ctx->rsrc_backup_node)
11158 io_rsrc_node_destroy(ctx->rsrc_backup_node);
11159 flush_delayed_work(&ctx->rsrc_put_work);
11160 flush_delayed_work(&ctx->fallback_work);
11162 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
11163 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
11165 #if defined(CONFIG_UNIX)
11166 if (ctx->ring_sock) {
11167 ctx->ring_sock->file = NULL; /* so that iput() is called */
11168 sock_release(ctx->ring_sock);
11171 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
11173 io_mem_free(ctx->rings);
11174 io_mem_free(ctx->sq_sqes);
11176 percpu_ref_exit(&ctx->refs);
11177 free_uid(ctx->user);
11178 io_req_caches_free(ctx);
11180 io_wq_put_hash(ctx->hash_map);
11181 kfree(ctx->cancel_hash);
11182 kfree(ctx->dummy_ubuf);
11184 xa_destroy(&ctx->io_bl_xa);
11188 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
11190 struct io_ring_ctx *ctx = file->private_data;
11193 poll_wait(file, &ctx->cq_wait, wait);
11195 * synchronizes with barrier from wq_has_sleeper call in
11199 if (!io_sqring_full(ctx))
11200 mask |= EPOLLOUT | EPOLLWRNORM;
11203 * Don't flush cqring overflow list here, just do a simple check.
11204 * Otherwise there could possible be ABBA deadlock:
11207 * lock(&ctx->uring_lock);
11209 * lock(&ctx->uring_lock);
11212 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
11213 * pushs them to do the flush.
11215 if (io_cqring_events(ctx) ||
11216 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
11217 mask |= EPOLLIN | EPOLLRDNORM;
11222 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
11224 const struct cred *creds;
11226 creds = xa_erase(&ctx->personalities, id);
11235 struct io_tctx_exit {
11236 struct callback_head task_work;
11237 struct completion completion;
11238 struct io_ring_ctx *ctx;
11241 static __cold void io_tctx_exit_cb(struct callback_head *cb)
11243 struct io_uring_task *tctx = current->io_uring;
11244 struct io_tctx_exit *work;
11246 work = container_of(cb, struct io_tctx_exit, task_work);
11248 * When @in_idle, we're in cancellation and it's racy to remove the
11249 * node. It'll be removed by the end of cancellation, just ignore it.
11251 if (!atomic_read(&tctx->in_idle))
11252 io_uring_del_tctx_node((unsigned long)work->ctx);
11253 complete(&work->completion);
11256 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
11258 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11260 return req->ctx == data;
11263 static __cold void io_ring_exit_work(struct work_struct *work)
11265 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
11266 unsigned long timeout = jiffies + HZ * 60 * 5;
11267 unsigned long interval = HZ / 20;
11268 struct io_tctx_exit exit;
11269 struct io_tctx_node *node;
11273 * If we're doing polled IO and end up having requests being
11274 * submitted async (out-of-line), then completions can come in while
11275 * we're waiting for refs to drop. We need to reap these manually,
11276 * as nobody else will be looking for them.
11279 io_uring_try_cancel_requests(ctx, NULL, true);
11280 if (ctx->sq_data) {
11281 struct io_sq_data *sqd = ctx->sq_data;
11282 struct task_struct *tsk;
11284 io_sq_thread_park(sqd);
11286 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
11287 io_wq_cancel_cb(tsk->io_uring->io_wq,
11288 io_cancel_ctx_cb, ctx, true);
11289 io_sq_thread_unpark(sqd);
11292 io_req_caches_free(ctx);
11294 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
11295 /* there is little hope left, don't run it too often */
11296 interval = HZ * 60;
11298 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
11300 init_completion(&exit.completion);
11301 init_task_work(&exit.task_work, io_tctx_exit_cb);
11304 * Some may use context even when all refs and requests have been put,
11305 * and they are free to do so while still holding uring_lock or
11306 * completion_lock, see io_req_task_submit(). Apart from other work,
11307 * this lock/unlock section also waits them to finish.
11309 mutex_lock(&ctx->uring_lock);
11310 while (!list_empty(&ctx->tctx_list)) {
11311 WARN_ON_ONCE(time_after(jiffies, timeout));
11313 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
11315 /* don't spin on a single task if cancellation failed */
11316 list_rotate_left(&ctx->tctx_list);
11317 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
11318 if (WARN_ON_ONCE(ret))
11321 mutex_unlock(&ctx->uring_lock);
11322 wait_for_completion(&exit.completion);
11323 mutex_lock(&ctx->uring_lock);
11325 mutex_unlock(&ctx->uring_lock);
11326 spin_lock(&ctx->completion_lock);
11327 spin_unlock(&ctx->completion_lock);
11329 io_ring_ctx_free(ctx);
11332 /* Returns true if we found and killed one or more timeouts */
11333 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
11334 struct task_struct *tsk, bool cancel_all)
11336 struct io_kiocb *req, *tmp;
11339 spin_lock(&ctx->completion_lock);
11340 spin_lock_irq(&ctx->timeout_lock);
11341 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11342 if (io_match_task(req, tsk, cancel_all)) {
11343 io_kill_timeout(req, -ECANCELED);
11347 spin_unlock_irq(&ctx->timeout_lock);
11348 io_commit_cqring(ctx);
11349 spin_unlock(&ctx->completion_lock);
11351 io_cqring_ev_posted(ctx);
11352 return canceled != 0;
11355 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11357 unsigned long index;
11358 struct creds *creds;
11360 mutex_lock(&ctx->uring_lock);
11361 percpu_ref_kill(&ctx->refs);
11363 __io_cqring_overflow_flush(ctx, true);
11364 xa_for_each(&ctx->personalities, index, creds)
11365 io_unregister_personality(ctx, index);
11366 mutex_unlock(&ctx->uring_lock);
11368 /* failed during ring init, it couldn't have issued any requests */
11370 io_kill_timeouts(ctx, NULL, true);
11371 io_poll_remove_all(ctx, NULL, true);
11372 /* if we failed setting up the ctx, we might not have any rings */
11373 io_iopoll_try_reap_events(ctx);
11376 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11378 * Use system_unbound_wq to avoid spawning tons of event kworkers
11379 * if we're exiting a ton of rings at the same time. It just adds
11380 * noise and overhead, there's no discernable change in runtime
11381 * over using system_wq.
11383 queue_work(system_unbound_wq, &ctx->exit_work);
11386 static int io_uring_release(struct inode *inode, struct file *file)
11388 struct io_ring_ctx *ctx = file->private_data;
11390 file->private_data = NULL;
11391 io_ring_ctx_wait_and_kill(ctx);
11395 struct io_task_cancel {
11396 struct task_struct *task;
11400 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11402 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11403 struct io_task_cancel *cancel = data;
11405 return io_match_task_safe(req, cancel->task, cancel->all);
11408 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11409 struct task_struct *task,
11412 struct io_defer_entry *de;
11415 spin_lock(&ctx->completion_lock);
11416 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11417 if (io_match_task_safe(de->req, task, cancel_all)) {
11418 list_cut_position(&list, &ctx->defer_list, &de->list);
11422 spin_unlock(&ctx->completion_lock);
11423 if (list_empty(&list))
11426 while (!list_empty(&list)) {
11427 de = list_first_entry(&list, struct io_defer_entry, list);
11428 list_del_init(&de->list);
11429 io_req_complete_failed(de->req, -ECANCELED);
11435 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11437 struct io_tctx_node *node;
11438 enum io_wq_cancel cret;
11441 mutex_lock(&ctx->uring_lock);
11442 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11443 struct io_uring_task *tctx = node->task->io_uring;
11446 * io_wq will stay alive while we hold uring_lock, because it's
11447 * killed after ctx nodes, which requires to take the lock.
11449 if (!tctx || !tctx->io_wq)
11451 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11452 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11454 mutex_unlock(&ctx->uring_lock);
11459 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11460 struct task_struct *task,
11463 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11464 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11466 /* failed during ring init, it couldn't have issued any requests */
11471 enum io_wq_cancel cret;
11475 ret |= io_uring_try_cancel_iowq(ctx);
11476 } else if (tctx && tctx->io_wq) {
11478 * Cancels requests of all rings, not only @ctx, but
11479 * it's fine as the task is in exit/exec.
11481 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11483 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11486 /* SQPOLL thread does its own polling */
11487 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11488 (ctx->sq_data && ctx->sq_data->thread == current)) {
11489 while (!wq_list_empty(&ctx->iopoll_list)) {
11490 io_iopoll_try_reap_events(ctx);
11495 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11496 ret |= io_poll_remove_all(ctx, task, cancel_all);
11497 ret |= io_kill_timeouts(ctx, task, cancel_all);
11499 ret |= io_run_task_work();
11506 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11508 struct io_uring_task *tctx = current->io_uring;
11509 struct io_tctx_node *node;
11512 if (unlikely(!tctx)) {
11513 ret = io_uring_alloc_task_context(current, ctx);
11517 tctx = current->io_uring;
11518 if (ctx->iowq_limits_set) {
11519 unsigned int limits[2] = { ctx->iowq_limits[0],
11520 ctx->iowq_limits[1], };
11522 ret = io_wq_max_workers(tctx->io_wq, limits);
11527 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11528 node = kmalloc(sizeof(*node), GFP_KERNEL);
11532 node->task = current;
11534 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11535 node, GFP_KERNEL));
11541 mutex_lock(&ctx->uring_lock);
11542 list_add(&node->ctx_node, &ctx->tctx_list);
11543 mutex_unlock(&ctx->uring_lock);
11550 * Note that this task has used io_uring. We use it for cancelation purposes.
11552 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11554 struct io_uring_task *tctx = current->io_uring;
11556 if (likely(tctx && tctx->last == ctx))
11558 return __io_uring_add_tctx_node(ctx);
11562 * Remove this io_uring_file -> task mapping.
11564 static __cold void io_uring_del_tctx_node(unsigned long index)
11566 struct io_uring_task *tctx = current->io_uring;
11567 struct io_tctx_node *node;
11571 node = xa_erase(&tctx->xa, index);
11575 WARN_ON_ONCE(current != node->task);
11576 WARN_ON_ONCE(list_empty(&node->ctx_node));
11578 mutex_lock(&node->ctx->uring_lock);
11579 list_del(&node->ctx_node);
11580 mutex_unlock(&node->ctx->uring_lock);
11582 if (tctx->last == node->ctx)
11587 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11589 struct io_wq *wq = tctx->io_wq;
11590 struct io_tctx_node *node;
11591 unsigned long index;
11593 xa_for_each(&tctx->xa, index, node) {
11594 io_uring_del_tctx_node(index);
11599 * Must be after io_uring_del_tctx_node() (removes nodes under
11600 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11602 io_wq_put_and_exit(wq);
11603 tctx->io_wq = NULL;
11607 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11610 return atomic_read(&tctx->inflight_tracked);
11611 return percpu_counter_sum(&tctx->inflight);
11615 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11616 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11618 static __cold void io_uring_cancel_generic(bool cancel_all,
11619 struct io_sq_data *sqd)
11621 struct io_uring_task *tctx = current->io_uring;
11622 struct io_ring_ctx *ctx;
11626 WARN_ON_ONCE(sqd && sqd->thread != current);
11628 if (!current->io_uring)
11631 io_wq_exit_start(tctx->io_wq);
11633 atomic_inc(&tctx->in_idle);
11635 io_uring_drop_tctx_refs(current);
11636 /* read completions before cancelations */
11637 inflight = tctx_inflight(tctx, !cancel_all);
11642 struct io_tctx_node *node;
11643 unsigned long index;
11645 xa_for_each(&tctx->xa, index, node) {
11646 /* sqpoll task will cancel all its requests */
11647 if (node->ctx->sq_data)
11649 io_uring_try_cancel_requests(node->ctx, current,
11653 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11654 io_uring_try_cancel_requests(ctx, current,
11658 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11659 io_run_task_work();
11660 io_uring_drop_tctx_refs(current);
11663 * If we've seen completions, retry without waiting. This
11664 * avoids a race where a completion comes in before we did
11665 * prepare_to_wait().
11667 if (inflight == tctx_inflight(tctx, !cancel_all))
11669 finish_wait(&tctx->wait, &wait);
11672 io_uring_clean_tctx(tctx);
11675 * We shouldn't run task_works after cancel, so just leave
11676 * ->in_idle set for normal exit.
11678 atomic_dec(&tctx->in_idle);
11679 /* for exec all current's requests should be gone, kill tctx */
11680 __io_uring_free(current);
11684 void __io_uring_cancel(bool cancel_all)
11686 io_uring_cancel_generic(cancel_all, NULL);
11689 void io_uring_unreg_ringfd(void)
11691 struct io_uring_task *tctx = current->io_uring;
11694 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11695 if (tctx->registered_rings[i]) {
11696 fput(tctx->registered_rings[i]);
11697 tctx->registered_rings[i] = NULL;
11702 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11703 int start, int end)
11708 for (offset = start; offset < end; offset++) {
11709 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11710 if (tctx->registered_rings[offset])
11716 } else if (file->f_op != &io_uring_fops) {
11718 return -EOPNOTSUPP;
11720 tctx->registered_rings[offset] = file;
11728 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11729 * invocation. User passes in an array of struct io_uring_rsrc_update
11730 * with ->data set to the ring_fd, and ->offset given for the desired
11731 * index. If no index is desired, application may set ->offset == -1U
11732 * and we'll find an available index. Returns number of entries
11733 * successfully processed, or < 0 on error if none were processed.
11735 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11738 struct io_uring_rsrc_update __user *arg = __arg;
11739 struct io_uring_rsrc_update reg;
11740 struct io_uring_task *tctx;
11743 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11746 mutex_unlock(&ctx->uring_lock);
11747 ret = io_uring_add_tctx_node(ctx);
11748 mutex_lock(&ctx->uring_lock);
11752 tctx = current->io_uring;
11753 for (i = 0; i < nr_args; i++) {
11756 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11766 if (reg.offset == -1U) {
11768 end = IO_RINGFD_REG_MAX;
11770 if (reg.offset >= IO_RINGFD_REG_MAX) {
11774 start = reg.offset;
11778 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11783 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11784 fput(tctx->registered_rings[reg.offset]);
11785 tctx->registered_rings[reg.offset] = NULL;
11791 return i ? i : ret;
11794 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11797 struct io_uring_rsrc_update __user *arg = __arg;
11798 struct io_uring_task *tctx = current->io_uring;
11799 struct io_uring_rsrc_update reg;
11802 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11807 for (i = 0; i < nr_args; i++) {
11808 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11812 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11817 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11818 if (tctx->registered_rings[reg.offset]) {
11819 fput(tctx->registered_rings[reg.offset]);
11820 tctx->registered_rings[reg.offset] = NULL;
11824 return i ? i : ret;
11827 static void *io_uring_validate_mmap_request(struct file *file,
11828 loff_t pgoff, size_t sz)
11830 struct io_ring_ctx *ctx = file->private_data;
11831 loff_t offset = pgoff << PAGE_SHIFT;
11836 case IORING_OFF_SQ_RING:
11837 case IORING_OFF_CQ_RING:
11840 case IORING_OFF_SQES:
11841 ptr = ctx->sq_sqes;
11844 return ERR_PTR(-EINVAL);
11847 page = virt_to_head_page(ptr);
11848 if (sz > page_size(page))
11849 return ERR_PTR(-EINVAL);
11856 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11858 size_t sz = vma->vm_end - vma->vm_start;
11862 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11864 return PTR_ERR(ptr);
11866 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11867 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11870 #else /* !CONFIG_MMU */
11872 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11874 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11877 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11879 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11882 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11883 unsigned long addr, unsigned long len,
11884 unsigned long pgoff, unsigned long flags)
11888 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11890 return PTR_ERR(ptr);
11892 return (unsigned long) ptr;
11895 #endif /* !CONFIG_MMU */
11897 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11902 if (!io_sqring_full(ctx))
11904 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11906 if (!io_sqring_full(ctx))
11909 } while (!signal_pending(current));
11911 finish_wait(&ctx->sqo_sq_wait, &wait);
11915 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11917 if (flags & IORING_ENTER_EXT_ARG) {
11918 struct io_uring_getevents_arg arg;
11920 if (argsz != sizeof(arg))
11922 if (copy_from_user(&arg, argp, sizeof(arg)))
11928 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11929 struct __kernel_timespec __user **ts,
11930 const sigset_t __user **sig)
11932 struct io_uring_getevents_arg arg;
11935 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11936 * is just a pointer to the sigset_t.
11938 if (!(flags & IORING_ENTER_EXT_ARG)) {
11939 *sig = (const sigset_t __user *) argp;
11945 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11946 * timespec and sigset_t pointers if good.
11948 if (*argsz != sizeof(arg))
11950 if (copy_from_user(&arg, argp, sizeof(arg)))
11954 *sig = u64_to_user_ptr(arg.sigmask);
11955 *argsz = arg.sigmask_sz;
11956 *ts = u64_to_user_ptr(arg.ts);
11960 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11961 u32, min_complete, u32, flags, const void __user *, argp,
11964 struct io_ring_ctx *ctx;
11968 io_run_task_work();
11970 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11971 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11972 IORING_ENTER_REGISTERED_RING)))
11976 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11977 * need only dereference our task private array to find it.
11979 if (flags & IORING_ENTER_REGISTERED_RING) {
11980 struct io_uring_task *tctx = current->io_uring;
11982 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11984 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11985 f.file = tctx->registered_rings[fd];
11991 if (unlikely(!f.file))
11995 if (unlikely(f.file->f_op != &io_uring_fops))
11999 ctx = f.file->private_data;
12000 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
12004 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
12008 * For SQ polling, the thread will do all submissions and completions.
12009 * Just return the requested submit count, and wake the thread if
12010 * we were asked to.
12013 if (ctx->flags & IORING_SETUP_SQPOLL) {
12014 io_cqring_overflow_flush(ctx);
12016 if (unlikely(ctx->sq_data->thread == NULL)) {
12020 if (flags & IORING_ENTER_SQ_WAKEUP)
12021 wake_up(&ctx->sq_data->wait);
12022 if (flags & IORING_ENTER_SQ_WAIT) {
12023 ret = io_sqpoll_wait_sq(ctx);
12028 } else if (to_submit) {
12029 ret = io_uring_add_tctx_node(ctx);
12033 mutex_lock(&ctx->uring_lock);
12034 ret = io_submit_sqes(ctx, to_submit);
12035 if (ret != to_submit) {
12036 mutex_unlock(&ctx->uring_lock);
12039 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
12040 goto iopoll_locked;
12041 mutex_unlock(&ctx->uring_lock);
12043 if (flags & IORING_ENTER_GETEVENTS) {
12045 if (ctx->syscall_iopoll) {
12047 * We disallow the app entering submit/complete with
12048 * polling, but we still need to lock the ring to
12049 * prevent racing with polled issue that got punted to
12052 mutex_lock(&ctx->uring_lock);
12054 ret2 = io_validate_ext_arg(flags, argp, argsz);
12055 if (likely(!ret2)) {
12056 min_complete = min(min_complete,
12058 ret2 = io_iopoll_check(ctx, min_complete);
12060 mutex_unlock(&ctx->uring_lock);
12062 const sigset_t __user *sig;
12063 struct __kernel_timespec __user *ts;
12065 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
12066 if (likely(!ret2)) {
12067 min_complete = min(min_complete,
12069 ret2 = io_cqring_wait(ctx, min_complete, sig,
12078 * EBADR indicates that one or more CQE were dropped.
12079 * Once the user has been informed we can clear the bit
12080 * as they are obviously ok with those drops.
12082 if (unlikely(ret2 == -EBADR))
12083 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
12089 percpu_ref_put(&ctx->refs);
12095 #ifdef CONFIG_PROC_FS
12096 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
12097 const struct cred *cred)
12099 struct user_namespace *uns = seq_user_ns(m);
12100 struct group_info *gi;
12105 seq_printf(m, "%5d\n", id);
12106 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
12107 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
12108 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
12109 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
12110 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
12111 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
12112 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
12113 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
12114 seq_puts(m, "\n\tGroups:\t");
12115 gi = cred->group_info;
12116 for (g = 0; g < gi->ngroups; g++) {
12117 seq_put_decimal_ull(m, g ? " " : "",
12118 from_kgid_munged(uns, gi->gid[g]));
12120 seq_puts(m, "\n\tCapEff:\t");
12121 cap = cred->cap_effective;
12122 CAP_FOR_EACH_U32(__capi)
12123 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
12128 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
12129 struct seq_file *m)
12131 struct io_sq_data *sq = NULL;
12132 struct io_overflow_cqe *ocqe;
12133 struct io_rings *r = ctx->rings;
12134 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
12135 unsigned int sq_head = READ_ONCE(r->sq.head);
12136 unsigned int sq_tail = READ_ONCE(r->sq.tail);
12137 unsigned int cq_head = READ_ONCE(r->cq.head);
12138 unsigned int cq_tail = READ_ONCE(r->cq.tail);
12139 unsigned int cq_shift = 0;
12140 unsigned int sq_entries, cq_entries;
12142 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
12149 * we may get imprecise sqe and cqe info if uring is actively running
12150 * since we get cached_sq_head and cached_cq_tail without uring_lock
12151 * and sq_tail and cq_head are changed by userspace. But it's ok since
12152 * we usually use these info when it is stuck.
12154 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
12155 seq_printf(m, "SqHead:\t%u\n", sq_head);
12156 seq_printf(m, "SqTail:\t%u\n", sq_tail);
12157 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
12158 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
12159 seq_printf(m, "CqHead:\t%u\n", cq_head);
12160 seq_printf(m, "CqTail:\t%u\n", cq_tail);
12161 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
12162 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
12163 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
12164 for (i = 0; i < sq_entries; i++) {
12165 unsigned int entry = i + sq_head;
12166 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
12167 struct io_uring_sqe *sqe;
12169 if (sq_idx > sq_mask)
12171 sqe = &ctx->sq_sqes[sq_idx];
12172 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
12173 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
12176 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
12177 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
12178 for (i = 0; i < cq_entries; i++) {
12179 unsigned int entry = i + cq_head;
12180 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
12183 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
12184 entry & cq_mask, cqe->user_data, cqe->res,
12187 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
12188 "extra1:%llu, extra2:%llu\n",
12189 entry & cq_mask, cqe->user_data, cqe->res,
12190 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
12195 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
12196 * since fdinfo case grabs it in the opposite direction of normal use
12197 * cases. If we fail to get the lock, we just don't iterate any
12198 * structures that could be going away outside the io_uring mutex.
12200 has_lock = mutex_trylock(&ctx->uring_lock);
12202 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
12208 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
12209 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
12210 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
12211 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
12212 struct file *f = io_file_from_index(ctx, i);
12215 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
12217 seq_printf(m, "%5u: <none>\n", i);
12219 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
12220 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
12221 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
12222 unsigned int len = buf->ubuf_end - buf->ubuf;
12224 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
12226 if (has_lock && !xa_empty(&ctx->personalities)) {
12227 unsigned long index;
12228 const struct cred *cred;
12230 seq_printf(m, "Personalities:\n");
12231 xa_for_each(&ctx->personalities, index, cred)
12232 io_uring_show_cred(m, index, cred);
12235 mutex_unlock(&ctx->uring_lock);
12237 seq_puts(m, "PollList:\n");
12238 spin_lock(&ctx->completion_lock);
12239 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
12240 struct hlist_head *list = &ctx->cancel_hash[i];
12241 struct io_kiocb *req;
12243 hlist_for_each_entry(req, list, hash_node)
12244 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
12245 task_work_pending(req->task));
12248 seq_puts(m, "CqOverflowList:\n");
12249 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
12250 struct io_uring_cqe *cqe = &ocqe->cqe;
12252 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
12253 cqe->user_data, cqe->res, cqe->flags);
12257 spin_unlock(&ctx->completion_lock);
12260 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
12262 struct io_ring_ctx *ctx = f->private_data;
12264 if (percpu_ref_tryget(&ctx->refs)) {
12265 __io_uring_show_fdinfo(ctx, m);
12266 percpu_ref_put(&ctx->refs);
12271 static const struct file_operations io_uring_fops = {
12272 .release = io_uring_release,
12273 .mmap = io_uring_mmap,
12275 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
12276 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
12278 .poll = io_uring_poll,
12279 #ifdef CONFIG_PROC_FS
12280 .show_fdinfo = io_uring_show_fdinfo,
12284 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
12285 struct io_uring_params *p)
12287 struct io_rings *rings;
12288 size_t size, sq_array_offset;
12290 /* make sure these are sane, as we already accounted them */
12291 ctx->sq_entries = p->sq_entries;
12292 ctx->cq_entries = p->cq_entries;
12294 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
12295 if (size == SIZE_MAX)
12298 rings = io_mem_alloc(size);
12302 ctx->rings = rings;
12303 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
12304 rings->sq_ring_mask = p->sq_entries - 1;
12305 rings->cq_ring_mask = p->cq_entries - 1;
12306 rings->sq_ring_entries = p->sq_entries;
12307 rings->cq_ring_entries = p->cq_entries;
12309 if (p->flags & IORING_SETUP_SQE128)
12310 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
12312 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
12313 if (size == SIZE_MAX) {
12314 io_mem_free(ctx->rings);
12319 ctx->sq_sqes = io_mem_alloc(size);
12320 if (!ctx->sq_sqes) {
12321 io_mem_free(ctx->rings);
12329 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
12333 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
12337 ret = io_uring_add_tctx_node(ctx);
12342 fd_install(fd, file);
12347 * Allocate an anonymous fd, this is what constitutes the application
12348 * visible backing of an io_uring instance. The application mmaps this
12349 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12350 * we have to tie this fd to a socket for file garbage collection purposes.
12352 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12355 #if defined(CONFIG_UNIX)
12358 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12361 return ERR_PTR(ret);
12364 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12365 O_RDWR | O_CLOEXEC, NULL);
12366 #if defined(CONFIG_UNIX)
12367 if (IS_ERR(file)) {
12368 sock_release(ctx->ring_sock);
12369 ctx->ring_sock = NULL;
12371 ctx->ring_sock->file = file;
12377 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12378 struct io_uring_params __user *params)
12380 struct io_ring_ctx *ctx;
12386 if (entries > IORING_MAX_ENTRIES) {
12387 if (!(p->flags & IORING_SETUP_CLAMP))
12389 entries = IORING_MAX_ENTRIES;
12393 * Use twice as many entries for the CQ ring. It's possible for the
12394 * application to drive a higher depth than the size of the SQ ring,
12395 * since the sqes are only used at submission time. This allows for
12396 * some flexibility in overcommitting a bit. If the application has
12397 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12398 * of CQ ring entries manually.
12400 p->sq_entries = roundup_pow_of_two(entries);
12401 if (p->flags & IORING_SETUP_CQSIZE) {
12403 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12404 * to a power-of-two, if it isn't already. We do NOT impose
12405 * any cq vs sq ring sizing.
12407 if (!p->cq_entries)
12409 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12410 if (!(p->flags & IORING_SETUP_CLAMP))
12412 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12414 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12415 if (p->cq_entries < p->sq_entries)
12418 p->cq_entries = 2 * p->sq_entries;
12421 ctx = io_ring_ctx_alloc(p);
12426 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12427 * space applications don't need to do io completion events
12428 * polling again, they can rely on io_sq_thread to do polling
12429 * work, which can reduce cpu usage and uring_lock contention.
12431 if (ctx->flags & IORING_SETUP_IOPOLL &&
12432 !(ctx->flags & IORING_SETUP_SQPOLL))
12433 ctx->syscall_iopoll = 1;
12435 ctx->compat = in_compat_syscall();
12436 if (!capable(CAP_IPC_LOCK))
12437 ctx->user = get_uid(current_user());
12440 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12441 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12444 if (ctx->flags & IORING_SETUP_SQPOLL) {
12445 /* IPI related flags don't make sense with SQPOLL */
12446 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12447 IORING_SETUP_TASKRUN_FLAG))
12449 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12450 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12451 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12453 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12455 ctx->notify_method = TWA_SIGNAL;
12459 * This is just grabbed for accounting purposes. When a process exits,
12460 * the mm is exited and dropped before the files, hence we need to hang
12461 * on to this mm purely for the purposes of being able to unaccount
12462 * memory (locked/pinned vm). It's not used for anything else.
12464 mmgrab(current->mm);
12465 ctx->mm_account = current->mm;
12467 ret = io_allocate_scq_urings(ctx, p);
12471 ret = io_sq_offload_create(ctx, p);
12474 /* always set a rsrc node */
12475 ret = io_rsrc_node_switch_start(ctx);
12478 io_rsrc_node_switch(ctx, NULL);
12480 memset(&p->sq_off, 0, sizeof(p->sq_off));
12481 p->sq_off.head = offsetof(struct io_rings, sq.head);
12482 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12483 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12484 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12485 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12486 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12487 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12489 memset(&p->cq_off, 0, sizeof(p->cq_off));
12490 p->cq_off.head = offsetof(struct io_rings, cq.head);
12491 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12492 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12493 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12494 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12495 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12496 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12498 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12499 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12500 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12501 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12502 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12503 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12504 IORING_FEAT_LINKED_FILE;
12506 if (copy_to_user(params, p, sizeof(*p))) {
12511 file = io_uring_get_file(ctx);
12512 if (IS_ERR(file)) {
12513 ret = PTR_ERR(file);
12518 * Install ring fd as the very last thing, so we don't risk someone
12519 * having closed it before we finish setup
12521 ret = io_uring_install_fd(ctx, file);
12523 /* fput will clean it up */
12528 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12531 io_ring_ctx_wait_and_kill(ctx);
12536 * Sets up an aio uring context, and returns the fd. Applications asks for a
12537 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12538 * params structure passed in.
12540 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12542 struct io_uring_params p;
12545 if (copy_from_user(&p, params, sizeof(p)))
12547 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12552 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12553 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12554 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12555 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12556 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12557 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12560 return io_uring_create(entries, &p, params);
12563 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12564 struct io_uring_params __user *, params)
12566 return io_uring_setup(entries, params);
12569 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12572 struct io_uring_probe *p;
12576 size = struct_size(p, ops, nr_args);
12577 if (size == SIZE_MAX)
12579 p = kzalloc(size, GFP_KERNEL);
12584 if (copy_from_user(p, arg, size))
12587 if (memchr_inv(p, 0, size))
12590 p->last_op = IORING_OP_LAST - 1;
12591 if (nr_args > IORING_OP_LAST)
12592 nr_args = IORING_OP_LAST;
12594 for (i = 0; i < nr_args; i++) {
12596 if (!io_op_defs[i].not_supported)
12597 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12602 if (copy_to_user(arg, p, size))
12609 static int io_register_personality(struct io_ring_ctx *ctx)
12611 const struct cred *creds;
12615 creds = get_current_cred();
12617 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12618 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12626 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12627 void __user *arg, unsigned int nr_args)
12629 struct io_uring_restriction *res;
12633 /* Restrictions allowed only if rings started disabled */
12634 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12637 /* We allow only a single restrictions registration */
12638 if (ctx->restrictions.registered)
12641 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12644 size = array_size(nr_args, sizeof(*res));
12645 if (size == SIZE_MAX)
12648 res = memdup_user(arg, size);
12650 return PTR_ERR(res);
12654 for (i = 0; i < nr_args; i++) {
12655 switch (res[i].opcode) {
12656 case IORING_RESTRICTION_REGISTER_OP:
12657 if (res[i].register_op >= IORING_REGISTER_LAST) {
12662 __set_bit(res[i].register_op,
12663 ctx->restrictions.register_op);
12665 case IORING_RESTRICTION_SQE_OP:
12666 if (res[i].sqe_op >= IORING_OP_LAST) {
12671 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12673 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12674 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12676 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12677 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12686 /* Reset all restrictions if an error happened */
12688 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12690 ctx->restrictions.registered = true;
12696 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12698 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12701 if (ctx->restrictions.registered)
12702 ctx->restricted = 1;
12704 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12705 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12706 wake_up(&ctx->sq_data->wait);
12710 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12711 struct io_uring_rsrc_update2 *up,
12717 if (check_add_overflow(up->offset, nr_args, &tmp))
12719 err = io_rsrc_node_switch_start(ctx);
12724 case IORING_RSRC_FILE:
12725 return __io_sqe_files_update(ctx, up, nr_args);
12726 case IORING_RSRC_BUFFER:
12727 return __io_sqe_buffers_update(ctx, up, nr_args);
12732 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12735 struct io_uring_rsrc_update2 up;
12739 memset(&up, 0, sizeof(up));
12740 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12742 if (up.resv || up.resv2)
12744 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12747 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12748 unsigned size, unsigned type)
12750 struct io_uring_rsrc_update2 up;
12752 if (size != sizeof(up))
12754 if (copy_from_user(&up, arg, sizeof(up)))
12756 if (!up.nr || up.resv || up.resv2)
12758 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12761 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12762 unsigned int size, unsigned int type)
12764 struct io_uring_rsrc_register rr;
12766 /* keep it extendible */
12767 if (size != sizeof(rr))
12770 memset(&rr, 0, sizeof(rr));
12771 if (copy_from_user(&rr, arg, size))
12773 if (!rr.nr || rr.resv2)
12775 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12779 case IORING_RSRC_FILE:
12780 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12782 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12783 rr.nr, u64_to_user_ptr(rr.tags));
12784 case IORING_RSRC_BUFFER:
12785 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12787 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12788 rr.nr, u64_to_user_ptr(rr.tags));
12793 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12794 void __user *arg, unsigned len)
12796 struct io_uring_task *tctx = current->io_uring;
12797 cpumask_var_t new_mask;
12800 if (!tctx || !tctx->io_wq)
12803 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12806 cpumask_clear(new_mask);
12807 if (len > cpumask_size())
12808 len = cpumask_size();
12810 if (in_compat_syscall()) {
12811 ret = compat_get_bitmap(cpumask_bits(new_mask),
12812 (const compat_ulong_t __user *)arg,
12813 len * 8 /* CHAR_BIT */);
12815 ret = copy_from_user(new_mask, arg, len);
12819 free_cpumask_var(new_mask);
12823 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12824 free_cpumask_var(new_mask);
12828 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12830 struct io_uring_task *tctx = current->io_uring;
12832 if (!tctx || !tctx->io_wq)
12835 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12838 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12840 __must_hold(&ctx->uring_lock)
12842 struct io_tctx_node *node;
12843 struct io_uring_task *tctx = NULL;
12844 struct io_sq_data *sqd = NULL;
12845 __u32 new_count[2];
12848 if (copy_from_user(new_count, arg, sizeof(new_count)))
12850 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12851 if (new_count[i] > INT_MAX)
12854 if (ctx->flags & IORING_SETUP_SQPOLL) {
12855 sqd = ctx->sq_data;
12858 * Observe the correct sqd->lock -> ctx->uring_lock
12859 * ordering. Fine to drop uring_lock here, we hold
12860 * a ref to the ctx.
12862 refcount_inc(&sqd->refs);
12863 mutex_unlock(&ctx->uring_lock);
12864 mutex_lock(&sqd->lock);
12865 mutex_lock(&ctx->uring_lock);
12867 tctx = sqd->thread->io_uring;
12870 tctx = current->io_uring;
12873 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12875 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12877 ctx->iowq_limits[i] = new_count[i];
12878 ctx->iowq_limits_set = true;
12880 if (tctx && tctx->io_wq) {
12881 ret = io_wq_max_workers(tctx->io_wq, new_count);
12885 memset(new_count, 0, sizeof(new_count));
12889 mutex_unlock(&sqd->lock);
12890 io_put_sq_data(sqd);
12893 if (copy_to_user(arg, new_count, sizeof(new_count)))
12896 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12900 /* now propagate the restriction to all registered users */
12901 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12902 struct io_uring_task *tctx = node->task->io_uring;
12904 if (WARN_ON_ONCE(!tctx->io_wq))
12907 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12908 new_count[i] = ctx->iowq_limits[i];
12909 /* ignore errors, it always returns zero anyway */
12910 (void)io_wq_max_workers(tctx->io_wq, new_count);
12915 mutex_unlock(&sqd->lock);
12916 io_put_sq_data(sqd);
12921 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12923 struct io_uring_buf_ring *br;
12924 struct io_uring_buf_reg reg;
12925 struct io_buffer_list *bl;
12926 struct page **pages;
12929 if (copy_from_user(®, arg, sizeof(reg)))
12932 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12934 if (!reg.ring_addr)
12936 if (reg.ring_addr & ~PAGE_MASK)
12938 if (!is_power_of_2(reg.ring_entries))
12941 /* cannot disambiguate full vs empty due to head/tail size */
12942 if (reg.ring_entries >= 65536)
12945 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12946 int ret = io_init_bl_list(ctx);
12951 bl = io_buffer_get_list(ctx, reg.bgid);
12953 /* if mapped buffer ring OR classic exists, don't allow */
12954 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12957 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12962 pages = io_pin_pages(reg.ring_addr,
12963 struct_size(br, bufs, reg.ring_entries),
12965 if (IS_ERR(pages)) {
12967 return PTR_ERR(pages);
12970 br = page_address(pages[0]);
12971 bl->buf_pages = pages;
12972 bl->buf_nr_pages = nr_pages;
12973 bl->nr_entries = reg.ring_entries;
12975 bl->mask = reg.ring_entries - 1;
12976 io_buffer_add_list(ctx, bl, reg.bgid);
12980 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12982 struct io_uring_buf_reg reg;
12983 struct io_buffer_list *bl;
12985 if (copy_from_user(®, arg, sizeof(reg)))
12987 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12990 bl = io_buffer_get_list(ctx, reg.bgid);
12993 if (!bl->buf_nr_pages)
12996 __io_remove_buffers(ctx, bl, -1U);
12997 if (bl->bgid >= BGID_ARRAY) {
12998 xa_erase(&ctx->io_bl_xa, bl->bgid);
13004 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
13005 void __user *arg, unsigned nr_args)
13006 __releases(ctx->uring_lock)
13007 __acquires(ctx->uring_lock)
13012 * We're inside the ring mutex, if the ref is already dying, then
13013 * someone else killed the ctx or is already going through
13014 * io_uring_register().
13016 if (percpu_ref_is_dying(&ctx->refs))
13019 if (ctx->restricted) {
13020 if (opcode >= IORING_REGISTER_LAST)
13022 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
13023 if (!test_bit(opcode, ctx->restrictions.register_op))
13028 case IORING_REGISTER_BUFFERS:
13032 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
13034 case IORING_UNREGISTER_BUFFERS:
13036 if (arg || nr_args)
13038 ret = io_sqe_buffers_unregister(ctx);
13040 case IORING_REGISTER_FILES:
13044 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
13046 case IORING_UNREGISTER_FILES:
13048 if (arg || nr_args)
13050 ret = io_sqe_files_unregister(ctx);
13052 case IORING_REGISTER_FILES_UPDATE:
13053 ret = io_register_files_update(ctx, arg, nr_args);
13055 case IORING_REGISTER_EVENTFD:
13059 ret = io_eventfd_register(ctx, arg, 0);
13061 case IORING_REGISTER_EVENTFD_ASYNC:
13065 ret = io_eventfd_register(ctx, arg, 1);
13067 case IORING_UNREGISTER_EVENTFD:
13069 if (arg || nr_args)
13071 ret = io_eventfd_unregister(ctx);
13073 case IORING_REGISTER_PROBE:
13075 if (!arg || nr_args > 256)
13077 ret = io_probe(ctx, arg, nr_args);
13079 case IORING_REGISTER_PERSONALITY:
13081 if (arg || nr_args)
13083 ret = io_register_personality(ctx);
13085 case IORING_UNREGISTER_PERSONALITY:
13089 ret = io_unregister_personality(ctx, nr_args);
13091 case IORING_REGISTER_ENABLE_RINGS:
13093 if (arg || nr_args)
13095 ret = io_register_enable_rings(ctx);
13097 case IORING_REGISTER_RESTRICTIONS:
13098 ret = io_register_restrictions(ctx, arg, nr_args);
13100 case IORING_REGISTER_FILES2:
13101 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
13103 case IORING_REGISTER_FILES_UPDATE2:
13104 ret = io_register_rsrc_update(ctx, arg, nr_args,
13107 case IORING_REGISTER_BUFFERS2:
13108 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
13110 case IORING_REGISTER_BUFFERS_UPDATE:
13111 ret = io_register_rsrc_update(ctx, arg, nr_args,
13112 IORING_RSRC_BUFFER);
13114 case IORING_REGISTER_IOWQ_AFF:
13116 if (!arg || !nr_args)
13118 ret = io_register_iowq_aff(ctx, arg, nr_args);
13120 case IORING_UNREGISTER_IOWQ_AFF:
13122 if (arg || nr_args)
13124 ret = io_unregister_iowq_aff(ctx);
13126 case IORING_REGISTER_IOWQ_MAX_WORKERS:
13128 if (!arg || nr_args != 2)
13130 ret = io_register_iowq_max_workers(ctx, arg);
13132 case IORING_REGISTER_RING_FDS:
13133 ret = io_ringfd_register(ctx, arg, nr_args);
13135 case IORING_UNREGISTER_RING_FDS:
13136 ret = io_ringfd_unregister(ctx, arg, nr_args);
13138 case IORING_REGISTER_PBUF_RING:
13140 if (!arg || nr_args != 1)
13142 ret = io_register_pbuf_ring(ctx, arg);
13144 case IORING_UNREGISTER_PBUF_RING:
13146 if (!arg || nr_args != 1)
13148 ret = io_unregister_pbuf_ring(ctx, arg);
13158 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
13159 void __user *, arg, unsigned int, nr_args)
13161 struct io_ring_ctx *ctx;
13170 if (f.file->f_op != &io_uring_fops)
13173 ctx = f.file->private_data;
13175 io_run_task_work();
13177 mutex_lock(&ctx->uring_lock);
13178 ret = __io_uring_register(ctx, opcode, arg, nr_args);
13179 mutex_unlock(&ctx->uring_lock);
13180 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
13186 static int __init io_uring_init(void)
13188 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13189 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13190 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13193 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13194 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13195 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13196 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13197 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13198 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13199 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13200 BUILD_BUG_SQE_ELEM(8, __u64, off);
13201 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13202 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13203 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13204 BUILD_BUG_SQE_ELEM(24, __u32, len);
13205 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13206 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13207 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13208 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13209 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13210 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13211 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13212 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13213 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13214 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13215 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13216 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13217 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13218 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13219 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13220 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13221 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13222 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13223 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13224 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13225 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13226 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13228 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13229 sizeof(struct io_uring_rsrc_update));
13230 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13231 sizeof(struct io_uring_rsrc_update2));
13233 /* ->buf_index is u16 */
13234 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13235 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13236 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13237 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13238 offsetof(struct io_uring_buf_ring, tail));
13240 /* should fit into one byte */
13241 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13242 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13243 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13245 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13246 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13248 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13250 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13252 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13256 __initcall(io_uring_init);