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;
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);
6035 /* if the file has a flush method, be safe and punt to async */
6036 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
6037 spin_unlock(&files->file_lock);
6041 file = __close_fd_get_file(close->fd);
6042 spin_unlock(&files->file_lock);
6046 /* No ->flush() or already async, safely close from here */
6047 ret = filp_close(file, current->files);
6051 __io_req_complete(req, issue_flags, ret, 0);
6055 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6057 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
6060 req->sync.off = READ_ONCE(sqe->off);
6061 req->sync.len = READ_ONCE(sqe->len);
6062 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
6066 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
6070 /* sync_file_range always requires a blocking context */
6071 if (issue_flags & IO_URING_F_NONBLOCK)
6074 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
6076 io_req_complete(req, ret);
6080 #if defined(CONFIG_NET)
6081 static int io_shutdown_prep(struct io_kiocb *req,
6082 const struct io_uring_sqe *sqe)
6084 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
6085 sqe->buf_index || sqe->splice_fd_in))
6088 req->shutdown.how = READ_ONCE(sqe->len);
6092 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
6094 struct socket *sock;
6097 if (issue_flags & IO_URING_F_NONBLOCK)
6100 sock = sock_from_file(req->file);
6101 if (unlikely(!sock))
6104 ret = __sys_shutdown_sock(sock, req->shutdown.how);
6105 io_req_complete(req, ret);
6109 static bool io_net_retry(struct socket *sock, int flags)
6111 if (!(flags & MSG_WAITALL))
6113 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
6116 static int io_setup_async_msg(struct io_kiocb *req,
6117 struct io_async_msghdr *kmsg)
6119 struct io_async_msghdr *async_msg = req->async_data;
6123 if (io_alloc_async_data(req)) {
6124 kfree(kmsg->free_iov);
6127 async_msg = req->async_data;
6128 req->flags |= REQ_F_NEED_CLEANUP;
6129 memcpy(async_msg, kmsg, sizeof(*kmsg));
6130 async_msg->msg.msg_name = &async_msg->addr;
6131 /* if were using fast_iov, set it to the new one */
6132 if (!async_msg->free_iov)
6133 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
6138 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
6139 struct io_async_msghdr *iomsg)
6141 iomsg->msg.msg_name = &iomsg->addr;
6142 iomsg->free_iov = iomsg->fast_iov;
6143 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
6144 req->sr_msg.msg_flags, &iomsg->free_iov);
6147 static int io_sendmsg_prep_async(struct io_kiocb *req)
6151 ret = io_sendmsg_copy_hdr(req, req->async_data);
6153 req->flags |= REQ_F_NEED_CLEANUP;
6157 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6159 struct io_sr_msg *sr = &req->sr_msg;
6161 if (unlikely(sqe->file_index))
6163 if (unlikely(sqe->addr2 || sqe->file_index))
6166 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6167 sr->len = READ_ONCE(sqe->len);
6168 sr->flags = READ_ONCE(sqe->addr2);
6169 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6171 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6172 if (sr->msg_flags & MSG_DONTWAIT)
6173 req->flags |= REQ_F_NOWAIT;
6175 #ifdef CONFIG_COMPAT
6176 if (req->ctx->compat)
6177 sr->msg_flags |= MSG_CMSG_COMPAT;
6183 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
6185 struct io_async_msghdr iomsg, *kmsg;
6186 struct io_sr_msg *sr = &req->sr_msg;
6187 struct socket *sock;
6192 sock = sock_from_file(req->file);
6193 if (unlikely(!sock))
6196 if (req_has_async_data(req)) {
6197 kmsg = req->async_data;
6199 ret = io_sendmsg_copy_hdr(req, &iomsg);
6205 if (!(req->flags & REQ_F_POLLED) &&
6206 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6207 return io_setup_async_msg(req, kmsg);
6209 flags = sr->msg_flags;
6210 if (issue_flags & IO_URING_F_NONBLOCK)
6211 flags |= MSG_DONTWAIT;
6212 if (flags & MSG_WAITALL)
6213 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6215 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
6217 if (ret < min_ret) {
6218 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6219 return io_setup_async_msg(req, kmsg);
6220 if (ret == -ERESTARTSYS)
6222 if (ret > 0 && io_net_retry(sock, flags)) {
6224 req->flags |= REQ_F_PARTIAL_IO;
6225 return io_setup_async_msg(req, kmsg);
6229 /* fast path, check for non-NULL to avoid function call */
6231 kfree(kmsg->free_iov);
6232 req->flags &= ~REQ_F_NEED_CLEANUP;
6235 else if (sr->done_io)
6237 __io_req_complete(req, issue_flags, ret, 0);
6241 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6243 struct io_sr_msg *sr = &req->sr_msg;
6246 struct socket *sock;
6251 if (!(req->flags & REQ_F_POLLED) &&
6252 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6255 sock = sock_from_file(req->file);
6256 if (unlikely(!sock))
6259 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6263 msg.msg_name = NULL;
6264 msg.msg_control = NULL;
6265 msg.msg_controllen = 0;
6266 msg.msg_namelen = 0;
6268 flags = sr->msg_flags;
6269 if (issue_flags & IO_URING_F_NONBLOCK)
6270 flags |= MSG_DONTWAIT;
6271 if (flags & MSG_WAITALL)
6272 min_ret = iov_iter_count(&msg.msg_iter);
6274 msg.msg_flags = flags;
6275 ret = sock_sendmsg(sock, &msg);
6276 if (ret < min_ret) {
6277 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6279 if (ret == -ERESTARTSYS)
6281 if (ret > 0 && io_net_retry(sock, flags)) {
6285 req->flags |= REQ_F_PARTIAL_IO;
6292 else if (sr->done_io)
6294 __io_req_complete(req, issue_flags, ret, 0);
6298 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6299 struct io_async_msghdr *iomsg)
6301 struct io_sr_msg *sr = &req->sr_msg;
6302 struct iovec __user *uiov;
6306 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6307 &iomsg->uaddr, &uiov, &iov_len);
6311 if (req->flags & REQ_F_BUFFER_SELECT) {
6314 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6316 sr->len = iomsg->fast_iov[0].iov_len;
6317 iomsg->free_iov = NULL;
6319 iomsg->free_iov = iomsg->fast_iov;
6320 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6321 &iomsg->free_iov, &iomsg->msg.msg_iter,
6330 #ifdef CONFIG_COMPAT
6331 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6332 struct io_async_msghdr *iomsg)
6334 struct io_sr_msg *sr = &req->sr_msg;
6335 struct compat_iovec __user *uiov;
6340 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6345 uiov = compat_ptr(ptr);
6346 if (req->flags & REQ_F_BUFFER_SELECT) {
6347 compat_ssize_t clen;
6351 if (!access_ok(uiov, sizeof(*uiov)))
6353 if (__get_user(clen, &uiov->iov_len))
6358 iomsg->free_iov = NULL;
6360 iomsg->free_iov = iomsg->fast_iov;
6361 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6362 UIO_FASTIOV, &iomsg->free_iov,
6363 &iomsg->msg.msg_iter, true);
6372 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6373 struct io_async_msghdr *iomsg)
6375 iomsg->msg.msg_name = &iomsg->addr;
6377 #ifdef CONFIG_COMPAT
6378 if (req->ctx->compat)
6379 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6382 return __io_recvmsg_copy_hdr(req, iomsg);
6385 static int io_recvmsg_prep_async(struct io_kiocb *req)
6389 ret = io_recvmsg_copy_hdr(req, req->async_data);
6391 req->flags |= REQ_F_NEED_CLEANUP;
6395 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6397 struct io_sr_msg *sr = &req->sr_msg;
6399 if (unlikely(sqe->file_index))
6401 if (unlikely(sqe->addr2 || sqe->file_index))
6404 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6405 sr->len = READ_ONCE(sqe->len);
6406 sr->flags = READ_ONCE(sqe->addr2);
6407 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6409 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6410 if (sr->msg_flags & MSG_DONTWAIT)
6411 req->flags |= REQ_F_NOWAIT;
6413 #ifdef CONFIG_COMPAT
6414 if (req->ctx->compat)
6415 sr->msg_flags |= MSG_CMSG_COMPAT;
6421 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6423 struct io_async_msghdr iomsg, *kmsg;
6424 struct io_sr_msg *sr = &req->sr_msg;
6425 struct socket *sock;
6426 unsigned int cflags;
6428 int ret, min_ret = 0;
6429 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6431 sock = sock_from_file(req->file);
6432 if (unlikely(!sock))
6435 if (req_has_async_data(req)) {
6436 kmsg = req->async_data;
6438 ret = io_recvmsg_copy_hdr(req, &iomsg);
6444 if (!(req->flags & REQ_F_POLLED) &&
6445 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6446 return io_setup_async_msg(req, kmsg);
6448 if (io_do_buffer_select(req)) {
6451 buf = io_buffer_select(req, &sr->len, issue_flags);
6454 kmsg->fast_iov[0].iov_base = buf;
6455 kmsg->fast_iov[0].iov_len = sr->len;
6456 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6460 flags = sr->msg_flags;
6462 flags |= MSG_DONTWAIT;
6463 if (flags & MSG_WAITALL)
6464 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6466 kmsg->msg.msg_get_inq = 1;
6467 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6468 if (ret < min_ret) {
6469 if (ret == -EAGAIN && force_nonblock)
6470 return io_setup_async_msg(req, kmsg);
6471 if (ret == -ERESTARTSYS)
6473 if (ret > 0 && io_net_retry(sock, flags)) {
6475 req->flags |= REQ_F_PARTIAL_IO;
6476 return io_setup_async_msg(req, kmsg);
6479 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6483 /* fast path, check for non-NULL to avoid function call */
6485 kfree(kmsg->free_iov);
6486 req->flags &= ~REQ_F_NEED_CLEANUP;
6489 else if (sr->done_io)
6491 cflags = io_put_kbuf(req, issue_flags);
6492 if (kmsg->msg.msg_inq)
6493 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6494 __io_req_complete(req, issue_flags, ret, cflags);
6498 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6500 struct io_sr_msg *sr = &req->sr_msg;
6502 struct socket *sock;
6504 unsigned int cflags;
6506 int ret, min_ret = 0;
6507 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6509 if (!(req->flags & REQ_F_POLLED) &&
6510 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6513 sock = sock_from_file(req->file);
6514 if (unlikely(!sock))
6517 if (io_do_buffer_select(req)) {
6520 buf = io_buffer_select(req, &sr->len, issue_flags);
6526 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6530 msg.msg_name = NULL;
6531 msg.msg_namelen = 0;
6532 msg.msg_control = NULL;
6533 msg.msg_get_inq = 1;
6535 msg.msg_controllen = 0;
6536 msg.msg_iocb = NULL;
6538 flags = sr->msg_flags;
6540 flags |= MSG_DONTWAIT;
6541 if (flags & MSG_WAITALL)
6542 min_ret = iov_iter_count(&msg.msg_iter);
6544 ret = sock_recvmsg(sock, &msg, flags);
6545 if (ret < min_ret) {
6546 if (ret == -EAGAIN && force_nonblock)
6548 if (ret == -ERESTARTSYS)
6550 if (ret > 0 && io_net_retry(sock, flags)) {
6554 req->flags |= REQ_F_PARTIAL_IO;
6558 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6565 else if (sr->done_io)
6567 cflags = io_put_kbuf(req, issue_flags);
6569 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6570 __io_req_complete(req, issue_flags, ret, cflags);
6574 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6576 struct io_accept *accept = &req->accept;
6579 if (sqe->len || sqe->buf_index)
6582 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6583 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6584 accept->flags = READ_ONCE(sqe->accept_flags);
6585 accept->nofile = rlimit(RLIMIT_NOFILE);
6586 flags = READ_ONCE(sqe->ioprio);
6587 if (flags & ~IORING_ACCEPT_MULTISHOT)
6590 accept->file_slot = READ_ONCE(sqe->file_index);
6591 if (accept->file_slot) {
6592 if (accept->flags & SOCK_CLOEXEC)
6594 if (flags & IORING_ACCEPT_MULTISHOT &&
6595 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6598 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6600 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6601 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6602 if (flags & IORING_ACCEPT_MULTISHOT)
6603 req->flags |= REQ_F_APOLL_MULTISHOT;
6607 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6609 struct io_ring_ctx *ctx = req->ctx;
6610 struct io_accept *accept = &req->accept;
6611 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6612 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6613 bool fixed = !!accept->file_slot;
6619 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6620 if (unlikely(fd < 0))
6623 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6628 ret = PTR_ERR(file);
6629 if (ret == -EAGAIN && force_nonblock) {
6631 * if it's multishot and polled, we don't need to
6632 * return EAGAIN to arm the poll infra since it
6633 * has already been done
6635 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6636 IO_APOLL_MULTI_POLLED)
6640 if (ret == -ERESTARTSYS)
6643 } else if (!fixed) {
6644 fd_install(fd, file);
6647 ret = io_fixed_fd_install(req, issue_flags, file,
6651 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6652 __io_req_complete(req, issue_flags, ret, 0);
6658 spin_lock(&ctx->completion_lock);
6659 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6661 io_commit_cqring(ctx);
6662 spin_unlock(&ctx->completion_lock);
6664 io_cqring_ev_posted(ctx);
6673 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6675 struct io_socket *sock = &req->sock;
6677 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6680 sock->domain = READ_ONCE(sqe->fd);
6681 sock->type = READ_ONCE(sqe->off);
6682 sock->protocol = READ_ONCE(sqe->len);
6683 sock->file_slot = READ_ONCE(sqe->file_index);
6684 sock->nofile = rlimit(RLIMIT_NOFILE);
6686 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6687 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6689 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6694 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6696 struct io_socket *sock = &req->sock;
6697 bool fixed = !!sock->file_slot;
6702 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6703 if (unlikely(fd < 0))
6706 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6710 ret = PTR_ERR(file);
6711 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6713 if (ret == -ERESTARTSYS)
6716 } else if (!fixed) {
6717 fd_install(fd, file);
6720 ret = io_fixed_fd_install(req, issue_flags, file,
6723 __io_req_complete(req, issue_flags, ret, 0);
6727 static int io_connect_prep_async(struct io_kiocb *req)
6729 struct io_async_connect *io = req->async_data;
6730 struct io_connect *conn = &req->connect;
6732 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6735 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6737 struct io_connect *conn = &req->connect;
6739 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6742 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6743 conn->addr_len = READ_ONCE(sqe->addr2);
6747 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6749 struct io_async_connect __io, *io;
6750 unsigned file_flags;
6752 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6754 if (req_has_async_data(req)) {
6755 io = req->async_data;
6757 ret = move_addr_to_kernel(req->connect.addr,
6758 req->connect.addr_len,
6765 file_flags = force_nonblock ? O_NONBLOCK : 0;
6767 ret = __sys_connect_file(req->file, &io->address,
6768 req->connect.addr_len, file_flags);
6769 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6770 if (req_has_async_data(req))
6772 if (io_alloc_async_data(req)) {
6776 memcpy(req->async_data, &__io, sizeof(__io));
6779 if (ret == -ERESTARTSYS)
6784 __io_req_complete(req, issue_flags, ret, 0);
6787 #else /* !CONFIG_NET */
6788 #define IO_NETOP_FN(op) \
6789 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6791 return -EOPNOTSUPP; \
6794 #define IO_NETOP_PREP(op) \
6796 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6798 return -EOPNOTSUPP; \
6801 #define IO_NETOP_PREP_ASYNC(op) \
6803 static int io_##op##_prep_async(struct io_kiocb *req) \
6805 return -EOPNOTSUPP; \
6808 IO_NETOP_PREP_ASYNC(sendmsg);
6809 IO_NETOP_PREP_ASYNC(recvmsg);
6810 IO_NETOP_PREP_ASYNC(connect);
6811 IO_NETOP_PREP(accept);
6812 IO_NETOP_PREP(socket);
6813 IO_NETOP_PREP(shutdown);
6816 #endif /* CONFIG_NET */
6818 struct io_poll_table {
6819 struct poll_table_struct pt;
6820 struct io_kiocb *req;
6825 #define IO_POLL_CANCEL_FLAG BIT(31)
6826 #define IO_POLL_REF_MASK GENMASK(30, 0)
6829 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6830 * bump it and acquire ownership. It's disallowed to modify requests while not
6831 * owning it, that prevents from races for enqueueing task_work's and b/w
6832 * arming poll and wakeups.
6834 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6836 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6839 static void io_poll_mark_cancelled(struct io_kiocb *req)
6841 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6844 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6846 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6847 if (req->opcode == IORING_OP_POLL_ADD)
6848 return req->async_data;
6849 return req->apoll->double_poll;
6852 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6854 if (req->opcode == IORING_OP_POLL_ADD)
6856 return &req->apoll->poll;
6859 static void io_poll_req_insert(struct io_kiocb *req)
6861 struct io_ring_ctx *ctx = req->ctx;
6862 struct hlist_head *list;
6864 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6865 hlist_add_head(&req->hash_node, list);
6868 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6869 wait_queue_func_t wake_func)
6872 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6873 /* mask in events that we always want/need */
6874 poll->events = events | IO_POLL_UNMASK;
6875 INIT_LIST_HEAD(&poll->wait.entry);
6876 init_waitqueue_func_entry(&poll->wait, wake_func);
6879 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6881 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6884 spin_lock_irq(&head->lock);
6885 list_del_init(&poll->wait.entry);
6887 spin_unlock_irq(&head->lock);
6891 static void io_poll_remove_entries(struct io_kiocb *req)
6894 * Nothing to do if neither of those flags are set. Avoid dipping
6895 * into the poll/apoll/double cachelines if we can.
6897 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6901 * While we hold the waitqueue lock and the waitqueue is nonempty,
6902 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6903 * lock in the first place can race with the waitqueue being freed.
6905 * We solve this as eventpoll does: by taking advantage of the fact that
6906 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6907 * we enter rcu_read_lock() and see that the pointer to the queue is
6908 * non-NULL, we can then lock it without the memory being freed out from
6911 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6912 * case the caller deletes the entry from the queue, leaving it empty.
6913 * In that case, only RCU prevents the queue memory from being freed.
6916 if (req->flags & REQ_F_SINGLE_POLL)
6917 io_poll_remove_entry(io_poll_get_single(req));
6918 if (req->flags & REQ_F_DOUBLE_POLL)
6919 io_poll_remove_entry(io_poll_get_double(req));
6923 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6925 * All poll tw should go through this. Checks for poll events, manages
6926 * references, does rewait, etc.
6928 * Returns a negative error on failure. >0 when no action require, which is
6929 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6930 * the request, then the mask is stored in req->cqe.res.
6932 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6934 struct io_ring_ctx *ctx = req->ctx;
6937 /* req->task == current here, checking PF_EXITING is safe */
6938 if (unlikely(req->task->flags & PF_EXITING))
6942 v = atomic_read(&req->poll_refs);
6944 /* tw handler should be the owner, and so have some references */
6945 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6947 if (v & IO_POLL_CANCEL_FLAG)
6950 if (!req->cqe.res) {
6951 struct poll_table_struct pt = { ._key = req->apoll_events };
6952 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6955 if ((unlikely(!req->cqe.res)))
6957 if (req->apoll_events & EPOLLONESHOT)
6960 /* multishot, just fill a CQE and proceed */
6961 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6962 __poll_t mask = mangle_poll(req->cqe.res &
6966 spin_lock(&ctx->completion_lock);
6967 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6968 mask, IORING_CQE_F_MORE);
6969 io_commit_cqring(ctx);
6970 spin_unlock(&ctx->completion_lock);
6972 io_cqring_ev_posted(ctx);
6978 io_tw_lock(req->ctx, locked);
6979 if (unlikely(req->task->flags & PF_EXITING))
6981 ret = io_issue_sqe(req,
6982 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6987 * Release all references, retry if someone tried to restart
6988 * task_work while we were executing it.
6990 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6995 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6997 struct io_ring_ctx *ctx = req->ctx;
7000 ret = io_poll_check_events(req, locked);
7005 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
7011 io_poll_remove_entries(req);
7012 spin_lock(&ctx->completion_lock);
7013 hash_del(&req->hash_node);
7014 __io_req_complete_post(req, req->cqe.res, 0);
7015 io_commit_cqring(ctx);
7016 spin_unlock(&ctx->completion_lock);
7017 io_cqring_ev_posted(ctx);
7020 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
7022 struct io_ring_ctx *ctx = req->ctx;
7025 ret = io_poll_check_events(req, locked);
7029 io_poll_remove_entries(req);
7030 spin_lock(&ctx->completion_lock);
7031 hash_del(&req->hash_node);
7032 spin_unlock(&ctx->completion_lock);
7035 io_req_task_submit(req, locked);
7037 io_req_complete_failed(req, ret);
7040 static void __io_poll_execute(struct io_kiocb *req, int mask, __poll_t events)
7042 req->cqe.res = mask;
7044 * This is useful for poll that is armed on behalf of another
7045 * request, and where the wakeup path could be on a different
7046 * CPU. We want to avoid pulling in req->apoll->events for that
7049 req->apoll_events = events;
7050 if (req->opcode == IORING_OP_POLL_ADD)
7051 req->io_task_work.func = io_poll_task_func;
7053 req->io_task_work.func = io_apoll_task_func;
7055 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
7056 io_req_task_work_add(req);
7059 static inline void io_poll_execute(struct io_kiocb *req, int res,
7062 if (io_poll_get_ownership(req))
7063 __io_poll_execute(req, res, events);
7066 static void io_poll_cancel_req(struct io_kiocb *req)
7068 io_poll_mark_cancelled(req);
7069 /* kick tw, which should complete the request */
7070 io_poll_execute(req, 0, 0);
7073 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
7074 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
7075 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
7077 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
7080 struct io_kiocb *req = wqe_to_req(wait);
7081 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
7083 __poll_t mask = key_to_poll(key);
7085 if (unlikely(mask & POLLFREE)) {
7086 io_poll_mark_cancelled(req);
7087 /* we have to kick tw in case it's not already */
7088 io_poll_execute(req, 0, poll->events);
7091 * If the waitqueue is being freed early but someone is already
7092 * holds ownership over it, we have to tear down the request as
7093 * best we can. That means immediately removing the request from
7094 * its waitqueue and preventing all further accesses to the
7095 * waitqueue via the request.
7097 list_del_init(&poll->wait.entry);
7100 * Careful: this *must* be the last step, since as soon
7101 * as req->head is NULL'ed out, the request can be
7102 * completed and freed, since aio_poll_complete_work()
7103 * will no longer need to take the waitqueue lock.
7105 smp_store_release(&poll->head, NULL);
7109 /* for instances that support it check for an event match first */
7110 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
7113 if (io_poll_get_ownership(req)) {
7114 /* optional, saves extra locking for removal in tw handler */
7115 if (mask && poll->events & EPOLLONESHOT) {
7116 list_del_init(&poll->wait.entry);
7118 if (wqe_is_double(wait))
7119 req->flags &= ~REQ_F_DOUBLE_POLL;
7121 req->flags &= ~REQ_F_SINGLE_POLL;
7123 __io_poll_execute(req, mask, poll->events);
7128 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
7129 struct wait_queue_head *head,
7130 struct io_poll_iocb **poll_ptr)
7132 struct io_kiocb *req = pt->req;
7133 unsigned long wqe_private = (unsigned long) req;
7136 * The file being polled uses multiple waitqueues for poll handling
7137 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
7140 if (unlikely(pt->nr_entries)) {
7141 struct io_poll_iocb *first = poll;
7143 /* double add on the same waitqueue head, ignore */
7144 if (first->head == head)
7146 /* already have a 2nd entry, fail a third attempt */
7148 if ((*poll_ptr)->head == head)
7150 pt->error = -EINVAL;
7154 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
7156 pt->error = -ENOMEM;
7159 /* mark as double wq entry */
7161 req->flags |= REQ_F_DOUBLE_POLL;
7162 io_init_poll_iocb(poll, first->events, first->wait.func);
7164 if (req->opcode == IORING_OP_POLL_ADD)
7165 req->flags |= REQ_F_ASYNC_DATA;
7168 req->flags |= REQ_F_SINGLE_POLL;
7171 poll->wait.private = (void *) wqe_private;
7173 if (poll->events & EPOLLEXCLUSIVE)
7174 add_wait_queue_exclusive(head, &poll->wait);
7176 add_wait_queue(head, &poll->wait);
7179 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
7180 struct poll_table_struct *p)
7182 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7184 __io_queue_proc(&pt->req->poll, pt, head,
7185 (struct io_poll_iocb **) &pt->req->async_data);
7188 static int __io_arm_poll_handler(struct io_kiocb *req,
7189 struct io_poll_iocb *poll,
7190 struct io_poll_table *ipt, __poll_t mask)
7192 struct io_ring_ctx *ctx = req->ctx;
7195 INIT_HLIST_NODE(&req->hash_node);
7196 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
7197 io_init_poll_iocb(poll, mask, io_poll_wake);
7198 poll->file = req->file;
7200 ipt->pt._key = mask;
7203 ipt->nr_entries = 0;
7206 * Take the ownership to delay any tw execution up until we're done
7207 * with poll arming. see io_poll_get_ownership().
7209 atomic_set(&req->poll_refs, 1);
7210 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
7212 if (mask && (poll->events & EPOLLONESHOT)) {
7213 io_poll_remove_entries(req);
7214 /* no one else has access to the req, forget about the ref */
7217 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
7218 io_poll_remove_entries(req);
7220 ipt->error = -EINVAL;
7224 spin_lock(&ctx->completion_lock);
7225 io_poll_req_insert(req);
7226 spin_unlock(&ctx->completion_lock);
7229 /* can't multishot if failed, just queue the event we've got */
7230 if (unlikely(ipt->error || !ipt->nr_entries))
7231 poll->events |= EPOLLONESHOT;
7232 __io_poll_execute(req, mask, poll->events);
7237 * Release ownership. If someone tried to queue a tw while it was
7238 * locked, kick it off for them.
7240 v = atomic_dec_return(&req->poll_refs);
7241 if (unlikely(v & IO_POLL_REF_MASK))
7242 __io_poll_execute(req, 0, poll->events);
7246 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
7247 struct poll_table_struct *p)
7249 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
7250 struct async_poll *apoll = pt->req->apoll;
7252 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
7261 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
7263 const struct io_op_def *def = &io_op_defs[req->opcode];
7264 struct io_ring_ctx *ctx = req->ctx;
7265 struct async_poll *apoll;
7266 struct io_poll_table ipt;
7267 __poll_t mask = POLLPRI | POLLERR;
7270 if (!def->pollin && !def->pollout)
7271 return IO_APOLL_ABORTED;
7272 if (!file_can_poll(req->file))
7273 return IO_APOLL_ABORTED;
7274 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
7275 return IO_APOLL_ABORTED;
7276 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
7277 mask |= EPOLLONESHOT;
7280 mask |= EPOLLIN | EPOLLRDNORM;
7282 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7283 if ((req->opcode == IORING_OP_RECVMSG) &&
7284 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7287 mask |= EPOLLOUT | EPOLLWRNORM;
7289 if (def->poll_exclusive)
7290 mask |= EPOLLEXCLUSIVE;
7291 if (req->flags & REQ_F_POLLED) {
7293 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7294 !list_empty(&ctx->apoll_cache)) {
7295 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7297 list_del_init(&apoll->poll.wait.entry);
7299 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7300 if (unlikely(!apoll))
7301 return IO_APOLL_ABORTED;
7303 apoll->double_poll = NULL;
7305 req->flags |= REQ_F_POLLED;
7306 ipt.pt._qproc = io_async_queue_proc;
7308 io_kbuf_recycle(req, issue_flags);
7310 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7311 if (ret || ipt.error)
7312 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7314 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7315 mask, apoll->poll.events);
7320 * Returns true if we found and killed one or more poll requests
7322 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7323 struct task_struct *tsk, bool cancel_all)
7325 struct hlist_node *tmp;
7326 struct io_kiocb *req;
7330 spin_lock(&ctx->completion_lock);
7331 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7332 struct hlist_head *list;
7334 list = &ctx->cancel_hash[i];
7335 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7336 if (io_match_task_safe(req, tsk, cancel_all)) {
7337 hlist_del_init(&req->hash_node);
7338 io_poll_cancel_req(req);
7343 spin_unlock(&ctx->completion_lock);
7347 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7348 struct io_cancel_data *cd)
7349 __must_hold(&ctx->completion_lock)
7351 struct hlist_head *list;
7352 struct io_kiocb *req;
7354 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7355 hlist_for_each_entry(req, list, hash_node) {
7356 if (cd->data != req->cqe.user_data)
7358 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7360 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7361 if (cd->seq == req->work.cancel_seq)
7363 req->work.cancel_seq = cd->seq;
7370 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7371 struct io_cancel_data *cd)
7372 __must_hold(&ctx->completion_lock)
7374 struct io_kiocb *req;
7377 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7378 struct hlist_head *list;
7380 list = &ctx->cancel_hash[i];
7381 hlist_for_each_entry(req, list, hash_node) {
7382 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7383 req->file != cd->file)
7385 if (cd->seq == req->work.cancel_seq)
7387 req->work.cancel_seq = cd->seq;
7394 static bool io_poll_disarm(struct io_kiocb *req)
7395 __must_hold(&ctx->completion_lock)
7397 if (!io_poll_get_ownership(req))
7399 io_poll_remove_entries(req);
7400 hash_del(&req->hash_node);
7404 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7405 __must_hold(&ctx->completion_lock)
7407 struct io_kiocb *req;
7409 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7410 req = io_poll_file_find(ctx, cd);
7412 req = io_poll_find(ctx, false, cd);
7415 io_poll_cancel_req(req);
7419 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7424 events = READ_ONCE(sqe->poll32_events);
7426 events = swahw32(events);
7428 if (!(flags & IORING_POLL_ADD_MULTI))
7429 events |= EPOLLONESHOT;
7430 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7433 static int io_poll_remove_prep(struct io_kiocb *req,
7434 const struct io_uring_sqe *sqe)
7436 struct io_poll_update *upd = &req->poll_update;
7439 if (sqe->buf_index || sqe->splice_fd_in)
7441 flags = READ_ONCE(sqe->len);
7442 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7443 IORING_POLL_ADD_MULTI))
7445 /* meaningless without update */
7446 if (flags == IORING_POLL_ADD_MULTI)
7449 upd->old_user_data = READ_ONCE(sqe->addr);
7450 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7451 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7453 upd->new_user_data = READ_ONCE(sqe->off);
7454 if (!upd->update_user_data && upd->new_user_data)
7456 if (upd->update_events)
7457 upd->events = io_poll_parse_events(sqe, flags);
7458 else if (sqe->poll32_events)
7464 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7466 struct io_poll_iocb *poll = &req->poll;
7469 if (sqe->buf_index || sqe->off || sqe->addr)
7471 flags = READ_ONCE(sqe->len);
7472 if (flags & ~IORING_POLL_ADD_MULTI)
7474 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7477 io_req_set_refcount(req);
7478 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
7482 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7484 struct io_poll_iocb *poll = &req->poll;
7485 struct io_poll_table ipt;
7488 ipt.pt._qproc = io_poll_queue_proc;
7490 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7491 ret = ret ?: ipt.error;
7493 __io_req_complete(req, issue_flags, ret, 0);
7497 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7499 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7500 struct io_ring_ctx *ctx = req->ctx;
7501 struct io_kiocb *preq;
7505 spin_lock(&ctx->completion_lock);
7506 preq = io_poll_find(ctx, true, &cd);
7507 if (!preq || !io_poll_disarm(preq)) {
7508 spin_unlock(&ctx->completion_lock);
7509 ret = preq ? -EALREADY : -ENOENT;
7512 spin_unlock(&ctx->completion_lock);
7514 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7515 /* only mask one event flags, keep behavior flags */
7516 if (req->poll_update.update_events) {
7517 preq->poll.events &= ~0xffff;
7518 preq->poll.events |= req->poll_update.events & 0xffff;
7519 preq->poll.events |= IO_POLL_UNMASK;
7521 if (req->poll_update.update_user_data)
7522 preq->cqe.user_data = req->poll_update.new_user_data;
7524 ret2 = io_poll_add(preq, issue_flags);
7525 /* successfully updated, don't complete poll request */
7531 preq->cqe.res = -ECANCELED;
7532 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7533 io_req_task_complete(preq, &locked);
7537 /* complete update request, we're done with it */
7538 __io_req_complete(req, issue_flags, ret, 0);
7542 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7544 struct io_timeout_data *data = container_of(timer,
7545 struct io_timeout_data, timer);
7546 struct io_kiocb *req = data->req;
7547 struct io_ring_ctx *ctx = req->ctx;
7548 unsigned long flags;
7550 spin_lock_irqsave(&ctx->timeout_lock, flags);
7551 list_del_init(&req->timeout.list);
7552 atomic_set(&req->ctx->cq_timeouts,
7553 atomic_read(&req->ctx->cq_timeouts) + 1);
7554 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7556 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7559 req->cqe.res = -ETIME;
7560 req->io_task_work.func = io_req_task_complete;
7561 io_req_task_work_add(req);
7562 return HRTIMER_NORESTART;
7565 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7566 struct io_cancel_data *cd)
7567 __must_hold(&ctx->timeout_lock)
7569 struct io_timeout_data *io;
7570 struct io_kiocb *req;
7573 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7574 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7575 cd->data != req->cqe.user_data)
7577 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7578 if (cd->seq == req->work.cancel_seq)
7580 req->work.cancel_seq = cd->seq;
7586 return ERR_PTR(-ENOENT);
7588 io = req->async_data;
7589 if (hrtimer_try_to_cancel(&io->timer) == -1)
7590 return ERR_PTR(-EALREADY);
7591 list_del_init(&req->timeout.list);
7595 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7596 __must_hold(&ctx->completion_lock)
7598 struct io_kiocb *req;
7600 spin_lock_irq(&ctx->timeout_lock);
7601 req = io_timeout_extract(ctx, cd);
7602 spin_unlock_irq(&ctx->timeout_lock);
7605 return PTR_ERR(req);
7606 io_req_task_queue_fail(req, -ECANCELED);
7610 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7612 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7613 case IORING_TIMEOUT_BOOTTIME:
7614 return CLOCK_BOOTTIME;
7615 case IORING_TIMEOUT_REALTIME:
7616 return CLOCK_REALTIME;
7618 /* can't happen, vetted at prep time */
7622 return CLOCK_MONOTONIC;
7626 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7627 struct timespec64 *ts, enum hrtimer_mode mode)
7628 __must_hold(&ctx->timeout_lock)
7630 struct io_timeout_data *io;
7631 struct io_kiocb *req;
7634 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7635 found = user_data == req->cqe.user_data;
7642 io = req->async_data;
7643 if (hrtimer_try_to_cancel(&io->timer) == -1)
7645 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7646 io->timer.function = io_link_timeout_fn;
7647 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7651 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7652 struct timespec64 *ts, enum hrtimer_mode mode)
7653 __must_hold(&ctx->timeout_lock)
7655 struct io_cancel_data cd = { .data = user_data, };
7656 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7657 struct io_timeout_data *data;
7660 return PTR_ERR(req);
7662 req->timeout.off = 0; /* noseq */
7663 data = req->async_data;
7664 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7665 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7666 data->timer.function = io_timeout_fn;
7667 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7671 static int io_timeout_remove_prep(struct io_kiocb *req,
7672 const struct io_uring_sqe *sqe)
7674 struct io_timeout_rem *tr = &req->timeout_rem;
7676 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7678 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7681 tr->ltimeout = false;
7682 tr->addr = READ_ONCE(sqe->addr);
7683 tr->flags = READ_ONCE(sqe->timeout_flags);
7684 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7685 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7687 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7688 tr->ltimeout = true;
7689 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7691 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7693 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7695 } else if (tr->flags) {
7696 /* timeout removal doesn't support flags */
7703 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7705 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7710 * Remove or update an existing timeout command
7712 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7714 struct io_timeout_rem *tr = &req->timeout_rem;
7715 struct io_ring_ctx *ctx = req->ctx;
7718 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7719 struct io_cancel_data cd = { .data = tr->addr, };
7721 spin_lock(&ctx->completion_lock);
7722 ret = io_timeout_cancel(ctx, &cd);
7723 spin_unlock(&ctx->completion_lock);
7725 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7727 spin_lock_irq(&ctx->timeout_lock);
7729 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7731 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7732 spin_unlock_irq(&ctx->timeout_lock);
7737 io_req_complete_post(req, ret, 0);
7741 static int __io_timeout_prep(struct io_kiocb *req,
7742 const struct io_uring_sqe *sqe,
7743 bool is_timeout_link)
7745 struct io_timeout_data *data;
7747 u32 off = READ_ONCE(sqe->off);
7749 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7751 if (off && is_timeout_link)
7753 flags = READ_ONCE(sqe->timeout_flags);
7754 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7755 IORING_TIMEOUT_ETIME_SUCCESS))
7757 /* more than one clock specified is invalid, obviously */
7758 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7761 INIT_LIST_HEAD(&req->timeout.list);
7762 req->timeout.off = off;
7763 if (unlikely(off && !req->ctx->off_timeout_used))
7764 req->ctx->off_timeout_used = true;
7766 if (WARN_ON_ONCE(req_has_async_data(req)))
7768 if (io_alloc_async_data(req))
7771 data = req->async_data;
7773 data->flags = flags;
7775 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7778 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7781 INIT_LIST_HEAD(&req->timeout.list);
7782 data->mode = io_translate_timeout_mode(flags);
7783 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7785 if (is_timeout_link) {
7786 struct io_submit_link *link = &req->ctx->submit_state.link;
7790 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7792 req->timeout.head = link->last;
7793 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7798 static int io_timeout_prep(struct io_kiocb *req,
7799 const struct io_uring_sqe *sqe)
7801 return __io_timeout_prep(req, sqe, false);
7804 static int io_link_timeout_prep(struct io_kiocb *req,
7805 const struct io_uring_sqe *sqe)
7807 return __io_timeout_prep(req, sqe, true);
7810 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7812 struct io_ring_ctx *ctx = req->ctx;
7813 struct io_timeout_data *data = req->async_data;
7814 struct list_head *entry;
7815 u32 tail, off = req->timeout.off;
7817 spin_lock_irq(&ctx->timeout_lock);
7820 * sqe->off holds how many events that need to occur for this
7821 * timeout event to be satisfied. If it isn't set, then this is
7822 * a pure timeout request, sequence isn't used.
7824 if (io_is_timeout_noseq(req)) {
7825 entry = ctx->timeout_list.prev;
7829 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7830 req->timeout.target_seq = tail + off;
7832 /* Update the last seq here in case io_flush_timeouts() hasn't.
7833 * This is safe because ->completion_lock is held, and submissions
7834 * and completions are never mixed in the same ->completion_lock section.
7836 ctx->cq_last_tm_flush = tail;
7839 * Insertion sort, ensuring the first entry in the list is always
7840 * the one we need first.
7842 list_for_each_prev(entry, &ctx->timeout_list) {
7843 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7846 if (io_is_timeout_noseq(nxt))
7848 /* nxt.seq is behind @tail, otherwise would've been completed */
7849 if (off >= nxt->timeout.target_seq - tail)
7853 list_add(&req->timeout.list, entry);
7854 data->timer.function = io_timeout_fn;
7855 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7856 spin_unlock_irq(&ctx->timeout_lock);
7860 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7862 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7863 struct io_cancel_data *cd = data;
7865 if (req->ctx != cd->ctx)
7867 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7869 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7870 if (req->file != cd->file)
7873 if (req->cqe.user_data != cd->data)
7876 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7877 if (cd->seq == req->work.cancel_seq)
7879 req->work.cancel_seq = cd->seq;
7884 static int io_async_cancel_one(struct io_uring_task *tctx,
7885 struct io_cancel_data *cd)
7887 enum io_wq_cancel cancel_ret;
7891 if (!tctx || !tctx->io_wq)
7894 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7895 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7896 switch (cancel_ret) {
7897 case IO_WQ_CANCEL_OK:
7900 case IO_WQ_CANCEL_RUNNING:
7903 case IO_WQ_CANCEL_NOTFOUND:
7911 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7913 struct io_ring_ctx *ctx = req->ctx;
7916 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7918 ret = io_async_cancel_one(req->task->io_uring, cd);
7920 * Fall-through even for -EALREADY, as we may have poll armed
7921 * that need unarming.
7926 spin_lock(&ctx->completion_lock);
7927 ret = io_poll_cancel(ctx, cd);
7930 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7931 ret = io_timeout_cancel(ctx, cd);
7933 spin_unlock(&ctx->completion_lock);
7937 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7938 IORING_ASYNC_CANCEL_ANY)
7940 static int io_async_cancel_prep(struct io_kiocb *req,
7941 const struct io_uring_sqe *sqe)
7943 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7945 if (sqe->off || sqe->len || sqe->splice_fd_in)
7948 req->cancel.addr = READ_ONCE(sqe->addr);
7949 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7950 if (req->cancel.flags & ~CANCEL_FLAGS)
7952 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7953 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7955 req->cancel.fd = READ_ONCE(sqe->fd);
7961 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7962 unsigned int issue_flags)
7964 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7965 struct io_ring_ctx *ctx = cd->ctx;
7966 struct io_tctx_node *node;
7970 ret = io_try_cancel(req, cd);
7978 /* slow path, try all io-wq's */
7979 io_ring_submit_lock(ctx, issue_flags);
7981 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7982 struct io_uring_task *tctx = node->task->io_uring;
7984 ret = io_async_cancel_one(tctx, cd);
7985 if (ret != -ENOENT) {
7991 io_ring_submit_unlock(ctx, issue_flags);
7992 return all ? nr : ret;
7995 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7997 struct io_cancel_data cd = {
7999 .data = req->cancel.addr,
8000 .flags = req->cancel.flags,
8001 .seq = atomic_inc_return(&req->ctx->cancel_seq),
8005 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
8006 if (req->flags & REQ_F_FIXED_FILE)
8007 req->file = io_file_get_fixed(req, req->cancel.fd,
8010 req->file = io_file_get_normal(req, req->cancel.fd);
8015 cd.file = req->file;
8018 ret = __io_async_cancel(&cd, req, issue_flags);
8022 io_req_complete_post(req, ret, 0);
8026 static int io_files_update_prep(struct io_kiocb *req,
8027 const struct io_uring_sqe *sqe)
8029 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
8031 if (sqe->rw_flags || sqe->splice_fd_in)
8034 req->rsrc_update.offset = READ_ONCE(sqe->off);
8035 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
8036 if (!req->rsrc_update.nr_args)
8038 req->rsrc_update.arg = READ_ONCE(sqe->addr);
8042 static int io_files_update_with_index_alloc(struct io_kiocb *req,
8043 unsigned int issue_flags)
8045 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
8050 for (done = 0; done < req->rsrc_update.nr_args; done++) {
8051 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
8061 ret = io_fixed_fd_install(req, issue_flags, file,
8062 IORING_FILE_INDEX_ALLOC);
8065 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
8067 __io_close_fixed(req, issue_flags, ret);
8077 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
8079 struct io_ring_ctx *ctx = req->ctx;
8080 struct io_uring_rsrc_update2 up;
8083 up.offset = req->rsrc_update.offset;
8084 up.data = req->rsrc_update.arg;
8090 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
8091 ret = io_files_update_with_index_alloc(req, issue_flags);
8093 io_ring_submit_lock(ctx, issue_flags);
8094 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
8095 &up, req->rsrc_update.nr_args);
8096 io_ring_submit_unlock(ctx, issue_flags);
8101 __io_req_complete(req, issue_flags, ret, 0);
8105 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
8107 switch (req->opcode) {
8109 return io_nop_prep(req, sqe);
8110 case IORING_OP_READV:
8111 case IORING_OP_READ_FIXED:
8112 case IORING_OP_READ:
8113 case IORING_OP_WRITEV:
8114 case IORING_OP_WRITE_FIXED:
8115 case IORING_OP_WRITE:
8116 return io_prep_rw(req, sqe);
8117 case IORING_OP_POLL_ADD:
8118 return io_poll_add_prep(req, sqe);
8119 case IORING_OP_POLL_REMOVE:
8120 return io_poll_remove_prep(req, sqe);
8121 case IORING_OP_FSYNC:
8122 return io_fsync_prep(req, sqe);
8123 case IORING_OP_SYNC_FILE_RANGE:
8124 return io_sfr_prep(req, sqe);
8125 case IORING_OP_SENDMSG:
8126 case IORING_OP_SEND:
8127 return io_sendmsg_prep(req, sqe);
8128 case IORING_OP_RECVMSG:
8129 case IORING_OP_RECV:
8130 return io_recvmsg_prep(req, sqe);
8131 case IORING_OP_CONNECT:
8132 return io_connect_prep(req, sqe);
8133 case IORING_OP_TIMEOUT:
8134 return io_timeout_prep(req, sqe);
8135 case IORING_OP_TIMEOUT_REMOVE:
8136 return io_timeout_remove_prep(req, sqe);
8137 case IORING_OP_ASYNC_CANCEL:
8138 return io_async_cancel_prep(req, sqe);
8139 case IORING_OP_LINK_TIMEOUT:
8140 return io_link_timeout_prep(req, sqe);
8141 case IORING_OP_ACCEPT:
8142 return io_accept_prep(req, sqe);
8143 case IORING_OP_FALLOCATE:
8144 return io_fallocate_prep(req, sqe);
8145 case IORING_OP_OPENAT:
8146 return io_openat_prep(req, sqe);
8147 case IORING_OP_CLOSE:
8148 return io_close_prep(req, sqe);
8149 case IORING_OP_FILES_UPDATE:
8150 return io_files_update_prep(req, sqe);
8151 case IORING_OP_STATX:
8152 return io_statx_prep(req, sqe);
8153 case IORING_OP_FADVISE:
8154 return io_fadvise_prep(req, sqe);
8155 case IORING_OP_MADVISE:
8156 return io_madvise_prep(req, sqe);
8157 case IORING_OP_OPENAT2:
8158 return io_openat2_prep(req, sqe);
8159 case IORING_OP_EPOLL_CTL:
8160 return io_epoll_ctl_prep(req, sqe);
8161 case IORING_OP_SPLICE:
8162 return io_splice_prep(req, sqe);
8163 case IORING_OP_PROVIDE_BUFFERS:
8164 return io_provide_buffers_prep(req, sqe);
8165 case IORING_OP_REMOVE_BUFFERS:
8166 return io_remove_buffers_prep(req, sqe);
8168 return io_tee_prep(req, sqe);
8169 case IORING_OP_SHUTDOWN:
8170 return io_shutdown_prep(req, sqe);
8171 case IORING_OP_RENAMEAT:
8172 return io_renameat_prep(req, sqe);
8173 case IORING_OP_UNLINKAT:
8174 return io_unlinkat_prep(req, sqe);
8175 case IORING_OP_MKDIRAT:
8176 return io_mkdirat_prep(req, sqe);
8177 case IORING_OP_SYMLINKAT:
8178 return io_symlinkat_prep(req, sqe);
8179 case IORING_OP_LINKAT:
8180 return io_linkat_prep(req, sqe);
8181 case IORING_OP_MSG_RING:
8182 return io_msg_ring_prep(req, sqe);
8183 case IORING_OP_FSETXATTR:
8184 return io_fsetxattr_prep(req, sqe);
8185 case IORING_OP_SETXATTR:
8186 return io_setxattr_prep(req, sqe);
8187 case IORING_OP_FGETXATTR:
8188 return io_fgetxattr_prep(req, sqe);
8189 case IORING_OP_GETXATTR:
8190 return io_getxattr_prep(req, sqe);
8191 case IORING_OP_SOCKET:
8192 return io_socket_prep(req, sqe);
8193 case IORING_OP_URING_CMD:
8194 return io_uring_cmd_prep(req, sqe);
8197 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
8202 static int io_req_prep_async(struct io_kiocb *req)
8204 const struct io_op_def *def = &io_op_defs[req->opcode];
8206 /* assign early for deferred execution for non-fixed file */
8207 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
8208 req->file = io_file_get_normal(req, req->cqe.fd);
8209 if (!def->needs_async_setup)
8211 if (WARN_ON_ONCE(req_has_async_data(req)))
8213 if (io_alloc_async_data(req))
8216 switch (req->opcode) {
8217 case IORING_OP_READV:
8218 return io_readv_prep_async(req);
8219 case IORING_OP_WRITEV:
8220 return io_writev_prep_async(req);
8221 case IORING_OP_SENDMSG:
8222 return io_sendmsg_prep_async(req);
8223 case IORING_OP_RECVMSG:
8224 return io_recvmsg_prep_async(req);
8225 case IORING_OP_CONNECT:
8226 return io_connect_prep_async(req);
8227 case IORING_OP_URING_CMD:
8228 return io_uring_cmd_prep_async(req);
8230 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
8235 static u32 io_get_sequence(struct io_kiocb *req)
8237 u32 seq = req->ctx->cached_sq_head;
8238 struct io_kiocb *cur;
8240 /* need original cached_sq_head, but it was increased for each req */
8241 io_for_each_link(cur, req)
8246 static __cold void io_drain_req(struct io_kiocb *req)
8248 struct io_ring_ctx *ctx = req->ctx;
8249 struct io_defer_entry *de;
8251 u32 seq = io_get_sequence(req);
8253 /* Still need defer if there is pending req in defer list. */
8254 spin_lock(&ctx->completion_lock);
8255 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
8256 spin_unlock(&ctx->completion_lock);
8258 ctx->drain_active = false;
8259 io_req_task_queue(req);
8262 spin_unlock(&ctx->completion_lock);
8264 ret = io_req_prep_async(req);
8267 io_req_complete_failed(req, ret);
8270 io_prep_async_link(req);
8271 de = kmalloc(sizeof(*de), GFP_KERNEL);
8277 spin_lock(&ctx->completion_lock);
8278 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
8279 spin_unlock(&ctx->completion_lock);
8284 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
8287 list_add_tail(&de->list, &ctx->defer_list);
8288 spin_unlock(&ctx->completion_lock);
8291 static void io_clean_op(struct io_kiocb *req)
8293 if (req->flags & REQ_F_BUFFER_SELECTED) {
8294 spin_lock(&req->ctx->completion_lock);
8295 io_put_kbuf_comp(req);
8296 spin_unlock(&req->ctx->completion_lock);
8299 if (req->flags & REQ_F_NEED_CLEANUP) {
8300 switch (req->opcode) {
8301 case IORING_OP_READV:
8302 case IORING_OP_READ_FIXED:
8303 case IORING_OP_READ:
8304 case IORING_OP_WRITEV:
8305 case IORING_OP_WRITE_FIXED:
8306 case IORING_OP_WRITE: {
8307 struct io_async_rw *io = req->async_data;
8309 kfree(io->free_iovec);
8312 case IORING_OP_RECVMSG:
8313 case IORING_OP_SENDMSG: {
8314 struct io_async_msghdr *io = req->async_data;
8316 kfree(io->free_iov);
8319 case IORING_OP_OPENAT:
8320 case IORING_OP_OPENAT2:
8321 if (req->open.filename)
8322 putname(req->open.filename);
8324 case IORING_OP_RENAMEAT:
8325 putname(req->rename.oldpath);
8326 putname(req->rename.newpath);
8328 case IORING_OP_UNLINKAT:
8329 putname(req->unlink.filename);
8331 case IORING_OP_MKDIRAT:
8332 putname(req->mkdir.filename);
8334 case IORING_OP_SYMLINKAT:
8335 putname(req->symlink.oldpath);
8336 putname(req->symlink.newpath);
8338 case IORING_OP_LINKAT:
8339 putname(req->hardlink.oldpath);
8340 putname(req->hardlink.newpath);
8342 case IORING_OP_STATX:
8343 if (req->statx.filename)
8344 putname(req->statx.filename);
8346 case IORING_OP_SETXATTR:
8347 case IORING_OP_FSETXATTR:
8348 case IORING_OP_GETXATTR:
8349 case IORING_OP_FGETXATTR:
8350 __io_xattr_finish(req);
8354 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8355 kfree(req->apoll->double_poll);
8359 if (req->flags & REQ_F_INFLIGHT) {
8360 struct io_uring_task *tctx = req->task->io_uring;
8362 atomic_dec(&tctx->inflight_tracked);
8364 if (req->flags & REQ_F_CREDS)
8365 put_cred(req->creds);
8366 if (req->flags & REQ_F_ASYNC_DATA) {
8367 kfree(req->async_data);
8368 req->async_data = NULL;
8370 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8373 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8375 if (req->file || !io_op_defs[req->opcode].needs_file)
8378 if (req->flags & REQ_F_FIXED_FILE)
8379 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8381 req->file = io_file_get_normal(req, req->cqe.fd);
8386 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8388 const struct io_op_def *def = &io_op_defs[req->opcode];
8389 const struct cred *creds = NULL;
8392 if (unlikely(!io_assign_file(req, issue_flags)))
8395 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8396 creds = override_creds(req->creds);
8398 if (!def->audit_skip)
8399 audit_uring_entry(req->opcode);
8401 switch (req->opcode) {
8403 ret = io_nop(req, issue_flags);
8405 case IORING_OP_READV:
8406 case IORING_OP_READ_FIXED:
8407 case IORING_OP_READ:
8408 ret = io_read(req, issue_flags);
8410 case IORING_OP_WRITEV:
8411 case IORING_OP_WRITE_FIXED:
8412 case IORING_OP_WRITE:
8413 ret = io_write(req, issue_flags);
8415 case IORING_OP_FSYNC:
8416 ret = io_fsync(req, issue_flags);
8418 case IORING_OP_POLL_ADD:
8419 ret = io_poll_add(req, issue_flags);
8421 case IORING_OP_POLL_REMOVE:
8422 ret = io_poll_remove(req, issue_flags);
8424 case IORING_OP_SYNC_FILE_RANGE:
8425 ret = io_sync_file_range(req, issue_flags);
8427 case IORING_OP_SENDMSG:
8428 ret = io_sendmsg(req, issue_flags);
8430 case IORING_OP_SEND:
8431 ret = io_send(req, issue_flags);
8433 case IORING_OP_RECVMSG:
8434 ret = io_recvmsg(req, issue_flags);
8436 case IORING_OP_RECV:
8437 ret = io_recv(req, issue_flags);
8439 case IORING_OP_TIMEOUT:
8440 ret = io_timeout(req, issue_flags);
8442 case IORING_OP_TIMEOUT_REMOVE:
8443 ret = io_timeout_remove(req, issue_flags);
8445 case IORING_OP_ACCEPT:
8446 ret = io_accept(req, issue_flags);
8448 case IORING_OP_CONNECT:
8449 ret = io_connect(req, issue_flags);
8451 case IORING_OP_ASYNC_CANCEL:
8452 ret = io_async_cancel(req, issue_flags);
8454 case IORING_OP_FALLOCATE:
8455 ret = io_fallocate(req, issue_flags);
8457 case IORING_OP_OPENAT:
8458 ret = io_openat(req, issue_flags);
8460 case IORING_OP_CLOSE:
8461 ret = io_close(req, issue_flags);
8463 case IORING_OP_FILES_UPDATE:
8464 ret = io_files_update(req, issue_flags);
8466 case IORING_OP_STATX:
8467 ret = io_statx(req, issue_flags);
8469 case IORING_OP_FADVISE:
8470 ret = io_fadvise(req, issue_flags);
8472 case IORING_OP_MADVISE:
8473 ret = io_madvise(req, issue_flags);
8475 case IORING_OP_OPENAT2:
8476 ret = io_openat2(req, issue_flags);
8478 case IORING_OP_EPOLL_CTL:
8479 ret = io_epoll_ctl(req, issue_flags);
8481 case IORING_OP_SPLICE:
8482 ret = io_splice(req, issue_flags);
8484 case IORING_OP_PROVIDE_BUFFERS:
8485 ret = io_provide_buffers(req, issue_flags);
8487 case IORING_OP_REMOVE_BUFFERS:
8488 ret = io_remove_buffers(req, issue_flags);
8491 ret = io_tee(req, issue_flags);
8493 case IORING_OP_SHUTDOWN:
8494 ret = io_shutdown(req, issue_flags);
8496 case IORING_OP_RENAMEAT:
8497 ret = io_renameat(req, issue_flags);
8499 case IORING_OP_UNLINKAT:
8500 ret = io_unlinkat(req, issue_flags);
8502 case IORING_OP_MKDIRAT:
8503 ret = io_mkdirat(req, issue_flags);
8505 case IORING_OP_SYMLINKAT:
8506 ret = io_symlinkat(req, issue_flags);
8508 case IORING_OP_LINKAT:
8509 ret = io_linkat(req, issue_flags);
8511 case IORING_OP_MSG_RING:
8512 ret = io_msg_ring(req, issue_flags);
8514 case IORING_OP_FSETXATTR:
8515 ret = io_fsetxattr(req, issue_flags);
8517 case IORING_OP_SETXATTR:
8518 ret = io_setxattr(req, issue_flags);
8520 case IORING_OP_FGETXATTR:
8521 ret = io_fgetxattr(req, issue_flags);
8523 case IORING_OP_GETXATTR:
8524 ret = io_getxattr(req, issue_flags);
8526 case IORING_OP_SOCKET:
8527 ret = io_socket(req, issue_flags);
8529 case IORING_OP_URING_CMD:
8530 ret = io_uring_cmd(req, issue_flags);
8537 if (!def->audit_skip)
8538 audit_uring_exit(!ret, ret);
8541 revert_creds(creds);
8544 /* If the op doesn't have a file, we're not polling for it */
8545 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8546 io_iopoll_req_issued(req, issue_flags);
8551 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8553 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8555 req = io_put_req_find_next(req);
8556 return req ? &req->work : NULL;
8559 static void io_wq_submit_work(struct io_wq_work *work)
8561 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8562 const struct io_op_def *def = &io_op_defs[req->opcode];
8563 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8564 bool needs_poll = false;
8565 int ret = 0, err = -ECANCELED;
8567 /* one will be dropped by ->io_free_work() after returning to io-wq */
8568 if (!(req->flags & REQ_F_REFCOUNT))
8569 __io_req_set_refcount(req, 2);
8573 io_arm_ltimeout(req);
8575 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8576 if (work->flags & IO_WQ_WORK_CANCEL) {
8578 io_req_task_queue_fail(req, err);
8581 if (!io_assign_file(req, issue_flags)) {
8583 work->flags |= IO_WQ_WORK_CANCEL;
8587 if (req->flags & REQ_F_FORCE_ASYNC) {
8588 bool opcode_poll = def->pollin || def->pollout;
8590 if (opcode_poll && file_can_poll(req->file)) {
8592 issue_flags |= IO_URING_F_NONBLOCK;
8597 ret = io_issue_sqe(req, issue_flags);
8601 * We can get EAGAIN for iopolled IO even though we're
8602 * forcing a sync submission from here, since we can't
8603 * wait for request slots on the block side.
8606 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8612 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8614 /* aborted or ready, in either case retry blocking */
8616 issue_flags &= ~IO_URING_F_NONBLOCK;
8619 /* avoid locking problems by failing it from a clean context */
8621 io_req_task_queue_fail(req, ret);
8624 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8627 return &table->files[i];
8630 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8633 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8635 return (struct file *) (slot->file_ptr & FFS_MASK);
8638 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8640 unsigned long file_ptr = (unsigned long) file;
8642 file_ptr |= io_file_get_flags(file);
8643 file_slot->file_ptr = file_ptr;
8646 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8647 unsigned int issue_flags)
8649 struct io_ring_ctx *ctx = req->ctx;
8650 struct file *file = NULL;
8651 unsigned long file_ptr;
8653 io_ring_submit_lock(ctx, issue_flags);
8655 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8657 fd = array_index_nospec(fd, ctx->nr_user_files);
8658 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8659 file = (struct file *) (file_ptr & FFS_MASK);
8660 file_ptr &= ~FFS_MASK;
8661 /* mask in overlapping REQ_F and FFS bits */
8662 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8663 io_req_set_rsrc_node(req, ctx, 0);
8664 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8666 io_ring_submit_unlock(ctx, issue_flags);
8670 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8672 struct file *file = fget(fd);
8674 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8676 /* we don't allow fixed io_uring files */
8677 if (file && file->f_op == &io_uring_fops)
8678 io_req_track_inflight(req);
8682 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8684 struct io_kiocb *prev = req->timeout.prev;
8688 if (!(req->task->flags & PF_EXITING)) {
8689 struct io_cancel_data cd = {
8691 .data = prev->cqe.user_data,
8694 ret = io_try_cancel(req, &cd);
8696 io_req_complete_post(req, ret ?: -ETIME, 0);
8699 io_req_complete_post(req, -ETIME, 0);
8703 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8705 struct io_timeout_data *data = container_of(timer,
8706 struct io_timeout_data, timer);
8707 struct io_kiocb *prev, *req = data->req;
8708 struct io_ring_ctx *ctx = req->ctx;
8709 unsigned long flags;
8711 spin_lock_irqsave(&ctx->timeout_lock, flags);
8712 prev = req->timeout.head;
8713 req->timeout.head = NULL;
8716 * We don't expect the list to be empty, that will only happen if we
8717 * race with the completion of the linked work.
8720 io_remove_next_linked(prev);
8721 if (!req_ref_inc_not_zero(prev))
8724 list_del(&req->timeout.list);
8725 req->timeout.prev = prev;
8726 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8728 req->io_task_work.func = io_req_task_link_timeout;
8729 io_req_task_work_add(req);
8730 return HRTIMER_NORESTART;
8733 static void io_queue_linked_timeout(struct io_kiocb *req)
8735 struct io_ring_ctx *ctx = req->ctx;
8737 spin_lock_irq(&ctx->timeout_lock);
8739 * If the back reference is NULL, then our linked request finished
8740 * before we got a chance to setup the timer
8742 if (req->timeout.head) {
8743 struct io_timeout_data *data = req->async_data;
8745 data->timer.function = io_link_timeout_fn;
8746 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8748 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8750 spin_unlock_irq(&ctx->timeout_lock);
8751 /* drop submission reference */
8755 static void io_queue_async(struct io_kiocb *req, int ret)
8756 __must_hold(&req->ctx->uring_lock)
8758 struct io_kiocb *linked_timeout;
8760 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8761 io_req_complete_failed(req, ret);
8765 linked_timeout = io_prep_linked_timeout(req);
8767 switch (io_arm_poll_handler(req, 0)) {
8768 case IO_APOLL_READY:
8769 io_req_task_queue(req);
8771 case IO_APOLL_ABORTED:
8773 * Queued up for async execution, worker will release
8774 * submit reference when the iocb is actually submitted.
8776 io_queue_iowq(req, NULL);
8783 io_queue_linked_timeout(linked_timeout);
8786 static inline void io_queue_sqe(struct io_kiocb *req)
8787 __must_hold(&req->ctx->uring_lock)
8791 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8793 if (req->flags & REQ_F_COMPLETE_INLINE) {
8794 io_req_add_compl_list(req);
8798 * We async punt it if the file wasn't marked NOWAIT, or if the file
8799 * doesn't support non-blocking read/write attempts
8802 io_arm_ltimeout(req);
8804 io_queue_async(req, ret);
8807 static void io_queue_sqe_fallback(struct io_kiocb *req)
8808 __must_hold(&req->ctx->uring_lock)
8810 if (unlikely(req->flags & REQ_F_FAIL)) {
8812 * We don't submit, fail them all, for that replace hardlinks
8813 * with normal links. Extra REQ_F_LINK is tolerated.
8815 req->flags &= ~REQ_F_HARDLINK;
8816 req->flags |= REQ_F_LINK;
8817 io_req_complete_failed(req, req->cqe.res);
8818 } else if (unlikely(req->ctx->drain_active)) {
8821 int ret = io_req_prep_async(req);
8824 io_req_complete_failed(req, ret);
8826 io_queue_iowq(req, NULL);
8831 * Check SQE restrictions (opcode and flags).
8833 * Returns 'true' if SQE is allowed, 'false' otherwise.
8835 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8836 struct io_kiocb *req,
8837 unsigned int sqe_flags)
8839 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8842 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8843 ctx->restrictions.sqe_flags_required)
8846 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8847 ctx->restrictions.sqe_flags_required))
8853 static void io_init_req_drain(struct io_kiocb *req)
8855 struct io_ring_ctx *ctx = req->ctx;
8856 struct io_kiocb *head = ctx->submit_state.link.head;
8858 ctx->drain_active = true;
8861 * If we need to drain a request in the middle of a link, drain
8862 * the head request and the next request/link after the current
8863 * link. Considering sequential execution of links,
8864 * REQ_F_IO_DRAIN will be maintained for every request of our
8867 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8868 ctx->drain_next = true;
8872 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8873 const struct io_uring_sqe *sqe)
8874 __must_hold(&ctx->uring_lock)
8876 const struct io_op_def *def;
8877 unsigned int sqe_flags;
8881 /* req is partially pre-initialised, see io_preinit_req() */
8882 req->opcode = opcode = READ_ONCE(sqe->opcode);
8883 /* same numerical values with corresponding REQ_F_*, safe to copy */
8884 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8885 req->cqe.user_data = READ_ONCE(sqe->user_data);
8887 req->rsrc_node = NULL;
8888 req->task = current;
8890 if (unlikely(opcode >= IORING_OP_LAST)) {
8894 def = &io_op_defs[opcode];
8895 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8896 /* enforce forwards compatibility on users */
8897 if (sqe_flags & ~SQE_VALID_FLAGS)
8899 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8900 if (!def->buffer_select)
8902 req->buf_index = READ_ONCE(sqe->buf_group);
8904 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8905 ctx->drain_disabled = true;
8906 if (sqe_flags & IOSQE_IO_DRAIN) {
8907 if (ctx->drain_disabled)
8909 io_init_req_drain(req);
8912 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8913 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8915 /* knock it to the slow queue path, will be drained there */
8916 if (ctx->drain_active)
8917 req->flags |= REQ_F_FORCE_ASYNC;
8918 /* if there is no link, we're at "next" request and need to drain */
8919 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8920 ctx->drain_next = false;
8921 ctx->drain_active = true;
8922 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8926 if (!def->ioprio && sqe->ioprio)
8928 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8931 if (def->needs_file) {
8932 struct io_submit_state *state = &ctx->submit_state;
8934 req->cqe.fd = READ_ONCE(sqe->fd);
8937 * Plug now if we have more than 2 IO left after this, and the
8938 * target is potentially a read/write to block based storage.
8940 if (state->need_plug && def->plug) {
8941 state->plug_started = true;
8942 state->need_plug = false;
8943 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8947 personality = READ_ONCE(sqe->personality);
8951 req->creds = xa_load(&ctx->personalities, personality);
8954 get_cred(req->creds);
8955 ret = security_uring_override_creds(req->creds);
8957 put_cred(req->creds);
8960 req->flags |= REQ_F_CREDS;
8963 return io_req_prep(req, sqe);
8966 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8967 struct io_kiocb *req, int ret)
8969 struct io_ring_ctx *ctx = req->ctx;
8970 struct io_submit_link *link = &ctx->submit_state.link;
8971 struct io_kiocb *head = link->head;
8973 trace_io_uring_req_failed(sqe, ctx, req, ret);
8976 * Avoid breaking links in the middle as it renders links with SQPOLL
8977 * unusable. Instead of failing eagerly, continue assembling the link if
8978 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8979 * should find the flag and handle the rest.
8981 req_fail_link_node(req, ret);
8982 if (head && !(head->flags & REQ_F_FAIL))
8983 req_fail_link_node(head, -ECANCELED);
8985 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8987 link->last->link = req;
8991 io_queue_sqe_fallback(req);
8996 link->last->link = req;
9003 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
9004 const struct io_uring_sqe *sqe)
9005 __must_hold(&ctx->uring_lock)
9007 struct io_submit_link *link = &ctx->submit_state.link;
9010 ret = io_init_req(ctx, req, sqe);
9012 return io_submit_fail_init(sqe, req, ret);
9014 /* don't need @sqe from now on */
9015 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
9017 ctx->flags & IORING_SETUP_SQPOLL);
9020 * If we already have a head request, queue this one for async
9021 * submittal once the head completes. If we don't have a head but
9022 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
9023 * submitted sync once the chain is complete. If none of those
9024 * conditions are true (normal request), then just queue it.
9026 if (unlikely(link->head)) {
9027 ret = io_req_prep_async(req);
9029 return io_submit_fail_init(sqe, req, ret);
9031 trace_io_uring_link(ctx, req, link->head);
9032 link->last->link = req;
9035 if (req->flags & IO_REQ_LINK_FLAGS)
9037 /* last request of the link, flush it */
9040 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
9043 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
9044 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
9045 if (req->flags & IO_REQ_LINK_FLAGS) {
9050 io_queue_sqe_fallback(req);
9060 * Batched submission is done, ensure local IO is flushed out.
9062 static void io_submit_state_end(struct io_ring_ctx *ctx)
9064 struct io_submit_state *state = &ctx->submit_state;
9066 if (unlikely(state->link.head))
9067 io_queue_sqe_fallback(state->link.head);
9068 /* flush only after queuing links as they can generate completions */
9069 io_submit_flush_completions(ctx);
9070 if (state->plug_started)
9071 blk_finish_plug(&state->plug);
9075 * Start submission side cache.
9077 static void io_submit_state_start(struct io_submit_state *state,
9078 unsigned int max_ios)
9080 state->plug_started = false;
9081 state->need_plug = max_ios > 2;
9082 state->submit_nr = max_ios;
9083 /* set only head, no need to init link_last in advance */
9084 state->link.head = NULL;
9087 static void io_commit_sqring(struct io_ring_ctx *ctx)
9089 struct io_rings *rings = ctx->rings;
9092 * Ensure any loads from the SQEs are done at this point,
9093 * since once we write the new head, the application could
9094 * write new data to them.
9096 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
9100 * Fetch an sqe, if one is available. Note this returns a pointer to memory
9101 * that is mapped by userspace. This means that care needs to be taken to
9102 * ensure that reads are stable, as we cannot rely on userspace always
9103 * being a good citizen. If members of the sqe are validated and then later
9104 * used, it's important that those reads are done through READ_ONCE() to
9105 * prevent a re-load down the line.
9107 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
9109 unsigned head, mask = ctx->sq_entries - 1;
9110 unsigned sq_idx = ctx->cached_sq_head++ & mask;
9113 * The cached sq head (or cq tail) serves two purposes:
9115 * 1) allows us to batch the cost of updating the user visible
9117 * 2) allows the kernel side to track the head on its own, even
9118 * though the application is the one updating it.
9120 head = READ_ONCE(ctx->sq_array[sq_idx]);
9121 if (likely(head < ctx->sq_entries)) {
9122 /* double index for 128-byte SQEs, twice as long */
9123 if (ctx->flags & IORING_SETUP_SQE128)
9125 return &ctx->sq_sqes[head];
9128 /* drop invalid entries */
9130 WRITE_ONCE(ctx->rings->sq_dropped,
9131 READ_ONCE(ctx->rings->sq_dropped) + 1);
9135 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
9136 __must_hold(&ctx->uring_lock)
9138 unsigned int entries = io_sqring_entries(ctx);
9142 if (unlikely(!entries))
9144 /* make sure SQ entry isn't read before tail */
9145 ret = left = min3(nr, ctx->sq_entries, entries);
9146 io_get_task_refs(left);
9147 io_submit_state_start(&ctx->submit_state, left);
9150 const struct io_uring_sqe *sqe;
9151 struct io_kiocb *req;
9153 if (unlikely(!io_alloc_req_refill(ctx)))
9155 req = io_alloc_req(ctx);
9156 sqe = io_get_sqe(ctx);
9157 if (unlikely(!sqe)) {
9158 io_req_add_to_cache(req, ctx);
9163 * Continue submitting even for sqe failure if the
9164 * ring was setup with IORING_SETUP_SUBMIT_ALL
9166 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
9167 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
9173 if (unlikely(left)) {
9175 /* try again if it submitted nothing and can't allocate a req */
9176 if (!ret && io_req_cache_empty(ctx))
9178 current->io_uring->cached_refs += left;
9181 io_submit_state_end(ctx);
9182 /* Commit SQ ring head once we've consumed and submitted all SQEs */
9183 io_commit_sqring(ctx);
9187 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
9189 return READ_ONCE(sqd->state);
9192 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
9194 unsigned int to_submit;
9197 to_submit = io_sqring_entries(ctx);
9198 /* if we're handling multiple rings, cap submit size for fairness */
9199 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
9200 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
9202 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
9203 const struct cred *creds = NULL;
9205 if (ctx->sq_creds != current_cred())
9206 creds = override_creds(ctx->sq_creds);
9208 mutex_lock(&ctx->uring_lock);
9209 if (!wq_list_empty(&ctx->iopoll_list))
9210 io_do_iopoll(ctx, true);
9213 * Don't submit if refs are dying, good for io_uring_register(),
9214 * but also it is relied upon by io_ring_exit_work()
9216 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
9217 !(ctx->flags & IORING_SETUP_R_DISABLED))
9218 ret = io_submit_sqes(ctx, to_submit);
9219 mutex_unlock(&ctx->uring_lock);
9221 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
9222 wake_up(&ctx->sqo_sq_wait);
9224 revert_creds(creds);
9230 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
9232 struct io_ring_ctx *ctx;
9233 unsigned sq_thread_idle = 0;
9235 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9236 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
9237 sqd->sq_thread_idle = sq_thread_idle;
9240 static bool io_sqd_handle_event(struct io_sq_data *sqd)
9242 bool did_sig = false;
9243 struct ksignal ksig;
9245 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
9246 signal_pending(current)) {
9247 mutex_unlock(&sqd->lock);
9248 if (signal_pending(current))
9249 did_sig = get_signal(&ksig);
9251 mutex_lock(&sqd->lock);
9253 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9256 static int io_sq_thread(void *data)
9258 struct io_sq_data *sqd = data;
9259 struct io_ring_ctx *ctx;
9260 unsigned long timeout = 0;
9261 char buf[TASK_COMM_LEN];
9264 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
9265 set_task_comm(current, buf);
9267 if (sqd->sq_cpu != -1)
9268 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
9270 set_cpus_allowed_ptr(current, cpu_online_mask);
9271 current->flags |= PF_NO_SETAFFINITY;
9273 audit_alloc_kernel(current);
9275 mutex_lock(&sqd->lock);
9277 bool cap_entries, sqt_spin = false;
9279 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
9280 if (io_sqd_handle_event(sqd))
9282 timeout = jiffies + sqd->sq_thread_idle;
9285 cap_entries = !list_is_singular(&sqd->ctx_list);
9286 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9287 int ret = __io_sq_thread(ctx, cap_entries);
9289 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
9292 if (io_run_task_work())
9295 if (sqt_spin || !time_after(jiffies, timeout)) {
9298 timeout = jiffies + sqd->sq_thread_idle;
9302 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
9303 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
9304 bool needs_sched = true;
9306 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
9307 atomic_or(IORING_SQ_NEED_WAKEUP,
9308 &ctx->rings->sq_flags);
9309 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
9310 !wq_list_empty(&ctx->iopoll_list)) {
9311 needs_sched = false;
9316 * Ensure the store of the wakeup flag is not
9317 * reordered with the load of the SQ tail
9319 smp_mb__after_atomic();
9321 if (io_sqring_entries(ctx)) {
9322 needs_sched = false;
9328 mutex_unlock(&sqd->lock);
9330 mutex_lock(&sqd->lock);
9332 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9333 atomic_andnot(IORING_SQ_NEED_WAKEUP,
9334 &ctx->rings->sq_flags);
9337 finish_wait(&sqd->wait, &wait);
9338 timeout = jiffies + sqd->sq_thread_idle;
9341 io_uring_cancel_generic(true, sqd);
9343 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9344 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9346 mutex_unlock(&sqd->lock);
9348 audit_free(current);
9350 complete(&sqd->exited);
9354 struct io_wait_queue {
9355 struct wait_queue_entry wq;
9356 struct io_ring_ctx *ctx;
9358 unsigned nr_timeouts;
9361 static inline bool io_should_wake(struct io_wait_queue *iowq)
9363 struct io_ring_ctx *ctx = iowq->ctx;
9364 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9367 * Wake up if we have enough events, or if a timeout occurred since we
9368 * started waiting. For timeouts, we always want to return to userspace,
9369 * regardless of event count.
9371 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9374 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9375 int wake_flags, void *key)
9377 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9381 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9382 * the task, and the next invocation will do it.
9384 if (io_should_wake(iowq) ||
9385 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9386 return autoremove_wake_function(curr, mode, wake_flags, key);
9390 static int io_run_task_work_sig(void)
9392 if (io_run_task_work())
9394 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9395 return -ERESTARTSYS;
9396 if (task_sigpending(current))
9401 /* when returns >0, the caller should retry */
9402 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9403 struct io_wait_queue *iowq,
9407 unsigned long check_cq;
9409 /* make sure we run task_work before checking for signals */
9410 ret = io_run_task_work_sig();
9411 if (ret || io_should_wake(iowq))
9413 check_cq = READ_ONCE(ctx->check_cq);
9414 /* let the caller flush overflows, retry */
9415 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9417 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9419 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9425 * Wait until events become available, if we don't already have some. The
9426 * application must reap them itself, as they reside on the shared cq ring.
9428 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9429 const sigset_t __user *sig, size_t sigsz,
9430 struct __kernel_timespec __user *uts)
9432 struct io_wait_queue iowq;
9433 struct io_rings *rings = ctx->rings;
9434 ktime_t timeout = KTIME_MAX;
9438 io_cqring_overflow_flush(ctx);
9439 if (io_cqring_events(ctx) >= min_events)
9441 if (!io_run_task_work())
9446 #ifdef CONFIG_COMPAT
9447 if (in_compat_syscall())
9448 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9452 ret = set_user_sigmask(sig, sigsz);
9459 struct timespec64 ts;
9461 if (get_timespec64(&ts, uts))
9463 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9466 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9467 iowq.wq.private = current;
9468 INIT_LIST_HEAD(&iowq.wq.entry);
9470 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9471 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9473 trace_io_uring_cqring_wait(ctx, min_events);
9475 /* if we can't even flush overflow, don't wait for more */
9476 if (!io_cqring_overflow_flush(ctx)) {
9480 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9481 TASK_INTERRUPTIBLE);
9482 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9486 finish_wait(&ctx->cq_wait, &iowq.wq);
9487 restore_saved_sigmask_unless(ret == -EINTR);
9489 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9492 static void io_free_page_table(void **table, size_t size)
9494 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9496 for (i = 0; i < nr_tables; i++)
9501 static __cold void **io_alloc_page_table(size_t size)
9503 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9504 size_t init_size = size;
9507 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9511 for (i = 0; i < nr_tables; i++) {
9512 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9514 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9516 io_free_page_table(table, init_size);
9524 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9526 percpu_ref_exit(&ref_node->refs);
9530 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9532 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9533 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9534 unsigned long flags;
9535 bool first_add = false;
9536 unsigned long delay = HZ;
9538 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9541 /* if we are mid-quiesce then do not delay */
9542 if (node->rsrc_data->quiesce)
9545 while (!list_empty(&ctx->rsrc_ref_list)) {
9546 node = list_first_entry(&ctx->rsrc_ref_list,
9547 struct io_rsrc_node, node);
9548 /* recycle ref nodes in order */
9551 list_del(&node->node);
9552 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9554 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9557 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9560 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9562 struct io_rsrc_node *ref_node;
9564 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9568 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9573 INIT_LIST_HEAD(&ref_node->node);
9574 INIT_LIST_HEAD(&ref_node->rsrc_list);
9575 ref_node->done = false;
9579 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9580 struct io_rsrc_data *data_to_kill)
9581 __must_hold(&ctx->uring_lock)
9583 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9584 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9586 io_rsrc_refs_drop(ctx);
9589 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9591 rsrc_node->rsrc_data = data_to_kill;
9592 spin_lock_irq(&ctx->rsrc_ref_lock);
9593 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9594 spin_unlock_irq(&ctx->rsrc_ref_lock);
9596 atomic_inc(&data_to_kill->refs);
9597 percpu_ref_kill(&rsrc_node->refs);
9598 ctx->rsrc_node = NULL;
9601 if (!ctx->rsrc_node) {
9602 ctx->rsrc_node = ctx->rsrc_backup_node;
9603 ctx->rsrc_backup_node = NULL;
9607 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9609 if (ctx->rsrc_backup_node)
9611 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9612 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9615 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9616 struct io_ring_ctx *ctx)
9620 /* As we may drop ->uring_lock, other task may have started quiesce */
9624 data->quiesce = true;
9626 ret = io_rsrc_node_switch_start(ctx);
9629 io_rsrc_node_switch(ctx, data);
9631 /* kill initial ref, already quiesced if zero */
9632 if (atomic_dec_and_test(&data->refs))
9634 mutex_unlock(&ctx->uring_lock);
9635 flush_delayed_work(&ctx->rsrc_put_work);
9636 ret = wait_for_completion_interruptible(&data->done);
9638 mutex_lock(&ctx->uring_lock);
9639 if (atomic_read(&data->refs) > 0) {
9641 * it has been revived by another thread while
9644 mutex_unlock(&ctx->uring_lock);
9650 atomic_inc(&data->refs);
9651 /* wait for all works potentially completing data->done */
9652 flush_delayed_work(&ctx->rsrc_put_work);
9653 reinit_completion(&data->done);
9655 ret = io_run_task_work_sig();
9656 mutex_lock(&ctx->uring_lock);
9658 data->quiesce = false;
9663 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9665 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9666 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9668 return &data->tags[table_idx][off];
9671 static void io_rsrc_data_free(struct io_rsrc_data *data)
9673 size_t size = data->nr * sizeof(data->tags[0][0]);
9676 io_free_page_table((void **)data->tags, size);
9680 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9681 u64 __user *utags, unsigned nr,
9682 struct io_rsrc_data **pdata)
9684 struct io_rsrc_data *data;
9688 data = kzalloc(sizeof(*data), GFP_KERNEL);
9691 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9699 data->do_put = do_put;
9702 for (i = 0; i < nr; i++) {
9703 u64 *tag_slot = io_get_tag_slot(data, i);
9705 if (copy_from_user(tag_slot, &utags[i],
9711 atomic_set(&data->refs, 1);
9712 init_completion(&data->done);
9716 io_rsrc_data_free(data);
9720 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9722 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9723 GFP_KERNEL_ACCOUNT);
9724 if (unlikely(!table->files))
9727 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9728 if (unlikely(!table->bitmap)) {
9729 kvfree(table->files);
9736 static void io_free_file_tables(struct io_file_table *table)
9738 kvfree(table->files);
9739 bitmap_free(table->bitmap);
9740 table->files = NULL;
9741 table->bitmap = NULL;
9744 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9746 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9747 __set_bit(bit, table->bitmap);
9748 table->alloc_hint = bit + 1;
9751 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9753 __clear_bit(bit, table->bitmap);
9754 table->alloc_hint = bit;
9757 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9759 #if !defined(IO_URING_SCM_ALL)
9762 for (i = 0; i < ctx->nr_user_files; i++) {
9763 struct file *file = io_file_from_index(ctx, i);
9767 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9769 io_file_bitmap_clear(&ctx->file_table, i);
9774 #if defined(CONFIG_UNIX)
9775 if (ctx->ring_sock) {
9776 struct sock *sock = ctx->ring_sock->sk;
9777 struct sk_buff *skb;
9779 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9783 io_free_file_tables(&ctx->file_table);
9784 io_rsrc_data_free(ctx->file_data);
9785 ctx->file_data = NULL;
9786 ctx->nr_user_files = 0;
9789 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9793 if (!ctx->file_data)
9795 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9797 __io_sqe_files_unregister(ctx);
9801 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9802 __releases(&sqd->lock)
9804 WARN_ON_ONCE(sqd->thread == current);
9807 * Do the dance but not conditional clear_bit() because it'd race with
9808 * other threads incrementing park_pending and setting the bit.
9810 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9811 if (atomic_dec_return(&sqd->park_pending))
9812 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9813 mutex_unlock(&sqd->lock);
9816 static void io_sq_thread_park(struct io_sq_data *sqd)
9817 __acquires(&sqd->lock)
9819 WARN_ON_ONCE(sqd->thread == current);
9821 atomic_inc(&sqd->park_pending);
9822 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9823 mutex_lock(&sqd->lock);
9825 wake_up_process(sqd->thread);
9828 static void io_sq_thread_stop(struct io_sq_data *sqd)
9830 WARN_ON_ONCE(sqd->thread == current);
9831 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9833 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9834 mutex_lock(&sqd->lock);
9836 wake_up_process(sqd->thread);
9837 mutex_unlock(&sqd->lock);
9838 wait_for_completion(&sqd->exited);
9841 static void io_put_sq_data(struct io_sq_data *sqd)
9843 if (refcount_dec_and_test(&sqd->refs)) {
9844 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9846 io_sq_thread_stop(sqd);
9851 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9853 struct io_sq_data *sqd = ctx->sq_data;
9856 io_sq_thread_park(sqd);
9857 list_del_init(&ctx->sqd_list);
9858 io_sqd_update_thread_idle(sqd);
9859 io_sq_thread_unpark(sqd);
9861 io_put_sq_data(sqd);
9862 ctx->sq_data = NULL;
9866 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9868 struct io_ring_ctx *ctx_attach;
9869 struct io_sq_data *sqd;
9872 f = fdget(p->wq_fd);
9874 return ERR_PTR(-ENXIO);
9875 if (f.file->f_op != &io_uring_fops) {
9877 return ERR_PTR(-EINVAL);
9880 ctx_attach = f.file->private_data;
9881 sqd = ctx_attach->sq_data;
9884 return ERR_PTR(-EINVAL);
9886 if (sqd->task_tgid != current->tgid) {
9888 return ERR_PTR(-EPERM);
9891 refcount_inc(&sqd->refs);
9896 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9899 struct io_sq_data *sqd;
9902 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9903 sqd = io_attach_sq_data(p);
9908 /* fall through for EPERM case, setup new sqd/task */
9909 if (PTR_ERR(sqd) != -EPERM)
9913 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9915 return ERR_PTR(-ENOMEM);
9917 atomic_set(&sqd->park_pending, 0);
9918 refcount_set(&sqd->refs, 1);
9919 INIT_LIST_HEAD(&sqd->ctx_list);
9920 mutex_init(&sqd->lock);
9921 init_waitqueue_head(&sqd->wait);
9922 init_completion(&sqd->exited);
9927 * Ensure the UNIX gc is aware of our file set, so we are certain that
9928 * the io_uring can be safely unregistered on process exit, even if we have
9929 * loops in the file referencing. We account only files that can hold other
9930 * files because otherwise they can't form a loop and so are not interesting
9933 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9935 #if defined(CONFIG_UNIX)
9936 struct sock *sk = ctx->ring_sock->sk;
9937 struct sk_buff_head *head = &sk->sk_receive_queue;
9938 struct scm_fp_list *fpl;
9939 struct sk_buff *skb;
9941 if (likely(!io_file_need_scm(file)))
9945 * See if we can merge this file into an existing skb SCM_RIGHTS
9946 * file set. If there's no room, fall back to allocating a new skb
9947 * and filling it in.
9949 spin_lock_irq(&head->lock);
9950 skb = skb_peek(head);
9951 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9952 __skb_unlink(skb, head);
9955 spin_unlock_irq(&head->lock);
9958 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9962 skb = alloc_skb(0, GFP_KERNEL);
9968 fpl->user = get_uid(current_user());
9969 fpl->max = SCM_MAX_FD;
9972 UNIXCB(skb).fp = fpl;
9974 skb->destructor = unix_destruct_scm;
9975 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9978 fpl = UNIXCB(skb).fp;
9979 fpl->fp[fpl->count++] = get_file(file);
9980 unix_inflight(fpl->user, file);
9981 skb_queue_head(head, skb);
9987 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9989 struct file *file = prsrc->file;
9990 #if defined(CONFIG_UNIX)
9991 struct sock *sock = ctx->ring_sock->sk;
9992 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9993 struct sk_buff *skb;
9996 if (!io_file_need_scm(file)) {
10001 __skb_queue_head_init(&list);
10004 * Find the skb that holds this file in its SCM_RIGHTS. When found,
10005 * remove this entry and rearrange the file array.
10007 skb = skb_dequeue(head);
10009 struct scm_fp_list *fp;
10011 fp = UNIXCB(skb).fp;
10012 for (i = 0; i < fp->count; i++) {
10015 if (fp->fp[i] != file)
10018 unix_notinflight(fp->user, fp->fp[i]);
10019 left = fp->count - 1 - i;
10021 memmove(&fp->fp[i], &fp->fp[i + 1],
10022 left * sizeof(struct file *));
10029 __skb_queue_tail(&list, skb);
10039 __skb_queue_tail(&list, skb);
10041 skb = skb_dequeue(head);
10044 if (skb_peek(&list)) {
10045 spin_lock_irq(&head->lock);
10046 while ((skb = __skb_dequeue(&list)) != NULL)
10047 __skb_queue_tail(head, skb);
10048 spin_unlock_irq(&head->lock);
10055 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
10057 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
10058 struct io_ring_ctx *ctx = rsrc_data->ctx;
10059 struct io_rsrc_put *prsrc, *tmp;
10061 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
10062 list_del(&prsrc->list);
10065 if (ctx->flags & IORING_SETUP_IOPOLL)
10066 mutex_lock(&ctx->uring_lock);
10068 spin_lock(&ctx->completion_lock);
10069 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
10070 io_commit_cqring(ctx);
10071 spin_unlock(&ctx->completion_lock);
10072 io_cqring_ev_posted(ctx);
10074 if (ctx->flags & IORING_SETUP_IOPOLL)
10075 mutex_unlock(&ctx->uring_lock);
10078 rsrc_data->do_put(ctx, prsrc);
10082 io_rsrc_node_destroy(ref_node);
10083 if (atomic_dec_and_test(&rsrc_data->refs))
10084 complete(&rsrc_data->done);
10087 static void io_rsrc_put_work(struct work_struct *work)
10089 struct io_ring_ctx *ctx;
10090 struct llist_node *node;
10092 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
10093 node = llist_del_all(&ctx->rsrc_put_llist);
10096 struct io_rsrc_node *ref_node;
10097 struct llist_node *next = node->next;
10099 ref_node = llist_entry(node, struct io_rsrc_node, llist);
10100 __io_rsrc_put_work(ref_node);
10105 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
10106 unsigned nr_args, u64 __user *tags)
10108 __s32 __user *fds = (__s32 __user *) arg;
10113 if (ctx->file_data)
10117 if (nr_args > IORING_MAX_FIXED_FILES)
10119 if (nr_args > rlimit(RLIMIT_NOFILE))
10121 ret = io_rsrc_node_switch_start(ctx);
10124 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
10129 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
10130 io_rsrc_data_free(ctx->file_data);
10131 ctx->file_data = NULL;
10135 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
10136 struct io_fixed_file *file_slot;
10138 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
10142 /* allow sparse sets */
10143 if (!fds || fd == -1) {
10145 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
10152 if (unlikely(!file))
10156 * Don't allow io_uring instances to be registered. If UNIX
10157 * isn't enabled, then this causes a reference cycle and this
10158 * instance can never get freed. If UNIX is enabled we'll
10159 * handle it just fine, but there's still no point in allowing
10160 * a ring fd as it doesn't support regular read/write anyway.
10162 if (file->f_op == &io_uring_fops) {
10166 ret = io_scm_file_account(ctx, file);
10171 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10172 io_fixed_file_set(file_slot, file);
10173 io_file_bitmap_set(&ctx->file_table, i);
10176 io_rsrc_node_switch(ctx, NULL);
10179 __io_sqe_files_unregister(ctx);
10183 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
10184 struct io_rsrc_node *node, void *rsrc)
10186 u64 *tag_slot = io_get_tag_slot(data, idx);
10187 struct io_rsrc_put *prsrc;
10189 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
10193 prsrc->tag = *tag_slot;
10195 prsrc->rsrc = rsrc;
10196 list_add(&prsrc->list, &node->rsrc_list);
10200 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
10201 unsigned int issue_flags, u32 slot_index)
10202 __must_hold(&req->ctx->uring_lock)
10204 struct io_ring_ctx *ctx = req->ctx;
10205 bool needs_switch = false;
10206 struct io_fixed_file *file_slot;
10209 if (file->f_op == &io_uring_fops)
10211 if (!ctx->file_data)
10213 if (slot_index >= ctx->nr_user_files)
10216 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
10217 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
10219 if (file_slot->file_ptr) {
10220 struct file *old_file;
10222 ret = io_rsrc_node_switch_start(ctx);
10226 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10227 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
10228 ctx->rsrc_node, old_file);
10231 file_slot->file_ptr = 0;
10232 io_file_bitmap_clear(&ctx->file_table, slot_index);
10233 needs_switch = true;
10236 ret = io_scm_file_account(ctx, file);
10238 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
10239 io_fixed_file_set(file_slot, file);
10240 io_file_bitmap_set(&ctx->file_table, slot_index);
10244 io_rsrc_node_switch(ctx, ctx->file_data);
10250 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
10251 unsigned int offset)
10253 struct io_ring_ctx *ctx = req->ctx;
10254 struct io_fixed_file *file_slot;
10258 io_ring_submit_lock(ctx, issue_flags);
10260 if (unlikely(!ctx->file_data))
10263 if (offset >= ctx->nr_user_files)
10265 ret = io_rsrc_node_switch_start(ctx);
10269 offset = array_index_nospec(offset, ctx->nr_user_files);
10270 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
10272 if (!file_slot->file_ptr)
10275 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10276 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
10280 file_slot->file_ptr = 0;
10281 io_file_bitmap_clear(&ctx->file_table, offset);
10282 io_rsrc_node_switch(ctx, ctx->file_data);
10285 io_ring_submit_unlock(ctx, issue_flags);
10289 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
10291 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
10294 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
10295 struct io_uring_rsrc_update2 *up,
10298 u64 __user *tags = u64_to_user_ptr(up->tags);
10299 __s32 __user *fds = u64_to_user_ptr(up->data);
10300 struct io_rsrc_data *data = ctx->file_data;
10301 struct io_fixed_file *file_slot;
10303 int fd, i, err = 0;
10305 bool needs_switch = false;
10307 if (!ctx->file_data)
10309 if (up->offset + nr_args > ctx->nr_user_files)
10312 for (done = 0; done < nr_args; done++) {
10315 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
10316 copy_from_user(&fd, &fds[done], sizeof(fd))) {
10320 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
10324 if (fd == IORING_REGISTER_FILES_SKIP)
10327 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
10328 file_slot = io_fixed_file_slot(&ctx->file_table, i);
10330 if (file_slot->file_ptr) {
10331 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
10332 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
10335 file_slot->file_ptr = 0;
10336 io_file_bitmap_clear(&ctx->file_table, i);
10337 needs_switch = true;
10346 * Don't allow io_uring instances to be registered. If
10347 * UNIX isn't enabled, then this causes a reference
10348 * cycle and this instance can never get freed. If UNIX
10349 * is enabled we'll handle it just fine, but there's
10350 * still no point in allowing a ring fd as it doesn't
10351 * support regular read/write anyway.
10353 if (file->f_op == &io_uring_fops) {
10358 err = io_scm_file_account(ctx, file);
10363 *io_get_tag_slot(data, i) = tag;
10364 io_fixed_file_set(file_slot, file);
10365 io_file_bitmap_set(&ctx->file_table, i);
10370 io_rsrc_node_switch(ctx, data);
10371 return done ? done : err;
10374 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
10375 struct task_struct *task)
10377 struct io_wq_hash *hash;
10378 struct io_wq_data data;
10379 unsigned int concurrency;
10381 mutex_lock(&ctx->uring_lock);
10382 hash = ctx->hash_map;
10384 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10386 mutex_unlock(&ctx->uring_lock);
10387 return ERR_PTR(-ENOMEM);
10389 refcount_set(&hash->refs, 1);
10390 init_waitqueue_head(&hash->wait);
10391 ctx->hash_map = hash;
10393 mutex_unlock(&ctx->uring_lock);
10397 data.free_work = io_wq_free_work;
10398 data.do_work = io_wq_submit_work;
10400 /* Do QD, or 4 * CPUS, whatever is smallest */
10401 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10403 return io_wq_create(concurrency, &data);
10406 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10407 struct io_ring_ctx *ctx)
10409 struct io_uring_task *tctx;
10412 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10413 if (unlikely(!tctx))
10416 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10417 sizeof(struct file *), GFP_KERNEL);
10418 if (unlikely(!tctx->registered_rings)) {
10423 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10424 if (unlikely(ret)) {
10425 kfree(tctx->registered_rings);
10430 tctx->io_wq = io_init_wq_offload(ctx, task);
10431 if (IS_ERR(tctx->io_wq)) {
10432 ret = PTR_ERR(tctx->io_wq);
10433 percpu_counter_destroy(&tctx->inflight);
10434 kfree(tctx->registered_rings);
10439 xa_init(&tctx->xa);
10440 init_waitqueue_head(&tctx->wait);
10441 atomic_set(&tctx->in_idle, 0);
10442 atomic_set(&tctx->inflight_tracked, 0);
10443 task->io_uring = tctx;
10444 spin_lock_init(&tctx->task_lock);
10445 INIT_WQ_LIST(&tctx->task_list);
10446 INIT_WQ_LIST(&tctx->prio_task_list);
10447 init_task_work(&tctx->task_work, tctx_task_work);
10451 void __io_uring_free(struct task_struct *tsk)
10453 struct io_uring_task *tctx = tsk->io_uring;
10455 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10456 WARN_ON_ONCE(tctx->io_wq);
10457 WARN_ON_ONCE(tctx->cached_refs);
10459 kfree(tctx->registered_rings);
10460 percpu_counter_destroy(&tctx->inflight);
10462 tsk->io_uring = NULL;
10465 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10466 struct io_uring_params *p)
10470 /* Retain compatibility with failing for an invalid attach attempt */
10471 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10472 IORING_SETUP_ATTACH_WQ) {
10475 f = fdget(p->wq_fd);
10478 if (f.file->f_op != &io_uring_fops) {
10484 if (ctx->flags & IORING_SETUP_SQPOLL) {
10485 struct task_struct *tsk;
10486 struct io_sq_data *sqd;
10489 ret = security_uring_sqpoll();
10493 sqd = io_get_sq_data(p, &attached);
10495 ret = PTR_ERR(sqd);
10499 ctx->sq_creds = get_current_cred();
10500 ctx->sq_data = sqd;
10501 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10502 if (!ctx->sq_thread_idle)
10503 ctx->sq_thread_idle = HZ;
10505 io_sq_thread_park(sqd);
10506 list_add(&ctx->sqd_list, &sqd->ctx_list);
10507 io_sqd_update_thread_idle(sqd);
10508 /* don't attach to a dying SQPOLL thread, would be racy */
10509 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10510 io_sq_thread_unpark(sqd);
10517 if (p->flags & IORING_SETUP_SQ_AFF) {
10518 int cpu = p->sq_thread_cpu;
10521 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10528 sqd->task_pid = current->pid;
10529 sqd->task_tgid = current->tgid;
10530 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10532 ret = PTR_ERR(tsk);
10537 ret = io_uring_alloc_task_context(tsk, ctx);
10538 wake_up_new_task(tsk);
10541 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10542 /* Can't have SQ_AFF without SQPOLL */
10549 complete(&ctx->sq_data->exited);
10551 io_sq_thread_finish(ctx);
10555 static inline void __io_unaccount_mem(struct user_struct *user,
10556 unsigned long nr_pages)
10558 atomic_long_sub(nr_pages, &user->locked_vm);
10561 static inline int __io_account_mem(struct user_struct *user,
10562 unsigned long nr_pages)
10564 unsigned long page_limit, cur_pages, new_pages;
10566 /* Don't allow more pages than we can safely lock */
10567 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10570 cur_pages = atomic_long_read(&user->locked_vm);
10571 new_pages = cur_pages + nr_pages;
10572 if (new_pages > page_limit)
10574 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10575 new_pages) != cur_pages);
10580 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10583 __io_unaccount_mem(ctx->user, nr_pages);
10585 if (ctx->mm_account)
10586 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10589 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10594 ret = __io_account_mem(ctx->user, nr_pages);
10599 if (ctx->mm_account)
10600 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10605 static void io_mem_free(void *ptr)
10612 page = virt_to_head_page(ptr);
10613 if (put_page_testzero(page))
10614 free_compound_page(page);
10617 static void *io_mem_alloc(size_t size)
10619 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10621 return (void *) __get_free_pages(gfp, get_order(size));
10624 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10625 unsigned int cq_entries, size_t *sq_offset)
10627 struct io_rings *rings;
10628 size_t off, sq_array_size;
10630 off = struct_size(rings, cqes, cq_entries);
10631 if (off == SIZE_MAX)
10633 if (ctx->flags & IORING_SETUP_CQE32) {
10634 if (check_shl_overflow(off, 1, &off))
10639 off = ALIGN(off, SMP_CACHE_BYTES);
10647 sq_array_size = array_size(sizeof(u32), sq_entries);
10648 if (sq_array_size == SIZE_MAX)
10651 if (check_add_overflow(off, sq_array_size, &off))
10657 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10659 struct io_mapped_ubuf *imu = *slot;
10662 if (imu != ctx->dummy_ubuf) {
10663 for (i = 0; i < imu->nr_bvecs; i++)
10664 unpin_user_page(imu->bvec[i].bv_page);
10665 if (imu->acct_pages)
10666 io_unaccount_mem(ctx, imu->acct_pages);
10672 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10674 io_buffer_unmap(ctx, &prsrc->buf);
10678 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10682 for (i = 0; i < ctx->nr_user_bufs; i++)
10683 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10684 kfree(ctx->user_bufs);
10685 io_rsrc_data_free(ctx->buf_data);
10686 ctx->user_bufs = NULL;
10687 ctx->buf_data = NULL;
10688 ctx->nr_user_bufs = 0;
10691 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10695 if (!ctx->buf_data)
10698 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10700 __io_sqe_buffers_unregister(ctx);
10704 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10705 void __user *arg, unsigned index)
10707 struct iovec __user *src;
10709 #ifdef CONFIG_COMPAT
10711 struct compat_iovec __user *ciovs;
10712 struct compat_iovec ciov;
10714 ciovs = (struct compat_iovec __user *) arg;
10715 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10718 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10719 dst->iov_len = ciov.iov_len;
10723 src = (struct iovec __user *) arg;
10724 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10730 * Not super efficient, but this is just a registration time. And we do cache
10731 * the last compound head, so generally we'll only do a full search if we don't
10734 * We check if the given compound head page has already been accounted, to
10735 * avoid double accounting it. This allows us to account the full size of the
10736 * page, not just the constituent pages of a huge page.
10738 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10739 int nr_pages, struct page *hpage)
10743 /* check current page array */
10744 for (i = 0; i < nr_pages; i++) {
10745 if (!PageCompound(pages[i]))
10747 if (compound_head(pages[i]) == hpage)
10751 /* check previously registered pages */
10752 for (i = 0; i < ctx->nr_user_bufs; i++) {
10753 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10755 for (j = 0; j < imu->nr_bvecs; j++) {
10756 if (!PageCompound(imu->bvec[j].bv_page))
10758 if (compound_head(imu->bvec[j].bv_page) == hpage)
10766 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10767 int nr_pages, struct io_mapped_ubuf *imu,
10768 struct page **last_hpage)
10772 imu->acct_pages = 0;
10773 for (i = 0; i < nr_pages; i++) {
10774 if (!PageCompound(pages[i])) {
10777 struct page *hpage;
10779 hpage = compound_head(pages[i]);
10780 if (hpage == *last_hpage)
10782 *last_hpage = hpage;
10783 if (headpage_already_acct(ctx, pages, i, hpage))
10785 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10789 if (!imu->acct_pages)
10792 ret = io_account_mem(ctx, imu->acct_pages);
10794 imu->acct_pages = 0;
10798 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10801 unsigned long start, end, nr_pages;
10802 struct vm_area_struct **vmas = NULL;
10803 struct page **pages = NULL;
10804 int i, pret, ret = -ENOMEM;
10806 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10807 start = ubuf >> PAGE_SHIFT;
10808 nr_pages = end - start;
10810 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10814 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10820 mmap_read_lock(current->mm);
10821 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10823 if (pret == nr_pages) {
10824 /* don't support file backed memory */
10825 for (i = 0; i < nr_pages; i++) {
10826 struct vm_area_struct *vma = vmas[i];
10828 if (vma_is_shmem(vma))
10830 if (vma->vm_file &&
10831 !is_file_hugepages(vma->vm_file)) {
10836 *npages = nr_pages;
10838 ret = pret < 0 ? pret : -EFAULT;
10840 mmap_read_unlock(current->mm);
10843 * if we did partial map, or found file backed vmas,
10844 * release any pages we did get
10847 unpin_user_pages(pages, pret);
10855 pages = ERR_PTR(ret);
10860 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10861 struct io_mapped_ubuf **pimu,
10862 struct page **last_hpage)
10864 struct io_mapped_ubuf *imu = NULL;
10865 struct page **pages = NULL;
10868 int ret, nr_pages, i;
10870 if (!iov->iov_base) {
10871 *pimu = ctx->dummy_ubuf;
10878 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10880 if (IS_ERR(pages)) {
10881 ret = PTR_ERR(pages);
10886 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10890 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10892 unpin_user_pages(pages, nr_pages);
10896 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10897 size = iov->iov_len;
10898 for (i = 0; i < nr_pages; i++) {
10901 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10902 imu->bvec[i].bv_page = pages[i];
10903 imu->bvec[i].bv_len = vec_len;
10904 imu->bvec[i].bv_offset = off;
10908 /* store original address for later verification */
10909 imu->ubuf = (unsigned long) iov->iov_base;
10910 imu->ubuf_end = imu->ubuf + iov->iov_len;
10911 imu->nr_bvecs = nr_pages;
10921 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10923 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10924 return ctx->user_bufs ? 0 : -ENOMEM;
10927 static int io_buffer_validate(struct iovec *iov)
10929 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10932 * Don't impose further limits on the size and buffer
10933 * constraints here, we'll -EINVAL later when IO is
10934 * submitted if they are wrong.
10936 if (!iov->iov_base)
10937 return iov->iov_len ? -EFAULT : 0;
10941 /* arbitrary limit, but we need something */
10942 if (iov->iov_len > SZ_1G)
10945 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10951 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10952 unsigned int nr_args, u64 __user *tags)
10954 struct page *last_hpage = NULL;
10955 struct io_rsrc_data *data;
10959 if (ctx->user_bufs)
10961 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10963 ret = io_rsrc_node_switch_start(ctx);
10966 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10969 ret = io_buffers_map_alloc(ctx, nr_args);
10971 io_rsrc_data_free(data);
10975 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10977 ret = io_copy_iov(ctx, &iov, arg, i);
10980 ret = io_buffer_validate(&iov);
10984 memset(&iov, 0, sizeof(iov));
10987 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10992 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10998 WARN_ON_ONCE(ctx->buf_data);
11000 ctx->buf_data = data;
11002 __io_sqe_buffers_unregister(ctx);
11004 io_rsrc_node_switch(ctx, NULL);
11008 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
11009 struct io_uring_rsrc_update2 *up,
11010 unsigned int nr_args)
11012 u64 __user *tags = u64_to_user_ptr(up->tags);
11013 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
11014 struct page *last_hpage = NULL;
11015 bool needs_switch = false;
11019 if (!ctx->buf_data)
11021 if (up->offset + nr_args > ctx->nr_user_bufs)
11024 for (done = 0; done < nr_args; done++) {
11025 struct io_mapped_ubuf *imu;
11026 int offset = up->offset + done;
11029 err = io_copy_iov(ctx, &iov, iovs, done);
11032 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
11036 err = io_buffer_validate(&iov);
11039 if (!iov.iov_base && tag) {
11043 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
11047 i = array_index_nospec(offset, ctx->nr_user_bufs);
11048 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
11049 err = io_queue_rsrc_removal(ctx->buf_data, i,
11050 ctx->rsrc_node, ctx->user_bufs[i]);
11051 if (unlikely(err)) {
11052 io_buffer_unmap(ctx, &imu);
11055 ctx->user_bufs[i] = NULL;
11056 needs_switch = true;
11059 ctx->user_bufs[i] = imu;
11060 *io_get_tag_slot(ctx->buf_data, offset) = tag;
11064 io_rsrc_node_switch(ctx, ctx->buf_data);
11065 return done ? done : err;
11068 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
11069 unsigned int eventfd_async)
11071 struct io_ev_fd *ev_fd;
11072 __s32 __user *fds = arg;
11075 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11076 lockdep_is_held(&ctx->uring_lock));
11080 if (copy_from_user(&fd, fds, sizeof(*fds)))
11083 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
11087 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
11088 if (IS_ERR(ev_fd->cq_ev_fd)) {
11089 int ret = PTR_ERR(ev_fd->cq_ev_fd);
11093 ev_fd->eventfd_async = eventfd_async;
11094 ctx->has_evfd = true;
11095 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
11099 static void io_eventfd_put(struct rcu_head *rcu)
11101 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
11103 eventfd_ctx_put(ev_fd->cq_ev_fd);
11107 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
11109 struct io_ev_fd *ev_fd;
11111 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
11112 lockdep_is_held(&ctx->uring_lock));
11114 ctx->has_evfd = false;
11115 rcu_assign_pointer(ctx->io_ev_fd, NULL);
11116 call_rcu(&ev_fd->rcu, io_eventfd_put);
11123 static void io_destroy_buffers(struct io_ring_ctx *ctx)
11125 struct io_buffer_list *bl;
11126 unsigned long index;
11129 for (i = 0; i < BGID_ARRAY; i++) {
11132 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
11135 xa_for_each(&ctx->io_bl_xa, index, bl) {
11136 xa_erase(&ctx->io_bl_xa, bl->bgid);
11137 __io_remove_buffers(ctx, bl, -1U);
11141 while (!list_empty(&ctx->io_buffers_pages)) {
11144 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
11145 list_del_init(&page->lru);
11150 static void io_req_caches_free(struct io_ring_ctx *ctx)
11152 struct io_submit_state *state = &ctx->submit_state;
11155 mutex_lock(&ctx->uring_lock);
11156 io_flush_cached_locked_reqs(ctx, state);
11158 while (!io_req_cache_empty(ctx)) {
11159 struct io_wq_work_node *node;
11160 struct io_kiocb *req;
11162 node = wq_stack_extract(&state->free_list);
11163 req = container_of(node, struct io_kiocb, comp_list);
11164 kmem_cache_free(req_cachep, req);
11168 percpu_ref_put_many(&ctx->refs, nr);
11169 mutex_unlock(&ctx->uring_lock);
11172 static void io_wait_rsrc_data(struct io_rsrc_data *data)
11174 if (data && !atomic_dec_and_test(&data->refs))
11175 wait_for_completion(&data->done);
11178 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
11180 struct async_poll *apoll;
11182 while (!list_empty(&ctx->apoll_cache)) {
11183 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
11185 list_del(&apoll->poll.wait.entry);
11190 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
11192 io_sq_thread_finish(ctx);
11194 if (ctx->mm_account) {
11195 mmdrop(ctx->mm_account);
11196 ctx->mm_account = NULL;
11199 io_rsrc_refs_drop(ctx);
11200 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
11201 io_wait_rsrc_data(ctx->buf_data);
11202 io_wait_rsrc_data(ctx->file_data);
11204 mutex_lock(&ctx->uring_lock);
11206 __io_sqe_buffers_unregister(ctx);
11207 if (ctx->file_data)
11208 __io_sqe_files_unregister(ctx);
11210 __io_cqring_overflow_flush(ctx, true);
11211 io_eventfd_unregister(ctx);
11212 io_flush_apoll_cache(ctx);
11213 mutex_unlock(&ctx->uring_lock);
11214 io_destroy_buffers(ctx);
11216 put_cred(ctx->sq_creds);
11218 /* there are no registered resources left, nobody uses it */
11219 if (ctx->rsrc_node)
11220 io_rsrc_node_destroy(ctx->rsrc_node);
11221 if (ctx->rsrc_backup_node)
11222 io_rsrc_node_destroy(ctx->rsrc_backup_node);
11223 flush_delayed_work(&ctx->rsrc_put_work);
11224 flush_delayed_work(&ctx->fallback_work);
11226 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
11227 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
11229 #if defined(CONFIG_UNIX)
11230 if (ctx->ring_sock) {
11231 ctx->ring_sock->file = NULL; /* so that iput() is called */
11232 sock_release(ctx->ring_sock);
11235 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
11237 io_mem_free(ctx->rings);
11238 io_mem_free(ctx->sq_sqes);
11240 percpu_ref_exit(&ctx->refs);
11241 free_uid(ctx->user);
11242 io_req_caches_free(ctx);
11244 io_wq_put_hash(ctx->hash_map);
11245 kfree(ctx->cancel_hash);
11246 kfree(ctx->dummy_ubuf);
11248 xa_destroy(&ctx->io_bl_xa);
11252 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
11254 struct io_ring_ctx *ctx = file->private_data;
11257 poll_wait(file, &ctx->cq_wait, wait);
11259 * synchronizes with barrier from wq_has_sleeper call in
11263 if (!io_sqring_full(ctx))
11264 mask |= EPOLLOUT | EPOLLWRNORM;
11267 * Don't flush cqring overflow list here, just do a simple check.
11268 * Otherwise there could possible be ABBA deadlock:
11271 * lock(&ctx->uring_lock);
11273 * lock(&ctx->uring_lock);
11276 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
11277 * pushs them to do the flush.
11279 if (io_cqring_events(ctx) ||
11280 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
11281 mask |= EPOLLIN | EPOLLRDNORM;
11286 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
11288 const struct cred *creds;
11290 creds = xa_erase(&ctx->personalities, id);
11299 struct io_tctx_exit {
11300 struct callback_head task_work;
11301 struct completion completion;
11302 struct io_ring_ctx *ctx;
11305 static __cold void io_tctx_exit_cb(struct callback_head *cb)
11307 struct io_uring_task *tctx = current->io_uring;
11308 struct io_tctx_exit *work;
11310 work = container_of(cb, struct io_tctx_exit, task_work);
11312 * When @in_idle, we're in cancellation and it's racy to remove the
11313 * node. It'll be removed by the end of cancellation, just ignore it.
11315 if (!atomic_read(&tctx->in_idle))
11316 io_uring_del_tctx_node((unsigned long)work->ctx);
11317 complete(&work->completion);
11320 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
11322 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11324 return req->ctx == data;
11327 static __cold void io_ring_exit_work(struct work_struct *work)
11329 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
11330 unsigned long timeout = jiffies + HZ * 60 * 5;
11331 unsigned long interval = HZ / 20;
11332 struct io_tctx_exit exit;
11333 struct io_tctx_node *node;
11337 * If we're doing polled IO and end up having requests being
11338 * submitted async (out-of-line), then completions can come in while
11339 * we're waiting for refs to drop. We need to reap these manually,
11340 * as nobody else will be looking for them.
11343 io_uring_try_cancel_requests(ctx, NULL, true);
11344 if (ctx->sq_data) {
11345 struct io_sq_data *sqd = ctx->sq_data;
11346 struct task_struct *tsk;
11348 io_sq_thread_park(sqd);
11350 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
11351 io_wq_cancel_cb(tsk->io_uring->io_wq,
11352 io_cancel_ctx_cb, ctx, true);
11353 io_sq_thread_unpark(sqd);
11356 io_req_caches_free(ctx);
11358 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
11359 /* there is little hope left, don't run it too often */
11360 interval = HZ * 60;
11362 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
11364 init_completion(&exit.completion);
11365 init_task_work(&exit.task_work, io_tctx_exit_cb);
11368 * Some may use context even when all refs and requests have been put,
11369 * and they are free to do so while still holding uring_lock or
11370 * completion_lock, see io_req_task_submit(). Apart from other work,
11371 * this lock/unlock section also waits them to finish.
11373 mutex_lock(&ctx->uring_lock);
11374 while (!list_empty(&ctx->tctx_list)) {
11375 WARN_ON_ONCE(time_after(jiffies, timeout));
11377 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
11379 /* don't spin on a single task if cancellation failed */
11380 list_rotate_left(&ctx->tctx_list);
11381 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
11382 if (WARN_ON_ONCE(ret))
11385 mutex_unlock(&ctx->uring_lock);
11386 wait_for_completion(&exit.completion);
11387 mutex_lock(&ctx->uring_lock);
11389 mutex_unlock(&ctx->uring_lock);
11390 spin_lock(&ctx->completion_lock);
11391 spin_unlock(&ctx->completion_lock);
11393 io_ring_ctx_free(ctx);
11396 /* Returns true if we found and killed one or more timeouts */
11397 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
11398 struct task_struct *tsk, bool cancel_all)
11400 struct io_kiocb *req, *tmp;
11403 spin_lock(&ctx->completion_lock);
11404 spin_lock_irq(&ctx->timeout_lock);
11405 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11406 if (io_match_task(req, tsk, cancel_all)) {
11407 io_kill_timeout(req, -ECANCELED);
11411 spin_unlock_irq(&ctx->timeout_lock);
11412 io_commit_cqring(ctx);
11413 spin_unlock(&ctx->completion_lock);
11415 io_cqring_ev_posted(ctx);
11416 return canceled != 0;
11419 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11421 unsigned long index;
11422 struct creds *creds;
11424 mutex_lock(&ctx->uring_lock);
11425 percpu_ref_kill(&ctx->refs);
11427 __io_cqring_overflow_flush(ctx, true);
11428 xa_for_each(&ctx->personalities, index, creds)
11429 io_unregister_personality(ctx, index);
11430 mutex_unlock(&ctx->uring_lock);
11432 /* failed during ring init, it couldn't have issued any requests */
11434 io_kill_timeouts(ctx, NULL, true);
11435 io_poll_remove_all(ctx, NULL, true);
11436 /* if we failed setting up the ctx, we might not have any rings */
11437 io_iopoll_try_reap_events(ctx);
11440 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11442 * Use system_unbound_wq to avoid spawning tons of event kworkers
11443 * if we're exiting a ton of rings at the same time. It just adds
11444 * noise and overhead, there's no discernable change in runtime
11445 * over using system_wq.
11447 queue_work(system_unbound_wq, &ctx->exit_work);
11450 static int io_uring_release(struct inode *inode, struct file *file)
11452 struct io_ring_ctx *ctx = file->private_data;
11454 file->private_data = NULL;
11455 io_ring_ctx_wait_and_kill(ctx);
11459 struct io_task_cancel {
11460 struct task_struct *task;
11464 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11466 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11467 struct io_task_cancel *cancel = data;
11469 return io_match_task_safe(req, cancel->task, cancel->all);
11472 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11473 struct task_struct *task,
11476 struct io_defer_entry *de;
11479 spin_lock(&ctx->completion_lock);
11480 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11481 if (io_match_task_safe(de->req, task, cancel_all)) {
11482 list_cut_position(&list, &ctx->defer_list, &de->list);
11486 spin_unlock(&ctx->completion_lock);
11487 if (list_empty(&list))
11490 while (!list_empty(&list)) {
11491 de = list_first_entry(&list, struct io_defer_entry, list);
11492 list_del_init(&de->list);
11493 io_req_complete_failed(de->req, -ECANCELED);
11499 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11501 struct io_tctx_node *node;
11502 enum io_wq_cancel cret;
11505 mutex_lock(&ctx->uring_lock);
11506 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11507 struct io_uring_task *tctx = node->task->io_uring;
11510 * io_wq will stay alive while we hold uring_lock, because it's
11511 * killed after ctx nodes, which requires to take the lock.
11513 if (!tctx || !tctx->io_wq)
11515 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11516 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11518 mutex_unlock(&ctx->uring_lock);
11523 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11524 struct task_struct *task,
11527 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11528 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11530 /* failed during ring init, it couldn't have issued any requests */
11535 enum io_wq_cancel cret;
11539 ret |= io_uring_try_cancel_iowq(ctx);
11540 } else if (tctx && tctx->io_wq) {
11542 * Cancels requests of all rings, not only @ctx, but
11543 * it's fine as the task is in exit/exec.
11545 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11547 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11550 /* SQPOLL thread does its own polling */
11551 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11552 (ctx->sq_data && ctx->sq_data->thread == current)) {
11553 while (!wq_list_empty(&ctx->iopoll_list)) {
11554 io_iopoll_try_reap_events(ctx);
11559 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11560 ret |= io_poll_remove_all(ctx, task, cancel_all);
11561 ret |= io_kill_timeouts(ctx, task, cancel_all);
11563 ret |= io_run_task_work();
11570 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11572 struct io_uring_task *tctx = current->io_uring;
11573 struct io_tctx_node *node;
11576 if (unlikely(!tctx)) {
11577 ret = io_uring_alloc_task_context(current, ctx);
11581 tctx = current->io_uring;
11582 if (ctx->iowq_limits_set) {
11583 unsigned int limits[2] = { ctx->iowq_limits[0],
11584 ctx->iowq_limits[1], };
11586 ret = io_wq_max_workers(tctx->io_wq, limits);
11591 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11592 node = kmalloc(sizeof(*node), GFP_KERNEL);
11596 node->task = current;
11598 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11599 node, GFP_KERNEL));
11605 mutex_lock(&ctx->uring_lock);
11606 list_add(&node->ctx_node, &ctx->tctx_list);
11607 mutex_unlock(&ctx->uring_lock);
11614 * Note that this task has used io_uring. We use it for cancelation purposes.
11616 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11618 struct io_uring_task *tctx = current->io_uring;
11620 if (likely(tctx && tctx->last == ctx))
11622 return __io_uring_add_tctx_node(ctx);
11626 * Remove this io_uring_file -> task mapping.
11628 static __cold void io_uring_del_tctx_node(unsigned long index)
11630 struct io_uring_task *tctx = current->io_uring;
11631 struct io_tctx_node *node;
11635 node = xa_erase(&tctx->xa, index);
11639 WARN_ON_ONCE(current != node->task);
11640 WARN_ON_ONCE(list_empty(&node->ctx_node));
11642 mutex_lock(&node->ctx->uring_lock);
11643 list_del(&node->ctx_node);
11644 mutex_unlock(&node->ctx->uring_lock);
11646 if (tctx->last == node->ctx)
11651 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11653 struct io_wq *wq = tctx->io_wq;
11654 struct io_tctx_node *node;
11655 unsigned long index;
11657 xa_for_each(&tctx->xa, index, node) {
11658 io_uring_del_tctx_node(index);
11663 * Must be after io_uring_del_tctx_node() (removes nodes under
11664 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11666 io_wq_put_and_exit(wq);
11667 tctx->io_wq = NULL;
11671 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11674 return atomic_read(&tctx->inflight_tracked);
11675 return percpu_counter_sum(&tctx->inflight);
11679 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11680 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11682 static __cold void io_uring_cancel_generic(bool cancel_all,
11683 struct io_sq_data *sqd)
11685 struct io_uring_task *tctx = current->io_uring;
11686 struct io_ring_ctx *ctx;
11690 WARN_ON_ONCE(sqd && sqd->thread != current);
11692 if (!current->io_uring)
11695 io_wq_exit_start(tctx->io_wq);
11697 atomic_inc(&tctx->in_idle);
11699 io_uring_drop_tctx_refs(current);
11700 /* read completions before cancelations */
11701 inflight = tctx_inflight(tctx, !cancel_all);
11706 struct io_tctx_node *node;
11707 unsigned long index;
11709 xa_for_each(&tctx->xa, index, node) {
11710 /* sqpoll task will cancel all its requests */
11711 if (node->ctx->sq_data)
11713 io_uring_try_cancel_requests(node->ctx, current,
11717 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11718 io_uring_try_cancel_requests(ctx, current,
11722 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11723 io_run_task_work();
11724 io_uring_drop_tctx_refs(current);
11727 * If we've seen completions, retry without waiting. This
11728 * avoids a race where a completion comes in before we did
11729 * prepare_to_wait().
11731 if (inflight == tctx_inflight(tctx, !cancel_all))
11733 finish_wait(&tctx->wait, &wait);
11736 io_uring_clean_tctx(tctx);
11739 * We shouldn't run task_works after cancel, so just leave
11740 * ->in_idle set for normal exit.
11742 atomic_dec(&tctx->in_idle);
11743 /* for exec all current's requests should be gone, kill tctx */
11744 __io_uring_free(current);
11748 void __io_uring_cancel(bool cancel_all)
11750 io_uring_cancel_generic(cancel_all, NULL);
11753 void io_uring_unreg_ringfd(void)
11755 struct io_uring_task *tctx = current->io_uring;
11758 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11759 if (tctx->registered_rings[i]) {
11760 fput(tctx->registered_rings[i]);
11761 tctx->registered_rings[i] = NULL;
11766 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11767 int start, int end)
11772 for (offset = start; offset < end; offset++) {
11773 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11774 if (tctx->registered_rings[offset])
11780 } else if (file->f_op != &io_uring_fops) {
11782 return -EOPNOTSUPP;
11784 tctx->registered_rings[offset] = file;
11792 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11793 * invocation. User passes in an array of struct io_uring_rsrc_update
11794 * with ->data set to the ring_fd, and ->offset given for the desired
11795 * index. If no index is desired, application may set ->offset == -1U
11796 * and we'll find an available index. Returns number of entries
11797 * successfully processed, or < 0 on error if none were processed.
11799 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11802 struct io_uring_rsrc_update __user *arg = __arg;
11803 struct io_uring_rsrc_update reg;
11804 struct io_uring_task *tctx;
11807 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11810 mutex_unlock(&ctx->uring_lock);
11811 ret = io_uring_add_tctx_node(ctx);
11812 mutex_lock(&ctx->uring_lock);
11816 tctx = current->io_uring;
11817 for (i = 0; i < nr_args; i++) {
11820 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11830 if (reg.offset == -1U) {
11832 end = IO_RINGFD_REG_MAX;
11834 if (reg.offset >= IO_RINGFD_REG_MAX) {
11838 start = reg.offset;
11842 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11847 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11848 fput(tctx->registered_rings[reg.offset]);
11849 tctx->registered_rings[reg.offset] = NULL;
11855 return i ? i : ret;
11858 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11861 struct io_uring_rsrc_update __user *arg = __arg;
11862 struct io_uring_task *tctx = current->io_uring;
11863 struct io_uring_rsrc_update reg;
11866 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11871 for (i = 0; i < nr_args; i++) {
11872 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11876 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11881 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11882 if (tctx->registered_rings[reg.offset]) {
11883 fput(tctx->registered_rings[reg.offset]);
11884 tctx->registered_rings[reg.offset] = NULL;
11888 return i ? i : ret;
11891 static void *io_uring_validate_mmap_request(struct file *file,
11892 loff_t pgoff, size_t sz)
11894 struct io_ring_ctx *ctx = file->private_data;
11895 loff_t offset = pgoff << PAGE_SHIFT;
11900 case IORING_OFF_SQ_RING:
11901 case IORING_OFF_CQ_RING:
11904 case IORING_OFF_SQES:
11905 ptr = ctx->sq_sqes;
11908 return ERR_PTR(-EINVAL);
11911 page = virt_to_head_page(ptr);
11912 if (sz > page_size(page))
11913 return ERR_PTR(-EINVAL);
11920 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11922 size_t sz = vma->vm_end - vma->vm_start;
11926 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11928 return PTR_ERR(ptr);
11930 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11931 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11934 #else /* !CONFIG_MMU */
11936 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11938 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11941 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11943 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11946 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11947 unsigned long addr, unsigned long len,
11948 unsigned long pgoff, unsigned long flags)
11952 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11954 return PTR_ERR(ptr);
11956 return (unsigned long) ptr;
11959 #endif /* !CONFIG_MMU */
11961 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11966 if (!io_sqring_full(ctx))
11968 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11970 if (!io_sqring_full(ctx))
11973 } while (!signal_pending(current));
11975 finish_wait(&ctx->sqo_sq_wait, &wait);
11979 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11981 if (flags & IORING_ENTER_EXT_ARG) {
11982 struct io_uring_getevents_arg arg;
11984 if (argsz != sizeof(arg))
11986 if (copy_from_user(&arg, argp, sizeof(arg)))
11992 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11993 struct __kernel_timespec __user **ts,
11994 const sigset_t __user **sig)
11996 struct io_uring_getevents_arg arg;
11999 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
12000 * is just a pointer to the sigset_t.
12002 if (!(flags & IORING_ENTER_EXT_ARG)) {
12003 *sig = (const sigset_t __user *) argp;
12009 * EXT_ARG is set - ensure we agree on the size of it and copy in our
12010 * timespec and sigset_t pointers if good.
12012 if (*argsz != sizeof(arg))
12014 if (copy_from_user(&arg, argp, sizeof(arg)))
12018 *sig = u64_to_user_ptr(arg.sigmask);
12019 *argsz = arg.sigmask_sz;
12020 *ts = u64_to_user_ptr(arg.ts);
12024 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
12025 u32, min_complete, u32, flags, const void __user *, argp,
12028 struct io_ring_ctx *ctx;
12032 io_run_task_work();
12034 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
12035 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
12036 IORING_ENTER_REGISTERED_RING)))
12040 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
12041 * need only dereference our task private array to find it.
12043 if (flags & IORING_ENTER_REGISTERED_RING) {
12044 struct io_uring_task *tctx = current->io_uring;
12046 if (!tctx || fd >= IO_RINGFD_REG_MAX)
12048 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
12049 f.file = tctx->registered_rings[fd];
12055 if (unlikely(!f.file))
12059 if (unlikely(f.file->f_op != &io_uring_fops))
12063 ctx = f.file->private_data;
12064 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
12068 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
12072 * For SQ polling, the thread will do all submissions and completions.
12073 * Just return the requested submit count, and wake the thread if
12074 * we were asked to.
12077 if (ctx->flags & IORING_SETUP_SQPOLL) {
12078 io_cqring_overflow_flush(ctx);
12080 if (unlikely(ctx->sq_data->thread == NULL)) {
12084 if (flags & IORING_ENTER_SQ_WAKEUP)
12085 wake_up(&ctx->sq_data->wait);
12086 if (flags & IORING_ENTER_SQ_WAIT) {
12087 ret = io_sqpoll_wait_sq(ctx);
12092 } else if (to_submit) {
12093 ret = io_uring_add_tctx_node(ctx);
12097 mutex_lock(&ctx->uring_lock);
12098 ret = io_submit_sqes(ctx, to_submit);
12099 if (ret != to_submit) {
12100 mutex_unlock(&ctx->uring_lock);
12103 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
12104 goto iopoll_locked;
12105 mutex_unlock(&ctx->uring_lock);
12107 if (flags & IORING_ENTER_GETEVENTS) {
12109 if (ctx->syscall_iopoll) {
12111 * We disallow the app entering submit/complete with
12112 * polling, but we still need to lock the ring to
12113 * prevent racing with polled issue that got punted to
12116 mutex_lock(&ctx->uring_lock);
12118 ret2 = io_validate_ext_arg(flags, argp, argsz);
12119 if (likely(!ret2)) {
12120 min_complete = min(min_complete,
12122 ret2 = io_iopoll_check(ctx, min_complete);
12124 mutex_unlock(&ctx->uring_lock);
12126 const sigset_t __user *sig;
12127 struct __kernel_timespec __user *ts;
12129 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
12130 if (likely(!ret2)) {
12131 min_complete = min(min_complete,
12133 ret2 = io_cqring_wait(ctx, min_complete, sig,
12142 * EBADR indicates that one or more CQE were dropped.
12143 * Once the user has been informed we can clear the bit
12144 * as they are obviously ok with those drops.
12146 if (unlikely(ret2 == -EBADR))
12147 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
12153 percpu_ref_put(&ctx->refs);
12159 #ifdef CONFIG_PROC_FS
12160 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
12161 const struct cred *cred)
12163 struct user_namespace *uns = seq_user_ns(m);
12164 struct group_info *gi;
12169 seq_printf(m, "%5d\n", id);
12170 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
12171 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
12172 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
12173 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
12174 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
12175 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
12176 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
12177 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
12178 seq_puts(m, "\n\tGroups:\t");
12179 gi = cred->group_info;
12180 for (g = 0; g < gi->ngroups; g++) {
12181 seq_put_decimal_ull(m, g ? " " : "",
12182 from_kgid_munged(uns, gi->gid[g]));
12184 seq_puts(m, "\n\tCapEff:\t");
12185 cap = cred->cap_effective;
12186 CAP_FOR_EACH_U32(__capi)
12187 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
12192 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
12193 struct seq_file *m)
12195 struct io_sq_data *sq = NULL;
12196 struct io_overflow_cqe *ocqe;
12197 struct io_rings *r = ctx->rings;
12198 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
12199 unsigned int sq_head = READ_ONCE(r->sq.head);
12200 unsigned int sq_tail = READ_ONCE(r->sq.tail);
12201 unsigned int cq_head = READ_ONCE(r->cq.head);
12202 unsigned int cq_tail = READ_ONCE(r->cq.tail);
12203 unsigned int cq_shift = 0;
12204 unsigned int sq_entries, cq_entries;
12206 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
12213 * we may get imprecise sqe and cqe info if uring is actively running
12214 * since we get cached_sq_head and cached_cq_tail without uring_lock
12215 * and sq_tail and cq_head are changed by userspace. But it's ok since
12216 * we usually use these info when it is stuck.
12218 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
12219 seq_printf(m, "SqHead:\t%u\n", sq_head);
12220 seq_printf(m, "SqTail:\t%u\n", sq_tail);
12221 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
12222 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
12223 seq_printf(m, "CqHead:\t%u\n", cq_head);
12224 seq_printf(m, "CqTail:\t%u\n", cq_tail);
12225 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
12226 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
12227 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
12228 for (i = 0; i < sq_entries; i++) {
12229 unsigned int entry = i + sq_head;
12230 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
12231 struct io_uring_sqe *sqe;
12233 if (sq_idx > sq_mask)
12235 sqe = &ctx->sq_sqes[sq_idx];
12236 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
12237 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
12240 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
12241 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
12242 for (i = 0; i < cq_entries; i++) {
12243 unsigned int entry = i + cq_head;
12244 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
12247 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
12248 entry & cq_mask, cqe->user_data, cqe->res,
12251 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
12252 "extra1:%llu, extra2:%llu\n",
12253 entry & cq_mask, cqe->user_data, cqe->res,
12254 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
12259 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
12260 * since fdinfo case grabs it in the opposite direction of normal use
12261 * cases. If we fail to get the lock, we just don't iterate any
12262 * structures that could be going away outside the io_uring mutex.
12264 has_lock = mutex_trylock(&ctx->uring_lock);
12266 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
12272 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
12273 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
12274 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
12275 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
12276 struct file *f = io_file_from_index(ctx, i);
12279 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
12281 seq_printf(m, "%5u: <none>\n", i);
12283 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
12284 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
12285 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
12286 unsigned int len = buf->ubuf_end - buf->ubuf;
12288 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
12290 if (has_lock && !xa_empty(&ctx->personalities)) {
12291 unsigned long index;
12292 const struct cred *cred;
12294 seq_printf(m, "Personalities:\n");
12295 xa_for_each(&ctx->personalities, index, cred)
12296 io_uring_show_cred(m, index, cred);
12299 mutex_unlock(&ctx->uring_lock);
12301 seq_puts(m, "PollList:\n");
12302 spin_lock(&ctx->completion_lock);
12303 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
12304 struct hlist_head *list = &ctx->cancel_hash[i];
12305 struct io_kiocb *req;
12307 hlist_for_each_entry(req, list, hash_node)
12308 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
12309 task_work_pending(req->task));
12312 seq_puts(m, "CqOverflowList:\n");
12313 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
12314 struct io_uring_cqe *cqe = &ocqe->cqe;
12316 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
12317 cqe->user_data, cqe->res, cqe->flags);
12321 spin_unlock(&ctx->completion_lock);
12324 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
12326 struct io_ring_ctx *ctx = f->private_data;
12328 if (percpu_ref_tryget(&ctx->refs)) {
12329 __io_uring_show_fdinfo(ctx, m);
12330 percpu_ref_put(&ctx->refs);
12335 static const struct file_operations io_uring_fops = {
12336 .release = io_uring_release,
12337 .mmap = io_uring_mmap,
12339 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
12340 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
12342 .poll = io_uring_poll,
12343 #ifdef CONFIG_PROC_FS
12344 .show_fdinfo = io_uring_show_fdinfo,
12348 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
12349 struct io_uring_params *p)
12351 struct io_rings *rings;
12352 size_t size, sq_array_offset;
12354 /* make sure these are sane, as we already accounted them */
12355 ctx->sq_entries = p->sq_entries;
12356 ctx->cq_entries = p->cq_entries;
12358 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
12359 if (size == SIZE_MAX)
12362 rings = io_mem_alloc(size);
12366 ctx->rings = rings;
12367 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
12368 rings->sq_ring_mask = p->sq_entries - 1;
12369 rings->cq_ring_mask = p->cq_entries - 1;
12370 rings->sq_ring_entries = p->sq_entries;
12371 rings->cq_ring_entries = p->cq_entries;
12373 if (p->flags & IORING_SETUP_SQE128)
12374 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
12376 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
12377 if (size == SIZE_MAX) {
12378 io_mem_free(ctx->rings);
12383 ctx->sq_sqes = io_mem_alloc(size);
12384 if (!ctx->sq_sqes) {
12385 io_mem_free(ctx->rings);
12393 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
12397 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
12401 ret = io_uring_add_tctx_node(ctx);
12406 fd_install(fd, file);
12411 * Allocate an anonymous fd, this is what constitutes the application
12412 * visible backing of an io_uring instance. The application mmaps this
12413 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12414 * we have to tie this fd to a socket for file garbage collection purposes.
12416 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12419 #if defined(CONFIG_UNIX)
12422 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12425 return ERR_PTR(ret);
12428 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12429 O_RDWR | O_CLOEXEC, NULL);
12430 #if defined(CONFIG_UNIX)
12431 if (IS_ERR(file)) {
12432 sock_release(ctx->ring_sock);
12433 ctx->ring_sock = NULL;
12435 ctx->ring_sock->file = file;
12441 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12442 struct io_uring_params __user *params)
12444 struct io_ring_ctx *ctx;
12450 if (entries > IORING_MAX_ENTRIES) {
12451 if (!(p->flags & IORING_SETUP_CLAMP))
12453 entries = IORING_MAX_ENTRIES;
12457 * Use twice as many entries for the CQ ring. It's possible for the
12458 * application to drive a higher depth than the size of the SQ ring,
12459 * since the sqes are only used at submission time. This allows for
12460 * some flexibility in overcommitting a bit. If the application has
12461 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12462 * of CQ ring entries manually.
12464 p->sq_entries = roundup_pow_of_two(entries);
12465 if (p->flags & IORING_SETUP_CQSIZE) {
12467 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12468 * to a power-of-two, if it isn't already. We do NOT impose
12469 * any cq vs sq ring sizing.
12471 if (!p->cq_entries)
12473 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12474 if (!(p->flags & IORING_SETUP_CLAMP))
12476 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12478 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12479 if (p->cq_entries < p->sq_entries)
12482 p->cq_entries = 2 * p->sq_entries;
12485 ctx = io_ring_ctx_alloc(p);
12490 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12491 * space applications don't need to do io completion events
12492 * polling again, they can rely on io_sq_thread to do polling
12493 * work, which can reduce cpu usage and uring_lock contention.
12495 if (ctx->flags & IORING_SETUP_IOPOLL &&
12496 !(ctx->flags & IORING_SETUP_SQPOLL))
12497 ctx->syscall_iopoll = 1;
12499 ctx->compat = in_compat_syscall();
12500 if (!capable(CAP_IPC_LOCK))
12501 ctx->user = get_uid(current_user());
12504 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12505 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12508 if (ctx->flags & IORING_SETUP_SQPOLL) {
12509 /* IPI related flags don't make sense with SQPOLL */
12510 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12511 IORING_SETUP_TASKRUN_FLAG))
12513 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12514 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12515 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12517 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12519 ctx->notify_method = TWA_SIGNAL;
12523 * This is just grabbed for accounting purposes. When a process exits,
12524 * the mm is exited and dropped before the files, hence we need to hang
12525 * on to this mm purely for the purposes of being able to unaccount
12526 * memory (locked/pinned vm). It's not used for anything else.
12528 mmgrab(current->mm);
12529 ctx->mm_account = current->mm;
12531 ret = io_allocate_scq_urings(ctx, p);
12535 ret = io_sq_offload_create(ctx, p);
12538 /* always set a rsrc node */
12539 ret = io_rsrc_node_switch_start(ctx);
12542 io_rsrc_node_switch(ctx, NULL);
12544 memset(&p->sq_off, 0, sizeof(p->sq_off));
12545 p->sq_off.head = offsetof(struct io_rings, sq.head);
12546 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12547 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12548 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12549 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12550 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12551 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12553 memset(&p->cq_off, 0, sizeof(p->cq_off));
12554 p->cq_off.head = offsetof(struct io_rings, cq.head);
12555 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12556 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12557 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12558 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12559 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12560 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12562 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12563 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12564 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12565 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12566 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12567 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12568 IORING_FEAT_LINKED_FILE;
12570 if (copy_to_user(params, p, sizeof(*p))) {
12575 file = io_uring_get_file(ctx);
12576 if (IS_ERR(file)) {
12577 ret = PTR_ERR(file);
12582 * Install ring fd as the very last thing, so we don't risk someone
12583 * having closed it before we finish setup
12585 ret = io_uring_install_fd(ctx, file);
12587 /* fput will clean it up */
12592 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12595 io_ring_ctx_wait_and_kill(ctx);
12600 * Sets up an aio uring context, and returns the fd. Applications asks for a
12601 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12602 * params structure passed in.
12604 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12606 struct io_uring_params p;
12609 if (copy_from_user(&p, params, sizeof(p)))
12611 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12616 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12617 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12618 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12619 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12620 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12621 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12624 return io_uring_create(entries, &p, params);
12627 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12628 struct io_uring_params __user *, params)
12630 return io_uring_setup(entries, params);
12633 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12636 struct io_uring_probe *p;
12640 size = struct_size(p, ops, nr_args);
12641 if (size == SIZE_MAX)
12643 p = kzalloc(size, GFP_KERNEL);
12648 if (copy_from_user(p, arg, size))
12651 if (memchr_inv(p, 0, size))
12654 p->last_op = IORING_OP_LAST - 1;
12655 if (nr_args > IORING_OP_LAST)
12656 nr_args = IORING_OP_LAST;
12658 for (i = 0; i < nr_args; i++) {
12660 if (!io_op_defs[i].not_supported)
12661 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12666 if (copy_to_user(arg, p, size))
12673 static int io_register_personality(struct io_ring_ctx *ctx)
12675 const struct cred *creds;
12679 creds = get_current_cred();
12681 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12682 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12690 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12691 void __user *arg, unsigned int nr_args)
12693 struct io_uring_restriction *res;
12697 /* Restrictions allowed only if rings started disabled */
12698 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12701 /* We allow only a single restrictions registration */
12702 if (ctx->restrictions.registered)
12705 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12708 size = array_size(nr_args, sizeof(*res));
12709 if (size == SIZE_MAX)
12712 res = memdup_user(arg, size);
12714 return PTR_ERR(res);
12718 for (i = 0; i < nr_args; i++) {
12719 switch (res[i].opcode) {
12720 case IORING_RESTRICTION_REGISTER_OP:
12721 if (res[i].register_op >= IORING_REGISTER_LAST) {
12726 __set_bit(res[i].register_op,
12727 ctx->restrictions.register_op);
12729 case IORING_RESTRICTION_SQE_OP:
12730 if (res[i].sqe_op >= IORING_OP_LAST) {
12735 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12737 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12738 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12740 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12741 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12750 /* Reset all restrictions if an error happened */
12752 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12754 ctx->restrictions.registered = true;
12760 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12762 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12765 if (ctx->restrictions.registered)
12766 ctx->restricted = 1;
12768 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12769 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12770 wake_up(&ctx->sq_data->wait);
12774 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12775 struct io_uring_rsrc_update2 *up,
12781 if (check_add_overflow(up->offset, nr_args, &tmp))
12783 err = io_rsrc_node_switch_start(ctx);
12788 case IORING_RSRC_FILE:
12789 return __io_sqe_files_update(ctx, up, nr_args);
12790 case IORING_RSRC_BUFFER:
12791 return __io_sqe_buffers_update(ctx, up, nr_args);
12796 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12799 struct io_uring_rsrc_update2 up;
12803 memset(&up, 0, sizeof(up));
12804 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12806 if (up.resv || up.resv2)
12808 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12811 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12812 unsigned size, unsigned type)
12814 struct io_uring_rsrc_update2 up;
12816 if (size != sizeof(up))
12818 if (copy_from_user(&up, arg, sizeof(up)))
12820 if (!up.nr || up.resv || up.resv2)
12822 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12825 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12826 unsigned int size, unsigned int type)
12828 struct io_uring_rsrc_register rr;
12830 /* keep it extendible */
12831 if (size != sizeof(rr))
12834 memset(&rr, 0, sizeof(rr));
12835 if (copy_from_user(&rr, arg, size))
12837 if (!rr.nr || rr.resv2)
12839 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12843 case IORING_RSRC_FILE:
12844 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12846 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12847 rr.nr, u64_to_user_ptr(rr.tags));
12848 case IORING_RSRC_BUFFER:
12849 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12851 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12852 rr.nr, u64_to_user_ptr(rr.tags));
12857 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12858 void __user *arg, unsigned len)
12860 struct io_uring_task *tctx = current->io_uring;
12861 cpumask_var_t new_mask;
12864 if (!tctx || !tctx->io_wq)
12867 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12870 cpumask_clear(new_mask);
12871 if (len > cpumask_size())
12872 len = cpumask_size();
12874 if (in_compat_syscall()) {
12875 ret = compat_get_bitmap(cpumask_bits(new_mask),
12876 (const compat_ulong_t __user *)arg,
12877 len * 8 /* CHAR_BIT */);
12879 ret = copy_from_user(new_mask, arg, len);
12883 free_cpumask_var(new_mask);
12887 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12888 free_cpumask_var(new_mask);
12892 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12894 struct io_uring_task *tctx = current->io_uring;
12896 if (!tctx || !tctx->io_wq)
12899 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12902 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12904 __must_hold(&ctx->uring_lock)
12906 struct io_tctx_node *node;
12907 struct io_uring_task *tctx = NULL;
12908 struct io_sq_data *sqd = NULL;
12909 __u32 new_count[2];
12912 if (copy_from_user(new_count, arg, sizeof(new_count)))
12914 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12915 if (new_count[i] > INT_MAX)
12918 if (ctx->flags & IORING_SETUP_SQPOLL) {
12919 sqd = ctx->sq_data;
12922 * Observe the correct sqd->lock -> ctx->uring_lock
12923 * ordering. Fine to drop uring_lock here, we hold
12924 * a ref to the ctx.
12926 refcount_inc(&sqd->refs);
12927 mutex_unlock(&ctx->uring_lock);
12928 mutex_lock(&sqd->lock);
12929 mutex_lock(&ctx->uring_lock);
12931 tctx = sqd->thread->io_uring;
12934 tctx = current->io_uring;
12937 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12939 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12941 ctx->iowq_limits[i] = new_count[i];
12942 ctx->iowq_limits_set = true;
12944 if (tctx && tctx->io_wq) {
12945 ret = io_wq_max_workers(tctx->io_wq, new_count);
12949 memset(new_count, 0, sizeof(new_count));
12953 mutex_unlock(&sqd->lock);
12954 io_put_sq_data(sqd);
12957 if (copy_to_user(arg, new_count, sizeof(new_count)))
12960 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12964 /* now propagate the restriction to all registered users */
12965 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12966 struct io_uring_task *tctx = node->task->io_uring;
12968 if (WARN_ON_ONCE(!tctx->io_wq))
12971 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12972 new_count[i] = ctx->iowq_limits[i];
12973 /* ignore errors, it always returns zero anyway */
12974 (void)io_wq_max_workers(tctx->io_wq, new_count);
12979 mutex_unlock(&sqd->lock);
12980 io_put_sq_data(sqd);
12985 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12987 struct io_uring_buf_ring *br;
12988 struct io_uring_buf_reg reg;
12989 struct io_buffer_list *bl;
12990 struct page **pages;
12993 if (copy_from_user(®, arg, sizeof(reg)))
12996 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12998 if (!reg.ring_addr)
13000 if (reg.ring_addr & ~PAGE_MASK)
13002 if (!is_power_of_2(reg.ring_entries))
13005 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
13006 int ret = io_init_bl_list(ctx);
13011 bl = io_buffer_get_list(ctx, reg.bgid);
13013 /* if mapped buffer ring OR classic exists, don't allow */
13014 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
13017 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
13022 pages = io_pin_pages(reg.ring_addr,
13023 struct_size(br, bufs, reg.ring_entries),
13025 if (IS_ERR(pages)) {
13027 return PTR_ERR(pages);
13030 br = page_address(pages[0]);
13031 bl->buf_pages = pages;
13032 bl->buf_nr_pages = nr_pages;
13033 bl->nr_entries = reg.ring_entries;
13035 bl->mask = reg.ring_entries - 1;
13036 io_buffer_add_list(ctx, bl, reg.bgid);
13040 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
13042 struct io_uring_buf_reg reg;
13043 struct io_buffer_list *bl;
13045 if (copy_from_user(®, arg, sizeof(reg)))
13047 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
13050 bl = io_buffer_get_list(ctx, reg.bgid);
13053 if (!bl->buf_nr_pages)
13056 __io_remove_buffers(ctx, bl, -1U);
13057 if (bl->bgid >= BGID_ARRAY) {
13058 xa_erase(&ctx->io_bl_xa, bl->bgid);
13064 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
13065 void __user *arg, unsigned nr_args)
13066 __releases(ctx->uring_lock)
13067 __acquires(ctx->uring_lock)
13072 * We're inside the ring mutex, if the ref is already dying, then
13073 * someone else killed the ctx or is already going through
13074 * io_uring_register().
13076 if (percpu_ref_is_dying(&ctx->refs))
13079 if (ctx->restricted) {
13080 if (opcode >= IORING_REGISTER_LAST)
13082 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
13083 if (!test_bit(opcode, ctx->restrictions.register_op))
13088 case IORING_REGISTER_BUFFERS:
13092 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
13094 case IORING_UNREGISTER_BUFFERS:
13096 if (arg || nr_args)
13098 ret = io_sqe_buffers_unregister(ctx);
13100 case IORING_REGISTER_FILES:
13104 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
13106 case IORING_UNREGISTER_FILES:
13108 if (arg || nr_args)
13110 ret = io_sqe_files_unregister(ctx);
13112 case IORING_REGISTER_FILES_UPDATE:
13113 ret = io_register_files_update(ctx, arg, nr_args);
13115 case IORING_REGISTER_EVENTFD:
13119 ret = io_eventfd_register(ctx, arg, 0);
13121 case IORING_REGISTER_EVENTFD_ASYNC:
13125 ret = io_eventfd_register(ctx, arg, 1);
13127 case IORING_UNREGISTER_EVENTFD:
13129 if (arg || nr_args)
13131 ret = io_eventfd_unregister(ctx);
13133 case IORING_REGISTER_PROBE:
13135 if (!arg || nr_args > 256)
13137 ret = io_probe(ctx, arg, nr_args);
13139 case IORING_REGISTER_PERSONALITY:
13141 if (arg || nr_args)
13143 ret = io_register_personality(ctx);
13145 case IORING_UNREGISTER_PERSONALITY:
13149 ret = io_unregister_personality(ctx, nr_args);
13151 case IORING_REGISTER_ENABLE_RINGS:
13153 if (arg || nr_args)
13155 ret = io_register_enable_rings(ctx);
13157 case IORING_REGISTER_RESTRICTIONS:
13158 ret = io_register_restrictions(ctx, arg, nr_args);
13160 case IORING_REGISTER_FILES2:
13161 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
13163 case IORING_REGISTER_FILES_UPDATE2:
13164 ret = io_register_rsrc_update(ctx, arg, nr_args,
13167 case IORING_REGISTER_BUFFERS2:
13168 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
13170 case IORING_REGISTER_BUFFERS_UPDATE:
13171 ret = io_register_rsrc_update(ctx, arg, nr_args,
13172 IORING_RSRC_BUFFER);
13174 case IORING_REGISTER_IOWQ_AFF:
13176 if (!arg || !nr_args)
13178 ret = io_register_iowq_aff(ctx, arg, nr_args);
13180 case IORING_UNREGISTER_IOWQ_AFF:
13182 if (arg || nr_args)
13184 ret = io_unregister_iowq_aff(ctx);
13186 case IORING_REGISTER_IOWQ_MAX_WORKERS:
13188 if (!arg || nr_args != 2)
13190 ret = io_register_iowq_max_workers(ctx, arg);
13192 case IORING_REGISTER_RING_FDS:
13193 ret = io_ringfd_register(ctx, arg, nr_args);
13195 case IORING_UNREGISTER_RING_FDS:
13196 ret = io_ringfd_unregister(ctx, arg, nr_args);
13198 case IORING_REGISTER_PBUF_RING:
13200 if (!arg || nr_args != 1)
13202 ret = io_register_pbuf_ring(ctx, arg);
13204 case IORING_UNREGISTER_PBUF_RING:
13206 if (!arg || nr_args != 1)
13208 ret = io_unregister_pbuf_ring(ctx, arg);
13218 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
13219 void __user *, arg, unsigned int, nr_args)
13221 struct io_ring_ctx *ctx;
13230 if (f.file->f_op != &io_uring_fops)
13233 ctx = f.file->private_data;
13235 io_run_task_work();
13237 mutex_lock(&ctx->uring_lock);
13238 ret = __io_uring_register(ctx, opcode, arg, nr_args);
13239 mutex_unlock(&ctx->uring_lock);
13240 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
13246 static int __init io_uring_init(void)
13248 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13249 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13250 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13253 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13254 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13255 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13256 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13257 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13258 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13259 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13260 BUILD_BUG_SQE_ELEM(8, __u64, off);
13261 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13262 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13263 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13264 BUILD_BUG_SQE_ELEM(24, __u32, len);
13265 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13266 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13267 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13268 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13269 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13270 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13271 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13272 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13273 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13274 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13275 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13276 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13277 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13278 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13279 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13280 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13281 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13282 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13283 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13284 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13285 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13286 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13288 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13289 sizeof(struct io_uring_rsrc_update));
13290 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13291 sizeof(struct io_uring_rsrc_update2));
13293 /* ->buf_index is u16 */
13294 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13295 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13296 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13297 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13298 offsetof(struct io_uring_buf_ring, tail));
13300 /* should fit into one byte */
13301 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13302 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13303 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13305 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13306 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13308 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13310 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13312 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13316 __initcall(io_uring_init);