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 << 15)
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_CREDS | REQ_F_ASYNC_DATA)
117 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
120 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
123 u32 head ____cacheline_aligned_in_smp;
124 u32 tail ____cacheline_aligned_in_smp;
128 * This data is shared with the application through the mmap at offsets
129 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
131 * The offsets to the member fields are published through struct
132 * io_sqring_offsets when calling io_uring_setup.
136 * Head and tail offsets into the ring; the offsets need to be
137 * masked to get valid indices.
139 * The kernel controls head of the sq ring and the tail of the cq ring,
140 * and the application controls tail of the sq ring and the head of the
143 struct io_uring sq, cq;
145 * Bitmasks to apply to head and tail offsets (constant, equals
148 u32 sq_ring_mask, cq_ring_mask;
149 /* Ring sizes (constant, power of 2) */
150 u32 sq_ring_entries, cq_ring_entries;
152 * Number of invalid entries dropped by the kernel due to
153 * invalid index stored in array
155 * Written by the kernel, shouldn't be modified by the
156 * application (i.e. get number of "new events" by comparing to
159 * After a new SQ head value was read by the application this
160 * counter includes all submissions that were dropped reaching
161 * the new SQ head (and possibly more).
167 * Written by the kernel, shouldn't be modified by the
170 * The application needs a full memory barrier before checking
171 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
177 * Written by the application, shouldn't be modified by the
182 * Number of completion events lost because the queue was full;
183 * this should be avoided by the application by making sure
184 * there are not more requests pending than there is space in
185 * the completion queue.
187 * Written by the kernel, shouldn't be modified by the
188 * application (i.e. get number of "new events" by comparing to
191 * As completion events come in out of order this counter is not
192 * ordered with any other data.
196 * Ring buffer of completion events.
198 * The kernel writes completion events fresh every time they are
199 * produced, so the application is allowed to modify pending
202 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
205 struct io_mapped_ubuf {
208 unsigned int nr_bvecs;
209 unsigned long acct_pages;
210 struct bio_vec bvec[];
215 struct io_overflow_cqe {
216 struct list_head list;
217 struct io_uring_cqe cqe;
221 * FFS_SCM is only available on 64-bit archs, for 32-bit we just define it as 0
222 * and define IO_URING_SCM_ALL. For this case, we use SCM for all files as we
223 * can't safely always dereference the file when the task has exited and ring
224 * cleanup is done. If a file is tracked and part of SCM, then unix gc on
225 * process exit may reap it before __io_sqe_files_unregister() is run.
227 #define FFS_NOWAIT 0x1UL
228 #define FFS_ISREG 0x2UL
229 #if defined(CONFIG_64BIT)
230 #define FFS_SCM 0x4UL
232 #define IO_URING_SCM_ALL
233 #define FFS_SCM 0x0UL
235 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG|FFS_SCM)
237 struct io_fixed_file {
238 /* file * with additional FFS_* flags */
239 unsigned long file_ptr;
243 struct list_head list;
248 struct io_mapped_ubuf *buf;
252 struct io_file_table {
253 struct io_fixed_file *files;
256 struct io_rsrc_node {
257 struct percpu_ref refs;
258 struct list_head node;
259 struct list_head rsrc_list;
260 struct io_rsrc_data *rsrc_data;
261 struct llist_node llist;
265 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
267 struct io_rsrc_data {
268 struct io_ring_ctx *ctx;
274 struct completion done;
278 struct io_buffer_list {
279 struct list_head buf_list;
284 struct list_head list;
291 struct io_restriction {
292 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
293 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
294 u8 sqe_flags_allowed;
295 u8 sqe_flags_required;
300 IO_SQ_THREAD_SHOULD_STOP = 0,
301 IO_SQ_THREAD_SHOULD_PARK,
306 atomic_t park_pending;
309 /* ctx's that are using this sqd */
310 struct list_head ctx_list;
312 struct task_struct *thread;
313 struct wait_queue_head wait;
315 unsigned sq_thread_idle;
321 struct completion exited;
324 #define IO_COMPL_BATCH 32
325 #define IO_REQ_CACHE_SIZE 32
326 #define IO_REQ_ALLOC_BATCH 8
328 struct io_submit_link {
329 struct io_kiocb *head;
330 struct io_kiocb *last;
333 struct io_submit_state {
334 /* inline/task_work completion list, under ->uring_lock */
335 struct io_wq_work_node free_list;
336 /* batch completion logic */
337 struct io_wq_work_list compl_reqs;
338 struct io_submit_link link;
343 unsigned short submit_nr;
344 struct blk_plug plug;
348 struct eventfd_ctx *cq_ev_fd;
349 unsigned int eventfd_async: 1;
353 #define BGID_ARRAY 64
356 /* const or read-mostly hot data */
358 struct percpu_ref refs;
360 struct io_rings *rings;
362 enum task_work_notify_mode notify_method;
363 unsigned int compat: 1;
364 unsigned int drain_next: 1;
365 unsigned int restricted: 1;
366 unsigned int off_timeout_used: 1;
367 unsigned int drain_active: 1;
368 unsigned int drain_disabled: 1;
369 unsigned int has_evfd: 1;
370 unsigned int syscall_iopoll: 1;
371 } ____cacheline_aligned_in_smp;
373 /* submission data */
375 struct mutex uring_lock;
378 * Ring buffer of indices into array of io_uring_sqe, which is
379 * mmapped by the application using the IORING_OFF_SQES offset.
381 * This indirection could e.g. be used to assign fixed
382 * io_uring_sqe entries to operations and only submit them to
383 * the queue when needed.
385 * The kernel modifies neither the indices array nor the entries
389 struct io_uring_sqe *sq_sqes;
390 unsigned cached_sq_head;
392 struct list_head defer_list;
395 * Fixed resources fast path, should be accessed only under
396 * uring_lock, and updated through io_uring_register(2)
398 struct io_rsrc_node *rsrc_node;
399 int rsrc_cached_refs;
401 struct io_file_table file_table;
402 unsigned nr_user_files;
403 unsigned nr_user_bufs;
404 struct io_mapped_ubuf **user_bufs;
406 struct io_submit_state submit_state;
408 struct io_buffer_list *io_bl;
409 struct xarray io_bl_xa;
410 struct list_head io_buffers_cache;
412 struct list_head timeout_list;
413 struct list_head ltimeout_list;
414 struct list_head cq_overflow_list;
415 struct list_head apoll_cache;
416 struct xarray personalities;
418 unsigned sq_thread_idle;
419 } ____cacheline_aligned_in_smp;
421 /* IRQ completion list, under ->completion_lock */
422 struct io_wq_work_list locked_free_list;
423 unsigned int locked_free_nr;
425 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
426 struct io_sq_data *sq_data; /* if using sq thread polling */
428 struct wait_queue_head sqo_sq_wait;
429 struct list_head sqd_list;
431 unsigned long check_cq;
435 * We cache a range of free CQEs we can use, once exhausted it
436 * should go through a slower range setup, see __io_get_cqe()
438 struct io_uring_cqe *cqe_cached;
439 struct io_uring_cqe *cqe_sentinel;
441 unsigned cached_cq_tail;
443 struct io_ev_fd __rcu *io_ev_fd;
444 struct wait_queue_head cq_wait;
446 atomic_t cq_timeouts;
447 unsigned cq_last_tm_flush;
448 } ____cacheline_aligned_in_smp;
451 spinlock_t completion_lock;
453 spinlock_t timeout_lock;
456 * ->iopoll_list is protected by the ctx->uring_lock for
457 * io_uring instances that don't use IORING_SETUP_SQPOLL.
458 * For SQPOLL, only the single threaded io_sq_thread() will
459 * manipulate the list, hence no extra locking is needed there.
461 struct io_wq_work_list iopoll_list;
462 struct hlist_head *cancel_hash;
463 unsigned cancel_hash_bits;
464 bool poll_multi_queue;
466 struct list_head io_buffers_comp;
467 } ____cacheline_aligned_in_smp;
469 struct io_restriction restrictions;
471 /* slow path rsrc auxilary data, used by update/register */
473 struct io_rsrc_node *rsrc_backup_node;
474 struct io_mapped_ubuf *dummy_ubuf;
475 struct io_rsrc_data *file_data;
476 struct io_rsrc_data *buf_data;
478 struct delayed_work rsrc_put_work;
479 struct llist_head rsrc_put_llist;
480 struct list_head rsrc_ref_list;
481 spinlock_t rsrc_ref_lock;
483 struct list_head io_buffers_pages;
486 /* Keep this last, we don't need it for the fast path */
488 #if defined(CONFIG_UNIX)
489 struct socket *ring_sock;
491 /* hashed buffered write serialization */
492 struct io_wq_hash *hash_map;
494 /* Only used for accounting purposes */
495 struct user_struct *user;
496 struct mm_struct *mm_account;
498 /* ctx exit and cancelation */
499 struct llist_head fallback_llist;
500 struct delayed_work fallback_work;
501 struct work_struct exit_work;
502 struct list_head tctx_list;
503 struct completion ref_comp;
505 bool iowq_limits_set;
510 * Arbitrary limit, can be raised if need be
512 #define IO_RINGFD_REG_MAX 16
514 struct io_uring_task {
515 /* submission side */
518 struct wait_queue_head wait;
519 const struct io_ring_ctx *last;
521 struct percpu_counter inflight;
524 spinlock_t task_lock;
525 struct io_wq_work_list task_list;
526 struct io_wq_work_list prior_task_list;
527 struct callback_head task_work;
528 struct file **registered_rings;
533 * First field must be the file pointer in all the
534 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
536 struct io_poll_iocb {
538 struct wait_queue_head *head;
540 struct wait_queue_entry wait;
543 struct io_poll_update {
549 bool update_user_data;
558 struct io_timeout_data {
559 struct io_kiocb *req;
560 struct hrtimer timer;
561 struct timespec64 ts;
562 enum hrtimer_mode mode;
568 struct sockaddr __user *addr;
569 int __user *addr_len;
572 unsigned long nofile;
582 unsigned long nofile;
604 struct list_head list;
605 /* head of the link, used by linked timeouts only */
606 struct io_kiocb *head;
607 /* for linked completions */
608 struct io_kiocb *prev;
611 struct io_timeout_rem {
616 struct timespec64 ts;
622 /* NOTE: kiocb has the file as the first member, so don't do it here */
631 struct sockaddr __user *addr;
638 struct compat_msghdr __user *umsg_compat;
639 struct user_msghdr __user *umsg;
652 struct filename *filename;
654 unsigned long nofile;
657 struct io_rsrc_update {
683 struct epoll_event event;
687 struct file *file_out;
695 struct io_provide_buf {
709 struct filename *filename;
710 struct statx __user *buffer;
722 struct filename *oldpath;
723 struct filename *newpath;
731 struct filename *filename;
738 struct filename *filename;
744 struct filename *oldpath;
745 struct filename *newpath;
752 struct filename *oldpath;
753 struct filename *newpath;
769 struct io_async_connect {
770 struct sockaddr_storage address;
773 struct io_async_msghdr {
774 struct iovec fast_iov[UIO_FASTIOV];
775 /* points to an allocated iov, if NULL we use fast_iov instead */
776 struct iovec *free_iov;
777 struct sockaddr __user *uaddr;
779 struct sockaddr_storage addr;
783 struct iov_iter iter;
784 struct iov_iter_state iter_state;
785 struct iovec fast_iov[UIO_FASTIOV];
789 struct io_rw_state s;
790 const struct iovec *free_iovec;
792 struct wait_page_queue wpq;
797 struct xattr_ctx ctx;
798 struct filename *filename;
802 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
803 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
804 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
805 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
806 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
807 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
808 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
810 /* first byte is taken by user flags, shift it to not overlap */
815 REQ_F_LINK_TIMEOUT_BIT,
816 REQ_F_NEED_CLEANUP_BIT,
818 REQ_F_BUFFER_SELECTED_BIT,
819 REQ_F_COMPLETE_INLINE_BIT,
823 REQ_F_ARM_LTIMEOUT_BIT,
824 REQ_F_ASYNC_DATA_BIT,
825 REQ_F_SKIP_LINK_CQES_BIT,
826 REQ_F_SINGLE_POLL_BIT,
827 REQ_F_DOUBLE_POLL_BIT,
828 REQ_F_PARTIAL_IO_BIT,
829 /* keep async read/write and isreg together and in order */
830 REQ_F_SUPPORT_NOWAIT_BIT,
833 /* not a real bit, just to check we're not overflowing the space */
839 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
840 /* drain existing IO first */
841 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
843 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
844 /* doesn't sever on completion < 0 */
845 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
847 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
848 /* IOSQE_BUFFER_SELECT */
849 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
850 /* IOSQE_CQE_SKIP_SUCCESS */
851 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
853 /* fail rest of links */
854 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
855 /* on inflight list, should be cancelled and waited on exit reliably */
856 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
857 /* read/write uses file position */
858 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
859 /* must not punt to workers */
860 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
861 /* has or had linked timeout */
862 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
864 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
865 /* already went through poll handler */
866 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
867 /* buffer already selected */
868 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
869 /* completion is deferred through io_comp_state */
870 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
871 /* caller should reissue async */
872 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
873 /* supports async reads/writes */
874 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
876 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
877 /* has creds assigned */
878 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
879 /* skip refcounting if not set */
880 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
881 /* there is a linked timeout that has to be armed */
882 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
883 /* ->async_data allocated */
884 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
885 /* don't post CQEs while failing linked requests */
886 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
887 /* single poll may be active */
888 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
889 /* double poll may active */
890 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
891 /* request has already done partial IO */
892 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
896 struct io_poll_iocb poll;
897 struct io_poll_iocb *double_poll;
900 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
902 struct io_task_work {
904 struct io_wq_work_node node;
905 struct llist_node fallback_node;
907 io_req_tw_func_t func;
911 IORING_RSRC_FILE = 0,
912 IORING_RSRC_BUFFER = 1,
918 /* fd initially, then cflags for completion */
926 IO_CHECK_CQ_OVERFLOW_BIT,
927 IO_CHECK_CQ_DROPPED_BIT,
931 * NOTE! Each of the iocb union members has the file pointer
932 * as the first entry in their struct definition. So you can
933 * access the file pointer through any of the sub-structs,
934 * or directly as just 'file' in this struct.
940 struct io_poll_iocb poll;
941 struct io_poll_update poll_update;
942 struct io_accept accept;
944 struct io_cancel cancel;
945 struct io_timeout timeout;
946 struct io_timeout_rem timeout_rem;
947 struct io_connect connect;
948 struct io_sr_msg sr_msg;
950 struct io_close close;
951 struct io_rsrc_update rsrc_update;
952 struct io_fadvise fadvise;
953 struct io_madvise madvise;
954 struct io_epoll epoll;
955 struct io_splice splice;
956 struct io_provide_buf pbuf;
957 struct io_statx statx;
958 struct io_shutdown shutdown;
959 struct io_rename rename;
960 struct io_unlink unlink;
961 struct io_mkdir mkdir;
962 struct io_symlink symlink;
963 struct io_hardlink hardlink;
965 struct io_xattr xattr;
966 struct io_socket sock;
968 struct io_uring_cmd uring_cmd;
972 /* polled IO has completed */
975 * Can be either a fixed buffer index, or used with provided buffers.
976 * For the latter, before issue it points to the buffer group ID,
977 * and after selection it points to the buffer ID itself.
984 struct io_ring_ctx *ctx;
985 struct task_struct *task;
987 struct io_rsrc_node *rsrc_node;
990 /* store used ubuf, so we can prevent reloading */
991 struct io_mapped_ubuf *imu;
993 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
994 struct io_buffer *kbuf;
998 /* used by request caches, completion batching and iopoll */
999 struct io_wq_work_node comp_list;
1000 /* cache ->apoll->events */
1005 struct io_task_work io_task_work;
1006 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1008 struct hlist_node hash_node;
1014 /* internal polling, see IORING_FEAT_FAST_POLL */
1015 struct async_poll *apoll;
1016 /* opcode allocated if it needs to store data for async defer */
1018 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1019 struct io_kiocb *link;
1020 /* custom credentials, valid IFF REQ_F_CREDS is set */
1021 const struct cred *creds;
1022 struct io_wq_work work;
1025 struct io_tctx_node {
1026 struct list_head ctx_node;
1027 struct task_struct *task;
1028 struct io_ring_ctx *ctx;
1031 struct io_defer_entry {
1032 struct list_head list;
1033 struct io_kiocb *req;
1037 struct io_cancel_data {
1038 struct io_ring_ctx *ctx;
1048 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
1049 * the following sqe if SQE128 is used.
1051 #define uring_cmd_pdu_size(is_sqe128) \
1052 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
1053 offsetof(struct io_uring_sqe, cmd))
1056 /* needs req->file assigned */
1057 unsigned needs_file : 1;
1058 /* should block plug */
1060 /* hash wq insertion if file is a regular file */
1061 unsigned hash_reg_file : 1;
1062 /* unbound wq insertion if file is a non-regular file */
1063 unsigned unbound_nonreg_file : 1;
1064 /* set if opcode supports polled "wait" */
1065 unsigned pollin : 1;
1066 unsigned pollout : 1;
1067 unsigned poll_exclusive : 1;
1068 /* op supports buffer selection */
1069 unsigned buffer_select : 1;
1070 /* do prep async if is going to be punted */
1071 unsigned needs_async_setup : 1;
1072 /* opcode is not supported by this kernel */
1073 unsigned not_supported : 1;
1075 unsigned audit_skip : 1;
1076 /* supports ioprio */
1077 unsigned ioprio : 1;
1078 /* supports iopoll */
1079 unsigned iopoll : 1;
1080 /* size of async data needed, if any */
1081 unsigned short async_size;
1084 static const struct io_op_def io_op_defs[] = {
1089 [IORING_OP_READV] = {
1091 .unbound_nonreg_file = 1,
1094 .needs_async_setup = 1,
1099 .async_size = sizeof(struct io_async_rw),
1101 [IORING_OP_WRITEV] = {
1104 .unbound_nonreg_file = 1,
1106 .needs_async_setup = 1,
1111 .async_size = sizeof(struct io_async_rw),
1113 [IORING_OP_FSYNC] = {
1117 [IORING_OP_READ_FIXED] = {
1119 .unbound_nonreg_file = 1,
1125 .async_size = sizeof(struct io_async_rw),
1127 [IORING_OP_WRITE_FIXED] = {
1130 .unbound_nonreg_file = 1,
1136 .async_size = sizeof(struct io_async_rw),
1138 [IORING_OP_POLL_ADD] = {
1140 .unbound_nonreg_file = 1,
1143 [IORING_OP_POLL_REMOVE] = {
1146 [IORING_OP_SYNC_FILE_RANGE] = {
1150 [IORING_OP_SENDMSG] = {
1152 .unbound_nonreg_file = 1,
1154 .needs_async_setup = 1,
1155 .async_size = sizeof(struct io_async_msghdr),
1157 [IORING_OP_RECVMSG] = {
1159 .unbound_nonreg_file = 1,
1162 .needs_async_setup = 1,
1163 .async_size = sizeof(struct io_async_msghdr),
1165 [IORING_OP_TIMEOUT] = {
1167 .async_size = sizeof(struct io_timeout_data),
1169 [IORING_OP_TIMEOUT_REMOVE] = {
1170 /* used by timeout updates' prep() */
1173 [IORING_OP_ACCEPT] = {
1175 .unbound_nonreg_file = 1,
1177 .poll_exclusive = 1,
1179 [IORING_OP_ASYNC_CANCEL] = {
1182 [IORING_OP_LINK_TIMEOUT] = {
1184 .async_size = sizeof(struct io_timeout_data),
1186 [IORING_OP_CONNECT] = {
1188 .unbound_nonreg_file = 1,
1190 .needs_async_setup = 1,
1191 .async_size = sizeof(struct io_async_connect),
1193 [IORING_OP_FALLOCATE] = {
1196 [IORING_OP_OPENAT] = {},
1197 [IORING_OP_CLOSE] = {},
1198 [IORING_OP_FILES_UPDATE] = {
1202 [IORING_OP_STATX] = {
1205 [IORING_OP_READ] = {
1207 .unbound_nonreg_file = 1,
1214 .async_size = sizeof(struct io_async_rw),
1216 [IORING_OP_WRITE] = {
1219 .unbound_nonreg_file = 1,
1225 .async_size = sizeof(struct io_async_rw),
1227 [IORING_OP_FADVISE] = {
1231 [IORING_OP_MADVISE] = {},
1232 [IORING_OP_SEND] = {
1234 .unbound_nonreg_file = 1,
1238 [IORING_OP_RECV] = {
1240 .unbound_nonreg_file = 1,
1245 [IORING_OP_OPENAT2] = {
1247 [IORING_OP_EPOLL_CTL] = {
1248 .unbound_nonreg_file = 1,
1251 [IORING_OP_SPLICE] = {
1254 .unbound_nonreg_file = 1,
1257 [IORING_OP_PROVIDE_BUFFERS] = {
1261 [IORING_OP_REMOVE_BUFFERS] = {
1268 .unbound_nonreg_file = 1,
1271 [IORING_OP_SHUTDOWN] = {
1274 [IORING_OP_RENAMEAT] = {},
1275 [IORING_OP_UNLINKAT] = {},
1276 [IORING_OP_MKDIRAT] = {},
1277 [IORING_OP_SYMLINKAT] = {},
1278 [IORING_OP_LINKAT] = {},
1279 [IORING_OP_MSG_RING] = {
1283 [IORING_OP_FSETXATTR] = {
1286 [IORING_OP_SETXATTR] = {},
1287 [IORING_OP_FGETXATTR] = {
1290 [IORING_OP_GETXATTR] = {},
1291 [IORING_OP_SOCKET] = {
1294 [IORING_OP_URING_CMD] = {
1297 .needs_async_setup = 1,
1298 .async_size = uring_cmd_pdu_size(1),
1302 /* requests with any of those set should undergo io_disarm_next() */
1303 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1304 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1306 static bool io_disarm_next(struct io_kiocb *req);
1307 static void io_uring_del_tctx_node(unsigned long index);
1308 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1309 struct task_struct *task,
1311 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1313 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1314 static void io_dismantle_req(struct io_kiocb *req);
1315 static void io_queue_linked_timeout(struct io_kiocb *req);
1316 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1317 struct io_uring_rsrc_update2 *up,
1319 static void io_clean_op(struct io_kiocb *req);
1320 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1321 unsigned issue_flags);
1322 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1323 static void io_drop_inflight_file(struct io_kiocb *req);
1324 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1325 static void io_queue_sqe(struct io_kiocb *req);
1326 static void io_rsrc_put_work(struct work_struct *work);
1328 static void io_req_task_queue(struct io_kiocb *req);
1329 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1330 static int io_req_prep_async(struct io_kiocb *req);
1332 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1333 unsigned int issue_flags, u32 slot_index);
1334 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1336 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1337 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1338 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1340 static struct kmem_cache *req_cachep;
1342 static const struct file_operations io_uring_fops;
1344 const char *io_uring_get_opcode(u8 opcode)
1346 switch ((enum io_uring_op)opcode) {
1349 case IORING_OP_READV:
1351 case IORING_OP_WRITEV:
1353 case IORING_OP_FSYNC:
1355 case IORING_OP_READ_FIXED:
1356 return "READ_FIXED";
1357 case IORING_OP_WRITE_FIXED:
1358 return "WRITE_FIXED";
1359 case IORING_OP_POLL_ADD:
1361 case IORING_OP_POLL_REMOVE:
1362 return "POLL_REMOVE";
1363 case IORING_OP_SYNC_FILE_RANGE:
1364 return "SYNC_FILE_RANGE";
1365 case IORING_OP_SENDMSG:
1367 case IORING_OP_RECVMSG:
1369 case IORING_OP_TIMEOUT:
1371 case IORING_OP_TIMEOUT_REMOVE:
1372 return "TIMEOUT_REMOVE";
1373 case IORING_OP_ACCEPT:
1375 case IORING_OP_ASYNC_CANCEL:
1376 return "ASYNC_CANCEL";
1377 case IORING_OP_LINK_TIMEOUT:
1378 return "LINK_TIMEOUT";
1379 case IORING_OP_CONNECT:
1381 case IORING_OP_FALLOCATE:
1383 case IORING_OP_OPENAT:
1385 case IORING_OP_CLOSE:
1387 case IORING_OP_FILES_UPDATE:
1388 return "FILES_UPDATE";
1389 case IORING_OP_STATX:
1391 case IORING_OP_READ:
1393 case IORING_OP_WRITE:
1395 case IORING_OP_FADVISE:
1397 case IORING_OP_MADVISE:
1399 case IORING_OP_SEND:
1401 case IORING_OP_RECV:
1403 case IORING_OP_OPENAT2:
1405 case IORING_OP_EPOLL_CTL:
1407 case IORING_OP_SPLICE:
1409 case IORING_OP_PROVIDE_BUFFERS:
1410 return "PROVIDE_BUFFERS";
1411 case IORING_OP_REMOVE_BUFFERS:
1412 return "REMOVE_BUFFERS";
1415 case IORING_OP_SHUTDOWN:
1417 case IORING_OP_RENAMEAT:
1419 case IORING_OP_UNLINKAT:
1421 case IORING_OP_MKDIRAT:
1423 case IORING_OP_SYMLINKAT:
1425 case IORING_OP_LINKAT:
1427 case IORING_OP_MSG_RING:
1429 case IORING_OP_FSETXATTR:
1431 case IORING_OP_SETXATTR:
1433 case IORING_OP_FGETXATTR:
1435 case IORING_OP_GETXATTR:
1437 case IORING_OP_SOCKET:
1439 case IORING_OP_URING_CMD:
1441 case IORING_OP_LAST:
1447 struct sock *io_uring_get_socket(struct file *file)
1449 #if defined(CONFIG_UNIX)
1450 if (file->f_op == &io_uring_fops) {
1451 struct io_ring_ctx *ctx = file->private_data;
1453 return ctx->ring_sock->sk;
1458 EXPORT_SYMBOL(io_uring_get_socket);
1460 #if defined(CONFIG_UNIX)
1461 static inline bool io_file_need_scm(struct file *filp)
1463 #if defined(IO_URING_SCM_ALL)
1466 return !!unix_get_socket(filp);
1470 static inline bool io_file_need_scm(struct file *filp)
1476 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1478 lockdep_assert_held(&ctx->uring_lock);
1479 if (issue_flags & IO_URING_F_UNLOCKED)
1480 mutex_unlock(&ctx->uring_lock);
1483 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1486 * "Normal" inline submissions always hold the uring_lock, since we
1487 * grab it from the system call. Same is true for the SQPOLL offload.
1488 * The only exception is when we've detached the request and issue it
1489 * from an async worker thread, grab the lock for that case.
1491 if (issue_flags & IO_URING_F_UNLOCKED)
1492 mutex_lock(&ctx->uring_lock);
1493 lockdep_assert_held(&ctx->uring_lock);
1496 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1499 mutex_lock(&ctx->uring_lock);
1504 #define io_for_each_link(pos, head) \
1505 for (pos = (head); pos; pos = pos->link)
1508 * Shamelessly stolen from the mm implementation of page reference checking,
1509 * see commit f958d7b528b1 for details.
1511 #define req_ref_zero_or_close_to_overflow(req) \
1512 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1514 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1516 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1517 return atomic_inc_not_zero(&req->refs);
1520 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1522 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1525 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1526 return atomic_dec_and_test(&req->refs);
1529 static inline void req_ref_get(struct io_kiocb *req)
1531 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1532 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1533 atomic_inc(&req->refs);
1536 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1538 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1539 __io_submit_flush_completions(ctx);
1542 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1544 if (!(req->flags & REQ_F_REFCOUNT)) {
1545 req->flags |= REQ_F_REFCOUNT;
1546 atomic_set(&req->refs, nr);
1550 static inline void io_req_set_refcount(struct io_kiocb *req)
1552 __io_req_set_refcount(req, 1);
1555 #define IO_RSRC_REF_BATCH 100
1557 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1559 percpu_ref_put_many(&node->refs, nr);
1562 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1563 struct io_ring_ctx *ctx)
1564 __must_hold(&ctx->uring_lock)
1566 struct io_rsrc_node *node = req->rsrc_node;
1569 if (node == ctx->rsrc_node)
1570 ctx->rsrc_cached_refs++;
1572 io_rsrc_put_node(node, 1);
1576 static inline void io_req_put_rsrc(struct io_kiocb *req)
1579 io_rsrc_put_node(req->rsrc_node, 1);
1582 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1583 __must_hold(&ctx->uring_lock)
1585 if (ctx->rsrc_cached_refs) {
1586 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1587 ctx->rsrc_cached_refs = 0;
1591 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1592 __must_hold(&ctx->uring_lock)
1594 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1595 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1598 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1599 struct io_ring_ctx *ctx,
1600 unsigned int issue_flags)
1602 if (!req->rsrc_node) {
1603 req->rsrc_node = ctx->rsrc_node;
1605 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1606 lockdep_assert_held(&ctx->uring_lock);
1607 ctx->rsrc_cached_refs--;
1608 if (unlikely(ctx->rsrc_cached_refs < 0))
1609 io_rsrc_refs_refill(ctx);
1611 percpu_ref_get(&req->rsrc_node->refs);
1616 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1618 req->flags &= ~REQ_F_BUFFER_SELECTED;
1619 list_add(&req->kbuf->list, list);
1621 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1624 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1626 lockdep_assert_held(&req->ctx->completion_lock);
1628 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1630 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1633 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1634 unsigned issue_flags)
1636 unsigned int cflags;
1638 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1642 * We can add this buffer back to two lists:
1644 * 1) The io_buffers_cache list. This one is protected by the
1645 * ctx->uring_lock. If we already hold this lock, add back to this
1646 * list as we can grab it from issue as well.
1647 * 2) The io_buffers_comp list. This one is protected by the
1648 * ctx->completion_lock.
1650 * We migrate buffers from the comp_list to the issue cache list
1653 if (issue_flags & IO_URING_F_UNLOCKED) {
1654 struct io_ring_ctx *ctx = req->ctx;
1656 spin_lock(&ctx->completion_lock);
1657 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1658 spin_unlock(&ctx->completion_lock);
1660 lockdep_assert_held(&req->ctx->uring_lock);
1662 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1668 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1671 if (ctx->io_bl && bgid < BGID_ARRAY)
1672 return &ctx->io_bl[bgid];
1674 return xa_load(&ctx->io_bl_xa, bgid);
1677 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1679 struct io_ring_ctx *ctx = req->ctx;
1680 struct io_buffer_list *bl;
1681 struct io_buffer *buf;
1683 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1685 /* don't recycle if we already did IO to this buffer */
1686 if (req->flags & REQ_F_PARTIAL_IO)
1689 io_ring_submit_lock(ctx, issue_flags);
1692 bl = io_buffer_get_list(ctx, buf->bgid);
1693 list_add(&buf->list, &bl->buf_list);
1694 req->flags &= ~REQ_F_BUFFER_SELECTED;
1695 req->buf_index = buf->bgid;
1697 io_ring_submit_unlock(ctx, issue_flags);
1700 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1702 __must_hold(&req->ctx->timeout_lock)
1704 if (task && head->task != task)
1710 * As io_match_task() but protected against racing with linked timeouts.
1711 * User must not hold timeout_lock.
1713 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1716 if (task && head->task != task)
1721 static inline bool req_has_async_data(struct io_kiocb *req)
1723 return req->flags & REQ_F_ASYNC_DATA;
1726 static inline void req_set_fail(struct io_kiocb *req)
1728 req->flags |= REQ_F_FAIL;
1729 if (req->flags & REQ_F_CQE_SKIP) {
1730 req->flags &= ~REQ_F_CQE_SKIP;
1731 req->flags |= REQ_F_SKIP_LINK_CQES;
1735 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1741 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1743 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1746 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1748 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1750 complete(&ctx->ref_comp);
1753 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1755 return !req->timeout.off;
1758 static __cold void io_fallback_req_func(struct work_struct *work)
1760 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1761 fallback_work.work);
1762 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1763 struct io_kiocb *req, *tmp;
1764 bool locked = false;
1766 percpu_ref_get(&ctx->refs);
1767 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1768 req->io_task_work.func(req, &locked);
1771 io_submit_flush_completions(ctx);
1772 mutex_unlock(&ctx->uring_lock);
1774 percpu_ref_put(&ctx->refs);
1777 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1779 struct io_ring_ctx *ctx;
1782 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1786 xa_init(&ctx->io_bl_xa);
1789 * Use 5 bits less than the max cq entries, that should give us around
1790 * 32 entries per hash list if totally full and uniformly spread.
1792 hash_bits = ilog2(p->cq_entries);
1796 ctx->cancel_hash_bits = hash_bits;
1797 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1799 if (!ctx->cancel_hash)
1801 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1803 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1804 if (!ctx->dummy_ubuf)
1806 /* set invalid range, so io_import_fixed() fails meeting it */
1807 ctx->dummy_ubuf->ubuf = -1UL;
1809 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1810 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1813 ctx->flags = p->flags;
1814 init_waitqueue_head(&ctx->sqo_sq_wait);
1815 INIT_LIST_HEAD(&ctx->sqd_list);
1816 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1817 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1818 INIT_LIST_HEAD(&ctx->apoll_cache);
1819 init_completion(&ctx->ref_comp);
1820 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1821 mutex_init(&ctx->uring_lock);
1822 init_waitqueue_head(&ctx->cq_wait);
1823 spin_lock_init(&ctx->completion_lock);
1824 spin_lock_init(&ctx->timeout_lock);
1825 INIT_WQ_LIST(&ctx->iopoll_list);
1826 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1827 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1828 INIT_LIST_HEAD(&ctx->defer_list);
1829 INIT_LIST_HEAD(&ctx->timeout_list);
1830 INIT_LIST_HEAD(&ctx->ltimeout_list);
1831 spin_lock_init(&ctx->rsrc_ref_lock);
1832 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1833 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1834 init_llist_head(&ctx->rsrc_put_llist);
1835 INIT_LIST_HEAD(&ctx->tctx_list);
1836 ctx->submit_state.free_list.next = NULL;
1837 INIT_WQ_LIST(&ctx->locked_free_list);
1838 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1839 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1842 kfree(ctx->dummy_ubuf);
1843 kfree(ctx->cancel_hash);
1845 xa_destroy(&ctx->io_bl_xa);
1850 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1852 struct io_rings *r = ctx->rings;
1854 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1858 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1860 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1861 struct io_ring_ctx *ctx = req->ctx;
1863 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1869 static inline bool io_req_ffs_set(struct io_kiocb *req)
1871 return req->flags & REQ_F_FIXED_FILE;
1874 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1876 if (WARN_ON_ONCE(!req->link))
1879 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1880 req->flags |= REQ_F_LINK_TIMEOUT;
1882 /* linked timeouts should have two refs once prep'ed */
1883 io_req_set_refcount(req);
1884 __io_req_set_refcount(req->link, 2);
1888 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1890 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1892 return __io_prep_linked_timeout(req);
1895 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1897 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1900 static inline void io_arm_ltimeout(struct io_kiocb *req)
1902 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1903 __io_arm_ltimeout(req);
1906 static void io_prep_async_work(struct io_kiocb *req)
1908 const struct io_op_def *def = &io_op_defs[req->opcode];
1909 struct io_ring_ctx *ctx = req->ctx;
1911 if (!(req->flags & REQ_F_CREDS)) {
1912 req->flags |= REQ_F_CREDS;
1913 req->creds = get_current_cred();
1916 req->work.list.next = NULL;
1917 req->work.flags = 0;
1918 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1919 if (req->flags & REQ_F_FORCE_ASYNC)
1920 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1922 if (req->flags & REQ_F_ISREG) {
1923 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1924 io_wq_hash_work(&req->work, file_inode(req->file));
1925 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1926 if (def->unbound_nonreg_file)
1927 req->work.flags |= IO_WQ_WORK_UNBOUND;
1931 static void io_prep_async_link(struct io_kiocb *req)
1933 struct io_kiocb *cur;
1935 if (req->flags & REQ_F_LINK_TIMEOUT) {
1936 struct io_ring_ctx *ctx = req->ctx;
1938 spin_lock_irq(&ctx->timeout_lock);
1939 io_for_each_link(cur, req)
1940 io_prep_async_work(cur);
1941 spin_unlock_irq(&ctx->timeout_lock);
1943 io_for_each_link(cur, req)
1944 io_prep_async_work(cur);
1948 static inline void io_req_add_compl_list(struct io_kiocb *req)
1950 struct io_submit_state *state = &req->ctx->submit_state;
1952 if (!(req->flags & REQ_F_CQE_SKIP))
1953 state->flush_cqes = true;
1954 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1957 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1959 struct io_kiocb *link = io_prep_linked_timeout(req);
1960 struct io_uring_task *tctx = req->task->io_uring;
1963 BUG_ON(!tctx->io_wq);
1965 /* init ->work of the whole link before punting */
1966 io_prep_async_link(req);
1969 * Not expected to happen, but if we do have a bug where this _can_
1970 * happen, catch it here and ensure the request is marked as
1971 * canceled. That will make io-wq go through the usual work cancel
1972 * procedure rather than attempt to run this request (or create a new
1975 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1976 req->work.flags |= IO_WQ_WORK_CANCEL;
1978 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1979 req->opcode, req->flags, &req->work,
1980 io_wq_is_hashed(&req->work));
1981 io_wq_enqueue(tctx->io_wq, &req->work);
1983 io_queue_linked_timeout(link);
1986 static void io_kill_timeout(struct io_kiocb *req, int status)
1987 __must_hold(&req->ctx->completion_lock)
1988 __must_hold(&req->ctx->timeout_lock)
1990 struct io_timeout_data *io = req->async_data;
1992 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1995 atomic_set(&req->ctx->cq_timeouts,
1996 atomic_read(&req->ctx->cq_timeouts) + 1);
1997 list_del_init(&req->timeout.list);
1998 io_req_tw_post_queue(req, status, 0);
2002 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
2004 while (!list_empty(&ctx->defer_list)) {
2005 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
2006 struct io_defer_entry, list);
2008 if (req_need_defer(de->req, de->seq))
2010 list_del_init(&de->list);
2011 io_req_task_queue(de->req);
2016 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
2017 __must_hold(&ctx->completion_lock)
2019 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
2020 struct io_kiocb *req, *tmp;
2022 spin_lock_irq(&ctx->timeout_lock);
2023 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
2024 u32 events_needed, events_got;
2026 if (io_is_timeout_noseq(req))
2030 * Since seq can easily wrap around over time, subtract
2031 * the last seq at which timeouts were flushed before comparing.
2032 * Assuming not more than 2^31-1 events have happened since,
2033 * these subtractions won't have wrapped, so we can check if
2034 * target is in [last_seq, current_seq] by comparing the two.
2036 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
2037 events_got = seq - ctx->cq_last_tm_flush;
2038 if (events_got < events_needed)
2041 io_kill_timeout(req, 0);
2043 ctx->cq_last_tm_flush = seq;
2044 spin_unlock_irq(&ctx->timeout_lock);
2047 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
2049 /* order cqe stores with ring update */
2050 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
2053 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
2055 if (ctx->off_timeout_used || ctx->drain_active) {
2056 spin_lock(&ctx->completion_lock);
2057 if (ctx->off_timeout_used)
2058 io_flush_timeouts(ctx);
2059 if (ctx->drain_active)
2060 io_queue_deferred(ctx);
2061 io_commit_cqring(ctx);
2062 spin_unlock(&ctx->completion_lock);
2065 io_eventfd_signal(ctx);
2068 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
2070 struct io_rings *r = ctx->rings;
2072 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
2075 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
2077 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
2081 * writes to the cq entry need to come after reading head; the
2082 * control dependency is enough as we're using WRITE_ONCE to
2085 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
2087 struct io_rings *rings = ctx->rings;
2088 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
2089 unsigned int shift = 0;
2090 unsigned int free, queued, len;
2092 if (ctx->flags & IORING_SETUP_CQE32)
2095 /* userspace may cheat modifying the tail, be safe and do min */
2096 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
2097 free = ctx->cq_entries - queued;
2098 /* we need a contiguous range, limit based on the current array offset */
2099 len = min(free, ctx->cq_entries - off);
2103 ctx->cached_cq_tail++;
2104 ctx->cqe_cached = &rings->cqes[off];
2105 ctx->cqe_sentinel = ctx->cqe_cached + len;
2107 return &rings->cqes[off << shift];
2110 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2112 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2113 struct io_uring_cqe *cqe = ctx->cqe_cached;
2115 if (ctx->flags & IORING_SETUP_CQE32) {
2116 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2121 ctx->cached_cq_tail++;
2126 return __io_get_cqe(ctx);
2129 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2131 struct io_ev_fd *ev_fd;
2135 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2136 * and eventfd_signal
2138 ev_fd = rcu_dereference(ctx->io_ev_fd);
2141 * Check again if ev_fd exists incase an io_eventfd_unregister call
2142 * completed between the NULL check of ctx->io_ev_fd at the start of
2143 * the function and rcu_read_lock.
2145 if (unlikely(!ev_fd))
2147 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2150 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2151 eventfd_signal(ev_fd->cq_ev_fd, 1);
2156 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2159 * wake_up_all() may seem excessive, but io_wake_function() and
2160 * io_should_wake() handle the termination of the loop and only
2161 * wake as many waiters as we need to.
2163 if (wq_has_sleeper(&ctx->cq_wait))
2164 wake_up_all(&ctx->cq_wait);
2168 * This should only get called when at least one event has been posted.
2169 * Some applications rely on the eventfd notification count only changing
2170 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2171 * 1:1 relationship between how many times this function is called (and
2172 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2174 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2176 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2178 __io_commit_cqring_flush(ctx);
2180 io_cqring_wake(ctx);
2183 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2185 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2187 __io_commit_cqring_flush(ctx);
2189 if (ctx->flags & IORING_SETUP_SQPOLL)
2190 io_cqring_wake(ctx);
2193 /* Returns true if there are no backlogged entries after the flush */
2194 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2196 bool all_flushed, posted;
2197 size_t cqe_size = sizeof(struct io_uring_cqe);
2199 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2202 if (ctx->flags & IORING_SETUP_CQE32)
2206 spin_lock(&ctx->completion_lock);
2207 while (!list_empty(&ctx->cq_overflow_list)) {
2208 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2209 struct io_overflow_cqe *ocqe;
2213 ocqe = list_first_entry(&ctx->cq_overflow_list,
2214 struct io_overflow_cqe, list);
2216 memcpy(cqe, &ocqe->cqe, cqe_size);
2218 io_account_cq_overflow(ctx);
2221 list_del(&ocqe->list);
2225 all_flushed = list_empty(&ctx->cq_overflow_list);
2227 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2228 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2231 io_commit_cqring(ctx);
2232 spin_unlock(&ctx->completion_lock);
2234 io_cqring_ev_posted(ctx);
2238 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2242 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2243 /* iopoll syncs against uring_lock, not completion_lock */
2244 if (ctx->flags & IORING_SETUP_IOPOLL)
2245 mutex_lock(&ctx->uring_lock);
2246 ret = __io_cqring_overflow_flush(ctx, false);
2247 if (ctx->flags & IORING_SETUP_IOPOLL)
2248 mutex_unlock(&ctx->uring_lock);
2254 static void __io_put_task(struct task_struct *task, int nr)
2256 struct io_uring_task *tctx = task->io_uring;
2258 percpu_counter_sub(&tctx->inflight, nr);
2259 if (unlikely(atomic_read(&tctx->in_idle)))
2260 wake_up(&tctx->wait);
2261 put_task_struct_many(task, nr);
2264 /* must to be called somewhat shortly after putting a request */
2265 static inline void io_put_task(struct task_struct *task, int nr)
2267 if (likely(task == current))
2268 task->io_uring->cached_refs += nr;
2270 __io_put_task(task, nr);
2273 static void io_task_refs_refill(struct io_uring_task *tctx)
2275 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2277 percpu_counter_add(&tctx->inflight, refill);
2278 refcount_add(refill, ¤t->usage);
2279 tctx->cached_refs += refill;
2282 static inline void io_get_task_refs(int nr)
2284 struct io_uring_task *tctx = current->io_uring;
2286 tctx->cached_refs -= nr;
2287 if (unlikely(tctx->cached_refs < 0))
2288 io_task_refs_refill(tctx);
2291 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2293 struct io_uring_task *tctx = task->io_uring;
2294 unsigned int refs = tctx->cached_refs;
2297 tctx->cached_refs = 0;
2298 percpu_counter_sub(&tctx->inflight, refs);
2299 put_task_struct_many(task, refs);
2303 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2304 s32 res, u32 cflags, u64 extra1,
2307 struct io_overflow_cqe *ocqe;
2308 size_t ocq_size = sizeof(struct io_overflow_cqe);
2309 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2312 ocq_size += sizeof(struct io_uring_cqe);
2314 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2315 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2318 * If we're in ring overflow flush mode, or in task cancel mode,
2319 * or cannot allocate an overflow entry, then we need to drop it
2322 io_account_cq_overflow(ctx);
2323 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2326 if (list_empty(&ctx->cq_overflow_list)) {
2327 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2328 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2331 ocqe->cqe.user_data = user_data;
2332 ocqe->cqe.res = res;
2333 ocqe->cqe.flags = cflags;
2335 ocqe->cqe.big_cqe[0] = extra1;
2336 ocqe->cqe.big_cqe[1] = extra2;
2338 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2342 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2343 s32 res, u32 cflags)
2345 struct io_uring_cqe *cqe;
2348 * If we can't get a cq entry, userspace overflowed the
2349 * submission (by quite a lot). Increment the overflow count in
2352 cqe = io_get_cqe(ctx);
2354 WRITE_ONCE(cqe->user_data, user_data);
2355 WRITE_ONCE(cqe->res, res);
2356 WRITE_ONCE(cqe->flags, cflags);
2359 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2362 static inline bool __io_fill_cqe_req_filled(struct io_ring_ctx *ctx,
2363 struct io_kiocb *req)
2365 struct io_uring_cqe *cqe;
2367 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2368 req->cqe.res, req->cqe.flags, 0, 0);
2371 * If we can't get a cq entry, userspace overflowed the
2372 * submission (by quite a lot). Increment the overflow count in
2375 cqe = io_get_cqe(ctx);
2377 memcpy(cqe, &req->cqe, sizeof(*cqe));
2380 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2381 req->cqe.res, req->cqe.flags, 0, 0);
2384 static inline bool __io_fill_cqe32_req_filled(struct io_ring_ctx *ctx,
2385 struct io_kiocb *req)
2387 struct io_uring_cqe *cqe;
2388 u64 extra1 = req->extra1;
2389 u64 extra2 = req->extra2;
2391 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2392 req->cqe.res, req->cqe.flags, extra1, extra2);
2395 * If we can't get a cq entry, userspace overflowed the
2396 * submission (by quite a lot). Increment the overflow count in
2399 cqe = io_get_cqe(ctx);
2401 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2402 cqe->big_cqe[0] = extra1;
2403 cqe->big_cqe[1] = extra2;
2407 return io_cqring_event_overflow(ctx, req->cqe.user_data, req->cqe.res,
2408 req->cqe.flags, extra1, extra2);
2411 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2413 trace_io_uring_complete(req->ctx, req, req->cqe.user_data, res, cflags, 0, 0);
2414 return __io_fill_cqe(req->ctx, req->cqe.user_data, res, cflags);
2417 static inline void __io_fill_cqe32_req(struct io_kiocb *req, s32 res, u32 cflags,
2418 u64 extra1, u64 extra2)
2420 struct io_ring_ctx *ctx = req->ctx;
2421 struct io_uring_cqe *cqe;
2423 if (WARN_ON_ONCE(!(ctx->flags & IORING_SETUP_CQE32)))
2425 if (req->flags & REQ_F_CQE_SKIP)
2428 trace_io_uring_complete(ctx, req, req->cqe.user_data, res, cflags,
2432 * If we can't get a cq entry, userspace overflowed the
2433 * submission (by quite a lot). Increment the overflow count in
2436 cqe = io_get_cqe(ctx);
2438 WRITE_ONCE(cqe->user_data, req->cqe.user_data);
2439 WRITE_ONCE(cqe->res, res);
2440 WRITE_ONCE(cqe->flags, cflags);
2441 WRITE_ONCE(cqe->big_cqe[0], extra1);
2442 WRITE_ONCE(cqe->big_cqe[1], extra2);
2446 io_cqring_event_overflow(ctx, req->cqe.user_data, res, cflags, extra1, extra2);
2449 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2450 s32 res, u32 cflags)
2453 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2454 return __io_fill_cqe(ctx, user_data, res, cflags);
2457 static void __io_req_complete_put(struct io_kiocb *req)
2460 * If we're the last reference to this request, add to our locked
2463 if (req_ref_put_and_test(req)) {
2464 struct io_ring_ctx *ctx = req->ctx;
2466 if (req->flags & IO_REQ_LINK_FLAGS) {
2467 if (req->flags & IO_DISARM_MASK)
2468 io_disarm_next(req);
2470 io_req_task_queue(req->link);
2474 io_req_put_rsrc(req);
2476 * Selected buffer deallocation in io_clean_op() assumes that
2477 * we don't hold ->completion_lock. Clean them here to avoid
2480 io_put_kbuf_comp(req);
2481 io_dismantle_req(req);
2482 io_put_task(req->task, 1);
2483 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2484 ctx->locked_free_nr++;
2488 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2491 if (!(req->flags & REQ_F_CQE_SKIP))
2492 __io_fill_cqe_req(req, res, cflags);
2493 __io_req_complete_put(req);
2496 static void __io_req_complete_post32(struct io_kiocb *req, s32 res,
2497 u32 cflags, u64 extra1, u64 extra2)
2499 if (!(req->flags & REQ_F_CQE_SKIP))
2500 __io_fill_cqe32_req(req, res, cflags, extra1, extra2);
2501 __io_req_complete_put(req);
2504 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2506 struct io_ring_ctx *ctx = req->ctx;
2508 spin_lock(&ctx->completion_lock);
2509 __io_req_complete_post(req, res, cflags);
2510 io_commit_cqring(ctx);
2511 spin_unlock(&ctx->completion_lock);
2512 io_cqring_ev_posted(ctx);
2515 static void io_req_complete_post32(struct io_kiocb *req, s32 res,
2516 u32 cflags, u64 extra1, u64 extra2)
2518 struct io_ring_ctx *ctx = req->ctx;
2520 spin_lock(&ctx->completion_lock);
2521 __io_req_complete_post32(req, res, cflags, extra1, extra2);
2522 io_commit_cqring(ctx);
2523 spin_unlock(&ctx->completion_lock);
2524 io_cqring_ev_posted(ctx);
2527 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2531 req->cqe.flags = cflags;
2532 req->flags |= REQ_F_COMPLETE_INLINE;
2535 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2536 s32 res, u32 cflags)
2538 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2539 io_req_complete_state(req, res, cflags);
2541 io_req_complete_post(req, res, cflags);
2544 static inline void __io_req_complete32(struct io_kiocb *req,
2545 unsigned int issue_flags, s32 res,
2546 u32 cflags, u64 extra1, u64 extra2)
2548 if (issue_flags & IO_URING_F_COMPLETE_DEFER) {
2549 io_req_complete_state(req, res, cflags);
2550 req->extra1 = extra1;
2551 req->extra2 = extra2;
2553 io_req_complete_post32(req, res, cflags, extra1, extra2);
2557 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2559 __io_req_complete(req, 0, res, 0);
2562 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2565 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2569 * Don't initialise the fields below on every allocation, but do that in
2570 * advance and keep them valid across allocations.
2572 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2576 req->async_data = NULL;
2577 /* not necessary, but safer to zero */
2581 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2582 struct io_submit_state *state)
2584 spin_lock(&ctx->completion_lock);
2585 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2586 ctx->locked_free_nr = 0;
2587 spin_unlock(&ctx->completion_lock);
2590 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2592 return !ctx->submit_state.free_list.next;
2596 * A request might get retired back into the request caches even before opcode
2597 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2598 * Because of that, io_alloc_req() should be called only under ->uring_lock
2599 * and with extra caution to not get a request that is still worked on.
2601 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2602 __must_hold(&ctx->uring_lock)
2604 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2605 void *reqs[IO_REQ_ALLOC_BATCH];
2609 * If we have more than a batch's worth of requests in our IRQ side
2610 * locked cache, grab the lock and move them over to our submission
2613 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2614 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2615 if (!io_req_cache_empty(ctx))
2619 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2622 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2623 * retry single alloc to be on the safe side.
2625 if (unlikely(ret <= 0)) {
2626 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2632 percpu_ref_get_many(&ctx->refs, ret);
2633 for (i = 0; i < ret; i++) {
2634 struct io_kiocb *req = reqs[i];
2636 io_preinit_req(req, ctx);
2637 io_req_add_to_cache(req, ctx);
2642 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2644 if (unlikely(io_req_cache_empty(ctx)))
2645 return __io_alloc_req_refill(ctx);
2649 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2651 struct io_wq_work_node *node;
2653 node = wq_stack_extract(&ctx->submit_state.free_list);
2654 return container_of(node, struct io_kiocb, comp_list);
2657 static inline void io_put_file(struct file *file)
2663 static inline void io_dismantle_req(struct io_kiocb *req)
2665 unsigned int flags = req->flags;
2667 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2669 if (!(flags & REQ_F_FIXED_FILE))
2670 io_put_file(req->file);
2673 static __cold void io_free_req(struct io_kiocb *req)
2675 struct io_ring_ctx *ctx = req->ctx;
2677 io_req_put_rsrc(req);
2678 io_dismantle_req(req);
2679 io_put_task(req->task, 1);
2681 spin_lock(&ctx->completion_lock);
2682 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2683 ctx->locked_free_nr++;
2684 spin_unlock(&ctx->completion_lock);
2687 static inline void io_remove_next_linked(struct io_kiocb *req)
2689 struct io_kiocb *nxt = req->link;
2691 req->link = nxt->link;
2695 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2696 __must_hold(&req->ctx->completion_lock)
2697 __must_hold(&req->ctx->timeout_lock)
2699 struct io_kiocb *link = req->link;
2701 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2702 struct io_timeout_data *io = link->async_data;
2704 io_remove_next_linked(req);
2705 link->timeout.head = NULL;
2706 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2707 list_del(&link->timeout.list);
2714 static void io_fail_links(struct io_kiocb *req)
2715 __must_hold(&req->ctx->completion_lock)
2717 struct io_kiocb *nxt, *link = req->link;
2718 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2722 long res = -ECANCELED;
2724 if (link->flags & REQ_F_FAIL)
2725 res = link->cqe.res;
2730 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2734 link->flags |= REQ_F_CQE_SKIP;
2736 link->flags &= ~REQ_F_CQE_SKIP;
2737 __io_req_complete_post(link, res, 0);
2742 static bool io_disarm_next(struct io_kiocb *req)
2743 __must_hold(&req->ctx->completion_lock)
2745 struct io_kiocb *link = NULL;
2746 bool posted = false;
2748 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2750 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2751 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2752 io_remove_next_linked(req);
2753 io_req_tw_post_queue(link, -ECANCELED, 0);
2756 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2757 struct io_ring_ctx *ctx = req->ctx;
2759 spin_lock_irq(&ctx->timeout_lock);
2760 link = io_disarm_linked_timeout(req);
2761 spin_unlock_irq(&ctx->timeout_lock);
2764 io_req_tw_post_queue(link, -ECANCELED, 0);
2767 if (unlikely((req->flags & REQ_F_FAIL) &&
2768 !(req->flags & REQ_F_HARDLINK))) {
2769 posted |= (req->link != NULL);
2775 static void __io_req_find_next_prep(struct io_kiocb *req)
2777 struct io_ring_ctx *ctx = req->ctx;
2780 spin_lock(&ctx->completion_lock);
2781 posted = io_disarm_next(req);
2782 io_commit_cqring(ctx);
2783 spin_unlock(&ctx->completion_lock);
2785 io_cqring_ev_posted(ctx);
2788 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2790 struct io_kiocb *nxt;
2793 * If LINK is set, we have dependent requests in this chain. If we
2794 * didn't fail this request, queue the first one up, moving any other
2795 * dependencies to the next request. In case of failure, fail the rest
2798 if (unlikely(req->flags & IO_DISARM_MASK))
2799 __io_req_find_next_prep(req);
2805 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2809 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2810 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2812 io_submit_flush_completions(ctx);
2813 mutex_unlock(&ctx->uring_lock);
2816 percpu_ref_put(&ctx->refs);
2819 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2821 io_commit_cqring(ctx);
2822 spin_unlock(&ctx->completion_lock);
2823 io_cqring_ev_posted(ctx);
2826 static void handle_prev_tw_list(struct io_wq_work_node *node,
2827 struct io_ring_ctx **ctx, bool *uring_locked)
2829 if (*ctx && !*uring_locked)
2830 spin_lock(&(*ctx)->completion_lock);
2833 struct io_wq_work_node *next = node->next;
2834 struct io_kiocb *req = container_of(node, struct io_kiocb,
2837 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2839 if (req->ctx != *ctx) {
2840 if (unlikely(!*uring_locked && *ctx))
2841 ctx_commit_and_unlock(*ctx);
2843 ctx_flush_and_put(*ctx, uring_locked);
2845 /* if not contended, grab and improve batching */
2846 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2847 percpu_ref_get(&(*ctx)->refs);
2848 if (unlikely(!*uring_locked))
2849 spin_lock(&(*ctx)->completion_lock);
2851 if (likely(*uring_locked))
2852 req->io_task_work.func(req, uring_locked);
2854 __io_req_complete_post(req, req->cqe.res,
2855 io_put_kbuf_comp(req));
2859 if (unlikely(!*uring_locked))
2860 ctx_commit_and_unlock(*ctx);
2863 static void handle_tw_list(struct io_wq_work_node *node,
2864 struct io_ring_ctx **ctx, bool *locked)
2867 struct io_wq_work_node *next = node->next;
2868 struct io_kiocb *req = container_of(node, struct io_kiocb,
2871 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2873 if (req->ctx != *ctx) {
2874 ctx_flush_and_put(*ctx, locked);
2876 /* if not contended, grab and improve batching */
2877 *locked = mutex_trylock(&(*ctx)->uring_lock);
2878 percpu_ref_get(&(*ctx)->refs);
2880 req->io_task_work.func(req, locked);
2885 static void tctx_task_work(struct callback_head *cb)
2887 bool uring_locked = false;
2888 struct io_ring_ctx *ctx = NULL;
2889 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2893 struct io_wq_work_node *node1, *node2;
2895 spin_lock_irq(&tctx->task_lock);
2896 node1 = tctx->prior_task_list.first;
2897 node2 = tctx->task_list.first;
2898 INIT_WQ_LIST(&tctx->task_list);
2899 INIT_WQ_LIST(&tctx->prior_task_list);
2900 if (!node2 && !node1)
2901 tctx->task_running = false;
2902 spin_unlock_irq(&tctx->task_lock);
2903 if (!node2 && !node1)
2907 handle_prev_tw_list(node1, &ctx, &uring_locked);
2909 handle_tw_list(node2, &ctx, &uring_locked);
2912 if (data_race(!tctx->task_list.first) &&
2913 data_race(!tctx->prior_task_list.first) && uring_locked)
2914 io_submit_flush_completions(ctx);
2917 ctx_flush_and_put(ctx, &uring_locked);
2919 /* relaxed read is enough as only the task itself sets ->in_idle */
2920 if (unlikely(atomic_read(&tctx->in_idle)))
2921 io_uring_drop_tctx_refs(current);
2924 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2926 struct task_struct *tsk = req->task;
2927 struct io_ring_ctx *ctx = req->ctx;
2928 struct io_uring_task *tctx = tsk->io_uring;
2929 struct io_wq_work_node *node;
2930 unsigned long flags;
2933 WARN_ON_ONCE(!tctx);
2935 io_drop_inflight_file(req);
2937 spin_lock_irqsave(&tctx->task_lock, flags);
2939 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2941 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2942 running = tctx->task_running;
2944 tctx->task_running = true;
2945 spin_unlock_irqrestore(&tctx->task_lock, flags);
2947 /* task_work already pending, we're done */
2951 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2952 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2954 if (likely(!task_work_add(tsk, &tctx->task_work, ctx->notify_method)))
2957 spin_lock_irqsave(&tctx->task_lock, flags);
2958 tctx->task_running = false;
2959 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2960 spin_unlock_irqrestore(&tctx->task_lock, flags);
2963 req = container_of(node, struct io_kiocb, io_task_work.node);
2965 if (llist_add(&req->io_task_work.fallback_node,
2966 &req->ctx->fallback_llist))
2967 schedule_delayed_work(&req->ctx->fallback_work, 1);
2971 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2973 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2976 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2979 req->cqe.flags = cflags;
2980 req->io_task_work.func = io_req_tw_post;
2981 io_req_task_work_add(req, false);
2984 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2986 /* not needed for normal modes, but SQPOLL depends on it */
2987 io_tw_lock(req->ctx, locked);
2988 io_req_complete_failed(req, req->cqe.res);
2991 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2993 io_tw_lock(req->ctx, locked);
2994 /* req->task == current here, checking PF_EXITING is safe */
2995 if (likely(!(req->task->flags & PF_EXITING)))
2998 io_req_complete_failed(req, -EFAULT);
3001 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
3004 req->io_task_work.func = io_req_task_cancel;
3005 io_req_task_work_add(req, false);
3008 static void io_req_task_queue(struct io_kiocb *req)
3010 req->io_task_work.func = io_req_task_submit;
3011 io_req_task_work_add(req, false);
3014 static void io_req_task_queue_reissue(struct io_kiocb *req)
3016 req->io_task_work.func = io_queue_iowq;
3017 io_req_task_work_add(req, false);
3020 static void io_queue_next(struct io_kiocb *req)
3022 struct io_kiocb *nxt = io_req_find_next(req);
3025 io_req_task_queue(nxt);
3028 static void io_free_batch_list(struct io_ring_ctx *ctx,
3029 struct io_wq_work_node *node)
3030 __must_hold(&ctx->uring_lock)
3032 struct task_struct *task = NULL;
3036 struct io_kiocb *req = container_of(node, struct io_kiocb,
3039 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
3040 if (req->flags & REQ_F_REFCOUNT) {
3041 node = req->comp_list.next;
3042 if (!req_ref_put_and_test(req))
3045 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3046 struct async_poll *apoll = req->apoll;
3048 if (apoll->double_poll)
3049 kfree(apoll->double_poll);
3050 list_add(&apoll->poll.wait.entry,
3052 req->flags &= ~REQ_F_POLLED;
3054 if (req->flags & IO_REQ_LINK_FLAGS)
3056 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
3059 if (!(req->flags & REQ_F_FIXED_FILE))
3060 io_put_file(req->file);
3062 io_req_put_rsrc_locked(req, ctx);
3064 if (req->task != task) {
3066 io_put_task(task, task_refs);
3071 node = req->comp_list.next;
3072 io_req_add_to_cache(req, ctx);
3076 io_put_task(task, task_refs);
3079 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
3080 __must_hold(&ctx->uring_lock)
3082 struct io_wq_work_node *node, *prev;
3083 struct io_submit_state *state = &ctx->submit_state;
3085 if (state->flush_cqes) {
3086 spin_lock(&ctx->completion_lock);
3087 wq_list_for_each(node, prev, &state->compl_reqs) {
3088 struct io_kiocb *req = container_of(node, struct io_kiocb,
3091 if (!(req->flags & REQ_F_CQE_SKIP)) {
3092 if (!(ctx->flags & IORING_SETUP_CQE32))
3093 __io_fill_cqe_req_filled(ctx, req);
3095 __io_fill_cqe32_req_filled(ctx, req);
3099 io_commit_cqring(ctx);
3100 spin_unlock(&ctx->completion_lock);
3101 io_cqring_ev_posted(ctx);
3102 state->flush_cqes = false;
3105 io_free_batch_list(ctx, state->compl_reqs.first);
3106 INIT_WQ_LIST(&state->compl_reqs);
3110 * Drop reference to request, return next in chain (if there is one) if this
3111 * was the last reference to this request.
3113 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
3115 struct io_kiocb *nxt = NULL;
3117 if (req_ref_put_and_test(req)) {
3118 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
3119 nxt = io_req_find_next(req);
3125 static inline void io_put_req(struct io_kiocb *req)
3127 if (req_ref_put_and_test(req)) {
3133 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
3135 /* See comment at the top of this file */
3137 return __io_cqring_events(ctx);
3140 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
3142 struct io_rings *rings = ctx->rings;
3144 /* make sure SQ entry isn't read before tail */
3145 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
3148 static inline bool io_run_task_work(void)
3150 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
3151 __set_current_state(TASK_RUNNING);
3152 clear_notify_signal();
3153 if (task_work_pending(current))
3161 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3163 struct io_wq_work_node *pos, *start, *prev;
3164 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3165 DEFINE_IO_COMP_BATCH(iob);
3169 * Only spin for completions if we don't have multiple devices hanging
3170 * off our complete list.
3172 if (ctx->poll_multi_queue || force_nonspin)
3173 poll_flags |= BLK_POLL_ONESHOT;
3175 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3176 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3177 struct kiocb *kiocb = &req->rw.kiocb;
3181 * Move completed and retryable entries to our local lists.
3182 * If we find a request that requires polling, break out
3183 * and complete those lists first, if we have entries there.
3185 if (READ_ONCE(req->iopoll_completed))
3188 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3189 if (unlikely(ret < 0))
3192 poll_flags |= BLK_POLL_ONESHOT;
3194 /* iopoll may have completed current req */
3195 if (!rq_list_empty(iob.req_list) ||
3196 READ_ONCE(req->iopoll_completed))
3200 if (!rq_list_empty(iob.req_list))
3206 wq_list_for_each_resume(pos, prev) {
3207 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3209 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3210 if (!smp_load_acquire(&req->iopoll_completed))
3213 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3215 __io_fill_cqe_req(req, req->cqe.res, io_put_kbuf(req, 0));
3218 if (unlikely(!nr_events))
3221 io_commit_cqring(ctx);
3222 io_cqring_ev_posted_iopoll(ctx);
3223 pos = start ? start->next : ctx->iopoll_list.first;
3224 wq_list_cut(&ctx->iopoll_list, prev, start);
3225 io_free_batch_list(ctx, pos);
3230 * We can't just wait for polled events to come to us, we have to actively
3231 * find and complete them.
3233 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3235 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3238 mutex_lock(&ctx->uring_lock);
3239 while (!wq_list_empty(&ctx->iopoll_list)) {
3240 /* let it sleep and repeat later if can't complete a request */
3241 if (io_do_iopoll(ctx, true) == 0)
3244 * Ensure we allow local-to-the-cpu processing to take place,
3245 * in this case we need to ensure that we reap all events.
3246 * Also let task_work, etc. to progress by releasing the mutex
3248 if (need_resched()) {
3249 mutex_unlock(&ctx->uring_lock);
3251 mutex_lock(&ctx->uring_lock);
3254 mutex_unlock(&ctx->uring_lock);
3257 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3259 unsigned int nr_events = 0;
3261 unsigned long check_cq;
3264 * Don't enter poll loop if we already have events pending.
3265 * If we do, we can potentially be spinning for commands that
3266 * already triggered a CQE (eg in error).
3268 check_cq = READ_ONCE(ctx->check_cq);
3269 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3270 __io_cqring_overflow_flush(ctx, false);
3271 if (io_cqring_events(ctx))
3275 * Similarly do not spin if we have not informed the user of any
3278 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3283 * If a submit got punted to a workqueue, we can have the
3284 * application entering polling for a command before it gets
3285 * issued. That app will hold the uring_lock for the duration
3286 * of the poll right here, so we need to take a breather every
3287 * now and then to ensure that the issue has a chance to add
3288 * the poll to the issued list. Otherwise we can spin here
3289 * forever, while the workqueue is stuck trying to acquire the
3292 if (wq_list_empty(&ctx->iopoll_list)) {
3293 u32 tail = ctx->cached_cq_tail;
3295 mutex_unlock(&ctx->uring_lock);
3297 mutex_lock(&ctx->uring_lock);
3299 /* some requests don't go through iopoll_list */
3300 if (tail != ctx->cached_cq_tail ||
3301 wq_list_empty(&ctx->iopoll_list))
3304 ret = io_do_iopoll(ctx, !min);
3309 } while (nr_events < min && !need_resched());
3314 static void kiocb_end_write(struct io_kiocb *req)
3317 * Tell lockdep we inherited freeze protection from submission
3320 if (req->flags & REQ_F_ISREG) {
3321 struct super_block *sb = file_inode(req->file)->i_sb;
3323 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3329 static bool io_resubmit_prep(struct io_kiocb *req)
3331 struct io_async_rw *rw = req->async_data;
3333 if (!req_has_async_data(req))
3334 return !io_req_prep_async(req);
3335 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3339 static bool io_rw_should_reissue(struct io_kiocb *req)
3341 umode_t mode = file_inode(req->file)->i_mode;
3342 struct io_ring_ctx *ctx = req->ctx;
3344 if (!S_ISBLK(mode) && !S_ISREG(mode))
3346 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3347 !(ctx->flags & IORING_SETUP_IOPOLL)))
3350 * If ref is dying, we might be running poll reap from the exit work.
3351 * Don't attempt to reissue from that path, just let it fail with
3354 if (percpu_ref_is_dying(&ctx->refs))
3357 * Play it safe and assume not safe to re-import and reissue if we're
3358 * not in the original thread group (or in task context).
3360 if (!same_thread_group(req->task, current) || !in_task())
3365 static bool io_resubmit_prep(struct io_kiocb *req)
3369 static bool io_rw_should_reissue(struct io_kiocb *req)
3375 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3377 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3378 kiocb_end_write(req);
3379 fsnotify_modify(req->file);
3381 fsnotify_access(req->file);
3383 if (unlikely(res != req->cqe.res)) {
3384 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3385 io_rw_should_reissue(req)) {
3386 req->flags |= REQ_F_REISSUE;
3395 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3397 int res = req->cqe.res;
3400 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3401 io_req_add_compl_list(req);
3403 io_req_complete_post(req, res,
3404 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3408 static void __io_complete_rw(struct io_kiocb *req, long res,
3409 unsigned int issue_flags)
3411 if (__io_complete_rw_common(req, res))
3413 __io_req_complete(req, issue_flags, req->cqe.res,
3414 io_put_kbuf(req, issue_flags));
3417 static void io_complete_rw(struct kiocb *kiocb, long res)
3419 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3421 if (__io_complete_rw_common(req, res))
3424 req->io_task_work.func = io_req_task_complete;
3425 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3428 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3430 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3432 if (kiocb->ki_flags & IOCB_WRITE)
3433 kiocb_end_write(req);
3434 if (unlikely(res != req->cqe.res)) {
3435 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3436 req->flags |= REQ_F_REISSUE;
3442 /* order with io_iopoll_complete() checking ->iopoll_completed */
3443 smp_store_release(&req->iopoll_completed, 1);
3447 * After the iocb has been issued, it's safe to be found on the poll list.
3448 * Adding the kiocb to the list AFTER submission ensures that we don't
3449 * find it from a io_do_iopoll() thread before the issuer is done
3450 * accessing the kiocb cookie.
3452 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3454 struct io_ring_ctx *ctx = req->ctx;
3455 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3457 /* workqueue context doesn't hold uring_lock, grab it now */
3458 if (unlikely(needs_lock))
3459 mutex_lock(&ctx->uring_lock);
3462 * Track whether we have multiple files in our lists. This will impact
3463 * how we do polling eventually, not spinning if we're on potentially
3464 * different devices.
3466 if (wq_list_empty(&ctx->iopoll_list)) {
3467 ctx->poll_multi_queue = false;
3468 } else if (!ctx->poll_multi_queue) {
3469 struct io_kiocb *list_req;
3471 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3473 if (list_req->file != req->file)
3474 ctx->poll_multi_queue = true;
3478 * For fast devices, IO may have already completed. If it has, add
3479 * it to the front so we find it first.
3481 if (READ_ONCE(req->iopoll_completed))
3482 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3484 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3486 if (unlikely(needs_lock)) {
3488 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3489 * in sq thread task context or in io worker task context. If
3490 * current task context is sq thread, we don't need to check
3491 * whether should wake up sq thread.
3493 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3494 wq_has_sleeper(&ctx->sq_data->wait))
3495 wake_up(&ctx->sq_data->wait);
3497 mutex_unlock(&ctx->uring_lock);
3501 static bool io_bdev_nowait(struct block_device *bdev)
3503 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3507 * If we tracked the file through the SCM inflight mechanism, we could support
3508 * any file. For now, just ensure that anything potentially problematic is done
3511 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3513 if (S_ISBLK(mode)) {
3514 if (IS_ENABLED(CONFIG_BLOCK) &&
3515 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3521 if (S_ISREG(mode)) {
3522 if (IS_ENABLED(CONFIG_BLOCK) &&
3523 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3524 file->f_op != &io_uring_fops)
3529 /* any ->read/write should understand O_NONBLOCK */
3530 if (file->f_flags & O_NONBLOCK)
3532 return file->f_mode & FMODE_NOWAIT;
3536 * If we tracked the file through the SCM inflight mechanism, we could support
3537 * any file. For now, just ensure that anything potentially problematic is done
3540 static unsigned int io_file_get_flags(struct file *file)
3542 umode_t mode = file_inode(file)->i_mode;
3543 unsigned int res = 0;
3547 if (__io_file_supports_nowait(file, mode))
3549 if (io_file_need_scm(file))
3554 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3556 return req->flags & REQ_F_SUPPORT_NOWAIT;
3559 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3561 struct kiocb *kiocb = &req->rw.kiocb;
3565 kiocb->ki_pos = READ_ONCE(sqe->off);
3567 ioprio = READ_ONCE(sqe->ioprio);
3569 ret = ioprio_check_cap(ioprio);
3573 kiocb->ki_ioprio = ioprio;
3575 kiocb->ki_ioprio = get_current_ioprio();
3579 req->rw.addr = READ_ONCE(sqe->addr);
3580 req->rw.len = READ_ONCE(sqe->len);
3581 req->rw.flags = READ_ONCE(sqe->rw_flags);
3582 /* used for fixed read/write too - just read unconditionally */
3583 req->buf_index = READ_ONCE(sqe->buf_index);
3587 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3593 case -ERESTARTNOINTR:
3594 case -ERESTARTNOHAND:
3595 case -ERESTART_RESTARTBLOCK:
3597 * We can't just restart the syscall, since previously
3598 * submitted sqes may already be in progress. Just fail this
3604 kiocb->ki_complete(kiocb, ret);
3608 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3610 struct kiocb *kiocb = &req->rw.kiocb;
3612 if (kiocb->ki_pos != -1)
3613 return &kiocb->ki_pos;
3615 if (!(req->file->f_mode & FMODE_STREAM)) {
3616 req->flags |= REQ_F_CUR_POS;
3617 kiocb->ki_pos = req->file->f_pos;
3618 return &kiocb->ki_pos;
3625 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3626 unsigned int issue_flags)
3628 struct io_async_rw *io = req->async_data;
3630 /* add previously done IO, if any */
3631 if (req_has_async_data(req) && io->bytes_done > 0) {
3633 ret = io->bytes_done;
3635 ret += io->bytes_done;
3638 if (req->flags & REQ_F_CUR_POS)
3639 req->file->f_pos = req->rw.kiocb.ki_pos;
3640 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3641 __io_complete_rw(req, ret, issue_flags);
3643 io_rw_done(&req->rw.kiocb, ret);
3645 if (req->flags & REQ_F_REISSUE) {
3646 req->flags &= ~REQ_F_REISSUE;
3647 if (io_resubmit_prep(req))
3648 io_req_task_queue_reissue(req);
3650 io_req_task_queue_fail(req, ret);
3654 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3655 struct io_mapped_ubuf *imu)
3657 size_t len = req->rw.len;
3658 u64 buf_end, buf_addr = req->rw.addr;
3661 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3663 /* not inside the mapped region */
3664 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3668 * May not be a start of buffer, set size appropriately
3669 * and advance us to the beginning.
3671 offset = buf_addr - imu->ubuf;
3672 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3676 * Don't use iov_iter_advance() here, as it's really slow for
3677 * using the latter parts of a big fixed buffer - it iterates
3678 * over each segment manually. We can cheat a bit here, because
3681 * 1) it's a BVEC iter, we set it up
3682 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3683 * first and last bvec
3685 * So just find our index, and adjust the iterator afterwards.
3686 * If the offset is within the first bvec (or the whole first
3687 * bvec, just use iov_iter_advance(). This makes it easier
3688 * since we can just skip the first segment, which may not
3689 * be PAGE_SIZE aligned.
3691 const struct bio_vec *bvec = imu->bvec;
3693 if (offset <= bvec->bv_len) {
3694 iov_iter_advance(iter, offset);
3696 unsigned long seg_skip;
3698 /* skip first vec */
3699 offset -= bvec->bv_len;
3700 seg_skip = 1 + (offset >> PAGE_SHIFT);
3702 iter->bvec = bvec + seg_skip;
3703 iter->nr_segs -= seg_skip;
3704 iter->count -= bvec->bv_len + offset;
3705 iter->iov_offset = offset & ~PAGE_MASK;
3712 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3713 unsigned int issue_flags)
3715 struct io_mapped_ubuf *imu = req->imu;
3716 u16 index, buf_index = req->buf_index;
3719 struct io_ring_ctx *ctx = req->ctx;
3721 if (unlikely(buf_index >= ctx->nr_user_bufs))
3723 io_req_set_rsrc_node(req, ctx, issue_flags);
3724 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3725 imu = READ_ONCE(ctx->user_bufs[index]);
3728 return __io_import_fixed(req, rw, iter, imu);
3731 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3732 struct io_buffer_list *bl, unsigned int bgid)
3735 if (bgid < BGID_ARRAY)
3738 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3741 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3742 struct io_buffer_list *bl,
3743 unsigned int issue_flags)
3745 struct io_buffer *kbuf;
3747 if (list_empty(&bl->buf_list))
3748 return ERR_PTR(-ENOBUFS);
3750 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3751 list_del(&kbuf->list);
3752 if (*len > kbuf->len)
3754 req->flags |= REQ_F_BUFFER_SELECTED;
3756 req->buf_index = kbuf->bid;
3757 io_ring_submit_unlock(req->ctx, issue_flags);
3758 return u64_to_user_ptr(kbuf->addr);
3761 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3762 unsigned int issue_flags)
3764 struct io_ring_ctx *ctx = req->ctx;
3765 struct io_buffer_list *bl;
3767 io_ring_submit_lock(req->ctx, issue_flags);
3769 bl = io_buffer_get_list(ctx, req->buf_index);
3770 if (unlikely(!bl)) {
3771 io_ring_submit_unlock(req->ctx, issue_flags);
3772 return ERR_PTR(-ENOBUFS);
3775 /* selection helpers drop the submit lock again, if needed */
3776 return io_provided_buffer_select(req, len, bl, issue_flags);
3779 #ifdef CONFIG_COMPAT
3780 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3781 unsigned int issue_flags)
3783 struct compat_iovec __user *uiov;
3784 compat_ssize_t clen;
3788 uiov = u64_to_user_ptr(req->rw.addr);
3789 if (!access_ok(uiov, sizeof(*uiov)))
3791 if (__get_user(clen, &uiov->iov_len))
3797 buf = io_buffer_select(req, &len, issue_flags);
3799 return PTR_ERR(buf);
3800 req->rw.addr = (unsigned long) buf;
3801 iov[0].iov_base = buf;
3802 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3807 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3808 unsigned int issue_flags)
3810 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3814 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3817 len = iov[0].iov_len;
3820 buf = io_buffer_select(req, &len, issue_flags);
3822 return PTR_ERR(buf);
3823 req->rw.addr = (unsigned long) buf;
3824 iov[0].iov_base = buf;
3825 req->rw.len = iov[0].iov_len = len;
3829 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3830 unsigned int issue_flags)
3832 if (req->flags & REQ_F_BUFFER_SELECTED) {
3833 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3834 iov[0].iov_len = req->rw.len;
3837 if (req->rw.len != 1)
3840 #ifdef CONFIG_COMPAT
3841 if (req->ctx->compat)
3842 return io_compat_import(req, iov, issue_flags);
3845 return __io_iov_buffer_select(req, iov, issue_flags);
3848 static inline bool io_do_buffer_select(struct io_kiocb *req)
3850 if (!(req->flags & REQ_F_BUFFER_SELECT))
3852 return !(req->flags & REQ_F_BUFFER_SELECTED);
3855 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3856 struct io_rw_state *s,
3857 unsigned int issue_flags)
3859 struct iov_iter *iter = &s->iter;
3860 u8 opcode = req->opcode;
3861 struct iovec *iovec;
3866 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3867 ret = io_import_fixed(req, rw, iter, issue_flags);
3869 return ERR_PTR(ret);
3873 buf = u64_to_user_ptr(req->rw.addr);
3874 sqe_len = req->rw.len;
3876 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3877 if (io_do_buffer_select(req)) {
3878 buf = io_buffer_select(req, &sqe_len, issue_flags);
3880 return ERR_CAST(buf);
3881 req->rw.addr = (unsigned long) buf;
3882 req->rw.len = sqe_len;
3885 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3887 return ERR_PTR(ret);
3891 iovec = s->fast_iov;
3892 if (req->flags & REQ_F_BUFFER_SELECT) {
3893 ret = io_iov_buffer_select(req, iovec, issue_flags);
3895 return ERR_PTR(ret);
3896 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3900 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3902 if (unlikely(ret < 0))
3903 return ERR_PTR(ret);
3907 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3908 struct iovec **iovec, struct io_rw_state *s,
3909 unsigned int issue_flags)
3911 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3912 if (unlikely(IS_ERR(*iovec)))
3913 return PTR_ERR(*iovec);
3915 iov_iter_save_state(&s->iter, &s->iter_state);
3919 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3921 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3925 * For files that don't have ->read_iter() and ->write_iter(), handle them
3926 * by looping over ->read() or ->write() manually.
3928 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3930 struct kiocb *kiocb = &req->rw.kiocb;
3931 struct file *file = req->file;
3936 * Don't support polled IO through this interface, and we can't
3937 * support non-blocking either. For the latter, this just causes
3938 * the kiocb to be handled from an async context.
3940 if (kiocb->ki_flags & IOCB_HIPRI)
3942 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3943 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3946 ppos = io_kiocb_ppos(kiocb);
3948 while (iov_iter_count(iter)) {
3952 if (!iov_iter_is_bvec(iter)) {
3953 iovec = iov_iter_iovec(iter);
3955 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3956 iovec.iov_len = req->rw.len;
3960 nr = file->f_op->read(file, iovec.iov_base,
3961 iovec.iov_len, ppos);
3963 nr = file->f_op->write(file, iovec.iov_base,
3964 iovec.iov_len, ppos);
3973 if (!iov_iter_is_bvec(iter)) {
3974 iov_iter_advance(iter, nr);
3981 if (nr != iovec.iov_len)
3988 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3989 const struct iovec *fast_iov, struct iov_iter *iter)
3991 struct io_async_rw *rw = req->async_data;
3993 memcpy(&rw->s.iter, iter, sizeof(*iter));
3994 rw->free_iovec = iovec;
3996 /* can only be fixed buffers, no need to do anything */
3997 if (iov_iter_is_bvec(iter))
4000 unsigned iov_off = 0;
4002 rw->s.iter.iov = rw->s.fast_iov;
4003 if (iter->iov != fast_iov) {
4004 iov_off = iter->iov - fast_iov;
4005 rw->s.iter.iov += iov_off;
4007 if (rw->s.fast_iov != fast_iov)
4008 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
4009 sizeof(struct iovec) * iter->nr_segs);
4011 req->flags |= REQ_F_NEED_CLEANUP;
4015 static inline bool io_alloc_async_data(struct io_kiocb *req)
4017 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
4018 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
4019 if (req->async_data) {
4020 req->flags |= REQ_F_ASYNC_DATA;
4026 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
4027 struct io_rw_state *s, bool force)
4029 if (!force && !io_op_defs[req->opcode].needs_async_setup)
4031 if (!req_has_async_data(req)) {
4032 struct io_async_rw *iorw;
4034 if (io_alloc_async_data(req)) {
4039 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
4040 iorw = req->async_data;
4041 /* we've copied and mapped the iter, ensure state is saved */
4042 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
4047 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
4049 struct io_async_rw *iorw = req->async_data;
4053 /* submission path, ->uring_lock should already be taken */
4054 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
4055 if (unlikely(ret < 0))
4058 iorw->bytes_done = 0;
4059 iorw->free_iovec = iov;
4061 req->flags |= REQ_F_NEED_CLEANUP;
4066 * This is our waitqueue callback handler, registered through __folio_lock_async()
4067 * when we initially tried to do the IO with the iocb armed our waitqueue.
4068 * This gets called when the page is unlocked, and we generally expect that to
4069 * happen when the page IO is completed and the page is now uptodate. This will
4070 * queue a task_work based retry of the operation, attempting to copy the data
4071 * again. If the latter fails because the page was NOT uptodate, then we will
4072 * do a thread based blocking retry of the operation. That's the unexpected
4075 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
4076 int sync, void *arg)
4078 struct wait_page_queue *wpq;
4079 struct io_kiocb *req = wait->private;
4080 struct wait_page_key *key = arg;
4082 wpq = container_of(wait, struct wait_page_queue, wait);
4084 if (!wake_page_match(wpq, key))
4087 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
4088 list_del_init(&wait->entry);
4089 io_req_task_queue(req);
4094 * This controls whether a given IO request should be armed for async page
4095 * based retry. If we return false here, the request is handed to the async
4096 * worker threads for retry. If we're doing buffered reads on a regular file,
4097 * we prepare a private wait_page_queue entry and retry the operation. This
4098 * will either succeed because the page is now uptodate and unlocked, or it
4099 * will register a callback when the page is unlocked at IO completion. Through
4100 * that callback, io_uring uses task_work to setup a retry of the operation.
4101 * That retry will attempt the buffered read again. The retry will generally
4102 * succeed, or in rare cases where it fails, we then fall back to using the
4103 * async worker threads for a blocking retry.
4105 static bool io_rw_should_retry(struct io_kiocb *req)
4107 struct io_async_rw *rw = req->async_data;
4108 struct wait_page_queue *wait = &rw->wpq;
4109 struct kiocb *kiocb = &req->rw.kiocb;
4111 /* never retry for NOWAIT, we just complete with -EAGAIN */
4112 if (req->flags & REQ_F_NOWAIT)
4115 /* Only for buffered IO */
4116 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4120 * just use poll if we can, and don't attempt if the fs doesn't
4121 * support callback based unlocks
4123 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4126 wait->wait.func = io_async_buf_func;
4127 wait->wait.private = req;
4128 wait->wait.flags = 0;
4129 INIT_LIST_HEAD(&wait->wait.entry);
4130 kiocb->ki_flags |= IOCB_WAITQ;
4131 kiocb->ki_flags &= ~IOCB_NOWAIT;
4132 kiocb->ki_waitq = wait;
4136 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4138 if (likely(req->file->f_op->read_iter))
4139 return call_read_iter(req->file, &req->rw.kiocb, iter);
4140 else if (req->file->f_op->read)
4141 return loop_rw_iter(READ, req, iter);
4146 static bool need_read_all(struct io_kiocb *req)
4148 return req->flags & REQ_F_ISREG ||
4149 S_ISBLK(file_inode(req->file)->i_mode);
4152 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4154 struct kiocb *kiocb = &req->rw.kiocb;
4155 struct io_ring_ctx *ctx = req->ctx;
4156 struct file *file = req->file;
4159 if (unlikely(!file || !(file->f_mode & mode)))
4162 if (!io_req_ffs_set(req))
4163 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4165 kiocb->ki_flags = iocb_flags(file);
4166 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4171 * If the file is marked O_NONBLOCK, still allow retry for it if it
4172 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4173 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4175 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4176 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4177 req->flags |= REQ_F_NOWAIT;
4179 if (ctx->flags & IORING_SETUP_IOPOLL) {
4180 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4183 kiocb->private = NULL;
4184 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4185 kiocb->ki_complete = io_complete_rw_iopoll;
4186 req->iopoll_completed = 0;
4188 if (kiocb->ki_flags & IOCB_HIPRI)
4190 kiocb->ki_complete = io_complete_rw;
4196 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4198 struct io_rw_state __s, *s = &__s;
4199 struct iovec *iovec;
4200 struct kiocb *kiocb = &req->rw.kiocb;
4201 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4202 struct io_async_rw *rw;
4206 if (!req_has_async_data(req)) {
4207 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4208 if (unlikely(ret < 0))
4212 * Safe and required to re-import if we're using provided
4213 * buffers, as we dropped the selected one before retry.
4215 if (req->flags & REQ_F_BUFFER_SELECT) {
4216 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4217 if (unlikely(ret < 0))
4221 rw = req->async_data;
4224 * We come here from an earlier attempt, restore our state to
4225 * match in case it doesn't. It's cheap enough that we don't
4226 * need to make this conditional.
4228 iov_iter_restore(&s->iter, &s->iter_state);
4231 ret = io_rw_init_file(req, FMODE_READ);
4232 if (unlikely(ret)) {
4236 req->cqe.res = iov_iter_count(&s->iter);
4238 if (force_nonblock) {
4239 /* If the file doesn't support async, just async punt */
4240 if (unlikely(!io_file_supports_nowait(req))) {
4241 ret = io_setup_async_rw(req, iovec, s, true);
4242 return ret ?: -EAGAIN;
4244 kiocb->ki_flags |= IOCB_NOWAIT;
4246 /* Ensure we clear previously set non-block flag */
4247 kiocb->ki_flags &= ~IOCB_NOWAIT;
4250 ppos = io_kiocb_update_pos(req);
4252 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4253 if (unlikely(ret)) {
4258 ret = io_iter_do_read(req, &s->iter);
4260 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4261 req->flags &= ~REQ_F_REISSUE;
4262 /* if we can poll, just do that */
4263 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4265 /* IOPOLL retry should happen for io-wq threads */
4266 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4268 /* no retry on NONBLOCK nor RWF_NOWAIT */
4269 if (req->flags & REQ_F_NOWAIT)
4272 } else if (ret == -EIOCBQUEUED) {
4274 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4275 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4276 /* read all, failed, already did sync or don't want to retry */
4281 * Don't depend on the iter state matching what was consumed, or being
4282 * untouched in case of error. Restore it and we'll advance it
4283 * manually if we need to.
4285 iov_iter_restore(&s->iter, &s->iter_state);
4287 ret2 = io_setup_async_rw(req, iovec, s, true);
4292 rw = req->async_data;
4295 * Now use our persistent iterator and state, if we aren't already.
4296 * We've restored and mapped the iter to match.
4301 * We end up here because of a partial read, either from
4302 * above or inside this loop. Advance the iter by the bytes
4303 * that were consumed.
4305 iov_iter_advance(&s->iter, ret);
4306 if (!iov_iter_count(&s->iter))
4308 rw->bytes_done += ret;
4309 iov_iter_save_state(&s->iter, &s->iter_state);
4311 /* if we can retry, do so with the callbacks armed */
4312 if (!io_rw_should_retry(req)) {
4313 kiocb->ki_flags &= ~IOCB_WAITQ;
4318 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4319 * we get -EIOCBQUEUED, then we'll get a notification when the
4320 * desired page gets unlocked. We can also get a partial read
4321 * here, and if we do, then just retry at the new offset.
4323 ret = io_iter_do_read(req, &s->iter);
4324 if (ret == -EIOCBQUEUED)
4326 /* we got some bytes, but not all. retry. */
4327 kiocb->ki_flags &= ~IOCB_WAITQ;
4328 iov_iter_restore(&s->iter, &s->iter_state);
4331 kiocb_done(req, ret, issue_flags);
4333 /* it's faster to check here then delegate to kfree */
4339 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4341 struct io_rw_state __s, *s = &__s;
4342 struct iovec *iovec;
4343 struct kiocb *kiocb = &req->rw.kiocb;
4344 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4348 if (!req_has_async_data(req)) {
4349 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4350 if (unlikely(ret < 0))
4353 struct io_async_rw *rw = req->async_data;
4356 iov_iter_restore(&s->iter, &s->iter_state);
4359 ret = io_rw_init_file(req, FMODE_WRITE);
4360 if (unlikely(ret)) {
4364 req->cqe.res = iov_iter_count(&s->iter);
4366 if (force_nonblock) {
4367 /* If the file doesn't support async, just async punt */
4368 if (unlikely(!io_file_supports_nowait(req)))
4371 /* file path doesn't support NOWAIT for non-direct_IO */
4372 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4373 (req->flags & REQ_F_ISREG))
4376 kiocb->ki_flags |= IOCB_NOWAIT;
4378 /* Ensure we clear previously set non-block flag */
4379 kiocb->ki_flags &= ~IOCB_NOWAIT;
4382 ppos = io_kiocb_update_pos(req);
4384 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4389 * Open-code file_start_write here to grab freeze protection,
4390 * which will be released by another thread in
4391 * io_complete_rw(). Fool lockdep by telling it the lock got
4392 * released so that it doesn't complain about the held lock when
4393 * we return to userspace.
4395 if (req->flags & REQ_F_ISREG) {
4396 sb_start_write(file_inode(req->file)->i_sb);
4397 __sb_writers_release(file_inode(req->file)->i_sb,
4400 kiocb->ki_flags |= IOCB_WRITE;
4402 if (likely(req->file->f_op->write_iter))
4403 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4404 else if (req->file->f_op->write)
4405 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4409 if (req->flags & REQ_F_REISSUE) {
4410 req->flags &= ~REQ_F_REISSUE;
4415 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4416 * retry them without IOCB_NOWAIT.
4418 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4420 /* no retry on NONBLOCK nor RWF_NOWAIT */
4421 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4423 if (!force_nonblock || ret2 != -EAGAIN) {
4424 /* IOPOLL retry should happen for io-wq threads */
4425 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4428 kiocb_done(req, ret2, issue_flags);
4431 iov_iter_restore(&s->iter, &s->iter_state);
4432 ret = io_setup_async_rw(req, iovec, s, false);
4433 return ret ?: -EAGAIN;
4436 /* it's reportedly faster than delegating the null check to kfree() */
4442 static int io_renameat_prep(struct io_kiocb *req,
4443 const struct io_uring_sqe *sqe)
4445 struct io_rename *ren = &req->rename;
4446 const char __user *oldf, *newf;
4448 if (sqe->buf_index || sqe->splice_fd_in)
4450 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4453 ren->old_dfd = READ_ONCE(sqe->fd);
4454 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4455 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4456 ren->new_dfd = READ_ONCE(sqe->len);
4457 ren->flags = READ_ONCE(sqe->rename_flags);
4459 ren->oldpath = getname(oldf);
4460 if (IS_ERR(ren->oldpath))
4461 return PTR_ERR(ren->oldpath);
4463 ren->newpath = getname(newf);
4464 if (IS_ERR(ren->newpath)) {
4465 putname(ren->oldpath);
4466 return PTR_ERR(ren->newpath);
4469 req->flags |= REQ_F_NEED_CLEANUP;
4473 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4475 struct io_rename *ren = &req->rename;
4478 if (issue_flags & IO_URING_F_NONBLOCK)
4481 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4482 ren->newpath, ren->flags);
4484 req->flags &= ~REQ_F_NEED_CLEANUP;
4487 io_req_complete(req, ret);
4491 static inline void __io_xattr_finish(struct io_kiocb *req)
4493 struct io_xattr *ix = &req->xattr;
4496 putname(ix->filename);
4498 kfree(ix->ctx.kname);
4499 kvfree(ix->ctx.kvalue);
4502 static void io_xattr_finish(struct io_kiocb *req, int ret)
4504 req->flags &= ~REQ_F_NEED_CLEANUP;
4506 __io_xattr_finish(req);
4510 io_req_complete(req, ret);
4513 static int __io_getxattr_prep(struct io_kiocb *req,
4514 const struct io_uring_sqe *sqe)
4516 struct io_xattr *ix = &req->xattr;
4517 const char __user *name;
4520 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4523 ix->filename = NULL;
4524 ix->ctx.kvalue = NULL;
4525 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4526 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4527 ix->ctx.size = READ_ONCE(sqe->len);
4528 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4533 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4537 ret = strncpy_from_user(ix->ctx.kname->name, name,
4538 sizeof(ix->ctx.kname->name));
4539 if (!ret || ret == sizeof(ix->ctx.kname->name))
4542 kfree(ix->ctx.kname);
4546 req->flags |= REQ_F_NEED_CLEANUP;
4550 static int io_fgetxattr_prep(struct io_kiocb *req,
4551 const struct io_uring_sqe *sqe)
4553 return __io_getxattr_prep(req, sqe);
4556 static int io_getxattr_prep(struct io_kiocb *req,
4557 const struct io_uring_sqe *sqe)
4559 struct io_xattr *ix = &req->xattr;
4560 const char __user *path;
4563 ret = __io_getxattr_prep(req, sqe);
4567 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4569 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4570 if (IS_ERR(ix->filename)) {
4571 ret = PTR_ERR(ix->filename);
4572 ix->filename = NULL;
4578 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4580 struct io_xattr *ix = &req->xattr;
4583 if (issue_flags & IO_URING_F_NONBLOCK)
4586 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4587 req->file->f_path.dentry,
4590 io_xattr_finish(req, ret);
4594 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4596 struct io_xattr *ix = &req->xattr;
4597 unsigned int lookup_flags = LOOKUP_FOLLOW;
4601 if (issue_flags & IO_URING_F_NONBLOCK)
4605 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4607 ret = do_getxattr(mnt_user_ns(path.mnt),
4612 if (retry_estale(ret, lookup_flags)) {
4613 lookup_flags |= LOOKUP_REVAL;
4618 io_xattr_finish(req, ret);
4622 static int __io_setxattr_prep(struct io_kiocb *req,
4623 const struct io_uring_sqe *sqe)
4625 struct io_xattr *ix = &req->xattr;
4626 const char __user *name;
4629 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4632 ix->filename = NULL;
4633 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4634 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4635 ix->ctx.kvalue = NULL;
4636 ix->ctx.size = READ_ONCE(sqe->len);
4637 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4639 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4643 ret = setxattr_copy(name, &ix->ctx);
4645 kfree(ix->ctx.kname);
4649 req->flags |= REQ_F_NEED_CLEANUP;
4653 static int io_setxattr_prep(struct io_kiocb *req,
4654 const struct io_uring_sqe *sqe)
4656 struct io_xattr *ix = &req->xattr;
4657 const char __user *path;
4660 ret = __io_setxattr_prep(req, sqe);
4664 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4666 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4667 if (IS_ERR(ix->filename)) {
4668 ret = PTR_ERR(ix->filename);
4669 ix->filename = NULL;
4675 static int io_fsetxattr_prep(struct io_kiocb *req,
4676 const struct io_uring_sqe *sqe)
4678 return __io_setxattr_prep(req, sqe);
4681 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4684 struct io_xattr *ix = &req->xattr;
4687 ret = mnt_want_write(path->mnt);
4689 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4690 mnt_drop_write(path->mnt);
4696 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4700 if (issue_flags & IO_URING_F_NONBLOCK)
4703 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4704 io_xattr_finish(req, ret);
4709 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4711 struct io_xattr *ix = &req->xattr;
4712 unsigned int lookup_flags = LOOKUP_FOLLOW;
4716 if (issue_flags & IO_URING_F_NONBLOCK)
4720 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4722 ret = __io_setxattr(req, issue_flags, &path);
4724 if (retry_estale(ret, lookup_flags)) {
4725 lookup_flags |= LOOKUP_REVAL;
4730 io_xattr_finish(req, ret);
4734 static int io_unlinkat_prep(struct io_kiocb *req,
4735 const struct io_uring_sqe *sqe)
4737 struct io_unlink *un = &req->unlink;
4738 const char __user *fname;
4740 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4742 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4745 un->dfd = READ_ONCE(sqe->fd);
4747 un->flags = READ_ONCE(sqe->unlink_flags);
4748 if (un->flags & ~AT_REMOVEDIR)
4751 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4752 un->filename = getname(fname);
4753 if (IS_ERR(un->filename))
4754 return PTR_ERR(un->filename);
4756 req->flags |= REQ_F_NEED_CLEANUP;
4760 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4762 struct io_unlink *un = &req->unlink;
4765 if (issue_flags & IO_URING_F_NONBLOCK)
4768 if (un->flags & AT_REMOVEDIR)
4769 ret = do_rmdir(un->dfd, un->filename);
4771 ret = do_unlinkat(un->dfd, un->filename);
4773 req->flags &= ~REQ_F_NEED_CLEANUP;
4776 io_req_complete(req, ret);
4780 static int io_mkdirat_prep(struct io_kiocb *req,
4781 const struct io_uring_sqe *sqe)
4783 struct io_mkdir *mkd = &req->mkdir;
4784 const char __user *fname;
4786 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4788 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4791 mkd->dfd = READ_ONCE(sqe->fd);
4792 mkd->mode = READ_ONCE(sqe->len);
4794 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4795 mkd->filename = getname(fname);
4796 if (IS_ERR(mkd->filename))
4797 return PTR_ERR(mkd->filename);
4799 req->flags |= REQ_F_NEED_CLEANUP;
4803 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4805 struct io_mkdir *mkd = &req->mkdir;
4808 if (issue_flags & IO_URING_F_NONBLOCK)
4811 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4813 req->flags &= ~REQ_F_NEED_CLEANUP;
4816 io_req_complete(req, ret);
4820 static int io_symlinkat_prep(struct io_kiocb *req,
4821 const struct io_uring_sqe *sqe)
4823 struct io_symlink *sl = &req->symlink;
4824 const char __user *oldpath, *newpath;
4826 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4828 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4831 sl->new_dfd = READ_ONCE(sqe->fd);
4832 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4833 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4835 sl->oldpath = getname(oldpath);
4836 if (IS_ERR(sl->oldpath))
4837 return PTR_ERR(sl->oldpath);
4839 sl->newpath = getname(newpath);
4840 if (IS_ERR(sl->newpath)) {
4841 putname(sl->oldpath);
4842 return PTR_ERR(sl->newpath);
4845 req->flags |= REQ_F_NEED_CLEANUP;
4849 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4851 struct io_symlink *sl = &req->symlink;
4854 if (issue_flags & IO_URING_F_NONBLOCK)
4857 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4859 req->flags &= ~REQ_F_NEED_CLEANUP;
4862 io_req_complete(req, ret);
4866 static int io_linkat_prep(struct io_kiocb *req,
4867 const struct io_uring_sqe *sqe)
4869 struct io_hardlink *lnk = &req->hardlink;
4870 const char __user *oldf, *newf;
4872 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4874 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4877 lnk->old_dfd = READ_ONCE(sqe->fd);
4878 lnk->new_dfd = READ_ONCE(sqe->len);
4879 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4880 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4881 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4883 lnk->oldpath = getname(oldf);
4884 if (IS_ERR(lnk->oldpath))
4885 return PTR_ERR(lnk->oldpath);
4887 lnk->newpath = getname(newf);
4888 if (IS_ERR(lnk->newpath)) {
4889 putname(lnk->oldpath);
4890 return PTR_ERR(lnk->newpath);
4893 req->flags |= REQ_F_NEED_CLEANUP;
4897 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4899 struct io_hardlink *lnk = &req->hardlink;
4902 if (issue_flags & IO_URING_F_NONBLOCK)
4905 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4906 lnk->newpath, lnk->flags);
4908 req->flags &= ~REQ_F_NEED_CLEANUP;
4911 io_req_complete(req, ret);
4915 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
4917 req->uring_cmd.task_work_cb(&req->uring_cmd);
4920 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
4921 void (*task_work_cb)(struct io_uring_cmd *))
4923 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4925 req->uring_cmd.task_work_cb = task_work_cb;
4926 req->io_task_work.func = io_uring_cmd_work;
4927 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
4929 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
4932 * Called by consumers of io_uring_cmd, if they originally returned
4933 * -EIOCBQUEUED upon receiving the command.
4935 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
4937 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4941 if (req->ctx->flags & IORING_SETUP_CQE32)
4942 __io_req_complete32(req, 0, ret, 0, res2, 0);
4944 io_req_complete(req, ret);
4946 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
4948 static int io_uring_cmd_prep_async(struct io_kiocb *req)
4952 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
4954 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
4958 static int io_uring_cmd_prep(struct io_kiocb *req,
4959 const struct io_uring_sqe *sqe)
4961 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4965 ioucmd->cmd = sqe->cmd;
4966 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
4970 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
4972 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4973 struct io_ring_ctx *ctx = req->ctx;
4974 struct file *file = req->file;
4977 if (!req->file->f_op->uring_cmd)
4980 if (ctx->flags & IORING_SETUP_SQE128)
4981 issue_flags |= IO_URING_F_SQE128;
4982 if (ctx->flags & IORING_SETUP_CQE32)
4983 issue_flags |= IO_URING_F_CQE32;
4984 if (ctx->flags & IORING_SETUP_IOPOLL)
4985 issue_flags |= IO_URING_F_IOPOLL;
4987 if (req_has_async_data(req))
4988 ioucmd->cmd = req->async_data;
4990 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
4991 if (ret == -EAGAIN) {
4992 if (!req_has_async_data(req)) {
4993 if (io_alloc_async_data(req))
4995 io_uring_cmd_prep_async(req);
5000 if (ret != -EIOCBQUEUED)
5001 io_uring_cmd_done(ioucmd, ret, 0);
5005 static int io_shutdown_prep(struct io_kiocb *req,
5006 const struct io_uring_sqe *sqe)
5008 #if defined(CONFIG_NET)
5009 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
5010 sqe->buf_index || sqe->splice_fd_in))
5013 req->shutdown.how = READ_ONCE(sqe->len);
5020 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
5022 #if defined(CONFIG_NET)
5023 struct socket *sock;
5026 if (issue_flags & IO_URING_F_NONBLOCK)
5029 sock = sock_from_file(req->file);
5030 if (unlikely(!sock))
5033 ret = __sys_shutdown_sock(sock, req->shutdown.how);
5036 io_req_complete(req, ret);
5043 static int __io_splice_prep(struct io_kiocb *req,
5044 const struct io_uring_sqe *sqe)
5046 struct io_splice *sp = &req->splice;
5047 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
5049 sp->len = READ_ONCE(sqe->len);
5050 sp->flags = READ_ONCE(sqe->splice_flags);
5051 if (unlikely(sp->flags & ~valid_flags))
5053 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
5057 static int io_tee_prep(struct io_kiocb *req,
5058 const struct io_uring_sqe *sqe)
5060 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
5062 return __io_splice_prep(req, sqe);
5065 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
5067 struct io_splice *sp = &req->splice;
5068 struct file *out = sp->file_out;
5069 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5073 if (issue_flags & IO_URING_F_NONBLOCK)
5076 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5077 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5079 in = io_file_get_normal(req, sp->splice_fd_in);
5086 ret = do_tee(in, out, sp->len, flags);
5088 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5093 io_req_complete(req, ret);
5097 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5099 struct io_splice *sp = &req->splice;
5101 sp->off_in = READ_ONCE(sqe->splice_off_in);
5102 sp->off_out = READ_ONCE(sqe->off);
5103 return __io_splice_prep(req, sqe);
5106 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
5108 struct io_splice *sp = &req->splice;
5109 struct file *out = sp->file_out;
5110 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
5111 loff_t *poff_in, *poff_out;
5115 if (issue_flags & IO_URING_F_NONBLOCK)
5118 if (sp->flags & SPLICE_F_FD_IN_FIXED)
5119 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
5121 in = io_file_get_normal(req, sp->splice_fd_in);
5127 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
5128 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
5131 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
5133 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5138 io_req_complete(req, ret);
5142 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5145 * If the ring is setup with CQE32, relay back addr/addr
5147 if (req->ctx->flags & IORING_SETUP_CQE32) {
5148 req->nop.extra1 = READ_ONCE(sqe->addr);
5149 req->nop.extra2 = READ_ONCE(sqe->addr2);
5156 * IORING_OP_NOP just posts a completion event, nothing else.
5158 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5160 if (!(req->ctx->flags & IORING_SETUP_CQE32))
5161 __io_req_complete(req, issue_flags, 0, 0);
5163 __io_req_complete32(req, issue_flags, 0, 0, req->nop.extra1,
5168 static int io_msg_ring_prep(struct io_kiocb *req,
5169 const struct io_uring_sqe *sqe)
5171 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5172 sqe->buf_index || sqe->personality))
5175 req->msg.user_data = READ_ONCE(sqe->off);
5176 req->msg.len = READ_ONCE(sqe->len);
5180 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5182 struct io_ring_ctx *target_ctx;
5183 struct io_msg *msg = &req->msg;
5188 if (req->file->f_op != &io_uring_fops)
5192 target_ctx = req->file->private_data;
5194 spin_lock(&target_ctx->completion_lock);
5195 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5196 io_commit_cqring(target_ctx);
5197 spin_unlock(&target_ctx->completion_lock);
5200 io_cqring_ev_posted(target_ctx);
5207 __io_req_complete(req, issue_flags, ret, 0);
5211 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5213 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5216 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5217 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5220 req->sync.off = READ_ONCE(sqe->off);
5221 req->sync.len = READ_ONCE(sqe->len);
5225 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5227 loff_t end = req->sync.off + req->sync.len;
5230 /* fsync always requires a blocking context */
5231 if (issue_flags & IO_URING_F_NONBLOCK)
5234 ret = vfs_fsync_range(req->file, req->sync.off,
5235 end > 0 ? end : LLONG_MAX,
5236 req->sync.flags & IORING_FSYNC_DATASYNC);
5239 io_req_complete(req, ret);
5243 static int io_fallocate_prep(struct io_kiocb *req,
5244 const struct io_uring_sqe *sqe)
5246 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5249 req->sync.off = READ_ONCE(sqe->off);
5250 req->sync.len = READ_ONCE(sqe->addr);
5251 req->sync.mode = READ_ONCE(sqe->len);
5255 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5259 /* fallocate always requiring blocking context */
5260 if (issue_flags & IO_URING_F_NONBLOCK)
5262 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5267 fsnotify_modify(req->file);
5268 io_req_complete(req, ret);
5272 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5274 const char __user *fname;
5277 if (unlikely(sqe->buf_index))
5279 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5282 /* open.how should be already initialised */
5283 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5284 req->open.how.flags |= O_LARGEFILE;
5286 req->open.dfd = READ_ONCE(sqe->fd);
5287 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5288 req->open.filename = getname(fname);
5289 if (IS_ERR(req->open.filename)) {
5290 ret = PTR_ERR(req->open.filename);
5291 req->open.filename = NULL;
5295 req->open.file_slot = READ_ONCE(sqe->file_index);
5296 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5299 req->open.nofile = rlimit(RLIMIT_NOFILE);
5300 req->flags |= REQ_F_NEED_CLEANUP;
5304 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5306 u64 mode = READ_ONCE(sqe->len);
5307 u64 flags = READ_ONCE(sqe->open_flags);
5309 req->open.how = build_open_how(flags, mode);
5310 return __io_openat_prep(req, sqe);
5313 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5315 struct open_how __user *how;
5319 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5320 len = READ_ONCE(sqe->len);
5321 if (len < OPEN_HOW_SIZE_VER0)
5324 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5329 return __io_openat_prep(req, sqe);
5332 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5334 struct open_flags op;
5336 bool resolve_nonblock, nonblock_set;
5337 bool fixed = !!req->open.file_slot;
5340 ret = build_open_flags(&req->open.how, &op);
5343 nonblock_set = op.open_flag & O_NONBLOCK;
5344 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5345 if (issue_flags & IO_URING_F_NONBLOCK) {
5347 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5348 * it'll always -EAGAIN
5350 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5352 op.lookup_flags |= LOOKUP_CACHED;
5353 op.open_flag |= O_NONBLOCK;
5357 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5362 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5365 * We could hang on to this 'fd' on retrying, but seems like
5366 * marginal gain for something that is now known to be a slower
5367 * path. So just put it, and we'll get a new one when we retry.
5372 ret = PTR_ERR(file);
5373 /* only retry if RESOLVE_CACHED wasn't already set by application */
5374 if (ret == -EAGAIN &&
5375 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5380 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5381 file->f_flags &= ~O_NONBLOCK;
5382 fsnotify_open(file);
5385 fd_install(ret, file);
5387 ret = io_install_fixed_file(req, file, issue_flags,
5388 req->open.file_slot - 1);
5390 putname(req->open.filename);
5391 req->flags &= ~REQ_F_NEED_CLEANUP;
5394 __io_req_complete(req, issue_flags, ret, 0);
5398 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5400 return io_openat2(req, issue_flags);
5403 static int io_remove_buffers_prep(struct io_kiocb *req,
5404 const struct io_uring_sqe *sqe)
5406 struct io_provide_buf *p = &req->pbuf;
5409 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5413 tmp = READ_ONCE(sqe->fd);
5414 if (!tmp || tmp > USHRT_MAX)
5417 memset(p, 0, sizeof(*p));
5419 p->bgid = READ_ONCE(sqe->buf_group);
5423 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5424 struct io_buffer_list *bl, unsigned nbufs)
5428 /* shouldn't happen */
5432 /* the head kbuf is the list itself */
5433 while (!list_empty(&bl->buf_list)) {
5434 struct io_buffer *nxt;
5436 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5437 list_del(&nxt->list);
5447 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5449 struct io_provide_buf *p = &req->pbuf;
5450 struct io_ring_ctx *ctx = req->ctx;
5451 struct io_buffer_list *bl;
5454 io_ring_submit_lock(ctx, issue_flags);
5457 bl = io_buffer_get_list(ctx, p->bgid);
5459 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5463 /* complete before unlock, IOPOLL may need the lock */
5464 __io_req_complete(req, issue_flags, ret, 0);
5465 io_ring_submit_unlock(ctx, issue_flags);
5469 static int io_provide_buffers_prep(struct io_kiocb *req,
5470 const struct io_uring_sqe *sqe)
5472 unsigned long size, tmp_check;
5473 struct io_provide_buf *p = &req->pbuf;
5476 if (sqe->rw_flags || sqe->splice_fd_in)
5479 tmp = READ_ONCE(sqe->fd);
5480 if (!tmp || tmp > USHRT_MAX)
5483 p->addr = READ_ONCE(sqe->addr);
5484 p->len = READ_ONCE(sqe->len);
5486 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5489 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5492 size = (unsigned long)p->len * p->nbufs;
5493 if (!access_ok(u64_to_user_ptr(p->addr), size))
5496 p->bgid = READ_ONCE(sqe->buf_group);
5497 tmp = READ_ONCE(sqe->off);
5498 if (tmp > USHRT_MAX)
5504 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5506 struct io_buffer *buf;
5511 * Completions that don't happen inline (eg not under uring_lock) will
5512 * add to ->io_buffers_comp. If we don't have any free buffers, check
5513 * the completion list and splice those entries first.
5515 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5516 spin_lock(&ctx->completion_lock);
5517 if (!list_empty(&ctx->io_buffers_comp)) {
5518 list_splice_init(&ctx->io_buffers_comp,
5519 &ctx->io_buffers_cache);
5520 spin_unlock(&ctx->completion_lock);
5523 spin_unlock(&ctx->completion_lock);
5527 * No free buffers and no completion entries either. Allocate a new
5528 * page worth of buffer entries and add those to our freelist.
5530 page = alloc_page(GFP_KERNEL_ACCOUNT);
5534 list_add(&page->lru, &ctx->io_buffers_pages);
5536 buf = page_address(page);
5537 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5538 while (bufs_in_page) {
5539 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5547 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5548 struct io_buffer_list *bl)
5550 struct io_buffer *buf;
5551 u64 addr = pbuf->addr;
5552 int i, bid = pbuf->bid;
5554 for (i = 0; i < pbuf->nbufs; i++) {
5555 if (list_empty(&ctx->io_buffers_cache) &&
5556 io_refill_buffer_cache(ctx))
5558 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5560 list_move_tail(&buf->list, &bl->buf_list);
5562 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5564 buf->bgid = pbuf->bgid;
5570 return i ? 0 : -ENOMEM;
5573 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5577 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5582 for (i = 0; i < BGID_ARRAY; i++) {
5583 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5584 ctx->io_bl[i].bgid = i;
5590 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5592 struct io_provide_buf *p = &req->pbuf;
5593 struct io_ring_ctx *ctx = req->ctx;
5594 struct io_buffer_list *bl;
5597 io_ring_submit_lock(ctx, issue_flags);
5599 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5600 ret = io_init_bl_list(ctx);
5605 bl = io_buffer_get_list(ctx, p->bgid);
5606 if (unlikely(!bl)) {
5607 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
5612 ret = io_buffer_add_list(ctx, bl, p->bgid);
5619 ret = io_add_buffers(ctx, p, bl);
5623 /* complete before unlock, IOPOLL may need the lock */
5624 __io_req_complete(req, issue_flags, ret, 0);
5625 io_ring_submit_unlock(ctx, issue_flags);
5629 static int io_epoll_ctl_prep(struct io_kiocb *req,
5630 const struct io_uring_sqe *sqe)
5632 #if defined(CONFIG_EPOLL)
5633 if (sqe->buf_index || sqe->splice_fd_in)
5636 req->epoll.epfd = READ_ONCE(sqe->fd);
5637 req->epoll.op = READ_ONCE(sqe->len);
5638 req->epoll.fd = READ_ONCE(sqe->off);
5640 if (ep_op_has_event(req->epoll.op)) {
5641 struct epoll_event __user *ev;
5643 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5644 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5654 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5656 #if defined(CONFIG_EPOLL)
5657 struct io_epoll *ie = &req->epoll;
5659 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5661 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5662 if (force_nonblock && ret == -EAGAIN)
5667 __io_req_complete(req, issue_flags, ret, 0);
5674 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5676 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5677 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5680 req->madvise.addr = READ_ONCE(sqe->addr);
5681 req->madvise.len = READ_ONCE(sqe->len);
5682 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5689 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5691 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5692 struct io_madvise *ma = &req->madvise;
5695 if (issue_flags & IO_URING_F_NONBLOCK)
5698 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5701 io_req_complete(req, ret);
5708 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5710 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5713 req->fadvise.offset = READ_ONCE(sqe->off);
5714 req->fadvise.len = READ_ONCE(sqe->len);
5715 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5719 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5721 struct io_fadvise *fa = &req->fadvise;
5724 if (issue_flags & IO_URING_F_NONBLOCK) {
5725 switch (fa->advice) {
5726 case POSIX_FADV_NORMAL:
5727 case POSIX_FADV_RANDOM:
5728 case POSIX_FADV_SEQUENTIAL:
5735 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5738 __io_req_complete(req, issue_flags, ret, 0);
5742 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5744 const char __user *path;
5746 if (sqe->buf_index || sqe->splice_fd_in)
5748 if (req->flags & REQ_F_FIXED_FILE)
5751 req->statx.dfd = READ_ONCE(sqe->fd);
5752 req->statx.mask = READ_ONCE(sqe->len);
5753 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5754 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5755 req->statx.flags = READ_ONCE(sqe->statx_flags);
5757 req->statx.filename = getname_flags(path,
5758 getname_statx_lookup_flags(req->statx.flags),
5761 if (IS_ERR(req->statx.filename)) {
5762 int ret = PTR_ERR(req->statx.filename);
5764 req->statx.filename = NULL;
5768 req->flags |= REQ_F_NEED_CLEANUP;
5772 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5774 struct io_statx *ctx = &req->statx;
5777 if (issue_flags & IO_URING_F_NONBLOCK)
5780 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5785 io_req_complete(req, ret);
5789 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5791 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5793 if (req->flags & REQ_F_FIXED_FILE)
5796 req->close.fd = READ_ONCE(sqe->fd);
5797 req->close.file_slot = READ_ONCE(sqe->file_index);
5798 if (req->close.file_slot && req->close.fd)
5804 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5806 struct files_struct *files = current->files;
5807 struct io_close *close = &req->close;
5808 struct fdtable *fdt;
5809 struct file *file = NULL;
5812 if (req->close.file_slot) {
5813 ret = io_close_fixed(req, issue_flags);
5817 spin_lock(&files->file_lock);
5818 fdt = files_fdtable(files);
5819 if (close->fd >= fdt->max_fds) {
5820 spin_unlock(&files->file_lock);
5823 file = fdt->fd[close->fd];
5824 if (!file || file->f_op == &io_uring_fops) {
5825 spin_unlock(&files->file_lock);
5830 /* if the file has a flush method, be safe and punt to async */
5831 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5832 spin_unlock(&files->file_lock);
5836 ret = __close_fd_get_file(close->fd, &file);
5837 spin_unlock(&files->file_lock);
5844 /* No ->flush() or already async, safely close from here */
5845 ret = filp_close(file, current->files);
5851 __io_req_complete(req, issue_flags, ret, 0);
5855 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5857 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5860 req->sync.off = READ_ONCE(sqe->off);
5861 req->sync.len = READ_ONCE(sqe->len);
5862 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5866 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5870 /* sync_file_range always requires a blocking context */
5871 if (issue_flags & IO_URING_F_NONBLOCK)
5874 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5878 io_req_complete(req, ret);
5882 #if defined(CONFIG_NET)
5883 static bool io_net_retry(struct socket *sock, int flags)
5885 if (!(flags & MSG_WAITALL))
5887 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5890 static int io_setup_async_msg(struct io_kiocb *req,
5891 struct io_async_msghdr *kmsg)
5893 struct io_async_msghdr *async_msg = req->async_data;
5897 if (io_alloc_async_data(req)) {
5898 kfree(kmsg->free_iov);
5901 async_msg = req->async_data;
5902 req->flags |= REQ_F_NEED_CLEANUP;
5903 memcpy(async_msg, kmsg, sizeof(*kmsg));
5904 async_msg->msg.msg_name = &async_msg->addr;
5905 /* if were using fast_iov, set it to the new one */
5906 if (!async_msg->free_iov)
5907 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5912 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5913 struct io_async_msghdr *iomsg)
5915 iomsg->msg.msg_name = &iomsg->addr;
5916 iomsg->free_iov = iomsg->fast_iov;
5917 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5918 req->sr_msg.msg_flags, &iomsg->free_iov);
5921 static int io_sendmsg_prep_async(struct io_kiocb *req)
5925 ret = io_sendmsg_copy_hdr(req, req->async_data);
5927 req->flags |= REQ_F_NEED_CLEANUP;
5931 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5933 struct io_sr_msg *sr = &req->sr_msg;
5935 if (unlikely(sqe->file_index))
5937 if (unlikely(sqe->addr2 || sqe->file_index))
5940 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5941 sr->len = READ_ONCE(sqe->len);
5942 sr->flags = READ_ONCE(sqe->addr2);
5943 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5945 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5946 if (sr->msg_flags & MSG_DONTWAIT)
5947 req->flags |= REQ_F_NOWAIT;
5949 #ifdef CONFIG_COMPAT
5950 if (req->ctx->compat)
5951 sr->msg_flags |= MSG_CMSG_COMPAT;
5957 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5959 struct io_async_msghdr iomsg, *kmsg;
5960 struct io_sr_msg *sr = &req->sr_msg;
5961 struct socket *sock;
5966 sock = sock_from_file(req->file);
5967 if (unlikely(!sock))
5970 if (req_has_async_data(req)) {
5971 kmsg = req->async_data;
5973 ret = io_sendmsg_copy_hdr(req, &iomsg);
5979 if (!(req->flags & REQ_F_POLLED) &&
5980 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5981 return io_setup_async_msg(req, kmsg);
5983 flags = sr->msg_flags;
5984 if (issue_flags & IO_URING_F_NONBLOCK)
5985 flags |= MSG_DONTWAIT;
5986 if (flags & MSG_WAITALL)
5987 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5989 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5991 if (ret < min_ret) {
5992 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5993 return io_setup_async_msg(req, kmsg);
5994 if (ret == -ERESTARTSYS)
5996 if (ret > 0 && io_net_retry(sock, flags)) {
5998 req->flags |= REQ_F_PARTIAL_IO;
5999 return io_setup_async_msg(req, kmsg);
6003 /* fast path, check for non-NULL to avoid function call */
6005 kfree(kmsg->free_iov);
6006 req->flags &= ~REQ_F_NEED_CLEANUP;
6009 else if (sr->done_io)
6011 __io_req_complete(req, issue_flags, ret, 0);
6015 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
6017 struct io_sr_msg *sr = &req->sr_msg;
6020 struct socket *sock;
6025 if (!(req->flags & REQ_F_POLLED) &&
6026 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6029 sock = sock_from_file(req->file);
6030 if (unlikely(!sock))
6033 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
6037 msg.msg_name = NULL;
6038 msg.msg_control = NULL;
6039 msg.msg_controllen = 0;
6040 msg.msg_namelen = 0;
6042 flags = sr->msg_flags;
6043 if (issue_flags & IO_URING_F_NONBLOCK)
6044 flags |= MSG_DONTWAIT;
6045 if (flags & MSG_WAITALL)
6046 min_ret = iov_iter_count(&msg.msg_iter);
6048 msg.msg_flags = flags;
6049 ret = sock_sendmsg(sock, &msg);
6050 if (ret < min_ret) {
6051 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6053 if (ret == -ERESTARTSYS)
6055 if (ret > 0 && io_net_retry(sock, flags)) {
6059 req->flags |= REQ_F_PARTIAL_IO;
6066 else if (sr->done_io)
6068 __io_req_complete(req, issue_flags, ret, 0);
6072 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6073 struct io_async_msghdr *iomsg)
6075 struct io_sr_msg *sr = &req->sr_msg;
6076 struct iovec __user *uiov;
6080 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6081 &iomsg->uaddr, &uiov, &iov_len);
6085 if (req->flags & REQ_F_BUFFER_SELECT) {
6088 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6090 sr->len = iomsg->fast_iov[0].iov_len;
6091 iomsg->free_iov = NULL;
6093 iomsg->free_iov = iomsg->fast_iov;
6094 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6095 &iomsg->free_iov, &iomsg->msg.msg_iter,
6104 #ifdef CONFIG_COMPAT
6105 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6106 struct io_async_msghdr *iomsg)
6108 struct io_sr_msg *sr = &req->sr_msg;
6109 struct compat_iovec __user *uiov;
6114 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6119 uiov = compat_ptr(ptr);
6120 if (req->flags & REQ_F_BUFFER_SELECT) {
6121 compat_ssize_t clen;
6125 if (!access_ok(uiov, sizeof(*uiov)))
6127 if (__get_user(clen, &uiov->iov_len))
6132 iomsg->free_iov = NULL;
6134 iomsg->free_iov = iomsg->fast_iov;
6135 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6136 UIO_FASTIOV, &iomsg->free_iov,
6137 &iomsg->msg.msg_iter, true);
6146 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6147 struct io_async_msghdr *iomsg)
6149 iomsg->msg.msg_name = &iomsg->addr;
6151 #ifdef CONFIG_COMPAT
6152 if (req->ctx->compat)
6153 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6156 return __io_recvmsg_copy_hdr(req, iomsg);
6159 static int io_recvmsg_prep_async(struct io_kiocb *req)
6163 ret = io_recvmsg_copy_hdr(req, req->async_data);
6165 req->flags |= REQ_F_NEED_CLEANUP;
6169 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6171 struct io_sr_msg *sr = &req->sr_msg;
6173 if (unlikely(sqe->file_index))
6175 if (unlikely(sqe->addr2 || sqe->file_index))
6178 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6179 sr->len = READ_ONCE(sqe->len);
6180 sr->flags = READ_ONCE(sqe->addr2);
6181 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6183 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6184 if (sr->msg_flags & MSG_DONTWAIT)
6185 req->flags |= REQ_F_NOWAIT;
6187 #ifdef CONFIG_COMPAT
6188 if (req->ctx->compat)
6189 sr->msg_flags |= MSG_CMSG_COMPAT;
6195 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6197 struct io_async_msghdr iomsg, *kmsg;
6198 struct io_sr_msg *sr = &req->sr_msg;
6199 struct socket *sock;
6201 int ret, min_ret = 0;
6202 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6204 sock = sock_from_file(req->file);
6205 if (unlikely(!sock))
6208 if (req_has_async_data(req)) {
6209 kmsg = req->async_data;
6211 ret = io_recvmsg_copy_hdr(req, &iomsg);
6217 if (!(req->flags & REQ_F_POLLED) &&
6218 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6219 return io_setup_async_msg(req, kmsg);
6221 if (io_do_buffer_select(req)) {
6224 buf = io_buffer_select(req, &sr->len, issue_flags);
6226 return PTR_ERR(buf);
6227 kmsg->fast_iov[0].iov_base = buf;
6228 kmsg->fast_iov[0].iov_len = sr->len;
6229 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6233 flags = sr->msg_flags;
6235 flags |= MSG_DONTWAIT;
6236 if (flags & MSG_WAITALL)
6237 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6239 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6240 if (ret < min_ret) {
6241 if (ret == -EAGAIN && force_nonblock)
6242 return io_setup_async_msg(req, kmsg);
6243 if (ret == -ERESTARTSYS)
6245 if (ret > 0 && io_net_retry(sock, flags)) {
6247 req->flags |= REQ_F_PARTIAL_IO;
6248 return io_setup_async_msg(req, kmsg);
6251 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6255 /* fast path, check for non-NULL to avoid function call */
6257 kfree(kmsg->free_iov);
6258 req->flags &= ~REQ_F_NEED_CLEANUP;
6261 else if (sr->done_io)
6263 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
6267 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6269 struct io_sr_msg *sr = &req->sr_msg;
6271 struct socket *sock;
6274 int ret, min_ret = 0;
6275 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6277 if (!(req->flags & REQ_F_POLLED) &&
6278 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6281 sock = sock_from_file(req->file);
6282 if (unlikely(!sock))
6285 if (io_do_buffer_select(req)) {
6288 buf = io_buffer_select(req, &sr->len, issue_flags);
6290 return PTR_ERR(buf);
6294 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6298 msg.msg_name = NULL;
6299 msg.msg_control = NULL;
6300 msg.msg_controllen = 0;
6301 msg.msg_namelen = 0;
6302 msg.msg_iocb = NULL;
6305 flags = sr->msg_flags;
6307 flags |= MSG_DONTWAIT;
6308 if (flags & MSG_WAITALL)
6309 min_ret = iov_iter_count(&msg.msg_iter);
6311 ret = sock_recvmsg(sock, &msg, flags);
6312 if (ret < min_ret) {
6313 if (ret == -EAGAIN && force_nonblock)
6315 if (ret == -ERESTARTSYS)
6317 if (ret > 0 && io_net_retry(sock, flags)) {
6321 req->flags |= REQ_F_PARTIAL_IO;
6325 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6332 else if (sr->done_io)
6334 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
6338 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6340 struct io_accept *accept = &req->accept;
6342 if (sqe->len || sqe->buf_index)
6345 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6346 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6347 accept->flags = READ_ONCE(sqe->accept_flags);
6348 accept->nofile = rlimit(RLIMIT_NOFILE);
6350 accept->file_slot = READ_ONCE(sqe->file_index);
6351 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
6353 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6355 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6356 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6360 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6362 struct io_accept *accept = &req->accept;
6363 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6364 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6365 bool fixed = !!accept->file_slot;
6370 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6371 if (unlikely(fd < 0))
6374 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6379 ret = PTR_ERR(file);
6380 if (ret == -EAGAIN && force_nonblock)
6382 if (ret == -ERESTARTSYS)
6385 } else if (!fixed) {
6386 fd_install(fd, file);
6389 ret = io_install_fixed_file(req, file, issue_flags,
6390 accept->file_slot - 1);
6392 __io_req_complete(req, issue_flags, ret, 0);
6396 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6398 struct io_socket *sock = &req->sock;
6400 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6403 sock->domain = READ_ONCE(sqe->fd);
6404 sock->type = READ_ONCE(sqe->off);
6405 sock->protocol = READ_ONCE(sqe->len);
6406 sock->file_slot = READ_ONCE(sqe->file_index);
6407 sock->nofile = rlimit(RLIMIT_NOFILE);
6409 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6410 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6412 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6417 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6419 struct io_socket *sock = &req->sock;
6420 bool fixed = !!sock->file_slot;
6425 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6426 if (unlikely(fd < 0))
6429 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6433 ret = PTR_ERR(file);
6434 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6436 if (ret == -ERESTARTSYS)
6439 } else if (!fixed) {
6440 fd_install(fd, file);
6443 ret = io_install_fixed_file(req, file, issue_flags,
6444 sock->file_slot - 1);
6446 __io_req_complete(req, issue_flags, ret, 0);
6450 static int io_connect_prep_async(struct io_kiocb *req)
6452 struct io_async_connect *io = req->async_data;
6453 struct io_connect *conn = &req->connect;
6455 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6458 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6460 struct io_connect *conn = &req->connect;
6462 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6465 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6466 conn->addr_len = READ_ONCE(sqe->addr2);
6470 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6472 struct io_async_connect __io, *io;
6473 unsigned file_flags;
6475 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6477 if (req_has_async_data(req)) {
6478 io = req->async_data;
6480 ret = move_addr_to_kernel(req->connect.addr,
6481 req->connect.addr_len,
6488 file_flags = force_nonblock ? O_NONBLOCK : 0;
6490 ret = __sys_connect_file(req->file, &io->address,
6491 req->connect.addr_len, file_flags);
6492 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6493 if (req_has_async_data(req))
6495 if (io_alloc_async_data(req)) {
6499 memcpy(req->async_data, &__io, sizeof(__io));
6502 if (ret == -ERESTARTSYS)
6507 __io_req_complete(req, issue_flags, ret, 0);
6510 #else /* !CONFIG_NET */
6511 #define IO_NETOP_FN(op) \
6512 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6514 return -EOPNOTSUPP; \
6517 #define IO_NETOP_PREP(op) \
6519 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6521 return -EOPNOTSUPP; \
6524 #define IO_NETOP_PREP_ASYNC(op) \
6526 static int io_##op##_prep_async(struct io_kiocb *req) \
6528 return -EOPNOTSUPP; \
6531 IO_NETOP_PREP_ASYNC(sendmsg);
6532 IO_NETOP_PREP_ASYNC(recvmsg);
6533 IO_NETOP_PREP_ASYNC(connect);
6534 IO_NETOP_PREP(accept);
6535 IO_NETOP_PREP(socket);
6538 #endif /* CONFIG_NET */
6540 struct io_poll_table {
6541 struct poll_table_struct pt;
6542 struct io_kiocb *req;
6547 #define IO_POLL_CANCEL_FLAG BIT(31)
6548 #define IO_POLL_REF_MASK GENMASK(30, 0)
6551 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6552 * bump it and acquire ownership. It's disallowed to modify requests while not
6553 * owning it, that prevents from races for enqueueing task_work's and b/w
6554 * arming poll and wakeups.
6556 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6558 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6561 static void io_poll_mark_cancelled(struct io_kiocb *req)
6563 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6566 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6568 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6569 if (req->opcode == IORING_OP_POLL_ADD)
6570 return req->async_data;
6571 return req->apoll->double_poll;
6574 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6576 if (req->opcode == IORING_OP_POLL_ADD)
6578 return &req->apoll->poll;
6581 static void io_poll_req_insert(struct io_kiocb *req)
6583 struct io_ring_ctx *ctx = req->ctx;
6584 struct hlist_head *list;
6586 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6587 hlist_add_head(&req->hash_node, list);
6590 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6591 wait_queue_func_t wake_func)
6594 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6595 /* mask in events that we always want/need */
6596 poll->events = events | IO_POLL_UNMASK;
6597 INIT_LIST_HEAD(&poll->wait.entry);
6598 init_waitqueue_func_entry(&poll->wait, wake_func);
6601 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6603 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6606 spin_lock_irq(&head->lock);
6607 list_del_init(&poll->wait.entry);
6609 spin_unlock_irq(&head->lock);
6613 static void io_poll_remove_entries(struct io_kiocb *req)
6616 * Nothing to do if neither of those flags are set. Avoid dipping
6617 * into the poll/apoll/double cachelines if we can.
6619 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6623 * While we hold the waitqueue lock and the waitqueue is nonempty,
6624 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6625 * lock in the first place can race with the waitqueue being freed.
6627 * We solve this as eventpoll does: by taking advantage of the fact that
6628 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6629 * we enter rcu_read_lock() and see that the pointer to the queue is
6630 * non-NULL, we can then lock it without the memory being freed out from
6633 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6634 * case the caller deletes the entry from the queue, leaving it empty.
6635 * In that case, only RCU prevents the queue memory from being freed.
6638 if (req->flags & REQ_F_SINGLE_POLL)
6639 io_poll_remove_entry(io_poll_get_single(req));
6640 if (req->flags & REQ_F_DOUBLE_POLL)
6641 io_poll_remove_entry(io_poll_get_double(req));
6646 * All poll tw should go through this. Checks for poll events, manages
6647 * references, does rewait, etc.
6649 * Returns a negative error on failure. >0 when no action require, which is
6650 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6651 * the request, then the mask is stored in req->cqe.res.
6653 static int io_poll_check_events(struct io_kiocb *req, bool locked)
6655 struct io_ring_ctx *ctx = req->ctx;
6658 /* req->task == current here, checking PF_EXITING is safe */
6659 if (unlikely(req->task->flags & PF_EXITING))
6663 v = atomic_read(&req->poll_refs);
6665 /* tw handler should be the owner, and so have some references */
6666 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6668 if (v & IO_POLL_CANCEL_FLAG)
6671 if (!req->cqe.res) {
6672 struct poll_table_struct pt = { ._key = req->apoll_events };
6673 unsigned flags = locked ? 0 : IO_URING_F_UNLOCKED;
6675 if (unlikely(!io_assign_file(req, flags)))
6677 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6680 /* multishot, just fill an CQE and proceed */
6681 if (req->cqe.res && !(req->apoll_events & EPOLLONESHOT)) {
6682 __poll_t mask = mangle_poll(req->cqe.res & req->apoll_events);
6685 spin_lock(&ctx->completion_lock);
6686 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, mask,
6688 io_commit_cqring(ctx);
6689 spin_unlock(&ctx->completion_lock);
6690 if (unlikely(!filled))
6692 io_cqring_ev_posted(ctx);
6693 } else if (req->cqe.res) {
6698 * Release all references, retry if someone tried to restart
6699 * task_work while we were executing it.
6701 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6706 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6708 struct io_ring_ctx *ctx = req->ctx;
6711 ret = io_poll_check_events(req, *locked);
6716 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6722 io_poll_remove_entries(req);
6723 spin_lock(&ctx->completion_lock);
6724 hash_del(&req->hash_node);
6725 __io_req_complete_post(req, req->cqe.res, 0);
6726 io_commit_cqring(ctx);
6727 spin_unlock(&ctx->completion_lock);
6728 io_cqring_ev_posted(ctx);
6731 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6733 struct io_ring_ctx *ctx = req->ctx;
6736 ret = io_poll_check_events(req, *locked);
6740 io_poll_remove_entries(req);
6741 spin_lock(&ctx->completion_lock);
6742 hash_del(&req->hash_node);
6743 spin_unlock(&ctx->completion_lock);
6746 io_req_task_submit(req, locked);
6748 io_req_complete_failed(req, ret);
6751 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
6753 req->cqe.res = mask;
6755 * This is useful for poll that is armed on behalf of another
6756 * request, and where the wakeup path could be on a different
6757 * CPU. We want to avoid pulling in req->apoll->events for that
6760 req->apoll_events = events;
6761 if (req->opcode == IORING_OP_POLL_ADD)
6762 req->io_task_work.func = io_poll_task_func;
6764 req->io_task_work.func = io_apoll_task_func;
6766 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6767 io_req_task_work_add(req, false);
6770 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
6772 if (io_poll_get_ownership(req))
6773 __io_poll_execute(req, res, events);
6776 static void io_poll_cancel_req(struct io_kiocb *req)
6778 io_poll_mark_cancelled(req);
6779 /* kick tw, which should complete the request */
6780 io_poll_execute(req, 0, 0);
6783 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6784 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6786 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6789 struct io_kiocb *req = wqe_to_req(wait);
6790 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6792 __poll_t mask = key_to_poll(key);
6794 if (unlikely(mask & POLLFREE)) {
6795 io_poll_mark_cancelled(req);
6796 /* we have to kick tw in case it's not already */
6797 io_poll_execute(req, 0, poll->events);
6800 * If the waitqueue is being freed early but someone is already
6801 * holds ownership over it, we have to tear down the request as
6802 * best we can. That means immediately removing the request from
6803 * its waitqueue and preventing all further accesses to the
6804 * waitqueue via the request.
6806 list_del_init(&poll->wait.entry);
6809 * Careful: this *must* be the last step, since as soon
6810 * as req->head is NULL'ed out, the request can be
6811 * completed and freed, since aio_poll_complete_work()
6812 * will no longer need to take the waitqueue lock.
6814 smp_store_release(&poll->head, NULL);
6818 /* for instances that support it check for an event match first */
6819 if (mask && !(mask & poll->events))
6822 if (io_poll_get_ownership(req)) {
6823 /* optional, saves extra locking for removal in tw handler */
6824 if (mask && poll->events & EPOLLONESHOT) {
6825 list_del_init(&poll->wait.entry);
6827 if (wqe_is_double(wait))
6828 req->flags &= ~REQ_F_DOUBLE_POLL;
6830 req->flags &= ~REQ_F_SINGLE_POLL;
6832 __io_poll_execute(req, mask, poll->events);
6837 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6838 struct wait_queue_head *head,
6839 struct io_poll_iocb **poll_ptr)
6841 struct io_kiocb *req = pt->req;
6842 unsigned long wqe_private = (unsigned long) req;
6845 * The file being polled uses multiple waitqueues for poll handling
6846 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6849 if (unlikely(pt->nr_entries)) {
6850 struct io_poll_iocb *first = poll;
6852 /* double add on the same waitqueue head, ignore */
6853 if (first->head == head)
6855 /* already have a 2nd entry, fail a third attempt */
6857 if ((*poll_ptr)->head == head)
6859 pt->error = -EINVAL;
6863 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6865 pt->error = -ENOMEM;
6868 /* mark as double wq entry */
6870 req->flags |= REQ_F_DOUBLE_POLL;
6871 io_init_poll_iocb(poll, first->events, first->wait.func);
6873 if (req->opcode == IORING_OP_POLL_ADD)
6874 req->flags |= REQ_F_ASYNC_DATA;
6877 req->flags |= REQ_F_SINGLE_POLL;
6880 poll->wait.private = (void *) wqe_private;
6882 if (poll->events & EPOLLEXCLUSIVE)
6883 add_wait_queue_exclusive(head, &poll->wait);
6885 add_wait_queue(head, &poll->wait);
6888 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6889 struct poll_table_struct *p)
6891 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6893 __io_queue_proc(&pt->req->poll, pt, head,
6894 (struct io_poll_iocb **) &pt->req->async_data);
6897 static int __io_arm_poll_handler(struct io_kiocb *req,
6898 struct io_poll_iocb *poll,
6899 struct io_poll_table *ipt, __poll_t mask)
6901 struct io_ring_ctx *ctx = req->ctx;
6904 INIT_HLIST_NODE(&req->hash_node);
6905 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
6906 io_init_poll_iocb(poll, mask, io_poll_wake);
6907 poll->file = req->file;
6909 ipt->pt._key = mask;
6912 ipt->nr_entries = 0;
6915 * Take the ownership to delay any tw execution up until we're done
6916 * with poll arming. see io_poll_get_ownership().
6918 atomic_set(&req->poll_refs, 1);
6919 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6921 if (mask && (poll->events & EPOLLONESHOT)) {
6922 io_poll_remove_entries(req);
6923 /* no one else has access to the req, forget about the ref */
6926 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6927 io_poll_remove_entries(req);
6929 ipt->error = -EINVAL;
6933 spin_lock(&ctx->completion_lock);
6934 io_poll_req_insert(req);
6935 spin_unlock(&ctx->completion_lock);
6938 /* can't multishot if failed, just queue the event we've got */
6939 if (unlikely(ipt->error || !ipt->nr_entries))
6940 poll->events |= EPOLLONESHOT;
6941 __io_poll_execute(req, mask, poll->events);
6946 * Release ownership. If someone tried to queue a tw while it was
6947 * locked, kick it off for them.
6949 v = atomic_dec_return(&req->poll_refs);
6950 if (unlikely(v & IO_POLL_REF_MASK))
6951 __io_poll_execute(req, 0, poll->events);
6955 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6956 struct poll_table_struct *p)
6958 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6959 struct async_poll *apoll = pt->req->apoll;
6961 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6970 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6972 const struct io_op_def *def = &io_op_defs[req->opcode];
6973 struct io_ring_ctx *ctx = req->ctx;
6974 struct async_poll *apoll;
6975 struct io_poll_table ipt;
6976 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6979 if (!def->pollin && !def->pollout)
6980 return IO_APOLL_ABORTED;
6981 if (!file_can_poll(req->file))
6982 return IO_APOLL_ABORTED;
6983 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
6984 return IO_APOLL_ABORTED;
6987 mask |= POLLIN | POLLRDNORM;
6989 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6990 if ((req->opcode == IORING_OP_RECVMSG) &&
6991 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6994 mask |= POLLOUT | POLLWRNORM;
6996 if (def->poll_exclusive)
6997 mask |= EPOLLEXCLUSIVE;
6998 if (req->flags & REQ_F_POLLED) {
7000 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7001 !list_empty(&ctx->apoll_cache)) {
7002 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7004 list_del_init(&apoll->poll.wait.entry);
7006 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7007 if (unlikely(!apoll))
7008 return IO_APOLL_ABORTED;
7010 apoll->double_poll = NULL;
7012 req->flags |= REQ_F_POLLED;
7013 ipt.pt._qproc = io_async_queue_proc;
7015 io_kbuf_recycle(req, issue_flags);
7017 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7018 if (ret || ipt.error)
7019 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7021 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7022 mask, apoll->poll.events);
7027 * Returns true if we found and killed one or more poll requests
7029 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7030 struct task_struct *tsk, bool cancel_all)
7032 struct hlist_node *tmp;
7033 struct io_kiocb *req;
7037 spin_lock(&ctx->completion_lock);
7038 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7039 struct hlist_head *list;
7041 list = &ctx->cancel_hash[i];
7042 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7043 if (io_match_task_safe(req, tsk, cancel_all)) {
7044 hlist_del_init(&req->hash_node);
7045 io_poll_cancel_req(req);
7050 spin_unlock(&ctx->completion_lock);
7054 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7055 struct io_cancel_data *cd)
7056 __must_hold(&ctx->completion_lock)
7058 struct hlist_head *list;
7059 struct io_kiocb *req;
7061 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7062 hlist_for_each_entry(req, list, hash_node) {
7063 if (cd->data != req->cqe.user_data)
7065 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7067 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7068 if (cd->seq == req->work.cancel_seq)
7070 req->work.cancel_seq = cd->seq;
7077 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7078 struct io_cancel_data *cd)
7079 __must_hold(&ctx->completion_lock)
7081 struct io_kiocb *req;
7084 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7085 struct hlist_head *list;
7087 list = &ctx->cancel_hash[i];
7088 hlist_for_each_entry(req, list, hash_node) {
7089 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7090 req->file != cd->file)
7092 if (cd->seq == req->work.cancel_seq)
7094 req->work.cancel_seq = cd->seq;
7101 static bool io_poll_disarm(struct io_kiocb *req)
7102 __must_hold(&ctx->completion_lock)
7104 if (!io_poll_get_ownership(req))
7106 io_poll_remove_entries(req);
7107 hash_del(&req->hash_node);
7111 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7112 __must_hold(&ctx->completion_lock)
7114 struct io_kiocb *req;
7116 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7117 req = io_poll_file_find(ctx, cd);
7119 req = io_poll_find(ctx, false, cd);
7122 io_poll_cancel_req(req);
7126 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7131 events = READ_ONCE(sqe->poll32_events);
7133 events = swahw32(events);
7135 if (!(flags & IORING_POLL_ADD_MULTI))
7136 events |= EPOLLONESHOT;
7137 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7140 static int io_poll_update_prep(struct io_kiocb *req,
7141 const struct io_uring_sqe *sqe)
7143 struct io_poll_update *upd = &req->poll_update;
7146 if (sqe->buf_index || sqe->splice_fd_in)
7148 flags = READ_ONCE(sqe->len);
7149 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7150 IORING_POLL_ADD_MULTI))
7152 /* meaningless without update */
7153 if (flags == IORING_POLL_ADD_MULTI)
7156 upd->old_user_data = READ_ONCE(sqe->addr);
7157 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7158 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7160 upd->new_user_data = READ_ONCE(sqe->off);
7161 if (!upd->update_user_data && upd->new_user_data)
7163 if (upd->update_events)
7164 upd->events = io_poll_parse_events(sqe, flags);
7165 else if (sqe->poll32_events)
7171 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7173 struct io_poll_iocb *poll = &req->poll;
7176 if (sqe->buf_index || sqe->off || sqe->addr)
7178 flags = READ_ONCE(sqe->len);
7179 if (flags & ~IORING_POLL_ADD_MULTI)
7181 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7184 io_req_set_refcount(req);
7185 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
7189 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7191 struct io_poll_iocb *poll = &req->poll;
7192 struct io_poll_table ipt;
7195 ipt.pt._qproc = io_poll_queue_proc;
7197 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7198 ret = ret ?: ipt.error;
7200 __io_req_complete(req, issue_flags, ret, 0);
7204 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
7206 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7207 struct io_ring_ctx *ctx = req->ctx;
7208 struct io_kiocb *preq;
7212 spin_lock(&ctx->completion_lock);
7213 preq = io_poll_find(ctx, true, &cd);
7214 if (!preq || !io_poll_disarm(preq)) {
7215 spin_unlock(&ctx->completion_lock);
7216 ret = preq ? -EALREADY : -ENOENT;
7219 spin_unlock(&ctx->completion_lock);
7221 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7222 /* only mask one event flags, keep behavior flags */
7223 if (req->poll_update.update_events) {
7224 preq->poll.events &= ~0xffff;
7225 preq->poll.events |= req->poll_update.events & 0xffff;
7226 preq->poll.events |= IO_POLL_UNMASK;
7228 if (req->poll_update.update_user_data)
7229 preq->cqe.user_data = req->poll_update.new_user_data;
7231 ret2 = io_poll_add(preq, issue_flags);
7232 /* successfully updated, don't complete poll request */
7238 preq->cqe.res = -ECANCELED;
7239 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7240 io_req_task_complete(preq, &locked);
7244 /* complete update request, we're done with it */
7245 __io_req_complete(req, issue_flags, ret, 0);
7249 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7251 struct io_timeout_data *data = container_of(timer,
7252 struct io_timeout_data, timer);
7253 struct io_kiocb *req = data->req;
7254 struct io_ring_ctx *ctx = req->ctx;
7255 unsigned long flags;
7257 spin_lock_irqsave(&ctx->timeout_lock, flags);
7258 list_del_init(&req->timeout.list);
7259 atomic_set(&req->ctx->cq_timeouts,
7260 atomic_read(&req->ctx->cq_timeouts) + 1);
7261 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7263 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7266 req->cqe.res = -ETIME;
7267 req->io_task_work.func = io_req_task_complete;
7268 io_req_task_work_add(req, false);
7269 return HRTIMER_NORESTART;
7272 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7273 struct io_cancel_data *cd)
7274 __must_hold(&ctx->timeout_lock)
7276 struct io_timeout_data *io;
7277 struct io_kiocb *req;
7280 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7281 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7282 cd->data != req->cqe.user_data)
7284 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7285 if (cd->seq == req->work.cancel_seq)
7287 req->work.cancel_seq = cd->seq;
7293 return ERR_PTR(-ENOENT);
7295 io = req->async_data;
7296 if (hrtimer_try_to_cancel(&io->timer) == -1)
7297 return ERR_PTR(-EALREADY);
7298 list_del_init(&req->timeout.list);
7302 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7303 __must_hold(&ctx->completion_lock)
7305 struct io_kiocb *req;
7307 spin_lock_irq(&ctx->timeout_lock);
7308 req = io_timeout_extract(ctx, cd);
7309 spin_unlock_irq(&ctx->timeout_lock);
7312 return PTR_ERR(req);
7313 io_req_task_queue_fail(req, -ECANCELED);
7317 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7319 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7320 case IORING_TIMEOUT_BOOTTIME:
7321 return CLOCK_BOOTTIME;
7322 case IORING_TIMEOUT_REALTIME:
7323 return CLOCK_REALTIME;
7325 /* can't happen, vetted at prep time */
7329 return CLOCK_MONOTONIC;
7333 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7334 struct timespec64 *ts, enum hrtimer_mode mode)
7335 __must_hold(&ctx->timeout_lock)
7337 struct io_timeout_data *io;
7338 struct io_kiocb *req;
7341 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7342 found = user_data == req->cqe.user_data;
7349 io = req->async_data;
7350 if (hrtimer_try_to_cancel(&io->timer) == -1)
7352 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7353 io->timer.function = io_link_timeout_fn;
7354 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7358 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7359 struct timespec64 *ts, enum hrtimer_mode mode)
7360 __must_hold(&ctx->timeout_lock)
7362 struct io_cancel_data cd = { .data = user_data, };
7363 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7364 struct io_timeout_data *data;
7367 return PTR_ERR(req);
7369 req->timeout.off = 0; /* noseq */
7370 data = req->async_data;
7371 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7372 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7373 data->timer.function = io_timeout_fn;
7374 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7378 static int io_timeout_remove_prep(struct io_kiocb *req,
7379 const struct io_uring_sqe *sqe)
7381 struct io_timeout_rem *tr = &req->timeout_rem;
7383 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7385 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7388 tr->ltimeout = false;
7389 tr->addr = READ_ONCE(sqe->addr);
7390 tr->flags = READ_ONCE(sqe->timeout_flags);
7391 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7392 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7394 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7395 tr->ltimeout = true;
7396 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7398 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7400 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7402 } else if (tr->flags) {
7403 /* timeout removal doesn't support flags */
7410 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7412 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7417 * Remove or update an existing timeout command
7419 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7421 struct io_timeout_rem *tr = &req->timeout_rem;
7422 struct io_ring_ctx *ctx = req->ctx;
7425 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7426 struct io_cancel_data cd = { .data = tr->addr, };
7428 spin_lock(&ctx->completion_lock);
7429 ret = io_timeout_cancel(ctx, &cd);
7430 spin_unlock(&ctx->completion_lock);
7432 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7434 spin_lock_irq(&ctx->timeout_lock);
7436 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7438 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7439 spin_unlock_irq(&ctx->timeout_lock);
7444 io_req_complete_post(req, ret, 0);
7448 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
7449 bool is_timeout_link)
7451 struct io_timeout_data *data;
7453 u32 off = READ_ONCE(sqe->off);
7455 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7457 if (off && is_timeout_link)
7459 flags = READ_ONCE(sqe->timeout_flags);
7460 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7461 IORING_TIMEOUT_ETIME_SUCCESS))
7463 /* more than one clock specified is invalid, obviously */
7464 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7467 INIT_LIST_HEAD(&req->timeout.list);
7468 req->timeout.off = off;
7469 if (unlikely(off && !req->ctx->off_timeout_used))
7470 req->ctx->off_timeout_used = true;
7472 if (WARN_ON_ONCE(req_has_async_data(req)))
7474 if (io_alloc_async_data(req))
7477 data = req->async_data;
7479 data->flags = flags;
7481 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7484 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7487 INIT_LIST_HEAD(&req->timeout.list);
7488 data->mode = io_translate_timeout_mode(flags);
7489 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7491 if (is_timeout_link) {
7492 struct io_submit_link *link = &req->ctx->submit_state.link;
7496 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7498 req->timeout.head = link->last;
7499 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7504 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7506 struct io_ring_ctx *ctx = req->ctx;
7507 struct io_timeout_data *data = req->async_data;
7508 struct list_head *entry;
7509 u32 tail, off = req->timeout.off;
7511 spin_lock_irq(&ctx->timeout_lock);
7514 * sqe->off holds how many events that need to occur for this
7515 * timeout event to be satisfied. If it isn't set, then this is
7516 * a pure timeout request, sequence isn't used.
7518 if (io_is_timeout_noseq(req)) {
7519 entry = ctx->timeout_list.prev;
7523 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7524 req->timeout.target_seq = tail + off;
7526 /* Update the last seq here in case io_flush_timeouts() hasn't.
7527 * This is safe because ->completion_lock is held, and submissions
7528 * and completions are never mixed in the same ->completion_lock section.
7530 ctx->cq_last_tm_flush = tail;
7533 * Insertion sort, ensuring the first entry in the list is always
7534 * the one we need first.
7536 list_for_each_prev(entry, &ctx->timeout_list) {
7537 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7540 if (io_is_timeout_noseq(nxt))
7542 /* nxt.seq is behind @tail, otherwise would've been completed */
7543 if (off >= nxt->timeout.target_seq - tail)
7547 list_add(&req->timeout.list, entry);
7548 data->timer.function = io_timeout_fn;
7549 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7550 spin_unlock_irq(&ctx->timeout_lock);
7554 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7556 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7557 struct io_cancel_data *cd = data;
7559 if (req->ctx != cd->ctx)
7561 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7563 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7564 if (req->file != cd->file)
7567 if (req->cqe.user_data != cd->data)
7570 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7571 if (cd->seq == req->work.cancel_seq)
7573 req->work.cancel_seq = cd->seq;
7578 static int io_async_cancel_one(struct io_uring_task *tctx,
7579 struct io_cancel_data *cd)
7581 enum io_wq_cancel cancel_ret;
7585 if (!tctx || !tctx->io_wq)
7588 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7589 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7590 switch (cancel_ret) {
7591 case IO_WQ_CANCEL_OK:
7594 case IO_WQ_CANCEL_RUNNING:
7597 case IO_WQ_CANCEL_NOTFOUND:
7605 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7607 struct io_ring_ctx *ctx = req->ctx;
7610 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7612 ret = io_async_cancel_one(req->task->io_uring, cd);
7614 * Fall-through even for -EALREADY, as we may have poll armed
7615 * that need unarming.
7620 spin_lock(&ctx->completion_lock);
7621 ret = io_poll_cancel(ctx, cd);
7624 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7625 ret = io_timeout_cancel(ctx, cd);
7627 spin_unlock(&ctx->completion_lock);
7631 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7632 IORING_ASYNC_CANCEL_ANY)
7634 static int io_async_cancel_prep(struct io_kiocb *req,
7635 const struct io_uring_sqe *sqe)
7637 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7639 if (sqe->off || sqe->len || sqe->splice_fd_in)
7642 req->cancel.addr = READ_ONCE(sqe->addr);
7643 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7644 if (req->cancel.flags & ~CANCEL_FLAGS)
7646 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7647 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7649 req->cancel.fd = READ_ONCE(sqe->fd);
7655 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7656 unsigned int issue_flags)
7658 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7659 struct io_ring_ctx *ctx = cd->ctx;
7660 struct io_tctx_node *node;
7664 ret = io_try_cancel(req, cd);
7672 /* slow path, try all io-wq's */
7673 io_ring_submit_lock(ctx, issue_flags);
7675 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7676 struct io_uring_task *tctx = node->task->io_uring;
7678 ret = io_async_cancel_one(tctx, cd);
7679 if (ret != -ENOENT) {
7685 io_ring_submit_unlock(ctx, issue_flags);
7686 return all ? nr : ret;
7689 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7691 struct io_cancel_data cd = {
7693 .data = req->cancel.addr,
7694 .flags = req->cancel.flags,
7695 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7699 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7700 if (req->flags & REQ_F_FIXED_FILE)
7701 req->file = io_file_get_fixed(req, req->cancel.fd,
7704 req->file = io_file_get_normal(req, req->cancel.fd);
7709 cd.file = req->file;
7712 ret = __io_async_cancel(&cd, req, issue_flags);
7716 io_req_complete_post(req, ret, 0);
7720 static int io_rsrc_update_prep(struct io_kiocb *req,
7721 const struct io_uring_sqe *sqe)
7723 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7725 if (sqe->rw_flags || sqe->splice_fd_in)
7728 req->rsrc_update.offset = READ_ONCE(sqe->off);
7729 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7730 if (!req->rsrc_update.nr_args)
7732 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7736 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7738 struct io_ring_ctx *ctx = req->ctx;
7739 struct io_uring_rsrc_update2 up;
7742 up.offset = req->rsrc_update.offset;
7743 up.data = req->rsrc_update.arg;
7749 io_ring_submit_lock(ctx, issue_flags);
7750 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
7751 &up, req->rsrc_update.nr_args);
7752 io_ring_submit_unlock(ctx, issue_flags);
7756 __io_req_complete(req, issue_flags, ret, 0);
7760 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7762 switch (req->opcode) {
7764 return io_nop_prep(req, sqe);
7765 case IORING_OP_READV:
7766 case IORING_OP_READ_FIXED:
7767 case IORING_OP_READ:
7768 case IORING_OP_WRITEV:
7769 case IORING_OP_WRITE_FIXED:
7770 case IORING_OP_WRITE:
7771 return io_prep_rw(req, sqe);
7772 case IORING_OP_POLL_ADD:
7773 return io_poll_add_prep(req, sqe);
7774 case IORING_OP_POLL_REMOVE:
7775 return io_poll_update_prep(req, sqe);
7776 case IORING_OP_FSYNC:
7777 return io_fsync_prep(req, sqe);
7778 case IORING_OP_SYNC_FILE_RANGE:
7779 return io_sfr_prep(req, sqe);
7780 case IORING_OP_SENDMSG:
7781 case IORING_OP_SEND:
7782 return io_sendmsg_prep(req, sqe);
7783 case IORING_OP_RECVMSG:
7784 case IORING_OP_RECV:
7785 return io_recvmsg_prep(req, sqe);
7786 case IORING_OP_CONNECT:
7787 return io_connect_prep(req, sqe);
7788 case IORING_OP_TIMEOUT:
7789 return io_timeout_prep(req, sqe, false);
7790 case IORING_OP_TIMEOUT_REMOVE:
7791 return io_timeout_remove_prep(req, sqe);
7792 case IORING_OP_ASYNC_CANCEL:
7793 return io_async_cancel_prep(req, sqe);
7794 case IORING_OP_LINK_TIMEOUT:
7795 return io_timeout_prep(req, sqe, true);
7796 case IORING_OP_ACCEPT:
7797 return io_accept_prep(req, sqe);
7798 case IORING_OP_FALLOCATE:
7799 return io_fallocate_prep(req, sqe);
7800 case IORING_OP_OPENAT:
7801 return io_openat_prep(req, sqe);
7802 case IORING_OP_CLOSE:
7803 return io_close_prep(req, sqe);
7804 case IORING_OP_FILES_UPDATE:
7805 return io_rsrc_update_prep(req, sqe);
7806 case IORING_OP_STATX:
7807 return io_statx_prep(req, sqe);
7808 case IORING_OP_FADVISE:
7809 return io_fadvise_prep(req, sqe);
7810 case IORING_OP_MADVISE:
7811 return io_madvise_prep(req, sqe);
7812 case IORING_OP_OPENAT2:
7813 return io_openat2_prep(req, sqe);
7814 case IORING_OP_EPOLL_CTL:
7815 return io_epoll_ctl_prep(req, sqe);
7816 case IORING_OP_SPLICE:
7817 return io_splice_prep(req, sqe);
7818 case IORING_OP_PROVIDE_BUFFERS:
7819 return io_provide_buffers_prep(req, sqe);
7820 case IORING_OP_REMOVE_BUFFERS:
7821 return io_remove_buffers_prep(req, sqe);
7823 return io_tee_prep(req, sqe);
7824 case IORING_OP_SHUTDOWN:
7825 return io_shutdown_prep(req, sqe);
7826 case IORING_OP_RENAMEAT:
7827 return io_renameat_prep(req, sqe);
7828 case IORING_OP_UNLINKAT:
7829 return io_unlinkat_prep(req, sqe);
7830 case IORING_OP_MKDIRAT:
7831 return io_mkdirat_prep(req, sqe);
7832 case IORING_OP_SYMLINKAT:
7833 return io_symlinkat_prep(req, sqe);
7834 case IORING_OP_LINKAT:
7835 return io_linkat_prep(req, sqe);
7836 case IORING_OP_MSG_RING:
7837 return io_msg_ring_prep(req, sqe);
7838 case IORING_OP_FSETXATTR:
7839 return io_fsetxattr_prep(req, sqe);
7840 case IORING_OP_SETXATTR:
7841 return io_setxattr_prep(req, sqe);
7842 case IORING_OP_FGETXATTR:
7843 return io_fgetxattr_prep(req, sqe);
7844 case IORING_OP_GETXATTR:
7845 return io_getxattr_prep(req, sqe);
7846 case IORING_OP_SOCKET:
7847 return io_socket_prep(req, sqe);
7848 case IORING_OP_URING_CMD:
7849 return io_uring_cmd_prep(req, sqe);
7852 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
7857 static int io_req_prep_async(struct io_kiocb *req)
7859 const struct io_op_def *def = &io_op_defs[req->opcode];
7861 /* assign early for deferred execution for non-fixed file */
7862 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
7863 req->file = io_file_get_normal(req, req->cqe.fd);
7864 if (!def->needs_async_setup)
7866 if (WARN_ON_ONCE(req_has_async_data(req)))
7868 if (io_alloc_async_data(req))
7871 switch (req->opcode) {
7872 case IORING_OP_READV:
7873 return io_rw_prep_async(req, READ);
7874 case IORING_OP_WRITEV:
7875 return io_rw_prep_async(req, WRITE);
7876 case IORING_OP_SENDMSG:
7877 return io_sendmsg_prep_async(req);
7878 case IORING_OP_RECVMSG:
7879 return io_recvmsg_prep_async(req);
7880 case IORING_OP_CONNECT:
7881 return io_connect_prep_async(req);
7882 case IORING_OP_URING_CMD:
7883 return io_uring_cmd_prep_async(req);
7885 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7890 static u32 io_get_sequence(struct io_kiocb *req)
7892 u32 seq = req->ctx->cached_sq_head;
7893 struct io_kiocb *cur;
7895 /* need original cached_sq_head, but it was increased for each req */
7896 io_for_each_link(cur, req)
7901 static __cold void io_drain_req(struct io_kiocb *req)
7903 struct io_ring_ctx *ctx = req->ctx;
7904 struct io_defer_entry *de;
7906 u32 seq = io_get_sequence(req);
7908 /* Still need defer if there is pending req in defer list. */
7909 spin_lock(&ctx->completion_lock);
7910 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7911 spin_unlock(&ctx->completion_lock);
7913 ctx->drain_active = false;
7914 io_req_task_queue(req);
7917 spin_unlock(&ctx->completion_lock);
7919 ret = io_req_prep_async(req);
7922 io_req_complete_failed(req, ret);
7925 io_prep_async_link(req);
7926 de = kmalloc(sizeof(*de), GFP_KERNEL);
7932 spin_lock(&ctx->completion_lock);
7933 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7934 spin_unlock(&ctx->completion_lock);
7939 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7942 list_add_tail(&de->list, &ctx->defer_list);
7943 spin_unlock(&ctx->completion_lock);
7946 static void io_clean_op(struct io_kiocb *req)
7948 if (req->flags & REQ_F_BUFFER_SELECTED) {
7949 spin_lock(&req->ctx->completion_lock);
7950 io_put_kbuf_comp(req);
7951 spin_unlock(&req->ctx->completion_lock);
7954 if (req->flags & REQ_F_NEED_CLEANUP) {
7955 switch (req->opcode) {
7956 case IORING_OP_READV:
7957 case IORING_OP_READ_FIXED:
7958 case IORING_OP_READ:
7959 case IORING_OP_WRITEV:
7960 case IORING_OP_WRITE_FIXED:
7961 case IORING_OP_WRITE: {
7962 struct io_async_rw *io = req->async_data;
7964 kfree(io->free_iovec);
7967 case IORING_OP_RECVMSG:
7968 case IORING_OP_SENDMSG: {
7969 struct io_async_msghdr *io = req->async_data;
7971 kfree(io->free_iov);
7974 case IORING_OP_OPENAT:
7975 case IORING_OP_OPENAT2:
7976 if (req->open.filename)
7977 putname(req->open.filename);
7979 case IORING_OP_RENAMEAT:
7980 putname(req->rename.oldpath);
7981 putname(req->rename.newpath);
7983 case IORING_OP_UNLINKAT:
7984 putname(req->unlink.filename);
7986 case IORING_OP_MKDIRAT:
7987 putname(req->mkdir.filename);
7989 case IORING_OP_SYMLINKAT:
7990 putname(req->symlink.oldpath);
7991 putname(req->symlink.newpath);
7993 case IORING_OP_LINKAT:
7994 putname(req->hardlink.oldpath);
7995 putname(req->hardlink.newpath);
7997 case IORING_OP_STATX:
7998 if (req->statx.filename)
7999 putname(req->statx.filename);
8001 case IORING_OP_SETXATTR:
8002 case IORING_OP_FSETXATTR:
8003 case IORING_OP_GETXATTR:
8004 case IORING_OP_FGETXATTR:
8005 __io_xattr_finish(req);
8009 if ((req->flags & REQ_F_POLLED) && req->apoll) {
8010 kfree(req->apoll->double_poll);
8014 if (req->flags & REQ_F_CREDS)
8015 put_cred(req->creds);
8016 if (req->flags & REQ_F_ASYNC_DATA) {
8017 kfree(req->async_data);
8018 req->async_data = NULL;
8020 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8023 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8025 if (req->file || !io_op_defs[req->opcode].needs_file)
8028 if (req->flags & REQ_F_FIXED_FILE)
8029 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8031 req->file = io_file_get_normal(req, req->cqe.fd);
8036 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8038 const struct cred *creds = NULL;
8041 if (unlikely(!io_assign_file(req, issue_flags)))
8044 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8045 creds = override_creds(req->creds);
8047 if (!io_op_defs[req->opcode].audit_skip)
8048 audit_uring_entry(req->opcode);
8050 switch (req->opcode) {
8052 ret = io_nop(req, issue_flags);
8054 case IORING_OP_READV:
8055 case IORING_OP_READ_FIXED:
8056 case IORING_OP_READ:
8057 ret = io_read(req, issue_flags);
8059 case IORING_OP_WRITEV:
8060 case IORING_OP_WRITE_FIXED:
8061 case IORING_OP_WRITE:
8062 ret = io_write(req, issue_flags);
8064 case IORING_OP_FSYNC:
8065 ret = io_fsync(req, issue_flags);
8067 case IORING_OP_POLL_ADD:
8068 ret = io_poll_add(req, issue_flags);
8070 case IORING_OP_POLL_REMOVE:
8071 ret = io_poll_update(req, issue_flags);
8073 case IORING_OP_SYNC_FILE_RANGE:
8074 ret = io_sync_file_range(req, issue_flags);
8076 case IORING_OP_SENDMSG:
8077 ret = io_sendmsg(req, issue_flags);
8079 case IORING_OP_SEND:
8080 ret = io_send(req, issue_flags);
8082 case IORING_OP_RECVMSG:
8083 ret = io_recvmsg(req, issue_flags);
8085 case IORING_OP_RECV:
8086 ret = io_recv(req, issue_flags);
8088 case IORING_OP_TIMEOUT:
8089 ret = io_timeout(req, issue_flags);
8091 case IORING_OP_TIMEOUT_REMOVE:
8092 ret = io_timeout_remove(req, issue_flags);
8094 case IORING_OP_ACCEPT:
8095 ret = io_accept(req, issue_flags);
8097 case IORING_OP_CONNECT:
8098 ret = io_connect(req, issue_flags);
8100 case IORING_OP_ASYNC_CANCEL:
8101 ret = io_async_cancel(req, issue_flags);
8103 case IORING_OP_FALLOCATE:
8104 ret = io_fallocate(req, issue_flags);
8106 case IORING_OP_OPENAT:
8107 ret = io_openat(req, issue_flags);
8109 case IORING_OP_CLOSE:
8110 ret = io_close(req, issue_flags);
8112 case IORING_OP_FILES_UPDATE:
8113 ret = io_files_update(req, issue_flags);
8115 case IORING_OP_STATX:
8116 ret = io_statx(req, issue_flags);
8118 case IORING_OP_FADVISE:
8119 ret = io_fadvise(req, issue_flags);
8121 case IORING_OP_MADVISE:
8122 ret = io_madvise(req, issue_flags);
8124 case IORING_OP_OPENAT2:
8125 ret = io_openat2(req, issue_flags);
8127 case IORING_OP_EPOLL_CTL:
8128 ret = io_epoll_ctl(req, issue_flags);
8130 case IORING_OP_SPLICE:
8131 ret = io_splice(req, issue_flags);
8133 case IORING_OP_PROVIDE_BUFFERS:
8134 ret = io_provide_buffers(req, issue_flags);
8136 case IORING_OP_REMOVE_BUFFERS:
8137 ret = io_remove_buffers(req, issue_flags);
8140 ret = io_tee(req, issue_flags);
8142 case IORING_OP_SHUTDOWN:
8143 ret = io_shutdown(req, issue_flags);
8145 case IORING_OP_RENAMEAT:
8146 ret = io_renameat(req, issue_flags);
8148 case IORING_OP_UNLINKAT:
8149 ret = io_unlinkat(req, issue_flags);
8151 case IORING_OP_MKDIRAT:
8152 ret = io_mkdirat(req, issue_flags);
8154 case IORING_OP_SYMLINKAT:
8155 ret = io_symlinkat(req, issue_flags);
8157 case IORING_OP_LINKAT:
8158 ret = io_linkat(req, issue_flags);
8160 case IORING_OP_MSG_RING:
8161 ret = io_msg_ring(req, issue_flags);
8163 case IORING_OP_FSETXATTR:
8164 ret = io_fsetxattr(req, issue_flags);
8166 case IORING_OP_SETXATTR:
8167 ret = io_setxattr(req, issue_flags);
8169 case IORING_OP_FGETXATTR:
8170 ret = io_fgetxattr(req, issue_flags);
8172 case IORING_OP_GETXATTR:
8173 ret = io_getxattr(req, issue_flags);
8175 case IORING_OP_SOCKET:
8176 ret = io_socket(req, issue_flags);
8178 case IORING_OP_URING_CMD:
8179 ret = io_uring_cmd(req, issue_flags);
8186 if (!io_op_defs[req->opcode].audit_skip)
8187 audit_uring_exit(!ret, ret);
8190 revert_creds(creds);
8193 /* If the op doesn't have a file, we're not polling for it */
8194 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8195 io_iopoll_req_issued(req, issue_flags);
8200 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8202 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8204 req = io_put_req_find_next(req);
8205 return req ? &req->work : NULL;
8208 static void io_wq_submit_work(struct io_wq_work *work)
8210 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8211 const struct io_op_def *def = &io_op_defs[req->opcode];
8212 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8213 bool needs_poll = false;
8214 int ret = 0, err = -ECANCELED;
8216 /* one will be dropped by ->io_free_work() after returning to io-wq */
8217 if (!(req->flags & REQ_F_REFCOUNT))
8218 __io_req_set_refcount(req, 2);
8222 io_arm_ltimeout(req);
8224 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8225 if (work->flags & IO_WQ_WORK_CANCEL) {
8227 io_req_task_queue_fail(req, err);
8230 if (!io_assign_file(req, issue_flags)) {
8232 work->flags |= IO_WQ_WORK_CANCEL;
8236 if (req->flags & REQ_F_FORCE_ASYNC) {
8237 bool opcode_poll = def->pollin || def->pollout;
8239 if (opcode_poll && file_can_poll(req->file)) {
8241 issue_flags |= IO_URING_F_NONBLOCK;
8246 ret = io_issue_sqe(req, issue_flags);
8250 * We can get EAGAIN for iopolled IO even though we're
8251 * forcing a sync submission from here, since we can't
8252 * wait for request slots on the block side.
8259 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8261 /* aborted or ready, in either case retry blocking */
8263 issue_flags &= ~IO_URING_F_NONBLOCK;
8266 /* avoid locking problems by failing it from a clean context */
8268 io_req_task_queue_fail(req, ret);
8271 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8274 return &table->files[i];
8277 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8280 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8282 return (struct file *) (slot->file_ptr & FFS_MASK);
8285 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8287 unsigned long file_ptr = (unsigned long) file;
8289 file_ptr |= io_file_get_flags(file);
8290 file_slot->file_ptr = file_ptr;
8293 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8294 unsigned int issue_flags)
8296 struct io_ring_ctx *ctx = req->ctx;
8297 struct file *file = NULL;
8298 unsigned long file_ptr;
8300 io_ring_submit_lock(ctx, issue_flags);
8302 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8304 fd = array_index_nospec(fd, ctx->nr_user_files);
8305 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8306 file = (struct file *) (file_ptr & FFS_MASK);
8307 file_ptr &= ~FFS_MASK;
8308 /* mask in overlapping REQ_F and FFS bits */
8309 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8310 io_req_set_rsrc_node(req, ctx, 0);
8312 io_ring_submit_unlock(ctx, issue_flags);
8317 * Drop the file for requeue operations. Only used of req->file is the
8318 * io_uring descriptor itself.
8320 static void io_drop_inflight_file(struct io_kiocb *req)
8322 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
8325 req->flags &= ~REQ_F_INFLIGHT;
8329 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8331 struct file *file = fget(fd);
8333 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8335 /* we don't allow fixed io_uring files */
8336 if (file && file->f_op == &io_uring_fops)
8337 req->flags |= REQ_F_INFLIGHT;
8341 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8343 struct io_kiocb *prev = req->timeout.prev;
8347 if (!(req->task->flags & PF_EXITING)) {
8348 struct io_cancel_data cd = {
8350 .data = prev->cqe.user_data,
8353 ret = io_try_cancel(req, &cd);
8355 io_req_complete_post(req, ret ?: -ETIME, 0);
8358 io_req_complete_post(req, -ETIME, 0);
8362 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8364 struct io_timeout_data *data = container_of(timer,
8365 struct io_timeout_data, timer);
8366 struct io_kiocb *prev, *req = data->req;
8367 struct io_ring_ctx *ctx = req->ctx;
8368 unsigned long flags;
8370 spin_lock_irqsave(&ctx->timeout_lock, flags);
8371 prev = req->timeout.head;
8372 req->timeout.head = NULL;
8375 * We don't expect the list to be empty, that will only happen if we
8376 * race with the completion of the linked work.
8379 io_remove_next_linked(prev);
8380 if (!req_ref_inc_not_zero(prev))
8383 list_del(&req->timeout.list);
8384 req->timeout.prev = prev;
8385 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8387 req->io_task_work.func = io_req_task_link_timeout;
8388 io_req_task_work_add(req, false);
8389 return HRTIMER_NORESTART;
8392 static void io_queue_linked_timeout(struct io_kiocb *req)
8394 struct io_ring_ctx *ctx = req->ctx;
8396 spin_lock_irq(&ctx->timeout_lock);
8398 * If the back reference is NULL, then our linked request finished
8399 * before we got a chance to setup the timer
8401 if (req->timeout.head) {
8402 struct io_timeout_data *data = req->async_data;
8404 data->timer.function = io_link_timeout_fn;
8405 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8407 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8409 spin_unlock_irq(&ctx->timeout_lock);
8410 /* drop submission reference */
8414 static void io_queue_async(struct io_kiocb *req, int ret)
8415 __must_hold(&req->ctx->uring_lock)
8417 struct io_kiocb *linked_timeout;
8419 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8420 io_req_complete_failed(req, ret);
8424 linked_timeout = io_prep_linked_timeout(req);
8426 switch (io_arm_poll_handler(req, 0)) {
8427 case IO_APOLL_READY:
8428 io_req_task_queue(req);
8430 case IO_APOLL_ABORTED:
8432 * Queued up for async execution, worker will release
8433 * submit reference when the iocb is actually submitted.
8435 io_queue_iowq(req, NULL);
8442 io_queue_linked_timeout(linked_timeout);
8445 static inline void io_queue_sqe(struct io_kiocb *req)
8446 __must_hold(&req->ctx->uring_lock)
8450 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8452 if (req->flags & REQ_F_COMPLETE_INLINE) {
8453 io_req_add_compl_list(req);
8457 * We async punt it if the file wasn't marked NOWAIT, or if the file
8458 * doesn't support non-blocking read/write attempts
8461 io_arm_ltimeout(req);
8463 io_queue_async(req, ret);
8466 static void io_queue_sqe_fallback(struct io_kiocb *req)
8467 __must_hold(&req->ctx->uring_lock)
8469 if (unlikely(req->flags & REQ_F_FAIL)) {
8471 * We don't submit, fail them all, for that replace hardlinks
8472 * with normal links. Extra REQ_F_LINK is tolerated.
8474 req->flags &= ~REQ_F_HARDLINK;
8475 req->flags |= REQ_F_LINK;
8476 io_req_complete_failed(req, req->cqe.res);
8477 } else if (unlikely(req->ctx->drain_active)) {
8480 int ret = io_req_prep_async(req);
8483 io_req_complete_failed(req, ret);
8485 io_queue_iowq(req, NULL);
8490 * Check SQE restrictions (opcode and flags).
8492 * Returns 'true' if SQE is allowed, 'false' otherwise.
8494 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8495 struct io_kiocb *req,
8496 unsigned int sqe_flags)
8498 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8501 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8502 ctx->restrictions.sqe_flags_required)
8505 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8506 ctx->restrictions.sqe_flags_required))
8512 static void io_init_req_drain(struct io_kiocb *req)
8514 struct io_ring_ctx *ctx = req->ctx;
8515 struct io_kiocb *head = ctx->submit_state.link.head;
8517 ctx->drain_active = true;
8520 * If we need to drain a request in the middle of a link, drain
8521 * the head request and the next request/link after the current
8522 * link. Considering sequential execution of links,
8523 * REQ_F_IO_DRAIN will be maintained for every request of our
8526 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8527 ctx->drain_next = true;
8531 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8532 const struct io_uring_sqe *sqe)
8533 __must_hold(&ctx->uring_lock)
8535 unsigned int sqe_flags;
8539 /* req is partially pre-initialised, see io_preinit_req() */
8540 req->opcode = opcode = READ_ONCE(sqe->opcode);
8541 /* same numerical values with corresponding REQ_F_*, safe to copy */
8542 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8543 req->cqe.user_data = READ_ONCE(sqe->user_data);
8545 req->rsrc_node = NULL;
8546 req->task = current;
8548 if (unlikely(opcode >= IORING_OP_LAST)) {
8552 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8553 /* enforce forwards compatibility on users */
8554 if (sqe_flags & ~SQE_VALID_FLAGS)
8556 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8557 if (!io_op_defs[opcode].buffer_select)
8559 req->buf_index = READ_ONCE(sqe->buf_group);
8561 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8562 ctx->drain_disabled = true;
8563 if (sqe_flags & IOSQE_IO_DRAIN) {
8564 if (ctx->drain_disabled)
8566 io_init_req_drain(req);
8569 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8570 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8572 /* knock it to the slow queue path, will be drained there */
8573 if (ctx->drain_active)
8574 req->flags |= REQ_F_FORCE_ASYNC;
8575 /* if there is no link, we're at "next" request and need to drain */
8576 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8577 ctx->drain_next = false;
8578 ctx->drain_active = true;
8579 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8583 if (!io_op_defs[opcode].ioprio && sqe->ioprio)
8585 if (!io_op_defs[opcode].iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8588 if (io_op_defs[opcode].needs_file) {
8589 struct io_submit_state *state = &ctx->submit_state;
8591 req->cqe.fd = READ_ONCE(sqe->fd);
8594 * Plug now if we have more than 2 IO left after this, and the
8595 * target is potentially a read/write to block based storage.
8597 if (state->need_plug && io_op_defs[opcode].plug) {
8598 state->plug_started = true;
8599 state->need_plug = false;
8600 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8604 personality = READ_ONCE(sqe->personality);
8608 req->creds = xa_load(&ctx->personalities, personality);
8611 get_cred(req->creds);
8612 ret = security_uring_override_creds(req->creds);
8614 put_cred(req->creds);
8617 req->flags |= REQ_F_CREDS;
8620 return io_req_prep(req, sqe);
8623 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8624 struct io_kiocb *req, int ret)
8626 struct io_ring_ctx *ctx = req->ctx;
8627 struct io_submit_link *link = &ctx->submit_state.link;
8628 struct io_kiocb *head = link->head;
8630 trace_io_uring_req_failed(sqe, ctx, req, ret);
8633 * Avoid breaking links in the middle as it renders links with SQPOLL
8634 * unusable. Instead of failing eagerly, continue assembling the link if
8635 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8636 * should find the flag and handle the rest.
8638 req_fail_link_node(req, ret);
8639 if (head && !(head->flags & REQ_F_FAIL))
8640 req_fail_link_node(head, -ECANCELED);
8642 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8644 link->last->link = req;
8648 io_queue_sqe_fallback(req);
8653 link->last->link = req;
8660 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8661 const struct io_uring_sqe *sqe)
8662 __must_hold(&ctx->uring_lock)
8664 struct io_submit_link *link = &ctx->submit_state.link;
8667 ret = io_init_req(ctx, req, sqe);
8669 return io_submit_fail_init(sqe, req, ret);
8671 /* don't need @sqe from now on */
8672 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8674 ctx->flags & IORING_SETUP_SQPOLL);
8677 * If we already have a head request, queue this one for async
8678 * submittal once the head completes. If we don't have a head but
8679 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8680 * submitted sync once the chain is complete. If none of those
8681 * conditions are true (normal request), then just queue it.
8683 if (unlikely(link->head)) {
8684 ret = io_req_prep_async(req);
8686 return io_submit_fail_init(sqe, req, ret);
8688 trace_io_uring_link(ctx, req, link->head);
8689 link->last->link = req;
8692 if (req->flags & IO_REQ_LINK_FLAGS)
8694 /* last request of the link, flush it */
8697 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8700 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8701 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8702 if (req->flags & IO_REQ_LINK_FLAGS) {
8707 io_queue_sqe_fallback(req);
8717 * Batched submission is done, ensure local IO is flushed out.
8719 static void io_submit_state_end(struct io_ring_ctx *ctx)
8721 struct io_submit_state *state = &ctx->submit_state;
8723 if (unlikely(state->link.head))
8724 io_queue_sqe_fallback(state->link.head);
8725 /* flush only after queuing links as they can generate completions */
8726 io_submit_flush_completions(ctx);
8727 if (state->plug_started)
8728 blk_finish_plug(&state->plug);
8732 * Start submission side cache.
8734 static void io_submit_state_start(struct io_submit_state *state,
8735 unsigned int max_ios)
8737 state->plug_started = false;
8738 state->need_plug = max_ios > 2;
8739 state->submit_nr = max_ios;
8740 /* set only head, no need to init link_last in advance */
8741 state->link.head = NULL;
8744 static void io_commit_sqring(struct io_ring_ctx *ctx)
8746 struct io_rings *rings = ctx->rings;
8749 * Ensure any loads from the SQEs are done at this point,
8750 * since once we write the new head, the application could
8751 * write new data to them.
8753 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
8757 * Fetch an sqe, if one is available. Note this returns a pointer to memory
8758 * that is mapped by userspace. This means that care needs to be taken to
8759 * ensure that reads are stable, as we cannot rely on userspace always
8760 * being a good citizen. If members of the sqe are validated and then later
8761 * used, it's important that those reads are done through READ_ONCE() to
8762 * prevent a re-load down the line.
8764 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
8766 unsigned head, mask = ctx->sq_entries - 1;
8767 unsigned sq_idx = ctx->cached_sq_head++ & mask;
8770 * The cached sq head (or cq tail) serves two purposes:
8772 * 1) allows us to batch the cost of updating the user visible
8774 * 2) allows the kernel side to track the head on its own, even
8775 * though the application is the one updating it.
8777 head = READ_ONCE(ctx->sq_array[sq_idx]);
8778 if (likely(head < ctx->sq_entries)) {
8779 /* double index for 128-byte SQEs, twice as long */
8780 if (ctx->flags & IORING_SETUP_SQE128)
8782 return &ctx->sq_sqes[head];
8785 /* drop invalid entries */
8787 WRITE_ONCE(ctx->rings->sq_dropped,
8788 READ_ONCE(ctx->rings->sq_dropped) + 1);
8792 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
8793 __must_hold(&ctx->uring_lock)
8795 unsigned int entries = io_sqring_entries(ctx);
8799 if (unlikely(!entries))
8801 /* make sure SQ entry isn't read before tail */
8802 ret = left = min3(nr, ctx->sq_entries, entries);
8803 io_get_task_refs(left);
8804 io_submit_state_start(&ctx->submit_state, left);
8807 const struct io_uring_sqe *sqe;
8808 struct io_kiocb *req;
8810 if (unlikely(!io_alloc_req_refill(ctx)))
8812 req = io_alloc_req(ctx);
8813 sqe = io_get_sqe(ctx);
8814 if (unlikely(!sqe)) {
8815 io_req_add_to_cache(req, ctx);
8820 * Continue submitting even for sqe failure if the
8821 * ring was setup with IORING_SETUP_SUBMIT_ALL
8823 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
8824 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
8830 if (unlikely(left)) {
8832 /* try again if it submitted nothing and can't allocate a req */
8833 if (!ret && io_req_cache_empty(ctx))
8835 current->io_uring->cached_refs += left;
8838 io_submit_state_end(ctx);
8839 /* Commit SQ ring head once we've consumed and submitted all SQEs */
8840 io_commit_sqring(ctx);
8844 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
8846 return READ_ONCE(sqd->state);
8849 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
8851 unsigned int to_submit;
8854 to_submit = io_sqring_entries(ctx);
8855 /* if we're handling multiple rings, cap submit size for fairness */
8856 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
8857 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
8859 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
8860 const struct cred *creds = NULL;
8862 if (ctx->sq_creds != current_cred())
8863 creds = override_creds(ctx->sq_creds);
8865 mutex_lock(&ctx->uring_lock);
8866 if (!wq_list_empty(&ctx->iopoll_list))
8867 io_do_iopoll(ctx, true);
8870 * Don't submit if refs are dying, good for io_uring_register(),
8871 * but also it is relied upon by io_ring_exit_work()
8873 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
8874 !(ctx->flags & IORING_SETUP_R_DISABLED))
8875 ret = io_submit_sqes(ctx, to_submit);
8876 mutex_unlock(&ctx->uring_lock);
8878 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8879 wake_up(&ctx->sqo_sq_wait);
8881 revert_creds(creds);
8887 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8889 struct io_ring_ctx *ctx;
8890 unsigned sq_thread_idle = 0;
8892 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8893 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8894 sqd->sq_thread_idle = sq_thread_idle;
8897 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8899 bool did_sig = false;
8900 struct ksignal ksig;
8902 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8903 signal_pending(current)) {
8904 mutex_unlock(&sqd->lock);
8905 if (signal_pending(current))
8906 did_sig = get_signal(&ksig);
8908 mutex_lock(&sqd->lock);
8910 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8913 static int io_sq_thread(void *data)
8915 struct io_sq_data *sqd = data;
8916 struct io_ring_ctx *ctx;
8917 unsigned long timeout = 0;
8918 char buf[TASK_COMM_LEN];
8921 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8922 set_task_comm(current, buf);
8924 if (sqd->sq_cpu != -1)
8925 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8927 set_cpus_allowed_ptr(current, cpu_online_mask);
8928 current->flags |= PF_NO_SETAFFINITY;
8930 audit_alloc_kernel(current);
8932 mutex_lock(&sqd->lock);
8934 bool cap_entries, sqt_spin = false;
8936 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8937 if (io_sqd_handle_event(sqd))
8939 timeout = jiffies + sqd->sq_thread_idle;
8942 cap_entries = !list_is_singular(&sqd->ctx_list);
8943 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8944 int ret = __io_sq_thread(ctx, cap_entries);
8946 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8949 if (io_run_task_work())
8952 if (sqt_spin || !time_after(jiffies, timeout)) {
8955 timeout = jiffies + sqd->sq_thread_idle;
8959 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8960 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8961 bool needs_sched = true;
8963 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8964 atomic_or(IORING_SQ_NEED_WAKEUP,
8965 &ctx->rings->sq_flags);
8966 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8967 !wq_list_empty(&ctx->iopoll_list)) {
8968 needs_sched = false;
8973 * Ensure the store of the wakeup flag is not
8974 * reordered with the load of the SQ tail
8976 smp_mb__after_atomic();
8978 if (io_sqring_entries(ctx)) {
8979 needs_sched = false;
8985 mutex_unlock(&sqd->lock);
8987 mutex_lock(&sqd->lock);
8989 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8990 atomic_andnot(IORING_SQ_NEED_WAKEUP,
8991 &ctx->rings->sq_flags);
8994 finish_wait(&sqd->wait, &wait);
8995 timeout = jiffies + sqd->sq_thread_idle;
8998 io_uring_cancel_generic(true, sqd);
9000 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9001 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
9003 mutex_unlock(&sqd->lock);
9005 audit_free(current);
9007 complete(&sqd->exited);
9011 struct io_wait_queue {
9012 struct wait_queue_entry wq;
9013 struct io_ring_ctx *ctx;
9015 unsigned nr_timeouts;
9018 static inline bool io_should_wake(struct io_wait_queue *iowq)
9020 struct io_ring_ctx *ctx = iowq->ctx;
9021 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
9024 * Wake up if we have enough events, or if a timeout occurred since we
9025 * started waiting. For timeouts, we always want to return to userspace,
9026 * regardless of event count.
9028 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
9031 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
9032 int wake_flags, void *key)
9034 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
9038 * Cannot safely flush overflowed CQEs from here, ensure we wake up
9039 * the task, and the next invocation will do it.
9041 if (io_should_wake(iowq) ||
9042 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
9043 return autoremove_wake_function(curr, mode, wake_flags, key);
9047 static int io_run_task_work_sig(void)
9049 if (io_run_task_work())
9051 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
9052 return -ERESTARTSYS;
9053 if (task_sigpending(current))
9058 /* when returns >0, the caller should retry */
9059 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
9060 struct io_wait_queue *iowq,
9064 unsigned long check_cq;
9066 /* make sure we run task_work before checking for signals */
9067 ret = io_run_task_work_sig();
9068 if (ret || io_should_wake(iowq))
9070 check_cq = READ_ONCE(ctx->check_cq);
9071 /* let the caller flush overflows, retry */
9072 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
9074 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
9076 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
9082 * Wait until events become available, if we don't already have some. The
9083 * application must reap them itself, as they reside on the shared cq ring.
9085 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
9086 const sigset_t __user *sig, size_t sigsz,
9087 struct __kernel_timespec __user *uts)
9089 struct io_wait_queue iowq;
9090 struct io_rings *rings = ctx->rings;
9091 ktime_t timeout = KTIME_MAX;
9095 io_cqring_overflow_flush(ctx);
9096 if (io_cqring_events(ctx) >= min_events)
9098 if (!io_run_task_work())
9103 #ifdef CONFIG_COMPAT
9104 if (in_compat_syscall())
9105 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
9109 ret = set_user_sigmask(sig, sigsz);
9116 struct timespec64 ts;
9118 if (get_timespec64(&ts, uts))
9120 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
9123 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
9124 iowq.wq.private = current;
9125 INIT_LIST_HEAD(&iowq.wq.entry);
9127 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
9128 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
9130 trace_io_uring_cqring_wait(ctx, min_events);
9132 /* if we can't even flush overflow, don't wait for more */
9133 if (!io_cqring_overflow_flush(ctx)) {
9137 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
9138 TASK_INTERRUPTIBLE);
9139 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
9143 finish_wait(&ctx->cq_wait, &iowq.wq);
9144 restore_saved_sigmask_unless(ret == -EINTR);
9146 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
9149 static void io_free_page_table(void **table, size_t size)
9151 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9153 for (i = 0; i < nr_tables; i++)
9158 static __cold void **io_alloc_page_table(size_t size)
9160 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9161 size_t init_size = size;
9164 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9168 for (i = 0; i < nr_tables; i++) {
9169 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9171 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9173 io_free_page_table(table, init_size);
9181 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9183 percpu_ref_exit(&ref_node->refs);
9187 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9189 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9190 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9191 unsigned long flags;
9192 bool first_add = false;
9193 unsigned long delay = HZ;
9195 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9198 /* if we are mid-quiesce then do not delay */
9199 if (node->rsrc_data->quiesce)
9202 while (!list_empty(&ctx->rsrc_ref_list)) {
9203 node = list_first_entry(&ctx->rsrc_ref_list,
9204 struct io_rsrc_node, node);
9205 /* recycle ref nodes in order */
9208 list_del(&node->node);
9209 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9211 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9214 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9217 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9219 struct io_rsrc_node *ref_node;
9221 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9225 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9230 INIT_LIST_HEAD(&ref_node->node);
9231 INIT_LIST_HEAD(&ref_node->rsrc_list);
9232 ref_node->done = false;
9236 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9237 struct io_rsrc_data *data_to_kill)
9238 __must_hold(&ctx->uring_lock)
9240 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9241 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9243 io_rsrc_refs_drop(ctx);
9246 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9248 rsrc_node->rsrc_data = data_to_kill;
9249 spin_lock_irq(&ctx->rsrc_ref_lock);
9250 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9251 spin_unlock_irq(&ctx->rsrc_ref_lock);
9253 atomic_inc(&data_to_kill->refs);
9254 percpu_ref_kill(&rsrc_node->refs);
9255 ctx->rsrc_node = NULL;
9258 if (!ctx->rsrc_node) {
9259 ctx->rsrc_node = ctx->rsrc_backup_node;
9260 ctx->rsrc_backup_node = NULL;
9264 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9266 if (ctx->rsrc_backup_node)
9268 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9269 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9272 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9273 struct io_ring_ctx *ctx)
9277 /* As we may drop ->uring_lock, other task may have started quiesce */
9281 data->quiesce = true;
9283 ret = io_rsrc_node_switch_start(ctx);
9286 io_rsrc_node_switch(ctx, data);
9288 /* kill initial ref, already quiesced if zero */
9289 if (atomic_dec_and_test(&data->refs))
9291 mutex_unlock(&ctx->uring_lock);
9292 flush_delayed_work(&ctx->rsrc_put_work);
9293 ret = wait_for_completion_interruptible(&data->done);
9295 mutex_lock(&ctx->uring_lock);
9296 if (atomic_read(&data->refs) > 0) {
9298 * it has been revived by another thread while
9301 mutex_unlock(&ctx->uring_lock);
9307 atomic_inc(&data->refs);
9308 /* wait for all works potentially completing data->done */
9309 flush_delayed_work(&ctx->rsrc_put_work);
9310 reinit_completion(&data->done);
9312 ret = io_run_task_work_sig();
9313 mutex_lock(&ctx->uring_lock);
9315 data->quiesce = false;
9320 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9322 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9323 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9325 return &data->tags[table_idx][off];
9328 static void io_rsrc_data_free(struct io_rsrc_data *data)
9330 size_t size = data->nr * sizeof(data->tags[0][0]);
9333 io_free_page_table((void **)data->tags, size);
9337 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9338 u64 __user *utags, unsigned nr,
9339 struct io_rsrc_data **pdata)
9341 struct io_rsrc_data *data;
9345 data = kzalloc(sizeof(*data), GFP_KERNEL);
9348 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9356 data->do_put = do_put;
9359 for (i = 0; i < nr; i++) {
9360 u64 *tag_slot = io_get_tag_slot(data, i);
9362 if (copy_from_user(tag_slot, &utags[i],
9368 atomic_set(&data->refs, 1);
9369 init_completion(&data->done);
9373 io_rsrc_data_free(data);
9377 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9379 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9380 GFP_KERNEL_ACCOUNT);
9381 return !!table->files;
9384 static void io_free_file_tables(struct io_file_table *table)
9386 kvfree(table->files);
9387 table->files = NULL;
9390 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9392 #if !defined(IO_URING_SCM_ALL)
9395 for (i = 0; i < ctx->nr_user_files; i++) {
9396 struct file *file = io_file_from_index(ctx, i);
9400 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9406 #if defined(CONFIG_UNIX)
9407 if (ctx->ring_sock) {
9408 struct sock *sock = ctx->ring_sock->sk;
9409 struct sk_buff *skb;
9411 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9415 io_free_file_tables(&ctx->file_table);
9416 io_rsrc_data_free(ctx->file_data);
9417 ctx->file_data = NULL;
9418 ctx->nr_user_files = 0;
9421 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9425 if (!ctx->file_data)
9427 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9429 __io_sqe_files_unregister(ctx);
9433 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9434 __releases(&sqd->lock)
9436 WARN_ON_ONCE(sqd->thread == current);
9439 * Do the dance but not conditional clear_bit() because it'd race with
9440 * other threads incrementing park_pending and setting the bit.
9442 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9443 if (atomic_dec_return(&sqd->park_pending))
9444 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9445 mutex_unlock(&sqd->lock);
9448 static void io_sq_thread_park(struct io_sq_data *sqd)
9449 __acquires(&sqd->lock)
9451 WARN_ON_ONCE(sqd->thread == current);
9453 atomic_inc(&sqd->park_pending);
9454 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9455 mutex_lock(&sqd->lock);
9457 wake_up_process(sqd->thread);
9460 static void io_sq_thread_stop(struct io_sq_data *sqd)
9462 WARN_ON_ONCE(sqd->thread == current);
9463 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9465 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9466 mutex_lock(&sqd->lock);
9468 wake_up_process(sqd->thread);
9469 mutex_unlock(&sqd->lock);
9470 wait_for_completion(&sqd->exited);
9473 static void io_put_sq_data(struct io_sq_data *sqd)
9475 if (refcount_dec_and_test(&sqd->refs)) {
9476 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9478 io_sq_thread_stop(sqd);
9483 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9485 struct io_sq_data *sqd = ctx->sq_data;
9488 io_sq_thread_park(sqd);
9489 list_del_init(&ctx->sqd_list);
9490 io_sqd_update_thread_idle(sqd);
9491 io_sq_thread_unpark(sqd);
9493 io_put_sq_data(sqd);
9494 ctx->sq_data = NULL;
9498 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9500 struct io_ring_ctx *ctx_attach;
9501 struct io_sq_data *sqd;
9504 f = fdget(p->wq_fd);
9506 return ERR_PTR(-ENXIO);
9507 if (f.file->f_op != &io_uring_fops) {
9509 return ERR_PTR(-EINVAL);
9512 ctx_attach = f.file->private_data;
9513 sqd = ctx_attach->sq_data;
9516 return ERR_PTR(-EINVAL);
9518 if (sqd->task_tgid != current->tgid) {
9520 return ERR_PTR(-EPERM);
9523 refcount_inc(&sqd->refs);
9528 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9531 struct io_sq_data *sqd;
9534 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9535 sqd = io_attach_sq_data(p);
9540 /* fall through for EPERM case, setup new sqd/task */
9541 if (PTR_ERR(sqd) != -EPERM)
9545 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9547 return ERR_PTR(-ENOMEM);
9549 atomic_set(&sqd->park_pending, 0);
9550 refcount_set(&sqd->refs, 1);
9551 INIT_LIST_HEAD(&sqd->ctx_list);
9552 mutex_init(&sqd->lock);
9553 init_waitqueue_head(&sqd->wait);
9554 init_completion(&sqd->exited);
9559 * Ensure the UNIX gc is aware of our file set, so we are certain that
9560 * the io_uring can be safely unregistered on process exit, even if we have
9561 * loops in the file referencing. We account only files that can hold other
9562 * files because otherwise they can't form a loop and so are not interesting
9565 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9567 #if defined(CONFIG_UNIX)
9568 struct sock *sk = ctx->ring_sock->sk;
9569 struct sk_buff_head *head = &sk->sk_receive_queue;
9570 struct scm_fp_list *fpl;
9571 struct sk_buff *skb;
9573 if (likely(!io_file_need_scm(file)))
9577 * See if we can merge this file into an existing skb SCM_RIGHTS
9578 * file set. If there's no room, fall back to allocating a new skb
9579 * and filling it in.
9581 spin_lock_irq(&head->lock);
9582 skb = skb_peek(head);
9583 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9584 __skb_unlink(skb, head);
9587 spin_unlock_irq(&head->lock);
9590 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9594 skb = alloc_skb(0, GFP_KERNEL);
9600 fpl->user = get_uid(current_user());
9601 fpl->max = SCM_MAX_FD;
9604 UNIXCB(skb).fp = fpl;
9606 skb->destructor = unix_destruct_scm;
9607 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9610 fpl = UNIXCB(skb).fp;
9611 fpl->fp[fpl->count++] = get_file(file);
9612 unix_inflight(fpl->user, file);
9613 skb_queue_head(head, skb);
9619 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9621 struct file *file = prsrc->file;
9622 #if defined(CONFIG_UNIX)
9623 struct sock *sock = ctx->ring_sock->sk;
9624 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9625 struct sk_buff *skb;
9628 if (!io_file_need_scm(file)) {
9633 __skb_queue_head_init(&list);
9636 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9637 * remove this entry and rearrange the file array.
9639 skb = skb_dequeue(head);
9641 struct scm_fp_list *fp;
9643 fp = UNIXCB(skb).fp;
9644 for (i = 0; i < fp->count; i++) {
9647 if (fp->fp[i] != file)
9650 unix_notinflight(fp->user, fp->fp[i]);
9651 left = fp->count - 1 - i;
9653 memmove(&fp->fp[i], &fp->fp[i + 1],
9654 left * sizeof(struct file *));
9661 __skb_queue_tail(&list, skb);
9671 __skb_queue_tail(&list, skb);
9673 skb = skb_dequeue(head);
9676 if (skb_peek(&list)) {
9677 spin_lock_irq(&head->lock);
9678 while ((skb = __skb_dequeue(&list)) != NULL)
9679 __skb_queue_tail(head, skb);
9680 spin_unlock_irq(&head->lock);
9687 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9689 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9690 struct io_ring_ctx *ctx = rsrc_data->ctx;
9691 struct io_rsrc_put *prsrc, *tmp;
9693 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9694 list_del(&prsrc->list);
9697 if (ctx->flags & IORING_SETUP_IOPOLL)
9698 mutex_lock(&ctx->uring_lock);
9700 spin_lock(&ctx->completion_lock);
9701 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9702 io_commit_cqring(ctx);
9703 spin_unlock(&ctx->completion_lock);
9704 io_cqring_ev_posted(ctx);
9706 if (ctx->flags & IORING_SETUP_IOPOLL)
9707 mutex_unlock(&ctx->uring_lock);
9710 rsrc_data->do_put(ctx, prsrc);
9714 io_rsrc_node_destroy(ref_node);
9715 if (atomic_dec_and_test(&rsrc_data->refs))
9716 complete(&rsrc_data->done);
9719 static void io_rsrc_put_work(struct work_struct *work)
9721 struct io_ring_ctx *ctx;
9722 struct llist_node *node;
9724 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
9725 node = llist_del_all(&ctx->rsrc_put_llist);
9728 struct io_rsrc_node *ref_node;
9729 struct llist_node *next = node->next;
9731 ref_node = llist_entry(node, struct io_rsrc_node, llist);
9732 __io_rsrc_put_work(ref_node);
9737 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
9738 unsigned nr_args, u64 __user *tags)
9740 __s32 __user *fds = (__s32 __user *) arg;
9749 if (nr_args > IORING_MAX_FIXED_FILES)
9751 if (nr_args > rlimit(RLIMIT_NOFILE))
9753 ret = io_rsrc_node_switch_start(ctx);
9756 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9761 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
9762 io_rsrc_data_free(ctx->file_data);
9763 ctx->file_data = NULL;
9767 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9768 struct io_fixed_file *file_slot;
9770 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
9774 /* allow sparse sets */
9777 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9784 if (unlikely(!file))
9788 * Don't allow io_uring instances to be registered. If UNIX
9789 * isn't enabled, then this causes a reference cycle and this
9790 * instance can never get freed. If UNIX is enabled we'll
9791 * handle it just fine, but there's still no point in allowing
9792 * a ring fd as it doesn't support regular read/write anyway.
9794 if (file->f_op == &io_uring_fops) {
9798 ret = io_scm_file_account(ctx, file);
9803 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9804 io_fixed_file_set(file_slot, file);
9807 io_rsrc_node_switch(ctx, NULL);
9810 __io_sqe_files_unregister(ctx);
9814 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9815 struct io_rsrc_node *node, void *rsrc)
9817 u64 *tag_slot = io_get_tag_slot(data, idx);
9818 struct io_rsrc_put *prsrc;
9820 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9824 prsrc->tag = *tag_slot;
9827 list_add(&prsrc->list, &node->rsrc_list);
9831 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9832 unsigned int issue_flags, u32 slot_index)
9834 struct io_ring_ctx *ctx = req->ctx;
9835 bool needs_switch = false;
9836 struct io_fixed_file *file_slot;
9839 io_ring_submit_lock(ctx, issue_flags);
9840 if (file->f_op == &io_uring_fops)
9843 if (!ctx->file_data)
9846 if (slot_index >= ctx->nr_user_files)
9849 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9850 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9852 if (file_slot->file_ptr) {
9853 struct file *old_file;
9855 ret = io_rsrc_node_switch_start(ctx);
9859 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9860 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9861 ctx->rsrc_node, old_file);
9864 file_slot->file_ptr = 0;
9865 needs_switch = true;
9868 ret = io_scm_file_account(ctx, file);
9870 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9871 io_fixed_file_set(file_slot, file);
9875 io_rsrc_node_switch(ctx, ctx->file_data);
9876 io_ring_submit_unlock(ctx, issue_flags);
9882 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9884 unsigned int offset = req->close.file_slot - 1;
9885 struct io_ring_ctx *ctx = req->ctx;
9886 struct io_fixed_file *file_slot;
9890 io_ring_submit_lock(ctx, issue_flags);
9892 if (unlikely(!ctx->file_data))
9895 if (offset >= ctx->nr_user_files)
9897 ret = io_rsrc_node_switch_start(ctx);
9901 offset = array_index_nospec(offset, ctx->nr_user_files);
9902 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9904 if (!file_slot->file_ptr)
9907 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9908 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9912 file_slot->file_ptr = 0;
9913 io_rsrc_node_switch(ctx, ctx->file_data);
9916 io_ring_submit_unlock(ctx, issue_flags);
9920 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9921 struct io_uring_rsrc_update2 *up,
9924 u64 __user *tags = u64_to_user_ptr(up->tags);
9925 __s32 __user *fds = u64_to_user_ptr(up->data);
9926 struct io_rsrc_data *data = ctx->file_data;
9927 struct io_fixed_file *file_slot;
9931 bool needs_switch = false;
9933 if (!ctx->file_data)
9935 if (up->offset + nr_args > ctx->nr_user_files)
9938 for (done = 0; done < nr_args; done++) {
9941 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9942 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9946 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9950 if (fd == IORING_REGISTER_FILES_SKIP)
9953 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9954 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9956 if (file_slot->file_ptr) {
9957 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9958 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9961 file_slot->file_ptr = 0;
9962 needs_switch = true;
9971 * Don't allow io_uring instances to be registered. If
9972 * UNIX isn't enabled, then this causes a reference
9973 * cycle and this instance can never get freed. If UNIX
9974 * is enabled we'll handle it just fine, but there's
9975 * still no point in allowing a ring fd as it doesn't
9976 * support regular read/write anyway.
9978 if (file->f_op == &io_uring_fops) {
9983 err = io_scm_file_account(ctx, file);
9988 *io_get_tag_slot(data, i) = tag;
9989 io_fixed_file_set(file_slot, file);
9994 io_rsrc_node_switch(ctx, data);
9995 return done ? done : err;
9998 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9999 struct task_struct *task)
10001 struct io_wq_hash *hash;
10002 struct io_wq_data data;
10003 unsigned int concurrency;
10005 mutex_lock(&ctx->uring_lock);
10006 hash = ctx->hash_map;
10008 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
10010 mutex_unlock(&ctx->uring_lock);
10011 return ERR_PTR(-ENOMEM);
10013 refcount_set(&hash->refs, 1);
10014 init_waitqueue_head(&hash->wait);
10015 ctx->hash_map = hash;
10017 mutex_unlock(&ctx->uring_lock);
10021 data.free_work = io_wq_free_work;
10022 data.do_work = io_wq_submit_work;
10024 /* Do QD, or 4 * CPUS, whatever is smallest */
10025 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
10027 return io_wq_create(concurrency, &data);
10030 static __cold int io_uring_alloc_task_context(struct task_struct *task,
10031 struct io_ring_ctx *ctx)
10033 struct io_uring_task *tctx;
10036 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
10037 if (unlikely(!tctx))
10040 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
10041 sizeof(struct file *), GFP_KERNEL);
10042 if (unlikely(!tctx->registered_rings)) {
10047 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
10048 if (unlikely(ret)) {
10049 kfree(tctx->registered_rings);
10054 tctx->io_wq = io_init_wq_offload(ctx, task);
10055 if (IS_ERR(tctx->io_wq)) {
10056 ret = PTR_ERR(tctx->io_wq);
10057 percpu_counter_destroy(&tctx->inflight);
10058 kfree(tctx->registered_rings);
10063 xa_init(&tctx->xa);
10064 init_waitqueue_head(&tctx->wait);
10065 atomic_set(&tctx->in_idle, 0);
10066 task->io_uring = tctx;
10067 spin_lock_init(&tctx->task_lock);
10068 INIT_WQ_LIST(&tctx->task_list);
10069 INIT_WQ_LIST(&tctx->prior_task_list);
10070 init_task_work(&tctx->task_work, tctx_task_work);
10074 void __io_uring_free(struct task_struct *tsk)
10076 struct io_uring_task *tctx = tsk->io_uring;
10078 WARN_ON_ONCE(!xa_empty(&tctx->xa));
10079 WARN_ON_ONCE(tctx->io_wq);
10080 WARN_ON_ONCE(tctx->cached_refs);
10082 kfree(tctx->registered_rings);
10083 percpu_counter_destroy(&tctx->inflight);
10085 tsk->io_uring = NULL;
10088 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
10089 struct io_uring_params *p)
10093 /* Retain compatibility with failing for an invalid attach attempt */
10094 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
10095 IORING_SETUP_ATTACH_WQ) {
10098 f = fdget(p->wq_fd);
10101 if (f.file->f_op != &io_uring_fops) {
10107 if (ctx->flags & IORING_SETUP_SQPOLL) {
10108 struct task_struct *tsk;
10109 struct io_sq_data *sqd;
10112 ret = security_uring_sqpoll();
10116 sqd = io_get_sq_data(p, &attached);
10118 ret = PTR_ERR(sqd);
10122 ctx->sq_creds = get_current_cred();
10123 ctx->sq_data = sqd;
10124 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10125 if (!ctx->sq_thread_idle)
10126 ctx->sq_thread_idle = HZ;
10128 io_sq_thread_park(sqd);
10129 list_add(&ctx->sqd_list, &sqd->ctx_list);
10130 io_sqd_update_thread_idle(sqd);
10131 /* don't attach to a dying SQPOLL thread, would be racy */
10132 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10133 io_sq_thread_unpark(sqd);
10140 if (p->flags & IORING_SETUP_SQ_AFF) {
10141 int cpu = p->sq_thread_cpu;
10144 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10151 sqd->task_pid = current->pid;
10152 sqd->task_tgid = current->tgid;
10153 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10155 ret = PTR_ERR(tsk);
10160 ret = io_uring_alloc_task_context(tsk, ctx);
10161 wake_up_new_task(tsk);
10164 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10165 /* Can't have SQ_AFF without SQPOLL */
10172 complete(&ctx->sq_data->exited);
10174 io_sq_thread_finish(ctx);
10178 static inline void __io_unaccount_mem(struct user_struct *user,
10179 unsigned long nr_pages)
10181 atomic_long_sub(nr_pages, &user->locked_vm);
10184 static inline int __io_account_mem(struct user_struct *user,
10185 unsigned long nr_pages)
10187 unsigned long page_limit, cur_pages, new_pages;
10189 /* Don't allow more pages than we can safely lock */
10190 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10193 cur_pages = atomic_long_read(&user->locked_vm);
10194 new_pages = cur_pages + nr_pages;
10195 if (new_pages > page_limit)
10197 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10198 new_pages) != cur_pages);
10203 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10206 __io_unaccount_mem(ctx->user, nr_pages);
10208 if (ctx->mm_account)
10209 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10212 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10217 ret = __io_account_mem(ctx->user, nr_pages);
10222 if (ctx->mm_account)
10223 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10228 static void io_mem_free(void *ptr)
10235 page = virt_to_head_page(ptr);
10236 if (put_page_testzero(page))
10237 free_compound_page(page);
10240 static void *io_mem_alloc(size_t size)
10242 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10244 return (void *) __get_free_pages(gfp, get_order(size));
10247 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10248 unsigned int cq_entries, size_t *sq_offset)
10250 struct io_rings *rings;
10251 size_t off, sq_array_size;
10253 off = struct_size(rings, cqes, cq_entries);
10254 if (off == SIZE_MAX)
10256 if (ctx->flags & IORING_SETUP_CQE32) {
10257 if (check_shl_overflow(off, 1, &off))
10262 off = ALIGN(off, SMP_CACHE_BYTES);
10270 sq_array_size = array_size(sizeof(u32), sq_entries);
10271 if (sq_array_size == SIZE_MAX)
10274 if (check_add_overflow(off, sq_array_size, &off))
10280 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10282 struct io_mapped_ubuf *imu = *slot;
10285 if (imu != ctx->dummy_ubuf) {
10286 for (i = 0; i < imu->nr_bvecs; i++)
10287 unpin_user_page(imu->bvec[i].bv_page);
10288 if (imu->acct_pages)
10289 io_unaccount_mem(ctx, imu->acct_pages);
10295 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10297 io_buffer_unmap(ctx, &prsrc->buf);
10301 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10305 for (i = 0; i < ctx->nr_user_bufs; i++)
10306 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10307 kfree(ctx->user_bufs);
10308 io_rsrc_data_free(ctx->buf_data);
10309 ctx->user_bufs = NULL;
10310 ctx->buf_data = NULL;
10311 ctx->nr_user_bufs = 0;
10314 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10318 if (!ctx->buf_data)
10321 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10323 __io_sqe_buffers_unregister(ctx);
10327 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10328 void __user *arg, unsigned index)
10330 struct iovec __user *src;
10332 #ifdef CONFIG_COMPAT
10334 struct compat_iovec __user *ciovs;
10335 struct compat_iovec ciov;
10337 ciovs = (struct compat_iovec __user *) arg;
10338 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10341 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10342 dst->iov_len = ciov.iov_len;
10346 src = (struct iovec __user *) arg;
10347 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10353 * Not super efficient, but this is just a registration time. And we do cache
10354 * the last compound head, so generally we'll only do a full search if we don't
10357 * We check if the given compound head page has already been accounted, to
10358 * avoid double accounting it. This allows us to account the full size of the
10359 * page, not just the constituent pages of a huge page.
10361 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10362 int nr_pages, struct page *hpage)
10366 /* check current page array */
10367 for (i = 0; i < nr_pages; i++) {
10368 if (!PageCompound(pages[i]))
10370 if (compound_head(pages[i]) == hpage)
10374 /* check previously registered pages */
10375 for (i = 0; i < ctx->nr_user_bufs; i++) {
10376 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10378 for (j = 0; j < imu->nr_bvecs; j++) {
10379 if (!PageCompound(imu->bvec[j].bv_page))
10381 if (compound_head(imu->bvec[j].bv_page) == hpage)
10389 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10390 int nr_pages, struct io_mapped_ubuf *imu,
10391 struct page **last_hpage)
10395 imu->acct_pages = 0;
10396 for (i = 0; i < nr_pages; i++) {
10397 if (!PageCompound(pages[i])) {
10400 struct page *hpage;
10402 hpage = compound_head(pages[i]);
10403 if (hpage == *last_hpage)
10405 *last_hpage = hpage;
10406 if (headpage_already_acct(ctx, pages, i, hpage))
10408 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10412 if (!imu->acct_pages)
10415 ret = io_account_mem(ctx, imu->acct_pages);
10417 imu->acct_pages = 0;
10421 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10422 struct io_mapped_ubuf **pimu,
10423 struct page **last_hpage)
10425 struct io_mapped_ubuf *imu = NULL;
10426 struct vm_area_struct **vmas = NULL;
10427 struct page **pages = NULL;
10428 unsigned long off, start, end, ubuf;
10430 int ret, pret, nr_pages, i;
10432 if (!iov->iov_base) {
10433 *pimu = ctx->dummy_ubuf;
10437 ubuf = (unsigned long) iov->iov_base;
10438 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10439 start = ubuf >> PAGE_SHIFT;
10440 nr_pages = end - start;
10445 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10449 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10454 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10459 mmap_read_lock(current->mm);
10460 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10462 if (pret == nr_pages) {
10463 /* don't support file backed memory */
10464 for (i = 0; i < nr_pages; i++) {
10465 struct vm_area_struct *vma = vmas[i];
10467 if (vma_is_shmem(vma))
10469 if (vma->vm_file &&
10470 !is_file_hugepages(vma->vm_file)) {
10476 ret = pret < 0 ? pret : -EFAULT;
10478 mmap_read_unlock(current->mm);
10481 * if we did partial map, or found file backed vmas,
10482 * release any pages we did get
10485 unpin_user_pages(pages, pret);
10489 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
10491 unpin_user_pages(pages, pret);
10495 off = ubuf & ~PAGE_MASK;
10496 size = iov->iov_len;
10497 for (i = 0; i < nr_pages; i++) {
10500 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10501 imu->bvec[i].bv_page = pages[i];
10502 imu->bvec[i].bv_len = vec_len;
10503 imu->bvec[i].bv_offset = off;
10507 /* store original address for later verification */
10509 imu->ubuf_end = ubuf + iov->iov_len;
10510 imu->nr_bvecs = nr_pages;
10521 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10523 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10524 return ctx->user_bufs ? 0 : -ENOMEM;
10527 static int io_buffer_validate(struct iovec *iov)
10529 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10532 * Don't impose further limits on the size and buffer
10533 * constraints here, we'll -EINVAL later when IO is
10534 * submitted if they are wrong.
10536 if (!iov->iov_base)
10537 return iov->iov_len ? -EFAULT : 0;
10541 /* arbitrary limit, but we need something */
10542 if (iov->iov_len > SZ_1G)
10545 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10551 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10552 unsigned int nr_args, u64 __user *tags)
10554 struct page *last_hpage = NULL;
10555 struct io_rsrc_data *data;
10559 if (ctx->user_bufs)
10561 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10563 ret = io_rsrc_node_switch_start(ctx);
10566 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10569 ret = io_buffers_map_alloc(ctx, nr_args);
10571 io_rsrc_data_free(data);
10575 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10576 ret = io_copy_iov(ctx, &iov, arg, i);
10579 ret = io_buffer_validate(&iov);
10582 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10587 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10593 WARN_ON_ONCE(ctx->buf_data);
10595 ctx->buf_data = data;
10597 __io_sqe_buffers_unregister(ctx);
10599 io_rsrc_node_switch(ctx, NULL);
10603 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10604 struct io_uring_rsrc_update2 *up,
10605 unsigned int nr_args)
10607 u64 __user *tags = u64_to_user_ptr(up->tags);
10608 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10609 struct page *last_hpage = NULL;
10610 bool needs_switch = false;
10614 if (!ctx->buf_data)
10616 if (up->offset + nr_args > ctx->nr_user_bufs)
10619 for (done = 0; done < nr_args; done++) {
10620 struct io_mapped_ubuf *imu;
10621 int offset = up->offset + done;
10624 err = io_copy_iov(ctx, &iov, iovs, done);
10627 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10631 err = io_buffer_validate(&iov);
10634 if (!iov.iov_base && tag) {
10638 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10642 i = array_index_nospec(offset, ctx->nr_user_bufs);
10643 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10644 err = io_queue_rsrc_removal(ctx->buf_data, i,
10645 ctx->rsrc_node, ctx->user_bufs[i]);
10646 if (unlikely(err)) {
10647 io_buffer_unmap(ctx, &imu);
10650 ctx->user_bufs[i] = NULL;
10651 needs_switch = true;
10654 ctx->user_bufs[i] = imu;
10655 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10659 io_rsrc_node_switch(ctx, ctx->buf_data);
10660 return done ? done : err;
10663 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10664 unsigned int eventfd_async)
10666 struct io_ev_fd *ev_fd;
10667 __s32 __user *fds = arg;
10670 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10671 lockdep_is_held(&ctx->uring_lock));
10675 if (copy_from_user(&fd, fds, sizeof(*fds)))
10678 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10682 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10683 if (IS_ERR(ev_fd->cq_ev_fd)) {
10684 int ret = PTR_ERR(ev_fd->cq_ev_fd);
10688 ev_fd->eventfd_async = eventfd_async;
10689 ctx->has_evfd = true;
10690 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10694 static void io_eventfd_put(struct rcu_head *rcu)
10696 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10698 eventfd_ctx_put(ev_fd->cq_ev_fd);
10702 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10704 struct io_ev_fd *ev_fd;
10706 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10707 lockdep_is_held(&ctx->uring_lock));
10709 ctx->has_evfd = false;
10710 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10711 call_rcu(&ev_fd->rcu, io_eventfd_put);
10718 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10720 struct io_buffer_list *bl;
10721 unsigned long index;
10724 for (i = 0; i < BGID_ARRAY; i++) {
10727 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
10730 xa_for_each(&ctx->io_bl_xa, index, bl) {
10731 xa_erase(&ctx->io_bl_xa, bl->bgid);
10732 __io_remove_buffers(ctx, bl, -1U);
10735 while (!list_empty(&ctx->io_buffers_pages)) {
10738 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10739 list_del_init(&page->lru);
10744 static void io_req_caches_free(struct io_ring_ctx *ctx)
10746 struct io_submit_state *state = &ctx->submit_state;
10749 mutex_lock(&ctx->uring_lock);
10750 io_flush_cached_locked_reqs(ctx, state);
10752 while (!io_req_cache_empty(ctx)) {
10753 struct io_wq_work_node *node;
10754 struct io_kiocb *req;
10756 node = wq_stack_extract(&state->free_list);
10757 req = container_of(node, struct io_kiocb, comp_list);
10758 kmem_cache_free(req_cachep, req);
10762 percpu_ref_put_many(&ctx->refs, nr);
10763 mutex_unlock(&ctx->uring_lock);
10766 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10768 if (data && !atomic_dec_and_test(&data->refs))
10769 wait_for_completion(&data->done);
10772 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10774 struct async_poll *apoll;
10776 while (!list_empty(&ctx->apoll_cache)) {
10777 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10779 list_del(&apoll->poll.wait.entry);
10784 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10786 io_sq_thread_finish(ctx);
10788 if (ctx->mm_account) {
10789 mmdrop(ctx->mm_account);
10790 ctx->mm_account = NULL;
10793 io_rsrc_refs_drop(ctx);
10794 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10795 io_wait_rsrc_data(ctx->buf_data);
10796 io_wait_rsrc_data(ctx->file_data);
10798 mutex_lock(&ctx->uring_lock);
10800 __io_sqe_buffers_unregister(ctx);
10801 if (ctx->file_data)
10802 __io_sqe_files_unregister(ctx);
10804 __io_cqring_overflow_flush(ctx, true);
10805 io_eventfd_unregister(ctx);
10806 io_flush_apoll_cache(ctx);
10807 mutex_unlock(&ctx->uring_lock);
10808 io_destroy_buffers(ctx);
10810 put_cred(ctx->sq_creds);
10812 /* there are no registered resources left, nobody uses it */
10813 if (ctx->rsrc_node)
10814 io_rsrc_node_destroy(ctx->rsrc_node);
10815 if (ctx->rsrc_backup_node)
10816 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10817 flush_delayed_work(&ctx->rsrc_put_work);
10818 flush_delayed_work(&ctx->fallback_work);
10820 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10821 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10823 #if defined(CONFIG_UNIX)
10824 if (ctx->ring_sock) {
10825 ctx->ring_sock->file = NULL; /* so that iput() is called */
10826 sock_release(ctx->ring_sock);
10829 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10831 io_mem_free(ctx->rings);
10832 io_mem_free(ctx->sq_sqes);
10834 percpu_ref_exit(&ctx->refs);
10835 free_uid(ctx->user);
10836 io_req_caches_free(ctx);
10838 io_wq_put_hash(ctx->hash_map);
10839 kfree(ctx->cancel_hash);
10840 kfree(ctx->dummy_ubuf);
10842 xa_destroy(&ctx->io_bl_xa);
10846 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10848 struct io_ring_ctx *ctx = file->private_data;
10851 poll_wait(file, &ctx->cq_wait, wait);
10853 * synchronizes with barrier from wq_has_sleeper call in
10857 if (!io_sqring_full(ctx))
10858 mask |= EPOLLOUT | EPOLLWRNORM;
10861 * Don't flush cqring overflow list here, just do a simple check.
10862 * Otherwise there could possible be ABBA deadlock:
10865 * lock(&ctx->uring_lock);
10867 * lock(&ctx->uring_lock);
10870 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10871 * pushs them to do the flush.
10873 if (io_cqring_events(ctx) ||
10874 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
10875 mask |= EPOLLIN | EPOLLRDNORM;
10880 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10882 const struct cred *creds;
10884 creds = xa_erase(&ctx->personalities, id);
10893 struct io_tctx_exit {
10894 struct callback_head task_work;
10895 struct completion completion;
10896 struct io_ring_ctx *ctx;
10899 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10901 struct io_uring_task *tctx = current->io_uring;
10902 struct io_tctx_exit *work;
10904 work = container_of(cb, struct io_tctx_exit, task_work);
10906 * When @in_idle, we're in cancellation and it's racy to remove the
10907 * node. It'll be removed by the end of cancellation, just ignore it.
10909 if (!atomic_read(&tctx->in_idle))
10910 io_uring_del_tctx_node((unsigned long)work->ctx);
10911 complete(&work->completion);
10914 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10916 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10918 return req->ctx == data;
10921 static __cold void io_ring_exit_work(struct work_struct *work)
10923 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10924 unsigned long timeout = jiffies + HZ * 60 * 5;
10925 unsigned long interval = HZ / 20;
10926 struct io_tctx_exit exit;
10927 struct io_tctx_node *node;
10931 * If we're doing polled IO and end up having requests being
10932 * submitted async (out-of-line), then completions can come in while
10933 * we're waiting for refs to drop. We need to reap these manually,
10934 * as nobody else will be looking for them.
10937 io_uring_try_cancel_requests(ctx, NULL, true);
10938 if (ctx->sq_data) {
10939 struct io_sq_data *sqd = ctx->sq_data;
10940 struct task_struct *tsk;
10942 io_sq_thread_park(sqd);
10944 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10945 io_wq_cancel_cb(tsk->io_uring->io_wq,
10946 io_cancel_ctx_cb, ctx, true);
10947 io_sq_thread_unpark(sqd);
10950 io_req_caches_free(ctx);
10952 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10953 /* there is little hope left, don't run it too often */
10954 interval = HZ * 60;
10956 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10958 init_completion(&exit.completion);
10959 init_task_work(&exit.task_work, io_tctx_exit_cb);
10962 * Some may use context even when all refs and requests have been put,
10963 * and they are free to do so while still holding uring_lock or
10964 * completion_lock, see io_req_task_submit(). Apart from other work,
10965 * this lock/unlock section also waits them to finish.
10967 mutex_lock(&ctx->uring_lock);
10968 while (!list_empty(&ctx->tctx_list)) {
10969 WARN_ON_ONCE(time_after(jiffies, timeout));
10971 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10973 /* don't spin on a single task if cancellation failed */
10974 list_rotate_left(&ctx->tctx_list);
10975 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10976 if (WARN_ON_ONCE(ret))
10979 mutex_unlock(&ctx->uring_lock);
10980 wait_for_completion(&exit.completion);
10981 mutex_lock(&ctx->uring_lock);
10983 mutex_unlock(&ctx->uring_lock);
10984 spin_lock(&ctx->completion_lock);
10985 spin_unlock(&ctx->completion_lock);
10987 io_ring_ctx_free(ctx);
10990 /* Returns true if we found and killed one or more timeouts */
10991 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10992 struct task_struct *tsk, bool cancel_all)
10994 struct io_kiocb *req, *tmp;
10997 spin_lock(&ctx->completion_lock);
10998 spin_lock_irq(&ctx->timeout_lock);
10999 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
11000 if (io_match_task(req, tsk, cancel_all)) {
11001 io_kill_timeout(req, -ECANCELED);
11005 spin_unlock_irq(&ctx->timeout_lock);
11006 io_commit_cqring(ctx);
11007 spin_unlock(&ctx->completion_lock);
11009 io_cqring_ev_posted(ctx);
11010 return canceled != 0;
11013 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
11015 unsigned long index;
11016 struct creds *creds;
11018 mutex_lock(&ctx->uring_lock);
11019 percpu_ref_kill(&ctx->refs);
11021 __io_cqring_overflow_flush(ctx, true);
11022 xa_for_each(&ctx->personalities, index, creds)
11023 io_unregister_personality(ctx, index);
11024 mutex_unlock(&ctx->uring_lock);
11026 /* failed during ring init, it couldn't have issued any requests */
11028 io_kill_timeouts(ctx, NULL, true);
11029 io_poll_remove_all(ctx, NULL, true);
11030 /* if we failed setting up the ctx, we might not have any rings */
11031 io_iopoll_try_reap_events(ctx);
11034 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
11036 * Use system_unbound_wq to avoid spawning tons of event kworkers
11037 * if we're exiting a ton of rings at the same time. It just adds
11038 * noise and overhead, there's no discernable change in runtime
11039 * over using system_wq.
11041 queue_work(system_unbound_wq, &ctx->exit_work);
11044 static int io_uring_release(struct inode *inode, struct file *file)
11046 struct io_ring_ctx *ctx = file->private_data;
11048 file->private_data = NULL;
11049 io_ring_ctx_wait_and_kill(ctx);
11053 struct io_task_cancel {
11054 struct task_struct *task;
11058 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
11060 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
11061 struct io_task_cancel *cancel = data;
11063 return io_match_task_safe(req, cancel->task, cancel->all);
11066 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
11067 struct task_struct *task,
11070 struct io_defer_entry *de;
11073 spin_lock(&ctx->completion_lock);
11074 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
11075 if (io_match_task_safe(de->req, task, cancel_all)) {
11076 list_cut_position(&list, &ctx->defer_list, &de->list);
11080 spin_unlock(&ctx->completion_lock);
11081 if (list_empty(&list))
11084 while (!list_empty(&list)) {
11085 de = list_first_entry(&list, struct io_defer_entry, list);
11086 list_del_init(&de->list);
11087 io_req_complete_failed(de->req, -ECANCELED);
11093 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11095 struct io_tctx_node *node;
11096 enum io_wq_cancel cret;
11099 mutex_lock(&ctx->uring_lock);
11100 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11101 struct io_uring_task *tctx = node->task->io_uring;
11104 * io_wq will stay alive while we hold uring_lock, because it's
11105 * killed after ctx nodes, which requires to take the lock.
11107 if (!tctx || !tctx->io_wq)
11109 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11110 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11112 mutex_unlock(&ctx->uring_lock);
11117 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11118 struct task_struct *task,
11121 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11122 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11124 /* failed during ring init, it couldn't have issued any requests */
11129 enum io_wq_cancel cret;
11133 ret |= io_uring_try_cancel_iowq(ctx);
11134 } else if (tctx && tctx->io_wq) {
11136 * Cancels requests of all rings, not only @ctx, but
11137 * it's fine as the task is in exit/exec.
11139 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11141 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11144 /* SQPOLL thread does its own polling */
11145 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11146 (ctx->sq_data && ctx->sq_data->thread == current)) {
11147 while (!wq_list_empty(&ctx->iopoll_list)) {
11148 io_iopoll_try_reap_events(ctx);
11153 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11154 ret |= io_poll_remove_all(ctx, task, cancel_all);
11155 ret |= io_kill_timeouts(ctx, task, cancel_all);
11157 ret |= io_run_task_work();
11164 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11166 struct io_uring_task *tctx = current->io_uring;
11167 struct io_tctx_node *node;
11170 if (unlikely(!tctx)) {
11171 ret = io_uring_alloc_task_context(current, ctx);
11175 tctx = current->io_uring;
11176 if (ctx->iowq_limits_set) {
11177 unsigned int limits[2] = { ctx->iowq_limits[0],
11178 ctx->iowq_limits[1], };
11180 ret = io_wq_max_workers(tctx->io_wq, limits);
11185 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11186 node = kmalloc(sizeof(*node), GFP_KERNEL);
11190 node->task = current;
11192 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11193 node, GFP_KERNEL));
11199 mutex_lock(&ctx->uring_lock);
11200 list_add(&node->ctx_node, &ctx->tctx_list);
11201 mutex_unlock(&ctx->uring_lock);
11208 * Note that this task has used io_uring. We use it for cancelation purposes.
11210 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11212 struct io_uring_task *tctx = current->io_uring;
11214 if (likely(tctx && tctx->last == ctx))
11216 return __io_uring_add_tctx_node(ctx);
11220 * Remove this io_uring_file -> task mapping.
11222 static __cold void io_uring_del_tctx_node(unsigned long index)
11224 struct io_uring_task *tctx = current->io_uring;
11225 struct io_tctx_node *node;
11229 node = xa_erase(&tctx->xa, index);
11233 WARN_ON_ONCE(current != node->task);
11234 WARN_ON_ONCE(list_empty(&node->ctx_node));
11236 mutex_lock(&node->ctx->uring_lock);
11237 list_del(&node->ctx_node);
11238 mutex_unlock(&node->ctx->uring_lock);
11240 if (tctx->last == node->ctx)
11245 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11247 struct io_wq *wq = tctx->io_wq;
11248 struct io_tctx_node *node;
11249 unsigned long index;
11251 xa_for_each(&tctx->xa, index, node) {
11252 io_uring_del_tctx_node(index);
11257 * Must be after io_uring_del_tctx_node() (removes nodes under
11258 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11260 io_wq_put_and_exit(wq);
11261 tctx->io_wq = NULL;
11265 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11269 return percpu_counter_sum(&tctx->inflight);
11273 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11274 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11276 static __cold void io_uring_cancel_generic(bool cancel_all,
11277 struct io_sq_data *sqd)
11279 struct io_uring_task *tctx = current->io_uring;
11280 struct io_ring_ctx *ctx;
11284 WARN_ON_ONCE(sqd && sqd->thread != current);
11286 if (!current->io_uring)
11289 io_wq_exit_start(tctx->io_wq);
11291 atomic_inc(&tctx->in_idle);
11293 io_uring_drop_tctx_refs(current);
11294 /* read completions before cancelations */
11295 inflight = tctx_inflight(tctx, !cancel_all);
11300 struct io_tctx_node *node;
11301 unsigned long index;
11303 xa_for_each(&tctx->xa, index, node) {
11304 /* sqpoll task will cancel all its requests */
11305 if (node->ctx->sq_data)
11307 io_uring_try_cancel_requests(node->ctx, current,
11311 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11312 io_uring_try_cancel_requests(ctx, current,
11316 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11317 io_run_task_work();
11318 io_uring_drop_tctx_refs(current);
11321 * If we've seen completions, retry without waiting. This
11322 * avoids a race where a completion comes in before we did
11323 * prepare_to_wait().
11325 if (inflight == tctx_inflight(tctx, !cancel_all))
11327 finish_wait(&tctx->wait, &wait);
11330 io_uring_clean_tctx(tctx);
11333 * We shouldn't run task_works after cancel, so just leave
11334 * ->in_idle set for normal exit.
11336 atomic_dec(&tctx->in_idle);
11337 /* for exec all current's requests should be gone, kill tctx */
11338 __io_uring_free(current);
11342 void __io_uring_cancel(bool cancel_all)
11344 io_uring_cancel_generic(cancel_all, NULL);
11347 void io_uring_unreg_ringfd(void)
11349 struct io_uring_task *tctx = current->io_uring;
11352 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11353 if (tctx->registered_rings[i]) {
11354 fput(tctx->registered_rings[i]);
11355 tctx->registered_rings[i] = NULL;
11360 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11361 int start, int end)
11366 for (offset = start; offset < end; offset++) {
11367 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11368 if (tctx->registered_rings[offset])
11374 } else if (file->f_op != &io_uring_fops) {
11376 return -EOPNOTSUPP;
11378 tctx->registered_rings[offset] = file;
11386 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11387 * invocation. User passes in an array of struct io_uring_rsrc_update
11388 * with ->data set to the ring_fd, and ->offset given for the desired
11389 * index. If no index is desired, application may set ->offset == -1U
11390 * and we'll find an available index. Returns number of entries
11391 * successfully processed, or < 0 on error if none were processed.
11393 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11396 struct io_uring_rsrc_update __user *arg = __arg;
11397 struct io_uring_rsrc_update reg;
11398 struct io_uring_task *tctx;
11401 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11404 mutex_unlock(&ctx->uring_lock);
11405 ret = io_uring_add_tctx_node(ctx);
11406 mutex_lock(&ctx->uring_lock);
11410 tctx = current->io_uring;
11411 for (i = 0; i < nr_args; i++) {
11414 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11424 if (reg.offset == -1U) {
11426 end = IO_RINGFD_REG_MAX;
11428 if (reg.offset >= IO_RINGFD_REG_MAX) {
11432 start = reg.offset;
11436 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11441 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11442 fput(tctx->registered_rings[reg.offset]);
11443 tctx->registered_rings[reg.offset] = NULL;
11449 return i ? i : ret;
11452 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11455 struct io_uring_rsrc_update __user *arg = __arg;
11456 struct io_uring_task *tctx = current->io_uring;
11457 struct io_uring_rsrc_update reg;
11460 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11465 for (i = 0; i < nr_args; i++) {
11466 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11470 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11475 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11476 if (tctx->registered_rings[reg.offset]) {
11477 fput(tctx->registered_rings[reg.offset]);
11478 tctx->registered_rings[reg.offset] = NULL;
11482 return i ? i : ret;
11485 static void *io_uring_validate_mmap_request(struct file *file,
11486 loff_t pgoff, size_t sz)
11488 struct io_ring_ctx *ctx = file->private_data;
11489 loff_t offset = pgoff << PAGE_SHIFT;
11494 case IORING_OFF_SQ_RING:
11495 case IORING_OFF_CQ_RING:
11498 case IORING_OFF_SQES:
11499 ptr = ctx->sq_sqes;
11502 return ERR_PTR(-EINVAL);
11505 page = virt_to_head_page(ptr);
11506 if (sz > page_size(page))
11507 return ERR_PTR(-EINVAL);
11514 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11516 size_t sz = vma->vm_end - vma->vm_start;
11520 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11522 return PTR_ERR(ptr);
11524 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11525 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11528 #else /* !CONFIG_MMU */
11530 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11532 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11535 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11537 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11540 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11541 unsigned long addr, unsigned long len,
11542 unsigned long pgoff, unsigned long flags)
11546 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11548 return PTR_ERR(ptr);
11550 return (unsigned long) ptr;
11553 #endif /* !CONFIG_MMU */
11555 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11560 if (!io_sqring_full(ctx))
11562 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11564 if (!io_sqring_full(ctx))
11567 } while (!signal_pending(current));
11569 finish_wait(&ctx->sqo_sq_wait, &wait);
11573 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11575 if (flags & IORING_ENTER_EXT_ARG) {
11576 struct io_uring_getevents_arg arg;
11578 if (argsz != sizeof(arg))
11580 if (copy_from_user(&arg, argp, sizeof(arg)))
11586 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11587 struct __kernel_timespec __user **ts,
11588 const sigset_t __user **sig)
11590 struct io_uring_getevents_arg arg;
11593 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11594 * is just a pointer to the sigset_t.
11596 if (!(flags & IORING_ENTER_EXT_ARG)) {
11597 *sig = (const sigset_t __user *) argp;
11603 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11604 * timespec and sigset_t pointers if good.
11606 if (*argsz != sizeof(arg))
11608 if (copy_from_user(&arg, argp, sizeof(arg)))
11612 *sig = u64_to_user_ptr(arg.sigmask);
11613 *argsz = arg.sigmask_sz;
11614 *ts = u64_to_user_ptr(arg.ts);
11618 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11619 u32, min_complete, u32, flags, const void __user *, argp,
11622 struct io_ring_ctx *ctx;
11626 io_run_task_work();
11628 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11629 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11630 IORING_ENTER_REGISTERED_RING)))
11634 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11635 * need only dereference our task private array to find it.
11637 if (flags & IORING_ENTER_REGISTERED_RING) {
11638 struct io_uring_task *tctx = current->io_uring;
11640 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11642 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11643 f.file = tctx->registered_rings[fd];
11644 if (unlikely(!f.file))
11648 if (unlikely(!f.file))
11653 if (unlikely(f.file->f_op != &io_uring_fops))
11657 ctx = f.file->private_data;
11658 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11662 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11666 * For SQ polling, the thread will do all submissions and completions.
11667 * Just return the requested submit count, and wake the thread if
11668 * we were asked to.
11671 if (ctx->flags & IORING_SETUP_SQPOLL) {
11672 io_cqring_overflow_flush(ctx);
11674 if (unlikely(ctx->sq_data->thread == NULL)) {
11678 if (flags & IORING_ENTER_SQ_WAKEUP)
11679 wake_up(&ctx->sq_data->wait);
11680 if (flags & IORING_ENTER_SQ_WAIT) {
11681 ret = io_sqpoll_wait_sq(ctx);
11686 } else if (to_submit) {
11687 ret = io_uring_add_tctx_node(ctx);
11691 mutex_lock(&ctx->uring_lock);
11692 ret = io_submit_sqes(ctx, to_submit);
11693 if (ret != to_submit) {
11694 mutex_unlock(&ctx->uring_lock);
11697 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
11698 goto iopoll_locked;
11699 mutex_unlock(&ctx->uring_lock);
11701 if (flags & IORING_ENTER_GETEVENTS) {
11703 if (ctx->syscall_iopoll) {
11705 * We disallow the app entering submit/complete with
11706 * polling, but we still need to lock the ring to
11707 * prevent racing with polled issue that got punted to
11710 mutex_lock(&ctx->uring_lock);
11712 ret2 = io_validate_ext_arg(flags, argp, argsz);
11713 if (likely(!ret2)) {
11714 min_complete = min(min_complete,
11716 ret2 = io_iopoll_check(ctx, min_complete);
11718 mutex_unlock(&ctx->uring_lock);
11720 const sigset_t __user *sig;
11721 struct __kernel_timespec __user *ts;
11723 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
11724 if (likely(!ret2)) {
11725 min_complete = min(min_complete,
11727 ret2 = io_cqring_wait(ctx, min_complete, sig,
11736 * EBADR indicates that one or more CQE were dropped.
11737 * Once the user has been informed we can clear the bit
11738 * as they are obviously ok with those drops.
11740 if (unlikely(ret2 == -EBADR))
11741 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
11747 percpu_ref_put(&ctx->refs);
11749 if (!(flags & IORING_ENTER_REGISTERED_RING))
11754 #ifdef CONFIG_PROC_FS
11755 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11756 const struct cred *cred)
11758 struct user_namespace *uns = seq_user_ns(m);
11759 struct group_info *gi;
11764 seq_printf(m, "%5d\n", id);
11765 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11766 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11767 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11768 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11769 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11770 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11771 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11772 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11773 seq_puts(m, "\n\tGroups:\t");
11774 gi = cred->group_info;
11775 for (g = 0; g < gi->ngroups; g++) {
11776 seq_put_decimal_ull(m, g ? " " : "",
11777 from_kgid_munged(uns, gi->gid[g]));
11779 seq_puts(m, "\n\tCapEff:\t");
11780 cap = cred->cap_effective;
11781 CAP_FOR_EACH_U32(__capi)
11782 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11787 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11788 struct seq_file *m)
11790 struct io_sq_data *sq = NULL;
11791 struct io_overflow_cqe *ocqe;
11792 struct io_rings *r = ctx->rings;
11793 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11794 unsigned int sq_head = READ_ONCE(r->sq.head);
11795 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11796 unsigned int cq_head = READ_ONCE(r->cq.head);
11797 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11798 unsigned int cq_shift = 0;
11799 unsigned int sq_entries, cq_entries;
11801 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
11808 * we may get imprecise sqe and cqe info if uring is actively running
11809 * since we get cached_sq_head and cached_cq_tail without uring_lock
11810 * and sq_tail and cq_head are changed by userspace. But it's ok since
11811 * we usually use these info when it is stuck.
11813 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11814 seq_printf(m, "SqHead:\t%u\n", sq_head);
11815 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11816 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11817 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11818 seq_printf(m, "CqHead:\t%u\n", cq_head);
11819 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11820 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11821 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11822 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11823 for (i = 0; i < sq_entries; i++) {
11824 unsigned int entry = i + sq_head;
11825 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11826 struct io_uring_sqe *sqe;
11828 if (sq_idx > sq_mask)
11830 sqe = &ctx->sq_sqes[sq_idx];
11831 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11832 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11835 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11836 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11837 for (i = 0; i < cq_entries; i++) {
11838 unsigned int entry = i + cq_head;
11839 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
11842 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11843 entry & cq_mask, cqe->user_data, cqe->res,
11846 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
11847 "extra1:%llu, extra2:%llu\n",
11848 entry & cq_mask, cqe->user_data, cqe->res,
11849 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
11854 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11855 * since fdinfo case grabs it in the opposite direction of normal use
11856 * cases. If we fail to get the lock, we just don't iterate any
11857 * structures that could be going away outside the io_uring mutex.
11859 has_lock = mutex_trylock(&ctx->uring_lock);
11861 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11867 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11868 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11869 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11870 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11871 struct file *f = io_file_from_index(ctx, i);
11874 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11876 seq_printf(m, "%5u: <none>\n", i);
11878 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11879 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11880 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11881 unsigned int len = buf->ubuf_end - buf->ubuf;
11883 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11885 if (has_lock && !xa_empty(&ctx->personalities)) {
11886 unsigned long index;
11887 const struct cred *cred;
11889 seq_printf(m, "Personalities:\n");
11890 xa_for_each(&ctx->personalities, index, cred)
11891 io_uring_show_cred(m, index, cred);
11894 mutex_unlock(&ctx->uring_lock);
11896 seq_puts(m, "PollList:\n");
11897 spin_lock(&ctx->completion_lock);
11898 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11899 struct hlist_head *list = &ctx->cancel_hash[i];
11900 struct io_kiocb *req;
11902 hlist_for_each_entry(req, list, hash_node)
11903 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11904 task_work_pending(req->task));
11907 seq_puts(m, "CqOverflowList:\n");
11908 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11909 struct io_uring_cqe *cqe = &ocqe->cqe;
11911 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11912 cqe->user_data, cqe->res, cqe->flags);
11916 spin_unlock(&ctx->completion_lock);
11919 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11921 struct io_ring_ctx *ctx = f->private_data;
11923 if (percpu_ref_tryget(&ctx->refs)) {
11924 __io_uring_show_fdinfo(ctx, m);
11925 percpu_ref_put(&ctx->refs);
11930 static const struct file_operations io_uring_fops = {
11931 .release = io_uring_release,
11932 .mmap = io_uring_mmap,
11934 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11935 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11937 .poll = io_uring_poll,
11938 #ifdef CONFIG_PROC_FS
11939 .show_fdinfo = io_uring_show_fdinfo,
11943 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11944 struct io_uring_params *p)
11946 struct io_rings *rings;
11947 size_t size, sq_array_offset;
11949 /* make sure these are sane, as we already accounted them */
11950 ctx->sq_entries = p->sq_entries;
11951 ctx->cq_entries = p->cq_entries;
11953 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
11954 if (size == SIZE_MAX)
11957 rings = io_mem_alloc(size);
11961 ctx->rings = rings;
11962 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11963 rings->sq_ring_mask = p->sq_entries - 1;
11964 rings->cq_ring_mask = p->cq_entries - 1;
11965 rings->sq_ring_entries = p->sq_entries;
11966 rings->cq_ring_entries = p->cq_entries;
11968 if (p->flags & IORING_SETUP_SQE128)
11969 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
11971 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11972 if (size == SIZE_MAX) {
11973 io_mem_free(ctx->rings);
11978 ctx->sq_sqes = io_mem_alloc(size);
11979 if (!ctx->sq_sqes) {
11980 io_mem_free(ctx->rings);
11988 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11992 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11996 ret = io_uring_add_tctx_node(ctx);
12001 fd_install(fd, file);
12006 * Allocate an anonymous fd, this is what constitutes the application
12007 * visible backing of an io_uring instance. The application mmaps this
12008 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
12009 * we have to tie this fd to a socket for file garbage collection purposes.
12011 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
12014 #if defined(CONFIG_UNIX)
12017 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
12020 return ERR_PTR(ret);
12023 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
12024 O_RDWR | O_CLOEXEC, NULL);
12025 #if defined(CONFIG_UNIX)
12026 if (IS_ERR(file)) {
12027 sock_release(ctx->ring_sock);
12028 ctx->ring_sock = NULL;
12030 ctx->ring_sock->file = file;
12036 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
12037 struct io_uring_params __user *params)
12039 struct io_ring_ctx *ctx;
12045 if (entries > IORING_MAX_ENTRIES) {
12046 if (!(p->flags & IORING_SETUP_CLAMP))
12048 entries = IORING_MAX_ENTRIES;
12052 * Use twice as many entries for the CQ ring. It's possible for the
12053 * application to drive a higher depth than the size of the SQ ring,
12054 * since the sqes are only used at submission time. This allows for
12055 * some flexibility in overcommitting a bit. If the application has
12056 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
12057 * of CQ ring entries manually.
12059 p->sq_entries = roundup_pow_of_two(entries);
12060 if (p->flags & IORING_SETUP_CQSIZE) {
12062 * If IORING_SETUP_CQSIZE is set, we do the same roundup
12063 * to a power-of-two, if it isn't already. We do NOT impose
12064 * any cq vs sq ring sizing.
12066 if (!p->cq_entries)
12068 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
12069 if (!(p->flags & IORING_SETUP_CLAMP))
12071 p->cq_entries = IORING_MAX_CQ_ENTRIES;
12073 p->cq_entries = roundup_pow_of_two(p->cq_entries);
12074 if (p->cq_entries < p->sq_entries)
12077 p->cq_entries = 2 * p->sq_entries;
12080 ctx = io_ring_ctx_alloc(p);
12085 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12086 * space applications don't need to do io completion events
12087 * polling again, they can rely on io_sq_thread to do polling
12088 * work, which can reduce cpu usage and uring_lock contention.
12090 if (ctx->flags & IORING_SETUP_IOPOLL &&
12091 !(ctx->flags & IORING_SETUP_SQPOLL))
12092 ctx->syscall_iopoll = 1;
12094 ctx->compat = in_compat_syscall();
12095 if (!capable(CAP_IPC_LOCK))
12096 ctx->user = get_uid(current_user());
12099 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12100 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12103 if (ctx->flags & IORING_SETUP_SQPOLL) {
12104 /* IPI related flags don't make sense with SQPOLL */
12105 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12106 IORING_SETUP_TASKRUN_FLAG))
12108 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12109 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12110 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12112 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12114 ctx->notify_method = TWA_SIGNAL;
12118 * This is just grabbed for accounting purposes. When a process exits,
12119 * the mm is exited and dropped before the files, hence we need to hang
12120 * on to this mm purely for the purposes of being able to unaccount
12121 * memory (locked/pinned vm). It's not used for anything else.
12123 mmgrab(current->mm);
12124 ctx->mm_account = current->mm;
12126 ret = io_allocate_scq_urings(ctx, p);
12130 ret = io_sq_offload_create(ctx, p);
12133 /* always set a rsrc node */
12134 ret = io_rsrc_node_switch_start(ctx);
12137 io_rsrc_node_switch(ctx, NULL);
12139 memset(&p->sq_off, 0, sizeof(p->sq_off));
12140 p->sq_off.head = offsetof(struct io_rings, sq.head);
12141 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12142 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12143 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12144 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12145 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12146 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12148 memset(&p->cq_off, 0, sizeof(p->cq_off));
12149 p->cq_off.head = offsetof(struct io_rings, cq.head);
12150 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12151 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12152 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12153 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12154 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12155 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12157 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12158 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12159 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12160 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12161 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12162 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12163 IORING_FEAT_LINKED_FILE;
12165 if (copy_to_user(params, p, sizeof(*p))) {
12170 file = io_uring_get_file(ctx);
12171 if (IS_ERR(file)) {
12172 ret = PTR_ERR(file);
12177 * Install ring fd as the very last thing, so we don't risk someone
12178 * having closed it before we finish setup
12180 ret = io_uring_install_fd(ctx, file);
12182 /* fput will clean it up */
12187 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12190 io_ring_ctx_wait_and_kill(ctx);
12195 * Sets up an aio uring context, and returns the fd. Applications asks for a
12196 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12197 * params structure passed in.
12199 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12201 struct io_uring_params p;
12204 if (copy_from_user(&p, params, sizeof(p)))
12206 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12211 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12212 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12213 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12214 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12215 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12216 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12219 return io_uring_create(entries, &p, params);
12222 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12223 struct io_uring_params __user *, params)
12225 return io_uring_setup(entries, params);
12228 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12231 struct io_uring_probe *p;
12235 size = struct_size(p, ops, nr_args);
12236 if (size == SIZE_MAX)
12238 p = kzalloc(size, GFP_KERNEL);
12243 if (copy_from_user(p, arg, size))
12246 if (memchr_inv(p, 0, size))
12249 p->last_op = IORING_OP_LAST - 1;
12250 if (nr_args > IORING_OP_LAST)
12251 nr_args = IORING_OP_LAST;
12253 for (i = 0; i < nr_args; i++) {
12255 if (!io_op_defs[i].not_supported)
12256 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12261 if (copy_to_user(arg, p, size))
12268 static int io_register_personality(struct io_ring_ctx *ctx)
12270 const struct cred *creds;
12274 creds = get_current_cred();
12276 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12277 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12285 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12286 void __user *arg, unsigned int nr_args)
12288 struct io_uring_restriction *res;
12292 /* Restrictions allowed only if rings started disabled */
12293 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12296 /* We allow only a single restrictions registration */
12297 if (ctx->restrictions.registered)
12300 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12303 size = array_size(nr_args, sizeof(*res));
12304 if (size == SIZE_MAX)
12307 res = memdup_user(arg, size);
12309 return PTR_ERR(res);
12313 for (i = 0; i < nr_args; i++) {
12314 switch (res[i].opcode) {
12315 case IORING_RESTRICTION_REGISTER_OP:
12316 if (res[i].register_op >= IORING_REGISTER_LAST) {
12321 __set_bit(res[i].register_op,
12322 ctx->restrictions.register_op);
12324 case IORING_RESTRICTION_SQE_OP:
12325 if (res[i].sqe_op >= IORING_OP_LAST) {
12330 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12332 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12333 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12335 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12336 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12345 /* Reset all restrictions if an error happened */
12347 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12349 ctx->restrictions.registered = true;
12355 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12357 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12360 if (ctx->restrictions.registered)
12361 ctx->restricted = 1;
12363 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12364 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12365 wake_up(&ctx->sq_data->wait);
12369 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12370 struct io_uring_rsrc_update2 *up,
12376 if (check_add_overflow(up->offset, nr_args, &tmp))
12378 err = io_rsrc_node_switch_start(ctx);
12383 case IORING_RSRC_FILE:
12384 return __io_sqe_files_update(ctx, up, nr_args);
12385 case IORING_RSRC_BUFFER:
12386 return __io_sqe_buffers_update(ctx, up, nr_args);
12391 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12394 struct io_uring_rsrc_update2 up;
12398 memset(&up, 0, sizeof(up));
12399 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12401 if (up.resv || up.resv2)
12403 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12406 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12407 unsigned size, unsigned type)
12409 struct io_uring_rsrc_update2 up;
12411 if (size != sizeof(up))
12413 if (copy_from_user(&up, arg, sizeof(up)))
12415 if (!up.nr || up.resv || up.resv2)
12417 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12420 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12421 unsigned int size, unsigned int type)
12423 struct io_uring_rsrc_register rr;
12425 /* keep it extendible */
12426 if (size != sizeof(rr))
12429 memset(&rr, 0, sizeof(rr));
12430 if (copy_from_user(&rr, arg, size))
12432 if (!rr.nr || rr.resv || rr.resv2)
12436 case IORING_RSRC_FILE:
12437 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12438 rr.nr, u64_to_user_ptr(rr.tags));
12439 case IORING_RSRC_BUFFER:
12440 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12441 rr.nr, u64_to_user_ptr(rr.tags));
12446 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12447 void __user *arg, unsigned len)
12449 struct io_uring_task *tctx = current->io_uring;
12450 cpumask_var_t new_mask;
12453 if (!tctx || !tctx->io_wq)
12456 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12459 cpumask_clear(new_mask);
12460 if (len > cpumask_size())
12461 len = cpumask_size();
12463 if (in_compat_syscall()) {
12464 ret = compat_get_bitmap(cpumask_bits(new_mask),
12465 (const compat_ulong_t __user *)arg,
12466 len * 8 /* CHAR_BIT */);
12468 ret = copy_from_user(new_mask, arg, len);
12472 free_cpumask_var(new_mask);
12476 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12477 free_cpumask_var(new_mask);
12481 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12483 struct io_uring_task *tctx = current->io_uring;
12485 if (!tctx || !tctx->io_wq)
12488 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12491 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12493 __must_hold(&ctx->uring_lock)
12495 struct io_tctx_node *node;
12496 struct io_uring_task *tctx = NULL;
12497 struct io_sq_data *sqd = NULL;
12498 __u32 new_count[2];
12501 if (copy_from_user(new_count, arg, sizeof(new_count)))
12503 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12504 if (new_count[i] > INT_MAX)
12507 if (ctx->flags & IORING_SETUP_SQPOLL) {
12508 sqd = ctx->sq_data;
12511 * Observe the correct sqd->lock -> ctx->uring_lock
12512 * ordering. Fine to drop uring_lock here, we hold
12513 * a ref to the ctx.
12515 refcount_inc(&sqd->refs);
12516 mutex_unlock(&ctx->uring_lock);
12517 mutex_lock(&sqd->lock);
12518 mutex_lock(&ctx->uring_lock);
12520 tctx = sqd->thread->io_uring;
12523 tctx = current->io_uring;
12526 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12528 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12530 ctx->iowq_limits[i] = new_count[i];
12531 ctx->iowq_limits_set = true;
12533 if (tctx && tctx->io_wq) {
12534 ret = io_wq_max_workers(tctx->io_wq, new_count);
12538 memset(new_count, 0, sizeof(new_count));
12542 mutex_unlock(&sqd->lock);
12543 io_put_sq_data(sqd);
12546 if (copy_to_user(arg, new_count, sizeof(new_count)))
12549 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12553 /* now propagate the restriction to all registered users */
12554 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12555 struct io_uring_task *tctx = node->task->io_uring;
12557 if (WARN_ON_ONCE(!tctx->io_wq))
12560 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12561 new_count[i] = ctx->iowq_limits[i];
12562 /* ignore errors, it always returns zero anyway */
12563 (void)io_wq_max_workers(tctx->io_wq, new_count);
12568 mutex_unlock(&sqd->lock);
12569 io_put_sq_data(sqd);
12574 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12575 void __user *arg, unsigned nr_args)
12576 __releases(ctx->uring_lock)
12577 __acquires(ctx->uring_lock)
12582 * We're inside the ring mutex, if the ref is already dying, then
12583 * someone else killed the ctx or is already going through
12584 * io_uring_register().
12586 if (percpu_ref_is_dying(&ctx->refs))
12589 if (ctx->restricted) {
12590 if (opcode >= IORING_REGISTER_LAST)
12592 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12593 if (!test_bit(opcode, ctx->restrictions.register_op))
12598 case IORING_REGISTER_BUFFERS:
12599 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
12601 case IORING_UNREGISTER_BUFFERS:
12603 if (arg || nr_args)
12605 ret = io_sqe_buffers_unregister(ctx);
12607 case IORING_REGISTER_FILES:
12608 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
12610 case IORING_UNREGISTER_FILES:
12612 if (arg || nr_args)
12614 ret = io_sqe_files_unregister(ctx);
12616 case IORING_REGISTER_FILES_UPDATE:
12617 ret = io_register_files_update(ctx, arg, nr_args);
12619 case IORING_REGISTER_EVENTFD:
12623 ret = io_eventfd_register(ctx, arg, 0);
12625 case IORING_REGISTER_EVENTFD_ASYNC:
12629 ret = io_eventfd_register(ctx, arg, 1);
12631 case IORING_UNREGISTER_EVENTFD:
12633 if (arg || nr_args)
12635 ret = io_eventfd_unregister(ctx);
12637 case IORING_REGISTER_PROBE:
12639 if (!arg || nr_args > 256)
12641 ret = io_probe(ctx, arg, nr_args);
12643 case IORING_REGISTER_PERSONALITY:
12645 if (arg || nr_args)
12647 ret = io_register_personality(ctx);
12649 case IORING_UNREGISTER_PERSONALITY:
12653 ret = io_unregister_personality(ctx, nr_args);
12655 case IORING_REGISTER_ENABLE_RINGS:
12657 if (arg || nr_args)
12659 ret = io_register_enable_rings(ctx);
12661 case IORING_REGISTER_RESTRICTIONS:
12662 ret = io_register_restrictions(ctx, arg, nr_args);
12664 case IORING_REGISTER_FILES2:
12665 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
12667 case IORING_REGISTER_FILES_UPDATE2:
12668 ret = io_register_rsrc_update(ctx, arg, nr_args,
12671 case IORING_REGISTER_BUFFERS2:
12672 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
12674 case IORING_REGISTER_BUFFERS_UPDATE:
12675 ret = io_register_rsrc_update(ctx, arg, nr_args,
12676 IORING_RSRC_BUFFER);
12678 case IORING_REGISTER_IOWQ_AFF:
12680 if (!arg || !nr_args)
12682 ret = io_register_iowq_aff(ctx, arg, nr_args);
12684 case IORING_UNREGISTER_IOWQ_AFF:
12686 if (arg || nr_args)
12688 ret = io_unregister_iowq_aff(ctx);
12690 case IORING_REGISTER_IOWQ_MAX_WORKERS:
12692 if (!arg || nr_args != 2)
12694 ret = io_register_iowq_max_workers(ctx, arg);
12696 case IORING_REGISTER_RING_FDS:
12697 ret = io_ringfd_register(ctx, arg, nr_args);
12699 case IORING_UNREGISTER_RING_FDS:
12700 ret = io_ringfd_unregister(ctx, arg, nr_args);
12710 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
12711 void __user *, arg, unsigned int, nr_args)
12713 struct io_ring_ctx *ctx;
12722 if (f.file->f_op != &io_uring_fops)
12725 ctx = f.file->private_data;
12727 io_run_task_work();
12729 mutex_lock(&ctx->uring_lock);
12730 ret = __io_uring_register(ctx, opcode, arg, nr_args);
12731 mutex_unlock(&ctx->uring_lock);
12732 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
12738 static int __init io_uring_init(void)
12740 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
12741 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
12742 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
12745 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
12746 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
12747 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
12748 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
12749 BUILD_BUG_SQE_ELEM(1, __u8, flags);
12750 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
12751 BUILD_BUG_SQE_ELEM(4, __s32, fd);
12752 BUILD_BUG_SQE_ELEM(8, __u64, off);
12753 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
12754 BUILD_BUG_SQE_ELEM(16, __u64, addr);
12755 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
12756 BUILD_BUG_SQE_ELEM(24, __u32, len);
12757 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
12758 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
12759 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
12760 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
12761 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
12762 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
12763 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
12764 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
12765 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
12766 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
12767 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
12768 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
12769 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
12770 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
12771 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
12772 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
12773 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
12774 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
12775 BUILD_BUG_SQE_ELEM(42, __u16, personality);
12776 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
12777 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
12778 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
12780 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
12781 sizeof(struct io_uring_rsrc_update));
12782 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
12783 sizeof(struct io_uring_rsrc_update2));
12785 /* ->buf_index is u16 */
12786 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
12787 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
12789 /* should fit into one byte */
12790 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
12791 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
12792 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
12794 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
12795 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
12797 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
12799 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
12801 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
12805 __initcall(io_uring_init);