1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/audit.h>
82 #include <linux/security.h>
84 #define CREATE_TRACE_POINTS
85 #include <trace/events/io_uring.h>
87 #include <uapi/linux/io_uring.h>
92 #define IORING_MAX_ENTRIES 32768
93 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
97 #define IORING_MAX_FIXED_FILES (1U << 15)
98 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
99 IORING_REGISTER_LAST + IORING_OP_LAST)
101 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
102 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
103 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
105 #define IORING_MAX_REG_BUFFERS (1U << 14)
107 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
111 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_CREDS | REQ_F_ASYNC_DATA)
116 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
119 u32 head ____cacheline_aligned_in_smp;
120 u32 tail ____cacheline_aligned_in_smp;
124 * This data is shared with the application through the mmap at offsets
125 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
127 * The offsets to the member fields are published through struct
128 * io_sqring_offsets when calling io_uring_setup.
132 * Head and tail offsets into the ring; the offsets need to be
133 * masked to get valid indices.
135 * The kernel controls head of the sq ring and the tail of the cq ring,
136 * and the application controls tail of the sq ring and the head of the
139 struct io_uring sq, cq;
141 * Bitmasks to apply to head and tail offsets (constant, equals
144 u32 sq_ring_mask, cq_ring_mask;
145 /* Ring sizes (constant, power of 2) */
146 u32 sq_ring_entries, cq_ring_entries;
148 * Number of invalid entries dropped by the kernel due to
149 * invalid index stored in array
151 * Written by the kernel, shouldn't be modified by the
152 * application (i.e. get number of "new events" by comparing to
155 * After a new SQ head value was read by the application this
156 * counter includes all submissions that were dropped reaching
157 * the new SQ head (and possibly more).
163 * Written by the kernel, shouldn't be modified by the
166 * The application needs a full memory barrier before checking
167 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
173 * Written by the application, shouldn't be modified by the
178 * Number of completion events lost because the queue was full;
179 * this should be avoided by the application by making sure
180 * there are not more requests pending than there is space in
181 * the completion queue.
183 * Written by the kernel, shouldn't be modified by the
184 * application (i.e. get number of "new events" by comparing to
187 * As completion events come in out of order this counter is not
188 * ordered with any other data.
192 * Ring buffer of completion events.
194 * The kernel writes completion events fresh every time they are
195 * produced, so the application is allowed to modify pending
198 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
201 enum io_uring_cmd_flags {
202 IO_URING_F_COMPLETE_DEFER = 1,
203 IO_URING_F_UNLOCKED = 2,
204 /* int's last bit, sign checks are usually faster than a bit test */
205 IO_URING_F_NONBLOCK = INT_MIN,
208 struct io_mapped_ubuf {
211 unsigned int nr_bvecs;
212 unsigned long acct_pages;
213 struct bio_vec bvec[];
218 struct io_overflow_cqe {
219 struct io_uring_cqe cqe;
220 struct list_head list;
223 struct io_fixed_file {
224 /* file * with additional FFS_* flags */
225 unsigned long file_ptr;
229 struct list_head list;
234 struct io_mapped_ubuf *buf;
238 struct io_file_table {
239 struct io_fixed_file *files;
242 struct io_rsrc_node {
243 struct percpu_ref refs;
244 struct list_head node;
245 struct list_head rsrc_list;
246 struct io_rsrc_data *rsrc_data;
247 struct llist_node llist;
251 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
253 struct io_rsrc_data {
254 struct io_ring_ctx *ctx;
260 struct completion done;
264 struct io_buffer_list {
265 struct list_head list;
266 struct list_head buf_list;
271 struct list_head list;
278 struct io_restriction {
279 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
280 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
281 u8 sqe_flags_allowed;
282 u8 sqe_flags_required;
287 IO_SQ_THREAD_SHOULD_STOP = 0,
288 IO_SQ_THREAD_SHOULD_PARK,
293 atomic_t park_pending;
296 /* ctx's that are using this sqd */
297 struct list_head ctx_list;
299 struct task_struct *thread;
300 struct wait_queue_head wait;
302 unsigned sq_thread_idle;
308 struct completion exited;
311 #define IO_COMPL_BATCH 32
312 #define IO_REQ_CACHE_SIZE 32
313 #define IO_REQ_ALLOC_BATCH 8
315 struct io_submit_link {
316 struct io_kiocb *head;
317 struct io_kiocb *last;
320 struct io_submit_state {
321 /* inline/task_work completion list, under ->uring_lock */
322 struct io_wq_work_node free_list;
323 /* batch completion logic */
324 struct io_wq_work_list compl_reqs;
325 struct io_submit_link link;
330 unsigned short submit_nr;
331 struct blk_plug plug;
335 struct eventfd_ctx *cq_ev_fd;
336 unsigned int eventfd_async: 1;
340 #define IO_BUFFERS_HASH_BITS 5
343 /* const or read-mostly hot data */
345 struct percpu_ref refs;
347 struct io_rings *rings;
349 unsigned int compat: 1;
350 unsigned int drain_next: 1;
351 unsigned int restricted: 1;
352 unsigned int off_timeout_used: 1;
353 unsigned int drain_active: 1;
354 unsigned int drain_disabled: 1;
355 unsigned int has_evfd: 1;
356 } ____cacheline_aligned_in_smp;
358 /* submission data */
360 struct mutex uring_lock;
363 * Ring buffer of indices into array of io_uring_sqe, which is
364 * mmapped by the application using the IORING_OFF_SQES offset.
366 * This indirection could e.g. be used to assign fixed
367 * io_uring_sqe entries to operations and only submit them to
368 * the queue when needed.
370 * The kernel modifies neither the indices array nor the entries
374 struct io_uring_sqe *sq_sqes;
375 unsigned cached_sq_head;
377 struct list_head defer_list;
380 * Fixed resources fast path, should be accessed only under
381 * uring_lock, and updated through io_uring_register(2)
383 struct io_rsrc_node *rsrc_node;
384 int rsrc_cached_refs;
385 struct io_file_table file_table;
386 unsigned nr_user_files;
387 unsigned nr_user_bufs;
388 struct io_mapped_ubuf **user_bufs;
390 struct io_submit_state submit_state;
391 struct list_head timeout_list;
392 struct list_head ltimeout_list;
393 struct list_head cq_overflow_list;
394 struct list_head *io_buffers;
395 struct list_head io_buffers_cache;
396 struct list_head apoll_cache;
397 struct xarray personalities;
399 unsigned sq_thread_idle;
400 } ____cacheline_aligned_in_smp;
402 /* IRQ completion list, under ->completion_lock */
403 struct io_wq_work_list locked_free_list;
404 unsigned int locked_free_nr;
406 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
407 struct io_sq_data *sq_data; /* if using sq thread polling */
409 struct wait_queue_head sqo_sq_wait;
410 struct list_head sqd_list;
412 unsigned long check_cq_overflow;
415 unsigned cached_cq_tail;
417 struct io_ev_fd __rcu *io_ev_fd;
418 struct wait_queue_head cq_wait;
420 atomic_t cq_timeouts;
421 unsigned cq_last_tm_flush;
422 } ____cacheline_aligned_in_smp;
425 spinlock_t completion_lock;
427 spinlock_t timeout_lock;
430 * ->iopoll_list is protected by the ctx->uring_lock for
431 * io_uring instances that don't use IORING_SETUP_SQPOLL.
432 * For SQPOLL, only the single threaded io_sq_thread() will
433 * manipulate the list, hence no extra locking is needed there.
435 struct io_wq_work_list iopoll_list;
436 struct hlist_head *cancel_hash;
437 unsigned cancel_hash_bits;
438 bool poll_multi_queue;
440 struct list_head io_buffers_comp;
441 } ____cacheline_aligned_in_smp;
443 struct io_restriction restrictions;
445 /* slow path rsrc auxilary data, used by update/register */
447 struct io_rsrc_node *rsrc_backup_node;
448 struct io_mapped_ubuf *dummy_ubuf;
449 struct io_rsrc_data *file_data;
450 struct io_rsrc_data *buf_data;
452 struct delayed_work rsrc_put_work;
453 struct llist_head rsrc_put_llist;
454 struct list_head rsrc_ref_list;
455 spinlock_t rsrc_ref_lock;
457 struct list_head io_buffers_pages;
460 /* Keep this last, we don't need it for the fast path */
462 #if defined(CONFIG_UNIX)
463 struct socket *ring_sock;
465 /* hashed buffered write serialization */
466 struct io_wq_hash *hash_map;
468 /* Only used for accounting purposes */
469 struct user_struct *user;
470 struct mm_struct *mm_account;
472 /* ctx exit and cancelation */
473 struct llist_head fallback_llist;
474 struct delayed_work fallback_work;
475 struct work_struct exit_work;
476 struct list_head tctx_list;
477 struct completion ref_comp;
479 bool iowq_limits_set;
484 * Arbitrary limit, can be raised if need be
486 #define IO_RINGFD_REG_MAX 16
488 struct io_uring_task {
489 /* submission side */
492 struct wait_queue_head wait;
493 const struct io_ring_ctx *last;
495 struct percpu_counter inflight;
498 spinlock_t task_lock;
499 struct io_wq_work_list task_list;
500 struct io_wq_work_list prior_task_list;
501 struct callback_head task_work;
502 struct file **registered_rings;
507 * First field must be the file pointer in all the
508 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
510 struct io_poll_iocb {
512 struct wait_queue_head *head;
514 struct wait_queue_entry wait;
517 struct io_poll_update {
523 bool update_user_data;
532 struct io_timeout_data {
533 struct io_kiocb *req;
534 struct hrtimer timer;
535 struct timespec64 ts;
536 enum hrtimer_mode mode;
542 struct sockaddr __user *addr;
543 int __user *addr_len;
546 unsigned long nofile;
566 struct list_head list;
567 /* head of the link, used by linked timeouts only */
568 struct io_kiocb *head;
569 /* for linked completions */
570 struct io_kiocb *prev;
573 struct io_timeout_rem {
578 struct timespec64 ts;
584 /* NOTE: kiocb has the file as the first member, so don't do it here */
593 struct sockaddr __user *addr;
600 struct compat_msghdr __user *umsg_compat;
601 struct user_msghdr __user *umsg;
614 struct filename *filename;
616 unsigned long nofile;
619 struct io_rsrc_update {
645 struct epoll_event event;
649 struct file *file_out;
657 struct io_provide_buf {
671 struct filename *filename;
672 struct statx __user *buffer;
684 struct filename *oldpath;
685 struct filename *newpath;
693 struct filename *filename;
700 struct filename *filename;
706 struct filename *oldpath;
707 struct filename *newpath;
714 struct filename *oldpath;
715 struct filename *newpath;
725 struct io_async_connect {
726 struct sockaddr_storage address;
729 struct io_async_msghdr {
730 struct iovec fast_iov[UIO_FASTIOV];
731 /* points to an allocated iov, if NULL we use fast_iov instead */
732 struct iovec *free_iov;
733 struct sockaddr __user *uaddr;
735 struct sockaddr_storage addr;
739 struct iov_iter iter;
740 struct iov_iter_state iter_state;
741 struct iovec fast_iov[UIO_FASTIOV];
745 struct io_rw_state s;
746 const struct iovec *free_iovec;
748 struct wait_page_queue wpq;
752 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
753 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
754 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
755 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
756 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
757 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
758 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
760 /* first byte is taken by user flags, shift it to not overlap */
765 REQ_F_LINK_TIMEOUT_BIT,
766 REQ_F_NEED_CLEANUP_BIT,
768 REQ_F_BUFFER_SELECTED_BIT,
769 REQ_F_COMPLETE_INLINE_BIT,
773 REQ_F_ARM_LTIMEOUT_BIT,
774 REQ_F_ASYNC_DATA_BIT,
775 REQ_F_SKIP_LINK_CQES_BIT,
776 REQ_F_SINGLE_POLL_BIT,
777 REQ_F_DOUBLE_POLL_BIT,
778 REQ_F_PARTIAL_IO_BIT,
779 /* keep async read/write and isreg together and in order */
780 REQ_F_SUPPORT_NOWAIT_BIT,
783 /* not a real bit, just to check we're not overflowing the space */
789 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
790 /* drain existing IO first */
791 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
793 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
794 /* doesn't sever on completion < 0 */
795 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
797 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
798 /* IOSQE_BUFFER_SELECT */
799 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
800 /* IOSQE_CQE_SKIP_SUCCESS */
801 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
803 /* fail rest of links */
804 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
805 /* on inflight list, should be cancelled and waited on exit reliably */
806 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
807 /* read/write uses file position */
808 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
809 /* must not punt to workers */
810 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
811 /* has or had linked timeout */
812 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
814 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
815 /* already went through poll handler */
816 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
817 /* buffer already selected */
818 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
819 /* completion is deferred through io_comp_state */
820 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
821 /* caller should reissue async */
822 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
823 /* supports async reads/writes */
824 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
826 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
827 /* has creds assigned */
828 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
829 /* skip refcounting if not set */
830 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
831 /* there is a linked timeout that has to be armed */
832 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
833 /* ->async_data allocated */
834 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
835 /* don't post CQEs while failing linked requests */
836 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
837 /* single poll may be active */
838 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
839 /* double poll may active */
840 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
841 /* request has already done partial IO */
842 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
846 struct io_poll_iocb poll;
847 struct io_poll_iocb *double_poll;
850 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
852 struct io_task_work {
854 struct io_wq_work_node node;
855 struct llist_node fallback_node;
857 io_req_tw_func_t func;
861 IORING_RSRC_FILE = 0,
862 IORING_RSRC_BUFFER = 1,
866 * NOTE! Each of the iocb union members has the file pointer
867 * as the first entry in their struct definition. So you can
868 * access the file pointer through any of the sub-structs,
869 * or directly as just 'file' in this struct.
875 struct io_poll_iocb poll;
876 struct io_poll_update poll_update;
877 struct io_accept accept;
879 struct io_cancel cancel;
880 struct io_timeout timeout;
881 struct io_timeout_rem timeout_rem;
882 struct io_connect connect;
883 struct io_sr_msg sr_msg;
885 struct io_close close;
886 struct io_rsrc_update rsrc_update;
887 struct io_fadvise fadvise;
888 struct io_madvise madvise;
889 struct io_epoll epoll;
890 struct io_splice splice;
891 struct io_provide_buf pbuf;
892 struct io_statx statx;
893 struct io_shutdown shutdown;
894 struct io_rename rename;
895 struct io_unlink unlink;
896 struct io_mkdir mkdir;
897 struct io_symlink symlink;
898 struct io_hardlink hardlink;
903 /* polled IO has completed */
912 struct io_ring_ctx *ctx;
913 struct task_struct *task;
915 struct percpu_ref *fixed_rsrc_refs;
916 /* store used ubuf, so we can prevent reloading */
917 struct io_mapped_ubuf *imu;
920 /* used by request caches, completion batching and iopoll */
921 struct io_wq_work_node comp_list;
922 /* cache ->apoll->events */
927 struct io_task_work io_task_work;
928 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
929 struct hlist_node hash_node;
930 /* internal polling, see IORING_FEAT_FAST_POLL */
931 struct async_poll *apoll;
932 /* opcode allocated if it needs to store data for async defer */
934 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
935 struct io_buffer *kbuf;
936 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
937 struct io_kiocb *link;
938 /* custom credentials, valid IFF REQ_F_CREDS is set */
939 const struct cred *creds;
940 struct io_wq_work work;
943 struct io_tctx_node {
944 struct list_head ctx_node;
945 struct task_struct *task;
946 struct io_ring_ctx *ctx;
949 struct io_defer_entry {
950 struct list_head list;
951 struct io_kiocb *req;
956 /* needs req->file assigned */
957 unsigned needs_file : 1;
958 /* should block plug */
960 /* hash wq insertion if file is a regular file */
961 unsigned hash_reg_file : 1;
962 /* unbound wq insertion if file is a non-regular file */
963 unsigned unbound_nonreg_file : 1;
964 /* set if opcode supports polled "wait" */
966 unsigned pollout : 1;
967 unsigned poll_exclusive : 1;
968 /* op supports buffer selection */
969 unsigned buffer_select : 1;
970 /* do prep async if is going to be punted */
971 unsigned needs_async_setup : 1;
972 /* opcode is not supported by this kernel */
973 unsigned not_supported : 1;
975 unsigned audit_skip : 1;
976 /* size of async data needed, if any */
977 unsigned short async_size;
980 static const struct io_op_def io_op_defs[] = {
981 [IORING_OP_NOP] = {},
982 [IORING_OP_READV] = {
984 .unbound_nonreg_file = 1,
987 .needs_async_setup = 1,
990 .async_size = sizeof(struct io_async_rw),
992 [IORING_OP_WRITEV] = {
995 .unbound_nonreg_file = 1,
997 .needs_async_setup = 1,
1000 .async_size = sizeof(struct io_async_rw),
1002 [IORING_OP_FSYNC] = {
1006 [IORING_OP_READ_FIXED] = {
1008 .unbound_nonreg_file = 1,
1012 .async_size = sizeof(struct io_async_rw),
1014 [IORING_OP_WRITE_FIXED] = {
1017 .unbound_nonreg_file = 1,
1021 .async_size = sizeof(struct io_async_rw),
1023 [IORING_OP_POLL_ADD] = {
1025 .unbound_nonreg_file = 1,
1028 [IORING_OP_POLL_REMOVE] = {
1031 [IORING_OP_SYNC_FILE_RANGE] = {
1035 [IORING_OP_SENDMSG] = {
1037 .unbound_nonreg_file = 1,
1039 .needs_async_setup = 1,
1040 .async_size = sizeof(struct io_async_msghdr),
1042 [IORING_OP_RECVMSG] = {
1044 .unbound_nonreg_file = 1,
1047 .needs_async_setup = 1,
1048 .async_size = sizeof(struct io_async_msghdr),
1050 [IORING_OP_TIMEOUT] = {
1052 .async_size = sizeof(struct io_timeout_data),
1054 [IORING_OP_TIMEOUT_REMOVE] = {
1055 /* used by timeout updates' prep() */
1058 [IORING_OP_ACCEPT] = {
1060 .unbound_nonreg_file = 1,
1062 .poll_exclusive = 1,
1064 [IORING_OP_ASYNC_CANCEL] = {
1067 [IORING_OP_LINK_TIMEOUT] = {
1069 .async_size = sizeof(struct io_timeout_data),
1071 [IORING_OP_CONNECT] = {
1073 .unbound_nonreg_file = 1,
1075 .needs_async_setup = 1,
1076 .async_size = sizeof(struct io_async_connect),
1078 [IORING_OP_FALLOCATE] = {
1081 [IORING_OP_OPENAT] = {},
1082 [IORING_OP_CLOSE] = {},
1083 [IORING_OP_FILES_UPDATE] = {
1086 [IORING_OP_STATX] = {
1089 [IORING_OP_READ] = {
1091 .unbound_nonreg_file = 1,
1096 .async_size = sizeof(struct io_async_rw),
1098 [IORING_OP_WRITE] = {
1101 .unbound_nonreg_file = 1,
1105 .async_size = sizeof(struct io_async_rw),
1107 [IORING_OP_FADVISE] = {
1111 [IORING_OP_MADVISE] = {},
1112 [IORING_OP_SEND] = {
1114 .unbound_nonreg_file = 1,
1118 [IORING_OP_RECV] = {
1120 .unbound_nonreg_file = 1,
1125 [IORING_OP_OPENAT2] = {
1127 [IORING_OP_EPOLL_CTL] = {
1128 .unbound_nonreg_file = 1,
1131 [IORING_OP_SPLICE] = {
1134 .unbound_nonreg_file = 1,
1137 [IORING_OP_PROVIDE_BUFFERS] = {
1140 [IORING_OP_REMOVE_BUFFERS] = {
1146 .unbound_nonreg_file = 1,
1149 [IORING_OP_SHUTDOWN] = {
1152 [IORING_OP_RENAMEAT] = {},
1153 [IORING_OP_UNLINKAT] = {},
1154 [IORING_OP_MKDIRAT] = {},
1155 [IORING_OP_SYMLINKAT] = {},
1156 [IORING_OP_LINKAT] = {},
1157 [IORING_OP_MSG_RING] = {
1162 /* requests with any of those set should undergo io_disarm_next() */
1163 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1165 static bool io_disarm_next(struct io_kiocb *req);
1166 static void io_uring_del_tctx_node(unsigned long index);
1167 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1168 struct task_struct *task,
1170 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1172 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1174 static void io_put_req(struct io_kiocb *req);
1175 static void io_put_req_deferred(struct io_kiocb *req);
1176 static void io_dismantle_req(struct io_kiocb *req);
1177 static void io_queue_linked_timeout(struct io_kiocb *req);
1178 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1179 struct io_uring_rsrc_update2 *up,
1181 static void io_clean_op(struct io_kiocb *req);
1182 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1183 unsigned issue_flags);
1184 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1185 static void io_drop_inflight_file(struct io_kiocb *req);
1186 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1187 static void __io_queue_sqe(struct io_kiocb *req);
1188 static void io_rsrc_put_work(struct work_struct *work);
1190 static void io_req_task_queue(struct io_kiocb *req);
1191 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1192 static int io_req_prep_async(struct io_kiocb *req);
1194 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1195 unsigned int issue_flags, u32 slot_index);
1196 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1198 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1199 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1201 static struct kmem_cache *req_cachep;
1203 static const struct file_operations io_uring_fops;
1205 struct sock *io_uring_get_socket(struct file *file)
1207 #if defined(CONFIG_UNIX)
1208 if (file->f_op == &io_uring_fops) {
1209 struct io_ring_ctx *ctx = file->private_data;
1211 return ctx->ring_sock->sk;
1216 EXPORT_SYMBOL(io_uring_get_socket);
1218 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1221 mutex_lock(&ctx->uring_lock);
1226 #define io_for_each_link(pos, head) \
1227 for (pos = (head); pos; pos = pos->link)
1230 * Shamelessly stolen from the mm implementation of page reference checking,
1231 * see commit f958d7b528b1 for details.
1233 #define req_ref_zero_or_close_to_overflow(req) \
1234 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1236 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1238 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1239 return atomic_inc_not_zero(&req->refs);
1242 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1244 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1247 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1248 return atomic_dec_and_test(&req->refs);
1251 static inline void req_ref_get(struct io_kiocb *req)
1253 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1254 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1255 atomic_inc(&req->refs);
1258 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1260 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1261 __io_submit_flush_completions(ctx);
1264 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1266 if (!(req->flags & REQ_F_REFCOUNT)) {
1267 req->flags |= REQ_F_REFCOUNT;
1268 atomic_set(&req->refs, nr);
1272 static inline void io_req_set_refcount(struct io_kiocb *req)
1274 __io_req_set_refcount(req, 1);
1277 #define IO_RSRC_REF_BATCH 100
1279 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1280 struct io_ring_ctx *ctx)
1281 __must_hold(&ctx->uring_lock)
1283 struct percpu_ref *ref = req->fixed_rsrc_refs;
1286 if (ref == &ctx->rsrc_node->refs)
1287 ctx->rsrc_cached_refs++;
1289 percpu_ref_put(ref);
1293 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1295 if (req->fixed_rsrc_refs)
1296 percpu_ref_put(req->fixed_rsrc_refs);
1299 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1300 __must_hold(&ctx->uring_lock)
1302 if (ctx->rsrc_cached_refs) {
1303 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1304 ctx->rsrc_cached_refs = 0;
1308 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1309 __must_hold(&ctx->uring_lock)
1311 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1312 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1315 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1316 struct io_ring_ctx *ctx,
1317 unsigned int issue_flags)
1319 if (!req->fixed_rsrc_refs) {
1320 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1322 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1323 lockdep_assert_held(&ctx->uring_lock);
1324 ctx->rsrc_cached_refs--;
1325 if (unlikely(ctx->rsrc_cached_refs < 0))
1326 io_rsrc_refs_refill(ctx);
1328 percpu_ref_get(req->fixed_rsrc_refs);
1333 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1335 struct io_buffer *kbuf = req->kbuf;
1336 unsigned int cflags;
1338 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1339 req->flags &= ~REQ_F_BUFFER_SELECTED;
1340 list_add(&kbuf->list, list);
1345 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1347 lockdep_assert_held(&req->ctx->completion_lock);
1349 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1351 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1354 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1355 unsigned issue_flags)
1357 unsigned int cflags;
1359 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1363 * We can add this buffer back to two lists:
1365 * 1) The io_buffers_cache list. This one is protected by the
1366 * ctx->uring_lock. If we already hold this lock, add back to this
1367 * list as we can grab it from issue as well.
1368 * 2) The io_buffers_comp list. This one is protected by the
1369 * ctx->completion_lock.
1371 * We migrate buffers from the comp_list to the issue cache list
1374 if (issue_flags & IO_URING_F_UNLOCKED) {
1375 struct io_ring_ctx *ctx = req->ctx;
1377 spin_lock(&ctx->completion_lock);
1378 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1379 spin_unlock(&ctx->completion_lock);
1381 lockdep_assert_held(&req->ctx->uring_lock);
1383 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1389 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1392 struct list_head *hash_list;
1393 struct io_buffer_list *bl;
1395 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1396 list_for_each_entry(bl, hash_list, list)
1397 if (bl->bgid == bgid || bgid == -1U)
1403 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1405 struct io_ring_ctx *ctx = req->ctx;
1406 struct io_buffer_list *bl;
1407 struct io_buffer *buf;
1409 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1411 /* don't recycle if we already did IO to this buffer */
1412 if (req->flags & REQ_F_PARTIAL_IO)
1415 if (issue_flags & IO_URING_F_UNLOCKED)
1416 mutex_lock(&ctx->uring_lock);
1418 lockdep_assert_held(&ctx->uring_lock);
1421 bl = io_buffer_get_list(ctx, buf->bgid);
1422 list_add(&buf->list, &bl->buf_list);
1423 req->flags &= ~REQ_F_BUFFER_SELECTED;
1426 if (issue_flags & IO_URING_F_UNLOCKED)
1427 mutex_unlock(&ctx->uring_lock);
1430 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1432 __must_hold(&req->ctx->timeout_lock)
1434 if (task && head->task != task)
1440 * As io_match_task() but protected against racing with linked timeouts.
1441 * User must not hold timeout_lock.
1443 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1446 if (task && head->task != task)
1451 static inline bool req_has_async_data(struct io_kiocb *req)
1453 return req->flags & REQ_F_ASYNC_DATA;
1456 static inline void req_set_fail(struct io_kiocb *req)
1458 req->flags |= REQ_F_FAIL;
1459 if (req->flags & REQ_F_CQE_SKIP) {
1460 req->flags &= ~REQ_F_CQE_SKIP;
1461 req->flags |= REQ_F_SKIP_LINK_CQES;
1465 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1471 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1473 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1475 complete(&ctx->ref_comp);
1478 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1480 return !req->timeout.off;
1483 static __cold void io_fallback_req_func(struct work_struct *work)
1485 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1486 fallback_work.work);
1487 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1488 struct io_kiocb *req, *tmp;
1489 bool locked = false;
1491 percpu_ref_get(&ctx->refs);
1492 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1493 req->io_task_work.func(req, &locked);
1496 io_submit_flush_completions(ctx);
1497 mutex_unlock(&ctx->uring_lock);
1499 percpu_ref_put(&ctx->refs);
1502 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1504 struct io_ring_ctx *ctx;
1507 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1512 * Use 5 bits less than the max cq entries, that should give us around
1513 * 32 entries per hash list if totally full and uniformly spread.
1515 hash_bits = ilog2(p->cq_entries);
1519 ctx->cancel_hash_bits = hash_bits;
1520 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1522 if (!ctx->cancel_hash)
1524 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1526 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1527 if (!ctx->dummy_ubuf)
1529 /* set invalid range, so io_import_fixed() fails meeting it */
1530 ctx->dummy_ubuf->ubuf = -1UL;
1532 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1533 sizeof(struct list_head), GFP_KERNEL);
1534 if (!ctx->io_buffers)
1536 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1537 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1539 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1540 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1543 ctx->flags = p->flags;
1544 init_waitqueue_head(&ctx->sqo_sq_wait);
1545 INIT_LIST_HEAD(&ctx->sqd_list);
1546 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1547 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1548 INIT_LIST_HEAD(&ctx->apoll_cache);
1549 init_completion(&ctx->ref_comp);
1550 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1551 mutex_init(&ctx->uring_lock);
1552 init_waitqueue_head(&ctx->cq_wait);
1553 spin_lock_init(&ctx->completion_lock);
1554 spin_lock_init(&ctx->timeout_lock);
1555 INIT_WQ_LIST(&ctx->iopoll_list);
1556 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1557 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1558 INIT_LIST_HEAD(&ctx->defer_list);
1559 INIT_LIST_HEAD(&ctx->timeout_list);
1560 INIT_LIST_HEAD(&ctx->ltimeout_list);
1561 spin_lock_init(&ctx->rsrc_ref_lock);
1562 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1563 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1564 init_llist_head(&ctx->rsrc_put_llist);
1565 INIT_LIST_HEAD(&ctx->tctx_list);
1566 ctx->submit_state.free_list.next = NULL;
1567 INIT_WQ_LIST(&ctx->locked_free_list);
1568 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1569 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1572 kfree(ctx->dummy_ubuf);
1573 kfree(ctx->cancel_hash);
1574 kfree(ctx->io_buffers);
1579 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1581 struct io_rings *r = ctx->rings;
1583 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1587 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1589 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1590 struct io_ring_ctx *ctx = req->ctx;
1592 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1598 #define FFS_NOWAIT 0x1UL
1599 #define FFS_ISREG 0x2UL
1600 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1602 static inline bool io_req_ffs_set(struct io_kiocb *req)
1604 return req->flags & REQ_F_FIXED_FILE;
1607 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1609 if (WARN_ON_ONCE(!req->link))
1612 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1613 req->flags |= REQ_F_LINK_TIMEOUT;
1615 /* linked timeouts should have two refs once prep'ed */
1616 io_req_set_refcount(req);
1617 __io_req_set_refcount(req->link, 2);
1621 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1623 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1625 return __io_prep_linked_timeout(req);
1628 static void io_prep_async_work(struct io_kiocb *req)
1630 const struct io_op_def *def = &io_op_defs[req->opcode];
1631 struct io_ring_ctx *ctx = req->ctx;
1633 if (!(req->flags & REQ_F_CREDS)) {
1634 req->flags |= REQ_F_CREDS;
1635 req->creds = get_current_cred();
1638 req->work.list.next = NULL;
1639 req->work.flags = 0;
1640 if (req->flags & REQ_F_FORCE_ASYNC)
1641 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1643 if (req->flags & REQ_F_ISREG) {
1644 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1645 io_wq_hash_work(&req->work, file_inode(req->file));
1646 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1647 if (def->unbound_nonreg_file)
1648 req->work.flags |= IO_WQ_WORK_UNBOUND;
1652 static void io_prep_async_link(struct io_kiocb *req)
1654 struct io_kiocb *cur;
1656 if (req->flags & REQ_F_LINK_TIMEOUT) {
1657 struct io_ring_ctx *ctx = req->ctx;
1659 spin_lock_irq(&ctx->timeout_lock);
1660 io_for_each_link(cur, req)
1661 io_prep_async_work(cur);
1662 spin_unlock_irq(&ctx->timeout_lock);
1664 io_for_each_link(cur, req)
1665 io_prep_async_work(cur);
1669 static inline void io_req_add_compl_list(struct io_kiocb *req)
1671 struct io_ring_ctx *ctx = req->ctx;
1672 struct io_submit_state *state = &ctx->submit_state;
1674 if (!(req->flags & REQ_F_CQE_SKIP))
1675 ctx->submit_state.flush_cqes = true;
1676 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1679 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1681 struct io_ring_ctx *ctx = req->ctx;
1682 struct io_kiocb *link = io_prep_linked_timeout(req);
1683 struct io_uring_task *tctx = req->task->io_uring;
1686 BUG_ON(!tctx->io_wq);
1688 /* init ->work of the whole link before punting */
1689 io_prep_async_link(req);
1692 * Not expected to happen, but if we do have a bug where this _can_
1693 * happen, catch it here and ensure the request is marked as
1694 * canceled. That will make io-wq go through the usual work cancel
1695 * procedure rather than attempt to run this request (or create a new
1698 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1699 req->work.flags |= IO_WQ_WORK_CANCEL;
1701 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1702 &req->work, io_wq_is_hashed(&req->work));
1703 io_wq_enqueue(tctx->io_wq, &req->work);
1705 io_queue_linked_timeout(link);
1708 static void io_kill_timeout(struct io_kiocb *req, int status)
1709 __must_hold(&req->ctx->completion_lock)
1710 __must_hold(&req->ctx->timeout_lock)
1712 struct io_timeout_data *io = req->async_data;
1714 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1717 atomic_set(&req->ctx->cq_timeouts,
1718 atomic_read(&req->ctx->cq_timeouts) + 1);
1719 list_del_init(&req->timeout.list);
1720 io_fill_cqe_req(req, status, 0);
1721 io_put_req_deferred(req);
1725 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1727 while (!list_empty(&ctx->defer_list)) {
1728 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1729 struct io_defer_entry, list);
1731 if (req_need_defer(de->req, de->seq))
1733 list_del_init(&de->list);
1734 io_req_task_queue(de->req);
1739 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1740 __must_hold(&ctx->completion_lock)
1742 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1743 struct io_kiocb *req, *tmp;
1745 spin_lock_irq(&ctx->timeout_lock);
1746 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1747 u32 events_needed, events_got;
1749 if (io_is_timeout_noseq(req))
1753 * Since seq can easily wrap around over time, subtract
1754 * the last seq at which timeouts were flushed before comparing.
1755 * Assuming not more than 2^31-1 events have happened since,
1756 * these subtractions won't have wrapped, so we can check if
1757 * target is in [last_seq, current_seq] by comparing the two.
1759 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1760 events_got = seq - ctx->cq_last_tm_flush;
1761 if (events_got < events_needed)
1764 io_kill_timeout(req, 0);
1766 ctx->cq_last_tm_flush = seq;
1767 spin_unlock_irq(&ctx->timeout_lock);
1770 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1772 /* order cqe stores with ring update */
1773 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1776 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1778 if (ctx->off_timeout_used || ctx->drain_active) {
1779 spin_lock(&ctx->completion_lock);
1780 if (ctx->off_timeout_used)
1781 io_flush_timeouts(ctx);
1782 if (ctx->drain_active)
1783 io_queue_deferred(ctx);
1784 io_commit_cqring(ctx);
1785 spin_unlock(&ctx->completion_lock);
1788 io_eventfd_signal(ctx);
1791 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1793 struct io_rings *r = ctx->rings;
1795 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1798 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1800 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1803 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1805 struct io_rings *rings = ctx->rings;
1806 unsigned tail, mask = ctx->cq_entries - 1;
1809 * writes to the cq entry need to come after reading head; the
1810 * control dependency is enough as we're using WRITE_ONCE to
1813 if (__io_cqring_events(ctx) == ctx->cq_entries)
1816 tail = ctx->cached_cq_tail++;
1817 return &rings->cqes[tail & mask];
1820 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1822 struct io_ev_fd *ev_fd;
1826 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1827 * and eventfd_signal
1829 ev_fd = rcu_dereference(ctx->io_ev_fd);
1832 * Check again if ev_fd exists incase an io_eventfd_unregister call
1833 * completed between the NULL check of ctx->io_ev_fd at the start of
1834 * the function and rcu_read_lock.
1836 if (unlikely(!ev_fd))
1838 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1841 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1842 eventfd_signal(ev_fd->cq_ev_fd, 1);
1847 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1850 * wake_up_all() may seem excessive, but io_wake_function() and
1851 * io_should_wake() handle the termination of the loop and only
1852 * wake as many waiters as we need to.
1854 if (wq_has_sleeper(&ctx->cq_wait))
1855 wake_up_all(&ctx->cq_wait);
1859 * This should only get called when at least one event has been posted.
1860 * Some applications rely on the eventfd notification count only changing
1861 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1862 * 1:1 relationship between how many times this function is called (and
1863 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1865 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1867 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1869 __io_commit_cqring_flush(ctx);
1871 io_cqring_wake(ctx);
1874 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1876 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1878 __io_commit_cqring_flush(ctx);
1880 if (ctx->flags & IORING_SETUP_SQPOLL)
1881 io_cqring_wake(ctx);
1884 /* Returns true if there are no backlogged entries after the flush */
1885 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1887 bool all_flushed, posted;
1889 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1893 spin_lock(&ctx->completion_lock);
1894 while (!list_empty(&ctx->cq_overflow_list)) {
1895 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1896 struct io_overflow_cqe *ocqe;
1900 ocqe = list_first_entry(&ctx->cq_overflow_list,
1901 struct io_overflow_cqe, list);
1903 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1905 io_account_cq_overflow(ctx);
1908 list_del(&ocqe->list);
1912 all_flushed = list_empty(&ctx->cq_overflow_list);
1914 clear_bit(0, &ctx->check_cq_overflow);
1915 WRITE_ONCE(ctx->rings->sq_flags,
1916 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1920 io_commit_cqring(ctx);
1921 spin_unlock(&ctx->completion_lock);
1923 io_cqring_ev_posted(ctx);
1927 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1931 if (test_bit(0, &ctx->check_cq_overflow)) {
1932 /* iopoll syncs against uring_lock, not completion_lock */
1933 if (ctx->flags & IORING_SETUP_IOPOLL)
1934 mutex_lock(&ctx->uring_lock);
1935 ret = __io_cqring_overflow_flush(ctx, false);
1936 if (ctx->flags & IORING_SETUP_IOPOLL)
1937 mutex_unlock(&ctx->uring_lock);
1943 /* must to be called somewhat shortly after putting a request */
1944 static inline void io_put_task(struct task_struct *task, int nr)
1946 struct io_uring_task *tctx = task->io_uring;
1948 if (likely(task == current)) {
1949 tctx->cached_refs += nr;
1951 percpu_counter_sub(&tctx->inflight, nr);
1952 if (unlikely(atomic_read(&tctx->in_idle)))
1953 wake_up(&tctx->wait);
1954 put_task_struct_many(task, nr);
1958 static void io_task_refs_refill(struct io_uring_task *tctx)
1960 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1962 percpu_counter_add(&tctx->inflight, refill);
1963 refcount_add(refill, ¤t->usage);
1964 tctx->cached_refs += refill;
1967 static inline void io_get_task_refs(int nr)
1969 struct io_uring_task *tctx = current->io_uring;
1971 tctx->cached_refs -= nr;
1972 if (unlikely(tctx->cached_refs < 0))
1973 io_task_refs_refill(tctx);
1976 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1978 struct io_uring_task *tctx = task->io_uring;
1979 unsigned int refs = tctx->cached_refs;
1982 tctx->cached_refs = 0;
1983 percpu_counter_sub(&tctx->inflight, refs);
1984 put_task_struct_many(task, refs);
1988 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1989 s32 res, u32 cflags)
1991 struct io_overflow_cqe *ocqe;
1993 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1996 * If we're in ring overflow flush mode, or in task cancel mode,
1997 * or cannot allocate an overflow entry, then we need to drop it
2000 io_account_cq_overflow(ctx);
2003 if (list_empty(&ctx->cq_overflow_list)) {
2004 set_bit(0, &ctx->check_cq_overflow);
2005 WRITE_ONCE(ctx->rings->sq_flags,
2006 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2009 ocqe->cqe.user_data = user_data;
2010 ocqe->cqe.res = res;
2011 ocqe->cqe.flags = cflags;
2012 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2016 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2017 s32 res, u32 cflags)
2019 struct io_uring_cqe *cqe;
2022 * If we can't get a cq entry, userspace overflowed the
2023 * submission (by quite a lot). Increment the overflow count in
2026 cqe = io_get_cqe(ctx);
2028 WRITE_ONCE(cqe->user_data, user_data);
2029 WRITE_ONCE(cqe->res, res);
2030 WRITE_ONCE(cqe->flags, cflags);
2033 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2036 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2038 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2039 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
2042 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2044 if (!(req->flags & REQ_F_CQE_SKIP))
2045 __io_fill_cqe_req(req, res, cflags);
2048 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2049 s32 res, u32 cflags)
2052 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2053 return __io_fill_cqe(ctx, user_data, res, cflags);
2056 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2059 struct io_ring_ctx *ctx = req->ctx;
2061 if (!(req->flags & REQ_F_CQE_SKIP))
2062 __io_fill_cqe_req(req, res, cflags);
2064 * If we're the last reference to this request, add to our locked
2067 if (req_ref_put_and_test(req)) {
2068 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2069 if (req->flags & IO_DISARM_MASK)
2070 io_disarm_next(req);
2072 io_req_task_queue(req->link);
2076 io_req_put_rsrc(req, ctx);
2078 * Selected buffer deallocation in io_clean_op() assumes that
2079 * we don't hold ->completion_lock. Clean them here to avoid
2082 io_put_kbuf_comp(req);
2083 io_dismantle_req(req);
2084 io_put_task(req->task, 1);
2085 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2086 ctx->locked_free_nr++;
2090 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2093 struct io_ring_ctx *ctx = req->ctx;
2095 spin_lock(&ctx->completion_lock);
2096 __io_req_complete_post(req, res, cflags);
2097 io_commit_cqring(ctx);
2098 spin_unlock(&ctx->completion_lock);
2099 io_cqring_ev_posted(ctx);
2102 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2106 req->cflags = cflags;
2107 req->flags |= REQ_F_COMPLETE_INLINE;
2110 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2111 s32 res, u32 cflags)
2113 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2114 io_req_complete_state(req, res, cflags);
2116 io_req_complete_post(req, res, cflags);
2119 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2121 __io_req_complete(req, 0, res, 0);
2124 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2127 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2130 static void io_req_complete_fail_submit(struct io_kiocb *req)
2133 * We don't submit, fail them all, for that replace hardlinks with
2134 * normal links. Extra REQ_F_LINK is tolerated.
2136 req->flags &= ~REQ_F_HARDLINK;
2137 req->flags |= REQ_F_LINK;
2138 io_req_complete_failed(req, req->result);
2142 * Don't initialise the fields below on every allocation, but do that in
2143 * advance and keep them valid across allocations.
2145 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2149 req->async_data = NULL;
2150 /* not necessary, but safer to zero */
2154 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2155 struct io_submit_state *state)
2157 spin_lock(&ctx->completion_lock);
2158 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2159 ctx->locked_free_nr = 0;
2160 spin_unlock(&ctx->completion_lock);
2163 /* Returns true IFF there are requests in the cache */
2164 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2166 struct io_submit_state *state = &ctx->submit_state;
2169 * If we have more than a batch's worth of requests in our IRQ side
2170 * locked cache, grab the lock and move them over to our submission
2173 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2174 io_flush_cached_locked_reqs(ctx, state);
2175 return !!state->free_list.next;
2179 * A request might get retired back into the request caches even before opcode
2180 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2181 * Because of that, io_alloc_req() should be called only under ->uring_lock
2182 * and with extra caution to not get a request that is still worked on.
2184 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2185 __must_hold(&ctx->uring_lock)
2187 struct io_submit_state *state = &ctx->submit_state;
2188 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2189 void *reqs[IO_REQ_ALLOC_BATCH];
2190 struct io_kiocb *req;
2193 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2196 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2199 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2200 * retry single alloc to be on the safe side.
2202 if (unlikely(ret <= 0)) {
2203 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2209 percpu_ref_get_many(&ctx->refs, ret);
2210 for (i = 0; i < ret; i++) {
2213 io_preinit_req(req, ctx);
2214 wq_stack_add_head(&req->comp_list, &state->free_list);
2219 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2221 if (unlikely(!ctx->submit_state.free_list.next))
2222 return __io_alloc_req_refill(ctx);
2226 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2228 struct io_wq_work_node *node;
2230 node = wq_stack_extract(&ctx->submit_state.free_list);
2231 return container_of(node, struct io_kiocb, comp_list);
2234 static inline void io_put_file(struct file *file)
2240 static inline void io_dismantle_req(struct io_kiocb *req)
2242 unsigned int flags = req->flags;
2244 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2246 if (!(flags & REQ_F_FIXED_FILE))
2247 io_put_file(req->file);
2250 static __cold void __io_free_req(struct io_kiocb *req)
2252 struct io_ring_ctx *ctx = req->ctx;
2254 io_req_put_rsrc(req, ctx);
2255 io_dismantle_req(req);
2256 io_put_task(req->task, 1);
2258 spin_lock(&ctx->completion_lock);
2259 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2260 ctx->locked_free_nr++;
2261 spin_unlock(&ctx->completion_lock);
2264 static inline void io_remove_next_linked(struct io_kiocb *req)
2266 struct io_kiocb *nxt = req->link;
2268 req->link = nxt->link;
2272 static bool io_kill_linked_timeout(struct io_kiocb *req)
2273 __must_hold(&req->ctx->completion_lock)
2274 __must_hold(&req->ctx->timeout_lock)
2276 struct io_kiocb *link = req->link;
2278 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2279 struct io_timeout_data *io = link->async_data;
2281 io_remove_next_linked(req);
2282 link->timeout.head = NULL;
2283 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2284 list_del(&link->timeout.list);
2285 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2286 io_fill_cqe_req(link, -ECANCELED, 0);
2287 io_put_req_deferred(link);
2294 static void io_fail_links(struct io_kiocb *req)
2295 __must_hold(&req->ctx->completion_lock)
2297 struct io_kiocb *nxt, *link = req->link;
2298 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2302 long res = -ECANCELED;
2304 if (link->flags & REQ_F_FAIL)
2310 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2314 link->flags &= ~REQ_F_CQE_SKIP;
2315 io_fill_cqe_req(link, res, 0);
2317 io_put_req_deferred(link);
2322 static bool io_disarm_next(struct io_kiocb *req)
2323 __must_hold(&req->ctx->completion_lock)
2325 bool posted = false;
2327 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2328 struct io_kiocb *link = req->link;
2330 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2331 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2332 io_remove_next_linked(req);
2333 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2334 io_fill_cqe_req(link, -ECANCELED, 0);
2335 io_put_req_deferred(link);
2338 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2339 struct io_ring_ctx *ctx = req->ctx;
2341 spin_lock_irq(&ctx->timeout_lock);
2342 posted = io_kill_linked_timeout(req);
2343 spin_unlock_irq(&ctx->timeout_lock);
2345 if (unlikely((req->flags & REQ_F_FAIL) &&
2346 !(req->flags & REQ_F_HARDLINK))) {
2347 posted |= (req->link != NULL);
2353 static void __io_req_find_next_prep(struct io_kiocb *req)
2355 struct io_ring_ctx *ctx = req->ctx;
2358 spin_lock(&ctx->completion_lock);
2359 posted = io_disarm_next(req);
2361 io_commit_cqring(ctx);
2362 spin_unlock(&ctx->completion_lock);
2364 io_cqring_ev_posted(ctx);
2367 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2369 struct io_kiocb *nxt;
2371 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2374 * If LINK is set, we have dependent requests in this chain. If we
2375 * didn't fail this request, queue the first one up, moving any other
2376 * dependencies to the next request. In case of failure, fail the rest
2379 if (unlikely(req->flags & IO_DISARM_MASK))
2380 __io_req_find_next_prep(req);
2386 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2391 io_submit_flush_completions(ctx);
2392 mutex_unlock(&ctx->uring_lock);
2395 percpu_ref_put(&ctx->refs);
2398 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2400 io_commit_cqring(ctx);
2401 spin_unlock(&ctx->completion_lock);
2402 io_cqring_ev_posted(ctx);
2405 static void handle_prev_tw_list(struct io_wq_work_node *node,
2406 struct io_ring_ctx **ctx, bool *uring_locked)
2408 if (*ctx && !*uring_locked)
2409 spin_lock(&(*ctx)->completion_lock);
2412 struct io_wq_work_node *next = node->next;
2413 struct io_kiocb *req = container_of(node, struct io_kiocb,
2416 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2418 if (req->ctx != *ctx) {
2419 if (unlikely(!*uring_locked && *ctx))
2420 ctx_commit_and_unlock(*ctx);
2422 ctx_flush_and_put(*ctx, uring_locked);
2424 /* if not contended, grab and improve batching */
2425 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2426 percpu_ref_get(&(*ctx)->refs);
2427 if (unlikely(!*uring_locked))
2428 spin_lock(&(*ctx)->completion_lock);
2430 if (likely(*uring_locked))
2431 req->io_task_work.func(req, uring_locked);
2433 __io_req_complete_post(req, req->result,
2434 io_put_kbuf_comp(req));
2438 if (unlikely(!*uring_locked))
2439 ctx_commit_and_unlock(*ctx);
2442 static void handle_tw_list(struct io_wq_work_node *node,
2443 struct io_ring_ctx **ctx, bool *locked)
2446 struct io_wq_work_node *next = node->next;
2447 struct io_kiocb *req = container_of(node, struct io_kiocb,
2450 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2452 if (req->ctx != *ctx) {
2453 ctx_flush_and_put(*ctx, locked);
2455 /* if not contended, grab and improve batching */
2456 *locked = mutex_trylock(&(*ctx)->uring_lock);
2457 percpu_ref_get(&(*ctx)->refs);
2459 req->io_task_work.func(req, locked);
2464 static void tctx_task_work(struct callback_head *cb)
2466 bool uring_locked = false;
2467 struct io_ring_ctx *ctx = NULL;
2468 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2472 struct io_wq_work_node *node1, *node2;
2474 if (!tctx->task_list.first &&
2475 !tctx->prior_task_list.first && uring_locked)
2476 io_submit_flush_completions(ctx);
2478 spin_lock_irq(&tctx->task_lock);
2479 node1 = tctx->prior_task_list.first;
2480 node2 = tctx->task_list.first;
2481 INIT_WQ_LIST(&tctx->task_list);
2482 INIT_WQ_LIST(&tctx->prior_task_list);
2483 if (!node2 && !node1)
2484 tctx->task_running = false;
2485 spin_unlock_irq(&tctx->task_lock);
2486 if (!node2 && !node1)
2490 handle_prev_tw_list(node1, &ctx, &uring_locked);
2493 handle_tw_list(node2, &ctx, &uring_locked);
2497 ctx_flush_and_put(ctx, &uring_locked);
2499 /* relaxed read is enough as only the task itself sets ->in_idle */
2500 if (unlikely(atomic_read(&tctx->in_idle)))
2501 io_uring_drop_tctx_refs(current);
2504 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2506 struct task_struct *tsk = req->task;
2507 struct io_uring_task *tctx = tsk->io_uring;
2508 enum task_work_notify_mode notify;
2509 struct io_wq_work_node *node;
2510 unsigned long flags;
2513 WARN_ON_ONCE(!tctx);
2515 io_drop_inflight_file(req);
2517 spin_lock_irqsave(&tctx->task_lock, flags);
2519 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2521 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2522 running = tctx->task_running;
2524 tctx->task_running = true;
2525 spin_unlock_irqrestore(&tctx->task_lock, flags);
2527 /* task_work already pending, we're done */
2532 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2533 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2534 * processing task_work. There's no reliable way to tell if TWA_RESUME
2537 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2538 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2539 if (notify == TWA_NONE)
2540 wake_up_process(tsk);
2544 spin_lock_irqsave(&tctx->task_lock, flags);
2545 tctx->task_running = false;
2546 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2547 spin_unlock_irqrestore(&tctx->task_lock, flags);
2550 req = container_of(node, struct io_kiocb, io_task_work.node);
2552 if (llist_add(&req->io_task_work.fallback_node,
2553 &req->ctx->fallback_llist))
2554 schedule_delayed_work(&req->ctx->fallback_work, 1);
2558 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2560 struct io_ring_ctx *ctx = req->ctx;
2562 /* not needed for normal modes, but SQPOLL depends on it */
2563 io_tw_lock(ctx, locked);
2564 io_req_complete_failed(req, req->result);
2567 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2569 struct io_ring_ctx *ctx = req->ctx;
2571 io_tw_lock(ctx, locked);
2572 /* req->task == current here, checking PF_EXITING is safe */
2573 if (likely(!(req->task->flags & PF_EXITING)))
2574 __io_queue_sqe(req);
2576 io_req_complete_failed(req, -EFAULT);
2579 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2582 req->io_task_work.func = io_req_task_cancel;
2583 io_req_task_work_add(req, false);
2586 static void io_req_task_queue(struct io_kiocb *req)
2588 req->io_task_work.func = io_req_task_submit;
2589 io_req_task_work_add(req, false);
2592 static void io_req_task_queue_reissue(struct io_kiocb *req)
2594 req->io_task_work.func = io_queue_async_work;
2595 io_req_task_work_add(req, false);
2598 static inline void io_queue_next(struct io_kiocb *req)
2600 struct io_kiocb *nxt = io_req_find_next(req);
2603 io_req_task_queue(nxt);
2606 static void io_free_req(struct io_kiocb *req)
2612 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2617 static void io_free_batch_list(struct io_ring_ctx *ctx,
2618 struct io_wq_work_node *node)
2619 __must_hold(&ctx->uring_lock)
2621 struct task_struct *task = NULL;
2625 struct io_kiocb *req = container_of(node, struct io_kiocb,
2628 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2629 node = req->comp_list.next;
2630 if (!req_ref_put_and_test(req))
2634 io_req_put_rsrc_locked(req, ctx);
2636 io_dismantle_req(req);
2638 if (req->task != task) {
2640 io_put_task(task, task_refs);
2645 node = req->comp_list.next;
2646 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2650 io_put_task(task, task_refs);
2653 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2654 __must_hold(&ctx->uring_lock)
2656 struct io_wq_work_node *node, *prev;
2657 struct io_submit_state *state = &ctx->submit_state;
2659 if (state->flush_cqes) {
2660 spin_lock(&ctx->completion_lock);
2661 wq_list_for_each(node, prev, &state->compl_reqs) {
2662 struct io_kiocb *req = container_of(node, struct io_kiocb,
2665 if (!(req->flags & REQ_F_CQE_SKIP))
2666 __io_fill_cqe_req(req, req->result, req->cflags);
2667 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2668 struct async_poll *apoll = req->apoll;
2670 if (apoll->double_poll)
2671 kfree(apoll->double_poll);
2672 list_add(&apoll->poll.wait.entry,
2674 req->flags &= ~REQ_F_POLLED;
2678 io_commit_cqring(ctx);
2679 spin_unlock(&ctx->completion_lock);
2680 io_cqring_ev_posted(ctx);
2681 state->flush_cqes = false;
2684 io_free_batch_list(ctx, state->compl_reqs.first);
2685 INIT_WQ_LIST(&state->compl_reqs);
2689 * Drop reference to request, return next in chain (if there is one) if this
2690 * was the last reference to this request.
2692 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2694 struct io_kiocb *nxt = NULL;
2696 if (req_ref_put_and_test(req)) {
2697 nxt = io_req_find_next(req);
2703 static inline void io_put_req(struct io_kiocb *req)
2705 if (req_ref_put_and_test(req))
2709 static inline void io_put_req_deferred(struct io_kiocb *req)
2711 if (req_ref_put_and_test(req)) {
2712 req->io_task_work.func = io_free_req_work;
2713 io_req_task_work_add(req, false);
2717 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2719 /* See comment at the top of this file */
2721 return __io_cqring_events(ctx);
2724 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2726 struct io_rings *rings = ctx->rings;
2728 /* make sure SQ entry isn't read before tail */
2729 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2732 static inline bool io_run_task_work(void)
2734 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2735 __set_current_state(TASK_RUNNING);
2736 clear_notify_signal();
2737 if (task_work_pending(current))
2745 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2747 struct io_wq_work_node *pos, *start, *prev;
2748 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2749 DEFINE_IO_COMP_BATCH(iob);
2753 * Only spin for completions if we don't have multiple devices hanging
2754 * off our complete list.
2756 if (ctx->poll_multi_queue || force_nonspin)
2757 poll_flags |= BLK_POLL_ONESHOT;
2759 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2760 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2761 struct kiocb *kiocb = &req->rw.kiocb;
2765 * Move completed and retryable entries to our local lists.
2766 * If we find a request that requires polling, break out
2767 * and complete those lists first, if we have entries there.
2769 if (READ_ONCE(req->iopoll_completed))
2772 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2773 if (unlikely(ret < 0))
2776 poll_flags |= BLK_POLL_ONESHOT;
2778 /* iopoll may have completed current req */
2779 if (!rq_list_empty(iob.req_list) ||
2780 READ_ONCE(req->iopoll_completed))
2784 if (!rq_list_empty(iob.req_list))
2790 wq_list_for_each_resume(pos, prev) {
2791 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2793 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2794 if (!smp_load_acquire(&req->iopoll_completed))
2796 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2799 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
2803 if (unlikely(!nr_events))
2806 io_commit_cqring(ctx);
2807 io_cqring_ev_posted_iopoll(ctx);
2808 pos = start ? start->next : ctx->iopoll_list.first;
2809 wq_list_cut(&ctx->iopoll_list, prev, start);
2810 io_free_batch_list(ctx, pos);
2815 * We can't just wait for polled events to come to us, we have to actively
2816 * find and complete them.
2818 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2820 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2823 mutex_lock(&ctx->uring_lock);
2824 while (!wq_list_empty(&ctx->iopoll_list)) {
2825 /* let it sleep and repeat later if can't complete a request */
2826 if (io_do_iopoll(ctx, true) == 0)
2829 * Ensure we allow local-to-the-cpu processing to take place,
2830 * in this case we need to ensure that we reap all events.
2831 * Also let task_work, etc. to progress by releasing the mutex
2833 if (need_resched()) {
2834 mutex_unlock(&ctx->uring_lock);
2836 mutex_lock(&ctx->uring_lock);
2839 mutex_unlock(&ctx->uring_lock);
2842 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2844 unsigned int nr_events = 0;
2848 * We disallow the app entering submit/complete with polling, but we
2849 * still need to lock the ring to prevent racing with polled issue
2850 * that got punted to a workqueue.
2852 mutex_lock(&ctx->uring_lock);
2854 * Don't enter poll loop if we already have events pending.
2855 * If we do, we can potentially be spinning for commands that
2856 * already triggered a CQE (eg in error).
2858 if (test_bit(0, &ctx->check_cq_overflow))
2859 __io_cqring_overflow_flush(ctx, false);
2860 if (io_cqring_events(ctx))
2864 * If a submit got punted to a workqueue, we can have the
2865 * application entering polling for a command before it gets
2866 * issued. That app will hold the uring_lock for the duration
2867 * of the poll right here, so we need to take a breather every
2868 * now and then to ensure that the issue has a chance to add
2869 * the poll to the issued list. Otherwise we can spin here
2870 * forever, while the workqueue is stuck trying to acquire the
2873 if (wq_list_empty(&ctx->iopoll_list)) {
2874 u32 tail = ctx->cached_cq_tail;
2876 mutex_unlock(&ctx->uring_lock);
2878 mutex_lock(&ctx->uring_lock);
2880 /* some requests don't go through iopoll_list */
2881 if (tail != ctx->cached_cq_tail ||
2882 wq_list_empty(&ctx->iopoll_list))
2885 ret = io_do_iopoll(ctx, !min);
2890 } while (nr_events < min && !need_resched());
2892 mutex_unlock(&ctx->uring_lock);
2896 static void kiocb_end_write(struct io_kiocb *req)
2899 * Tell lockdep we inherited freeze protection from submission
2902 if (req->flags & REQ_F_ISREG) {
2903 struct super_block *sb = file_inode(req->file)->i_sb;
2905 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2911 static bool io_resubmit_prep(struct io_kiocb *req)
2913 struct io_async_rw *rw = req->async_data;
2915 if (!req_has_async_data(req))
2916 return !io_req_prep_async(req);
2917 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2921 static bool io_rw_should_reissue(struct io_kiocb *req)
2923 umode_t mode = file_inode(req->file)->i_mode;
2924 struct io_ring_ctx *ctx = req->ctx;
2926 if (!S_ISBLK(mode) && !S_ISREG(mode))
2928 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2929 !(ctx->flags & IORING_SETUP_IOPOLL)))
2932 * If ref is dying, we might be running poll reap from the exit work.
2933 * Don't attempt to reissue from that path, just let it fail with
2936 if (percpu_ref_is_dying(&ctx->refs))
2939 * Play it safe and assume not safe to re-import and reissue if we're
2940 * not in the original thread group (or in task context).
2942 if (!same_thread_group(req->task, current) || !in_task())
2947 static bool io_resubmit_prep(struct io_kiocb *req)
2951 static bool io_rw_should_reissue(struct io_kiocb *req)
2957 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2959 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
2960 kiocb_end_write(req);
2961 fsnotify_modify(req->file);
2963 fsnotify_access(req->file);
2965 if (unlikely(res != req->result)) {
2966 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2967 io_rw_should_reissue(req)) {
2968 req->flags |= REQ_F_REISSUE;
2977 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2979 int res = req->result;
2982 io_req_complete_state(req, res, io_put_kbuf(req, 0));
2983 io_req_add_compl_list(req);
2985 io_req_complete_post(req, res,
2986 io_put_kbuf(req, IO_URING_F_UNLOCKED));
2990 static void __io_complete_rw(struct io_kiocb *req, long res,
2991 unsigned int issue_flags)
2993 if (__io_complete_rw_common(req, res))
2995 __io_req_complete(req, issue_flags, req->result,
2996 io_put_kbuf(req, issue_flags));
2999 static void io_complete_rw(struct kiocb *kiocb, long res)
3001 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3003 if (__io_complete_rw_common(req, res))
3006 req->io_task_work.func = io_req_task_complete;
3007 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3010 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3012 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3014 if (kiocb->ki_flags & IOCB_WRITE)
3015 kiocb_end_write(req);
3016 if (unlikely(res != req->result)) {
3017 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3018 req->flags |= REQ_F_REISSUE;
3024 /* order with io_iopoll_complete() checking ->iopoll_completed */
3025 smp_store_release(&req->iopoll_completed, 1);
3029 * After the iocb has been issued, it's safe to be found on the poll list.
3030 * Adding the kiocb to the list AFTER submission ensures that we don't
3031 * find it from a io_do_iopoll() thread before the issuer is done
3032 * accessing the kiocb cookie.
3034 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3036 struct io_ring_ctx *ctx = req->ctx;
3037 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3039 /* workqueue context doesn't hold uring_lock, grab it now */
3040 if (unlikely(needs_lock))
3041 mutex_lock(&ctx->uring_lock);
3044 * Track whether we have multiple files in our lists. This will impact
3045 * how we do polling eventually, not spinning if we're on potentially
3046 * different devices.
3048 if (wq_list_empty(&ctx->iopoll_list)) {
3049 ctx->poll_multi_queue = false;
3050 } else if (!ctx->poll_multi_queue) {
3051 struct io_kiocb *list_req;
3053 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3055 if (list_req->file != req->file)
3056 ctx->poll_multi_queue = true;
3060 * For fast devices, IO may have already completed. If it has, add
3061 * it to the front so we find it first.
3063 if (READ_ONCE(req->iopoll_completed))
3064 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3066 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3068 if (unlikely(needs_lock)) {
3070 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3071 * in sq thread task context or in io worker task context. If
3072 * current task context is sq thread, we don't need to check
3073 * whether should wake up sq thread.
3075 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3076 wq_has_sleeper(&ctx->sq_data->wait))
3077 wake_up(&ctx->sq_data->wait);
3079 mutex_unlock(&ctx->uring_lock);
3083 static bool io_bdev_nowait(struct block_device *bdev)
3085 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3089 * If we tracked the file through the SCM inflight mechanism, we could support
3090 * any file. For now, just ensure that anything potentially problematic is done
3093 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3095 if (S_ISBLK(mode)) {
3096 if (IS_ENABLED(CONFIG_BLOCK) &&
3097 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3103 if (S_ISREG(mode)) {
3104 if (IS_ENABLED(CONFIG_BLOCK) &&
3105 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3106 file->f_op != &io_uring_fops)
3111 /* any ->read/write should understand O_NONBLOCK */
3112 if (file->f_flags & O_NONBLOCK)
3114 return file->f_mode & FMODE_NOWAIT;
3118 * If we tracked the file through the SCM inflight mechanism, we could support
3119 * any file. For now, just ensure that anything potentially problematic is done
3122 static unsigned int io_file_get_flags(struct file *file)
3124 umode_t mode = file_inode(file)->i_mode;
3125 unsigned int res = 0;
3129 if (__io_file_supports_nowait(file, mode))
3134 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3136 return req->flags & REQ_F_SUPPORT_NOWAIT;
3139 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3141 struct kiocb *kiocb = &req->rw.kiocb;
3145 kiocb->ki_pos = READ_ONCE(sqe->off);
3147 ioprio = READ_ONCE(sqe->ioprio);
3149 ret = ioprio_check_cap(ioprio);
3153 kiocb->ki_ioprio = ioprio;
3155 kiocb->ki_ioprio = get_current_ioprio();
3159 req->rw.addr = READ_ONCE(sqe->addr);
3160 req->rw.len = READ_ONCE(sqe->len);
3161 req->rw.flags = READ_ONCE(sqe->rw_flags);
3162 req->buf_index = READ_ONCE(sqe->buf_index);
3166 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3172 case -ERESTARTNOINTR:
3173 case -ERESTARTNOHAND:
3174 case -ERESTART_RESTARTBLOCK:
3176 * We can't just restart the syscall, since previously
3177 * submitted sqes may already be in progress. Just fail this
3183 kiocb->ki_complete(kiocb, ret);
3187 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3189 struct kiocb *kiocb = &req->rw.kiocb;
3191 if (kiocb->ki_pos != -1)
3192 return &kiocb->ki_pos;
3194 if (!(req->file->f_mode & FMODE_STREAM)) {
3195 req->flags |= REQ_F_CUR_POS;
3196 kiocb->ki_pos = req->file->f_pos;
3197 return &kiocb->ki_pos;
3204 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3205 unsigned int issue_flags)
3207 struct io_async_rw *io = req->async_data;
3209 /* add previously done IO, if any */
3210 if (req_has_async_data(req) && io->bytes_done > 0) {
3212 ret = io->bytes_done;
3214 ret += io->bytes_done;
3217 if (req->flags & REQ_F_CUR_POS)
3218 req->file->f_pos = req->rw.kiocb.ki_pos;
3219 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3220 __io_complete_rw(req, ret, issue_flags);
3222 io_rw_done(&req->rw.kiocb, ret);
3224 if (req->flags & REQ_F_REISSUE) {
3225 req->flags &= ~REQ_F_REISSUE;
3226 if (io_resubmit_prep(req))
3227 io_req_task_queue_reissue(req);
3229 io_req_task_queue_fail(req, ret);
3233 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3234 struct io_mapped_ubuf *imu)
3236 size_t len = req->rw.len;
3237 u64 buf_end, buf_addr = req->rw.addr;
3240 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3242 /* not inside the mapped region */
3243 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3247 * May not be a start of buffer, set size appropriately
3248 * and advance us to the beginning.
3250 offset = buf_addr - imu->ubuf;
3251 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3255 * Don't use iov_iter_advance() here, as it's really slow for
3256 * using the latter parts of a big fixed buffer - it iterates
3257 * over each segment manually. We can cheat a bit here, because
3260 * 1) it's a BVEC iter, we set it up
3261 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3262 * first and last bvec
3264 * So just find our index, and adjust the iterator afterwards.
3265 * If the offset is within the first bvec (or the whole first
3266 * bvec, just use iov_iter_advance(). This makes it easier
3267 * since we can just skip the first segment, which may not
3268 * be PAGE_SIZE aligned.
3270 const struct bio_vec *bvec = imu->bvec;
3272 if (offset <= bvec->bv_len) {
3273 iov_iter_advance(iter, offset);
3275 unsigned long seg_skip;
3277 /* skip first vec */
3278 offset -= bvec->bv_len;
3279 seg_skip = 1 + (offset >> PAGE_SHIFT);
3281 iter->bvec = bvec + seg_skip;
3282 iter->nr_segs -= seg_skip;
3283 iter->count -= bvec->bv_len + offset;
3284 iter->iov_offset = offset & ~PAGE_MASK;
3291 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3292 unsigned int issue_flags)
3294 struct io_mapped_ubuf *imu = req->imu;
3295 u16 index, buf_index = req->buf_index;
3298 struct io_ring_ctx *ctx = req->ctx;
3300 if (unlikely(buf_index >= ctx->nr_user_bufs))
3302 io_req_set_rsrc_node(req, ctx, issue_flags);
3303 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3304 imu = READ_ONCE(ctx->user_bufs[index]);
3307 return __io_import_fixed(req, rw, iter, imu);
3310 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3313 mutex_unlock(&ctx->uring_lock);
3316 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3319 * "Normal" inline submissions always hold the uring_lock, since we
3320 * grab it from the system call. Same is true for the SQPOLL offload.
3321 * The only exception is when we've detached the request and issue it
3322 * from an async worker thread, grab the lock for that case.
3325 mutex_lock(&ctx->uring_lock);
3328 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3329 struct io_buffer_list *bl, unsigned int bgid)
3331 struct list_head *list;
3333 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3334 INIT_LIST_HEAD(&bl->buf_list);
3336 list_add(&bl->list, list);
3339 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3340 int bgid, unsigned int issue_flags)
3342 struct io_buffer *kbuf = req->kbuf;
3343 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3344 struct io_ring_ctx *ctx = req->ctx;
3345 struct io_buffer_list *bl;
3347 if (req->flags & REQ_F_BUFFER_SELECTED)
3350 io_ring_submit_lock(ctx, needs_lock);
3352 lockdep_assert_held(&ctx->uring_lock);
3354 bl = io_buffer_get_list(ctx, bgid);
3355 if (bl && !list_empty(&bl->buf_list)) {
3356 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3357 list_del(&kbuf->list);
3358 if (*len > kbuf->len)
3360 req->flags |= REQ_F_BUFFER_SELECTED;
3363 kbuf = ERR_PTR(-ENOBUFS);
3366 io_ring_submit_unlock(req->ctx, needs_lock);
3370 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3371 unsigned int issue_flags)
3373 struct io_buffer *kbuf;
3376 bgid = req->buf_index;
3377 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3380 return u64_to_user_ptr(kbuf->addr);
3383 #ifdef CONFIG_COMPAT
3384 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3385 unsigned int issue_flags)
3387 struct compat_iovec __user *uiov;
3388 compat_ssize_t clen;
3392 uiov = u64_to_user_ptr(req->rw.addr);
3393 if (!access_ok(uiov, sizeof(*uiov)))
3395 if (__get_user(clen, &uiov->iov_len))
3401 buf = io_rw_buffer_select(req, &len, issue_flags);
3403 return PTR_ERR(buf);
3404 iov[0].iov_base = buf;
3405 iov[0].iov_len = (compat_size_t) len;
3410 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3411 unsigned int issue_flags)
3413 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3417 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3420 len = iov[0].iov_len;
3423 buf = io_rw_buffer_select(req, &len, issue_flags);
3425 return PTR_ERR(buf);
3426 iov[0].iov_base = buf;
3427 iov[0].iov_len = len;
3431 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3432 unsigned int issue_flags)
3434 if (req->flags & REQ_F_BUFFER_SELECTED) {
3435 struct io_buffer *kbuf = req->kbuf;
3437 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3438 iov[0].iov_len = kbuf->len;
3441 if (req->rw.len != 1)
3444 #ifdef CONFIG_COMPAT
3445 if (req->ctx->compat)
3446 return io_compat_import(req, iov, issue_flags);
3449 return __io_iov_buffer_select(req, iov, issue_flags);
3452 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3453 struct io_rw_state *s,
3454 unsigned int issue_flags)
3456 struct iov_iter *iter = &s->iter;
3457 u8 opcode = req->opcode;
3458 struct iovec *iovec;
3463 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3464 ret = io_import_fixed(req, rw, iter, issue_flags);
3466 return ERR_PTR(ret);
3470 /* buffer index only valid with fixed read/write, or buffer select */
3471 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3472 return ERR_PTR(-EINVAL);
3474 buf = u64_to_user_ptr(req->rw.addr);
3475 sqe_len = req->rw.len;
3477 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3478 if (req->flags & REQ_F_BUFFER_SELECT) {
3479 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3481 return ERR_CAST(buf);
3482 req->rw.len = sqe_len;
3485 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3487 return ERR_PTR(ret);
3491 iovec = s->fast_iov;
3492 if (req->flags & REQ_F_BUFFER_SELECT) {
3493 ret = io_iov_buffer_select(req, iovec, issue_flags);
3495 return ERR_PTR(ret);
3496 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3500 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3502 if (unlikely(ret < 0))
3503 return ERR_PTR(ret);
3507 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3508 struct iovec **iovec, struct io_rw_state *s,
3509 unsigned int issue_flags)
3511 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3512 if (unlikely(IS_ERR(*iovec)))
3513 return PTR_ERR(*iovec);
3515 iov_iter_save_state(&s->iter, &s->iter_state);
3519 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3521 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3525 * For files that don't have ->read_iter() and ->write_iter(), handle them
3526 * by looping over ->read() or ->write() manually.
3528 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3530 struct kiocb *kiocb = &req->rw.kiocb;
3531 struct file *file = req->file;
3536 * Don't support polled IO through this interface, and we can't
3537 * support non-blocking either. For the latter, this just causes
3538 * the kiocb to be handled from an async context.
3540 if (kiocb->ki_flags & IOCB_HIPRI)
3542 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3543 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3546 ppos = io_kiocb_ppos(kiocb);
3548 while (iov_iter_count(iter)) {
3552 if (!iov_iter_is_bvec(iter)) {
3553 iovec = iov_iter_iovec(iter);
3555 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3556 iovec.iov_len = req->rw.len;
3560 nr = file->f_op->read(file, iovec.iov_base,
3561 iovec.iov_len, ppos);
3563 nr = file->f_op->write(file, iovec.iov_base,
3564 iovec.iov_len, ppos);
3573 if (!iov_iter_is_bvec(iter)) {
3574 iov_iter_advance(iter, nr);
3581 if (nr != iovec.iov_len)
3588 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3589 const struct iovec *fast_iov, struct iov_iter *iter)
3591 struct io_async_rw *rw = req->async_data;
3593 memcpy(&rw->s.iter, iter, sizeof(*iter));
3594 rw->free_iovec = iovec;
3596 /* can only be fixed buffers, no need to do anything */
3597 if (iov_iter_is_bvec(iter))
3600 unsigned iov_off = 0;
3602 rw->s.iter.iov = rw->s.fast_iov;
3603 if (iter->iov != fast_iov) {
3604 iov_off = iter->iov - fast_iov;
3605 rw->s.iter.iov += iov_off;
3607 if (rw->s.fast_iov != fast_iov)
3608 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3609 sizeof(struct iovec) * iter->nr_segs);
3611 req->flags |= REQ_F_NEED_CLEANUP;
3615 static inline bool io_alloc_async_data(struct io_kiocb *req)
3617 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3618 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3619 if (req->async_data) {
3620 req->flags |= REQ_F_ASYNC_DATA;
3626 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3627 struct io_rw_state *s, bool force)
3629 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3631 if (!req_has_async_data(req)) {
3632 struct io_async_rw *iorw;
3634 if (io_alloc_async_data(req)) {
3639 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3640 iorw = req->async_data;
3641 /* we've copied and mapped the iter, ensure state is saved */
3642 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3647 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3649 struct io_async_rw *iorw = req->async_data;
3653 /* submission path, ->uring_lock should already be taken */
3654 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3655 if (unlikely(ret < 0))
3658 iorw->bytes_done = 0;
3659 iorw->free_iovec = iov;
3661 req->flags |= REQ_F_NEED_CLEANUP;
3666 * This is our waitqueue callback handler, registered through __folio_lock_async()
3667 * when we initially tried to do the IO with the iocb armed our waitqueue.
3668 * This gets called when the page is unlocked, and we generally expect that to
3669 * happen when the page IO is completed and the page is now uptodate. This will
3670 * queue a task_work based retry of the operation, attempting to copy the data
3671 * again. If the latter fails because the page was NOT uptodate, then we will
3672 * do a thread based blocking retry of the operation. That's the unexpected
3675 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3676 int sync, void *arg)
3678 struct wait_page_queue *wpq;
3679 struct io_kiocb *req = wait->private;
3680 struct wait_page_key *key = arg;
3682 wpq = container_of(wait, struct wait_page_queue, wait);
3684 if (!wake_page_match(wpq, key))
3687 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3688 list_del_init(&wait->entry);
3689 io_req_task_queue(req);
3694 * This controls whether a given IO request should be armed for async page
3695 * based retry. If we return false here, the request is handed to the async
3696 * worker threads for retry. If we're doing buffered reads on a regular file,
3697 * we prepare a private wait_page_queue entry and retry the operation. This
3698 * will either succeed because the page is now uptodate and unlocked, or it
3699 * will register a callback when the page is unlocked at IO completion. Through
3700 * that callback, io_uring uses task_work to setup a retry of the operation.
3701 * That retry will attempt the buffered read again. The retry will generally
3702 * succeed, or in rare cases where it fails, we then fall back to using the
3703 * async worker threads for a blocking retry.
3705 static bool io_rw_should_retry(struct io_kiocb *req)
3707 struct io_async_rw *rw = req->async_data;
3708 struct wait_page_queue *wait = &rw->wpq;
3709 struct kiocb *kiocb = &req->rw.kiocb;
3711 /* never retry for NOWAIT, we just complete with -EAGAIN */
3712 if (req->flags & REQ_F_NOWAIT)
3715 /* Only for buffered IO */
3716 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3720 * just use poll if we can, and don't attempt if the fs doesn't
3721 * support callback based unlocks
3723 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3726 wait->wait.func = io_async_buf_func;
3727 wait->wait.private = req;
3728 wait->wait.flags = 0;
3729 INIT_LIST_HEAD(&wait->wait.entry);
3730 kiocb->ki_flags |= IOCB_WAITQ;
3731 kiocb->ki_flags &= ~IOCB_NOWAIT;
3732 kiocb->ki_waitq = wait;
3736 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3738 if (likely(req->file->f_op->read_iter))
3739 return call_read_iter(req->file, &req->rw.kiocb, iter);
3740 else if (req->file->f_op->read)
3741 return loop_rw_iter(READ, req, iter);
3746 static bool need_read_all(struct io_kiocb *req)
3748 return req->flags & REQ_F_ISREG ||
3749 S_ISBLK(file_inode(req->file)->i_mode);
3752 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3754 struct kiocb *kiocb = &req->rw.kiocb;
3755 struct io_ring_ctx *ctx = req->ctx;
3756 struct file *file = req->file;
3759 if (unlikely(!file || !(file->f_mode & mode)))
3762 if (!io_req_ffs_set(req))
3763 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3765 kiocb->ki_flags = iocb_flags(file);
3766 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
3771 * If the file is marked O_NONBLOCK, still allow retry for it if it
3772 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3773 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3775 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3776 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3777 req->flags |= REQ_F_NOWAIT;
3779 if (ctx->flags & IORING_SETUP_IOPOLL) {
3780 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3783 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3784 kiocb->ki_complete = io_complete_rw_iopoll;
3785 req->iopoll_completed = 0;
3787 if (kiocb->ki_flags & IOCB_HIPRI)
3789 kiocb->ki_complete = io_complete_rw;
3795 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3797 struct io_rw_state __s, *s = &__s;
3798 struct iovec *iovec;
3799 struct kiocb *kiocb = &req->rw.kiocb;
3800 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3801 struct io_async_rw *rw;
3805 if (!req_has_async_data(req)) {
3806 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3807 if (unlikely(ret < 0))
3811 * Safe and required to re-import if we're using provided
3812 * buffers, as we dropped the selected one before retry.
3814 if (req->flags & REQ_F_BUFFER_SELECT) {
3815 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3816 if (unlikely(ret < 0))
3820 rw = req->async_data;
3823 * We come here from an earlier attempt, restore our state to
3824 * match in case it doesn't. It's cheap enough that we don't
3825 * need to make this conditional.
3827 iov_iter_restore(&s->iter, &s->iter_state);
3830 ret = io_rw_init_file(req, FMODE_READ);
3833 req->result = iov_iter_count(&s->iter);
3835 if (force_nonblock) {
3836 /* If the file doesn't support async, just async punt */
3837 if (unlikely(!io_file_supports_nowait(req))) {
3838 ret = io_setup_async_rw(req, iovec, s, true);
3839 return ret ?: -EAGAIN;
3841 kiocb->ki_flags |= IOCB_NOWAIT;
3843 /* Ensure we clear previously set non-block flag */
3844 kiocb->ki_flags &= ~IOCB_NOWAIT;
3847 ppos = io_kiocb_update_pos(req);
3849 ret = rw_verify_area(READ, req->file, ppos, req->result);
3850 if (unlikely(ret)) {
3855 ret = io_iter_do_read(req, &s->iter);
3857 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3858 req->flags &= ~REQ_F_REISSUE;
3859 /* if we can poll, just do that */
3860 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3862 /* IOPOLL retry should happen for io-wq threads */
3863 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3865 /* no retry on NONBLOCK nor RWF_NOWAIT */
3866 if (req->flags & REQ_F_NOWAIT)
3869 } else if (ret == -EIOCBQUEUED) {
3871 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3872 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3873 /* read all, failed, already did sync or don't want to retry */
3878 * Don't depend on the iter state matching what was consumed, or being
3879 * untouched in case of error. Restore it and we'll advance it
3880 * manually if we need to.
3882 iov_iter_restore(&s->iter, &s->iter_state);
3884 ret2 = io_setup_async_rw(req, iovec, s, true);
3889 rw = req->async_data;
3892 * Now use our persistent iterator and state, if we aren't already.
3893 * We've restored and mapped the iter to match.
3898 * We end up here because of a partial read, either from
3899 * above or inside this loop. Advance the iter by the bytes
3900 * that were consumed.
3902 iov_iter_advance(&s->iter, ret);
3903 if (!iov_iter_count(&s->iter))
3905 rw->bytes_done += ret;
3906 iov_iter_save_state(&s->iter, &s->iter_state);
3908 /* if we can retry, do so with the callbacks armed */
3909 if (!io_rw_should_retry(req)) {
3910 kiocb->ki_flags &= ~IOCB_WAITQ;
3915 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3916 * we get -EIOCBQUEUED, then we'll get a notification when the
3917 * desired page gets unlocked. We can also get a partial read
3918 * here, and if we do, then just retry at the new offset.
3920 ret = io_iter_do_read(req, &s->iter);
3921 if (ret == -EIOCBQUEUED)
3923 /* we got some bytes, but not all. retry. */
3924 kiocb->ki_flags &= ~IOCB_WAITQ;
3925 iov_iter_restore(&s->iter, &s->iter_state);
3928 kiocb_done(req, ret, issue_flags);
3930 /* it's faster to check here then delegate to kfree */
3936 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3938 struct io_rw_state __s, *s = &__s;
3939 struct iovec *iovec;
3940 struct kiocb *kiocb = &req->rw.kiocb;
3941 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3945 if (!req_has_async_data(req)) {
3946 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3947 if (unlikely(ret < 0))
3950 struct io_async_rw *rw = req->async_data;
3953 iov_iter_restore(&s->iter, &s->iter_state);
3956 ret = io_rw_init_file(req, FMODE_WRITE);
3959 req->result = iov_iter_count(&s->iter);
3961 if (force_nonblock) {
3962 /* If the file doesn't support async, just async punt */
3963 if (unlikely(!io_file_supports_nowait(req)))
3966 /* file path doesn't support NOWAIT for non-direct_IO */
3967 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3968 (req->flags & REQ_F_ISREG))
3971 kiocb->ki_flags |= IOCB_NOWAIT;
3973 /* Ensure we clear previously set non-block flag */
3974 kiocb->ki_flags &= ~IOCB_NOWAIT;
3977 ppos = io_kiocb_update_pos(req);
3979 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3984 * Open-code file_start_write here to grab freeze protection,
3985 * which will be released by another thread in
3986 * io_complete_rw(). Fool lockdep by telling it the lock got
3987 * released so that it doesn't complain about the held lock when
3988 * we return to userspace.
3990 if (req->flags & REQ_F_ISREG) {
3991 sb_start_write(file_inode(req->file)->i_sb);
3992 __sb_writers_release(file_inode(req->file)->i_sb,
3995 kiocb->ki_flags |= IOCB_WRITE;
3997 if (likely(req->file->f_op->write_iter))
3998 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3999 else if (req->file->f_op->write)
4000 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4004 if (req->flags & REQ_F_REISSUE) {
4005 req->flags &= ~REQ_F_REISSUE;
4010 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4011 * retry them without IOCB_NOWAIT.
4013 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4015 /* no retry on NONBLOCK nor RWF_NOWAIT */
4016 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4018 if (!force_nonblock || ret2 != -EAGAIN) {
4019 /* IOPOLL retry should happen for io-wq threads */
4020 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4023 kiocb_done(req, ret2, issue_flags);
4026 iov_iter_restore(&s->iter, &s->iter_state);
4027 ret = io_setup_async_rw(req, iovec, s, false);
4028 return ret ?: -EAGAIN;
4031 /* it's reportedly faster than delegating the null check to kfree() */
4037 static int io_renameat_prep(struct io_kiocb *req,
4038 const struct io_uring_sqe *sqe)
4040 struct io_rename *ren = &req->rename;
4041 const char __user *oldf, *newf;
4043 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4045 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4047 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4050 ren->old_dfd = READ_ONCE(sqe->fd);
4051 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4052 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4053 ren->new_dfd = READ_ONCE(sqe->len);
4054 ren->flags = READ_ONCE(sqe->rename_flags);
4056 ren->oldpath = getname(oldf);
4057 if (IS_ERR(ren->oldpath))
4058 return PTR_ERR(ren->oldpath);
4060 ren->newpath = getname(newf);
4061 if (IS_ERR(ren->newpath)) {
4062 putname(ren->oldpath);
4063 return PTR_ERR(ren->newpath);
4066 req->flags |= REQ_F_NEED_CLEANUP;
4070 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4072 struct io_rename *ren = &req->rename;
4075 if (issue_flags & IO_URING_F_NONBLOCK)
4078 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4079 ren->newpath, ren->flags);
4081 req->flags &= ~REQ_F_NEED_CLEANUP;
4084 io_req_complete(req, ret);
4088 static int io_unlinkat_prep(struct io_kiocb *req,
4089 const struct io_uring_sqe *sqe)
4091 struct io_unlink *un = &req->unlink;
4092 const char __user *fname;
4094 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4096 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4099 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4102 un->dfd = READ_ONCE(sqe->fd);
4104 un->flags = READ_ONCE(sqe->unlink_flags);
4105 if (un->flags & ~AT_REMOVEDIR)
4108 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4109 un->filename = getname(fname);
4110 if (IS_ERR(un->filename))
4111 return PTR_ERR(un->filename);
4113 req->flags |= REQ_F_NEED_CLEANUP;
4117 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4119 struct io_unlink *un = &req->unlink;
4122 if (issue_flags & IO_URING_F_NONBLOCK)
4125 if (un->flags & AT_REMOVEDIR)
4126 ret = do_rmdir(un->dfd, un->filename);
4128 ret = do_unlinkat(un->dfd, un->filename);
4130 req->flags &= ~REQ_F_NEED_CLEANUP;
4133 io_req_complete(req, ret);
4137 static int io_mkdirat_prep(struct io_kiocb *req,
4138 const struct io_uring_sqe *sqe)
4140 struct io_mkdir *mkd = &req->mkdir;
4141 const char __user *fname;
4143 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4145 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4148 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4151 mkd->dfd = READ_ONCE(sqe->fd);
4152 mkd->mode = READ_ONCE(sqe->len);
4154 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4155 mkd->filename = getname(fname);
4156 if (IS_ERR(mkd->filename))
4157 return PTR_ERR(mkd->filename);
4159 req->flags |= REQ_F_NEED_CLEANUP;
4163 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4165 struct io_mkdir *mkd = &req->mkdir;
4168 if (issue_flags & IO_URING_F_NONBLOCK)
4171 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4173 req->flags &= ~REQ_F_NEED_CLEANUP;
4176 io_req_complete(req, ret);
4180 static int io_symlinkat_prep(struct io_kiocb *req,
4181 const struct io_uring_sqe *sqe)
4183 struct io_symlink *sl = &req->symlink;
4184 const char __user *oldpath, *newpath;
4186 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4188 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4191 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4194 sl->new_dfd = READ_ONCE(sqe->fd);
4195 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4196 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4198 sl->oldpath = getname(oldpath);
4199 if (IS_ERR(sl->oldpath))
4200 return PTR_ERR(sl->oldpath);
4202 sl->newpath = getname(newpath);
4203 if (IS_ERR(sl->newpath)) {
4204 putname(sl->oldpath);
4205 return PTR_ERR(sl->newpath);
4208 req->flags |= REQ_F_NEED_CLEANUP;
4212 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4214 struct io_symlink *sl = &req->symlink;
4217 if (issue_flags & IO_URING_F_NONBLOCK)
4220 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4222 req->flags &= ~REQ_F_NEED_CLEANUP;
4225 io_req_complete(req, ret);
4229 static int io_linkat_prep(struct io_kiocb *req,
4230 const struct io_uring_sqe *sqe)
4232 struct io_hardlink *lnk = &req->hardlink;
4233 const char __user *oldf, *newf;
4235 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4237 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4239 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4242 lnk->old_dfd = READ_ONCE(sqe->fd);
4243 lnk->new_dfd = READ_ONCE(sqe->len);
4244 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4245 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4246 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4248 lnk->oldpath = getname(oldf);
4249 if (IS_ERR(lnk->oldpath))
4250 return PTR_ERR(lnk->oldpath);
4252 lnk->newpath = getname(newf);
4253 if (IS_ERR(lnk->newpath)) {
4254 putname(lnk->oldpath);
4255 return PTR_ERR(lnk->newpath);
4258 req->flags |= REQ_F_NEED_CLEANUP;
4262 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4264 struct io_hardlink *lnk = &req->hardlink;
4267 if (issue_flags & IO_URING_F_NONBLOCK)
4270 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4271 lnk->newpath, lnk->flags);
4273 req->flags &= ~REQ_F_NEED_CLEANUP;
4276 io_req_complete(req, ret);
4280 static int io_shutdown_prep(struct io_kiocb *req,
4281 const struct io_uring_sqe *sqe)
4283 #if defined(CONFIG_NET)
4284 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4286 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4287 sqe->buf_index || sqe->splice_fd_in))
4290 req->shutdown.how = READ_ONCE(sqe->len);
4297 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4299 #if defined(CONFIG_NET)
4300 struct socket *sock;
4303 if (issue_flags & IO_URING_F_NONBLOCK)
4306 sock = sock_from_file(req->file);
4307 if (unlikely(!sock))
4310 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4313 io_req_complete(req, ret);
4320 static int __io_splice_prep(struct io_kiocb *req,
4321 const struct io_uring_sqe *sqe)
4323 struct io_splice *sp = &req->splice;
4324 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4326 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4329 sp->len = READ_ONCE(sqe->len);
4330 sp->flags = READ_ONCE(sqe->splice_flags);
4331 if (unlikely(sp->flags & ~valid_flags))
4333 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4337 static int io_tee_prep(struct io_kiocb *req,
4338 const struct io_uring_sqe *sqe)
4340 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4342 return __io_splice_prep(req, sqe);
4345 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4347 struct io_splice *sp = &req->splice;
4348 struct file *out = sp->file_out;
4349 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4353 if (issue_flags & IO_URING_F_NONBLOCK)
4356 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4357 in = io_file_get_fixed(req, sp->splice_fd_in, IO_URING_F_UNLOCKED);
4359 in = io_file_get_normal(req, sp->splice_fd_in);
4366 ret = do_tee(in, out, sp->len, flags);
4368 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4373 io_req_complete(req, ret);
4377 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4379 struct io_splice *sp = &req->splice;
4381 sp->off_in = READ_ONCE(sqe->splice_off_in);
4382 sp->off_out = READ_ONCE(sqe->off);
4383 return __io_splice_prep(req, sqe);
4386 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4388 struct io_splice *sp = &req->splice;
4389 struct file *out = sp->file_out;
4390 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4391 loff_t *poff_in, *poff_out;
4395 if (issue_flags & IO_URING_F_NONBLOCK)
4398 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4399 in = io_file_get_fixed(req, sp->splice_fd_in, IO_URING_F_UNLOCKED);
4401 in = io_file_get_normal(req, sp->splice_fd_in);
4407 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4408 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4411 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4413 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4418 io_req_complete(req, ret);
4423 * IORING_OP_NOP just posts a completion event, nothing else.
4425 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4427 struct io_ring_ctx *ctx = req->ctx;
4429 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4432 __io_req_complete(req, issue_flags, 0, 0);
4436 static int io_msg_ring_prep(struct io_kiocb *req,
4437 const struct io_uring_sqe *sqe)
4439 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4440 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4443 req->msg.user_data = READ_ONCE(sqe->off);
4444 req->msg.len = READ_ONCE(sqe->len);
4448 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4450 struct io_ring_ctx *target_ctx;
4451 struct io_msg *msg = &req->msg;
4456 if (req->file->f_op != &io_uring_fops)
4460 target_ctx = req->file->private_data;
4462 spin_lock(&target_ctx->completion_lock);
4463 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
4464 io_commit_cqring(target_ctx);
4465 spin_unlock(&target_ctx->completion_lock);
4468 io_cqring_ev_posted(target_ctx);
4475 __io_req_complete(req, issue_flags, ret, 0);
4479 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4481 struct io_ring_ctx *ctx = req->ctx;
4483 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4485 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4489 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4490 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4493 req->sync.off = READ_ONCE(sqe->off);
4494 req->sync.len = READ_ONCE(sqe->len);
4498 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4500 loff_t end = req->sync.off + req->sync.len;
4503 /* fsync always requires a blocking context */
4504 if (issue_flags & IO_URING_F_NONBLOCK)
4507 ret = vfs_fsync_range(req->file, req->sync.off,
4508 end > 0 ? end : LLONG_MAX,
4509 req->sync.flags & IORING_FSYNC_DATASYNC);
4512 io_req_complete(req, ret);
4516 static int io_fallocate_prep(struct io_kiocb *req,
4517 const struct io_uring_sqe *sqe)
4519 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4522 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4525 req->sync.off = READ_ONCE(sqe->off);
4526 req->sync.len = READ_ONCE(sqe->addr);
4527 req->sync.mode = READ_ONCE(sqe->len);
4531 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4535 /* fallocate always requiring blocking context */
4536 if (issue_flags & IO_URING_F_NONBLOCK)
4538 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4543 fsnotify_modify(req->file);
4544 io_req_complete(req, ret);
4548 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4550 const char __user *fname;
4553 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4555 if (unlikely(sqe->ioprio || sqe->buf_index))
4557 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4560 /* open.how should be already initialised */
4561 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4562 req->open.how.flags |= O_LARGEFILE;
4564 req->open.dfd = READ_ONCE(sqe->fd);
4565 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4566 req->open.filename = getname(fname);
4567 if (IS_ERR(req->open.filename)) {
4568 ret = PTR_ERR(req->open.filename);
4569 req->open.filename = NULL;
4573 req->open.file_slot = READ_ONCE(sqe->file_index);
4574 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4577 req->open.nofile = rlimit(RLIMIT_NOFILE);
4578 req->flags |= REQ_F_NEED_CLEANUP;
4582 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4584 u64 mode = READ_ONCE(sqe->len);
4585 u64 flags = READ_ONCE(sqe->open_flags);
4587 req->open.how = build_open_how(flags, mode);
4588 return __io_openat_prep(req, sqe);
4591 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4593 struct open_how __user *how;
4597 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4598 len = READ_ONCE(sqe->len);
4599 if (len < OPEN_HOW_SIZE_VER0)
4602 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4607 return __io_openat_prep(req, sqe);
4610 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4612 struct open_flags op;
4614 bool resolve_nonblock, nonblock_set;
4615 bool fixed = !!req->open.file_slot;
4618 ret = build_open_flags(&req->open.how, &op);
4621 nonblock_set = op.open_flag & O_NONBLOCK;
4622 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4623 if (issue_flags & IO_URING_F_NONBLOCK) {
4625 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4626 * it'll always -EAGAIN
4628 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4630 op.lookup_flags |= LOOKUP_CACHED;
4631 op.open_flag |= O_NONBLOCK;
4635 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4640 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4643 * We could hang on to this 'fd' on retrying, but seems like
4644 * marginal gain for something that is now known to be a slower
4645 * path. So just put it, and we'll get a new one when we retry.
4650 ret = PTR_ERR(file);
4651 /* only retry if RESOLVE_CACHED wasn't already set by application */
4652 if (ret == -EAGAIN &&
4653 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4658 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4659 file->f_flags &= ~O_NONBLOCK;
4660 fsnotify_open(file);
4663 fd_install(ret, file);
4665 ret = io_install_fixed_file(req, file, issue_flags,
4666 req->open.file_slot - 1);
4668 putname(req->open.filename);
4669 req->flags &= ~REQ_F_NEED_CLEANUP;
4672 __io_req_complete(req, issue_flags, ret, 0);
4676 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4678 return io_openat2(req, issue_flags);
4681 static int io_remove_buffers_prep(struct io_kiocb *req,
4682 const struct io_uring_sqe *sqe)
4684 struct io_provide_buf *p = &req->pbuf;
4687 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4691 tmp = READ_ONCE(sqe->fd);
4692 if (!tmp || tmp > USHRT_MAX)
4695 memset(p, 0, sizeof(*p));
4697 p->bgid = READ_ONCE(sqe->buf_group);
4701 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4702 struct io_buffer_list *bl, unsigned nbufs)
4706 /* shouldn't happen */
4710 /* the head kbuf is the list itself */
4711 while (!list_empty(&bl->buf_list)) {
4712 struct io_buffer *nxt;
4714 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4715 list_del(&nxt->list);
4725 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4727 struct io_provide_buf *p = &req->pbuf;
4728 struct io_ring_ctx *ctx = req->ctx;
4729 struct io_buffer_list *bl;
4731 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4733 io_ring_submit_lock(ctx, needs_lock);
4735 lockdep_assert_held(&ctx->uring_lock);
4738 bl = io_buffer_get_list(ctx, p->bgid);
4740 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4744 /* complete before unlock, IOPOLL may need the lock */
4745 __io_req_complete(req, issue_flags, ret, 0);
4746 io_ring_submit_unlock(ctx, needs_lock);
4750 static int io_provide_buffers_prep(struct io_kiocb *req,
4751 const struct io_uring_sqe *sqe)
4753 unsigned long size, tmp_check;
4754 struct io_provide_buf *p = &req->pbuf;
4757 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4760 tmp = READ_ONCE(sqe->fd);
4761 if (!tmp || tmp > USHRT_MAX)
4764 p->addr = READ_ONCE(sqe->addr);
4765 p->len = READ_ONCE(sqe->len);
4767 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4770 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4773 size = (unsigned long)p->len * p->nbufs;
4774 if (!access_ok(u64_to_user_ptr(p->addr), size))
4777 p->bgid = READ_ONCE(sqe->buf_group);
4778 tmp = READ_ONCE(sqe->off);
4779 if (tmp > USHRT_MAX)
4785 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4787 struct io_buffer *buf;
4792 * Completions that don't happen inline (eg not under uring_lock) will
4793 * add to ->io_buffers_comp. If we don't have any free buffers, check
4794 * the completion list and splice those entries first.
4796 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4797 spin_lock(&ctx->completion_lock);
4798 if (!list_empty(&ctx->io_buffers_comp)) {
4799 list_splice_init(&ctx->io_buffers_comp,
4800 &ctx->io_buffers_cache);
4801 spin_unlock(&ctx->completion_lock);
4804 spin_unlock(&ctx->completion_lock);
4808 * No free buffers and no completion entries either. Allocate a new
4809 * page worth of buffer entries and add those to our freelist.
4811 page = alloc_page(GFP_KERNEL_ACCOUNT);
4815 list_add(&page->lru, &ctx->io_buffers_pages);
4817 buf = page_address(page);
4818 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4819 while (bufs_in_page) {
4820 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4828 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4829 struct io_buffer_list *bl)
4831 struct io_buffer *buf;
4832 u64 addr = pbuf->addr;
4833 int i, bid = pbuf->bid;
4835 for (i = 0; i < pbuf->nbufs; i++) {
4836 if (list_empty(&ctx->io_buffers_cache) &&
4837 io_refill_buffer_cache(ctx))
4839 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4841 list_move_tail(&buf->list, &bl->buf_list);
4843 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4845 buf->bgid = pbuf->bgid;
4851 return i ? 0 : -ENOMEM;
4854 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4856 struct io_provide_buf *p = &req->pbuf;
4857 struct io_ring_ctx *ctx = req->ctx;
4858 struct io_buffer_list *bl;
4860 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4862 io_ring_submit_lock(ctx, needs_lock);
4864 lockdep_assert_held(&ctx->uring_lock);
4866 bl = io_buffer_get_list(ctx, p->bgid);
4867 if (unlikely(!bl)) {
4868 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4873 io_buffer_add_list(ctx, bl, p->bgid);
4876 ret = io_add_buffers(ctx, p, bl);
4880 /* complete before unlock, IOPOLL may need the lock */
4881 __io_req_complete(req, issue_flags, ret, 0);
4882 io_ring_submit_unlock(ctx, needs_lock);
4886 static int io_epoll_ctl_prep(struct io_kiocb *req,
4887 const struct io_uring_sqe *sqe)
4889 #if defined(CONFIG_EPOLL)
4890 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4892 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4895 req->epoll.epfd = READ_ONCE(sqe->fd);
4896 req->epoll.op = READ_ONCE(sqe->len);
4897 req->epoll.fd = READ_ONCE(sqe->off);
4899 if (ep_op_has_event(req->epoll.op)) {
4900 struct epoll_event __user *ev;
4902 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4903 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4913 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4915 #if defined(CONFIG_EPOLL)
4916 struct io_epoll *ie = &req->epoll;
4918 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4920 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4921 if (force_nonblock && ret == -EAGAIN)
4926 __io_req_complete(req, issue_flags, ret, 0);
4933 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4935 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4936 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4938 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4941 req->madvise.addr = READ_ONCE(sqe->addr);
4942 req->madvise.len = READ_ONCE(sqe->len);
4943 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4950 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4952 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4953 struct io_madvise *ma = &req->madvise;
4956 if (issue_flags & IO_URING_F_NONBLOCK)
4959 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4962 io_req_complete(req, ret);
4969 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4971 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4973 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4976 req->fadvise.offset = READ_ONCE(sqe->off);
4977 req->fadvise.len = READ_ONCE(sqe->len);
4978 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4982 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4984 struct io_fadvise *fa = &req->fadvise;
4987 if (issue_flags & IO_URING_F_NONBLOCK) {
4988 switch (fa->advice) {
4989 case POSIX_FADV_NORMAL:
4990 case POSIX_FADV_RANDOM:
4991 case POSIX_FADV_SEQUENTIAL:
4998 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5001 __io_req_complete(req, issue_flags, ret, 0);
5005 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5007 const char __user *path;
5009 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5011 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5013 if (req->flags & REQ_F_FIXED_FILE)
5016 req->statx.dfd = READ_ONCE(sqe->fd);
5017 req->statx.mask = READ_ONCE(sqe->len);
5018 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5019 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5020 req->statx.flags = READ_ONCE(sqe->statx_flags);
5022 req->statx.filename = getname_flags(path,
5023 getname_statx_lookup_flags(req->statx.flags),
5026 if (IS_ERR(req->statx.filename)) {
5027 int ret = PTR_ERR(req->statx.filename);
5029 req->statx.filename = NULL;
5033 req->flags |= REQ_F_NEED_CLEANUP;
5037 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5039 struct io_statx *ctx = &req->statx;
5042 if (issue_flags & IO_URING_F_NONBLOCK)
5045 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5050 io_req_complete(req, ret);
5054 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5056 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5058 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5059 sqe->rw_flags || sqe->buf_index)
5061 if (req->flags & REQ_F_FIXED_FILE)
5064 req->close.fd = READ_ONCE(sqe->fd);
5065 req->close.file_slot = READ_ONCE(sqe->file_index);
5066 if (req->close.file_slot && req->close.fd)
5072 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5074 struct files_struct *files = current->files;
5075 struct io_close *close = &req->close;
5076 struct fdtable *fdt;
5077 struct file *file = NULL;
5080 if (req->close.file_slot) {
5081 ret = io_close_fixed(req, issue_flags);
5085 spin_lock(&files->file_lock);
5086 fdt = files_fdtable(files);
5087 if (close->fd >= fdt->max_fds) {
5088 spin_unlock(&files->file_lock);
5091 file = fdt->fd[close->fd];
5092 if (!file || file->f_op == &io_uring_fops) {
5093 spin_unlock(&files->file_lock);
5098 /* if the file has a flush method, be safe and punt to async */
5099 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5100 spin_unlock(&files->file_lock);
5104 ret = __close_fd_get_file(close->fd, &file);
5105 spin_unlock(&files->file_lock);
5112 /* No ->flush() or already async, safely close from here */
5113 ret = filp_close(file, current->files);
5119 __io_req_complete(req, issue_flags, ret, 0);
5123 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5125 struct io_ring_ctx *ctx = req->ctx;
5127 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5129 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5133 req->sync.off = READ_ONCE(sqe->off);
5134 req->sync.len = READ_ONCE(sqe->len);
5135 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5139 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5143 /* sync_file_range always requires a blocking context */
5144 if (issue_flags & IO_URING_F_NONBLOCK)
5147 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5151 io_req_complete(req, ret);
5155 #if defined(CONFIG_NET)
5156 static int io_setup_async_msg(struct io_kiocb *req,
5157 struct io_async_msghdr *kmsg)
5159 struct io_async_msghdr *async_msg = req->async_data;
5163 if (io_alloc_async_data(req)) {
5164 kfree(kmsg->free_iov);
5167 async_msg = req->async_data;
5168 req->flags |= REQ_F_NEED_CLEANUP;
5169 memcpy(async_msg, kmsg, sizeof(*kmsg));
5170 async_msg->msg.msg_name = &async_msg->addr;
5171 /* if were using fast_iov, set it to the new one */
5172 if (!async_msg->free_iov)
5173 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5178 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5179 struct io_async_msghdr *iomsg)
5181 iomsg->msg.msg_name = &iomsg->addr;
5182 iomsg->free_iov = iomsg->fast_iov;
5183 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5184 req->sr_msg.msg_flags, &iomsg->free_iov);
5187 static int io_sendmsg_prep_async(struct io_kiocb *req)
5191 ret = io_sendmsg_copy_hdr(req, req->async_data);
5193 req->flags |= REQ_F_NEED_CLEANUP;
5197 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5199 struct io_sr_msg *sr = &req->sr_msg;
5201 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5204 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5205 sr->len = READ_ONCE(sqe->len);
5206 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5207 if (sr->msg_flags & MSG_DONTWAIT)
5208 req->flags |= REQ_F_NOWAIT;
5210 #ifdef CONFIG_COMPAT
5211 if (req->ctx->compat)
5212 sr->msg_flags |= MSG_CMSG_COMPAT;
5217 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5219 struct io_async_msghdr iomsg, *kmsg;
5220 struct socket *sock;
5225 sock = sock_from_file(req->file);
5226 if (unlikely(!sock))
5229 if (req_has_async_data(req)) {
5230 kmsg = req->async_data;
5232 ret = io_sendmsg_copy_hdr(req, &iomsg);
5238 flags = req->sr_msg.msg_flags;
5239 if (issue_flags & IO_URING_F_NONBLOCK)
5240 flags |= MSG_DONTWAIT;
5241 if (flags & MSG_WAITALL)
5242 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5244 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5246 if (ret < min_ret) {
5247 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5248 return io_setup_async_msg(req, kmsg);
5249 if (ret == -ERESTARTSYS)
5253 /* fast path, check for non-NULL to avoid function call */
5255 kfree(kmsg->free_iov);
5256 req->flags &= ~REQ_F_NEED_CLEANUP;
5257 __io_req_complete(req, issue_flags, ret, 0);
5261 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5263 struct io_sr_msg *sr = &req->sr_msg;
5266 struct socket *sock;
5271 sock = sock_from_file(req->file);
5272 if (unlikely(!sock))
5275 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5279 msg.msg_name = NULL;
5280 msg.msg_control = NULL;
5281 msg.msg_controllen = 0;
5282 msg.msg_namelen = 0;
5284 flags = req->sr_msg.msg_flags;
5285 if (issue_flags & IO_URING_F_NONBLOCK)
5286 flags |= MSG_DONTWAIT;
5287 if (flags & MSG_WAITALL)
5288 min_ret = iov_iter_count(&msg.msg_iter);
5290 msg.msg_flags = flags;
5291 ret = sock_sendmsg(sock, &msg);
5292 if (ret < min_ret) {
5293 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5295 if (ret == -ERESTARTSYS)
5299 __io_req_complete(req, issue_flags, ret, 0);
5303 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5304 struct io_async_msghdr *iomsg)
5306 struct io_sr_msg *sr = &req->sr_msg;
5307 struct iovec __user *uiov;
5311 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5312 &iomsg->uaddr, &uiov, &iov_len);
5316 if (req->flags & REQ_F_BUFFER_SELECT) {
5319 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5321 sr->len = iomsg->fast_iov[0].iov_len;
5322 iomsg->free_iov = NULL;
5324 iomsg->free_iov = iomsg->fast_iov;
5325 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5326 &iomsg->free_iov, &iomsg->msg.msg_iter,
5335 #ifdef CONFIG_COMPAT
5336 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5337 struct io_async_msghdr *iomsg)
5339 struct io_sr_msg *sr = &req->sr_msg;
5340 struct compat_iovec __user *uiov;
5345 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5350 uiov = compat_ptr(ptr);
5351 if (req->flags & REQ_F_BUFFER_SELECT) {
5352 compat_ssize_t clen;
5356 if (!access_ok(uiov, sizeof(*uiov)))
5358 if (__get_user(clen, &uiov->iov_len))
5363 iomsg->free_iov = NULL;
5365 iomsg->free_iov = iomsg->fast_iov;
5366 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5367 UIO_FASTIOV, &iomsg->free_iov,
5368 &iomsg->msg.msg_iter, true);
5377 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5378 struct io_async_msghdr *iomsg)
5380 iomsg->msg.msg_name = &iomsg->addr;
5382 #ifdef CONFIG_COMPAT
5383 if (req->ctx->compat)
5384 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5387 return __io_recvmsg_copy_hdr(req, iomsg);
5390 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5391 unsigned int issue_flags)
5393 struct io_sr_msg *sr = &req->sr_msg;
5395 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5398 static int io_recvmsg_prep_async(struct io_kiocb *req)
5402 ret = io_recvmsg_copy_hdr(req, req->async_data);
5404 req->flags |= REQ_F_NEED_CLEANUP;
5408 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5410 struct io_sr_msg *sr = &req->sr_msg;
5412 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5415 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5416 sr->len = READ_ONCE(sqe->len);
5417 sr->bgid = READ_ONCE(sqe->buf_group);
5418 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5419 if (sr->msg_flags & MSG_DONTWAIT)
5420 req->flags |= REQ_F_NOWAIT;
5422 #ifdef CONFIG_COMPAT
5423 if (req->ctx->compat)
5424 sr->msg_flags |= MSG_CMSG_COMPAT;
5430 static bool io_net_retry(struct socket *sock, int flags)
5432 if (!(flags & MSG_WAITALL))
5434 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5437 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5439 struct io_async_msghdr iomsg, *kmsg;
5440 struct io_sr_msg *sr = &req->sr_msg;
5441 struct socket *sock;
5442 struct io_buffer *kbuf;
5444 int ret, min_ret = 0;
5445 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5447 sock = sock_from_file(req->file);
5448 if (unlikely(!sock))
5451 if (req_has_async_data(req)) {
5452 kmsg = req->async_data;
5454 ret = io_recvmsg_copy_hdr(req, &iomsg);
5460 if (req->flags & REQ_F_BUFFER_SELECT) {
5461 kbuf = io_recv_buffer_select(req, issue_flags);
5463 return PTR_ERR(kbuf);
5464 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5465 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5466 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5467 1, req->sr_msg.len);
5470 flags = req->sr_msg.msg_flags;
5472 flags |= MSG_DONTWAIT;
5473 if (flags & MSG_WAITALL)
5474 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5476 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5477 kmsg->uaddr, flags);
5478 if (ret < min_ret) {
5479 if (ret == -EAGAIN && force_nonblock)
5480 return io_setup_async_msg(req, kmsg);
5481 if (ret == -ERESTARTSYS)
5483 if (ret > 0 && io_net_retry(sock, flags)) {
5485 req->flags |= REQ_F_PARTIAL_IO;
5486 return io_setup_async_msg(req, kmsg);
5489 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5493 /* fast path, check for non-NULL to avoid function call */
5495 kfree(kmsg->free_iov);
5496 req->flags &= ~REQ_F_NEED_CLEANUP;
5499 else if (sr->done_io)
5501 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5505 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5507 struct io_buffer *kbuf;
5508 struct io_sr_msg *sr = &req->sr_msg;
5510 void __user *buf = sr->buf;
5511 struct socket *sock;
5514 int ret, min_ret = 0;
5515 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5517 sock = sock_from_file(req->file);
5518 if (unlikely(!sock))
5521 if (req->flags & REQ_F_BUFFER_SELECT) {
5522 kbuf = io_recv_buffer_select(req, issue_flags);
5524 return PTR_ERR(kbuf);
5525 buf = u64_to_user_ptr(kbuf->addr);
5528 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5532 msg.msg_name = NULL;
5533 msg.msg_control = NULL;
5534 msg.msg_controllen = 0;
5535 msg.msg_namelen = 0;
5536 msg.msg_iocb = NULL;
5539 flags = req->sr_msg.msg_flags;
5541 flags |= MSG_DONTWAIT;
5542 if (flags & MSG_WAITALL)
5543 min_ret = iov_iter_count(&msg.msg_iter);
5545 ret = sock_recvmsg(sock, &msg, flags);
5546 if (ret < min_ret) {
5547 if (ret == -EAGAIN && force_nonblock)
5549 if (ret == -ERESTARTSYS)
5551 if (ret > 0 && io_net_retry(sock, flags)) {
5555 req->flags |= REQ_F_PARTIAL_IO;
5559 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5566 else if (sr->done_io)
5568 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5572 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5574 struct io_accept *accept = &req->accept;
5576 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5578 if (sqe->ioprio || sqe->len || sqe->buf_index)
5581 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5582 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5583 accept->flags = READ_ONCE(sqe->accept_flags);
5584 accept->nofile = rlimit(RLIMIT_NOFILE);
5586 accept->file_slot = READ_ONCE(sqe->file_index);
5587 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5589 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5591 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5592 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5596 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5598 struct io_accept *accept = &req->accept;
5599 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5600 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5601 bool fixed = !!accept->file_slot;
5606 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5607 if (unlikely(fd < 0))
5610 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5615 ret = PTR_ERR(file);
5616 if (ret == -EAGAIN && force_nonblock)
5618 if (ret == -ERESTARTSYS)
5621 } else if (!fixed) {
5622 fd_install(fd, file);
5625 ret = io_install_fixed_file(req, file, issue_flags,
5626 accept->file_slot - 1);
5628 __io_req_complete(req, issue_flags, ret, 0);
5632 static int io_connect_prep_async(struct io_kiocb *req)
5634 struct io_async_connect *io = req->async_data;
5635 struct io_connect *conn = &req->connect;
5637 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5640 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5642 struct io_connect *conn = &req->connect;
5644 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5646 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5650 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5651 conn->addr_len = READ_ONCE(sqe->addr2);
5655 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5657 struct io_async_connect __io, *io;
5658 unsigned file_flags;
5660 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5662 if (req_has_async_data(req)) {
5663 io = req->async_data;
5665 ret = move_addr_to_kernel(req->connect.addr,
5666 req->connect.addr_len,
5673 file_flags = force_nonblock ? O_NONBLOCK : 0;
5675 ret = __sys_connect_file(req->file, &io->address,
5676 req->connect.addr_len, file_flags);
5677 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5678 if (req_has_async_data(req))
5680 if (io_alloc_async_data(req)) {
5684 memcpy(req->async_data, &__io, sizeof(__io));
5687 if (ret == -ERESTARTSYS)
5692 __io_req_complete(req, issue_flags, ret, 0);
5695 #else /* !CONFIG_NET */
5696 #define IO_NETOP_FN(op) \
5697 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5699 return -EOPNOTSUPP; \
5702 #define IO_NETOP_PREP(op) \
5704 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5706 return -EOPNOTSUPP; \
5709 #define IO_NETOP_PREP_ASYNC(op) \
5711 static int io_##op##_prep_async(struct io_kiocb *req) \
5713 return -EOPNOTSUPP; \
5716 IO_NETOP_PREP_ASYNC(sendmsg);
5717 IO_NETOP_PREP_ASYNC(recvmsg);
5718 IO_NETOP_PREP_ASYNC(connect);
5719 IO_NETOP_PREP(accept);
5722 #endif /* CONFIG_NET */
5724 struct io_poll_table {
5725 struct poll_table_struct pt;
5726 struct io_kiocb *req;
5731 #define IO_POLL_CANCEL_FLAG BIT(31)
5732 #define IO_POLL_REF_MASK GENMASK(30, 0)
5735 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5736 * bump it and acquire ownership. It's disallowed to modify requests while not
5737 * owning it, that prevents from races for enqueueing task_work's and b/w
5738 * arming poll and wakeups.
5740 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5742 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5745 static void io_poll_mark_cancelled(struct io_kiocb *req)
5747 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5750 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5752 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5753 if (req->opcode == IORING_OP_POLL_ADD)
5754 return req->async_data;
5755 return req->apoll->double_poll;
5758 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5760 if (req->opcode == IORING_OP_POLL_ADD)
5762 return &req->apoll->poll;
5765 static void io_poll_req_insert(struct io_kiocb *req)
5767 struct io_ring_ctx *ctx = req->ctx;
5768 struct hlist_head *list;
5770 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5771 hlist_add_head(&req->hash_node, list);
5774 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5775 wait_queue_func_t wake_func)
5778 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5779 /* mask in events that we always want/need */
5780 poll->events = events | IO_POLL_UNMASK;
5781 INIT_LIST_HEAD(&poll->wait.entry);
5782 init_waitqueue_func_entry(&poll->wait, wake_func);
5785 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5787 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5790 spin_lock_irq(&head->lock);
5791 list_del_init(&poll->wait.entry);
5793 spin_unlock_irq(&head->lock);
5797 static void io_poll_remove_entries(struct io_kiocb *req)
5800 * Nothing to do if neither of those flags are set. Avoid dipping
5801 * into the poll/apoll/double cachelines if we can.
5803 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5807 * While we hold the waitqueue lock and the waitqueue is nonempty,
5808 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5809 * lock in the first place can race with the waitqueue being freed.
5811 * We solve this as eventpoll does: by taking advantage of the fact that
5812 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5813 * we enter rcu_read_lock() and see that the pointer to the queue is
5814 * non-NULL, we can then lock it without the memory being freed out from
5817 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5818 * case the caller deletes the entry from the queue, leaving it empty.
5819 * In that case, only RCU prevents the queue memory from being freed.
5822 if (req->flags & REQ_F_SINGLE_POLL)
5823 io_poll_remove_entry(io_poll_get_single(req));
5824 if (req->flags & REQ_F_DOUBLE_POLL)
5825 io_poll_remove_entry(io_poll_get_double(req));
5830 * All poll tw should go through this. Checks for poll events, manages
5831 * references, does rewait, etc.
5833 * Returns a negative error on failure. >0 when no action require, which is
5834 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5835 * the request, then the mask is stored in req->result.
5837 static int io_poll_check_events(struct io_kiocb *req, bool locked)
5839 struct io_ring_ctx *ctx = req->ctx;
5842 /* req->task == current here, checking PF_EXITING is safe */
5843 if (unlikely(req->task->flags & PF_EXITING))
5844 io_poll_mark_cancelled(req);
5847 v = atomic_read(&req->poll_refs);
5849 /* tw handler should be the owner, and so have some references */
5850 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5852 if (v & IO_POLL_CANCEL_FLAG)
5856 struct poll_table_struct pt = { ._key = req->apoll_events };
5858 if (unlikely(!io_assign_file(req, IO_URING_F_UNLOCKED)))
5859 req->result = -EBADF;
5861 req->result = vfs_poll(req->file, &pt) & req->apoll_events;
5864 /* multishot, just fill an CQE and proceed */
5865 if (req->result && !(req->apoll_events & EPOLLONESHOT)) {
5866 __poll_t mask = mangle_poll(req->result & req->apoll_events);
5869 spin_lock(&ctx->completion_lock);
5870 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5872 io_commit_cqring(ctx);
5873 spin_unlock(&ctx->completion_lock);
5874 if (unlikely(!filled))
5876 io_cqring_ev_posted(ctx);
5877 } else if (req->result) {
5882 * Release all references, retry if someone tried to restart
5883 * task_work while we were executing it.
5885 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5890 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5892 struct io_ring_ctx *ctx = req->ctx;
5895 ret = io_poll_check_events(req, *locked);
5900 req->result = mangle_poll(req->result & req->poll.events);
5906 io_poll_remove_entries(req);
5907 spin_lock(&ctx->completion_lock);
5908 hash_del(&req->hash_node);
5909 __io_req_complete_post(req, req->result, 0);
5910 io_commit_cqring(ctx);
5911 spin_unlock(&ctx->completion_lock);
5912 io_cqring_ev_posted(ctx);
5915 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5917 struct io_ring_ctx *ctx = req->ctx;
5920 ret = io_poll_check_events(req, *locked);
5924 io_poll_remove_entries(req);
5925 spin_lock(&ctx->completion_lock);
5926 hash_del(&req->hash_node);
5927 spin_unlock(&ctx->completion_lock);
5930 io_req_task_submit(req, locked);
5932 io_req_complete_failed(req, ret);
5935 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
5939 * This is useful for poll that is armed on behalf of another
5940 * request, and where the wakeup path could be on a different
5941 * CPU. We want to avoid pulling in req->apoll->events for that
5944 req->apoll_events = events;
5945 if (req->opcode == IORING_OP_POLL_ADD)
5946 req->io_task_work.func = io_poll_task_func;
5948 req->io_task_work.func = io_apoll_task_func;
5950 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
5951 io_req_task_work_add(req, false);
5954 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
5956 if (io_poll_get_ownership(req))
5957 __io_poll_execute(req, res, events);
5960 static void io_poll_cancel_req(struct io_kiocb *req)
5962 io_poll_mark_cancelled(req);
5963 /* kick tw, which should complete the request */
5964 io_poll_execute(req, 0, 0);
5967 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
5968 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
5970 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5973 struct io_kiocb *req = wqe_to_req(wait);
5974 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5976 __poll_t mask = key_to_poll(key);
5978 if (unlikely(mask & POLLFREE)) {
5979 io_poll_mark_cancelled(req);
5980 /* we have to kick tw in case it's not already */
5981 io_poll_execute(req, 0, poll->events);
5984 * If the waitqueue is being freed early but someone is already
5985 * holds ownership over it, we have to tear down the request as
5986 * best we can. That means immediately removing the request from
5987 * its waitqueue and preventing all further accesses to the
5988 * waitqueue via the request.
5990 list_del_init(&poll->wait.entry);
5993 * Careful: this *must* be the last step, since as soon
5994 * as req->head is NULL'ed out, the request can be
5995 * completed and freed, since aio_poll_complete_work()
5996 * will no longer need to take the waitqueue lock.
5998 smp_store_release(&poll->head, NULL);
6002 /* for instances that support it check for an event match first */
6003 if (mask && !(mask & poll->events))
6006 if (io_poll_get_ownership(req)) {
6007 /* optional, saves extra locking for removal in tw handler */
6008 if (mask && poll->events & EPOLLONESHOT) {
6009 list_del_init(&poll->wait.entry);
6011 if (wqe_is_double(wait))
6012 req->flags &= ~REQ_F_DOUBLE_POLL;
6014 req->flags &= ~REQ_F_SINGLE_POLL;
6016 __io_poll_execute(req, mask, poll->events);
6021 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6022 struct wait_queue_head *head,
6023 struct io_poll_iocb **poll_ptr)
6025 struct io_kiocb *req = pt->req;
6026 unsigned long wqe_private = (unsigned long) req;
6029 * The file being polled uses multiple waitqueues for poll handling
6030 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6033 if (unlikely(pt->nr_entries)) {
6034 struct io_poll_iocb *first = poll;
6036 /* double add on the same waitqueue head, ignore */
6037 if (first->head == head)
6039 /* already have a 2nd entry, fail a third attempt */
6041 if ((*poll_ptr)->head == head)
6043 pt->error = -EINVAL;
6047 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6049 pt->error = -ENOMEM;
6052 /* mark as double wq entry */
6054 req->flags |= REQ_F_DOUBLE_POLL;
6055 io_init_poll_iocb(poll, first->events, first->wait.func);
6057 if (req->opcode == IORING_OP_POLL_ADD)
6058 req->flags |= REQ_F_ASYNC_DATA;
6061 req->flags |= REQ_F_SINGLE_POLL;
6064 poll->wait.private = (void *) wqe_private;
6066 if (poll->events & EPOLLEXCLUSIVE)
6067 add_wait_queue_exclusive(head, &poll->wait);
6069 add_wait_queue(head, &poll->wait);
6072 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6073 struct poll_table_struct *p)
6075 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6077 __io_queue_proc(&pt->req->poll, pt, head,
6078 (struct io_poll_iocb **) &pt->req->async_data);
6081 static int __io_arm_poll_handler(struct io_kiocb *req,
6082 struct io_poll_iocb *poll,
6083 struct io_poll_table *ipt, __poll_t mask)
6085 struct io_ring_ctx *ctx = req->ctx;
6088 INIT_HLIST_NODE(&req->hash_node);
6089 io_init_poll_iocb(poll, mask, io_poll_wake);
6090 poll->file = req->file;
6092 ipt->pt._key = mask;
6095 ipt->nr_entries = 0;
6098 * Take the ownership to delay any tw execution up until we're done
6099 * with poll arming. see io_poll_get_ownership().
6101 atomic_set(&req->poll_refs, 1);
6102 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6104 if (mask && (poll->events & EPOLLONESHOT)) {
6105 io_poll_remove_entries(req);
6106 /* no one else has access to the req, forget about the ref */
6109 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6110 io_poll_remove_entries(req);
6112 ipt->error = -EINVAL;
6116 spin_lock(&ctx->completion_lock);
6117 io_poll_req_insert(req);
6118 spin_unlock(&ctx->completion_lock);
6121 /* can't multishot if failed, just queue the event we've got */
6122 if (unlikely(ipt->error || !ipt->nr_entries))
6123 poll->events |= EPOLLONESHOT;
6124 __io_poll_execute(req, mask, poll->events);
6129 * Release ownership. If someone tried to queue a tw while it was
6130 * locked, kick it off for them.
6132 v = atomic_dec_return(&req->poll_refs);
6133 if (unlikely(v & IO_POLL_REF_MASK))
6134 __io_poll_execute(req, 0, poll->events);
6138 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6139 struct poll_table_struct *p)
6141 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6142 struct async_poll *apoll = pt->req->apoll;
6144 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6153 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6155 const struct io_op_def *def = &io_op_defs[req->opcode];
6156 struct io_ring_ctx *ctx = req->ctx;
6157 struct async_poll *apoll;
6158 struct io_poll_table ipt;
6159 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6162 if (!def->pollin && !def->pollout)
6163 return IO_APOLL_ABORTED;
6164 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6165 return IO_APOLL_ABORTED;
6168 mask |= POLLIN | POLLRDNORM;
6170 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6171 if ((req->opcode == IORING_OP_RECVMSG) &&
6172 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6175 mask |= POLLOUT | POLLWRNORM;
6177 if (def->poll_exclusive)
6178 mask |= EPOLLEXCLUSIVE;
6179 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6180 !list_empty(&ctx->apoll_cache)) {
6181 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6183 list_del_init(&apoll->poll.wait.entry);
6185 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6186 if (unlikely(!apoll))
6187 return IO_APOLL_ABORTED;
6189 apoll->double_poll = NULL;
6191 req->flags |= REQ_F_POLLED;
6192 ipt.pt._qproc = io_async_queue_proc;
6194 io_kbuf_recycle(req, issue_flags);
6196 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6197 if (ret || ipt.error)
6198 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6200 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6201 mask, apoll->poll.events);
6206 * Returns true if we found and killed one or more poll requests
6208 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6209 struct task_struct *tsk, bool cancel_all)
6211 struct hlist_node *tmp;
6212 struct io_kiocb *req;
6216 spin_lock(&ctx->completion_lock);
6217 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6218 struct hlist_head *list;
6220 list = &ctx->cancel_hash[i];
6221 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6222 if (io_match_task_safe(req, tsk, cancel_all)) {
6223 hlist_del_init(&req->hash_node);
6224 io_poll_cancel_req(req);
6229 spin_unlock(&ctx->completion_lock);
6233 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6235 __must_hold(&ctx->completion_lock)
6237 struct hlist_head *list;
6238 struct io_kiocb *req;
6240 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6241 hlist_for_each_entry(req, list, hash_node) {
6242 if (sqe_addr != req->user_data)
6244 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6251 static bool io_poll_disarm(struct io_kiocb *req)
6252 __must_hold(&ctx->completion_lock)
6254 if (!io_poll_get_ownership(req))
6256 io_poll_remove_entries(req);
6257 hash_del(&req->hash_node);
6261 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6263 __must_hold(&ctx->completion_lock)
6265 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6269 io_poll_cancel_req(req);
6273 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6278 events = READ_ONCE(sqe->poll32_events);
6280 events = swahw32(events);
6282 if (!(flags & IORING_POLL_ADD_MULTI))
6283 events |= EPOLLONESHOT;
6284 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6287 static int io_poll_update_prep(struct io_kiocb *req,
6288 const struct io_uring_sqe *sqe)
6290 struct io_poll_update *upd = &req->poll_update;
6293 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6295 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6297 flags = READ_ONCE(sqe->len);
6298 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6299 IORING_POLL_ADD_MULTI))
6301 /* meaningless without update */
6302 if (flags == IORING_POLL_ADD_MULTI)
6305 upd->old_user_data = READ_ONCE(sqe->addr);
6306 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6307 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6309 upd->new_user_data = READ_ONCE(sqe->off);
6310 if (!upd->update_user_data && upd->new_user_data)
6312 if (upd->update_events)
6313 upd->events = io_poll_parse_events(sqe, flags);
6314 else if (sqe->poll32_events)
6320 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6322 struct io_poll_iocb *poll = &req->poll;
6325 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6327 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6329 flags = READ_ONCE(sqe->len);
6330 if (flags & ~IORING_POLL_ADD_MULTI)
6332 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6335 io_req_set_refcount(req);
6336 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
6340 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6342 struct io_poll_iocb *poll = &req->poll;
6343 struct io_poll_table ipt;
6346 ipt.pt._qproc = io_poll_queue_proc;
6348 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6349 ret = ret ?: ipt.error;
6351 __io_req_complete(req, issue_flags, ret, 0);
6355 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6357 struct io_ring_ctx *ctx = req->ctx;
6358 struct io_kiocb *preq;
6362 spin_lock(&ctx->completion_lock);
6363 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6364 if (!preq || !io_poll_disarm(preq)) {
6365 spin_unlock(&ctx->completion_lock);
6366 ret = preq ? -EALREADY : -ENOENT;
6369 spin_unlock(&ctx->completion_lock);
6371 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6372 /* only mask one event flags, keep behavior flags */
6373 if (req->poll_update.update_events) {
6374 preq->poll.events &= ~0xffff;
6375 preq->poll.events |= req->poll_update.events & 0xffff;
6376 preq->poll.events |= IO_POLL_UNMASK;
6378 if (req->poll_update.update_user_data)
6379 preq->user_data = req->poll_update.new_user_data;
6381 ret2 = io_poll_add(preq, issue_flags);
6382 /* successfully updated, don't complete poll request */
6388 preq->result = -ECANCELED;
6389 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6390 io_req_task_complete(preq, &locked);
6394 /* complete update request, we're done with it */
6395 __io_req_complete(req, issue_flags, ret, 0);
6399 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6401 struct io_timeout_data *data = container_of(timer,
6402 struct io_timeout_data, timer);
6403 struct io_kiocb *req = data->req;
6404 struct io_ring_ctx *ctx = req->ctx;
6405 unsigned long flags;
6407 spin_lock_irqsave(&ctx->timeout_lock, flags);
6408 list_del_init(&req->timeout.list);
6409 atomic_set(&req->ctx->cq_timeouts,
6410 atomic_read(&req->ctx->cq_timeouts) + 1);
6411 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6413 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6416 req->result = -ETIME;
6417 req->io_task_work.func = io_req_task_complete;
6418 io_req_task_work_add(req, false);
6419 return HRTIMER_NORESTART;
6422 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6424 __must_hold(&ctx->timeout_lock)
6426 struct io_timeout_data *io;
6427 struct io_kiocb *req;
6430 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6431 found = user_data == req->user_data;
6436 return ERR_PTR(-ENOENT);
6438 io = req->async_data;
6439 if (hrtimer_try_to_cancel(&io->timer) == -1)
6440 return ERR_PTR(-EALREADY);
6441 list_del_init(&req->timeout.list);
6445 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6446 __must_hold(&ctx->completion_lock)
6447 __must_hold(&ctx->timeout_lock)
6449 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6452 return PTR_ERR(req);
6453 io_req_task_queue_fail(req, -ECANCELED);
6457 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6459 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6460 case IORING_TIMEOUT_BOOTTIME:
6461 return CLOCK_BOOTTIME;
6462 case IORING_TIMEOUT_REALTIME:
6463 return CLOCK_REALTIME;
6465 /* can't happen, vetted at prep time */
6469 return CLOCK_MONOTONIC;
6473 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6474 struct timespec64 *ts, enum hrtimer_mode mode)
6475 __must_hold(&ctx->timeout_lock)
6477 struct io_timeout_data *io;
6478 struct io_kiocb *req;
6481 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6482 found = user_data == req->user_data;
6489 io = req->async_data;
6490 if (hrtimer_try_to_cancel(&io->timer) == -1)
6492 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6493 io->timer.function = io_link_timeout_fn;
6494 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6498 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6499 struct timespec64 *ts, enum hrtimer_mode mode)
6500 __must_hold(&ctx->timeout_lock)
6502 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6503 struct io_timeout_data *data;
6506 return PTR_ERR(req);
6508 req->timeout.off = 0; /* noseq */
6509 data = req->async_data;
6510 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6511 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6512 data->timer.function = io_timeout_fn;
6513 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6517 static int io_timeout_remove_prep(struct io_kiocb *req,
6518 const struct io_uring_sqe *sqe)
6520 struct io_timeout_rem *tr = &req->timeout_rem;
6522 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6524 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6526 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6529 tr->ltimeout = false;
6530 tr->addr = READ_ONCE(sqe->addr);
6531 tr->flags = READ_ONCE(sqe->timeout_flags);
6532 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6533 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6535 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6536 tr->ltimeout = true;
6537 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6539 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6541 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6543 } else if (tr->flags) {
6544 /* timeout removal doesn't support flags */
6551 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6553 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6558 * Remove or update an existing timeout command
6560 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6562 struct io_timeout_rem *tr = &req->timeout_rem;
6563 struct io_ring_ctx *ctx = req->ctx;
6566 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6567 spin_lock(&ctx->completion_lock);
6568 spin_lock_irq(&ctx->timeout_lock);
6569 ret = io_timeout_cancel(ctx, tr->addr);
6570 spin_unlock_irq(&ctx->timeout_lock);
6571 spin_unlock(&ctx->completion_lock);
6573 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6575 spin_lock_irq(&ctx->timeout_lock);
6577 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6579 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6580 spin_unlock_irq(&ctx->timeout_lock);
6585 io_req_complete_post(req, ret, 0);
6589 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6590 bool is_timeout_link)
6592 struct io_timeout_data *data;
6594 u32 off = READ_ONCE(sqe->off);
6596 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6598 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6601 if (off && is_timeout_link)
6603 flags = READ_ONCE(sqe->timeout_flags);
6604 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6605 IORING_TIMEOUT_ETIME_SUCCESS))
6607 /* more than one clock specified is invalid, obviously */
6608 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6611 INIT_LIST_HEAD(&req->timeout.list);
6612 req->timeout.off = off;
6613 if (unlikely(off && !req->ctx->off_timeout_used))
6614 req->ctx->off_timeout_used = true;
6616 if (WARN_ON_ONCE(req_has_async_data(req)))
6618 if (io_alloc_async_data(req))
6621 data = req->async_data;
6623 data->flags = flags;
6625 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6628 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6631 INIT_LIST_HEAD(&req->timeout.list);
6632 data->mode = io_translate_timeout_mode(flags);
6633 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6635 if (is_timeout_link) {
6636 struct io_submit_link *link = &req->ctx->submit_state.link;
6640 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6642 req->timeout.head = link->last;
6643 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6648 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6650 struct io_ring_ctx *ctx = req->ctx;
6651 struct io_timeout_data *data = req->async_data;
6652 struct list_head *entry;
6653 u32 tail, off = req->timeout.off;
6655 spin_lock_irq(&ctx->timeout_lock);
6658 * sqe->off holds how many events that need to occur for this
6659 * timeout event to be satisfied. If it isn't set, then this is
6660 * a pure timeout request, sequence isn't used.
6662 if (io_is_timeout_noseq(req)) {
6663 entry = ctx->timeout_list.prev;
6667 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6668 req->timeout.target_seq = tail + off;
6670 /* Update the last seq here in case io_flush_timeouts() hasn't.
6671 * This is safe because ->completion_lock is held, and submissions
6672 * and completions are never mixed in the same ->completion_lock section.
6674 ctx->cq_last_tm_flush = tail;
6677 * Insertion sort, ensuring the first entry in the list is always
6678 * the one we need first.
6680 list_for_each_prev(entry, &ctx->timeout_list) {
6681 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6684 if (io_is_timeout_noseq(nxt))
6686 /* nxt.seq is behind @tail, otherwise would've been completed */
6687 if (off >= nxt->timeout.target_seq - tail)
6691 list_add(&req->timeout.list, entry);
6692 data->timer.function = io_timeout_fn;
6693 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6694 spin_unlock_irq(&ctx->timeout_lock);
6698 struct io_cancel_data {
6699 struct io_ring_ctx *ctx;
6703 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6705 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6706 struct io_cancel_data *cd = data;
6708 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6711 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6712 struct io_ring_ctx *ctx)
6714 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6715 enum io_wq_cancel cancel_ret;
6718 if (!tctx || !tctx->io_wq)
6721 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6722 switch (cancel_ret) {
6723 case IO_WQ_CANCEL_OK:
6726 case IO_WQ_CANCEL_RUNNING:
6729 case IO_WQ_CANCEL_NOTFOUND:
6737 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6739 struct io_ring_ctx *ctx = req->ctx;
6742 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6744 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6746 * Fall-through even for -EALREADY, as we may have poll armed
6747 * that need unarming.
6752 spin_lock(&ctx->completion_lock);
6753 ret = io_poll_cancel(ctx, sqe_addr, false);
6757 spin_lock_irq(&ctx->timeout_lock);
6758 ret = io_timeout_cancel(ctx, sqe_addr);
6759 spin_unlock_irq(&ctx->timeout_lock);
6761 spin_unlock(&ctx->completion_lock);
6765 static int io_async_cancel_prep(struct io_kiocb *req,
6766 const struct io_uring_sqe *sqe)
6768 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6770 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6772 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6776 req->cancel.addr = READ_ONCE(sqe->addr);
6780 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6782 struct io_ring_ctx *ctx = req->ctx;
6783 u64 sqe_addr = req->cancel.addr;
6784 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6785 struct io_tctx_node *node;
6788 ret = io_try_cancel_userdata(req, sqe_addr);
6792 /* slow path, try all io-wq's */
6793 io_ring_submit_lock(ctx, needs_lock);
6795 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6796 struct io_uring_task *tctx = node->task->io_uring;
6798 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6802 io_ring_submit_unlock(ctx, needs_lock);
6806 io_req_complete_post(req, ret, 0);
6810 static int io_rsrc_update_prep(struct io_kiocb *req,
6811 const struct io_uring_sqe *sqe)
6813 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6815 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6818 req->rsrc_update.offset = READ_ONCE(sqe->off);
6819 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6820 if (!req->rsrc_update.nr_args)
6822 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6826 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6828 struct io_ring_ctx *ctx = req->ctx;
6829 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6830 struct io_uring_rsrc_update2 up;
6833 up.offset = req->rsrc_update.offset;
6834 up.data = req->rsrc_update.arg;
6839 io_ring_submit_lock(ctx, needs_lock);
6840 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6841 &up, req->rsrc_update.nr_args);
6842 io_ring_submit_unlock(ctx, needs_lock);
6846 __io_req_complete(req, issue_flags, ret, 0);
6850 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6852 switch (req->opcode) {
6855 case IORING_OP_READV:
6856 case IORING_OP_READ_FIXED:
6857 case IORING_OP_READ:
6858 case IORING_OP_WRITEV:
6859 case IORING_OP_WRITE_FIXED:
6860 case IORING_OP_WRITE:
6861 return io_prep_rw(req, sqe);
6862 case IORING_OP_POLL_ADD:
6863 return io_poll_add_prep(req, sqe);
6864 case IORING_OP_POLL_REMOVE:
6865 return io_poll_update_prep(req, sqe);
6866 case IORING_OP_FSYNC:
6867 return io_fsync_prep(req, sqe);
6868 case IORING_OP_SYNC_FILE_RANGE:
6869 return io_sfr_prep(req, sqe);
6870 case IORING_OP_SENDMSG:
6871 case IORING_OP_SEND:
6872 return io_sendmsg_prep(req, sqe);
6873 case IORING_OP_RECVMSG:
6874 case IORING_OP_RECV:
6875 return io_recvmsg_prep(req, sqe);
6876 case IORING_OP_CONNECT:
6877 return io_connect_prep(req, sqe);
6878 case IORING_OP_TIMEOUT:
6879 return io_timeout_prep(req, sqe, false);
6880 case IORING_OP_TIMEOUT_REMOVE:
6881 return io_timeout_remove_prep(req, sqe);
6882 case IORING_OP_ASYNC_CANCEL:
6883 return io_async_cancel_prep(req, sqe);
6884 case IORING_OP_LINK_TIMEOUT:
6885 return io_timeout_prep(req, sqe, true);
6886 case IORING_OP_ACCEPT:
6887 return io_accept_prep(req, sqe);
6888 case IORING_OP_FALLOCATE:
6889 return io_fallocate_prep(req, sqe);
6890 case IORING_OP_OPENAT:
6891 return io_openat_prep(req, sqe);
6892 case IORING_OP_CLOSE:
6893 return io_close_prep(req, sqe);
6894 case IORING_OP_FILES_UPDATE:
6895 return io_rsrc_update_prep(req, sqe);
6896 case IORING_OP_STATX:
6897 return io_statx_prep(req, sqe);
6898 case IORING_OP_FADVISE:
6899 return io_fadvise_prep(req, sqe);
6900 case IORING_OP_MADVISE:
6901 return io_madvise_prep(req, sqe);
6902 case IORING_OP_OPENAT2:
6903 return io_openat2_prep(req, sqe);
6904 case IORING_OP_EPOLL_CTL:
6905 return io_epoll_ctl_prep(req, sqe);
6906 case IORING_OP_SPLICE:
6907 return io_splice_prep(req, sqe);
6908 case IORING_OP_PROVIDE_BUFFERS:
6909 return io_provide_buffers_prep(req, sqe);
6910 case IORING_OP_REMOVE_BUFFERS:
6911 return io_remove_buffers_prep(req, sqe);
6913 return io_tee_prep(req, sqe);
6914 case IORING_OP_SHUTDOWN:
6915 return io_shutdown_prep(req, sqe);
6916 case IORING_OP_RENAMEAT:
6917 return io_renameat_prep(req, sqe);
6918 case IORING_OP_UNLINKAT:
6919 return io_unlinkat_prep(req, sqe);
6920 case IORING_OP_MKDIRAT:
6921 return io_mkdirat_prep(req, sqe);
6922 case IORING_OP_SYMLINKAT:
6923 return io_symlinkat_prep(req, sqe);
6924 case IORING_OP_LINKAT:
6925 return io_linkat_prep(req, sqe);
6926 case IORING_OP_MSG_RING:
6927 return io_msg_ring_prep(req, sqe);
6930 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6935 static int io_req_prep_async(struct io_kiocb *req)
6937 if (!io_op_defs[req->opcode].needs_async_setup)
6939 if (WARN_ON_ONCE(req_has_async_data(req)))
6941 if (io_alloc_async_data(req))
6944 switch (req->opcode) {
6945 case IORING_OP_READV:
6946 return io_rw_prep_async(req, READ);
6947 case IORING_OP_WRITEV:
6948 return io_rw_prep_async(req, WRITE);
6949 case IORING_OP_SENDMSG:
6950 return io_sendmsg_prep_async(req);
6951 case IORING_OP_RECVMSG:
6952 return io_recvmsg_prep_async(req);
6953 case IORING_OP_CONNECT:
6954 return io_connect_prep_async(req);
6956 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6961 static u32 io_get_sequence(struct io_kiocb *req)
6963 u32 seq = req->ctx->cached_sq_head;
6965 /* need original cached_sq_head, but it was increased for each req */
6966 io_for_each_link(req, req)
6971 static __cold void io_drain_req(struct io_kiocb *req)
6973 struct io_ring_ctx *ctx = req->ctx;
6974 struct io_defer_entry *de;
6976 u32 seq = io_get_sequence(req);
6978 /* Still need defer if there is pending req in defer list. */
6979 spin_lock(&ctx->completion_lock);
6980 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6981 spin_unlock(&ctx->completion_lock);
6983 ctx->drain_active = false;
6984 io_req_task_queue(req);
6987 spin_unlock(&ctx->completion_lock);
6989 ret = io_req_prep_async(req);
6992 io_req_complete_failed(req, ret);
6995 io_prep_async_link(req);
6996 de = kmalloc(sizeof(*de), GFP_KERNEL);
7002 spin_lock(&ctx->completion_lock);
7003 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7004 spin_unlock(&ctx->completion_lock);
7009 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7012 list_add_tail(&de->list, &ctx->defer_list);
7013 spin_unlock(&ctx->completion_lock);
7016 static void io_clean_op(struct io_kiocb *req)
7018 if (req->flags & REQ_F_BUFFER_SELECTED) {
7019 spin_lock(&req->ctx->completion_lock);
7020 io_put_kbuf_comp(req);
7021 spin_unlock(&req->ctx->completion_lock);
7024 if (req->flags & REQ_F_NEED_CLEANUP) {
7025 switch (req->opcode) {
7026 case IORING_OP_READV:
7027 case IORING_OP_READ_FIXED:
7028 case IORING_OP_READ:
7029 case IORING_OP_WRITEV:
7030 case IORING_OP_WRITE_FIXED:
7031 case IORING_OP_WRITE: {
7032 struct io_async_rw *io = req->async_data;
7034 kfree(io->free_iovec);
7037 case IORING_OP_RECVMSG:
7038 case IORING_OP_SENDMSG: {
7039 struct io_async_msghdr *io = req->async_data;
7041 kfree(io->free_iov);
7044 case IORING_OP_OPENAT:
7045 case IORING_OP_OPENAT2:
7046 if (req->open.filename)
7047 putname(req->open.filename);
7049 case IORING_OP_RENAMEAT:
7050 putname(req->rename.oldpath);
7051 putname(req->rename.newpath);
7053 case IORING_OP_UNLINKAT:
7054 putname(req->unlink.filename);
7056 case IORING_OP_MKDIRAT:
7057 putname(req->mkdir.filename);
7059 case IORING_OP_SYMLINKAT:
7060 putname(req->symlink.oldpath);
7061 putname(req->symlink.newpath);
7063 case IORING_OP_LINKAT:
7064 putname(req->hardlink.oldpath);
7065 putname(req->hardlink.newpath);
7067 case IORING_OP_STATX:
7068 if (req->statx.filename)
7069 putname(req->statx.filename);
7073 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7074 kfree(req->apoll->double_poll);
7078 if (req->flags & REQ_F_CREDS)
7079 put_cred(req->creds);
7080 if (req->flags & REQ_F_ASYNC_DATA) {
7081 kfree(req->async_data);
7082 req->async_data = NULL;
7084 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7087 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
7089 if (req->file || !io_op_defs[req->opcode].needs_file)
7092 if (req->flags & REQ_F_FIXED_FILE)
7093 req->file = io_file_get_fixed(req, req->work.fd, issue_flags);
7095 req->file = io_file_get_normal(req, req->work.fd);
7100 req->result = -EBADF;
7104 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7106 const struct cred *creds = NULL;
7109 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7110 creds = override_creds(req->creds);
7112 if (!io_op_defs[req->opcode].audit_skip)
7113 audit_uring_entry(req->opcode);
7114 if (unlikely(!io_assign_file(req, issue_flags)))
7117 switch (req->opcode) {
7119 ret = io_nop(req, issue_flags);
7121 case IORING_OP_READV:
7122 case IORING_OP_READ_FIXED:
7123 case IORING_OP_READ:
7124 ret = io_read(req, issue_flags);
7126 case IORING_OP_WRITEV:
7127 case IORING_OP_WRITE_FIXED:
7128 case IORING_OP_WRITE:
7129 ret = io_write(req, issue_flags);
7131 case IORING_OP_FSYNC:
7132 ret = io_fsync(req, issue_flags);
7134 case IORING_OP_POLL_ADD:
7135 ret = io_poll_add(req, issue_flags);
7137 case IORING_OP_POLL_REMOVE:
7138 ret = io_poll_update(req, issue_flags);
7140 case IORING_OP_SYNC_FILE_RANGE:
7141 ret = io_sync_file_range(req, issue_flags);
7143 case IORING_OP_SENDMSG:
7144 ret = io_sendmsg(req, issue_flags);
7146 case IORING_OP_SEND:
7147 ret = io_send(req, issue_flags);
7149 case IORING_OP_RECVMSG:
7150 ret = io_recvmsg(req, issue_flags);
7152 case IORING_OP_RECV:
7153 ret = io_recv(req, issue_flags);
7155 case IORING_OP_TIMEOUT:
7156 ret = io_timeout(req, issue_flags);
7158 case IORING_OP_TIMEOUT_REMOVE:
7159 ret = io_timeout_remove(req, issue_flags);
7161 case IORING_OP_ACCEPT:
7162 ret = io_accept(req, issue_flags);
7164 case IORING_OP_CONNECT:
7165 ret = io_connect(req, issue_flags);
7167 case IORING_OP_ASYNC_CANCEL:
7168 ret = io_async_cancel(req, issue_flags);
7170 case IORING_OP_FALLOCATE:
7171 ret = io_fallocate(req, issue_flags);
7173 case IORING_OP_OPENAT:
7174 ret = io_openat(req, issue_flags);
7176 case IORING_OP_CLOSE:
7177 ret = io_close(req, issue_flags);
7179 case IORING_OP_FILES_UPDATE:
7180 ret = io_files_update(req, issue_flags);
7182 case IORING_OP_STATX:
7183 ret = io_statx(req, issue_flags);
7185 case IORING_OP_FADVISE:
7186 ret = io_fadvise(req, issue_flags);
7188 case IORING_OP_MADVISE:
7189 ret = io_madvise(req, issue_flags);
7191 case IORING_OP_OPENAT2:
7192 ret = io_openat2(req, issue_flags);
7194 case IORING_OP_EPOLL_CTL:
7195 ret = io_epoll_ctl(req, issue_flags);
7197 case IORING_OP_SPLICE:
7198 ret = io_splice(req, issue_flags);
7200 case IORING_OP_PROVIDE_BUFFERS:
7201 ret = io_provide_buffers(req, issue_flags);
7203 case IORING_OP_REMOVE_BUFFERS:
7204 ret = io_remove_buffers(req, issue_flags);
7207 ret = io_tee(req, issue_flags);
7209 case IORING_OP_SHUTDOWN:
7210 ret = io_shutdown(req, issue_flags);
7212 case IORING_OP_RENAMEAT:
7213 ret = io_renameat(req, issue_flags);
7215 case IORING_OP_UNLINKAT:
7216 ret = io_unlinkat(req, issue_flags);
7218 case IORING_OP_MKDIRAT:
7219 ret = io_mkdirat(req, issue_flags);
7221 case IORING_OP_SYMLINKAT:
7222 ret = io_symlinkat(req, issue_flags);
7224 case IORING_OP_LINKAT:
7225 ret = io_linkat(req, issue_flags);
7227 case IORING_OP_MSG_RING:
7228 ret = io_msg_ring(req, issue_flags);
7235 if (!io_op_defs[req->opcode].audit_skip)
7236 audit_uring_exit(!ret, ret);
7239 revert_creds(creds);
7242 /* If the op doesn't have a file, we're not polling for it */
7243 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7244 io_iopoll_req_issued(req, issue_flags);
7249 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7251 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7253 req = io_put_req_find_next(req);
7254 return req ? &req->work : NULL;
7257 static void io_wq_submit_work(struct io_wq_work *work)
7259 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7260 const struct io_op_def *def = &io_op_defs[req->opcode];
7261 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7262 bool needs_poll = false;
7263 struct io_kiocb *timeout;
7264 int ret = 0, err = -ECANCELED;
7266 /* one will be dropped by ->io_free_work() after returning to io-wq */
7267 if (!(req->flags & REQ_F_REFCOUNT))
7268 __io_req_set_refcount(req, 2);
7272 timeout = io_prep_linked_timeout(req);
7274 io_queue_linked_timeout(timeout);
7276 if (!io_assign_file(req, issue_flags)) {
7278 work->flags |= IO_WQ_WORK_CANCEL;
7281 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7282 if (work->flags & IO_WQ_WORK_CANCEL) {
7283 io_req_task_queue_fail(req, err);
7287 if (req->flags & REQ_F_FORCE_ASYNC) {
7288 bool opcode_poll = def->pollin || def->pollout;
7290 if (opcode_poll && file_can_poll(req->file)) {
7292 issue_flags |= IO_URING_F_NONBLOCK;
7297 ret = io_issue_sqe(req, issue_flags);
7301 * We can get EAGAIN for iopolled IO even though we're
7302 * forcing a sync submission from here, since we can't
7303 * wait for request slots on the block side.
7310 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7312 /* aborted or ready, in either case retry blocking */
7314 issue_flags &= ~IO_URING_F_NONBLOCK;
7317 /* avoid locking problems by failing it from a clean context */
7319 io_req_task_queue_fail(req, ret);
7322 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7325 return &table->files[i];
7328 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7331 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7333 return (struct file *) (slot->file_ptr & FFS_MASK);
7336 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7338 unsigned long file_ptr = (unsigned long) file;
7340 file_ptr |= io_file_get_flags(file);
7341 file_slot->file_ptr = file_ptr;
7344 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
7345 unsigned int issue_flags)
7347 struct io_ring_ctx *ctx = req->ctx;
7348 struct file *file = NULL;
7349 unsigned long file_ptr;
7351 if (issue_flags & IO_URING_F_UNLOCKED)
7352 mutex_lock(&ctx->uring_lock);
7354 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7356 fd = array_index_nospec(fd, ctx->nr_user_files);
7357 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7358 file = (struct file *) (file_ptr & FFS_MASK);
7359 file_ptr &= ~FFS_MASK;
7360 /* mask in overlapping REQ_F and FFS bits */
7361 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7362 io_req_set_rsrc_node(req, ctx, 0);
7364 if (issue_flags & IO_URING_F_UNLOCKED)
7365 mutex_unlock(&ctx->uring_lock);
7370 * Drop the file for requeue operations. Only used of req->file is the
7371 * io_uring descriptor itself.
7373 static void io_drop_inflight_file(struct io_kiocb *req)
7375 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
7378 req->flags &= ~REQ_F_INFLIGHT;
7382 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
7384 struct file *file = fget(fd);
7386 trace_io_uring_file_get(req->ctx, req, req->user_data, fd);
7388 /* we don't allow fixed io_uring files */
7389 if (file && file->f_op == &io_uring_fops)
7390 req->flags |= REQ_F_INFLIGHT;
7394 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7396 struct io_kiocb *prev = req->timeout.prev;
7400 if (!(req->task->flags & PF_EXITING))
7401 ret = io_try_cancel_userdata(req, prev->user_data);
7402 io_req_complete_post(req, ret ?: -ETIME, 0);
7405 io_req_complete_post(req, -ETIME, 0);
7409 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7411 struct io_timeout_data *data = container_of(timer,
7412 struct io_timeout_data, timer);
7413 struct io_kiocb *prev, *req = data->req;
7414 struct io_ring_ctx *ctx = req->ctx;
7415 unsigned long flags;
7417 spin_lock_irqsave(&ctx->timeout_lock, flags);
7418 prev = req->timeout.head;
7419 req->timeout.head = NULL;
7422 * We don't expect the list to be empty, that will only happen if we
7423 * race with the completion of the linked work.
7426 io_remove_next_linked(prev);
7427 if (!req_ref_inc_not_zero(prev))
7430 list_del(&req->timeout.list);
7431 req->timeout.prev = prev;
7432 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7434 req->io_task_work.func = io_req_task_link_timeout;
7435 io_req_task_work_add(req, false);
7436 return HRTIMER_NORESTART;
7439 static void io_queue_linked_timeout(struct io_kiocb *req)
7441 struct io_ring_ctx *ctx = req->ctx;
7443 spin_lock_irq(&ctx->timeout_lock);
7445 * If the back reference is NULL, then our linked request finished
7446 * before we got a chance to setup the timer
7448 if (req->timeout.head) {
7449 struct io_timeout_data *data = req->async_data;
7451 data->timer.function = io_link_timeout_fn;
7452 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7454 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7456 spin_unlock_irq(&ctx->timeout_lock);
7457 /* drop submission reference */
7461 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7462 __must_hold(&req->ctx->uring_lock)
7464 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7466 switch (io_arm_poll_handler(req, 0)) {
7467 case IO_APOLL_READY:
7468 io_req_task_queue(req);
7470 case IO_APOLL_ABORTED:
7472 * Queued up for async execution, worker will release
7473 * submit reference when the iocb is actually submitted.
7475 io_queue_async_work(req, NULL);
7482 io_queue_linked_timeout(linked_timeout);
7485 static inline void __io_queue_sqe(struct io_kiocb *req)
7486 __must_hold(&req->ctx->uring_lock)
7488 struct io_kiocb *linked_timeout;
7491 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7493 if (req->flags & REQ_F_COMPLETE_INLINE) {
7494 io_req_add_compl_list(req);
7498 * We async punt it if the file wasn't marked NOWAIT, or if the file
7499 * doesn't support non-blocking read/write attempts
7502 linked_timeout = io_prep_linked_timeout(req);
7504 io_queue_linked_timeout(linked_timeout);
7505 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7506 io_queue_sqe_arm_apoll(req);
7508 io_req_complete_failed(req, ret);
7512 static void io_queue_sqe_fallback(struct io_kiocb *req)
7513 __must_hold(&req->ctx->uring_lock)
7515 if (req->flags & REQ_F_FAIL) {
7516 io_req_complete_fail_submit(req);
7517 } else if (unlikely(req->ctx->drain_active)) {
7520 int ret = io_req_prep_async(req);
7523 io_req_complete_failed(req, ret);
7525 io_queue_async_work(req, NULL);
7529 static inline void io_queue_sqe(struct io_kiocb *req)
7530 __must_hold(&req->ctx->uring_lock)
7532 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7533 __io_queue_sqe(req);
7535 io_queue_sqe_fallback(req);
7539 * Check SQE restrictions (opcode and flags).
7541 * Returns 'true' if SQE is allowed, 'false' otherwise.
7543 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7544 struct io_kiocb *req,
7545 unsigned int sqe_flags)
7547 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7550 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7551 ctx->restrictions.sqe_flags_required)
7554 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7555 ctx->restrictions.sqe_flags_required))
7561 static void io_init_req_drain(struct io_kiocb *req)
7563 struct io_ring_ctx *ctx = req->ctx;
7564 struct io_kiocb *head = ctx->submit_state.link.head;
7566 ctx->drain_active = true;
7569 * If we need to drain a request in the middle of a link, drain
7570 * the head request and the next request/link after the current
7571 * link. Considering sequential execution of links,
7572 * REQ_F_IO_DRAIN will be maintained for every request of our
7575 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7576 ctx->drain_next = true;
7580 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7581 const struct io_uring_sqe *sqe)
7582 __must_hold(&ctx->uring_lock)
7584 unsigned int sqe_flags;
7588 /* req is partially pre-initialised, see io_preinit_req() */
7589 req->opcode = opcode = READ_ONCE(sqe->opcode);
7590 /* same numerical values with corresponding REQ_F_*, safe to copy */
7591 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7592 req->user_data = READ_ONCE(sqe->user_data);
7594 req->fixed_rsrc_refs = NULL;
7595 req->task = current;
7597 if (unlikely(opcode >= IORING_OP_LAST)) {
7601 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7602 /* enforce forwards compatibility on users */
7603 if (sqe_flags & ~SQE_VALID_FLAGS)
7605 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7606 !io_op_defs[opcode].buffer_select)
7608 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7609 ctx->drain_disabled = true;
7610 if (sqe_flags & IOSQE_IO_DRAIN) {
7611 if (ctx->drain_disabled)
7613 io_init_req_drain(req);
7616 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7617 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7619 /* knock it to the slow queue path, will be drained there */
7620 if (ctx->drain_active)
7621 req->flags |= REQ_F_FORCE_ASYNC;
7622 /* if there is no link, we're at "next" request and need to drain */
7623 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7624 ctx->drain_next = false;
7625 ctx->drain_active = true;
7626 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7630 if (io_op_defs[opcode].needs_file) {
7631 struct io_submit_state *state = &ctx->submit_state;
7633 req->work.fd = READ_ONCE(sqe->fd);
7636 * Plug now if we have more than 2 IO left after this, and the
7637 * target is potentially a read/write to block based storage.
7639 if (state->need_plug && io_op_defs[opcode].plug) {
7640 state->plug_started = true;
7641 state->need_plug = false;
7642 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7646 personality = READ_ONCE(sqe->personality);
7650 req->creds = xa_load(&ctx->personalities, personality);
7653 get_cred(req->creds);
7654 ret = security_uring_override_creds(req->creds);
7656 put_cred(req->creds);
7659 req->flags |= REQ_F_CREDS;
7662 return io_req_prep(req, sqe);
7665 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7666 const struct io_uring_sqe *sqe)
7667 __must_hold(&ctx->uring_lock)
7669 struct io_submit_link *link = &ctx->submit_state.link;
7672 ret = io_init_req(ctx, req, sqe);
7673 if (unlikely(ret)) {
7674 trace_io_uring_req_failed(sqe, ctx, req, ret);
7676 /* fail even hard links since we don't submit */
7679 * we can judge a link req is failed or cancelled by if
7680 * REQ_F_FAIL is set, but the head is an exception since
7681 * it may be set REQ_F_FAIL because of other req's failure
7682 * so let's leverage req->result to distinguish if a head
7683 * is set REQ_F_FAIL because of its failure or other req's
7684 * failure so that we can set the correct ret code for it.
7685 * init result here to avoid affecting the normal path.
7687 if (!(link->head->flags & REQ_F_FAIL))
7688 req_fail_link_node(link->head, -ECANCELED);
7689 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7691 * the current req is a normal req, we should return
7692 * error and thus break the submittion loop.
7694 io_req_complete_failed(req, ret);
7697 req_fail_link_node(req, ret);
7700 /* don't need @sqe from now on */
7701 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7703 ctx->flags & IORING_SETUP_SQPOLL);
7706 * If we already have a head request, queue this one for async
7707 * submittal once the head completes. If we don't have a head but
7708 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7709 * submitted sync once the chain is complete. If none of those
7710 * conditions are true (normal request), then just queue it.
7713 struct io_kiocb *head = link->head;
7715 if (!(req->flags & REQ_F_FAIL)) {
7716 ret = io_req_prep_async(req);
7717 if (unlikely(ret)) {
7718 req_fail_link_node(req, ret);
7719 if (!(head->flags & REQ_F_FAIL))
7720 req_fail_link_node(head, -ECANCELED);
7723 trace_io_uring_link(ctx, req, head);
7724 link->last->link = req;
7727 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7729 /* last request of a link, enqueue the link */
7732 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7743 * Batched submission is done, ensure local IO is flushed out.
7745 static void io_submit_state_end(struct io_ring_ctx *ctx)
7747 struct io_submit_state *state = &ctx->submit_state;
7749 if (state->link.head)
7750 io_queue_sqe(state->link.head);
7751 /* flush only after queuing links as they can generate completions */
7752 io_submit_flush_completions(ctx);
7753 if (state->plug_started)
7754 blk_finish_plug(&state->plug);
7758 * Start submission side cache.
7760 static void io_submit_state_start(struct io_submit_state *state,
7761 unsigned int max_ios)
7763 state->plug_started = false;
7764 state->need_plug = max_ios > 2;
7765 state->submit_nr = max_ios;
7766 /* set only head, no need to init link_last in advance */
7767 state->link.head = NULL;
7770 static void io_commit_sqring(struct io_ring_ctx *ctx)
7772 struct io_rings *rings = ctx->rings;
7775 * Ensure any loads from the SQEs are done at this point,
7776 * since once we write the new head, the application could
7777 * write new data to them.
7779 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7783 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7784 * that is mapped by userspace. This means that care needs to be taken to
7785 * ensure that reads are stable, as we cannot rely on userspace always
7786 * being a good citizen. If members of the sqe are validated and then later
7787 * used, it's important that those reads are done through READ_ONCE() to
7788 * prevent a re-load down the line.
7790 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7792 unsigned head, mask = ctx->sq_entries - 1;
7793 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7796 * The cached sq head (or cq tail) serves two purposes:
7798 * 1) allows us to batch the cost of updating the user visible
7800 * 2) allows the kernel side to track the head on its own, even
7801 * though the application is the one updating it.
7803 head = READ_ONCE(ctx->sq_array[sq_idx]);
7804 if (likely(head < ctx->sq_entries))
7805 return &ctx->sq_sqes[head];
7807 /* drop invalid entries */
7809 WRITE_ONCE(ctx->rings->sq_dropped,
7810 READ_ONCE(ctx->rings->sq_dropped) + 1);
7814 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7815 __must_hold(&ctx->uring_lock)
7817 unsigned int entries = io_sqring_entries(ctx);
7820 if (unlikely(!entries))
7822 /* make sure SQ entry isn't read before tail */
7823 nr = min3(nr, ctx->sq_entries, entries);
7824 io_get_task_refs(nr);
7826 io_submit_state_start(&ctx->submit_state, nr);
7828 const struct io_uring_sqe *sqe;
7829 struct io_kiocb *req;
7831 if (unlikely(!io_alloc_req_refill(ctx))) {
7833 submitted = -EAGAIN;
7836 req = io_alloc_req(ctx);
7837 sqe = io_get_sqe(ctx);
7838 if (unlikely(!sqe)) {
7839 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7842 /* will complete beyond this point, count as submitted */
7844 if (io_submit_sqe(ctx, req, sqe)) {
7846 * Continue submitting even for sqe failure if the
7847 * ring was setup with IORING_SETUP_SUBMIT_ALL
7849 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7852 } while (submitted < nr);
7854 if (unlikely(submitted != nr)) {
7855 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7856 int unused = nr - ref_used;
7858 current->io_uring->cached_refs += unused;
7861 io_submit_state_end(ctx);
7862 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7863 io_commit_sqring(ctx);
7868 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7870 return READ_ONCE(sqd->state);
7873 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7875 /* Tell userspace we may need a wakeup call */
7876 spin_lock(&ctx->completion_lock);
7877 WRITE_ONCE(ctx->rings->sq_flags,
7878 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7879 spin_unlock(&ctx->completion_lock);
7882 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7884 spin_lock(&ctx->completion_lock);
7885 WRITE_ONCE(ctx->rings->sq_flags,
7886 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7887 spin_unlock(&ctx->completion_lock);
7890 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7892 unsigned int to_submit;
7895 to_submit = io_sqring_entries(ctx);
7896 /* if we're handling multiple rings, cap submit size for fairness */
7897 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7898 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7900 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7901 const struct cred *creds = NULL;
7903 if (ctx->sq_creds != current_cred())
7904 creds = override_creds(ctx->sq_creds);
7906 mutex_lock(&ctx->uring_lock);
7907 if (!wq_list_empty(&ctx->iopoll_list))
7908 io_do_iopoll(ctx, true);
7911 * Don't submit if refs are dying, good for io_uring_register(),
7912 * but also it is relied upon by io_ring_exit_work()
7914 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7915 !(ctx->flags & IORING_SETUP_R_DISABLED))
7916 ret = io_submit_sqes(ctx, to_submit);
7917 mutex_unlock(&ctx->uring_lock);
7919 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7920 wake_up(&ctx->sqo_sq_wait);
7922 revert_creds(creds);
7928 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7930 struct io_ring_ctx *ctx;
7931 unsigned sq_thread_idle = 0;
7933 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7934 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7935 sqd->sq_thread_idle = sq_thread_idle;
7938 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7940 bool did_sig = false;
7941 struct ksignal ksig;
7943 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7944 signal_pending(current)) {
7945 mutex_unlock(&sqd->lock);
7946 if (signal_pending(current))
7947 did_sig = get_signal(&ksig);
7949 mutex_lock(&sqd->lock);
7951 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7954 static int io_sq_thread(void *data)
7956 struct io_sq_data *sqd = data;
7957 struct io_ring_ctx *ctx;
7958 unsigned long timeout = 0;
7959 char buf[TASK_COMM_LEN];
7962 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7963 set_task_comm(current, buf);
7965 if (sqd->sq_cpu != -1)
7966 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7968 set_cpus_allowed_ptr(current, cpu_online_mask);
7969 current->flags |= PF_NO_SETAFFINITY;
7971 audit_alloc_kernel(current);
7973 mutex_lock(&sqd->lock);
7975 bool cap_entries, sqt_spin = false;
7977 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7978 if (io_sqd_handle_event(sqd))
7980 timeout = jiffies + sqd->sq_thread_idle;
7983 cap_entries = !list_is_singular(&sqd->ctx_list);
7984 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7985 int ret = __io_sq_thread(ctx, cap_entries);
7987 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7990 if (io_run_task_work())
7993 if (sqt_spin || !time_after(jiffies, timeout)) {
7996 timeout = jiffies + sqd->sq_thread_idle;
8000 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8001 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8002 bool needs_sched = true;
8004 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8005 io_ring_set_wakeup_flag(ctx);
8007 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8008 !wq_list_empty(&ctx->iopoll_list)) {
8009 needs_sched = false;
8014 * Ensure the store of the wakeup flag is not
8015 * reordered with the load of the SQ tail
8019 if (io_sqring_entries(ctx)) {
8020 needs_sched = false;
8026 mutex_unlock(&sqd->lock);
8028 mutex_lock(&sqd->lock);
8030 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8031 io_ring_clear_wakeup_flag(ctx);
8034 finish_wait(&sqd->wait, &wait);
8035 timeout = jiffies + sqd->sq_thread_idle;
8038 io_uring_cancel_generic(true, sqd);
8040 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8041 io_ring_set_wakeup_flag(ctx);
8043 mutex_unlock(&sqd->lock);
8045 audit_free(current);
8047 complete(&sqd->exited);
8051 struct io_wait_queue {
8052 struct wait_queue_entry wq;
8053 struct io_ring_ctx *ctx;
8055 unsigned nr_timeouts;
8058 static inline bool io_should_wake(struct io_wait_queue *iowq)
8060 struct io_ring_ctx *ctx = iowq->ctx;
8061 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8064 * Wake up if we have enough events, or if a timeout occurred since we
8065 * started waiting. For timeouts, we always want to return to userspace,
8066 * regardless of event count.
8068 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8071 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8072 int wake_flags, void *key)
8074 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8078 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8079 * the task, and the next invocation will do it.
8081 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8082 return autoremove_wake_function(curr, mode, wake_flags, key);
8086 static int io_run_task_work_sig(void)
8088 if (io_run_task_work())
8090 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8091 return -ERESTARTSYS;
8092 if (task_sigpending(current))
8097 /* when returns >0, the caller should retry */
8098 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8099 struct io_wait_queue *iowq,
8104 /* make sure we run task_work before checking for signals */
8105 ret = io_run_task_work_sig();
8106 if (ret || io_should_wake(iowq))
8108 /* let the caller flush overflows, retry */
8109 if (test_bit(0, &ctx->check_cq_overflow))
8112 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8118 * Wait until events become available, if we don't already have some. The
8119 * application must reap them itself, as they reside on the shared cq ring.
8121 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8122 const sigset_t __user *sig, size_t sigsz,
8123 struct __kernel_timespec __user *uts)
8125 struct io_wait_queue iowq;
8126 struct io_rings *rings = ctx->rings;
8127 ktime_t timeout = KTIME_MAX;
8131 io_cqring_overflow_flush(ctx);
8132 if (io_cqring_events(ctx) >= min_events)
8134 if (!io_run_task_work())
8139 #ifdef CONFIG_COMPAT
8140 if (in_compat_syscall())
8141 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8145 ret = set_user_sigmask(sig, sigsz);
8152 struct timespec64 ts;
8154 if (get_timespec64(&ts, uts))
8156 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8159 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8160 iowq.wq.private = current;
8161 INIT_LIST_HEAD(&iowq.wq.entry);
8163 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8164 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8166 trace_io_uring_cqring_wait(ctx, min_events);
8168 /* if we can't even flush overflow, don't wait for more */
8169 if (!io_cqring_overflow_flush(ctx)) {
8173 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8174 TASK_INTERRUPTIBLE);
8175 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8176 finish_wait(&ctx->cq_wait, &iowq.wq);
8180 restore_saved_sigmask_unless(ret == -EINTR);
8182 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8185 static void io_free_page_table(void **table, size_t size)
8187 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8189 for (i = 0; i < nr_tables; i++)
8194 static __cold void **io_alloc_page_table(size_t size)
8196 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8197 size_t init_size = size;
8200 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8204 for (i = 0; i < nr_tables; i++) {
8205 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8207 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8209 io_free_page_table(table, init_size);
8217 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8219 percpu_ref_exit(&ref_node->refs);
8223 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8225 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8226 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8227 unsigned long flags;
8228 bool first_add = false;
8229 unsigned long delay = HZ;
8231 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8234 /* if we are mid-quiesce then do not delay */
8235 if (node->rsrc_data->quiesce)
8238 while (!list_empty(&ctx->rsrc_ref_list)) {
8239 node = list_first_entry(&ctx->rsrc_ref_list,
8240 struct io_rsrc_node, node);
8241 /* recycle ref nodes in order */
8244 list_del(&node->node);
8245 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8247 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8250 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8253 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8255 struct io_rsrc_node *ref_node;
8257 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8261 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8266 INIT_LIST_HEAD(&ref_node->node);
8267 INIT_LIST_HEAD(&ref_node->rsrc_list);
8268 ref_node->done = false;
8272 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8273 struct io_rsrc_data *data_to_kill)
8274 __must_hold(&ctx->uring_lock)
8276 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8277 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8279 io_rsrc_refs_drop(ctx);
8282 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8284 rsrc_node->rsrc_data = data_to_kill;
8285 spin_lock_irq(&ctx->rsrc_ref_lock);
8286 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8287 spin_unlock_irq(&ctx->rsrc_ref_lock);
8289 atomic_inc(&data_to_kill->refs);
8290 percpu_ref_kill(&rsrc_node->refs);
8291 ctx->rsrc_node = NULL;
8294 if (!ctx->rsrc_node) {
8295 ctx->rsrc_node = ctx->rsrc_backup_node;
8296 ctx->rsrc_backup_node = NULL;
8300 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8302 if (ctx->rsrc_backup_node)
8304 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8305 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8308 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8309 struct io_ring_ctx *ctx)
8313 /* As we may drop ->uring_lock, other task may have started quiesce */
8317 data->quiesce = true;
8319 ret = io_rsrc_node_switch_start(ctx);
8322 io_rsrc_node_switch(ctx, data);
8324 /* kill initial ref, already quiesced if zero */
8325 if (atomic_dec_and_test(&data->refs))
8327 mutex_unlock(&ctx->uring_lock);
8328 flush_delayed_work(&ctx->rsrc_put_work);
8329 ret = wait_for_completion_interruptible(&data->done);
8331 mutex_lock(&ctx->uring_lock);
8332 if (atomic_read(&data->refs) > 0) {
8334 * it has been revived by another thread while
8337 mutex_unlock(&ctx->uring_lock);
8343 atomic_inc(&data->refs);
8344 /* wait for all works potentially completing data->done */
8345 flush_delayed_work(&ctx->rsrc_put_work);
8346 reinit_completion(&data->done);
8348 ret = io_run_task_work_sig();
8349 mutex_lock(&ctx->uring_lock);
8351 data->quiesce = false;
8356 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8358 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8359 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8361 return &data->tags[table_idx][off];
8364 static void io_rsrc_data_free(struct io_rsrc_data *data)
8366 size_t size = data->nr * sizeof(data->tags[0][0]);
8369 io_free_page_table((void **)data->tags, size);
8373 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8374 u64 __user *utags, unsigned nr,
8375 struct io_rsrc_data **pdata)
8377 struct io_rsrc_data *data;
8381 data = kzalloc(sizeof(*data), GFP_KERNEL);
8384 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8392 data->do_put = do_put;
8395 for (i = 0; i < nr; i++) {
8396 u64 *tag_slot = io_get_tag_slot(data, i);
8398 if (copy_from_user(tag_slot, &utags[i],
8404 atomic_set(&data->refs, 1);
8405 init_completion(&data->done);
8409 io_rsrc_data_free(data);
8413 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8415 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8416 GFP_KERNEL_ACCOUNT);
8417 return !!table->files;
8420 static void io_free_file_tables(struct io_file_table *table)
8422 kvfree(table->files);
8423 table->files = NULL;
8426 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8428 #if defined(CONFIG_UNIX)
8429 if (ctx->ring_sock) {
8430 struct sock *sock = ctx->ring_sock->sk;
8431 struct sk_buff *skb;
8433 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8439 for (i = 0; i < ctx->nr_user_files; i++) {
8442 file = io_file_from_index(ctx, i);
8447 io_free_file_tables(&ctx->file_table);
8448 io_rsrc_data_free(ctx->file_data);
8449 ctx->file_data = NULL;
8450 ctx->nr_user_files = 0;
8453 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8457 if (!ctx->file_data)
8459 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8461 __io_sqe_files_unregister(ctx);
8465 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8466 __releases(&sqd->lock)
8468 WARN_ON_ONCE(sqd->thread == current);
8471 * Do the dance but not conditional clear_bit() because it'd race with
8472 * other threads incrementing park_pending and setting the bit.
8474 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8475 if (atomic_dec_return(&sqd->park_pending))
8476 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8477 mutex_unlock(&sqd->lock);
8480 static void io_sq_thread_park(struct io_sq_data *sqd)
8481 __acquires(&sqd->lock)
8483 WARN_ON_ONCE(sqd->thread == current);
8485 atomic_inc(&sqd->park_pending);
8486 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8487 mutex_lock(&sqd->lock);
8489 wake_up_process(sqd->thread);
8492 static void io_sq_thread_stop(struct io_sq_data *sqd)
8494 WARN_ON_ONCE(sqd->thread == current);
8495 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8497 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8498 mutex_lock(&sqd->lock);
8500 wake_up_process(sqd->thread);
8501 mutex_unlock(&sqd->lock);
8502 wait_for_completion(&sqd->exited);
8505 static void io_put_sq_data(struct io_sq_data *sqd)
8507 if (refcount_dec_and_test(&sqd->refs)) {
8508 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8510 io_sq_thread_stop(sqd);
8515 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8517 struct io_sq_data *sqd = ctx->sq_data;
8520 io_sq_thread_park(sqd);
8521 list_del_init(&ctx->sqd_list);
8522 io_sqd_update_thread_idle(sqd);
8523 io_sq_thread_unpark(sqd);
8525 io_put_sq_data(sqd);
8526 ctx->sq_data = NULL;
8530 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8532 struct io_ring_ctx *ctx_attach;
8533 struct io_sq_data *sqd;
8536 f = fdget(p->wq_fd);
8538 return ERR_PTR(-ENXIO);
8539 if (f.file->f_op != &io_uring_fops) {
8541 return ERR_PTR(-EINVAL);
8544 ctx_attach = f.file->private_data;
8545 sqd = ctx_attach->sq_data;
8548 return ERR_PTR(-EINVAL);
8550 if (sqd->task_tgid != current->tgid) {
8552 return ERR_PTR(-EPERM);
8555 refcount_inc(&sqd->refs);
8560 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8563 struct io_sq_data *sqd;
8566 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8567 sqd = io_attach_sq_data(p);
8572 /* fall through for EPERM case, setup new sqd/task */
8573 if (PTR_ERR(sqd) != -EPERM)
8577 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8579 return ERR_PTR(-ENOMEM);
8581 atomic_set(&sqd->park_pending, 0);
8582 refcount_set(&sqd->refs, 1);
8583 INIT_LIST_HEAD(&sqd->ctx_list);
8584 mutex_init(&sqd->lock);
8585 init_waitqueue_head(&sqd->wait);
8586 init_completion(&sqd->exited);
8590 #if defined(CONFIG_UNIX)
8592 * Ensure the UNIX gc is aware of our file set, so we are certain that
8593 * the io_uring can be safely unregistered on process exit, even if we have
8594 * loops in the file referencing.
8596 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8598 struct sock *sk = ctx->ring_sock->sk;
8599 struct scm_fp_list *fpl;
8600 struct sk_buff *skb;
8603 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8607 skb = alloc_skb(0, GFP_KERNEL);
8616 fpl->user = get_uid(current_user());
8617 for (i = 0; i < nr; i++) {
8618 struct file *file = io_file_from_index(ctx, i + offset);
8622 fpl->fp[nr_files] = get_file(file);
8623 unix_inflight(fpl->user, fpl->fp[nr_files]);
8628 fpl->max = SCM_MAX_FD;
8629 fpl->count = nr_files;
8630 UNIXCB(skb).fp = fpl;
8631 skb->destructor = unix_destruct_scm;
8632 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8633 skb_queue_head(&sk->sk_receive_queue, skb);
8635 for (i = 0; i < nr; i++) {
8636 struct file *file = io_file_from_index(ctx, i + offset);
8643 free_uid(fpl->user);
8651 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8652 * causes regular reference counting to break down. We rely on the UNIX
8653 * garbage collection to take care of this problem for us.
8655 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8657 unsigned left, total;
8661 left = ctx->nr_user_files;
8663 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8665 ret = __io_sqe_files_scm(ctx, this_files, total);
8669 total += this_files;
8675 while (total < ctx->nr_user_files) {
8676 struct file *file = io_file_from_index(ctx, total);
8686 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8692 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8694 struct file *file = prsrc->file;
8695 #if defined(CONFIG_UNIX)
8696 struct sock *sock = ctx->ring_sock->sk;
8697 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8698 struct sk_buff *skb;
8701 __skb_queue_head_init(&list);
8704 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8705 * remove this entry and rearrange the file array.
8707 skb = skb_dequeue(head);
8709 struct scm_fp_list *fp;
8711 fp = UNIXCB(skb).fp;
8712 for (i = 0; i < fp->count; i++) {
8715 if (fp->fp[i] != file)
8718 unix_notinflight(fp->user, fp->fp[i]);
8719 left = fp->count - 1 - i;
8721 memmove(&fp->fp[i], &fp->fp[i + 1],
8722 left * sizeof(struct file *));
8729 __skb_queue_tail(&list, skb);
8739 __skb_queue_tail(&list, skb);
8741 skb = skb_dequeue(head);
8744 if (skb_peek(&list)) {
8745 spin_lock_irq(&head->lock);
8746 while ((skb = __skb_dequeue(&list)) != NULL)
8747 __skb_queue_tail(head, skb);
8748 spin_unlock_irq(&head->lock);
8755 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8757 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8758 struct io_ring_ctx *ctx = rsrc_data->ctx;
8759 struct io_rsrc_put *prsrc, *tmp;
8761 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8762 list_del(&prsrc->list);
8765 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8767 io_ring_submit_lock(ctx, lock_ring);
8768 spin_lock(&ctx->completion_lock);
8769 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8770 io_commit_cqring(ctx);
8771 spin_unlock(&ctx->completion_lock);
8772 io_cqring_ev_posted(ctx);
8773 io_ring_submit_unlock(ctx, lock_ring);
8776 rsrc_data->do_put(ctx, prsrc);
8780 io_rsrc_node_destroy(ref_node);
8781 if (atomic_dec_and_test(&rsrc_data->refs))
8782 complete(&rsrc_data->done);
8785 static void io_rsrc_put_work(struct work_struct *work)
8787 struct io_ring_ctx *ctx;
8788 struct llist_node *node;
8790 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8791 node = llist_del_all(&ctx->rsrc_put_llist);
8794 struct io_rsrc_node *ref_node;
8795 struct llist_node *next = node->next;
8797 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8798 __io_rsrc_put_work(ref_node);
8803 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8804 unsigned nr_args, u64 __user *tags)
8806 __s32 __user *fds = (__s32 __user *) arg;
8815 if (nr_args > IORING_MAX_FIXED_FILES)
8817 if (nr_args > rlimit(RLIMIT_NOFILE))
8819 ret = io_rsrc_node_switch_start(ctx);
8822 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8828 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8831 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8832 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8836 /* allow sparse sets */
8839 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8846 if (unlikely(!file))
8850 * Don't allow io_uring instances to be registered. If UNIX
8851 * isn't enabled, then this causes a reference cycle and this
8852 * instance can never get freed. If UNIX is enabled we'll
8853 * handle it just fine, but there's still no point in allowing
8854 * a ring fd as it doesn't support regular read/write anyway.
8856 if (file->f_op == &io_uring_fops) {
8860 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8863 ret = io_sqe_files_scm(ctx);
8865 __io_sqe_files_unregister(ctx);
8869 io_rsrc_node_switch(ctx, NULL);
8872 for (i = 0; i < ctx->nr_user_files; i++) {
8873 file = io_file_from_index(ctx, i);
8877 io_free_file_tables(&ctx->file_table);
8878 ctx->nr_user_files = 0;
8880 io_rsrc_data_free(ctx->file_data);
8881 ctx->file_data = NULL;
8885 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8888 #if defined(CONFIG_UNIX)
8889 struct sock *sock = ctx->ring_sock->sk;
8890 struct sk_buff_head *head = &sock->sk_receive_queue;
8891 struct sk_buff *skb;
8894 * See if we can merge this file into an existing skb SCM_RIGHTS
8895 * file set. If there's no room, fall back to allocating a new skb
8896 * and filling it in.
8898 spin_lock_irq(&head->lock);
8899 skb = skb_peek(head);
8901 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8903 if (fpl->count < SCM_MAX_FD) {
8904 __skb_unlink(skb, head);
8905 spin_unlock_irq(&head->lock);
8906 fpl->fp[fpl->count] = get_file(file);
8907 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8909 spin_lock_irq(&head->lock);
8910 __skb_queue_head(head, skb);
8915 spin_unlock_irq(&head->lock);
8922 return __io_sqe_files_scm(ctx, 1, index);
8928 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8929 struct io_rsrc_node *node, void *rsrc)
8931 u64 *tag_slot = io_get_tag_slot(data, idx);
8932 struct io_rsrc_put *prsrc;
8934 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8938 prsrc->tag = *tag_slot;
8941 list_add(&prsrc->list, &node->rsrc_list);
8945 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8946 unsigned int issue_flags, u32 slot_index)
8948 struct io_ring_ctx *ctx = req->ctx;
8949 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8950 bool needs_switch = false;
8951 struct io_fixed_file *file_slot;
8954 io_ring_submit_lock(ctx, needs_lock);
8955 if (file->f_op == &io_uring_fops)
8958 if (!ctx->file_data)
8961 if (slot_index >= ctx->nr_user_files)
8964 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8965 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8967 if (file_slot->file_ptr) {
8968 struct file *old_file;
8970 ret = io_rsrc_node_switch_start(ctx);
8974 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8975 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8976 ctx->rsrc_node, old_file);
8979 file_slot->file_ptr = 0;
8980 needs_switch = true;
8983 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8984 io_fixed_file_set(file_slot, file);
8985 ret = io_sqe_file_register(ctx, file, slot_index);
8987 file_slot->file_ptr = 0;
8994 io_rsrc_node_switch(ctx, ctx->file_data);
8995 io_ring_submit_unlock(ctx, needs_lock);
9001 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9003 unsigned int offset = req->close.file_slot - 1;
9004 struct io_ring_ctx *ctx = req->ctx;
9005 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9006 struct io_fixed_file *file_slot;
9010 io_ring_submit_lock(ctx, needs_lock);
9012 if (unlikely(!ctx->file_data))
9015 if (offset >= ctx->nr_user_files)
9017 ret = io_rsrc_node_switch_start(ctx);
9021 offset = array_index_nospec(offset, ctx->nr_user_files);
9022 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9024 if (!file_slot->file_ptr)
9027 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9028 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9032 file_slot->file_ptr = 0;
9033 io_rsrc_node_switch(ctx, ctx->file_data);
9036 io_ring_submit_unlock(ctx, needs_lock);
9040 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9041 struct io_uring_rsrc_update2 *up,
9044 u64 __user *tags = u64_to_user_ptr(up->tags);
9045 __s32 __user *fds = u64_to_user_ptr(up->data);
9046 struct io_rsrc_data *data = ctx->file_data;
9047 struct io_fixed_file *file_slot;
9051 bool needs_switch = false;
9053 if (!ctx->file_data)
9055 if (up->offset + nr_args > ctx->nr_user_files)
9058 for (done = 0; done < nr_args; done++) {
9061 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9062 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9066 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9070 if (fd == IORING_REGISTER_FILES_SKIP)
9073 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9074 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9076 if (file_slot->file_ptr) {
9077 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9078 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9081 file_slot->file_ptr = 0;
9082 needs_switch = true;
9091 * Don't allow io_uring instances to be registered. If
9092 * UNIX isn't enabled, then this causes a reference
9093 * cycle and this instance can never get freed. If UNIX
9094 * is enabled we'll handle it just fine, but there's
9095 * still no point in allowing a ring fd as it doesn't
9096 * support regular read/write anyway.
9098 if (file->f_op == &io_uring_fops) {
9103 *io_get_tag_slot(data, i) = tag;
9104 io_fixed_file_set(file_slot, file);
9105 err = io_sqe_file_register(ctx, file, i);
9107 file_slot->file_ptr = 0;
9115 io_rsrc_node_switch(ctx, data);
9116 return done ? done : err;
9119 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9120 struct task_struct *task)
9122 struct io_wq_hash *hash;
9123 struct io_wq_data data;
9124 unsigned int concurrency;
9126 mutex_lock(&ctx->uring_lock);
9127 hash = ctx->hash_map;
9129 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9131 mutex_unlock(&ctx->uring_lock);
9132 return ERR_PTR(-ENOMEM);
9134 refcount_set(&hash->refs, 1);
9135 init_waitqueue_head(&hash->wait);
9136 ctx->hash_map = hash;
9138 mutex_unlock(&ctx->uring_lock);
9142 data.free_work = io_wq_free_work;
9143 data.do_work = io_wq_submit_work;
9145 /* Do QD, or 4 * CPUS, whatever is smallest */
9146 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9148 return io_wq_create(concurrency, &data);
9151 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9152 struct io_ring_ctx *ctx)
9154 struct io_uring_task *tctx;
9157 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9158 if (unlikely(!tctx))
9161 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9162 sizeof(struct file *), GFP_KERNEL);
9163 if (unlikely(!tctx->registered_rings)) {
9168 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9169 if (unlikely(ret)) {
9170 kfree(tctx->registered_rings);
9175 tctx->io_wq = io_init_wq_offload(ctx, task);
9176 if (IS_ERR(tctx->io_wq)) {
9177 ret = PTR_ERR(tctx->io_wq);
9178 percpu_counter_destroy(&tctx->inflight);
9179 kfree(tctx->registered_rings);
9185 init_waitqueue_head(&tctx->wait);
9186 atomic_set(&tctx->in_idle, 0);
9187 task->io_uring = tctx;
9188 spin_lock_init(&tctx->task_lock);
9189 INIT_WQ_LIST(&tctx->task_list);
9190 INIT_WQ_LIST(&tctx->prior_task_list);
9191 init_task_work(&tctx->task_work, tctx_task_work);
9195 void __io_uring_free(struct task_struct *tsk)
9197 struct io_uring_task *tctx = tsk->io_uring;
9199 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9200 WARN_ON_ONCE(tctx->io_wq);
9201 WARN_ON_ONCE(tctx->cached_refs);
9203 kfree(tctx->registered_rings);
9204 percpu_counter_destroy(&tctx->inflight);
9206 tsk->io_uring = NULL;
9209 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9210 struct io_uring_params *p)
9214 /* Retain compatibility with failing for an invalid attach attempt */
9215 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9216 IORING_SETUP_ATTACH_WQ) {
9219 f = fdget(p->wq_fd);
9222 if (f.file->f_op != &io_uring_fops) {
9228 if (ctx->flags & IORING_SETUP_SQPOLL) {
9229 struct task_struct *tsk;
9230 struct io_sq_data *sqd;
9233 ret = security_uring_sqpoll();
9237 sqd = io_get_sq_data(p, &attached);
9243 ctx->sq_creds = get_current_cred();
9245 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9246 if (!ctx->sq_thread_idle)
9247 ctx->sq_thread_idle = HZ;
9249 io_sq_thread_park(sqd);
9250 list_add(&ctx->sqd_list, &sqd->ctx_list);
9251 io_sqd_update_thread_idle(sqd);
9252 /* don't attach to a dying SQPOLL thread, would be racy */
9253 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9254 io_sq_thread_unpark(sqd);
9261 if (p->flags & IORING_SETUP_SQ_AFF) {
9262 int cpu = p->sq_thread_cpu;
9265 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9272 sqd->task_pid = current->pid;
9273 sqd->task_tgid = current->tgid;
9274 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9281 ret = io_uring_alloc_task_context(tsk, ctx);
9282 wake_up_new_task(tsk);
9285 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9286 /* Can't have SQ_AFF without SQPOLL */
9293 complete(&ctx->sq_data->exited);
9295 io_sq_thread_finish(ctx);
9299 static inline void __io_unaccount_mem(struct user_struct *user,
9300 unsigned long nr_pages)
9302 atomic_long_sub(nr_pages, &user->locked_vm);
9305 static inline int __io_account_mem(struct user_struct *user,
9306 unsigned long nr_pages)
9308 unsigned long page_limit, cur_pages, new_pages;
9310 /* Don't allow more pages than we can safely lock */
9311 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9314 cur_pages = atomic_long_read(&user->locked_vm);
9315 new_pages = cur_pages + nr_pages;
9316 if (new_pages > page_limit)
9318 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9319 new_pages) != cur_pages);
9324 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9327 __io_unaccount_mem(ctx->user, nr_pages);
9329 if (ctx->mm_account)
9330 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9333 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9338 ret = __io_account_mem(ctx->user, nr_pages);
9343 if (ctx->mm_account)
9344 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9349 static void io_mem_free(void *ptr)
9356 page = virt_to_head_page(ptr);
9357 if (put_page_testzero(page))
9358 free_compound_page(page);
9361 static void *io_mem_alloc(size_t size)
9363 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9365 return (void *) __get_free_pages(gfp, get_order(size));
9368 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9371 struct io_rings *rings;
9372 size_t off, sq_array_size;
9374 off = struct_size(rings, cqes, cq_entries);
9375 if (off == SIZE_MAX)
9379 off = ALIGN(off, SMP_CACHE_BYTES);
9387 sq_array_size = array_size(sizeof(u32), sq_entries);
9388 if (sq_array_size == SIZE_MAX)
9391 if (check_add_overflow(off, sq_array_size, &off))
9397 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9399 struct io_mapped_ubuf *imu = *slot;
9402 if (imu != ctx->dummy_ubuf) {
9403 for (i = 0; i < imu->nr_bvecs; i++)
9404 unpin_user_page(imu->bvec[i].bv_page);
9405 if (imu->acct_pages)
9406 io_unaccount_mem(ctx, imu->acct_pages);
9412 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9414 io_buffer_unmap(ctx, &prsrc->buf);
9418 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9422 for (i = 0; i < ctx->nr_user_bufs; i++)
9423 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9424 kfree(ctx->user_bufs);
9425 io_rsrc_data_free(ctx->buf_data);
9426 ctx->user_bufs = NULL;
9427 ctx->buf_data = NULL;
9428 ctx->nr_user_bufs = 0;
9431 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9438 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9440 __io_sqe_buffers_unregister(ctx);
9444 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9445 void __user *arg, unsigned index)
9447 struct iovec __user *src;
9449 #ifdef CONFIG_COMPAT
9451 struct compat_iovec __user *ciovs;
9452 struct compat_iovec ciov;
9454 ciovs = (struct compat_iovec __user *) arg;
9455 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9458 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9459 dst->iov_len = ciov.iov_len;
9463 src = (struct iovec __user *) arg;
9464 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9470 * Not super efficient, but this is just a registration time. And we do cache
9471 * the last compound head, so generally we'll only do a full search if we don't
9474 * We check if the given compound head page has already been accounted, to
9475 * avoid double accounting it. This allows us to account the full size of the
9476 * page, not just the constituent pages of a huge page.
9478 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9479 int nr_pages, struct page *hpage)
9483 /* check current page array */
9484 for (i = 0; i < nr_pages; i++) {
9485 if (!PageCompound(pages[i]))
9487 if (compound_head(pages[i]) == hpage)
9491 /* check previously registered pages */
9492 for (i = 0; i < ctx->nr_user_bufs; i++) {
9493 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9495 for (j = 0; j < imu->nr_bvecs; j++) {
9496 if (!PageCompound(imu->bvec[j].bv_page))
9498 if (compound_head(imu->bvec[j].bv_page) == hpage)
9506 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9507 int nr_pages, struct io_mapped_ubuf *imu,
9508 struct page **last_hpage)
9512 imu->acct_pages = 0;
9513 for (i = 0; i < nr_pages; i++) {
9514 if (!PageCompound(pages[i])) {
9519 hpage = compound_head(pages[i]);
9520 if (hpage == *last_hpage)
9522 *last_hpage = hpage;
9523 if (headpage_already_acct(ctx, pages, i, hpage))
9525 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9529 if (!imu->acct_pages)
9532 ret = io_account_mem(ctx, imu->acct_pages);
9534 imu->acct_pages = 0;
9538 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9539 struct io_mapped_ubuf **pimu,
9540 struct page **last_hpage)
9542 struct io_mapped_ubuf *imu = NULL;
9543 struct vm_area_struct **vmas = NULL;
9544 struct page **pages = NULL;
9545 unsigned long off, start, end, ubuf;
9547 int ret, pret, nr_pages, i;
9549 if (!iov->iov_base) {
9550 *pimu = ctx->dummy_ubuf;
9554 ubuf = (unsigned long) iov->iov_base;
9555 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9556 start = ubuf >> PAGE_SHIFT;
9557 nr_pages = end - start;
9562 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9566 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9571 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9576 mmap_read_lock(current->mm);
9577 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9579 if (pret == nr_pages) {
9580 /* don't support file backed memory */
9581 for (i = 0; i < nr_pages; i++) {
9582 struct vm_area_struct *vma = vmas[i];
9584 if (vma_is_shmem(vma))
9587 !is_file_hugepages(vma->vm_file)) {
9593 ret = pret < 0 ? pret : -EFAULT;
9595 mmap_read_unlock(current->mm);
9598 * if we did partial map, or found file backed vmas,
9599 * release any pages we did get
9602 unpin_user_pages(pages, pret);
9606 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9608 unpin_user_pages(pages, pret);
9612 off = ubuf & ~PAGE_MASK;
9613 size = iov->iov_len;
9614 for (i = 0; i < nr_pages; i++) {
9617 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9618 imu->bvec[i].bv_page = pages[i];
9619 imu->bvec[i].bv_len = vec_len;
9620 imu->bvec[i].bv_offset = off;
9624 /* store original address for later verification */
9626 imu->ubuf_end = ubuf + iov->iov_len;
9627 imu->nr_bvecs = nr_pages;
9638 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9640 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9641 return ctx->user_bufs ? 0 : -ENOMEM;
9644 static int io_buffer_validate(struct iovec *iov)
9646 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9649 * Don't impose further limits on the size and buffer
9650 * constraints here, we'll -EINVAL later when IO is
9651 * submitted if they are wrong.
9654 return iov->iov_len ? -EFAULT : 0;
9658 /* arbitrary limit, but we need something */
9659 if (iov->iov_len > SZ_1G)
9662 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9668 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9669 unsigned int nr_args, u64 __user *tags)
9671 struct page *last_hpage = NULL;
9672 struct io_rsrc_data *data;
9678 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9680 ret = io_rsrc_node_switch_start(ctx);
9683 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9686 ret = io_buffers_map_alloc(ctx, nr_args);
9688 io_rsrc_data_free(data);
9692 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9693 ret = io_copy_iov(ctx, &iov, arg, i);
9696 ret = io_buffer_validate(&iov);
9699 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9704 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9710 WARN_ON_ONCE(ctx->buf_data);
9712 ctx->buf_data = data;
9714 __io_sqe_buffers_unregister(ctx);
9716 io_rsrc_node_switch(ctx, NULL);
9720 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9721 struct io_uring_rsrc_update2 *up,
9722 unsigned int nr_args)
9724 u64 __user *tags = u64_to_user_ptr(up->tags);
9725 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9726 struct page *last_hpage = NULL;
9727 bool needs_switch = false;
9733 if (up->offset + nr_args > ctx->nr_user_bufs)
9736 for (done = 0; done < nr_args; done++) {
9737 struct io_mapped_ubuf *imu;
9738 int offset = up->offset + done;
9741 err = io_copy_iov(ctx, &iov, iovs, done);
9744 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9748 err = io_buffer_validate(&iov);
9751 if (!iov.iov_base && tag) {
9755 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9759 i = array_index_nospec(offset, ctx->nr_user_bufs);
9760 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9761 err = io_queue_rsrc_removal(ctx->buf_data, i,
9762 ctx->rsrc_node, ctx->user_bufs[i]);
9763 if (unlikely(err)) {
9764 io_buffer_unmap(ctx, &imu);
9767 ctx->user_bufs[i] = NULL;
9768 needs_switch = true;
9771 ctx->user_bufs[i] = imu;
9772 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9776 io_rsrc_node_switch(ctx, ctx->buf_data);
9777 return done ? done : err;
9780 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9781 unsigned int eventfd_async)
9783 struct io_ev_fd *ev_fd;
9784 __s32 __user *fds = arg;
9787 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9788 lockdep_is_held(&ctx->uring_lock));
9792 if (copy_from_user(&fd, fds, sizeof(*fds)))
9795 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9799 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9800 if (IS_ERR(ev_fd->cq_ev_fd)) {
9801 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9805 ev_fd->eventfd_async = eventfd_async;
9806 ctx->has_evfd = true;
9807 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9811 static void io_eventfd_put(struct rcu_head *rcu)
9813 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9815 eventfd_ctx_put(ev_fd->cq_ev_fd);
9819 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9821 struct io_ev_fd *ev_fd;
9823 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9824 lockdep_is_held(&ctx->uring_lock));
9826 ctx->has_evfd = false;
9827 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9828 call_rcu(&ev_fd->rcu, io_eventfd_put);
9835 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9839 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9840 struct list_head *list = &ctx->io_buffers[i];
9842 while (!list_empty(list)) {
9843 struct io_buffer_list *bl;
9845 bl = list_first_entry(list, struct io_buffer_list, list);
9846 __io_remove_buffers(ctx, bl, -1U);
9847 list_del(&bl->list);
9852 while (!list_empty(&ctx->io_buffers_pages)) {
9855 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9856 list_del_init(&page->lru);
9861 static void io_req_caches_free(struct io_ring_ctx *ctx)
9863 struct io_submit_state *state = &ctx->submit_state;
9866 mutex_lock(&ctx->uring_lock);
9867 io_flush_cached_locked_reqs(ctx, state);
9869 while (state->free_list.next) {
9870 struct io_wq_work_node *node;
9871 struct io_kiocb *req;
9873 node = wq_stack_extract(&state->free_list);
9874 req = container_of(node, struct io_kiocb, comp_list);
9875 kmem_cache_free(req_cachep, req);
9879 percpu_ref_put_many(&ctx->refs, nr);
9880 mutex_unlock(&ctx->uring_lock);
9883 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9885 if (data && !atomic_dec_and_test(&data->refs))
9886 wait_for_completion(&data->done);
9889 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
9891 struct async_poll *apoll;
9893 while (!list_empty(&ctx->apoll_cache)) {
9894 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
9896 list_del(&apoll->poll.wait.entry);
9901 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9903 io_sq_thread_finish(ctx);
9905 if (ctx->mm_account) {
9906 mmdrop(ctx->mm_account);
9907 ctx->mm_account = NULL;
9910 io_rsrc_refs_drop(ctx);
9911 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9912 io_wait_rsrc_data(ctx->buf_data);
9913 io_wait_rsrc_data(ctx->file_data);
9915 mutex_lock(&ctx->uring_lock);
9917 __io_sqe_buffers_unregister(ctx);
9919 __io_sqe_files_unregister(ctx);
9921 __io_cqring_overflow_flush(ctx, true);
9922 io_eventfd_unregister(ctx);
9923 io_flush_apoll_cache(ctx);
9924 mutex_unlock(&ctx->uring_lock);
9925 io_destroy_buffers(ctx);
9927 put_cred(ctx->sq_creds);
9929 /* there are no registered resources left, nobody uses it */
9931 io_rsrc_node_destroy(ctx->rsrc_node);
9932 if (ctx->rsrc_backup_node)
9933 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9934 flush_delayed_work(&ctx->rsrc_put_work);
9935 flush_delayed_work(&ctx->fallback_work);
9937 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9938 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9940 #if defined(CONFIG_UNIX)
9941 if (ctx->ring_sock) {
9942 ctx->ring_sock->file = NULL; /* so that iput() is called */
9943 sock_release(ctx->ring_sock);
9946 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9948 io_mem_free(ctx->rings);
9949 io_mem_free(ctx->sq_sqes);
9951 percpu_ref_exit(&ctx->refs);
9952 free_uid(ctx->user);
9953 io_req_caches_free(ctx);
9955 io_wq_put_hash(ctx->hash_map);
9956 kfree(ctx->cancel_hash);
9957 kfree(ctx->dummy_ubuf);
9958 kfree(ctx->io_buffers);
9962 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9964 struct io_ring_ctx *ctx = file->private_data;
9967 poll_wait(file, &ctx->cq_wait, wait);
9969 * synchronizes with barrier from wq_has_sleeper call in
9973 if (!io_sqring_full(ctx))
9974 mask |= EPOLLOUT | EPOLLWRNORM;
9977 * Don't flush cqring overflow list here, just do a simple check.
9978 * Otherwise there could possible be ABBA deadlock:
9981 * lock(&ctx->uring_lock);
9983 * lock(&ctx->uring_lock);
9986 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9987 * pushs them to do the flush.
9989 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9990 mask |= EPOLLIN | EPOLLRDNORM;
9995 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9997 const struct cred *creds;
9999 creds = xa_erase(&ctx->personalities, id);
10008 struct io_tctx_exit {
10009 struct callback_head task_work;
10010 struct completion completion;
10011 struct io_ring_ctx *ctx;
10014 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10016 struct io_uring_task *tctx = current->io_uring;
10017 struct io_tctx_exit *work;
10019 work = container_of(cb, struct io_tctx_exit, task_work);
10021 * When @in_idle, we're in cancellation and it's racy to remove the
10022 * node. It'll be removed by the end of cancellation, just ignore it.
10024 if (!atomic_read(&tctx->in_idle))
10025 io_uring_del_tctx_node((unsigned long)work->ctx);
10026 complete(&work->completion);
10029 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10031 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10033 return req->ctx == data;
10036 static __cold void io_ring_exit_work(struct work_struct *work)
10038 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10039 unsigned long timeout = jiffies + HZ * 60 * 5;
10040 unsigned long interval = HZ / 20;
10041 struct io_tctx_exit exit;
10042 struct io_tctx_node *node;
10046 * If we're doing polled IO and end up having requests being
10047 * submitted async (out-of-line), then completions can come in while
10048 * we're waiting for refs to drop. We need to reap these manually,
10049 * as nobody else will be looking for them.
10052 io_uring_try_cancel_requests(ctx, NULL, true);
10053 if (ctx->sq_data) {
10054 struct io_sq_data *sqd = ctx->sq_data;
10055 struct task_struct *tsk;
10057 io_sq_thread_park(sqd);
10059 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10060 io_wq_cancel_cb(tsk->io_uring->io_wq,
10061 io_cancel_ctx_cb, ctx, true);
10062 io_sq_thread_unpark(sqd);
10065 io_req_caches_free(ctx);
10067 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10068 /* there is little hope left, don't run it too often */
10069 interval = HZ * 60;
10071 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10073 init_completion(&exit.completion);
10074 init_task_work(&exit.task_work, io_tctx_exit_cb);
10077 * Some may use context even when all refs and requests have been put,
10078 * and they are free to do so while still holding uring_lock or
10079 * completion_lock, see io_req_task_submit(). Apart from other work,
10080 * this lock/unlock section also waits them to finish.
10082 mutex_lock(&ctx->uring_lock);
10083 while (!list_empty(&ctx->tctx_list)) {
10084 WARN_ON_ONCE(time_after(jiffies, timeout));
10086 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10088 /* don't spin on a single task if cancellation failed */
10089 list_rotate_left(&ctx->tctx_list);
10090 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10091 if (WARN_ON_ONCE(ret))
10094 mutex_unlock(&ctx->uring_lock);
10095 wait_for_completion(&exit.completion);
10096 mutex_lock(&ctx->uring_lock);
10098 mutex_unlock(&ctx->uring_lock);
10099 spin_lock(&ctx->completion_lock);
10100 spin_unlock(&ctx->completion_lock);
10102 io_ring_ctx_free(ctx);
10105 /* Returns true if we found and killed one or more timeouts */
10106 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10107 struct task_struct *tsk, bool cancel_all)
10109 struct io_kiocb *req, *tmp;
10112 spin_lock(&ctx->completion_lock);
10113 spin_lock_irq(&ctx->timeout_lock);
10114 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10115 if (io_match_task(req, tsk, cancel_all)) {
10116 io_kill_timeout(req, -ECANCELED);
10120 spin_unlock_irq(&ctx->timeout_lock);
10122 io_commit_cqring(ctx);
10123 spin_unlock(&ctx->completion_lock);
10125 io_cqring_ev_posted(ctx);
10126 return canceled != 0;
10129 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10131 unsigned long index;
10132 struct creds *creds;
10134 mutex_lock(&ctx->uring_lock);
10135 percpu_ref_kill(&ctx->refs);
10137 __io_cqring_overflow_flush(ctx, true);
10138 xa_for_each(&ctx->personalities, index, creds)
10139 io_unregister_personality(ctx, index);
10140 mutex_unlock(&ctx->uring_lock);
10142 io_kill_timeouts(ctx, NULL, true);
10143 io_poll_remove_all(ctx, NULL, true);
10145 /* if we failed setting up the ctx, we might not have any rings */
10146 io_iopoll_try_reap_events(ctx);
10148 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10150 * Use system_unbound_wq to avoid spawning tons of event kworkers
10151 * if we're exiting a ton of rings at the same time. It just adds
10152 * noise and overhead, there's no discernable change in runtime
10153 * over using system_wq.
10155 queue_work(system_unbound_wq, &ctx->exit_work);
10158 static int io_uring_release(struct inode *inode, struct file *file)
10160 struct io_ring_ctx *ctx = file->private_data;
10162 file->private_data = NULL;
10163 io_ring_ctx_wait_and_kill(ctx);
10167 struct io_task_cancel {
10168 struct task_struct *task;
10172 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10174 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10175 struct io_task_cancel *cancel = data;
10177 return io_match_task_safe(req, cancel->task, cancel->all);
10180 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10181 struct task_struct *task,
10184 struct io_defer_entry *de;
10187 spin_lock(&ctx->completion_lock);
10188 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10189 if (io_match_task_safe(de->req, task, cancel_all)) {
10190 list_cut_position(&list, &ctx->defer_list, &de->list);
10194 spin_unlock(&ctx->completion_lock);
10195 if (list_empty(&list))
10198 while (!list_empty(&list)) {
10199 de = list_first_entry(&list, struct io_defer_entry, list);
10200 list_del_init(&de->list);
10201 io_req_complete_failed(de->req, -ECANCELED);
10207 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10209 struct io_tctx_node *node;
10210 enum io_wq_cancel cret;
10213 mutex_lock(&ctx->uring_lock);
10214 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10215 struct io_uring_task *tctx = node->task->io_uring;
10218 * io_wq will stay alive while we hold uring_lock, because it's
10219 * killed after ctx nodes, which requires to take the lock.
10221 if (!tctx || !tctx->io_wq)
10223 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10224 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10226 mutex_unlock(&ctx->uring_lock);
10231 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10232 struct task_struct *task,
10235 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10236 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10239 enum io_wq_cancel cret;
10243 ret |= io_uring_try_cancel_iowq(ctx);
10244 } else if (tctx && tctx->io_wq) {
10246 * Cancels requests of all rings, not only @ctx, but
10247 * it's fine as the task is in exit/exec.
10249 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10251 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10254 /* SQPOLL thread does its own polling */
10255 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10256 (ctx->sq_data && ctx->sq_data->thread == current)) {
10257 while (!wq_list_empty(&ctx->iopoll_list)) {
10258 io_iopoll_try_reap_events(ctx);
10263 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10264 ret |= io_poll_remove_all(ctx, task, cancel_all);
10265 ret |= io_kill_timeouts(ctx, task, cancel_all);
10267 ret |= io_run_task_work();
10274 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10276 struct io_uring_task *tctx = current->io_uring;
10277 struct io_tctx_node *node;
10280 if (unlikely(!tctx)) {
10281 ret = io_uring_alloc_task_context(current, ctx);
10285 tctx = current->io_uring;
10286 if (ctx->iowq_limits_set) {
10287 unsigned int limits[2] = { ctx->iowq_limits[0],
10288 ctx->iowq_limits[1], };
10290 ret = io_wq_max_workers(tctx->io_wq, limits);
10295 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10296 node = kmalloc(sizeof(*node), GFP_KERNEL);
10300 node->task = current;
10302 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10303 node, GFP_KERNEL));
10309 mutex_lock(&ctx->uring_lock);
10310 list_add(&node->ctx_node, &ctx->tctx_list);
10311 mutex_unlock(&ctx->uring_lock);
10318 * Note that this task has used io_uring. We use it for cancelation purposes.
10320 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10322 struct io_uring_task *tctx = current->io_uring;
10324 if (likely(tctx && tctx->last == ctx))
10326 return __io_uring_add_tctx_node(ctx);
10330 * Remove this io_uring_file -> task mapping.
10332 static __cold void io_uring_del_tctx_node(unsigned long index)
10334 struct io_uring_task *tctx = current->io_uring;
10335 struct io_tctx_node *node;
10339 node = xa_erase(&tctx->xa, index);
10343 WARN_ON_ONCE(current != node->task);
10344 WARN_ON_ONCE(list_empty(&node->ctx_node));
10346 mutex_lock(&node->ctx->uring_lock);
10347 list_del(&node->ctx_node);
10348 mutex_unlock(&node->ctx->uring_lock);
10350 if (tctx->last == node->ctx)
10355 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10357 struct io_wq *wq = tctx->io_wq;
10358 struct io_tctx_node *node;
10359 unsigned long index;
10361 xa_for_each(&tctx->xa, index, node) {
10362 io_uring_del_tctx_node(index);
10367 * Must be after io_uring_del_tctx_node() (removes nodes under
10368 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10370 io_wq_put_and_exit(wq);
10371 tctx->io_wq = NULL;
10375 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10379 return percpu_counter_sum(&tctx->inflight);
10383 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10384 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10386 static __cold void io_uring_cancel_generic(bool cancel_all,
10387 struct io_sq_data *sqd)
10389 struct io_uring_task *tctx = current->io_uring;
10390 struct io_ring_ctx *ctx;
10394 WARN_ON_ONCE(sqd && sqd->thread != current);
10396 if (!current->io_uring)
10399 io_wq_exit_start(tctx->io_wq);
10401 atomic_inc(&tctx->in_idle);
10403 io_uring_drop_tctx_refs(current);
10404 /* read completions before cancelations */
10405 inflight = tctx_inflight(tctx, !cancel_all);
10410 struct io_tctx_node *node;
10411 unsigned long index;
10413 xa_for_each(&tctx->xa, index, node) {
10414 /* sqpoll task will cancel all its requests */
10415 if (node->ctx->sq_data)
10417 io_uring_try_cancel_requests(node->ctx, current,
10421 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10422 io_uring_try_cancel_requests(ctx, current,
10426 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10427 io_run_task_work();
10428 io_uring_drop_tctx_refs(current);
10431 * If we've seen completions, retry without waiting. This
10432 * avoids a race where a completion comes in before we did
10433 * prepare_to_wait().
10435 if (inflight == tctx_inflight(tctx, !cancel_all))
10437 finish_wait(&tctx->wait, &wait);
10440 io_uring_clean_tctx(tctx);
10443 * We shouldn't run task_works after cancel, so just leave
10444 * ->in_idle set for normal exit.
10446 atomic_dec(&tctx->in_idle);
10447 /* for exec all current's requests should be gone, kill tctx */
10448 __io_uring_free(current);
10452 void __io_uring_cancel(bool cancel_all)
10454 io_uring_cancel_generic(cancel_all, NULL);
10457 void io_uring_unreg_ringfd(void)
10459 struct io_uring_task *tctx = current->io_uring;
10462 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10463 if (tctx->registered_rings[i]) {
10464 fput(tctx->registered_rings[i]);
10465 tctx->registered_rings[i] = NULL;
10470 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10471 int start, int end)
10476 for (offset = start; offset < end; offset++) {
10477 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10478 if (tctx->registered_rings[offset])
10484 } else if (file->f_op != &io_uring_fops) {
10486 return -EOPNOTSUPP;
10488 tctx->registered_rings[offset] = file;
10496 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10497 * invocation. User passes in an array of struct io_uring_rsrc_update
10498 * with ->data set to the ring_fd, and ->offset given for the desired
10499 * index. If no index is desired, application may set ->offset == -1U
10500 * and we'll find an available index. Returns number of entries
10501 * successfully processed, or < 0 on error if none were processed.
10503 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10506 struct io_uring_rsrc_update __user *arg = __arg;
10507 struct io_uring_rsrc_update reg;
10508 struct io_uring_task *tctx;
10511 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10514 mutex_unlock(&ctx->uring_lock);
10515 ret = io_uring_add_tctx_node(ctx);
10516 mutex_lock(&ctx->uring_lock);
10520 tctx = current->io_uring;
10521 for (i = 0; i < nr_args; i++) {
10524 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10529 if (reg.offset == -1U) {
10531 end = IO_RINGFD_REG_MAX;
10533 if (reg.offset >= IO_RINGFD_REG_MAX) {
10537 start = reg.offset;
10541 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10546 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10547 fput(tctx->registered_rings[reg.offset]);
10548 tctx->registered_rings[reg.offset] = NULL;
10554 return i ? i : ret;
10557 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10560 struct io_uring_rsrc_update __user *arg = __arg;
10561 struct io_uring_task *tctx = current->io_uring;
10562 struct io_uring_rsrc_update reg;
10565 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10570 for (i = 0; i < nr_args; i++) {
10571 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10575 if (reg.offset >= IO_RINGFD_REG_MAX) {
10580 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10581 if (tctx->registered_rings[reg.offset]) {
10582 fput(tctx->registered_rings[reg.offset]);
10583 tctx->registered_rings[reg.offset] = NULL;
10587 return i ? i : ret;
10590 static void *io_uring_validate_mmap_request(struct file *file,
10591 loff_t pgoff, size_t sz)
10593 struct io_ring_ctx *ctx = file->private_data;
10594 loff_t offset = pgoff << PAGE_SHIFT;
10599 case IORING_OFF_SQ_RING:
10600 case IORING_OFF_CQ_RING:
10603 case IORING_OFF_SQES:
10604 ptr = ctx->sq_sqes;
10607 return ERR_PTR(-EINVAL);
10610 page = virt_to_head_page(ptr);
10611 if (sz > page_size(page))
10612 return ERR_PTR(-EINVAL);
10619 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10621 size_t sz = vma->vm_end - vma->vm_start;
10625 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10627 return PTR_ERR(ptr);
10629 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10630 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10633 #else /* !CONFIG_MMU */
10635 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10637 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10640 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10642 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10645 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10646 unsigned long addr, unsigned long len,
10647 unsigned long pgoff, unsigned long flags)
10651 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10653 return PTR_ERR(ptr);
10655 return (unsigned long) ptr;
10658 #endif /* !CONFIG_MMU */
10660 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10665 if (!io_sqring_full(ctx))
10667 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10669 if (!io_sqring_full(ctx))
10672 } while (!signal_pending(current));
10674 finish_wait(&ctx->sqo_sq_wait, &wait);
10678 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10679 struct __kernel_timespec __user **ts,
10680 const sigset_t __user **sig)
10682 struct io_uring_getevents_arg arg;
10685 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10686 * is just a pointer to the sigset_t.
10688 if (!(flags & IORING_ENTER_EXT_ARG)) {
10689 *sig = (const sigset_t __user *) argp;
10695 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10696 * timespec and sigset_t pointers if good.
10698 if (*argsz != sizeof(arg))
10700 if (copy_from_user(&arg, argp, sizeof(arg)))
10702 *sig = u64_to_user_ptr(arg.sigmask);
10703 *argsz = arg.sigmask_sz;
10704 *ts = u64_to_user_ptr(arg.ts);
10708 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10709 u32, min_complete, u32, flags, const void __user *, argp,
10712 struct io_ring_ctx *ctx;
10717 io_run_task_work();
10719 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10720 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10721 IORING_ENTER_REGISTERED_RING)))
10725 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10726 * need only dereference our task private array to find it.
10728 if (flags & IORING_ENTER_REGISTERED_RING) {
10729 struct io_uring_task *tctx = current->io_uring;
10731 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10733 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10734 f.file = tctx->registered_rings[fd];
10735 if (unlikely(!f.file))
10739 if (unlikely(!f.file))
10744 if (unlikely(f.file->f_op != &io_uring_fops))
10748 ctx = f.file->private_data;
10749 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10753 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10757 * For SQ polling, the thread will do all submissions and completions.
10758 * Just return the requested submit count, and wake the thread if
10759 * we were asked to.
10762 if (ctx->flags & IORING_SETUP_SQPOLL) {
10763 io_cqring_overflow_flush(ctx);
10765 if (unlikely(ctx->sq_data->thread == NULL)) {
10769 if (flags & IORING_ENTER_SQ_WAKEUP)
10770 wake_up(&ctx->sq_data->wait);
10771 if (flags & IORING_ENTER_SQ_WAIT) {
10772 ret = io_sqpoll_wait_sq(ctx);
10776 submitted = to_submit;
10777 } else if (to_submit) {
10778 ret = io_uring_add_tctx_node(ctx);
10781 mutex_lock(&ctx->uring_lock);
10782 submitted = io_submit_sqes(ctx, to_submit);
10783 mutex_unlock(&ctx->uring_lock);
10785 if (submitted != to_submit)
10788 if (flags & IORING_ENTER_GETEVENTS) {
10789 const sigset_t __user *sig;
10790 struct __kernel_timespec __user *ts;
10792 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10796 min_complete = min(min_complete, ctx->cq_entries);
10799 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10800 * space applications don't need to do io completion events
10801 * polling again, they can rely on io_sq_thread to do polling
10802 * work, which can reduce cpu usage and uring_lock contention.
10804 if (ctx->flags & IORING_SETUP_IOPOLL &&
10805 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10806 ret = io_iopoll_check(ctx, min_complete);
10808 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10813 percpu_ref_put(&ctx->refs);
10815 if (!(flags & IORING_ENTER_REGISTERED_RING))
10817 return submitted ? submitted : ret;
10820 #ifdef CONFIG_PROC_FS
10821 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10822 const struct cred *cred)
10824 struct user_namespace *uns = seq_user_ns(m);
10825 struct group_info *gi;
10830 seq_printf(m, "%5d\n", id);
10831 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10832 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10833 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10834 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10835 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10836 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10837 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10838 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10839 seq_puts(m, "\n\tGroups:\t");
10840 gi = cred->group_info;
10841 for (g = 0; g < gi->ngroups; g++) {
10842 seq_put_decimal_ull(m, g ? " " : "",
10843 from_kgid_munged(uns, gi->gid[g]));
10845 seq_puts(m, "\n\tCapEff:\t");
10846 cap = cred->cap_effective;
10847 CAP_FOR_EACH_U32(__capi)
10848 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10853 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10854 struct seq_file *m)
10856 struct io_sq_data *sq = NULL;
10857 struct io_overflow_cqe *ocqe;
10858 struct io_rings *r = ctx->rings;
10859 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10860 unsigned int sq_head = READ_ONCE(r->sq.head);
10861 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10862 unsigned int cq_head = READ_ONCE(r->cq.head);
10863 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10864 unsigned int sq_entries, cq_entries;
10869 * we may get imprecise sqe and cqe info if uring is actively running
10870 * since we get cached_sq_head and cached_cq_tail without uring_lock
10871 * and sq_tail and cq_head are changed by userspace. But it's ok since
10872 * we usually use these info when it is stuck.
10874 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10875 seq_printf(m, "SqHead:\t%u\n", sq_head);
10876 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10877 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10878 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10879 seq_printf(m, "CqHead:\t%u\n", cq_head);
10880 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10881 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10882 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10883 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10884 for (i = 0; i < sq_entries; i++) {
10885 unsigned int entry = i + sq_head;
10886 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10887 struct io_uring_sqe *sqe;
10889 if (sq_idx > sq_mask)
10891 sqe = &ctx->sq_sqes[sq_idx];
10892 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10893 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10896 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10897 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10898 for (i = 0; i < cq_entries; i++) {
10899 unsigned int entry = i + cq_head;
10900 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10902 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10903 entry & cq_mask, cqe->user_data, cqe->res,
10908 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10909 * since fdinfo case grabs it in the opposite direction of normal use
10910 * cases. If we fail to get the lock, we just don't iterate any
10911 * structures that could be going away outside the io_uring mutex.
10913 has_lock = mutex_trylock(&ctx->uring_lock);
10915 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10921 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10922 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10923 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10924 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10925 struct file *f = io_file_from_index(ctx, i);
10928 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10930 seq_printf(m, "%5u: <none>\n", i);
10932 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10933 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10934 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10935 unsigned int len = buf->ubuf_end - buf->ubuf;
10937 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10939 if (has_lock && !xa_empty(&ctx->personalities)) {
10940 unsigned long index;
10941 const struct cred *cred;
10943 seq_printf(m, "Personalities:\n");
10944 xa_for_each(&ctx->personalities, index, cred)
10945 io_uring_show_cred(m, index, cred);
10948 mutex_unlock(&ctx->uring_lock);
10950 seq_puts(m, "PollList:\n");
10951 spin_lock(&ctx->completion_lock);
10952 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10953 struct hlist_head *list = &ctx->cancel_hash[i];
10954 struct io_kiocb *req;
10956 hlist_for_each_entry(req, list, hash_node)
10957 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10958 task_work_pending(req->task));
10961 seq_puts(m, "CqOverflowList:\n");
10962 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10963 struct io_uring_cqe *cqe = &ocqe->cqe;
10965 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10966 cqe->user_data, cqe->res, cqe->flags);
10970 spin_unlock(&ctx->completion_lock);
10973 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10975 struct io_ring_ctx *ctx = f->private_data;
10977 if (percpu_ref_tryget(&ctx->refs)) {
10978 __io_uring_show_fdinfo(ctx, m);
10979 percpu_ref_put(&ctx->refs);
10984 static const struct file_operations io_uring_fops = {
10985 .release = io_uring_release,
10986 .mmap = io_uring_mmap,
10988 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10989 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10991 .poll = io_uring_poll,
10992 #ifdef CONFIG_PROC_FS
10993 .show_fdinfo = io_uring_show_fdinfo,
10997 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10998 struct io_uring_params *p)
11000 struct io_rings *rings;
11001 size_t size, sq_array_offset;
11003 /* make sure these are sane, as we already accounted them */
11004 ctx->sq_entries = p->sq_entries;
11005 ctx->cq_entries = p->cq_entries;
11007 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11008 if (size == SIZE_MAX)
11011 rings = io_mem_alloc(size);
11015 ctx->rings = rings;
11016 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11017 rings->sq_ring_mask = p->sq_entries - 1;
11018 rings->cq_ring_mask = p->cq_entries - 1;
11019 rings->sq_ring_entries = p->sq_entries;
11020 rings->cq_ring_entries = p->cq_entries;
11022 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11023 if (size == SIZE_MAX) {
11024 io_mem_free(ctx->rings);
11029 ctx->sq_sqes = io_mem_alloc(size);
11030 if (!ctx->sq_sqes) {
11031 io_mem_free(ctx->rings);
11039 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11043 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11047 ret = io_uring_add_tctx_node(ctx);
11052 fd_install(fd, file);
11057 * Allocate an anonymous fd, this is what constitutes the application
11058 * visible backing of an io_uring instance. The application mmaps this
11059 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11060 * we have to tie this fd to a socket for file garbage collection purposes.
11062 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11065 #if defined(CONFIG_UNIX)
11068 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11071 return ERR_PTR(ret);
11074 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11075 O_RDWR | O_CLOEXEC, NULL);
11076 #if defined(CONFIG_UNIX)
11077 if (IS_ERR(file)) {
11078 sock_release(ctx->ring_sock);
11079 ctx->ring_sock = NULL;
11081 ctx->ring_sock->file = file;
11087 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11088 struct io_uring_params __user *params)
11090 struct io_ring_ctx *ctx;
11096 if (entries > IORING_MAX_ENTRIES) {
11097 if (!(p->flags & IORING_SETUP_CLAMP))
11099 entries = IORING_MAX_ENTRIES;
11103 * Use twice as many entries for the CQ ring. It's possible for the
11104 * application to drive a higher depth than the size of the SQ ring,
11105 * since the sqes are only used at submission time. This allows for
11106 * some flexibility in overcommitting a bit. If the application has
11107 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11108 * of CQ ring entries manually.
11110 p->sq_entries = roundup_pow_of_two(entries);
11111 if (p->flags & IORING_SETUP_CQSIZE) {
11113 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11114 * to a power-of-two, if it isn't already. We do NOT impose
11115 * any cq vs sq ring sizing.
11117 if (!p->cq_entries)
11119 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11120 if (!(p->flags & IORING_SETUP_CLAMP))
11122 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11124 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11125 if (p->cq_entries < p->sq_entries)
11128 p->cq_entries = 2 * p->sq_entries;
11131 ctx = io_ring_ctx_alloc(p);
11134 ctx->compat = in_compat_syscall();
11135 if (!capable(CAP_IPC_LOCK))
11136 ctx->user = get_uid(current_user());
11139 * This is just grabbed for accounting purposes. When a process exits,
11140 * the mm is exited and dropped before the files, hence we need to hang
11141 * on to this mm purely for the purposes of being able to unaccount
11142 * memory (locked/pinned vm). It's not used for anything else.
11144 mmgrab(current->mm);
11145 ctx->mm_account = current->mm;
11147 ret = io_allocate_scq_urings(ctx, p);
11151 ret = io_sq_offload_create(ctx, p);
11154 /* always set a rsrc node */
11155 ret = io_rsrc_node_switch_start(ctx);
11158 io_rsrc_node_switch(ctx, NULL);
11160 memset(&p->sq_off, 0, sizeof(p->sq_off));
11161 p->sq_off.head = offsetof(struct io_rings, sq.head);
11162 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11163 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11164 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11165 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11166 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11167 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11169 memset(&p->cq_off, 0, sizeof(p->cq_off));
11170 p->cq_off.head = offsetof(struct io_rings, cq.head);
11171 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11172 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11173 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11174 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11175 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11176 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11178 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11179 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11180 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11181 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11182 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11183 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
11184 IORING_FEAT_LINKED_FILE;
11186 if (copy_to_user(params, p, sizeof(*p))) {
11191 file = io_uring_get_file(ctx);
11192 if (IS_ERR(file)) {
11193 ret = PTR_ERR(file);
11198 * Install ring fd as the very last thing, so we don't risk someone
11199 * having closed it before we finish setup
11201 ret = io_uring_install_fd(ctx, file);
11203 /* fput will clean it up */
11208 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11211 io_ring_ctx_wait_and_kill(ctx);
11216 * Sets up an aio uring context, and returns the fd. Applications asks for a
11217 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11218 * params structure passed in.
11220 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11222 struct io_uring_params p;
11225 if (copy_from_user(&p, params, sizeof(p)))
11227 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11232 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11233 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11234 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11235 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11238 return io_uring_create(entries, &p, params);
11241 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11242 struct io_uring_params __user *, params)
11244 return io_uring_setup(entries, params);
11247 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11250 struct io_uring_probe *p;
11254 size = struct_size(p, ops, nr_args);
11255 if (size == SIZE_MAX)
11257 p = kzalloc(size, GFP_KERNEL);
11262 if (copy_from_user(p, arg, size))
11265 if (memchr_inv(p, 0, size))
11268 p->last_op = IORING_OP_LAST - 1;
11269 if (nr_args > IORING_OP_LAST)
11270 nr_args = IORING_OP_LAST;
11272 for (i = 0; i < nr_args; i++) {
11274 if (!io_op_defs[i].not_supported)
11275 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11280 if (copy_to_user(arg, p, size))
11287 static int io_register_personality(struct io_ring_ctx *ctx)
11289 const struct cred *creds;
11293 creds = get_current_cred();
11295 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11296 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11304 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11305 void __user *arg, unsigned int nr_args)
11307 struct io_uring_restriction *res;
11311 /* Restrictions allowed only if rings started disabled */
11312 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11315 /* We allow only a single restrictions registration */
11316 if (ctx->restrictions.registered)
11319 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11322 size = array_size(nr_args, sizeof(*res));
11323 if (size == SIZE_MAX)
11326 res = memdup_user(arg, size);
11328 return PTR_ERR(res);
11332 for (i = 0; i < nr_args; i++) {
11333 switch (res[i].opcode) {
11334 case IORING_RESTRICTION_REGISTER_OP:
11335 if (res[i].register_op >= IORING_REGISTER_LAST) {
11340 __set_bit(res[i].register_op,
11341 ctx->restrictions.register_op);
11343 case IORING_RESTRICTION_SQE_OP:
11344 if (res[i].sqe_op >= IORING_OP_LAST) {
11349 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11351 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11352 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11354 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11355 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11364 /* Reset all restrictions if an error happened */
11366 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11368 ctx->restrictions.registered = true;
11374 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11376 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11379 if (ctx->restrictions.registered)
11380 ctx->restricted = 1;
11382 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11383 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11384 wake_up(&ctx->sq_data->wait);
11388 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11389 struct io_uring_rsrc_update2 *up,
11397 if (check_add_overflow(up->offset, nr_args, &tmp))
11399 err = io_rsrc_node_switch_start(ctx);
11404 case IORING_RSRC_FILE:
11405 return __io_sqe_files_update(ctx, up, nr_args);
11406 case IORING_RSRC_BUFFER:
11407 return __io_sqe_buffers_update(ctx, up, nr_args);
11412 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11415 struct io_uring_rsrc_update2 up;
11419 memset(&up, 0, sizeof(up));
11420 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11422 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11425 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11426 unsigned size, unsigned type)
11428 struct io_uring_rsrc_update2 up;
11430 if (size != sizeof(up))
11432 if (copy_from_user(&up, arg, sizeof(up)))
11434 if (!up.nr || up.resv)
11436 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11439 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11440 unsigned int size, unsigned int type)
11442 struct io_uring_rsrc_register rr;
11444 /* keep it extendible */
11445 if (size != sizeof(rr))
11448 memset(&rr, 0, sizeof(rr));
11449 if (copy_from_user(&rr, arg, size))
11451 if (!rr.nr || rr.resv || rr.resv2)
11455 case IORING_RSRC_FILE:
11456 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11457 rr.nr, u64_to_user_ptr(rr.tags));
11458 case IORING_RSRC_BUFFER:
11459 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11460 rr.nr, u64_to_user_ptr(rr.tags));
11465 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11466 void __user *arg, unsigned len)
11468 struct io_uring_task *tctx = current->io_uring;
11469 cpumask_var_t new_mask;
11472 if (!tctx || !tctx->io_wq)
11475 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11478 cpumask_clear(new_mask);
11479 if (len > cpumask_size())
11480 len = cpumask_size();
11482 if (in_compat_syscall()) {
11483 ret = compat_get_bitmap(cpumask_bits(new_mask),
11484 (const compat_ulong_t __user *)arg,
11485 len * 8 /* CHAR_BIT */);
11487 ret = copy_from_user(new_mask, arg, len);
11491 free_cpumask_var(new_mask);
11495 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11496 free_cpumask_var(new_mask);
11500 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11502 struct io_uring_task *tctx = current->io_uring;
11504 if (!tctx || !tctx->io_wq)
11507 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11510 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11512 __must_hold(&ctx->uring_lock)
11514 struct io_tctx_node *node;
11515 struct io_uring_task *tctx = NULL;
11516 struct io_sq_data *sqd = NULL;
11517 __u32 new_count[2];
11520 if (copy_from_user(new_count, arg, sizeof(new_count)))
11522 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11523 if (new_count[i] > INT_MAX)
11526 if (ctx->flags & IORING_SETUP_SQPOLL) {
11527 sqd = ctx->sq_data;
11530 * Observe the correct sqd->lock -> ctx->uring_lock
11531 * ordering. Fine to drop uring_lock here, we hold
11532 * a ref to the ctx.
11534 refcount_inc(&sqd->refs);
11535 mutex_unlock(&ctx->uring_lock);
11536 mutex_lock(&sqd->lock);
11537 mutex_lock(&ctx->uring_lock);
11539 tctx = sqd->thread->io_uring;
11542 tctx = current->io_uring;
11545 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11547 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11549 ctx->iowq_limits[i] = new_count[i];
11550 ctx->iowq_limits_set = true;
11552 if (tctx && tctx->io_wq) {
11553 ret = io_wq_max_workers(tctx->io_wq, new_count);
11557 memset(new_count, 0, sizeof(new_count));
11561 mutex_unlock(&sqd->lock);
11562 io_put_sq_data(sqd);
11565 if (copy_to_user(arg, new_count, sizeof(new_count)))
11568 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11572 /* now propagate the restriction to all registered users */
11573 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11574 struct io_uring_task *tctx = node->task->io_uring;
11576 if (WARN_ON_ONCE(!tctx->io_wq))
11579 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11580 new_count[i] = ctx->iowq_limits[i];
11581 /* ignore errors, it always returns zero anyway */
11582 (void)io_wq_max_workers(tctx->io_wq, new_count);
11587 mutex_unlock(&sqd->lock);
11588 io_put_sq_data(sqd);
11593 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11594 void __user *arg, unsigned nr_args)
11595 __releases(ctx->uring_lock)
11596 __acquires(ctx->uring_lock)
11601 * We're inside the ring mutex, if the ref is already dying, then
11602 * someone else killed the ctx or is already going through
11603 * io_uring_register().
11605 if (percpu_ref_is_dying(&ctx->refs))
11608 if (ctx->restricted) {
11609 if (opcode >= IORING_REGISTER_LAST)
11611 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11612 if (!test_bit(opcode, ctx->restrictions.register_op))
11617 case IORING_REGISTER_BUFFERS:
11618 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11620 case IORING_UNREGISTER_BUFFERS:
11622 if (arg || nr_args)
11624 ret = io_sqe_buffers_unregister(ctx);
11626 case IORING_REGISTER_FILES:
11627 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11629 case IORING_UNREGISTER_FILES:
11631 if (arg || nr_args)
11633 ret = io_sqe_files_unregister(ctx);
11635 case IORING_REGISTER_FILES_UPDATE:
11636 ret = io_register_files_update(ctx, arg, nr_args);
11638 case IORING_REGISTER_EVENTFD:
11642 ret = io_eventfd_register(ctx, arg, 0);
11644 case IORING_REGISTER_EVENTFD_ASYNC:
11648 ret = io_eventfd_register(ctx, arg, 1);
11650 case IORING_UNREGISTER_EVENTFD:
11652 if (arg || nr_args)
11654 ret = io_eventfd_unregister(ctx);
11656 case IORING_REGISTER_PROBE:
11658 if (!arg || nr_args > 256)
11660 ret = io_probe(ctx, arg, nr_args);
11662 case IORING_REGISTER_PERSONALITY:
11664 if (arg || nr_args)
11666 ret = io_register_personality(ctx);
11668 case IORING_UNREGISTER_PERSONALITY:
11672 ret = io_unregister_personality(ctx, nr_args);
11674 case IORING_REGISTER_ENABLE_RINGS:
11676 if (arg || nr_args)
11678 ret = io_register_enable_rings(ctx);
11680 case IORING_REGISTER_RESTRICTIONS:
11681 ret = io_register_restrictions(ctx, arg, nr_args);
11683 case IORING_REGISTER_FILES2:
11684 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11686 case IORING_REGISTER_FILES_UPDATE2:
11687 ret = io_register_rsrc_update(ctx, arg, nr_args,
11690 case IORING_REGISTER_BUFFERS2:
11691 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11693 case IORING_REGISTER_BUFFERS_UPDATE:
11694 ret = io_register_rsrc_update(ctx, arg, nr_args,
11695 IORING_RSRC_BUFFER);
11697 case IORING_REGISTER_IOWQ_AFF:
11699 if (!arg || !nr_args)
11701 ret = io_register_iowq_aff(ctx, arg, nr_args);
11703 case IORING_UNREGISTER_IOWQ_AFF:
11705 if (arg || nr_args)
11707 ret = io_unregister_iowq_aff(ctx);
11709 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11711 if (!arg || nr_args != 2)
11713 ret = io_register_iowq_max_workers(ctx, arg);
11715 case IORING_REGISTER_RING_FDS:
11716 ret = io_ringfd_register(ctx, arg, nr_args);
11718 case IORING_UNREGISTER_RING_FDS:
11719 ret = io_ringfd_unregister(ctx, arg, nr_args);
11729 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11730 void __user *, arg, unsigned int, nr_args)
11732 struct io_ring_ctx *ctx;
11741 if (f.file->f_op != &io_uring_fops)
11744 ctx = f.file->private_data;
11746 io_run_task_work();
11748 mutex_lock(&ctx->uring_lock);
11749 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11750 mutex_unlock(&ctx->uring_lock);
11751 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11757 static int __init io_uring_init(void)
11759 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11760 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11761 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11764 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11765 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11766 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11767 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11768 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11769 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11770 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11771 BUILD_BUG_SQE_ELEM(8, __u64, off);
11772 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11773 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11774 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11775 BUILD_BUG_SQE_ELEM(24, __u32, len);
11776 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11777 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11778 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11779 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11780 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11781 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11782 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11783 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11784 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11785 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11786 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11787 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11788 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11789 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11790 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11791 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11792 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11793 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11794 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11795 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11796 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11798 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11799 sizeof(struct io_uring_rsrc_update));
11800 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11801 sizeof(struct io_uring_rsrc_update2));
11803 /* ->buf_index is u16 */
11804 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11806 /* should fit into one byte */
11807 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11808 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11809 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11811 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11812 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11814 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11818 __initcall(io_uring_init);