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 */
910 /* fd initially, then cflags for completion */
916 struct io_ring_ctx *ctx;
917 struct task_struct *task;
919 struct percpu_ref *fixed_rsrc_refs;
920 /* store used ubuf, so we can prevent reloading */
921 struct io_mapped_ubuf *imu;
924 /* used by request caches, completion batching and iopoll */
925 struct io_wq_work_node comp_list;
926 /* cache ->apoll->events */
931 struct io_task_work io_task_work;
932 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
933 struct hlist_node hash_node;
934 /* internal polling, see IORING_FEAT_FAST_POLL */
935 struct async_poll *apoll;
936 /* opcode allocated if it needs to store data for async defer */
938 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
939 struct io_buffer *kbuf;
940 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
941 struct io_kiocb *link;
942 /* custom credentials, valid IFF REQ_F_CREDS is set */
943 const struct cred *creds;
944 struct io_wq_work work;
947 struct io_tctx_node {
948 struct list_head ctx_node;
949 struct task_struct *task;
950 struct io_ring_ctx *ctx;
953 struct io_defer_entry {
954 struct list_head list;
955 struct io_kiocb *req;
960 /* needs req->file assigned */
961 unsigned needs_file : 1;
962 /* should block plug */
964 /* hash wq insertion if file is a regular file */
965 unsigned hash_reg_file : 1;
966 /* unbound wq insertion if file is a non-regular file */
967 unsigned unbound_nonreg_file : 1;
968 /* set if opcode supports polled "wait" */
970 unsigned pollout : 1;
971 unsigned poll_exclusive : 1;
972 /* op supports buffer selection */
973 unsigned buffer_select : 1;
974 /* do prep async if is going to be punted */
975 unsigned needs_async_setup : 1;
976 /* opcode is not supported by this kernel */
977 unsigned not_supported : 1;
979 unsigned audit_skip : 1;
980 /* size of async data needed, if any */
981 unsigned short async_size;
984 static const struct io_op_def io_op_defs[] = {
985 [IORING_OP_NOP] = {},
986 [IORING_OP_READV] = {
988 .unbound_nonreg_file = 1,
991 .needs_async_setup = 1,
994 .async_size = sizeof(struct io_async_rw),
996 [IORING_OP_WRITEV] = {
999 .unbound_nonreg_file = 1,
1001 .needs_async_setup = 1,
1004 .async_size = sizeof(struct io_async_rw),
1006 [IORING_OP_FSYNC] = {
1010 [IORING_OP_READ_FIXED] = {
1012 .unbound_nonreg_file = 1,
1016 .async_size = sizeof(struct io_async_rw),
1018 [IORING_OP_WRITE_FIXED] = {
1021 .unbound_nonreg_file = 1,
1025 .async_size = sizeof(struct io_async_rw),
1027 [IORING_OP_POLL_ADD] = {
1029 .unbound_nonreg_file = 1,
1032 [IORING_OP_POLL_REMOVE] = {
1035 [IORING_OP_SYNC_FILE_RANGE] = {
1039 [IORING_OP_SENDMSG] = {
1041 .unbound_nonreg_file = 1,
1043 .needs_async_setup = 1,
1044 .async_size = sizeof(struct io_async_msghdr),
1046 [IORING_OP_RECVMSG] = {
1048 .unbound_nonreg_file = 1,
1051 .needs_async_setup = 1,
1052 .async_size = sizeof(struct io_async_msghdr),
1054 [IORING_OP_TIMEOUT] = {
1056 .async_size = sizeof(struct io_timeout_data),
1058 [IORING_OP_TIMEOUT_REMOVE] = {
1059 /* used by timeout updates' prep() */
1062 [IORING_OP_ACCEPT] = {
1064 .unbound_nonreg_file = 1,
1066 .poll_exclusive = 1,
1068 [IORING_OP_ASYNC_CANCEL] = {
1071 [IORING_OP_LINK_TIMEOUT] = {
1073 .async_size = sizeof(struct io_timeout_data),
1075 [IORING_OP_CONNECT] = {
1077 .unbound_nonreg_file = 1,
1079 .needs_async_setup = 1,
1080 .async_size = sizeof(struct io_async_connect),
1082 [IORING_OP_FALLOCATE] = {
1085 [IORING_OP_OPENAT] = {},
1086 [IORING_OP_CLOSE] = {},
1087 [IORING_OP_FILES_UPDATE] = {
1090 [IORING_OP_STATX] = {
1093 [IORING_OP_READ] = {
1095 .unbound_nonreg_file = 1,
1100 .async_size = sizeof(struct io_async_rw),
1102 [IORING_OP_WRITE] = {
1105 .unbound_nonreg_file = 1,
1109 .async_size = sizeof(struct io_async_rw),
1111 [IORING_OP_FADVISE] = {
1115 [IORING_OP_MADVISE] = {},
1116 [IORING_OP_SEND] = {
1118 .unbound_nonreg_file = 1,
1122 [IORING_OP_RECV] = {
1124 .unbound_nonreg_file = 1,
1129 [IORING_OP_OPENAT2] = {
1131 [IORING_OP_EPOLL_CTL] = {
1132 .unbound_nonreg_file = 1,
1135 [IORING_OP_SPLICE] = {
1138 .unbound_nonreg_file = 1,
1141 [IORING_OP_PROVIDE_BUFFERS] = {
1144 [IORING_OP_REMOVE_BUFFERS] = {
1150 .unbound_nonreg_file = 1,
1153 [IORING_OP_SHUTDOWN] = {
1156 [IORING_OP_RENAMEAT] = {},
1157 [IORING_OP_UNLINKAT] = {},
1158 [IORING_OP_MKDIRAT] = {},
1159 [IORING_OP_SYMLINKAT] = {},
1160 [IORING_OP_LINKAT] = {},
1161 [IORING_OP_MSG_RING] = {
1166 /* requests with any of those set should undergo io_disarm_next() */
1167 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1169 static bool io_disarm_next(struct io_kiocb *req);
1170 static void io_uring_del_tctx_node(unsigned long index);
1171 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1172 struct task_struct *task,
1174 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1176 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1178 static void io_put_req(struct io_kiocb *req);
1179 static void io_put_req_deferred(struct io_kiocb *req);
1180 static void io_dismantle_req(struct io_kiocb *req);
1181 static void io_queue_linked_timeout(struct io_kiocb *req);
1182 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1183 struct io_uring_rsrc_update2 *up,
1185 static void io_clean_op(struct io_kiocb *req);
1186 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1187 unsigned issue_flags);
1188 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1189 static void io_drop_inflight_file(struct io_kiocb *req);
1190 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1191 static void __io_queue_sqe(struct io_kiocb *req);
1192 static void io_rsrc_put_work(struct work_struct *work);
1194 static void io_req_task_queue(struct io_kiocb *req);
1195 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1196 static int io_req_prep_async(struct io_kiocb *req);
1198 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1199 unsigned int issue_flags, u32 slot_index);
1200 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1202 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1203 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1205 static struct kmem_cache *req_cachep;
1207 static const struct file_operations io_uring_fops;
1209 struct sock *io_uring_get_socket(struct file *file)
1211 #if defined(CONFIG_UNIX)
1212 if (file->f_op == &io_uring_fops) {
1213 struct io_ring_ctx *ctx = file->private_data;
1215 return ctx->ring_sock->sk;
1220 EXPORT_SYMBOL(io_uring_get_socket);
1222 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1225 mutex_lock(&ctx->uring_lock);
1230 #define io_for_each_link(pos, head) \
1231 for (pos = (head); pos; pos = pos->link)
1234 * Shamelessly stolen from the mm implementation of page reference checking,
1235 * see commit f958d7b528b1 for details.
1237 #define req_ref_zero_or_close_to_overflow(req) \
1238 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1240 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1242 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1243 return atomic_inc_not_zero(&req->refs);
1246 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1248 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1251 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1252 return atomic_dec_and_test(&req->refs);
1255 static inline void req_ref_get(struct io_kiocb *req)
1257 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1258 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1259 atomic_inc(&req->refs);
1262 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1264 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1265 __io_submit_flush_completions(ctx);
1268 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1270 if (!(req->flags & REQ_F_REFCOUNT)) {
1271 req->flags |= REQ_F_REFCOUNT;
1272 atomic_set(&req->refs, nr);
1276 static inline void io_req_set_refcount(struct io_kiocb *req)
1278 __io_req_set_refcount(req, 1);
1281 #define IO_RSRC_REF_BATCH 100
1283 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1284 struct io_ring_ctx *ctx)
1285 __must_hold(&ctx->uring_lock)
1287 struct percpu_ref *ref = req->fixed_rsrc_refs;
1290 if (ref == &ctx->rsrc_node->refs)
1291 ctx->rsrc_cached_refs++;
1293 percpu_ref_put(ref);
1297 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1299 if (req->fixed_rsrc_refs)
1300 percpu_ref_put(req->fixed_rsrc_refs);
1303 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1304 __must_hold(&ctx->uring_lock)
1306 if (ctx->rsrc_cached_refs) {
1307 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1308 ctx->rsrc_cached_refs = 0;
1312 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1313 __must_hold(&ctx->uring_lock)
1315 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1316 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1319 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1320 struct io_ring_ctx *ctx,
1321 unsigned int issue_flags)
1323 if (!req->fixed_rsrc_refs) {
1324 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1326 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1327 lockdep_assert_held(&ctx->uring_lock);
1328 ctx->rsrc_cached_refs--;
1329 if (unlikely(ctx->rsrc_cached_refs < 0))
1330 io_rsrc_refs_refill(ctx);
1332 percpu_ref_get(req->fixed_rsrc_refs);
1337 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1339 struct io_buffer *kbuf = req->kbuf;
1340 unsigned int cflags;
1342 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1343 req->flags &= ~REQ_F_BUFFER_SELECTED;
1344 list_add(&kbuf->list, list);
1349 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1351 lockdep_assert_held(&req->ctx->completion_lock);
1353 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1355 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1358 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1359 unsigned issue_flags)
1361 unsigned int cflags;
1363 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1367 * We can add this buffer back to two lists:
1369 * 1) The io_buffers_cache list. This one is protected by the
1370 * ctx->uring_lock. If we already hold this lock, add back to this
1371 * list as we can grab it from issue as well.
1372 * 2) The io_buffers_comp list. This one is protected by the
1373 * ctx->completion_lock.
1375 * We migrate buffers from the comp_list to the issue cache list
1378 if (issue_flags & IO_URING_F_UNLOCKED) {
1379 struct io_ring_ctx *ctx = req->ctx;
1381 spin_lock(&ctx->completion_lock);
1382 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1383 spin_unlock(&ctx->completion_lock);
1385 lockdep_assert_held(&req->ctx->uring_lock);
1387 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1393 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1396 struct list_head *hash_list;
1397 struct io_buffer_list *bl;
1399 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1400 list_for_each_entry(bl, hash_list, list)
1401 if (bl->bgid == bgid || bgid == -1U)
1407 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1409 struct io_ring_ctx *ctx = req->ctx;
1410 struct io_buffer_list *bl;
1411 struct io_buffer *buf;
1413 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1415 /* don't recycle if we already did IO to this buffer */
1416 if (req->flags & REQ_F_PARTIAL_IO)
1419 if (issue_flags & IO_URING_F_UNLOCKED)
1420 mutex_lock(&ctx->uring_lock);
1422 lockdep_assert_held(&ctx->uring_lock);
1425 bl = io_buffer_get_list(ctx, buf->bgid);
1426 list_add(&buf->list, &bl->buf_list);
1427 req->flags &= ~REQ_F_BUFFER_SELECTED;
1430 if (issue_flags & IO_URING_F_UNLOCKED)
1431 mutex_unlock(&ctx->uring_lock);
1434 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1436 __must_hold(&req->ctx->timeout_lock)
1438 if (task && head->task != task)
1444 * As io_match_task() but protected against racing with linked timeouts.
1445 * User must not hold timeout_lock.
1447 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1450 if (task && head->task != task)
1455 static inline bool req_has_async_data(struct io_kiocb *req)
1457 return req->flags & REQ_F_ASYNC_DATA;
1460 static inline void req_set_fail(struct io_kiocb *req)
1462 req->flags |= REQ_F_FAIL;
1463 if (req->flags & REQ_F_CQE_SKIP) {
1464 req->flags &= ~REQ_F_CQE_SKIP;
1465 req->flags |= REQ_F_SKIP_LINK_CQES;
1469 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1475 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1477 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1479 complete(&ctx->ref_comp);
1482 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1484 return !req->timeout.off;
1487 static __cold void io_fallback_req_func(struct work_struct *work)
1489 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1490 fallback_work.work);
1491 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1492 struct io_kiocb *req, *tmp;
1493 bool locked = false;
1495 percpu_ref_get(&ctx->refs);
1496 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1497 req->io_task_work.func(req, &locked);
1500 io_submit_flush_completions(ctx);
1501 mutex_unlock(&ctx->uring_lock);
1503 percpu_ref_put(&ctx->refs);
1506 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1508 struct io_ring_ctx *ctx;
1511 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1516 * Use 5 bits less than the max cq entries, that should give us around
1517 * 32 entries per hash list if totally full and uniformly spread.
1519 hash_bits = ilog2(p->cq_entries);
1523 ctx->cancel_hash_bits = hash_bits;
1524 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1526 if (!ctx->cancel_hash)
1528 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1530 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1531 if (!ctx->dummy_ubuf)
1533 /* set invalid range, so io_import_fixed() fails meeting it */
1534 ctx->dummy_ubuf->ubuf = -1UL;
1536 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1537 sizeof(struct list_head), GFP_KERNEL);
1538 if (!ctx->io_buffers)
1540 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1541 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1543 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1544 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1547 ctx->flags = p->flags;
1548 init_waitqueue_head(&ctx->sqo_sq_wait);
1549 INIT_LIST_HEAD(&ctx->sqd_list);
1550 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1551 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1552 INIT_LIST_HEAD(&ctx->apoll_cache);
1553 init_completion(&ctx->ref_comp);
1554 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1555 mutex_init(&ctx->uring_lock);
1556 init_waitqueue_head(&ctx->cq_wait);
1557 spin_lock_init(&ctx->completion_lock);
1558 spin_lock_init(&ctx->timeout_lock);
1559 INIT_WQ_LIST(&ctx->iopoll_list);
1560 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1561 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1562 INIT_LIST_HEAD(&ctx->defer_list);
1563 INIT_LIST_HEAD(&ctx->timeout_list);
1564 INIT_LIST_HEAD(&ctx->ltimeout_list);
1565 spin_lock_init(&ctx->rsrc_ref_lock);
1566 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1567 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1568 init_llist_head(&ctx->rsrc_put_llist);
1569 INIT_LIST_HEAD(&ctx->tctx_list);
1570 ctx->submit_state.free_list.next = NULL;
1571 INIT_WQ_LIST(&ctx->locked_free_list);
1572 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1573 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1576 kfree(ctx->dummy_ubuf);
1577 kfree(ctx->cancel_hash);
1578 kfree(ctx->io_buffers);
1583 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1585 struct io_rings *r = ctx->rings;
1587 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1591 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1593 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1594 struct io_ring_ctx *ctx = req->ctx;
1596 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1602 #define FFS_NOWAIT 0x1UL
1603 #define FFS_ISREG 0x2UL
1604 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1606 static inline bool io_req_ffs_set(struct io_kiocb *req)
1608 return req->flags & REQ_F_FIXED_FILE;
1611 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1613 if (WARN_ON_ONCE(!req->link))
1616 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1617 req->flags |= REQ_F_LINK_TIMEOUT;
1619 /* linked timeouts should have two refs once prep'ed */
1620 io_req_set_refcount(req);
1621 __io_req_set_refcount(req->link, 2);
1625 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1627 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1629 return __io_prep_linked_timeout(req);
1632 static void io_prep_async_work(struct io_kiocb *req)
1634 const struct io_op_def *def = &io_op_defs[req->opcode];
1635 struct io_ring_ctx *ctx = req->ctx;
1637 if (!(req->flags & REQ_F_CREDS)) {
1638 req->flags |= REQ_F_CREDS;
1639 req->creds = get_current_cred();
1642 req->work.list.next = NULL;
1643 req->work.flags = 0;
1644 if (req->flags & REQ_F_FORCE_ASYNC)
1645 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1647 if (req->flags & REQ_F_ISREG) {
1648 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1649 io_wq_hash_work(&req->work, file_inode(req->file));
1650 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1651 if (def->unbound_nonreg_file)
1652 req->work.flags |= IO_WQ_WORK_UNBOUND;
1656 static void io_prep_async_link(struct io_kiocb *req)
1658 struct io_kiocb *cur;
1660 if (req->flags & REQ_F_LINK_TIMEOUT) {
1661 struct io_ring_ctx *ctx = req->ctx;
1663 spin_lock_irq(&ctx->timeout_lock);
1664 io_for_each_link(cur, req)
1665 io_prep_async_work(cur);
1666 spin_unlock_irq(&ctx->timeout_lock);
1668 io_for_each_link(cur, req)
1669 io_prep_async_work(cur);
1673 static inline void io_req_add_compl_list(struct io_kiocb *req)
1675 struct io_ring_ctx *ctx = req->ctx;
1676 struct io_submit_state *state = &ctx->submit_state;
1678 if (!(req->flags & REQ_F_CQE_SKIP))
1679 ctx->submit_state.flush_cqes = true;
1680 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1683 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1685 struct io_ring_ctx *ctx = req->ctx;
1686 struct io_kiocb *link = io_prep_linked_timeout(req);
1687 struct io_uring_task *tctx = req->task->io_uring;
1690 BUG_ON(!tctx->io_wq);
1692 /* init ->work of the whole link before punting */
1693 io_prep_async_link(req);
1696 * Not expected to happen, but if we do have a bug where this _can_
1697 * happen, catch it here and ensure the request is marked as
1698 * canceled. That will make io-wq go through the usual work cancel
1699 * procedure rather than attempt to run this request (or create a new
1702 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1703 req->work.flags |= IO_WQ_WORK_CANCEL;
1705 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1706 &req->work, io_wq_is_hashed(&req->work));
1707 io_wq_enqueue(tctx->io_wq, &req->work);
1709 io_queue_linked_timeout(link);
1712 static void io_kill_timeout(struct io_kiocb *req, int status)
1713 __must_hold(&req->ctx->completion_lock)
1714 __must_hold(&req->ctx->timeout_lock)
1716 struct io_timeout_data *io = req->async_data;
1718 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1721 atomic_set(&req->ctx->cq_timeouts,
1722 atomic_read(&req->ctx->cq_timeouts) + 1);
1723 list_del_init(&req->timeout.list);
1724 io_fill_cqe_req(req, status, 0);
1725 io_put_req_deferred(req);
1729 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1731 while (!list_empty(&ctx->defer_list)) {
1732 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1733 struct io_defer_entry, list);
1735 if (req_need_defer(de->req, de->seq))
1737 list_del_init(&de->list);
1738 io_req_task_queue(de->req);
1743 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1744 __must_hold(&ctx->completion_lock)
1746 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1747 struct io_kiocb *req, *tmp;
1749 spin_lock_irq(&ctx->timeout_lock);
1750 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1751 u32 events_needed, events_got;
1753 if (io_is_timeout_noseq(req))
1757 * Since seq can easily wrap around over time, subtract
1758 * the last seq at which timeouts were flushed before comparing.
1759 * Assuming not more than 2^31-1 events have happened since,
1760 * these subtractions won't have wrapped, so we can check if
1761 * target is in [last_seq, current_seq] by comparing the two.
1763 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1764 events_got = seq - ctx->cq_last_tm_flush;
1765 if (events_got < events_needed)
1768 io_kill_timeout(req, 0);
1770 ctx->cq_last_tm_flush = seq;
1771 spin_unlock_irq(&ctx->timeout_lock);
1774 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1776 /* order cqe stores with ring update */
1777 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1780 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1782 if (ctx->off_timeout_used || ctx->drain_active) {
1783 spin_lock(&ctx->completion_lock);
1784 if (ctx->off_timeout_used)
1785 io_flush_timeouts(ctx);
1786 if (ctx->drain_active)
1787 io_queue_deferred(ctx);
1788 io_commit_cqring(ctx);
1789 spin_unlock(&ctx->completion_lock);
1792 io_eventfd_signal(ctx);
1795 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1797 struct io_rings *r = ctx->rings;
1799 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1802 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1804 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1807 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1809 struct io_rings *rings = ctx->rings;
1810 unsigned tail, mask = ctx->cq_entries - 1;
1813 * writes to the cq entry need to come after reading head; the
1814 * control dependency is enough as we're using WRITE_ONCE to
1817 if (__io_cqring_events(ctx) == ctx->cq_entries)
1820 tail = ctx->cached_cq_tail++;
1821 return &rings->cqes[tail & mask];
1824 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1826 struct io_ev_fd *ev_fd;
1830 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1831 * and eventfd_signal
1833 ev_fd = rcu_dereference(ctx->io_ev_fd);
1836 * Check again if ev_fd exists incase an io_eventfd_unregister call
1837 * completed between the NULL check of ctx->io_ev_fd at the start of
1838 * the function and rcu_read_lock.
1840 if (unlikely(!ev_fd))
1842 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1845 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1846 eventfd_signal(ev_fd->cq_ev_fd, 1);
1851 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1854 * wake_up_all() may seem excessive, but io_wake_function() and
1855 * io_should_wake() handle the termination of the loop and only
1856 * wake as many waiters as we need to.
1858 if (wq_has_sleeper(&ctx->cq_wait))
1859 wake_up_all(&ctx->cq_wait);
1863 * This should only get called when at least one event has been posted.
1864 * Some applications rely on the eventfd notification count only changing
1865 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1866 * 1:1 relationship between how many times this function is called (and
1867 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1869 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1871 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1873 __io_commit_cqring_flush(ctx);
1875 io_cqring_wake(ctx);
1878 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1880 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1882 __io_commit_cqring_flush(ctx);
1884 if (ctx->flags & IORING_SETUP_SQPOLL)
1885 io_cqring_wake(ctx);
1888 /* Returns true if there are no backlogged entries after the flush */
1889 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1891 bool all_flushed, posted;
1893 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1897 spin_lock(&ctx->completion_lock);
1898 while (!list_empty(&ctx->cq_overflow_list)) {
1899 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1900 struct io_overflow_cqe *ocqe;
1904 ocqe = list_first_entry(&ctx->cq_overflow_list,
1905 struct io_overflow_cqe, list);
1907 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1909 io_account_cq_overflow(ctx);
1912 list_del(&ocqe->list);
1916 all_flushed = list_empty(&ctx->cq_overflow_list);
1918 clear_bit(0, &ctx->check_cq_overflow);
1919 WRITE_ONCE(ctx->rings->sq_flags,
1920 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1924 io_commit_cqring(ctx);
1925 spin_unlock(&ctx->completion_lock);
1927 io_cqring_ev_posted(ctx);
1931 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1935 if (test_bit(0, &ctx->check_cq_overflow)) {
1936 /* iopoll syncs against uring_lock, not completion_lock */
1937 if (ctx->flags & IORING_SETUP_IOPOLL)
1938 mutex_lock(&ctx->uring_lock);
1939 ret = __io_cqring_overflow_flush(ctx, false);
1940 if (ctx->flags & IORING_SETUP_IOPOLL)
1941 mutex_unlock(&ctx->uring_lock);
1947 /* must to be called somewhat shortly after putting a request */
1948 static inline void io_put_task(struct task_struct *task, int nr)
1950 struct io_uring_task *tctx = task->io_uring;
1952 if (likely(task == current)) {
1953 tctx->cached_refs += nr;
1955 percpu_counter_sub(&tctx->inflight, nr);
1956 if (unlikely(atomic_read(&tctx->in_idle)))
1957 wake_up(&tctx->wait);
1958 put_task_struct_many(task, nr);
1962 static void io_task_refs_refill(struct io_uring_task *tctx)
1964 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1966 percpu_counter_add(&tctx->inflight, refill);
1967 refcount_add(refill, ¤t->usage);
1968 tctx->cached_refs += refill;
1971 static inline void io_get_task_refs(int nr)
1973 struct io_uring_task *tctx = current->io_uring;
1975 tctx->cached_refs -= nr;
1976 if (unlikely(tctx->cached_refs < 0))
1977 io_task_refs_refill(tctx);
1980 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1982 struct io_uring_task *tctx = task->io_uring;
1983 unsigned int refs = tctx->cached_refs;
1986 tctx->cached_refs = 0;
1987 percpu_counter_sub(&tctx->inflight, refs);
1988 put_task_struct_many(task, refs);
1992 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1993 s32 res, u32 cflags)
1995 struct io_overflow_cqe *ocqe;
1997 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2000 * If we're in ring overflow flush mode, or in task cancel mode,
2001 * or cannot allocate an overflow entry, then we need to drop it
2004 io_account_cq_overflow(ctx);
2007 if (list_empty(&ctx->cq_overflow_list)) {
2008 set_bit(0, &ctx->check_cq_overflow);
2009 WRITE_ONCE(ctx->rings->sq_flags,
2010 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2013 ocqe->cqe.user_data = user_data;
2014 ocqe->cqe.res = res;
2015 ocqe->cqe.flags = cflags;
2016 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2020 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2021 s32 res, u32 cflags)
2023 struct io_uring_cqe *cqe;
2026 * If we can't get a cq entry, userspace overflowed the
2027 * submission (by quite a lot). Increment the overflow count in
2030 cqe = io_get_cqe(ctx);
2032 WRITE_ONCE(cqe->user_data, user_data);
2033 WRITE_ONCE(cqe->res, res);
2034 WRITE_ONCE(cqe->flags, cflags);
2037 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2040 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2042 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2043 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
2046 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2048 if (!(req->flags & REQ_F_CQE_SKIP))
2049 __io_fill_cqe_req(req, res, cflags);
2052 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2053 s32 res, u32 cflags)
2056 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2057 return __io_fill_cqe(ctx, user_data, res, cflags);
2060 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2063 struct io_ring_ctx *ctx = req->ctx;
2065 if (!(req->flags & REQ_F_CQE_SKIP))
2066 __io_fill_cqe_req(req, res, cflags);
2068 * If we're the last reference to this request, add to our locked
2071 if (req_ref_put_and_test(req)) {
2072 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2073 if (req->flags & IO_DISARM_MASK)
2074 io_disarm_next(req);
2076 io_req_task_queue(req->link);
2080 io_req_put_rsrc(req, ctx);
2082 * Selected buffer deallocation in io_clean_op() assumes that
2083 * we don't hold ->completion_lock. Clean them here to avoid
2086 io_put_kbuf_comp(req);
2087 io_dismantle_req(req);
2088 io_put_task(req->task, 1);
2089 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2090 ctx->locked_free_nr++;
2094 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2097 struct io_ring_ctx *ctx = req->ctx;
2099 spin_lock(&ctx->completion_lock);
2100 __io_req_complete_post(req, res, cflags);
2101 io_commit_cqring(ctx);
2102 spin_unlock(&ctx->completion_lock);
2103 io_cqring_ev_posted(ctx);
2106 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2110 req->cflags = cflags;
2111 req->flags |= REQ_F_COMPLETE_INLINE;
2114 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2115 s32 res, u32 cflags)
2117 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2118 io_req_complete_state(req, res, cflags);
2120 io_req_complete_post(req, res, cflags);
2123 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2125 __io_req_complete(req, 0, res, 0);
2128 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2131 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2134 static void io_req_complete_fail_submit(struct io_kiocb *req)
2137 * We don't submit, fail them all, for that replace hardlinks with
2138 * normal links. Extra REQ_F_LINK is tolerated.
2140 req->flags &= ~REQ_F_HARDLINK;
2141 req->flags |= REQ_F_LINK;
2142 io_req_complete_failed(req, req->result);
2146 * Don't initialise the fields below on every allocation, but do that in
2147 * advance and keep them valid across allocations.
2149 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2153 req->async_data = NULL;
2154 /* not necessary, but safer to zero */
2158 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2159 struct io_submit_state *state)
2161 spin_lock(&ctx->completion_lock);
2162 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2163 ctx->locked_free_nr = 0;
2164 spin_unlock(&ctx->completion_lock);
2167 /* Returns true IFF there are requests in the cache */
2168 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2170 struct io_submit_state *state = &ctx->submit_state;
2173 * If we have more than a batch's worth of requests in our IRQ side
2174 * locked cache, grab the lock and move them over to our submission
2177 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2178 io_flush_cached_locked_reqs(ctx, state);
2179 return !!state->free_list.next;
2183 * A request might get retired back into the request caches even before opcode
2184 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2185 * Because of that, io_alloc_req() should be called only under ->uring_lock
2186 * and with extra caution to not get a request that is still worked on.
2188 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2189 __must_hold(&ctx->uring_lock)
2191 struct io_submit_state *state = &ctx->submit_state;
2192 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2193 void *reqs[IO_REQ_ALLOC_BATCH];
2194 struct io_kiocb *req;
2197 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2200 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2203 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2204 * retry single alloc to be on the safe side.
2206 if (unlikely(ret <= 0)) {
2207 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2213 percpu_ref_get_many(&ctx->refs, ret);
2214 for (i = 0; i < ret; i++) {
2217 io_preinit_req(req, ctx);
2218 wq_stack_add_head(&req->comp_list, &state->free_list);
2223 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2225 if (unlikely(!ctx->submit_state.free_list.next))
2226 return __io_alloc_req_refill(ctx);
2230 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2232 struct io_wq_work_node *node;
2234 node = wq_stack_extract(&ctx->submit_state.free_list);
2235 return container_of(node, struct io_kiocb, comp_list);
2238 static inline void io_put_file(struct file *file)
2244 static inline void io_dismantle_req(struct io_kiocb *req)
2246 unsigned int flags = req->flags;
2248 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2250 if (!(flags & REQ_F_FIXED_FILE))
2251 io_put_file(req->file);
2254 static __cold void __io_free_req(struct io_kiocb *req)
2256 struct io_ring_ctx *ctx = req->ctx;
2258 io_req_put_rsrc(req, ctx);
2259 io_dismantle_req(req);
2260 io_put_task(req->task, 1);
2262 spin_lock(&ctx->completion_lock);
2263 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2264 ctx->locked_free_nr++;
2265 spin_unlock(&ctx->completion_lock);
2268 static inline void io_remove_next_linked(struct io_kiocb *req)
2270 struct io_kiocb *nxt = req->link;
2272 req->link = nxt->link;
2276 static bool io_kill_linked_timeout(struct io_kiocb *req)
2277 __must_hold(&req->ctx->completion_lock)
2278 __must_hold(&req->ctx->timeout_lock)
2280 struct io_kiocb *link = req->link;
2282 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2283 struct io_timeout_data *io = link->async_data;
2285 io_remove_next_linked(req);
2286 link->timeout.head = NULL;
2287 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2288 list_del(&link->timeout.list);
2289 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2290 io_fill_cqe_req(link, -ECANCELED, 0);
2291 io_put_req_deferred(link);
2298 static void io_fail_links(struct io_kiocb *req)
2299 __must_hold(&req->ctx->completion_lock)
2301 struct io_kiocb *nxt, *link = req->link;
2302 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2306 long res = -ECANCELED;
2308 if (link->flags & REQ_F_FAIL)
2314 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2318 link->flags &= ~REQ_F_CQE_SKIP;
2319 io_fill_cqe_req(link, res, 0);
2321 io_put_req_deferred(link);
2326 static bool io_disarm_next(struct io_kiocb *req)
2327 __must_hold(&req->ctx->completion_lock)
2329 bool posted = false;
2331 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2332 struct io_kiocb *link = req->link;
2334 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2335 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2336 io_remove_next_linked(req);
2337 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2338 io_fill_cqe_req(link, -ECANCELED, 0);
2339 io_put_req_deferred(link);
2342 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2343 struct io_ring_ctx *ctx = req->ctx;
2345 spin_lock_irq(&ctx->timeout_lock);
2346 posted = io_kill_linked_timeout(req);
2347 spin_unlock_irq(&ctx->timeout_lock);
2349 if (unlikely((req->flags & REQ_F_FAIL) &&
2350 !(req->flags & REQ_F_HARDLINK))) {
2351 posted |= (req->link != NULL);
2357 static void __io_req_find_next_prep(struct io_kiocb *req)
2359 struct io_ring_ctx *ctx = req->ctx;
2362 spin_lock(&ctx->completion_lock);
2363 posted = io_disarm_next(req);
2365 io_commit_cqring(ctx);
2366 spin_unlock(&ctx->completion_lock);
2368 io_cqring_ev_posted(ctx);
2371 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2373 struct io_kiocb *nxt;
2375 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2378 * If LINK is set, we have dependent requests in this chain. If we
2379 * didn't fail this request, queue the first one up, moving any other
2380 * dependencies to the next request. In case of failure, fail the rest
2383 if (unlikely(req->flags & IO_DISARM_MASK))
2384 __io_req_find_next_prep(req);
2390 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2395 io_submit_flush_completions(ctx);
2396 mutex_unlock(&ctx->uring_lock);
2399 percpu_ref_put(&ctx->refs);
2402 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2404 io_commit_cqring(ctx);
2405 spin_unlock(&ctx->completion_lock);
2406 io_cqring_ev_posted(ctx);
2409 static void handle_prev_tw_list(struct io_wq_work_node *node,
2410 struct io_ring_ctx **ctx, bool *uring_locked)
2412 if (*ctx && !*uring_locked)
2413 spin_lock(&(*ctx)->completion_lock);
2416 struct io_wq_work_node *next = node->next;
2417 struct io_kiocb *req = container_of(node, struct io_kiocb,
2420 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2422 if (req->ctx != *ctx) {
2423 if (unlikely(!*uring_locked && *ctx))
2424 ctx_commit_and_unlock(*ctx);
2426 ctx_flush_and_put(*ctx, uring_locked);
2428 /* if not contended, grab and improve batching */
2429 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2430 percpu_ref_get(&(*ctx)->refs);
2431 if (unlikely(!*uring_locked))
2432 spin_lock(&(*ctx)->completion_lock);
2434 if (likely(*uring_locked))
2435 req->io_task_work.func(req, uring_locked);
2437 __io_req_complete_post(req, req->result,
2438 io_put_kbuf_comp(req));
2442 if (unlikely(!*uring_locked))
2443 ctx_commit_and_unlock(*ctx);
2446 static void handle_tw_list(struct io_wq_work_node *node,
2447 struct io_ring_ctx **ctx, bool *locked)
2450 struct io_wq_work_node *next = node->next;
2451 struct io_kiocb *req = container_of(node, struct io_kiocb,
2454 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2456 if (req->ctx != *ctx) {
2457 ctx_flush_and_put(*ctx, locked);
2459 /* if not contended, grab and improve batching */
2460 *locked = mutex_trylock(&(*ctx)->uring_lock);
2461 percpu_ref_get(&(*ctx)->refs);
2463 req->io_task_work.func(req, locked);
2468 static void tctx_task_work(struct callback_head *cb)
2470 bool uring_locked = false;
2471 struct io_ring_ctx *ctx = NULL;
2472 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2476 struct io_wq_work_node *node1, *node2;
2478 if (!tctx->task_list.first &&
2479 !tctx->prior_task_list.first && uring_locked)
2480 io_submit_flush_completions(ctx);
2482 spin_lock_irq(&tctx->task_lock);
2483 node1 = tctx->prior_task_list.first;
2484 node2 = tctx->task_list.first;
2485 INIT_WQ_LIST(&tctx->task_list);
2486 INIT_WQ_LIST(&tctx->prior_task_list);
2487 if (!node2 && !node1)
2488 tctx->task_running = false;
2489 spin_unlock_irq(&tctx->task_lock);
2490 if (!node2 && !node1)
2494 handle_prev_tw_list(node1, &ctx, &uring_locked);
2497 handle_tw_list(node2, &ctx, &uring_locked);
2501 ctx_flush_and_put(ctx, &uring_locked);
2503 /* relaxed read is enough as only the task itself sets ->in_idle */
2504 if (unlikely(atomic_read(&tctx->in_idle)))
2505 io_uring_drop_tctx_refs(current);
2508 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2510 struct task_struct *tsk = req->task;
2511 struct io_uring_task *tctx = tsk->io_uring;
2512 enum task_work_notify_mode notify;
2513 struct io_wq_work_node *node;
2514 unsigned long flags;
2517 WARN_ON_ONCE(!tctx);
2519 io_drop_inflight_file(req);
2521 spin_lock_irqsave(&tctx->task_lock, flags);
2523 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2525 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2526 running = tctx->task_running;
2528 tctx->task_running = true;
2529 spin_unlock_irqrestore(&tctx->task_lock, flags);
2531 /* task_work already pending, we're done */
2536 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2537 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2538 * processing task_work. There's no reliable way to tell if TWA_RESUME
2541 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2542 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2543 if (notify == TWA_NONE)
2544 wake_up_process(tsk);
2548 spin_lock_irqsave(&tctx->task_lock, flags);
2549 tctx->task_running = false;
2550 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2551 spin_unlock_irqrestore(&tctx->task_lock, flags);
2554 req = container_of(node, struct io_kiocb, io_task_work.node);
2556 if (llist_add(&req->io_task_work.fallback_node,
2557 &req->ctx->fallback_llist))
2558 schedule_delayed_work(&req->ctx->fallback_work, 1);
2562 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2564 struct io_ring_ctx *ctx = req->ctx;
2566 /* not needed for normal modes, but SQPOLL depends on it */
2567 io_tw_lock(ctx, locked);
2568 io_req_complete_failed(req, req->result);
2571 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2573 struct io_ring_ctx *ctx = req->ctx;
2575 io_tw_lock(ctx, locked);
2576 /* req->task == current here, checking PF_EXITING is safe */
2577 if (likely(!(req->task->flags & PF_EXITING)))
2578 __io_queue_sqe(req);
2580 io_req_complete_failed(req, -EFAULT);
2583 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2586 req->io_task_work.func = io_req_task_cancel;
2587 io_req_task_work_add(req, false);
2590 static void io_req_task_queue(struct io_kiocb *req)
2592 req->io_task_work.func = io_req_task_submit;
2593 io_req_task_work_add(req, false);
2596 static void io_req_task_queue_reissue(struct io_kiocb *req)
2598 req->io_task_work.func = io_queue_async_work;
2599 io_req_task_work_add(req, false);
2602 static inline void io_queue_next(struct io_kiocb *req)
2604 struct io_kiocb *nxt = io_req_find_next(req);
2607 io_req_task_queue(nxt);
2610 static void io_free_req(struct io_kiocb *req)
2616 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2621 static void io_free_batch_list(struct io_ring_ctx *ctx,
2622 struct io_wq_work_node *node)
2623 __must_hold(&ctx->uring_lock)
2625 struct task_struct *task = NULL;
2629 struct io_kiocb *req = container_of(node, struct io_kiocb,
2632 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2633 node = req->comp_list.next;
2634 if (!req_ref_put_and_test(req))
2638 io_req_put_rsrc_locked(req, ctx);
2640 io_dismantle_req(req);
2642 if (req->task != task) {
2644 io_put_task(task, task_refs);
2649 node = req->comp_list.next;
2650 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2654 io_put_task(task, task_refs);
2657 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2658 __must_hold(&ctx->uring_lock)
2660 struct io_wq_work_node *node, *prev;
2661 struct io_submit_state *state = &ctx->submit_state;
2663 if (state->flush_cqes) {
2664 spin_lock(&ctx->completion_lock);
2665 wq_list_for_each(node, prev, &state->compl_reqs) {
2666 struct io_kiocb *req = container_of(node, struct io_kiocb,
2669 if (!(req->flags & REQ_F_CQE_SKIP))
2670 __io_fill_cqe_req(req, req->result, req->cflags);
2671 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2672 struct async_poll *apoll = req->apoll;
2674 if (apoll->double_poll)
2675 kfree(apoll->double_poll);
2676 list_add(&apoll->poll.wait.entry,
2678 req->flags &= ~REQ_F_POLLED;
2682 io_commit_cqring(ctx);
2683 spin_unlock(&ctx->completion_lock);
2684 io_cqring_ev_posted(ctx);
2685 state->flush_cqes = false;
2688 io_free_batch_list(ctx, state->compl_reqs.first);
2689 INIT_WQ_LIST(&state->compl_reqs);
2693 * Drop reference to request, return next in chain (if there is one) if this
2694 * was the last reference to this request.
2696 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2698 struct io_kiocb *nxt = NULL;
2700 if (req_ref_put_and_test(req)) {
2701 nxt = io_req_find_next(req);
2707 static inline void io_put_req(struct io_kiocb *req)
2709 if (req_ref_put_and_test(req))
2713 static inline void io_put_req_deferred(struct io_kiocb *req)
2715 if (req_ref_put_and_test(req)) {
2716 req->io_task_work.func = io_free_req_work;
2717 io_req_task_work_add(req, false);
2721 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2723 /* See comment at the top of this file */
2725 return __io_cqring_events(ctx);
2728 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2730 struct io_rings *rings = ctx->rings;
2732 /* make sure SQ entry isn't read before tail */
2733 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2736 static inline bool io_run_task_work(void)
2738 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2739 __set_current_state(TASK_RUNNING);
2740 clear_notify_signal();
2741 if (task_work_pending(current))
2749 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2751 struct io_wq_work_node *pos, *start, *prev;
2752 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2753 DEFINE_IO_COMP_BATCH(iob);
2757 * Only spin for completions if we don't have multiple devices hanging
2758 * off our complete list.
2760 if (ctx->poll_multi_queue || force_nonspin)
2761 poll_flags |= BLK_POLL_ONESHOT;
2763 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2764 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2765 struct kiocb *kiocb = &req->rw.kiocb;
2769 * Move completed and retryable entries to our local lists.
2770 * If we find a request that requires polling, break out
2771 * and complete those lists first, if we have entries there.
2773 if (READ_ONCE(req->iopoll_completed))
2776 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2777 if (unlikely(ret < 0))
2780 poll_flags |= BLK_POLL_ONESHOT;
2782 /* iopoll may have completed current req */
2783 if (!rq_list_empty(iob.req_list) ||
2784 READ_ONCE(req->iopoll_completed))
2788 if (!rq_list_empty(iob.req_list))
2794 wq_list_for_each_resume(pos, prev) {
2795 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2797 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2798 if (!smp_load_acquire(&req->iopoll_completed))
2801 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2803 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
2806 if (unlikely(!nr_events))
2809 io_commit_cqring(ctx);
2810 io_cqring_ev_posted_iopoll(ctx);
2811 pos = start ? start->next : ctx->iopoll_list.first;
2812 wq_list_cut(&ctx->iopoll_list, prev, start);
2813 io_free_batch_list(ctx, pos);
2818 * We can't just wait for polled events to come to us, we have to actively
2819 * find and complete them.
2821 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2823 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2826 mutex_lock(&ctx->uring_lock);
2827 while (!wq_list_empty(&ctx->iopoll_list)) {
2828 /* let it sleep and repeat later if can't complete a request */
2829 if (io_do_iopoll(ctx, true) == 0)
2832 * Ensure we allow local-to-the-cpu processing to take place,
2833 * in this case we need to ensure that we reap all events.
2834 * Also let task_work, etc. to progress by releasing the mutex
2836 if (need_resched()) {
2837 mutex_unlock(&ctx->uring_lock);
2839 mutex_lock(&ctx->uring_lock);
2842 mutex_unlock(&ctx->uring_lock);
2845 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2847 unsigned int nr_events = 0;
2851 * We disallow the app entering submit/complete with polling, but we
2852 * still need to lock the ring to prevent racing with polled issue
2853 * that got punted to a workqueue.
2855 mutex_lock(&ctx->uring_lock);
2857 * Don't enter poll loop if we already have events pending.
2858 * If we do, we can potentially be spinning for commands that
2859 * already triggered a CQE (eg in error).
2861 if (test_bit(0, &ctx->check_cq_overflow))
2862 __io_cqring_overflow_flush(ctx, false);
2863 if (io_cqring_events(ctx))
2867 * If a submit got punted to a workqueue, we can have the
2868 * application entering polling for a command before it gets
2869 * issued. That app will hold the uring_lock for the duration
2870 * of the poll right here, so we need to take a breather every
2871 * now and then to ensure that the issue has a chance to add
2872 * the poll to the issued list. Otherwise we can spin here
2873 * forever, while the workqueue is stuck trying to acquire the
2876 if (wq_list_empty(&ctx->iopoll_list)) {
2877 u32 tail = ctx->cached_cq_tail;
2879 mutex_unlock(&ctx->uring_lock);
2881 mutex_lock(&ctx->uring_lock);
2883 /* some requests don't go through iopoll_list */
2884 if (tail != ctx->cached_cq_tail ||
2885 wq_list_empty(&ctx->iopoll_list))
2888 ret = io_do_iopoll(ctx, !min);
2893 } while (nr_events < min && !need_resched());
2895 mutex_unlock(&ctx->uring_lock);
2899 static void kiocb_end_write(struct io_kiocb *req)
2902 * Tell lockdep we inherited freeze protection from submission
2905 if (req->flags & REQ_F_ISREG) {
2906 struct super_block *sb = file_inode(req->file)->i_sb;
2908 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2914 static bool io_resubmit_prep(struct io_kiocb *req)
2916 struct io_async_rw *rw = req->async_data;
2918 if (!req_has_async_data(req))
2919 return !io_req_prep_async(req);
2920 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2924 static bool io_rw_should_reissue(struct io_kiocb *req)
2926 umode_t mode = file_inode(req->file)->i_mode;
2927 struct io_ring_ctx *ctx = req->ctx;
2929 if (!S_ISBLK(mode) && !S_ISREG(mode))
2931 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2932 !(ctx->flags & IORING_SETUP_IOPOLL)))
2935 * If ref is dying, we might be running poll reap from the exit work.
2936 * Don't attempt to reissue from that path, just let it fail with
2939 if (percpu_ref_is_dying(&ctx->refs))
2942 * Play it safe and assume not safe to re-import and reissue if we're
2943 * not in the original thread group (or in task context).
2945 if (!same_thread_group(req->task, current) || !in_task())
2950 static bool io_resubmit_prep(struct io_kiocb *req)
2954 static bool io_rw_should_reissue(struct io_kiocb *req)
2960 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2962 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
2963 kiocb_end_write(req);
2964 fsnotify_modify(req->file);
2966 fsnotify_access(req->file);
2968 if (unlikely(res != req->result)) {
2969 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2970 io_rw_should_reissue(req)) {
2971 req->flags |= REQ_F_REISSUE;
2980 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2982 int res = req->result;
2985 io_req_complete_state(req, res, io_put_kbuf(req, 0));
2986 io_req_add_compl_list(req);
2988 io_req_complete_post(req, res,
2989 io_put_kbuf(req, IO_URING_F_UNLOCKED));
2993 static void __io_complete_rw(struct io_kiocb *req, long res,
2994 unsigned int issue_flags)
2996 if (__io_complete_rw_common(req, res))
2998 __io_req_complete(req, issue_flags, req->result,
2999 io_put_kbuf(req, issue_flags));
3002 static void io_complete_rw(struct kiocb *kiocb, long res)
3004 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3006 if (__io_complete_rw_common(req, res))
3009 req->io_task_work.func = io_req_task_complete;
3010 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3013 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3015 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3017 if (kiocb->ki_flags & IOCB_WRITE)
3018 kiocb_end_write(req);
3019 if (unlikely(res != req->result)) {
3020 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3021 req->flags |= REQ_F_REISSUE;
3027 /* order with io_iopoll_complete() checking ->iopoll_completed */
3028 smp_store_release(&req->iopoll_completed, 1);
3032 * After the iocb has been issued, it's safe to be found on the poll list.
3033 * Adding the kiocb to the list AFTER submission ensures that we don't
3034 * find it from a io_do_iopoll() thread before the issuer is done
3035 * accessing the kiocb cookie.
3037 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3039 struct io_ring_ctx *ctx = req->ctx;
3040 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3042 /* workqueue context doesn't hold uring_lock, grab it now */
3043 if (unlikely(needs_lock))
3044 mutex_lock(&ctx->uring_lock);
3047 * Track whether we have multiple files in our lists. This will impact
3048 * how we do polling eventually, not spinning if we're on potentially
3049 * different devices.
3051 if (wq_list_empty(&ctx->iopoll_list)) {
3052 ctx->poll_multi_queue = false;
3053 } else if (!ctx->poll_multi_queue) {
3054 struct io_kiocb *list_req;
3056 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3058 if (list_req->file != req->file)
3059 ctx->poll_multi_queue = true;
3063 * For fast devices, IO may have already completed. If it has, add
3064 * it to the front so we find it first.
3066 if (READ_ONCE(req->iopoll_completed))
3067 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3069 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3071 if (unlikely(needs_lock)) {
3073 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3074 * in sq thread task context or in io worker task context. If
3075 * current task context is sq thread, we don't need to check
3076 * whether should wake up sq thread.
3078 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3079 wq_has_sleeper(&ctx->sq_data->wait))
3080 wake_up(&ctx->sq_data->wait);
3082 mutex_unlock(&ctx->uring_lock);
3086 static bool io_bdev_nowait(struct block_device *bdev)
3088 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3092 * If we tracked the file through the SCM inflight mechanism, we could support
3093 * any file. For now, just ensure that anything potentially problematic is done
3096 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3098 if (S_ISBLK(mode)) {
3099 if (IS_ENABLED(CONFIG_BLOCK) &&
3100 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3106 if (S_ISREG(mode)) {
3107 if (IS_ENABLED(CONFIG_BLOCK) &&
3108 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3109 file->f_op != &io_uring_fops)
3114 /* any ->read/write should understand O_NONBLOCK */
3115 if (file->f_flags & O_NONBLOCK)
3117 return file->f_mode & FMODE_NOWAIT;
3121 * If we tracked the file through the SCM inflight mechanism, we could support
3122 * any file. For now, just ensure that anything potentially problematic is done
3125 static unsigned int io_file_get_flags(struct file *file)
3127 umode_t mode = file_inode(file)->i_mode;
3128 unsigned int res = 0;
3132 if (__io_file_supports_nowait(file, mode))
3137 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3139 return req->flags & REQ_F_SUPPORT_NOWAIT;
3142 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3144 struct kiocb *kiocb = &req->rw.kiocb;
3148 kiocb->ki_pos = READ_ONCE(sqe->off);
3150 ioprio = READ_ONCE(sqe->ioprio);
3152 ret = ioprio_check_cap(ioprio);
3156 kiocb->ki_ioprio = ioprio;
3158 kiocb->ki_ioprio = get_current_ioprio();
3162 req->rw.addr = READ_ONCE(sqe->addr);
3163 req->rw.len = READ_ONCE(sqe->len);
3164 req->rw.flags = READ_ONCE(sqe->rw_flags);
3165 req->buf_index = READ_ONCE(sqe->buf_index);
3169 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3175 case -ERESTARTNOINTR:
3176 case -ERESTARTNOHAND:
3177 case -ERESTART_RESTARTBLOCK:
3179 * We can't just restart the syscall, since previously
3180 * submitted sqes may already be in progress. Just fail this
3186 kiocb->ki_complete(kiocb, ret);
3190 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3192 struct kiocb *kiocb = &req->rw.kiocb;
3194 if (kiocb->ki_pos != -1)
3195 return &kiocb->ki_pos;
3197 if (!(req->file->f_mode & FMODE_STREAM)) {
3198 req->flags |= REQ_F_CUR_POS;
3199 kiocb->ki_pos = req->file->f_pos;
3200 return &kiocb->ki_pos;
3207 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3208 unsigned int issue_flags)
3210 struct io_async_rw *io = req->async_data;
3212 /* add previously done IO, if any */
3213 if (req_has_async_data(req) && io->bytes_done > 0) {
3215 ret = io->bytes_done;
3217 ret += io->bytes_done;
3220 if (req->flags & REQ_F_CUR_POS)
3221 req->file->f_pos = req->rw.kiocb.ki_pos;
3222 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3223 __io_complete_rw(req, ret, issue_flags);
3225 io_rw_done(&req->rw.kiocb, ret);
3227 if (req->flags & REQ_F_REISSUE) {
3228 req->flags &= ~REQ_F_REISSUE;
3229 if (io_resubmit_prep(req))
3230 io_req_task_queue_reissue(req);
3232 io_req_task_queue_fail(req, ret);
3236 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3237 struct io_mapped_ubuf *imu)
3239 size_t len = req->rw.len;
3240 u64 buf_end, buf_addr = req->rw.addr;
3243 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3245 /* not inside the mapped region */
3246 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3250 * May not be a start of buffer, set size appropriately
3251 * and advance us to the beginning.
3253 offset = buf_addr - imu->ubuf;
3254 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3258 * Don't use iov_iter_advance() here, as it's really slow for
3259 * using the latter parts of a big fixed buffer - it iterates
3260 * over each segment manually. We can cheat a bit here, because
3263 * 1) it's a BVEC iter, we set it up
3264 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3265 * first and last bvec
3267 * So just find our index, and adjust the iterator afterwards.
3268 * If the offset is within the first bvec (or the whole first
3269 * bvec, just use iov_iter_advance(). This makes it easier
3270 * since we can just skip the first segment, which may not
3271 * be PAGE_SIZE aligned.
3273 const struct bio_vec *bvec = imu->bvec;
3275 if (offset <= bvec->bv_len) {
3276 iov_iter_advance(iter, offset);
3278 unsigned long seg_skip;
3280 /* skip first vec */
3281 offset -= bvec->bv_len;
3282 seg_skip = 1 + (offset >> PAGE_SHIFT);
3284 iter->bvec = bvec + seg_skip;
3285 iter->nr_segs -= seg_skip;
3286 iter->count -= bvec->bv_len + offset;
3287 iter->iov_offset = offset & ~PAGE_MASK;
3294 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3295 unsigned int issue_flags)
3297 struct io_mapped_ubuf *imu = req->imu;
3298 u16 index, buf_index = req->buf_index;
3301 struct io_ring_ctx *ctx = req->ctx;
3303 if (unlikely(buf_index >= ctx->nr_user_bufs))
3305 io_req_set_rsrc_node(req, ctx, issue_flags);
3306 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3307 imu = READ_ONCE(ctx->user_bufs[index]);
3310 return __io_import_fixed(req, rw, iter, imu);
3313 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3316 mutex_unlock(&ctx->uring_lock);
3319 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3322 * "Normal" inline submissions always hold the uring_lock, since we
3323 * grab it from the system call. Same is true for the SQPOLL offload.
3324 * The only exception is when we've detached the request and issue it
3325 * from an async worker thread, grab the lock for that case.
3328 mutex_lock(&ctx->uring_lock);
3331 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3332 struct io_buffer_list *bl, unsigned int bgid)
3334 struct list_head *list;
3336 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3337 INIT_LIST_HEAD(&bl->buf_list);
3339 list_add(&bl->list, list);
3342 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3343 int bgid, unsigned int issue_flags)
3345 struct io_buffer *kbuf = req->kbuf;
3346 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3347 struct io_ring_ctx *ctx = req->ctx;
3348 struct io_buffer_list *bl;
3350 if (req->flags & REQ_F_BUFFER_SELECTED)
3353 io_ring_submit_lock(ctx, needs_lock);
3355 lockdep_assert_held(&ctx->uring_lock);
3357 bl = io_buffer_get_list(ctx, bgid);
3358 if (bl && !list_empty(&bl->buf_list)) {
3359 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3360 list_del(&kbuf->list);
3361 if (*len > kbuf->len)
3363 req->flags |= REQ_F_BUFFER_SELECTED;
3366 kbuf = ERR_PTR(-ENOBUFS);
3369 io_ring_submit_unlock(req->ctx, needs_lock);
3373 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3374 unsigned int issue_flags)
3376 struct io_buffer *kbuf;
3379 bgid = req->buf_index;
3380 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3383 return u64_to_user_ptr(kbuf->addr);
3386 #ifdef CONFIG_COMPAT
3387 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3388 unsigned int issue_flags)
3390 struct compat_iovec __user *uiov;
3391 compat_ssize_t clen;
3395 uiov = u64_to_user_ptr(req->rw.addr);
3396 if (!access_ok(uiov, sizeof(*uiov)))
3398 if (__get_user(clen, &uiov->iov_len))
3404 buf = io_rw_buffer_select(req, &len, issue_flags);
3406 return PTR_ERR(buf);
3407 iov[0].iov_base = buf;
3408 iov[0].iov_len = (compat_size_t) len;
3413 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3414 unsigned int issue_flags)
3416 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3420 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3423 len = iov[0].iov_len;
3426 buf = io_rw_buffer_select(req, &len, issue_flags);
3428 return PTR_ERR(buf);
3429 iov[0].iov_base = buf;
3430 iov[0].iov_len = len;
3434 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3435 unsigned int issue_flags)
3437 if (req->flags & REQ_F_BUFFER_SELECTED) {
3438 struct io_buffer *kbuf = req->kbuf;
3440 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3441 iov[0].iov_len = kbuf->len;
3444 if (req->rw.len != 1)
3447 #ifdef CONFIG_COMPAT
3448 if (req->ctx->compat)
3449 return io_compat_import(req, iov, issue_flags);
3452 return __io_iov_buffer_select(req, iov, issue_flags);
3455 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3456 struct io_rw_state *s,
3457 unsigned int issue_flags)
3459 struct iov_iter *iter = &s->iter;
3460 u8 opcode = req->opcode;
3461 struct iovec *iovec;
3466 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3467 ret = io_import_fixed(req, rw, iter, issue_flags);
3469 return ERR_PTR(ret);
3473 /* buffer index only valid with fixed read/write, or buffer select */
3474 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3475 return ERR_PTR(-EINVAL);
3477 buf = u64_to_user_ptr(req->rw.addr);
3478 sqe_len = req->rw.len;
3480 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3481 if (req->flags & REQ_F_BUFFER_SELECT) {
3482 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3484 return ERR_CAST(buf);
3485 req->rw.len = sqe_len;
3488 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3490 return ERR_PTR(ret);
3494 iovec = s->fast_iov;
3495 if (req->flags & REQ_F_BUFFER_SELECT) {
3496 ret = io_iov_buffer_select(req, iovec, issue_flags);
3498 return ERR_PTR(ret);
3499 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3503 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3505 if (unlikely(ret < 0))
3506 return ERR_PTR(ret);
3510 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3511 struct iovec **iovec, struct io_rw_state *s,
3512 unsigned int issue_flags)
3514 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3515 if (unlikely(IS_ERR(*iovec)))
3516 return PTR_ERR(*iovec);
3518 iov_iter_save_state(&s->iter, &s->iter_state);
3522 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3524 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3528 * For files that don't have ->read_iter() and ->write_iter(), handle them
3529 * by looping over ->read() or ->write() manually.
3531 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3533 struct kiocb *kiocb = &req->rw.kiocb;
3534 struct file *file = req->file;
3539 * Don't support polled IO through this interface, and we can't
3540 * support non-blocking either. For the latter, this just causes
3541 * the kiocb to be handled from an async context.
3543 if (kiocb->ki_flags & IOCB_HIPRI)
3545 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3546 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3549 ppos = io_kiocb_ppos(kiocb);
3551 while (iov_iter_count(iter)) {
3555 if (!iov_iter_is_bvec(iter)) {
3556 iovec = iov_iter_iovec(iter);
3558 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3559 iovec.iov_len = req->rw.len;
3563 nr = file->f_op->read(file, iovec.iov_base,
3564 iovec.iov_len, ppos);
3566 nr = file->f_op->write(file, iovec.iov_base,
3567 iovec.iov_len, ppos);
3576 if (!iov_iter_is_bvec(iter)) {
3577 iov_iter_advance(iter, nr);
3584 if (nr != iovec.iov_len)
3591 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3592 const struct iovec *fast_iov, struct iov_iter *iter)
3594 struct io_async_rw *rw = req->async_data;
3596 memcpy(&rw->s.iter, iter, sizeof(*iter));
3597 rw->free_iovec = iovec;
3599 /* can only be fixed buffers, no need to do anything */
3600 if (iov_iter_is_bvec(iter))
3603 unsigned iov_off = 0;
3605 rw->s.iter.iov = rw->s.fast_iov;
3606 if (iter->iov != fast_iov) {
3607 iov_off = iter->iov - fast_iov;
3608 rw->s.iter.iov += iov_off;
3610 if (rw->s.fast_iov != fast_iov)
3611 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3612 sizeof(struct iovec) * iter->nr_segs);
3614 req->flags |= REQ_F_NEED_CLEANUP;
3618 static inline bool io_alloc_async_data(struct io_kiocb *req)
3620 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3621 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3622 if (req->async_data) {
3623 req->flags |= REQ_F_ASYNC_DATA;
3629 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3630 struct io_rw_state *s, bool force)
3632 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3634 if (!req_has_async_data(req)) {
3635 struct io_async_rw *iorw;
3637 if (io_alloc_async_data(req)) {
3642 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3643 iorw = req->async_data;
3644 /* we've copied and mapped the iter, ensure state is saved */
3645 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3650 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3652 struct io_async_rw *iorw = req->async_data;
3656 /* submission path, ->uring_lock should already be taken */
3657 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3658 if (unlikely(ret < 0))
3661 iorw->bytes_done = 0;
3662 iorw->free_iovec = iov;
3664 req->flags |= REQ_F_NEED_CLEANUP;
3669 * This is our waitqueue callback handler, registered through __folio_lock_async()
3670 * when we initially tried to do the IO with the iocb armed our waitqueue.
3671 * This gets called when the page is unlocked, and we generally expect that to
3672 * happen when the page IO is completed and the page is now uptodate. This will
3673 * queue a task_work based retry of the operation, attempting to copy the data
3674 * again. If the latter fails because the page was NOT uptodate, then we will
3675 * do a thread based blocking retry of the operation. That's the unexpected
3678 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3679 int sync, void *arg)
3681 struct wait_page_queue *wpq;
3682 struct io_kiocb *req = wait->private;
3683 struct wait_page_key *key = arg;
3685 wpq = container_of(wait, struct wait_page_queue, wait);
3687 if (!wake_page_match(wpq, key))
3690 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3691 list_del_init(&wait->entry);
3692 io_req_task_queue(req);
3697 * This controls whether a given IO request should be armed for async page
3698 * based retry. If we return false here, the request is handed to the async
3699 * worker threads for retry. If we're doing buffered reads on a regular file,
3700 * we prepare a private wait_page_queue entry and retry the operation. This
3701 * will either succeed because the page is now uptodate and unlocked, or it
3702 * will register a callback when the page is unlocked at IO completion. Through
3703 * that callback, io_uring uses task_work to setup a retry of the operation.
3704 * That retry will attempt the buffered read again. The retry will generally
3705 * succeed, or in rare cases where it fails, we then fall back to using the
3706 * async worker threads for a blocking retry.
3708 static bool io_rw_should_retry(struct io_kiocb *req)
3710 struct io_async_rw *rw = req->async_data;
3711 struct wait_page_queue *wait = &rw->wpq;
3712 struct kiocb *kiocb = &req->rw.kiocb;
3714 /* never retry for NOWAIT, we just complete with -EAGAIN */
3715 if (req->flags & REQ_F_NOWAIT)
3718 /* Only for buffered IO */
3719 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3723 * just use poll if we can, and don't attempt if the fs doesn't
3724 * support callback based unlocks
3726 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3729 wait->wait.func = io_async_buf_func;
3730 wait->wait.private = req;
3731 wait->wait.flags = 0;
3732 INIT_LIST_HEAD(&wait->wait.entry);
3733 kiocb->ki_flags |= IOCB_WAITQ;
3734 kiocb->ki_flags &= ~IOCB_NOWAIT;
3735 kiocb->ki_waitq = wait;
3739 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3741 if (likely(req->file->f_op->read_iter))
3742 return call_read_iter(req->file, &req->rw.kiocb, iter);
3743 else if (req->file->f_op->read)
3744 return loop_rw_iter(READ, req, iter);
3749 static bool need_read_all(struct io_kiocb *req)
3751 return req->flags & REQ_F_ISREG ||
3752 S_ISBLK(file_inode(req->file)->i_mode);
3755 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3757 struct kiocb *kiocb = &req->rw.kiocb;
3758 struct io_ring_ctx *ctx = req->ctx;
3759 struct file *file = req->file;
3762 if (unlikely(!file || !(file->f_mode & mode)))
3765 if (!io_req_ffs_set(req))
3766 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3768 kiocb->ki_flags = iocb_flags(file);
3769 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
3774 * If the file is marked O_NONBLOCK, still allow retry for it if it
3775 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3776 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3778 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3779 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3780 req->flags |= REQ_F_NOWAIT;
3782 if (ctx->flags & IORING_SETUP_IOPOLL) {
3783 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3786 kiocb->private = NULL;
3787 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3788 kiocb->ki_complete = io_complete_rw_iopoll;
3789 req->iopoll_completed = 0;
3791 if (kiocb->ki_flags & IOCB_HIPRI)
3793 kiocb->ki_complete = io_complete_rw;
3799 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3801 struct io_rw_state __s, *s = &__s;
3802 struct iovec *iovec;
3803 struct kiocb *kiocb = &req->rw.kiocb;
3804 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3805 struct io_async_rw *rw;
3809 if (!req_has_async_data(req)) {
3810 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3811 if (unlikely(ret < 0))
3815 * Safe and required to re-import if we're using provided
3816 * buffers, as we dropped the selected one before retry.
3818 if (req->flags & REQ_F_BUFFER_SELECT) {
3819 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3820 if (unlikely(ret < 0))
3824 rw = req->async_data;
3827 * We come here from an earlier attempt, restore our state to
3828 * match in case it doesn't. It's cheap enough that we don't
3829 * need to make this conditional.
3831 iov_iter_restore(&s->iter, &s->iter_state);
3834 ret = io_rw_init_file(req, FMODE_READ);
3835 if (unlikely(ret)) {
3839 req->result = iov_iter_count(&s->iter);
3841 if (force_nonblock) {
3842 /* If the file doesn't support async, just async punt */
3843 if (unlikely(!io_file_supports_nowait(req))) {
3844 ret = io_setup_async_rw(req, iovec, s, true);
3845 return ret ?: -EAGAIN;
3847 kiocb->ki_flags |= IOCB_NOWAIT;
3849 /* Ensure we clear previously set non-block flag */
3850 kiocb->ki_flags &= ~IOCB_NOWAIT;
3853 ppos = io_kiocb_update_pos(req);
3855 ret = rw_verify_area(READ, req->file, ppos, req->result);
3856 if (unlikely(ret)) {
3861 ret = io_iter_do_read(req, &s->iter);
3863 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3864 req->flags &= ~REQ_F_REISSUE;
3865 /* if we can poll, just do that */
3866 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3868 /* IOPOLL retry should happen for io-wq threads */
3869 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3871 /* no retry on NONBLOCK nor RWF_NOWAIT */
3872 if (req->flags & REQ_F_NOWAIT)
3875 } else if (ret == -EIOCBQUEUED) {
3877 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3878 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3879 /* read all, failed, already did sync or don't want to retry */
3884 * Don't depend on the iter state matching what was consumed, or being
3885 * untouched in case of error. Restore it and we'll advance it
3886 * manually if we need to.
3888 iov_iter_restore(&s->iter, &s->iter_state);
3890 ret2 = io_setup_async_rw(req, iovec, s, true);
3895 rw = req->async_data;
3898 * Now use our persistent iterator and state, if we aren't already.
3899 * We've restored and mapped the iter to match.
3904 * We end up here because of a partial read, either from
3905 * above or inside this loop. Advance the iter by the bytes
3906 * that were consumed.
3908 iov_iter_advance(&s->iter, ret);
3909 if (!iov_iter_count(&s->iter))
3911 rw->bytes_done += ret;
3912 iov_iter_save_state(&s->iter, &s->iter_state);
3914 /* if we can retry, do so with the callbacks armed */
3915 if (!io_rw_should_retry(req)) {
3916 kiocb->ki_flags &= ~IOCB_WAITQ;
3921 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3922 * we get -EIOCBQUEUED, then we'll get a notification when the
3923 * desired page gets unlocked. We can also get a partial read
3924 * here, and if we do, then just retry at the new offset.
3926 ret = io_iter_do_read(req, &s->iter);
3927 if (ret == -EIOCBQUEUED)
3929 /* we got some bytes, but not all. retry. */
3930 kiocb->ki_flags &= ~IOCB_WAITQ;
3931 iov_iter_restore(&s->iter, &s->iter_state);
3934 kiocb_done(req, ret, issue_flags);
3936 /* it's faster to check here then delegate to kfree */
3942 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3944 struct io_rw_state __s, *s = &__s;
3945 struct iovec *iovec;
3946 struct kiocb *kiocb = &req->rw.kiocb;
3947 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3951 if (!req_has_async_data(req)) {
3952 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3953 if (unlikely(ret < 0))
3956 struct io_async_rw *rw = req->async_data;
3959 iov_iter_restore(&s->iter, &s->iter_state);
3962 ret = io_rw_init_file(req, FMODE_WRITE);
3963 if (unlikely(ret)) {
3967 req->result = iov_iter_count(&s->iter);
3969 if (force_nonblock) {
3970 /* If the file doesn't support async, just async punt */
3971 if (unlikely(!io_file_supports_nowait(req)))
3974 /* file path doesn't support NOWAIT for non-direct_IO */
3975 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3976 (req->flags & REQ_F_ISREG))
3979 kiocb->ki_flags |= IOCB_NOWAIT;
3981 /* Ensure we clear previously set non-block flag */
3982 kiocb->ki_flags &= ~IOCB_NOWAIT;
3985 ppos = io_kiocb_update_pos(req);
3987 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3992 * Open-code file_start_write here to grab freeze protection,
3993 * which will be released by another thread in
3994 * io_complete_rw(). Fool lockdep by telling it the lock got
3995 * released so that it doesn't complain about the held lock when
3996 * we return to userspace.
3998 if (req->flags & REQ_F_ISREG) {
3999 sb_start_write(file_inode(req->file)->i_sb);
4000 __sb_writers_release(file_inode(req->file)->i_sb,
4003 kiocb->ki_flags |= IOCB_WRITE;
4005 if (likely(req->file->f_op->write_iter))
4006 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4007 else if (req->file->f_op->write)
4008 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4012 if (req->flags & REQ_F_REISSUE) {
4013 req->flags &= ~REQ_F_REISSUE;
4018 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4019 * retry them without IOCB_NOWAIT.
4021 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4023 /* no retry on NONBLOCK nor RWF_NOWAIT */
4024 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4026 if (!force_nonblock || ret2 != -EAGAIN) {
4027 /* IOPOLL retry should happen for io-wq threads */
4028 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4031 kiocb_done(req, ret2, issue_flags);
4034 iov_iter_restore(&s->iter, &s->iter_state);
4035 ret = io_setup_async_rw(req, iovec, s, false);
4036 return ret ?: -EAGAIN;
4039 /* it's reportedly faster than delegating the null check to kfree() */
4045 static int io_renameat_prep(struct io_kiocb *req,
4046 const struct io_uring_sqe *sqe)
4048 struct io_rename *ren = &req->rename;
4049 const char __user *oldf, *newf;
4051 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4053 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4055 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4058 ren->old_dfd = READ_ONCE(sqe->fd);
4059 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4060 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4061 ren->new_dfd = READ_ONCE(sqe->len);
4062 ren->flags = READ_ONCE(sqe->rename_flags);
4064 ren->oldpath = getname(oldf);
4065 if (IS_ERR(ren->oldpath))
4066 return PTR_ERR(ren->oldpath);
4068 ren->newpath = getname(newf);
4069 if (IS_ERR(ren->newpath)) {
4070 putname(ren->oldpath);
4071 return PTR_ERR(ren->newpath);
4074 req->flags |= REQ_F_NEED_CLEANUP;
4078 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4080 struct io_rename *ren = &req->rename;
4083 if (issue_flags & IO_URING_F_NONBLOCK)
4086 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4087 ren->newpath, ren->flags);
4089 req->flags &= ~REQ_F_NEED_CLEANUP;
4092 io_req_complete(req, ret);
4096 static int io_unlinkat_prep(struct io_kiocb *req,
4097 const struct io_uring_sqe *sqe)
4099 struct io_unlink *un = &req->unlink;
4100 const char __user *fname;
4102 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4104 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4107 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4110 un->dfd = READ_ONCE(sqe->fd);
4112 un->flags = READ_ONCE(sqe->unlink_flags);
4113 if (un->flags & ~AT_REMOVEDIR)
4116 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4117 un->filename = getname(fname);
4118 if (IS_ERR(un->filename))
4119 return PTR_ERR(un->filename);
4121 req->flags |= REQ_F_NEED_CLEANUP;
4125 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4127 struct io_unlink *un = &req->unlink;
4130 if (issue_flags & IO_URING_F_NONBLOCK)
4133 if (un->flags & AT_REMOVEDIR)
4134 ret = do_rmdir(un->dfd, un->filename);
4136 ret = do_unlinkat(un->dfd, un->filename);
4138 req->flags &= ~REQ_F_NEED_CLEANUP;
4141 io_req_complete(req, ret);
4145 static int io_mkdirat_prep(struct io_kiocb *req,
4146 const struct io_uring_sqe *sqe)
4148 struct io_mkdir *mkd = &req->mkdir;
4149 const char __user *fname;
4151 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4153 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4156 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4159 mkd->dfd = READ_ONCE(sqe->fd);
4160 mkd->mode = READ_ONCE(sqe->len);
4162 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4163 mkd->filename = getname(fname);
4164 if (IS_ERR(mkd->filename))
4165 return PTR_ERR(mkd->filename);
4167 req->flags |= REQ_F_NEED_CLEANUP;
4171 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4173 struct io_mkdir *mkd = &req->mkdir;
4176 if (issue_flags & IO_URING_F_NONBLOCK)
4179 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4181 req->flags &= ~REQ_F_NEED_CLEANUP;
4184 io_req_complete(req, ret);
4188 static int io_symlinkat_prep(struct io_kiocb *req,
4189 const struct io_uring_sqe *sqe)
4191 struct io_symlink *sl = &req->symlink;
4192 const char __user *oldpath, *newpath;
4194 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4196 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4199 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4202 sl->new_dfd = READ_ONCE(sqe->fd);
4203 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4204 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4206 sl->oldpath = getname(oldpath);
4207 if (IS_ERR(sl->oldpath))
4208 return PTR_ERR(sl->oldpath);
4210 sl->newpath = getname(newpath);
4211 if (IS_ERR(sl->newpath)) {
4212 putname(sl->oldpath);
4213 return PTR_ERR(sl->newpath);
4216 req->flags |= REQ_F_NEED_CLEANUP;
4220 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4222 struct io_symlink *sl = &req->symlink;
4225 if (issue_flags & IO_URING_F_NONBLOCK)
4228 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4230 req->flags &= ~REQ_F_NEED_CLEANUP;
4233 io_req_complete(req, ret);
4237 static int io_linkat_prep(struct io_kiocb *req,
4238 const struct io_uring_sqe *sqe)
4240 struct io_hardlink *lnk = &req->hardlink;
4241 const char __user *oldf, *newf;
4243 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4245 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4247 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4250 lnk->old_dfd = READ_ONCE(sqe->fd);
4251 lnk->new_dfd = READ_ONCE(sqe->len);
4252 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4253 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4254 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4256 lnk->oldpath = getname(oldf);
4257 if (IS_ERR(lnk->oldpath))
4258 return PTR_ERR(lnk->oldpath);
4260 lnk->newpath = getname(newf);
4261 if (IS_ERR(lnk->newpath)) {
4262 putname(lnk->oldpath);
4263 return PTR_ERR(lnk->newpath);
4266 req->flags |= REQ_F_NEED_CLEANUP;
4270 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4272 struct io_hardlink *lnk = &req->hardlink;
4275 if (issue_flags & IO_URING_F_NONBLOCK)
4278 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4279 lnk->newpath, lnk->flags);
4281 req->flags &= ~REQ_F_NEED_CLEANUP;
4284 io_req_complete(req, ret);
4288 static int io_shutdown_prep(struct io_kiocb *req,
4289 const struct io_uring_sqe *sqe)
4291 #if defined(CONFIG_NET)
4292 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4294 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4295 sqe->buf_index || sqe->splice_fd_in))
4298 req->shutdown.how = READ_ONCE(sqe->len);
4305 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4307 #if defined(CONFIG_NET)
4308 struct socket *sock;
4311 if (issue_flags & IO_URING_F_NONBLOCK)
4314 sock = sock_from_file(req->file);
4315 if (unlikely(!sock))
4318 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4321 io_req_complete(req, ret);
4328 static int __io_splice_prep(struct io_kiocb *req,
4329 const struct io_uring_sqe *sqe)
4331 struct io_splice *sp = &req->splice;
4332 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4334 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4337 sp->len = READ_ONCE(sqe->len);
4338 sp->flags = READ_ONCE(sqe->splice_flags);
4339 if (unlikely(sp->flags & ~valid_flags))
4341 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4345 static int io_tee_prep(struct io_kiocb *req,
4346 const struct io_uring_sqe *sqe)
4348 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4350 return __io_splice_prep(req, sqe);
4353 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4355 struct io_splice *sp = &req->splice;
4356 struct file *out = sp->file_out;
4357 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4361 if (issue_flags & IO_URING_F_NONBLOCK)
4364 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4365 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4367 in = io_file_get_normal(req, sp->splice_fd_in);
4374 ret = do_tee(in, out, sp->len, flags);
4376 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4381 io_req_complete(req, ret);
4385 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4387 struct io_splice *sp = &req->splice;
4389 sp->off_in = READ_ONCE(sqe->splice_off_in);
4390 sp->off_out = READ_ONCE(sqe->off);
4391 return __io_splice_prep(req, sqe);
4394 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4396 struct io_splice *sp = &req->splice;
4397 struct file *out = sp->file_out;
4398 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4399 loff_t *poff_in, *poff_out;
4403 if (issue_flags & IO_URING_F_NONBLOCK)
4406 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4407 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4409 in = io_file_get_normal(req, sp->splice_fd_in);
4415 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4416 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4419 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4421 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4426 io_req_complete(req, ret);
4431 * IORING_OP_NOP just posts a completion event, nothing else.
4433 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4435 struct io_ring_ctx *ctx = req->ctx;
4437 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4440 __io_req_complete(req, issue_flags, 0, 0);
4444 static int io_msg_ring_prep(struct io_kiocb *req,
4445 const struct io_uring_sqe *sqe)
4447 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4448 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4451 req->msg.user_data = READ_ONCE(sqe->off);
4452 req->msg.len = READ_ONCE(sqe->len);
4456 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4458 struct io_ring_ctx *target_ctx;
4459 struct io_msg *msg = &req->msg;
4464 if (req->file->f_op != &io_uring_fops)
4468 target_ctx = req->file->private_data;
4470 spin_lock(&target_ctx->completion_lock);
4471 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
4472 io_commit_cqring(target_ctx);
4473 spin_unlock(&target_ctx->completion_lock);
4476 io_cqring_ev_posted(target_ctx);
4483 __io_req_complete(req, issue_flags, ret, 0);
4487 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4489 struct io_ring_ctx *ctx = req->ctx;
4491 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4493 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4497 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4498 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4501 req->sync.off = READ_ONCE(sqe->off);
4502 req->sync.len = READ_ONCE(sqe->len);
4506 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4508 loff_t end = req->sync.off + req->sync.len;
4511 /* fsync always requires a blocking context */
4512 if (issue_flags & IO_URING_F_NONBLOCK)
4515 ret = vfs_fsync_range(req->file, req->sync.off,
4516 end > 0 ? end : LLONG_MAX,
4517 req->sync.flags & IORING_FSYNC_DATASYNC);
4520 io_req_complete(req, ret);
4524 static int io_fallocate_prep(struct io_kiocb *req,
4525 const struct io_uring_sqe *sqe)
4527 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4530 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4533 req->sync.off = READ_ONCE(sqe->off);
4534 req->sync.len = READ_ONCE(sqe->addr);
4535 req->sync.mode = READ_ONCE(sqe->len);
4539 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4543 /* fallocate always requiring blocking context */
4544 if (issue_flags & IO_URING_F_NONBLOCK)
4546 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4551 fsnotify_modify(req->file);
4552 io_req_complete(req, ret);
4556 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4558 const char __user *fname;
4561 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4563 if (unlikely(sqe->ioprio || sqe->buf_index))
4565 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4568 /* open.how should be already initialised */
4569 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4570 req->open.how.flags |= O_LARGEFILE;
4572 req->open.dfd = READ_ONCE(sqe->fd);
4573 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4574 req->open.filename = getname(fname);
4575 if (IS_ERR(req->open.filename)) {
4576 ret = PTR_ERR(req->open.filename);
4577 req->open.filename = NULL;
4581 req->open.file_slot = READ_ONCE(sqe->file_index);
4582 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4585 req->open.nofile = rlimit(RLIMIT_NOFILE);
4586 req->flags |= REQ_F_NEED_CLEANUP;
4590 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4592 u64 mode = READ_ONCE(sqe->len);
4593 u64 flags = READ_ONCE(sqe->open_flags);
4595 req->open.how = build_open_how(flags, mode);
4596 return __io_openat_prep(req, sqe);
4599 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4601 struct open_how __user *how;
4605 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4606 len = READ_ONCE(sqe->len);
4607 if (len < OPEN_HOW_SIZE_VER0)
4610 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4615 return __io_openat_prep(req, sqe);
4618 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4620 struct open_flags op;
4622 bool resolve_nonblock, nonblock_set;
4623 bool fixed = !!req->open.file_slot;
4626 ret = build_open_flags(&req->open.how, &op);
4629 nonblock_set = op.open_flag & O_NONBLOCK;
4630 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4631 if (issue_flags & IO_URING_F_NONBLOCK) {
4633 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4634 * it'll always -EAGAIN
4636 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4638 op.lookup_flags |= LOOKUP_CACHED;
4639 op.open_flag |= O_NONBLOCK;
4643 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4648 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4651 * We could hang on to this 'fd' on retrying, but seems like
4652 * marginal gain for something that is now known to be a slower
4653 * path. So just put it, and we'll get a new one when we retry.
4658 ret = PTR_ERR(file);
4659 /* only retry if RESOLVE_CACHED wasn't already set by application */
4660 if (ret == -EAGAIN &&
4661 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4666 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4667 file->f_flags &= ~O_NONBLOCK;
4668 fsnotify_open(file);
4671 fd_install(ret, file);
4673 ret = io_install_fixed_file(req, file, issue_flags,
4674 req->open.file_slot - 1);
4676 putname(req->open.filename);
4677 req->flags &= ~REQ_F_NEED_CLEANUP;
4680 __io_req_complete(req, issue_flags, ret, 0);
4684 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4686 return io_openat2(req, issue_flags);
4689 static int io_remove_buffers_prep(struct io_kiocb *req,
4690 const struct io_uring_sqe *sqe)
4692 struct io_provide_buf *p = &req->pbuf;
4695 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4699 tmp = READ_ONCE(sqe->fd);
4700 if (!tmp || tmp > USHRT_MAX)
4703 memset(p, 0, sizeof(*p));
4705 p->bgid = READ_ONCE(sqe->buf_group);
4709 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4710 struct io_buffer_list *bl, unsigned nbufs)
4714 /* shouldn't happen */
4718 /* the head kbuf is the list itself */
4719 while (!list_empty(&bl->buf_list)) {
4720 struct io_buffer *nxt;
4722 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4723 list_del(&nxt->list);
4733 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4735 struct io_provide_buf *p = &req->pbuf;
4736 struct io_ring_ctx *ctx = req->ctx;
4737 struct io_buffer_list *bl;
4739 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4741 io_ring_submit_lock(ctx, needs_lock);
4743 lockdep_assert_held(&ctx->uring_lock);
4746 bl = io_buffer_get_list(ctx, p->bgid);
4748 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4752 /* complete before unlock, IOPOLL may need the lock */
4753 __io_req_complete(req, issue_flags, ret, 0);
4754 io_ring_submit_unlock(ctx, needs_lock);
4758 static int io_provide_buffers_prep(struct io_kiocb *req,
4759 const struct io_uring_sqe *sqe)
4761 unsigned long size, tmp_check;
4762 struct io_provide_buf *p = &req->pbuf;
4765 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4768 tmp = READ_ONCE(sqe->fd);
4769 if (!tmp || tmp > USHRT_MAX)
4772 p->addr = READ_ONCE(sqe->addr);
4773 p->len = READ_ONCE(sqe->len);
4775 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4778 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4781 size = (unsigned long)p->len * p->nbufs;
4782 if (!access_ok(u64_to_user_ptr(p->addr), size))
4785 p->bgid = READ_ONCE(sqe->buf_group);
4786 tmp = READ_ONCE(sqe->off);
4787 if (tmp > USHRT_MAX)
4793 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4795 struct io_buffer *buf;
4800 * Completions that don't happen inline (eg not under uring_lock) will
4801 * add to ->io_buffers_comp. If we don't have any free buffers, check
4802 * the completion list and splice those entries first.
4804 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4805 spin_lock(&ctx->completion_lock);
4806 if (!list_empty(&ctx->io_buffers_comp)) {
4807 list_splice_init(&ctx->io_buffers_comp,
4808 &ctx->io_buffers_cache);
4809 spin_unlock(&ctx->completion_lock);
4812 spin_unlock(&ctx->completion_lock);
4816 * No free buffers and no completion entries either. Allocate a new
4817 * page worth of buffer entries and add those to our freelist.
4819 page = alloc_page(GFP_KERNEL_ACCOUNT);
4823 list_add(&page->lru, &ctx->io_buffers_pages);
4825 buf = page_address(page);
4826 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4827 while (bufs_in_page) {
4828 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4836 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4837 struct io_buffer_list *bl)
4839 struct io_buffer *buf;
4840 u64 addr = pbuf->addr;
4841 int i, bid = pbuf->bid;
4843 for (i = 0; i < pbuf->nbufs; i++) {
4844 if (list_empty(&ctx->io_buffers_cache) &&
4845 io_refill_buffer_cache(ctx))
4847 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4849 list_move_tail(&buf->list, &bl->buf_list);
4851 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4853 buf->bgid = pbuf->bgid;
4859 return i ? 0 : -ENOMEM;
4862 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4864 struct io_provide_buf *p = &req->pbuf;
4865 struct io_ring_ctx *ctx = req->ctx;
4866 struct io_buffer_list *bl;
4868 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4870 io_ring_submit_lock(ctx, needs_lock);
4872 lockdep_assert_held(&ctx->uring_lock);
4874 bl = io_buffer_get_list(ctx, p->bgid);
4875 if (unlikely(!bl)) {
4876 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4881 io_buffer_add_list(ctx, bl, p->bgid);
4884 ret = io_add_buffers(ctx, p, bl);
4888 /* complete before unlock, IOPOLL may need the lock */
4889 __io_req_complete(req, issue_flags, ret, 0);
4890 io_ring_submit_unlock(ctx, needs_lock);
4894 static int io_epoll_ctl_prep(struct io_kiocb *req,
4895 const struct io_uring_sqe *sqe)
4897 #if defined(CONFIG_EPOLL)
4898 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4900 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4903 req->epoll.epfd = READ_ONCE(sqe->fd);
4904 req->epoll.op = READ_ONCE(sqe->len);
4905 req->epoll.fd = READ_ONCE(sqe->off);
4907 if (ep_op_has_event(req->epoll.op)) {
4908 struct epoll_event __user *ev;
4910 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4911 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4921 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4923 #if defined(CONFIG_EPOLL)
4924 struct io_epoll *ie = &req->epoll;
4926 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4928 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4929 if (force_nonblock && ret == -EAGAIN)
4934 __io_req_complete(req, issue_flags, ret, 0);
4941 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4943 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4944 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4946 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4949 req->madvise.addr = READ_ONCE(sqe->addr);
4950 req->madvise.len = READ_ONCE(sqe->len);
4951 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4958 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4960 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4961 struct io_madvise *ma = &req->madvise;
4964 if (issue_flags & IO_URING_F_NONBLOCK)
4967 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4970 io_req_complete(req, ret);
4977 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4979 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4981 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4984 req->fadvise.offset = READ_ONCE(sqe->off);
4985 req->fadvise.len = READ_ONCE(sqe->len);
4986 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4990 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4992 struct io_fadvise *fa = &req->fadvise;
4995 if (issue_flags & IO_URING_F_NONBLOCK) {
4996 switch (fa->advice) {
4997 case POSIX_FADV_NORMAL:
4998 case POSIX_FADV_RANDOM:
4999 case POSIX_FADV_SEQUENTIAL:
5006 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5009 __io_req_complete(req, issue_flags, ret, 0);
5013 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5015 const char __user *path;
5017 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5019 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5021 if (req->flags & REQ_F_FIXED_FILE)
5024 req->statx.dfd = READ_ONCE(sqe->fd);
5025 req->statx.mask = READ_ONCE(sqe->len);
5026 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5027 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5028 req->statx.flags = READ_ONCE(sqe->statx_flags);
5030 req->statx.filename = getname_flags(path,
5031 getname_statx_lookup_flags(req->statx.flags),
5034 if (IS_ERR(req->statx.filename)) {
5035 int ret = PTR_ERR(req->statx.filename);
5037 req->statx.filename = NULL;
5041 req->flags |= REQ_F_NEED_CLEANUP;
5045 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5047 struct io_statx *ctx = &req->statx;
5050 if (issue_flags & IO_URING_F_NONBLOCK)
5053 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5058 io_req_complete(req, ret);
5062 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5064 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5066 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5067 sqe->rw_flags || sqe->buf_index)
5069 if (req->flags & REQ_F_FIXED_FILE)
5072 req->close.fd = READ_ONCE(sqe->fd);
5073 req->close.file_slot = READ_ONCE(sqe->file_index);
5074 if (req->close.file_slot && req->close.fd)
5080 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5082 struct files_struct *files = current->files;
5083 struct io_close *close = &req->close;
5084 struct fdtable *fdt;
5085 struct file *file = NULL;
5088 if (req->close.file_slot) {
5089 ret = io_close_fixed(req, issue_flags);
5093 spin_lock(&files->file_lock);
5094 fdt = files_fdtable(files);
5095 if (close->fd >= fdt->max_fds) {
5096 spin_unlock(&files->file_lock);
5099 file = fdt->fd[close->fd];
5100 if (!file || file->f_op == &io_uring_fops) {
5101 spin_unlock(&files->file_lock);
5106 /* if the file has a flush method, be safe and punt to async */
5107 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5108 spin_unlock(&files->file_lock);
5112 ret = __close_fd_get_file(close->fd, &file);
5113 spin_unlock(&files->file_lock);
5120 /* No ->flush() or already async, safely close from here */
5121 ret = filp_close(file, current->files);
5127 __io_req_complete(req, issue_flags, ret, 0);
5131 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5133 struct io_ring_ctx *ctx = req->ctx;
5135 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5137 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5141 req->sync.off = READ_ONCE(sqe->off);
5142 req->sync.len = READ_ONCE(sqe->len);
5143 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5147 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5151 /* sync_file_range always requires a blocking context */
5152 if (issue_flags & IO_URING_F_NONBLOCK)
5155 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5159 io_req_complete(req, ret);
5163 #if defined(CONFIG_NET)
5164 static int io_setup_async_msg(struct io_kiocb *req,
5165 struct io_async_msghdr *kmsg)
5167 struct io_async_msghdr *async_msg = req->async_data;
5171 if (io_alloc_async_data(req)) {
5172 kfree(kmsg->free_iov);
5175 async_msg = req->async_data;
5176 req->flags |= REQ_F_NEED_CLEANUP;
5177 memcpy(async_msg, kmsg, sizeof(*kmsg));
5178 async_msg->msg.msg_name = &async_msg->addr;
5179 /* if were using fast_iov, set it to the new one */
5180 if (!async_msg->free_iov)
5181 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5186 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5187 struct io_async_msghdr *iomsg)
5189 iomsg->msg.msg_name = &iomsg->addr;
5190 iomsg->free_iov = iomsg->fast_iov;
5191 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5192 req->sr_msg.msg_flags, &iomsg->free_iov);
5195 static int io_sendmsg_prep_async(struct io_kiocb *req)
5199 ret = io_sendmsg_copy_hdr(req, req->async_data);
5201 req->flags |= REQ_F_NEED_CLEANUP;
5205 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5207 struct io_sr_msg *sr = &req->sr_msg;
5209 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5211 if (unlikely(sqe->addr2 || sqe->file_index))
5214 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5215 sr->len = READ_ONCE(sqe->len);
5216 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5217 if (sr->msg_flags & MSG_DONTWAIT)
5218 req->flags |= REQ_F_NOWAIT;
5220 #ifdef CONFIG_COMPAT
5221 if (req->ctx->compat)
5222 sr->msg_flags |= MSG_CMSG_COMPAT;
5227 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5229 struct io_async_msghdr iomsg, *kmsg;
5230 struct socket *sock;
5235 sock = sock_from_file(req->file);
5236 if (unlikely(!sock))
5239 if (req_has_async_data(req)) {
5240 kmsg = req->async_data;
5242 ret = io_sendmsg_copy_hdr(req, &iomsg);
5248 flags = req->sr_msg.msg_flags;
5249 if (issue_flags & IO_URING_F_NONBLOCK)
5250 flags |= MSG_DONTWAIT;
5251 if (flags & MSG_WAITALL)
5252 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5254 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5256 if (ret < min_ret) {
5257 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5258 return io_setup_async_msg(req, kmsg);
5259 if (ret == -ERESTARTSYS)
5263 /* fast path, check for non-NULL to avoid function call */
5265 kfree(kmsg->free_iov);
5266 req->flags &= ~REQ_F_NEED_CLEANUP;
5267 __io_req_complete(req, issue_flags, ret, 0);
5271 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5273 struct io_sr_msg *sr = &req->sr_msg;
5276 struct socket *sock;
5281 sock = sock_from_file(req->file);
5282 if (unlikely(!sock))
5285 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5289 msg.msg_name = NULL;
5290 msg.msg_control = NULL;
5291 msg.msg_controllen = 0;
5292 msg.msg_namelen = 0;
5294 flags = req->sr_msg.msg_flags;
5295 if (issue_flags & IO_URING_F_NONBLOCK)
5296 flags |= MSG_DONTWAIT;
5297 if (flags & MSG_WAITALL)
5298 min_ret = iov_iter_count(&msg.msg_iter);
5300 msg.msg_flags = flags;
5301 ret = sock_sendmsg(sock, &msg);
5302 if (ret < min_ret) {
5303 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5305 if (ret == -ERESTARTSYS)
5309 __io_req_complete(req, issue_flags, ret, 0);
5313 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5314 struct io_async_msghdr *iomsg)
5316 struct io_sr_msg *sr = &req->sr_msg;
5317 struct iovec __user *uiov;
5321 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5322 &iomsg->uaddr, &uiov, &iov_len);
5326 if (req->flags & REQ_F_BUFFER_SELECT) {
5329 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5331 sr->len = iomsg->fast_iov[0].iov_len;
5332 iomsg->free_iov = NULL;
5334 iomsg->free_iov = iomsg->fast_iov;
5335 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5336 &iomsg->free_iov, &iomsg->msg.msg_iter,
5345 #ifdef CONFIG_COMPAT
5346 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5347 struct io_async_msghdr *iomsg)
5349 struct io_sr_msg *sr = &req->sr_msg;
5350 struct compat_iovec __user *uiov;
5355 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5360 uiov = compat_ptr(ptr);
5361 if (req->flags & REQ_F_BUFFER_SELECT) {
5362 compat_ssize_t clen;
5366 if (!access_ok(uiov, sizeof(*uiov)))
5368 if (__get_user(clen, &uiov->iov_len))
5373 iomsg->free_iov = NULL;
5375 iomsg->free_iov = iomsg->fast_iov;
5376 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5377 UIO_FASTIOV, &iomsg->free_iov,
5378 &iomsg->msg.msg_iter, true);
5387 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5388 struct io_async_msghdr *iomsg)
5390 iomsg->msg.msg_name = &iomsg->addr;
5392 #ifdef CONFIG_COMPAT
5393 if (req->ctx->compat)
5394 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5397 return __io_recvmsg_copy_hdr(req, iomsg);
5400 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5401 unsigned int issue_flags)
5403 struct io_sr_msg *sr = &req->sr_msg;
5405 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5408 static int io_recvmsg_prep_async(struct io_kiocb *req)
5412 ret = io_recvmsg_copy_hdr(req, req->async_data);
5414 req->flags |= REQ_F_NEED_CLEANUP;
5418 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5420 struct io_sr_msg *sr = &req->sr_msg;
5422 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5424 if (unlikely(sqe->addr2 || sqe->file_index))
5427 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5428 sr->len = READ_ONCE(sqe->len);
5429 sr->bgid = READ_ONCE(sqe->buf_group);
5430 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5431 if (sr->msg_flags & MSG_DONTWAIT)
5432 req->flags |= REQ_F_NOWAIT;
5434 #ifdef CONFIG_COMPAT
5435 if (req->ctx->compat)
5436 sr->msg_flags |= MSG_CMSG_COMPAT;
5442 static bool io_net_retry(struct socket *sock, int flags)
5444 if (!(flags & MSG_WAITALL))
5446 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5449 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5451 struct io_async_msghdr iomsg, *kmsg;
5452 struct io_sr_msg *sr = &req->sr_msg;
5453 struct socket *sock;
5454 struct io_buffer *kbuf;
5456 int ret, min_ret = 0;
5457 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5459 sock = sock_from_file(req->file);
5460 if (unlikely(!sock))
5463 if (req_has_async_data(req)) {
5464 kmsg = req->async_data;
5466 ret = io_recvmsg_copy_hdr(req, &iomsg);
5472 if (req->flags & REQ_F_BUFFER_SELECT) {
5473 kbuf = io_recv_buffer_select(req, issue_flags);
5475 return PTR_ERR(kbuf);
5476 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5477 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5478 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5479 1, req->sr_msg.len);
5482 flags = req->sr_msg.msg_flags;
5484 flags |= MSG_DONTWAIT;
5485 if (flags & MSG_WAITALL)
5486 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5488 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5489 kmsg->uaddr, flags);
5490 if (ret < min_ret) {
5491 if (ret == -EAGAIN && force_nonblock)
5492 return io_setup_async_msg(req, kmsg);
5493 if (ret == -ERESTARTSYS)
5495 if (ret > 0 && io_net_retry(sock, flags)) {
5497 req->flags |= REQ_F_PARTIAL_IO;
5498 return io_setup_async_msg(req, kmsg);
5501 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5505 /* fast path, check for non-NULL to avoid function call */
5507 kfree(kmsg->free_iov);
5508 req->flags &= ~REQ_F_NEED_CLEANUP;
5511 else if (sr->done_io)
5513 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5517 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5519 struct io_buffer *kbuf;
5520 struct io_sr_msg *sr = &req->sr_msg;
5522 void __user *buf = sr->buf;
5523 struct socket *sock;
5526 int ret, min_ret = 0;
5527 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5529 sock = sock_from_file(req->file);
5530 if (unlikely(!sock))
5533 if (req->flags & REQ_F_BUFFER_SELECT) {
5534 kbuf = io_recv_buffer_select(req, issue_flags);
5536 return PTR_ERR(kbuf);
5537 buf = u64_to_user_ptr(kbuf->addr);
5540 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5544 msg.msg_name = NULL;
5545 msg.msg_control = NULL;
5546 msg.msg_controllen = 0;
5547 msg.msg_namelen = 0;
5548 msg.msg_iocb = NULL;
5551 flags = req->sr_msg.msg_flags;
5553 flags |= MSG_DONTWAIT;
5554 if (flags & MSG_WAITALL)
5555 min_ret = iov_iter_count(&msg.msg_iter);
5557 ret = sock_recvmsg(sock, &msg, flags);
5558 if (ret < min_ret) {
5559 if (ret == -EAGAIN && force_nonblock)
5561 if (ret == -ERESTARTSYS)
5563 if (ret > 0 && io_net_retry(sock, flags)) {
5567 req->flags |= REQ_F_PARTIAL_IO;
5571 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5578 else if (sr->done_io)
5580 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5584 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5586 struct io_accept *accept = &req->accept;
5588 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5590 if (sqe->ioprio || sqe->len || sqe->buf_index)
5593 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5594 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5595 accept->flags = READ_ONCE(sqe->accept_flags);
5596 accept->nofile = rlimit(RLIMIT_NOFILE);
5598 accept->file_slot = READ_ONCE(sqe->file_index);
5599 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5601 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5603 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5604 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5608 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5610 struct io_accept *accept = &req->accept;
5611 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5612 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5613 bool fixed = !!accept->file_slot;
5618 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5619 if (unlikely(fd < 0))
5622 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5627 ret = PTR_ERR(file);
5628 if (ret == -EAGAIN && force_nonblock)
5630 if (ret == -ERESTARTSYS)
5633 } else if (!fixed) {
5634 fd_install(fd, file);
5637 ret = io_install_fixed_file(req, file, issue_flags,
5638 accept->file_slot - 1);
5640 __io_req_complete(req, issue_flags, ret, 0);
5644 static int io_connect_prep_async(struct io_kiocb *req)
5646 struct io_async_connect *io = req->async_data;
5647 struct io_connect *conn = &req->connect;
5649 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5652 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5654 struct io_connect *conn = &req->connect;
5656 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5658 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5662 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5663 conn->addr_len = READ_ONCE(sqe->addr2);
5667 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5669 struct io_async_connect __io, *io;
5670 unsigned file_flags;
5672 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5674 if (req_has_async_data(req)) {
5675 io = req->async_data;
5677 ret = move_addr_to_kernel(req->connect.addr,
5678 req->connect.addr_len,
5685 file_flags = force_nonblock ? O_NONBLOCK : 0;
5687 ret = __sys_connect_file(req->file, &io->address,
5688 req->connect.addr_len, file_flags);
5689 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5690 if (req_has_async_data(req))
5692 if (io_alloc_async_data(req)) {
5696 memcpy(req->async_data, &__io, sizeof(__io));
5699 if (ret == -ERESTARTSYS)
5704 __io_req_complete(req, issue_flags, ret, 0);
5707 #else /* !CONFIG_NET */
5708 #define IO_NETOP_FN(op) \
5709 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5711 return -EOPNOTSUPP; \
5714 #define IO_NETOP_PREP(op) \
5716 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5718 return -EOPNOTSUPP; \
5721 #define IO_NETOP_PREP_ASYNC(op) \
5723 static int io_##op##_prep_async(struct io_kiocb *req) \
5725 return -EOPNOTSUPP; \
5728 IO_NETOP_PREP_ASYNC(sendmsg);
5729 IO_NETOP_PREP_ASYNC(recvmsg);
5730 IO_NETOP_PREP_ASYNC(connect);
5731 IO_NETOP_PREP(accept);
5734 #endif /* CONFIG_NET */
5736 struct io_poll_table {
5737 struct poll_table_struct pt;
5738 struct io_kiocb *req;
5743 #define IO_POLL_CANCEL_FLAG BIT(31)
5744 #define IO_POLL_REF_MASK GENMASK(30, 0)
5747 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5748 * bump it and acquire ownership. It's disallowed to modify requests while not
5749 * owning it, that prevents from races for enqueueing task_work's and b/w
5750 * arming poll and wakeups.
5752 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5754 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5757 static void io_poll_mark_cancelled(struct io_kiocb *req)
5759 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5762 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5764 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5765 if (req->opcode == IORING_OP_POLL_ADD)
5766 return req->async_data;
5767 return req->apoll->double_poll;
5770 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5772 if (req->opcode == IORING_OP_POLL_ADD)
5774 return &req->apoll->poll;
5777 static void io_poll_req_insert(struct io_kiocb *req)
5779 struct io_ring_ctx *ctx = req->ctx;
5780 struct hlist_head *list;
5782 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5783 hlist_add_head(&req->hash_node, list);
5786 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5787 wait_queue_func_t wake_func)
5790 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5791 /* mask in events that we always want/need */
5792 poll->events = events | IO_POLL_UNMASK;
5793 INIT_LIST_HEAD(&poll->wait.entry);
5794 init_waitqueue_func_entry(&poll->wait, wake_func);
5797 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5799 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5802 spin_lock_irq(&head->lock);
5803 list_del_init(&poll->wait.entry);
5805 spin_unlock_irq(&head->lock);
5809 static void io_poll_remove_entries(struct io_kiocb *req)
5812 * Nothing to do if neither of those flags are set. Avoid dipping
5813 * into the poll/apoll/double cachelines if we can.
5815 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5819 * While we hold the waitqueue lock and the waitqueue is nonempty,
5820 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5821 * lock in the first place can race with the waitqueue being freed.
5823 * We solve this as eventpoll does: by taking advantage of the fact that
5824 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5825 * we enter rcu_read_lock() and see that the pointer to the queue is
5826 * non-NULL, we can then lock it without the memory being freed out from
5829 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5830 * case the caller deletes the entry from the queue, leaving it empty.
5831 * In that case, only RCU prevents the queue memory from being freed.
5834 if (req->flags & REQ_F_SINGLE_POLL)
5835 io_poll_remove_entry(io_poll_get_single(req));
5836 if (req->flags & REQ_F_DOUBLE_POLL)
5837 io_poll_remove_entry(io_poll_get_double(req));
5842 * All poll tw should go through this. Checks for poll events, manages
5843 * references, does rewait, etc.
5845 * Returns a negative error on failure. >0 when no action require, which is
5846 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5847 * the request, then the mask is stored in req->result.
5849 static int io_poll_check_events(struct io_kiocb *req, bool locked)
5851 struct io_ring_ctx *ctx = req->ctx;
5854 /* req->task == current here, checking PF_EXITING is safe */
5855 if (unlikely(req->task->flags & PF_EXITING))
5856 io_poll_mark_cancelled(req);
5859 v = atomic_read(&req->poll_refs);
5861 /* tw handler should be the owner, and so have some references */
5862 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5864 if (v & IO_POLL_CANCEL_FLAG)
5868 struct poll_table_struct pt = { ._key = req->apoll_events };
5869 unsigned flags = locked ? 0 : IO_URING_F_UNLOCKED;
5871 if (unlikely(!io_assign_file(req, flags)))
5873 req->result = vfs_poll(req->file, &pt) & req->apoll_events;
5876 /* multishot, just fill an CQE and proceed */
5877 if (req->result && !(req->apoll_events & EPOLLONESHOT)) {
5878 __poll_t mask = mangle_poll(req->result & req->apoll_events);
5881 spin_lock(&ctx->completion_lock);
5882 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5884 io_commit_cqring(ctx);
5885 spin_unlock(&ctx->completion_lock);
5886 if (unlikely(!filled))
5888 io_cqring_ev_posted(ctx);
5889 } else if (req->result) {
5894 * Release all references, retry if someone tried to restart
5895 * task_work while we were executing it.
5897 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5902 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5904 struct io_ring_ctx *ctx = req->ctx;
5907 ret = io_poll_check_events(req, *locked);
5912 req->result = mangle_poll(req->result & req->poll.events);
5918 io_poll_remove_entries(req);
5919 spin_lock(&ctx->completion_lock);
5920 hash_del(&req->hash_node);
5921 __io_req_complete_post(req, req->result, 0);
5922 io_commit_cqring(ctx);
5923 spin_unlock(&ctx->completion_lock);
5924 io_cqring_ev_posted(ctx);
5927 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5929 struct io_ring_ctx *ctx = req->ctx;
5932 ret = io_poll_check_events(req, *locked);
5936 io_poll_remove_entries(req);
5937 spin_lock(&ctx->completion_lock);
5938 hash_del(&req->hash_node);
5939 spin_unlock(&ctx->completion_lock);
5942 io_req_task_submit(req, locked);
5944 io_req_complete_failed(req, ret);
5947 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
5951 * This is useful for poll that is armed on behalf of another
5952 * request, and where the wakeup path could be on a different
5953 * CPU. We want to avoid pulling in req->apoll->events for that
5956 req->apoll_events = events;
5957 if (req->opcode == IORING_OP_POLL_ADD)
5958 req->io_task_work.func = io_poll_task_func;
5960 req->io_task_work.func = io_apoll_task_func;
5962 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
5963 io_req_task_work_add(req, false);
5966 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
5968 if (io_poll_get_ownership(req))
5969 __io_poll_execute(req, res, events);
5972 static void io_poll_cancel_req(struct io_kiocb *req)
5974 io_poll_mark_cancelled(req);
5975 /* kick tw, which should complete the request */
5976 io_poll_execute(req, 0, 0);
5979 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
5980 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
5982 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5985 struct io_kiocb *req = wqe_to_req(wait);
5986 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5988 __poll_t mask = key_to_poll(key);
5990 if (unlikely(mask & POLLFREE)) {
5991 io_poll_mark_cancelled(req);
5992 /* we have to kick tw in case it's not already */
5993 io_poll_execute(req, 0, poll->events);
5996 * If the waitqueue is being freed early but someone is already
5997 * holds ownership over it, we have to tear down the request as
5998 * best we can. That means immediately removing the request from
5999 * its waitqueue and preventing all further accesses to the
6000 * waitqueue via the request.
6002 list_del_init(&poll->wait.entry);
6005 * Careful: this *must* be the last step, since as soon
6006 * as req->head is NULL'ed out, the request can be
6007 * completed and freed, since aio_poll_complete_work()
6008 * will no longer need to take the waitqueue lock.
6010 smp_store_release(&poll->head, NULL);
6014 /* for instances that support it check for an event match first */
6015 if (mask && !(mask & poll->events))
6018 if (io_poll_get_ownership(req)) {
6019 /* optional, saves extra locking for removal in tw handler */
6020 if (mask && poll->events & EPOLLONESHOT) {
6021 list_del_init(&poll->wait.entry);
6023 if (wqe_is_double(wait))
6024 req->flags &= ~REQ_F_DOUBLE_POLL;
6026 req->flags &= ~REQ_F_SINGLE_POLL;
6028 __io_poll_execute(req, mask, poll->events);
6033 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6034 struct wait_queue_head *head,
6035 struct io_poll_iocb **poll_ptr)
6037 struct io_kiocb *req = pt->req;
6038 unsigned long wqe_private = (unsigned long) req;
6041 * The file being polled uses multiple waitqueues for poll handling
6042 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6045 if (unlikely(pt->nr_entries)) {
6046 struct io_poll_iocb *first = poll;
6048 /* double add on the same waitqueue head, ignore */
6049 if (first->head == head)
6051 /* already have a 2nd entry, fail a third attempt */
6053 if ((*poll_ptr)->head == head)
6055 pt->error = -EINVAL;
6059 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6061 pt->error = -ENOMEM;
6064 /* mark as double wq entry */
6066 req->flags |= REQ_F_DOUBLE_POLL;
6067 io_init_poll_iocb(poll, first->events, first->wait.func);
6069 if (req->opcode == IORING_OP_POLL_ADD)
6070 req->flags |= REQ_F_ASYNC_DATA;
6073 req->flags |= REQ_F_SINGLE_POLL;
6076 poll->wait.private = (void *) wqe_private;
6078 if (poll->events & EPOLLEXCLUSIVE)
6079 add_wait_queue_exclusive(head, &poll->wait);
6081 add_wait_queue(head, &poll->wait);
6084 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6085 struct poll_table_struct *p)
6087 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6089 __io_queue_proc(&pt->req->poll, pt, head,
6090 (struct io_poll_iocb **) &pt->req->async_data);
6093 static int __io_arm_poll_handler(struct io_kiocb *req,
6094 struct io_poll_iocb *poll,
6095 struct io_poll_table *ipt, __poll_t mask)
6097 struct io_ring_ctx *ctx = req->ctx;
6100 INIT_HLIST_NODE(&req->hash_node);
6101 io_init_poll_iocb(poll, mask, io_poll_wake);
6102 poll->file = req->file;
6104 ipt->pt._key = mask;
6107 ipt->nr_entries = 0;
6110 * Take the ownership to delay any tw execution up until we're done
6111 * with poll arming. see io_poll_get_ownership().
6113 atomic_set(&req->poll_refs, 1);
6114 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6116 if (mask && (poll->events & EPOLLONESHOT)) {
6117 io_poll_remove_entries(req);
6118 /* no one else has access to the req, forget about the ref */
6121 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6122 io_poll_remove_entries(req);
6124 ipt->error = -EINVAL;
6128 spin_lock(&ctx->completion_lock);
6129 io_poll_req_insert(req);
6130 spin_unlock(&ctx->completion_lock);
6133 /* can't multishot if failed, just queue the event we've got */
6134 if (unlikely(ipt->error || !ipt->nr_entries))
6135 poll->events |= EPOLLONESHOT;
6136 __io_poll_execute(req, mask, poll->events);
6141 * Release ownership. If someone tried to queue a tw while it was
6142 * locked, kick it off for them.
6144 v = atomic_dec_return(&req->poll_refs);
6145 if (unlikely(v & IO_POLL_REF_MASK))
6146 __io_poll_execute(req, 0, poll->events);
6150 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6151 struct poll_table_struct *p)
6153 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6154 struct async_poll *apoll = pt->req->apoll;
6156 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6165 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6167 const struct io_op_def *def = &io_op_defs[req->opcode];
6168 struct io_ring_ctx *ctx = req->ctx;
6169 struct async_poll *apoll;
6170 struct io_poll_table ipt;
6171 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6174 if (!def->pollin && !def->pollout)
6175 return IO_APOLL_ABORTED;
6176 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6177 return IO_APOLL_ABORTED;
6180 mask |= POLLIN | POLLRDNORM;
6182 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6183 if ((req->opcode == IORING_OP_RECVMSG) &&
6184 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6187 mask |= POLLOUT | POLLWRNORM;
6189 if (def->poll_exclusive)
6190 mask |= EPOLLEXCLUSIVE;
6191 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6192 !list_empty(&ctx->apoll_cache)) {
6193 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6195 list_del_init(&apoll->poll.wait.entry);
6197 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6198 if (unlikely(!apoll))
6199 return IO_APOLL_ABORTED;
6201 apoll->double_poll = NULL;
6203 req->flags |= REQ_F_POLLED;
6204 ipt.pt._qproc = io_async_queue_proc;
6206 io_kbuf_recycle(req, issue_flags);
6208 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6209 if (ret || ipt.error)
6210 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6212 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6213 mask, apoll->poll.events);
6218 * Returns true if we found and killed one or more poll requests
6220 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6221 struct task_struct *tsk, bool cancel_all)
6223 struct hlist_node *tmp;
6224 struct io_kiocb *req;
6228 spin_lock(&ctx->completion_lock);
6229 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6230 struct hlist_head *list;
6232 list = &ctx->cancel_hash[i];
6233 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6234 if (io_match_task_safe(req, tsk, cancel_all)) {
6235 hlist_del_init(&req->hash_node);
6236 io_poll_cancel_req(req);
6241 spin_unlock(&ctx->completion_lock);
6245 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6247 __must_hold(&ctx->completion_lock)
6249 struct hlist_head *list;
6250 struct io_kiocb *req;
6252 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6253 hlist_for_each_entry(req, list, hash_node) {
6254 if (sqe_addr != req->user_data)
6256 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6263 static bool io_poll_disarm(struct io_kiocb *req)
6264 __must_hold(&ctx->completion_lock)
6266 if (!io_poll_get_ownership(req))
6268 io_poll_remove_entries(req);
6269 hash_del(&req->hash_node);
6273 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6275 __must_hold(&ctx->completion_lock)
6277 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6281 io_poll_cancel_req(req);
6285 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6290 events = READ_ONCE(sqe->poll32_events);
6292 events = swahw32(events);
6294 if (!(flags & IORING_POLL_ADD_MULTI))
6295 events |= EPOLLONESHOT;
6296 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6299 static int io_poll_update_prep(struct io_kiocb *req,
6300 const struct io_uring_sqe *sqe)
6302 struct io_poll_update *upd = &req->poll_update;
6305 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6307 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6309 flags = READ_ONCE(sqe->len);
6310 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6311 IORING_POLL_ADD_MULTI))
6313 /* meaningless without update */
6314 if (flags == IORING_POLL_ADD_MULTI)
6317 upd->old_user_data = READ_ONCE(sqe->addr);
6318 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6319 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6321 upd->new_user_data = READ_ONCE(sqe->off);
6322 if (!upd->update_user_data && upd->new_user_data)
6324 if (upd->update_events)
6325 upd->events = io_poll_parse_events(sqe, flags);
6326 else if (sqe->poll32_events)
6332 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6334 struct io_poll_iocb *poll = &req->poll;
6337 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6339 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6341 flags = READ_ONCE(sqe->len);
6342 if (flags & ~IORING_POLL_ADD_MULTI)
6344 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6347 io_req_set_refcount(req);
6348 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
6352 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6354 struct io_poll_iocb *poll = &req->poll;
6355 struct io_poll_table ipt;
6358 ipt.pt._qproc = io_poll_queue_proc;
6360 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6361 ret = ret ?: ipt.error;
6363 __io_req_complete(req, issue_flags, ret, 0);
6367 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6369 struct io_ring_ctx *ctx = req->ctx;
6370 struct io_kiocb *preq;
6374 spin_lock(&ctx->completion_lock);
6375 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6376 if (!preq || !io_poll_disarm(preq)) {
6377 spin_unlock(&ctx->completion_lock);
6378 ret = preq ? -EALREADY : -ENOENT;
6381 spin_unlock(&ctx->completion_lock);
6383 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6384 /* only mask one event flags, keep behavior flags */
6385 if (req->poll_update.update_events) {
6386 preq->poll.events &= ~0xffff;
6387 preq->poll.events |= req->poll_update.events & 0xffff;
6388 preq->poll.events |= IO_POLL_UNMASK;
6390 if (req->poll_update.update_user_data)
6391 preq->user_data = req->poll_update.new_user_data;
6393 ret2 = io_poll_add(preq, issue_flags);
6394 /* successfully updated, don't complete poll request */
6400 preq->result = -ECANCELED;
6401 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6402 io_req_task_complete(preq, &locked);
6406 /* complete update request, we're done with it */
6407 __io_req_complete(req, issue_flags, ret, 0);
6411 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6413 struct io_timeout_data *data = container_of(timer,
6414 struct io_timeout_data, timer);
6415 struct io_kiocb *req = data->req;
6416 struct io_ring_ctx *ctx = req->ctx;
6417 unsigned long flags;
6419 spin_lock_irqsave(&ctx->timeout_lock, flags);
6420 list_del_init(&req->timeout.list);
6421 atomic_set(&req->ctx->cq_timeouts,
6422 atomic_read(&req->ctx->cq_timeouts) + 1);
6423 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6425 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6428 req->result = -ETIME;
6429 req->io_task_work.func = io_req_task_complete;
6430 io_req_task_work_add(req, false);
6431 return HRTIMER_NORESTART;
6434 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6436 __must_hold(&ctx->timeout_lock)
6438 struct io_timeout_data *io;
6439 struct io_kiocb *req;
6442 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6443 found = user_data == req->user_data;
6448 return ERR_PTR(-ENOENT);
6450 io = req->async_data;
6451 if (hrtimer_try_to_cancel(&io->timer) == -1)
6452 return ERR_PTR(-EALREADY);
6453 list_del_init(&req->timeout.list);
6457 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6458 __must_hold(&ctx->completion_lock)
6459 __must_hold(&ctx->timeout_lock)
6461 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6464 return PTR_ERR(req);
6465 io_req_task_queue_fail(req, -ECANCELED);
6469 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6471 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6472 case IORING_TIMEOUT_BOOTTIME:
6473 return CLOCK_BOOTTIME;
6474 case IORING_TIMEOUT_REALTIME:
6475 return CLOCK_REALTIME;
6477 /* can't happen, vetted at prep time */
6481 return CLOCK_MONOTONIC;
6485 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6486 struct timespec64 *ts, enum hrtimer_mode mode)
6487 __must_hold(&ctx->timeout_lock)
6489 struct io_timeout_data *io;
6490 struct io_kiocb *req;
6493 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6494 found = user_data == req->user_data;
6501 io = req->async_data;
6502 if (hrtimer_try_to_cancel(&io->timer) == -1)
6504 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6505 io->timer.function = io_link_timeout_fn;
6506 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6510 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6511 struct timespec64 *ts, enum hrtimer_mode mode)
6512 __must_hold(&ctx->timeout_lock)
6514 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6515 struct io_timeout_data *data;
6518 return PTR_ERR(req);
6520 req->timeout.off = 0; /* noseq */
6521 data = req->async_data;
6522 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6523 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6524 data->timer.function = io_timeout_fn;
6525 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6529 static int io_timeout_remove_prep(struct io_kiocb *req,
6530 const struct io_uring_sqe *sqe)
6532 struct io_timeout_rem *tr = &req->timeout_rem;
6534 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6536 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6538 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6541 tr->ltimeout = false;
6542 tr->addr = READ_ONCE(sqe->addr);
6543 tr->flags = READ_ONCE(sqe->timeout_flags);
6544 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6545 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6547 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6548 tr->ltimeout = true;
6549 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6551 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6553 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6555 } else if (tr->flags) {
6556 /* timeout removal doesn't support flags */
6563 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6565 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6570 * Remove or update an existing timeout command
6572 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6574 struct io_timeout_rem *tr = &req->timeout_rem;
6575 struct io_ring_ctx *ctx = req->ctx;
6578 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6579 spin_lock(&ctx->completion_lock);
6580 spin_lock_irq(&ctx->timeout_lock);
6581 ret = io_timeout_cancel(ctx, tr->addr);
6582 spin_unlock_irq(&ctx->timeout_lock);
6583 spin_unlock(&ctx->completion_lock);
6585 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6587 spin_lock_irq(&ctx->timeout_lock);
6589 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6591 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6592 spin_unlock_irq(&ctx->timeout_lock);
6597 io_req_complete_post(req, ret, 0);
6601 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6602 bool is_timeout_link)
6604 struct io_timeout_data *data;
6606 u32 off = READ_ONCE(sqe->off);
6608 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6610 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6613 if (off && is_timeout_link)
6615 flags = READ_ONCE(sqe->timeout_flags);
6616 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6617 IORING_TIMEOUT_ETIME_SUCCESS))
6619 /* more than one clock specified is invalid, obviously */
6620 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6623 INIT_LIST_HEAD(&req->timeout.list);
6624 req->timeout.off = off;
6625 if (unlikely(off && !req->ctx->off_timeout_used))
6626 req->ctx->off_timeout_used = true;
6628 if (WARN_ON_ONCE(req_has_async_data(req)))
6630 if (io_alloc_async_data(req))
6633 data = req->async_data;
6635 data->flags = flags;
6637 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6640 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6643 INIT_LIST_HEAD(&req->timeout.list);
6644 data->mode = io_translate_timeout_mode(flags);
6645 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6647 if (is_timeout_link) {
6648 struct io_submit_link *link = &req->ctx->submit_state.link;
6652 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6654 req->timeout.head = link->last;
6655 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6660 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6662 struct io_ring_ctx *ctx = req->ctx;
6663 struct io_timeout_data *data = req->async_data;
6664 struct list_head *entry;
6665 u32 tail, off = req->timeout.off;
6667 spin_lock_irq(&ctx->timeout_lock);
6670 * sqe->off holds how many events that need to occur for this
6671 * timeout event to be satisfied. If it isn't set, then this is
6672 * a pure timeout request, sequence isn't used.
6674 if (io_is_timeout_noseq(req)) {
6675 entry = ctx->timeout_list.prev;
6679 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6680 req->timeout.target_seq = tail + off;
6682 /* Update the last seq here in case io_flush_timeouts() hasn't.
6683 * This is safe because ->completion_lock is held, and submissions
6684 * and completions are never mixed in the same ->completion_lock section.
6686 ctx->cq_last_tm_flush = tail;
6689 * Insertion sort, ensuring the first entry in the list is always
6690 * the one we need first.
6692 list_for_each_prev(entry, &ctx->timeout_list) {
6693 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6696 if (io_is_timeout_noseq(nxt))
6698 /* nxt.seq is behind @tail, otherwise would've been completed */
6699 if (off >= nxt->timeout.target_seq - tail)
6703 list_add(&req->timeout.list, entry);
6704 data->timer.function = io_timeout_fn;
6705 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6706 spin_unlock_irq(&ctx->timeout_lock);
6710 struct io_cancel_data {
6711 struct io_ring_ctx *ctx;
6715 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6717 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6718 struct io_cancel_data *cd = data;
6720 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6723 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6724 struct io_ring_ctx *ctx)
6726 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6727 enum io_wq_cancel cancel_ret;
6730 if (!tctx || !tctx->io_wq)
6733 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6734 switch (cancel_ret) {
6735 case IO_WQ_CANCEL_OK:
6738 case IO_WQ_CANCEL_RUNNING:
6741 case IO_WQ_CANCEL_NOTFOUND:
6749 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6751 struct io_ring_ctx *ctx = req->ctx;
6754 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6756 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6758 * Fall-through even for -EALREADY, as we may have poll armed
6759 * that need unarming.
6764 spin_lock(&ctx->completion_lock);
6765 ret = io_poll_cancel(ctx, sqe_addr, false);
6769 spin_lock_irq(&ctx->timeout_lock);
6770 ret = io_timeout_cancel(ctx, sqe_addr);
6771 spin_unlock_irq(&ctx->timeout_lock);
6773 spin_unlock(&ctx->completion_lock);
6777 static int io_async_cancel_prep(struct io_kiocb *req,
6778 const struct io_uring_sqe *sqe)
6780 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6782 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6784 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6788 req->cancel.addr = READ_ONCE(sqe->addr);
6792 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6794 struct io_ring_ctx *ctx = req->ctx;
6795 u64 sqe_addr = req->cancel.addr;
6796 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6797 struct io_tctx_node *node;
6800 ret = io_try_cancel_userdata(req, sqe_addr);
6804 /* slow path, try all io-wq's */
6805 io_ring_submit_lock(ctx, needs_lock);
6807 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6808 struct io_uring_task *tctx = node->task->io_uring;
6810 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6814 io_ring_submit_unlock(ctx, needs_lock);
6818 io_req_complete_post(req, ret, 0);
6822 static int io_rsrc_update_prep(struct io_kiocb *req,
6823 const struct io_uring_sqe *sqe)
6825 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6827 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6830 req->rsrc_update.offset = READ_ONCE(sqe->off);
6831 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6832 if (!req->rsrc_update.nr_args)
6834 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6838 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6840 struct io_ring_ctx *ctx = req->ctx;
6841 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6842 struct io_uring_rsrc_update2 up;
6845 up.offset = req->rsrc_update.offset;
6846 up.data = req->rsrc_update.arg;
6852 io_ring_submit_lock(ctx, needs_lock);
6853 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6854 &up, req->rsrc_update.nr_args);
6855 io_ring_submit_unlock(ctx, needs_lock);
6859 __io_req_complete(req, issue_flags, ret, 0);
6863 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6865 switch (req->opcode) {
6868 case IORING_OP_READV:
6869 case IORING_OP_READ_FIXED:
6870 case IORING_OP_READ:
6871 case IORING_OP_WRITEV:
6872 case IORING_OP_WRITE_FIXED:
6873 case IORING_OP_WRITE:
6874 return io_prep_rw(req, sqe);
6875 case IORING_OP_POLL_ADD:
6876 return io_poll_add_prep(req, sqe);
6877 case IORING_OP_POLL_REMOVE:
6878 return io_poll_update_prep(req, sqe);
6879 case IORING_OP_FSYNC:
6880 return io_fsync_prep(req, sqe);
6881 case IORING_OP_SYNC_FILE_RANGE:
6882 return io_sfr_prep(req, sqe);
6883 case IORING_OP_SENDMSG:
6884 case IORING_OP_SEND:
6885 return io_sendmsg_prep(req, sqe);
6886 case IORING_OP_RECVMSG:
6887 case IORING_OP_RECV:
6888 return io_recvmsg_prep(req, sqe);
6889 case IORING_OP_CONNECT:
6890 return io_connect_prep(req, sqe);
6891 case IORING_OP_TIMEOUT:
6892 return io_timeout_prep(req, sqe, false);
6893 case IORING_OP_TIMEOUT_REMOVE:
6894 return io_timeout_remove_prep(req, sqe);
6895 case IORING_OP_ASYNC_CANCEL:
6896 return io_async_cancel_prep(req, sqe);
6897 case IORING_OP_LINK_TIMEOUT:
6898 return io_timeout_prep(req, sqe, true);
6899 case IORING_OP_ACCEPT:
6900 return io_accept_prep(req, sqe);
6901 case IORING_OP_FALLOCATE:
6902 return io_fallocate_prep(req, sqe);
6903 case IORING_OP_OPENAT:
6904 return io_openat_prep(req, sqe);
6905 case IORING_OP_CLOSE:
6906 return io_close_prep(req, sqe);
6907 case IORING_OP_FILES_UPDATE:
6908 return io_rsrc_update_prep(req, sqe);
6909 case IORING_OP_STATX:
6910 return io_statx_prep(req, sqe);
6911 case IORING_OP_FADVISE:
6912 return io_fadvise_prep(req, sqe);
6913 case IORING_OP_MADVISE:
6914 return io_madvise_prep(req, sqe);
6915 case IORING_OP_OPENAT2:
6916 return io_openat2_prep(req, sqe);
6917 case IORING_OP_EPOLL_CTL:
6918 return io_epoll_ctl_prep(req, sqe);
6919 case IORING_OP_SPLICE:
6920 return io_splice_prep(req, sqe);
6921 case IORING_OP_PROVIDE_BUFFERS:
6922 return io_provide_buffers_prep(req, sqe);
6923 case IORING_OP_REMOVE_BUFFERS:
6924 return io_remove_buffers_prep(req, sqe);
6926 return io_tee_prep(req, sqe);
6927 case IORING_OP_SHUTDOWN:
6928 return io_shutdown_prep(req, sqe);
6929 case IORING_OP_RENAMEAT:
6930 return io_renameat_prep(req, sqe);
6931 case IORING_OP_UNLINKAT:
6932 return io_unlinkat_prep(req, sqe);
6933 case IORING_OP_MKDIRAT:
6934 return io_mkdirat_prep(req, sqe);
6935 case IORING_OP_SYMLINKAT:
6936 return io_symlinkat_prep(req, sqe);
6937 case IORING_OP_LINKAT:
6938 return io_linkat_prep(req, sqe);
6939 case IORING_OP_MSG_RING:
6940 return io_msg_ring_prep(req, sqe);
6943 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6948 static int io_req_prep_async(struct io_kiocb *req)
6950 if (!io_op_defs[req->opcode].needs_async_setup)
6952 if (WARN_ON_ONCE(req_has_async_data(req)))
6954 if (io_alloc_async_data(req))
6957 switch (req->opcode) {
6958 case IORING_OP_READV:
6959 return io_rw_prep_async(req, READ);
6960 case IORING_OP_WRITEV:
6961 return io_rw_prep_async(req, WRITE);
6962 case IORING_OP_SENDMSG:
6963 return io_sendmsg_prep_async(req);
6964 case IORING_OP_RECVMSG:
6965 return io_recvmsg_prep_async(req);
6966 case IORING_OP_CONNECT:
6967 return io_connect_prep_async(req);
6969 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6974 static u32 io_get_sequence(struct io_kiocb *req)
6976 u32 seq = req->ctx->cached_sq_head;
6978 /* need original cached_sq_head, but it was increased for each req */
6979 io_for_each_link(req, req)
6984 static __cold void io_drain_req(struct io_kiocb *req)
6986 struct io_ring_ctx *ctx = req->ctx;
6987 struct io_defer_entry *de;
6989 u32 seq = io_get_sequence(req);
6991 /* Still need defer if there is pending req in defer list. */
6992 spin_lock(&ctx->completion_lock);
6993 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6994 spin_unlock(&ctx->completion_lock);
6996 ctx->drain_active = false;
6997 io_req_task_queue(req);
7000 spin_unlock(&ctx->completion_lock);
7002 ret = io_req_prep_async(req);
7005 io_req_complete_failed(req, ret);
7008 io_prep_async_link(req);
7009 de = kmalloc(sizeof(*de), GFP_KERNEL);
7015 spin_lock(&ctx->completion_lock);
7016 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7017 spin_unlock(&ctx->completion_lock);
7022 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7025 list_add_tail(&de->list, &ctx->defer_list);
7026 spin_unlock(&ctx->completion_lock);
7029 static void io_clean_op(struct io_kiocb *req)
7031 if (req->flags & REQ_F_BUFFER_SELECTED) {
7032 spin_lock(&req->ctx->completion_lock);
7033 io_put_kbuf_comp(req);
7034 spin_unlock(&req->ctx->completion_lock);
7037 if (req->flags & REQ_F_NEED_CLEANUP) {
7038 switch (req->opcode) {
7039 case IORING_OP_READV:
7040 case IORING_OP_READ_FIXED:
7041 case IORING_OP_READ:
7042 case IORING_OP_WRITEV:
7043 case IORING_OP_WRITE_FIXED:
7044 case IORING_OP_WRITE: {
7045 struct io_async_rw *io = req->async_data;
7047 kfree(io->free_iovec);
7050 case IORING_OP_RECVMSG:
7051 case IORING_OP_SENDMSG: {
7052 struct io_async_msghdr *io = req->async_data;
7054 kfree(io->free_iov);
7057 case IORING_OP_OPENAT:
7058 case IORING_OP_OPENAT2:
7059 if (req->open.filename)
7060 putname(req->open.filename);
7062 case IORING_OP_RENAMEAT:
7063 putname(req->rename.oldpath);
7064 putname(req->rename.newpath);
7066 case IORING_OP_UNLINKAT:
7067 putname(req->unlink.filename);
7069 case IORING_OP_MKDIRAT:
7070 putname(req->mkdir.filename);
7072 case IORING_OP_SYMLINKAT:
7073 putname(req->symlink.oldpath);
7074 putname(req->symlink.newpath);
7076 case IORING_OP_LINKAT:
7077 putname(req->hardlink.oldpath);
7078 putname(req->hardlink.newpath);
7080 case IORING_OP_STATX:
7081 if (req->statx.filename)
7082 putname(req->statx.filename);
7086 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7087 kfree(req->apoll->double_poll);
7091 if (req->flags & REQ_F_CREDS)
7092 put_cred(req->creds);
7093 if (req->flags & REQ_F_ASYNC_DATA) {
7094 kfree(req->async_data);
7095 req->async_data = NULL;
7097 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7100 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
7102 if (req->file || !io_op_defs[req->opcode].needs_file)
7105 if (req->flags & REQ_F_FIXED_FILE)
7106 req->file = io_file_get_fixed(req, req->fd, issue_flags);
7108 req->file = io_file_get_normal(req, req->fd);
7113 req->result = -EBADF;
7117 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7119 const struct cred *creds = NULL;
7122 if (unlikely(!io_assign_file(req, issue_flags)))
7125 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7126 creds = override_creds(req->creds);
7128 if (!io_op_defs[req->opcode].audit_skip)
7129 audit_uring_entry(req->opcode);
7131 switch (req->opcode) {
7133 ret = io_nop(req, issue_flags);
7135 case IORING_OP_READV:
7136 case IORING_OP_READ_FIXED:
7137 case IORING_OP_READ:
7138 ret = io_read(req, issue_flags);
7140 case IORING_OP_WRITEV:
7141 case IORING_OP_WRITE_FIXED:
7142 case IORING_OP_WRITE:
7143 ret = io_write(req, issue_flags);
7145 case IORING_OP_FSYNC:
7146 ret = io_fsync(req, issue_flags);
7148 case IORING_OP_POLL_ADD:
7149 ret = io_poll_add(req, issue_flags);
7151 case IORING_OP_POLL_REMOVE:
7152 ret = io_poll_update(req, issue_flags);
7154 case IORING_OP_SYNC_FILE_RANGE:
7155 ret = io_sync_file_range(req, issue_flags);
7157 case IORING_OP_SENDMSG:
7158 ret = io_sendmsg(req, issue_flags);
7160 case IORING_OP_SEND:
7161 ret = io_send(req, issue_flags);
7163 case IORING_OP_RECVMSG:
7164 ret = io_recvmsg(req, issue_flags);
7166 case IORING_OP_RECV:
7167 ret = io_recv(req, issue_flags);
7169 case IORING_OP_TIMEOUT:
7170 ret = io_timeout(req, issue_flags);
7172 case IORING_OP_TIMEOUT_REMOVE:
7173 ret = io_timeout_remove(req, issue_flags);
7175 case IORING_OP_ACCEPT:
7176 ret = io_accept(req, issue_flags);
7178 case IORING_OP_CONNECT:
7179 ret = io_connect(req, issue_flags);
7181 case IORING_OP_ASYNC_CANCEL:
7182 ret = io_async_cancel(req, issue_flags);
7184 case IORING_OP_FALLOCATE:
7185 ret = io_fallocate(req, issue_flags);
7187 case IORING_OP_OPENAT:
7188 ret = io_openat(req, issue_flags);
7190 case IORING_OP_CLOSE:
7191 ret = io_close(req, issue_flags);
7193 case IORING_OP_FILES_UPDATE:
7194 ret = io_files_update(req, issue_flags);
7196 case IORING_OP_STATX:
7197 ret = io_statx(req, issue_flags);
7199 case IORING_OP_FADVISE:
7200 ret = io_fadvise(req, issue_flags);
7202 case IORING_OP_MADVISE:
7203 ret = io_madvise(req, issue_flags);
7205 case IORING_OP_OPENAT2:
7206 ret = io_openat2(req, issue_flags);
7208 case IORING_OP_EPOLL_CTL:
7209 ret = io_epoll_ctl(req, issue_flags);
7211 case IORING_OP_SPLICE:
7212 ret = io_splice(req, issue_flags);
7214 case IORING_OP_PROVIDE_BUFFERS:
7215 ret = io_provide_buffers(req, issue_flags);
7217 case IORING_OP_REMOVE_BUFFERS:
7218 ret = io_remove_buffers(req, issue_flags);
7221 ret = io_tee(req, issue_flags);
7223 case IORING_OP_SHUTDOWN:
7224 ret = io_shutdown(req, issue_flags);
7226 case IORING_OP_RENAMEAT:
7227 ret = io_renameat(req, issue_flags);
7229 case IORING_OP_UNLINKAT:
7230 ret = io_unlinkat(req, issue_flags);
7232 case IORING_OP_MKDIRAT:
7233 ret = io_mkdirat(req, issue_flags);
7235 case IORING_OP_SYMLINKAT:
7236 ret = io_symlinkat(req, issue_flags);
7238 case IORING_OP_LINKAT:
7239 ret = io_linkat(req, issue_flags);
7241 case IORING_OP_MSG_RING:
7242 ret = io_msg_ring(req, issue_flags);
7249 if (!io_op_defs[req->opcode].audit_skip)
7250 audit_uring_exit(!ret, ret);
7253 revert_creds(creds);
7256 /* If the op doesn't have a file, we're not polling for it */
7257 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7258 io_iopoll_req_issued(req, issue_flags);
7263 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7265 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7267 req = io_put_req_find_next(req);
7268 return req ? &req->work : NULL;
7271 static void io_wq_submit_work(struct io_wq_work *work)
7273 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7274 const struct io_op_def *def = &io_op_defs[req->opcode];
7275 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7276 bool needs_poll = false;
7277 struct io_kiocb *timeout;
7278 int ret = 0, err = -ECANCELED;
7280 /* one will be dropped by ->io_free_work() after returning to io-wq */
7281 if (!(req->flags & REQ_F_REFCOUNT))
7282 __io_req_set_refcount(req, 2);
7286 timeout = io_prep_linked_timeout(req);
7288 io_queue_linked_timeout(timeout);
7291 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7292 if (work->flags & IO_WQ_WORK_CANCEL) {
7294 io_req_task_queue_fail(req, err);
7297 if (!io_assign_file(req, issue_flags)) {
7299 work->flags |= IO_WQ_WORK_CANCEL;
7303 if (req->flags & REQ_F_FORCE_ASYNC) {
7304 bool opcode_poll = def->pollin || def->pollout;
7306 if (opcode_poll && file_can_poll(req->file)) {
7308 issue_flags |= IO_URING_F_NONBLOCK;
7313 ret = io_issue_sqe(req, issue_flags);
7317 * We can get EAGAIN for iopolled IO even though we're
7318 * forcing a sync submission from here, since we can't
7319 * wait for request slots on the block side.
7326 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7328 /* aborted or ready, in either case retry blocking */
7330 issue_flags &= ~IO_URING_F_NONBLOCK;
7333 /* avoid locking problems by failing it from a clean context */
7335 io_req_task_queue_fail(req, ret);
7338 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7341 return &table->files[i];
7344 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7347 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7349 return (struct file *) (slot->file_ptr & FFS_MASK);
7352 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7354 unsigned long file_ptr = (unsigned long) file;
7356 file_ptr |= io_file_get_flags(file);
7357 file_slot->file_ptr = file_ptr;
7360 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
7361 unsigned int issue_flags)
7363 struct io_ring_ctx *ctx = req->ctx;
7364 struct file *file = NULL;
7365 unsigned long file_ptr;
7367 if (issue_flags & IO_URING_F_UNLOCKED)
7368 mutex_lock(&ctx->uring_lock);
7370 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7372 fd = array_index_nospec(fd, ctx->nr_user_files);
7373 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7374 file = (struct file *) (file_ptr & FFS_MASK);
7375 file_ptr &= ~FFS_MASK;
7376 /* mask in overlapping REQ_F and FFS bits */
7377 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7378 io_req_set_rsrc_node(req, ctx, 0);
7380 if (issue_flags & IO_URING_F_UNLOCKED)
7381 mutex_unlock(&ctx->uring_lock);
7386 * Drop the file for requeue operations. Only used of req->file is the
7387 * io_uring descriptor itself.
7389 static void io_drop_inflight_file(struct io_kiocb *req)
7391 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
7394 req->flags &= ~REQ_F_INFLIGHT;
7398 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
7400 struct file *file = fget(fd);
7402 trace_io_uring_file_get(req->ctx, req, req->user_data, fd);
7404 /* we don't allow fixed io_uring files */
7405 if (file && file->f_op == &io_uring_fops)
7406 req->flags |= REQ_F_INFLIGHT;
7410 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7412 struct io_kiocb *prev = req->timeout.prev;
7416 if (!(req->task->flags & PF_EXITING))
7417 ret = io_try_cancel_userdata(req, prev->user_data);
7418 io_req_complete_post(req, ret ?: -ETIME, 0);
7421 io_req_complete_post(req, -ETIME, 0);
7425 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7427 struct io_timeout_data *data = container_of(timer,
7428 struct io_timeout_data, timer);
7429 struct io_kiocb *prev, *req = data->req;
7430 struct io_ring_ctx *ctx = req->ctx;
7431 unsigned long flags;
7433 spin_lock_irqsave(&ctx->timeout_lock, flags);
7434 prev = req->timeout.head;
7435 req->timeout.head = NULL;
7438 * We don't expect the list to be empty, that will only happen if we
7439 * race with the completion of the linked work.
7442 io_remove_next_linked(prev);
7443 if (!req_ref_inc_not_zero(prev))
7446 list_del(&req->timeout.list);
7447 req->timeout.prev = prev;
7448 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7450 req->io_task_work.func = io_req_task_link_timeout;
7451 io_req_task_work_add(req, false);
7452 return HRTIMER_NORESTART;
7455 static void io_queue_linked_timeout(struct io_kiocb *req)
7457 struct io_ring_ctx *ctx = req->ctx;
7459 spin_lock_irq(&ctx->timeout_lock);
7461 * If the back reference is NULL, then our linked request finished
7462 * before we got a chance to setup the timer
7464 if (req->timeout.head) {
7465 struct io_timeout_data *data = req->async_data;
7467 data->timer.function = io_link_timeout_fn;
7468 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7470 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7472 spin_unlock_irq(&ctx->timeout_lock);
7473 /* drop submission reference */
7477 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7478 __must_hold(&req->ctx->uring_lock)
7480 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7482 switch (io_arm_poll_handler(req, 0)) {
7483 case IO_APOLL_READY:
7484 io_req_task_queue(req);
7486 case IO_APOLL_ABORTED:
7488 * Queued up for async execution, worker will release
7489 * submit reference when the iocb is actually submitted.
7491 io_queue_async_work(req, NULL);
7498 io_queue_linked_timeout(linked_timeout);
7501 static inline void __io_queue_sqe(struct io_kiocb *req)
7502 __must_hold(&req->ctx->uring_lock)
7504 struct io_kiocb *linked_timeout;
7507 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7509 if (req->flags & REQ_F_COMPLETE_INLINE) {
7510 io_req_add_compl_list(req);
7514 * We async punt it if the file wasn't marked NOWAIT, or if the file
7515 * doesn't support non-blocking read/write attempts
7518 linked_timeout = io_prep_linked_timeout(req);
7520 io_queue_linked_timeout(linked_timeout);
7521 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7522 io_queue_sqe_arm_apoll(req);
7524 io_req_complete_failed(req, ret);
7528 static void io_queue_sqe_fallback(struct io_kiocb *req)
7529 __must_hold(&req->ctx->uring_lock)
7531 if (req->flags & REQ_F_FAIL) {
7532 io_req_complete_fail_submit(req);
7533 } else if (unlikely(req->ctx->drain_active)) {
7536 int ret = io_req_prep_async(req);
7539 io_req_complete_failed(req, ret);
7541 io_queue_async_work(req, NULL);
7545 static inline void io_queue_sqe(struct io_kiocb *req)
7546 __must_hold(&req->ctx->uring_lock)
7548 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7549 __io_queue_sqe(req);
7551 io_queue_sqe_fallback(req);
7555 * Check SQE restrictions (opcode and flags).
7557 * Returns 'true' if SQE is allowed, 'false' otherwise.
7559 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7560 struct io_kiocb *req,
7561 unsigned int sqe_flags)
7563 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7566 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7567 ctx->restrictions.sqe_flags_required)
7570 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7571 ctx->restrictions.sqe_flags_required))
7577 static void io_init_req_drain(struct io_kiocb *req)
7579 struct io_ring_ctx *ctx = req->ctx;
7580 struct io_kiocb *head = ctx->submit_state.link.head;
7582 ctx->drain_active = true;
7585 * If we need to drain a request in the middle of a link, drain
7586 * the head request and the next request/link after the current
7587 * link. Considering sequential execution of links,
7588 * REQ_F_IO_DRAIN will be maintained for every request of our
7591 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7592 ctx->drain_next = true;
7596 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7597 const struct io_uring_sqe *sqe)
7598 __must_hold(&ctx->uring_lock)
7600 unsigned int sqe_flags;
7604 /* req is partially pre-initialised, see io_preinit_req() */
7605 req->opcode = opcode = READ_ONCE(sqe->opcode);
7606 /* same numerical values with corresponding REQ_F_*, safe to copy */
7607 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7608 req->user_data = READ_ONCE(sqe->user_data);
7610 req->fixed_rsrc_refs = NULL;
7611 req->task = current;
7613 if (unlikely(opcode >= IORING_OP_LAST)) {
7617 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7618 /* enforce forwards compatibility on users */
7619 if (sqe_flags & ~SQE_VALID_FLAGS)
7621 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7622 !io_op_defs[opcode].buffer_select)
7624 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7625 ctx->drain_disabled = true;
7626 if (sqe_flags & IOSQE_IO_DRAIN) {
7627 if (ctx->drain_disabled)
7629 io_init_req_drain(req);
7632 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7633 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7635 /* knock it to the slow queue path, will be drained there */
7636 if (ctx->drain_active)
7637 req->flags |= REQ_F_FORCE_ASYNC;
7638 /* if there is no link, we're at "next" request and need to drain */
7639 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7640 ctx->drain_next = false;
7641 ctx->drain_active = true;
7642 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7646 if (io_op_defs[opcode].needs_file) {
7647 struct io_submit_state *state = &ctx->submit_state;
7649 req->fd = READ_ONCE(sqe->fd);
7652 * Plug now if we have more than 2 IO left after this, and the
7653 * target is potentially a read/write to block based storage.
7655 if (state->need_plug && io_op_defs[opcode].plug) {
7656 state->plug_started = true;
7657 state->need_plug = false;
7658 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7662 personality = READ_ONCE(sqe->personality);
7666 req->creds = xa_load(&ctx->personalities, personality);
7669 get_cred(req->creds);
7670 ret = security_uring_override_creds(req->creds);
7672 put_cred(req->creds);
7675 req->flags |= REQ_F_CREDS;
7678 return io_req_prep(req, sqe);
7681 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7682 const struct io_uring_sqe *sqe)
7683 __must_hold(&ctx->uring_lock)
7685 struct io_submit_link *link = &ctx->submit_state.link;
7688 ret = io_init_req(ctx, req, sqe);
7689 if (unlikely(ret)) {
7690 trace_io_uring_req_failed(sqe, ctx, req, ret);
7692 /* fail even hard links since we don't submit */
7695 * we can judge a link req is failed or cancelled by if
7696 * REQ_F_FAIL is set, but the head is an exception since
7697 * it may be set REQ_F_FAIL because of other req's failure
7698 * so let's leverage req->result to distinguish if a head
7699 * is set REQ_F_FAIL because of its failure or other req's
7700 * failure so that we can set the correct ret code for it.
7701 * init result here to avoid affecting the normal path.
7703 if (!(link->head->flags & REQ_F_FAIL))
7704 req_fail_link_node(link->head, -ECANCELED);
7705 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7707 * the current req is a normal req, we should return
7708 * error and thus break the submittion loop.
7710 io_req_complete_failed(req, ret);
7713 req_fail_link_node(req, ret);
7716 /* don't need @sqe from now on */
7717 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7719 ctx->flags & IORING_SETUP_SQPOLL);
7722 * If we already have a head request, queue this one for async
7723 * submittal once the head completes. If we don't have a head but
7724 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7725 * submitted sync once the chain is complete. If none of those
7726 * conditions are true (normal request), then just queue it.
7729 struct io_kiocb *head = link->head;
7731 if (!(req->flags & REQ_F_FAIL)) {
7732 ret = io_req_prep_async(req);
7733 if (unlikely(ret)) {
7734 req_fail_link_node(req, ret);
7735 if (!(head->flags & REQ_F_FAIL))
7736 req_fail_link_node(head, -ECANCELED);
7739 trace_io_uring_link(ctx, req, head);
7740 link->last->link = req;
7743 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7745 /* last request of a link, enqueue the link */
7748 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7759 * Batched submission is done, ensure local IO is flushed out.
7761 static void io_submit_state_end(struct io_ring_ctx *ctx)
7763 struct io_submit_state *state = &ctx->submit_state;
7765 if (state->link.head)
7766 io_queue_sqe(state->link.head);
7767 /* flush only after queuing links as they can generate completions */
7768 io_submit_flush_completions(ctx);
7769 if (state->plug_started)
7770 blk_finish_plug(&state->plug);
7774 * Start submission side cache.
7776 static void io_submit_state_start(struct io_submit_state *state,
7777 unsigned int max_ios)
7779 state->plug_started = false;
7780 state->need_plug = max_ios > 2;
7781 state->submit_nr = max_ios;
7782 /* set only head, no need to init link_last in advance */
7783 state->link.head = NULL;
7786 static void io_commit_sqring(struct io_ring_ctx *ctx)
7788 struct io_rings *rings = ctx->rings;
7791 * Ensure any loads from the SQEs are done at this point,
7792 * since once we write the new head, the application could
7793 * write new data to them.
7795 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7799 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7800 * that is mapped by userspace. This means that care needs to be taken to
7801 * ensure that reads are stable, as we cannot rely on userspace always
7802 * being a good citizen. If members of the sqe are validated and then later
7803 * used, it's important that those reads are done through READ_ONCE() to
7804 * prevent a re-load down the line.
7806 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7808 unsigned head, mask = ctx->sq_entries - 1;
7809 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7812 * The cached sq head (or cq tail) serves two purposes:
7814 * 1) allows us to batch the cost of updating the user visible
7816 * 2) allows the kernel side to track the head on its own, even
7817 * though the application is the one updating it.
7819 head = READ_ONCE(ctx->sq_array[sq_idx]);
7820 if (likely(head < ctx->sq_entries))
7821 return &ctx->sq_sqes[head];
7823 /* drop invalid entries */
7825 WRITE_ONCE(ctx->rings->sq_dropped,
7826 READ_ONCE(ctx->rings->sq_dropped) + 1);
7830 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7831 __must_hold(&ctx->uring_lock)
7833 unsigned int entries = io_sqring_entries(ctx);
7836 if (unlikely(!entries))
7838 /* make sure SQ entry isn't read before tail */
7839 nr = min3(nr, ctx->sq_entries, entries);
7840 io_get_task_refs(nr);
7842 io_submit_state_start(&ctx->submit_state, nr);
7844 const struct io_uring_sqe *sqe;
7845 struct io_kiocb *req;
7847 if (unlikely(!io_alloc_req_refill(ctx))) {
7849 submitted = -EAGAIN;
7852 req = io_alloc_req(ctx);
7853 sqe = io_get_sqe(ctx);
7854 if (unlikely(!sqe)) {
7855 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7858 /* will complete beyond this point, count as submitted */
7860 if (io_submit_sqe(ctx, req, sqe)) {
7862 * Continue submitting even for sqe failure if the
7863 * ring was setup with IORING_SETUP_SUBMIT_ALL
7865 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7868 } while (submitted < nr);
7870 if (unlikely(submitted != nr)) {
7871 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7872 int unused = nr - ref_used;
7874 current->io_uring->cached_refs += unused;
7877 io_submit_state_end(ctx);
7878 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7879 io_commit_sqring(ctx);
7884 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7886 return READ_ONCE(sqd->state);
7889 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7891 /* Tell userspace we may need a wakeup call */
7892 spin_lock(&ctx->completion_lock);
7893 WRITE_ONCE(ctx->rings->sq_flags,
7894 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7895 spin_unlock(&ctx->completion_lock);
7898 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7900 spin_lock(&ctx->completion_lock);
7901 WRITE_ONCE(ctx->rings->sq_flags,
7902 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7903 spin_unlock(&ctx->completion_lock);
7906 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7908 unsigned int to_submit;
7911 to_submit = io_sqring_entries(ctx);
7912 /* if we're handling multiple rings, cap submit size for fairness */
7913 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7914 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7916 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7917 const struct cred *creds = NULL;
7919 if (ctx->sq_creds != current_cred())
7920 creds = override_creds(ctx->sq_creds);
7922 mutex_lock(&ctx->uring_lock);
7923 if (!wq_list_empty(&ctx->iopoll_list))
7924 io_do_iopoll(ctx, true);
7927 * Don't submit if refs are dying, good for io_uring_register(),
7928 * but also it is relied upon by io_ring_exit_work()
7930 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7931 !(ctx->flags & IORING_SETUP_R_DISABLED))
7932 ret = io_submit_sqes(ctx, to_submit);
7933 mutex_unlock(&ctx->uring_lock);
7935 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7936 wake_up(&ctx->sqo_sq_wait);
7938 revert_creds(creds);
7944 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7946 struct io_ring_ctx *ctx;
7947 unsigned sq_thread_idle = 0;
7949 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7950 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7951 sqd->sq_thread_idle = sq_thread_idle;
7954 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7956 bool did_sig = false;
7957 struct ksignal ksig;
7959 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7960 signal_pending(current)) {
7961 mutex_unlock(&sqd->lock);
7962 if (signal_pending(current))
7963 did_sig = get_signal(&ksig);
7965 mutex_lock(&sqd->lock);
7967 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7970 static int io_sq_thread(void *data)
7972 struct io_sq_data *sqd = data;
7973 struct io_ring_ctx *ctx;
7974 unsigned long timeout = 0;
7975 char buf[TASK_COMM_LEN];
7978 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7979 set_task_comm(current, buf);
7981 if (sqd->sq_cpu != -1)
7982 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7984 set_cpus_allowed_ptr(current, cpu_online_mask);
7985 current->flags |= PF_NO_SETAFFINITY;
7987 audit_alloc_kernel(current);
7989 mutex_lock(&sqd->lock);
7991 bool cap_entries, sqt_spin = false;
7993 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7994 if (io_sqd_handle_event(sqd))
7996 timeout = jiffies + sqd->sq_thread_idle;
7999 cap_entries = !list_is_singular(&sqd->ctx_list);
8000 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8001 int ret = __io_sq_thread(ctx, cap_entries);
8003 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8006 if (io_run_task_work())
8009 if (sqt_spin || !time_after(jiffies, timeout)) {
8012 timeout = jiffies + sqd->sq_thread_idle;
8016 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8017 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8018 bool needs_sched = true;
8020 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8021 io_ring_set_wakeup_flag(ctx);
8023 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8024 !wq_list_empty(&ctx->iopoll_list)) {
8025 needs_sched = false;
8030 * Ensure the store of the wakeup flag is not
8031 * reordered with the load of the SQ tail
8035 if (io_sqring_entries(ctx)) {
8036 needs_sched = false;
8042 mutex_unlock(&sqd->lock);
8044 mutex_lock(&sqd->lock);
8046 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8047 io_ring_clear_wakeup_flag(ctx);
8050 finish_wait(&sqd->wait, &wait);
8051 timeout = jiffies + sqd->sq_thread_idle;
8054 io_uring_cancel_generic(true, sqd);
8056 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8057 io_ring_set_wakeup_flag(ctx);
8059 mutex_unlock(&sqd->lock);
8061 audit_free(current);
8063 complete(&sqd->exited);
8067 struct io_wait_queue {
8068 struct wait_queue_entry wq;
8069 struct io_ring_ctx *ctx;
8071 unsigned nr_timeouts;
8074 static inline bool io_should_wake(struct io_wait_queue *iowq)
8076 struct io_ring_ctx *ctx = iowq->ctx;
8077 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8080 * Wake up if we have enough events, or if a timeout occurred since we
8081 * started waiting. For timeouts, we always want to return to userspace,
8082 * regardless of event count.
8084 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8087 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8088 int wake_flags, void *key)
8090 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8094 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8095 * the task, and the next invocation will do it.
8097 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8098 return autoremove_wake_function(curr, mode, wake_flags, key);
8102 static int io_run_task_work_sig(void)
8104 if (io_run_task_work())
8106 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8107 return -ERESTARTSYS;
8108 if (task_sigpending(current))
8113 /* when returns >0, the caller should retry */
8114 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8115 struct io_wait_queue *iowq,
8120 /* make sure we run task_work before checking for signals */
8121 ret = io_run_task_work_sig();
8122 if (ret || io_should_wake(iowq))
8124 /* let the caller flush overflows, retry */
8125 if (test_bit(0, &ctx->check_cq_overflow))
8128 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8134 * Wait until events become available, if we don't already have some. The
8135 * application must reap them itself, as they reside on the shared cq ring.
8137 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8138 const sigset_t __user *sig, size_t sigsz,
8139 struct __kernel_timespec __user *uts)
8141 struct io_wait_queue iowq;
8142 struct io_rings *rings = ctx->rings;
8143 ktime_t timeout = KTIME_MAX;
8147 io_cqring_overflow_flush(ctx);
8148 if (io_cqring_events(ctx) >= min_events)
8150 if (!io_run_task_work())
8155 #ifdef CONFIG_COMPAT
8156 if (in_compat_syscall())
8157 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8161 ret = set_user_sigmask(sig, sigsz);
8168 struct timespec64 ts;
8170 if (get_timespec64(&ts, uts))
8172 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8175 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8176 iowq.wq.private = current;
8177 INIT_LIST_HEAD(&iowq.wq.entry);
8179 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8180 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8182 trace_io_uring_cqring_wait(ctx, min_events);
8184 /* if we can't even flush overflow, don't wait for more */
8185 if (!io_cqring_overflow_flush(ctx)) {
8189 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8190 TASK_INTERRUPTIBLE);
8191 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8192 finish_wait(&ctx->cq_wait, &iowq.wq);
8196 restore_saved_sigmask_unless(ret == -EINTR);
8198 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8201 static void io_free_page_table(void **table, size_t size)
8203 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8205 for (i = 0; i < nr_tables; i++)
8210 static __cold void **io_alloc_page_table(size_t size)
8212 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8213 size_t init_size = size;
8216 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8220 for (i = 0; i < nr_tables; i++) {
8221 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8223 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8225 io_free_page_table(table, init_size);
8233 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8235 percpu_ref_exit(&ref_node->refs);
8239 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8241 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8242 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8243 unsigned long flags;
8244 bool first_add = false;
8245 unsigned long delay = HZ;
8247 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8250 /* if we are mid-quiesce then do not delay */
8251 if (node->rsrc_data->quiesce)
8254 while (!list_empty(&ctx->rsrc_ref_list)) {
8255 node = list_first_entry(&ctx->rsrc_ref_list,
8256 struct io_rsrc_node, node);
8257 /* recycle ref nodes in order */
8260 list_del(&node->node);
8261 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8263 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8266 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8269 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8271 struct io_rsrc_node *ref_node;
8273 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8277 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8282 INIT_LIST_HEAD(&ref_node->node);
8283 INIT_LIST_HEAD(&ref_node->rsrc_list);
8284 ref_node->done = false;
8288 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8289 struct io_rsrc_data *data_to_kill)
8290 __must_hold(&ctx->uring_lock)
8292 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8293 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8295 io_rsrc_refs_drop(ctx);
8298 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8300 rsrc_node->rsrc_data = data_to_kill;
8301 spin_lock_irq(&ctx->rsrc_ref_lock);
8302 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8303 spin_unlock_irq(&ctx->rsrc_ref_lock);
8305 atomic_inc(&data_to_kill->refs);
8306 percpu_ref_kill(&rsrc_node->refs);
8307 ctx->rsrc_node = NULL;
8310 if (!ctx->rsrc_node) {
8311 ctx->rsrc_node = ctx->rsrc_backup_node;
8312 ctx->rsrc_backup_node = NULL;
8316 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8318 if (ctx->rsrc_backup_node)
8320 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8321 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8324 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8325 struct io_ring_ctx *ctx)
8329 /* As we may drop ->uring_lock, other task may have started quiesce */
8333 data->quiesce = true;
8335 ret = io_rsrc_node_switch_start(ctx);
8338 io_rsrc_node_switch(ctx, data);
8340 /* kill initial ref, already quiesced if zero */
8341 if (atomic_dec_and_test(&data->refs))
8343 mutex_unlock(&ctx->uring_lock);
8344 flush_delayed_work(&ctx->rsrc_put_work);
8345 ret = wait_for_completion_interruptible(&data->done);
8347 mutex_lock(&ctx->uring_lock);
8348 if (atomic_read(&data->refs) > 0) {
8350 * it has been revived by another thread while
8353 mutex_unlock(&ctx->uring_lock);
8359 atomic_inc(&data->refs);
8360 /* wait for all works potentially completing data->done */
8361 flush_delayed_work(&ctx->rsrc_put_work);
8362 reinit_completion(&data->done);
8364 ret = io_run_task_work_sig();
8365 mutex_lock(&ctx->uring_lock);
8367 data->quiesce = false;
8372 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8374 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8375 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8377 return &data->tags[table_idx][off];
8380 static void io_rsrc_data_free(struct io_rsrc_data *data)
8382 size_t size = data->nr * sizeof(data->tags[0][0]);
8385 io_free_page_table((void **)data->tags, size);
8389 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8390 u64 __user *utags, unsigned nr,
8391 struct io_rsrc_data **pdata)
8393 struct io_rsrc_data *data;
8397 data = kzalloc(sizeof(*data), GFP_KERNEL);
8400 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8408 data->do_put = do_put;
8411 for (i = 0; i < nr; i++) {
8412 u64 *tag_slot = io_get_tag_slot(data, i);
8414 if (copy_from_user(tag_slot, &utags[i],
8420 atomic_set(&data->refs, 1);
8421 init_completion(&data->done);
8425 io_rsrc_data_free(data);
8429 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8431 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8432 GFP_KERNEL_ACCOUNT);
8433 return !!table->files;
8436 static void io_free_file_tables(struct io_file_table *table)
8438 kvfree(table->files);
8439 table->files = NULL;
8442 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8444 #if defined(CONFIG_UNIX)
8445 if (ctx->ring_sock) {
8446 struct sock *sock = ctx->ring_sock->sk;
8447 struct sk_buff *skb;
8449 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8455 for (i = 0; i < ctx->nr_user_files; i++) {
8458 file = io_file_from_index(ctx, i);
8463 io_free_file_tables(&ctx->file_table);
8464 io_rsrc_data_free(ctx->file_data);
8465 ctx->file_data = NULL;
8466 ctx->nr_user_files = 0;
8469 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8473 if (!ctx->file_data)
8475 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8477 __io_sqe_files_unregister(ctx);
8481 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8482 __releases(&sqd->lock)
8484 WARN_ON_ONCE(sqd->thread == current);
8487 * Do the dance but not conditional clear_bit() because it'd race with
8488 * other threads incrementing park_pending and setting the bit.
8490 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8491 if (atomic_dec_return(&sqd->park_pending))
8492 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8493 mutex_unlock(&sqd->lock);
8496 static void io_sq_thread_park(struct io_sq_data *sqd)
8497 __acquires(&sqd->lock)
8499 WARN_ON_ONCE(sqd->thread == current);
8501 atomic_inc(&sqd->park_pending);
8502 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8503 mutex_lock(&sqd->lock);
8505 wake_up_process(sqd->thread);
8508 static void io_sq_thread_stop(struct io_sq_data *sqd)
8510 WARN_ON_ONCE(sqd->thread == current);
8511 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8513 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8514 mutex_lock(&sqd->lock);
8516 wake_up_process(sqd->thread);
8517 mutex_unlock(&sqd->lock);
8518 wait_for_completion(&sqd->exited);
8521 static void io_put_sq_data(struct io_sq_data *sqd)
8523 if (refcount_dec_and_test(&sqd->refs)) {
8524 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8526 io_sq_thread_stop(sqd);
8531 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8533 struct io_sq_data *sqd = ctx->sq_data;
8536 io_sq_thread_park(sqd);
8537 list_del_init(&ctx->sqd_list);
8538 io_sqd_update_thread_idle(sqd);
8539 io_sq_thread_unpark(sqd);
8541 io_put_sq_data(sqd);
8542 ctx->sq_data = NULL;
8546 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8548 struct io_ring_ctx *ctx_attach;
8549 struct io_sq_data *sqd;
8552 f = fdget(p->wq_fd);
8554 return ERR_PTR(-ENXIO);
8555 if (f.file->f_op != &io_uring_fops) {
8557 return ERR_PTR(-EINVAL);
8560 ctx_attach = f.file->private_data;
8561 sqd = ctx_attach->sq_data;
8564 return ERR_PTR(-EINVAL);
8566 if (sqd->task_tgid != current->tgid) {
8568 return ERR_PTR(-EPERM);
8571 refcount_inc(&sqd->refs);
8576 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8579 struct io_sq_data *sqd;
8582 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8583 sqd = io_attach_sq_data(p);
8588 /* fall through for EPERM case, setup new sqd/task */
8589 if (PTR_ERR(sqd) != -EPERM)
8593 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8595 return ERR_PTR(-ENOMEM);
8597 atomic_set(&sqd->park_pending, 0);
8598 refcount_set(&sqd->refs, 1);
8599 INIT_LIST_HEAD(&sqd->ctx_list);
8600 mutex_init(&sqd->lock);
8601 init_waitqueue_head(&sqd->wait);
8602 init_completion(&sqd->exited);
8606 #if defined(CONFIG_UNIX)
8608 * Ensure the UNIX gc is aware of our file set, so we are certain that
8609 * the io_uring can be safely unregistered on process exit, even if we have
8610 * loops in the file referencing.
8612 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8614 struct sock *sk = ctx->ring_sock->sk;
8615 struct scm_fp_list *fpl;
8616 struct sk_buff *skb;
8619 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8623 skb = alloc_skb(0, GFP_KERNEL);
8632 fpl->user = get_uid(current_user());
8633 for (i = 0; i < nr; i++) {
8634 struct file *file = io_file_from_index(ctx, i + offset);
8638 fpl->fp[nr_files] = get_file(file);
8639 unix_inflight(fpl->user, fpl->fp[nr_files]);
8644 fpl->max = SCM_MAX_FD;
8645 fpl->count = nr_files;
8646 UNIXCB(skb).fp = fpl;
8647 skb->destructor = unix_destruct_scm;
8648 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8649 skb_queue_head(&sk->sk_receive_queue, skb);
8651 for (i = 0; i < nr; i++) {
8652 struct file *file = io_file_from_index(ctx, i + offset);
8659 free_uid(fpl->user);
8667 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8668 * causes regular reference counting to break down. We rely on the UNIX
8669 * garbage collection to take care of this problem for us.
8671 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8673 unsigned left, total;
8677 left = ctx->nr_user_files;
8679 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8681 ret = __io_sqe_files_scm(ctx, this_files, total);
8685 total += this_files;
8691 while (total < ctx->nr_user_files) {
8692 struct file *file = io_file_from_index(ctx, total);
8702 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8708 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8710 struct file *file = prsrc->file;
8711 #if defined(CONFIG_UNIX)
8712 struct sock *sock = ctx->ring_sock->sk;
8713 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8714 struct sk_buff *skb;
8717 __skb_queue_head_init(&list);
8720 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8721 * remove this entry and rearrange the file array.
8723 skb = skb_dequeue(head);
8725 struct scm_fp_list *fp;
8727 fp = UNIXCB(skb).fp;
8728 for (i = 0; i < fp->count; i++) {
8731 if (fp->fp[i] != file)
8734 unix_notinflight(fp->user, fp->fp[i]);
8735 left = fp->count - 1 - i;
8737 memmove(&fp->fp[i], &fp->fp[i + 1],
8738 left * sizeof(struct file *));
8745 __skb_queue_tail(&list, skb);
8755 __skb_queue_tail(&list, skb);
8757 skb = skb_dequeue(head);
8760 if (skb_peek(&list)) {
8761 spin_lock_irq(&head->lock);
8762 while ((skb = __skb_dequeue(&list)) != NULL)
8763 __skb_queue_tail(head, skb);
8764 spin_unlock_irq(&head->lock);
8771 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8773 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8774 struct io_ring_ctx *ctx = rsrc_data->ctx;
8775 struct io_rsrc_put *prsrc, *tmp;
8777 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8778 list_del(&prsrc->list);
8781 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8783 io_ring_submit_lock(ctx, lock_ring);
8784 spin_lock(&ctx->completion_lock);
8785 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8786 io_commit_cqring(ctx);
8787 spin_unlock(&ctx->completion_lock);
8788 io_cqring_ev_posted(ctx);
8789 io_ring_submit_unlock(ctx, lock_ring);
8792 rsrc_data->do_put(ctx, prsrc);
8796 io_rsrc_node_destroy(ref_node);
8797 if (atomic_dec_and_test(&rsrc_data->refs))
8798 complete(&rsrc_data->done);
8801 static void io_rsrc_put_work(struct work_struct *work)
8803 struct io_ring_ctx *ctx;
8804 struct llist_node *node;
8806 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8807 node = llist_del_all(&ctx->rsrc_put_llist);
8810 struct io_rsrc_node *ref_node;
8811 struct llist_node *next = node->next;
8813 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8814 __io_rsrc_put_work(ref_node);
8819 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8820 unsigned nr_args, u64 __user *tags)
8822 __s32 __user *fds = (__s32 __user *) arg;
8831 if (nr_args > IORING_MAX_FIXED_FILES)
8833 if (nr_args > rlimit(RLIMIT_NOFILE))
8835 ret = io_rsrc_node_switch_start(ctx);
8838 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8844 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8847 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8848 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8852 /* allow sparse sets */
8855 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8862 if (unlikely(!file))
8866 * Don't allow io_uring instances to be registered. If UNIX
8867 * isn't enabled, then this causes a reference cycle and this
8868 * instance can never get freed. If UNIX is enabled we'll
8869 * handle it just fine, but there's still no point in allowing
8870 * a ring fd as it doesn't support regular read/write anyway.
8872 if (file->f_op == &io_uring_fops) {
8876 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8879 ret = io_sqe_files_scm(ctx);
8881 __io_sqe_files_unregister(ctx);
8885 io_rsrc_node_switch(ctx, NULL);
8888 for (i = 0; i < ctx->nr_user_files; i++) {
8889 file = io_file_from_index(ctx, i);
8893 io_free_file_tables(&ctx->file_table);
8894 ctx->nr_user_files = 0;
8896 io_rsrc_data_free(ctx->file_data);
8897 ctx->file_data = NULL;
8901 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8904 #if defined(CONFIG_UNIX)
8905 struct sock *sock = ctx->ring_sock->sk;
8906 struct sk_buff_head *head = &sock->sk_receive_queue;
8907 struct sk_buff *skb;
8910 * See if we can merge this file into an existing skb SCM_RIGHTS
8911 * file set. If there's no room, fall back to allocating a new skb
8912 * and filling it in.
8914 spin_lock_irq(&head->lock);
8915 skb = skb_peek(head);
8917 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8919 if (fpl->count < SCM_MAX_FD) {
8920 __skb_unlink(skb, head);
8921 spin_unlock_irq(&head->lock);
8922 fpl->fp[fpl->count] = get_file(file);
8923 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8925 spin_lock_irq(&head->lock);
8926 __skb_queue_head(head, skb);
8931 spin_unlock_irq(&head->lock);
8938 return __io_sqe_files_scm(ctx, 1, index);
8944 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8945 struct io_rsrc_node *node, void *rsrc)
8947 u64 *tag_slot = io_get_tag_slot(data, idx);
8948 struct io_rsrc_put *prsrc;
8950 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8954 prsrc->tag = *tag_slot;
8957 list_add(&prsrc->list, &node->rsrc_list);
8961 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8962 unsigned int issue_flags, u32 slot_index)
8964 struct io_ring_ctx *ctx = req->ctx;
8965 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8966 bool needs_switch = false;
8967 struct io_fixed_file *file_slot;
8970 io_ring_submit_lock(ctx, needs_lock);
8971 if (file->f_op == &io_uring_fops)
8974 if (!ctx->file_data)
8977 if (slot_index >= ctx->nr_user_files)
8980 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8981 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8983 if (file_slot->file_ptr) {
8984 struct file *old_file;
8986 ret = io_rsrc_node_switch_start(ctx);
8990 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8991 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8992 ctx->rsrc_node, old_file);
8995 file_slot->file_ptr = 0;
8996 needs_switch = true;
8999 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9000 io_fixed_file_set(file_slot, file);
9001 ret = io_sqe_file_register(ctx, file, slot_index);
9003 file_slot->file_ptr = 0;
9010 io_rsrc_node_switch(ctx, ctx->file_data);
9011 io_ring_submit_unlock(ctx, needs_lock);
9017 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9019 unsigned int offset = req->close.file_slot - 1;
9020 struct io_ring_ctx *ctx = req->ctx;
9021 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9022 struct io_fixed_file *file_slot;
9026 io_ring_submit_lock(ctx, needs_lock);
9028 if (unlikely(!ctx->file_data))
9031 if (offset >= ctx->nr_user_files)
9033 ret = io_rsrc_node_switch_start(ctx);
9037 offset = array_index_nospec(offset, ctx->nr_user_files);
9038 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9040 if (!file_slot->file_ptr)
9043 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9044 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9048 file_slot->file_ptr = 0;
9049 io_rsrc_node_switch(ctx, ctx->file_data);
9052 io_ring_submit_unlock(ctx, needs_lock);
9056 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9057 struct io_uring_rsrc_update2 *up,
9060 u64 __user *tags = u64_to_user_ptr(up->tags);
9061 __s32 __user *fds = u64_to_user_ptr(up->data);
9062 struct io_rsrc_data *data = ctx->file_data;
9063 struct io_fixed_file *file_slot;
9067 bool needs_switch = false;
9069 if (!ctx->file_data)
9071 if (up->offset + nr_args > ctx->nr_user_files)
9074 for (done = 0; done < nr_args; done++) {
9077 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9078 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9082 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9086 if (fd == IORING_REGISTER_FILES_SKIP)
9089 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9090 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9092 if (file_slot->file_ptr) {
9093 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9094 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9097 file_slot->file_ptr = 0;
9098 needs_switch = true;
9107 * Don't allow io_uring instances to be registered. If
9108 * UNIX isn't enabled, then this causes a reference
9109 * cycle and this instance can never get freed. If UNIX
9110 * is enabled we'll handle it just fine, but there's
9111 * still no point in allowing a ring fd as it doesn't
9112 * support regular read/write anyway.
9114 if (file->f_op == &io_uring_fops) {
9119 *io_get_tag_slot(data, i) = tag;
9120 io_fixed_file_set(file_slot, file);
9121 err = io_sqe_file_register(ctx, file, i);
9123 file_slot->file_ptr = 0;
9131 io_rsrc_node_switch(ctx, data);
9132 return done ? done : err;
9135 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9136 struct task_struct *task)
9138 struct io_wq_hash *hash;
9139 struct io_wq_data data;
9140 unsigned int concurrency;
9142 mutex_lock(&ctx->uring_lock);
9143 hash = ctx->hash_map;
9145 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9147 mutex_unlock(&ctx->uring_lock);
9148 return ERR_PTR(-ENOMEM);
9150 refcount_set(&hash->refs, 1);
9151 init_waitqueue_head(&hash->wait);
9152 ctx->hash_map = hash;
9154 mutex_unlock(&ctx->uring_lock);
9158 data.free_work = io_wq_free_work;
9159 data.do_work = io_wq_submit_work;
9161 /* Do QD, or 4 * CPUS, whatever is smallest */
9162 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9164 return io_wq_create(concurrency, &data);
9167 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9168 struct io_ring_ctx *ctx)
9170 struct io_uring_task *tctx;
9173 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9174 if (unlikely(!tctx))
9177 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9178 sizeof(struct file *), GFP_KERNEL);
9179 if (unlikely(!tctx->registered_rings)) {
9184 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9185 if (unlikely(ret)) {
9186 kfree(tctx->registered_rings);
9191 tctx->io_wq = io_init_wq_offload(ctx, task);
9192 if (IS_ERR(tctx->io_wq)) {
9193 ret = PTR_ERR(tctx->io_wq);
9194 percpu_counter_destroy(&tctx->inflight);
9195 kfree(tctx->registered_rings);
9201 init_waitqueue_head(&tctx->wait);
9202 atomic_set(&tctx->in_idle, 0);
9203 task->io_uring = tctx;
9204 spin_lock_init(&tctx->task_lock);
9205 INIT_WQ_LIST(&tctx->task_list);
9206 INIT_WQ_LIST(&tctx->prior_task_list);
9207 init_task_work(&tctx->task_work, tctx_task_work);
9211 void __io_uring_free(struct task_struct *tsk)
9213 struct io_uring_task *tctx = tsk->io_uring;
9215 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9216 WARN_ON_ONCE(tctx->io_wq);
9217 WARN_ON_ONCE(tctx->cached_refs);
9219 kfree(tctx->registered_rings);
9220 percpu_counter_destroy(&tctx->inflight);
9222 tsk->io_uring = NULL;
9225 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9226 struct io_uring_params *p)
9230 /* Retain compatibility with failing for an invalid attach attempt */
9231 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9232 IORING_SETUP_ATTACH_WQ) {
9235 f = fdget(p->wq_fd);
9238 if (f.file->f_op != &io_uring_fops) {
9244 if (ctx->flags & IORING_SETUP_SQPOLL) {
9245 struct task_struct *tsk;
9246 struct io_sq_data *sqd;
9249 ret = security_uring_sqpoll();
9253 sqd = io_get_sq_data(p, &attached);
9259 ctx->sq_creds = get_current_cred();
9261 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9262 if (!ctx->sq_thread_idle)
9263 ctx->sq_thread_idle = HZ;
9265 io_sq_thread_park(sqd);
9266 list_add(&ctx->sqd_list, &sqd->ctx_list);
9267 io_sqd_update_thread_idle(sqd);
9268 /* don't attach to a dying SQPOLL thread, would be racy */
9269 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9270 io_sq_thread_unpark(sqd);
9277 if (p->flags & IORING_SETUP_SQ_AFF) {
9278 int cpu = p->sq_thread_cpu;
9281 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9288 sqd->task_pid = current->pid;
9289 sqd->task_tgid = current->tgid;
9290 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9297 ret = io_uring_alloc_task_context(tsk, ctx);
9298 wake_up_new_task(tsk);
9301 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9302 /* Can't have SQ_AFF without SQPOLL */
9309 complete(&ctx->sq_data->exited);
9311 io_sq_thread_finish(ctx);
9315 static inline void __io_unaccount_mem(struct user_struct *user,
9316 unsigned long nr_pages)
9318 atomic_long_sub(nr_pages, &user->locked_vm);
9321 static inline int __io_account_mem(struct user_struct *user,
9322 unsigned long nr_pages)
9324 unsigned long page_limit, cur_pages, new_pages;
9326 /* Don't allow more pages than we can safely lock */
9327 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9330 cur_pages = atomic_long_read(&user->locked_vm);
9331 new_pages = cur_pages + nr_pages;
9332 if (new_pages > page_limit)
9334 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9335 new_pages) != cur_pages);
9340 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9343 __io_unaccount_mem(ctx->user, nr_pages);
9345 if (ctx->mm_account)
9346 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9349 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9354 ret = __io_account_mem(ctx->user, nr_pages);
9359 if (ctx->mm_account)
9360 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9365 static void io_mem_free(void *ptr)
9372 page = virt_to_head_page(ptr);
9373 if (put_page_testzero(page))
9374 free_compound_page(page);
9377 static void *io_mem_alloc(size_t size)
9379 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9381 return (void *) __get_free_pages(gfp, get_order(size));
9384 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9387 struct io_rings *rings;
9388 size_t off, sq_array_size;
9390 off = struct_size(rings, cqes, cq_entries);
9391 if (off == SIZE_MAX)
9395 off = ALIGN(off, SMP_CACHE_BYTES);
9403 sq_array_size = array_size(sizeof(u32), sq_entries);
9404 if (sq_array_size == SIZE_MAX)
9407 if (check_add_overflow(off, sq_array_size, &off))
9413 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9415 struct io_mapped_ubuf *imu = *slot;
9418 if (imu != ctx->dummy_ubuf) {
9419 for (i = 0; i < imu->nr_bvecs; i++)
9420 unpin_user_page(imu->bvec[i].bv_page);
9421 if (imu->acct_pages)
9422 io_unaccount_mem(ctx, imu->acct_pages);
9428 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9430 io_buffer_unmap(ctx, &prsrc->buf);
9434 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9438 for (i = 0; i < ctx->nr_user_bufs; i++)
9439 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9440 kfree(ctx->user_bufs);
9441 io_rsrc_data_free(ctx->buf_data);
9442 ctx->user_bufs = NULL;
9443 ctx->buf_data = NULL;
9444 ctx->nr_user_bufs = 0;
9447 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9454 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9456 __io_sqe_buffers_unregister(ctx);
9460 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9461 void __user *arg, unsigned index)
9463 struct iovec __user *src;
9465 #ifdef CONFIG_COMPAT
9467 struct compat_iovec __user *ciovs;
9468 struct compat_iovec ciov;
9470 ciovs = (struct compat_iovec __user *) arg;
9471 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9474 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9475 dst->iov_len = ciov.iov_len;
9479 src = (struct iovec __user *) arg;
9480 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9486 * Not super efficient, but this is just a registration time. And we do cache
9487 * the last compound head, so generally we'll only do a full search if we don't
9490 * We check if the given compound head page has already been accounted, to
9491 * avoid double accounting it. This allows us to account the full size of the
9492 * page, not just the constituent pages of a huge page.
9494 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9495 int nr_pages, struct page *hpage)
9499 /* check current page array */
9500 for (i = 0; i < nr_pages; i++) {
9501 if (!PageCompound(pages[i]))
9503 if (compound_head(pages[i]) == hpage)
9507 /* check previously registered pages */
9508 for (i = 0; i < ctx->nr_user_bufs; i++) {
9509 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9511 for (j = 0; j < imu->nr_bvecs; j++) {
9512 if (!PageCompound(imu->bvec[j].bv_page))
9514 if (compound_head(imu->bvec[j].bv_page) == hpage)
9522 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9523 int nr_pages, struct io_mapped_ubuf *imu,
9524 struct page **last_hpage)
9528 imu->acct_pages = 0;
9529 for (i = 0; i < nr_pages; i++) {
9530 if (!PageCompound(pages[i])) {
9535 hpage = compound_head(pages[i]);
9536 if (hpage == *last_hpage)
9538 *last_hpage = hpage;
9539 if (headpage_already_acct(ctx, pages, i, hpage))
9541 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9545 if (!imu->acct_pages)
9548 ret = io_account_mem(ctx, imu->acct_pages);
9550 imu->acct_pages = 0;
9554 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9555 struct io_mapped_ubuf **pimu,
9556 struct page **last_hpage)
9558 struct io_mapped_ubuf *imu = NULL;
9559 struct vm_area_struct **vmas = NULL;
9560 struct page **pages = NULL;
9561 unsigned long off, start, end, ubuf;
9563 int ret, pret, nr_pages, i;
9565 if (!iov->iov_base) {
9566 *pimu = ctx->dummy_ubuf;
9570 ubuf = (unsigned long) iov->iov_base;
9571 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9572 start = ubuf >> PAGE_SHIFT;
9573 nr_pages = end - start;
9578 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9582 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9587 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9592 mmap_read_lock(current->mm);
9593 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9595 if (pret == nr_pages) {
9596 /* don't support file backed memory */
9597 for (i = 0; i < nr_pages; i++) {
9598 struct vm_area_struct *vma = vmas[i];
9600 if (vma_is_shmem(vma))
9603 !is_file_hugepages(vma->vm_file)) {
9609 ret = pret < 0 ? pret : -EFAULT;
9611 mmap_read_unlock(current->mm);
9614 * if we did partial map, or found file backed vmas,
9615 * release any pages we did get
9618 unpin_user_pages(pages, pret);
9622 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9624 unpin_user_pages(pages, pret);
9628 off = ubuf & ~PAGE_MASK;
9629 size = iov->iov_len;
9630 for (i = 0; i < nr_pages; i++) {
9633 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9634 imu->bvec[i].bv_page = pages[i];
9635 imu->bvec[i].bv_len = vec_len;
9636 imu->bvec[i].bv_offset = off;
9640 /* store original address for later verification */
9642 imu->ubuf_end = ubuf + iov->iov_len;
9643 imu->nr_bvecs = nr_pages;
9654 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9656 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9657 return ctx->user_bufs ? 0 : -ENOMEM;
9660 static int io_buffer_validate(struct iovec *iov)
9662 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9665 * Don't impose further limits on the size and buffer
9666 * constraints here, we'll -EINVAL later when IO is
9667 * submitted if they are wrong.
9670 return iov->iov_len ? -EFAULT : 0;
9674 /* arbitrary limit, but we need something */
9675 if (iov->iov_len > SZ_1G)
9678 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9684 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9685 unsigned int nr_args, u64 __user *tags)
9687 struct page *last_hpage = NULL;
9688 struct io_rsrc_data *data;
9694 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9696 ret = io_rsrc_node_switch_start(ctx);
9699 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9702 ret = io_buffers_map_alloc(ctx, nr_args);
9704 io_rsrc_data_free(data);
9708 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9709 ret = io_copy_iov(ctx, &iov, arg, i);
9712 ret = io_buffer_validate(&iov);
9715 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9720 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9726 WARN_ON_ONCE(ctx->buf_data);
9728 ctx->buf_data = data;
9730 __io_sqe_buffers_unregister(ctx);
9732 io_rsrc_node_switch(ctx, NULL);
9736 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9737 struct io_uring_rsrc_update2 *up,
9738 unsigned int nr_args)
9740 u64 __user *tags = u64_to_user_ptr(up->tags);
9741 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9742 struct page *last_hpage = NULL;
9743 bool needs_switch = false;
9749 if (up->offset + nr_args > ctx->nr_user_bufs)
9752 for (done = 0; done < nr_args; done++) {
9753 struct io_mapped_ubuf *imu;
9754 int offset = up->offset + done;
9757 err = io_copy_iov(ctx, &iov, iovs, done);
9760 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9764 err = io_buffer_validate(&iov);
9767 if (!iov.iov_base && tag) {
9771 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9775 i = array_index_nospec(offset, ctx->nr_user_bufs);
9776 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9777 err = io_queue_rsrc_removal(ctx->buf_data, i,
9778 ctx->rsrc_node, ctx->user_bufs[i]);
9779 if (unlikely(err)) {
9780 io_buffer_unmap(ctx, &imu);
9783 ctx->user_bufs[i] = NULL;
9784 needs_switch = true;
9787 ctx->user_bufs[i] = imu;
9788 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9792 io_rsrc_node_switch(ctx, ctx->buf_data);
9793 return done ? done : err;
9796 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9797 unsigned int eventfd_async)
9799 struct io_ev_fd *ev_fd;
9800 __s32 __user *fds = arg;
9803 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9804 lockdep_is_held(&ctx->uring_lock));
9808 if (copy_from_user(&fd, fds, sizeof(*fds)))
9811 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9815 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9816 if (IS_ERR(ev_fd->cq_ev_fd)) {
9817 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9821 ev_fd->eventfd_async = eventfd_async;
9822 ctx->has_evfd = true;
9823 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9827 static void io_eventfd_put(struct rcu_head *rcu)
9829 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9831 eventfd_ctx_put(ev_fd->cq_ev_fd);
9835 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9837 struct io_ev_fd *ev_fd;
9839 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9840 lockdep_is_held(&ctx->uring_lock));
9842 ctx->has_evfd = false;
9843 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9844 call_rcu(&ev_fd->rcu, io_eventfd_put);
9851 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9855 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9856 struct list_head *list = &ctx->io_buffers[i];
9858 while (!list_empty(list)) {
9859 struct io_buffer_list *bl;
9861 bl = list_first_entry(list, struct io_buffer_list, list);
9862 __io_remove_buffers(ctx, bl, -1U);
9863 list_del(&bl->list);
9868 while (!list_empty(&ctx->io_buffers_pages)) {
9871 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9872 list_del_init(&page->lru);
9877 static void io_req_caches_free(struct io_ring_ctx *ctx)
9879 struct io_submit_state *state = &ctx->submit_state;
9882 mutex_lock(&ctx->uring_lock);
9883 io_flush_cached_locked_reqs(ctx, state);
9885 while (state->free_list.next) {
9886 struct io_wq_work_node *node;
9887 struct io_kiocb *req;
9889 node = wq_stack_extract(&state->free_list);
9890 req = container_of(node, struct io_kiocb, comp_list);
9891 kmem_cache_free(req_cachep, req);
9895 percpu_ref_put_many(&ctx->refs, nr);
9896 mutex_unlock(&ctx->uring_lock);
9899 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9901 if (data && !atomic_dec_and_test(&data->refs))
9902 wait_for_completion(&data->done);
9905 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
9907 struct async_poll *apoll;
9909 while (!list_empty(&ctx->apoll_cache)) {
9910 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
9912 list_del(&apoll->poll.wait.entry);
9917 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9919 io_sq_thread_finish(ctx);
9921 if (ctx->mm_account) {
9922 mmdrop(ctx->mm_account);
9923 ctx->mm_account = NULL;
9926 io_rsrc_refs_drop(ctx);
9927 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9928 io_wait_rsrc_data(ctx->buf_data);
9929 io_wait_rsrc_data(ctx->file_data);
9931 mutex_lock(&ctx->uring_lock);
9933 __io_sqe_buffers_unregister(ctx);
9935 __io_sqe_files_unregister(ctx);
9937 __io_cqring_overflow_flush(ctx, true);
9938 io_eventfd_unregister(ctx);
9939 io_flush_apoll_cache(ctx);
9940 mutex_unlock(&ctx->uring_lock);
9941 io_destroy_buffers(ctx);
9943 put_cred(ctx->sq_creds);
9945 /* there are no registered resources left, nobody uses it */
9947 io_rsrc_node_destroy(ctx->rsrc_node);
9948 if (ctx->rsrc_backup_node)
9949 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9950 flush_delayed_work(&ctx->rsrc_put_work);
9951 flush_delayed_work(&ctx->fallback_work);
9953 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9954 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9956 #if defined(CONFIG_UNIX)
9957 if (ctx->ring_sock) {
9958 ctx->ring_sock->file = NULL; /* so that iput() is called */
9959 sock_release(ctx->ring_sock);
9962 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9964 io_mem_free(ctx->rings);
9965 io_mem_free(ctx->sq_sqes);
9967 percpu_ref_exit(&ctx->refs);
9968 free_uid(ctx->user);
9969 io_req_caches_free(ctx);
9971 io_wq_put_hash(ctx->hash_map);
9972 kfree(ctx->cancel_hash);
9973 kfree(ctx->dummy_ubuf);
9974 kfree(ctx->io_buffers);
9978 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9980 struct io_ring_ctx *ctx = file->private_data;
9983 poll_wait(file, &ctx->cq_wait, wait);
9985 * synchronizes with barrier from wq_has_sleeper call in
9989 if (!io_sqring_full(ctx))
9990 mask |= EPOLLOUT | EPOLLWRNORM;
9993 * Don't flush cqring overflow list here, just do a simple check.
9994 * Otherwise there could possible be ABBA deadlock:
9997 * lock(&ctx->uring_lock);
9999 * lock(&ctx->uring_lock);
10002 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10003 * pushs them to do the flush.
10005 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
10006 mask |= EPOLLIN | EPOLLRDNORM;
10011 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10013 const struct cred *creds;
10015 creds = xa_erase(&ctx->personalities, id);
10024 struct io_tctx_exit {
10025 struct callback_head task_work;
10026 struct completion completion;
10027 struct io_ring_ctx *ctx;
10030 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10032 struct io_uring_task *tctx = current->io_uring;
10033 struct io_tctx_exit *work;
10035 work = container_of(cb, struct io_tctx_exit, task_work);
10037 * When @in_idle, we're in cancellation and it's racy to remove the
10038 * node. It'll be removed by the end of cancellation, just ignore it.
10040 if (!atomic_read(&tctx->in_idle))
10041 io_uring_del_tctx_node((unsigned long)work->ctx);
10042 complete(&work->completion);
10045 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10047 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10049 return req->ctx == data;
10052 static __cold void io_ring_exit_work(struct work_struct *work)
10054 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10055 unsigned long timeout = jiffies + HZ * 60 * 5;
10056 unsigned long interval = HZ / 20;
10057 struct io_tctx_exit exit;
10058 struct io_tctx_node *node;
10062 * If we're doing polled IO and end up having requests being
10063 * submitted async (out-of-line), then completions can come in while
10064 * we're waiting for refs to drop. We need to reap these manually,
10065 * as nobody else will be looking for them.
10068 io_uring_try_cancel_requests(ctx, NULL, true);
10069 if (ctx->sq_data) {
10070 struct io_sq_data *sqd = ctx->sq_data;
10071 struct task_struct *tsk;
10073 io_sq_thread_park(sqd);
10075 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10076 io_wq_cancel_cb(tsk->io_uring->io_wq,
10077 io_cancel_ctx_cb, ctx, true);
10078 io_sq_thread_unpark(sqd);
10081 io_req_caches_free(ctx);
10083 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10084 /* there is little hope left, don't run it too often */
10085 interval = HZ * 60;
10087 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10089 init_completion(&exit.completion);
10090 init_task_work(&exit.task_work, io_tctx_exit_cb);
10093 * Some may use context even when all refs and requests have been put,
10094 * and they are free to do so while still holding uring_lock or
10095 * completion_lock, see io_req_task_submit(). Apart from other work,
10096 * this lock/unlock section also waits them to finish.
10098 mutex_lock(&ctx->uring_lock);
10099 while (!list_empty(&ctx->tctx_list)) {
10100 WARN_ON_ONCE(time_after(jiffies, timeout));
10102 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10104 /* don't spin on a single task if cancellation failed */
10105 list_rotate_left(&ctx->tctx_list);
10106 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10107 if (WARN_ON_ONCE(ret))
10110 mutex_unlock(&ctx->uring_lock);
10111 wait_for_completion(&exit.completion);
10112 mutex_lock(&ctx->uring_lock);
10114 mutex_unlock(&ctx->uring_lock);
10115 spin_lock(&ctx->completion_lock);
10116 spin_unlock(&ctx->completion_lock);
10118 io_ring_ctx_free(ctx);
10121 /* Returns true if we found and killed one or more timeouts */
10122 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10123 struct task_struct *tsk, bool cancel_all)
10125 struct io_kiocb *req, *tmp;
10128 spin_lock(&ctx->completion_lock);
10129 spin_lock_irq(&ctx->timeout_lock);
10130 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10131 if (io_match_task(req, tsk, cancel_all)) {
10132 io_kill_timeout(req, -ECANCELED);
10136 spin_unlock_irq(&ctx->timeout_lock);
10138 io_commit_cqring(ctx);
10139 spin_unlock(&ctx->completion_lock);
10141 io_cqring_ev_posted(ctx);
10142 return canceled != 0;
10145 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10147 unsigned long index;
10148 struct creds *creds;
10150 mutex_lock(&ctx->uring_lock);
10151 percpu_ref_kill(&ctx->refs);
10153 __io_cqring_overflow_flush(ctx, true);
10154 xa_for_each(&ctx->personalities, index, creds)
10155 io_unregister_personality(ctx, index);
10156 mutex_unlock(&ctx->uring_lock);
10158 io_kill_timeouts(ctx, NULL, true);
10159 io_poll_remove_all(ctx, NULL, true);
10161 /* if we failed setting up the ctx, we might not have any rings */
10162 io_iopoll_try_reap_events(ctx);
10164 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10166 * Use system_unbound_wq to avoid spawning tons of event kworkers
10167 * if we're exiting a ton of rings at the same time. It just adds
10168 * noise and overhead, there's no discernable change in runtime
10169 * over using system_wq.
10171 queue_work(system_unbound_wq, &ctx->exit_work);
10174 static int io_uring_release(struct inode *inode, struct file *file)
10176 struct io_ring_ctx *ctx = file->private_data;
10178 file->private_data = NULL;
10179 io_ring_ctx_wait_and_kill(ctx);
10183 struct io_task_cancel {
10184 struct task_struct *task;
10188 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10190 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10191 struct io_task_cancel *cancel = data;
10193 return io_match_task_safe(req, cancel->task, cancel->all);
10196 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10197 struct task_struct *task,
10200 struct io_defer_entry *de;
10203 spin_lock(&ctx->completion_lock);
10204 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10205 if (io_match_task_safe(de->req, task, cancel_all)) {
10206 list_cut_position(&list, &ctx->defer_list, &de->list);
10210 spin_unlock(&ctx->completion_lock);
10211 if (list_empty(&list))
10214 while (!list_empty(&list)) {
10215 de = list_first_entry(&list, struct io_defer_entry, list);
10216 list_del_init(&de->list);
10217 io_req_complete_failed(de->req, -ECANCELED);
10223 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10225 struct io_tctx_node *node;
10226 enum io_wq_cancel cret;
10229 mutex_lock(&ctx->uring_lock);
10230 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10231 struct io_uring_task *tctx = node->task->io_uring;
10234 * io_wq will stay alive while we hold uring_lock, because it's
10235 * killed after ctx nodes, which requires to take the lock.
10237 if (!tctx || !tctx->io_wq)
10239 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10240 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10242 mutex_unlock(&ctx->uring_lock);
10247 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10248 struct task_struct *task,
10251 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10252 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10255 enum io_wq_cancel cret;
10259 ret |= io_uring_try_cancel_iowq(ctx);
10260 } else if (tctx && tctx->io_wq) {
10262 * Cancels requests of all rings, not only @ctx, but
10263 * it's fine as the task is in exit/exec.
10265 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10267 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10270 /* SQPOLL thread does its own polling */
10271 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10272 (ctx->sq_data && ctx->sq_data->thread == current)) {
10273 while (!wq_list_empty(&ctx->iopoll_list)) {
10274 io_iopoll_try_reap_events(ctx);
10279 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10280 ret |= io_poll_remove_all(ctx, task, cancel_all);
10281 ret |= io_kill_timeouts(ctx, task, cancel_all);
10283 ret |= io_run_task_work();
10290 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10292 struct io_uring_task *tctx = current->io_uring;
10293 struct io_tctx_node *node;
10296 if (unlikely(!tctx)) {
10297 ret = io_uring_alloc_task_context(current, ctx);
10301 tctx = current->io_uring;
10302 if (ctx->iowq_limits_set) {
10303 unsigned int limits[2] = { ctx->iowq_limits[0],
10304 ctx->iowq_limits[1], };
10306 ret = io_wq_max_workers(tctx->io_wq, limits);
10311 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10312 node = kmalloc(sizeof(*node), GFP_KERNEL);
10316 node->task = current;
10318 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10319 node, GFP_KERNEL));
10325 mutex_lock(&ctx->uring_lock);
10326 list_add(&node->ctx_node, &ctx->tctx_list);
10327 mutex_unlock(&ctx->uring_lock);
10334 * Note that this task has used io_uring. We use it for cancelation purposes.
10336 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10338 struct io_uring_task *tctx = current->io_uring;
10340 if (likely(tctx && tctx->last == ctx))
10342 return __io_uring_add_tctx_node(ctx);
10346 * Remove this io_uring_file -> task mapping.
10348 static __cold void io_uring_del_tctx_node(unsigned long index)
10350 struct io_uring_task *tctx = current->io_uring;
10351 struct io_tctx_node *node;
10355 node = xa_erase(&tctx->xa, index);
10359 WARN_ON_ONCE(current != node->task);
10360 WARN_ON_ONCE(list_empty(&node->ctx_node));
10362 mutex_lock(&node->ctx->uring_lock);
10363 list_del(&node->ctx_node);
10364 mutex_unlock(&node->ctx->uring_lock);
10366 if (tctx->last == node->ctx)
10371 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10373 struct io_wq *wq = tctx->io_wq;
10374 struct io_tctx_node *node;
10375 unsigned long index;
10377 xa_for_each(&tctx->xa, index, node) {
10378 io_uring_del_tctx_node(index);
10383 * Must be after io_uring_del_tctx_node() (removes nodes under
10384 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10386 io_wq_put_and_exit(wq);
10387 tctx->io_wq = NULL;
10391 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10395 return percpu_counter_sum(&tctx->inflight);
10399 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10400 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10402 static __cold void io_uring_cancel_generic(bool cancel_all,
10403 struct io_sq_data *sqd)
10405 struct io_uring_task *tctx = current->io_uring;
10406 struct io_ring_ctx *ctx;
10410 WARN_ON_ONCE(sqd && sqd->thread != current);
10412 if (!current->io_uring)
10415 io_wq_exit_start(tctx->io_wq);
10417 atomic_inc(&tctx->in_idle);
10419 io_uring_drop_tctx_refs(current);
10420 /* read completions before cancelations */
10421 inflight = tctx_inflight(tctx, !cancel_all);
10426 struct io_tctx_node *node;
10427 unsigned long index;
10429 xa_for_each(&tctx->xa, index, node) {
10430 /* sqpoll task will cancel all its requests */
10431 if (node->ctx->sq_data)
10433 io_uring_try_cancel_requests(node->ctx, current,
10437 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10438 io_uring_try_cancel_requests(ctx, current,
10442 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10443 io_run_task_work();
10444 io_uring_drop_tctx_refs(current);
10447 * If we've seen completions, retry without waiting. This
10448 * avoids a race where a completion comes in before we did
10449 * prepare_to_wait().
10451 if (inflight == tctx_inflight(tctx, !cancel_all))
10453 finish_wait(&tctx->wait, &wait);
10456 io_uring_clean_tctx(tctx);
10459 * We shouldn't run task_works after cancel, so just leave
10460 * ->in_idle set for normal exit.
10462 atomic_dec(&tctx->in_idle);
10463 /* for exec all current's requests should be gone, kill tctx */
10464 __io_uring_free(current);
10468 void __io_uring_cancel(bool cancel_all)
10470 io_uring_cancel_generic(cancel_all, NULL);
10473 void io_uring_unreg_ringfd(void)
10475 struct io_uring_task *tctx = current->io_uring;
10478 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10479 if (tctx->registered_rings[i]) {
10480 fput(tctx->registered_rings[i]);
10481 tctx->registered_rings[i] = NULL;
10486 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10487 int start, int end)
10492 for (offset = start; offset < end; offset++) {
10493 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10494 if (tctx->registered_rings[offset])
10500 } else if (file->f_op != &io_uring_fops) {
10502 return -EOPNOTSUPP;
10504 tctx->registered_rings[offset] = file;
10512 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10513 * invocation. User passes in an array of struct io_uring_rsrc_update
10514 * with ->data set to the ring_fd, and ->offset given for the desired
10515 * index. If no index is desired, application may set ->offset == -1U
10516 * and we'll find an available index. Returns number of entries
10517 * successfully processed, or < 0 on error if none were processed.
10519 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10522 struct io_uring_rsrc_update __user *arg = __arg;
10523 struct io_uring_rsrc_update reg;
10524 struct io_uring_task *tctx;
10527 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10530 mutex_unlock(&ctx->uring_lock);
10531 ret = io_uring_add_tctx_node(ctx);
10532 mutex_lock(&ctx->uring_lock);
10536 tctx = current->io_uring;
10537 for (i = 0; i < nr_args; i++) {
10540 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10550 if (reg.offset == -1U) {
10552 end = IO_RINGFD_REG_MAX;
10554 if (reg.offset >= IO_RINGFD_REG_MAX) {
10558 start = reg.offset;
10562 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10567 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10568 fput(tctx->registered_rings[reg.offset]);
10569 tctx->registered_rings[reg.offset] = NULL;
10575 return i ? i : ret;
10578 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10581 struct io_uring_rsrc_update __user *arg = __arg;
10582 struct io_uring_task *tctx = current->io_uring;
10583 struct io_uring_rsrc_update reg;
10586 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10591 for (i = 0; i < nr_args; i++) {
10592 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10596 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
10601 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10602 if (tctx->registered_rings[reg.offset]) {
10603 fput(tctx->registered_rings[reg.offset]);
10604 tctx->registered_rings[reg.offset] = NULL;
10608 return i ? i : ret;
10611 static void *io_uring_validate_mmap_request(struct file *file,
10612 loff_t pgoff, size_t sz)
10614 struct io_ring_ctx *ctx = file->private_data;
10615 loff_t offset = pgoff << PAGE_SHIFT;
10620 case IORING_OFF_SQ_RING:
10621 case IORING_OFF_CQ_RING:
10624 case IORING_OFF_SQES:
10625 ptr = ctx->sq_sqes;
10628 return ERR_PTR(-EINVAL);
10631 page = virt_to_head_page(ptr);
10632 if (sz > page_size(page))
10633 return ERR_PTR(-EINVAL);
10640 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10642 size_t sz = vma->vm_end - vma->vm_start;
10646 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10648 return PTR_ERR(ptr);
10650 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10651 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10654 #else /* !CONFIG_MMU */
10656 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10658 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10661 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10663 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10666 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10667 unsigned long addr, unsigned long len,
10668 unsigned long pgoff, unsigned long flags)
10672 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10674 return PTR_ERR(ptr);
10676 return (unsigned long) ptr;
10679 #endif /* !CONFIG_MMU */
10681 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10686 if (!io_sqring_full(ctx))
10688 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10690 if (!io_sqring_full(ctx))
10693 } while (!signal_pending(current));
10695 finish_wait(&ctx->sqo_sq_wait, &wait);
10699 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10700 struct __kernel_timespec __user **ts,
10701 const sigset_t __user **sig)
10703 struct io_uring_getevents_arg arg;
10706 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10707 * is just a pointer to the sigset_t.
10709 if (!(flags & IORING_ENTER_EXT_ARG)) {
10710 *sig = (const sigset_t __user *) argp;
10716 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10717 * timespec and sigset_t pointers if good.
10719 if (*argsz != sizeof(arg))
10721 if (copy_from_user(&arg, argp, sizeof(arg)))
10725 *sig = u64_to_user_ptr(arg.sigmask);
10726 *argsz = arg.sigmask_sz;
10727 *ts = u64_to_user_ptr(arg.ts);
10731 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10732 u32, min_complete, u32, flags, const void __user *, argp,
10735 struct io_ring_ctx *ctx;
10740 io_run_task_work();
10742 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10743 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10744 IORING_ENTER_REGISTERED_RING)))
10748 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10749 * need only dereference our task private array to find it.
10751 if (flags & IORING_ENTER_REGISTERED_RING) {
10752 struct io_uring_task *tctx = current->io_uring;
10754 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10756 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10757 f.file = tctx->registered_rings[fd];
10758 if (unlikely(!f.file))
10762 if (unlikely(!f.file))
10767 if (unlikely(f.file->f_op != &io_uring_fops))
10771 ctx = f.file->private_data;
10772 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10776 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10780 * For SQ polling, the thread will do all submissions and completions.
10781 * Just return the requested submit count, and wake the thread if
10782 * we were asked to.
10785 if (ctx->flags & IORING_SETUP_SQPOLL) {
10786 io_cqring_overflow_flush(ctx);
10788 if (unlikely(ctx->sq_data->thread == NULL)) {
10792 if (flags & IORING_ENTER_SQ_WAKEUP)
10793 wake_up(&ctx->sq_data->wait);
10794 if (flags & IORING_ENTER_SQ_WAIT) {
10795 ret = io_sqpoll_wait_sq(ctx);
10799 submitted = to_submit;
10800 } else if (to_submit) {
10801 ret = io_uring_add_tctx_node(ctx);
10804 mutex_lock(&ctx->uring_lock);
10805 submitted = io_submit_sqes(ctx, to_submit);
10806 mutex_unlock(&ctx->uring_lock);
10808 if (submitted != to_submit)
10811 if (flags & IORING_ENTER_GETEVENTS) {
10812 const sigset_t __user *sig;
10813 struct __kernel_timespec __user *ts;
10815 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10819 min_complete = min(min_complete, ctx->cq_entries);
10822 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10823 * space applications don't need to do io completion events
10824 * polling again, they can rely on io_sq_thread to do polling
10825 * work, which can reduce cpu usage and uring_lock contention.
10827 if (ctx->flags & IORING_SETUP_IOPOLL &&
10828 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10829 ret = io_iopoll_check(ctx, min_complete);
10831 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10836 percpu_ref_put(&ctx->refs);
10838 if (!(flags & IORING_ENTER_REGISTERED_RING))
10840 return submitted ? submitted : ret;
10843 #ifdef CONFIG_PROC_FS
10844 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10845 const struct cred *cred)
10847 struct user_namespace *uns = seq_user_ns(m);
10848 struct group_info *gi;
10853 seq_printf(m, "%5d\n", id);
10854 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10855 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10856 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10857 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10858 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10859 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10860 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10861 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10862 seq_puts(m, "\n\tGroups:\t");
10863 gi = cred->group_info;
10864 for (g = 0; g < gi->ngroups; g++) {
10865 seq_put_decimal_ull(m, g ? " " : "",
10866 from_kgid_munged(uns, gi->gid[g]));
10868 seq_puts(m, "\n\tCapEff:\t");
10869 cap = cred->cap_effective;
10870 CAP_FOR_EACH_U32(__capi)
10871 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10876 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10877 struct seq_file *m)
10879 struct io_sq_data *sq = NULL;
10880 struct io_overflow_cqe *ocqe;
10881 struct io_rings *r = ctx->rings;
10882 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10883 unsigned int sq_head = READ_ONCE(r->sq.head);
10884 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10885 unsigned int cq_head = READ_ONCE(r->cq.head);
10886 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10887 unsigned int sq_entries, cq_entries;
10892 * we may get imprecise sqe and cqe info if uring is actively running
10893 * since we get cached_sq_head and cached_cq_tail without uring_lock
10894 * and sq_tail and cq_head are changed by userspace. But it's ok since
10895 * we usually use these info when it is stuck.
10897 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10898 seq_printf(m, "SqHead:\t%u\n", sq_head);
10899 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10900 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10901 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10902 seq_printf(m, "CqHead:\t%u\n", cq_head);
10903 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10904 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10905 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10906 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10907 for (i = 0; i < sq_entries; i++) {
10908 unsigned int entry = i + sq_head;
10909 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10910 struct io_uring_sqe *sqe;
10912 if (sq_idx > sq_mask)
10914 sqe = &ctx->sq_sqes[sq_idx];
10915 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10916 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10919 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10920 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10921 for (i = 0; i < cq_entries; i++) {
10922 unsigned int entry = i + cq_head;
10923 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10925 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10926 entry & cq_mask, cqe->user_data, cqe->res,
10931 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10932 * since fdinfo case grabs it in the opposite direction of normal use
10933 * cases. If we fail to get the lock, we just don't iterate any
10934 * structures that could be going away outside the io_uring mutex.
10936 has_lock = mutex_trylock(&ctx->uring_lock);
10938 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10944 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10945 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10946 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10947 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10948 struct file *f = io_file_from_index(ctx, i);
10951 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10953 seq_printf(m, "%5u: <none>\n", i);
10955 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10956 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10957 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10958 unsigned int len = buf->ubuf_end - buf->ubuf;
10960 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10962 if (has_lock && !xa_empty(&ctx->personalities)) {
10963 unsigned long index;
10964 const struct cred *cred;
10966 seq_printf(m, "Personalities:\n");
10967 xa_for_each(&ctx->personalities, index, cred)
10968 io_uring_show_cred(m, index, cred);
10971 mutex_unlock(&ctx->uring_lock);
10973 seq_puts(m, "PollList:\n");
10974 spin_lock(&ctx->completion_lock);
10975 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10976 struct hlist_head *list = &ctx->cancel_hash[i];
10977 struct io_kiocb *req;
10979 hlist_for_each_entry(req, list, hash_node)
10980 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10981 task_work_pending(req->task));
10984 seq_puts(m, "CqOverflowList:\n");
10985 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10986 struct io_uring_cqe *cqe = &ocqe->cqe;
10988 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10989 cqe->user_data, cqe->res, cqe->flags);
10993 spin_unlock(&ctx->completion_lock);
10996 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10998 struct io_ring_ctx *ctx = f->private_data;
11000 if (percpu_ref_tryget(&ctx->refs)) {
11001 __io_uring_show_fdinfo(ctx, m);
11002 percpu_ref_put(&ctx->refs);
11007 static const struct file_operations io_uring_fops = {
11008 .release = io_uring_release,
11009 .mmap = io_uring_mmap,
11011 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11012 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11014 .poll = io_uring_poll,
11015 #ifdef CONFIG_PROC_FS
11016 .show_fdinfo = io_uring_show_fdinfo,
11020 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11021 struct io_uring_params *p)
11023 struct io_rings *rings;
11024 size_t size, sq_array_offset;
11026 /* make sure these are sane, as we already accounted them */
11027 ctx->sq_entries = p->sq_entries;
11028 ctx->cq_entries = p->cq_entries;
11030 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11031 if (size == SIZE_MAX)
11034 rings = io_mem_alloc(size);
11038 ctx->rings = rings;
11039 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11040 rings->sq_ring_mask = p->sq_entries - 1;
11041 rings->cq_ring_mask = p->cq_entries - 1;
11042 rings->sq_ring_entries = p->sq_entries;
11043 rings->cq_ring_entries = p->cq_entries;
11045 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11046 if (size == SIZE_MAX) {
11047 io_mem_free(ctx->rings);
11052 ctx->sq_sqes = io_mem_alloc(size);
11053 if (!ctx->sq_sqes) {
11054 io_mem_free(ctx->rings);
11062 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11066 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11070 ret = io_uring_add_tctx_node(ctx);
11075 fd_install(fd, file);
11080 * Allocate an anonymous fd, this is what constitutes the application
11081 * visible backing of an io_uring instance. The application mmaps this
11082 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11083 * we have to tie this fd to a socket for file garbage collection purposes.
11085 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11088 #if defined(CONFIG_UNIX)
11091 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11094 return ERR_PTR(ret);
11097 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11098 O_RDWR | O_CLOEXEC, NULL);
11099 #if defined(CONFIG_UNIX)
11100 if (IS_ERR(file)) {
11101 sock_release(ctx->ring_sock);
11102 ctx->ring_sock = NULL;
11104 ctx->ring_sock->file = file;
11110 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11111 struct io_uring_params __user *params)
11113 struct io_ring_ctx *ctx;
11119 if (entries > IORING_MAX_ENTRIES) {
11120 if (!(p->flags & IORING_SETUP_CLAMP))
11122 entries = IORING_MAX_ENTRIES;
11126 * Use twice as many entries for the CQ ring. It's possible for the
11127 * application to drive a higher depth than the size of the SQ ring,
11128 * since the sqes are only used at submission time. This allows for
11129 * some flexibility in overcommitting a bit. If the application has
11130 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11131 * of CQ ring entries manually.
11133 p->sq_entries = roundup_pow_of_two(entries);
11134 if (p->flags & IORING_SETUP_CQSIZE) {
11136 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11137 * to a power-of-two, if it isn't already. We do NOT impose
11138 * any cq vs sq ring sizing.
11140 if (!p->cq_entries)
11142 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11143 if (!(p->flags & IORING_SETUP_CLAMP))
11145 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11147 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11148 if (p->cq_entries < p->sq_entries)
11151 p->cq_entries = 2 * p->sq_entries;
11154 ctx = io_ring_ctx_alloc(p);
11157 ctx->compat = in_compat_syscall();
11158 if (!capable(CAP_IPC_LOCK))
11159 ctx->user = get_uid(current_user());
11162 * This is just grabbed for accounting purposes. When a process exits,
11163 * the mm is exited and dropped before the files, hence we need to hang
11164 * on to this mm purely for the purposes of being able to unaccount
11165 * memory (locked/pinned vm). It's not used for anything else.
11167 mmgrab(current->mm);
11168 ctx->mm_account = current->mm;
11170 ret = io_allocate_scq_urings(ctx, p);
11174 ret = io_sq_offload_create(ctx, p);
11177 /* always set a rsrc node */
11178 ret = io_rsrc_node_switch_start(ctx);
11181 io_rsrc_node_switch(ctx, NULL);
11183 memset(&p->sq_off, 0, sizeof(p->sq_off));
11184 p->sq_off.head = offsetof(struct io_rings, sq.head);
11185 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11186 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11187 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11188 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11189 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11190 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11192 memset(&p->cq_off, 0, sizeof(p->cq_off));
11193 p->cq_off.head = offsetof(struct io_rings, cq.head);
11194 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11195 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11196 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11197 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11198 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11199 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11201 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11202 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11203 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11204 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11205 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11206 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
11207 IORING_FEAT_LINKED_FILE;
11209 if (copy_to_user(params, p, sizeof(*p))) {
11214 file = io_uring_get_file(ctx);
11215 if (IS_ERR(file)) {
11216 ret = PTR_ERR(file);
11221 * Install ring fd as the very last thing, so we don't risk someone
11222 * having closed it before we finish setup
11224 ret = io_uring_install_fd(ctx, file);
11226 /* fput will clean it up */
11231 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11234 io_ring_ctx_wait_and_kill(ctx);
11239 * Sets up an aio uring context, and returns the fd. Applications asks for a
11240 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11241 * params structure passed in.
11243 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11245 struct io_uring_params p;
11248 if (copy_from_user(&p, params, sizeof(p)))
11250 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11255 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11256 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11257 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11258 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11261 return io_uring_create(entries, &p, params);
11264 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11265 struct io_uring_params __user *, params)
11267 return io_uring_setup(entries, params);
11270 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11273 struct io_uring_probe *p;
11277 size = struct_size(p, ops, nr_args);
11278 if (size == SIZE_MAX)
11280 p = kzalloc(size, GFP_KERNEL);
11285 if (copy_from_user(p, arg, size))
11288 if (memchr_inv(p, 0, size))
11291 p->last_op = IORING_OP_LAST - 1;
11292 if (nr_args > IORING_OP_LAST)
11293 nr_args = IORING_OP_LAST;
11295 for (i = 0; i < nr_args; i++) {
11297 if (!io_op_defs[i].not_supported)
11298 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11303 if (copy_to_user(arg, p, size))
11310 static int io_register_personality(struct io_ring_ctx *ctx)
11312 const struct cred *creds;
11316 creds = get_current_cred();
11318 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11319 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11327 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11328 void __user *arg, unsigned int nr_args)
11330 struct io_uring_restriction *res;
11334 /* Restrictions allowed only if rings started disabled */
11335 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11338 /* We allow only a single restrictions registration */
11339 if (ctx->restrictions.registered)
11342 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11345 size = array_size(nr_args, sizeof(*res));
11346 if (size == SIZE_MAX)
11349 res = memdup_user(arg, size);
11351 return PTR_ERR(res);
11355 for (i = 0; i < nr_args; i++) {
11356 switch (res[i].opcode) {
11357 case IORING_RESTRICTION_REGISTER_OP:
11358 if (res[i].register_op >= IORING_REGISTER_LAST) {
11363 __set_bit(res[i].register_op,
11364 ctx->restrictions.register_op);
11366 case IORING_RESTRICTION_SQE_OP:
11367 if (res[i].sqe_op >= IORING_OP_LAST) {
11372 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11374 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11375 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11377 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11378 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11387 /* Reset all restrictions if an error happened */
11389 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11391 ctx->restrictions.registered = true;
11397 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11399 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11402 if (ctx->restrictions.registered)
11403 ctx->restricted = 1;
11405 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11406 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11407 wake_up(&ctx->sq_data->wait);
11411 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11412 struct io_uring_rsrc_update2 *up,
11418 if (check_add_overflow(up->offset, nr_args, &tmp))
11420 err = io_rsrc_node_switch_start(ctx);
11425 case IORING_RSRC_FILE:
11426 return __io_sqe_files_update(ctx, up, nr_args);
11427 case IORING_RSRC_BUFFER:
11428 return __io_sqe_buffers_update(ctx, up, nr_args);
11433 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11436 struct io_uring_rsrc_update2 up;
11440 memset(&up, 0, sizeof(up));
11441 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11443 if (up.resv || up.resv2)
11445 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11448 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11449 unsigned size, unsigned type)
11451 struct io_uring_rsrc_update2 up;
11453 if (size != sizeof(up))
11455 if (copy_from_user(&up, arg, sizeof(up)))
11457 if (!up.nr || up.resv || up.resv2)
11459 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11462 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11463 unsigned int size, unsigned int type)
11465 struct io_uring_rsrc_register rr;
11467 /* keep it extendible */
11468 if (size != sizeof(rr))
11471 memset(&rr, 0, sizeof(rr));
11472 if (copy_from_user(&rr, arg, size))
11474 if (!rr.nr || rr.resv || rr.resv2)
11478 case IORING_RSRC_FILE:
11479 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11480 rr.nr, u64_to_user_ptr(rr.tags));
11481 case IORING_RSRC_BUFFER:
11482 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11483 rr.nr, u64_to_user_ptr(rr.tags));
11488 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11489 void __user *arg, unsigned len)
11491 struct io_uring_task *tctx = current->io_uring;
11492 cpumask_var_t new_mask;
11495 if (!tctx || !tctx->io_wq)
11498 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11501 cpumask_clear(new_mask);
11502 if (len > cpumask_size())
11503 len = cpumask_size();
11505 if (in_compat_syscall()) {
11506 ret = compat_get_bitmap(cpumask_bits(new_mask),
11507 (const compat_ulong_t __user *)arg,
11508 len * 8 /* CHAR_BIT */);
11510 ret = copy_from_user(new_mask, arg, len);
11514 free_cpumask_var(new_mask);
11518 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11519 free_cpumask_var(new_mask);
11523 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11525 struct io_uring_task *tctx = current->io_uring;
11527 if (!tctx || !tctx->io_wq)
11530 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11533 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11535 __must_hold(&ctx->uring_lock)
11537 struct io_tctx_node *node;
11538 struct io_uring_task *tctx = NULL;
11539 struct io_sq_data *sqd = NULL;
11540 __u32 new_count[2];
11543 if (copy_from_user(new_count, arg, sizeof(new_count)))
11545 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11546 if (new_count[i] > INT_MAX)
11549 if (ctx->flags & IORING_SETUP_SQPOLL) {
11550 sqd = ctx->sq_data;
11553 * Observe the correct sqd->lock -> ctx->uring_lock
11554 * ordering. Fine to drop uring_lock here, we hold
11555 * a ref to the ctx.
11557 refcount_inc(&sqd->refs);
11558 mutex_unlock(&ctx->uring_lock);
11559 mutex_lock(&sqd->lock);
11560 mutex_lock(&ctx->uring_lock);
11562 tctx = sqd->thread->io_uring;
11565 tctx = current->io_uring;
11568 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11570 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11572 ctx->iowq_limits[i] = new_count[i];
11573 ctx->iowq_limits_set = true;
11575 if (tctx && tctx->io_wq) {
11576 ret = io_wq_max_workers(tctx->io_wq, new_count);
11580 memset(new_count, 0, sizeof(new_count));
11584 mutex_unlock(&sqd->lock);
11585 io_put_sq_data(sqd);
11588 if (copy_to_user(arg, new_count, sizeof(new_count)))
11591 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11595 /* now propagate the restriction to all registered users */
11596 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11597 struct io_uring_task *tctx = node->task->io_uring;
11599 if (WARN_ON_ONCE(!tctx->io_wq))
11602 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11603 new_count[i] = ctx->iowq_limits[i];
11604 /* ignore errors, it always returns zero anyway */
11605 (void)io_wq_max_workers(tctx->io_wq, new_count);
11610 mutex_unlock(&sqd->lock);
11611 io_put_sq_data(sqd);
11616 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11617 void __user *arg, unsigned nr_args)
11618 __releases(ctx->uring_lock)
11619 __acquires(ctx->uring_lock)
11624 * We're inside the ring mutex, if the ref is already dying, then
11625 * someone else killed the ctx or is already going through
11626 * io_uring_register().
11628 if (percpu_ref_is_dying(&ctx->refs))
11631 if (ctx->restricted) {
11632 if (opcode >= IORING_REGISTER_LAST)
11634 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11635 if (!test_bit(opcode, ctx->restrictions.register_op))
11640 case IORING_REGISTER_BUFFERS:
11641 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11643 case IORING_UNREGISTER_BUFFERS:
11645 if (arg || nr_args)
11647 ret = io_sqe_buffers_unregister(ctx);
11649 case IORING_REGISTER_FILES:
11650 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11652 case IORING_UNREGISTER_FILES:
11654 if (arg || nr_args)
11656 ret = io_sqe_files_unregister(ctx);
11658 case IORING_REGISTER_FILES_UPDATE:
11659 ret = io_register_files_update(ctx, arg, nr_args);
11661 case IORING_REGISTER_EVENTFD:
11665 ret = io_eventfd_register(ctx, arg, 0);
11667 case IORING_REGISTER_EVENTFD_ASYNC:
11671 ret = io_eventfd_register(ctx, arg, 1);
11673 case IORING_UNREGISTER_EVENTFD:
11675 if (arg || nr_args)
11677 ret = io_eventfd_unregister(ctx);
11679 case IORING_REGISTER_PROBE:
11681 if (!arg || nr_args > 256)
11683 ret = io_probe(ctx, arg, nr_args);
11685 case IORING_REGISTER_PERSONALITY:
11687 if (arg || nr_args)
11689 ret = io_register_personality(ctx);
11691 case IORING_UNREGISTER_PERSONALITY:
11695 ret = io_unregister_personality(ctx, nr_args);
11697 case IORING_REGISTER_ENABLE_RINGS:
11699 if (arg || nr_args)
11701 ret = io_register_enable_rings(ctx);
11703 case IORING_REGISTER_RESTRICTIONS:
11704 ret = io_register_restrictions(ctx, arg, nr_args);
11706 case IORING_REGISTER_FILES2:
11707 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11709 case IORING_REGISTER_FILES_UPDATE2:
11710 ret = io_register_rsrc_update(ctx, arg, nr_args,
11713 case IORING_REGISTER_BUFFERS2:
11714 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11716 case IORING_REGISTER_BUFFERS_UPDATE:
11717 ret = io_register_rsrc_update(ctx, arg, nr_args,
11718 IORING_RSRC_BUFFER);
11720 case IORING_REGISTER_IOWQ_AFF:
11722 if (!arg || !nr_args)
11724 ret = io_register_iowq_aff(ctx, arg, nr_args);
11726 case IORING_UNREGISTER_IOWQ_AFF:
11728 if (arg || nr_args)
11730 ret = io_unregister_iowq_aff(ctx);
11732 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11734 if (!arg || nr_args != 2)
11736 ret = io_register_iowq_max_workers(ctx, arg);
11738 case IORING_REGISTER_RING_FDS:
11739 ret = io_ringfd_register(ctx, arg, nr_args);
11741 case IORING_UNREGISTER_RING_FDS:
11742 ret = io_ringfd_unregister(ctx, arg, nr_args);
11752 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11753 void __user *, arg, unsigned int, nr_args)
11755 struct io_ring_ctx *ctx;
11764 if (f.file->f_op != &io_uring_fops)
11767 ctx = f.file->private_data;
11769 io_run_task_work();
11771 mutex_lock(&ctx->uring_lock);
11772 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11773 mutex_unlock(&ctx->uring_lock);
11774 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11780 static int __init io_uring_init(void)
11782 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11783 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11784 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11787 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11788 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11789 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11790 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11791 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11792 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11793 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11794 BUILD_BUG_SQE_ELEM(8, __u64, off);
11795 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11796 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11797 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11798 BUILD_BUG_SQE_ELEM(24, __u32, len);
11799 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11800 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11801 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11802 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11803 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11804 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11805 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11806 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11807 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11808 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11809 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11810 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11811 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11812 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11813 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11814 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11815 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11816 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11817 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11818 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11819 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11821 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11822 sizeof(struct io_uring_rsrc_update));
11823 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11824 sizeof(struct io_uring_rsrc_update2));
11826 /* ->buf_index is u16 */
11827 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11829 /* should fit into one byte */
11830 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11831 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11832 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11834 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11835 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11837 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11841 __initcall(io_uring_init);