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>
84 #define CREATE_TRACE_POINTS
85 #include <trace/events/io_uring.h>
87 #include <uapi/linux/io_uring.h>
92 #define IORING_MAX_ENTRIES 32768
93 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
97 #define IORING_MAX_FIXED_FILES (1U << 15)
98 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
99 IORING_REGISTER_LAST + IORING_OP_LAST)
101 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
102 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
103 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
105 #define IORING_MAX_REG_BUFFERS (1U << 14)
107 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
111 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_CREDS | REQ_F_ASYNC_DATA)
116 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
119 u32 head ____cacheline_aligned_in_smp;
120 u32 tail ____cacheline_aligned_in_smp;
124 * This data is shared with the application through the mmap at offsets
125 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
127 * The offsets to the member fields are published through struct
128 * io_sqring_offsets when calling io_uring_setup.
132 * Head and tail offsets into the ring; the offsets need to be
133 * masked to get valid indices.
135 * The kernel controls head of the sq ring and the tail of the cq ring,
136 * and the application controls tail of the sq ring and the head of the
139 struct io_uring sq, cq;
141 * Bitmasks to apply to head and tail offsets (constant, equals
144 u32 sq_ring_mask, cq_ring_mask;
145 /* Ring sizes (constant, power of 2) */
146 u32 sq_ring_entries, cq_ring_entries;
148 * Number of invalid entries dropped by the kernel due to
149 * invalid index stored in array
151 * Written by the kernel, shouldn't be modified by the
152 * application (i.e. get number of "new events" by comparing to
155 * After a new SQ head value was read by the application this
156 * counter includes all submissions that were dropped reaching
157 * the new SQ head (and possibly more).
163 * Written by the kernel, shouldn't be modified by the
166 * The application needs a full memory barrier before checking
167 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
173 * Written by the application, shouldn't be modified by the
178 * Number of completion events lost because the queue was full;
179 * this should be avoided by the application by making sure
180 * there are not more requests pending than there is space in
181 * the completion queue.
183 * Written by the kernel, shouldn't be modified by the
184 * application (i.e. get number of "new events" by comparing to
187 * As completion events come in out of order this counter is not
188 * ordered with any other data.
192 * Ring buffer of completion events.
194 * The kernel writes completion events fresh every time they are
195 * produced, so the application is allowed to modify pending
198 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
201 enum io_uring_cmd_flags {
202 IO_URING_F_COMPLETE_DEFER = 1,
203 IO_URING_F_UNLOCKED = 2,
204 /* int's last bit, sign checks are usually faster than a bit test */
205 IO_URING_F_NONBLOCK = INT_MIN,
208 struct io_mapped_ubuf {
211 unsigned int nr_bvecs;
212 unsigned long acct_pages;
213 struct bio_vec bvec[];
218 struct io_overflow_cqe {
219 struct io_uring_cqe cqe;
220 struct list_head list;
223 struct io_fixed_file {
224 /* file * with additional FFS_* flags */
225 unsigned long file_ptr;
229 struct list_head list;
234 struct io_mapped_ubuf *buf;
238 struct io_file_table {
239 struct io_fixed_file *files;
242 struct io_rsrc_node {
243 struct percpu_ref refs;
244 struct list_head node;
245 struct list_head rsrc_list;
246 struct io_rsrc_data *rsrc_data;
247 struct llist_node llist;
251 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
253 struct io_rsrc_data {
254 struct io_ring_ctx *ctx;
260 struct completion done;
264 struct io_buffer_list {
265 struct list_head list;
266 struct list_head buf_list;
271 struct list_head list;
278 struct io_restriction {
279 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
280 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
281 u8 sqe_flags_allowed;
282 u8 sqe_flags_required;
287 IO_SQ_THREAD_SHOULD_STOP = 0,
288 IO_SQ_THREAD_SHOULD_PARK,
293 atomic_t park_pending;
296 /* ctx's that are using this sqd */
297 struct list_head ctx_list;
299 struct task_struct *thread;
300 struct wait_queue_head wait;
302 unsigned sq_thread_idle;
308 struct completion exited;
311 #define IO_COMPL_BATCH 32
312 #define IO_REQ_CACHE_SIZE 32
313 #define IO_REQ_ALLOC_BATCH 8
315 struct io_submit_link {
316 struct io_kiocb *head;
317 struct io_kiocb *last;
320 struct io_submit_state {
321 /* inline/task_work completion list, under ->uring_lock */
322 struct io_wq_work_node free_list;
323 /* batch completion logic */
324 struct io_wq_work_list compl_reqs;
325 struct io_submit_link link;
330 unsigned short submit_nr;
331 struct blk_plug plug;
335 struct eventfd_ctx *cq_ev_fd;
336 unsigned int eventfd_async: 1;
340 #define IO_BUFFERS_HASH_BITS 5
343 /* const or read-mostly hot data */
345 struct percpu_ref refs;
347 struct io_rings *rings;
349 unsigned int compat: 1;
350 unsigned int drain_next: 1;
351 unsigned int restricted: 1;
352 unsigned int off_timeout_used: 1;
353 unsigned int drain_active: 1;
354 unsigned int drain_disabled: 1;
355 unsigned int has_evfd: 1;
356 } ____cacheline_aligned_in_smp;
358 /* submission data */
360 struct mutex uring_lock;
363 * Ring buffer of indices into array of io_uring_sqe, which is
364 * mmapped by the application using the IORING_OFF_SQES offset.
366 * This indirection could e.g. be used to assign fixed
367 * io_uring_sqe entries to operations and only submit them to
368 * the queue when needed.
370 * The kernel modifies neither the indices array nor the entries
374 struct io_uring_sqe *sq_sqes;
375 unsigned cached_sq_head;
377 struct list_head defer_list;
380 * Fixed resources fast path, should be accessed only under
381 * uring_lock, and updated through io_uring_register(2)
383 struct io_rsrc_node *rsrc_node;
384 int rsrc_cached_refs;
385 struct io_file_table file_table;
386 unsigned nr_user_files;
387 unsigned nr_user_bufs;
388 struct io_mapped_ubuf **user_bufs;
390 struct io_submit_state submit_state;
391 struct list_head timeout_list;
392 struct list_head ltimeout_list;
393 struct list_head cq_overflow_list;
394 struct list_head *io_buffers;
395 struct list_head io_buffers_cache;
396 struct list_head apoll_cache;
397 struct xarray personalities;
399 unsigned sq_thread_idle;
400 } ____cacheline_aligned_in_smp;
402 /* IRQ completion list, under ->completion_lock */
403 struct io_wq_work_list locked_free_list;
404 unsigned int locked_free_nr;
406 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
407 struct io_sq_data *sq_data; /* if using sq thread polling */
409 struct wait_queue_head sqo_sq_wait;
410 struct list_head sqd_list;
412 unsigned long check_cq_overflow;
415 unsigned cached_cq_tail;
417 struct io_ev_fd __rcu *io_ev_fd;
418 struct wait_queue_head cq_wait;
420 atomic_t cq_timeouts;
421 unsigned cq_last_tm_flush;
422 } ____cacheline_aligned_in_smp;
425 spinlock_t completion_lock;
427 spinlock_t timeout_lock;
430 * ->iopoll_list is protected by the ctx->uring_lock for
431 * io_uring instances that don't use IORING_SETUP_SQPOLL.
432 * For SQPOLL, only the single threaded io_sq_thread() will
433 * manipulate the list, hence no extra locking is needed there.
435 struct io_wq_work_list iopoll_list;
436 struct hlist_head *cancel_hash;
437 unsigned cancel_hash_bits;
438 bool poll_multi_queue;
440 struct list_head io_buffers_comp;
441 } ____cacheline_aligned_in_smp;
443 struct io_restriction restrictions;
445 /* slow path rsrc auxilary data, used by update/register */
447 struct io_rsrc_node *rsrc_backup_node;
448 struct io_mapped_ubuf *dummy_ubuf;
449 struct io_rsrc_data *file_data;
450 struct io_rsrc_data *buf_data;
452 struct delayed_work rsrc_put_work;
453 struct llist_head rsrc_put_llist;
454 struct list_head rsrc_ref_list;
455 spinlock_t rsrc_ref_lock;
457 struct list_head io_buffers_pages;
460 /* Keep this last, we don't need it for the fast path */
462 #if defined(CONFIG_UNIX)
463 struct socket *ring_sock;
465 /* hashed buffered write serialization */
466 struct io_wq_hash *hash_map;
468 /* Only used for accounting purposes */
469 struct user_struct *user;
470 struct mm_struct *mm_account;
472 /* ctx exit and cancelation */
473 struct llist_head fallback_llist;
474 struct delayed_work fallback_work;
475 struct work_struct exit_work;
476 struct list_head tctx_list;
477 struct completion ref_comp;
479 bool iowq_limits_set;
484 * Arbitrary limit, can be raised if need be
486 #define IO_RINGFD_REG_MAX 16
488 struct io_uring_task {
489 /* submission side */
492 struct wait_queue_head wait;
493 const struct io_ring_ctx *last;
495 struct percpu_counter inflight;
498 spinlock_t task_lock;
499 struct io_wq_work_list task_list;
500 struct io_wq_work_list prior_task_list;
501 struct callback_head task_work;
502 struct file **registered_rings;
507 * First field must be the file pointer in all the
508 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
510 struct io_poll_iocb {
512 struct wait_queue_head *head;
514 struct wait_queue_entry wait;
517 struct io_poll_update {
523 bool update_user_data;
532 struct io_timeout_data {
533 struct io_kiocb *req;
534 struct hrtimer timer;
535 struct timespec64 ts;
536 enum hrtimer_mode mode;
542 struct sockaddr __user *addr;
543 int __user *addr_len;
546 unsigned long nofile;
566 struct list_head list;
567 /* head of the link, used by linked timeouts only */
568 struct io_kiocb *head;
569 /* for linked completions */
570 struct io_kiocb *prev;
573 struct io_timeout_rem {
578 struct timespec64 ts;
584 /* NOTE: kiocb has the file as the first member, so don't do it here */
593 struct sockaddr __user *addr;
600 struct compat_msghdr __user *umsg_compat;
601 struct user_msghdr __user *umsg;
614 struct filename *filename;
616 unsigned long nofile;
619 struct io_rsrc_update {
645 struct epoll_event event;
649 struct file *file_out;
657 struct io_provide_buf {
671 struct filename *filename;
672 struct statx __user *buffer;
684 struct filename *oldpath;
685 struct filename *newpath;
693 struct filename *filename;
700 struct filename *filename;
706 struct filename *oldpath;
707 struct filename *newpath;
714 struct filename *oldpath;
715 struct filename *newpath;
725 struct io_async_connect {
726 struct sockaddr_storage address;
729 struct io_async_msghdr {
730 struct iovec fast_iov[UIO_FASTIOV];
731 /* points to an allocated iov, if NULL we use fast_iov instead */
732 struct iovec *free_iov;
733 struct sockaddr __user *uaddr;
735 struct sockaddr_storage addr;
739 struct iov_iter iter;
740 struct iov_iter_state iter_state;
741 struct iovec fast_iov[UIO_FASTIOV];
745 struct io_rw_state s;
746 const struct iovec *free_iovec;
748 struct wait_page_queue wpq;
752 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
753 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
754 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
755 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
756 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
757 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
758 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
760 /* first byte is taken by user flags, shift it to not overlap */
765 REQ_F_LINK_TIMEOUT_BIT,
766 REQ_F_NEED_CLEANUP_BIT,
768 REQ_F_BUFFER_SELECTED_BIT,
769 REQ_F_COMPLETE_INLINE_BIT,
773 REQ_F_ARM_LTIMEOUT_BIT,
774 REQ_F_ASYNC_DATA_BIT,
775 REQ_F_SKIP_LINK_CQES_BIT,
776 REQ_F_SINGLE_POLL_BIT,
777 REQ_F_DOUBLE_POLL_BIT,
778 REQ_F_PARTIAL_IO_BIT,
779 /* keep async read/write and isreg together and in order */
780 REQ_F_SUPPORT_NOWAIT_BIT,
783 /* not a real bit, just to check we're not overflowing the space */
789 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
790 /* drain existing IO first */
791 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
793 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
794 /* doesn't sever on completion < 0 */
795 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
797 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
798 /* IOSQE_BUFFER_SELECT */
799 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
800 /* IOSQE_CQE_SKIP_SUCCESS */
801 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
803 /* fail rest of links */
804 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
805 /* on inflight list, should be cancelled and waited on exit reliably */
806 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
807 /* read/write uses file position */
808 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
809 /* must not punt to workers */
810 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
811 /* has or had linked timeout */
812 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
814 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
815 /* already went through poll handler */
816 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
817 /* buffer already selected */
818 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
819 /* completion is deferred through io_comp_state */
820 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
821 /* caller should reissue async */
822 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
823 /* supports async reads/writes */
824 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
826 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
827 /* has creds assigned */
828 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
829 /* skip refcounting if not set */
830 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
831 /* there is a linked timeout that has to be armed */
832 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
833 /* ->async_data allocated */
834 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
835 /* don't post CQEs while failing linked requests */
836 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
837 /* single poll may be active */
838 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
839 /* double poll may active */
840 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
841 /* request has already done partial IO */
842 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
846 struct io_poll_iocb poll;
847 struct io_poll_iocb *double_poll;
850 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
852 struct io_task_work {
854 struct io_wq_work_node node;
855 struct llist_node fallback_node;
857 io_req_tw_func_t func;
861 IORING_RSRC_FILE = 0,
862 IORING_RSRC_BUFFER = 1,
866 * NOTE! Each of the iocb union members has the file pointer
867 * as the first entry in their struct definition. So you can
868 * access the file pointer through any of the sub-structs,
869 * or directly as just 'file' in this struct.
875 struct io_poll_iocb poll;
876 struct io_poll_update poll_update;
877 struct io_accept accept;
879 struct io_cancel cancel;
880 struct io_timeout timeout;
881 struct io_timeout_rem timeout_rem;
882 struct io_connect connect;
883 struct io_sr_msg sr_msg;
885 struct io_close close;
886 struct io_rsrc_update rsrc_update;
887 struct io_fadvise fadvise;
888 struct io_madvise madvise;
889 struct io_epoll epoll;
890 struct io_splice splice;
891 struct io_provide_buf pbuf;
892 struct io_statx statx;
893 struct io_shutdown shutdown;
894 struct io_rename rename;
895 struct io_unlink unlink;
896 struct io_mkdir mkdir;
897 struct io_symlink symlink;
898 struct io_hardlink hardlink;
903 /* polled IO has completed */
912 struct io_ring_ctx *ctx;
913 struct task_struct *task;
915 struct percpu_ref *fixed_rsrc_refs;
916 /* store used ubuf, so we can prevent reloading */
917 struct io_mapped_ubuf *imu;
919 /* used by request caches, completion batching and iopoll */
920 struct io_wq_work_node comp_list;
923 struct io_task_work io_task_work;
924 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
925 struct hlist_node hash_node;
926 /* internal polling, see IORING_FEAT_FAST_POLL */
927 struct async_poll *apoll;
928 /* opcode allocated if it needs to store data for async defer */
930 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
931 struct io_buffer *kbuf;
932 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
933 struct io_kiocb *link;
934 /* custom credentials, valid IFF REQ_F_CREDS is set */
935 const struct cred *creds;
936 struct io_wq_work work;
939 struct io_tctx_node {
940 struct list_head ctx_node;
941 struct task_struct *task;
942 struct io_ring_ctx *ctx;
945 struct io_defer_entry {
946 struct list_head list;
947 struct io_kiocb *req;
952 /* needs req->file assigned */
953 unsigned needs_file : 1;
954 /* should block plug */
956 /* hash wq insertion if file is a regular file */
957 unsigned hash_reg_file : 1;
958 /* unbound wq insertion if file is a non-regular file */
959 unsigned unbound_nonreg_file : 1;
960 /* set if opcode supports polled "wait" */
962 unsigned pollout : 1;
963 unsigned poll_exclusive : 1;
964 /* op supports buffer selection */
965 unsigned buffer_select : 1;
966 /* do prep async if is going to be punted */
967 unsigned needs_async_setup : 1;
968 /* opcode is not supported by this kernel */
969 unsigned not_supported : 1;
971 unsigned audit_skip : 1;
972 /* size of async data needed, if any */
973 unsigned short async_size;
976 static const struct io_op_def io_op_defs[] = {
977 [IORING_OP_NOP] = {},
978 [IORING_OP_READV] = {
980 .unbound_nonreg_file = 1,
983 .needs_async_setup = 1,
986 .async_size = sizeof(struct io_async_rw),
988 [IORING_OP_WRITEV] = {
991 .unbound_nonreg_file = 1,
993 .needs_async_setup = 1,
996 .async_size = sizeof(struct io_async_rw),
998 [IORING_OP_FSYNC] = {
1002 [IORING_OP_READ_FIXED] = {
1004 .unbound_nonreg_file = 1,
1008 .async_size = sizeof(struct io_async_rw),
1010 [IORING_OP_WRITE_FIXED] = {
1013 .unbound_nonreg_file = 1,
1017 .async_size = sizeof(struct io_async_rw),
1019 [IORING_OP_POLL_ADD] = {
1021 .unbound_nonreg_file = 1,
1024 [IORING_OP_POLL_REMOVE] = {
1027 [IORING_OP_SYNC_FILE_RANGE] = {
1031 [IORING_OP_SENDMSG] = {
1033 .unbound_nonreg_file = 1,
1035 .needs_async_setup = 1,
1036 .async_size = sizeof(struct io_async_msghdr),
1038 [IORING_OP_RECVMSG] = {
1040 .unbound_nonreg_file = 1,
1043 .needs_async_setup = 1,
1044 .async_size = sizeof(struct io_async_msghdr),
1046 [IORING_OP_TIMEOUT] = {
1048 .async_size = sizeof(struct io_timeout_data),
1050 [IORING_OP_TIMEOUT_REMOVE] = {
1051 /* used by timeout updates' prep() */
1054 [IORING_OP_ACCEPT] = {
1056 .unbound_nonreg_file = 1,
1058 .poll_exclusive = 1,
1060 [IORING_OP_ASYNC_CANCEL] = {
1063 [IORING_OP_LINK_TIMEOUT] = {
1065 .async_size = sizeof(struct io_timeout_data),
1067 [IORING_OP_CONNECT] = {
1069 .unbound_nonreg_file = 1,
1071 .needs_async_setup = 1,
1072 .async_size = sizeof(struct io_async_connect),
1074 [IORING_OP_FALLOCATE] = {
1077 [IORING_OP_OPENAT] = {},
1078 [IORING_OP_CLOSE] = {},
1079 [IORING_OP_FILES_UPDATE] = {
1082 [IORING_OP_STATX] = {
1085 [IORING_OP_READ] = {
1087 .unbound_nonreg_file = 1,
1092 .async_size = sizeof(struct io_async_rw),
1094 [IORING_OP_WRITE] = {
1097 .unbound_nonreg_file = 1,
1101 .async_size = sizeof(struct io_async_rw),
1103 [IORING_OP_FADVISE] = {
1107 [IORING_OP_MADVISE] = {},
1108 [IORING_OP_SEND] = {
1110 .unbound_nonreg_file = 1,
1114 [IORING_OP_RECV] = {
1116 .unbound_nonreg_file = 1,
1121 [IORING_OP_OPENAT2] = {
1123 [IORING_OP_EPOLL_CTL] = {
1124 .unbound_nonreg_file = 1,
1127 [IORING_OP_SPLICE] = {
1130 .unbound_nonreg_file = 1,
1133 [IORING_OP_PROVIDE_BUFFERS] = {
1136 [IORING_OP_REMOVE_BUFFERS] = {
1142 .unbound_nonreg_file = 1,
1145 [IORING_OP_SHUTDOWN] = {
1148 [IORING_OP_RENAMEAT] = {},
1149 [IORING_OP_UNLINKAT] = {},
1150 [IORING_OP_MKDIRAT] = {},
1151 [IORING_OP_SYMLINKAT] = {},
1152 [IORING_OP_LINKAT] = {},
1153 [IORING_OP_MSG_RING] = {
1158 /* requests with any of those set should undergo io_disarm_next() */
1159 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1161 static bool io_disarm_next(struct io_kiocb *req);
1162 static void io_uring_del_tctx_node(unsigned long index);
1163 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1164 struct task_struct *task,
1166 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1168 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1170 static void io_put_req(struct io_kiocb *req);
1171 static void io_put_req_deferred(struct io_kiocb *req);
1172 static void io_dismantle_req(struct io_kiocb *req);
1173 static void io_queue_linked_timeout(struct io_kiocb *req);
1174 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1175 struct io_uring_rsrc_update2 *up,
1177 static void io_clean_op(struct io_kiocb *req);
1178 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1179 unsigned issue_flags);
1180 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1181 static void io_drop_inflight_file(struct io_kiocb *req);
1182 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1183 static void __io_queue_sqe(struct io_kiocb *req);
1184 static void io_rsrc_put_work(struct work_struct *work);
1186 static void io_req_task_queue(struct io_kiocb *req);
1187 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1188 static int io_req_prep_async(struct io_kiocb *req);
1190 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1191 unsigned int issue_flags, u32 slot_index);
1192 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1194 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1195 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1197 static struct kmem_cache *req_cachep;
1199 static const struct file_operations io_uring_fops;
1201 struct sock *io_uring_get_socket(struct file *file)
1203 #if defined(CONFIG_UNIX)
1204 if (file->f_op == &io_uring_fops) {
1205 struct io_ring_ctx *ctx = file->private_data;
1207 return ctx->ring_sock->sk;
1212 EXPORT_SYMBOL(io_uring_get_socket);
1214 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1217 mutex_lock(&ctx->uring_lock);
1222 #define io_for_each_link(pos, head) \
1223 for (pos = (head); pos; pos = pos->link)
1226 * Shamelessly stolen from the mm implementation of page reference checking,
1227 * see commit f958d7b528b1 for details.
1229 #define req_ref_zero_or_close_to_overflow(req) \
1230 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1232 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1234 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1235 return atomic_inc_not_zero(&req->refs);
1238 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1240 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1243 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1244 return atomic_dec_and_test(&req->refs);
1247 static inline void req_ref_get(struct io_kiocb *req)
1249 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1250 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1251 atomic_inc(&req->refs);
1254 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1256 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1257 __io_submit_flush_completions(ctx);
1260 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1262 if (!(req->flags & REQ_F_REFCOUNT)) {
1263 req->flags |= REQ_F_REFCOUNT;
1264 atomic_set(&req->refs, nr);
1268 static inline void io_req_set_refcount(struct io_kiocb *req)
1270 __io_req_set_refcount(req, 1);
1273 #define IO_RSRC_REF_BATCH 100
1275 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1276 struct io_ring_ctx *ctx)
1277 __must_hold(&ctx->uring_lock)
1279 struct percpu_ref *ref = req->fixed_rsrc_refs;
1282 if (ref == &ctx->rsrc_node->refs)
1283 ctx->rsrc_cached_refs++;
1285 percpu_ref_put(ref);
1289 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1291 if (req->fixed_rsrc_refs)
1292 percpu_ref_put(req->fixed_rsrc_refs);
1295 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1296 __must_hold(&ctx->uring_lock)
1298 if (ctx->rsrc_cached_refs) {
1299 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1300 ctx->rsrc_cached_refs = 0;
1304 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1305 __must_hold(&ctx->uring_lock)
1307 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1308 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1311 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1312 struct io_ring_ctx *ctx,
1313 unsigned int issue_flags)
1315 if (!req->fixed_rsrc_refs) {
1316 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1318 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1319 lockdep_assert_held(&ctx->uring_lock);
1320 ctx->rsrc_cached_refs--;
1321 if (unlikely(ctx->rsrc_cached_refs < 0))
1322 io_rsrc_refs_refill(ctx);
1324 percpu_ref_get(req->fixed_rsrc_refs);
1329 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1331 struct io_buffer *kbuf = req->kbuf;
1332 unsigned int cflags;
1334 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1335 req->flags &= ~REQ_F_BUFFER_SELECTED;
1336 list_add(&kbuf->list, list);
1341 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1343 lockdep_assert_held(&req->ctx->completion_lock);
1345 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1347 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1350 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1351 unsigned issue_flags)
1353 unsigned int cflags;
1355 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1359 * We can add this buffer back to two lists:
1361 * 1) The io_buffers_cache list. This one is protected by the
1362 * ctx->uring_lock. If we already hold this lock, add back to this
1363 * list as we can grab it from issue as well.
1364 * 2) The io_buffers_comp list. This one is protected by the
1365 * ctx->completion_lock.
1367 * We migrate buffers from the comp_list to the issue cache list
1370 if (issue_flags & IO_URING_F_UNLOCKED) {
1371 struct io_ring_ctx *ctx = req->ctx;
1373 spin_lock(&ctx->completion_lock);
1374 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1375 spin_unlock(&ctx->completion_lock);
1377 lockdep_assert_held(&req->ctx->uring_lock);
1379 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1385 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1388 struct list_head *hash_list;
1389 struct io_buffer_list *bl;
1391 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1392 list_for_each_entry(bl, hash_list, list)
1393 if (bl->bgid == bgid || bgid == -1U)
1399 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1401 struct io_ring_ctx *ctx = req->ctx;
1402 struct io_buffer_list *bl;
1403 struct io_buffer *buf;
1405 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1407 /* don't recycle if we already did IO to this buffer */
1408 if (req->flags & REQ_F_PARTIAL_IO)
1411 if (issue_flags & IO_URING_F_UNLOCKED)
1412 mutex_lock(&ctx->uring_lock);
1414 lockdep_assert_held(&ctx->uring_lock);
1417 bl = io_buffer_get_list(ctx, buf->bgid);
1418 list_add(&buf->list, &bl->buf_list);
1419 req->flags &= ~REQ_F_BUFFER_SELECTED;
1422 if (issue_flags & IO_URING_F_UNLOCKED)
1423 mutex_unlock(&ctx->uring_lock);
1426 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1428 __must_hold(&req->ctx->timeout_lock)
1430 if (task && head->task != task)
1436 * As io_match_task() but protected against racing with linked timeouts.
1437 * User must not hold timeout_lock.
1439 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1442 if (task && head->task != task)
1447 static inline bool req_has_async_data(struct io_kiocb *req)
1449 return req->flags & REQ_F_ASYNC_DATA;
1452 static inline void req_set_fail(struct io_kiocb *req)
1454 req->flags |= REQ_F_FAIL;
1455 if (req->flags & REQ_F_CQE_SKIP) {
1456 req->flags &= ~REQ_F_CQE_SKIP;
1457 req->flags |= REQ_F_SKIP_LINK_CQES;
1461 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1467 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1469 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1471 complete(&ctx->ref_comp);
1474 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1476 return !req->timeout.off;
1479 static __cold void io_fallback_req_func(struct work_struct *work)
1481 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1482 fallback_work.work);
1483 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1484 struct io_kiocb *req, *tmp;
1485 bool locked = false;
1487 percpu_ref_get(&ctx->refs);
1488 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1489 req->io_task_work.func(req, &locked);
1492 io_submit_flush_completions(ctx);
1493 mutex_unlock(&ctx->uring_lock);
1495 percpu_ref_put(&ctx->refs);
1498 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1500 struct io_ring_ctx *ctx;
1503 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1508 * Use 5 bits less than the max cq entries, that should give us around
1509 * 32 entries per hash list if totally full and uniformly spread.
1511 hash_bits = ilog2(p->cq_entries);
1515 ctx->cancel_hash_bits = hash_bits;
1516 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1518 if (!ctx->cancel_hash)
1520 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1522 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1523 if (!ctx->dummy_ubuf)
1525 /* set invalid range, so io_import_fixed() fails meeting it */
1526 ctx->dummy_ubuf->ubuf = -1UL;
1528 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1529 sizeof(struct list_head), GFP_KERNEL);
1530 if (!ctx->io_buffers)
1532 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1533 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1535 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1536 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1539 ctx->flags = p->flags;
1540 init_waitqueue_head(&ctx->sqo_sq_wait);
1541 INIT_LIST_HEAD(&ctx->sqd_list);
1542 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1543 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1544 INIT_LIST_HEAD(&ctx->apoll_cache);
1545 init_completion(&ctx->ref_comp);
1546 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1547 mutex_init(&ctx->uring_lock);
1548 init_waitqueue_head(&ctx->cq_wait);
1549 spin_lock_init(&ctx->completion_lock);
1550 spin_lock_init(&ctx->timeout_lock);
1551 INIT_WQ_LIST(&ctx->iopoll_list);
1552 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1553 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1554 INIT_LIST_HEAD(&ctx->defer_list);
1555 INIT_LIST_HEAD(&ctx->timeout_list);
1556 INIT_LIST_HEAD(&ctx->ltimeout_list);
1557 spin_lock_init(&ctx->rsrc_ref_lock);
1558 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1559 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1560 init_llist_head(&ctx->rsrc_put_llist);
1561 INIT_LIST_HEAD(&ctx->tctx_list);
1562 ctx->submit_state.free_list.next = NULL;
1563 INIT_WQ_LIST(&ctx->locked_free_list);
1564 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1565 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1568 kfree(ctx->dummy_ubuf);
1569 kfree(ctx->cancel_hash);
1570 kfree(ctx->io_buffers);
1575 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1577 struct io_rings *r = ctx->rings;
1579 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1583 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1585 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1586 struct io_ring_ctx *ctx = req->ctx;
1588 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1594 #define FFS_NOWAIT 0x1UL
1595 #define FFS_ISREG 0x2UL
1596 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1598 static inline bool io_req_ffs_set(struct io_kiocb *req)
1600 return req->flags & REQ_F_FIXED_FILE;
1603 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1605 if (WARN_ON_ONCE(!req->link))
1608 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1609 req->flags |= REQ_F_LINK_TIMEOUT;
1611 /* linked timeouts should have two refs once prep'ed */
1612 io_req_set_refcount(req);
1613 __io_req_set_refcount(req->link, 2);
1617 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1619 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1621 return __io_prep_linked_timeout(req);
1624 static void io_prep_async_work(struct io_kiocb *req)
1626 const struct io_op_def *def = &io_op_defs[req->opcode];
1627 struct io_ring_ctx *ctx = req->ctx;
1629 if (!(req->flags & REQ_F_CREDS)) {
1630 req->flags |= REQ_F_CREDS;
1631 req->creds = get_current_cred();
1634 req->work.list.next = NULL;
1635 req->work.flags = 0;
1636 if (req->flags & REQ_F_FORCE_ASYNC)
1637 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1639 if (req->flags & REQ_F_ISREG) {
1640 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1641 io_wq_hash_work(&req->work, file_inode(req->file));
1642 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1643 if (def->unbound_nonreg_file)
1644 req->work.flags |= IO_WQ_WORK_UNBOUND;
1648 static void io_prep_async_link(struct io_kiocb *req)
1650 struct io_kiocb *cur;
1652 if (req->flags & REQ_F_LINK_TIMEOUT) {
1653 struct io_ring_ctx *ctx = req->ctx;
1655 spin_lock_irq(&ctx->timeout_lock);
1656 io_for_each_link(cur, req)
1657 io_prep_async_work(cur);
1658 spin_unlock_irq(&ctx->timeout_lock);
1660 io_for_each_link(cur, req)
1661 io_prep_async_work(cur);
1665 static inline void io_req_add_compl_list(struct io_kiocb *req)
1667 struct io_ring_ctx *ctx = req->ctx;
1668 struct io_submit_state *state = &ctx->submit_state;
1670 if (!(req->flags & REQ_F_CQE_SKIP))
1671 ctx->submit_state.flush_cqes = true;
1672 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1675 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1677 struct io_ring_ctx *ctx = req->ctx;
1678 struct io_kiocb *link = io_prep_linked_timeout(req);
1679 struct io_uring_task *tctx = req->task->io_uring;
1682 BUG_ON(!tctx->io_wq);
1684 /* init ->work of the whole link before punting */
1685 io_prep_async_link(req);
1688 * Not expected to happen, but if we do have a bug where this _can_
1689 * happen, catch it here and ensure the request is marked as
1690 * canceled. That will make io-wq go through the usual work cancel
1691 * procedure rather than attempt to run this request (or create a new
1694 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1695 req->work.flags |= IO_WQ_WORK_CANCEL;
1697 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1698 &req->work, io_wq_is_hashed(&req->work));
1699 io_wq_enqueue(tctx->io_wq, &req->work);
1701 io_queue_linked_timeout(link);
1704 static void io_kill_timeout(struct io_kiocb *req, int status)
1705 __must_hold(&req->ctx->completion_lock)
1706 __must_hold(&req->ctx->timeout_lock)
1708 struct io_timeout_data *io = req->async_data;
1710 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1713 atomic_set(&req->ctx->cq_timeouts,
1714 atomic_read(&req->ctx->cq_timeouts) + 1);
1715 list_del_init(&req->timeout.list);
1716 io_fill_cqe_req(req, status, 0);
1717 io_put_req_deferred(req);
1721 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1723 while (!list_empty(&ctx->defer_list)) {
1724 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1725 struct io_defer_entry, list);
1727 if (req_need_defer(de->req, de->seq))
1729 list_del_init(&de->list);
1730 io_req_task_queue(de->req);
1735 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1736 __must_hold(&ctx->completion_lock)
1738 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1739 struct io_kiocb *req, *tmp;
1741 spin_lock_irq(&ctx->timeout_lock);
1742 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1743 u32 events_needed, events_got;
1745 if (io_is_timeout_noseq(req))
1749 * Since seq can easily wrap around over time, subtract
1750 * the last seq at which timeouts were flushed before comparing.
1751 * Assuming not more than 2^31-1 events have happened since,
1752 * these subtractions won't have wrapped, so we can check if
1753 * target is in [last_seq, current_seq] by comparing the two.
1755 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1756 events_got = seq - ctx->cq_last_tm_flush;
1757 if (events_got < events_needed)
1760 io_kill_timeout(req, 0);
1762 ctx->cq_last_tm_flush = seq;
1763 spin_unlock_irq(&ctx->timeout_lock);
1766 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1768 /* order cqe stores with ring update */
1769 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1772 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1774 if (ctx->off_timeout_used || ctx->drain_active) {
1775 spin_lock(&ctx->completion_lock);
1776 if (ctx->off_timeout_used)
1777 io_flush_timeouts(ctx);
1778 if (ctx->drain_active)
1779 io_queue_deferred(ctx);
1780 io_commit_cqring(ctx);
1781 spin_unlock(&ctx->completion_lock);
1784 io_eventfd_signal(ctx);
1787 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1789 struct io_rings *r = ctx->rings;
1791 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1794 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1796 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1799 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1801 struct io_rings *rings = ctx->rings;
1802 unsigned tail, mask = ctx->cq_entries - 1;
1805 * writes to the cq entry need to come after reading head; the
1806 * control dependency is enough as we're using WRITE_ONCE to
1809 if (__io_cqring_events(ctx) == ctx->cq_entries)
1812 tail = ctx->cached_cq_tail++;
1813 return &rings->cqes[tail & mask];
1816 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1818 struct io_ev_fd *ev_fd;
1822 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1823 * and eventfd_signal
1825 ev_fd = rcu_dereference(ctx->io_ev_fd);
1828 * Check again if ev_fd exists incase an io_eventfd_unregister call
1829 * completed between the NULL check of ctx->io_ev_fd at the start of
1830 * the function and rcu_read_lock.
1832 if (unlikely(!ev_fd))
1834 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1837 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1838 eventfd_signal(ev_fd->cq_ev_fd, 1);
1843 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1846 * wake_up_all() may seem excessive, but io_wake_function() and
1847 * io_should_wake() handle the termination of the loop and only
1848 * wake as many waiters as we need to.
1850 if (wq_has_sleeper(&ctx->cq_wait))
1851 wake_up_all(&ctx->cq_wait);
1855 * This should only get called when at least one event has been posted.
1856 * Some applications rely on the eventfd notification count only changing
1857 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1858 * 1:1 relationship between how many times this function is called (and
1859 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1861 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1863 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1865 __io_commit_cqring_flush(ctx);
1867 io_cqring_wake(ctx);
1870 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1872 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1874 __io_commit_cqring_flush(ctx);
1876 if (ctx->flags & IORING_SETUP_SQPOLL)
1877 io_cqring_wake(ctx);
1880 /* Returns true if there are no backlogged entries after the flush */
1881 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1883 bool all_flushed, posted;
1885 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1889 spin_lock(&ctx->completion_lock);
1890 while (!list_empty(&ctx->cq_overflow_list)) {
1891 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1892 struct io_overflow_cqe *ocqe;
1896 ocqe = list_first_entry(&ctx->cq_overflow_list,
1897 struct io_overflow_cqe, list);
1899 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1901 io_account_cq_overflow(ctx);
1904 list_del(&ocqe->list);
1908 all_flushed = list_empty(&ctx->cq_overflow_list);
1910 clear_bit(0, &ctx->check_cq_overflow);
1911 WRITE_ONCE(ctx->rings->sq_flags,
1912 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1916 io_commit_cqring(ctx);
1917 spin_unlock(&ctx->completion_lock);
1919 io_cqring_ev_posted(ctx);
1923 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1927 if (test_bit(0, &ctx->check_cq_overflow)) {
1928 /* iopoll syncs against uring_lock, not completion_lock */
1929 if (ctx->flags & IORING_SETUP_IOPOLL)
1930 mutex_lock(&ctx->uring_lock);
1931 ret = __io_cqring_overflow_flush(ctx, false);
1932 if (ctx->flags & IORING_SETUP_IOPOLL)
1933 mutex_unlock(&ctx->uring_lock);
1939 /* must to be called somewhat shortly after putting a request */
1940 static inline void io_put_task(struct task_struct *task, int nr)
1942 struct io_uring_task *tctx = task->io_uring;
1944 if (likely(task == current)) {
1945 tctx->cached_refs += nr;
1947 percpu_counter_sub(&tctx->inflight, nr);
1948 if (unlikely(atomic_read(&tctx->in_idle)))
1949 wake_up(&tctx->wait);
1950 put_task_struct_many(task, nr);
1954 static void io_task_refs_refill(struct io_uring_task *tctx)
1956 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1958 percpu_counter_add(&tctx->inflight, refill);
1959 refcount_add(refill, ¤t->usage);
1960 tctx->cached_refs += refill;
1963 static inline void io_get_task_refs(int nr)
1965 struct io_uring_task *tctx = current->io_uring;
1967 tctx->cached_refs -= nr;
1968 if (unlikely(tctx->cached_refs < 0))
1969 io_task_refs_refill(tctx);
1972 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1974 struct io_uring_task *tctx = task->io_uring;
1975 unsigned int refs = tctx->cached_refs;
1978 tctx->cached_refs = 0;
1979 percpu_counter_sub(&tctx->inflight, refs);
1980 put_task_struct_many(task, refs);
1984 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1985 s32 res, u32 cflags)
1987 struct io_overflow_cqe *ocqe;
1989 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1992 * If we're in ring overflow flush mode, or in task cancel mode,
1993 * or cannot allocate an overflow entry, then we need to drop it
1996 io_account_cq_overflow(ctx);
1999 if (list_empty(&ctx->cq_overflow_list)) {
2000 set_bit(0, &ctx->check_cq_overflow);
2001 WRITE_ONCE(ctx->rings->sq_flags,
2002 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2005 ocqe->cqe.user_data = user_data;
2006 ocqe->cqe.res = res;
2007 ocqe->cqe.flags = cflags;
2008 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2012 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2013 s32 res, u32 cflags)
2015 struct io_uring_cqe *cqe;
2018 * If we can't get a cq entry, userspace overflowed the
2019 * submission (by quite a lot). Increment the overflow count in
2022 cqe = io_get_cqe(ctx);
2024 WRITE_ONCE(cqe->user_data, user_data);
2025 WRITE_ONCE(cqe->res, res);
2026 WRITE_ONCE(cqe->flags, cflags);
2029 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2032 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2034 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2035 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
2038 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2040 if (!(req->flags & REQ_F_CQE_SKIP))
2041 __io_fill_cqe_req(req, res, cflags);
2044 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2045 s32 res, u32 cflags)
2048 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2049 return __io_fill_cqe(ctx, user_data, res, cflags);
2052 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2055 struct io_ring_ctx *ctx = req->ctx;
2057 if (!(req->flags & REQ_F_CQE_SKIP))
2058 __io_fill_cqe_req(req, res, cflags);
2060 * If we're the last reference to this request, add to our locked
2063 if (req_ref_put_and_test(req)) {
2064 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2065 if (req->flags & IO_DISARM_MASK)
2066 io_disarm_next(req);
2068 io_req_task_queue(req->link);
2072 io_req_put_rsrc(req, ctx);
2074 * Selected buffer deallocation in io_clean_op() assumes that
2075 * we don't hold ->completion_lock. Clean them here to avoid
2078 io_put_kbuf_comp(req);
2079 io_dismantle_req(req);
2080 io_put_task(req->task, 1);
2081 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2082 ctx->locked_free_nr++;
2086 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2089 struct io_ring_ctx *ctx = req->ctx;
2091 spin_lock(&ctx->completion_lock);
2092 __io_req_complete_post(req, res, cflags);
2093 io_commit_cqring(ctx);
2094 spin_unlock(&ctx->completion_lock);
2095 io_cqring_ev_posted(ctx);
2098 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2102 req->cflags = cflags;
2103 req->flags |= REQ_F_COMPLETE_INLINE;
2106 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2107 s32 res, u32 cflags)
2109 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2110 io_req_complete_state(req, res, cflags);
2112 io_req_complete_post(req, res, cflags);
2115 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2117 __io_req_complete(req, 0, res, 0);
2120 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2123 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2126 static void io_req_complete_fail_submit(struct io_kiocb *req)
2129 * We don't submit, fail them all, for that replace hardlinks with
2130 * normal links. Extra REQ_F_LINK is tolerated.
2132 req->flags &= ~REQ_F_HARDLINK;
2133 req->flags |= REQ_F_LINK;
2134 io_req_complete_failed(req, req->result);
2138 * Don't initialise the fields below on every allocation, but do that in
2139 * advance and keep them valid across allocations.
2141 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2145 req->async_data = NULL;
2146 /* not necessary, but safer to zero */
2150 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2151 struct io_submit_state *state)
2153 spin_lock(&ctx->completion_lock);
2154 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2155 ctx->locked_free_nr = 0;
2156 spin_unlock(&ctx->completion_lock);
2159 /* Returns true IFF there are requests in the cache */
2160 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2162 struct io_submit_state *state = &ctx->submit_state;
2165 * If we have more than a batch's worth of requests in our IRQ side
2166 * locked cache, grab the lock and move them over to our submission
2169 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2170 io_flush_cached_locked_reqs(ctx, state);
2171 return !!state->free_list.next;
2175 * A request might get retired back into the request caches even before opcode
2176 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2177 * Because of that, io_alloc_req() should be called only under ->uring_lock
2178 * and with extra caution to not get a request that is still worked on.
2180 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2181 __must_hold(&ctx->uring_lock)
2183 struct io_submit_state *state = &ctx->submit_state;
2184 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2185 void *reqs[IO_REQ_ALLOC_BATCH];
2186 struct io_kiocb *req;
2189 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2192 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2195 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2196 * retry single alloc to be on the safe side.
2198 if (unlikely(ret <= 0)) {
2199 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2205 percpu_ref_get_many(&ctx->refs, ret);
2206 for (i = 0; i < ret; i++) {
2209 io_preinit_req(req, ctx);
2210 wq_stack_add_head(&req->comp_list, &state->free_list);
2215 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2217 if (unlikely(!ctx->submit_state.free_list.next))
2218 return __io_alloc_req_refill(ctx);
2222 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2224 struct io_wq_work_node *node;
2226 node = wq_stack_extract(&ctx->submit_state.free_list);
2227 return container_of(node, struct io_kiocb, comp_list);
2230 static inline void io_put_file(struct file *file)
2236 static inline void io_dismantle_req(struct io_kiocb *req)
2238 unsigned int flags = req->flags;
2240 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2242 if (!(flags & REQ_F_FIXED_FILE))
2243 io_put_file(req->file);
2246 static __cold void __io_free_req(struct io_kiocb *req)
2248 struct io_ring_ctx *ctx = req->ctx;
2250 io_req_put_rsrc(req, ctx);
2251 io_dismantle_req(req);
2252 io_put_task(req->task, 1);
2254 spin_lock(&ctx->completion_lock);
2255 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2256 ctx->locked_free_nr++;
2257 spin_unlock(&ctx->completion_lock);
2260 static inline void io_remove_next_linked(struct io_kiocb *req)
2262 struct io_kiocb *nxt = req->link;
2264 req->link = nxt->link;
2268 static bool io_kill_linked_timeout(struct io_kiocb *req)
2269 __must_hold(&req->ctx->completion_lock)
2270 __must_hold(&req->ctx->timeout_lock)
2272 struct io_kiocb *link = req->link;
2274 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2275 struct io_timeout_data *io = link->async_data;
2277 io_remove_next_linked(req);
2278 link->timeout.head = NULL;
2279 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2280 list_del(&link->timeout.list);
2281 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2282 io_fill_cqe_req(link, -ECANCELED, 0);
2283 io_put_req_deferred(link);
2290 static void io_fail_links(struct io_kiocb *req)
2291 __must_hold(&req->ctx->completion_lock)
2293 struct io_kiocb *nxt, *link = req->link;
2294 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2298 long res = -ECANCELED;
2300 if (link->flags & REQ_F_FAIL)
2306 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2310 link->flags &= ~REQ_F_CQE_SKIP;
2311 io_fill_cqe_req(link, res, 0);
2313 io_put_req_deferred(link);
2318 static bool io_disarm_next(struct io_kiocb *req)
2319 __must_hold(&req->ctx->completion_lock)
2321 bool posted = false;
2323 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2324 struct io_kiocb *link = req->link;
2326 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2327 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2328 io_remove_next_linked(req);
2329 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2330 io_fill_cqe_req(link, -ECANCELED, 0);
2331 io_put_req_deferred(link);
2334 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2335 struct io_ring_ctx *ctx = req->ctx;
2337 spin_lock_irq(&ctx->timeout_lock);
2338 posted = io_kill_linked_timeout(req);
2339 spin_unlock_irq(&ctx->timeout_lock);
2341 if (unlikely((req->flags & REQ_F_FAIL) &&
2342 !(req->flags & REQ_F_HARDLINK))) {
2343 posted |= (req->link != NULL);
2349 static void __io_req_find_next_prep(struct io_kiocb *req)
2351 struct io_ring_ctx *ctx = req->ctx;
2354 spin_lock(&ctx->completion_lock);
2355 posted = io_disarm_next(req);
2357 io_commit_cqring(ctx);
2358 spin_unlock(&ctx->completion_lock);
2360 io_cqring_ev_posted(ctx);
2363 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2365 struct io_kiocb *nxt;
2367 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2370 * If LINK is set, we have dependent requests in this chain. If we
2371 * didn't fail this request, queue the first one up, moving any other
2372 * dependencies to the next request. In case of failure, fail the rest
2375 if (unlikely(req->flags & IO_DISARM_MASK))
2376 __io_req_find_next_prep(req);
2382 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2387 io_submit_flush_completions(ctx);
2388 mutex_unlock(&ctx->uring_lock);
2391 percpu_ref_put(&ctx->refs);
2394 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2396 io_commit_cqring(ctx);
2397 spin_unlock(&ctx->completion_lock);
2398 io_cqring_ev_posted(ctx);
2401 static void handle_prev_tw_list(struct io_wq_work_node *node,
2402 struct io_ring_ctx **ctx, bool *uring_locked)
2404 if (*ctx && !*uring_locked)
2405 spin_lock(&(*ctx)->completion_lock);
2408 struct io_wq_work_node *next = node->next;
2409 struct io_kiocb *req = container_of(node, struct io_kiocb,
2412 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2414 if (req->ctx != *ctx) {
2415 if (unlikely(!*uring_locked && *ctx))
2416 ctx_commit_and_unlock(*ctx);
2418 ctx_flush_and_put(*ctx, uring_locked);
2420 /* if not contended, grab and improve batching */
2421 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2422 percpu_ref_get(&(*ctx)->refs);
2423 if (unlikely(!*uring_locked))
2424 spin_lock(&(*ctx)->completion_lock);
2426 if (likely(*uring_locked))
2427 req->io_task_work.func(req, uring_locked);
2429 __io_req_complete_post(req, req->result,
2430 io_put_kbuf_comp(req));
2434 if (unlikely(!*uring_locked))
2435 ctx_commit_and_unlock(*ctx);
2438 static void handle_tw_list(struct io_wq_work_node *node,
2439 struct io_ring_ctx **ctx, bool *locked)
2442 struct io_wq_work_node *next = node->next;
2443 struct io_kiocb *req = container_of(node, struct io_kiocb,
2446 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2448 if (req->ctx != *ctx) {
2449 ctx_flush_and_put(*ctx, locked);
2451 /* if not contended, grab and improve batching */
2452 *locked = mutex_trylock(&(*ctx)->uring_lock);
2453 percpu_ref_get(&(*ctx)->refs);
2455 req->io_task_work.func(req, locked);
2460 static void tctx_task_work(struct callback_head *cb)
2462 bool uring_locked = false;
2463 struct io_ring_ctx *ctx = NULL;
2464 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2468 struct io_wq_work_node *node1, *node2;
2470 if (!tctx->task_list.first &&
2471 !tctx->prior_task_list.first && uring_locked)
2472 io_submit_flush_completions(ctx);
2474 spin_lock_irq(&tctx->task_lock);
2475 node1 = tctx->prior_task_list.first;
2476 node2 = tctx->task_list.first;
2477 INIT_WQ_LIST(&tctx->task_list);
2478 INIT_WQ_LIST(&tctx->prior_task_list);
2479 if (!node2 && !node1)
2480 tctx->task_running = false;
2481 spin_unlock_irq(&tctx->task_lock);
2482 if (!node2 && !node1)
2486 handle_prev_tw_list(node1, &ctx, &uring_locked);
2489 handle_tw_list(node2, &ctx, &uring_locked);
2493 ctx_flush_and_put(ctx, &uring_locked);
2495 /* relaxed read is enough as only the task itself sets ->in_idle */
2496 if (unlikely(atomic_read(&tctx->in_idle)))
2497 io_uring_drop_tctx_refs(current);
2500 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2502 struct task_struct *tsk = req->task;
2503 struct io_uring_task *tctx = tsk->io_uring;
2504 enum task_work_notify_mode notify;
2505 struct io_wq_work_node *node;
2506 unsigned long flags;
2509 WARN_ON_ONCE(!tctx);
2511 io_drop_inflight_file(req);
2513 spin_lock_irqsave(&tctx->task_lock, flags);
2515 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2517 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2518 running = tctx->task_running;
2520 tctx->task_running = true;
2521 spin_unlock_irqrestore(&tctx->task_lock, flags);
2523 /* task_work already pending, we're done */
2528 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2529 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2530 * processing task_work. There's no reliable way to tell if TWA_RESUME
2533 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2534 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2535 if (notify == TWA_NONE)
2536 wake_up_process(tsk);
2540 spin_lock_irqsave(&tctx->task_lock, flags);
2541 tctx->task_running = false;
2542 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2543 spin_unlock_irqrestore(&tctx->task_lock, flags);
2546 req = container_of(node, struct io_kiocb, io_task_work.node);
2548 if (llist_add(&req->io_task_work.fallback_node,
2549 &req->ctx->fallback_llist))
2550 schedule_delayed_work(&req->ctx->fallback_work, 1);
2554 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2556 struct io_ring_ctx *ctx = req->ctx;
2558 /* not needed for normal modes, but SQPOLL depends on it */
2559 io_tw_lock(ctx, locked);
2560 io_req_complete_failed(req, req->result);
2563 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2565 struct io_ring_ctx *ctx = req->ctx;
2567 io_tw_lock(ctx, locked);
2568 /* req->task == current here, checking PF_EXITING is safe */
2569 if (likely(!(req->task->flags & PF_EXITING)))
2570 __io_queue_sqe(req);
2572 io_req_complete_failed(req, -EFAULT);
2575 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2578 req->io_task_work.func = io_req_task_cancel;
2579 io_req_task_work_add(req, false);
2582 static void io_req_task_queue(struct io_kiocb *req)
2584 req->io_task_work.func = io_req_task_submit;
2585 io_req_task_work_add(req, false);
2588 static void io_req_task_queue_reissue(struct io_kiocb *req)
2590 req->io_task_work.func = io_queue_async_work;
2591 io_req_task_work_add(req, false);
2594 static inline void io_queue_next(struct io_kiocb *req)
2596 struct io_kiocb *nxt = io_req_find_next(req);
2599 io_req_task_queue(nxt);
2602 static void io_free_req(struct io_kiocb *req)
2608 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2613 static void io_free_batch_list(struct io_ring_ctx *ctx,
2614 struct io_wq_work_node *node)
2615 __must_hold(&ctx->uring_lock)
2617 struct task_struct *task = NULL;
2621 struct io_kiocb *req = container_of(node, struct io_kiocb,
2624 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2625 node = req->comp_list.next;
2626 if (!req_ref_put_and_test(req))
2630 io_req_put_rsrc_locked(req, ctx);
2632 io_dismantle_req(req);
2634 if (req->task != task) {
2636 io_put_task(task, task_refs);
2641 node = req->comp_list.next;
2642 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2646 io_put_task(task, task_refs);
2649 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2650 __must_hold(&ctx->uring_lock)
2652 struct io_wq_work_node *node, *prev;
2653 struct io_submit_state *state = &ctx->submit_state;
2655 if (state->flush_cqes) {
2656 spin_lock(&ctx->completion_lock);
2657 wq_list_for_each(node, prev, &state->compl_reqs) {
2658 struct io_kiocb *req = container_of(node, struct io_kiocb,
2661 if (!(req->flags & REQ_F_CQE_SKIP))
2662 __io_fill_cqe_req(req, req->result, req->cflags);
2663 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2664 struct async_poll *apoll = req->apoll;
2666 if (apoll->double_poll)
2667 kfree(apoll->double_poll);
2668 list_add(&apoll->poll.wait.entry,
2670 req->flags &= ~REQ_F_POLLED;
2674 io_commit_cqring(ctx);
2675 spin_unlock(&ctx->completion_lock);
2676 io_cqring_ev_posted(ctx);
2677 state->flush_cqes = false;
2680 io_free_batch_list(ctx, state->compl_reqs.first);
2681 INIT_WQ_LIST(&state->compl_reqs);
2685 * Drop reference to request, return next in chain (if there is one) if this
2686 * was the last reference to this request.
2688 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2690 struct io_kiocb *nxt = NULL;
2692 if (req_ref_put_and_test(req)) {
2693 nxt = io_req_find_next(req);
2699 static inline void io_put_req(struct io_kiocb *req)
2701 if (req_ref_put_and_test(req))
2705 static inline void io_put_req_deferred(struct io_kiocb *req)
2707 if (req_ref_put_and_test(req)) {
2708 req->io_task_work.func = io_free_req_work;
2709 io_req_task_work_add(req, false);
2713 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2715 /* See comment at the top of this file */
2717 return __io_cqring_events(ctx);
2720 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2722 struct io_rings *rings = ctx->rings;
2724 /* make sure SQ entry isn't read before tail */
2725 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2728 static inline bool io_run_task_work(void)
2730 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2731 __set_current_state(TASK_RUNNING);
2732 clear_notify_signal();
2733 if (task_work_pending(current))
2741 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2743 struct io_wq_work_node *pos, *start, *prev;
2744 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2745 DEFINE_IO_COMP_BATCH(iob);
2749 * Only spin for completions if we don't have multiple devices hanging
2750 * off our complete list.
2752 if (ctx->poll_multi_queue || force_nonspin)
2753 poll_flags |= BLK_POLL_ONESHOT;
2755 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2756 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2757 struct kiocb *kiocb = &req->rw.kiocb;
2761 * Move completed and retryable entries to our local lists.
2762 * If we find a request that requires polling, break out
2763 * and complete those lists first, if we have entries there.
2765 if (READ_ONCE(req->iopoll_completed))
2768 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2769 if (unlikely(ret < 0))
2772 poll_flags |= BLK_POLL_ONESHOT;
2774 /* iopoll may have completed current req */
2775 if (!rq_list_empty(iob.req_list) ||
2776 READ_ONCE(req->iopoll_completed))
2780 if (!rq_list_empty(iob.req_list))
2786 wq_list_for_each_resume(pos, prev) {
2787 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2789 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2790 if (!smp_load_acquire(&req->iopoll_completed))
2792 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2795 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
2799 if (unlikely(!nr_events))
2802 io_commit_cqring(ctx);
2803 io_cqring_ev_posted_iopoll(ctx);
2804 pos = start ? start->next : ctx->iopoll_list.first;
2805 wq_list_cut(&ctx->iopoll_list, prev, start);
2806 io_free_batch_list(ctx, pos);
2811 * We can't just wait for polled events to come to us, we have to actively
2812 * find and complete them.
2814 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2816 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2819 mutex_lock(&ctx->uring_lock);
2820 while (!wq_list_empty(&ctx->iopoll_list)) {
2821 /* let it sleep and repeat later if can't complete a request */
2822 if (io_do_iopoll(ctx, true) == 0)
2825 * Ensure we allow local-to-the-cpu processing to take place,
2826 * in this case we need to ensure that we reap all events.
2827 * Also let task_work, etc. to progress by releasing the mutex
2829 if (need_resched()) {
2830 mutex_unlock(&ctx->uring_lock);
2832 mutex_lock(&ctx->uring_lock);
2835 mutex_unlock(&ctx->uring_lock);
2838 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2840 unsigned int nr_events = 0;
2844 * We disallow the app entering submit/complete with polling, but we
2845 * still need to lock the ring to prevent racing with polled issue
2846 * that got punted to a workqueue.
2848 mutex_lock(&ctx->uring_lock);
2850 * Don't enter poll loop if we already have events pending.
2851 * If we do, we can potentially be spinning for commands that
2852 * already triggered a CQE (eg in error).
2854 if (test_bit(0, &ctx->check_cq_overflow))
2855 __io_cqring_overflow_flush(ctx, false);
2856 if (io_cqring_events(ctx))
2860 * If a submit got punted to a workqueue, we can have the
2861 * application entering polling for a command before it gets
2862 * issued. That app will hold the uring_lock for the duration
2863 * of the poll right here, so we need to take a breather every
2864 * now and then to ensure that the issue has a chance to add
2865 * the poll to the issued list. Otherwise we can spin here
2866 * forever, while the workqueue is stuck trying to acquire the
2869 if (wq_list_empty(&ctx->iopoll_list)) {
2870 u32 tail = ctx->cached_cq_tail;
2872 mutex_unlock(&ctx->uring_lock);
2874 mutex_lock(&ctx->uring_lock);
2876 /* some requests don't go through iopoll_list */
2877 if (tail != ctx->cached_cq_tail ||
2878 wq_list_empty(&ctx->iopoll_list))
2881 ret = io_do_iopoll(ctx, !min);
2886 } while (nr_events < min && !need_resched());
2888 mutex_unlock(&ctx->uring_lock);
2892 static void kiocb_end_write(struct io_kiocb *req)
2895 * Tell lockdep we inherited freeze protection from submission
2898 if (req->flags & REQ_F_ISREG) {
2899 struct super_block *sb = file_inode(req->file)->i_sb;
2901 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2907 static bool io_resubmit_prep(struct io_kiocb *req)
2909 struct io_async_rw *rw = req->async_data;
2911 if (!req_has_async_data(req))
2912 return !io_req_prep_async(req);
2913 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2917 static bool io_rw_should_reissue(struct io_kiocb *req)
2919 umode_t mode = file_inode(req->file)->i_mode;
2920 struct io_ring_ctx *ctx = req->ctx;
2922 if (!S_ISBLK(mode) && !S_ISREG(mode))
2924 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2925 !(ctx->flags & IORING_SETUP_IOPOLL)))
2928 * If ref is dying, we might be running poll reap from the exit work.
2929 * Don't attempt to reissue from that path, just let it fail with
2932 if (percpu_ref_is_dying(&ctx->refs))
2935 * Play it safe and assume not safe to re-import and reissue if we're
2936 * not in the original thread group (or in task context).
2938 if (!same_thread_group(req->task, current) || !in_task())
2943 static bool io_resubmit_prep(struct io_kiocb *req)
2947 static bool io_rw_should_reissue(struct io_kiocb *req)
2953 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2955 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
2956 kiocb_end_write(req);
2957 fsnotify_modify(req->file);
2959 fsnotify_access(req->file);
2961 if (unlikely(res != req->result)) {
2962 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2963 io_rw_should_reissue(req)) {
2964 req->flags |= REQ_F_REISSUE;
2973 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2975 int res = req->result;
2978 io_req_complete_state(req, res, io_put_kbuf(req, 0));
2979 io_req_add_compl_list(req);
2981 io_req_complete_post(req, res,
2982 io_put_kbuf(req, IO_URING_F_UNLOCKED));
2986 static void __io_complete_rw(struct io_kiocb *req, long res,
2987 unsigned int issue_flags)
2989 if (__io_complete_rw_common(req, res))
2991 __io_req_complete(req, issue_flags, req->result,
2992 io_put_kbuf(req, issue_flags));
2995 static void io_complete_rw(struct kiocb *kiocb, long res)
2997 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2999 if (__io_complete_rw_common(req, res))
3002 req->io_task_work.func = io_req_task_complete;
3003 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3006 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3008 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3010 if (kiocb->ki_flags & IOCB_WRITE)
3011 kiocb_end_write(req);
3012 if (unlikely(res != req->result)) {
3013 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3014 req->flags |= REQ_F_REISSUE;
3020 /* order with io_iopoll_complete() checking ->iopoll_completed */
3021 smp_store_release(&req->iopoll_completed, 1);
3025 * After the iocb has been issued, it's safe to be found on the poll list.
3026 * Adding the kiocb to the list AFTER submission ensures that we don't
3027 * find it from a io_do_iopoll() thread before the issuer is done
3028 * accessing the kiocb cookie.
3030 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3032 struct io_ring_ctx *ctx = req->ctx;
3033 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3035 /* workqueue context doesn't hold uring_lock, grab it now */
3036 if (unlikely(needs_lock))
3037 mutex_lock(&ctx->uring_lock);
3040 * Track whether we have multiple files in our lists. This will impact
3041 * how we do polling eventually, not spinning if we're on potentially
3042 * different devices.
3044 if (wq_list_empty(&ctx->iopoll_list)) {
3045 ctx->poll_multi_queue = false;
3046 } else if (!ctx->poll_multi_queue) {
3047 struct io_kiocb *list_req;
3049 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3051 if (list_req->file != req->file)
3052 ctx->poll_multi_queue = true;
3056 * For fast devices, IO may have already completed. If it has, add
3057 * it to the front so we find it first.
3059 if (READ_ONCE(req->iopoll_completed))
3060 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3062 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3064 if (unlikely(needs_lock)) {
3066 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3067 * in sq thread task context or in io worker task context. If
3068 * current task context is sq thread, we don't need to check
3069 * whether should wake up sq thread.
3071 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3072 wq_has_sleeper(&ctx->sq_data->wait))
3073 wake_up(&ctx->sq_data->wait);
3075 mutex_unlock(&ctx->uring_lock);
3079 static bool io_bdev_nowait(struct block_device *bdev)
3081 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3085 * If we tracked the file through the SCM inflight mechanism, we could support
3086 * any file. For now, just ensure that anything potentially problematic is done
3089 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3091 if (S_ISBLK(mode)) {
3092 if (IS_ENABLED(CONFIG_BLOCK) &&
3093 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3099 if (S_ISREG(mode)) {
3100 if (IS_ENABLED(CONFIG_BLOCK) &&
3101 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3102 file->f_op != &io_uring_fops)
3107 /* any ->read/write should understand O_NONBLOCK */
3108 if (file->f_flags & O_NONBLOCK)
3110 return file->f_mode & FMODE_NOWAIT;
3114 * If we tracked the file through the SCM inflight mechanism, we could support
3115 * any file. For now, just ensure that anything potentially problematic is done
3118 static unsigned int io_file_get_flags(struct file *file)
3120 umode_t mode = file_inode(file)->i_mode;
3121 unsigned int res = 0;
3125 if (__io_file_supports_nowait(file, mode))
3130 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3132 return req->flags & REQ_F_SUPPORT_NOWAIT;
3135 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3137 struct kiocb *kiocb = &req->rw.kiocb;
3141 kiocb->ki_pos = READ_ONCE(sqe->off);
3143 ioprio = READ_ONCE(sqe->ioprio);
3145 ret = ioprio_check_cap(ioprio);
3149 kiocb->ki_ioprio = ioprio;
3151 kiocb->ki_ioprio = get_current_ioprio();
3155 req->rw.addr = READ_ONCE(sqe->addr);
3156 req->rw.len = READ_ONCE(sqe->len);
3157 req->rw.flags = READ_ONCE(sqe->rw_flags);
3158 req->buf_index = READ_ONCE(sqe->buf_index);
3162 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3168 case -ERESTARTNOINTR:
3169 case -ERESTARTNOHAND:
3170 case -ERESTART_RESTARTBLOCK:
3172 * We can't just restart the syscall, since previously
3173 * submitted sqes may already be in progress. Just fail this
3179 kiocb->ki_complete(kiocb, ret);
3183 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3185 struct kiocb *kiocb = &req->rw.kiocb;
3186 bool is_stream = req->file->f_mode & FMODE_STREAM;
3188 if (kiocb->ki_pos == -1) {
3190 req->flags |= REQ_F_CUR_POS;
3191 kiocb->ki_pos = req->file->f_pos;
3192 return &kiocb->ki_pos;
3198 return is_stream ? NULL : &kiocb->ki_pos;
3201 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3202 unsigned int issue_flags)
3204 struct io_async_rw *io = req->async_data;
3206 /* add previously done IO, if any */
3207 if (req_has_async_data(req) && io->bytes_done > 0) {
3209 ret = io->bytes_done;
3211 ret += io->bytes_done;
3214 if (req->flags & REQ_F_CUR_POS)
3215 req->file->f_pos = req->rw.kiocb.ki_pos;
3216 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3217 __io_complete_rw(req, ret, issue_flags);
3219 io_rw_done(&req->rw.kiocb, ret);
3221 if (req->flags & REQ_F_REISSUE) {
3222 req->flags &= ~REQ_F_REISSUE;
3223 if (io_resubmit_prep(req))
3224 io_req_task_queue_reissue(req);
3226 io_req_task_queue_fail(req, ret);
3230 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3231 struct io_mapped_ubuf *imu)
3233 size_t len = req->rw.len;
3234 u64 buf_end, buf_addr = req->rw.addr;
3237 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3239 /* not inside the mapped region */
3240 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3244 * May not be a start of buffer, set size appropriately
3245 * and advance us to the beginning.
3247 offset = buf_addr - imu->ubuf;
3248 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3252 * Don't use iov_iter_advance() here, as it's really slow for
3253 * using the latter parts of a big fixed buffer - it iterates
3254 * over each segment manually. We can cheat a bit here, because
3257 * 1) it's a BVEC iter, we set it up
3258 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3259 * first and last bvec
3261 * So just find our index, and adjust the iterator afterwards.
3262 * If the offset is within the first bvec (or the whole first
3263 * bvec, just use iov_iter_advance(). This makes it easier
3264 * since we can just skip the first segment, which may not
3265 * be PAGE_SIZE aligned.
3267 const struct bio_vec *bvec = imu->bvec;
3269 if (offset <= bvec->bv_len) {
3270 iov_iter_advance(iter, offset);
3272 unsigned long seg_skip;
3274 /* skip first vec */
3275 offset -= bvec->bv_len;
3276 seg_skip = 1 + (offset >> PAGE_SHIFT);
3278 iter->bvec = bvec + seg_skip;
3279 iter->nr_segs -= seg_skip;
3280 iter->count -= bvec->bv_len + offset;
3281 iter->iov_offset = offset & ~PAGE_MASK;
3288 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3289 unsigned int issue_flags)
3291 struct io_mapped_ubuf *imu = req->imu;
3292 u16 index, buf_index = req->buf_index;
3295 struct io_ring_ctx *ctx = req->ctx;
3297 if (unlikely(buf_index >= ctx->nr_user_bufs))
3299 io_req_set_rsrc_node(req, ctx, issue_flags);
3300 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3301 imu = READ_ONCE(ctx->user_bufs[index]);
3304 return __io_import_fixed(req, rw, iter, imu);
3307 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3310 mutex_unlock(&ctx->uring_lock);
3313 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3316 * "Normal" inline submissions always hold the uring_lock, since we
3317 * grab it from the system call. Same is true for the SQPOLL offload.
3318 * The only exception is when we've detached the request and issue it
3319 * from an async worker thread, grab the lock for that case.
3322 mutex_lock(&ctx->uring_lock);
3325 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3326 struct io_buffer_list *bl, unsigned int bgid)
3328 struct list_head *list;
3330 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3331 INIT_LIST_HEAD(&bl->buf_list);
3333 list_add(&bl->list, list);
3336 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3337 int bgid, unsigned int issue_flags)
3339 struct io_buffer *kbuf = req->kbuf;
3340 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3341 struct io_ring_ctx *ctx = req->ctx;
3342 struct io_buffer_list *bl;
3344 if (req->flags & REQ_F_BUFFER_SELECTED)
3347 io_ring_submit_lock(ctx, needs_lock);
3349 lockdep_assert_held(&ctx->uring_lock);
3351 bl = io_buffer_get_list(ctx, bgid);
3352 if (bl && !list_empty(&bl->buf_list)) {
3353 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3354 list_del(&kbuf->list);
3355 if (*len > kbuf->len)
3357 req->flags |= REQ_F_BUFFER_SELECTED;
3360 kbuf = ERR_PTR(-ENOBUFS);
3363 io_ring_submit_unlock(req->ctx, needs_lock);
3367 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3368 unsigned int issue_flags)
3370 struct io_buffer *kbuf;
3373 bgid = req->buf_index;
3374 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3377 return u64_to_user_ptr(kbuf->addr);
3380 #ifdef CONFIG_COMPAT
3381 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3382 unsigned int issue_flags)
3384 struct compat_iovec __user *uiov;
3385 compat_ssize_t clen;
3389 uiov = u64_to_user_ptr(req->rw.addr);
3390 if (!access_ok(uiov, sizeof(*uiov)))
3392 if (__get_user(clen, &uiov->iov_len))
3398 buf = io_rw_buffer_select(req, &len, issue_flags);
3400 return PTR_ERR(buf);
3401 iov[0].iov_base = buf;
3402 iov[0].iov_len = (compat_size_t) len;
3407 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3408 unsigned int issue_flags)
3410 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3414 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3417 len = iov[0].iov_len;
3420 buf = io_rw_buffer_select(req, &len, issue_flags);
3422 return PTR_ERR(buf);
3423 iov[0].iov_base = buf;
3424 iov[0].iov_len = len;
3428 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3429 unsigned int issue_flags)
3431 if (req->flags & REQ_F_BUFFER_SELECTED) {
3432 struct io_buffer *kbuf = req->kbuf;
3434 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3435 iov[0].iov_len = kbuf->len;
3438 if (req->rw.len != 1)
3441 #ifdef CONFIG_COMPAT
3442 if (req->ctx->compat)
3443 return io_compat_import(req, iov, issue_flags);
3446 return __io_iov_buffer_select(req, iov, issue_flags);
3449 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3450 struct io_rw_state *s,
3451 unsigned int issue_flags)
3453 struct iov_iter *iter = &s->iter;
3454 u8 opcode = req->opcode;
3455 struct iovec *iovec;
3460 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3461 ret = io_import_fixed(req, rw, iter, issue_flags);
3463 return ERR_PTR(ret);
3467 /* buffer index only valid with fixed read/write, or buffer select */
3468 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3469 return ERR_PTR(-EINVAL);
3471 buf = u64_to_user_ptr(req->rw.addr);
3472 sqe_len = req->rw.len;
3474 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3475 if (req->flags & REQ_F_BUFFER_SELECT) {
3476 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3478 return ERR_CAST(buf);
3479 req->rw.len = sqe_len;
3482 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3484 return ERR_PTR(ret);
3488 iovec = s->fast_iov;
3489 if (req->flags & REQ_F_BUFFER_SELECT) {
3490 ret = io_iov_buffer_select(req, iovec, issue_flags);
3492 return ERR_PTR(ret);
3493 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3497 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3499 if (unlikely(ret < 0))
3500 return ERR_PTR(ret);
3504 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3505 struct iovec **iovec, struct io_rw_state *s,
3506 unsigned int issue_flags)
3508 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3509 if (unlikely(IS_ERR(*iovec)))
3510 return PTR_ERR(*iovec);
3512 iov_iter_save_state(&s->iter, &s->iter_state);
3516 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3518 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3522 * For files that don't have ->read_iter() and ->write_iter(), handle them
3523 * by looping over ->read() or ->write() manually.
3525 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3527 struct kiocb *kiocb = &req->rw.kiocb;
3528 struct file *file = req->file;
3533 * Don't support polled IO through this interface, and we can't
3534 * support non-blocking either. For the latter, this just causes
3535 * the kiocb to be handled from an async context.
3537 if (kiocb->ki_flags & IOCB_HIPRI)
3539 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3540 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3543 ppos = io_kiocb_ppos(kiocb);
3545 while (iov_iter_count(iter)) {
3549 if (!iov_iter_is_bvec(iter)) {
3550 iovec = iov_iter_iovec(iter);
3552 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3553 iovec.iov_len = req->rw.len;
3557 nr = file->f_op->read(file, iovec.iov_base,
3558 iovec.iov_len, ppos);
3560 nr = file->f_op->write(file, iovec.iov_base,
3561 iovec.iov_len, ppos);
3570 if (!iov_iter_is_bvec(iter)) {
3571 iov_iter_advance(iter, nr);
3578 if (nr != iovec.iov_len)
3585 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3586 const struct iovec *fast_iov, struct iov_iter *iter)
3588 struct io_async_rw *rw = req->async_data;
3590 memcpy(&rw->s.iter, iter, sizeof(*iter));
3591 rw->free_iovec = iovec;
3593 /* can only be fixed buffers, no need to do anything */
3594 if (iov_iter_is_bvec(iter))
3597 unsigned iov_off = 0;
3599 rw->s.iter.iov = rw->s.fast_iov;
3600 if (iter->iov != fast_iov) {
3601 iov_off = iter->iov - fast_iov;
3602 rw->s.iter.iov += iov_off;
3604 if (rw->s.fast_iov != fast_iov)
3605 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3606 sizeof(struct iovec) * iter->nr_segs);
3608 req->flags |= REQ_F_NEED_CLEANUP;
3612 static inline bool io_alloc_async_data(struct io_kiocb *req)
3614 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3615 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3616 if (req->async_data) {
3617 req->flags |= REQ_F_ASYNC_DATA;
3623 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3624 struct io_rw_state *s, bool force)
3626 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3628 if (!req_has_async_data(req)) {
3629 struct io_async_rw *iorw;
3631 if (io_alloc_async_data(req)) {
3636 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3637 iorw = req->async_data;
3638 /* we've copied and mapped the iter, ensure state is saved */
3639 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3644 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3646 struct io_async_rw *iorw = req->async_data;
3650 /* submission path, ->uring_lock should already be taken */
3651 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3652 if (unlikely(ret < 0))
3655 iorw->bytes_done = 0;
3656 iorw->free_iovec = iov;
3658 req->flags |= REQ_F_NEED_CLEANUP;
3663 * This is our waitqueue callback handler, registered through __folio_lock_async()
3664 * when we initially tried to do the IO with the iocb armed our waitqueue.
3665 * This gets called when the page is unlocked, and we generally expect that to
3666 * happen when the page IO is completed and the page is now uptodate. This will
3667 * queue a task_work based retry of the operation, attempting to copy the data
3668 * again. If the latter fails because the page was NOT uptodate, then we will
3669 * do a thread based blocking retry of the operation. That's the unexpected
3672 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3673 int sync, void *arg)
3675 struct wait_page_queue *wpq;
3676 struct io_kiocb *req = wait->private;
3677 struct wait_page_key *key = arg;
3679 wpq = container_of(wait, struct wait_page_queue, wait);
3681 if (!wake_page_match(wpq, key))
3684 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3685 list_del_init(&wait->entry);
3686 io_req_task_queue(req);
3691 * This controls whether a given IO request should be armed for async page
3692 * based retry. If we return false here, the request is handed to the async
3693 * worker threads for retry. If we're doing buffered reads on a regular file,
3694 * we prepare a private wait_page_queue entry and retry the operation. This
3695 * will either succeed because the page is now uptodate and unlocked, or it
3696 * will register a callback when the page is unlocked at IO completion. Through
3697 * that callback, io_uring uses task_work to setup a retry of the operation.
3698 * That retry will attempt the buffered read again. The retry will generally
3699 * succeed, or in rare cases where it fails, we then fall back to using the
3700 * async worker threads for a blocking retry.
3702 static bool io_rw_should_retry(struct io_kiocb *req)
3704 struct io_async_rw *rw = req->async_data;
3705 struct wait_page_queue *wait = &rw->wpq;
3706 struct kiocb *kiocb = &req->rw.kiocb;
3708 /* never retry for NOWAIT, we just complete with -EAGAIN */
3709 if (req->flags & REQ_F_NOWAIT)
3712 /* Only for buffered IO */
3713 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3717 * just use poll if we can, and don't attempt if the fs doesn't
3718 * support callback based unlocks
3720 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3723 wait->wait.func = io_async_buf_func;
3724 wait->wait.private = req;
3725 wait->wait.flags = 0;
3726 INIT_LIST_HEAD(&wait->wait.entry);
3727 kiocb->ki_flags |= IOCB_WAITQ;
3728 kiocb->ki_flags &= ~IOCB_NOWAIT;
3729 kiocb->ki_waitq = wait;
3733 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3735 if (likely(req->file->f_op->read_iter))
3736 return call_read_iter(req->file, &req->rw.kiocb, iter);
3737 else if (req->file->f_op->read)
3738 return loop_rw_iter(READ, req, iter);
3743 static bool need_read_all(struct io_kiocb *req)
3745 return req->flags & REQ_F_ISREG ||
3746 S_ISBLK(file_inode(req->file)->i_mode);
3749 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3751 struct kiocb *kiocb = &req->rw.kiocb;
3752 struct io_ring_ctx *ctx = req->ctx;
3753 struct file *file = req->file;
3756 if (unlikely(!file || !(file->f_mode & mode)))
3759 if (!io_req_ffs_set(req))
3760 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3762 kiocb->ki_flags = iocb_flags(file);
3763 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
3768 * If the file is marked O_NONBLOCK, still allow retry for it if it
3769 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3770 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3772 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3773 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3774 req->flags |= REQ_F_NOWAIT;
3776 if (ctx->flags & IORING_SETUP_IOPOLL) {
3777 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3780 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3781 kiocb->ki_complete = io_complete_rw_iopoll;
3782 req->iopoll_completed = 0;
3784 if (kiocb->ki_flags & IOCB_HIPRI)
3786 kiocb->ki_complete = io_complete_rw;
3792 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3794 struct io_rw_state __s, *s = &__s;
3795 struct iovec *iovec;
3796 struct kiocb *kiocb = &req->rw.kiocb;
3797 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3798 struct io_async_rw *rw;
3802 if (!req_has_async_data(req)) {
3803 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3804 if (unlikely(ret < 0))
3808 * Safe and required to re-import if we're using provided
3809 * buffers, as we dropped the selected one before retry.
3811 if (req->flags & REQ_F_BUFFER_SELECT) {
3812 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3813 if (unlikely(ret < 0))
3817 rw = req->async_data;
3820 * We come here from an earlier attempt, restore our state to
3821 * match in case it doesn't. It's cheap enough that we don't
3822 * need to make this conditional.
3824 iov_iter_restore(&s->iter, &s->iter_state);
3827 ret = io_rw_init_file(req, FMODE_READ);
3830 req->result = iov_iter_count(&s->iter);
3832 if (force_nonblock) {
3833 /* If the file doesn't support async, just async punt */
3834 if (unlikely(!io_file_supports_nowait(req))) {
3835 ret = io_setup_async_rw(req, iovec, s, true);
3836 return ret ?: -EAGAIN;
3838 kiocb->ki_flags |= IOCB_NOWAIT;
3840 /* Ensure we clear previously set non-block flag */
3841 kiocb->ki_flags &= ~IOCB_NOWAIT;
3844 ppos = io_kiocb_update_pos(req);
3846 ret = rw_verify_area(READ, req->file, ppos, req->result);
3847 if (unlikely(ret)) {
3852 ret = io_iter_do_read(req, &s->iter);
3854 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3855 req->flags &= ~REQ_F_REISSUE;
3856 /* if we can poll, just do that */
3857 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3859 /* IOPOLL retry should happen for io-wq threads */
3860 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3862 /* no retry on NONBLOCK nor RWF_NOWAIT */
3863 if (req->flags & REQ_F_NOWAIT)
3866 } else if (ret == -EIOCBQUEUED) {
3868 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3869 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3870 /* read all, failed, already did sync or don't want to retry */
3875 * Don't depend on the iter state matching what was consumed, or being
3876 * untouched in case of error. Restore it and we'll advance it
3877 * manually if we need to.
3879 iov_iter_restore(&s->iter, &s->iter_state);
3881 ret2 = io_setup_async_rw(req, iovec, s, true);
3886 rw = req->async_data;
3889 * Now use our persistent iterator and state, if we aren't already.
3890 * We've restored and mapped the iter to match.
3895 * We end up here because of a partial read, either from
3896 * above or inside this loop. Advance the iter by the bytes
3897 * that were consumed.
3899 iov_iter_advance(&s->iter, ret);
3900 if (!iov_iter_count(&s->iter))
3902 rw->bytes_done += ret;
3903 iov_iter_save_state(&s->iter, &s->iter_state);
3905 /* if we can retry, do so with the callbacks armed */
3906 if (!io_rw_should_retry(req)) {
3907 kiocb->ki_flags &= ~IOCB_WAITQ;
3912 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3913 * we get -EIOCBQUEUED, then we'll get a notification when the
3914 * desired page gets unlocked. We can also get a partial read
3915 * here, and if we do, then just retry at the new offset.
3917 ret = io_iter_do_read(req, &s->iter);
3918 if (ret == -EIOCBQUEUED)
3920 /* we got some bytes, but not all. retry. */
3921 kiocb->ki_flags &= ~IOCB_WAITQ;
3922 iov_iter_restore(&s->iter, &s->iter_state);
3925 kiocb_done(req, ret, issue_flags);
3927 /* it's faster to check here then delegate to kfree */
3933 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3935 struct io_rw_state __s, *s = &__s;
3936 struct iovec *iovec;
3937 struct kiocb *kiocb = &req->rw.kiocb;
3938 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3942 if (!req_has_async_data(req)) {
3943 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3944 if (unlikely(ret < 0))
3947 struct io_async_rw *rw = req->async_data;
3950 iov_iter_restore(&s->iter, &s->iter_state);
3953 ret = io_rw_init_file(req, FMODE_WRITE);
3956 req->result = iov_iter_count(&s->iter);
3958 if (force_nonblock) {
3959 /* If the file doesn't support async, just async punt */
3960 if (unlikely(!io_file_supports_nowait(req)))
3963 /* file path doesn't support NOWAIT for non-direct_IO */
3964 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3965 (req->flags & REQ_F_ISREG))
3968 kiocb->ki_flags |= IOCB_NOWAIT;
3970 /* Ensure we clear previously set non-block flag */
3971 kiocb->ki_flags &= ~IOCB_NOWAIT;
3974 ppos = io_kiocb_update_pos(req);
3976 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3981 * Open-code file_start_write here to grab freeze protection,
3982 * which will be released by another thread in
3983 * io_complete_rw(). Fool lockdep by telling it the lock got
3984 * released so that it doesn't complain about the held lock when
3985 * we return to userspace.
3987 if (req->flags & REQ_F_ISREG) {
3988 sb_start_write(file_inode(req->file)->i_sb);
3989 __sb_writers_release(file_inode(req->file)->i_sb,
3992 kiocb->ki_flags |= IOCB_WRITE;
3994 if (likely(req->file->f_op->write_iter))
3995 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3996 else if (req->file->f_op->write)
3997 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4001 if (req->flags & REQ_F_REISSUE) {
4002 req->flags &= ~REQ_F_REISSUE;
4007 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4008 * retry them without IOCB_NOWAIT.
4010 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4012 /* no retry on NONBLOCK nor RWF_NOWAIT */
4013 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4015 if (!force_nonblock || ret2 != -EAGAIN) {
4016 /* IOPOLL retry should happen for io-wq threads */
4017 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4020 kiocb_done(req, ret2, issue_flags);
4023 iov_iter_restore(&s->iter, &s->iter_state);
4024 ret = io_setup_async_rw(req, iovec, s, false);
4025 return ret ?: -EAGAIN;
4028 /* it's reportedly faster than delegating the null check to kfree() */
4034 static int io_renameat_prep(struct io_kiocb *req,
4035 const struct io_uring_sqe *sqe)
4037 struct io_rename *ren = &req->rename;
4038 const char __user *oldf, *newf;
4040 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4042 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4044 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4047 ren->old_dfd = READ_ONCE(sqe->fd);
4048 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4049 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4050 ren->new_dfd = READ_ONCE(sqe->len);
4051 ren->flags = READ_ONCE(sqe->rename_flags);
4053 ren->oldpath = getname(oldf);
4054 if (IS_ERR(ren->oldpath))
4055 return PTR_ERR(ren->oldpath);
4057 ren->newpath = getname(newf);
4058 if (IS_ERR(ren->newpath)) {
4059 putname(ren->oldpath);
4060 return PTR_ERR(ren->newpath);
4063 req->flags |= REQ_F_NEED_CLEANUP;
4067 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4069 struct io_rename *ren = &req->rename;
4072 if (issue_flags & IO_URING_F_NONBLOCK)
4075 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4076 ren->newpath, ren->flags);
4078 req->flags &= ~REQ_F_NEED_CLEANUP;
4081 io_req_complete(req, ret);
4085 static int io_unlinkat_prep(struct io_kiocb *req,
4086 const struct io_uring_sqe *sqe)
4088 struct io_unlink *un = &req->unlink;
4089 const char __user *fname;
4091 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4093 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4096 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4099 un->dfd = READ_ONCE(sqe->fd);
4101 un->flags = READ_ONCE(sqe->unlink_flags);
4102 if (un->flags & ~AT_REMOVEDIR)
4105 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4106 un->filename = getname(fname);
4107 if (IS_ERR(un->filename))
4108 return PTR_ERR(un->filename);
4110 req->flags |= REQ_F_NEED_CLEANUP;
4114 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4116 struct io_unlink *un = &req->unlink;
4119 if (issue_flags & IO_URING_F_NONBLOCK)
4122 if (un->flags & AT_REMOVEDIR)
4123 ret = do_rmdir(un->dfd, un->filename);
4125 ret = do_unlinkat(un->dfd, un->filename);
4127 req->flags &= ~REQ_F_NEED_CLEANUP;
4130 io_req_complete(req, ret);
4134 static int io_mkdirat_prep(struct io_kiocb *req,
4135 const struct io_uring_sqe *sqe)
4137 struct io_mkdir *mkd = &req->mkdir;
4138 const char __user *fname;
4140 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4142 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4145 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4148 mkd->dfd = READ_ONCE(sqe->fd);
4149 mkd->mode = READ_ONCE(sqe->len);
4151 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4152 mkd->filename = getname(fname);
4153 if (IS_ERR(mkd->filename))
4154 return PTR_ERR(mkd->filename);
4156 req->flags |= REQ_F_NEED_CLEANUP;
4160 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4162 struct io_mkdir *mkd = &req->mkdir;
4165 if (issue_flags & IO_URING_F_NONBLOCK)
4168 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4170 req->flags &= ~REQ_F_NEED_CLEANUP;
4173 io_req_complete(req, ret);
4177 static int io_symlinkat_prep(struct io_kiocb *req,
4178 const struct io_uring_sqe *sqe)
4180 struct io_symlink *sl = &req->symlink;
4181 const char __user *oldpath, *newpath;
4183 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4185 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4188 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4191 sl->new_dfd = READ_ONCE(sqe->fd);
4192 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4193 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4195 sl->oldpath = getname(oldpath);
4196 if (IS_ERR(sl->oldpath))
4197 return PTR_ERR(sl->oldpath);
4199 sl->newpath = getname(newpath);
4200 if (IS_ERR(sl->newpath)) {
4201 putname(sl->oldpath);
4202 return PTR_ERR(sl->newpath);
4205 req->flags |= REQ_F_NEED_CLEANUP;
4209 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4211 struct io_symlink *sl = &req->symlink;
4214 if (issue_flags & IO_URING_F_NONBLOCK)
4217 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4219 req->flags &= ~REQ_F_NEED_CLEANUP;
4222 io_req_complete(req, ret);
4226 static int io_linkat_prep(struct io_kiocb *req,
4227 const struct io_uring_sqe *sqe)
4229 struct io_hardlink *lnk = &req->hardlink;
4230 const char __user *oldf, *newf;
4232 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4234 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4236 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4239 lnk->old_dfd = READ_ONCE(sqe->fd);
4240 lnk->new_dfd = READ_ONCE(sqe->len);
4241 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4242 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4243 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4245 lnk->oldpath = getname(oldf);
4246 if (IS_ERR(lnk->oldpath))
4247 return PTR_ERR(lnk->oldpath);
4249 lnk->newpath = getname(newf);
4250 if (IS_ERR(lnk->newpath)) {
4251 putname(lnk->oldpath);
4252 return PTR_ERR(lnk->newpath);
4255 req->flags |= REQ_F_NEED_CLEANUP;
4259 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4261 struct io_hardlink *lnk = &req->hardlink;
4264 if (issue_flags & IO_URING_F_NONBLOCK)
4267 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4268 lnk->newpath, lnk->flags);
4270 req->flags &= ~REQ_F_NEED_CLEANUP;
4273 io_req_complete(req, ret);
4277 static int io_shutdown_prep(struct io_kiocb *req,
4278 const struct io_uring_sqe *sqe)
4280 #if defined(CONFIG_NET)
4281 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4283 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4284 sqe->buf_index || sqe->splice_fd_in))
4287 req->shutdown.how = READ_ONCE(sqe->len);
4294 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4296 #if defined(CONFIG_NET)
4297 struct socket *sock;
4300 if (issue_flags & IO_URING_F_NONBLOCK)
4303 sock = sock_from_file(req->file);
4304 if (unlikely(!sock))
4307 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4310 io_req_complete(req, ret);
4317 static int __io_splice_prep(struct io_kiocb *req,
4318 const struct io_uring_sqe *sqe)
4320 struct io_splice *sp = &req->splice;
4321 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4323 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4326 sp->len = READ_ONCE(sqe->len);
4327 sp->flags = READ_ONCE(sqe->splice_flags);
4328 if (unlikely(sp->flags & ~valid_flags))
4330 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4334 static int io_tee_prep(struct io_kiocb *req,
4335 const struct io_uring_sqe *sqe)
4337 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4339 return __io_splice_prep(req, sqe);
4342 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4344 struct io_splice *sp = &req->splice;
4345 struct file *out = sp->file_out;
4346 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4350 if (issue_flags & IO_URING_F_NONBLOCK)
4353 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4354 in = io_file_get_fixed(req, sp->splice_fd_in, IO_URING_F_UNLOCKED);
4356 in = io_file_get_normal(req, sp->splice_fd_in);
4363 ret = do_tee(in, out, sp->len, flags);
4365 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4370 io_req_complete(req, ret);
4374 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4376 struct io_splice *sp = &req->splice;
4378 sp->off_in = READ_ONCE(sqe->splice_off_in);
4379 sp->off_out = READ_ONCE(sqe->off);
4380 return __io_splice_prep(req, sqe);
4383 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4385 struct io_splice *sp = &req->splice;
4386 struct file *out = sp->file_out;
4387 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4388 loff_t *poff_in, *poff_out;
4392 if (issue_flags & IO_URING_F_NONBLOCK)
4395 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4396 in = io_file_get_fixed(req, sp->splice_fd_in, IO_URING_F_UNLOCKED);
4398 in = io_file_get_normal(req, sp->splice_fd_in);
4404 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4405 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4408 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4410 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4415 io_req_complete(req, ret);
4420 * IORING_OP_NOP just posts a completion event, nothing else.
4422 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4424 struct io_ring_ctx *ctx = req->ctx;
4426 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4429 __io_req_complete(req, issue_flags, 0, 0);
4433 static int io_msg_ring_prep(struct io_kiocb *req,
4434 const struct io_uring_sqe *sqe)
4436 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4437 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4440 req->msg.user_data = READ_ONCE(sqe->off);
4441 req->msg.len = READ_ONCE(sqe->len);
4445 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4447 struct io_ring_ctx *target_ctx;
4448 struct io_msg *msg = &req->msg;
4453 if (req->file->f_op != &io_uring_fops)
4457 target_ctx = req->file->private_data;
4459 spin_lock(&target_ctx->completion_lock);
4460 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
4461 io_commit_cqring(target_ctx);
4462 spin_unlock(&target_ctx->completion_lock);
4465 io_cqring_ev_posted(target_ctx);
4472 __io_req_complete(req, issue_flags, ret, 0);
4476 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4478 struct io_ring_ctx *ctx = req->ctx;
4480 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4482 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4486 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4487 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4490 req->sync.off = READ_ONCE(sqe->off);
4491 req->sync.len = READ_ONCE(sqe->len);
4495 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4497 loff_t end = req->sync.off + req->sync.len;
4500 /* fsync always requires a blocking context */
4501 if (issue_flags & IO_URING_F_NONBLOCK)
4504 ret = vfs_fsync_range(req->file, req->sync.off,
4505 end > 0 ? end : LLONG_MAX,
4506 req->sync.flags & IORING_FSYNC_DATASYNC);
4509 io_req_complete(req, ret);
4513 static int io_fallocate_prep(struct io_kiocb *req,
4514 const struct io_uring_sqe *sqe)
4516 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4519 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4522 req->sync.off = READ_ONCE(sqe->off);
4523 req->sync.len = READ_ONCE(sqe->addr);
4524 req->sync.mode = READ_ONCE(sqe->len);
4528 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4532 /* fallocate always requiring blocking context */
4533 if (issue_flags & IO_URING_F_NONBLOCK)
4535 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4540 fsnotify_modify(req->file);
4541 io_req_complete(req, ret);
4545 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4547 const char __user *fname;
4550 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4552 if (unlikely(sqe->ioprio || sqe->buf_index))
4554 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4557 /* open.how should be already initialised */
4558 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4559 req->open.how.flags |= O_LARGEFILE;
4561 req->open.dfd = READ_ONCE(sqe->fd);
4562 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4563 req->open.filename = getname(fname);
4564 if (IS_ERR(req->open.filename)) {
4565 ret = PTR_ERR(req->open.filename);
4566 req->open.filename = NULL;
4570 req->open.file_slot = READ_ONCE(sqe->file_index);
4571 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4574 req->open.nofile = rlimit(RLIMIT_NOFILE);
4575 req->flags |= REQ_F_NEED_CLEANUP;
4579 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4581 u64 mode = READ_ONCE(sqe->len);
4582 u64 flags = READ_ONCE(sqe->open_flags);
4584 req->open.how = build_open_how(flags, mode);
4585 return __io_openat_prep(req, sqe);
4588 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4590 struct open_how __user *how;
4594 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4595 len = READ_ONCE(sqe->len);
4596 if (len < OPEN_HOW_SIZE_VER0)
4599 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4604 return __io_openat_prep(req, sqe);
4607 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4609 struct open_flags op;
4611 bool resolve_nonblock, nonblock_set;
4612 bool fixed = !!req->open.file_slot;
4615 ret = build_open_flags(&req->open.how, &op);
4618 nonblock_set = op.open_flag & O_NONBLOCK;
4619 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4620 if (issue_flags & IO_URING_F_NONBLOCK) {
4622 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4623 * it'll always -EAGAIN
4625 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4627 op.lookup_flags |= LOOKUP_CACHED;
4628 op.open_flag |= O_NONBLOCK;
4632 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4637 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4640 * We could hang on to this 'fd' on retrying, but seems like
4641 * marginal gain for something that is now known to be a slower
4642 * path. So just put it, and we'll get a new one when we retry.
4647 ret = PTR_ERR(file);
4648 /* only retry if RESOLVE_CACHED wasn't already set by application */
4649 if (ret == -EAGAIN &&
4650 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4655 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4656 file->f_flags &= ~O_NONBLOCK;
4657 fsnotify_open(file);
4660 fd_install(ret, file);
4662 ret = io_install_fixed_file(req, file, issue_flags,
4663 req->open.file_slot - 1);
4665 putname(req->open.filename);
4666 req->flags &= ~REQ_F_NEED_CLEANUP;
4669 __io_req_complete(req, issue_flags, ret, 0);
4673 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4675 return io_openat2(req, issue_flags);
4678 static int io_remove_buffers_prep(struct io_kiocb *req,
4679 const struct io_uring_sqe *sqe)
4681 struct io_provide_buf *p = &req->pbuf;
4684 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4688 tmp = READ_ONCE(sqe->fd);
4689 if (!tmp || tmp > USHRT_MAX)
4692 memset(p, 0, sizeof(*p));
4694 p->bgid = READ_ONCE(sqe->buf_group);
4698 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4699 struct io_buffer_list *bl, unsigned nbufs)
4703 /* shouldn't happen */
4707 /* the head kbuf is the list itself */
4708 while (!list_empty(&bl->buf_list)) {
4709 struct io_buffer *nxt;
4711 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4712 list_del(&nxt->list);
4722 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4724 struct io_provide_buf *p = &req->pbuf;
4725 struct io_ring_ctx *ctx = req->ctx;
4726 struct io_buffer_list *bl;
4728 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4730 io_ring_submit_lock(ctx, needs_lock);
4732 lockdep_assert_held(&ctx->uring_lock);
4735 bl = io_buffer_get_list(ctx, p->bgid);
4737 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4741 /* complete before unlock, IOPOLL may need the lock */
4742 __io_req_complete(req, issue_flags, ret, 0);
4743 io_ring_submit_unlock(ctx, needs_lock);
4747 static int io_provide_buffers_prep(struct io_kiocb *req,
4748 const struct io_uring_sqe *sqe)
4750 unsigned long size, tmp_check;
4751 struct io_provide_buf *p = &req->pbuf;
4754 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4757 tmp = READ_ONCE(sqe->fd);
4758 if (!tmp || tmp > USHRT_MAX)
4761 p->addr = READ_ONCE(sqe->addr);
4762 p->len = READ_ONCE(sqe->len);
4764 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4767 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4770 size = (unsigned long)p->len * p->nbufs;
4771 if (!access_ok(u64_to_user_ptr(p->addr), size))
4774 p->bgid = READ_ONCE(sqe->buf_group);
4775 tmp = READ_ONCE(sqe->off);
4776 if (tmp > USHRT_MAX)
4782 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4784 struct io_buffer *buf;
4789 * Completions that don't happen inline (eg not under uring_lock) will
4790 * add to ->io_buffers_comp. If we don't have any free buffers, check
4791 * the completion list and splice those entries first.
4793 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4794 spin_lock(&ctx->completion_lock);
4795 if (!list_empty(&ctx->io_buffers_comp)) {
4796 list_splice_init(&ctx->io_buffers_comp,
4797 &ctx->io_buffers_cache);
4798 spin_unlock(&ctx->completion_lock);
4801 spin_unlock(&ctx->completion_lock);
4805 * No free buffers and no completion entries either. Allocate a new
4806 * page worth of buffer entries and add those to our freelist.
4808 page = alloc_page(GFP_KERNEL_ACCOUNT);
4812 list_add(&page->lru, &ctx->io_buffers_pages);
4814 buf = page_address(page);
4815 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4816 while (bufs_in_page) {
4817 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4825 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4826 struct io_buffer_list *bl)
4828 struct io_buffer *buf;
4829 u64 addr = pbuf->addr;
4830 int i, bid = pbuf->bid;
4832 for (i = 0; i < pbuf->nbufs; i++) {
4833 if (list_empty(&ctx->io_buffers_cache) &&
4834 io_refill_buffer_cache(ctx))
4836 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4838 list_move_tail(&buf->list, &bl->buf_list);
4840 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4842 buf->bgid = pbuf->bgid;
4848 return i ? 0 : -ENOMEM;
4851 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4853 struct io_provide_buf *p = &req->pbuf;
4854 struct io_ring_ctx *ctx = req->ctx;
4855 struct io_buffer_list *bl;
4857 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4859 io_ring_submit_lock(ctx, needs_lock);
4861 lockdep_assert_held(&ctx->uring_lock);
4863 bl = io_buffer_get_list(ctx, p->bgid);
4864 if (unlikely(!bl)) {
4865 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4870 io_buffer_add_list(ctx, bl, p->bgid);
4873 ret = io_add_buffers(ctx, p, bl);
4877 /* complete before unlock, IOPOLL may need the lock */
4878 __io_req_complete(req, issue_flags, ret, 0);
4879 io_ring_submit_unlock(ctx, needs_lock);
4883 static int io_epoll_ctl_prep(struct io_kiocb *req,
4884 const struct io_uring_sqe *sqe)
4886 #if defined(CONFIG_EPOLL)
4887 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4889 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4892 req->epoll.epfd = READ_ONCE(sqe->fd);
4893 req->epoll.op = READ_ONCE(sqe->len);
4894 req->epoll.fd = READ_ONCE(sqe->off);
4896 if (ep_op_has_event(req->epoll.op)) {
4897 struct epoll_event __user *ev;
4899 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4900 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4910 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4912 #if defined(CONFIG_EPOLL)
4913 struct io_epoll *ie = &req->epoll;
4915 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4917 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4918 if (force_nonblock && ret == -EAGAIN)
4923 __io_req_complete(req, issue_flags, ret, 0);
4930 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4932 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4933 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4935 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4938 req->madvise.addr = READ_ONCE(sqe->addr);
4939 req->madvise.len = READ_ONCE(sqe->len);
4940 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4947 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4949 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4950 struct io_madvise *ma = &req->madvise;
4953 if (issue_flags & IO_URING_F_NONBLOCK)
4956 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4959 io_req_complete(req, ret);
4966 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4968 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4970 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4973 req->fadvise.offset = READ_ONCE(sqe->off);
4974 req->fadvise.len = READ_ONCE(sqe->len);
4975 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4979 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4981 struct io_fadvise *fa = &req->fadvise;
4984 if (issue_flags & IO_URING_F_NONBLOCK) {
4985 switch (fa->advice) {
4986 case POSIX_FADV_NORMAL:
4987 case POSIX_FADV_RANDOM:
4988 case POSIX_FADV_SEQUENTIAL:
4995 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4998 __io_req_complete(req, issue_flags, ret, 0);
5002 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5004 const char __user *path;
5006 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5008 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5010 if (req->flags & REQ_F_FIXED_FILE)
5013 req->statx.dfd = READ_ONCE(sqe->fd);
5014 req->statx.mask = READ_ONCE(sqe->len);
5015 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5016 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5017 req->statx.flags = READ_ONCE(sqe->statx_flags);
5019 req->statx.filename = getname_flags(path,
5020 getname_statx_lookup_flags(req->statx.flags),
5023 if (IS_ERR(req->statx.filename)) {
5024 int ret = PTR_ERR(req->statx.filename);
5026 req->statx.filename = NULL;
5030 req->flags |= REQ_F_NEED_CLEANUP;
5034 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5036 struct io_statx *ctx = &req->statx;
5039 if (issue_flags & IO_URING_F_NONBLOCK)
5042 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5047 io_req_complete(req, ret);
5051 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5053 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5055 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5056 sqe->rw_flags || sqe->buf_index)
5058 if (req->flags & REQ_F_FIXED_FILE)
5061 req->close.fd = READ_ONCE(sqe->fd);
5062 req->close.file_slot = READ_ONCE(sqe->file_index);
5063 if (req->close.file_slot && req->close.fd)
5069 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5071 struct files_struct *files = current->files;
5072 struct io_close *close = &req->close;
5073 struct fdtable *fdt;
5074 struct file *file = NULL;
5077 if (req->close.file_slot) {
5078 ret = io_close_fixed(req, issue_flags);
5082 spin_lock(&files->file_lock);
5083 fdt = files_fdtable(files);
5084 if (close->fd >= fdt->max_fds) {
5085 spin_unlock(&files->file_lock);
5088 file = fdt->fd[close->fd];
5089 if (!file || file->f_op == &io_uring_fops) {
5090 spin_unlock(&files->file_lock);
5095 /* if the file has a flush method, be safe and punt to async */
5096 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5097 spin_unlock(&files->file_lock);
5101 ret = __close_fd_get_file(close->fd, &file);
5102 spin_unlock(&files->file_lock);
5109 /* No ->flush() or already async, safely close from here */
5110 ret = filp_close(file, current->files);
5116 __io_req_complete(req, issue_flags, ret, 0);
5120 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5122 struct io_ring_ctx *ctx = req->ctx;
5124 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5126 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5130 req->sync.off = READ_ONCE(sqe->off);
5131 req->sync.len = READ_ONCE(sqe->len);
5132 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5136 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5140 /* sync_file_range always requires a blocking context */
5141 if (issue_flags & IO_URING_F_NONBLOCK)
5144 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5148 io_req_complete(req, ret);
5152 #if defined(CONFIG_NET)
5153 static int io_setup_async_msg(struct io_kiocb *req,
5154 struct io_async_msghdr *kmsg)
5156 struct io_async_msghdr *async_msg = req->async_data;
5160 if (io_alloc_async_data(req)) {
5161 kfree(kmsg->free_iov);
5164 async_msg = req->async_data;
5165 req->flags |= REQ_F_NEED_CLEANUP;
5166 memcpy(async_msg, kmsg, sizeof(*kmsg));
5167 async_msg->msg.msg_name = &async_msg->addr;
5168 /* if were using fast_iov, set it to the new one */
5169 if (!async_msg->free_iov)
5170 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5175 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5176 struct io_async_msghdr *iomsg)
5178 iomsg->msg.msg_name = &iomsg->addr;
5179 iomsg->free_iov = iomsg->fast_iov;
5180 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5181 req->sr_msg.msg_flags, &iomsg->free_iov);
5184 static int io_sendmsg_prep_async(struct io_kiocb *req)
5188 ret = io_sendmsg_copy_hdr(req, req->async_data);
5190 req->flags |= REQ_F_NEED_CLEANUP;
5194 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5196 struct io_sr_msg *sr = &req->sr_msg;
5198 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5201 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5202 sr->len = READ_ONCE(sqe->len);
5203 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5204 if (sr->msg_flags & MSG_DONTWAIT)
5205 req->flags |= REQ_F_NOWAIT;
5207 #ifdef CONFIG_COMPAT
5208 if (req->ctx->compat)
5209 sr->msg_flags |= MSG_CMSG_COMPAT;
5214 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5216 struct io_async_msghdr iomsg, *kmsg;
5217 struct socket *sock;
5222 sock = sock_from_file(req->file);
5223 if (unlikely(!sock))
5226 if (req_has_async_data(req)) {
5227 kmsg = req->async_data;
5229 ret = io_sendmsg_copy_hdr(req, &iomsg);
5235 flags = req->sr_msg.msg_flags;
5236 if (issue_flags & IO_URING_F_NONBLOCK)
5237 flags |= MSG_DONTWAIT;
5238 if (flags & MSG_WAITALL)
5239 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5241 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5243 if (ret < min_ret) {
5244 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5245 return io_setup_async_msg(req, kmsg);
5246 if (ret == -ERESTARTSYS)
5250 /* fast path, check for non-NULL to avoid function call */
5252 kfree(kmsg->free_iov);
5253 req->flags &= ~REQ_F_NEED_CLEANUP;
5254 __io_req_complete(req, issue_flags, ret, 0);
5258 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5260 struct io_sr_msg *sr = &req->sr_msg;
5263 struct socket *sock;
5268 sock = sock_from_file(req->file);
5269 if (unlikely(!sock))
5272 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5276 msg.msg_name = NULL;
5277 msg.msg_control = NULL;
5278 msg.msg_controllen = 0;
5279 msg.msg_namelen = 0;
5281 flags = req->sr_msg.msg_flags;
5282 if (issue_flags & IO_URING_F_NONBLOCK)
5283 flags |= MSG_DONTWAIT;
5284 if (flags & MSG_WAITALL)
5285 min_ret = iov_iter_count(&msg.msg_iter);
5287 msg.msg_flags = flags;
5288 ret = sock_sendmsg(sock, &msg);
5289 if (ret < min_ret) {
5290 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5292 if (ret == -ERESTARTSYS)
5296 __io_req_complete(req, issue_flags, ret, 0);
5300 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5301 struct io_async_msghdr *iomsg)
5303 struct io_sr_msg *sr = &req->sr_msg;
5304 struct iovec __user *uiov;
5308 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5309 &iomsg->uaddr, &uiov, &iov_len);
5313 if (req->flags & REQ_F_BUFFER_SELECT) {
5316 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5318 sr->len = iomsg->fast_iov[0].iov_len;
5319 iomsg->free_iov = NULL;
5321 iomsg->free_iov = iomsg->fast_iov;
5322 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5323 &iomsg->free_iov, &iomsg->msg.msg_iter,
5332 #ifdef CONFIG_COMPAT
5333 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5334 struct io_async_msghdr *iomsg)
5336 struct io_sr_msg *sr = &req->sr_msg;
5337 struct compat_iovec __user *uiov;
5342 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5347 uiov = compat_ptr(ptr);
5348 if (req->flags & REQ_F_BUFFER_SELECT) {
5349 compat_ssize_t clen;
5353 if (!access_ok(uiov, sizeof(*uiov)))
5355 if (__get_user(clen, &uiov->iov_len))
5360 iomsg->free_iov = NULL;
5362 iomsg->free_iov = iomsg->fast_iov;
5363 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5364 UIO_FASTIOV, &iomsg->free_iov,
5365 &iomsg->msg.msg_iter, true);
5374 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5375 struct io_async_msghdr *iomsg)
5377 iomsg->msg.msg_name = &iomsg->addr;
5379 #ifdef CONFIG_COMPAT
5380 if (req->ctx->compat)
5381 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5384 return __io_recvmsg_copy_hdr(req, iomsg);
5387 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5388 unsigned int issue_flags)
5390 struct io_sr_msg *sr = &req->sr_msg;
5392 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5395 static int io_recvmsg_prep_async(struct io_kiocb *req)
5399 ret = io_recvmsg_copy_hdr(req, req->async_data);
5401 req->flags |= REQ_F_NEED_CLEANUP;
5405 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5407 struct io_sr_msg *sr = &req->sr_msg;
5409 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5412 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5413 sr->len = READ_ONCE(sqe->len);
5414 sr->bgid = READ_ONCE(sqe->buf_group);
5415 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5416 if (sr->msg_flags & MSG_DONTWAIT)
5417 req->flags |= REQ_F_NOWAIT;
5419 #ifdef CONFIG_COMPAT
5420 if (req->ctx->compat)
5421 sr->msg_flags |= MSG_CMSG_COMPAT;
5427 static bool io_net_retry(struct socket *sock, int flags)
5429 if (!(flags & MSG_WAITALL))
5431 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5434 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5436 struct io_async_msghdr iomsg, *kmsg;
5437 struct io_sr_msg *sr = &req->sr_msg;
5438 struct socket *sock;
5439 struct io_buffer *kbuf;
5441 int ret, min_ret = 0;
5442 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5444 sock = sock_from_file(req->file);
5445 if (unlikely(!sock))
5448 if (req_has_async_data(req)) {
5449 kmsg = req->async_data;
5451 ret = io_recvmsg_copy_hdr(req, &iomsg);
5457 if (req->flags & REQ_F_BUFFER_SELECT) {
5458 kbuf = io_recv_buffer_select(req, issue_flags);
5460 return PTR_ERR(kbuf);
5461 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5462 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5463 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5464 1, req->sr_msg.len);
5467 flags = req->sr_msg.msg_flags;
5469 flags |= MSG_DONTWAIT;
5470 if (flags & MSG_WAITALL)
5471 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5473 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5474 kmsg->uaddr, flags);
5475 if (ret < min_ret) {
5476 if (ret == -EAGAIN && force_nonblock)
5477 return io_setup_async_msg(req, kmsg);
5478 if (ret == -ERESTARTSYS)
5480 if (ret > 0 && io_net_retry(sock, flags)) {
5482 req->flags |= REQ_F_PARTIAL_IO;
5483 return io_setup_async_msg(req, kmsg);
5486 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5490 /* fast path, check for non-NULL to avoid function call */
5492 kfree(kmsg->free_iov);
5493 req->flags &= ~REQ_F_NEED_CLEANUP;
5496 else if (sr->done_io)
5498 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5502 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5504 struct io_buffer *kbuf;
5505 struct io_sr_msg *sr = &req->sr_msg;
5507 void __user *buf = sr->buf;
5508 struct socket *sock;
5511 int ret, min_ret = 0;
5512 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5514 sock = sock_from_file(req->file);
5515 if (unlikely(!sock))
5518 if (req->flags & REQ_F_BUFFER_SELECT) {
5519 kbuf = io_recv_buffer_select(req, issue_flags);
5521 return PTR_ERR(kbuf);
5522 buf = u64_to_user_ptr(kbuf->addr);
5525 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5529 msg.msg_name = NULL;
5530 msg.msg_control = NULL;
5531 msg.msg_controllen = 0;
5532 msg.msg_namelen = 0;
5533 msg.msg_iocb = NULL;
5536 flags = req->sr_msg.msg_flags;
5538 flags |= MSG_DONTWAIT;
5539 if (flags & MSG_WAITALL)
5540 min_ret = iov_iter_count(&msg.msg_iter);
5542 ret = sock_recvmsg(sock, &msg, flags);
5543 if (ret < min_ret) {
5544 if (ret == -EAGAIN && force_nonblock)
5546 if (ret == -ERESTARTSYS)
5548 if (ret > 0 && io_net_retry(sock, flags)) {
5552 req->flags |= REQ_F_PARTIAL_IO;
5556 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5563 else if (sr->done_io)
5565 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5569 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5571 struct io_accept *accept = &req->accept;
5573 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5575 if (sqe->ioprio || sqe->len || sqe->buf_index)
5578 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5579 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5580 accept->flags = READ_ONCE(sqe->accept_flags);
5581 accept->nofile = rlimit(RLIMIT_NOFILE);
5583 accept->file_slot = READ_ONCE(sqe->file_index);
5584 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5586 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5588 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5589 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5593 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5595 struct io_accept *accept = &req->accept;
5596 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5597 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5598 bool fixed = !!accept->file_slot;
5603 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5604 if (unlikely(fd < 0))
5607 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5612 ret = PTR_ERR(file);
5613 if (ret == -EAGAIN && force_nonblock)
5615 if (ret == -ERESTARTSYS)
5618 } else if (!fixed) {
5619 fd_install(fd, file);
5622 ret = io_install_fixed_file(req, file, issue_flags,
5623 accept->file_slot - 1);
5625 __io_req_complete(req, issue_flags, ret, 0);
5629 static int io_connect_prep_async(struct io_kiocb *req)
5631 struct io_async_connect *io = req->async_data;
5632 struct io_connect *conn = &req->connect;
5634 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5637 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5639 struct io_connect *conn = &req->connect;
5641 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5643 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5647 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5648 conn->addr_len = READ_ONCE(sqe->addr2);
5652 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5654 struct io_async_connect __io, *io;
5655 unsigned file_flags;
5657 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5659 if (req_has_async_data(req)) {
5660 io = req->async_data;
5662 ret = move_addr_to_kernel(req->connect.addr,
5663 req->connect.addr_len,
5670 file_flags = force_nonblock ? O_NONBLOCK : 0;
5672 ret = __sys_connect_file(req->file, &io->address,
5673 req->connect.addr_len, file_flags);
5674 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5675 if (req_has_async_data(req))
5677 if (io_alloc_async_data(req)) {
5681 memcpy(req->async_data, &__io, sizeof(__io));
5684 if (ret == -ERESTARTSYS)
5689 __io_req_complete(req, issue_flags, ret, 0);
5692 #else /* !CONFIG_NET */
5693 #define IO_NETOP_FN(op) \
5694 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5696 return -EOPNOTSUPP; \
5699 #define IO_NETOP_PREP(op) \
5701 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5703 return -EOPNOTSUPP; \
5706 #define IO_NETOP_PREP_ASYNC(op) \
5708 static int io_##op##_prep_async(struct io_kiocb *req) \
5710 return -EOPNOTSUPP; \
5713 IO_NETOP_PREP_ASYNC(sendmsg);
5714 IO_NETOP_PREP_ASYNC(recvmsg);
5715 IO_NETOP_PREP_ASYNC(connect);
5716 IO_NETOP_PREP(accept);
5719 #endif /* CONFIG_NET */
5721 struct io_poll_table {
5722 struct poll_table_struct pt;
5723 struct io_kiocb *req;
5728 #define IO_POLL_CANCEL_FLAG BIT(31)
5729 #define IO_POLL_REF_MASK GENMASK(30, 0)
5732 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5733 * bump it and acquire ownership. It's disallowed to modify requests while not
5734 * owning it, that prevents from races for enqueueing task_work's and b/w
5735 * arming poll and wakeups.
5737 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5739 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5742 static void io_poll_mark_cancelled(struct io_kiocb *req)
5744 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5747 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5749 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5750 if (req->opcode == IORING_OP_POLL_ADD)
5751 return req->async_data;
5752 return req->apoll->double_poll;
5755 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5757 if (req->opcode == IORING_OP_POLL_ADD)
5759 return &req->apoll->poll;
5762 static void io_poll_req_insert(struct io_kiocb *req)
5764 struct io_ring_ctx *ctx = req->ctx;
5765 struct hlist_head *list;
5767 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5768 hlist_add_head(&req->hash_node, list);
5771 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5772 wait_queue_func_t wake_func)
5775 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5776 /* mask in events that we always want/need */
5777 poll->events = events | IO_POLL_UNMASK;
5778 INIT_LIST_HEAD(&poll->wait.entry);
5779 init_waitqueue_func_entry(&poll->wait, wake_func);
5782 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5784 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5787 spin_lock_irq(&head->lock);
5788 list_del_init(&poll->wait.entry);
5790 spin_unlock_irq(&head->lock);
5794 static void io_poll_remove_entries(struct io_kiocb *req)
5797 * Nothing to do if neither of those flags are set. Avoid dipping
5798 * into the poll/apoll/double cachelines if we can.
5800 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5804 * While we hold the waitqueue lock and the waitqueue is nonempty,
5805 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5806 * lock in the first place can race with the waitqueue being freed.
5808 * We solve this as eventpoll does: by taking advantage of the fact that
5809 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5810 * we enter rcu_read_lock() and see that the pointer to the queue is
5811 * non-NULL, we can then lock it without the memory being freed out from
5814 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5815 * case the caller deletes the entry from the queue, leaving it empty.
5816 * In that case, only RCU prevents the queue memory from being freed.
5819 if (req->flags & REQ_F_SINGLE_POLL)
5820 io_poll_remove_entry(io_poll_get_single(req));
5821 if (req->flags & REQ_F_DOUBLE_POLL)
5822 io_poll_remove_entry(io_poll_get_double(req));
5827 * All poll tw should go through this. Checks for poll events, manages
5828 * references, does rewait, etc.
5830 * Returns a negative error on failure. >0 when no action require, which is
5831 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5832 * the request, then the mask is stored in req->result.
5834 static int io_poll_check_events(struct io_kiocb *req, bool locked)
5836 struct io_ring_ctx *ctx = req->ctx;
5837 struct io_poll_iocb *poll = io_poll_get_single(req);
5840 /* req->task == current here, checking PF_EXITING is safe */
5841 if (unlikely(req->task->flags & PF_EXITING))
5842 io_poll_mark_cancelled(req);
5845 v = atomic_read(&req->poll_refs);
5847 /* tw handler should be the owner, and so have some references */
5848 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5850 if (v & IO_POLL_CANCEL_FLAG)
5854 struct poll_table_struct pt = { ._key = req->cflags };
5856 if (unlikely(!io_assign_file(req, IO_URING_F_UNLOCKED)))
5857 req->result = -EBADF;
5859 req->result = vfs_poll(req->file, &pt) & req->cflags;
5862 /* multishot, just fill an CQE and proceed */
5863 if (req->result && !(req->cflags & EPOLLONESHOT)) {
5864 __poll_t mask = mangle_poll(req->result & poll->events);
5867 spin_lock(&ctx->completion_lock);
5868 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5870 io_commit_cqring(ctx);
5871 spin_unlock(&ctx->completion_lock);
5872 if (unlikely(!filled))
5874 io_cqring_ev_posted(ctx);
5875 } else if (req->result) {
5880 * Release all references, retry if someone tried to restart
5881 * task_work while we were executing it.
5883 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5888 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5890 struct io_ring_ctx *ctx = req->ctx;
5893 ret = io_poll_check_events(req, *locked);
5898 req->result = mangle_poll(req->result & req->poll.events);
5904 io_poll_remove_entries(req);
5905 spin_lock(&ctx->completion_lock);
5906 hash_del(&req->hash_node);
5907 __io_req_complete_post(req, req->result, 0);
5908 io_commit_cqring(ctx);
5909 spin_unlock(&ctx->completion_lock);
5910 io_cqring_ev_posted(ctx);
5913 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5915 struct io_ring_ctx *ctx = req->ctx;
5918 ret = io_poll_check_events(req, *locked);
5922 io_poll_remove_entries(req);
5923 spin_lock(&ctx->completion_lock);
5924 hash_del(&req->hash_node);
5925 spin_unlock(&ctx->completion_lock);
5928 io_req_task_submit(req, locked);
5930 io_req_complete_failed(req, ret);
5933 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
5937 * This is useful for poll that is armed on behalf of another
5938 * request, and where the wakeup path could be on a different
5939 * CPU. We want to avoid pulling in req->apoll->events for that
5942 req->cflags = events;
5943 if (req->opcode == IORING_OP_POLL_ADD)
5944 req->io_task_work.func = io_poll_task_func;
5946 req->io_task_work.func = io_apoll_task_func;
5948 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
5949 io_req_task_work_add(req, false);
5952 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
5954 if (io_poll_get_ownership(req))
5955 __io_poll_execute(req, res, events);
5958 static void io_poll_cancel_req(struct io_kiocb *req)
5960 io_poll_mark_cancelled(req);
5961 /* kick tw, which should complete the request */
5962 io_poll_execute(req, 0, 0);
5965 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
5966 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
5968 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5971 struct io_kiocb *req = wqe_to_req(wait);
5972 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5974 __poll_t mask = key_to_poll(key);
5976 if (unlikely(mask & POLLFREE)) {
5977 io_poll_mark_cancelled(req);
5978 /* we have to kick tw in case it's not already */
5979 io_poll_execute(req, 0, poll->events);
5982 * If the waitqueue is being freed early but someone is already
5983 * holds ownership over it, we have to tear down the request as
5984 * best we can. That means immediately removing the request from
5985 * its waitqueue and preventing all further accesses to the
5986 * waitqueue via the request.
5988 list_del_init(&poll->wait.entry);
5991 * Careful: this *must* be the last step, since as soon
5992 * as req->head is NULL'ed out, the request can be
5993 * completed and freed, since aio_poll_complete_work()
5994 * will no longer need to take the waitqueue lock.
5996 smp_store_release(&poll->head, NULL);
6000 /* for instances that support it check for an event match first */
6001 if (mask && !(mask & poll->events))
6004 if (io_poll_get_ownership(req)) {
6005 /* optional, saves extra locking for removal in tw handler */
6006 if (mask && poll->events & EPOLLONESHOT) {
6007 list_del_init(&poll->wait.entry);
6009 if (wqe_is_double(wait))
6010 req->flags &= ~REQ_F_DOUBLE_POLL;
6012 req->flags &= ~REQ_F_SINGLE_POLL;
6014 __io_poll_execute(req, mask, poll->events);
6019 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6020 struct wait_queue_head *head,
6021 struct io_poll_iocb **poll_ptr)
6023 struct io_kiocb *req = pt->req;
6024 unsigned long wqe_private = (unsigned long) req;
6027 * The file being polled uses multiple waitqueues for poll handling
6028 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6031 if (unlikely(pt->nr_entries)) {
6032 struct io_poll_iocb *first = poll;
6034 /* double add on the same waitqueue head, ignore */
6035 if (first->head == head)
6037 /* already have a 2nd entry, fail a third attempt */
6039 if ((*poll_ptr)->head == head)
6041 pt->error = -EINVAL;
6045 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6047 pt->error = -ENOMEM;
6050 /* mark as double wq entry */
6052 req->flags |= REQ_F_DOUBLE_POLL;
6053 io_init_poll_iocb(poll, first->events, first->wait.func);
6055 if (req->opcode == IORING_OP_POLL_ADD)
6056 req->flags |= REQ_F_ASYNC_DATA;
6059 req->flags |= REQ_F_SINGLE_POLL;
6062 poll->wait.private = (void *) wqe_private;
6064 if (poll->events & EPOLLEXCLUSIVE)
6065 add_wait_queue_exclusive(head, &poll->wait);
6067 add_wait_queue(head, &poll->wait);
6070 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6071 struct poll_table_struct *p)
6073 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6075 __io_queue_proc(&pt->req->poll, pt, head,
6076 (struct io_poll_iocb **) &pt->req->async_data);
6079 static int __io_arm_poll_handler(struct io_kiocb *req,
6080 struct io_poll_iocb *poll,
6081 struct io_poll_table *ipt, __poll_t mask)
6083 struct io_ring_ctx *ctx = req->ctx;
6086 INIT_HLIST_NODE(&req->hash_node);
6087 io_init_poll_iocb(poll, mask, io_poll_wake);
6088 poll->file = req->file;
6090 ipt->pt._key = mask;
6093 ipt->nr_entries = 0;
6096 * Take the ownership to delay any tw execution up until we're done
6097 * with poll arming. see io_poll_get_ownership().
6099 atomic_set(&req->poll_refs, 1);
6100 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6102 if (mask && (poll->events & EPOLLONESHOT)) {
6103 io_poll_remove_entries(req);
6104 /* no one else has access to the req, forget about the ref */
6107 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6108 io_poll_remove_entries(req);
6110 ipt->error = -EINVAL;
6114 spin_lock(&ctx->completion_lock);
6115 io_poll_req_insert(req);
6116 spin_unlock(&ctx->completion_lock);
6119 /* can't multishot if failed, just queue the event we've got */
6120 if (unlikely(ipt->error || !ipt->nr_entries))
6121 poll->events |= EPOLLONESHOT;
6122 __io_poll_execute(req, mask, poll->events);
6127 * Release ownership. If someone tried to queue a tw while it was
6128 * locked, kick it off for them.
6130 v = atomic_dec_return(&req->poll_refs);
6131 if (unlikely(v & IO_POLL_REF_MASK))
6132 __io_poll_execute(req, 0, poll->events);
6136 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6137 struct poll_table_struct *p)
6139 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6140 struct async_poll *apoll = pt->req->apoll;
6142 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6151 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6153 const struct io_op_def *def = &io_op_defs[req->opcode];
6154 struct io_ring_ctx *ctx = req->ctx;
6155 struct async_poll *apoll;
6156 struct io_poll_table ipt;
6157 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6160 if (!def->pollin && !def->pollout)
6161 return IO_APOLL_ABORTED;
6162 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6163 return IO_APOLL_ABORTED;
6166 mask |= POLLIN | POLLRDNORM;
6168 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6169 if ((req->opcode == IORING_OP_RECVMSG) &&
6170 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6173 mask |= POLLOUT | POLLWRNORM;
6175 if (def->poll_exclusive)
6176 mask |= EPOLLEXCLUSIVE;
6177 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6178 !list_empty(&ctx->apoll_cache)) {
6179 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6181 list_del_init(&apoll->poll.wait.entry);
6183 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6184 if (unlikely(!apoll))
6185 return IO_APOLL_ABORTED;
6187 apoll->double_poll = NULL;
6189 req->flags |= REQ_F_POLLED;
6190 ipt.pt._qproc = io_async_queue_proc;
6192 io_kbuf_recycle(req, issue_flags);
6194 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6195 if (ret || ipt.error)
6196 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6198 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6199 mask, apoll->poll.events);
6204 * Returns true if we found and killed one or more poll requests
6206 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6207 struct task_struct *tsk, bool cancel_all)
6209 struct hlist_node *tmp;
6210 struct io_kiocb *req;
6214 spin_lock(&ctx->completion_lock);
6215 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6216 struct hlist_head *list;
6218 list = &ctx->cancel_hash[i];
6219 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6220 if (io_match_task_safe(req, tsk, cancel_all)) {
6221 hlist_del_init(&req->hash_node);
6222 io_poll_cancel_req(req);
6227 spin_unlock(&ctx->completion_lock);
6231 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6233 __must_hold(&ctx->completion_lock)
6235 struct hlist_head *list;
6236 struct io_kiocb *req;
6238 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6239 hlist_for_each_entry(req, list, hash_node) {
6240 if (sqe_addr != req->user_data)
6242 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6249 static bool io_poll_disarm(struct io_kiocb *req)
6250 __must_hold(&ctx->completion_lock)
6252 if (!io_poll_get_ownership(req))
6254 io_poll_remove_entries(req);
6255 hash_del(&req->hash_node);
6259 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6261 __must_hold(&ctx->completion_lock)
6263 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6267 io_poll_cancel_req(req);
6271 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6276 events = READ_ONCE(sqe->poll32_events);
6278 events = swahw32(events);
6280 if (!(flags & IORING_POLL_ADD_MULTI))
6281 events |= EPOLLONESHOT;
6282 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6285 static int io_poll_update_prep(struct io_kiocb *req,
6286 const struct io_uring_sqe *sqe)
6288 struct io_poll_update *upd = &req->poll_update;
6291 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6293 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6295 flags = READ_ONCE(sqe->len);
6296 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6297 IORING_POLL_ADD_MULTI))
6299 /* meaningless without update */
6300 if (flags == IORING_POLL_ADD_MULTI)
6303 upd->old_user_data = READ_ONCE(sqe->addr);
6304 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6305 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6307 upd->new_user_data = READ_ONCE(sqe->off);
6308 if (!upd->update_user_data && upd->new_user_data)
6310 if (upd->update_events)
6311 upd->events = io_poll_parse_events(sqe, flags);
6312 else if (sqe->poll32_events)
6318 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6320 struct io_poll_iocb *poll = &req->poll;
6323 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6325 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6327 flags = READ_ONCE(sqe->len);
6328 if (flags & ~IORING_POLL_ADD_MULTI)
6330 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6333 io_req_set_refcount(req);
6334 req->cflags = poll->events = io_poll_parse_events(sqe, flags);
6338 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6340 struct io_poll_iocb *poll = &req->poll;
6341 struct io_poll_table ipt;
6344 ipt.pt._qproc = io_poll_queue_proc;
6346 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6347 ret = ret ?: ipt.error;
6349 __io_req_complete(req, issue_flags, ret, 0);
6353 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6355 struct io_ring_ctx *ctx = req->ctx;
6356 struct io_kiocb *preq;
6360 spin_lock(&ctx->completion_lock);
6361 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6362 if (!preq || !io_poll_disarm(preq)) {
6363 spin_unlock(&ctx->completion_lock);
6364 ret = preq ? -EALREADY : -ENOENT;
6367 spin_unlock(&ctx->completion_lock);
6369 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6370 /* only mask one event flags, keep behavior flags */
6371 if (req->poll_update.update_events) {
6372 preq->poll.events &= ~0xffff;
6373 preq->poll.events |= req->poll_update.events & 0xffff;
6374 preq->poll.events |= IO_POLL_UNMASK;
6376 if (req->poll_update.update_user_data)
6377 preq->user_data = req->poll_update.new_user_data;
6379 ret2 = io_poll_add(preq, issue_flags);
6380 /* successfully updated, don't complete poll request */
6386 preq->result = -ECANCELED;
6387 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6388 io_req_task_complete(preq, &locked);
6392 /* complete update request, we're done with it */
6393 __io_req_complete(req, issue_flags, ret, 0);
6397 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6399 struct io_timeout_data *data = container_of(timer,
6400 struct io_timeout_data, timer);
6401 struct io_kiocb *req = data->req;
6402 struct io_ring_ctx *ctx = req->ctx;
6403 unsigned long flags;
6405 spin_lock_irqsave(&ctx->timeout_lock, flags);
6406 list_del_init(&req->timeout.list);
6407 atomic_set(&req->ctx->cq_timeouts,
6408 atomic_read(&req->ctx->cq_timeouts) + 1);
6409 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6411 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6414 req->result = -ETIME;
6415 req->io_task_work.func = io_req_task_complete;
6416 io_req_task_work_add(req, false);
6417 return HRTIMER_NORESTART;
6420 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6422 __must_hold(&ctx->timeout_lock)
6424 struct io_timeout_data *io;
6425 struct io_kiocb *req;
6428 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6429 found = user_data == req->user_data;
6434 return ERR_PTR(-ENOENT);
6436 io = req->async_data;
6437 if (hrtimer_try_to_cancel(&io->timer) == -1)
6438 return ERR_PTR(-EALREADY);
6439 list_del_init(&req->timeout.list);
6443 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6444 __must_hold(&ctx->completion_lock)
6445 __must_hold(&ctx->timeout_lock)
6447 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6450 return PTR_ERR(req);
6451 io_req_task_queue_fail(req, -ECANCELED);
6455 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6457 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6458 case IORING_TIMEOUT_BOOTTIME:
6459 return CLOCK_BOOTTIME;
6460 case IORING_TIMEOUT_REALTIME:
6461 return CLOCK_REALTIME;
6463 /* can't happen, vetted at prep time */
6467 return CLOCK_MONOTONIC;
6471 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6472 struct timespec64 *ts, enum hrtimer_mode mode)
6473 __must_hold(&ctx->timeout_lock)
6475 struct io_timeout_data *io;
6476 struct io_kiocb *req;
6479 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6480 found = user_data == req->user_data;
6487 io = req->async_data;
6488 if (hrtimer_try_to_cancel(&io->timer) == -1)
6490 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6491 io->timer.function = io_link_timeout_fn;
6492 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6496 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6497 struct timespec64 *ts, enum hrtimer_mode mode)
6498 __must_hold(&ctx->timeout_lock)
6500 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6501 struct io_timeout_data *data;
6504 return PTR_ERR(req);
6506 req->timeout.off = 0; /* noseq */
6507 data = req->async_data;
6508 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6509 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6510 data->timer.function = io_timeout_fn;
6511 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6515 static int io_timeout_remove_prep(struct io_kiocb *req,
6516 const struct io_uring_sqe *sqe)
6518 struct io_timeout_rem *tr = &req->timeout_rem;
6520 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6522 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6524 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6527 tr->ltimeout = false;
6528 tr->addr = READ_ONCE(sqe->addr);
6529 tr->flags = READ_ONCE(sqe->timeout_flags);
6530 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6531 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6533 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6534 tr->ltimeout = true;
6535 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6537 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6539 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6541 } else if (tr->flags) {
6542 /* timeout removal doesn't support flags */
6549 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6551 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6556 * Remove or update an existing timeout command
6558 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6560 struct io_timeout_rem *tr = &req->timeout_rem;
6561 struct io_ring_ctx *ctx = req->ctx;
6564 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6565 spin_lock(&ctx->completion_lock);
6566 spin_lock_irq(&ctx->timeout_lock);
6567 ret = io_timeout_cancel(ctx, tr->addr);
6568 spin_unlock_irq(&ctx->timeout_lock);
6569 spin_unlock(&ctx->completion_lock);
6571 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6573 spin_lock_irq(&ctx->timeout_lock);
6575 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6577 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6578 spin_unlock_irq(&ctx->timeout_lock);
6583 io_req_complete_post(req, ret, 0);
6587 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6588 bool is_timeout_link)
6590 struct io_timeout_data *data;
6592 u32 off = READ_ONCE(sqe->off);
6594 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6596 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6599 if (off && is_timeout_link)
6601 flags = READ_ONCE(sqe->timeout_flags);
6602 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6603 IORING_TIMEOUT_ETIME_SUCCESS))
6605 /* more than one clock specified is invalid, obviously */
6606 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6609 INIT_LIST_HEAD(&req->timeout.list);
6610 req->timeout.off = off;
6611 if (unlikely(off && !req->ctx->off_timeout_used))
6612 req->ctx->off_timeout_used = true;
6614 if (WARN_ON_ONCE(req_has_async_data(req)))
6616 if (io_alloc_async_data(req))
6619 data = req->async_data;
6621 data->flags = flags;
6623 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6626 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6629 INIT_LIST_HEAD(&req->timeout.list);
6630 data->mode = io_translate_timeout_mode(flags);
6631 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6633 if (is_timeout_link) {
6634 struct io_submit_link *link = &req->ctx->submit_state.link;
6638 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6640 req->timeout.head = link->last;
6641 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6646 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6648 struct io_ring_ctx *ctx = req->ctx;
6649 struct io_timeout_data *data = req->async_data;
6650 struct list_head *entry;
6651 u32 tail, off = req->timeout.off;
6653 spin_lock_irq(&ctx->timeout_lock);
6656 * sqe->off holds how many events that need to occur for this
6657 * timeout event to be satisfied. If it isn't set, then this is
6658 * a pure timeout request, sequence isn't used.
6660 if (io_is_timeout_noseq(req)) {
6661 entry = ctx->timeout_list.prev;
6665 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6666 req->timeout.target_seq = tail + off;
6668 /* Update the last seq here in case io_flush_timeouts() hasn't.
6669 * This is safe because ->completion_lock is held, and submissions
6670 * and completions are never mixed in the same ->completion_lock section.
6672 ctx->cq_last_tm_flush = tail;
6675 * Insertion sort, ensuring the first entry in the list is always
6676 * the one we need first.
6678 list_for_each_prev(entry, &ctx->timeout_list) {
6679 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6682 if (io_is_timeout_noseq(nxt))
6684 /* nxt.seq is behind @tail, otherwise would've been completed */
6685 if (off >= nxt->timeout.target_seq - tail)
6689 list_add(&req->timeout.list, entry);
6690 data->timer.function = io_timeout_fn;
6691 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6692 spin_unlock_irq(&ctx->timeout_lock);
6696 struct io_cancel_data {
6697 struct io_ring_ctx *ctx;
6701 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6703 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6704 struct io_cancel_data *cd = data;
6706 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6709 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6710 struct io_ring_ctx *ctx)
6712 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6713 enum io_wq_cancel cancel_ret;
6716 if (!tctx || !tctx->io_wq)
6719 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6720 switch (cancel_ret) {
6721 case IO_WQ_CANCEL_OK:
6724 case IO_WQ_CANCEL_RUNNING:
6727 case IO_WQ_CANCEL_NOTFOUND:
6735 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6737 struct io_ring_ctx *ctx = req->ctx;
6740 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6742 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6744 * Fall-through even for -EALREADY, as we may have poll armed
6745 * that need unarming.
6750 spin_lock(&ctx->completion_lock);
6751 ret = io_poll_cancel(ctx, sqe_addr, false);
6755 spin_lock_irq(&ctx->timeout_lock);
6756 ret = io_timeout_cancel(ctx, sqe_addr);
6757 spin_unlock_irq(&ctx->timeout_lock);
6759 spin_unlock(&ctx->completion_lock);
6763 static int io_async_cancel_prep(struct io_kiocb *req,
6764 const struct io_uring_sqe *sqe)
6766 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6768 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6770 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6774 req->cancel.addr = READ_ONCE(sqe->addr);
6778 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6780 struct io_ring_ctx *ctx = req->ctx;
6781 u64 sqe_addr = req->cancel.addr;
6782 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6783 struct io_tctx_node *node;
6786 ret = io_try_cancel_userdata(req, sqe_addr);
6790 /* slow path, try all io-wq's */
6791 io_ring_submit_lock(ctx, needs_lock);
6793 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6794 struct io_uring_task *tctx = node->task->io_uring;
6796 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6800 io_ring_submit_unlock(ctx, needs_lock);
6804 io_req_complete_post(req, ret, 0);
6808 static int io_rsrc_update_prep(struct io_kiocb *req,
6809 const struct io_uring_sqe *sqe)
6811 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6813 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6816 req->rsrc_update.offset = READ_ONCE(sqe->off);
6817 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6818 if (!req->rsrc_update.nr_args)
6820 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6824 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6826 struct io_ring_ctx *ctx = req->ctx;
6827 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6828 struct io_uring_rsrc_update2 up;
6831 up.offset = req->rsrc_update.offset;
6832 up.data = req->rsrc_update.arg;
6837 io_ring_submit_lock(ctx, needs_lock);
6838 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6839 &up, req->rsrc_update.nr_args);
6840 io_ring_submit_unlock(ctx, needs_lock);
6844 __io_req_complete(req, issue_flags, ret, 0);
6848 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6850 switch (req->opcode) {
6853 case IORING_OP_READV:
6854 case IORING_OP_READ_FIXED:
6855 case IORING_OP_READ:
6856 case IORING_OP_WRITEV:
6857 case IORING_OP_WRITE_FIXED:
6858 case IORING_OP_WRITE:
6859 return io_prep_rw(req, sqe);
6860 case IORING_OP_POLL_ADD:
6861 return io_poll_add_prep(req, sqe);
6862 case IORING_OP_POLL_REMOVE:
6863 return io_poll_update_prep(req, sqe);
6864 case IORING_OP_FSYNC:
6865 return io_fsync_prep(req, sqe);
6866 case IORING_OP_SYNC_FILE_RANGE:
6867 return io_sfr_prep(req, sqe);
6868 case IORING_OP_SENDMSG:
6869 case IORING_OP_SEND:
6870 return io_sendmsg_prep(req, sqe);
6871 case IORING_OP_RECVMSG:
6872 case IORING_OP_RECV:
6873 return io_recvmsg_prep(req, sqe);
6874 case IORING_OP_CONNECT:
6875 return io_connect_prep(req, sqe);
6876 case IORING_OP_TIMEOUT:
6877 return io_timeout_prep(req, sqe, false);
6878 case IORING_OP_TIMEOUT_REMOVE:
6879 return io_timeout_remove_prep(req, sqe);
6880 case IORING_OP_ASYNC_CANCEL:
6881 return io_async_cancel_prep(req, sqe);
6882 case IORING_OP_LINK_TIMEOUT:
6883 return io_timeout_prep(req, sqe, true);
6884 case IORING_OP_ACCEPT:
6885 return io_accept_prep(req, sqe);
6886 case IORING_OP_FALLOCATE:
6887 return io_fallocate_prep(req, sqe);
6888 case IORING_OP_OPENAT:
6889 return io_openat_prep(req, sqe);
6890 case IORING_OP_CLOSE:
6891 return io_close_prep(req, sqe);
6892 case IORING_OP_FILES_UPDATE:
6893 return io_rsrc_update_prep(req, sqe);
6894 case IORING_OP_STATX:
6895 return io_statx_prep(req, sqe);
6896 case IORING_OP_FADVISE:
6897 return io_fadvise_prep(req, sqe);
6898 case IORING_OP_MADVISE:
6899 return io_madvise_prep(req, sqe);
6900 case IORING_OP_OPENAT2:
6901 return io_openat2_prep(req, sqe);
6902 case IORING_OP_EPOLL_CTL:
6903 return io_epoll_ctl_prep(req, sqe);
6904 case IORING_OP_SPLICE:
6905 return io_splice_prep(req, sqe);
6906 case IORING_OP_PROVIDE_BUFFERS:
6907 return io_provide_buffers_prep(req, sqe);
6908 case IORING_OP_REMOVE_BUFFERS:
6909 return io_remove_buffers_prep(req, sqe);
6911 return io_tee_prep(req, sqe);
6912 case IORING_OP_SHUTDOWN:
6913 return io_shutdown_prep(req, sqe);
6914 case IORING_OP_RENAMEAT:
6915 return io_renameat_prep(req, sqe);
6916 case IORING_OP_UNLINKAT:
6917 return io_unlinkat_prep(req, sqe);
6918 case IORING_OP_MKDIRAT:
6919 return io_mkdirat_prep(req, sqe);
6920 case IORING_OP_SYMLINKAT:
6921 return io_symlinkat_prep(req, sqe);
6922 case IORING_OP_LINKAT:
6923 return io_linkat_prep(req, sqe);
6924 case IORING_OP_MSG_RING:
6925 return io_msg_ring_prep(req, sqe);
6928 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6933 static int io_req_prep_async(struct io_kiocb *req)
6935 if (!io_op_defs[req->opcode].needs_async_setup)
6937 if (WARN_ON_ONCE(req_has_async_data(req)))
6939 if (io_alloc_async_data(req))
6942 switch (req->opcode) {
6943 case IORING_OP_READV:
6944 return io_rw_prep_async(req, READ);
6945 case IORING_OP_WRITEV:
6946 return io_rw_prep_async(req, WRITE);
6947 case IORING_OP_SENDMSG:
6948 return io_sendmsg_prep_async(req);
6949 case IORING_OP_RECVMSG:
6950 return io_recvmsg_prep_async(req);
6951 case IORING_OP_CONNECT:
6952 return io_connect_prep_async(req);
6954 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6959 static u32 io_get_sequence(struct io_kiocb *req)
6961 u32 seq = req->ctx->cached_sq_head;
6963 /* need original cached_sq_head, but it was increased for each req */
6964 io_for_each_link(req, req)
6969 static __cold void io_drain_req(struct io_kiocb *req)
6971 struct io_ring_ctx *ctx = req->ctx;
6972 struct io_defer_entry *de;
6974 u32 seq = io_get_sequence(req);
6976 /* Still need defer if there is pending req in defer list. */
6977 spin_lock(&ctx->completion_lock);
6978 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6979 spin_unlock(&ctx->completion_lock);
6981 ctx->drain_active = false;
6982 io_req_task_queue(req);
6985 spin_unlock(&ctx->completion_lock);
6987 ret = io_req_prep_async(req);
6990 io_req_complete_failed(req, ret);
6993 io_prep_async_link(req);
6994 de = kmalloc(sizeof(*de), GFP_KERNEL);
7000 spin_lock(&ctx->completion_lock);
7001 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7002 spin_unlock(&ctx->completion_lock);
7007 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7010 list_add_tail(&de->list, &ctx->defer_list);
7011 spin_unlock(&ctx->completion_lock);
7014 static void io_clean_op(struct io_kiocb *req)
7016 if (req->flags & REQ_F_BUFFER_SELECTED) {
7017 spin_lock(&req->ctx->completion_lock);
7018 io_put_kbuf_comp(req);
7019 spin_unlock(&req->ctx->completion_lock);
7022 if (req->flags & REQ_F_NEED_CLEANUP) {
7023 switch (req->opcode) {
7024 case IORING_OP_READV:
7025 case IORING_OP_READ_FIXED:
7026 case IORING_OP_READ:
7027 case IORING_OP_WRITEV:
7028 case IORING_OP_WRITE_FIXED:
7029 case IORING_OP_WRITE: {
7030 struct io_async_rw *io = req->async_data;
7032 kfree(io->free_iovec);
7035 case IORING_OP_RECVMSG:
7036 case IORING_OP_SENDMSG: {
7037 struct io_async_msghdr *io = req->async_data;
7039 kfree(io->free_iov);
7042 case IORING_OP_OPENAT:
7043 case IORING_OP_OPENAT2:
7044 if (req->open.filename)
7045 putname(req->open.filename);
7047 case IORING_OP_RENAMEAT:
7048 putname(req->rename.oldpath);
7049 putname(req->rename.newpath);
7051 case IORING_OP_UNLINKAT:
7052 putname(req->unlink.filename);
7054 case IORING_OP_MKDIRAT:
7055 putname(req->mkdir.filename);
7057 case IORING_OP_SYMLINKAT:
7058 putname(req->symlink.oldpath);
7059 putname(req->symlink.newpath);
7061 case IORING_OP_LINKAT:
7062 putname(req->hardlink.oldpath);
7063 putname(req->hardlink.newpath);
7065 case IORING_OP_STATX:
7066 if (req->statx.filename)
7067 putname(req->statx.filename);
7071 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7072 kfree(req->apoll->double_poll);
7076 if (req->flags & REQ_F_CREDS)
7077 put_cred(req->creds);
7078 if (req->flags & REQ_F_ASYNC_DATA) {
7079 kfree(req->async_data);
7080 req->async_data = NULL;
7082 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7085 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
7087 if (req->file || !io_op_defs[req->opcode].needs_file)
7090 if (req->flags & REQ_F_FIXED_FILE)
7091 req->file = io_file_get_fixed(req, req->work.fd, issue_flags);
7093 req->file = io_file_get_normal(req, req->work.fd);
7098 req->result = -EBADF;
7102 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7104 const struct cred *creds = NULL;
7107 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7108 creds = override_creds(req->creds);
7110 if (!io_op_defs[req->opcode].audit_skip)
7111 audit_uring_entry(req->opcode);
7112 if (unlikely(!io_assign_file(req, issue_flags)))
7115 switch (req->opcode) {
7117 ret = io_nop(req, issue_flags);
7119 case IORING_OP_READV:
7120 case IORING_OP_READ_FIXED:
7121 case IORING_OP_READ:
7122 ret = io_read(req, issue_flags);
7124 case IORING_OP_WRITEV:
7125 case IORING_OP_WRITE_FIXED:
7126 case IORING_OP_WRITE:
7127 ret = io_write(req, issue_flags);
7129 case IORING_OP_FSYNC:
7130 ret = io_fsync(req, issue_flags);
7132 case IORING_OP_POLL_ADD:
7133 ret = io_poll_add(req, issue_flags);
7135 case IORING_OP_POLL_REMOVE:
7136 ret = io_poll_update(req, issue_flags);
7138 case IORING_OP_SYNC_FILE_RANGE:
7139 ret = io_sync_file_range(req, issue_flags);
7141 case IORING_OP_SENDMSG:
7142 ret = io_sendmsg(req, issue_flags);
7144 case IORING_OP_SEND:
7145 ret = io_send(req, issue_flags);
7147 case IORING_OP_RECVMSG:
7148 ret = io_recvmsg(req, issue_flags);
7150 case IORING_OP_RECV:
7151 ret = io_recv(req, issue_flags);
7153 case IORING_OP_TIMEOUT:
7154 ret = io_timeout(req, issue_flags);
7156 case IORING_OP_TIMEOUT_REMOVE:
7157 ret = io_timeout_remove(req, issue_flags);
7159 case IORING_OP_ACCEPT:
7160 ret = io_accept(req, issue_flags);
7162 case IORING_OP_CONNECT:
7163 ret = io_connect(req, issue_flags);
7165 case IORING_OP_ASYNC_CANCEL:
7166 ret = io_async_cancel(req, issue_flags);
7168 case IORING_OP_FALLOCATE:
7169 ret = io_fallocate(req, issue_flags);
7171 case IORING_OP_OPENAT:
7172 ret = io_openat(req, issue_flags);
7174 case IORING_OP_CLOSE:
7175 ret = io_close(req, issue_flags);
7177 case IORING_OP_FILES_UPDATE:
7178 ret = io_files_update(req, issue_flags);
7180 case IORING_OP_STATX:
7181 ret = io_statx(req, issue_flags);
7183 case IORING_OP_FADVISE:
7184 ret = io_fadvise(req, issue_flags);
7186 case IORING_OP_MADVISE:
7187 ret = io_madvise(req, issue_flags);
7189 case IORING_OP_OPENAT2:
7190 ret = io_openat2(req, issue_flags);
7192 case IORING_OP_EPOLL_CTL:
7193 ret = io_epoll_ctl(req, issue_flags);
7195 case IORING_OP_SPLICE:
7196 ret = io_splice(req, issue_flags);
7198 case IORING_OP_PROVIDE_BUFFERS:
7199 ret = io_provide_buffers(req, issue_flags);
7201 case IORING_OP_REMOVE_BUFFERS:
7202 ret = io_remove_buffers(req, issue_flags);
7205 ret = io_tee(req, issue_flags);
7207 case IORING_OP_SHUTDOWN:
7208 ret = io_shutdown(req, issue_flags);
7210 case IORING_OP_RENAMEAT:
7211 ret = io_renameat(req, issue_flags);
7213 case IORING_OP_UNLINKAT:
7214 ret = io_unlinkat(req, issue_flags);
7216 case IORING_OP_MKDIRAT:
7217 ret = io_mkdirat(req, issue_flags);
7219 case IORING_OP_SYMLINKAT:
7220 ret = io_symlinkat(req, issue_flags);
7222 case IORING_OP_LINKAT:
7223 ret = io_linkat(req, issue_flags);
7225 case IORING_OP_MSG_RING:
7226 ret = io_msg_ring(req, issue_flags);
7233 if (!io_op_defs[req->opcode].audit_skip)
7234 audit_uring_exit(!ret, ret);
7237 revert_creds(creds);
7240 /* If the op doesn't have a file, we're not polling for it */
7241 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7242 io_iopoll_req_issued(req, issue_flags);
7247 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7249 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7251 req = io_put_req_find_next(req);
7252 return req ? &req->work : NULL;
7255 static void io_wq_submit_work(struct io_wq_work *work)
7257 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7258 const struct io_op_def *def = &io_op_defs[req->opcode];
7259 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7260 bool needs_poll = false;
7261 struct io_kiocb *timeout;
7262 int ret = 0, err = -ECANCELED;
7264 /* one will be dropped by ->io_free_work() after returning to io-wq */
7265 if (!(req->flags & REQ_F_REFCOUNT))
7266 __io_req_set_refcount(req, 2);
7270 timeout = io_prep_linked_timeout(req);
7272 io_queue_linked_timeout(timeout);
7274 if (!io_assign_file(req, issue_flags)) {
7276 work->flags |= IO_WQ_WORK_CANCEL;
7279 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7280 if (work->flags & IO_WQ_WORK_CANCEL) {
7281 io_req_task_queue_fail(req, err);
7285 if (req->flags & REQ_F_FORCE_ASYNC) {
7286 bool opcode_poll = def->pollin || def->pollout;
7288 if (opcode_poll && file_can_poll(req->file)) {
7290 issue_flags |= IO_URING_F_NONBLOCK;
7295 ret = io_issue_sqe(req, issue_flags);
7299 * We can get EAGAIN for iopolled IO even though we're
7300 * forcing a sync submission from here, since we can't
7301 * wait for request slots on the block side.
7308 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7310 /* aborted or ready, in either case retry blocking */
7312 issue_flags &= ~IO_URING_F_NONBLOCK;
7315 /* avoid locking problems by failing it from a clean context */
7317 io_req_task_queue_fail(req, ret);
7320 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7323 return &table->files[i];
7326 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7329 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7331 return (struct file *) (slot->file_ptr & FFS_MASK);
7334 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7336 unsigned long file_ptr = (unsigned long) file;
7338 file_ptr |= io_file_get_flags(file);
7339 file_slot->file_ptr = file_ptr;
7342 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
7343 unsigned int issue_flags)
7345 struct io_ring_ctx *ctx = req->ctx;
7346 struct file *file = NULL;
7347 unsigned long file_ptr;
7349 if (issue_flags & IO_URING_F_UNLOCKED)
7350 mutex_lock(&ctx->uring_lock);
7352 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7354 fd = array_index_nospec(fd, ctx->nr_user_files);
7355 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7356 file = (struct file *) (file_ptr & FFS_MASK);
7357 file_ptr &= ~FFS_MASK;
7358 /* mask in overlapping REQ_F and FFS bits */
7359 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7360 io_req_set_rsrc_node(req, ctx, 0);
7362 if (issue_flags & IO_URING_F_UNLOCKED)
7363 mutex_unlock(&ctx->uring_lock);
7368 * Drop the file for requeue operations. Only used of req->file is the
7369 * io_uring descriptor itself.
7371 static void io_drop_inflight_file(struct io_kiocb *req)
7373 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
7376 req->flags &= ~REQ_F_INFLIGHT;
7380 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
7382 struct file *file = fget(fd);
7384 trace_io_uring_file_get(req->ctx, req, req->user_data, fd);
7386 /* we don't allow fixed io_uring files */
7387 if (file && file->f_op == &io_uring_fops)
7388 req->flags |= REQ_F_INFLIGHT;
7392 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7394 struct io_kiocb *prev = req->timeout.prev;
7398 if (!(req->task->flags & PF_EXITING))
7399 ret = io_try_cancel_userdata(req, prev->user_data);
7400 io_req_complete_post(req, ret ?: -ETIME, 0);
7403 io_req_complete_post(req, -ETIME, 0);
7407 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7409 struct io_timeout_data *data = container_of(timer,
7410 struct io_timeout_data, timer);
7411 struct io_kiocb *prev, *req = data->req;
7412 struct io_ring_ctx *ctx = req->ctx;
7413 unsigned long flags;
7415 spin_lock_irqsave(&ctx->timeout_lock, flags);
7416 prev = req->timeout.head;
7417 req->timeout.head = NULL;
7420 * We don't expect the list to be empty, that will only happen if we
7421 * race with the completion of the linked work.
7424 io_remove_next_linked(prev);
7425 if (!req_ref_inc_not_zero(prev))
7428 list_del(&req->timeout.list);
7429 req->timeout.prev = prev;
7430 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7432 req->io_task_work.func = io_req_task_link_timeout;
7433 io_req_task_work_add(req, false);
7434 return HRTIMER_NORESTART;
7437 static void io_queue_linked_timeout(struct io_kiocb *req)
7439 struct io_ring_ctx *ctx = req->ctx;
7441 spin_lock_irq(&ctx->timeout_lock);
7443 * If the back reference is NULL, then our linked request finished
7444 * before we got a chance to setup the timer
7446 if (req->timeout.head) {
7447 struct io_timeout_data *data = req->async_data;
7449 data->timer.function = io_link_timeout_fn;
7450 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7452 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7454 spin_unlock_irq(&ctx->timeout_lock);
7455 /* drop submission reference */
7459 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7460 __must_hold(&req->ctx->uring_lock)
7462 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7464 switch (io_arm_poll_handler(req, 0)) {
7465 case IO_APOLL_READY:
7466 io_req_task_queue(req);
7468 case IO_APOLL_ABORTED:
7470 * Queued up for async execution, worker will release
7471 * submit reference when the iocb is actually submitted.
7473 io_queue_async_work(req, NULL);
7480 io_queue_linked_timeout(linked_timeout);
7483 static inline void __io_queue_sqe(struct io_kiocb *req)
7484 __must_hold(&req->ctx->uring_lock)
7486 struct io_kiocb *linked_timeout;
7489 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7491 if (req->flags & REQ_F_COMPLETE_INLINE) {
7492 io_req_add_compl_list(req);
7496 * We async punt it if the file wasn't marked NOWAIT, or if the file
7497 * doesn't support non-blocking read/write attempts
7500 linked_timeout = io_prep_linked_timeout(req);
7502 io_queue_linked_timeout(linked_timeout);
7503 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7504 io_queue_sqe_arm_apoll(req);
7506 io_req_complete_failed(req, ret);
7510 static void io_queue_sqe_fallback(struct io_kiocb *req)
7511 __must_hold(&req->ctx->uring_lock)
7513 if (req->flags & REQ_F_FAIL) {
7514 io_req_complete_fail_submit(req);
7515 } else if (unlikely(req->ctx->drain_active)) {
7518 int ret = io_req_prep_async(req);
7521 io_req_complete_failed(req, ret);
7523 io_queue_async_work(req, NULL);
7527 static inline void io_queue_sqe(struct io_kiocb *req)
7528 __must_hold(&req->ctx->uring_lock)
7530 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7531 __io_queue_sqe(req);
7533 io_queue_sqe_fallback(req);
7537 * Check SQE restrictions (opcode and flags).
7539 * Returns 'true' if SQE is allowed, 'false' otherwise.
7541 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7542 struct io_kiocb *req,
7543 unsigned int sqe_flags)
7545 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7548 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7549 ctx->restrictions.sqe_flags_required)
7552 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7553 ctx->restrictions.sqe_flags_required))
7559 static void io_init_req_drain(struct io_kiocb *req)
7561 struct io_ring_ctx *ctx = req->ctx;
7562 struct io_kiocb *head = ctx->submit_state.link.head;
7564 ctx->drain_active = true;
7567 * If we need to drain a request in the middle of a link, drain
7568 * the head request and the next request/link after the current
7569 * link. Considering sequential execution of links,
7570 * REQ_F_IO_DRAIN will be maintained for every request of our
7573 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7574 ctx->drain_next = true;
7578 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7579 const struct io_uring_sqe *sqe)
7580 __must_hold(&ctx->uring_lock)
7582 unsigned int sqe_flags;
7586 /* req is partially pre-initialised, see io_preinit_req() */
7587 req->opcode = opcode = READ_ONCE(sqe->opcode);
7588 /* same numerical values with corresponding REQ_F_*, safe to copy */
7589 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7590 req->user_data = READ_ONCE(sqe->user_data);
7592 req->fixed_rsrc_refs = NULL;
7593 req->task = current;
7595 if (unlikely(opcode >= IORING_OP_LAST)) {
7599 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7600 /* enforce forwards compatibility on users */
7601 if (sqe_flags & ~SQE_VALID_FLAGS)
7603 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7604 !io_op_defs[opcode].buffer_select)
7606 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7607 ctx->drain_disabled = true;
7608 if (sqe_flags & IOSQE_IO_DRAIN) {
7609 if (ctx->drain_disabled)
7611 io_init_req_drain(req);
7614 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7615 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7617 /* knock it to the slow queue path, will be drained there */
7618 if (ctx->drain_active)
7619 req->flags |= REQ_F_FORCE_ASYNC;
7620 /* if there is no link, we're at "next" request and need to drain */
7621 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7622 ctx->drain_next = false;
7623 ctx->drain_active = true;
7624 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7628 if (io_op_defs[opcode].needs_file) {
7629 struct io_submit_state *state = &ctx->submit_state;
7631 req->work.fd = READ_ONCE(sqe->fd);
7634 * Plug now if we have more than 2 IO left after this, and the
7635 * target is potentially a read/write to block based storage.
7637 if (state->need_plug && io_op_defs[opcode].plug) {
7638 state->plug_started = true;
7639 state->need_plug = false;
7640 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7644 personality = READ_ONCE(sqe->personality);
7648 req->creds = xa_load(&ctx->personalities, personality);
7651 get_cred(req->creds);
7652 ret = security_uring_override_creds(req->creds);
7654 put_cred(req->creds);
7657 req->flags |= REQ_F_CREDS;
7660 return io_req_prep(req, sqe);
7663 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7664 const struct io_uring_sqe *sqe)
7665 __must_hold(&ctx->uring_lock)
7667 struct io_submit_link *link = &ctx->submit_state.link;
7670 ret = io_init_req(ctx, req, sqe);
7671 if (unlikely(ret)) {
7672 trace_io_uring_req_failed(sqe, ctx, req, ret);
7674 /* fail even hard links since we don't submit */
7677 * we can judge a link req is failed or cancelled by if
7678 * REQ_F_FAIL is set, but the head is an exception since
7679 * it may be set REQ_F_FAIL because of other req's failure
7680 * so let's leverage req->result to distinguish if a head
7681 * is set REQ_F_FAIL because of its failure or other req's
7682 * failure so that we can set the correct ret code for it.
7683 * init result here to avoid affecting the normal path.
7685 if (!(link->head->flags & REQ_F_FAIL))
7686 req_fail_link_node(link->head, -ECANCELED);
7687 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7689 * the current req is a normal req, we should return
7690 * error and thus break the submittion loop.
7692 io_req_complete_failed(req, ret);
7695 req_fail_link_node(req, ret);
7698 /* don't need @sqe from now on */
7699 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7701 ctx->flags & IORING_SETUP_SQPOLL);
7704 * If we already have a head request, queue this one for async
7705 * submittal once the head completes. If we don't have a head but
7706 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7707 * submitted sync once the chain is complete. If none of those
7708 * conditions are true (normal request), then just queue it.
7711 struct io_kiocb *head = link->head;
7713 if (!(req->flags & REQ_F_FAIL)) {
7714 ret = io_req_prep_async(req);
7715 if (unlikely(ret)) {
7716 req_fail_link_node(req, ret);
7717 if (!(head->flags & REQ_F_FAIL))
7718 req_fail_link_node(head, -ECANCELED);
7721 trace_io_uring_link(ctx, req, head);
7722 link->last->link = req;
7725 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7727 /* last request of a link, enqueue the link */
7730 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7741 * Batched submission is done, ensure local IO is flushed out.
7743 static void io_submit_state_end(struct io_ring_ctx *ctx)
7745 struct io_submit_state *state = &ctx->submit_state;
7747 if (state->link.head)
7748 io_queue_sqe(state->link.head);
7749 /* flush only after queuing links as they can generate completions */
7750 io_submit_flush_completions(ctx);
7751 if (state->plug_started)
7752 blk_finish_plug(&state->plug);
7756 * Start submission side cache.
7758 static void io_submit_state_start(struct io_submit_state *state,
7759 unsigned int max_ios)
7761 state->plug_started = false;
7762 state->need_plug = max_ios > 2;
7763 state->submit_nr = max_ios;
7764 /* set only head, no need to init link_last in advance */
7765 state->link.head = NULL;
7768 static void io_commit_sqring(struct io_ring_ctx *ctx)
7770 struct io_rings *rings = ctx->rings;
7773 * Ensure any loads from the SQEs are done at this point,
7774 * since once we write the new head, the application could
7775 * write new data to them.
7777 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7781 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7782 * that is mapped by userspace. This means that care needs to be taken to
7783 * ensure that reads are stable, as we cannot rely on userspace always
7784 * being a good citizen. If members of the sqe are validated and then later
7785 * used, it's important that those reads are done through READ_ONCE() to
7786 * prevent a re-load down the line.
7788 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7790 unsigned head, mask = ctx->sq_entries - 1;
7791 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7794 * The cached sq head (or cq tail) serves two purposes:
7796 * 1) allows us to batch the cost of updating the user visible
7798 * 2) allows the kernel side to track the head on its own, even
7799 * though the application is the one updating it.
7801 head = READ_ONCE(ctx->sq_array[sq_idx]);
7802 if (likely(head < ctx->sq_entries))
7803 return &ctx->sq_sqes[head];
7805 /* drop invalid entries */
7807 WRITE_ONCE(ctx->rings->sq_dropped,
7808 READ_ONCE(ctx->rings->sq_dropped) + 1);
7812 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7813 __must_hold(&ctx->uring_lock)
7815 unsigned int entries = io_sqring_entries(ctx);
7818 if (unlikely(!entries))
7820 /* make sure SQ entry isn't read before tail */
7821 nr = min3(nr, ctx->sq_entries, entries);
7822 io_get_task_refs(nr);
7824 io_submit_state_start(&ctx->submit_state, nr);
7826 const struct io_uring_sqe *sqe;
7827 struct io_kiocb *req;
7829 if (unlikely(!io_alloc_req_refill(ctx))) {
7831 submitted = -EAGAIN;
7834 req = io_alloc_req(ctx);
7835 sqe = io_get_sqe(ctx);
7836 if (unlikely(!sqe)) {
7837 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7840 /* will complete beyond this point, count as submitted */
7842 if (io_submit_sqe(ctx, req, sqe)) {
7844 * Continue submitting even for sqe failure if the
7845 * ring was setup with IORING_SETUP_SUBMIT_ALL
7847 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7850 } while (submitted < nr);
7852 if (unlikely(submitted != nr)) {
7853 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7854 int unused = nr - ref_used;
7856 current->io_uring->cached_refs += unused;
7859 io_submit_state_end(ctx);
7860 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7861 io_commit_sqring(ctx);
7866 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7868 return READ_ONCE(sqd->state);
7871 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7873 /* Tell userspace we may need a wakeup call */
7874 spin_lock(&ctx->completion_lock);
7875 WRITE_ONCE(ctx->rings->sq_flags,
7876 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7877 spin_unlock(&ctx->completion_lock);
7880 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7882 spin_lock(&ctx->completion_lock);
7883 WRITE_ONCE(ctx->rings->sq_flags,
7884 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7885 spin_unlock(&ctx->completion_lock);
7888 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7890 unsigned int to_submit;
7893 to_submit = io_sqring_entries(ctx);
7894 /* if we're handling multiple rings, cap submit size for fairness */
7895 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7896 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7898 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7899 const struct cred *creds = NULL;
7901 if (ctx->sq_creds != current_cred())
7902 creds = override_creds(ctx->sq_creds);
7904 mutex_lock(&ctx->uring_lock);
7905 if (!wq_list_empty(&ctx->iopoll_list))
7906 io_do_iopoll(ctx, true);
7909 * Don't submit if refs are dying, good for io_uring_register(),
7910 * but also it is relied upon by io_ring_exit_work()
7912 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7913 !(ctx->flags & IORING_SETUP_R_DISABLED))
7914 ret = io_submit_sqes(ctx, to_submit);
7915 mutex_unlock(&ctx->uring_lock);
7917 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7918 wake_up(&ctx->sqo_sq_wait);
7920 revert_creds(creds);
7926 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7928 struct io_ring_ctx *ctx;
7929 unsigned sq_thread_idle = 0;
7931 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7932 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7933 sqd->sq_thread_idle = sq_thread_idle;
7936 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7938 bool did_sig = false;
7939 struct ksignal ksig;
7941 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7942 signal_pending(current)) {
7943 mutex_unlock(&sqd->lock);
7944 if (signal_pending(current))
7945 did_sig = get_signal(&ksig);
7947 mutex_lock(&sqd->lock);
7949 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7952 static int io_sq_thread(void *data)
7954 struct io_sq_data *sqd = data;
7955 struct io_ring_ctx *ctx;
7956 unsigned long timeout = 0;
7957 char buf[TASK_COMM_LEN];
7960 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7961 set_task_comm(current, buf);
7963 if (sqd->sq_cpu != -1)
7964 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7966 set_cpus_allowed_ptr(current, cpu_online_mask);
7967 current->flags |= PF_NO_SETAFFINITY;
7969 audit_alloc_kernel(current);
7971 mutex_lock(&sqd->lock);
7973 bool cap_entries, sqt_spin = false;
7975 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7976 if (io_sqd_handle_event(sqd))
7978 timeout = jiffies + sqd->sq_thread_idle;
7981 cap_entries = !list_is_singular(&sqd->ctx_list);
7982 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7983 int ret = __io_sq_thread(ctx, cap_entries);
7985 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7988 if (io_run_task_work())
7991 if (sqt_spin || !time_after(jiffies, timeout)) {
7994 timeout = jiffies + sqd->sq_thread_idle;
7998 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7999 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8000 bool needs_sched = true;
8002 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8003 io_ring_set_wakeup_flag(ctx);
8005 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8006 !wq_list_empty(&ctx->iopoll_list)) {
8007 needs_sched = false;
8012 * Ensure the store of the wakeup flag is not
8013 * reordered with the load of the SQ tail
8017 if (io_sqring_entries(ctx)) {
8018 needs_sched = false;
8024 mutex_unlock(&sqd->lock);
8026 mutex_lock(&sqd->lock);
8028 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8029 io_ring_clear_wakeup_flag(ctx);
8032 finish_wait(&sqd->wait, &wait);
8033 timeout = jiffies + sqd->sq_thread_idle;
8036 io_uring_cancel_generic(true, sqd);
8038 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8039 io_ring_set_wakeup_flag(ctx);
8041 mutex_unlock(&sqd->lock);
8043 audit_free(current);
8045 complete(&sqd->exited);
8049 struct io_wait_queue {
8050 struct wait_queue_entry wq;
8051 struct io_ring_ctx *ctx;
8053 unsigned nr_timeouts;
8056 static inline bool io_should_wake(struct io_wait_queue *iowq)
8058 struct io_ring_ctx *ctx = iowq->ctx;
8059 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8062 * Wake up if we have enough events, or if a timeout occurred since we
8063 * started waiting. For timeouts, we always want to return to userspace,
8064 * regardless of event count.
8066 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8069 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8070 int wake_flags, void *key)
8072 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8076 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8077 * the task, and the next invocation will do it.
8079 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8080 return autoremove_wake_function(curr, mode, wake_flags, key);
8084 static int io_run_task_work_sig(void)
8086 if (io_run_task_work())
8088 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8089 return -ERESTARTSYS;
8090 if (task_sigpending(current))
8095 /* when returns >0, the caller should retry */
8096 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8097 struct io_wait_queue *iowq,
8102 /* make sure we run task_work before checking for signals */
8103 ret = io_run_task_work_sig();
8104 if (ret || io_should_wake(iowq))
8106 /* let the caller flush overflows, retry */
8107 if (test_bit(0, &ctx->check_cq_overflow))
8110 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8116 * Wait until events become available, if we don't already have some. The
8117 * application must reap them itself, as they reside on the shared cq ring.
8119 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8120 const sigset_t __user *sig, size_t sigsz,
8121 struct __kernel_timespec __user *uts)
8123 struct io_wait_queue iowq;
8124 struct io_rings *rings = ctx->rings;
8125 ktime_t timeout = KTIME_MAX;
8129 io_cqring_overflow_flush(ctx);
8130 if (io_cqring_events(ctx) >= min_events)
8132 if (!io_run_task_work())
8137 #ifdef CONFIG_COMPAT
8138 if (in_compat_syscall())
8139 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8143 ret = set_user_sigmask(sig, sigsz);
8150 struct timespec64 ts;
8152 if (get_timespec64(&ts, uts))
8154 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8157 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8158 iowq.wq.private = current;
8159 INIT_LIST_HEAD(&iowq.wq.entry);
8161 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8162 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8164 trace_io_uring_cqring_wait(ctx, min_events);
8166 /* if we can't even flush overflow, don't wait for more */
8167 if (!io_cqring_overflow_flush(ctx)) {
8171 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8172 TASK_INTERRUPTIBLE);
8173 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8174 finish_wait(&ctx->cq_wait, &iowq.wq);
8178 restore_saved_sigmask_unless(ret == -EINTR);
8180 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8183 static void io_free_page_table(void **table, size_t size)
8185 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8187 for (i = 0; i < nr_tables; i++)
8192 static __cold void **io_alloc_page_table(size_t size)
8194 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8195 size_t init_size = size;
8198 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8202 for (i = 0; i < nr_tables; i++) {
8203 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8205 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8207 io_free_page_table(table, init_size);
8215 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8217 percpu_ref_exit(&ref_node->refs);
8221 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8223 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8224 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8225 unsigned long flags;
8226 bool first_add = false;
8227 unsigned long delay = HZ;
8229 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8232 /* if we are mid-quiesce then do not delay */
8233 if (node->rsrc_data->quiesce)
8236 while (!list_empty(&ctx->rsrc_ref_list)) {
8237 node = list_first_entry(&ctx->rsrc_ref_list,
8238 struct io_rsrc_node, node);
8239 /* recycle ref nodes in order */
8242 list_del(&node->node);
8243 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8245 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8248 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8251 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8253 struct io_rsrc_node *ref_node;
8255 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8259 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8264 INIT_LIST_HEAD(&ref_node->node);
8265 INIT_LIST_HEAD(&ref_node->rsrc_list);
8266 ref_node->done = false;
8270 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8271 struct io_rsrc_data *data_to_kill)
8272 __must_hold(&ctx->uring_lock)
8274 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8275 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8277 io_rsrc_refs_drop(ctx);
8280 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8282 rsrc_node->rsrc_data = data_to_kill;
8283 spin_lock_irq(&ctx->rsrc_ref_lock);
8284 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8285 spin_unlock_irq(&ctx->rsrc_ref_lock);
8287 atomic_inc(&data_to_kill->refs);
8288 percpu_ref_kill(&rsrc_node->refs);
8289 ctx->rsrc_node = NULL;
8292 if (!ctx->rsrc_node) {
8293 ctx->rsrc_node = ctx->rsrc_backup_node;
8294 ctx->rsrc_backup_node = NULL;
8298 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8300 if (ctx->rsrc_backup_node)
8302 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8303 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8306 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8307 struct io_ring_ctx *ctx)
8311 /* As we may drop ->uring_lock, other task may have started quiesce */
8315 data->quiesce = true;
8317 ret = io_rsrc_node_switch_start(ctx);
8320 io_rsrc_node_switch(ctx, data);
8322 /* kill initial ref, already quiesced if zero */
8323 if (atomic_dec_and_test(&data->refs))
8325 mutex_unlock(&ctx->uring_lock);
8326 flush_delayed_work(&ctx->rsrc_put_work);
8327 ret = wait_for_completion_interruptible(&data->done);
8329 mutex_lock(&ctx->uring_lock);
8330 if (atomic_read(&data->refs) > 0) {
8332 * it has been revived by another thread while
8335 mutex_unlock(&ctx->uring_lock);
8341 atomic_inc(&data->refs);
8342 /* wait for all works potentially completing data->done */
8343 flush_delayed_work(&ctx->rsrc_put_work);
8344 reinit_completion(&data->done);
8346 ret = io_run_task_work_sig();
8347 mutex_lock(&ctx->uring_lock);
8349 data->quiesce = false;
8354 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8356 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8357 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8359 return &data->tags[table_idx][off];
8362 static void io_rsrc_data_free(struct io_rsrc_data *data)
8364 size_t size = data->nr * sizeof(data->tags[0][0]);
8367 io_free_page_table((void **)data->tags, size);
8371 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8372 u64 __user *utags, unsigned nr,
8373 struct io_rsrc_data **pdata)
8375 struct io_rsrc_data *data;
8379 data = kzalloc(sizeof(*data), GFP_KERNEL);
8382 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8390 data->do_put = do_put;
8393 for (i = 0; i < nr; i++) {
8394 u64 *tag_slot = io_get_tag_slot(data, i);
8396 if (copy_from_user(tag_slot, &utags[i],
8402 atomic_set(&data->refs, 1);
8403 init_completion(&data->done);
8407 io_rsrc_data_free(data);
8411 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8413 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8414 GFP_KERNEL_ACCOUNT);
8415 return !!table->files;
8418 static void io_free_file_tables(struct io_file_table *table)
8420 kvfree(table->files);
8421 table->files = NULL;
8424 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8426 #if defined(CONFIG_UNIX)
8427 if (ctx->ring_sock) {
8428 struct sock *sock = ctx->ring_sock->sk;
8429 struct sk_buff *skb;
8431 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8437 for (i = 0; i < ctx->nr_user_files; i++) {
8440 file = io_file_from_index(ctx, i);
8445 io_free_file_tables(&ctx->file_table);
8446 io_rsrc_data_free(ctx->file_data);
8447 ctx->file_data = NULL;
8448 ctx->nr_user_files = 0;
8451 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8455 if (!ctx->file_data)
8457 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8459 __io_sqe_files_unregister(ctx);
8463 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8464 __releases(&sqd->lock)
8466 WARN_ON_ONCE(sqd->thread == current);
8469 * Do the dance but not conditional clear_bit() because it'd race with
8470 * other threads incrementing park_pending and setting the bit.
8472 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8473 if (atomic_dec_return(&sqd->park_pending))
8474 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8475 mutex_unlock(&sqd->lock);
8478 static void io_sq_thread_park(struct io_sq_data *sqd)
8479 __acquires(&sqd->lock)
8481 WARN_ON_ONCE(sqd->thread == current);
8483 atomic_inc(&sqd->park_pending);
8484 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8485 mutex_lock(&sqd->lock);
8487 wake_up_process(sqd->thread);
8490 static void io_sq_thread_stop(struct io_sq_data *sqd)
8492 WARN_ON_ONCE(sqd->thread == current);
8493 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8495 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8496 mutex_lock(&sqd->lock);
8498 wake_up_process(sqd->thread);
8499 mutex_unlock(&sqd->lock);
8500 wait_for_completion(&sqd->exited);
8503 static void io_put_sq_data(struct io_sq_data *sqd)
8505 if (refcount_dec_and_test(&sqd->refs)) {
8506 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8508 io_sq_thread_stop(sqd);
8513 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8515 struct io_sq_data *sqd = ctx->sq_data;
8518 io_sq_thread_park(sqd);
8519 list_del_init(&ctx->sqd_list);
8520 io_sqd_update_thread_idle(sqd);
8521 io_sq_thread_unpark(sqd);
8523 io_put_sq_data(sqd);
8524 ctx->sq_data = NULL;
8528 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8530 struct io_ring_ctx *ctx_attach;
8531 struct io_sq_data *sqd;
8534 f = fdget(p->wq_fd);
8536 return ERR_PTR(-ENXIO);
8537 if (f.file->f_op != &io_uring_fops) {
8539 return ERR_PTR(-EINVAL);
8542 ctx_attach = f.file->private_data;
8543 sqd = ctx_attach->sq_data;
8546 return ERR_PTR(-EINVAL);
8548 if (sqd->task_tgid != current->tgid) {
8550 return ERR_PTR(-EPERM);
8553 refcount_inc(&sqd->refs);
8558 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8561 struct io_sq_data *sqd;
8564 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8565 sqd = io_attach_sq_data(p);
8570 /* fall through for EPERM case, setup new sqd/task */
8571 if (PTR_ERR(sqd) != -EPERM)
8575 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8577 return ERR_PTR(-ENOMEM);
8579 atomic_set(&sqd->park_pending, 0);
8580 refcount_set(&sqd->refs, 1);
8581 INIT_LIST_HEAD(&sqd->ctx_list);
8582 mutex_init(&sqd->lock);
8583 init_waitqueue_head(&sqd->wait);
8584 init_completion(&sqd->exited);
8588 #if defined(CONFIG_UNIX)
8590 * Ensure the UNIX gc is aware of our file set, so we are certain that
8591 * the io_uring can be safely unregistered on process exit, even if we have
8592 * loops in the file referencing.
8594 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8596 struct sock *sk = ctx->ring_sock->sk;
8597 struct scm_fp_list *fpl;
8598 struct sk_buff *skb;
8601 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8605 skb = alloc_skb(0, GFP_KERNEL);
8614 fpl->user = get_uid(current_user());
8615 for (i = 0; i < nr; i++) {
8616 struct file *file = io_file_from_index(ctx, i + offset);
8620 fpl->fp[nr_files] = get_file(file);
8621 unix_inflight(fpl->user, fpl->fp[nr_files]);
8626 fpl->max = SCM_MAX_FD;
8627 fpl->count = nr_files;
8628 UNIXCB(skb).fp = fpl;
8629 skb->destructor = unix_destruct_scm;
8630 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8631 skb_queue_head(&sk->sk_receive_queue, skb);
8633 for (i = 0; i < nr; i++) {
8634 struct file *file = io_file_from_index(ctx, i + offset);
8641 free_uid(fpl->user);
8649 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8650 * causes regular reference counting to break down. We rely on the UNIX
8651 * garbage collection to take care of this problem for us.
8653 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8655 unsigned left, total;
8659 left = ctx->nr_user_files;
8661 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8663 ret = __io_sqe_files_scm(ctx, this_files, total);
8667 total += this_files;
8673 while (total < ctx->nr_user_files) {
8674 struct file *file = io_file_from_index(ctx, total);
8684 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8690 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8692 struct file *file = prsrc->file;
8693 #if defined(CONFIG_UNIX)
8694 struct sock *sock = ctx->ring_sock->sk;
8695 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8696 struct sk_buff *skb;
8699 __skb_queue_head_init(&list);
8702 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8703 * remove this entry and rearrange the file array.
8705 skb = skb_dequeue(head);
8707 struct scm_fp_list *fp;
8709 fp = UNIXCB(skb).fp;
8710 for (i = 0; i < fp->count; i++) {
8713 if (fp->fp[i] != file)
8716 unix_notinflight(fp->user, fp->fp[i]);
8717 left = fp->count - 1 - i;
8719 memmove(&fp->fp[i], &fp->fp[i + 1],
8720 left * sizeof(struct file *));
8727 __skb_queue_tail(&list, skb);
8737 __skb_queue_tail(&list, skb);
8739 skb = skb_dequeue(head);
8742 if (skb_peek(&list)) {
8743 spin_lock_irq(&head->lock);
8744 while ((skb = __skb_dequeue(&list)) != NULL)
8745 __skb_queue_tail(head, skb);
8746 spin_unlock_irq(&head->lock);
8753 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8755 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8756 struct io_ring_ctx *ctx = rsrc_data->ctx;
8757 struct io_rsrc_put *prsrc, *tmp;
8759 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8760 list_del(&prsrc->list);
8763 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8765 io_ring_submit_lock(ctx, lock_ring);
8766 spin_lock(&ctx->completion_lock);
8767 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8768 io_commit_cqring(ctx);
8769 spin_unlock(&ctx->completion_lock);
8770 io_cqring_ev_posted(ctx);
8771 io_ring_submit_unlock(ctx, lock_ring);
8774 rsrc_data->do_put(ctx, prsrc);
8778 io_rsrc_node_destroy(ref_node);
8779 if (atomic_dec_and_test(&rsrc_data->refs))
8780 complete(&rsrc_data->done);
8783 static void io_rsrc_put_work(struct work_struct *work)
8785 struct io_ring_ctx *ctx;
8786 struct llist_node *node;
8788 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8789 node = llist_del_all(&ctx->rsrc_put_llist);
8792 struct io_rsrc_node *ref_node;
8793 struct llist_node *next = node->next;
8795 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8796 __io_rsrc_put_work(ref_node);
8801 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8802 unsigned nr_args, u64 __user *tags)
8804 __s32 __user *fds = (__s32 __user *) arg;
8813 if (nr_args > IORING_MAX_FIXED_FILES)
8815 if (nr_args > rlimit(RLIMIT_NOFILE))
8817 ret = io_rsrc_node_switch_start(ctx);
8820 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8826 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8829 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8830 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8834 /* allow sparse sets */
8837 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8844 if (unlikely(!file))
8848 * Don't allow io_uring instances to be registered. If UNIX
8849 * isn't enabled, then this causes a reference cycle and this
8850 * instance can never get freed. If UNIX is enabled we'll
8851 * handle it just fine, but there's still no point in allowing
8852 * a ring fd as it doesn't support regular read/write anyway.
8854 if (file->f_op == &io_uring_fops) {
8858 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8861 ret = io_sqe_files_scm(ctx);
8863 __io_sqe_files_unregister(ctx);
8867 io_rsrc_node_switch(ctx, NULL);
8870 for (i = 0; i < ctx->nr_user_files; i++) {
8871 file = io_file_from_index(ctx, i);
8875 io_free_file_tables(&ctx->file_table);
8876 ctx->nr_user_files = 0;
8878 io_rsrc_data_free(ctx->file_data);
8879 ctx->file_data = NULL;
8883 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8886 #if defined(CONFIG_UNIX)
8887 struct sock *sock = ctx->ring_sock->sk;
8888 struct sk_buff_head *head = &sock->sk_receive_queue;
8889 struct sk_buff *skb;
8892 * See if we can merge this file into an existing skb SCM_RIGHTS
8893 * file set. If there's no room, fall back to allocating a new skb
8894 * and filling it in.
8896 spin_lock_irq(&head->lock);
8897 skb = skb_peek(head);
8899 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8901 if (fpl->count < SCM_MAX_FD) {
8902 __skb_unlink(skb, head);
8903 spin_unlock_irq(&head->lock);
8904 fpl->fp[fpl->count] = get_file(file);
8905 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8907 spin_lock_irq(&head->lock);
8908 __skb_queue_head(head, skb);
8913 spin_unlock_irq(&head->lock);
8920 return __io_sqe_files_scm(ctx, 1, index);
8926 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8927 struct io_rsrc_node *node, void *rsrc)
8929 u64 *tag_slot = io_get_tag_slot(data, idx);
8930 struct io_rsrc_put *prsrc;
8932 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8936 prsrc->tag = *tag_slot;
8939 list_add(&prsrc->list, &node->rsrc_list);
8943 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8944 unsigned int issue_flags, u32 slot_index)
8946 struct io_ring_ctx *ctx = req->ctx;
8947 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8948 bool needs_switch = false;
8949 struct io_fixed_file *file_slot;
8952 io_ring_submit_lock(ctx, needs_lock);
8953 if (file->f_op == &io_uring_fops)
8956 if (!ctx->file_data)
8959 if (slot_index >= ctx->nr_user_files)
8962 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8963 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8965 if (file_slot->file_ptr) {
8966 struct file *old_file;
8968 ret = io_rsrc_node_switch_start(ctx);
8972 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8973 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8974 ctx->rsrc_node, old_file);
8977 file_slot->file_ptr = 0;
8978 needs_switch = true;
8981 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8982 io_fixed_file_set(file_slot, file);
8983 ret = io_sqe_file_register(ctx, file, slot_index);
8985 file_slot->file_ptr = 0;
8992 io_rsrc_node_switch(ctx, ctx->file_data);
8993 io_ring_submit_unlock(ctx, needs_lock);
8999 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9001 unsigned int offset = req->close.file_slot - 1;
9002 struct io_ring_ctx *ctx = req->ctx;
9003 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9004 struct io_fixed_file *file_slot;
9008 io_ring_submit_lock(ctx, needs_lock);
9010 if (unlikely(!ctx->file_data))
9013 if (offset >= ctx->nr_user_files)
9015 ret = io_rsrc_node_switch_start(ctx);
9019 offset = array_index_nospec(offset, ctx->nr_user_files);
9020 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9022 if (!file_slot->file_ptr)
9025 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9026 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9030 file_slot->file_ptr = 0;
9031 io_rsrc_node_switch(ctx, ctx->file_data);
9034 io_ring_submit_unlock(ctx, needs_lock);
9038 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9039 struct io_uring_rsrc_update2 *up,
9042 u64 __user *tags = u64_to_user_ptr(up->tags);
9043 __s32 __user *fds = u64_to_user_ptr(up->data);
9044 struct io_rsrc_data *data = ctx->file_data;
9045 struct io_fixed_file *file_slot;
9049 bool needs_switch = false;
9051 if (!ctx->file_data)
9053 if (up->offset + nr_args > ctx->nr_user_files)
9056 for (done = 0; done < nr_args; done++) {
9059 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9060 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9064 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9068 if (fd == IORING_REGISTER_FILES_SKIP)
9071 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9072 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9074 if (file_slot->file_ptr) {
9075 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9076 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9079 file_slot->file_ptr = 0;
9080 needs_switch = true;
9089 * Don't allow io_uring instances to be registered. If
9090 * UNIX isn't enabled, then this causes a reference
9091 * cycle and this instance can never get freed. If UNIX
9092 * is enabled we'll handle it just fine, but there's
9093 * still no point in allowing a ring fd as it doesn't
9094 * support regular read/write anyway.
9096 if (file->f_op == &io_uring_fops) {
9101 *io_get_tag_slot(data, i) = tag;
9102 io_fixed_file_set(file_slot, file);
9103 err = io_sqe_file_register(ctx, file, i);
9105 file_slot->file_ptr = 0;
9113 io_rsrc_node_switch(ctx, data);
9114 return done ? done : err;
9117 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9118 struct task_struct *task)
9120 struct io_wq_hash *hash;
9121 struct io_wq_data data;
9122 unsigned int concurrency;
9124 mutex_lock(&ctx->uring_lock);
9125 hash = ctx->hash_map;
9127 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9129 mutex_unlock(&ctx->uring_lock);
9130 return ERR_PTR(-ENOMEM);
9132 refcount_set(&hash->refs, 1);
9133 init_waitqueue_head(&hash->wait);
9134 ctx->hash_map = hash;
9136 mutex_unlock(&ctx->uring_lock);
9140 data.free_work = io_wq_free_work;
9141 data.do_work = io_wq_submit_work;
9143 /* Do QD, or 4 * CPUS, whatever is smallest */
9144 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9146 return io_wq_create(concurrency, &data);
9149 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9150 struct io_ring_ctx *ctx)
9152 struct io_uring_task *tctx;
9155 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9156 if (unlikely(!tctx))
9159 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9160 sizeof(struct file *), GFP_KERNEL);
9161 if (unlikely(!tctx->registered_rings)) {
9166 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9167 if (unlikely(ret)) {
9168 kfree(tctx->registered_rings);
9173 tctx->io_wq = io_init_wq_offload(ctx, task);
9174 if (IS_ERR(tctx->io_wq)) {
9175 ret = PTR_ERR(tctx->io_wq);
9176 percpu_counter_destroy(&tctx->inflight);
9177 kfree(tctx->registered_rings);
9183 init_waitqueue_head(&tctx->wait);
9184 atomic_set(&tctx->in_idle, 0);
9185 task->io_uring = tctx;
9186 spin_lock_init(&tctx->task_lock);
9187 INIT_WQ_LIST(&tctx->task_list);
9188 INIT_WQ_LIST(&tctx->prior_task_list);
9189 init_task_work(&tctx->task_work, tctx_task_work);
9193 void __io_uring_free(struct task_struct *tsk)
9195 struct io_uring_task *tctx = tsk->io_uring;
9197 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9198 WARN_ON_ONCE(tctx->io_wq);
9199 WARN_ON_ONCE(tctx->cached_refs);
9201 kfree(tctx->registered_rings);
9202 percpu_counter_destroy(&tctx->inflight);
9204 tsk->io_uring = NULL;
9207 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9208 struct io_uring_params *p)
9212 /* Retain compatibility with failing for an invalid attach attempt */
9213 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9214 IORING_SETUP_ATTACH_WQ) {
9217 f = fdget(p->wq_fd);
9220 if (f.file->f_op != &io_uring_fops) {
9226 if (ctx->flags & IORING_SETUP_SQPOLL) {
9227 struct task_struct *tsk;
9228 struct io_sq_data *sqd;
9231 ret = security_uring_sqpoll();
9235 sqd = io_get_sq_data(p, &attached);
9241 ctx->sq_creds = get_current_cred();
9243 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9244 if (!ctx->sq_thread_idle)
9245 ctx->sq_thread_idle = HZ;
9247 io_sq_thread_park(sqd);
9248 list_add(&ctx->sqd_list, &sqd->ctx_list);
9249 io_sqd_update_thread_idle(sqd);
9250 /* don't attach to a dying SQPOLL thread, would be racy */
9251 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9252 io_sq_thread_unpark(sqd);
9259 if (p->flags & IORING_SETUP_SQ_AFF) {
9260 int cpu = p->sq_thread_cpu;
9263 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9270 sqd->task_pid = current->pid;
9271 sqd->task_tgid = current->tgid;
9272 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9279 ret = io_uring_alloc_task_context(tsk, ctx);
9280 wake_up_new_task(tsk);
9283 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9284 /* Can't have SQ_AFF without SQPOLL */
9291 complete(&ctx->sq_data->exited);
9293 io_sq_thread_finish(ctx);
9297 static inline void __io_unaccount_mem(struct user_struct *user,
9298 unsigned long nr_pages)
9300 atomic_long_sub(nr_pages, &user->locked_vm);
9303 static inline int __io_account_mem(struct user_struct *user,
9304 unsigned long nr_pages)
9306 unsigned long page_limit, cur_pages, new_pages;
9308 /* Don't allow more pages than we can safely lock */
9309 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9312 cur_pages = atomic_long_read(&user->locked_vm);
9313 new_pages = cur_pages + nr_pages;
9314 if (new_pages > page_limit)
9316 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9317 new_pages) != cur_pages);
9322 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9325 __io_unaccount_mem(ctx->user, nr_pages);
9327 if (ctx->mm_account)
9328 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9331 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9336 ret = __io_account_mem(ctx->user, nr_pages);
9341 if (ctx->mm_account)
9342 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9347 static void io_mem_free(void *ptr)
9354 page = virt_to_head_page(ptr);
9355 if (put_page_testzero(page))
9356 free_compound_page(page);
9359 static void *io_mem_alloc(size_t size)
9361 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9363 return (void *) __get_free_pages(gfp, get_order(size));
9366 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9369 struct io_rings *rings;
9370 size_t off, sq_array_size;
9372 off = struct_size(rings, cqes, cq_entries);
9373 if (off == SIZE_MAX)
9377 off = ALIGN(off, SMP_CACHE_BYTES);
9385 sq_array_size = array_size(sizeof(u32), sq_entries);
9386 if (sq_array_size == SIZE_MAX)
9389 if (check_add_overflow(off, sq_array_size, &off))
9395 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9397 struct io_mapped_ubuf *imu = *slot;
9400 if (imu != ctx->dummy_ubuf) {
9401 for (i = 0; i < imu->nr_bvecs; i++)
9402 unpin_user_page(imu->bvec[i].bv_page);
9403 if (imu->acct_pages)
9404 io_unaccount_mem(ctx, imu->acct_pages);
9410 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9412 io_buffer_unmap(ctx, &prsrc->buf);
9416 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9420 for (i = 0; i < ctx->nr_user_bufs; i++)
9421 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9422 kfree(ctx->user_bufs);
9423 io_rsrc_data_free(ctx->buf_data);
9424 ctx->user_bufs = NULL;
9425 ctx->buf_data = NULL;
9426 ctx->nr_user_bufs = 0;
9429 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9436 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9438 __io_sqe_buffers_unregister(ctx);
9442 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9443 void __user *arg, unsigned index)
9445 struct iovec __user *src;
9447 #ifdef CONFIG_COMPAT
9449 struct compat_iovec __user *ciovs;
9450 struct compat_iovec ciov;
9452 ciovs = (struct compat_iovec __user *) arg;
9453 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9456 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9457 dst->iov_len = ciov.iov_len;
9461 src = (struct iovec __user *) arg;
9462 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9468 * Not super efficient, but this is just a registration time. And we do cache
9469 * the last compound head, so generally we'll only do a full search if we don't
9472 * We check if the given compound head page has already been accounted, to
9473 * avoid double accounting it. This allows us to account the full size of the
9474 * page, not just the constituent pages of a huge page.
9476 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9477 int nr_pages, struct page *hpage)
9481 /* check current page array */
9482 for (i = 0; i < nr_pages; i++) {
9483 if (!PageCompound(pages[i]))
9485 if (compound_head(pages[i]) == hpage)
9489 /* check previously registered pages */
9490 for (i = 0; i < ctx->nr_user_bufs; i++) {
9491 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9493 for (j = 0; j < imu->nr_bvecs; j++) {
9494 if (!PageCompound(imu->bvec[j].bv_page))
9496 if (compound_head(imu->bvec[j].bv_page) == hpage)
9504 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9505 int nr_pages, struct io_mapped_ubuf *imu,
9506 struct page **last_hpage)
9510 imu->acct_pages = 0;
9511 for (i = 0; i < nr_pages; i++) {
9512 if (!PageCompound(pages[i])) {
9517 hpage = compound_head(pages[i]);
9518 if (hpage == *last_hpage)
9520 *last_hpage = hpage;
9521 if (headpage_already_acct(ctx, pages, i, hpage))
9523 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9527 if (!imu->acct_pages)
9530 ret = io_account_mem(ctx, imu->acct_pages);
9532 imu->acct_pages = 0;
9536 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9537 struct io_mapped_ubuf **pimu,
9538 struct page **last_hpage)
9540 struct io_mapped_ubuf *imu = NULL;
9541 struct vm_area_struct **vmas = NULL;
9542 struct page **pages = NULL;
9543 unsigned long off, start, end, ubuf;
9545 int ret, pret, nr_pages, i;
9547 if (!iov->iov_base) {
9548 *pimu = ctx->dummy_ubuf;
9552 ubuf = (unsigned long) iov->iov_base;
9553 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9554 start = ubuf >> PAGE_SHIFT;
9555 nr_pages = end - start;
9560 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9564 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9569 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9574 mmap_read_lock(current->mm);
9575 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9577 if (pret == nr_pages) {
9578 /* don't support file backed memory */
9579 for (i = 0; i < nr_pages; i++) {
9580 struct vm_area_struct *vma = vmas[i];
9582 if (vma_is_shmem(vma))
9585 !is_file_hugepages(vma->vm_file)) {
9591 ret = pret < 0 ? pret : -EFAULT;
9593 mmap_read_unlock(current->mm);
9596 * if we did partial map, or found file backed vmas,
9597 * release any pages we did get
9600 unpin_user_pages(pages, pret);
9604 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9606 unpin_user_pages(pages, pret);
9610 off = ubuf & ~PAGE_MASK;
9611 size = iov->iov_len;
9612 for (i = 0; i < nr_pages; i++) {
9615 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9616 imu->bvec[i].bv_page = pages[i];
9617 imu->bvec[i].bv_len = vec_len;
9618 imu->bvec[i].bv_offset = off;
9622 /* store original address for later verification */
9624 imu->ubuf_end = ubuf + iov->iov_len;
9625 imu->nr_bvecs = nr_pages;
9636 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9638 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9639 return ctx->user_bufs ? 0 : -ENOMEM;
9642 static int io_buffer_validate(struct iovec *iov)
9644 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9647 * Don't impose further limits on the size and buffer
9648 * constraints here, we'll -EINVAL later when IO is
9649 * submitted if they are wrong.
9652 return iov->iov_len ? -EFAULT : 0;
9656 /* arbitrary limit, but we need something */
9657 if (iov->iov_len > SZ_1G)
9660 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9666 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9667 unsigned int nr_args, u64 __user *tags)
9669 struct page *last_hpage = NULL;
9670 struct io_rsrc_data *data;
9676 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9678 ret = io_rsrc_node_switch_start(ctx);
9681 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9684 ret = io_buffers_map_alloc(ctx, nr_args);
9686 io_rsrc_data_free(data);
9690 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9691 ret = io_copy_iov(ctx, &iov, arg, i);
9694 ret = io_buffer_validate(&iov);
9697 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9702 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9708 WARN_ON_ONCE(ctx->buf_data);
9710 ctx->buf_data = data;
9712 __io_sqe_buffers_unregister(ctx);
9714 io_rsrc_node_switch(ctx, NULL);
9718 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9719 struct io_uring_rsrc_update2 *up,
9720 unsigned int nr_args)
9722 u64 __user *tags = u64_to_user_ptr(up->tags);
9723 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9724 struct page *last_hpage = NULL;
9725 bool needs_switch = false;
9731 if (up->offset + nr_args > ctx->nr_user_bufs)
9734 for (done = 0; done < nr_args; done++) {
9735 struct io_mapped_ubuf *imu;
9736 int offset = up->offset + done;
9739 err = io_copy_iov(ctx, &iov, iovs, done);
9742 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9746 err = io_buffer_validate(&iov);
9749 if (!iov.iov_base && tag) {
9753 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9757 i = array_index_nospec(offset, ctx->nr_user_bufs);
9758 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9759 err = io_queue_rsrc_removal(ctx->buf_data, i,
9760 ctx->rsrc_node, ctx->user_bufs[i]);
9761 if (unlikely(err)) {
9762 io_buffer_unmap(ctx, &imu);
9765 ctx->user_bufs[i] = NULL;
9766 needs_switch = true;
9769 ctx->user_bufs[i] = imu;
9770 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9774 io_rsrc_node_switch(ctx, ctx->buf_data);
9775 return done ? done : err;
9778 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9779 unsigned int eventfd_async)
9781 struct io_ev_fd *ev_fd;
9782 __s32 __user *fds = arg;
9785 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9786 lockdep_is_held(&ctx->uring_lock));
9790 if (copy_from_user(&fd, fds, sizeof(*fds)))
9793 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9797 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9798 if (IS_ERR(ev_fd->cq_ev_fd)) {
9799 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9803 ev_fd->eventfd_async = eventfd_async;
9804 ctx->has_evfd = true;
9805 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9809 static void io_eventfd_put(struct rcu_head *rcu)
9811 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9813 eventfd_ctx_put(ev_fd->cq_ev_fd);
9817 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9819 struct io_ev_fd *ev_fd;
9821 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9822 lockdep_is_held(&ctx->uring_lock));
9824 ctx->has_evfd = false;
9825 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9826 call_rcu(&ev_fd->rcu, io_eventfd_put);
9833 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9837 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9838 struct list_head *list = &ctx->io_buffers[i];
9840 while (!list_empty(list)) {
9841 struct io_buffer_list *bl;
9843 bl = list_first_entry(list, struct io_buffer_list, list);
9844 __io_remove_buffers(ctx, bl, -1U);
9845 list_del(&bl->list);
9850 while (!list_empty(&ctx->io_buffers_pages)) {
9853 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9854 list_del_init(&page->lru);
9859 static void io_req_caches_free(struct io_ring_ctx *ctx)
9861 struct io_submit_state *state = &ctx->submit_state;
9864 mutex_lock(&ctx->uring_lock);
9865 io_flush_cached_locked_reqs(ctx, state);
9867 while (state->free_list.next) {
9868 struct io_wq_work_node *node;
9869 struct io_kiocb *req;
9871 node = wq_stack_extract(&state->free_list);
9872 req = container_of(node, struct io_kiocb, comp_list);
9873 kmem_cache_free(req_cachep, req);
9877 percpu_ref_put_many(&ctx->refs, nr);
9878 mutex_unlock(&ctx->uring_lock);
9881 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9883 if (data && !atomic_dec_and_test(&data->refs))
9884 wait_for_completion(&data->done);
9887 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
9889 struct async_poll *apoll;
9891 while (!list_empty(&ctx->apoll_cache)) {
9892 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
9894 list_del(&apoll->poll.wait.entry);
9899 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9901 io_sq_thread_finish(ctx);
9903 if (ctx->mm_account) {
9904 mmdrop(ctx->mm_account);
9905 ctx->mm_account = NULL;
9908 io_rsrc_refs_drop(ctx);
9909 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9910 io_wait_rsrc_data(ctx->buf_data);
9911 io_wait_rsrc_data(ctx->file_data);
9913 mutex_lock(&ctx->uring_lock);
9915 __io_sqe_buffers_unregister(ctx);
9917 __io_sqe_files_unregister(ctx);
9919 __io_cqring_overflow_flush(ctx, true);
9920 io_eventfd_unregister(ctx);
9921 io_flush_apoll_cache(ctx);
9922 mutex_unlock(&ctx->uring_lock);
9923 io_destroy_buffers(ctx);
9925 put_cred(ctx->sq_creds);
9927 /* there are no registered resources left, nobody uses it */
9929 io_rsrc_node_destroy(ctx->rsrc_node);
9930 if (ctx->rsrc_backup_node)
9931 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9932 flush_delayed_work(&ctx->rsrc_put_work);
9933 flush_delayed_work(&ctx->fallback_work);
9935 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9936 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9938 #if defined(CONFIG_UNIX)
9939 if (ctx->ring_sock) {
9940 ctx->ring_sock->file = NULL; /* so that iput() is called */
9941 sock_release(ctx->ring_sock);
9944 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9946 io_mem_free(ctx->rings);
9947 io_mem_free(ctx->sq_sqes);
9949 percpu_ref_exit(&ctx->refs);
9950 free_uid(ctx->user);
9951 io_req_caches_free(ctx);
9953 io_wq_put_hash(ctx->hash_map);
9954 kfree(ctx->cancel_hash);
9955 kfree(ctx->dummy_ubuf);
9956 kfree(ctx->io_buffers);
9960 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9962 struct io_ring_ctx *ctx = file->private_data;
9965 poll_wait(file, &ctx->cq_wait, wait);
9967 * synchronizes with barrier from wq_has_sleeper call in
9971 if (!io_sqring_full(ctx))
9972 mask |= EPOLLOUT | EPOLLWRNORM;
9975 * Don't flush cqring overflow list here, just do a simple check.
9976 * Otherwise there could possible be ABBA deadlock:
9979 * lock(&ctx->uring_lock);
9981 * lock(&ctx->uring_lock);
9984 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9985 * pushs them to do the flush.
9987 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9988 mask |= EPOLLIN | EPOLLRDNORM;
9993 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9995 const struct cred *creds;
9997 creds = xa_erase(&ctx->personalities, id);
10006 struct io_tctx_exit {
10007 struct callback_head task_work;
10008 struct completion completion;
10009 struct io_ring_ctx *ctx;
10012 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10014 struct io_uring_task *tctx = current->io_uring;
10015 struct io_tctx_exit *work;
10017 work = container_of(cb, struct io_tctx_exit, task_work);
10019 * When @in_idle, we're in cancellation and it's racy to remove the
10020 * node. It'll be removed by the end of cancellation, just ignore it.
10022 if (!atomic_read(&tctx->in_idle))
10023 io_uring_del_tctx_node((unsigned long)work->ctx);
10024 complete(&work->completion);
10027 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10029 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10031 return req->ctx == data;
10034 static __cold void io_ring_exit_work(struct work_struct *work)
10036 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10037 unsigned long timeout = jiffies + HZ * 60 * 5;
10038 unsigned long interval = HZ / 20;
10039 struct io_tctx_exit exit;
10040 struct io_tctx_node *node;
10044 * If we're doing polled IO and end up having requests being
10045 * submitted async (out-of-line), then completions can come in while
10046 * we're waiting for refs to drop. We need to reap these manually,
10047 * as nobody else will be looking for them.
10050 io_uring_try_cancel_requests(ctx, NULL, true);
10051 if (ctx->sq_data) {
10052 struct io_sq_data *sqd = ctx->sq_data;
10053 struct task_struct *tsk;
10055 io_sq_thread_park(sqd);
10057 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10058 io_wq_cancel_cb(tsk->io_uring->io_wq,
10059 io_cancel_ctx_cb, ctx, true);
10060 io_sq_thread_unpark(sqd);
10063 io_req_caches_free(ctx);
10065 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10066 /* there is little hope left, don't run it too often */
10067 interval = HZ * 60;
10069 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10071 init_completion(&exit.completion);
10072 init_task_work(&exit.task_work, io_tctx_exit_cb);
10075 * Some may use context even when all refs and requests have been put,
10076 * and they are free to do so while still holding uring_lock or
10077 * completion_lock, see io_req_task_submit(). Apart from other work,
10078 * this lock/unlock section also waits them to finish.
10080 mutex_lock(&ctx->uring_lock);
10081 while (!list_empty(&ctx->tctx_list)) {
10082 WARN_ON_ONCE(time_after(jiffies, timeout));
10084 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10086 /* don't spin on a single task if cancellation failed */
10087 list_rotate_left(&ctx->tctx_list);
10088 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10089 if (WARN_ON_ONCE(ret))
10092 mutex_unlock(&ctx->uring_lock);
10093 wait_for_completion(&exit.completion);
10094 mutex_lock(&ctx->uring_lock);
10096 mutex_unlock(&ctx->uring_lock);
10097 spin_lock(&ctx->completion_lock);
10098 spin_unlock(&ctx->completion_lock);
10100 io_ring_ctx_free(ctx);
10103 /* Returns true if we found and killed one or more timeouts */
10104 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10105 struct task_struct *tsk, bool cancel_all)
10107 struct io_kiocb *req, *tmp;
10110 spin_lock(&ctx->completion_lock);
10111 spin_lock_irq(&ctx->timeout_lock);
10112 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10113 if (io_match_task(req, tsk, cancel_all)) {
10114 io_kill_timeout(req, -ECANCELED);
10118 spin_unlock_irq(&ctx->timeout_lock);
10120 io_commit_cqring(ctx);
10121 spin_unlock(&ctx->completion_lock);
10123 io_cqring_ev_posted(ctx);
10124 return canceled != 0;
10127 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10129 unsigned long index;
10130 struct creds *creds;
10132 mutex_lock(&ctx->uring_lock);
10133 percpu_ref_kill(&ctx->refs);
10135 __io_cqring_overflow_flush(ctx, true);
10136 xa_for_each(&ctx->personalities, index, creds)
10137 io_unregister_personality(ctx, index);
10138 mutex_unlock(&ctx->uring_lock);
10140 io_kill_timeouts(ctx, NULL, true);
10141 io_poll_remove_all(ctx, NULL, true);
10143 /* if we failed setting up the ctx, we might not have any rings */
10144 io_iopoll_try_reap_events(ctx);
10146 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10148 * Use system_unbound_wq to avoid spawning tons of event kworkers
10149 * if we're exiting a ton of rings at the same time. It just adds
10150 * noise and overhead, there's no discernable change in runtime
10151 * over using system_wq.
10153 queue_work(system_unbound_wq, &ctx->exit_work);
10156 static int io_uring_release(struct inode *inode, struct file *file)
10158 struct io_ring_ctx *ctx = file->private_data;
10160 file->private_data = NULL;
10161 io_ring_ctx_wait_and_kill(ctx);
10165 struct io_task_cancel {
10166 struct task_struct *task;
10170 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10172 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10173 struct io_task_cancel *cancel = data;
10175 return io_match_task_safe(req, cancel->task, cancel->all);
10178 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10179 struct task_struct *task,
10182 struct io_defer_entry *de;
10185 spin_lock(&ctx->completion_lock);
10186 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10187 if (io_match_task_safe(de->req, task, cancel_all)) {
10188 list_cut_position(&list, &ctx->defer_list, &de->list);
10192 spin_unlock(&ctx->completion_lock);
10193 if (list_empty(&list))
10196 while (!list_empty(&list)) {
10197 de = list_first_entry(&list, struct io_defer_entry, list);
10198 list_del_init(&de->list);
10199 io_req_complete_failed(de->req, -ECANCELED);
10205 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10207 struct io_tctx_node *node;
10208 enum io_wq_cancel cret;
10211 mutex_lock(&ctx->uring_lock);
10212 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10213 struct io_uring_task *tctx = node->task->io_uring;
10216 * io_wq will stay alive while we hold uring_lock, because it's
10217 * killed after ctx nodes, which requires to take the lock.
10219 if (!tctx || !tctx->io_wq)
10221 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10222 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10224 mutex_unlock(&ctx->uring_lock);
10229 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10230 struct task_struct *task,
10233 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10234 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10237 enum io_wq_cancel cret;
10241 ret |= io_uring_try_cancel_iowq(ctx);
10242 } else if (tctx && tctx->io_wq) {
10244 * Cancels requests of all rings, not only @ctx, but
10245 * it's fine as the task is in exit/exec.
10247 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10249 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10252 /* SQPOLL thread does its own polling */
10253 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10254 (ctx->sq_data && ctx->sq_data->thread == current)) {
10255 while (!wq_list_empty(&ctx->iopoll_list)) {
10256 io_iopoll_try_reap_events(ctx);
10261 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10262 ret |= io_poll_remove_all(ctx, task, cancel_all);
10263 ret |= io_kill_timeouts(ctx, task, cancel_all);
10265 ret |= io_run_task_work();
10272 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10274 struct io_uring_task *tctx = current->io_uring;
10275 struct io_tctx_node *node;
10278 if (unlikely(!tctx)) {
10279 ret = io_uring_alloc_task_context(current, ctx);
10283 tctx = current->io_uring;
10284 if (ctx->iowq_limits_set) {
10285 unsigned int limits[2] = { ctx->iowq_limits[0],
10286 ctx->iowq_limits[1], };
10288 ret = io_wq_max_workers(tctx->io_wq, limits);
10293 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10294 node = kmalloc(sizeof(*node), GFP_KERNEL);
10298 node->task = current;
10300 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10301 node, GFP_KERNEL));
10307 mutex_lock(&ctx->uring_lock);
10308 list_add(&node->ctx_node, &ctx->tctx_list);
10309 mutex_unlock(&ctx->uring_lock);
10316 * Note that this task has used io_uring. We use it for cancelation purposes.
10318 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10320 struct io_uring_task *tctx = current->io_uring;
10322 if (likely(tctx && tctx->last == ctx))
10324 return __io_uring_add_tctx_node(ctx);
10328 * Remove this io_uring_file -> task mapping.
10330 static __cold void io_uring_del_tctx_node(unsigned long index)
10332 struct io_uring_task *tctx = current->io_uring;
10333 struct io_tctx_node *node;
10337 node = xa_erase(&tctx->xa, index);
10341 WARN_ON_ONCE(current != node->task);
10342 WARN_ON_ONCE(list_empty(&node->ctx_node));
10344 mutex_lock(&node->ctx->uring_lock);
10345 list_del(&node->ctx_node);
10346 mutex_unlock(&node->ctx->uring_lock);
10348 if (tctx->last == node->ctx)
10353 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10355 struct io_wq *wq = tctx->io_wq;
10356 struct io_tctx_node *node;
10357 unsigned long index;
10359 xa_for_each(&tctx->xa, index, node) {
10360 io_uring_del_tctx_node(index);
10365 * Must be after io_uring_del_tctx_node() (removes nodes under
10366 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10368 io_wq_put_and_exit(wq);
10369 tctx->io_wq = NULL;
10373 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10377 return percpu_counter_sum(&tctx->inflight);
10381 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10382 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10384 static __cold void io_uring_cancel_generic(bool cancel_all,
10385 struct io_sq_data *sqd)
10387 struct io_uring_task *tctx = current->io_uring;
10388 struct io_ring_ctx *ctx;
10392 WARN_ON_ONCE(sqd && sqd->thread != current);
10394 if (!current->io_uring)
10397 io_wq_exit_start(tctx->io_wq);
10399 atomic_inc(&tctx->in_idle);
10401 io_uring_drop_tctx_refs(current);
10402 /* read completions before cancelations */
10403 inflight = tctx_inflight(tctx, !cancel_all);
10408 struct io_tctx_node *node;
10409 unsigned long index;
10411 xa_for_each(&tctx->xa, index, node) {
10412 /* sqpoll task will cancel all its requests */
10413 if (node->ctx->sq_data)
10415 io_uring_try_cancel_requests(node->ctx, current,
10419 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10420 io_uring_try_cancel_requests(ctx, current,
10424 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10425 io_run_task_work();
10426 io_uring_drop_tctx_refs(current);
10429 * If we've seen completions, retry without waiting. This
10430 * avoids a race where a completion comes in before we did
10431 * prepare_to_wait().
10433 if (inflight == tctx_inflight(tctx, !cancel_all))
10435 finish_wait(&tctx->wait, &wait);
10438 io_uring_clean_tctx(tctx);
10441 * We shouldn't run task_works after cancel, so just leave
10442 * ->in_idle set for normal exit.
10444 atomic_dec(&tctx->in_idle);
10445 /* for exec all current's requests should be gone, kill tctx */
10446 __io_uring_free(current);
10450 void __io_uring_cancel(bool cancel_all)
10452 io_uring_cancel_generic(cancel_all, NULL);
10455 void io_uring_unreg_ringfd(void)
10457 struct io_uring_task *tctx = current->io_uring;
10460 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10461 if (tctx->registered_rings[i]) {
10462 fput(tctx->registered_rings[i]);
10463 tctx->registered_rings[i] = NULL;
10468 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10469 int start, int end)
10474 for (offset = start; offset < end; offset++) {
10475 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10476 if (tctx->registered_rings[offset])
10482 } else if (file->f_op != &io_uring_fops) {
10484 return -EOPNOTSUPP;
10486 tctx->registered_rings[offset] = file;
10494 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10495 * invocation. User passes in an array of struct io_uring_rsrc_update
10496 * with ->data set to the ring_fd, and ->offset given for the desired
10497 * index. If no index is desired, application may set ->offset == -1U
10498 * and we'll find an available index. Returns number of entries
10499 * successfully processed, or < 0 on error if none were processed.
10501 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10504 struct io_uring_rsrc_update __user *arg = __arg;
10505 struct io_uring_rsrc_update reg;
10506 struct io_uring_task *tctx;
10509 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10512 mutex_unlock(&ctx->uring_lock);
10513 ret = io_uring_add_tctx_node(ctx);
10514 mutex_lock(&ctx->uring_lock);
10518 tctx = current->io_uring;
10519 for (i = 0; i < nr_args; i++) {
10522 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10527 if (reg.offset == -1U) {
10529 end = IO_RINGFD_REG_MAX;
10531 if (reg.offset >= IO_RINGFD_REG_MAX) {
10535 start = reg.offset;
10539 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10544 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10545 fput(tctx->registered_rings[reg.offset]);
10546 tctx->registered_rings[reg.offset] = NULL;
10552 return i ? i : ret;
10555 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10558 struct io_uring_rsrc_update __user *arg = __arg;
10559 struct io_uring_task *tctx = current->io_uring;
10560 struct io_uring_rsrc_update reg;
10563 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10568 for (i = 0; i < nr_args; i++) {
10569 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10573 if (reg.offset >= IO_RINGFD_REG_MAX) {
10578 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10579 if (tctx->registered_rings[reg.offset]) {
10580 fput(tctx->registered_rings[reg.offset]);
10581 tctx->registered_rings[reg.offset] = NULL;
10585 return i ? i : ret;
10588 static void *io_uring_validate_mmap_request(struct file *file,
10589 loff_t pgoff, size_t sz)
10591 struct io_ring_ctx *ctx = file->private_data;
10592 loff_t offset = pgoff << PAGE_SHIFT;
10597 case IORING_OFF_SQ_RING:
10598 case IORING_OFF_CQ_RING:
10601 case IORING_OFF_SQES:
10602 ptr = ctx->sq_sqes;
10605 return ERR_PTR(-EINVAL);
10608 page = virt_to_head_page(ptr);
10609 if (sz > page_size(page))
10610 return ERR_PTR(-EINVAL);
10617 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10619 size_t sz = vma->vm_end - vma->vm_start;
10623 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10625 return PTR_ERR(ptr);
10627 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10628 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10631 #else /* !CONFIG_MMU */
10633 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10635 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10638 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10640 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10643 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10644 unsigned long addr, unsigned long len,
10645 unsigned long pgoff, unsigned long flags)
10649 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10651 return PTR_ERR(ptr);
10653 return (unsigned long) ptr;
10656 #endif /* !CONFIG_MMU */
10658 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10663 if (!io_sqring_full(ctx))
10665 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10667 if (!io_sqring_full(ctx))
10670 } while (!signal_pending(current));
10672 finish_wait(&ctx->sqo_sq_wait, &wait);
10676 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10677 struct __kernel_timespec __user **ts,
10678 const sigset_t __user **sig)
10680 struct io_uring_getevents_arg arg;
10683 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10684 * is just a pointer to the sigset_t.
10686 if (!(flags & IORING_ENTER_EXT_ARG)) {
10687 *sig = (const sigset_t __user *) argp;
10693 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10694 * timespec and sigset_t pointers if good.
10696 if (*argsz != sizeof(arg))
10698 if (copy_from_user(&arg, argp, sizeof(arg)))
10700 *sig = u64_to_user_ptr(arg.sigmask);
10701 *argsz = arg.sigmask_sz;
10702 *ts = u64_to_user_ptr(arg.ts);
10706 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10707 u32, min_complete, u32, flags, const void __user *, argp,
10710 struct io_ring_ctx *ctx;
10715 io_run_task_work();
10717 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10718 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10719 IORING_ENTER_REGISTERED_RING)))
10723 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10724 * need only dereference our task private array to find it.
10726 if (flags & IORING_ENTER_REGISTERED_RING) {
10727 struct io_uring_task *tctx = current->io_uring;
10729 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10731 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10732 f.file = tctx->registered_rings[fd];
10733 if (unlikely(!f.file))
10737 if (unlikely(!f.file))
10742 if (unlikely(f.file->f_op != &io_uring_fops))
10746 ctx = f.file->private_data;
10747 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10751 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10755 * For SQ polling, the thread will do all submissions and completions.
10756 * Just return the requested submit count, and wake the thread if
10757 * we were asked to.
10760 if (ctx->flags & IORING_SETUP_SQPOLL) {
10761 io_cqring_overflow_flush(ctx);
10763 if (unlikely(ctx->sq_data->thread == NULL)) {
10767 if (flags & IORING_ENTER_SQ_WAKEUP)
10768 wake_up(&ctx->sq_data->wait);
10769 if (flags & IORING_ENTER_SQ_WAIT) {
10770 ret = io_sqpoll_wait_sq(ctx);
10774 submitted = to_submit;
10775 } else if (to_submit) {
10776 ret = io_uring_add_tctx_node(ctx);
10779 mutex_lock(&ctx->uring_lock);
10780 submitted = io_submit_sqes(ctx, to_submit);
10781 mutex_unlock(&ctx->uring_lock);
10783 if (submitted != to_submit)
10786 if (flags & IORING_ENTER_GETEVENTS) {
10787 const sigset_t __user *sig;
10788 struct __kernel_timespec __user *ts;
10790 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10794 min_complete = min(min_complete, ctx->cq_entries);
10797 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10798 * space applications don't need to do io completion events
10799 * polling again, they can rely on io_sq_thread to do polling
10800 * work, which can reduce cpu usage and uring_lock contention.
10802 if (ctx->flags & IORING_SETUP_IOPOLL &&
10803 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10804 ret = io_iopoll_check(ctx, min_complete);
10806 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10811 percpu_ref_put(&ctx->refs);
10813 if (!(flags & IORING_ENTER_REGISTERED_RING))
10815 return submitted ? submitted : ret;
10818 #ifdef CONFIG_PROC_FS
10819 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10820 const struct cred *cred)
10822 struct user_namespace *uns = seq_user_ns(m);
10823 struct group_info *gi;
10828 seq_printf(m, "%5d\n", id);
10829 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10830 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10831 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10832 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10833 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10834 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10835 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10836 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10837 seq_puts(m, "\n\tGroups:\t");
10838 gi = cred->group_info;
10839 for (g = 0; g < gi->ngroups; g++) {
10840 seq_put_decimal_ull(m, g ? " " : "",
10841 from_kgid_munged(uns, gi->gid[g]));
10843 seq_puts(m, "\n\tCapEff:\t");
10844 cap = cred->cap_effective;
10845 CAP_FOR_EACH_U32(__capi)
10846 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10851 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10852 struct seq_file *m)
10854 struct io_sq_data *sq = NULL;
10855 struct io_overflow_cqe *ocqe;
10856 struct io_rings *r = ctx->rings;
10857 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10858 unsigned int sq_head = READ_ONCE(r->sq.head);
10859 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10860 unsigned int cq_head = READ_ONCE(r->cq.head);
10861 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10862 unsigned int sq_entries, cq_entries;
10867 * we may get imprecise sqe and cqe info if uring is actively running
10868 * since we get cached_sq_head and cached_cq_tail without uring_lock
10869 * and sq_tail and cq_head are changed by userspace. But it's ok since
10870 * we usually use these info when it is stuck.
10872 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10873 seq_printf(m, "SqHead:\t%u\n", sq_head);
10874 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10875 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10876 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10877 seq_printf(m, "CqHead:\t%u\n", cq_head);
10878 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10879 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10880 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10881 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10882 for (i = 0; i < sq_entries; i++) {
10883 unsigned int entry = i + sq_head;
10884 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10885 struct io_uring_sqe *sqe;
10887 if (sq_idx > sq_mask)
10889 sqe = &ctx->sq_sqes[sq_idx];
10890 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10891 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10894 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10895 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10896 for (i = 0; i < cq_entries; i++) {
10897 unsigned int entry = i + cq_head;
10898 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10900 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10901 entry & cq_mask, cqe->user_data, cqe->res,
10906 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10907 * since fdinfo case grabs it in the opposite direction of normal use
10908 * cases. If we fail to get the lock, we just don't iterate any
10909 * structures that could be going away outside the io_uring mutex.
10911 has_lock = mutex_trylock(&ctx->uring_lock);
10913 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10919 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10920 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10921 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10922 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10923 struct file *f = io_file_from_index(ctx, i);
10926 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10928 seq_printf(m, "%5u: <none>\n", i);
10930 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10931 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10932 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10933 unsigned int len = buf->ubuf_end - buf->ubuf;
10935 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10937 if (has_lock && !xa_empty(&ctx->personalities)) {
10938 unsigned long index;
10939 const struct cred *cred;
10941 seq_printf(m, "Personalities:\n");
10942 xa_for_each(&ctx->personalities, index, cred)
10943 io_uring_show_cred(m, index, cred);
10946 mutex_unlock(&ctx->uring_lock);
10948 seq_puts(m, "PollList:\n");
10949 spin_lock(&ctx->completion_lock);
10950 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10951 struct hlist_head *list = &ctx->cancel_hash[i];
10952 struct io_kiocb *req;
10954 hlist_for_each_entry(req, list, hash_node)
10955 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10956 task_work_pending(req->task));
10959 seq_puts(m, "CqOverflowList:\n");
10960 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10961 struct io_uring_cqe *cqe = &ocqe->cqe;
10963 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10964 cqe->user_data, cqe->res, cqe->flags);
10968 spin_unlock(&ctx->completion_lock);
10971 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10973 struct io_ring_ctx *ctx = f->private_data;
10975 if (percpu_ref_tryget(&ctx->refs)) {
10976 __io_uring_show_fdinfo(ctx, m);
10977 percpu_ref_put(&ctx->refs);
10982 static const struct file_operations io_uring_fops = {
10983 .release = io_uring_release,
10984 .mmap = io_uring_mmap,
10986 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10987 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10989 .poll = io_uring_poll,
10990 #ifdef CONFIG_PROC_FS
10991 .show_fdinfo = io_uring_show_fdinfo,
10995 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10996 struct io_uring_params *p)
10998 struct io_rings *rings;
10999 size_t size, sq_array_offset;
11001 /* make sure these are sane, as we already accounted them */
11002 ctx->sq_entries = p->sq_entries;
11003 ctx->cq_entries = p->cq_entries;
11005 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11006 if (size == SIZE_MAX)
11009 rings = io_mem_alloc(size);
11013 ctx->rings = rings;
11014 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11015 rings->sq_ring_mask = p->sq_entries - 1;
11016 rings->cq_ring_mask = p->cq_entries - 1;
11017 rings->sq_ring_entries = p->sq_entries;
11018 rings->cq_ring_entries = p->cq_entries;
11020 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11021 if (size == SIZE_MAX) {
11022 io_mem_free(ctx->rings);
11027 ctx->sq_sqes = io_mem_alloc(size);
11028 if (!ctx->sq_sqes) {
11029 io_mem_free(ctx->rings);
11037 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11041 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11045 ret = io_uring_add_tctx_node(ctx);
11050 fd_install(fd, file);
11055 * Allocate an anonymous fd, this is what constitutes the application
11056 * visible backing of an io_uring instance. The application mmaps this
11057 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11058 * we have to tie this fd to a socket for file garbage collection purposes.
11060 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11063 #if defined(CONFIG_UNIX)
11066 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11069 return ERR_PTR(ret);
11072 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11073 O_RDWR | O_CLOEXEC, NULL);
11074 #if defined(CONFIG_UNIX)
11075 if (IS_ERR(file)) {
11076 sock_release(ctx->ring_sock);
11077 ctx->ring_sock = NULL;
11079 ctx->ring_sock->file = file;
11085 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11086 struct io_uring_params __user *params)
11088 struct io_ring_ctx *ctx;
11094 if (entries > IORING_MAX_ENTRIES) {
11095 if (!(p->flags & IORING_SETUP_CLAMP))
11097 entries = IORING_MAX_ENTRIES;
11101 * Use twice as many entries for the CQ ring. It's possible for the
11102 * application to drive a higher depth than the size of the SQ ring,
11103 * since the sqes are only used at submission time. This allows for
11104 * some flexibility in overcommitting a bit. If the application has
11105 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11106 * of CQ ring entries manually.
11108 p->sq_entries = roundup_pow_of_two(entries);
11109 if (p->flags & IORING_SETUP_CQSIZE) {
11111 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11112 * to a power-of-two, if it isn't already. We do NOT impose
11113 * any cq vs sq ring sizing.
11115 if (!p->cq_entries)
11117 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11118 if (!(p->flags & IORING_SETUP_CLAMP))
11120 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11122 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11123 if (p->cq_entries < p->sq_entries)
11126 p->cq_entries = 2 * p->sq_entries;
11129 ctx = io_ring_ctx_alloc(p);
11132 ctx->compat = in_compat_syscall();
11133 if (!capable(CAP_IPC_LOCK))
11134 ctx->user = get_uid(current_user());
11137 * This is just grabbed for accounting purposes. When a process exits,
11138 * the mm is exited and dropped before the files, hence we need to hang
11139 * on to this mm purely for the purposes of being able to unaccount
11140 * memory (locked/pinned vm). It's not used for anything else.
11142 mmgrab(current->mm);
11143 ctx->mm_account = current->mm;
11145 ret = io_allocate_scq_urings(ctx, p);
11149 ret = io_sq_offload_create(ctx, p);
11152 /* always set a rsrc node */
11153 ret = io_rsrc_node_switch_start(ctx);
11156 io_rsrc_node_switch(ctx, NULL);
11158 memset(&p->sq_off, 0, sizeof(p->sq_off));
11159 p->sq_off.head = offsetof(struct io_rings, sq.head);
11160 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11161 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11162 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11163 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11164 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11165 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11167 memset(&p->cq_off, 0, sizeof(p->cq_off));
11168 p->cq_off.head = offsetof(struct io_rings, cq.head);
11169 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11170 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11171 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11172 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11173 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11174 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11176 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11177 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11178 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11179 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11180 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11181 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
11183 if (copy_to_user(params, p, sizeof(*p))) {
11188 file = io_uring_get_file(ctx);
11189 if (IS_ERR(file)) {
11190 ret = PTR_ERR(file);
11195 * Install ring fd as the very last thing, so we don't risk someone
11196 * having closed it before we finish setup
11198 ret = io_uring_install_fd(ctx, file);
11200 /* fput will clean it up */
11205 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11208 io_ring_ctx_wait_and_kill(ctx);
11213 * Sets up an aio uring context, and returns the fd. Applications asks for a
11214 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11215 * params structure passed in.
11217 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11219 struct io_uring_params p;
11222 if (copy_from_user(&p, params, sizeof(p)))
11224 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11229 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11230 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11231 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11232 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11235 return io_uring_create(entries, &p, params);
11238 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11239 struct io_uring_params __user *, params)
11241 return io_uring_setup(entries, params);
11244 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11247 struct io_uring_probe *p;
11251 size = struct_size(p, ops, nr_args);
11252 if (size == SIZE_MAX)
11254 p = kzalloc(size, GFP_KERNEL);
11259 if (copy_from_user(p, arg, size))
11262 if (memchr_inv(p, 0, size))
11265 p->last_op = IORING_OP_LAST - 1;
11266 if (nr_args > IORING_OP_LAST)
11267 nr_args = IORING_OP_LAST;
11269 for (i = 0; i < nr_args; i++) {
11271 if (!io_op_defs[i].not_supported)
11272 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11277 if (copy_to_user(arg, p, size))
11284 static int io_register_personality(struct io_ring_ctx *ctx)
11286 const struct cred *creds;
11290 creds = get_current_cred();
11292 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11293 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11301 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11302 void __user *arg, unsigned int nr_args)
11304 struct io_uring_restriction *res;
11308 /* Restrictions allowed only if rings started disabled */
11309 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11312 /* We allow only a single restrictions registration */
11313 if (ctx->restrictions.registered)
11316 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11319 size = array_size(nr_args, sizeof(*res));
11320 if (size == SIZE_MAX)
11323 res = memdup_user(arg, size);
11325 return PTR_ERR(res);
11329 for (i = 0; i < nr_args; i++) {
11330 switch (res[i].opcode) {
11331 case IORING_RESTRICTION_REGISTER_OP:
11332 if (res[i].register_op >= IORING_REGISTER_LAST) {
11337 __set_bit(res[i].register_op,
11338 ctx->restrictions.register_op);
11340 case IORING_RESTRICTION_SQE_OP:
11341 if (res[i].sqe_op >= IORING_OP_LAST) {
11346 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11348 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11349 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11351 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11352 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11361 /* Reset all restrictions if an error happened */
11363 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11365 ctx->restrictions.registered = true;
11371 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11373 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11376 if (ctx->restrictions.registered)
11377 ctx->restricted = 1;
11379 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11380 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11381 wake_up(&ctx->sq_data->wait);
11385 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11386 struct io_uring_rsrc_update2 *up,
11394 if (check_add_overflow(up->offset, nr_args, &tmp))
11396 err = io_rsrc_node_switch_start(ctx);
11401 case IORING_RSRC_FILE:
11402 return __io_sqe_files_update(ctx, up, nr_args);
11403 case IORING_RSRC_BUFFER:
11404 return __io_sqe_buffers_update(ctx, up, nr_args);
11409 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11412 struct io_uring_rsrc_update2 up;
11416 memset(&up, 0, sizeof(up));
11417 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11419 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11422 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11423 unsigned size, unsigned type)
11425 struct io_uring_rsrc_update2 up;
11427 if (size != sizeof(up))
11429 if (copy_from_user(&up, arg, sizeof(up)))
11431 if (!up.nr || up.resv)
11433 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11436 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11437 unsigned int size, unsigned int type)
11439 struct io_uring_rsrc_register rr;
11441 /* keep it extendible */
11442 if (size != sizeof(rr))
11445 memset(&rr, 0, sizeof(rr));
11446 if (copy_from_user(&rr, arg, size))
11448 if (!rr.nr || rr.resv || rr.resv2)
11452 case IORING_RSRC_FILE:
11453 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11454 rr.nr, u64_to_user_ptr(rr.tags));
11455 case IORING_RSRC_BUFFER:
11456 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11457 rr.nr, u64_to_user_ptr(rr.tags));
11462 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11463 void __user *arg, unsigned len)
11465 struct io_uring_task *tctx = current->io_uring;
11466 cpumask_var_t new_mask;
11469 if (!tctx || !tctx->io_wq)
11472 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11475 cpumask_clear(new_mask);
11476 if (len > cpumask_size())
11477 len = cpumask_size();
11479 if (in_compat_syscall()) {
11480 ret = compat_get_bitmap(cpumask_bits(new_mask),
11481 (const compat_ulong_t __user *)arg,
11482 len * 8 /* CHAR_BIT */);
11484 ret = copy_from_user(new_mask, arg, len);
11488 free_cpumask_var(new_mask);
11492 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11493 free_cpumask_var(new_mask);
11497 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11499 struct io_uring_task *tctx = current->io_uring;
11501 if (!tctx || !tctx->io_wq)
11504 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11507 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11509 __must_hold(&ctx->uring_lock)
11511 struct io_tctx_node *node;
11512 struct io_uring_task *tctx = NULL;
11513 struct io_sq_data *sqd = NULL;
11514 __u32 new_count[2];
11517 if (copy_from_user(new_count, arg, sizeof(new_count)))
11519 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11520 if (new_count[i] > INT_MAX)
11523 if (ctx->flags & IORING_SETUP_SQPOLL) {
11524 sqd = ctx->sq_data;
11527 * Observe the correct sqd->lock -> ctx->uring_lock
11528 * ordering. Fine to drop uring_lock here, we hold
11529 * a ref to the ctx.
11531 refcount_inc(&sqd->refs);
11532 mutex_unlock(&ctx->uring_lock);
11533 mutex_lock(&sqd->lock);
11534 mutex_lock(&ctx->uring_lock);
11536 tctx = sqd->thread->io_uring;
11539 tctx = current->io_uring;
11542 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11544 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11546 ctx->iowq_limits[i] = new_count[i];
11547 ctx->iowq_limits_set = true;
11549 if (tctx && tctx->io_wq) {
11550 ret = io_wq_max_workers(tctx->io_wq, new_count);
11554 memset(new_count, 0, sizeof(new_count));
11558 mutex_unlock(&sqd->lock);
11559 io_put_sq_data(sqd);
11562 if (copy_to_user(arg, new_count, sizeof(new_count)))
11565 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11569 /* now propagate the restriction to all registered users */
11570 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11571 struct io_uring_task *tctx = node->task->io_uring;
11573 if (WARN_ON_ONCE(!tctx->io_wq))
11576 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11577 new_count[i] = ctx->iowq_limits[i];
11578 /* ignore errors, it always returns zero anyway */
11579 (void)io_wq_max_workers(tctx->io_wq, new_count);
11584 mutex_unlock(&sqd->lock);
11585 io_put_sq_data(sqd);
11590 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11591 void __user *arg, unsigned nr_args)
11592 __releases(ctx->uring_lock)
11593 __acquires(ctx->uring_lock)
11598 * We're inside the ring mutex, if the ref is already dying, then
11599 * someone else killed the ctx or is already going through
11600 * io_uring_register().
11602 if (percpu_ref_is_dying(&ctx->refs))
11605 if (ctx->restricted) {
11606 if (opcode >= IORING_REGISTER_LAST)
11608 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11609 if (!test_bit(opcode, ctx->restrictions.register_op))
11614 case IORING_REGISTER_BUFFERS:
11615 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11617 case IORING_UNREGISTER_BUFFERS:
11619 if (arg || nr_args)
11621 ret = io_sqe_buffers_unregister(ctx);
11623 case IORING_REGISTER_FILES:
11624 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11626 case IORING_UNREGISTER_FILES:
11628 if (arg || nr_args)
11630 ret = io_sqe_files_unregister(ctx);
11632 case IORING_REGISTER_FILES_UPDATE:
11633 ret = io_register_files_update(ctx, arg, nr_args);
11635 case IORING_REGISTER_EVENTFD:
11639 ret = io_eventfd_register(ctx, arg, 0);
11641 case IORING_REGISTER_EVENTFD_ASYNC:
11645 ret = io_eventfd_register(ctx, arg, 1);
11647 case IORING_UNREGISTER_EVENTFD:
11649 if (arg || nr_args)
11651 ret = io_eventfd_unregister(ctx);
11653 case IORING_REGISTER_PROBE:
11655 if (!arg || nr_args > 256)
11657 ret = io_probe(ctx, arg, nr_args);
11659 case IORING_REGISTER_PERSONALITY:
11661 if (arg || nr_args)
11663 ret = io_register_personality(ctx);
11665 case IORING_UNREGISTER_PERSONALITY:
11669 ret = io_unregister_personality(ctx, nr_args);
11671 case IORING_REGISTER_ENABLE_RINGS:
11673 if (arg || nr_args)
11675 ret = io_register_enable_rings(ctx);
11677 case IORING_REGISTER_RESTRICTIONS:
11678 ret = io_register_restrictions(ctx, arg, nr_args);
11680 case IORING_REGISTER_FILES2:
11681 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11683 case IORING_REGISTER_FILES_UPDATE2:
11684 ret = io_register_rsrc_update(ctx, arg, nr_args,
11687 case IORING_REGISTER_BUFFERS2:
11688 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11690 case IORING_REGISTER_BUFFERS_UPDATE:
11691 ret = io_register_rsrc_update(ctx, arg, nr_args,
11692 IORING_RSRC_BUFFER);
11694 case IORING_REGISTER_IOWQ_AFF:
11696 if (!arg || !nr_args)
11698 ret = io_register_iowq_aff(ctx, arg, nr_args);
11700 case IORING_UNREGISTER_IOWQ_AFF:
11702 if (arg || nr_args)
11704 ret = io_unregister_iowq_aff(ctx);
11706 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11708 if (!arg || nr_args != 2)
11710 ret = io_register_iowq_max_workers(ctx, arg);
11712 case IORING_REGISTER_RING_FDS:
11713 ret = io_ringfd_register(ctx, arg, nr_args);
11715 case IORING_UNREGISTER_RING_FDS:
11716 ret = io_ringfd_unregister(ctx, arg, nr_args);
11726 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11727 void __user *, arg, unsigned int, nr_args)
11729 struct io_ring_ctx *ctx;
11738 if (f.file->f_op != &io_uring_fops)
11741 ctx = f.file->private_data;
11743 io_run_task_work();
11745 mutex_lock(&ctx->uring_lock);
11746 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11747 mutex_unlock(&ctx->uring_lock);
11748 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11754 static int __init io_uring_init(void)
11756 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11757 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11758 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11761 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11762 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11763 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11764 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11765 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11766 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11767 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11768 BUILD_BUG_SQE_ELEM(8, __u64, off);
11769 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11770 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11771 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11772 BUILD_BUG_SQE_ELEM(24, __u32, len);
11773 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11774 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11775 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11776 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11777 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11778 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11779 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11780 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11781 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11782 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11783 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11784 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11785 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11786 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11787 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11788 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11789 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11790 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11791 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11792 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11793 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11795 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11796 sizeof(struct io_uring_rsrc_update));
11797 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11798 sizeof(struct io_uring_rsrc_update2));
11800 /* ->buf_index is u16 */
11801 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11803 /* should fit into one byte */
11804 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11805 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11806 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11808 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11809 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11811 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11815 __initcall(io_uring_init);