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;
582 struct io_timeout_data {
583 struct io_kiocb *req;
584 struct hrtimer timer;
585 struct timespec64 ts;
586 enum hrtimer_mode mode;
592 struct sockaddr __user *addr;
593 int __user *addr_len;
596 unsigned long nofile;
606 unsigned long nofile;
628 struct list_head list;
629 /* head of the link, used by linked timeouts only */
630 struct io_kiocb *head;
631 /* for linked completions */
632 struct io_kiocb *prev;
635 struct io_timeout_rem {
640 struct timespec64 ts;
646 /* NOTE: kiocb has the file as the first member, so don't do it here */
655 struct sockaddr __user *addr;
662 struct compat_msghdr __user *umsg_compat;
663 struct user_msghdr __user *umsg;
676 struct filename *filename;
678 unsigned long nofile;
681 struct io_rsrc_update {
707 struct epoll_event event;
711 struct file *file_out;
719 struct io_provide_buf {
733 struct filename *filename;
734 struct statx __user *buffer;
746 struct filename *oldpath;
747 struct filename *newpath;
755 struct filename *filename;
762 struct filename *filename;
768 struct filename *oldpath;
769 struct filename *newpath;
776 struct filename *oldpath;
777 struct filename *newpath;
793 struct io_async_connect {
794 struct sockaddr_storage address;
797 struct io_async_msghdr {
798 struct iovec fast_iov[UIO_FASTIOV];
799 /* points to an allocated iov, if NULL we use fast_iov instead */
800 struct iovec *free_iov;
801 struct sockaddr __user *uaddr;
803 struct sockaddr_storage addr;
807 struct iov_iter iter;
808 struct iov_iter_state iter_state;
809 struct iovec fast_iov[UIO_FASTIOV];
813 struct io_rw_state s;
814 const struct iovec *free_iovec;
816 struct wait_page_queue wpq;
821 struct xattr_ctx ctx;
822 struct filename *filename;
826 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
827 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
828 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
829 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
830 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
831 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
832 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
834 /* first byte is taken by user flags, shift it to not overlap */
839 REQ_F_LINK_TIMEOUT_BIT,
840 REQ_F_NEED_CLEANUP_BIT,
842 REQ_F_BUFFER_SELECTED_BIT,
843 REQ_F_BUFFER_RING_BIT,
844 REQ_F_COMPLETE_INLINE_BIT,
848 REQ_F_ARM_LTIMEOUT_BIT,
849 REQ_F_ASYNC_DATA_BIT,
850 REQ_F_SKIP_LINK_CQES_BIT,
851 REQ_F_SINGLE_POLL_BIT,
852 REQ_F_DOUBLE_POLL_BIT,
853 REQ_F_PARTIAL_IO_BIT,
854 REQ_F_APOLL_MULTISHOT_BIT,
855 /* keep async read/write and isreg together and in order */
856 REQ_F_SUPPORT_NOWAIT_BIT,
859 /* not a real bit, just to check we're not overflowing the space */
865 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
866 /* drain existing IO first */
867 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
869 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
870 /* doesn't sever on completion < 0 */
871 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
873 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
874 /* IOSQE_BUFFER_SELECT */
875 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
876 /* IOSQE_CQE_SKIP_SUCCESS */
877 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
879 /* fail rest of links */
880 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
881 /* on inflight list, should be cancelled and waited on exit reliably */
882 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
883 /* read/write uses file position */
884 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
885 /* must not punt to workers */
886 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
887 /* has or had linked timeout */
888 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
890 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
891 /* already went through poll handler */
892 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
893 /* buffer already selected */
894 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
895 /* buffer selected from ring, needs commit */
896 REQ_F_BUFFER_RING = BIT(REQ_F_BUFFER_RING_BIT),
897 /* completion is deferred through io_comp_state */
898 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
899 /* caller should reissue async */
900 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
901 /* supports async reads/writes */
902 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
904 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
905 /* has creds assigned */
906 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
907 /* skip refcounting if not set */
908 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
909 /* there is a linked timeout that has to be armed */
910 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
911 /* ->async_data allocated */
912 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
913 /* don't post CQEs while failing linked requests */
914 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
915 /* single poll may be active */
916 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
917 /* double poll may active */
918 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
919 /* request has already done partial IO */
920 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
921 /* fast poll multishot mode */
922 REQ_F_APOLL_MULTISHOT = BIT(REQ_F_APOLL_MULTISHOT_BIT),
926 struct io_poll_iocb poll;
927 struct io_poll_iocb *double_poll;
930 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
932 struct io_task_work {
934 struct io_wq_work_node node;
935 struct llist_node fallback_node;
937 io_req_tw_func_t func;
941 IORING_RSRC_FILE = 0,
942 IORING_RSRC_BUFFER = 1,
948 /* fd initially, then cflags for completion */
956 IO_CHECK_CQ_OVERFLOW_BIT,
957 IO_CHECK_CQ_DROPPED_BIT,
961 * NOTE! Each of the iocb union members has the file pointer
962 * as the first entry in their struct definition. So you can
963 * access the file pointer through any of the sub-structs,
964 * or directly as just 'file' in this struct.
970 struct io_poll_iocb poll;
971 struct io_poll_update poll_update;
972 struct io_accept accept;
974 struct io_cancel cancel;
975 struct io_timeout timeout;
976 struct io_timeout_rem timeout_rem;
977 struct io_connect connect;
978 struct io_sr_msg sr_msg;
980 struct io_close close;
981 struct io_rsrc_update rsrc_update;
982 struct io_fadvise fadvise;
983 struct io_madvise madvise;
984 struct io_epoll epoll;
985 struct io_splice splice;
986 struct io_provide_buf pbuf;
987 struct io_statx statx;
988 struct io_shutdown shutdown;
989 struct io_rename rename;
990 struct io_unlink unlink;
991 struct io_mkdir mkdir;
992 struct io_symlink symlink;
993 struct io_hardlink hardlink;
995 struct io_xattr xattr;
996 struct io_socket sock;
998 struct io_uring_cmd uring_cmd;
1002 /* polled IO has completed */
1003 u8 iopoll_completed;
1005 * Can be either a fixed buffer index, or used with provided buffers.
1006 * For the latter, before issue it points to the buffer group ID,
1007 * and after selection it points to the buffer ID itself.
1014 struct io_ring_ctx *ctx;
1015 struct task_struct *task;
1017 struct io_rsrc_node *rsrc_node;
1020 /* store used ubuf, so we can prevent reloading */
1021 struct io_mapped_ubuf *imu;
1023 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
1024 struct io_buffer *kbuf;
1027 * stores buffer ID for ring provided buffers, valid IFF
1028 * REQ_F_BUFFER_RING is set.
1030 struct io_buffer_list *buf_list;
1034 /* used by request caches, completion batching and iopoll */
1035 struct io_wq_work_node comp_list;
1036 /* cache ->apoll->events */
1037 __poll_t apoll_events;
1041 struct io_task_work io_task_work;
1042 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1044 struct hlist_node hash_node;
1050 /* internal polling, see IORING_FEAT_FAST_POLL */
1051 struct async_poll *apoll;
1052 /* opcode allocated if it needs to store data for async defer */
1054 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1055 struct io_kiocb *link;
1056 /* custom credentials, valid IFF REQ_F_CREDS is set */
1057 const struct cred *creds;
1058 struct io_wq_work work;
1061 struct io_tctx_node {
1062 struct list_head ctx_node;
1063 struct task_struct *task;
1064 struct io_ring_ctx *ctx;
1067 struct io_defer_entry {
1068 struct list_head list;
1069 struct io_kiocb *req;
1073 struct io_cancel_data {
1074 struct io_ring_ctx *ctx;
1084 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
1085 * the following sqe if SQE128 is used.
1087 #define uring_cmd_pdu_size(is_sqe128) \
1088 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
1089 offsetof(struct io_uring_sqe, cmd))
1092 /* needs req->file assigned */
1093 unsigned needs_file : 1;
1094 /* should block plug */
1096 /* hash wq insertion if file is a regular file */
1097 unsigned hash_reg_file : 1;
1098 /* unbound wq insertion if file is a non-regular file */
1099 unsigned unbound_nonreg_file : 1;
1100 /* set if opcode supports polled "wait" */
1101 unsigned pollin : 1;
1102 unsigned pollout : 1;
1103 unsigned poll_exclusive : 1;
1104 /* op supports buffer selection */
1105 unsigned buffer_select : 1;
1106 /* do prep async if is going to be punted */
1107 unsigned needs_async_setup : 1;
1108 /* opcode is not supported by this kernel */
1109 unsigned not_supported : 1;
1111 unsigned audit_skip : 1;
1112 /* supports ioprio */
1113 unsigned ioprio : 1;
1114 /* supports iopoll */
1115 unsigned iopoll : 1;
1116 /* size of async data needed, if any */
1117 unsigned short async_size;
1120 static const struct io_op_def io_op_defs[] = {
1126 [IORING_OP_READV] = {
1128 .unbound_nonreg_file = 1,
1131 .needs_async_setup = 1,
1136 .async_size = sizeof(struct io_async_rw),
1138 [IORING_OP_WRITEV] = {
1141 .unbound_nonreg_file = 1,
1143 .needs_async_setup = 1,
1148 .async_size = sizeof(struct io_async_rw),
1150 [IORING_OP_FSYNC] = {
1154 [IORING_OP_READ_FIXED] = {
1156 .unbound_nonreg_file = 1,
1162 .async_size = sizeof(struct io_async_rw),
1164 [IORING_OP_WRITE_FIXED] = {
1167 .unbound_nonreg_file = 1,
1173 .async_size = sizeof(struct io_async_rw),
1175 [IORING_OP_POLL_ADD] = {
1177 .unbound_nonreg_file = 1,
1180 [IORING_OP_POLL_REMOVE] = {
1183 [IORING_OP_SYNC_FILE_RANGE] = {
1187 [IORING_OP_SENDMSG] = {
1189 .unbound_nonreg_file = 1,
1191 .needs_async_setup = 1,
1192 .async_size = sizeof(struct io_async_msghdr),
1194 [IORING_OP_RECVMSG] = {
1196 .unbound_nonreg_file = 1,
1199 .needs_async_setup = 1,
1200 .async_size = sizeof(struct io_async_msghdr),
1202 [IORING_OP_TIMEOUT] = {
1204 .async_size = sizeof(struct io_timeout_data),
1206 [IORING_OP_TIMEOUT_REMOVE] = {
1207 /* used by timeout updates' prep() */
1210 [IORING_OP_ACCEPT] = {
1212 .unbound_nonreg_file = 1,
1214 .poll_exclusive = 1,
1215 .ioprio = 1, /* used for flags */
1217 [IORING_OP_ASYNC_CANCEL] = {
1220 [IORING_OP_LINK_TIMEOUT] = {
1222 .async_size = sizeof(struct io_timeout_data),
1224 [IORING_OP_CONNECT] = {
1226 .unbound_nonreg_file = 1,
1228 .needs_async_setup = 1,
1229 .async_size = sizeof(struct io_async_connect),
1231 [IORING_OP_FALLOCATE] = {
1234 [IORING_OP_OPENAT] = {},
1235 [IORING_OP_CLOSE] = {},
1236 [IORING_OP_FILES_UPDATE] = {
1240 [IORING_OP_STATX] = {
1243 [IORING_OP_READ] = {
1245 .unbound_nonreg_file = 1,
1252 .async_size = sizeof(struct io_async_rw),
1254 [IORING_OP_WRITE] = {
1257 .unbound_nonreg_file = 1,
1263 .async_size = sizeof(struct io_async_rw),
1265 [IORING_OP_FADVISE] = {
1269 [IORING_OP_MADVISE] = {},
1270 [IORING_OP_SEND] = {
1272 .unbound_nonreg_file = 1,
1276 [IORING_OP_RECV] = {
1278 .unbound_nonreg_file = 1,
1283 [IORING_OP_OPENAT2] = {
1285 [IORING_OP_EPOLL_CTL] = {
1286 .unbound_nonreg_file = 1,
1289 [IORING_OP_SPLICE] = {
1292 .unbound_nonreg_file = 1,
1295 [IORING_OP_PROVIDE_BUFFERS] = {
1299 [IORING_OP_REMOVE_BUFFERS] = {
1306 .unbound_nonreg_file = 1,
1309 [IORING_OP_SHUTDOWN] = {
1312 [IORING_OP_RENAMEAT] = {},
1313 [IORING_OP_UNLINKAT] = {},
1314 [IORING_OP_MKDIRAT] = {},
1315 [IORING_OP_SYMLINKAT] = {},
1316 [IORING_OP_LINKAT] = {},
1317 [IORING_OP_MSG_RING] = {
1321 [IORING_OP_FSETXATTR] = {
1324 [IORING_OP_SETXATTR] = {},
1325 [IORING_OP_FGETXATTR] = {
1328 [IORING_OP_GETXATTR] = {},
1329 [IORING_OP_SOCKET] = {
1332 [IORING_OP_URING_CMD] = {
1335 .needs_async_setup = 1,
1336 .async_size = uring_cmd_pdu_size(1),
1340 /* requests with any of those set should undergo io_disarm_next() */
1341 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1342 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1344 static bool io_disarm_next(struct io_kiocb *req);
1345 static void io_uring_del_tctx_node(unsigned long index);
1346 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1347 struct task_struct *task,
1349 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1351 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1352 static void io_dismantle_req(struct io_kiocb *req);
1353 static void io_queue_linked_timeout(struct io_kiocb *req);
1354 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1355 struct io_uring_rsrc_update2 *up,
1357 static void io_clean_op(struct io_kiocb *req);
1358 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1359 unsigned issue_flags);
1360 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1361 static void io_queue_sqe(struct io_kiocb *req);
1362 static void io_rsrc_put_work(struct work_struct *work);
1364 static void io_req_task_queue(struct io_kiocb *req);
1365 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1366 static int io_req_prep_async(struct io_kiocb *req);
1368 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1369 unsigned int issue_flags, u32 slot_index);
1370 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
1371 unsigned int offset);
1372 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1374 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1375 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1376 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1378 static struct kmem_cache *req_cachep;
1380 static const struct file_operations io_uring_fops;
1382 const char *io_uring_get_opcode(u8 opcode)
1384 switch ((enum io_uring_op)opcode) {
1387 case IORING_OP_READV:
1389 case IORING_OP_WRITEV:
1391 case IORING_OP_FSYNC:
1393 case IORING_OP_READ_FIXED:
1394 return "READ_FIXED";
1395 case IORING_OP_WRITE_FIXED:
1396 return "WRITE_FIXED";
1397 case IORING_OP_POLL_ADD:
1399 case IORING_OP_POLL_REMOVE:
1400 return "POLL_REMOVE";
1401 case IORING_OP_SYNC_FILE_RANGE:
1402 return "SYNC_FILE_RANGE";
1403 case IORING_OP_SENDMSG:
1405 case IORING_OP_RECVMSG:
1407 case IORING_OP_TIMEOUT:
1409 case IORING_OP_TIMEOUT_REMOVE:
1410 return "TIMEOUT_REMOVE";
1411 case IORING_OP_ACCEPT:
1413 case IORING_OP_ASYNC_CANCEL:
1414 return "ASYNC_CANCEL";
1415 case IORING_OP_LINK_TIMEOUT:
1416 return "LINK_TIMEOUT";
1417 case IORING_OP_CONNECT:
1419 case IORING_OP_FALLOCATE:
1421 case IORING_OP_OPENAT:
1423 case IORING_OP_CLOSE:
1425 case IORING_OP_FILES_UPDATE:
1426 return "FILES_UPDATE";
1427 case IORING_OP_STATX:
1429 case IORING_OP_READ:
1431 case IORING_OP_WRITE:
1433 case IORING_OP_FADVISE:
1435 case IORING_OP_MADVISE:
1437 case IORING_OP_SEND:
1439 case IORING_OP_RECV:
1441 case IORING_OP_OPENAT2:
1443 case IORING_OP_EPOLL_CTL:
1445 case IORING_OP_SPLICE:
1447 case IORING_OP_PROVIDE_BUFFERS:
1448 return "PROVIDE_BUFFERS";
1449 case IORING_OP_REMOVE_BUFFERS:
1450 return "REMOVE_BUFFERS";
1453 case IORING_OP_SHUTDOWN:
1455 case IORING_OP_RENAMEAT:
1457 case IORING_OP_UNLINKAT:
1459 case IORING_OP_MKDIRAT:
1461 case IORING_OP_SYMLINKAT:
1463 case IORING_OP_LINKAT:
1465 case IORING_OP_MSG_RING:
1467 case IORING_OP_FSETXATTR:
1469 case IORING_OP_SETXATTR:
1471 case IORING_OP_FGETXATTR:
1473 case IORING_OP_GETXATTR:
1475 case IORING_OP_SOCKET:
1477 case IORING_OP_URING_CMD:
1479 case IORING_OP_LAST:
1485 struct sock *io_uring_get_socket(struct file *file)
1487 #if defined(CONFIG_UNIX)
1488 if (file->f_op == &io_uring_fops) {
1489 struct io_ring_ctx *ctx = file->private_data;
1491 return ctx->ring_sock->sk;
1496 EXPORT_SYMBOL(io_uring_get_socket);
1498 #if defined(CONFIG_UNIX)
1499 static inline bool io_file_need_scm(struct file *filp)
1501 #if defined(IO_URING_SCM_ALL)
1504 return !!unix_get_socket(filp);
1508 static inline bool io_file_need_scm(struct file *filp)
1514 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1516 lockdep_assert_held(&ctx->uring_lock);
1517 if (issue_flags & IO_URING_F_UNLOCKED)
1518 mutex_unlock(&ctx->uring_lock);
1521 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1524 * "Normal" inline submissions always hold the uring_lock, since we
1525 * grab it from the system call. Same is true for the SQPOLL offload.
1526 * The only exception is when we've detached the request and issue it
1527 * from an async worker thread, grab the lock for that case.
1529 if (issue_flags & IO_URING_F_UNLOCKED)
1530 mutex_lock(&ctx->uring_lock);
1531 lockdep_assert_held(&ctx->uring_lock);
1534 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1537 mutex_lock(&ctx->uring_lock);
1542 #define io_for_each_link(pos, head) \
1543 for (pos = (head); pos; pos = pos->link)
1546 * Shamelessly stolen from the mm implementation of page reference checking,
1547 * see commit f958d7b528b1 for details.
1549 #define req_ref_zero_or_close_to_overflow(req) \
1550 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1552 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1554 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1555 return atomic_inc_not_zero(&req->refs);
1558 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1560 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1563 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1564 return atomic_dec_and_test(&req->refs);
1567 static inline void req_ref_get(struct io_kiocb *req)
1569 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1570 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1571 atomic_inc(&req->refs);
1574 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1576 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1577 __io_submit_flush_completions(ctx);
1580 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1582 if (!(req->flags & REQ_F_REFCOUNT)) {
1583 req->flags |= REQ_F_REFCOUNT;
1584 atomic_set(&req->refs, nr);
1588 static inline void io_req_set_refcount(struct io_kiocb *req)
1590 __io_req_set_refcount(req, 1);
1593 #define IO_RSRC_REF_BATCH 100
1595 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1597 percpu_ref_put_many(&node->refs, nr);
1600 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1601 struct io_ring_ctx *ctx)
1602 __must_hold(&ctx->uring_lock)
1604 struct io_rsrc_node *node = req->rsrc_node;
1607 if (node == ctx->rsrc_node)
1608 ctx->rsrc_cached_refs++;
1610 io_rsrc_put_node(node, 1);
1614 static inline void io_req_put_rsrc(struct io_kiocb *req)
1617 io_rsrc_put_node(req->rsrc_node, 1);
1620 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1621 __must_hold(&ctx->uring_lock)
1623 if (ctx->rsrc_cached_refs) {
1624 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1625 ctx->rsrc_cached_refs = 0;
1629 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1630 __must_hold(&ctx->uring_lock)
1632 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1633 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1636 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1637 struct io_ring_ctx *ctx,
1638 unsigned int issue_flags)
1640 if (!req->rsrc_node) {
1641 req->rsrc_node = ctx->rsrc_node;
1643 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1644 lockdep_assert_held(&ctx->uring_lock);
1645 ctx->rsrc_cached_refs--;
1646 if (unlikely(ctx->rsrc_cached_refs < 0))
1647 io_rsrc_refs_refill(ctx);
1649 percpu_ref_get(&req->rsrc_node->refs);
1654 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1656 if (req->flags & REQ_F_BUFFER_RING) {
1658 req->buf_list->head++;
1659 req->flags &= ~REQ_F_BUFFER_RING;
1661 list_add(&req->kbuf->list, list);
1662 req->flags &= ~REQ_F_BUFFER_SELECTED;
1665 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1668 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1670 lockdep_assert_held(&req->ctx->completion_lock);
1672 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1674 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1677 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1678 unsigned issue_flags)
1680 unsigned int cflags;
1682 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1686 * We can add this buffer back to two lists:
1688 * 1) The io_buffers_cache list. This one is protected by the
1689 * ctx->uring_lock. If we already hold this lock, add back to this
1690 * list as we can grab it from issue as well.
1691 * 2) The io_buffers_comp list. This one is protected by the
1692 * ctx->completion_lock.
1694 * We migrate buffers from the comp_list to the issue cache list
1697 if (req->flags & REQ_F_BUFFER_RING) {
1698 /* no buffers to recycle for this case */
1699 cflags = __io_put_kbuf(req, NULL);
1700 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1701 struct io_ring_ctx *ctx = req->ctx;
1703 spin_lock(&ctx->completion_lock);
1704 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1705 spin_unlock(&ctx->completion_lock);
1707 lockdep_assert_held(&req->ctx->uring_lock);
1709 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1715 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1718 if (ctx->io_bl && bgid < BGID_ARRAY)
1719 return &ctx->io_bl[bgid];
1721 return xa_load(&ctx->io_bl_xa, bgid);
1724 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1726 struct io_ring_ctx *ctx = req->ctx;
1727 struct io_buffer_list *bl;
1728 struct io_buffer *buf;
1730 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1732 /* don't recycle if we already did IO to this buffer */
1733 if (req->flags & REQ_F_PARTIAL_IO)
1736 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1737 * the flag and hence ensure that bl->head doesn't get incremented.
1738 * If the tail has already been incremented, hang on to it.
1740 if (req->flags & REQ_F_BUFFER_RING) {
1741 if (req->buf_list) {
1742 req->buf_index = req->buf_list->bgid;
1743 req->flags &= ~REQ_F_BUFFER_RING;
1748 io_ring_submit_lock(ctx, issue_flags);
1751 bl = io_buffer_get_list(ctx, buf->bgid);
1752 list_add(&buf->list, &bl->buf_list);
1753 req->flags &= ~REQ_F_BUFFER_SELECTED;
1754 req->buf_index = buf->bgid;
1756 io_ring_submit_unlock(ctx, issue_flags);
1759 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1761 __must_hold(&req->ctx->timeout_lock)
1763 struct io_kiocb *req;
1765 if (task && head->task != task)
1770 io_for_each_link(req, head) {
1771 if (req->flags & REQ_F_INFLIGHT)
1777 static bool io_match_linked(struct io_kiocb *head)
1779 struct io_kiocb *req;
1781 io_for_each_link(req, head) {
1782 if (req->flags & REQ_F_INFLIGHT)
1789 * As io_match_task() but protected against racing with linked timeouts.
1790 * User must not hold timeout_lock.
1792 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1797 if (task && head->task != task)
1802 if (head->flags & REQ_F_LINK_TIMEOUT) {
1803 struct io_ring_ctx *ctx = head->ctx;
1805 /* protect against races with linked timeouts */
1806 spin_lock_irq(&ctx->timeout_lock);
1807 matched = io_match_linked(head);
1808 spin_unlock_irq(&ctx->timeout_lock);
1810 matched = io_match_linked(head);
1815 static inline bool req_has_async_data(struct io_kiocb *req)
1817 return req->flags & REQ_F_ASYNC_DATA;
1820 static inline void req_set_fail(struct io_kiocb *req)
1822 req->flags |= REQ_F_FAIL;
1823 if (req->flags & REQ_F_CQE_SKIP) {
1824 req->flags &= ~REQ_F_CQE_SKIP;
1825 req->flags |= REQ_F_SKIP_LINK_CQES;
1829 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1835 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1837 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1840 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1842 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1844 complete(&ctx->ref_comp);
1847 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1849 return !req->timeout.off;
1852 static __cold void io_fallback_req_func(struct work_struct *work)
1854 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1855 fallback_work.work);
1856 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1857 struct io_kiocb *req, *tmp;
1858 bool locked = false;
1860 percpu_ref_get(&ctx->refs);
1861 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1862 req->io_task_work.func(req, &locked);
1865 io_submit_flush_completions(ctx);
1866 mutex_unlock(&ctx->uring_lock);
1868 percpu_ref_put(&ctx->refs);
1871 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1873 struct io_ring_ctx *ctx;
1876 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1880 xa_init(&ctx->io_bl_xa);
1883 * Use 5 bits less than the max cq entries, that should give us around
1884 * 32 entries per hash list if totally full and uniformly spread.
1886 hash_bits = ilog2(p->cq_entries);
1890 ctx->cancel_hash_bits = hash_bits;
1891 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1893 if (!ctx->cancel_hash)
1895 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1897 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1898 if (!ctx->dummy_ubuf)
1900 /* set invalid range, so io_import_fixed() fails meeting it */
1901 ctx->dummy_ubuf->ubuf = -1UL;
1903 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1904 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1907 ctx->flags = p->flags;
1908 init_waitqueue_head(&ctx->sqo_sq_wait);
1909 INIT_LIST_HEAD(&ctx->sqd_list);
1910 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1911 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1912 INIT_LIST_HEAD(&ctx->apoll_cache);
1913 init_completion(&ctx->ref_comp);
1914 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1915 mutex_init(&ctx->uring_lock);
1916 init_waitqueue_head(&ctx->cq_wait);
1917 spin_lock_init(&ctx->completion_lock);
1918 spin_lock_init(&ctx->timeout_lock);
1919 INIT_WQ_LIST(&ctx->iopoll_list);
1920 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1921 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1922 INIT_LIST_HEAD(&ctx->defer_list);
1923 INIT_LIST_HEAD(&ctx->timeout_list);
1924 INIT_LIST_HEAD(&ctx->ltimeout_list);
1925 spin_lock_init(&ctx->rsrc_ref_lock);
1926 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1927 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1928 init_llist_head(&ctx->rsrc_put_llist);
1929 INIT_LIST_HEAD(&ctx->tctx_list);
1930 ctx->submit_state.free_list.next = NULL;
1931 INIT_WQ_LIST(&ctx->locked_free_list);
1932 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1933 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1936 kfree(ctx->dummy_ubuf);
1937 kfree(ctx->cancel_hash);
1939 xa_destroy(&ctx->io_bl_xa);
1944 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1946 struct io_rings *r = ctx->rings;
1948 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1952 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1954 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1955 struct io_ring_ctx *ctx = req->ctx;
1957 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1963 static inline bool io_req_ffs_set(struct io_kiocb *req)
1965 return req->flags & REQ_F_FIXED_FILE;
1968 static inline void io_req_track_inflight(struct io_kiocb *req)
1970 if (!(req->flags & REQ_F_INFLIGHT)) {
1971 req->flags |= REQ_F_INFLIGHT;
1972 atomic_inc(¤t->io_uring->inflight_tracked);
1976 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1978 if (WARN_ON_ONCE(!req->link))
1981 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1982 req->flags |= REQ_F_LINK_TIMEOUT;
1984 /* linked timeouts should have two refs once prep'ed */
1985 io_req_set_refcount(req);
1986 __io_req_set_refcount(req->link, 2);
1990 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1992 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1994 return __io_prep_linked_timeout(req);
1997 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1999 io_queue_linked_timeout(__io_prep_linked_timeout(req));
2002 static inline void io_arm_ltimeout(struct io_kiocb *req)
2004 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
2005 __io_arm_ltimeout(req);
2008 static void io_prep_async_work(struct io_kiocb *req)
2010 const struct io_op_def *def = &io_op_defs[req->opcode];
2011 struct io_ring_ctx *ctx = req->ctx;
2013 if (!(req->flags & REQ_F_CREDS)) {
2014 req->flags |= REQ_F_CREDS;
2015 req->creds = get_current_cred();
2018 req->work.list.next = NULL;
2019 req->work.flags = 0;
2020 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
2021 if (req->flags & REQ_F_FORCE_ASYNC)
2022 req->work.flags |= IO_WQ_WORK_CONCURRENT;
2024 if (req->flags & REQ_F_ISREG) {
2025 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
2026 io_wq_hash_work(&req->work, file_inode(req->file));
2027 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
2028 if (def->unbound_nonreg_file)
2029 req->work.flags |= IO_WQ_WORK_UNBOUND;
2033 static void io_prep_async_link(struct io_kiocb *req)
2035 struct io_kiocb *cur;
2037 if (req->flags & REQ_F_LINK_TIMEOUT) {
2038 struct io_ring_ctx *ctx = req->ctx;
2040 spin_lock_irq(&ctx->timeout_lock);
2041 io_for_each_link(cur, req)
2042 io_prep_async_work(cur);
2043 spin_unlock_irq(&ctx->timeout_lock);
2045 io_for_each_link(cur, req)
2046 io_prep_async_work(cur);
2050 static inline void io_req_add_compl_list(struct io_kiocb *req)
2052 struct io_submit_state *state = &req->ctx->submit_state;
2054 if (!(req->flags & REQ_F_CQE_SKIP))
2055 state->flush_cqes = true;
2056 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
2059 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
2061 struct io_kiocb *link = io_prep_linked_timeout(req);
2062 struct io_uring_task *tctx = req->task->io_uring;
2065 BUG_ON(!tctx->io_wq);
2067 /* init ->work of the whole link before punting */
2068 io_prep_async_link(req);
2071 * Not expected to happen, but if we do have a bug where this _can_
2072 * happen, catch it here and ensure the request is marked as
2073 * canceled. That will make io-wq go through the usual work cancel
2074 * procedure rather than attempt to run this request (or create a new
2077 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
2078 req->work.flags |= IO_WQ_WORK_CANCEL;
2080 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
2081 req->opcode, req->flags, &req->work,
2082 io_wq_is_hashed(&req->work));
2083 io_wq_enqueue(tctx->io_wq, &req->work);
2085 io_queue_linked_timeout(link);
2088 static void io_kill_timeout(struct io_kiocb *req, int status)
2089 __must_hold(&req->ctx->completion_lock)
2090 __must_hold(&req->ctx->timeout_lock)
2092 struct io_timeout_data *io = req->async_data;
2094 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2097 atomic_set(&req->ctx->cq_timeouts,
2098 atomic_read(&req->ctx->cq_timeouts) + 1);
2099 list_del_init(&req->timeout.list);
2100 io_req_tw_post_queue(req, status, 0);
2104 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
2106 while (!list_empty(&ctx->defer_list)) {
2107 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
2108 struct io_defer_entry, list);
2110 if (req_need_defer(de->req, de->seq))
2112 list_del_init(&de->list);
2113 io_req_task_queue(de->req);
2118 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
2119 __must_hold(&ctx->completion_lock)
2121 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
2122 struct io_kiocb *req, *tmp;
2124 spin_lock_irq(&ctx->timeout_lock);
2125 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
2126 u32 events_needed, events_got;
2128 if (io_is_timeout_noseq(req))
2132 * Since seq can easily wrap around over time, subtract
2133 * the last seq at which timeouts were flushed before comparing.
2134 * Assuming not more than 2^31-1 events have happened since,
2135 * these subtractions won't have wrapped, so we can check if
2136 * target is in [last_seq, current_seq] by comparing the two.
2138 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
2139 events_got = seq - ctx->cq_last_tm_flush;
2140 if (events_got < events_needed)
2143 io_kill_timeout(req, 0);
2145 ctx->cq_last_tm_flush = seq;
2146 spin_unlock_irq(&ctx->timeout_lock);
2149 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
2151 /* order cqe stores with ring update */
2152 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
2155 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
2157 if (ctx->off_timeout_used || ctx->drain_active) {
2158 spin_lock(&ctx->completion_lock);
2159 if (ctx->off_timeout_used)
2160 io_flush_timeouts(ctx);
2161 if (ctx->drain_active)
2162 io_queue_deferred(ctx);
2163 io_commit_cqring(ctx);
2164 spin_unlock(&ctx->completion_lock);
2167 io_eventfd_signal(ctx);
2170 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
2172 struct io_rings *r = ctx->rings;
2174 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
2177 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
2179 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
2183 * writes to the cq entry need to come after reading head; the
2184 * control dependency is enough as we're using WRITE_ONCE to
2187 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
2189 struct io_rings *rings = ctx->rings;
2190 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
2191 unsigned int shift = 0;
2192 unsigned int free, queued, len;
2194 if (ctx->flags & IORING_SETUP_CQE32)
2197 /* userspace may cheat modifying the tail, be safe and do min */
2198 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2199 free = ctx->cq_entries - queued;
2200 /* we need a contiguous range, limit based on the current array offset */
2201 len = min(free, ctx->cq_entries - off);
2205 ctx->cached_cq_tail++;
2206 ctx->cqe_cached = &rings->cqes[off];
2207 ctx->cqe_sentinel = ctx->cqe_cached + len;
2209 return &rings->cqes[off << shift];
2212 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2214 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2215 struct io_uring_cqe *cqe = ctx->cqe_cached;
2217 if (ctx->flags & IORING_SETUP_CQE32) {
2218 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2223 ctx->cached_cq_tail++;
2228 return __io_get_cqe(ctx);
2231 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2233 struct io_ev_fd *ev_fd;
2237 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2238 * and eventfd_signal
2240 ev_fd = rcu_dereference(ctx->io_ev_fd);
2243 * Check again if ev_fd exists incase an io_eventfd_unregister call
2244 * completed between the NULL check of ctx->io_ev_fd at the start of
2245 * the function and rcu_read_lock.
2247 if (unlikely(!ev_fd))
2249 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2252 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2253 eventfd_signal(ev_fd->cq_ev_fd, 1);
2258 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2261 * wake_up_all() may seem excessive, but io_wake_function() and
2262 * io_should_wake() handle the termination of the loop and only
2263 * wake as many waiters as we need to.
2265 if (wq_has_sleeper(&ctx->cq_wait))
2266 wake_up_all(&ctx->cq_wait);
2270 * This should only get called when at least one event has been posted.
2271 * Some applications rely on the eventfd notification count only changing
2272 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2273 * 1:1 relationship between how many times this function is called (and
2274 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2276 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2278 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2280 __io_commit_cqring_flush(ctx);
2282 io_cqring_wake(ctx);
2285 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2287 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2289 __io_commit_cqring_flush(ctx);
2291 if (ctx->flags & IORING_SETUP_SQPOLL)
2292 io_cqring_wake(ctx);
2295 /* Returns true if there are no backlogged entries after the flush */
2296 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2298 bool all_flushed, posted;
2299 size_t cqe_size = sizeof(struct io_uring_cqe);
2301 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2304 if (ctx->flags & IORING_SETUP_CQE32)
2308 spin_lock(&ctx->completion_lock);
2309 while (!list_empty(&ctx->cq_overflow_list)) {
2310 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2311 struct io_overflow_cqe *ocqe;
2315 ocqe = list_first_entry(&ctx->cq_overflow_list,
2316 struct io_overflow_cqe, list);
2318 memcpy(cqe, &ocqe->cqe, cqe_size);
2320 io_account_cq_overflow(ctx);
2323 list_del(&ocqe->list);
2327 all_flushed = list_empty(&ctx->cq_overflow_list);
2329 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2330 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2333 io_commit_cqring(ctx);
2334 spin_unlock(&ctx->completion_lock);
2336 io_cqring_ev_posted(ctx);
2340 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2344 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2345 /* iopoll syncs against uring_lock, not completion_lock */
2346 if (ctx->flags & IORING_SETUP_IOPOLL)
2347 mutex_lock(&ctx->uring_lock);
2348 ret = __io_cqring_overflow_flush(ctx, false);
2349 if (ctx->flags & IORING_SETUP_IOPOLL)
2350 mutex_unlock(&ctx->uring_lock);
2356 static void __io_put_task(struct task_struct *task, int nr)
2358 struct io_uring_task *tctx = task->io_uring;
2360 percpu_counter_sub(&tctx->inflight, nr);
2361 if (unlikely(atomic_read(&tctx->in_idle)))
2362 wake_up(&tctx->wait);
2363 put_task_struct_many(task, nr);
2366 /* must to be called somewhat shortly after putting a request */
2367 static inline void io_put_task(struct task_struct *task, int nr)
2369 if (likely(task == current))
2370 task->io_uring->cached_refs += nr;
2372 __io_put_task(task, nr);
2375 static void io_task_refs_refill(struct io_uring_task *tctx)
2377 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2379 percpu_counter_add(&tctx->inflight, refill);
2380 refcount_add(refill, ¤t->usage);
2381 tctx->cached_refs += refill;
2384 static inline void io_get_task_refs(int nr)
2386 struct io_uring_task *tctx = current->io_uring;
2388 tctx->cached_refs -= nr;
2389 if (unlikely(tctx->cached_refs < 0))
2390 io_task_refs_refill(tctx);
2393 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2395 struct io_uring_task *tctx = task->io_uring;
2396 unsigned int refs = tctx->cached_refs;
2399 tctx->cached_refs = 0;
2400 percpu_counter_sub(&tctx->inflight, refs);
2401 put_task_struct_many(task, refs);
2405 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2406 s32 res, u32 cflags, u64 extra1,
2409 struct io_overflow_cqe *ocqe;
2410 size_t ocq_size = sizeof(struct io_overflow_cqe);
2411 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2414 ocq_size += sizeof(struct io_uring_cqe);
2416 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2417 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2420 * If we're in ring overflow flush mode, or in task cancel mode,
2421 * or cannot allocate an overflow entry, then we need to drop it
2424 io_account_cq_overflow(ctx);
2425 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2428 if (list_empty(&ctx->cq_overflow_list)) {
2429 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2430 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2433 ocqe->cqe.user_data = user_data;
2434 ocqe->cqe.res = res;
2435 ocqe->cqe.flags = cflags;
2437 ocqe->cqe.big_cqe[0] = extra1;
2438 ocqe->cqe.big_cqe[1] = extra2;
2440 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2444 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2445 s32 res, u32 cflags)
2447 struct io_uring_cqe *cqe;
2450 * If we can't get a cq entry, userspace overflowed the
2451 * submission (by quite a lot). Increment the overflow count in
2454 cqe = io_get_cqe(ctx);
2456 WRITE_ONCE(cqe->user_data, user_data);
2457 WRITE_ONCE(cqe->res, res);
2458 WRITE_ONCE(cqe->flags, cflags);
2461 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2464 static inline bool __io_fill_cqe_req_filled(struct io_ring_ctx *ctx,
2465 struct io_kiocb *req)
2467 struct io_uring_cqe *cqe;
2469 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2470 req->cqe.res, req->cqe.flags, 0, 0);
2473 * If we can't get a cq entry, userspace overflowed the
2474 * submission (by quite a lot). Increment the overflow count in
2477 cqe = io_get_cqe(ctx);
2479 memcpy(cqe, &req->cqe, sizeof(*cqe));
2482 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2483 req->cqe.res, req->cqe.flags, 0, 0);
2486 static inline bool __io_fill_cqe32_req_filled(struct io_ring_ctx *ctx,
2487 struct io_kiocb *req)
2489 struct io_uring_cqe *cqe;
2490 u64 extra1 = req->extra1;
2491 u64 extra2 = req->extra2;
2493 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2494 req->cqe.res, req->cqe.flags, extra1, extra2);
2497 * If we can't get a cq entry, userspace overflowed the
2498 * submission (by quite a lot). Increment the overflow count in
2501 cqe = io_get_cqe(ctx);
2503 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2504 cqe->big_cqe[0] = extra1;
2505 cqe->big_cqe[1] = extra2;
2509 return io_cqring_event_overflow(ctx, req->cqe.user_data, req->cqe.res,
2510 req->cqe.flags, extra1, extra2);
2513 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2515 trace_io_uring_complete(req->ctx, req, req->cqe.user_data, res, cflags, 0, 0);
2516 return __io_fill_cqe(req->ctx, req->cqe.user_data, res, cflags);
2519 static inline void __io_fill_cqe32_req(struct io_kiocb *req, s32 res, u32 cflags,
2520 u64 extra1, u64 extra2)
2522 struct io_ring_ctx *ctx = req->ctx;
2523 struct io_uring_cqe *cqe;
2525 if (WARN_ON_ONCE(!(ctx->flags & IORING_SETUP_CQE32)))
2527 if (req->flags & REQ_F_CQE_SKIP)
2530 trace_io_uring_complete(ctx, req, req->cqe.user_data, res, cflags,
2534 * If we can't get a cq entry, userspace overflowed the
2535 * submission (by quite a lot). Increment the overflow count in
2538 cqe = io_get_cqe(ctx);
2540 WRITE_ONCE(cqe->user_data, req->cqe.user_data);
2541 WRITE_ONCE(cqe->res, res);
2542 WRITE_ONCE(cqe->flags, cflags);
2543 WRITE_ONCE(cqe->big_cqe[0], extra1);
2544 WRITE_ONCE(cqe->big_cqe[1], extra2);
2548 io_cqring_event_overflow(ctx, req->cqe.user_data, res, cflags, extra1, extra2);
2551 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2552 s32 res, u32 cflags)
2555 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2556 return __io_fill_cqe(ctx, user_data, res, cflags);
2559 static void __io_req_complete_put(struct io_kiocb *req)
2562 * If we're the last reference to this request, add to our locked
2565 if (req_ref_put_and_test(req)) {
2566 struct io_ring_ctx *ctx = req->ctx;
2568 if (req->flags & IO_REQ_LINK_FLAGS) {
2569 if (req->flags & IO_DISARM_MASK)
2570 io_disarm_next(req);
2572 io_req_task_queue(req->link);
2576 io_req_put_rsrc(req);
2578 * Selected buffer deallocation in io_clean_op() assumes that
2579 * we don't hold ->completion_lock. Clean them here to avoid
2582 io_put_kbuf_comp(req);
2583 io_dismantle_req(req);
2584 io_put_task(req->task, 1);
2585 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2586 ctx->locked_free_nr++;
2590 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2593 if (!(req->flags & REQ_F_CQE_SKIP))
2594 __io_fill_cqe_req(req, res, cflags);
2595 __io_req_complete_put(req);
2598 static void __io_req_complete_post32(struct io_kiocb *req, s32 res,
2599 u32 cflags, u64 extra1, u64 extra2)
2601 if (!(req->flags & REQ_F_CQE_SKIP))
2602 __io_fill_cqe32_req(req, res, cflags, extra1, extra2);
2603 __io_req_complete_put(req);
2606 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2608 struct io_ring_ctx *ctx = req->ctx;
2610 spin_lock(&ctx->completion_lock);
2611 __io_req_complete_post(req, res, cflags);
2612 io_commit_cqring(ctx);
2613 spin_unlock(&ctx->completion_lock);
2614 io_cqring_ev_posted(ctx);
2617 static void io_req_complete_post32(struct io_kiocb *req, s32 res,
2618 u32 cflags, u64 extra1, u64 extra2)
2620 struct io_ring_ctx *ctx = req->ctx;
2622 spin_lock(&ctx->completion_lock);
2623 __io_req_complete_post32(req, res, cflags, extra1, extra2);
2624 io_commit_cqring(ctx);
2625 spin_unlock(&ctx->completion_lock);
2626 io_cqring_ev_posted(ctx);
2629 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2633 req->cqe.flags = cflags;
2634 req->flags |= REQ_F_COMPLETE_INLINE;
2637 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2638 s32 res, u32 cflags)
2640 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2641 io_req_complete_state(req, res, cflags);
2643 io_req_complete_post(req, res, cflags);
2646 static inline void __io_req_complete32(struct io_kiocb *req,
2647 unsigned int issue_flags, s32 res,
2648 u32 cflags, u64 extra1, u64 extra2)
2650 if (issue_flags & IO_URING_F_COMPLETE_DEFER) {
2651 io_req_complete_state(req, res, cflags);
2652 req->extra1 = extra1;
2653 req->extra2 = extra2;
2655 io_req_complete_post32(req, res, cflags, extra1, extra2);
2659 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2663 __io_req_complete(req, 0, res, 0);
2666 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2669 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2673 * Don't initialise the fields below on every allocation, but do that in
2674 * advance and keep them valid across allocations.
2676 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2680 req->async_data = NULL;
2681 /* not necessary, but safer to zero */
2685 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2686 struct io_submit_state *state)
2688 spin_lock(&ctx->completion_lock);
2689 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2690 ctx->locked_free_nr = 0;
2691 spin_unlock(&ctx->completion_lock);
2694 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2696 return !ctx->submit_state.free_list.next;
2700 * A request might get retired back into the request caches even before opcode
2701 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2702 * Because of that, io_alloc_req() should be called only under ->uring_lock
2703 * and with extra caution to not get a request that is still worked on.
2705 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2706 __must_hold(&ctx->uring_lock)
2708 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2709 void *reqs[IO_REQ_ALLOC_BATCH];
2713 * If we have more than a batch's worth of requests in our IRQ side
2714 * locked cache, grab the lock and move them over to our submission
2717 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2718 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2719 if (!io_req_cache_empty(ctx))
2723 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2726 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2727 * retry single alloc to be on the safe side.
2729 if (unlikely(ret <= 0)) {
2730 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2736 percpu_ref_get_many(&ctx->refs, ret);
2737 for (i = 0; i < ret; i++) {
2738 struct io_kiocb *req = reqs[i];
2740 io_preinit_req(req, ctx);
2741 io_req_add_to_cache(req, ctx);
2746 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2748 if (unlikely(io_req_cache_empty(ctx)))
2749 return __io_alloc_req_refill(ctx);
2753 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2755 struct io_wq_work_node *node;
2757 node = wq_stack_extract(&ctx->submit_state.free_list);
2758 return container_of(node, struct io_kiocb, comp_list);
2761 static inline void io_put_file(struct file *file)
2767 static inline void io_dismantle_req(struct io_kiocb *req)
2769 unsigned int flags = req->flags;
2771 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2773 if (!(flags & REQ_F_FIXED_FILE))
2774 io_put_file(req->file);
2777 static __cold void io_free_req(struct io_kiocb *req)
2779 struct io_ring_ctx *ctx = req->ctx;
2781 io_req_put_rsrc(req);
2782 io_dismantle_req(req);
2783 io_put_task(req->task, 1);
2785 spin_lock(&ctx->completion_lock);
2786 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2787 ctx->locked_free_nr++;
2788 spin_unlock(&ctx->completion_lock);
2791 static inline void io_remove_next_linked(struct io_kiocb *req)
2793 struct io_kiocb *nxt = req->link;
2795 req->link = nxt->link;
2799 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2800 __must_hold(&req->ctx->completion_lock)
2801 __must_hold(&req->ctx->timeout_lock)
2803 struct io_kiocb *link = req->link;
2805 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2806 struct io_timeout_data *io = link->async_data;
2808 io_remove_next_linked(req);
2809 link->timeout.head = NULL;
2810 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2811 list_del(&link->timeout.list);
2818 static void io_fail_links(struct io_kiocb *req)
2819 __must_hold(&req->ctx->completion_lock)
2821 struct io_kiocb *nxt, *link = req->link;
2822 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2826 long res = -ECANCELED;
2828 if (link->flags & REQ_F_FAIL)
2829 res = link->cqe.res;
2834 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2838 link->flags |= REQ_F_CQE_SKIP;
2840 link->flags &= ~REQ_F_CQE_SKIP;
2841 __io_req_complete_post(link, res, 0);
2846 static bool io_disarm_next(struct io_kiocb *req)
2847 __must_hold(&req->ctx->completion_lock)
2849 struct io_kiocb *link = NULL;
2850 bool posted = false;
2852 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2854 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2855 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2856 io_remove_next_linked(req);
2857 io_req_tw_post_queue(link, -ECANCELED, 0);
2860 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2861 struct io_ring_ctx *ctx = req->ctx;
2863 spin_lock_irq(&ctx->timeout_lock);
2864 link = io_disarm_linked_timeout(req);
2865 spin_unlock_irq(&ctx->timeout_lock);
2868 io_req_tw_post_queue(link, -ECANCELED, 0);
2871 if (unlikely((req->flags & REQ_F_FAIL) &&
2872 !(req->flags & REQ_F_HARDLINK))) {
2873 posted |= (req->link != NULL);
2879 static void __io_req_find_next_prep(struct io_kiocb *req)
2881 struct io_ring_ctx *ctx = req->ctx;
2884 spin_lock(&ctx->completion_lock);
2885 posted = io_disarm_next(req);
2886 io_commit_cqring(ctx);
2887 spin_unlock(&ctx->completion_lock);
2889 io_cqring_ev_posted(ctx);
2892 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2894 struct io_kiocb *nxt;
2897 * If LINK is set, we have dependent requests in this chain. If we
2898 * didn't fail this request, queue the first one up, moving any other
2899 * dependencies to the next request. In case of failure, fail the rest
2902 if (unlikely(req->flags & IO_DISARM_MASK))
2903 __io_req_find_next_prep(req);
2909 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2913 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2914 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2916 io_submit_flush_completions(ctx);
2917 mutex_unlock(&ctx->uring_lock);
2920 percpu_ref_put(&ctx->refs);
2923 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2925 io_commit_cqring(ctx);
2926 spin_unlock(&ctx->completion_lock);
2927 io_cqring_ev_posted(ctx);
2930 static void handle_prev_tw_list(struct io_wq_work_node *node,
2931 struct io_ring_ctx **ctx, bool *uring_locked)
2933 if (*ctx && !*uring_locked)
2934 spin_lock(&(*ctx)->completion_lock);
2937 struct io_wq_work_node *next = node->next;
2938 struct io_kiocb *req = container_of(node, struct io_kiocb,
2941 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2943 if (req->ctx != *ctx) {
2944 if (unlikely(!*uring_locked && *ctx))
2945 ctx_commit_and_unlock(*ctx);
2947 ctx_flush_and_put(*ctx, uring_locked);
2949 /* if not contended, grab and improve batching */
2950 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2951 percpu_ref_get(&(*ctx)->refs);
2952 if (unlikely(!*uring_locked))
2953 spin_lock(&(*ctx)->completion_lock);
2955 if (likely(*uring_locked))
2956 req->io_task_work.func(req, uring_locked);
2958 __io_req_complete_post(req, req->cqe.res,
2959 io_put_kbuf_comp(req));
2963 if (unlikely(!*uring_locked))
2964 ctx_commit_and_unlock(*ctx);
2967 static void handle_tw_list(struct io_wq_work_node *node,
2968 struct io_ring_ctx **ctx, bool *locked)
2971 struct io_wq_work_node *next = node->next;
2972 struct io_kiocb *req = container_of(node, struct io_kiocb,
2975 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2977 if (req->ctx != *ctx) {
2978 ctx_flush_and_put(*ctx, locked);
2980 /* if not contended, grab and improve batching */
2981 *locked = mutex_trylock(&(*ctx)->uring_lock);
2982 percpu_ref_get(&(*ctx)->refs);
2984 req->io_task_work.func(req, locked);
2989 static void tctx_task_work(struct callback_head *cb)
2991 bool uring_locked = false;
2992 struct io_ring_ctx *ctx = NULL;
2993 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2997 struct io_wq_work_node *node1, *node2;
2999 spin_lock_irq(&tctx->task_lock);
3000 node1 = tctx->prio_task_list.first;
3001 node2 = tctx->task_list.first;
3002 INIT_WQ_LIST(&tctx->task_list);
3003 INIT_WQ_LIST(&tctx->prio_task_list);
3004 if (!node2 && !node1)
3005 tctx->task_running = false;
3006 spin_unlock_irq(&tctx->task_lock);
3007 if (!node2 && !node1)
3011 handle_prev_tw_list(node1, &ctx, &uring_locked);
3013 handle_tw_list(node2, &ctx, &uring_locked);
3016 if (data_race(!tctx->task_list.first) &&
3017 data_race(!tctx->prio_task_list.first) && uring_locked)
3018 io_submit_flush_completions(ctx);
3021 ctx_flush_and_put(ctx, &uring_locked);
3023 /* relaxed read is enough as only the task itself sets ->in_idle */
3024 if (unlikely(atomic_read(&tctx->in_idle)))
3025 io_uring_drop_tctx_refs(current);
3028 static void __io_req_task_work_add(struct io_kiocb *req,
3029 struct io_uring_task *tctx,
3030 struct io_wq_work_list *list)
3032 struct io_ring_ctx *ctx = req->ctx;
3033 struct io_wq_work_node *node;
3034 unsigned long flags;
3037 spin_lock_irqsave(&tctx->task_lock, flags);
3038 wq_list_add_tail(&req->io_task_work.node, list);
3039 running = tctx->task_running;
3041 tctx->task_running = true;
3042 spin_unlock_irqrestore(&tctx->task_lock, flags);
3044 /* task_work already pending, we're done */
3048 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
3049 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
3051 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
3054 spin_lock_irqsave(&tctx->task_lock, flags);
3055 tctx->task_running = false;
3056 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
3057 spin_unlock_irqrestore(&tctx->task_lock, flags);
3060 req = container_of(node, struct io_kiocb, io_task_work.node);
3062 if (llist_add(&req->io_task_work.fallback_node,
3063 &req->ctx->fallback_llist))
3064 schedule_delayed_work(&req->ctx->fallback_work, 1);
3068 static void io_req_task_work_add(struct io_kiocb *req)
3070 struct io_uring_task *tctx = req->task->io_uring;
3072 __io_req_task_work_add(req, tctx, &tctx->task_list);
3075 static void io_req_task_prio_work_add(struct io_kiocb *req)
3077 struct io_uring_task *tctx = req->task->io_uring;
3079 if (req->ctx->flags & IORING_SETUP_SQPOLL)
3080 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
3082 __io_req_task_work_add(req, tctx, &tctx->task_list);
3085 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
3087 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
3090 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
3093 req->cqe.flags = cflags;
3094 req->io_task_work.func = io_req_tw_post;
3095 io_req_task_work_add(req);
3098 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
3100 /* not needed for normal modes, but SQPOLL depends on it */
3101 io_tw_lock(req->ctx, locked);
3102 io_req_complete_failed(req, req->cqe.res);
3105 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
3107 io_tw_lock(req->ctx, locked);
3108 /* req->task == current here, checking PF_EXITING is safe */
3109 if (likely(!(req->task->flags & PF_EXITING)))
3112 io_req_complete_failed(req, -EFAULT);
3115 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
3118 req->io_task_work.func = io_req_task_cancel;
3119 io_req_task_work_add(req);
3122 static void io_req_task_queue(struct io_kiocb *req)
3124 req->io_task_work.func = io_req_task_submit;
3125 io_req_task_work_add(req);
3128 static void io_req_task_queue_reissue(struct io_kiocb *req)
3130 req->io_task_work.func = io_queue_iowq;
3131 io_req_task_work_add(req);
3134 static void io_queue_next(struct io_kiocb *req)
3136 struct io_kiocb *nxt = io_req_find_next(req);
3139 io_req_task_queue(nxt);
3142 static void io_free_batch_list(struct io_ring_ctx *ctx,
3143 struct io_wq_work_node *node)
3144 __must_hold(&ctx->uring_lock)
3146 struct task_struct *task = NULL;
3150 struct io_kiocb *req = container_of(node, struct io_kiocb,
3153 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
3154 if (req->flags & REQ_F_REFCOUNT) {
3155 node = req->comp_list.next;
3156 if (!req_ref_put_and_test(req))
3159 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3160 struct async_poll *apoll = req->apoll;
3162 if (apoll->double_poll)
3163 kfree(apoll->double_poll);
3164 list_add(&apoll->poll.wait.entry,
3166 req->flags &= ~REQ_F_POLLED;
3168 if (req->flags & IO_REQ_LINK_FLAGS)
3170 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
3173 if (!(req->flags & REQ_F_FIXED_FILE))
3174 io_put_file(req->file);
3176 io_req_put_rsrc_locked(req, ctx);
3178 if (req->task != task) {
3180 io_put_task(task, task_refs);
3185 node = req->comp_list.next;
3186 io_req_add_to_cache(req, ctx);
3190 io_put_task(task, task_refs);
3193 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
3194 __must_hold(&ctx->uring_lock)
3196 struct io_wq_work_node *node, *prev;
3197 struct io_submit_state *state = &ctx->submit_state;
3199 if (state->flush_cqes) {
3200 spin_lock(&ctx->completion_lock);
3201 wq_list_for_each(node, prev, &state->compl_reqs) {
3202 struct io_kiocb *req = container_of(node, struct io_kiocb,
3205 if (!(req->flags & REQ_F_CQE_SKIP)) {
3206 if (!(ctx->flags & IORING_SETUP_CQE32))
3207 __io_fill_cqe_req_filled(ctx, req);
3209 __io_fill_cqe32_req_filled(ctx, req);
3213 io_commit_cqring(ctx);
3214 spin_unlock(&ctx->completion_lock);
3215 io_cqring_ev_posted(ctx);
3216 state->flush_cqes = false;
3219 io_free_batch_list(ctx, state->compl_reqs.first);
3220 INIT_WQ_LIST(&state->compl_reqs);
3224 * Drop reference to request, return next in chain (if there is one) if this
3225 * was the last reference to this request.
3227 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
3229 struct io_kiocb *nxt = NULL;
3231 if (req_ref_put_and_test(req)) {
3232 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
3233 nxt = io_req_find_next(req);
3239 static inline void io_put_req(struct io_kiocb *req)
3241 if (req_ref_put_and_test(req)) {
3247 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
3249 /* See comment at the top of this file */
3251 return __io_cqring_events(ctx);
3254 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
3256 struct io_rings *rings = ctx->rings;
3258 /* make sure SQ entry isn't read before tail */
3259 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3262 static inline bool io_run_task_work(void)
3264 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3265 __set_current_state(TASK_RUNNING);
3266 clear_notify_signal();
3267 if (task_work_pending(current))
3275 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3277 struct io_wq_work_node *pos, *start, *prev;
3278 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3279 DEFINE_IO_COMP_BATCH(iob);
3283 * Only spin for completions if we don't have multiple devices hanging
3284 * off our complete list.
3286 if (ctx->poll_multi_queue || force_nonspin)
3287 poll_flags |= BLK_POLL_ONESHOT;
3289 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3290 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3291 struct kiocb *kiocb = &req->rw.kiocb;
3295 * Move completed and retryable entries to our local lists.
3296 * If we find a request that requires polling, break out
3297 * and complete those lists first, if we have entries there.
3299 if (READ_ONCE(req->iopoll_completed))
3302 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3303 if (unlikely(ret < 0))
3306 poll_flags |= BLK_POLL_ONESHOT;
3308 /* iopoll may have completed current req */
3309 if (!rq_list_empty(iob.req_list) ||
3310 READ_ONCE(req->iopoll_completed))
3314 if (!rq_list_empty(iob.req_list))
3320 wq_list_for_each_resume(pos, prev) {
3321 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3323 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3324 if (!smp_load_acquire(&req->iopoll_completed))
3327 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3329 __io_fill_cqe_req(req, req->cqe.res, io_put_kbuf(req, 0));
3332 if (unlikely(!nr_events))
3335 io_commit_cqring(ctx);
3336 io_cqring_ev_posted_iopoll(ctx);
3337 pos = start ? start->next : ctx->iopoll_list.first;
3338 wq_list_cut(&ctx->iopoll_list, prev, start);
3339 io_free_batch_list(ctx, pos);
3344 * We can't just wait for polled events to come to us, we have to actively
3345 * find and complete them.
3347 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3349 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3352 mutex_lock(&ctx->uring_lock);
3353 while (!wq_list_empty(&ctx->iopoll_list)) {
3354 /* let it sleep and repeat later if can't complete a request */
3355 if (io_do_iopoll(ctx, true) == 0)
3358 * Ensure we allow local-to-the-cpu processing to take place,
3359 * in this case we need to ensure that we reap all events.
3360 * Also let task_work, etc. to progress by releasing the mutex
3362 if (need_resched()) {
3363 mutex_unlock(&ctx->uring_lock);
3365 mutex_lock(&ctx->uring_lock);
3368 mutex_unlock(&ctx->uring_lock);
3371 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3373 unsigned int nr_events = 0;
3375 unsigned long check_cq;
3378 * Don't enter poll loop if we already have events pending.
3379 * If we do, we can potentially be spinning for commands that
3380 * already triggered a CQE (eg in error).
3382 check_cq = READ_ONCE(ctx->check_cq);
3383 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3384 __io_cqring_overflow_flush(ctx, false);
3385 if (io_cqring_events(ctx))
3389 * Similarly do not spin if we have not informed the user of any
3392 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3397 * If a submit got punted to a workqueue, we can have the
3398 * application entering polling for a command before it gets
3399 * issued. That app will hold the uring_lock for the duration
3400 * of the poll right here, so we need to take a breather every
3401 * now and then to ensure that the issue has a chance to add
3402 * the poll to the issued list. Otherwise we can spin here
3403 * forever, while the workqueue is stuck trying to acquire the
3406 if (wq_list_empty(&ctx->iopoll_list)) {
3407 u32 tail = ctx->cached_cq_tail;
3409 mutex_unlock(&ctx->uring_lock);
3411 mutex_lock(&ctx->uring_lock);
3413 /* some requests don't go through iopoll_list */
3414 if (tail != ctx->cached_cq_tail ||
3415 wq_list_empty(&ctx->iopoll_list))
3418 ret = io_do_iopoll(ctx, !min);
3423 } while (nr_events < min && !need_resched());
3428 static void kiocb_end_write(struct io_kiocb *req)
3431 * Tell lockdep we inherited freeze protection from submission
3434 if (req->flags & REQ_F_ISREG) {
3435 struct super_block *sb = file_inode(req->file)->i_sb;
3437 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3443 static bool io_resubmit_prep(struct io_kiocb *req)
3445 struct io_async_rw *rw = req->async_data;
3447 if (!req_has_async_data(req))
3448 return !io_req_prep_async(req);
3449 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3453 static bool io_rw_should_reissue(struct io_kiocb *req)
3455 umode_t mode = file_inode(req->file)->i_mode;
3456 struct io_ring_ctx *ctx = req->ctx;
3458 if (!S_ISBLK(mode) && !S_ISREG(mode))
3460 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3461 !(ctx->flags & IORING_SETUP_IOPOLL)))
3464 * If ref is dying, we might be running poll reap from the exit work.
3465 * Don't attempt to reissue from that path, just let it fail with
3468 if (percpu_ref_is_dying(&ctx->refs))
3471 * Play it safe and assume not safe to re-import and reissue if we're
3472 * not in the original thread group (or in task context).
3474 if (!same_thread_group(req->task, current) || !in_task())
3479 static bool io_resubmit_prep(struct io_kiocb *req)
3483 static bool io_rw_should_reissue(struct io_kiocb *req)
3489 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3491 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3492 kiocb_end_write(req);
3493 fsnotify_modify(req->file);
3495 fsnotify_access(req->file);
3497 if (unlikely(res != req->cqe.res)) {
3498 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3499 io_rw_should_reissue(req)) {
3500 req->flags |= REQ_F_REISSUE;
3509 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3511 int res = req->cqe.res;
3514 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3515 io_req_add_compl_list(req);
3517 io_req_complete_post(req, res,
3518 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3522 static void __io_complete_rw(struct io_kiocb *req, long res,
3523 unsigned int issue_flags)
3525 if (__io_complete_rw_common(req, res))
3527 __io_req_complete(req, issue_flags, req->cqe.res,
3528 io_put_kbuf(req, issue_flags));
3531 static void io_complete_rw(struct kiocb *kiocb, long res)
3533 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3535 if (__io_complete_rw_common(req, res))
3538 req->io_task_work.func = io_req_task_complete;
3539 io_req_task_prio_work_add(req);
3542 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3544 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3546 if (kiocb->ki_flags & IOCB_WRITE)
3547 kiocb_end_write(req);
3548 if (unlikely(res != req->cqe.res)) {
3549 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3550 req->flags |= REQ_F_REISSUE;
3556 /* order with io_iopoll_complete() checking ->iopoll_completed */
3557 smp_store_release(&req->iopoll_completed, 1);
3561 * After the iocb has been issued, it's safe to be found on the poll list.
3562 * Adding the kiocb to the list AFTER submission ensures that we don't
3563 * find it from a io_do_iopoll() thread before the issuer is done
3564 * accessing the kiocb cookie.
3566 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3568 struct io_ring_ctx *ctx = req->ctx;
3569 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3571 /* workqueue context doesn't hold uring_lock, grab it now */
3572 if (unlikely(needs_lock))
3573 mutex_lock(&ctx->uring_lock);
3576 * Track whether we have multiple files in our lists. This will impact
3577 * how we do polling eventually, not spinning if we're on potentially
3578 * different devices.
3580 if (wq_list_empty(&ctx->iopoll_list)) {
3581 ctx->poll_multi_queue = false;
3582 } else if (!ctx->poll_multi_queue) {
3583 struct io_kiocb *list_req;
3585 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3587 if (list_req->file != req->file)
3588 ctx->poll_multi_queue = true;
3592 * For fast devices, IO may have already completed. If it has, add
3593 * it to the front so we find it first.
3595 if (READ_ONCE(req->iopoll_completed))
3596 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3598 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3600 if (unlikely(needs_lock)) {
3602 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3603 * in sq thread task context or in io worker task context. If
3604 * current task context is sq thread, we don't need to check
3605 * whether should wake up sq thread.
3607 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3608 wq_has_sleeper(&ctx->sq_data->wait))
3609 wake_up(&ctx->sq_data->wait);
3611 mutex_unlock(&ctx->uring_lock);
3615 static bool io_bdev_nowait(struct block_device *bdev)
3617 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3621 * If we tracked the file through the SCM inflight mechanism, we could support
3622 * any file. For now, just ensure that anything potentially problematic is done
3625 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3627 if (S_ISBLK(mode)) {
3628 if (IS_ENABLED(CONFIG_BLOCK) &&
3629 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3635 if (S_ISREG(mode)) {
3636 if (IS_ENABLED(CONFIG_BLOCK) &&
3637 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3638 file->f_op != &io_uring_fops)
3643 /* any ->read/write should understand O_NONBLOCK */
3644 if (file->f_flags & O_NONBLOCK)
3646 return file->f_mode & FMODE_NOWAIT;
3650 * If we tracked the file through the SCM inflight mechanism, we could support
3651 * any file. For now, just ensure that anything potentially problematic is done
3654 static unsigned int io_file_get_flags(struct file *file)
3656 umode_t mode = file_inode(file)->i_mode;
3657 unsigned int res = 0;
3661 if (__io_file_supports_nowait(file, mode))
3663 if (io_file_need_scm(file))
3668 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3670 return req->flags & REQ_F_SUPPORT_NOWAIT;
3673 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3675 struct kiocb *kiocb = &req->rw.kiocb;
3679 kiocb->ki_pos = READ_ONCE(sqe->off);
3681 ioprio = READ_ONCE(sqe->ioprio);
3683 ret = ioprio_check_cap(ioprio);
3687 kiocb->ki_ioprio = ioprio;
3689 kiocb->ki_ioprio = get_current_ioprio();
3693 req->rw.addr = READ_ONCE(sqe->addr);
3694 req->rw.len = READ_ONCE(sqe->len);
3695 req->rw.flags = READ_ONCE(sqe->rw_flags);
3696 /* used for fixed read/write too - just read unconditionally */
3697 req->buf_index = READ_ONCE(sqe->buf_index);
3701 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3707 case -ERESTARTNOINTR:
3708 case -ERESTARTNOHAND:
3709 case -ERESTART_RESTARTBLOCK:
3711 * We can't just restart the syscall, since previously
3712 * submitted sqes may already be in progress. Just fail this
3718 kiocb->ki_complete(kiocb, ret);
3722 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3724 struct kiocb *kiocb = &req->rw.kiocb;
3726 if (kiocb->ki_pos != -1)
3727 return &kiocb->ki_pos;
3729 if (!(req->file->f_mode & FMODE_STREAM)) {
3730 req->flags |= REQ_F_CUR_POS;
3731 kiocb->ki_pos = req->file->f_pos;
3732 return &kiocb->ki_pos;
3739 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3740 unsigned int issue_flags)
3742 struct io_async_rw *io = req->async_data;
3744 /* add previously done IO, if any */
3745 if (req_has_async_data(req) && io->bytes_done > 0) {
3747 ret = io->bytes_done;
3749 ret += io->bytes_done;
3752 if (req->flags & REQ_F_CUR_POS)
3753 req->file->f_pos = req->rw.kiocb.ki_pos;
3754 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3755 __io_complete_rw(req, ret, issue_flags);
3757 io_rw_done(&req->rw.kiocb, ret);
3759 if (req->flags & REQ_F_REISSUE) {
3760 req->flags &= ~REQ_F_REISSUE;
3761 if (io_resubmit_prep(req))
3762 io_req_task_queue_reissue(req);
3764 io_req_task_queue_fail(req, ret);
3768 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3769 struct io_mapped_ubuf *imu)
3771 size_t len = req->rw.len;
3772 u64 buf_end, buf_addr = req->rw.addr;
3775 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3777 /* not inside the mapped region */
3778 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3782 * May not be a start of buffer, set size appropriately
3783 * and advance us to the beginning.
3785 offset = buf_addr - imu->ubuf;
3786 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3790 * Don't use iov_iter_advance() here, as it's really slow for
3791 * using the latter parts of a big fixed buffer - it iterates
3792 * over each segment manually. We can cheat a bit here, because
3795 * 1) it's a BVEC iter, we set it up
3796 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3797 * first and last bvec
3799 * So just find our index, and adjust the iterator afterwards.
3800 * If the offset is within the first bvec (or the whole first
3801 * bvec, just use iov_iter_advance(). This makes it easier
3802 * since we can just skip the first segment, which may not
3803 * be PAGE_SIZE aligned.
3805 const struct bio_vec *bvec = imu->bvec;
3807 if (offset <= bvec->bv_len) {
3808 iov_iter_advance(iter, offset);
3810 unsigned long seg_skip;
3812 /* skip first vec */
3813 offset -= bvec->bv_len;
3814 seg_skip = 1 + (offset >> PAGE_SHIFT);
3816 iter->bvec = bvec + seg_skip;
3817 iter->nr_segs -= seg_skip;
3818 iter->count -= bvec->bv_len + offset;
3819 iter->iov_offset = offset & ~PAGE_MASK;
3826 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3827 unsigned int issue_flags)
3829 struct io_mapped_ubuf *imu = req->imu;
3830 u16 index, buf_index = req->buf_index;
3833 struct io_ring_ctx *ctx = req->ctx;
3835 if (unlikely(buf_index >= ctx->nr_user_bufs))
3837 io_req_set_rsrc_node(req, ctx, issue_flags);
3838 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3839 imu = READ_ONCE(ctx->user_bufs[index]);
3842 return __io_import_fixed(req, rw, iter, imu);
3845 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3846 struct io_buffer_list *bl, unsigned int bgid)
3849 if (bgid < BGID_ARRAY)
3852 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3855 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3856 struct io_buffer_list *bl)
3858 if (!list_empty(&bl->buf_list)) {
3859 struct io_buffer *kbuf;
3861 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3862 list_del(&kbuf->list);
3863 if (*len > kbuf->len)
3865 req->flags |= REQ_F_BUFFER_SELECTED;
3867 req->buf_index = kbuf->bid;
3868 return u64_to_user_ptr(kbuf->addr);
3873 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3874 struct io_buffer_list *bl,
3875 unsigned int issue_flags)
3877 struct io_uring_buf_ring *br = bl->buf_ring;
3878 struct io_uring_buf *buf;
3879 __u32 head = bl->head;
3881 if (unlikely(smp_load_acquire(&br->tail) == head)) {
3882 io_ring_submit_unlock(req->ctx, issue_flags);
3887 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3888 buf = &br->bufs[head];
3890 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3891 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE - 1;
3892 buf = page_address(bl->buf_pages[index]);
3895 if (*len > buf->len)
3897 req->flags |= REQ_F_BUFFER_RING;
3899 req->buf_index = buf->bid;
3901 if (issue_flags & IO_URING_F_UNLOCKED) {
3903 * If we came in unlocked, we have no choice but to consume the
3904 * buffer here. This does mean it'll be pinned until the IO
3905 * completes. But coming in unlocked means we're in io-wq
3906 * context, hence there should be no further retry. For the
3907 * locked case, the caller must ensure to call the commit when
3908 * the transfer completes (or if we get -EAGAIN and must poll
3911 req->buf_list = NULL;
3914 return u64_to_user_ptr(buf->addr);
3917 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3918 unsigned int issue_flags)
3920 struct io_ring_ctx *ctx = req->ctx;
3921 struct io_buffer_list *bl;
3922 void __user *ret = NULL;
3924 io_ring_submit_lock(req->ctx, issue_flags);
3926 bl = io_buffer_get_list(ctx, req->buf_index);
3928 if (bl->buf_nr_pages)
3929 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3931 ret = io_provided_buffer_select(req, len, bl);
3933 io_ring_submit_unlock(req->ctx, issue_flags);
3937 #ifdef CONFIG_COMPAT
3938 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3939 unsigned int issue_flags)
3941 struct compat_iovec __user *uiov;
3942 compat_ssize_t clen;
3946 uiov = u64_to_user_ptr(req->rw.addr);
3947 if (!access_ok(uiov, sizeof(*uiov)))
3949 if (__get_user(clen, &uiov->iov_len))
3955 buf = io_buffer_select(req, &len, issue_flags);
3958 req->rw.addr = (unsigned long) buf;
3959 iov[0].iov_base = buf;
3960 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3965 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3966 unsigned int issue_flags)
3968 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3972 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3975 len = iov[0].iov_len;
3978 buf = io_buffer_select(req, &len, issue_flags);
3981 req->rw.addr = (unsigned long) buf;
3982 iov[0].iov_base = buf;
3983 req->rw.len = iov[0].iov_len = len;
3987 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3988 unsigned int issue_flags)
3990 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3991 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3992 iov[0].iov_len = req->rw.len;
3995 if (req->rw.len != 1)
3998 #ifdef CONFIG_COMPAT
3999 if (req->ctx->compat)
4000 return io_compat_import(req, iov, issue_flags);
4003 return __io_iov_buffer_select(req, iov, issue_flags);
4006 static inline bool io_do_buffer_select(struct io_kiocb *req)
4008 if (!(req->flags & REQ_F_BUFFER_SELECT))
4010 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
4013 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
4014 struct io_rw_state *s,
4015 unsigned int issue_flags)
4017 struct iov_iter *iter = &s->iter;
4018 u8 opcode = req->opcode;
4019 struct iovec *iovec;
4024 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
4025 ret = io_import_fixed(req, rw, iter, issue_flags);
4027 return ERR_PTR(ret);
4031 buf = u64_to_user_ptr(req->rw.addr);
4032 sqe_len = req->rw.len;
4034 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
4035 if (io_do_buffer_select(req)) {
4036 buf = io_buffer_select(req, &sqe_len, issue_flags);
4038 return ERR_PTR(-ENOBUFS);
4039 req->rw.addr = (unsigned long) buf;
4040 req->rw.len = sqe_len;
4043 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
4045 return ERR_PTR(ret);
4049 iovec = s->fast_iov;
4050 if (req->flags & REQ_F_BUFFER_SELECT) {
4051 ret = io_iov_buffer_select(req, iovec, issue_flags);
4053 return ERR_PTR(ret);
4054 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
4058 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
4060 if (unlikely(ret < 0))
4061 return ERR_PTR(ret);
4065 static inline int io_import_iovec(int rw, struct io_kiocb *req,
4066 struct iovec **iovec, struct io_rw_state *s,
4067 unsigned int issue_flags)
4069 *iovec = __io_import_iovec(rw, req, s, issue_flags);
4070 if (unlikely(IS_ERR(*iovec)))
4071 return PTR_ERR(*iovec);
4073 iov_iter_save_state(&s->iter, &s->iter_state);
4077 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
4079 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
4083 * For files that don't have ->read_iter() and ->write_iter(), handle them
4084 * by looping over ->read() or ->write() manually.
4086 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
4088 struct kiocb *kiocb = &req->rw.kiocb;
4089 struct file *file = req->file;
4094 * Don't support polled IO through this interface, and we can't
4095 * support non-blocking either. For the latter, this just causes
4096 * the kiocb to be handled from an async context.
4098 if (kiocb->ki_flags & IOCB_HIPRI)
4100 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
4101 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
4104 ppos = io_kiocb_ppos(kiocb);
4106 while (iov_iter_count(iter)) {
4110 if (!iov_iter_is_bvec(iter)) {
4111 iovec = iov_iter_iovec(iter);
4113 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
4114 iovec.iov_len = req->rw.len;
4118 nr = file->f_op->read(file, iovec.iov_base,
4119 iovec.iov_len, ppos);
4121 nr = file->f_op->write(file, iovec.iov_base,
4122 iovec.iov_len, ppos);
4131 if (!iov_iter_is_bvec(iter)) {
4132 iov_iter_advance(iter, nr);
4139 if (nr != iovec.iov_len)
4146 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
4147 const struct iovec *fast_iov, struct iov_iter *iter)
4149 struct io_async_rw *rw = req->async_data;
4151 memcpy(&rw->s.iter, iter, sizeof(*iter));
4152 rw->free_iovec = iovec;
4154 /* can only be fixed buffers, no need to do anything */
4155 if (iov_iter_is_bvec(iter))
4158 unsigned iov_off = 0;
4160 rw->s.iter.iov = rw->s.fast_iov;
4161 if (iter->iov != fast_iov) {
4162 iov_off = iter->iov - fast_iov;
4163 rw->s.iter.iov += iov_off;
4165 if (rw->s.fast_iov != fast_iov)
4166 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
4167 sizeof(struct iovec) * iter->nr_segs);
4169 req->flags |= REQ_F_NEED_CLEANUP;
4173 static inline bool io_alloc_async_data(struct io_kiocb *req)
4175 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
4176 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
4177 if (req->async_data) {
4178 req->flags |= REQ_F_ASYNC_DATA;
4184 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
4185 struct io_rw_state *s, bool force)
4187 if (!force && !io_op_defs[req->opcode].needs_async_setup)
4189 if (!req_has_async_data(req)) {
4190 struct io_async_rw *iorw;
4192 if (io_alloc_async_data(req)) {
4197 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
4198 iorw = req->async_data;
4199 /* we've copied and mapped the iter, ensure state is saved */
4200 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
4205 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
4207 struct io_async_rw *iorw = req->async_data;
4211 /* submission path, ->uring_lock should already be taken */
4212 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
4213 if (unlikely(ret < 0))
4216 iorw->bytes_done = 0;
4217 iorw->free_iovec = iov;
4219 req->flags |= REQ_F_NEED_CLEANUP;
4223 static int io_readv_prep_async(struct io_kiocb *req)
4225 return io_rw_prep_async(req, READ);
4228 static int io_writev_prep_async(struct io_kiocb *req)
4230 return io_rw_prep_async(req, WRITE);
4234 * This is our waitqueue callback handler, registered through __folio_lock_async()
4235 * when we initially tried to do the IO with the iocb armed our waitqueue.
4236 * This gets called when the page is unlocked, and we generally expect that to
4237 * happen when the page IO is completed and the page is now uptodate. This will
4238 * queue a task_work based retry of the operation, attempting to copy the data
4239 * again. If the latter fails because the page was NOT uptodate, then we will
4240 * do a thread based blocking retry of the operation. That's the unexpected
4243 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
4244 int sync, void *arg)
4246 struct wait_page_queue *wpq;
4247 struct io_kiocb *req = wait->private;
4248 struct wait_page_key *key = arg;
4250 wpq = container_of(wait, struct wait_page_queue, wait);
4252 if (!wake_page_match(wpq, key))
4255 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
4256 list_del_init(&wait->entry);
4257 io_req_task_queue(req);
4262 * This controls whether a given IO request should be armed for async page
4263 * based retry. If we return false here, the request is handed to the async
4264 * worker threads for retry. If we're doing buffered reads on a regular file,
4265 * we prepare a private wait_page_queue entry and retry the operation. This
4266 * will either succeed because the page is now uptodate and unlocked, or it
4267 * will register a callback when the page is unlocked at IO completion. Through
4268 * that callback, io_uring uses task_work to setup a retry of the operation.
4269 * That retry will attempt the buffered read again. The retry will generally
4270 * succeed, or in rare cases where it fails, we then fall back to using the
4271 * async worker threads for a blocking retry.
4273 static bool io_rw_should_retry(struct io_kiocb *req)
4275 struct io_async_rw *rw = req->async_data;
4276 struct wait_page_queue *wait = &rw->wpq;
4277 struct kiocb *kiocb = &req->rw.kiocb;
4279 /* never retry for NOWAIT, we just complete with -EAGAIN */
4280 if (req->flags & REQ_F_NOWAIT)
4283 /* Only for buffered IO */
4284 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4288 * just use poll if we can, and don't attempt if the fs doesn't
4289 * support callback based unlocks
4291 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4294 wait->wait.func = io_async_buf_func;
4295 wait->wait.private = req;
4296 wait->wait.flags = 0;
4297 INIT_LIST_HEAD(&wait->wait.entry);
4298 kiocb->ki_flags |= IOCB_WAITQ;
4299 kiocb->ki_flags &= ~IOCB_NOWAIT;
4300 kiocb->ki_waitq = wait;
4304 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4306 if (likely(req->file->f_op->read_iter))
4307 return call_read_iter(req->file, &req->rw.kiocb, iter);
4308 else if (req->file->f_op->read)
4309 return loop_rw_iter(READ, req, iter);
4314 static bool need_read_all(struct io_kiocb *req)
4316 return req->flags & REQ_F_ISREG ||
4317 S_ISBLK(file_inode(req->file)->i_mode);
4320 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4322 struct kiocb *kiocb = &req->rw.kiocb;
4323 struct io_ring_ctx *ctx = req->ctx;
4324 struct file *file = req->file;
4327 if (unlikely(!file || !(file->f_mode & mode)))
4330 if (!io_req_ffs_set(req))
4331 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4333 kiocb->ki_flags = iocb_flags(file);
4334 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4339 * If the file is marked O_NONBLOCK, still allow retry for it if it
4340 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4341 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4343 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4344 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4345 req->flags |= REQ_F_NOWAIT;
4347 if (ctx->flags & IORING_SETUP_IOPOLL) {
4348 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4351 kiocb->private = NULL;
4352 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4353 kiocb->ki_complete = io_complete_rw_iopoll;
4354 req->iopoll_completed = 0;
4356 if (kiocb->ki_flags & IOCB_HIPRI)
4358 kiocb->ki_complete = io_complete_rw;
4364 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4366 struct io_rw_state __s, *s = &__s;
4367 struct iovec *iovec;
4368 struct kiocb *kiocb = &req->rw.kiocb;
4369 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4370 struct io_async_rw *rw;
4374 if (!req_has_async_data(req)) {
4375 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4376 if (unlikely(ret < 0))
4380 * Safe and required to re-import if we're using provided
4381 * buffers, as we dropped the selected one before retry.
4383 if (req->flags & REQ_F_BUFFER_SELECT) {
4384 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4385 if (unlikely(ret < 0))
4389 rw = req->async_data;
4392 * We come here from an earlier attempt, restore our state to
4393 * match in case it doesn't. It's cheap enough that we don't
4394 * need to make this conditional.
4396 iov_iter_restore(&s->iter, &s->iter_state);
4399 ret = io_rw_init_file(req, FMODE_READ);
4400 if (unlikely(ret)) {
4404 req->cqe.res = iov_iter_count(&s->iter);
4406 if (force_nonblock) {
4407 /* If the file doesn't support async, just async punt */
4408 if (unlikely(!io_file_supports_nowait(req))) {
4409 ret = io_setup_async_rw(req, iovec, s, true);
4410 return ret ?: -EAGAIN;
4412 kiocb->ki_flags |= IOCB_NOWAIT;
4414 /* Ensure we clear previously set non-block flag */
4415 kiocb->ki_flags &= ~IOCB_NOWAIT;
4418 ppos = io_kiocb_update_pos(req);
4420 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4421 if (unlikely(ret)) {
4426 ret = io_iter_do_read(req, &s->iter);
4428 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4429 req->flags &= ~REQ_F_REISSUE;
4430 /* if we can poll, just do that */
4431 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4433 /* IOPOLL retry should happen for io-wq threads */
4434 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4436 /* no retry on NONBLOCK nor RWF_NOWAIT */
4437 if (req->flags & REQ_F_NOWAIT)
4440 } else if (ret == -EIOCBQUEUED) {
4442 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4443 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4444 /* read all, failed, already did sync or don't want to retry */
4449 * Don't depend on the iter state matching what was consumed, or being
4450 * untouched in case of error. Restore it and we'll advance it
4451 * manually if we need to.
4453 iov_iter_restore(&s->iter, &s->iter_state);
4455 ret2 = io_setup_async_rw(req, iovec, s, true);
4460 rw = req->async_data;
4463 * Now use our persistent iterator and state, if we aren't already.
4464 * We've restored and mapped the iter to match.
4469 * We end up here because of a partial read, either from
4470 * above or inside this loop. Advance the iter by the bytes
4471 * that were consumed.
4473 iov_iter_advance(&s->iter, ret);
4474 if (!iov_iter_count(&s->iter))
4476 rw->bytes_done += ret;
4477 iov_iter_save_state(&s->iter, &s->iter_state);
4479 /* if we can retry, do so with the callbacks armed */
4480 if (!io_rw_should_retry(req)) {
4481 kiocb->ki_flags &= ~IOCB_WAITQ;
4486 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4487 * we get -EIOCBQUEUED, then we'll get a notification when the
4488 * desired page gets unlocked. We can also get a partial read
4489 * here, and if we do, then just retry at the new offset.
4491 ret = io_iter_do_read(req, &s->iter);
4492 if (ret == -EIOCBQUEUED)
4494 /* we got some bytes, but not all. retry. */
4495 kiocb->ki_flags &= ~IOCB_WAITQ;
4496 iov_iter_restore(&s->iter, &s->iter_state);
4499 kiocb_done(req, ret, issue_flags);
4501 /* it's faster to check here then delegate to kfree */
4507 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4509 struct io_rw_state __s, *s = &__s;
4510 struct iovec *iovec;
4511 struct kiocb *kiocb = &req->rw.kiocb;
4512 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4516 if (!req_has_async_data(req)) {
4517 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4518 if (unlikely(ret < 0))
4521 struct io_async_rw *rw = req->async_data;
4524 iov_iter_restore(&s->iter, &s->iter_state);
4527 ret = io_rw_init_file(req, FMODE_WRITE);
4528 if (unlikely(ret)) {
4532 req->cqe.res = iov_iter_count(&s->iter);
4534 if (force_nonblock) {
4535 /* If the file doesn't support async, just async punt */
4536 if (unlikely(!io_file_supports_nowait(req)))
4539 /* file path doesn't support NOWAIT for non-direct_IO */
4540 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4541 (req->flags & REQ_F_ISREG))
4544 kiocb->ki_flags |= IOCB_NOWAIT;
4546 /* Ensure we clear previously set non-block flag */
4547 kiocb->ki_flags &= ~IOCB_NOWAIT;
4550 ppos = io_kiocb_update_pos(req);
4552 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4557 * Open-code file_start_write here to grab freeze protection,
4558 * which will be released by another thread in
4559 * io_complete_rw(). Fool lockdep by telling it the lock got
4560 * released so that it doesn't complain about the held lock when
4561 * we return to userspace.
4563 if (req->flags & REQ_F_ISREG) {
4564 sb_start_write(file_inode(req->file)->i_sb);
4565 __sb_writers_release(file_inode(req->file)->i_sb,
4568 kiocb->ki_flags |= IOCB_WRITE;
4570 if (likely(req->file->f_op->write_iter))
4571 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4572 else if (req->file->f_op->write)
4573 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4577 if (req->flags & REQ_F_REISSUE) {
4578 req->flags &= ~REQ_F_REISSUE;
4583 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4584 * retry them without IOCB_NOWAIT.
4586 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4588 /* no retry on NONBLOCK nor RWF_NOWAIT */
4589 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4591 if (!force_nonblock || ret2 != -EAGAIN) {
4592 /* IOPOLL retry should happen for io-wq threads */
4593 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4596 kiocb_done(req, ret2, issue_flags);
4599 iov_iter_restore(&s->iter, &s->iter_state);
4600 ret = io_setup_async_rw(req, iovec, s, false);
4601 return ret ?: -EAGAIN;
4604 /* it's reportedly faster than delegating the null check to kfree() */
4610 static int io_renameat_prep(struct io_kiocb *req,
4611 const struct io_uring_sqe *sqe)
4613 struct io_rename *ren = &req->rename;
4614 const char __user *oldf, *newf;
4616 if (sqe->buf_index || sqe->splice_fd_in)
4618 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4621 ren->old_dfd = READ_ONCE(sqe->fd);
4622 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4623 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4624 ren->new_dfd = READ_ONCE(sqe->len);
4625 ren->flags = READ_ONCE(sqe->rename_flags);
4627 ren->oldpath = getname(oldf);
4628 if (IS_ERR(ren->oldpath))
4629 return PTR_ERR(ren->oldpath);
4631 ren->newpath = getname(newf);
4632 if (IS_ERR(ren->newpath)) {
4633 putname(ren->oldpath);
4634 return PTR_ERR(ren->newpath);
4637 req->flags |= REQ_F_NEED_CLEANUP;
4641 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4643 struct io_rename *ren = &req->rename;
4646 if (issue_flags & IO_URING_F_NONBLOCK)
4649 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4650 ren->newpath, ren->flags);
4652 req->flags &= ~REQ_F_NEED_CLEANUP;
4653 io_req_complete(req, ret);
4657 static inline void __io_xattr_finish(struct io_kiocb *req)
4659 struct io_xattr *ix = &req->xattr;
4662 putname(ix->filename);
4664 kfree(ix->ctx.kname);
4665 kvfree(ix->ctx.kvalue);
4668 static void io_xattr_finish(struct io_kiocb *req, int ret)
4670 req->flags &= ~REQ_F_NEED_CLEANUP;
4672 __io_xattr_finish(req);
4673 io_req_complete(req, ret);
4676 static int __io_getxattr_prep(struct io_kiocb *req,
4677 const struct io_uring_sqe *sqe)
4679 struct io_xattr *ix = &req->xattr;
4680 const char __user *name;
4683 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4686 ix->filename = NULL;
4687 ix->ctx.kvalue = NULL;
4688 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4689 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4690 ix->ctx.size = READ_ONCE(sqe->len);
4691 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4696 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4700 ret = strncpy_from_user(ix->ctx.kname->name, name,
4701 sizeof(ix->ctx.kname->name));
4702 if (!ret || ret == sizeof(ix->ctx.kname->name))
4705 kfree(ix->ctx.kname);
4709 req->flags |= REQ_F_NEED_CLEANUP;
4713 static int io_fgetxattr_prep(struct io_kiocb *req,
4714 const struct io_uring_sqe *sqe)
4716 return __io_getxattr_prep(req, sqe);
4719 static int io_getxattr_prep(struct io_kiocb *req,
4720 const struct io_uring_sqe *sqe)
4722 struct io_xattr *ix = &req->xattr;
4723 const char __user *path;
4726 ret = __io_getxattr_prep(req, sqe);
4730 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4732 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4733 if (IS_ERR(ix->filename)) {
4734 ret = PTR_ERR(ix->filename);
4735 ix->filename = NULL;
4741 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4743 struct io_xattr *ix = &req->xattr;
4746 if (issue_flags & IO_URING_F_NONBLOCK)
4749 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4750 req->file->f_path.dentry,
4753 io_xattr_finish(req, ret);
4757 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4759 struct io_xattr *ix = &req->xattr;
4760 unsigned int lookup_flags = LOOKUP_FOLLOW;
4764 if (issue_flags & IO_URING_F_NONBLOCK)
4768 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4770 ret = do_getxattr(mnt_user_ns(path.mnt),
4775 if (retry_estale(ret, lookup_flags)) {
4776 lookup_flags |= LOOKUP_REVAL;
4781 io_xattr_finish(req, ret);
4785 static int __io_setxattr_prep(struct io_kiocb *req,
4786 const struct io_uring_sqe *sqe)
4788 struct io_xattr *ix = &req->xattr;
4789 const char __user *name;
4792 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4795 ix->filename = NULL;
4796 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4797 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4798 ix->ctx.kvalue = NULL;
4799 ix->ctx.size = READ_ONCE(sqe->len);
4800 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4802 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4806 ret = setxattr_copy(name, &ix->ctx);
4808 kfree(ix->ctx.kname);
4812 req->flags |= REQ_F_NEED_CLEANUP;
4816 static int io_setxattr_prep(struct io_kiocb *req,
4817 const struct io_uring_sqe *sqe)
4819 struct io_xattr *ix = &req->xattr;
4820 const char __user *path;
4823 ret = __io_setxattr_prep(req, sqe);
4827 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4829 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4830 if (IS_ERR(ix->filename)) {
4831 ret = PTR_ERR(ix->filename);
4832 ix->filename = NULL;
4838 static int io_fsetxattr_prep(struct io_kiocb *req,
4839 const struct io_uring_sqe *sqe)
4841 return __io_setxattr_prep(req, sqe);
4844 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4847 struct io_xattr *ix = &req->xattr;
4850 ret = mnt_want_write(path->mnt);
4852 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4853 mnt_drop_write(path->mnt);
4859 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4863 if (issue_flags & IO_URING_F_NONBLOCK)
4866 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4867 io_xattr_finish(req, ret);
4872 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4874 struct io_xattr *ix = &req->xattr;
4875 unsigned int lookup_flags = LOOKUP_FOLLOW;
4879 if (issue_flags & IO_URING_F_NONBLOCK)
4883 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4885 ret = __io_setxattr(req, issue_flags, &path);
4887 if (retry_estale(ret, lookup_flags)) {
4888 lookup_flags |= LOOKUP_REVAL;
4893 io_xattr_finish(req, ret);
4897 static int io_unlinkat_prep(struct io_kiocb *req,
4898 const struct io_uring_sqe *sqe)
4900 struct io_unlink *un = &req->unlink;
4901 const char __user *fname;
4903 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4905 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4908 un->dfd = READ_ONCE(sqe->fd);
4910 un->flags = READ_ONCE(sqe->unlink_flags);
4911 if (un->flags & ~AT_REMOVEDIR)
4914 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4915 un->filename = getname(fname);
4916 if (IS_ERR(un->filename))
4917 return PTR_ERR(un->filename);
4919 req->flags |= REQ_F_NEED_CLEANUP;
4923 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4925 struct io_unlink *un = &req->unlink;
4928 if (issue_flags & IO_URING_F_NONBLOCK)
4931 if (un->flags & AT_REMOVEDIR)
4932 ret = do_rmdir(un->dfd, un->filename);
4934 ret = do_unlinkat(un->dfd, un->filename);
4936 req->flags &= ~REQ_F_NEED_CLEANUP;
4937 io_req_complete(req, ret);
4941 static int io_mkdirat_prep(struct io_kiocb *req,
4942 const struct io_uring_sqe *sqe)
4944 struct io_mkdir *mkd = &req->mkdir;
4945 const char __user *fname;
4947 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4949 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4952 mkd->dfd = READ_ONCE(sqe->fd);
4953 mkd->mode = READ_ONCE(sqe->len);
4955 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4956 mkd->filename = getname(fname);
4957 if (IS_ERR(mkd->filename))
4958 return PTR_ERR(mkd->filename);
4960 req->flags |= REQ_F_NEED_CLEANUP;
4964 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4966 struct io_mkdir *mkd = &req->mkdir;
4969 if (issue_flags & IO_URING_F_NONBLOCK)
4972 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4974 req->flags &= ~REQ_F_NEED_CLEANUP;
4975 io_req_complete(req, ret);
4979 static int io_symlinkat_prep(struct io_kiocb *req,
4980 const struct io_uring_sqe *sqe)
4982 struct io_symlink *sl = &req->symlink;
4983 const char __user *oldpath, *newpath;
4985 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4987 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4990 sl->new_dfd = READ_ONCE(sqe->fd);
4991 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4992 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4994 sl->oldpath = getname(oldpath);
4995 if (IS_ERR(sl->oldpath))
4996 return PTR_ERR(sl->oldpath);
4998 sl->newpath = getname(newpath);
4999 if (IS_ERR(sl->newpath)) {
5000 putname(sl->oldpath);
5001 return PTR_ERR(sl->newpath);
5004 req->flags |= REQ_F_NEED_CLEANUP;
5008 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
5010 struct io_symlink *sl = &req->symlink;
5013 if (issue_flags & IO_URING_F_NONBLOCK)
5016 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
5018 req->flags &= ~REQ_F_NEED_CLEANUP;
5019 io_req_complete(req, ret);
5023 static int io_linkat_prep(struct io_kiocb *req,
5024 const struct io_uring_sqe *sqe)
5026 struct io_hardlink *lnk = &req->hardlink;
5027 const char __user *oldf, *newf;
5029 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
5031 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5034 lnk->old_dfd = READ_ONCE(sqe->fd);
5035 lnk->new_dfd = READ_ONCE(sqe->len);
5036 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
5037 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5038 lnk->flags = READ_ONCE(sqe->hardlink_flags);
5040 lnk->oldpath = getname(oldf);
5041 if (IS_ERR(lnk->oldpath))
5042 return PTR_ERR(lnk->oldpath);
5044 lnk->newpath = getname(newf);
5045 if (IS_ERR(lnk->newpath)) {
5046 putname(lnk->oldpath);
5047 return PTR_ERR(lnk->newpath);
5050 req->flags |= REQ_F_NEED_CLEANUP;
5054 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
5056 struct io_hardlink *lnk = &req->hardlink;
5059 if (issue_flags & IO_URING_F_NONBLOCK)
5062 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
5063 lnk->newpath, lnk->flags);
5065 req->flags &= ~REQ_F_NEED_CLEANUP;
5066 io_req_complete(req, ret);
5070 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
5072 req->uring_cmd.task_work_cb(&req->uring_cmd);
5075 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
5076 void (*task_work_cb)(struct io_uring_cmd *))
5078 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5080 req->uring_cmd.task_work_cb = task_work_cb;
5081 req->io_task_work.func = io_uring_cmd_work;
5082 io_req_task_prio_work_add(req);
5084 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
5087 * Called by consumers of io_uring_cmd, if they originally returned
5088 * -EIOCBQUEUED upon receiving the command.
5090 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
5092 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
5096 if (req->ctx->flags & IORING_SETUP_CQE32)
5097 __io_req_complete32(req, 0, ret, 0, res2, 0);
5099 io_req_complete(req, ret);
5101 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
5103 static int io_uring_cmd_prep_async(struct io_kiocb *req)
5107 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
5109 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
5113 static int io_uring_cmd_prep(struct io_kiocb *req,
5114 const struct io_uring_sqe *sqe)
5116 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5120 ioucmd->cmd = sqe->cmd;
5121 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
5125 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
5127 struct io_uring_cmd *ioucmd = &req->uring_cmd;
5128 struct io_ring_ctx *ctx = req->ctx;
5129 struct file *file = req->file;
5132 if (!req->file->f_op->uring_cmd)
5135 if (ctx->flags & IORING_SETUP_SQE128)
5136 issue_flags |= IO_URING_F_SQE128;
5137 if (ctx->flags & IORING_SETUP_CQE32)
5138 issue_flags |= IO_URING_F_CQE32;
5139 if (ctx->flags & IORING_SETUP_IOPOLL)
5140 issue_flags |= IO_URING_F_IOPOLL;
5142 if (req_has_async_data(req))
5143 ioucmd->cmd = req->async_data;
5145 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
5146 if (ret == -EAGAIN) {
5147 if (!req_has_async_data(req)) {
5148 if (io_alloc_async_data(req))
5150 io_uring_cmd_prep_async(req);
5155 if (ret != -EIOCBQUEUED)
5156 io_uring_cmd_done(ioucmd, ret, 0);
5160 static int __io_splice_prep(struct io_kiocb *req,
5161 const struct io_uring_sqe *sqe)
5163 struct io_splice *sp = &req->splice;
5164 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
5166 sp->len = READ_ONCE(sqe->len);
5167 sp->flags = READ_ONCE(sqe->splice_flags);
5168 if (unlikely(sp->flags & ~valid_flags))
5170 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
5174 static int io_tee_prep(struct io_kiocb *req,
5175 const struct io_uring_sqe *sqe)
5177 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
5179 return __io_splice_prep(req, sqe);
5182 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
5184 struct io_splice *sp = &req->splice;
5185 struct file *out = sp->file_out;
5186 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5190 if (issue_flags & IO_URING_F_NONBLOCK)
5193 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5194 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5196 in = io_file_get_normal(req, sp->splice_fd_in);
5203 ret = do_tee(in, out, sp->len, flags);
5205 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5210 __io_req_complete(req, 0, ret, 0);
5214 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5216 struct io_splice *sp = &req->splice;
5218 sp->off_in = READ_ONCE(sqe->splice_off_in);
5219 sp->off_out = READ_ONCE(sqe->off);
5220 return __io_splice_prep(req, sqe);
5223 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5225 struct io_splice *sp = &req->splice;
5226 struct file *out = sp->file_out;
5227 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5228 loff_t *poff_in, *poff_out;
5232 if (issue_flags & IO_URING_F_NONBLOCK)
5235 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5236 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5238 in = io_file_get_normal(req, sp->splice_fd_in);
5244 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5245 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5248 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5250 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5255 __io_req_complete(req, 0, ret, 0);
5259 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5262 * If the ring is setup with CQE32, relay back addr/addr
5264 if (req->ctx->flags & IORING_SETUP_CQE32) {
5265 req->nop.extra1 = READ_ONCE(sqe->addr);
5266 req->nop.extra2 = READ_ONCE(sqe->addr2);
5273 * IORING_OP_NOP just posts a completion event, nothing else.
5275 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5277 unsigned int cflags;
5280 if (req->flags & REQ_F_BUFFER_SELECT) {
5283 buf = io_buffer_select(req, &len, issue_flags);
5288 cflags = io_put_kbuf(req, issue_flags);
5289 if (!(req->ctx->flags & IORING_SETUP_CQE32))
5290 __io_req_complete(req, issue_flags, 0, cflags);
5292 __io_req_complete32(req, issue_flags, 0, cflags,
5293 req->nop.extra1, req->nop.extra2);
5297 static int io_msg_ring_prep(struct io_kiocb *req,
5298 const struct io_uring_sqe *sqe)
5300 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5301 sqe->buf_index || sqe->personality))
5304 req->msg.user_data = READ_ONCE(sqe->off);
5305 req->msg.len = READ_ONCE(sqe->len);
5309 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5311 struct io_ring_ctx *target_ctx;
5312 struct io_msg *msg = &req->msg;
5317 if (req->file->f_op != &io_uring_fops)
5321 target_ctx = req->file->private_data;
5323 spin_lock(&target_ctx->completion_lock);
5324 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5325 io_commit_cqring(target_ctx);
5326 spin_unlock(&target_ctx->completion_lock);
5329 io_cqring_ev_posted(target_ctx);
5336 __io_req_complete(req, issue_flags, ret, 0);
5337 /* put file to avoid an attempt to IOPOLL the req */
5338 io_put_file(req->file);
5343 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5345 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5348 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5349 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5352 req->sync.off = READ_ONCE(sqe->off);
5353 req->sync.len = READ_ONCE(sqe->len);
5357 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5359 loff_t end = req->sync.off + req->sync.len;
5362 /* fsync always requires a blocking context */
5363 if (issue_flags & IO_URING_F_NONBLOCK)
5366 ret = vfs_fsync_range(req->file, req->sync.off,
5367 end > 0 ? end : LLONG_MAX,
5368 req->sync.flags & IORING_FSYNC_DATASYNC);
5369 io_req_complete(req, ret);
5373 static int io_fallocate_prep(struct io_kiocb *req,
5374 const struct io_uring_sqe *sqe)
5376 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5379 req->sync.off = READ_ONCE(sqe->off);
5380 req->sync.len = READ_ONCE(sqe->addr);
5381 req->sync.mode = READ_ONCE(sqe->len);
5385 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5389 /* fallocate always requiring blocking context */
5390 if (issue_flags & IO_URING_F_NONBLOCK)
5392 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5395 fsnotify_modify(req->file);
5396 io_req_complete(req, ret);
5400 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5402 const char __user *fname;
5405 if (unlikely(sqe->buf_index))
5407 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5410 /* open.how should be already initialised */
5411 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5412 req->open.how.flags |= O_LARGEFILE;
5414 req->open.dfd = READ_ONCE(sqe->fd);
5415 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5416 req->open.filename = getname(fname);
5417 if (IS_ERR(req->open.filename)) {
5418 ret = PTR_ERR(req->open.filename);
5419 req->open.filename = NULL;
5423 req->open.file_slot = READ_ONCE(sqe->file_index);
5424 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5427 req->open.nofile = rlimit(RLIMIT_NOFILE);
5428 req->flags |= REQ_F_NEED_CLEANUP;
5432 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5434 u64 mode = READ_ONCE(sqe->len);
5435 u64 flags = READ_ONCE(sqe->open_flags);
5437 req->open.how = build_open_how(flags, mode);
5438 return __io_openat_prep(req, sqe);
5441 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5443 struct open_how __user *how;
5447 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5448 len = READ_ONCE(sqe->len);
5449 if (len < OPEN_HOW_SIZE_VER0)
5452 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5457 return __io_openat_prep(req, sqe);
5460 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5462 struct io_file_table *table = &ctx->file_table;
5463 unsigned long nr = ctx->nr_user_files;
5467 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5471 if (!table->alloc_hint)
5474 nr = table->alloc_hint;
5475 table->alloc_hint = 0;
5482 * Note when io_fixed_fd_install() returns error value, it will ensure
5483 * fput() is called correspondingly.
5485 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5486 struct file *file, unsigned int file_slot)
5488 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5489 struct io_ring_ctx *ctx = req->ctx;
5492 io_ring_submit_lock(ctx, issue_flags);
5495 ret = io_file_bitmap_get(ctx);
5496 if (unlikely(ret < 0))
5503 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5504 if (!ret && alloc_slot)
5507 io_ring_submit_unlock(ctx, issue_flags);
5508 if (unlikely(ret < 0))
5513 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5515 struct open_flags op;
5517 bool resolve_nonblock, nonblock_set;
5518 bool fixed = !!req->open.file_slot;
5521 ret = build_open_flags(&req->open.how, &op);
5524 nonblock_set = op.open_flag & O_NONBLOCK;
5525 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5526 if (issue_flags & IO_URING_F_NONBLOCK) {
5528 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5529 * it'll always -EAGAIN
5531 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5533 op.lookup_flags |= LOOKUP_CACHED;
5534 op.open_flag |= O_NONBLOCK;
5538 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5543 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5546 * We could hang on to this 'fd' on retrying, but seems like
5547 * marginal gain for something that is now known to be a slower
5548 * path. So just put it, and we'll get a new one when we retry.
5553 ret = PTR_ERR(file);
5554 /* only retry if RESOLVE_CACHED wasn't already set by application */
5555 if (ret == -EAGAIN &&
5556 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5561 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5562 file->f_flags &= ~O_NONBLOCK;
5563 fsnotify_open(file);
5566 fd_install(ret, file);
5568 ret = io_fixed_fd_install(req, issue_flags, file,
5569 req->open.file_slot);
5571 putname(req->open.filename);
5572 req->flags &= ~REQ_F_NEED_CLEANUP;
5575 __io_req_complete(req, issue_flags, ret, 0);
5579 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5581 return io_openat2(req, issue_flags);
5584 static int io_remove_buffers_prep(struct io_kiocb *req,
5585 const struct io_uring_sqe *sqe)
5587 struct io_provide_buf *p = &req->pbuf;
5590 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5594 tmp = READ_ONCE(sqe->fd);
5595 if (!tmp || tmp > USHRT_MAX)
5598 memset(p, 0, sizeof(*p));
5600 p->bgid = READ_ONCE(sqe->buf_group);
5604 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5605 struct io_buffer_list *bl, unsigned nbufs)
5609 /* shouldn't happen */
5613 if (bl->buf_nr_pages) {
5616 i = bl->buf_ring->tail - bl->head;
5617 for (j = 0; j < bl->buf_nr_pages; j++)
5618 unpin_user_page(bl->buf_pages[j]);
5619 kvfree(bl->buf_pages);
5620 bl->buf_pages = NULL;
5621 bl->buf_nr_pages = 0;
5622 /* make sure it's seen as empty */
5623 INIT_LIST_HEAD(&bl->buf_list);
5627 /* the head kbuf is the list itself */
5628 while (!list_empty(&bl->buf_list)) {
5629 struct io_buffer *nxt;
5631 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5632 list_del(&nxt->list);
5642 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5644 struct io_provide_buf *p = &req->pbuf;
5645 struct io_ring_ctx *ctx = req->ctx;
5646 struct io_buffer_list *bl;
5649 io_ring_submit_lock(ctx, issue_flags);
5652 bl = io_buffer_get_list(ctx, p->bgid);
5655 /* can't use provide/remove buffers command on mapped buffers */
5656 if (!bl->buf_nr_pages)
5657 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5662 /* complete before unlock, IOPOLL may need the lock */
5663 __io_req_complete(req, issue_flags, ret, 0);
5664 io_ring_submit_unlock(ctx, issue_flags);
5668 static int io_provide_buffers_prep(struct io_kiocb *req,
5669 const struct io_uring_sqe *sqe)
5671 unsigned long size, tmp_check;
5672 struct io_provide_buf *p = &req->pbuf;
5675 if (sqe->rw_flags || sqe->splice_fd_in)
5678 tmp = READ_ONCE(sqe->fd);
5679 if (!tmp || tmp > USHRT_MAX)
5682 p->addr = READ_ONCE(sqe->addr);
5683 p->len = READ_ONCE(sqe->len);
5685 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5688 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5691 size = (unsigned long)p->len * p->nbufs;
5692 if (!access_ok(u64_to_user_ptr(p->addr), size))
5695 p->bgid = READ_ONCE(sqe->buf_group);
5696 tmp = READ_ONCE(sqe->off);
5697 if (tmp > USHRT_MAX)
5703 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5705 struct io_buffer *buf;
5710 * Completions that don't happen inline (eg not under uring_lock) will
5711 * add to ->io_buffers_comp. If we don't have any free buffers, check
5712 * the completion list and splice those entries first.
5714 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5715 spin_lock(&ctx->completion_lock);
5716 if (!list_empty(&ctx->io_buffers_comp)) {
5717 list_splice_init(&ctx->io_buffers_comp,
5718 &ctx->io_buffers_cache);
5719 spin_unlock(&ctx->completion_lock);
5722 spin_unlock(&ctx->completion_lock);
5726 * No free buffers and no completion entries either. Allocate a new
5727 * page worth of buffer entries and add those to our freelist.
5729 page = alloc_page(GFP_KERNEL_ACCOUNT);
5733 list_add(&page->lru, &ctx->io_buffers_pages);
5735 buf = page_address(page);
5736 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5737 while (bufs_in_page) {
5738 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5746 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5747 struct io_buffer_list *bl)
5749 struct io_buffer *buf;
5750 u64 addr = pbuf->addr;
5751 int i, bid = pbuf->bid;
5753 for (i = 0; i < pbuf->nbufs; i++) {
5754 if (list_empty(&ctx->io_buffers_cache) &&
5755 io_refill_buffer_cache(ctx))
5757 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5759 list_move_tail(&buf->list, &bl->buf_list);
5761 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5763 buf->bgid = pbuf->bgid;
5769 return i ? 0 : -ENOMEM;
5772 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5776 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5781 for (i = 0; i < BGID_ARRAY; i++) {
5782 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5783 ctx->io_bl[i].bgid = i;
5789 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5791 struct io_provide_buf *p = &req->pbuf;
5792 struct io_ring_ctx *ctx = req->ctx;
5793 struct io_buffer_list *bl;
5796 io_ring_submit_lock(ctx, issue_flags);
5798 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5799 ret = io_init_bl_list(ctx);
5804 bl = io_buffer_get_list(ctx, p->bgid);
5805 if (unlikely(!bl)) {
5806 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5811 INIT_LIST_HEAD(&bl->buf_list);
5812 ret = io_buffer_add_list(ctx, bl, p->bgid);
5818 /* can't add buffers via this command for a mapped buffer ring */
5819 if (bl->buf_nr_pages) {
5824 ret = io_add_buffers(ctx, p, bl);
5828 /* complete before unlock, IOPOLL may need the lock */
5829 __io_req_complete(req, issue_flags, ret, 0);
5830 io_ring_submit_unlock(ctx, issue_flags);
5834 static int io_epoll_ctl_prep(struct io_kiocb *req,
5835 const struct io_uring_sqe *sqe)
5837 #if defined(CONFIG_EPOLL)
5838 if (sqe->buf_index || sqe->splice_fd_in)
5841 req->epoll.epfd = READ_ONCE(sqe->fd);
5842 req->epoll.op = READ_ONCE(sqe->len);
5843 req->epoll.fd = READ_ONCE(sqe->off);
5845 if (ep_op_has_event(req->epoll.op)) {
5846 struct epoll_event __user *ev;
5848 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5849 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5859 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5861 #if defined(CONFIG_EPOLL)
5862 struct io_epoll *ie = &req->epoll;
5864 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5866 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5867 if (force_nonblock && ret == -EAGAIN)
5872 __io_req_complete(req, issue_flags, ret, 0);
5879 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5881 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5882 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5885 req->madvise.addr = READ_ONCE(sqe->addr);
5886 req->madvise.len = READ_ONCE(sqe->len);
5887 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5894 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5896 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5897 struct io_madvise *ma = &req->madvise;
5900 if (issue_flags & IO_URING_F_NONBLOCK)
5903 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5904 io_req_complete(req, ret);
5911 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5913 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5916 req->fadvise.offset = READ_ONCE(sqe->off);
5917 req->fadvise.len = READ_ONCE(sqe->len);
5918 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5922 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5924 struct io_fadvise *fa = &req->fadvise;
5927 if (issue_flags & IO_URING_F_NONBLOCK) {
5928 switch (fa->advice) {
5929 case POSIX_FADV_NORMAL:
5930 case POSIX_FADV_RANDOM:
5931 case POSIX_FADV_SEQUENTIAL:
5938 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5941 __io_req_complete(req, issue_flags, ret, 0);
5945 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5947 const char __user *path;
5949 if (sqe->buf_index || sqe->splice_fd_in)
5951 if (req->flags & REQ_F_FIXED_FILE)
5954 req->statx.dfd = READ_ONCE(sqe->fd);
5955 req->statx.mask = READ_ONCE(sqe->len);
5956 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5957 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5958 req->statx.flags = READ_ONCE(sqe->statx_flags);
5960 req->statx.filename = getname_flags(path,
5961 getname_statx_lookup_flags(req->statx.flags),
5964 if (IS_ERR(req->statx.filename)) {
5965 int ret = PTR_ERR(req->statx.filename);
5967 req->statx.filename = NULL;
5971 req->flags |= REQ_F_NEED_CLEANUP;
5975 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5977 struct io_statx *ctx = &req->statx;
5980 if (issue_flags & IO_URING_F_NONBLOCK)
5983 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5985 io_req_complete(req, ret);
5989 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5991 if (sqe->off || sqe->addr || sqe->len || sqe->buf_index)
5993 if (req->flags & REQ_F_FIXED_FILE)
5996 req->close.fd = READ_ONCE(sqe->fd);
5997 req->close.file_slot = READ_ONCE(sqe->file_index);
5998 req->close.flags = READ_ONCE(sqe->close_flags);
5999 if (req->close.flags & ~IORING_CLOSE_FD_AND_FILE_SLOT)
6001 if (!(req->close.flags & IORING_CLOSE_FD_AND_FILE_SLOT) &&
6002 req->close.file_slot && req->close.fd)
6008 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
6010 struct files_struct *files = current->files;
6011 struct io_close *close = &req->close;
6012 struct fdtable *fdt;
6013 struct file *file = NULL;
6016 if (req->close.file_slot) {
6017 ret = io_close_fixed(req, issue_flags);
6018 if (ret || !(req->close.flags & IORING_CLOSE_FD_AND_FILE_SLOT))
6022 spin_lock(&files->file_lock);
6023 fdt = files_fdtable(files);
6024 if (close->fd >= fdt->max_fds) {
6025 spin_unlock(&files->file_lock);
6028 file = rcu_dereference_protected(fdt->fd[close->fd],
6029 lockdep_is_held(&files->file_lock));
6030 if (!file || file->f_op == &io_uring_fops) {
6031 spin_unlock(&files->file_lock);
6036 /* if the file has a flush method, be safe and punt to async */
6037 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
6038 spin_unlock(&files->file_lock);
6042 file = __close_fd_get_file(close->fd);
6043 spin_unlock(&files->file_lock);
6047 /* No ->flush() or already async, safely close from here */
6048 ret = filp_close(file, current->files);
6054 __io_req_complete(req, issue_flags, ret, 0);
6058 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6060 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
6063 req->sync.off = READ_ONCE(sqe->off);
6064 req->sync.len = READ_ONCE(sqe->len);
6065 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
6069 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
6073 /* sync_file_range always requires a blocking context */
6074 if (issue_flags & IO_URING_F_NONBLOCK)
6077 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
6079 io_req_complete(req, ret);
6083 #if defined(CONFIG_NET)
6084 static int io_shutdown_prep(struct io_kiocb *req,
6085 const struct io_uring_sqe *sqe)
6087 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
6088 sqe->buf_index || sqe->splice_fd_in))
6091 req->shutdown.how = READ_ONCE(sqe->len);
6095 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
6097 struct socket *sock;
6100 if (issue_flags & IO_URING_F_NONBLOCK)
6103 sock = sock_from_file(req->file);
6104 if (unlikely(!sock))
6107 ret = __sys_shutdown_sock(sock, req->shutdown.how);
6108 io_req_complete(req, ret);
6112 static bool io_net_retry(struct socket *sock, int flags)
6114 if (!(flags & MSG_WAITALL))
6116 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
6119 static int io_setup_async_msg(struct io_kiocb *req,
6120 struct io_async_msghdr *kmsg)
6122 struct io_async_msghdr *async_msg = req->async_data;
6126 if (io_alloc_async_data(req)) {
6127 kfree(kmsg->free_iov);
6130 async_msg = req->async_data;
6131 req->flags |= REQ_F_NEED_CLEANUP;
6132 memcpy(async_msg, kmsg, sizeof(*kmsg));
6133 async_msg->msg.msg_name = &async_msg->addr;
6134 /* if were using fast_iov, set it to the new one */
6135 if (!async_msg->free_iov)
6136 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
6141 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
6142 struct io_async_msghdr *iomsg)
6144 iomsg->msg.msg_name = &iomsg->addr;
6145 iomsg->free_iov = iomsg->fast_iov;
6146 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
6147 req->sr_msg.msg_flags, &iomsg->free_iov);
6150 static int io_sendmsg_prep_async(struct io_kiocb *req)
6154 ret = io_sendmsg_copy_hdr(req, req->async_data);
6156 req->flags |= REQ_F_NEED_CLEANUP;
6160 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6162 struct io_sr_msg *sr = &req->sr_msg;
6164 if (unlikely(sqe->file_index))
6166 if (unlikely(sqe->addr2 || sqe->file_index))
6169 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6170 sr->len = READ_ONCE(sqe->len);
6171 sr->flags = READ_ONCE(sqe->addr2);
6172 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6174 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6175 if (sr->msg_flags & MSG_DONTWAIT)
6176 req->flags |= REQ_F_NOWAIT;
6178 #ifdef CONFIG_COMPAT
6179 if (req->ctx->compat)
6180 sr->msg_flags |= MSG_CMSG_COMPAT;
6186 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
6188 struct io_async_msghdr iomsg, *kmsg;
6189 struct io_sr_msg *sr = &req->sr_msg;
6190 struct socket *sock;
6195 sock = sock_from_file(req->file);
6196 if (unlikely(!sock))
6199 if (req_has_async_data(req)) {
6200 kmsg = req->async_data;
6202 ret = io_sendmsg_copy_hdr(req, &iomsg);
6208 if (!(req->flags & REQ_F_POLLED) &&
6209 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6210 return io_setup_async_msg(req, kmsg);
6212 flags = sr->msg_flags;
6213 if (issue_flags & IO_URING_F_NONBLOCK)
6214 flags |= MSG_DONTWAIT;
6215 if (flags & MSG_WAITALL)
6216 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6218 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
6220 if (ret < min_ret) {
6221 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6222 return io_setup_async_msg(req, kmsg);
6223 if (ret == -ERESTARTSYS)
6225 if (ret > 0 && io_net_retry(sock, flags)) {
6227 req->flags |= REQ_F_PARTIAL_IO;
6228 return io_setup_async_msg(req, kmsg);
6232 /* fast path, check for non-NULL to avoid function call */
6234 kfree(kmsg->free_iov);
6235 req->flags &= ~REQ_F_NEED_CLEANUP;
6238 else if (sr->done_io)
6240 __io_req_complete(req, issue_flags, ret, 0);
6244 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6246 struct io_sr_msg *sr = &req->sr_msg;
6249 struct socket *sock;
6254 if (!(req->flags & REQ_F_POLLED) &&
6255 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6258 sock = sock_from_file(req->file);
6259 if (unlikely(!sock))
6262 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6266 msg.msg_name = NULL;
6267 msg.msg_control = NULL;
6268 msg.msg_controllen = 0;
6269 msg.msg_namelen = 0;
6271 flags = sr->msg_flags;
6272 if (issue_flags & IO_URING_F_NONBLOCK)
6273 flags |= MSG_DONTWAIT;
6274 if (flags & MSG_WAITALL)
6275 min_ret = iov_iter_count(&msg.msg_iter);
6277 msg.msg_flags = flags;
6278 ret = sock_sendmsg(sock, &msg);
6279 if (ret < min_ret) {
6280 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6282 if (ret == -ERESTARTSYS)
6284 if (ret > 0 && io_net_retry(sock, flags)) {
6288 req->flags |= REQ_F_PARTIAL_IO;
6295 else if (sr->done_io)
6297 __io_req_complete(req, issue_flags, ret, 0);
6301 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6302 struct io_async_msghdr *iomsg)
6304 struct io_sr_msg *sr = &req->sr_msg;
6305 struct iovec __user *uiov;
6309 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6310 &iomsg->uaddr, &uiov, &iov_len);
6314 if (req->flags & REQ_F_BUFFER_SELECT) {
6317 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6319 sr->len = iomsg->fast_iov[0].iov_len;
6320 iomsg->free_iov = NULL;
6322 iomsg->free_iov = iomsg->fast_iov;
6323 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6324 &iomsg->free_iov, &iomsg->msg.msg_iter,
6333 #ifdef CONFIG_COMPAT
6334 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6335 struct io_async_msghdr *iomsg)
6337 struct io_sr_msg *sr = &req->sr_msg;
6338 struct compat_iovec __user *uiov;
6343 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6348 uiov = compat_ptr(ptr);
6349 if (req->flags & REQ_F_BUFFER_SELECT) {
6350 compat_ssize_t clen;
6354 if (!access_ok(uiov, sizeof(*uiov)))
6356 if (__get_user(clen, &uiov->iov_len))
6361 iomsg->free_iov = NULL;
6363 iomsg->free_iov = iomsg->fast_iov;
6364 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6365 UIO_FASTIOV, &iomsg->free_iov,
6366 &iomsg->msg.msg_iter, true);
6375 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6376 struct io_async_msghdr *iomsg)
6378 iomsg->msg.msg_name = &iomsg->addr;
6380 #ifdef CONFIG_COMPAT
6381 if (req->ctx->compat)
6382 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6385 return __io_recvmsg_copy_hdr(req, iomsg);
6388 static int io_recvmsg_prep_async(struct io_kiocb *req)
6392 ret = io_recvmsg_copy_hdr(req, req->async_data);
6394 req->flags |= REQ_F_NEED_CLEANUP;
6398 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6400 struct io_sr_msg *sr = &req->sr_msg;
6402 if (unlikely(sqe->file_index))
6404 if (unlikely(sqe->addr2 || sqe->file_index))
6407 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6408 sr->len = READ_ONCE(sqe->len);
6409 sr->flags = READ_ONCE(sqe->addr2);
6410 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6412 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6413 if (sr->msg_flags & MSG_DONTWAIT)
6414 req->flags |= REQ_F_NOWAIT;
6416 #ifdef CONFIG_COMPAT
6417 if (req->ctx->compat)
6418 sr->msg_flags |= MSG_CMSG_COMPAT;
6424 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6426 struct io_async_msghdr iomsg, *kmsg;
6427 struct io_sr_msg *sr = &req->sr_msg;
6428 struct socket *sock;
6429 unsigned int cflags;
6431 int ret, min_ret = 0;
6432 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6434 sock = sock_from_file(req->file);
6435 if (unlikely(!sock))
6438 if (req_has_async_data(req)) {
6439 kmsg = req->async_data;
6441 ret = io_recvmsg_copy_hdr(req, &iomsg);
6447 if (!(req->flags & REQ_F_POLLED) &&
6448 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6449 return io_setup_async_msg(req, kmsg);
6451 if (io_do_buffer_select(req)) {
6454 buf = io_buffer_select(req, &sr->len, issue_flags);
6457 kmsg->fast_iov[0].iov_base = buf;
6458 kmsg->fast_iov[0].iov_len = sr->len;
6459 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6463 flags = sr->msg_flags;
6465 flags |= MSG_DONTWAIT;
6466 if (flags & MSG_WAITALL)
6467 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6469 kmsg->msg.msg_get_inq = 1;
6470 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6471 if (ret < min_ret) {
6472 if (ret == -EAGAIN && force_nonblock)
6473 return io_setup_async_msg(req, kmsg);
6474 if (ret == -ERESTARTSYS)
6476 if (ret > 0 && io_net_retry(sock, flags)) {
6478 req->flags |= REQ_F_PARTIAL_IO;
6479 return io_setup_async_msg(req, kmsg);
6482 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6486 /* fast path, check for non-NULL to avoid function call */
6488 kfree(kmsg->free_iov);
6489 req->flags &= ~REQ_F_NEED_CLEANUP;
6492 else if (sr->done_io)
6494 cflags = io_put_kbuf(req, issue_flags);
6495 if (kmsg->msg.msg_inq)
6496 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6497 __io_req_complete(req, issue_flags, ret, cflags);
6501 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6503 struct io_sr_msg *sr = &req->sr_msg;
6505 struct socket *sock;
6507 unsigned int cflags;
6509 int ret, min_ret = 0;
6510 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6512 if (!(req->flags & REQ_F_POLLED) &&
6513 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6516 sock = sock_from_file(req->file);
6517 if (unlikely(!sock))
6520 if (io_do_buffer_select(req)) {
6523 buf = io_buffer_select(req, &sr->len, issue_flags);
6529 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6533 msg.msg_name = NULL;
6534 msg.msg_namelen = 0;
6535 msg.msg_control = NULL;
6536 msg.msg_get_inq = 1;
6538 msg.msg_controllen = 0;
6539 msg.msg_iocb = NULL;
6541 flags = sr->msg_flags;
6543 flags |= MSG_DONTWAIT;
6544 if (flags & MSG_WAITALL)
6545 min_ret = iov_iter_count(&msg.msg_iter);
6547 ret = sock_recvmsg(sock, &msg, flags);
6548 if (ret < min_ret) {
6549 if (ret == -EAGAIN && force_nonblock)
6551 if (ret == -ERESTARTSYS)
6553 if (ret > 0 && io_net_retry(sock, flags)) {
6557 req->flags |= REQ_F_PARTIAL_IO;
6561 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6568 else if (sr->done_io)
6570 cflags = io_put_kbuf(req, issue_flags);
6572 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6573 __io_req_complete(req, issue_flags, ret, cflags);
6577 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6579 struct io_accept *accept = &req->accept;
6582 if (sqe->len || sqe->buf_index)
6585 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6586 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6587 accept->flags = READ_ONCE(sqe->accept_flags);
6588 accept->nofile = rlimit(RLIMIT_NOFILE);
6589 flags = READ_ONCE(sqe->ioprio);
6590 if (flags & ~IORING_ACCEPT_MULTISHOT)
6593 accept->file_slot = READ_ONCE(sqe->file_index);
6594 if (accept->file_slot) {
6595 if (accept->flags & SOCK_CLOEXEC)
6597 if (flags & IORING_ACCEPT_MULTISHOT &&
6598 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6601 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6603 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6604 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6605 if (flags & IORING_ACCEPT_MULTISHOT)
6606 req->flags |= REQ_F_APOLL_MULTISHOT;
6610 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6612 struct io_ring_ctx *ctx = req->ctx;
6613 struct io_accept *accept = &req->accept;
6614 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6615 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6616 bool fixed = !!accept->file_slot;
6622 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6623 if (unlikely(fd < 0))
6626 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6631 ret = PTR_ERR(file);
6632 if (ret == -EAGAIN && force_nonblock) {
6634 * if it's multishot and polled, we don't need to
6635 * return EAGAIN to arm the poll infra since it
6636 * has already been done
6638 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6639 IO_APOLL_MULTI_POLLED)
6643 if (ret == -ERESTARTSYS)
6646 } else if (!fixed) {
6647 fd_install(fd, file);
6650 ret = io_fixed_fd_install(req, issue_flags, file,
6654 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6655 __io_req_complete(req, issue_flags, ret, 0);
6661 spin_lock(&ctx->completion_lock);
6662 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6664 io_commit_cqring(ctx);
6665 spin_unlock(&ctx->completion_lock);
6667 io_cqring_ev_posted(ctx);
6676 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6678 struct io_socket *sock = &req->sock;
6680 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6683 sock->domain = READ_ONCE(sqe->fd);
6684 sock->type = READ_ONCE(sqe->off);
6685 sock->protocol = READ_ONCE(sqe->len);
6686 sock->file_slot = READ_ONCE(sqe->file_index);
6687 sock->nofile = rlimit(RLIMIT_NOFILE);
6689 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6690 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6692 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6697 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6699 struct io_socket *sock = &req->sock;
6700 bool fixed = !!sock->file_slot;
6705 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6706 if (unlikely(fd < 0))
6709 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6713 ret = PTR_ERR(file);
6714 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6716 if (ret == -ERESTARTSYS)
6719 } else if (!fixed) {
6720 fd_install(fd, file);
6723 ret = io_fixed_fd_install(req, issue_flags, file,
6726 __io_req_complete(req, issue_flags, ret, 0);
6730 static int io_connect_prep_async(struct io_kiocb *req)
6732 struct io_async_connect *io = req->async_data;
6733 struct io_connect *conn = &req->connect;
6735 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6738 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6740 struct io_connect *conn = &req->connect;
6742 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6745 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6746 conn->addr_len = READ_ONCE(sqe->addr2);
6750 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6752 struct io_async_connect __io, *io;
6753 unsigned file_flags;
6755 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6757 if (req_has_async_data(req)) {
6758 io = req->async_data;
6760 ret = move_addr_to_kernel(req->connect.addr,
6761 req->connect.addr_len,
6768 file_flags = force_nonblock ? O_NONBLOCK : 0;
6770 ret = __sys_connect_file(req->file, &io->address,
6771 req->connect.addr_len, file_flags);
6772 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6773 if (req_has_async_data(req))
6775 if (io_alloc_async_data(req)) {
6779 memcpy(req->async_data, &__io, sizeof(__io));
6782 if (ret == -ERESTARTSYS)
6787 __io_req_complete(req, issue_flags, ret, 0);
6790 #else /* !CONFIG_NET */
6791 #define IO_NETOP_FN(op) \
6792 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6794 return -EOPNOTSUPP; \
6797 #define IO_NETOP_PREP(op) \
6799 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6801 return -EOPNOTSUPP; \
6804 #define IO_NETOP_PREP_ASYNC(op) \
6806 static int io_##op##_prep_async(struct io_kiocb *req) \
6808 return -EOPNOTSUPP; \
6811 IO_NETOP_PREP_ASYNC(sendmsg);
6812 IO_NETOP_PREP_ASYNC(recvmsg);
6813 IO_NETOP_PREP_ASYNC(connect);
6814 IO_NETOP_PREP(accept);
6815 IO_NETOP_PREP(socket);
6816 IO_NETOP_PREP(shutdown);
6819 #endif /* CONFIG_NET */
6821 struct io_poll_table {
6822 struct poll_table_struct pt;
6823 struct io_kiocb *req;
6828 #define IO_POLL_CANCEL_FLAG BIT(31)
6829 #define IO_POLL_REF_MASK GENMASK(30, 0)
6832 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6833 * bump it and acquire ownership. It's disallowed to modify requests while not
6834 * owning it, that prevents from races for enqueueing task_work's and b/w
6835 * arming poll and wakeups.
6837 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6839 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6842 static void io_poll_mark_cancelled(struct io_kiocb *req)
6844 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6847 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6849 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6850 if (req->opcode == IORING_OP_POLL_ADD)
6851 return req->async_data;
6852 return req->apoll->double_poll;
6855 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6857 if (req->opcode == IORING_OP_POLL_ADD)
6859 return &req->apoll->poll;
6862 static void io_poll_req_insert(struct io_kiocb *req)
6864 struct io_ring_ctx *ctx = req->ctx;
6865 struct hlist_head *list;
6867 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6868 hlist_add_head(&req->hash_node, list);
6871 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6872 wait_queue_func_t wake_func)
6875 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6876 /* mask in events that we always want/need */
6877 poll->events = events | IO_POLL_UNMASK;
6878 INIT_LIST_HEAD(&poll->wait.entry);
6879 init_waitqueue_func_entry(&poll->wait, wake_func);
6882 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6884 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6887 spin_lock_irq(&head->lock);
6888 list_del_init(&poll->wait.entry);
6890 spin_unlock_irq(&head->lock);
6894 static void io_poll_remove_entries(struct io_kiocb *req)
6897 * Nothing to do if neither of those flags are set. Avoid dipping
6898 * into the poll/apoll/double cachelines if we can.
6900 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6904 * While we hold the waitqueue lock and the waitqueue is nonempty,
6905 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6906 * lock in the first place can race with the waitqueue being freed.
6908 * We solve this as eventpoll does: by taking advantage of the fact that
6909 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6910 * we enter rcu_read_lock() and see that the pointer to the queue is
6911 * non-NULL, we can then lock it without the memory being freed out from
6914 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6915 * case the caller deletes the entry from the queue, leaving it empty.
6916 * In that case, only RCU prevents the queue memory from being freed.
6919 if (req->flags & REQ_F_SINGLE_POLL)
6920 io_poll_remove_entry(io_poll_get_single(req));
6921 if (req->flags & REQ_F_DOUBLE_POLL)
6922 io_poll_remove_entry(io_poll_get_double(req));
6926 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6928 * All poll tw should go through this. Checks for poll events, manages
6929 * references, does rewait, etc.
6931 * Returns a negative error on failure. >0 when no action require, which is
6932 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6933 * the request, then the mask is stored in req->cqe.res.
6935 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6937 struct io_ring_ctx *ctx = req->ctx;
6940 /* req->task == current here, checking PF_EXITING is safe */
6941 if (unlikely(req->task->flags & PF_EXITING))
6945 v = atomic_read(&req->poll_refs);
6947 /* tw handler should be the owner, and so have some references */
6948 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6950 if (v & IO_POLL_CANCEL_FLAG)
6953 if (!req->cqe.res) {
6954 struct poll_table_struct pt = { ._key = req->apoll_events };
6955 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6958 if ((unlikely(!req->cqe.res)))
6960 if (req->apoll_events & EPOLLONESHOT)
6963 /* multishot, just fill a CQE and proceed */
6964 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6965 __poll_t mask = mangle_poll(req->cqe.res &
6969 spin_lock(&ctx->completion_lock);
6970 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6971 mask, IORING_CQE_F_MORE);
6972 io_commit_cqring(ctx);
6973 spin_unlock(&ctx->completion_lock);
6975 io_cqring_ev_posted(ctx);
6981 io_tw_lock(req->ctx, locked);
6982 if (unlikely(req->task->flags & PF_EXITING))
6984 ret = io_issue_sqe(req,
6985 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6990 * Release all references, retry if someone tried to restart
6991 * task_work while we were executing it.
6993 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6998 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
7000 struct io_ring_ctx *ctx = req->ctx;
7003 ret = io_poll_check_events(req, locked);
7008 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
7014 io_poll_remove_entries(req);
7015 spin_lock(&ctx->completion_lock);
7016 hash_del(&req->hash_node);
7017 __io_req_complete_post(req, req->cqe.res, 0);
7018 io_commit_cqring(ctx);
7019 spin_unlock(&ctx->completion_lock);
7020 io_cqring_ev_posted(ctx);
7023 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
7025 struct io_ring_ctx *ctx = req->ctx;
7028 ret = io_poll_check_events(req, locked);
7032 io_poll_remove_entries(req);
7033 spin_lock(&ctx->completion_lock);
7034 hash_del(&req->hash_node);
7035 spin_unlock(&ctx->completion_lock);
7038 io_req_task_submit(req, locked);
7040 io_req_complete_failed(req, ret);
7043 static void __io_poll_execute(struct io_kiocb *req, int mask, __poll_t events)
7045 req->cqe.res = mask;
7047 * This is useful for poll that is armed on behalf of another
7048 * request, and where the wakeup path could be on a different
7049 * CPU. We want to avoid pulling in req->apoll->events for that
7052 req->apoll_events = events;
7053 if (req->opcode == IORING_OP_POLL_ADD)
7054 req->io_task_work.func = io_poll_task_func;
7056 req->io_task_work.func = io_apoll_task_func;
7058 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
7059 io_req_task_work_add(req);
7062 static inline void io_poll_execute(struct io_kiocb *req, int res,
7065 if (io_poll_get_ownership(req))
7066 __io_poll_execute(req, res, events);
7069 static void io_poll_cancel_req(struct io_kiocb *req)
7071 io_poll_mark_cancelled(req);
7072 /* kick tw, which should complete the request */
7073 io_poll_execute(req, 0, 0);
7076 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
7077 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
7078 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
7080 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
7083 struct io_kiocb *req = wqe_to_req(wait);
7084 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
7086 __poll_t mask = key_to_poll(key);
7088 if (unlikely(mask & POLLFREE)) {
7089 io_poll_mark_cancelled(req);
7090 /* we have to kick tw in case it's not already */
7091 io_poll_execute(req, 0, poll->events);
7094 * If the waitqueue is being freed early but someone is already
7095 * holds ownership over it, we have to tear down the request as
7096 * best we can. That means immediately removing the request from
7097 * its waitqueue and preventing all further accesses to the
7098 * waitqueue via the request.
7100 list_del_init(&poll->wait.entry);
7103 * Careful: this *must* be the last step, since as soon
7104 * as req->head is NULL'ed out, the request can be
7105 * completed and freed, since aio_poll_complete_work()
7106 * will no longer need to take the waitqueue lock.
7108 smp_store_release(&poll->head, NULL);
7112 /* for instances that support it check for an event match first */
7113 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
7116 if (io_poll_get_ownership(req)) {
7117 /* optional, saves extra locking for removal in tw handler */
7118 if (mask && poll->events & EPOLLONESHOT) {
7119 list_del_init(&poll->wait.entry);
7121 if (wqe_is_double(wait))
7122 req->flags &= ~REQ_F_DOUBLE_POLL;
7124 req->flags &= ~REQ_F_SINGLE_POLL;
7126 __io_poll_execute(req, mask, poll->events);
7131 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
7132 struct wait_queue_head *head,
7133 struct io_poll_iocb **poll_ptr)
7135 struct io_kiocb *req = pt->req;
7136 unsigned long wqe_private = (unsigned long) req;
7139 * The file being polled uses multiple waitqueues for poll handling
7140 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
7143 if (unlikely(pt->nr_entries)) {
7144 struct io_poll_iocb *first = poll;
7146 /* double add on the same waitqueue head, ignore */
7147 if (first->head == head)
7149 /* already have a 2nd entry, fail a third attempt */
7151 if ((*poll_ptr)->head == head)
7153 pt->error = -EINVAL;
7157 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
7159 pt->error = -ENOMEM;
7162 /* mark as double wq entry */
7164 req->flags |= REQ_F_DOUBLE_POLL;
7165 io_init_poll_iocb(poll, first->events, first->wait.func);
7167 if (req->opcode == IORING_OP_POLL_ADD)
7168 req->flags |= REQ_F_ASYNC_DATA;
7171 req->flags |= REQ_F_SINGLE_POLL;
7174 poll->wait.private = (void *) wqe_private;
7176 if (poll->events & EPOLLEXCLUSIVE)
7177 add_wait_queue_exclusive(head, &poll->wait);
7179 add_wait_queue(head, &poll->wait);
7182 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
7183 struct poll_table_struct *p)
7185 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7187 __io_queue_proc(&pt->req->poll, pt, head,
7188 (struct io_poll_iocb **) &pt->req->async_data);
7191 static int __io_arm_poll_handler(struct io_kiocb *req,
7192 struct io_poll_iocb *poll,
7193 struct io_poll_table *ipt, __poll_t mask)
7195 struct io_ring_ctx *ctx = req->ctx;
7198 INIT_HLIST_NODE(&req->hash_node);
7199 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
7200 io_init_poll_iocb(poll, mask, io_poll_wake);
7201 poll->file = req->file;
7203 ipt->pt._key = mask;
7206 ipt->nr_entries = 0;
7209 * Take the ownership to delay any tw execution up until we're done
7210 * with poll arming. see io_poll_get_ownership().
7212 atomic_set(&req->poll_refs, 1);
7213 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
7215 if (mask && (poll->events & EPOLLONESHOT)) {
7216 io_poll_remove_entries(req);
7217 /* no one else has access to the req, forget about the ref */
7220 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
7221 io_poll_remove_entries(req);
7223 ipt->error = -EINVAL;
7227 spin_lock(&ctx->completion_lock);
7228 io_poll_req_insert(req);
7229 spin_unlock(&ctx->completion_lock);
7232 /* can't multishot if failed, just queue the event we've got */
7233 if (unlikely(ipt->error || !ipt->nr_entries))
7234 poll->events |= EPOLLONESHOT;
7235 __io_poll_execute(req, mask, poll->events);
7240 * Release ownership. If someone tried to queue a tw while it was
7241 * locked, kick it off for them.
7243 v = atomic_dec_return(&req->poll_refs);
7244 if (unlikely(v & IO_POLL_REF_MASK))
7245 __io_poll_execute(req, 0, poll->events);
7249 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7250 struct poll_table_struct *p)
7252 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7253 struct async_poll *apoll = pt->req->apoll;
7255 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7264 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7266 const struct io_op_def *def = &io_op_defs[req->opcode];
7267 struct io_ring_ctx *ctx = req->ctx;
7268 struct async_poll *apoll;
7269 struct io_poll_table ipt;
7270 __poll_t mask = POLLPRI | POLLERR;
7273 if (!def->pollin && !def->pollout)
7274 return IO_APOLL_ABORTED;
7275 if (!file_can_poll(req->file))
7276 return IO_APOLL_ABORTED;
7277 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7278 return IO_APOLL_ABORTED;
7279 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7280 mask |= EPOLLONESHOT;
7283 mask |= EPOLLIN | EPOLLRDNORM;
7285 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7286 if ((req->opcode == IORING_OP_RECVMSG) &&
7287 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7290 mask |= EPOLLOUT | EPOLLWRNORM;
7292 if (def->poll_exclusive)
7293 mask |= EPOLLEXCLUSIVE;
7294 if (req->flags & REQ_F_POLLED) {
7296 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7297 !list_empty(&ctx->apoll_cache)) {
7298 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7300 list_del_init(&apoll->poll.wait.entry);
7302 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7303 if (unlikely(!apoll))
7304 return IO_APOLL_ABORTED;
7306 apoll->double_poll = NULL;
7308 req->flags |= REQ_F_POLLED;
7309 ipt.pt._qproc = io_async_queue_proc;
7311 io_kbuf_recycle(req, issue_flags);
7313 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7314 if (ret || ipt.error)
7315 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7317 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7318 mask, apoll->poll.events);
7323 * Returns true if we found and killed one or more poll requests
7325 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7326 struct task_struct *tsk, bool cancel_all)
7328 struct hlist_node *tmp;
7329 struct io_kiocb *req;
7333 spin_lock(&ctx->completion_lock);
7334 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7335 struct hlist_head *list;
7337 list = &ctx->cancel_hash[i];
7338 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7339 if (io_match_task_safe(req, tsk, cancel_all)) {
7340 hlist_del_init(&req->hash_node);
7341 io_poll_cancel_req(req);
7346 spin_unlock(&ctx->completion_lock);
7350 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7351 struct io_cancel_data *cd)
7352 __must_hold(&ctx->completion_lock)
7354 struct hlist_head *list;
7355 struct io_kiocb *req;
7357 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7358 hlist_for_each_entry(req, list, hash_node) {
7359 if (cd->data != req->cqe.user_data)
7361 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7363 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7364 if (cd->seq == req->work.cancel_seq)
7366 req->work.cancel_seq = cd->seq;
7373 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7374 struct io_cancel_data *cd)
7375 __must_hold(&ctx->completion_lock)
7377 struct io_kiocb *req;
7380 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7381 struct hlist_head *list;
7383 list = &ctx->cancel_hash[i];
7384 hlist_for_each_entry(req, list, hash_node) {
7385 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7386 req->file != cd->file)
7388 if (cd->seq == req->work.cancel_seq)
7390 req->work.cancel_seq = cd->seq;
7397 static bool io_poll_disarm(struct io_kiocb *req)
7398 __must_hold(&ctx->completion_lock)
7400 if (!io_poll_get_ownership(req))
7402 io_poll_remove_entries(req);
7403 hash_del(&req->hash_node);
7407 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7408 __must_hold(&ctx->completion_lock)
7410 struct io_kiocb *req;
7412 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7413 req = io_poll_file_find(ctx, cd);
7415 req = io_poll_find(ctx, false, cd);
7418 io_poll_cancel_req(req);
7422 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7427 events = READ_ONCE(sqe->poll32_events);
7429 events = swahw32(events);
7431 if (!(flags & IORING_POLL_ADD_MULTI))
7432 events |= EPOLLONESHOT;
7433 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7436 static int io_poll_remove_prep(struct io_kiocb *req,
7437 const struct io_uring_sqe *sqe)
7439 struct io_poll_update *upd = &req->poll_update;
7442 if (sqe->buf_index || sqe->splice_fd_in)
7444 flags = READ_ONCE(sqe->len);
7445 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7446 IORING_POLL_ADD_MULTI))
7448 /* meaningless without update */
7449 if (flags == IORING_POLL_ADD_MULTI)
7452 upd->old_user_data = READ_ONCE(sqe->addr);
7453 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7454 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7456 upd->new_user_data = READ_ONCE(sqe->off);
7457 if (!upd->update_user_data && upd->new_user_data)
7459 if (upd->update_events)
7460 upd->events = io_poll_parse_events(sqe, flags);
7461 else if (sqe->poll32_events)
7467 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7469 struct io_poll_iocb *poll = &req->poll;
7472 if (sqe->buf_index || sqe->off || sqe->addr)
7474 flags = READ_ONCE(sqe->len);
7475 if (flags & ~IORING_POLL_ADD_MULTI)
7477 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7480 io_req_set_refcount(req);
7481 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
7485 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7487 struct io_poll_iocb *poll = &req->poll;
7488 struct io_poll_table ipt;
7491 ipt.pt._qproc = io_poll_queue_proc;
7493 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7494 ret = ret ?: ipt.error;
7496 __io_req_complete(req, issue_flags, ret, 0);
7500 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7502 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7503 struct io_ring_ctx *ctx = req->ctx;
7504 struct io_kiocb *preq;
7508 spin_lock(&ctx->completion_lock);
7509 preq = io_poll_find(ctx, true, &cd);
7510 if (!preq || !io_poll_disarm(preq)) {
7511 spin_unlock(&ctx->completion_lock);
7512 ret = preq ? -EALREADY : -ENOENT;
7515 spin_unlock(&ctx->completion_lock);
7517 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7518 /* only mask one event flags, keep behavior flags */
7519 if (req->poll_update.update_events) {
7520 preq->poll.events &= ~0xffff;
7521 preq->poll.events |= req->poll_update.events & 0xffff;
7522 preq->poll.events |= IO_POLL_UNMASK;
7524 if (req->poll_update.update_user_data)
7525 preq->cqe.user_data = req->poll_update.new_user_data;
7527 ret2 = io_poll_add(preq, issue_flags);
7528 /* successfully updated, don't complete poll request */
7534 preq->cqe.res = -ECANCELED;
7535 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7536 io_req_task_complete(preq, &locked);
7540 /* complete update request, we're done with it */
7541 __io_req_complete(req, issue_flags, ret, 0);
7545 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7547 struct io_timeout_data *data = container_of(timer,
7548 struct io_timeout_data, timer);
7549 struct io_kiocb *req = data->req;
7550 struct io_ring_ctx *ctx = req->ctx;
7551 unsigned long flags;
7553 spin_lock_irqsave(&ctx->timeout_lock, flags);
7554 list_del_init(&req->timeout.list);
7555 atomic_set(&req->ctx->cq_timeouts,
7556 atomic_read(&req->ctx->cq_timeouts) + 1);
7557 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7559 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7562 req->cqe.res = -ETIME;
7563 req->io_task_work.func = io_req_task_complete;
7564 io_req_task_work_add(req);
7565 return HRTIMER_NORESTART;
7568 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7569 struct io_cancel_data *cd)
7570 __must_hold(&ctx->timeout_lock)
7572 struct io_timeout_data *io;
7573 struct io_kiocb *req;
7576 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7577 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7578 cd->data != req->cqe.user_data)
7580 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7581 if (cd->seq == req->work.cancel_seq)
7583 req->work.cancel_seq = cd->seq;
7589 return ERR_PTR(-ENOENT);
7591 io = req->async_data;
7592 if (hrtimer_try_to_cancel(&io->timer) == -1)
7593 return ERR_PTR(-EALREADY);
7594 list_del_init(&req->timeout.list);
7598 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7599 __must_hold(&ctx->completion_lock)
7601 struct io_kiocb *req;
7603 spin_lock_irq(&ctx->timeout_lock);
7604 req = io_timeout_extract(ctx, cd);
7605 spin_unlock_irq(&ctx->timeout_lock);
7608 return PTR_ERR(req);
7609 io_req_task_queue_fail(req, -ECANCELED);
7613 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7615 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7616 case IORING_TIMEOUT_BOOTTIME:
7617 return CLOCK_BOOTTIME;
7618 case IORING_TIMEOUT_REALTIME:
7619 return CLOCK_REALTIME;
7621 /* can't happen, vetted at prep time */
7625 return CLOCK_MONOTONIC;
7629 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7630 struct timespec64 *ts, enum hrtimer_mode mode)
7631 __must_hold(&ctx->timeout_lock)
7633 struct io_timeout_data *io;
7634 struct io_kiocb *req;
7637 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7638 found = user_data == req->cqe.user_data;
7645 io = req->async_data;
7646 if (hrtimer_try_to_cancel(&io->timer) == -1)
7648 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7649 io->timer.function = io_link_timeout_fn;
7650 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7654 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7655 struct timespec64 *ts, enum hrtimer_mode mode)
7656 __must_hold(&ctx->timeout_lock)
7658 struct io_cancel_data cd = { .data = user_data, };
7659 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7660 struct io_timeout_data *data;
7663 return PTR_ERR(req);
7665 req->timeout.off = 0; /* noseq */
7666 data = req->async_data;
7667 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7668 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7669 data->timer.function = io_timeout_fn;
7670 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7674 static int io_timeout_remove_prep(struct io_kiocb *req,
7675 const struct io_uring_sqe *sqe)
7677 struct io_timeout_rem *tr = &req->timeout_rem;
7679 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7681 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7684 tr->ltimeout = false;
7685 tr->addr = READ_ONCE(sqe->addr);
7686 tr->flags = READ_ONCE(sqe->timeout_flags);
7687 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7688 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7690 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7691 tr->ltimeout = true;
7692 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7694 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7696 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7698 } else if (tr->flags) {
7699 /* timeout removal doesn't support flags */
7706 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7708 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7713 * Remove or update an existing timeout command
7715 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7717 struct io_timeout_rem *tr = &req->timeout_rem;
7718 struct io_ring_ctx *ctx = req->ctx;
7721 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7722 struct io_cancel_data cd = { .data = tr->addr, };
7724 spin_lock(&ctx->completion_lock);
7725 ret = io_timeout_cancel(ctx, &cd);
7726 spin_unlock(&ctx->completion_lock);
7728 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7730 spin_lock_irq(&ctx->timeout_lock);
7732 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7734 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7735 spin_unlock_irq(&ctx->timeout_lock);
7740 io_req_complete_post(req, ret, 0);
7744 static int __io_timeout_prep(struct io_kiocb *req,
7745 const struct io_uring_sqe *sqe,
7746 bool is_timeout_link)
7748 struct io_timeout_data *data;
7750 u32 off = READ_ONCE(sqe->off);
7752 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7754 if (off && is_timeout_link)
7756 flags = READ_ONCE(sqe->timeout_flags);
7757 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7758 IORING_TIMEOUT_ETIME_SUCCESS))
7760 /* more than one clock specified is invalid, obviously */
7761 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7764 INIT_LIST_HEAD(&req->timeout.list);
7765 req->timeout.off = off;
7766 if (unlikely(off && !req->ctx->off_timeout_used))
7767 req->ctx->off_timeout_used = true;
7769 if (WARN_ON_ONCE(req_has_async_data(req)))
7771 if (io_alloc_async_data(req))
7774 data = req->async_data;
7776 data->flags = flags;
7778 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7781 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7784 INIT_LIST_HEAD(&req->timeout.list);
7785 data->mode = io_translate_timeout_mode(flags);
7786 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7788 if (is_timeout_link) {
7789 struct io_submit_link *link = &req->ctx->submit_state.link;
7793 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7795 req->timeout.head = link->last;
7796 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7801 static int io_timeout_prep(struct io_kiocb *req,
7802 const struct io_uring_sqe *sqe)
7804 return __io_timeout_prep(req, sqe, false);
7807 static int io_link_timeout_prep(struct io_kiocb *req,
7808 const struct io_uring_sqe *sqe)
7810 return __io_timeout_prep(req, sqe, true);
7813 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7815 struct io_ring_ctx *ctx = req->ctx;
7816 struct io_timeout_data *data = req->async_data;
7817 struct list_head *entry;
7818 u32 tail, off = req->timeout.off;
7820 spin_lock_irq(&ctx->timeout_lock);
7823 * sqe->off holds how many events that need to occur for this
7824 * timeout event to be satisfied. If it isn't set, then this is
7825 * a pure timeout request, sequence isn't used.
7827 if (io_is_timeout_noseq(req)) {
7828 entry = ctx->timeout_list.prev;
7832 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7833 req->timeout.target_seq = tail + off;
7835 /* Update the last seq here in case io_flush_timeouts() hasn't.
7836 * This is safe because ->completion_lock is held, and submissions
7837 * and completions are never mixed in the same ->completion_lock section.
7839 ctx->cq_last_tm_flush = tail;
7842 * Insertion sort, ensuring the first entry in the list is always
7843 * the one we need first.
7845 list_for_each_prev(entry, &ctx->timeout_list) {
7846 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7849 if (io_is_timeout_noseq(nxt))
7851 /* nxt.seq is behind @tail, otherwise would've been completed */
7852 if (off >= nxt->timeout.target_seq - tail)
7856 list_add(&req->timeout.list, entry);
7857 data->timer.function = io_timeout_fn;
7858 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7859 spin_unlock_irq(&ctx->timeout_lock);
7863 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7865 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7866 struct io_cancel_data *cd = data;
7868 if (req->ctx != cd->ctx)
7870 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7872 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7873 if (req->file != cd->file)
7876 if (req->cqe.user_data != cd->data)
7879 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7880 if (cd->seq == req->work.cancel_seq)
7882 req->work.cancel_seq = cd->seq;
7887 static int io_async_cancel_one(struct io_uring_task *tctx,
7888 struct io_cancel_data *cd)
7890 enum io_wq_cancel cancel_ret;
7894 if (!tctx || !tctx->io_wq)
7897 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7898 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7899 switch (cancel_ret) {
7900 case IO_WQ_CANCEL_OK:
7903 case IO_WQ_CANCEL_RUNNING:
7906 case IO_WQ_CANCEL_NOTFOUND:
7914 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7916 struct io_ring_ctx *ctx = req->ctx;
7919 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7921 ret = io_async_cancel_one(req->task->io_uring, cd);
7923 * Fall-through even for -EALREADY, as we may have poll armed
7924 * that need unarming.
7929 spin_lock(&ctx->completion_lock);
7930 ret = io_poll_cancel(ctx, cd);
7933 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7934 ret = io_timeout_cancel(ctx, cd);
7936 spin_unlock(&ctx->completion_lock);
7940 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7941 IORING_ASYNC_CANCEL_ANY)
7943 static int io_async_cancel_prep(struct io_kiocb *req,
7944 const struct io_uring_sqe *sqe)
7946 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7948 if (sqe->off || sqe->len || sqe->splice_fd_in)
7951 req->cancel.addr = READ_ONCE(sqe->addr);
7952 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7953 if (req->cancel.flags & ~CANCEL_FLAGS)
7955 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7956 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7958 req->cancel.fd = READ_ONCE(sqe->fd);
7964 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7965 unsigned int issue_flags)
7967 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7968 struct io_ring_ctx *ctx = cd->ctx;
7969 struct io_tctx_node *node;
7973 ret = io_try_cancel(req, cd);
7981 /* slow path, try all io-wq's */
7982 io_ring_submit_lock(ctx, issue_flags);
7984 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7985 struct io_uring_task *tctx = node->task->io_uring;
7987 ret = io_async_cancel_one(tctx, cd);
7988 if (ret != -ENOENT) {
7994 io_ring_submit_unlock(ctx, issue_flags);
7995 return all ? nr : ret;
7998 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
8000 struct io_cancel_data cd = {
8002 .data = req->cancel.addr,
8003 .flags = req->cancel.flags,
8004 .seq = atomic_inc_return(&req->ctx->cancel_seq),
8008 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
8009 if (req->flags & REQ_F_FIXED_FILE)
8010 req->file = io_file_get_fixed(req, req->cancel.fd,
8013 req->file = io_file_get_normal(req, req->cancel.fd);
8018 cd.file = req->file;
8021 ret = __io_async_cancel(&cd, req, issue_flags);
8025 io_req_complete_post(req, ret, 0);
8029 static int io_files_update_prep(struct io_kiocb *req,
8030 const struct io_uring_sqe *sqe)
8032 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
8034 if (sqe->rw_flags || sqe->splice_fd_in)
8037 req->rsrc_update.offset = READ_ONCE(sqe->off);
8038 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
8039 if (!req->rsrc_update.nr_args)
8041 req->rsrc_update.arg = READ_ONCE(sqe->addr);
8045 static int io_files_update_with_index_alloc(struct io_kiocb *req,
8046 unsigned int issue_flags)
8048 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
8053 for (done = 0; done < req->rsrc_update.nr_args; done++) {
8054 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
8064 ret = io_fixed_fd_install(req, issue_flags, file,
8065 IORING_FILE_INDEX_ALLOC);
8068 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
8070 __io_close_fixed(req, issue_flags, ret);
8080 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
8082 struct io_ring_ctx *ctx = req->ctx;
8083 struct io_uring_rsrc_update2 up;
8086 up.offset = req->rsrc_update.offset;
8087 up.data = req->rsrc_update.arg;
8093 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
8094 ret = io_files_update_with_index_alloc(req, issue_flags);
8096 io_ring_submit_lock(ctx, issue_flags);
8097 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
8098 &up, req->rsrc_update.nr_args);
8099 io_ring_submit_unlock(ctx, issue_flags);
8104 __io_req_complete(req, issue_flags, ret, 0);
8108 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
8110 switch (req->opcode) {
8112 return io_nop_prep(req, sqe);
8113 case IORING_OP_READV:
8114 case IORING_OP_READ_FIXED:
8115 case IORING_OP_READ:
8116 case IORING_OP_WRITEV:
8117 case IORING_OP_WRITE_FIXED:
8118 case IORING_OP_WRITE:
8119 return io_prep_rw(req, sqe);
8120 case IORING_OP_POLL_ADD:
8121 return io_poll_add_prep(req, sqe);
8122 case IORING_OP_POLL_REMOVE:
8123 return io_poll_remove_prep(req, sqe);
8124 case IORING_OP_FSYNC:
8125 return io_fsync_prep(req, sqe);
8126 case IORING_OP_SYNC_FILE_RANGE:
8127 return io_sfr_prep(req, sqe);
8128 case IORING_OP_SENDMSG:
8129 case IORING_OP_SEND:
8130 return io_sendmsg_prep(req, sqe);
8131 case IORING_OP_RECVMSG:
8132 case IORING_OP_RECV:
8133 return io_recvmsg_prep(req, sqe);
8134 case IORING_OP_CONNECT:
8135 return io_connect_prep(req, sqe);
8136 case IORING_OP_TIMEOUT:
8137 return io_timeout_prep(req, sqe);
8138 case IORING_OP_TIMEOUT_REMOVE:
8139 return io_timeout_remove_prep(req, sqe);
8140 case IORING_OP_ASYNC_CANCEL:
8141 return io_async_cancel_prep(req, sqe);
8142 case IORING_OP_LINK_TIMEOUT:
8143 return io_link_timeout_prep(req, sqe);
8144 case IORING_OP_ACCEPT:
8145 return io_accept_prep(req, sqe);
8146 case IORING_OP_FALLOCATE:
8147 return io_fallocate_prep(req, sqe);
8148 case IORING_OP_OPENAT:
8149 return io_openat_prep(req, sqe);
8150 case IORING_OP_CLOSE:
8151 return io_close_prep(req, sqe);
8152 case IORING_OP_FILES_UPDATE:
8153 return io_files_update_prep(req, sqe);
8154 case IORING_OP_STATX:
8155 return io_statx_prep(req, sqe);
8156 case IORING_OP_FADVISE:
8157 return io_fadvise_prep(req, sqe);
8158 case IORING_OP_MADVISE:
8159 return io_madvise_prep(req, sqe);
8160 case IORING_OP_OPENAT2:
8161 return io_openat2_prep(req, sqe);
8162 case IORING_OP_EPOLL_CTL:
8163 return io_epoll_ctl_prep(req, sqe);
8164 case IORING_OP_SPLICE:
8165 return io_splice_prep(req, sqe);
8166 case IORING_OP_PROVIDE_BUFFERS:
8167 return io_provide_buffers_prep(req, sqe);
8168 case IORING_OP_REMOVE_BUFFERS:
8169 return io_remove_buffers_prep(req, sqe);
8171 return io_tee_prep(req, sqe);
8172 case IORING_OP_SHUTDOWN:
8173 return io_shutdown_prep(req, sqe);
8174 case IORING_OP_RENAMEAT:
8175 return io_renameat_prep(req, sqe);
8176 case IORING_OP_UNLINKAT:
8177 return io_unlinkat_prep(req, sqe);
8178 case IORING_OP_MKDIRAT:
8179 return io_mkdirat_prep(req, sqe);
8180 case IORING_OP_SYMLINKAT:
8181 return io_symlinkat_prep(req, sqe);
8182 case IORING_OP_LINKAT:
8183 return io_linkat_prep(req, sqe);
8184 case IORING_OP_MSG_RING:
8185 return io_msg_ring_prep(req, sqe);
8186 case IORING_OP_FSETXATTR:
8187 return io_fsetxattr_prep(req, sqe);
8188 case IORING_OP_SETXATTR:
8189 return io_setxattr_prep(req, sqe);
8190 case IORING_OP_FGETXATTR:
8191 return io_fgetxattr_prep(req, sqe);
8192 case IORING_OP_GETXATTR:
8193 return io_getxattr_prep(req, sqe);
8194 case IORING_OP_SOCKET:
8195 return io_socket_prep(req, sqe);
8196 case IORING_OP_URING_CMD:
8197 return io_uring_cmd_prep(req, sqe);
8200 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
8205 static int io_req_prep_async(struct io_kiocb *req)
8207 const struct io_op_def *def = &io_op_defs[req->opcode];
8209 /* assign early for deferred execution for non-fixed file */
8210 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
8211 req->file = io_file_get_normal(req, req->cqe.fd);
8212 if (!def->needs_async_setup)
8214 if (WARN_ON_ONCE(req_has_async_data(req)))
8216 if (io_alloc_async_data(req))
8219 switch (req->opcode) {
8220 case IORING_OP_READV:
8221 return io_readv_prep_async(req);
8222 case IORING_OP_WRITEV:
8223 return io_writev_prep_async(req);
8224 case IORING_OP_SENDMSG:
8225 return io_sendmsg_prep_async(req);
8226 case IORING_OP_RECVMSG:
8227 return io_recvmsg_prep_async(req);
8228 case IORING_OP_CONNECT:
8229 return io_connect_prep_async(req);
8230 case IORING_OP_URING_CMD:
8231 return io_uring_cmd_prep_async(req);
8233 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
8238 static u32 io_get_sequence(struct io_kiocb *req)
8240 u32 seq = req->ctx->cached_sq_head;
8241 struct io_kiocb *cur;
8243 /* need original cached_sq_head, but it was increased for each req */
8244 io_for_each_link(cur, req)
8249 static __cold void io_drain_req(struct io_kiocb *req)
8251 struct io_ring_ctx *ctx = req->ctx;
8252 struct io_defer_entry *de;
8254 u32 seq = io_get_sequence(req);
8256 /* Still need defer if there is pending req in defer list. */
8257 spin_lock(&ctx->completion_lock);
8258 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
8259 spin_unlock(&ctx->completion_lock);
8261 ctx->drain_active = false;
8262 io_req_task_queue(req);
8265 spin_unlock(&ctx->completion_lock);
8267 ret = io_req_prep_async(req);
8270 io_req_complete_failed(req, ret);
8273 io_prep_async_link(req);
8274 de = kmalloc(sizeof(*de), GFP_KERNEL);
8280 spin_lock(&ctx->completion_lock);
8281 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
8282 spin_unlock(&ctx->completion_lock);
8287 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
8290 list_add_tail(&de->list, &ctx->defer_list);
8291 spin_unlock(&ctx->completion_lock);
8294 static void io_clean_op(struct io_kiocb *req)
8296 if (req->flags & REQ_F_BUFFER_SELECTED) {
8297 spin_lock(&req->ctx->completion_lock);
8298 io_put_kbuf_comp(req);
8299 spin_unlock(&req->ctx->completion_lock);
8302 if (req->flags & REQ_F_NEED_CLEANUP) {
8303 switch (req->opcode) {
8304 case IORING_OP_READV:
8305 case IORING_OP_READ_FIXED:
8306 case IORING_OP_READ:
8307 case IORING_OP_WRITEV:
8308 case IORING_OP_WRITE_FIXED:
8309 case IORING_OP_WRITE: {
8310 struct io_async_rw *io = req->async_data;
8312 kfree(io->free_iovec);
8315 case IORING_OP_RECVMSG:
8316 case IORING_OP_SENDMSG: {
8317 struct io_async_msghdr *io = req->async_data;
8319 kfree(io->free_iov);
8322 case IORING_OP_OPENAT:
8323 case IORING_OP_OPENAT2:
8324 if (req->open.filename)
8325 putname(req->open.filename);
8327 case IORING_OP_RENAMEAT:
8328 putname(req->rename.oldpath);
8329 putname(req->rename.newpath);
8331 case IORING_OP_UNLINKAT:
8332 putname(req->unlink.filename);
8334 case IORING_OP_MKDIRAT:
8335 putname(req->mkdir.filename);
8337 case IORING_OP_SYMLINKAT:
8338 putname(req->symlink.oldpath);
8339 putname(req->symlink.newpath);
8341 case IORING_OP_LINKAT:
8342 putname(req->hardlink.oldpath);
8343 putname(req->hardlink.newpath);
8345 case IORING_OP_STATX:
8346 if (req->statx.filename)
8347 putname(req->statx.filename);
8349 case IORING_OP_SETXATTR:
8350 case IORING_OP_FSETXATTR:
8351 case IORING_OP_GETXATTR:
8352 case IORING_OP_FGETXATTR:
8353 __io_xattr_finish(req);
8357 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8358 kfree(req->apoll->double_poll);
8362 if (req->flags & REQ_F_INFLIGHT) {
8363 struct io_uring_task *tctx = req->task->io_uring;
8365 atomic_dec(&tctx->inflight_tracked);
8367 if (req->flags & REQ_F_CREDS)
8368 put_cred(req->creds);
8369 if (req->flags & REQ_F_ASYNC_DATA) {
8370 kfree(req->async_data);
8371 req->async_data = NULL;
8373 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8376 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8378 if (req->file || !io_op_defs[req->opcode].needs_file)
8381 if (req->flags & REQ_F_FIXED_FILE)
8382 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8384 req->file = io_file_get_normal(req, req->cqe.fd);
8389 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8391 const struct io_op_def *def = &io_op_defs[req->opcode];
8392 const struct cred *creds = NULL;
8395 if (unlikely(!io_assign_file(req, issue_flags)))
8398 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8399 creds = override_creds(req->creds);
8401 if (!def->audit_skip)
8402 audit_uring_entry(req->opcode);
8404 switch (req->opcode) {
8406 ret = io_nop(req, issue_flags);
8408 case IORING_OP_READV:
8409 case IORING_OP_READ_FIXED:
8410 case IORING_OP_READ:
8411 ret = io_read(req, issue_flags);
8413 case IORING_OP_WRITEV:
8414 case IORING_OP_WRITE_FIXED:
8415 case IORING_OP_WRITE:
8416 ret = io_write(req, issue_flags);
8418 case IORING_OP_FSYNC:
8419 ret = io_fsync(req, issue_flags);
8421 case IORING_OP_POLL_ADD:
8422 ret = io_poll_add(req, issue_flags);
8424 case IORING_OP_POLL_REMOVE:
8425 ret = io_poll_remove(req, issue_flags);
8427 case IORING_OP_SYNC_FILE_RANGE:
8428 ret = io_sync_file_range(req, issue_flags);
8430 case IORING_OP_SENDMSG:
8431 ret = io_sendmsg(req, issue_flags);
8433 case IORING_OP_SEND:
8434 ret = io_send(req, issue_flags);
8436 case IORING_OP_RECVMSG:
8437 ret = io_recvmsg(req, issue_flags);
8439 case IORING_OP_RECV:
8440 ret = io_recv(req, issue_flags);
8442 case IORING_OP_TIMEOUT:
8443 ret = io_timeout(req, issue_flags);
8445 case IORING_OP_TIMEOUT_REMOVE:
8446 ret = io_timeout_remove(req, issue_flags);
8448 case IORING_OP_ACCEPT:
8449 ret = io_accept(req, issue_flags);
8451 case IORING_OP_CONNECT:
8452 ret = io_connect(req, issue_flags);
8454 case IORING_OP_ASYNC_CANCEL:
8455 ret = io_async_cancel(req, issue_flags);
8457 case IORING_OP_FALLOCATE:
8458 ret = io_fallocate(req, issue_flags);
8460 case IORING_OP_OPENAT:
8461 ret = io_openat(req, issue_flags);
8463 case IORING_OP_CLOSE:
8464 ret = io_close(req, issue_flags);
8466 case IORING_OP_FILES_UPDATE:
8467 ret = io_files_update(req, issue_flags);
8469 case IORING_OP_STATX:
8470 ret = io_statx(req, issue_flags);
8472 case IORING_OP_FADVISE:
8473 ret = io_fadvise(req, issue_flags);
8475 case IORING_OP_MADVISE:
8476 ret = io_madvise(req, issue_flags);
8478 case IORING_OP_OPENAT2:
8479 ret = io_openat2(req, issue_flags);
8481 case IORING_OP_EPOLL_CTL:
8482 ret = io_epoll_ctl(req, issue_flags);
8484 case IORING_OP_SPLICE:
8485 ret = io_splice(req, issue_flags);
8487 case IORING_OP_PROVIDE_BUFFERS:
8488 ret = io_provide_buffers(req, issue_flags);
8490 case IORING_OP_REMOVE_BUFFERS:
8491 ret = io_remove_buffers(req, issue_flags);
8494 ret = io_tee(req, issue_flags);
8496 case IORING_OP_SHUTDOWN:
8497 ret = io_shutdown(req, issue_flags);
8499 case IORING_OP_RENAMEAT:
8500 ret = io_renameat(req, issue_flags);
8502 case IORING_OP_UNLINKAT:
8503 ret = io_unlinkat(req, issue_flags);
8505 case IORING_OP_MKDIRAT:
8506 ret = io_mkdirat(req, issue_flags);
8508 case IORING_OP_SYMLINKAT:
8509 ret = io_symlinkat(req, issue_flags);
8511 case IORING_OP_LINKAT:
8512 ret = io_linkat(req, issue_flags);
8514 case IORING_OP_MSG_RING:
8515 ret = io_msg_ring(req, issue_flags);
8517 case IORING_OP_FSETXATTR:
8518 ret = io_fsetxattr(req, issue_flags);
8520 case IORING_OP_SETXATTR:
8521 ret = io_setxattr(req, issue_flags);
8523 case IORING_OP_FGETXATTR:
8524 ret = io_fgetxattr(req, issue_flags);
8526 case IORING_OP_GETXATTR:
8527 ret = io_getxattr(req, issue_flags);
8529 case IORING_OP_SOCKET:
8530 ret = io_socket(req, issue_flags);
8532 case IORING_OP_URING_CMD:
8533 ret = io_uring_cmd(req, issue_flags);
8540 if (!def->audit_skip)
8541 audit_uring_exit(!ret, ret);
8544 revert_creds(creds);
8547 /* If the op doesn't have a file, we're not polling for it */
8548 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8549 io_iopoll_req_issued(req, issue_flags);
8554 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8556 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8558 req = io_put_req_find_next(req);
8559 return req ? &req->work : NULL;
8562 static void io_wq_submit_work(struct io_wq_work *work)
8564 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8565 const struct io_op_def *def = &io_op_defs[req->opcode];
8566 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8567 bool needs_poll = false;
8568 int ret = 0, err = -ECANCELED;
8570 /* one will be dropped by ->io_free_work() after returning to io-wq */
8571 if (!(req->flags & REQ_F_REFCOUNT))
8572 __io_req_set_refcount(req, 2);
8576 io_arm_ltimeout(req);
8578 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8579 if (work->flags & IO_WQ_WORK_CANCEL) {
8581 io_req_task_queue_fail(req, err);
8584 if (!io_assign_file(req, issue_flags)) {
8586 work->flags |= IO_WQ_WORK_CANCEL;
8590 if (req->flags & REQ_F_FORCE_ASYNC) {
8591 bool opcode_poll = def->pollin || def->pollout;
8593 if (opcode_poll && file_can_poll(req->file)) {
8595 issue_flags |= IO_URING_F_NONBLOCK;
8600 ret = io_issue_sqe(req, issue_flags);
8604 * We can get EAGAIN for iopolled IO even though we're
8605 * forcing a sync submission from here, since we can't
8606 * wait for request slots on the block side.
8609 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8615 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8617 /* aborted or ready, in either case retry blocking */
8619 issue_flags &= ~IO_URING_F_NONBLOCK;
8622 /* avoid locking problems by failing it from a clean context */
8624 io_req_task_queue_fail(req, ret);
8627 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8630 return &table->files[i];
8633 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8636 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8638 return (struct file *) (slot->file_ptr & FFS_MASK);
8641 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8643 unsigned long file_ptr = (unsigned long) file;
8645 file_ptr |= io_file_get_flags(file);
8646 file_slot->file_ptr = file_ptr;
8649 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8650 unsigned int issue_flags)
8652 struct io_ring_ctx *ctx = req->ctx;
8653 struct file *file = NULL;
8654 unsigned long file_ptr;
8656 io_ring_submit_lock(ctx, issue_flags);
8658 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8660 fd = array_index_nospec(fd, ctx->nr_user_files);
8661 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8662 file = (struct file *) (file_ptr & FFS_MASK);
8663 file_ptr &= ~FFS_MASK;
8664 /* mask in overlapping REQ_F and FFS bits */
8665 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8666 io_req_set_rsrc_node(req, ctx, 0);
8667 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8669 io_ring_submit_unlock(ctx, issue_flags);
8673 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8675 struct file *file = fget(fd);
8677 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8679 /* we don't allow fixed io_uring files */
8680 if (file && file->f_op == &io_uring_fops)
8681 io_req_track_inflight(req);
8685 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8687 struct io_kiocb *prev = req->timeout.prev;
8691 if (!(req->task->flags & PF_EXITING)) {
8692 struct io_cancel_data cd = {
8694 .data = prev->cqe.user_data,
8697 ret = io_try_cancel(req, &cd);
8699 io_req_complete_post(req, ret ?: -ETIME, 0);
8702 io_req_complete_post(req, -ETIME, 0);
8706 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8708 struct io_timeout_data *data = container_of(timer,
8709 struct io_timeout_data, timer);
8710 struct io_kiocb *prev, *req = data->req;
8711 struct io_ring_ctx *ctx = req->ctx;
8712 unsigned long flags;
8714 spin_lock_irqsave(&ctx->timeout_lock, flags);
8715 prev = req->timeout.head;
8716 req->timeout.head = NULL;
8719 * We don't expect the list to be empty, that will only happen if we
8720 * race with the completion of the linked work.
8723 io_remove_next_linked(prev);
8724 if (!req_ref_inc_not_zero(prev))
8727 list_del(&req->timeout.list);
8728 req->timeout.prev = prev;
8729 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8731 req->io_task_work.func = io_req_task_link_timeout;
8732 io_req_task_work_add(req);
8733 return HRTIMER_NORESTART;
8736 static void io_queue_linked_timeout(struct io_kiocb *req)
8738 struct io_ring_ctx *ctx = req->ctx;
8740 spin_lock_irq(&ctx->timeout_lock);
8742 * If the back reference is NULL, then our linked request finished
8743 * before we got a chance to setup the timer
8745 if (req->timeout.head) {
8746 struct io_timeout_data *data = req->async_data;
8748 data->timer.function = io_link_timeout_fn;
8749 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8751 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8753 spin_unlock_irq(&ctx->timeout_lock);
8754 /* drop submission reference */
8758 static void io_queue_async(struct io_kiocb *req, int ret)
8759 __must_hold(&req->ctx->uring_lock)
8761 struct io_kiocb *linked_timeout;
8763 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8764 io_req_complete_failed(req, ret);
8768 linked_timeout = io_prep_linked_timeout(req);
8770 switch (io_arm_poll_handler(req, 0)) {
8771 case IO_APOLL_READY:
8772 io_req_task_queue(req);
8774 case IO_APOLL_ABORTED:
8776 * Queued up for async execution, worker will release
8777 * submit reference when the iocb is actually submitted.
8779 io_queue_iowq(req, NULL);
8786 io_queue_linked_timeout(linked_timeout);
8789 static inline void io_queue_sqe(struct io_kiocb *req)
8790 __must_hold(&req->ctx->uring_lock)
8794 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8796 if (req->flags & REQ_F_COMPLETE_INLINE) {
8797 io_req_add_compl_list(req);
8801 * We async punt it if the file wasn't marked NOWAIT, or if the file
8802 * doesn't support non-blocking read/write attempts
8805 io_arm_ltimeout(req);
8807 io_queue_async(req, ret);
8810 static void io_queue_sqe_fallback(struct io_kiocb *req)
8811 __must_hold(&req->ctx->uring_lock)
8813 if (unlikely(req->flags & REQ_F_FAIL)) {
8815 * We don't submit, fail them all, for that replace hardlinks
8816 * with normal links. Extra REQ_F_LINK is tolerated.
8818 req->flags &= ~REQ_F_HARDLINK;
8819 req->flags |= REQ_F_LINK;
8820 io_req_complete_failed(req, req->cqe.res);
8821 } else if (unlikely(req->ctx->drain_active)) {
8824 int ret = io_req_prep_async(req);
8827 io_req_complete_failed(req, ret);
8829 io_queue_iowq(req, NULL);
8834 * Check SQE restrictions (opcode and flags).
8836 * Returns 'true' if SQE is allowed, 'false' otherwise.
8838 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8839 struct io_kiocb *req,
8840 unsigned int sqe_flags)
8842 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8845 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8846 ctx->restrictions.sqe_flags_required)
8849 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8850 ctx->restrictions.sqe_flags_required))
8856 static void io_init_req_drain(struct io_kiocb *req)
8858 struct io_ring_ctx *ctx = req->ctx;
8859 struct io_kiocb *head = ctx->submit_state.link.head;
8861 ctx->drain_active = true;
8864 * If we need to drain a request in the middle of a link, drain
8865 * the head request and the next request/link after the current
8866 * link. Considering sequential execution of links,
8867 * REQ_F_IO_DRAIN will be maintained for every request of our
8870 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8871 ctx->drain_next = true;
8875 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8876 const struct io_uring_sqe *sqe)
8877 __must_hold(&ctx->uring_lock)
8879 const struct io_op_def *def;
8880 unsigned int sqe_flags;
8884 /* req is partially pre-initialised, see io_preinit_req() */
8885 req->opcode = opcode = READ_ONCE(sqe->opcode);
8886 /* same numerical values with corresponding REQ_F_*, safe to copy */
8887 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8888 req->cqe.user_data = READ_ONCE(sqe->user_data);
8890 req->rsrc_node = NULL;
8891 req->task = current;
8893 if (unlikely(opcode >= IORING_OP_LAST)) {
8897 def = &io_op_defs[opcode];
8898 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8899 /* enforce forwards compatibility on users */
8900 if (sqe_flags & ~SQE_VALID_FLAGS)
8902 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8903 if (!def->buffer_select)
8905 req->buf_index = READ_ONCE(sqe->buf_group);
8907 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8908 ctx->drain_disabled = true;
8909 if (sqe_flags & IOSQE_IO_DRAIN) {
8910 if (ctx->drain_disabled)
8912 io_init_req_drain(req);
8915 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8916 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8918 /* knock it to the slow queue path, will be drained there */
8919 if (ctx->drain_active)
8920 req->flags |= REQ_F_FORCE_ASYNC;
8921 /* if there is no link, we're at "next" request and need to drain */
8922 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8923 ctx->drain_next = false;
8924 ctx->drain_active = true;
8925 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8929 if (!def->ioprio && sqe->ioprio)
8931 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8934 if (def->needs_file) {
8935 struct io_submit_state *state = &ctx->submit_state;
8937 req->cqe.fd = READ_ONCE(sqe->fd);
8940 * Plug now if we have more than 2 IO left after this, and the
8941 * target is potentially a read/write to block based storage.
8943 if (state->need_plug && def->plug) {
8944 state->plug_started = true;
8945 state->need_plug = false;
8946 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8950 personality = READ_ONCE(sqe->personality);
8954 req->creds = xa_load(&ctx->personalities, personality);
8957 get_cred(req->creds);
8958 ret = security_uring_override_creds(req->creds);
8960 put_cred(req->creds);
8963 req->flags |= REQ_F_CREDS;
8966 return io_req_prep(req, sqe);
8969 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8970 struct io_kiocb *req, int ret)
8972 struct io_ring_ctx *ctx = req->ctx;
8973 struct io_submit_link *link = &ctx->submit_state.link;
8974 struct io_kiocb *head = link->head;
8976 trace_io_uring_req_failed(sqe, ctx, req, ret);
8979 * Avoid breaking links in the middle as it renders links with SQPOLL
8980 * unusable. Instead of failing eagerly, continue assembling the link if
8981 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8982 * should find the flag and handle the rest.
8984 req_fail_link_node(req, ret);
8985 if (head && !(head->flags & REQ_F_FAIL))
8986 req_fail_link_node(head, -ECANCELED);
8988 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8990 link->last->link = req;
8994 io_queue_sqe_fallback(req);
8999 link->last->link = req;
9006 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
9007 const struct io_uring_sqe *sqe)
9008 __must_hold(&ctx->uring_lock)
9010 struct io_submit_link *link = &ctx->submit_state.link;
9013 ret = io_init_req(ctx, req, sqe);
9015 return io_submit_fail_init(sqe, req, ret);
9017 /* don't need @sqe from now on */
9018 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
9020 ctx->flags & IORING_SETUP_SQPOLL);
9023 * If we already have a head request, queue this one for async
9024 * submittal once the head completes. If we don't have a head but
9025 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
9026 * submitted sync once the chain is complete. If none of those
9027 * conditions are true (normal request), then just queue it.
9029 if (unlikely(link->head)) {
9030 ret = io_req_prep_async(req);
9032 return io_submit_fail_init(sqe, req, ret);
9034 trace_io_uring_link(ctx, req, link->head);
9035 link->last->link = req;
9038 if (req->flags & IO_REQ_LINK_FLAGS)
9040 /* last request of the link, flush it */
9043 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
9046 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
9047 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
9048 if (req->flags & IO_REQ_LINK_FLAGS) {
9053 io_queue_sqe_fallback(req);
9063 * Batched submission is done, ensure local IO is flushed out.
9065 static void io_submit_state_end(struct io_ring_ctx *ctx)
9067 struct io_submit_state *state = &ctx->submit_state;
9069 if (unlikely(state->link.head))
9070 io_queue_sqe_fallback(state->link.head);
9071 /* flush only after queuing links as they can generate completions */
9072 io_submit_flush_completions(ctx);
9073 if (state->plug_started)
9074 blk_finish_plug(&state->plug);
9078 * Start submission side cache.
9080 static void io_submit_state_start(struct io_submit_state *state,
9081 unsigned int max_ios)
9083 state->plug_started = false;
9084 state->need_plug = max_ios > 2;
9085 state->submit_nr = max_ios;
9086 /* set only head, no need to init link_last in advance */
9087 state->link.head = NULL;
9090 static void io_commit_sqring(struct io_ring_ctx *ctx)
9092 struct io_rings *rings = ctx->rings;
9095 * Ensure any loads from the SQEs are done at this point,
9096 * since once we write the new head, the application could
9097 * write new data to them.
9099 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
9103 * Fetch an sqe, if one is available. Note this returns a pointer to memory
9104 * that is mapped by userspace. This means that care needs to be taken to
9105 * ensure that reads are stable, as we cannot rely on userspace always
9106 * being a good citizen. If members of the sqe are validated and then later
9107 * used, it's important that those reads are done through READ_ONCE() to
9108 * prevent a re-load down the line.
9110 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
9112 unsigned head, mask = ctx->sq_entries - 1;
9113 unsigned sq_idx = ctx->cached_sq_head++ & mask;
9116 * The cached sq head (or cq tail) serves two purposes:
9118 * 1) allows us to batch the cost of updating the user visible
9120 * 2) allows the kernel side to track the head on its own, even
9121 * though the application is the one updating it.
9123 head = READ_ONCE(ctx->sq_array[sq_idx]);
9124 if (likely(head < ctx->sq_entries)) {
9125 /* double index for 128-byte SQEs, twice as long */
9126 if (ctx->flags & IORING_SETUP_SQE128)
9128 return &ctx->sq_sqes[head];
9131 /* drop invalid entries */
9133 WRITE_ONCE(ctx->rings->sq_dropped,
9134 READ_ONCE(ctx->rings->sq_dropped) + 1);
9138 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
9139 __must_hold(&ctx->uring_lock)
9141 unsigned int entries = io_sqring_entries(ctx);
9145 if (unlikely(!entries))
9147 /* make sure SQ entry isn't read before tail */
9148 ret = left = min3(nr, ctx->sq_entries, entries);
9149 io_get_task_refs(left);
9150 io_submit_state_start(&ctx->submit_state, left);
9153 const struct io_uring_sqe *sqe;
9154 struct io_kiocb *req;
9156 if (unlikely(!io_alloc_req_refill(ctx)))
9158 req = io_alloc_req(ctx);
9159 sqe = io_get_sqe(ctx);
9160 if (unlikely(!sqe)) {
9161 io_req_add_to_cache(req, ctx);
9166 * Continue submitting even for sqe failure if the
9167 * ring was setup with IORING_SETUP_SUBMIT_ALL
9169 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
9170 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
9176 if (unlikely(left)) {
9178 /* try again if it submitted nothing and can't allocate a req */
9179 if (!ret && io_req_cache_empty(ctx))
9181 current->io_uring->cached_refs += left;
9184 io_submit_state_end(ctx);
9185 /* Commit SQ ring head once we've consumed and submitted all SQEs */
9186 io_commit_sqring(ctx);
9190 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
9192 return READ_ONCE(sqd->state);
9195 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
9197 unsigned int to_submit;
9200 to_submit = io_sqring_entries(ctx);
9201 /* if we're handling multiple rings, cap submit size for fairness */
9202 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
9203 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
9205 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
9206 const struct cred *creds = NULL;
9208 if (ctx->sq_creds != current_cred())
9209 creds = override_creds(ctx->sq_creds);
9211 mutex_lock(&ctx->uring_lock);
9212 if (!wq_list_empty(&ctx->iopoll_list))
9213 io_do_iopoll(ctx, true);
9216 * Don't submit if refs are dying, good for io_uring_register(),
9217 * but also it is relied upon by io_ring_exit_work()
9219 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
9220 !(ctx->flags & IORING_SETUP_R_DISABLED))
9221 ret = io_submit_sqes(ctx, to_submit);
9222 mutex_unlock(&ctx->uring_lock);
9224 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
9225 wake_up(&ctx->sqo_sq_wait);
9227 revert_creds(creds);
9233 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
9235 struct io_ring_ctx *ctx;
9236 unsigned sq_thread_idle = 0;
9238 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9239 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
9240 sqd->sq_thread_idle = sq_thread_idle;
9243 static bool io_sqd_handle_event(struct io_sq_data *sqd)
9245 bool did_sig = false;
9246 struct ksignal ksig;
9248 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
9249 signal_pending(current)) {
9250 mutex_unlock(&sqd->lock);
9251 if (signal_pending(current))
9252 did_sig = get_signal(&ksig);
9254 mutex_lock(&sqd->lock);
9256 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9259 static int io_sq_thread(void *data)
9261 struct io_sq_data *sqd = data;
9262 struct io_ring_ctx *ctx;
9263 unsigned long timeout = 0;
9264 char buf[TASK_COMM_LEN];
9267 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
9268 set_task_comm(current, buf);
9270 if (sqd->sq_cpu != -1)
9271 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
9273 set_cpus_allowed_ptr(current, cpu_online_mask);
9274 current->flags |= PF_NO_SETAFFINITY;
9276 audit_alloc_kernel(current);
9278 mutex_lock(&sqd->lock);
9280 bool cap_entries, sqt_spin = false;
9282 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
9283 if (io_sqd_handle_event(sqd))
9285 timeout = jiffies + sqd->sq_thread_idle;
9288 cap_entries = !list_is_singular(&sqd->ctx_list);
9289 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9290 int ret = __io_sq_thread(ctx, cap_entries);
9292 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
9295 if (io_run_task_work())
9298 if (sqt_spin || !time_after(jiffies, timeout)) {
9301 timeout = jiffies + sqd->sq_thread_idle;
9305 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
9306 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
9307 bool needs_sched = true;
9309 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9310 atomic_or(IORING_SQ_NEED_WAKEUP,
9311 &ctx->rings->sq_flags);
9312 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
9313 !wq_list_empty(&ctx->iopoll_list)) {
9314 needs_sched = false;
9319 * Ensure the store of the wakeup flag is not
9320 * reordered with the load of the SQ tail
9322 smp_mb__after_atomic();
9324 if (io_sqring_entries(ctx)) {
9325 needs_sched = false;
9331 mutex_unlock(&sqd->lock);
9333 mutex_lock(&sqd->lock);
9335 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9336 atomic_andnot(IORING_SQ_NEED_WAKEUP,
9337 &ctx->rings->sq_flags);
9340 finish_wait(&sqd->wait, &wait);
9341 timeout = jiffies + sqd->sq_thread_idle;
9344 io_uring_cancel_generic(true, sqd);
9346 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9347 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9349 mutex_unlock(&sqd->lock);
9351 audit_free(current);
9353 complete(&sqd->exited);
9357 struct io_wait_queue {
9358 struct wait_queue_entry wq;
9359 struct io_ring_ctx *ctx;
9361 unsigned nr_timeouts;
9364 static inline bool io_should_wake(struct io_wait_queue *iowq)
9366 struct io_ring_ctx *ctx = iowq->ctx;
9367 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9370 * Wake up if we have enough events, or if a timeout occurred since we
9371 * started waiting. For timeouts, we always want to return to userspace,
9372 * regardless of event count.
9374 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9377 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9378 int wake_flags, void *key)
9380 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9384 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9385 * the task, and the next invocation will do it.
9387 if (io_should_wake(iowq) ||
9388 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9389 return autoremove_wake_function(curr, mode, wake_flags, key);
9393 static int io_run_task_work_sig(void)
9395 if (io_run_task_work())
9397 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9398 return -ERESTARTSYS;
9399 if (task_sigpending(current))
9404 /* when returns >0, the caller should retry */
9405 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9406 struct io_wait_queue *iowq,
9410 unsigned long check_cq;
9412 /* make sure we run task_work before checking for signals */
9413 ret = io_run_task_work_sig();
9414 if (ret || io_should_wake(iowq))
9416 check_cq = READ_ONCE(ctx->check_cq);
9417 /* let the caller flush overflows, retry */
9418 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9420 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9422 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9428 * Wait until events become available, if we don't already have some. The
9429 * application must reap them itself, as they reside on the shared cq ring.
9431 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9432 const sigset_t __user *sig, size_t sigsz,
9433 struct __kernel_timespec __user *uts)
9435 struct io_wait_queue iowq;
9436 struct io_rings *rings = ctx->rings;
9437 ktime_t timeout = KTIME_MAX;
9441 io_cqring_overflow_flush(ctx);
9442 if (io_cqring_events(ctx) >= min_events)
9444 if (!io_run_task_work())
9449 #ifdef CONFIG_COMPAT
9450 if (in_compat_syscall())
9451 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9455 ret = set_user_sigmask(sig, sigsz);
9462 struct timespec64 ts;
9464 if (get_timespec64(&ts, uts))
9466 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9469 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9470 iowq.wq.private = current;
9471 INIT_LIST_HEAD(&iowq.wq.entry);
9473 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9474 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9476 trace_io_uring_cqring_wait(ctx, min_events);
9478 /* if we can't even flush overflow, don't wait for more */
9479 if (!io_cqring_overflow_flush(ctx)) {
9483 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9484 TASK_INTERRUPTIBLE);
9485 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9489 finish_wait(&ctx->cq_wait, &iowq.wq);
9490 restore_saved_sigmask_unless(ret == -EINTR);
9492 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9495 static void io_free_page_table(void **table, size_t size)
9497 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9499 for (i = 0; i < nr_tables; i++)
9504 static __cold void **io_alloc_page_table(size_t size)
9506 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9507 size_t init_size = size;
9510 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9514 for (i = 0; i < nr_tables; i++) {
9515 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9517 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9519 io_free_page_table(table, init_size);
9527 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9529 percpu_ref_exit(&ref_node->refs);
9533 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9535 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9536 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9537 unsigned long flags;
9538 bool first_add = false;
9539 unsigned long delay = HZ;
9541 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9544 /* if we are mid-quiesce then do not delay */
9545 if (node->rsrc_data->quiesce)
9548 while (!list_empty(&ctx->rsrc_ref_list)) {
9549 node = list_first_entry(&ctx->rsrc_ref_list,
9550 struct io_rsrc_node, node);
9551 /* recycle ref nodes in order */
9554 list_del(&node->node);
9555 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9557 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9560 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9563 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9565 struct io_rsrc_node *ref_node;
9567 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9571 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9576 INIT_LIST_HEAD(&ref_node->node);
9577 INIT_LIST_HEAD(&ref_node->rsrc_list);
9578 ref_node->done = false;
9582 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9583 struct io_rsrc_data *data_to_kill)
9584 __must_hold(&ctx->uring_lock)
9586 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9587 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9589 io_rsrc_refs_drop(ctx);
9592 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9594 rsrc_node->rsrc_data = data_to_kill;
9595 spin_lock_irq(&ctx->rsrc_ref_lock);
9596 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9597 spin_unlock_irq(&ctx->rsrc_ref_lock);
9599 atomic_inc(&data_to_kill->refs);
9600 percpu_ref_kill(&rsrc_node->refs);
9601 ctx->rsrc_node = NULL;
9604 if (!ctx->rsrc_node) {
9605 ctx->rsrc_node = ctx->rsrc_backup_node;
9606 ctx->rsrc_backup_node = NULL;
9610 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9612 if (ctx->rsrc_backup_node)
9614 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9615 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9618 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9619 struct io_ring_ctx *ctx)
9623 /* As we may drop ->uring_lock, other task may have started quiesce */
9627 data->quiesce = true;
9629 ret = io_rsrc_node_switch_start(ctx);
9632 io_rsrc_node_switch(ctx, data);
9634 /* kill initial ref, already quiesced if zero */
9635 if (atomic_dec_and_test(&data->refs))
9637 mutex_unlock(&ctx->uring_lock);
9638 flush_delayed_work(&ctx->rsrc_put_work);
9639 ret = wait_for_completion_interruptible(&data->done);
9641 mutex_lock(&ctx->uring_lock);
9642 if (atomic_read(&data->refs) > 0) {
9644 * it has been revived by another thread while
9647 mutex_unlock(&ctx->uring_lock);
9653 atomic_inc(&data->refs);
9654 /* wait for all works potentially completing data->done */
9655 flush_delayed_work(&ctx->rsrc_put_work);
9656 reinit_completion(&data->done);
9658 ret = io_run_task_work_sig();
9659 mutex_lock(&ctx->uring_lock);
9661 data->quiesce = false;
9666 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9668 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9669 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9671 return &data->tags[table_idx][off];
9674 static void io_rsrc_data_free(struct io_rsrc_data *data)
9676 size_t size = data->nr * sizeof(data->tags[0][0]);
9679 io_free_page_table((void **)data->tags, size);
9683 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9684 u64 __user *utags, unsigned nr,
9685 struct io_rsrc_data **pdata)
9687 struct io_rsrc_data *data;
9691 data = kzalloc(sizeof(*data), GFP_KERNEL);
9694 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9702 data->do_put = do_put;
9705 for (i = 0; i < nr; i++) {
9706 u64 *tag_slot = io_get_tag_slot(data, i);
9708 if (copy_from_user(tag_slot, &utags[i],
9714 atomic_set(&data->refs, 1);
9715 init_completion(&data->done);
9719 io_rsrc_data_free(data);
9723 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9725 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9726 GFP_KERNEL_ACCOUNT);
9727 if (unlikely(!table->files))
9730 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9731 if (unlikely(!table->bitmap)) {
9732 kvfree(table->files);
9739 static void io_free_file_tables(struct io_file_table *table)
9741 kvfree(table->files);
9742 bitmap_free(table->bitmap);
9743 table->files = NULL;
9744 table->bitmap = NULL;
9747 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9749 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9750 __set_bit(bit, table->bitmap);
9751 table->alloc_hint = bit + 1;
9754 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9756 __clear_bit(bit, table->bitmap);
9757 table->alloc_hint = bit;
9760 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9762 #if !defined(IO_URING_SCM_ALL)
9765 for (i = 0; i < ctx->nr_user_files; i++) {
9766 struct file *file = io_file_from_index(ctx, i);
9770 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9772 io_file_bitmap_clear(&ctx->file_table, i);
9777 #if defined(CONFIG_UNIX)
9778 if (ctx->ring_sock) {
9779 struct sock *sock = ctx->ring_sock->sk;
9780 struct sk_buff *skb;
9782 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9786 io_free_file_tables(&ctx->file_table);
9787 io_rsrc_data_free(ctx->file_data);
9788 ctx->file_data = NULL;
9789 ctx->nr_user_files = 0;
9792 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9796 if (!ctx->file_data)
9798 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9800 __io_sqe_files_unregister(ctx);
9804 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9805 __releases(&sqd->lock)
9807 WARN_ON_ONCE(sqd->thread == current);
9810 * Do the dance but not conditional clear_bit() because it'd race with
9811 * other threads incrementing park_pending and setting the bit.
9813 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9814 if (atomic_dec_return(&sqd->park_pending))
9815 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9816 mutex_unlock(&sqd->lock);
9819 static void io_sq_thread_park(struct io_sq_data *sqd)
9820 __acquires(&sqd->lock)
9822 WARN_ON_ONCE(sqd->thread == current);
9824 atomic_inc(&sqd->park_pending);
9825 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9826 mutex_lock(&sqd->lock);
9828 wake_up_process(sqd->thread);
9831 static void io_sq_thread_stop(struct io_sq_data *sqd)
9833 WARN_ON_ONCE(sqd->thread == current);
9834 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9836 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9837 mutex_lock(&sqd->lock);
9839 wake_up_process(sqd->thread);
9840 mutex_unlock(&sqd->lock);
9841 wait_for_completion(&sqd->exited);
9844 static void io_put_sq_data(struct io_sq_data *sqd)
9846 if (refcount_dec_and_test(&sqd->refs)) {
9847 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9849 io_sq_thread_stop(sqd);
9854 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9856 struct io_sq_data *sqd = ctx->sq_data;
9859 io_sq_thread_park(sqd);
9860 list_del_init(&ctx->sqd_list);
9861 io_sqd_update_thread_idle(sqd);
9862 io_sq_thread_unpark(sqd);
9864 io_put_sq_data(sqd);
9865 ctx->sq_data = NULL;
9869 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9871 struct io_ring_ctx *ctx_attach;
9872 struct io_sq_data *sqd;
9875 f = fdget(p->wq_fd);
9877 return ERR_PTR(-ENXIO);
9878 if (f.file->f_op != &io_uring_fops) {
9880 return ERR_PTR(-EINVAL);
9883 ctx_attach = f.file->private_data;
9884 sqd = ctx_attach->sq_data;
9887 return ERR_PTR(-EINVAL);
9889 if (sqd->task_tgid != current->tgid) {
9891 return ERR_PTR(-EPERM);
9894 refcount_inc(&sqd->refs);
9899 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9902 struct io_sq_data *sqd;
9905 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9906 sqd = io_attach_sq_data(p);
9911 /* fall through for EPERM case, setup new sqd/task */
9912 if (PTR_ERR(sqd) != -EPERM)
9916 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9918 return ERR_PTR(-ENOMEM);
9920 atomic_set(&sqd->park_pending, 0);
9921 refcount_set(&sqd->refs, 1);
9922 INIT_LIST_HEAD(&sqd->ctx_list);
9923 mutex_init(&sqd->lock);
9924 init_waitqueue_head(&sqd->wait);
9925 init_completion(&sqd->exited);
9930 * Ensure the UNIX gc is aware of our file set, so we are certain that
9931 * the io_uring can be safely unregistered on process exit, even if we have
9932 * loops in the file referencing. We account only files that can hold other
9933 * files because otherwise they can't form a loop and so are not interesting
9936 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9938 #if defined(CONFIG_UNIX)
9939 struct sock *sk = ctx->ring_sock->sk;
9940 struct sk_buff_head *head = &sk->sk_receive_queue;
9941 struct scm_fp_list *fpl;
9942 struct sk_buff *skb;
9944 if (likely(!io_file_need_scm(file)))
9948 * See if we can merge this file into an existing skb SCM_RIGHTS
9949 * file set. If there's no room, fall back to allocating a new skb
9950 * and filling it in.
9952 spin_lock_irq(&head->lock);
9953 skb = skb_peek(head);
9954 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9955 __skb_unlink(skb, head);
9958 spin_unlock_irq(&head->lock);
9961 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9965 skb = alloc_skb(0, GFP_KERNEL);
9971 fpl->user = get_uid(current_user());
9972 fpl->max = SCM_MAX_FD;
9975 UNIXCB(skb).fp = fpl;
9977 skb->destructor = unix_destruct_scm;
9978 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9981 fpl = UNIXCB(skb).fp;
9982 fpl->fp[fpl->count++] = get_file(file);
9983 unix_inflight(fpl->user, file);
9984 skb_queue_head(head, skb);
9990 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9992 struct file *file = prsrc->file;
9993 #if defined(CONFIG_UNIX)
9994 struct sock *sock = ctx->ring_sock->sk;
9995 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9996 struct sk_buff *skb;
9999 if (!io_file_need_scm(file)) {
10004 __skb_queue_head_init(&list);
10007 * Find the skb that holds this file in its SCM_RIGHTS. When found,
10008 * remove this entry and rearrange the file array.
10010 skb = skb_dequeue(head);
10012 struct scm_fp_list *fp;
10014 fp = UNIXCB(skb).fp;
10015 for (i = 0; i < fp->count; i++) {
10018 if (fp->fp[i] != file)
10021 unix_notinflight(fp->user, fp->fp[i]);
10022 left = fp->count - 1 - i;
10024 memmove(&fp->fp[i], &fp->fp[i + 1],
10025 left * sizeof(struct file *));
10032 __skb_queue_tail(&list, skb);
10042 __skb_queue_tail(&list, skb);
10044 skb = skb_dequeue(head);
10047 if (skb_peek(&list)) {
10048 spin_lock_irq(&head->lock);
10049 while ((skb = __skb_dequeue(&list)) != NULL)
10050 __skb_queue_tail(head, skb);
10051 spin_unlock_irq(&head->lock);
10058 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
10060 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
10061 struct io_ring_ctx *ctx = rsrc_data->ctx;
10062 struct io_rsrc_put *prsrc, *tmp;
10064 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
10065 list_del(&prsrc->list);
10068 if (ctx->flags & IORING_SETUP_IOPOLL)
10069 mutex_lock(&ctx->uring_lock);
10071 spin_lock(&ctx->completion_lock);
10072 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
10073 io_commit_cqring(ctx);
10074 spin_unlock(&ctx->completion_lock);
10075 io_cqring_ev_posted(ctx);
10077 if (ctx->flags & IORING_SETUP_IOPOLL)
10078 mutex_unlock(&ctx->uring_lock);
10081 rsrc_data->do_put(ctx, prsrc);
10085 io_rsrc_node_destroy(ref_node);
10086 if (atomic_dec_and_test(&rsrc_data->refs))
10087 complete(&rsrc_data->done);
10090 static void io_rsrc_put_work(struct work_struct *work)
10092 struct io_ring_ctx *ctx;
10093 struct llist_node *node;
10095 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
10096 node = llist_del_all(&ctx->rsrc_put_llist);
10099 struct io_rsrc_node *ref_node;
10100 struct llist_node *next = node->next;
10102 ref_node = llist_entry(node, struct io_rsrc_node, llist);
10103 __io_rsrc_put_work(ref_node);
10108 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
10109 unsigned nr_args, u64 __user *tags)
10111 __s32 __user *fds = (__s32 __user *) arg;
10116 if (ctx->file_data)
10120 if (nr_args > IORING_MAX_FIXED_FILES)
10122 if (nr_args > rlimit(RLIMIT_NOFILE))
10124 ret = io_rsrc_node_switch_start(ctx);
10127 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
10132 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
10133 io_rsrc_data_free(ctx->file_data);
10134 ctx->file_data = NULL;
10138 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
10139 struct io_fixed_file *file_slot;
10141 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
10145 /* allow sparse sets */
10146 if (!fds || fd == -1) {
10148 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
10155 if (unlikely(!file))
10159 * Don't allow io_uring instances to be registered. If UNIX
10160 * isn't enabled, then this causes a reference cycle and this
10161 * instance can never get freed. If UNIX is enabled we'll
10162 * handle it just fine, but there's still no point in allowing
10163 * a ring fd as it doesn't support regular read/write anyway.
10165 if (file->f_op == &io_uring_fops) {
10169 ret = io_scm_file_account(ctx, file);
10174 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10175 io_fixed_file_set(file_slot, file);
10176 io_file_bitmap_set(&ctx->file_table, i);
10179 io_rsrc_node_switch(ctx, NULL);
10182 __io_sqe_files_unregister(ctx);
10186 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
10187 struct io_rsrc_node *node, void *rsrc)
10189 u64 *tag_slot = io_get_tag_slot(data, idx);
10190 struct io_rsrc_put *prsrc;
10192 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
10196 prsrc->tag = *tag_slot;
10198 prsrc->rsrc = rsrc;
10199 list_add(&prsrc->list, &node->rsrc_list);
10203 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
10204 unsigned int issue_flags, u32 slot_index)
10205 __must_hold(&req->ctx->uring_lock)
10207 struct io_ring_ctx *ctx = req->ctx;
10208 bool needs_switch = false;
10209 struct io_fixed_file *file_slot;
10212 if (file->f_op == &io_uring_fops)
10214 if (!ctx->file_data)
10216 if (slot_index >= ctx->nr_user_files)
10219 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
10220 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
10222 if (file_slot->file_ptr) {
10223 struct file *old_file;
10225 ret = io_rsrc_node_switch_start(ctx);
10229 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10230 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
10231 ctx->rsrc_node, old_file);
10234 file_slot->file_ptr = 0;
10235 io_file_bitmap_clear(&ctx->file_table, slot_index);
10236 needs_switch = true;
10239 ret = io_scm_file_account(ctx, file);
10241 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
10242 io_fixed_file_set(file_slot, file);
10243 io_file_bitmap_set(&ctx->file_table, slot_index);
10247 io_rsrc_node_switch(ctx, ctx->file_data);
10253 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
10254 unsigned int offset)
10256 struct io_ring_ctx *ctx = req->ctx;
10257 struct io_fixed_file *file_slot;
10261 io_ring_submit_lock(ctx, issue_flags);
10263 if (unlikely(!ctx->file_data))
10266 if (offset >= ctx->nr_user_files)
10268 ret = io_rsrc_node_switch_start(ctx);
10272 offset = array_index_nospec(offset, ctx->nr_user_files);
10273 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
10275 if (!file_slot->file_ptr)
10278 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10279 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
10283 file_slot->file_ptr = 0;
10284 io_file_bitmap_clear(&ctx->file_table, offset);
10285 io_rsrc_node_switch(ctx, ctx->file_data);
10288 io_ring_submit_unlock(ctx, issue_flags);
10292 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
10294 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
10297 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
10298 struct io_uring_rsrc_update2 *up,
10301 u64 __user *tags = u64_to_user_ptr(up->tags);
10302 __s32 __user *fds = u64_to_user_ptr(up->data);
10303 struct io_rsrc_data *data = ctx->file_data;
10304 struct io_fixed_file *file_slot;
10306 int fd, i, err = 0;
10308 bool needs_switch = false;
10310 if (!ctx->file_data)
10312 if (up->offset + nr_args > ctx->nr_user_files)
10315 for (done = 0; done < nr_args; done++) {
10318 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
10319 copy_from_user(&fd, &fds[done], sizeof(fd))) {
10323 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
10327 if (fd == IORING_REGISTER_FILES_SKIP)
10330 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
10331 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10333 if (file_slot->file_ptr) {
10334 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10335 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
10338 file_slot->file_ptr = 0;
10339 io_file_bitmap_clear(&ctx->file_table, i);
10340 needs_switch = true;
10349 * Don't allow io_uring instances to be registered. If
10350 * UNIX isn't enabled, then this causes a reference
10351 * cycle and this instance can never get freed. If UNIX
10352 * is enabled we'll handle it just fine, but there's
10353 * still no point in allowing a ring fd as it doesn't
10354 * support regular read/write anyway.
10356 if (file->f_op == &io_uring_fops) {
10361 err = io_scm_file_account(ctx, file);
10366 *io_get_tag_slot(data, i) = tag;
10367 io_fixed_file_set(file_slot, file);
10368 io_file_bitmap_set(&ctx->file_table, i);
10373 io_rsrc_node_switch(ctx, data);
10374 return done ? done : err;
10377 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
10378 struct task_struct *task)
10380 struct io_wq_hash *hash;
10381 struct io_wq_data data;
10382 unsigned int concurrency;
10384 mutex_lock(&ctx->uring_lock);
10385 hash = ctx->hash_map;
10387 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10389 mutex_unlock(&ctx->uring_lock);
10390 return ERR_PTR(-ENOMEM);
10392 refcount_set(&hash->refs, 1);
10393 init_waitqueue_head(&hash->wait);
10394 ctx->hash_map = hash;
10396 mutex_unlock(&ctx->uring_lock);
10400 data.free_work = io_wq_free_work;
10401 data.do_work = io_wq_submit_work;
10403 /* Do QD, or 4 * CPUS, whatever is smallest */
10404 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10406 return io_wq_create(concurrency, &data);
10409 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10410 struct io_ring_ctx *ctx)
10412 struct io_uring_task *tctx;
10415 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10416 if (unlikely(!tctx))
10419 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10420 sizeof(struct file *), GFP_KERNEL);
10421 if (unlikely(!tctx->registered_rings)) {
10426 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10427 if (unlikely(ret)) {
10428 kfree(tctx->registered_rings);
10433 tctx->io_wq = io_init_wq_offload(ctx, task);
10434 if (IS_ERR(tctx->io_wq)) {
10435 ret = PTR_ERR(tctx->io_wq);
10436 percpu_counter_destroy(&tctx->inflight);
10437 kfree(tctx->registered_rings);
10442 xa_init(&tctx->xa);
10443 init_waitqueue_head(&tctx->wait);
10444 atomic_set(&tctx->in_idle, 0);
10445 atomic_set(&tctx->inflight_tracked, 0);
10446 task->io_uring = tctx;
10447 spin_lock_init(&tctx->task_lock);
10448 INIT_WQ_LIST(&tctx->task_list);
10449 INIT_WQ_LIST(&tctx->prio_task_list);
10450 init_task_work(&tctx->task_work, tctx_task_work);
10454 void __io_uring_free(struct task_struct *tsk)
10456 struct io_uring_task *tctx = tsk->io_uring;
10458 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10459 WARN_ON_ONCE(tctx->io_wq);
10460 WARN_ON_ONCE(tctx->cached_refs);
10462 kfree(tctx->registered_rings);
10463 percpu_counter_destroy(&tctx->inflight);
10465 tsk->io_uring = NULL;
10468 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10469 struct io_uring_params *p)
10473 /* Retain compatibility with failing for an invalid attach attempt */
10474 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10475 IORING_SETUP_ATTACH_WQ) {
10478 f = fdget(p->wq_fd);
10481 if (f.file->f_op != &io_uring_fops) {
10487 if (ctx->flags & IORING_SETUP_SQPOLL) {
10488 struct task_struct *tsk;
10489 struct io_sq_data *sqd;
10492 ret = security_uring_sqpoll();
10496 sqd = io_get_sq_data(p, &attached);
10498 ret = PTR_ERR(sqd);
10502 ctx->sq_creds = get_current_cred();
10503 ctx->sq_data = sqd;
10504 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10505 if (!ctx->sq_thread_idle)
10506 ctx->sq_thread_idle = HZ;
10508 io_sq_thread_park(sqd);
10509 list_add(&ctx->sqd_list, &sqd->ctx_list);
10510 io_sqd_update_thread_idle(sqd);
10511 /* don't attach to a dying SQPOLL thread, would be racy */
10512 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10513 io_sq_thread_unpark(sqd);
10520 if (p->flags & IORING_SETUP_SQ_AFF) {
10521 int cpu = p->sq_thread_cpu;
10524 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10531 sqd->task_pid = current->pid;
10532 sqd->task_tgid = current->tgid;
10533 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10535 ret = PTR_ERR(tsk);
10540 ret = io_uring_alloc_task_context(tsk, ctx);
10541 wake_up_new_task(tsk);
10544 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10545 /* Can't have SQ_AFF without SQPOLL */
10552 complete(&ctx->sq_data->exited);
10554 io_sq_thread_finish(ctx);
10558 static inline void __io_unaccount_mem(struct user_struct *user,
10559 unsigned long nr_pages)
10561 atomic_long_sub(nr_pages, &user->locked_vm);
10564 static inline int __io_account_mem(struct user_struct *user,
10565 unsigned long nr_pages)
10567 unsigned long page_limit, cur_pages, new_pages;
10569 /* Don't allow more pages than we can safely lock */
10570 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10573 cur_pages = atomic_long_read(&user->locked_vm);
10574 new_pages = cur_pages + nr_pages;
10575 if (new_pages > page_limit)
10577 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10578 new_pages) != cur_pages);
10583 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10586 __io_unaccount_mem(ctx->user, nr_pages);
10588 if (ctx->mm_account)
10589 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10592 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10597 ret = __io_account_mem(ctx->user, nr_pages);
10602 if (ctx->mm_account)
10603 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10608 static void io_mem_free(void *ptr)
10615 page = virt_to_head_page(ptr);
10616 if (put_page_testzero(page))
10617 free_compound_page(page);
10620 static void *io_mem_alloc(size_t size)
10622 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10624 return (void *) __get_free_pages(gfp, get_order(size));
10627 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10628 unsigned int cq_entries, size_t *sq_offset)
10630 struct io_rings *rings;
10631 size_t off, sq_array_size;
10633 off = struct_size(rings, cqes, cq_entries);
10634 if (off == SIZE_MAX)
10636 if (ctx->flags & IORING_SETUP_CQE32) {
10637 if (check_shl_overflow(off, 1, &off))
10642 off = ALIGN(off, SMP_CACHE_BYTES);
10650 sq_array_size = array_size(sizeof(u32), sq_entries);
10651 if (sq_array_size == SIZE_MAX)
10654 if (check_add_overflow(off, sq_array_size, &off))
10660 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10662 struct io_mapped_ubuf *imu = *slot;
10665 if (imu != ctx->dummy_ubuf) {
10666 for (i = 0; i < imu->nr_bvecs; i++)
10667 unpin_user_page(imu->bvec[i].bv_page);
10668 if (imu->acct_pages)
10669 io_unaccount_mem(ctx, imu->acct_pages);
10675 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10677 io_buffer_unmap(ctx, &prsrc->buf);
10681 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10685 for (i = 0; i < ctx->nr_user_bufs; i++)
10686 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10687 kfree(ctx->user_bufs);
10688 io_rsrc_data_free(ctx->buf_data);
10689 ctx->user_bufs = NULL;
10690 ctx->buf_data = NULL;
10691 ctx->nr_user_bufs = 0;
10694 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10698 if (!ctx->buf_data)
10701 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10703 __io_sqe_buffers_unregister(ctx);
10707 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10708 void __user *arg, unsigned index)
10710 struct iovec __user *src;
10712 #ifdef CONFIG_COMPAT
10714 struct compat_iovec __user *ciovs;
10715 struct compat_iovec ciov;
10717 ciovs = (struct compat_iovec __user *) arg;
10718 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10721 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10722 dst->iov_len = ciov.iov_len;
10726 src = (struct iovec __user *) arg;
10727 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10733 * Not super efficient, but this is just a registration time. And we do cache
10734 * the last compound head, so generally we'll only do a full search if we don't
10737 * We check if the given compound head page has already been accounted, to
10738 * avoid double accounting it. This allows us to account the full size of the
10739 * page, not just the constituent pages of a huge page.
10741 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10742 int nr_pages, struct page *hpage)
10746 /* check current page array */
10747 for (i = 0; i < nr_pages; i++) {
10748 if (!PageCompound(pages[i]))
10750 if (compound_head(pages[i]) == hpage)
10754 /* check previously registered pages */
10755 for (i = 0; i < ctx->nr_user_bufs; i++) {
10756 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10758 for (j = 0; j < imu->nr_bvecs; j++) {
10759 if (!PageCompound(imu->bvec[j].bv_page))
10761 if (compound_head(imu->bvec[j].bv_page) == hpage)
10769 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10770 int nr_pages, struct io_mapped_ubuf *imu,
10771 struct page **last_hpage)
10775 imu->acct_pages = 0;
10776 for (i = 0; i < nr_pages; i++) {
10777 if (!PageCompound(pages[i])) {
10780 struct page *hpage;
10782 hpage = compound_head(pages[i]);
10783 if (hpage == *last_hpage)
10785 *last_hpage = hpage;
10786 if (headpage_already_acct(ctx, pages, i, hpage))
10788 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10792 if (!imu->acct_pages)
10795 ret = io_account_mem(ctx, imu->acct_pages);
10797 imu->acct_pages = 0;
10801 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10804 unsigned long start, end, nr_pages;
10805 struct vm_area_struct **vmas = NULL;
10806 struct page **pages = NULL;
10807 int i, pret, ret = -ENOMEM;
10809 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10810 start = ubuf >> PAGE_SHIFT;
10811 nr_pages = end - start;
10813 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10817 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10823 mmap_read_lock(current->mm);
10824 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10826 if (pret == nr_pages) {
10827 /* don't support file backed memory */
10828 for (i = 0; i < nr_pages; i++) {
10829 struct vm_area_struct *vma = vmas[i];
10831 if (vma_is_shmem(vma))
10833 if (vma->vm_file &&
10834 !is_file_hugepages(vma->vm_file)) {
10839 *npages = nr_pages;
10841 ret = pret < 0 ? pret : -EFAULT;
10843 mmap_read_unlock(current->mm);
10846 * if we did partial map, or found file backed vmas,
10847 * release any pages we did get
10850 unpin_user_pages(pages, pret);
10858 pages = ERR_PTR(ret);
10863 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10864 struct io_mapped_ubuf **pimu,
10865 struct page **last_hpage)
10867 struct io_mapped_ubuf *imu = NULL;
10868 struct page **pages = NULL;
10871 int ret, nr_pages, i;
10873 if (!iov->iov_base) {
10874 *pimu = ctx->dummy_ubuf;
10881 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10883 if (IS_ERR(pages)) {
10884 ret = PTR_ERR(pages);
10889 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10893 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10895 unpin_user_pages(pages, nr_pages);
10899 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10900 size = iov->iov_len;
10901 for (i = 0; i < nr_pages; i++) {
10904 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10905 imu->bvec[i].bv_page = pages[i];
10906 imu->bvec[i].bv_len = vec_len;
10907 imu->bvec[i].bv_offset = off;
10911 /* store original address for later verification */
10912 imu->ubuf = (unsigned long) iov->iov_base;
10913 imu->ubuf_end = imu->ubuf + iov->iov_len;
10914 imu->nr_bvecs = nr_pages;
10924 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10926 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10927 return ctx->user_bufs ? 0 : -ENOMEM;
10930 static int io_buffer_validate(struct iovec *iov)
10932 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10935 * Don't impose further limits on the size and buffer
10936 * constraints here, we'll -EINVAL later when IO is
10937 * submitted if they are wrong.
10939 if (!iov->iov_base)
10940 return iov->iov_len ? -EFAULT : 0;
10944 /* arbitrary limit, but we need something */
10945 if (iov->iov_len > SZ_1G)
10948 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10954 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10955 unsigned int nr_args, u64 __user *tags)
10957 struct page *last_hpage = NULL;
10958 struct io_rsrc_data *data;
10962 if (ctx->user_bufs)
10964 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10966 ret = io_rsrc_node_switch_start(ctx);
10969 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10972 ret = io_buffers_map_alloc(ctx, nr_args);
10974 io_rsrc_data_free(data);
10978 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10980 ret = io_copy_iov(ctx, &iov, arg, i);
10983 ret = io_buffer_validate(&iov);
10987 memset(&iov, 0, sizeof(iov));
10990 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10995 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
11001 WARN_ON_ONCE(ctx->buf_data);
11003 ctx->buf_data = data;
11005 __io_sqe_buffers_unregister(ctx);
11007 io_rsrc_node_switch(ctx, NULL);
11011 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
11012 struct io_uring_rsrc_update2 *up,
11013 unsigned int nr_args)
11015 u64 __user *tags = u64_to_user_ptr(up->tags);
11016 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
11017 struct page *last_hpage = NULL;
11018 bool needs_switch = false;
11022 if (!ctx->buf_data)
11024 if (up->offset + nr_args > ctx->nr_user_bufs)
11027 for (done = 0; done < nr_args; done++) {
11028 struct io_mapped_ubuf *imu;
11029 int offset = up->offset + done;
11032 err = io_copy_iov(ctx, &iov, iovs, done);
11035 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
11039 err = io_buffer_validate(&iov);
11042 if (!iov.iov_base && tag) {
11046 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
11050 i = array_index_nospec(offset, ctx->nr_user_bufs);
11051 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
11052 err = io_queue_rsrc_removal(ctx->buf_data, i,
11053 ctx->rsrc_node, ctx->user_bufs[i]);
11054 if (unlikely(err)) {
11055 io_buffer_unmap(ctx, &imu);
11058 ctx->user_bufs[i] = NULL;
11059 needs_switch = true;
11062 ctx->user_bufs[i] = imu;
11063 *io_get_tag_slot(ctx->buf_data, offset) = tag;
11067 io_rsrc_node_switch(ctx, ctx->buf_data);
11068 return done ? done : err;
11071 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
11072 unsigned int eventfd_async)
11074 struct io_ev_fd *ev_fd;
11075 __s32 __user *fds = arg;
11078 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11079 lockdep_is_held(&ctx->uring_lock));
11083 if (copy_from_user(&fd, fds, sizeof(*fds)))
11086 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
11090 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
11091 if (IS_ERR(ev_fd->cq_ev_fd)) {
11092 int ret = PTR_ERR(ev_fd->cq_ev_fd);
11096 ev_fd->eventfd_async = eventfd_async;
11097 ctx->has_evfd = true;
11098 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
11102 static void io_eventfd_put(struct rcu_head *rcu)
11104 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
11106 eventfd_ctx_put(ev_fd->cq_ev_fd);
11110 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
11112 struct io_ev_fd *ev_fd;
11114 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11115 lockdep_is_held(&ctx->uring_lock));
11117 ctx->has_evfd = false;
11118 rcu_assign_pointer(ctx->io_ev_fd, NULL);
11119 call_rcu(&ev_fd->rcu, io_eventfd_put);
11126 static void io_destroy_buffers(struct io_ring_ctx *ctx)
11128 struct io_buffer_list *bl;
11129 unsigned long index;
11132 for (i = 0; i < BGID_ARRAY; i++) {
11135 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
11138 xa_for_each(&ctx->io_bl_xa, index, bl) {
11139 xa_erase(&ctx->io_bl_xa, bl->bgid);
11140 __io_remove_buffers(ctx, bl, -1U);
11144 while (!list_empty(&ctx->io_buffers_pages)) {
11147 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
11148 list_del_init(&page->lru);
11153 static void io_req_caches_free(struct io_ring_ctx *ctx)
11155 struct io_submit_state *state = &ctx->submit_state;
11158 mutex_lock(&ctx->uring_lock);
11159 io_flush_cached_locked_reqs(ctx, state);
11161 while (!io_req_cache_empty(ctx)) {
11162 struct io_wq_work_node *node;
11163 struct io_kiocb *req;
11165 node = wq_stack_extract(&state->free_list);
11166 req = container_of(node, struct io_kiocb, comp_list);
11167 kmem_cache_free(req_cachep, req);
11171 percpu_ref_put_many(&ctx->refs, nr);
11172 mutex_unlock(&ctx->uring_lock);
11175 static void io_wait_rsrc_data(struct io_rsrc_data *data)
11177 if (data && !atomic_dec_and_test(&data->refs))
11178 wait_for_completion(&data->done);
11181 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
11183 struct async_poll *apoll;
11185 while (!list_empty(&ctx->apoll_cache)) {
11186 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
11188 list_del(&apoll->poll.wait.entry);
11193 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
11195 io_sq_thread_finish(ctx);
11197 if (ctx->mm_account) {
11198 mmdrop(ctx->mm_account);
11199 ctx->mm_account = NULL;
11202 io_rsrc_refs_drop(ctx);
11203 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
11204 io_wait_rsrc_data(ctx->buf_data);
11205 io_wait_rsrc_data(ctx->file_data);
11207 mutex_lock(&ctx->uring_lock);
11209 __io_sqe_buffers_unregister(ctx);
11210 if (ctx->file_data)
11211 __io_sqe_files_unregister(ctx);
11213 __io_cqring_overflow_flush(ctx, true);
11214 io_eventfd_unregister(ctx);
11215 io_flush_apoll_cache(ctx);
11216 mutex_unlock(&ctx->uring_lock);
11217 io_destroy_buffers(ctx);
11219 put_cred(ctx->sq_creds);
11221 /* there are no registered resources left, nobody uses it */
11222 if (ctx->rsrc_node)
11223 io_rsrc_node_destroy(ctx->rsrc_node);
11224 if (ctx->rsrc_backup_node)
11225 io_rsrc_node_destroy(ctx->rsrc_backup_node);
11226 flush_delayed_work(&ctx->rsrc_put_work);
11227 flush_delayed_work(&ctx->fallback_work);
11229 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
11230 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
11232 #if defined(CONFIG_UNIX)
11233 if (ctx->ring_sock) {
11234 ctx->ring_sock->file = NULL; /* so that iput() is called */
11235 sock_release(ctx->ring_sock);
11238 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
11240 io_mem_free(ctx->rings);
11241 io_mem_free(ctx->sq_sqes);
11243 percpu_ref_exit(&ctx->refs);
11244 free_uid(ctx->user);
11245 io_req_caches_free(ctx);
11247 io_wq_put_hash(ctx->hash_map);
11248 kfree(ctx->cancel_hash);
11249 kfree(ctx->dummy_ubuf);
11251 xa_destroy(&ctx->io_bl_xa);
11255 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
11257 struct io_ring_ctx *ctx = file->private_data;
11260 poll_wait(file, &ctx->cq_wait, wait);
11262 * synchronizes with barrier from wq_has_sleeper call in
11266 if (!io_sqring_full(ctx))
11267 mask |= EPOLLOUT | EPOLLWRNORM;
11270 * Don't flush cqring overflow list here, just do a simple check.
11271 * Otherwise there could possible be ABBA deadlock:
11274 * lock(&ctx->uring_lock);
11276 * lock(&ctx->uring_lock);
11279 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
11280 * pushs them to do the flush.
11282 if (io_cqring_events(ctx) ||
11283 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
11284 mask |= EPOLLIN | EPOLLRDNORM;
11289 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
11291 const struct cred *creds;
11293 creds = xa_erase(&ctx->personalities, id);
11302 struct io_tctx_exit {
11303 struct callback_head task_work;
11304 struct completion completion;
11305 struct io_ring_ctx *ctx;
11308 static __cold void io_tctx_exit_cb(struct callback_head *cb)
11310 struct io_uring_task *tctx = current->io_uring;
11311 struct io_tctx_exit *work;
11313 work = container_of(cb, struct io_tctx_exit, task_work);
11315 * When @in_idle, we're in cancellation and it's racy to remove the
11316 * node. It'll be removed by the end of cancellation, just ignore it.
11318 if (!atomic_read(&tctx->in_idle))
11319 io_uring_del_tctx_node((unsigned long)work->ctx);
11320 complete(&work->completion);
11323 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
11325 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11327 return req->ctx == data;
11330 static __cold void io_ring_exit_work(struct work_struct *work)
11332 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
11333 unsigned long timeout = jiffies + HZ * 60 * 5;
11334 unsigned long interval = HZ / 20;
11335 struct io_tctx_exit exit;
11336 struct io_tctx_node *node;
11340 * If we're doing polled IO and end up having requests being
11341 * submitted async (out-of-line), then completions can come in while
11342 * we're waiting for refs to drop. We need to reap these manually,
11343 * as nobody else will be looking for them.
11346 io_uring_try_cancel_requests(ctx, NULL, true);
11347 if (ctx->sq_data) {
11348 struct io_sq_data *sqd = ctx->sq_data;
11349 struct task_struct *tsk;
11351 io_sq_thread_park(sqd);
11353 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
11354 io_wq_cancel_cb(tsk->io_uring->io_wq,
11355 io_cancel_ctx_cb, ctx, true);
11356 io_sq_thread_unpark(sqd);
11359 io_req_caches_free(ctx);
11361 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
11362 /* there is little hope left, don't run it too often */
11363 interval = HZ * 60;
11365 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
11367 init_completion(&exit.completion);
11368 init_task_work(&exit.task_work, io_tctx_exit_cb);
11371 * Some may use context even when all refs and requests have been put,
11372 * and they are free to do so while still holding uring_lock or
11373 * completion_lock, see io_req_task_submit(). Apart from other work,
11374 * this lock/unlock section also waits them to finish.
11376 mutex_lock(&ctx->uring_lock);
11377 while (!list_empty(&ctx->tctx_list)) {
11378 WARN_ON_ONCE(time_after(jiffies, timeout));
11380 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
11382 /* don't spin on a single task if cancellation failed */
11383 list_rotate_left(&ctx->tctx_list);
11384 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
11385 if (WARN_ON_ONCE(ret))
11388 mutex_unlock(&ctx->uring_lock);
11389 wait_for_completion(&exit.completion);
11390 mutex_lock(&ctx->uring_lock);
11392 mutex_unlock(&ctx->uring_lock);
11393 spin_lock(&ctx->completion_lock);
11394 spin_unlock(&ctx->completion_lock);
11396 io_ring_ctx_free(ctx);
11399 /* Returns true if we found and killed one or more timeouts */
11400 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
11401 struct task_struct *tsk, bool cancel_all)
11403 struct io_kiocb *req, *tmp;
11406 spin_lock(&ctx->completion_lock);
11407 spin_lock_irq(&ctx->timeout_lock);
11408 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11409 if (io_match_task(req, tsk, cancel_all)) {
11410 io_kill_timeout(req, -ECANCELED);
11414 spin_unlock_irq(&ctx->timeout_lock);
11415 io_commit_cqring(ctx);
11416 spin_unlock(&ctx->completion_lock);
11418 io_cqring_ev_posted(ctx);
11419 return canceled != 0;
11422 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11424 unsigned long index;
11425 struct creds *creds;
11427 mutex_lock(&ctx->uring_lock);
11428 percpu_ref_kill(&ctx->refs);
11430 __io_cqring_overflow_flush(ctx, true);
11431 xa_for_each(&ctx->personalities, index, creds)
11432 io_unregister_personality(ctx, index);
11433 mutex_unlock(&ctx->uring_lock);
11435 /* failed during ring init, it couldn't have issued any requests */
11437 io_kill_timeouts(ctx, NULL, true);
11438 io_poll_remove_all(ctx, NULL, true);
11439 /* if we failed setting up the ctx, we might not have any rings */
11440 io_iopoll_try_reap_events(ctx);
11443 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11445 * Use system_unbound_wq to avoid spawning tons of event kworkers
11446 * if we're exiting a ton of rings at the same time. It just adds
11447 * noise and overhead, there's no discernable change in runtime
11448 * over using system_wq.
11450 queue_work(system_unbound_wq, &ctx->exit_work);
11453 static int io_uring_release(struct inode *inode, struct file *file)
11455 struct io_ring_ctx *ctx = file->private_data;
11457 file->private_data = NULL;
11458 io_ring_ctx_wait_and_kill(ctx);
11462 struct io_task_cancel {
11463 struct task_struct *task;
11467 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11469 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11470 struct io_task_cancel *cancel = data;
11472 return io_match_task_safe(req, cancel->task, cancel->all);
11475 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11476 struct task_struct *task,
11479 struct io_defer_entry *de;
11482 spin_lock(&ctx->completion_lock);
11483 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11484 if (io_match_task_safe(de->req, task, cancel_all)) {
11485 list_cut_position(&list, &ctx->defer_list, &de->list);
11489 spin_unlock(&ctx->completion_lock);
11490 if (list_empty(&list))
11493 while (!list_empty(&list)) {
11494 de = list_first_entry(&list, struct io_defer_entry, list);
11495 list_del_init(&de->list);
11496 io_req_complete_failed(de->req, -ECANCELED);
11502 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11504 struct io_tctx_node *node;
11505 enum io_wq_cancel cret;
11508 mutex_lock(&ctx->uring_lock);
11509 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11510 struct io_uring_task *tctx = node->task->io_uring;
11513 * io_wq will stay alive while we hold uring_lock, because it's
11514 * killed after ctx nodes, which requires to take the lock.
11516 if (!tctx || !tctx->io_wq)
11518 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11519 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11521 mutex_unlock(&ctx->uring_lock);
11526 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11527 struct task_struct *task,
11530 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11531 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11533 /* failed during ring init, it couldn't have issued any requests */
11538 enum io_wq_cancel cret;
11542 ret |= io_uring_try_cancel_iowq(ctx);
11543 } else if (tctx && tctx->io_wq) {
11545 * Cancels requests of all rings, not only @ctx, but
11546 * it's fine as the task is in exit/exec.
11548 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11550 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11553 /* SQPOLL thread does its own polling */
11554 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11555 (ctx->sq_data && ctx->sq_data->thread == current)) {
11556 while (!wq_list_empty(&ctx->iopoll_list)) {
11557 io_iopoll_try_reap_events(ctx);
11562 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11563 ret |= io_poll_remove_all(ctx, task, cancel_all);
11564 ret |= io_kill_timeouts(ctx, task, cancel_all);
11566 ret |= io_run_task_work();
11573 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11575 struct io_uring_task *tctx = current->io_uring;
11576 struct io_tctx_node *node;
11579 if (unlikely(!tctx)) {
11580 ret = io_uring_alloc_task_context(current, ctx);
11584 tctx = current->io_uring;
11585 if (ctx->iowq_limits_set) {
11586 unsigned int limits[2] = { ctx->iowq_limits[0],
11587 ctx->iowq_limits[1], };
11589 ret = io_wq_max_workers(tctx->io_wq, limits);
11594 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11595 node = kmalloc(sizeof(*node), GFP_KERNEL);
11599 node->task = current;
11601 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11602 node, GFP_KERNEL));
11608 mutex_lock(&ctx->uring_lock);
11609 list_add(&node->ctx_node, &ctx->tctx_list);
11610 mutex_unlock(&ctx->uring_lock);
11617 * Note that this task has used io_uring. We use it for cancelation purposes.
11619 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11621 struct io_uring_task *tctx = current->io_uring;
11623 if (likely(tctx && tctx->last == ctx))
11625 return __io_uring_add_tctx_node(ctx);
11629 * Remove this io_uring_file -> task mapping.
11631 static __cold void io_uring_del_tctx_node(unsigned long index)
11633 struct io_uring_task *tctx = current->io_uring;
11634 struct io_tctx_node *node;
11638 node = xa_erase(&tctx->xa, index);
11642 WARN_ON_ONCE(current != node->task);
11643 WARN_ON_ONCE(list_empty(&node->ctx_node));
11645 mutex_lock(&node->ctx->uring_lock);
11646 list_del(&node->ctx_node);
11647 mutex_unlock(&node->ctx->uring_lock);
11649 if (tctx->last == node->ctx)
11654 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11656 struct io_wq *wq = tctx->io_wq;
11657 struct io_tctx_node *node;
11658 unsigned long index;
11660 xa_for_each(&tctx->xa, index, node) {
11661 io_uring_del_tctx_node(index);
11666 * Must be after io_uring_del_tctx_node() (removes nodes under
11667 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11669 io_wq_put_and_exit(wq);
11670 tctx->io_wq = NULL;
11674 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11677 return atomic_read(&tctx->inflight_tracked);
11678 return percpu_counter_sum(&tctx->inflight);
11682 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11683 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11685 static __cold void io_uring_cancel_generic(bool cancel_all,
11686 struct io_sq_data *sqd)
11688 struct io_uring_task *tctx = current->io_uring;
11689 struct io_ring_ctx *ctx;
11693 WARN_ON_ONCE(sqd && sqd->thread != current);
11695 if (!current->io_uring)
11698 io_wq_exit_start(tctx->io_wq);
11700 atomic_inc(&tctx->in_idle);
11702 io_uring_drop_tctx_refs(current);
11703 /* read completions before cancelations */
11704 inflight = tctx_inflight(tctx, !cancel_all);
11709 struct io_tctx_node *node;
11710 unsigned long index;
11712 xa_for_each(&tctx->xa, index, node) {
11713 /* sqpoll task will cancel all its requests */
11714 if (node->ctx->sq_data)
11716 io_uring_try_cancel_requests(node->ctx, current,
11720 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11721 io_uring_try_cancel_requests(ctx, current,
11725 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11726 io_run_task_work();
11727 io_uring_drop_tctx_refs(current);
11730 * If we've seen completions, retry without waiting. This
11731 * avoids a race where a completion comes in before we did
11732 * prepare_to_wait().
11734 if (inflight == tctx_inflight(tctx, !cancel_all))
11736 finish_wait(&tctx->wait, &wait);
11739 io_uring_clean_tctx(tctx);
11742 * We shouldn't run task_works after cancel, so just leave
11743 * ->in_idle set for normal exit.
11745 atomic_dec(&tctx->in_idle);
11746 /* for exec all current's requests should be gone, kill tctx */
11747 __io_uring_free(current);
11751 void __io_uring_cancel(bool cancel_all)
11753 io_uring_cancel_generic(cancel_all, NULL);
11756 void io_uring_unreg_ringfd(void)
11758 struct io_uring_task *tctx = current->io_uring;
11761 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11762 if (tctx->registered_rings[i]) {
11763 fput(tctx->registered_rings[i]);
11764 tctx->registered_rings[i] = NULL;
11769 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11770 int start, int end)
11775 for (offset = start; offset < end; offset++) {
11776 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11777 if (tctx->registered_rings[offset])
11783 } else if (file->f_op != &io_uring_fops) {
11785 return -EOPNOTSUPP;
11787 tctx->registered_rings[offset] = file;
11795 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11796 * invocation. User passes in an array of struct io_uring_rsrc_update
11797 * with ->data set to the ring_fd, and ->offset given for the desired
11798 * index. If no index is desired, application may set ->offset == -1U
11799 * and we'll find an available index. Returns number of entries
11800 * successfully processed, or < 0 on error if none were processed.
11802 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11805 struct io_uring_rsrc_update __user *arg = __arg;
11806 struct io_uring_rsrc_update reg;
11807 struct io_uring_task *tctx;
11810 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11813 mutex_unlock(&ctx->uring_lock);
11814 ret = io_uring_add_tctx_node(ctx);
11815 mutex_lock(&ctx->uring_lock);
11819 tctx = current->io_uring;
11820 for (i = 0; i < nr_args; i++) {
11823 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11833 if (reg.offset == -1U) {
11835 end = IO_RINGFD_REG_MAX;
11837 if (reg.offset >= IO_RINGFD_REG_MAX) {
11841 start = reg.offset;
11845 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11850 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11851 fput(tctx->registered_rings[reg.offset]);
11852 tctx->registered_rings[reg.offset] = NULL;
11858 return i ? i : ret;
11861 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11864 struct io_uring_rsrc_update __user *arg = __arg;
11865 struct io_uring_task *tctx = current->io_uring;
11866 struct io_uring_rsrc_update reg;
11869 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11874 for (i = 0; i < nr_args; i++) {
11875 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11879 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11884 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11885 if (tctx->registered_rings[reg.offset]) {
11886 fput(tctx->registered_rings[reg.offset]);
11887 tctx->registered_rings[reg.offset] = NULL;
11891 return i ? i : ret;
11894 static void *io_uring_validate_mmap_request(struct file *file,
11895 loff_t pgoff, size_t sz)
11897 struct io_ring_ctx *ctx = file->private_data;
11898 loff_t offset = pgoff << PAGE_SHIFT;
11903 case IORING_OFF_SQ_RING:
11904 case IORING_OFF_CQ_RING:
11907 case IORING_OFF_SQES:
11908 ptr = ctx->sq_sqes;
11911 return ERR_PTR(-EINVAL);
11914 page = virt_to_head_page(ptr);
11915 if (sz > page_size(page))
11916 return ERR_PTR(-EINVAL);
11923 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11925 size_t sz = vma->vm_end - vma->vm_start;
11929 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11931 return PTR_ERR(ptr);
11933 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11934 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11937 #else /* !CONFIG_MMU */
11939 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11941 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11944 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11946 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11949 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11950 unsigned long addr, unsigned long len,
11951 unsigned long pgoff, unsigned long flags)
11955 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11957 return PTR_ERR(ptr);
11959 return (unsigned long) ptr;
11962 #endif /* !CONFIG_MMU */
11964 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11969 if (!io_sqring_full(ctx))
11971 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11973 if (!io_sqring_full(ctx))
11976 } while (!signal_pending(current));
11978 finish_wait(&ctx->sqo_sq_wait, &wait);
11982 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11984 if (flags & IORING_ENTER_EXT_ARG) {
11985 struct io_uring_getevents_arg arg;
11987 if (argsz != sizeof(arg))
11989 if (copy_from_user(&arg, argp, sizeof(arg)))
11995 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11996 struct __kernel_timespec __user **ts,
11997 const sigset_t __user **sig)
11999 struct io_uring_getevents_arg arg;
12002 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
12003 * is just a pointer to the sigset_t.
12005 if (!(flags & IORING_ENTER_EXT_ARG)) {
12006 *sig = (const sigset_t __user *) argp;
12012 * EXT_ARG is set - ensure we agree on the size of it and copy in our
12013 * timespec and sigset_t pointers if good.
12015 if (*argsz != sizeof(arg))
12017 if (copy_from_user(&arg, argp, sizeof(arg)))
12021 *sig = u64_to_user_ptr(arg.sigmask);
12022 *argsz = arg.sigmask_sz;
12023 *ts = u64_to_user_ptr(arg.ts);
12027 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
12028 u32, min_complete, u32, flags, const void __user *, argp,
12031 struct io_ring_ctx *ctx;
12035 io_run_task_work();
12037 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
12038 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
12039 IORING_ENTER_REGISTERED_RING)))
12043 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
12044 * need only dereference our task private array to find it.
12046 if (flags & IORING_ENTER_REGISTERED_RING) {
12047 struct io_uring_task *tctx = current->io_uring;
12049 if (!tctx || fd >= IO_RINGFD_REG_MAX)
12051 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
12052 f.file = tctx->registered_rings[fd];
12058 if (unlikely(!f.file))
12062 if (unlikely(f.file->f_op != &io_uring_fops))
12066 ctx = f.file->private_data;
12067 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
12071 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
12075 * For SQ polling, the thread will do all submissions and completions.
12076 * Just return the requested submit count, and wake the thread if
12077 * we were asked to.
12080 if (ctx->flags & IORING_SETUP_SQPOLL) {
12081 io_cqring_overflow_flush(ctx);
12083 if (unlikely(ctx->sq_data->thread == NULL)) {
12087 if (flags & IORING_ENTER_SQ_WAKEUP)
12088 wake_up(&ctx->sq_data->wait);
12089 if (flags & IORING_ENTER_SQ_WAIT) {
12090 ret = io_sqpoll_wait_sq(ctx);
12095 } else if (to_submit) {
12096 ret = io_uring_add_tctx_node(ctx);
12100 mutex_lock(&ctx->uring_lock);
12101 ret = io_submit_sqes(ctx, to_submit);
12102 if (ret != to_submit) {
12103 mutex_unlock(&ctx->uring_lock);
12106 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
12107 goto iopoll_locked;
12108 mutex_unlock(&ctx->uring_lock);
12110 if (flags & IORING_ENTER_GETEVENTS) {
12112 if (ctx->syscall_iopoll) {
12114 * We disallow the app entering submit/complete with
12115 * polling, but we still need to lock the ring to
12116 * prevent racing with polled issue that got punted to
12119 mutex_lock(&ctx->uring_lock);
12121 ret2 = io_validate_ext_arg(flags, argp, argsz);
12122 if (likely(!ret2)) {
12123 min_complete = min(min_complete,
12125 ret2 = io_iopoll_check(ctx, min_complete);
12127 mutex_unlock(&ctx->uring_lock);
12129 const sigset_t __user *sig;
12130 struct __kernel_timespec __user *ts;
12132 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
12133 if (likely(!ret2)) {
12134 min_complete = min(min_complete,
12136 ret2 = io_cqring_wait(ctx, min_complete, sig,
12145 * EBADR indicates that one or more CQE were dropped.
12146 * Once the user has been informed we can clear the bit
12147 * as they are obviously ok with those drops.
12149 if (unlikely(ret2 == -EBADR))
12150 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
12156 percpu_ref_put(&ctx->refs);
12162 #ifdef CONFIG_PROC_FS
12163 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
12164 const struct cred *cred)
12166 struct user_namespace *uns = seq_user_ns(m);
12167 struct group_info *gi;
12172 seq_printf(m, "%5d\n", id);
12173 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
12174 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
12175 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
12176 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
12177 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
12178 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
12179 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
12180 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
12181 seq_puts(m, "\n\tGroups:\t");
12182 gi = cred->group_info;
12183 for (g = 0; g < gi->ngroups; g++) {
12184 seq_put_decimal_ull(m, g ? " " : "",
12185 from_kgid_munged(uns, gi->gid[g]));
12187 seq_puts(m, "\n\tCapEff:\t");
12188 cap = cred->cap_effective;
12189 CAP_FOR_EACH_U32(__capi)
12190 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
12195 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
12196 struct seq_file *m)
12198 struct io_sq_data *sq = NULL;
12199 struct io_overflow_cqe *ocqe;
12200 struct io_rings *r = ctx->rings;
12201 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
12202 unsigned int sq_head = READ_ONCE(r->sq.head);
12203 unsigned int sq_tail = READ_ONCE(r->sq.tail);
12204 unsigned int cq_head = READ_ONCE(r->cq.head);
12205 unsigned int cq_tail = READ_ONCE(r->cq.tail);
12206 unsigned int cq_shift = 0;
12207 unsigned int sq_entries, cq_entries;
12209 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
12216 * we may get imprecise sqe and cqe info if uring is actively running
12217 * since we get cached_sq_head and cached_cq_tail without uring_lock
12218 * and sq_tail and cq_head are changed by userspace. But it's ok since
12219 * we usually use these info when it is stuck.
12221 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
12222 seq_printf(m, "SqHead:\t%u\n", sq_head);
12223 seq_printf(m, "SqTail:\t%u\n", sq_tail);
12224 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
12225 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
12226 seq_printf(m, "CqHead:\t%u\n", cq_head);
12227 seq_printf(m, "CqTail:\t%u\n", cq_tail);
12228 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
12229 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
12230 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
12231 for (i = 0; i < sq_entries; i++) {
12232 unsigned int entry = i + sq_head;
12233 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
12234 struct io_uring_sqe *sqe;
12236 if (sq_idx > sq_mask)
12238 sqe = &ctx->sq_sqes[sq_idx];
12239 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
12240 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
12243 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
12244 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
12245 for (i = 0; i < cq_entries; i++) {
12246 unsigned int entry = i + cq_head;
12247 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
12250 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
12251 entry & cq_mask, cqe->user_data, cqe->res,
12254 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
12255 "extra1:%llu, extra2:%llu\n",
12256 entry & cq_mask, cqe->user_data, cqe->res,
12257 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
12262 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
12263 * since fdinfo case grabs it in the opposite direction of normal use
12264 * cases. If we fail to get the lock, we just don't iterate any
12265 * structures that could be going away outside the io_uring mutex.
12267 has_lock = mutex_trylock(&ctx->uring_lock);
12269 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
12275 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
12276 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
12277 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
12278 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
12279 struct file *f = io_file_from_index(ctx, i);
12282 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
12284 seq_printf(m, "%5u: <none>\n", i);
12286 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
12287 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
12288 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
12289 unsigned int len = buf->ubuf_end - buf->ubuf;
12291 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
12293 if (has_lock && !xa_empty(&ctx->personalities)) {
12294 unsigned long index;
12295 const struct cred *cred;
12297 seq_printf(m, "Personalities:\n");
12298 xa_for_each(&ctx->personalities, index, cred)
12299 io_uring_show_cred(m, index, cred);
12302 mutex_unlock(&ctx->uring_lock);
12304 seq_puts(m, "PollList:\n");
12305 spin_lock(&ctx->completion_lock);
12306 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
12307 struct hlist_head *list = &ctx->cancel_hash[i];
12308 struct io_kiocb *req;
12310 hlist_for_each_entry(req, list, hash_node)
12311 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
12312 task_work_pending(req->task));
12315 seq_puts(m, "CqOverflowList:\n");
12316 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
12317 struct io_uring_cqe *cqe = &ocqe->cqe;
12319 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
12320 cqe->user_data, cqe->res, cqe->flags);
12324 spin_unlock(&ctx->completion_lock);
12327 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
12329 struct io_ring_ctx *ctx = f->private_data;
12331 if (percpu_ref_tryget(&ctx->refs)) {
12332 __io_uring_show_fdinfo(ctx, m);
12333 percpu_ref_put(&ctx->refs);
12338 static const struct file_operations io_uring_fops = {
12339 .release = io_uring_release,
12340 .mmap = io_uring_mmap,
12342 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
12343 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
12345 .poll = io_uring_poll,
12346 #ifdef CONFIG_PROC_FS
12347 .show_fdinfo = io_uring_show_fdinfo,
12351 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
12352 struct io_uring_params *p)
12354 struct io_rings *rings;
12355 size_t size, sq_array_offset;
12357 /* make sure these are sane, as we already accounted them */
12358 ctx->sq_entries = p->sq_entries;
12359 ctx->cq_entries = p->cq_entries;
12361 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
12362 if (size == SIZE_MAX)
12365 rings = io_mem_alloc(size);
12369 ctx->rings = rings;
12370 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
12371 rings->sq_ring_mask = p->sq_entries - 1;
12372 rings->cq_ring_mask = p->cq_entries - 1;
12373 rings->sq_ring_entries = p->sq_entries;
12374 rings->cq_ring_entries = p->cq_entries;
12376 if (p->flags & IORING_SETUP_SQE128)
12377 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
12379 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
12380 if (size == SIZE_MAX) {
12381 io_mem_free(ctx->rings);
12386 ctx->sq_sqes = io_mem_alloc(size);
12387 if (!ctx->sq_sqes) {
12388 io_mem_free(ctx->rings);
12396 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
12400 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
12404 ret = io_uring_add_tctx_node(ctx);
12409 fd_install(fd, file);
12414 * Allocate an anonymous fd, this is what constitutes the application
12415 * visible backing of an io_uring instance. The application mmaps this
12416 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12417 * we have to tie this fd to a socket for file garbage collection purposes.
12419 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12422 #if defined(CONFIG_UNIX)
12425 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12428 return ERR_PTR(ret);
12431 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12432 O_RDWR | O_CLOEXEC, NULL);
12433 #if defined(CONFIG_UNIX)
12434 if (IS_ERR(file)) {
12435 sock_release(ctx->ring_sock);
12436 ctx->ring_sock = NULL;
12438 ctx->ring_sock->file = file;
12444 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12445 struct io_uring_params __user *params)
12447 struct io_ring_ctx *ctx;
12453 if (entries > IORING_MAX_ENTRIES) {
12454 if (!(p->flags & IORING_SETUP_CLAMP))
12456 entries = IORING_MAX_ENTRIES;
12460 * Use twice as many entries for the CQ ring. It's possible for the
12461 * application to drive a higher depth than the size of the SQ ring,
12462 * since the sqes are only used at submission time. This allows for
12463 * some flexibility in overcommitting a bit. If the application has
12464 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12465 * of CQ ring entries manually.
12467 p->sq_entries = roundup_pow_of_two(entries);
12468 if (p->flags & IORING_SETUP_CQSIZE) {
12470 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12471 * to a power-of-two, if it isn't already. We do NOT impose
12472 * any cq vs sq ring sizing.
12474 if (!p->cq_entries)
12476 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12477 if (!(p->flags & IORING_SETUP_CLAMP))
12479 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12481 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12482 if (p->cq_entries < p->sq_entries)
12485 p->cq_entries = 2 * p->sq_entries;
12488 ctx = io_ring_ctx_alloc(p);
12493 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12494 * space applications don't need to do io completion events
12495 * polling again, they can rely on io_sq_thread to do polling
12496 * work, which can reduce cpu usage and uring_lock contention.
12498 if (ctx->flags & IORING_SETUP_IOPOLL &&
12499 !(ctx->flags & IORING_SETUP_SQPOLL))
12500 ctx->syscall_iopoll = 1;
12502 ctx->compat = in_compat_syscall();
12503 if (!capable(CAP_IPC_LOCK))
12504 ctx->user = get_uid(current_user());
12507 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12508 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12511 if (ctx->flags & IORING_SETUP_SQPOLL) {
12512 /* IPI related flags don't make sense with SQPOLL */
12513 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12514 IORING_SETUP_TASKRUN_FLAG))
12516 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12517 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12518 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12520 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12522 ctx->notify_method = TWA_SIGNAL;
12526 * This is just grabbed for accounting purposes. When a process exits,
12527 * the mm is exited and dropped before the files, hence we need to hang
12528 * on to this mm purely for the purposes of being able to unaccount
12529 * memory (locked/pinned vm). It's not used for anything else.
12531 mmgrab(current->mm);
12532 ctx->mm_account = current->mm;
12534 ret = io_allocate_scq_urings(ctx, p);
12538 ret = io_sq_offload_create(ctx, p);
12541 /* always set a rsrc node */
12542 ret = io_rsrc_node_switch_start(ctx);
12545 io_rsrc_node_switch(ctx, NULL);
12547 memset(&p->sq_off, 0, sizeof(p->sq_off));
12548 p->sq_off.head = offsetof(struct io_rings, sq.head);
12549 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12550 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12551 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12552 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12553 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12554 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12556 memset(&p->cq_off, 0, sizeof(p->cq_off));
12557 p->cq_off.head = offsetof(struct io_rings, cq.head);
12558 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12559 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12560 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12561 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12562 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12563 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12565 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12566 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12567 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12568 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12569 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12570 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12571 IORING_FEAT_LINKED_FILE;
12573 if (copy_to_user(params, p, sizeof(*p))) {
12578 file = io_uring_get_file(ctx);
12579 if (IS_ERR(file)) {
12580 ret = PTR_ERR(file);
12585 * Install ring fd as the very last thing, so we don't risk someone
12586 * having closed it before we finish setup
12588 ret = io_uring_install_fd(ctx, file);
12590 /* fput will clean it up */
12595 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12598 io_ring_ctx_wait_and_kill(ctx);
12603 * Sets up an aio uring context, and returns the fd. Applications asks for a
12604 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12605 * params structure passed in.
12607 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12609 struct io_uring_params p;
12612 if (copy_from_user(&p, params, sizeof(p)))
12614 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12619 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12620 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12621 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12622 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12623 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12624 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12627 return io_uring_create(entries, &p, params);
12630 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12631 struct io_uring_params __user *, params)
12633 return io_uring_setup(entries, params);
12636 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12639 struct io_uring_probe *p;
12643 size = struct_size(p, ops, nr_args);
12644 if (size == SIZE_MAX)
12646 p = kzalloc(size, GFP_KERNEL);
12651 if (copy_from_user(p, arg, size))
12654 if (memchr_inv(p, 0, size))
12657 p->last_op = IORING_OP_LAST - 1;
12658 if (nr_args > IORING_OP_LAST)
12659 nr_args = IORING_OP_LAST;
12661 for (i = 0; i < nr_args; i++) {
12663 if (!io_op_defs[i].not_supported)
12664 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12669 if (copy_to_user(arg, p, size))
12676 static int io_register_personality(struct io_ring_ctx *ctx)
12678 const struct cred *creds;
12682 creds = get_current_cred();
12684 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12685 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12693 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12694 void __user *arg, unsigned int nr_args)
12696 struct io_uring_restriction *res;
12700 /* Restrictions allowed only if rings started disabled */
12701 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12704 /* We allow only a single restrictions registration */
12705 if (ctx->restrictions.registered)
12708 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12711 size = array_size(nr_args, sizeof(*res));
12712 if (size == SIZE_MAX)
12715 res = memdup_user(arg, size);
12717 return PTR_ERR(res);
12721 for (i = 0; i < nr_args; i++) {
12722 switch (res[i].opcode) {
12723 case IORING_RESTRICTION_REGISTER_OP:
12724 if (res[i].register_op >= IORING_REGISTER_LAST) {
12729 __set_bit(res[i].register_op,
12730 ctx->restrictions.register_op);
12732 case IORING_RESTRICTION_SQE_OP:
12733 if (res[i].sqe_op >= IORING_OP_LAST) {
12738 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12740 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12741 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12743 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12744 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12753 /* Reset all restrictions if an error happened */
12755 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12757 ctx->restrictions.registered = true;
12763 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12765 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12768 if (ctx->restrictions.registered)
12769 ctx->restricted = 1;
12771 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12772 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12773 wake_up(&ctx->sq_data->wait);
12777 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12778 struct io_uring_rsrc_update2 *up,
12784 if (check_add_overflow(up->offset, nr_args, &tmp))
12786 err = io_rsrc_node_switch_start(ctx);
12791 case IORING_RSRC_FILE:
12792 return __io_sqe_files_update(ctx, up, nr_args);
12793 case IORING_RSRC_BUFFER:
12794 return __io_sqe_buffers_update(ctx, up, nr_args);
12799 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12802 struct io_uring_rsrc_update2 up;
12806 memset(&up, 0, sizeof(up));
12807 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12809 if (up.resv || up.resv2)
12811 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12814 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12815 unsigned size, unsigned type)
12817 struct io_uring_rsrc_update2 up;
12819 if (size != sizeof(up))
12821 if (copy_from_user(&up, arg, sizeof(up)))
12823 if (!up.nr || up.resv || up.resv2)
12825 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12828 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12829 unsigned int size, unsigned int type)
12831 struct io_uring_rsrc_register rr;
12833 /* keep it extendible */
12834 if (size != sizeof(rr))
12837 memset(&rr, 0, sizeof(rr));
12838 if (copy_from_user(&rr, arg, size))
12840 if (!rr.nr || rr.resv2)
12842 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12846 case IORING_RSRC_FILE:
12847 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12849 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12850 rr.nr, u64_to_user_ptr(rr.tags));
12851 case IORING_RSRC_BUFFER:
12852 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12854 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12855 rr.nr, u64_to_user_ptr(rr.tags));
12860 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12861 void __user *arg, unsigned len)
12863 struct io_uring_task *tctx = current->io_uring;
12864 cpumask_var_t new_mask;
12867 if (!tctx || !tctx->io_wq)
12870 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12873 cpumask_clear(new_mask);
12874 if (len > cpumask_size())
12875 len = cpumask_size();
12877 if (in_compat_syscall()) {
12878 ret = compat_get_bitmap(cpumask_bits(new_mask),
12879 (const compat_ulong_t __user *)arg,
12880 len * 8 /* CHAR_BIT */);
12882 ret = copy_from_user(new_mask, arg, len);
12886 free_cpumask_var(new_mask);
12890 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12891 free_cpumask_var(new_mask);
12895 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12897 struct io_uring_task *tctx = current->io_uring;
12899 if (!tctx || !tctx->io_wq)
12902 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12905 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12907 __must_hold(&ctx->uring_lock)
12909 struct io_tctx_node *node;
12910 struct io_uring_task *tctx = NULL;
12911 struct io_sq_data *sqd = NULL;
12912 __u32 new_count[2];
12915 if (copy_from_user(new_count, arg, sizeof(new_count)))
12917 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12918 if (new_count[i] > INT_MAX)
12921 if (ctx->flags & IORING_SETUP_SQPOLL) {
12922 sqd = ctx->sq_data;
12925 * Observe the correct sqd->lock -> ctx->uring_lock
12926 * ordering. Fine to drop uring_lock here, we hold
12927 * a ref to the ctx.
12929 refcount_inc(&sqd->refs);
12930 mutex_unlock(&ctx->uring_lock);
12931 mutex_lock(&sqd->lock);
12932 mutex_lock(&ctx->uring_lock);
12934 tctx = sqd->thread->io_uring;
12937 tctx = current->io_uring;
12940 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12942 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12944 ctx->iowq_limits[i] = new_count[i];
12945 ctx->iowq_limits_set = true;
12947 if (tctx && tctx->io_wq) {
12948 ret = io_wq_max_workers(tctx->io_wq, new_count);
12952 memset(new_count, 0, sizeof(new_count));
12956 mutex_unlock(&sqd->lock);
12957 io_put_sq_data(sqd);
12960 if (copy_to_user(arg, new_count, sizeof(new_count)))
12963 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12967 /* now propagate the restriction to all registered users */
12968 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12969 struct io_uring_task *tctx = node->task->io_uring;
12971 if (WARN_ON_ONCE(!tctx->io_wq))
12974 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12975 new_count[i] = ctx->iowq_limits[i];
12976 /* ignore errors, it always returns zero anyway */
12977 (void)io_wq_max_workers(tctx->io_wq, new_count);
12982 mutex_unlock(&sqd->lock);
12983 io_put_sq_data(sqd);
12988 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12990 struct io_uring_buf_ring *br;
12991 struct io_uring_buf_reg reg;
12992 struct io_buffer_list *bl;
12993 struct page **pages;
12996 if (copy_from_user(®, arg, sizeof(reg)))
12999 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
13001 if (!reg.ring_addr)
13003 if (reg.ring_addr & ~PAGE_MASK)
13005 if (!is_power_of_2(reg.ring_entries))
13008 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
13009 int ret = io_init_bl_list(ctx);
13014 bl = io_buffer_get_list(ctx, reg.bgid);
13016 /* if mapped buffer ring OR classic exists, don't allow */
13017 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
13020 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
13025 pages = io_pin_pages(reg.ring_addr,
13026 struct_size(br, bufs, reg.ring_entries),
13028 if (IS_ERR(pages)) {
13030 return PTR_ERR(pages);
13033 br = page_address(pages[0]);
13034 bl->buf_pages = pages;
13035 bl->buf_nr_pages = nr_pages;
13036 bl->nr_entries = reg.ring_entries;
13038 bl->mask = reg.ring_entries - 1;
13039 io_buffer_add_list(ctx, bl, reg.bgid);
13043 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
13045 struct io_uring_buf_reg reg;
13046 struct io_buffer_list *bl;
13048 if (copy_from_user(®, arg, sizeof(reg)))
13050 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
13053 bl = io_buffer_get_list(ctx, reg.bgid);
13056 if (!bl->buf_nr_pages)
13059 __io_remove_buffers(ctx, bl, -1U);
13060 if (bl->bgid >= BGID_ARRAY) {
13061 xa_erase(&ctx->io_bl_xa, bl->bgid);
13067 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
13068 void __user *arg, unsigned nr_args)
13069 __releases(ctx->uring_lock)
13070 __acquires(ctx->uring_lock)
13075 * We're inside the ring mutex, if the ref is already dying, then
13076 * someone else killed the ctx or is already going through
13077 * io_uring_register().
13079 if (percpu_ref_is_dying(&ctx->refs))
13082 if (ctx->restricted) {
13083 if (opcode >= IORING_REGISTER_LAST)
13085 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
13086 if (!test_bit(opcode, ctx->restrictions.register_op))
13091 case IORING_REGISTER_BUFFERS:
13095 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
13097 case IORING_UNREGISTER_BUFFERS:
13099 if (arg || nr_args)
13101 ret = io_sqe_buffers_unregister(ctx);
13103 case IORING_REGISTER_FILES:
13107 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
13109 case IORING_UNREGISTER_FILES:
13111 if (arg || nr_args)
13113 ret = io_sqe_files_unregister(ctx);
13115 case IORING_REGISTER_FILES_UPDATE:
13116 ret = io_register_files_update(ctx, arg, nr_args);
13118 case IORING_REGISTER_EVENTFD:
13122 ret = io_eventfd_register(ctx, arg, 0);
13124 case IORING_REGISTER_EVENTFD_ASYNC:
13128 ret = io_eventfd_register(ctx, arg, 1);
13130 case IORING_UNREGISTER_EVENTFD:
13132 if (arg || nr_args)
13134 ret = io_eventfd_unregister(ctx);
13136 case IORING_REGISTER_PROBE:
13138 if (!arg || nr_args > 256)
13140 ret = io_probe(ctx, arg, nr_args);
13142 case IORING_REGISTER_PERSONALITY:
13144 if (arg || nr_args)
13146 ret = io_register_personality(ctx);
13148 case IORING_UNREGISTER_PERSONALITY:
13152 ret = io_unregister_personality(ctx, nr_args);
13154 case IORING_REGISTER_ENABLE_RINGS:
13156 if (arg || nr_args)
13158 ret = io_register_enable_rings(ctx);
13160 case IORING_REGISTER_RESTRICTIONS:
13161 ret = io_register_restrictions(ctx, arg, nr_args);
13163 case IORING_REGISTER_FILES2:
13164 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
13166 case IORING_REGISTER_FILES_UPDATE2:
13167 ret = io_register_rsrc_update(ctx, arg, nr_args,
13170 case IORING_REGISTER_BUFFERS2:
13171 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
13173 case IORING_REGISTER_BUFFERS_UPDATE:
13174 ret = io_register_rsrc_update(ctx, arg, nr_args,
13175 IORING_RSRC_BUFFER);
13177 case IORING_REGISTER_IOWQ_AFF:
13179 if (!arg || !nr_args)
13181 ret = io_register_iowq_aff(ctx, arg, nr_args);
13183 case IORING_UNREGISTER_IOWQ_AFF:
13185 if (arg || nr_args)
13187 ret = io_unregister_iowq_aff(ctx);
13189 case IORING_REGISTER_IOWQ_MAX_WORKERS:
13191 if (!arg || nr_args != 2)
13193 ret = io_register_iowq_max_workers(ctx, arg);
13195 case IORING_REGISTER_RING_FDS:
13196 ret = io_ringfd_register(ctx, arg, nr_args);
13198 case IORING_UNREGISTER_RING_FDS:
13199 ret = io_ringfd_unregister(ctx, arg, nr_args);
13201 case IORING_REGISTER_PBUF_RING:
13203 if (!arg || nr_args != 1)
13205 ret = io_register_pbuf_ring(ctx, arg);
13207 case IORING_UNREGISTER_PBUF_RING:
13209 if (!arg || nr_args != 1)
13211 ret = io_unregister_pbuf_ring(ctx, arg);
13221 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
13222 void __user *, arg, unsigned int, nr_args)
13224 struct io_ring_ctx *ctx;
13233 if (f.file->f_op != &io_uring_fops)
13236 ctx = f.file->private_data;
13238 io_run_task_work();
13240 mutex_lock(&ctx->uring_lock);
13241 ret = __io_uring_register(ctx, opcode, arg, nr_args);
13242 mutex_unlock(&ctx->uring_lock);
13243 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
13249 static int __init io_uring_init(void)
13251 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13252 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13253 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13256 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13257 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13258 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13259 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13260 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13261 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13262 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13263 BUILD_BUG_SQE_ELEM(8, __u64, off);
13264 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13265 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13266 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13267 BUILD_BUG_SQE_ELEM(24, __u32, len);
13268 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13269 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13270 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13271 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13272 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13273 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13274 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13275 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13276 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13277 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13278 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13279 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13280 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13281 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13282 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13283 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13284 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13285 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13286 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13287 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13288 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13289 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13291 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13292 sizeof(struct io_uring_rsrc_update));
13293 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13294 sizeof(struct io_uring_rsrc_update2));
13296 /* ->buf_index is u16 */
13297 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13298 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13299 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13300 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13301 offsetof(struct io_uring_buf_ring, tail));
13303 /* should fit into one byte */
13304 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13305 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13306 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13308 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13309 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13311 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13313 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13315 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13319 __initcall(io_uring_init);