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_cqring (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/blkdev.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/tracehook.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
97 #define IORING_FILE_TABLE_SHIFT 9
98 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
99 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
100 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
101 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
102 IORING_REGISTER_LAST + IORING_OP_LAST)
104 #define IORING_MAX_REG_BUFFERS (1U << 14)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
111 u32 head ____cacheline_aligned_in_smp;
112 u32 tail ____cacheline_aligned_in_smp;
116 * This data is shared with the application through the mmap at offsets
117 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
119 * The offsets to the member fields are published through struct
120 * io_sqring_offsets when calling io_uring_setup.
124 * Head and tail offsets into the ring; the offsets need to be
125 * masked to get valid indices.
127 * The kernel controls head of the sq ring and the tail of the cq ring,
128 * and the application controls tail of the sq ring and the head of the
131 struct io_uring sq, cq;
133 * Bitmasks to apply to head and tail offsets (constant, equals
136 u32 sq_ring_mask, cq_ring_mask;
137 /* Ring sizes (constant, power of 2) */
138 u32 sq_ring_entries, cq_ring_entries;
140 * Number of invalid entries dropped by the kernel due to
141 * invalid index stored in array
143 * Written by the kernel, shouldn't be modified by the
144 * application (i.e. get number of "new events" by comparing to
147 * After a new SQ head value was read by the application this
148 * counter includes all submissions that were dropped reaching
149 * the new SQ head (and possibly more).
155 * Written by the kernel, shouldn't be modified by the
158 * The application needs a full memory barrier before checking
159 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
165 * Written by the application, shouldn't be modified by the
170 * Number of completion events lost because the queue was full;
171 * this should be avoided by the application by making sure
172 * there are not more requests pending than there is space in
173 * the completion queue.
175 * Written by the kernel, shouldn't be modified by the
176 * application (i.e. get number of "new events" by comparing to
179 * As completion events come in out of order this counter is not
180 * ordered with any other data.
184 * Ring buffer of completion events.
186 * The kernel writes completion events fresh every time they are
187 * produced, so the application is allowed to modify pending
190 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
193 enum io_uring_cmd_flags {
194 IO_URING_F_NONBLOCK = 1,
195 IO_URING_F_COMPLETE_DEFER = 2,
198 struct io_mapped_ubuf {
201 unsigned int nr_bvecs;
202 unsigned long acct_pages;
203 struct bio_vec bvec[];
208 struct io_overflow_cqe {
209 struct io_uring_cqe cqe;
210 struct list_head list;
213 struct io_fixed_file {
214 /* file * with additional FFS_* flags */
215 unsigned long file_ptr;
219 struct list_head list;
224 struct io_mapped_ubuf *buf;
228 struct io_file_table {
229 /* two level table */
230 struct io_fixed_file **files;
233 struct io_rsrc_node {
234 struct percpu_ref refs;
235 struct list_head node;
236 struct list_head rsrc_list;
237 struct io_rsrc_data *rsrc_data;
238 struct llist_node llist;
242 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
244 struct io_rsrc_data {
245 struct io_ring_ctx *ctx;
250 struct completion done;
255 struct list_head list;
261 struct io_restriction {
262 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
263 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
264 u8 sqe_flags_allowed;
265 u8 sqe_flags_required;
270 IO_SQ_THREAD_SHOULD_STOP = 0,
271 IO_SQ_THREAD_SHOULD_PARK,
276 atomic_t park_pending;
279 /* ctx's that are using this sqd */
280 struct list_head ctx_list;
282 struct task_struct *thread;
283 struct wait_queue_head wait;
285 unsigned sq_thread_idle;
291 struct completion exited;
292 struct callback_head *park_task_work;
295 #define IO_IOPOLL_BATCH 8
296 #define IO_COMPL_BATCH 32
297 #define IO_REQ_CACHE_SIZE 32
298 #define IO_REQ_ALLOC_BATCH 8
300 struct io_comp_state {
301 struct io_kiocb *reqs[IO_COMPL_BATCH];
303 /* inline/task_work completion list, under ->uring_lock */
304 struct list_head free_list;
307 struct io_submit_link {
308 struct io_kiocb *head;
309 struct io_kiocb *last;
312 struct io_submit_state {
313 struct blk_plug plug;
314 struct io_submit_link link;
317 * io_kiocb alloc cache
319 void *reqs[IO_REQ_CACHE_SIZE];
320 unsigned int free_reqs;
325 * Batch completion logic
327 struct io_comp_state comp;
330 * File reference cache
334 unsigned int file_refs;
335 unsigned int ios_left;
340 struct percpu_ref refs;
341 } ____cacheline_aligned_in_smp;
345 unsigned int compat: 1;
346 unsigned int drain_next: 1;
347 unsigned int eventfd_async: 1;
348 unsigned int restricted: 1;
351 * Ring buffer of indices into array of io_uring_sqe, which is
352 * mmapped by the application using the IORING_OFF_SQES offset.
354 * This indirection could e.g. be used to assign fixed
355 * io_uring_sqe entries to operations and only submit them to
356 * the queue when needed.
358 * The kernel modifies neither the indices array nor the entries
362 unsigned cached_sq_head;
365 unsigned sq_thread_idle;
366 unsigned cached_sq_dropped;
367 unsigned cached_cq_overflow;
368 unsigned long sq_check_overflow;
370 struct list_head defer_list;
371 struct list_head timeout_list;
372 struct list_head cq_overflow_list;
374 struct io_uring_sqe *sq_sqes;
375 } ____cacheline_aligned_in_smp;
378 struct mutex uring_lock;
379 wait_queue_head_t wait;
380 } ____cacheline_aligned_in_smp;
382 struct io_submit_state submit_state;
383 /* IRQ completion list, under ->completion_lock */
384 struct list_head locked_free_list;
385 unsigned int locked_free_nr;
387 struct io_rings *rings;
389 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
396 * If used, fixed file set. Writers must ensure that ->refs is dead,
397 * readers must ensure that ->refs is alive as long as the file* is
398 * used. Only updated through io_uring_register(2).
400 struct io_rsrc_data *file_data;
401 struct io_file_table file_table;
402 unsigned nr_user_files;
404 /* if used, fixed mapped user buffers */
405 struct io_rsrc_data *buf_data;
406 unsigned nr_user_bufs;
407 struct io_mapped_ubuf **user_bufs;
409 struct xarray io_buffers;
411 struct xarray personalities;
415 unsigned cached_cq_tail;
418 atomic_t cq_timeouts;
419 unsigned cq_last_tm_flush;
421 unsigned long cq_check_overflow;
422 struct wait_queue_head cq_wait;
423 struct fasync_struct *cq_fasync;
424 struct eventfd_ctx *cq_ev_fd;
425 } ____cacheline_aligned_in_smp;
428 spinlock_t completion_lock;
431 * ->iopoll_list is protected by the ctx->uring_lock for
432 * io_uring instances that don't use IORING_SETUP_SQPOLL.
433 * For SQPOLL, only the single threaded io_sq_thread() will
434 * manipulate the list, hence no extra locking is needed there.
436 struct list_head iopoll_list;
437 struct hlist_head *cancel_hash;
438 unsigned cancel_hash_bits;
439 bool poll_multi_file;
440 } ____cacheline_aligned_in_smp;
442 struct delayed_work rsrc_put_work;
443 struct llist_head rsrc_put_llist;
444 struct list_head rsrc_ref_list;
445 spinlock_t rsrc_ref_lock;
446 struct io_rsrc_node *rsrc_node;
447 struct io_rsrc_node *rsrc_backup_node;
448 struct io_mapped_ubuf *dummy_ubuf;
450 struct io_restriction restrictions;
452 /* Keep this last, we don't need it for the fast path */
454 #if defined(CONFIG_UNIX)
455 struct socket *ring_sock;
457 /* hashed buffered write serialization */
458 struct io_wq_hash *hash_map;
460 /* Only used for accounting purposes */
461 struct user_struct *user;
462 struct mm_struct *mm_account;
464 /* ctx exit and cancelation */
465 struct callback_head *exit_task_work;
466 struct work_struct exit_work;
467 struct list_head tctx_list;
468 struct completion ref_comp;
472 struct io_uring_task {
473 /* submission side */
475 struct wait_queue_head wait;
476 const struct io_ring_ctx *last;
478 struct percpu_counter inflight;
479 atomic_t inflight_tracked;
482 spinlock_t task_lock;
483 struct io_wq_work_list task_list;
484 unsigned long task_state;
485 struct callback_head task_work;
489 * First field must be the file pointer in all the
490 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
492 struct io_poll_iocb {
494 struct wait_queue_head *head;
498 struct wait_queue_entry wait;
501 struct io_poll_update {
507 bool update_user_data;
515 struct io_timeout_data {
516 struct io_kiocb *req;
517 struct hrtimer timer;
518 struct timespec64 ts;
519 enum hrtimer_mode mode;
524 struct sockaddr __user *addr;
525 int __user *addr_len;
527 unsigned long nofile;
547 struct list_head list;
548 /* head of the link, used by linked timeouts only */
549 struct io_kiocb *head;
552 struct io_timeout_rem {
557 struct timespec64 ts;
562 /* NOTE: kiocb has the file as the first member, so don't do it here */
570 struct sockaddr __user *addr;
577 struct compat_msghdr __user *umsg_compat;
578 struct user_msghdr __user *umsg;
584 struct io_buffer *kbuf;
590 struct filename *filename;
592 unsigned long nofile;
595 struct io_rsrc_update {
621 struct epoll_event event;
625 struct file *file_out;
626 struct file *file_in;
633 struct io_provide_buf {
647 const char __user *filename;
648 struct statx __user *buffer;
660 struct filename *oldpath;
661 struct filename *newpath;
669 struct filename *filename;
672 struct io_completion {
674 struct list_head list;
678 struct io_async_connect {
679 struct sockaddr_storage address;
682 struct io_async_msghdr {
683 struct iovec fast_iov[UIO_FASTIOV];
684 /* points to an allocated iov, if NULL we use fast_iov instead */
685 struct iovec *free_iov;
686 struct sockaddr __user *uaddr;
688 struct sockaddr_storage addr;
692 struct iovec fast_iov[UIO_FASTIOV];
693 const struct iovec *free_iovec;
694 struct iov_iter iter;
696 struct wait_page_queue wpq;
700 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
701 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
702 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
703 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
704 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
705 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
707 /* first byte is taken by user flags, shift it to not overlap */
708 REQ_F_FAIL_LINK_BIT = 8,
712 REQ_F_LINK_TIMEOUT_BIT,
713 REQ_F_NEED_CLEANUP_BIT,
715 REQ_F_BUFFER_SELECTED_BIT,
716 REQ_F_LTIMEOUT_ACTIVE_BIT,
717 REQ_F_COMPLETE_INLINE_BIT,
719 REQ_F_DONT_REISSUE_BIT,
720 /* keep async read/write and isreg together and in order */
721 REQ_F_ASYNC_READ_BIT,
722 REQ_F_ASYNC_WRITE_BIT,
725 /* not a real bit, just to check we're not overflowing the space */
731 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
732 /* drain existing IO first */
733 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
735 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
736 /* doesn't sever on completion < 0 */
737 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
739 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
740 /* IOSQE_BUFFER_SELECT */
741 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
743 /* fail rest of links */
744 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
745 /* on inflight list, should be cancelled and waited on exit reliably */
746 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
747 /* read/write uses file position */
748 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
749 /* must not punt to workers */
750 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
751 /* has or had linked timeout */
752 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
754 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
755 /* already went through poll handler */
756 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
757 /* buffer already selected */
758 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
759 /* linked timeout is active, i.e. prepared by link's head */
760 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
761 /* completion is deferred through io_comp_state */
762 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
763 /* caller should reissue async */
764 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
765 /* don't attempt request reissue, see io_rw_reissue() */
766 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
767 /* supports async reads */
768 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
769 /* supports async writes */
770 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
772 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
776 struct io_poll_iocb poll;
777 struct io_poll_iocb *double_poll;
780 struct io_task_work {
781 struct io_wq_work_node node;
782 task_work_func_t func;
786 IORING_RSRC_FILE = 0,
787 IORING_RSRC_BUFFER = 1,
791 * NOTE! Each of the iocb union members has the file pointer
792 * as the first entry in their struct definition. So you can
793 * access the file pointer through any of the sub-structs,
794 * or directly as just 'ki_filp' in this struct.
800 struct io_poll_iocb poll;
801 struct io_poll_update poll_update;
802 struct io_accept accept;
804 struct io_cancel cancel;
805 struct io_timeout timeout;
806 struct io_timeout_rem timeout_rem;
807 struct io_connect connect;
808 struct io_sr_msg sr_msg;
810 struct io_close close;
811 struct io_rsrc_update rsrc_update;
812 struct io_fadvise fadvise;
813 struct io_madvise madvise;
814 struct io_epoll epoll;
815 struct io_splice splice;
816 struct io_provide_buf pbuf;
817 struct io_statx statx;
818 struct io_shutdown shutdown;
819 struct io_rename rename;
820 struct io_unlink unlink;
821 /* use only after cleaning per-op data, see io_clean_op() */
822 struct io_completion compl;
825 /* opcode allocated if it needs to store data for async defer */
828 /* polled IO has completed */
834 struct io_ring_ctx *ctx;
837 struct task_struct *task;
840 struct io_kiocb *link;
841 struct percpu_ref *fixed_rsrc_refs;
843 /* used with ctx->iopoll_list with reads/writes */
844 struct list_head inflight_entry;
846 struct io_task_work io_task_work;
847 struct callback_head task_work;
849 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
850 struct hlist_node hash_node;
851 struct async_poll *apoll;
852 struct io_wq_work work;
853 const struct cred *creds;
855 /* store used ubuf, so we can prevent reloading */
856 struct io_mapped_ubuf *imu;
859 struct io_tctx_node {
860 struct list_head ctx_node;
861 struct task_struct *task;
862 struct io_ring_ctx *ctx;
865 struct io_defer_entry {
866 struct list_head list;
867 struct io_kiocb *req;
872 /* needs req->file assigned */
873 unsigned needs_file : 1;
874 /* hash wq insertion if file is a regular file */
875 unsigned hash_reg_file : 1;
876 /* unbound wq insertion if file is a non-regular file */
877 unsigned unbound_nonreg_file : 1;
878 /* opcode is not supported by this kernel */
879 unsigned not_supported : 1;
880 /* set if opcode supports polled "wait" */
882 unsigned pollout : 1;
883 /* op supports buffer selection */
884 unsigned buffer_select : 1;
885 /* do prep async if is going to be punted */
886 unsigned needs_async_setup : 1;
887 /* should block plug */
889 /* size of async data needed, if any */
890 unsigned short async_size;
893 static const struct io_op_def io_op_defs[] = {
894 [IORING_OP_NOP] = {},
895 [IORING_OP_READV] = {
897 .unbound_nonreg_file = 1,
900 .needs_async_setup = 1,
902 .async_size = sizeof(struct io_async_rw),
904 [IORING_OP_WRITEV] = {
907 .unbound_nonreg_file = 1,
909 .needs_async_setup = 1,
911 .async_size = sizeof(struct io_async_rw),
913 [IORING_OP_FSYNC] = {
916 [IORING_OP_READ_FIXED] = {
918 .unbound_nonreg_file = 1,
921 .async_size = sizeof(struct io_async_rw),
923 [IORING_OP_WRITE_FIXED] = {
926 .unbound_nonreg_file = 1,
929 .async_size = sizeof(struct io_async_rw),
931 [IORING_OP_POLL_ADD] = {
933 .unbound_nonreg_file = 1,
935 [IORING_OP_POLL_REMOVE] = {},
936 [IORING_OP_SYNC_FILE_RANGE] = {
939 [IORING_OP_SENDMSG] = {
941 .unbound_nonreg_file = 1,
943 .needs_async_setup = 1,
944 .async_size = sizeof(struct io_async_msghdr),
946 [IORING_OP_RECVMSG] = {
948 .unbound_nonreg_file = 1,
951 .needs_async_setup = 1,
952 .async_size = sizeof(struct io_async_msghdr),
954 [IORING_OP_TIMEOUT] = {
955 .async_size = sizeof(struct io_timeout_data),
957 [IORING_OP_TIMEOUT_REMOVE] = {
958 /* used by timeout updates' prep() */
960 [IORING_OP_ACCEPT] = {
962 .unbound_nonreg_file = 1,
965 [IORING_OP_ASYNC_CANCEL] = {},
966 [IORING_OP_LINK_TIMEOUT] = {
967 .async_size = sizeof(struct io_timeout_data),
969 [IORING_OP_CONNECT] = {
971 .unbound_nonreg_file = 1,
973 .needs_async_setup = 1,
974 .async_size = sizeof(struct io_async_connect),
976 [IORING_OP_FALLOCATE] = {
979 [IORING_OP_OPENAT] = {},
980 [IORING_OP_CLOSE] = {},
981 [IORING_OP_FILES_UPDATE] = {},
982 [IORING_OP_STATX] = {},
985 .unbound_nonreg_file = 1,
989 .async_size = sizeof(struct io_async_rw),
991 [IORING_OP_WRITE] = {
993 .unbound_nonreg_file = 1,
996 .async_size = sizeof(struct io_async_rw),
998 [IORING_OP_FADVISE] = {
1001 [IORING_OP_MADVISE] = {},
1002 [IORING_OP_SEND] = {
1004 .unbound_nonreg_file = 1,
1007 [IORING_OP_RECV] = {
1009 .unbound_nonreg_file = 1,
1013 [IORING_OP_OPENAT2] = {
1015 [IORING_OP_EPOLL_CTL] = {
1016 .unbound_nonreg_file = 1,
1018 [IORING_OP_SPLICE] = {
1021 .unbound_nonreg_file = 1,
1023 [IORING_OP_PROVIDE_BUFFERS] = {},
1024 [IORING_OP_REMOVE_BUFFERS] = {},
1028 .unbound_nonreg_file = 1,
1030 [IORING_OP_SHUTDOWN] = {
1033 [IORING_OP_RENAMEAT] = {},
1034 [IORING_OP_UNLINKAT] = {},
1037 static bool io_disarm_next(struct io_kiocb *req);
1038 static void io_uring_del_task_file(unsigned long index);
1039 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1040 struct task_struct *task,
1042 static void io_uring_cancel_sqpoll(struct io_sq_data *sqd);
1043 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1045 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1046 long res, unsigned int cflags);
1047 static void io_put_req(struct io_kiocb *req);
1048 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1049 static void io_dismantle_req(struct io_kiocb *req);
1050 static void io_put_task(struct task_struct *task, int nr);
1051 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1052 static void io_queue_linked_timeout(struct io_kiocb *req);
1053 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1054 struct io_uring_rsrc_update2 *up,
1056 static void io_clean_op(struct io_kiocb *req);
1057 static struct file *io_file_get(struct io_submit_state *state,
1058 struct io_kiocb *req, int fd, bool fixed);
1059 static void __io_queue_sqe(struct io_kiocb *req);
1060 static void io_rsrc_put_work(struct work_struct *work);
1062 static void io_req_task_queue(struct io_kiocb *req);
1063 static void io_submit_flush_completions(struct io_comp_state *cs,
1064 struct io_ring_ctx *ctx);
1065 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1066 static int io_req_prep_async(struct io_kiocb *req);
1068 static struct kmem_cache *req_cachep;
1070 static const struct file_operations io_uring_fops;
1072 struct sock *io_uring_get_socket(struct file *file)
1074 #if defined(CONFIG_UNIX)
1075 if (file->f_op == &io_uring_fops) {
1076 struct io_ring_ctx *ctx = file->private_data;
1078 return ctx->ring_sock->sk;
1083 EXPORT_SYMBOL(io_uring_get_socket);
1085 #define io_for_each_link(pos, head) \
1086 for (pos = (head); pos; pos = pos->link)
1088 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1090 struct io_ring_ctx *ctx = req->ctx;
1092 if (!req->fixed_rsrc_refs) {
1093 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1094 percpu_ref_get(req->fixed_rsrc_refs);
1098 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1100 bool got = percpu_ref_tryget(ref);
1102 /* already at zero, wait for ->release() */
1104 wait_for_completion(compl);
1105 percpu_ref_resurrect(ref);
1107 percpu_ref_put(ref);
1110 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1113 struct io_kiocb *req;
1115 if (task && head->task != task)
1120 io_for_each_link(req, head) {
1121 if (req->flags & REQ_F_INFLIGHT)
1127 static inline void req_set_fail_links(struct io_kiocb *req)
1129 if (req->flags & REQ_F_LINK)
1130 req->flags |= REQ_F_FAIL_LINK;
1133 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1135 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1137 complete(&ctx->ref_comp);
1140 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1142 return !req->timeout.off;
1145 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1147 struct io_ring_ctx *ctx;
1150 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1155 * Use 5 bits less than the max cq entries, that should give us around
1156 * 32 entries per hash list if totally full and uniformly spread.
1158 hash_bits = ilog2(p->cq_entries);
1162 ctx->cancel_hash_bits = hash_bits;
1163 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1165 if (!ctx->cancel_hash)
1167 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1169 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1170 if (!ctx->dummy_ubuf)
1172 /* set invalid range, so io_import_fixed() fails meeting it */
1173 ctx->dummy_ubuf->ubuf = -1UL;
1175 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1176 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1179 ctx->flags = p->flags;
1180 init_waitqueue_head(&ctx->sqo_sq_wait);
1181 INIT_LIST_HEAD(&ctx->sqd_list);
1182 init_waitqueue_head(&ctx->cq_wait);
1183 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1184 init_completion(&ctx->ref_comp);
1185 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1186 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1187 mutex_init(&ctx->uring_lock);
1188 init_waitqueue_head(&ctx->wait);
1189 spin_lock_init(&ctx->completion_lock);
1190 INIT_LIST_HEAD(&ctx->iopoll_list);
1191 INIT_LIST_HEAD(&ctx->defer_list);
1192 INIT_LIST_HEAD(&ctx->timeout_list);
1193 spin_lock_init(&ctx->rsrc_ref_lock);
1194 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1195 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1196 init_llist_head(&ctx->rsrc_put_llist);
1197 INIT_LIST_HEAD(&ctx->tctx_list);
1198 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1199 INIT_LIST_HEAD(&ctx->locked_free_list);
1202 kfree(ctx->dummy_ubuf);
1203 kfree(ctx->cancel_hash);
1208 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1210 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1211 struct io_ring_ctx *ctx = req->ctx;
1213 return seq + ctx->cq_extra != ctx->cached_cq_tail
1214 + READ_ONCE(ctx->cached_cq_overflow);
1220 static void io_req_track_inflight(struct io_kiocb *req)
1222 if (!(req->flags & REQ_F_INFLIGHT)) {
1223 req->flags |= REQ_F_INFLIGHT;
1224 atomic_inc(¤t->io_uring->inflight_tracked);
1228 static void io_prep_async_work(struct io_kiocb *req)
1230 const struct io_op_def *def = &io_op_defs[req->opcode];
1231 struct io_ring_ctx *ctx = req->ctx;
1234 req->creds = get_current_cred();
1236 req->work.list.next = NULL;
1237 req->work.flags = 0;
1238 if (req->flags & REQ_F_FORCE_ASYNC)
1239 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1241 if (req->flags & REQ_F_ISREG) {
1242 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1243 io_wq_hash_work(&req->work, file_inode(req->file));
1244 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1245 if (def->unbound_nonreg_file)
1246 req->work.flags |= IO_WQ_WORK_UNBOUND;
1249 switch (req->opcode) {
1250 case IORING_OP_SPLICE:
1252 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1253 req->work.flags |= IO_WQ_WORK_UNBOUND;
1258 static void io_prep_async_link(struct io_kiocb *req)
1260 struct io_kiocb *cur;
1262 if (req->flags & REQ_F_LINK_TIMEOUT) {
1263 struct io_ring_ctx *ctx = req->ctx;
1265 spin_lock_irq(&ctx->completion_lock);
1266 io_for_each_link(cur, req)
1267 io_prep_async_work(cur);
1268 spin_unlock_irq(&ctx->completion_lock);
1270 io_for_each_link(cur, req)
1271 io_prep_async_work(cur);
1275 static void io_queue_async_work(struct io_kiocb *req)
1277 struct io_ring_ctx *ctx = req->ctx;
1278 struct io_kiocb *link = io_prep_linked_timeout(req);
1279 struct io_uring_task *tctx = req->task->io_uring;
1282 BUG_ON(!tctx->io_wq);
1284 /* init ->work of the whole link before punting */
1285 io_prep_async_link(req);
1288 * Not expected to happen, but if we do have a bug where this _can_
1289 * happen, catch it here and ensure the request is marked as
1290 * canceled. That will make io-wq go through the usual work cancel
1291 * procedure rather than attempt to run this request (or create a new
1294 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1295 req->work.flags |= IO_WQ_WORK_CANCEL;
1297 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1298 &req->work, req->flags);
1299 io_wq_enqueue(tctx->io_wq, &req->work);
1301 io_queue_linked_timeout(link);
1304 static void io_kill_timeout(struct io_kiocb *req, int status)
1305 __must_hold(&req->ctx->completion_lock)
1307 struct io_timeout_data *io = req->async_data;
1309 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1310 atomic_set(&req->ctx->cq_timeouts,
1311 atomic_read(&req->ctx->cq_timeouts) + 1);
1312 list_del_init(&req->timeout.list);
1313 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1314 io_put_req_deferred(req, 1);
1318 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1321 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1322 struct io_defer_entry, list);
1324 if (req_need_defer(de->req, de->seq))
1326 list_del_init(&de->list);
1327 io_req_task_queue(de->req);
1329 } while (!list_empty(&ctx->defer_list));
1332 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1336 if (list_empty(&ctx->timeout_list))
1339 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1342 u32 events_needed, events_got;
1343 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1344 struct io_kiocb, timeout.list);
1346 if (io_is_timeout_noseq(req))
1350 * Since seq can easily wrap around over time, subtract
1351 * the last seq at which timeouts were flushed before comparing.
1352 * Assuming not more than 2^31-1 events have happened since,
1353 * these subtractions won't have wrapped, so we can check if
1354 * target is in [last_seq, current_seq] by comparing the two.
1356 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1357 events_got = seq - ctx->cq_last_tm_flush;
1358 if (events_got < events_needed)
1361 list_del_init(&req->timeout.list);
1362 io_kill_timeout(req, 0);
1363 } while (!list_empty(&ctx->timeout_list));
1365 ctx->cq_last_tm_flush = seq;
1368 static void io_commit_cqring(struct io_ring_ctx *ctx)
1370 io_flush_timeouts(ctx);
1372 /* order cqe stores with ring update */
1373 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1375 if (unlikely(!list_empty(&ctx->defer_list)))
1376 __io_queue_deferred(ctx);
1379 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1381 struct io_rings *r = ctx->rings;
1383 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1386 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1388 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1391 static inline struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1393 struct io_rings *rings = ctx->rings;
1397 * writes to the cq entry need to come after reading head; the
1398 * control dependency is enough as we're using WRITE_ONCE to
1401 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1404 tail = ctx->cached_cq_tail++;
1405 return &rings->cqes[tail & ctx->cq_mask];
1408 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1410 if (likely(!ctx->cq_ev_fd))
1412 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1414 return !ctx->eventfd_async || io_wq_current_is_worker();
1417 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1419 /* see waitqueue_active() comment */
1422 if (waitqueue_active(&ctx->wait))
1423 wake_up(&ctx->wait);
1424 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1425 wake_up(&ctx->sq_data->wait);
1426 if (io_should_trigger_evfd(ctx))
1427 eventfd_signal(ctx->cq_ev_fd, 1);
1428 if (waitqueue_active(&ctx->cq_wait)) {
1429 wake_up_interruptible(&ctx->cq_wait);
1430 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1434 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1436 /* see waitqueue_active() comment */
1439 if (ctx->flags & IORING_SETUP_SQPOLL) {
1440 if (waitqueue_active(&ctx->wait))
1441 wake_up(&ctx->wait);
1443 if (io_should_trigger_evfd(ctx))
1444 eventfd_signal(ctx->cq_ev_fd, 1);
1445 if (waitqueue_active(&ctx->cq_wait)) {
1446 wake_up_interruptible(&ctx->cq_wait);
1447 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1451 /* Returns true if there are no backlogged entries after the flush */
1452 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1454 struct io_rings *rings = ctx->rings;
1455 unsigned long flags;
1456 bool all_flushed, posted;
1458 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1462 spin_lock_irqsave(&ctx->completion_lock, flags);
1463 while (!list_empty(&ctx->cq_overflow_list)) {
1464 struct io_uring_cqe *cqe = io_get_cqring(ctx);
1465 struct io_overflow_cqe *ocqe;
1469 ocqe = list_first_entry(&ctx->cq_overflow_list,
1470 struct io_overflow_cqe, list);
1472 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1474 WRITE_ONCE(ctx->rings->cq_overflow,
1475 ++ctx->cached_cq_overflow);
1477 list_del(&ocqe->list);
1481 all_flushed = list_empty(&ctx->cq_overflow_list);
1483 clear_bit(0, &ctx->sq_check_overflow);
1484 clear_bit(0, &ctx->cq_check_overflow);
1485 WRITE_ONCE(ctx->rings->sq_flags,
1486 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1490 io_commit_cqring(ctx);
1491 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1493 io_cqring_ev_posted(ctx);
1497 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1501 if (test_bit(0, &ctx->cq_check_overflow)) {
1502 /* iopoll syncs against uring_lock, not completion_lock */
1503 if (ctx->flags & IORING_SETUP_IOPOLL)
1504 mutex_lock(&ctx->uring_lock);
1505 ret = __io_cqring_overflow_flush(ctx, force);
1506 if (ctx->flags & IORING_SETUP_IOPOLL)
1507 mutex_unlock(&ctx->uring_lock);
1514 * Shamelessly stolen from the mm implementation of page reference checking,
1515 * see commit f958d7b528b1 for details.
1517 #define req_ref_zero_or_close_to_overflow(req) \
1518 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1520 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1522 return atomic_inc_not_zero(&req->refs);
1525 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1527 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1528 return atomic_sub_and_test(refs, &req->refs);
1531 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1533 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1534 return atomic_dec_and_test(&req->refs);
1537 static inline void req_ref_put(struct io_kiocb *req)
1539 WARN_ON_ONCE(req_ref_put_and_test(req));
1542 static inline void req_ref_get(struct io_kiocb *req)
1544 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1545 atomic_inc(&req->refs);
1548 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1549 long res, unsigned int cflags)
1551 struct io_overflow_cqe *ocqe;
1553 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1556 * If we're in ring overflow flush mode, or in task cancel mode,
1557 * or cannot allocate an overflow entry, then we need to drop it
1560 WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
1563 if (list_empty(&ctx->cq_overflow_list)) {
1564 set_bit(0, &ctx->sq_check_overflow);
1565 set_bit(0, &ctx->cq_check_overflow);
1566 WRITE_ONCE(ctx->rings->sq_flags,
1567 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1570 ocqe->cqe.user_data = user_data;
1571 ocqe->cqe.res = res;
1572 ocqe->cqe.flags = cflags;
1573 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1577 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1578 long res, unsigned int cflags)
1580 struct io_uring_cqe *cqe;
1582 trace_io_uring_complete(ctx, user_data, res, cflags);
1585 * If we can't get a cq entry, userspace overflowed the
1586 * submission (by quite a lot). Increment the overflow count in
1589 cqe = io_get_cqring(ctx);
1591 WRITE_ONCE(cqe->user_data, user_data);
1592 WRITE_ONCE(cqe->res, res);
1593 WRITE_ONCE(cqe->flags, cflags);
1596 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1599 /* not as hot to bloat with inlining */
1600 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1601 long res, unsigned int cflags)
1603 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1606 static void io_req_complete_post(struct io_kiocb *req, long res,
1607 unsigned int cflags)
1609 struct io_ring_ctx *ctx = req->ctx;
1610 unsigned long flags;
1612 spin_lock_irqsave(&ctx->completion_lock, flags);
1613 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1615 * If we're the last reference to this request, add to our locked
1618 if (req_ref_put_and_test(req)) {
1619 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1620 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1621 io_disarm_next(req);
1623 io_req_task_queue(req->link);
1627 io_dismantle_req(req);
1628 io_put_task(req->task, 1);
1629 list_add(&req->compl.list, &ctx->locked_free_list);
1630 ctx->locked_free_nr++;
1632 if (!percpu_ref_tryget(&ctx->refs))
1635 io_commit_cqring(ctx);
1636 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1639 io_cqring_ev_posted(ctx);
1640 percpu_ref_put(&ctx->refs);
1644 static inline bool io_req_needs_clean(struct io_kiocb *req)
1646 return req->flags & (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP |
1647 REQ_F_POLLED | REQ_F_INFLIGHT);
1650 static void io_req_complete_state(struct io_kiocb *req, long res,
1651 unsigned int cflags)
1653 if (io_req_needs_clean(req))
1656 req->compl.cflags = cflags;
1657 req->flags |= REQ_F_COMPLETE_INLINE;
1660 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1661 long res, unsigned cflags)
1663 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1664 io_req_complete_state(req, res, cflags);
1666 io_req_complete_post(req, res, cflags);
1669 static inline void io_req_complete(struct io_kiocb *req, long res)
1671 __io_req_complete(req, 0, res, 0);
1674 static void io_req_complete_failed(struct io_kiocb *req, long res)
1676 req_set_fail_links(req);
1678 io_req_complete_post(req, res, 0);
1681 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1682 struct io_comp_state *cs)
1684 spin_lock_irq(&ctx->completion_lock);
1685 list_splice_init(&ctx->locked_free_list, &cs->free_list);
1686 ctx->locked_free_nr = 0;
1687 spin_unlock_irq(&ctx->completion_lock);
1690 /* Returns true IFF there are requests in the cache */
1691 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1693 struct io_submit_state *state = &ctx->submit_state;
1694 struct io_comp_state *cs = &state->comp;
1698 * If we have more than a batch's worth of requests in our IRQ side
1699 * locked cache, grab the lock and move them over to our submission
1702 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1703 io_flush_cached_locked_reqs(ctx, cs);
1705 nr = state->free_reqs;
1706 while (!list_empty(&cs->free_list)) {
1707 struct io_kiocb *req = list_first_entry(&cs->free_list,
1708 struct io_kiocb, compl.list);
1710 list_del(&req->compl.list);
1711 state->reqs[nr++] = req;
1712 if (nr == ARRAY_SIZE(state->reqs))
1716 state->free_reqs = nr;
1720 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1722 struct io_submit_state *state = &ctx->submit_state;
1724 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1726 if (!state->free_reqs) {
1727 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1730 if (io_flush_cached_reqs(ctx))
1733 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1737 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1738 * retry single alloc to be on the safe side.
1740 if (unlikely(ret <= 0)) {
1741 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1742 if (!state->reqs[0])
1746 state->free_reqs = ret;
1750 return state->reqs[state->free_reqs];
1753 static inline void io_put_file(struct file *file)
1759 static void io_dismantle_req(struct io_kiocb *req)
1761 unsigned int flags = req->flags;
1763 if (io_req_needs_clean(req))
1765 if (!(flags & REQ_F_FIXED_FILE))
1766 io_put_file(req->file);
1767 if (req->fixed_rsrc_refs)
1768 percpu_ref_put(req->fixed_rsrc_refs);
1769 if (req->async_data)
1770 kfree(req->async_data);
1772 put_cred(req->creds);
1777 /* must to be called somewhat shortly after putting a request */
1778 static inline void io_put_task(struct task_struct *task, int nr)
1780 struct io_uring_task *tctx = task->io_uring;
1782 percpu_counter_sub(&tctx->inflight, nr);
1783 if (unlikely(atomic_read(&tctx->in_idle)))
1784 wake_up(&tctx->wait);
1785 put_task_struct_many(task, nr);
1788 static void __io_free_req(struct io_kiocb *req)
1790 struct io_ring_ctx *ctx = req->ctx;
1792 io_dismantle_req(req);
1793 io_put_task(req->task, 1);
1795 kmem_cache_free(req_cachep, req);
1796 percpu_ref_put(&ctx->refs);
1799 static inline void io_remove_next_linked(struct io_kiocb *req)
1801 struct io_kiocb *nxt = req->link;
1803 req->link = nxt->link;
1807 static bool io_kill_linked_timeout(struct io_kiocb *req)
1808 __must_hold(&req->ctx->completion_lock)
1810 struct io_kiocb *link = req->link;
1813 * Can happen if a linked timeout fired and link had been like
1814 * req -> link t-out -> link t-out [-> ...]
1816 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1817 struct io_timeout_data *io = link->async_data;
1819 io_remove_next_linked(req);
1820 link->timeout.head = NULL;
1821 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1822 io_cqring_fill_event(link->ctx, link->user_data,
1824 io_put_req_deferred(link, 1);
1831 static void io_fail_links(struct io_kiocb *req)
1832 __must_hold(&req->ctx->completion_lock)
1834 struct io_kiocb *nxt, *link = req->link;
1841 trace_io_uring_fail_link(req, link);
1842 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1843 io_put_req_deferred(link, 2);
1848 static bool io_disarm_next(struct io_kiocb *req)
1849 __must_hold(&req->ctx->completion_lock)
1851 bool posted = false;
1853 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1854 posted = io_kill_linked_timeout(req);
1855 if (unlikely((req->flags & REQ_F_FAIL_LINK) &&
1856 !(req->flags & REQ_F_HARDLINK))) {
1857 posted |= (req->link != NULL);
1863 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1865 struct io_kiocb *nxt;
1868 * If LINK is set, we have dependent requests in this chain. If we
1869 * didn't fail this request, queue the first one up, moving any other
1870 * dependencies to the next request. In case of failure, fail the rest
1873 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1874 struct io_ring_ctx *ctx = req->ctx;
1875 unsigned long flags;
1878 spin_lock_irqsave(&ctx->completion_lock, flags);
1879 posted = io_disarm_next(req);
1881 io_commit_cqring(req->ctx);
1882 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1884 io_cqring_ev_posted(ctx);
1891 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1893 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1895 return __io_req_find_next(req);
1898 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1902 if (ctx->submit_state.comp.nr) {
1903 mutex_lock(&ctx->uring_lock);
1904 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1905 mutex_unlock(&ctx->uring_lock);
1907 percpu_ref_put(&ctx->refs);
1910 static void tctx_task_work(struct callback_head *cb)
1912 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1915 clear_bit(0, &tctx->task_state);
1918 struct io_ring_ctx *ctx = NULL;
1919 struct io_wq_work_list list;
1920 struct io_wq_work_node *node;
1922 spin_lock_irq(&tctx->task_lock);
1923 list = tctx->task_list;
1924 INIT_WQ_LIST(&tctx->task_list);
1925 spin_unlock_irq(&tctx->task_lock);
1927 if (wq_list_empty(&list))
1932 struct io_wq_work_node *next = node->next;
1933 struct io_kiocb *req = container_of(node, struct io_kiocb,
1936 if (req->ctx != ctx) {
1937 ctx_flush_and_put(ctx);
1939 percpu_ref_get(&ctx->refs);
1941 req->task_work.func(&req->task_work);
1945 ctx_flush_and_put(ctx);
1952 static int io_req_task_work_add(struct io_kiocb *req)
1954 struct task_struct *tsk = req->task;
1955 struct io_uring_task *tctx = tsk->io_uring;
1956 enum task_work_notify_mode notify;
1957 struct io_wq_work_node *node, *prev;
1958 unsigned long flags;
1961 if (unlikely(tsk->flags & PF_EXITING))
1964 WARN_ON_ONCE(!tctx);
1966 spin_lock_irqsave(&tctx->task_lock, flags);
1967 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1968 spin_unlock_irqrestore(&tctx->task_lock, flags);
1970 /* task_work already pending, we're done */
1971 if (test_bit(0, &tctx->task_state) ||
1972 test_and_set_bit(0, &tctx->task_state))
1976 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1977 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1978 * processing task_work. There's no reliable way to tell if TWA_RESUME
1981 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
1983 if (!task_work_add(tsk, &tctx->task_work, notify)) {
1984 wake_up_process(tsk);
1989 * Slow path - we failed, find and delete work. if the work is not
1990 * in the list, it got run and we're fine.
1992 spin_lock_irqsave(&tctx->task_lock, flags);
1993 wq_list_for_each(node, prev, &tctx->task_list) {
1994 if (&req->io_task_work.node == node) {
1995 wq_list_del(&tctx->task_list, node, prev);
2000 spin_unlock_irqrestore(&tctx->task_lock, flags);
2001 clear_bit(0, &tctx->task_state);
2005 static bool io_run_task_work_head(struct callback_head **work_head)
2007 struct callback_head *work, *next;
2008 bool executed = false;
2011 work = xchg(work_head, NULL);
2027 static void io_task_work_add_head(struct callback_head **work_head,
2028 struct callback_head *task_work)
2030 struct callback_head *head;
2033 head = READ_ONCE(*work_head);
2034 task_work->next = head;
2035 } while (cmpxchg(work_head, head, task_work) != head);
2038 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2039 task_work_func_t cb)
2041 init_task_work(&req->task_work, cb);
2042 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2045 static void io_req_task_cancel(struct callback_head *cb)
2047 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2048 struct io_ring_ctx *ctx = req->ctx;
2050 /* ctx is guaranteed to stay alive while we hold uring_lock */
2051 mutex_lock(&ctx->uring_lock);
2052 io_req_complete_failed(req, req->result);
2053 mutex_unlock(&ctx->uring_lock);
2056 static void __io_req_task_submit(struct io_kiocb *req)
2058 struct io_ring_ctx *ctx = req->ctx;
2060 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2061 mutex_lock(&ctx->uring_lock);
2062 if (!(req->task->flags & PF_EXITING) && !req->task->in_execve)
2063 __io_queue_sqe(req);
2065 io_req_complete_failed(req, -EFAULT);
2066 mutex_unlock(&ctx->uring_lock);
2069 static void io_req_task_submit(struct callback_head *cb)
2071 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2073 __io_req_task_submit(req);
2076 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2079 req->task_work.func = io_req_task_cancel;
2081 if (unlikely(io_req_task_work_add(req)))
2082 io_req_task_work_add_fallback(req, io_req_task_cancel);
2085 static void io_req_task_queue(struct io_kiocb *req)
2087 req->task_work.func = io_req_task_submit;
2089 if (unlikely(io_req_task_work_add(req)))
2090 io_req_task_queue_fail(req, -ECANCELED);
2093 static inline void io_queue_next(struct io_kiocb *req)
2095 struct io_kiocb *nxt = io_req_find_next(req);
2098 io_req_task_queue(nxt);
2101 static void io_free_req(struct io_kiocb *req)
2108 struct task_struct *task;
2113 static inline void io_init_req_batch(struct req_batch *rb)
2120 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2121 struct req_batch *rb)
2124 io_put_task(rb->task, rb->task_refs);
2126 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2129 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2130 struct io_submit_state *state)
2133 io_dismantle_req(req);
2135 if (req->task != rb->task) {
2137 io_put_task(rb->task, rb->task_refs);
2138 rb->task = req->task;
2144 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2145 state->reqs[state->free_reqs++] = req;
2147 list_add(&req->compl.list, &state->comp.free_list);
2150 static void io_submit_flush_completions(struct io_comp_state *cs,
2151 struct io_ring_ctx *ctx)
2154 struct io_kiocb *req;
2155 struct req_batch rb;
2157 io_init_req_batch(&rb);
2158 spin_lock_irq(&ctx->completion_lock);
2159 for (i = 0; i < nr; i++) {
2161 __io_cqring_fill_event(ctx, req->user_data, req->result,
2164 io_commit_cqring(ctx);
2165 spin_unlock_irq(&ctx->completion_lock);
2167 io_cqring_ev_posted(ctx);
2168 for (i = 0; i < nr; i++) {
2171 /* submission and completion refs */
2172 if (req_ref_sub_and_test(req, 2))
2173 io_req_free_batch(&rb, req, &ctx->submit_state);
2176 io_req_free_batch_finish(ctx, &rb);
2181 * Drop reference to request, return next in chain (if there is one) if this
2182 * was the last reference to this request.
2184 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2186 struct io_kiocb *nxt = NULL;
2188 if (req_ref_put_and_test(req)) {
2189 nxt = io_req_find_next(req);
2195 static inline void io_put_req(struct io_kiocb *req)
2197 if (req_ref_put_and_test(req))
2201 static void io_put_req_deferred_cb(struct callback_head *cb)
2203 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2208 static void io_free_req_deferred(struct io_kiocb *req)
2210 req->task_work.func = io_put_req_deferred_cb;
2211 if (unlikely(io_req_task_work_add(req)))
2212 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2215 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2217 if (req_ref_sub_and_test(req, refs))
2218 io_free_req_deferred(req);
2221 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2223 /* See comment at the top of this file */
2225 return __io_cqring_events(ctx);
2228 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2230 struct io_rings *rings = ctx->rings;
2232 /* make sure SQ entry isn't read before tail */
2233 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2236 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2238 unsigned int cflags;
2240 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2241 cflags |= IORING_CQE_F_BUFFER;
2242 req->flags &= ~REQ_F_BUFFER_SELECTED;
2247 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2249 struct io_buffer *kbuf;
2251 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2252 return io_put_kbuf(req, kbuf);
2255 static inline bool io_run_task_work(void)
2257 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2258 __set_current_state(TASK_RUNNING);
2259 tracehook_notify_signal();
2267 * Find and free completed poll iocbs
2269 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2270 struct list_head *done, bool resubmit)
2272 struct req_batch rb;
2273 struct io_kiocb *req;
2275 /* order with ->result store in io_complete_rw_iopoll() */
2278 io_init_req_batch(&rb);
2279 while (!list_empty(done)) {
2282 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2283 list_del(&req->inflight_entry);
2285 if (READ_ONCE(req->result) == -EAGAIN && resubmit &&
2286 !(req->flags & REQ_F_DONT_REISSUE)) {
2287 req->iopoll_completed = 0;
2289 io_queue_async_work(req);
2293 if (req->flags & REQ_F_BUFFER_SELECTED)
2294 cflags = io_put_rw_kbuf(req);
2296 __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2299 if (req_ref_put_and_test(req))
2300 io_req_free_batch(&rb, req, &ctx->submit_state);
2303 io_commit_cqring(ctx);
2304 io_cqring_ev_posted_iopoll(ctx);
2305 io_req_free_batch_finish(ctx, &rb);
2308 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2309 long min, bool resubmit)
2311 struct io_kiocb *req, *tmp;
2317 * Only spin for completions if we don't have multiple devices hanging
2318 * off our complete list, and we're under the requested amount.
2320 spin = !ctx->poll_multi_file && *nr_events < min;
2323 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2324 struct kiocb *kiocb = &req->rw.kiocb;
2327 * Move completed and retryable entries to our local lists.
2328 * If we find a request that requires polling, break out
2329 * and complete those lists first, if we have entries there.
2331 if (READ_ONCE(req->iopoll_completed)) {
2332 list_move_tail(&req->inflight_entry, &done);
2335 if (!list_empty(&done))
2338 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2342 /* iopoll may have completed current req */
2343 if (READ_ONCE(req->iopoll_completed))
2344 list_move_tail(&req->inflight_entry, &done);
2351 if (!list_empty(&done))
2352 io_iopoll_complete(ctx, nr_events, &done, resubmit);
2358 * We can't just wait for polled events to come to us, we have to actively
2359 * find and complete them.
2361 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2363 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2366 mutex_lock(&ctx->uring_lock);
2367 while (!list_empty(&ctx->iopoll_list)) {
2368 unsigned int nr_events = 0;
2370 io_do_iopoll(ctx, &nr_events, 0, false);
2372 /* let it sleep and repeat later if can't complete a request */
2376 * Ensure we allow local-to-the-cpu processing to take place,
2377 * in this case we need to ensure that we reap all events.
2378 * Also let task_work, etc. to progress by releasing the mutex
2380 if (need_resched()) {
2381 mutex_unlock(&ctx->uring_lock);
2383 mutex_lock(&ctx->uring_lock);
2386 mutex_unlock(&ctx->uring_lock);
2389 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2391 unsigned int nr_events = 0;
2395 * We disallow the app entering submit/complete with polling, but we
2396 * still need to lock the ring to prevent racing with polled issue
2397 * that got punted to a workqueue.
2399 mutex_lock(&ctx->uring_lock);
2401 * Don't enter poll loop if we already have events pending.
2402 * If we do, we can potentially be spinning for commands that
2403 * already triggered a CQE (eg in error).
2405 if (test_bit(0, &ctx->cq_check_overflow))
2406 __io_cqring_overflow_flush(ctx, false);
2407 if (io_cqring_events(ctx))
2411 * If a submit got punted to a workqueue, we can have the
2412 * application entering polling for a command before it gets
2413 * issued. That app will hold the uring_lock for the duration
2414 * of the poll right here, so we need to take a breather every
2415 * now and then to ensure that the issue has a chance to add
2416 * the poll to the issued list. Otherwise we can spin here
2417 * forever, while the workqueue is stuck trying to acquire the
2420 if (list_empty(&ctx->iopoll_list)) {
2421 mutex_unlock(&ctx->uring_lock);
2423 mutex_lock(&ctx->uring_lock);
2425 if (list_empty(&ctx->iopoll_list))
2428 ret = io_do_iopoll(ctx, &nr_events, min, true);
2429 } while (!ret && nr_events < min && !need_resched());
2431 mutex_unlock(&ctx->uring_lock);
2435 static void kiocb_end_write(struct io_kiocb *req)
2438 * Tell lockdep we inherited freeze protection from submission
2441 if (req->flags & REQ_F_ISREG) {
2442 struct super_block *sb = file_inode(req->file)->i_sb;
2444 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2450 static bool io_resubmit_prep(struct io_kiocb *req)
2452 struct io_async_rw *rw = req->async_data;
2455 return !io_req_prep_async(req);
2456 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2457 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2461 static bool io_rw_should_reissue(struct io_kiocb *req)
2463 umode_t mode = file_inode(req->file)->i_mode;
2464 struct io_ring_ctx *ctx = req->ctx;
2466 if (!S_ISBLK(mode) && !S_ISREG(mode))
2468 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2469 !(ctx->flags & IORING_SETUP_IOPOLL)))
2472 * If ref is dying, we might be running poll reap from the exit work.
2473 * Don't attempt to reissue from that path, just let it fail with
2476 if (percpu_ref_is_dying(&ctx->refs))
2479 * Play it safe and assume not safe to re-import and reissue if we're
2480 * not in the original thread group (or in task context).
2482 if (!same_thread_group(req->task, current) || !in_task())
2487 static bool io_resubmit_prep(struct io_kiocb *req)
2491 static bool io_rw_should_reissue(struct io_kiocb *req)
2497 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2498 unsigned int issue_flags)
2502 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2503 kiocb_end_write(req);
2504 if (res != req->result) {
2505 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2506 io_rw_should_reissue(req)) {
2507 req->flags |= REQ_F_REISSUE;
2510 req_set_fail_links(req);
2512 if (req->flags & REQ_F_BUFFER_SELECTED)
2513 cflags = io_put_rw_kbuf(req);
2514 __io_req_complete(req, issue_flags, res, cflags);
2517 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2519 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2521 __io_complete_rw(req, res, res2, 0);
2524 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2526 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2528 if (kiocb->ki_flags & IOCB_WRITE)
2529 kiocb_end_write(req);
2530 if (unlikely(res != req->result)) {
2531 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2532 io_resubmit_prep(req))) {
2533 req_set_fail_links(req);
2534 req->flags |= REQ_F_DONT_REISSUE;
2538 WRITE_ONCE(req->result, res);
2539 /* order with io_iopoll_complete() checking ->result */
2541 WRITE_ONCE(req->iopoll_completed, 1);
2545 * After the iocb has been issued, it's safe to be found on the poll list.
2546 * Adding the kiocb to the list AFTER submission ensures that we don't
2547 * find it from a io_do_iopoll() thread before the issuer is done
2548 * accessing the kiocb cookie.
2550 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2552 struct io_ring_ctx *ctx = req->ctx;
2555 * Track whether we have multiple files in our lists. This will impact
2556 * how we do polling eventually, not spinning if we're on potentially
2557 * different devices.
2559 if (list_empty(&ctx->iopoll_list)) {
2560 ctx->poll_multi_file = false;
2561 } else if (!ctx->poll_multi_file) {
2562 struct io_kiocb *list_req;
2564 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2566 if (list_req->file != req->file)
2567 ctx->poll_multi_file = true;
2571 * For fast devices, IO may have already completed. If it has, add
2572 * it to the front so we find it first.
2574 if (READ_ONCE(req->iopoll_completed))
2575 list_add(&req->inflight_entry, &ctx->iopoll_list);
2577 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2580 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2581 * task context or in io worker task context. If current task context is
2582 * sq thread, we don't need to check whether should wake up sq thread.
2584 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2585 wq_has_sleeper(&ctx->sq_data->wait))
2586 wake_up(&ctx->sq_data->wait);
2589 static inline void io_state_file_put(struct io_submit_state *state)
2591 if (state->file_refs) {
2592 fput_many(state->file, state->file_refs);
2593 state->file_refs = 0;
2598 * Get as many references to a file as we have IOs left in this submission,
2599 * assuming most submissions are for one file, or at least that each file
2600 * has more than one submission.
2602 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2607 if (state->file_refs) {
2608 if (state->fd == fd) {
2612 io_state_file_put(state);
2614 state->file = fget_many(fd, state->ios_left);
2615 if (unlikely(!state->file))
2619 state->file_refs = state->ios_left - 1;
2623 static bool io_bdev_nowait(struct block_device *bdev)
2625 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2629 * If we tracked the file through the SCM inflight mechanism, we could support
2630 * any file. For now, just ensure that anything potentially problematic is done
2633 static bool __io_file_supports_async(struct file *file, int rw)
2635 umode_t mode = file_inode(file)->i_mode;
2637 if (S_ISBLK(mode)) {
2638 if (IS_ENABLED(CONFIG_BLOCK) &&
2639 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2645 if (S_ISREG(mode)) {
2646 if (IS_ENABLED(CONFIG_BLOCK) &&
2647 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2648 file->f_op != &io_uring_fops)
2653 /* any ->read/write should understand O_NONBLOCK */
2654 if (file->f_flags & O_NONBLOCK)
2657 if (!(file->f_mode & FMODE_NOWAIT))
2661 return file->f_op->read_iter != NULL;
2663 return file->f_op->write_iter != NULL;
2666 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2668 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2670 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2673 return __io_file_supports_async(req->file, rw);
2676 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2678 struct io_ring_ctx *ctx = req->ctx;
2679 struct kiocb *kiocb = &req->rw.kiocb;
2680 struct file *file = req->file;
2684 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2685 req->flags |= REQ_F_ISREG;
2687 kiocb->ki_pos = READ_ONCE(sqe->off);
2688 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2689 req->flags |= REQ_F_CUR_POS;
2690 kiocb->ki_pos = file->f_pos;
2692 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2693 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2694 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2698 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2699 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2700 req->flags |= REQ_F_NOWAIT;
2702 ioprio = READ_ONCE(sqe->ioprio);
2704 ret = ioprio_check_cap(ioprio);
2708 kiocb->ki_ioprio = ioprio;
2710 kiocb->ki_ioprio = get_current_ioprio();
2712 if (ctx->flags & IORING_SETUP_IOPOLL) {
2713 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2714 !kiocb->ki_filp->f_op->iopoll)
2717 kiocb->ki_flags |= IOCB_HIPRI;
2718 kiocb->ki_complete = io_complete_rw_iopoll;
2719 req->iopoll_completed = 0;
2721 if (kiocb->ki_flags & IOCB_HIPRI)
2723 kiocb->ki_complete = io_complete_rw;
2726 if (req->opcode == IORING_OP_READ_FIXED ||
2727 req->opcode == IORING_OP_WRITE_FIXED) {
2729 io_req_set_rsrc_node(req);
2732 req->rw.addr = READ_ONCE(sqe->addr);
2733 req->rw.len = READ_ONCE(sqe->len);
2734 req->buf_index = READ_ONCE(sqe->buf_index);
2738 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2744 case -ERESTARTNOINTR:
2745 case -ERESTARTNOHAND:
2746 case -ERESTART_RESTARTBLOCK:
2748 * We can't just restart the syscall, since previously
2749 * submitted sqes may already be in progress. Just fail this
2755 kiocb->ki_complete(kiocb, ret, 0);
2759 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2760 unsigned int issue_flags)
2762 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2763 struct io_async_rw *io = req->async_data;
2764 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2766 /* add previously done IO, if any */
2767 if (io && io->bytes_done > 0) {
2769 ret = io->bytes_done;
2771 ret += io->bytes_done;
2774 if (req->flags & REQ_F_CUR_POS)
2775 req->file->f_pos = kiocb->ki_pos;
2776 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2777 __io_complete_rw(req, ret, 0, issue_flags);
2779 io_rw_done(kiocb, ret);
2781 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2782 req->flags &= ~REQ_F_REISSUE;
2783 if (io_resubmit_prep(req)) {
2785 io_queue_async_work(req);
2789 req_set_fail_links(req);
2790 if (req->flags & REQ_F_BUFFER_SELECTED)
2791 cflags = io_put_rw_kbuf(req);
2792 __io_req_complete(req, issue_flags, ret, cflags);
2797 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2798 struct io_mapped_ubuf *imu)
2800 size_t len = req->rw.len;
2801 u64 buf_end, buf_addr = req->rw.addr;
2804 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2806 /* not inside the mapped region */
2807 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2811 * May not be a start of buffer, set size appropriately
2812 * and advance us to the beginning.
2814 offset = buf_addr - imu->ubuf;
2815 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2819 * Don't use iov_iter_advance() here, as it's really slow for
2820 * using the latter parts of a big fixed buffer - it iterates
2821 * over each segment manually. We can cheat a bit here, because
2824 * 1) it's a BVEC iter, we set it up
2825 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2826 * first and last bvec
2828 * So just find our index, and adjust the iterator afterwards.
2829 * If the offset is within the first bvec (or the whole first
2830 * bvec, just use iov_iter_advance(). This makes it easier
2831 * since we can just skip the first segment, which may not
2832 * be PAGE_SIZE aligned.
2834 const struct bio_vec *bvec = imu->bvec;
2836 if (offset <= bvec->bv_len) {
2837 iov_iter_advance(iter, offset);
2839 unsigned long seg_skip;
2841 /* skip first vec */
2842 offset -= bvec->bv_len;
2843 seg_skip = 1 + (offset >> PAGE_SHIFT);
2845 iter->bvec = bvec + seg_skip;
2846 iter->nr_segs -= seg_skip;
2847 iter->count -= bvec->bv_len + offset;
2848 iter->iov_offset = offset & ~PAGE_MASK;
2855 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2857 struct io_ring_ctx *ctx = req->ctx;
2858 struct io_mapped_ubuf *imu = req->imu;
2859 u16 index, buf_index = req->buf_index;
2862 if (unlikely(buf_index >= ctx->nr_user_bufs))
2864 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2865 imu = READ_ONCE(ctx->user_bufs[index]);
2868 return __io_import_fixed(req, rw, iter, imu);
2871 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2874 mutex_unlock(&ctx->uring_lock);
2877 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2880 * "Normal" inline submissions always hold the uring_lock, since we
2881 * grab it from the system call. Same is true for the SQPOLL offload.
2882 * The only exception is when we've detached the request and issue it
2883 * from an async worker thread, grab the lock for that case.
2886 mutex_lock(&ctx->uring_lock);
2889 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2890 int bgid, struct io_buffer *kbuf,
2893 struct io_buffer *head;
2895 if (req->flags & REQ_F_BUFFER_SELECTED)
2898 io_ring_submit_lock(req->ctx, needs_lock);
2900 lockdep_assert_held(&req->ctx->uring_lock);
2902 head = xa_load(&req->ctx->io_buffers, bgid);
2904 if (!list_empty(&head->list)) {
2905 kbuf = list_last_entry(&head->list, struct io_buffer,
2907 list_del(&kbuf->list);
2910 xa_erase(&req->ctx->io_buffers, bgid);
2912 if (*len > kbuf->len)
2915 kbuf = ERR_PTR(-ENOBUFS);
2918 io_ring_submit_unlock(req->ctx, needs_lock);
2923 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2926 struct io_buffer *kbuf;
2929 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2930 bgid = req->buf_index;
2931 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2934 req->rw.addr = (u64) (unsigned long) kbuf;
2935 req->flags |= REQ_F_BUFFER_SELECTED;
2936 return u64_to_user_ptr(kbuf->addr);
2939 #ifdef CONFIG_COMPAT
2940 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2943 struct compat_iovec __user *uiov;
2944 compat_ssize_t clen;
2948 uiov = u64_to_user_ptr(req->rw.addr);
2949 if (!access_ok(uiov, sizeof(*uiov)))
2951 if (__get_user(clen, &uiov->iov_len))
2957 buf = io_rw_buffer_select(req, &len, needs_lock);
2959 return PTR_ERR(buf);
2960 iov[0].iov_base = buf;
2961 iov[0].iov_len = (compat_size_t) len;
2966 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2969 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2973 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2976 len = iov[0].iov_len;
2979 buf = io_rw_buffer_select(req, &len, needs_lock);
2981 return PTR_ERR(buf);
2982 iov[0].iov_base = buf;
2983 iov[0].iov_len = len;
2987 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2990 if (req->flags & REQ_F_BUFFER_SELECTED) {
2991 struct io_buffer *kbuf;
2993 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2994 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2995 iov[0].iov_len = kbuf->len;
2998 if (req->rw.len != 1)
3001 #ifdef CONFIG_COMPAT
3002 if (req->ctx->compat)
3003 return io_compat_import(req, iov, needs_lock);
3006 return __io_iov_buffer_select(req, iov, needs_lock);
3009 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3010 struct iov_iter *iter, bool needs_lock)
3012 void __user *buf = u64_to_user_ptr(req->rw.addr);
3013 size_t sqe_len = req->rw.len;
3014 u8 opcode = req->opcode;
3017 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3019 return io_import_fixed(req, rw, iter);
3022 /* buffer index only valid with fixed read/write, or buffer select */
3023 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3026 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3027 if (req->flags & REQ_F_BUFFER_SELECT) {
3028 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3030 return PTR_ERR(buf);
3031 req->rw.len = sqe_len;
3034 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3039 if (req->flags & REQ_F_BUFFER_SELECT) {
3040 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3042 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3047 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3051 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3053 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3057 * For files that don't have ->read_iter() and ->write_iter(), handle them
3058 * by looping over ->read() or ->write() manually.
3060 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3062 struct kiocb *kiocb = &req->rw.kiocb;
3063 struct file *file = req->file;
3067 * Don't support polled IO through this interface, and we can't
3068 * support non-blocking either. For the latter, this just causes
3069 * the kiocb to be handled from an async context.
3071 if (kiocb->ki_flags & IOCB_HIPRI)
3073 if (kiocb->ki_flags & IOCB_NOWAIT)
3076 while (iov_iter_count(iter)) {
3080 if (!iov_iter_is_bvec(iter)) {
3081 iovec = iov_iter_iovec(iter);
3083 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3084 iovec.iov_len = req->rw.len;
3088 nr = file->f_op->read(file, iovec.iov_base,
3089 iovec.iov_len, io_kiocb_ppos(kiocb));
3091 nr = file->f_op->write(file, iovec.iov_base,
3092 iovec.iov_len, io_kiocb_ppos(kiocb));
3101 if (nr != iovec.iov_len)
3105 iov_iter_advance(iter, nr);
3111 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3112 const struct iovec *fast_iov, struct iov_iter *iter)
3114 struct io_async_rw *rw = req->async_data;
3116 memcpy(&rw->iter, iter, sizeof(*iter));
3117 rw->free_iovec = iovec;
3119 /* can only be fixed buffers, no need to do anything */
3120 if (iov_iter_is_bvec(iter))
3123 unsigned iov_off = 0;
3125 rw->iter.iov = rw->fast_iov;
3126 if (iter->iov != fast_iov) {
3127 iov_off = iter->iov - fast_iov;
3128 rw->iter.iov += iov_off;
3130 if (rw->fast_iov != fast_iov)
3131 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3132 sizeof(struct iovec) * iter->nr_segs);
3134 req->flags |= REQ_F_NEED_CLEANUP;
3138 static inline int io_alloc_async_data(struct io_kiocb *req)
3140 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3141 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3142 return req->async_data == NULL;
3145 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3146 const struct iovec *fast_iov,
3147 struct iov_iter *iter, bool force)
3149 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3151 if (!req->async_data) {
3152 if (io_alloc_async_data(req)) {
3157 io_req_map_rw(req, iovec, fast_iov, iter);
3162 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3164 struct io_async_rw *iorw = req->async_data;
3165 struct iovec *iov = iorw->fast_iov;
3168 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3169 if (unlikely(ret < 0))
3172 iorw->bytes_done = 0;
3173 iorw->free_iovec = iov;
3175 req->flags |= REQ_F_NEED_CLEANUP;
3179 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3181 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3183 return io_prep_rw(req, sqe);
3187 * This is our waitqueue callback handler, registered through lock_page_async()
3188 * when we initially tried to do the IO with the iocb armed our waitqueue.
3189 * This gets called when the page is unlocked, and we generally expect that to
3190 * happen when the page IO is completed and the page is now uptodate. This will
3191 * queue a task_work based retry of the operation, attempting to copy the data
3192 * again. If the latter fails because the page was NOT uptodate, then we will
3193 * do a thread based blocking retry of the operation. That's the unexpected
3196 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3197 int sync, void *arg)
3199 struct wait_page_queue *wpq;
3200 struct io_kiocb *req = wait->private;
3201 struct wait_page_key *key = arg;
3203 wpq = container_of(wait, struct wait_page_queue, wait);
3205 if (!wake_page_match(wpq, key))
3208 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3209 list_del_init(&wait->entry);
3211 /* submit ref gets dropped, acquire a new one */
3213 io_req_task_queue(req);
3218 * This controls whether a given IO request should be armed for async page
3219 * based retry. If we return false here, the request is handed to the async
3220 * worker threads for retry. If we're doing buffered reads on a regular file,
3221 * we prepare a private wait_page_queue entry and retry the operation. This
3222 * will either succeed because the page is now uptodate and unlocked, or it
3223 * will register a callback when the page is unlocked at IO completion. Through
3224 * that callback, io_uring uses task_work to setup a retry of the operation.
3225 * That retry will attempt the buffered read again. The retry will generally
3226 * succeed, or in rare cases where it fails, we then fall back to using the
3227 * async worker threads for a blocking retry.
3229 static bool io_rw_should_retry(struct io_kiocb *req)
3231 struct io_async_rw *rw = req->async_data;
3232 struct wait_page_queue *wait = &rw->wpq;
3233 struct kiocb *kiocb = &req->rw.kiocb;
3235 /* never retry for NOWAIT, we just complete with -EAGAIN */
3236 if (req->flags & REQ_F_NOWAIT)
3239 /* Only for buffered IO */
3240 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3244 * just use poll if we can, and don't attempt if the fs doesn't
3245 * support callback based unlocks
3247 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3250 wait->wait.func = io_async_buf_func;
3251 wait->wait.private = req;
3252 wait->wait.flags = 0;
3253 INIT_LIST_HEAD(&wait->wait.entry);
3254 kiocb->ki_flags |= IOCB_WAITQ;
3255 kiocb->ki_flags &= ~IOCB_NOWAIT;
3256 kiocb->ki_waitq = wait;
3260 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3262 if (req->file->f_op->read_iter)
3263 return call_read_iter(req->file, &req->rw.kiocb, iter);
3264 else if (req->file->f_op->read)
3265 return loop_rw_iter(READ, req, iter);
3270 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3272 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3273 struct kiocb *kiocb = &req->rw.kiocb;
3274 struct iov_iter __iter, *iter = &__iter;
3275 struct io_async_rw *rw = req->async_data;
3276 ssize_t io_size, ret, ret2;
3277 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3283 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3287 io_size = iov_iter_count(iter);
3288 req->result = io_size;
3290 /* Ensure we clear previously set non-block flag */
3291 if (!force_nonblock)
3292 kiocb->ki_flags &= ~IOCB_NOWAIT;
3294 kiocb->ki_flags |= IOCB_NOWAIT;
3296 /* If the file doesn't support async, just async punt */
3297 if (force_nonblock && !io_file_supports_async(req, READ)) {
3298 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3299 return ret ?: -EAGAIN;
3302 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3303 if (unlikely(ret)) {
3308 ret = io_iter_do_read(req, iter);
3310 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3311 req->flags &= ~REQ_F_REISSUE;
3312 /* IOPOLL retry should happen for io-wq threads */
3313 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3315 /* no retry on NONBLOCK nor RWF_NOWAIT */
3316 if (req->flags & REQ_F_NOWAIT)
3318 /* some cases will consume bytes even on error returns */
3319 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3321 } else if (ret == -EIOCBQUEUED) {
3323 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3324 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3325 /* read all, failed, already did sync or don't want to retry */
3329 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3334 rw = req->async_data;
3335 /* now use our persistent iterator, if we aren't already */
3340 rw->bytes_done += ret;
3341 /* if we can retry, do so with the callbacks armed */
3342 if (!io_rw_should_retry(req)) {
3343 kiocb->ki_flags &= ~IOCB_WAITQ;
3348 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3349 * we get -EIOCBQUEUED, then we'll get a notification when the
3350 * desired page gets unlocked. We can also get a partial read
3351 * here, and if we do, then just retry at the new offset.
3353 ret = io_iter_do_read(req, iter);
3354 if (ret == -EIOCBQUEUED)
3356 /* we got some bytes, but not all. retry. */
3357 kiocb->ki_flags &= ~IOCB_WAITQ;
3358 } while (ret > 0 && ret < io_size);
3360 kiocb_done(kiocb, ret, issue_flags);
3362 /* it's faster to check here then delegate to kfree */
3368 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3370 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3372 return io_prep_rw(req, sqe);
3375 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3377 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3378 struct kiocb *kiocb = &req->rw.kiocb;
3379 struct iov_iter __iter, *iter = &__iter;
3380 struct io_async_rw *rw = req->async_data;
3381 ssize_t ret, ret2, io_size;
3382 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3388 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3392 io_size = iov_iter_count(iter);
3393 req->result = io_size;
3395 /* Ensure we clear previously set non-block flag */
3396 if (!force_nonblock)
3397 kiocb->ki_flags &= ~IOCB_NOWAIT;
3399 kiocb->ki_flags |= IOCB_NOWAIT;
3401 /* If the file doesn't support async, just async punt */
3402 if (force_nonblock && !io_file_supports_async(req, WRITE))
3405 /* file path doesn't support NOWAIT for non-direct_IO */
3406 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3407 (req->flags & REQ_F_ISREG))
3410 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3415 * Open-code file_start_write here to grab freeze protection,
3416 * which will be released by another thread in
3417 * io_complete_rw(). Fool lockdep by telling it the lock got
3418 * released so that it doesn't complain about the held lock when
3419 * we return to userspace.
3421 if (req->flags & REQ_F_ISREG) {
3422 sb_start_write(file_inode(req->file)->i_sb);
3423 __sb_writers_release(file_inode(req->file)->i_sb,
3426 kiocb->ki_flags |= IOCB_WRITE;
3428 if (req->file->f_op->write_iter)
3429 ret2 = call_write_iter(req->file, kiocb, iter);
3430 else if (req->file->f_op->write)
3431 ret2 = loop_rw_iter(WRITE, req, iter);
3435 if (req->flags & REQ_F_REISSUE) {
3436 req->flags &= ~REQ_F_REISSUE;
3441 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3442 * retry them without IOCB_NOWAIT.
3444 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3446 /* no retry on NONBLOCK nor RWF_NOWAIT */
3447 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3449 if (!force_nonblock || ret2 != -EAGAIN) {
3450 /* IOPOLL retry should happen for io-wq threads */
3451 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3454 kiocb_done(kiocb, ret2, issue_flags);
3457 /* some cases will consume bytes even on error returns */
3458 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3459 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3460 return ret ?: -EAGAIN;
3463 /* it's reportedly faster than delegating the null check to kfree() */
3469 static int io_renameat_prep(struct io_kiocb *req,
3470 const struct io_uring_sqe *sqe)
3472 struct io_rename *ren = &req->rename;
3473 const char __user *oldf, *newf;
3475 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3477 if (sqe->ioprio || sqe->buf_index)
3479 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3482 ren->old_dfd = READ_ONCE(sqe->fd);
3483 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3484 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3485 ren->new_dfd = READ_ONCE(sqe->len);
3486 ren->flags = READ_ONCE(sqe->rename_flags);
3488 ren->oldpath = getname(oldf);
3489 if (IS_ERR(ren->oldpath))
3490 return PTR_ERR(ren->oldpath);
3492 ren->newpath = getname(newf);
3493 if (IS_ERR(ren->newpath)) {
3494 putname(ren->oldpath);
3495 return PTR_ERR(ren->newpath);
3498 req->flags |= REQ_F_NEED_CLEANUP;
3502 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3504 struct io_rename *ren = &req->rename;
3507 if (issue_flags & IO_URING_F_NONBLOCK)
3510 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3511 ren->newpath, ren->flags);
3513 req->flags &= ~REQ_F_NEED_CLEANUP;
3515 req_set_fail_links(req);
3516 io_req_complete(req, ret);
3520 static int io_unlinkat_prep(struct io_kiocb *req,
3521 const struct io_uring_sqe *sqe)
3523 struct io_unlink *un = &req->unlink;
3524 const char __user *fname;
3526 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3528 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3530 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3533 un->dfd = READ_ONCE(sqe->fd);
3535 un->flags = READ_ONCE(sqe->unlink_flags);
3536 if (un->flags & ~AT_REMOVEDIR)
3539 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3540 un->filename = getname(fname);
3541 if (IS_ERR(un->filename))
3542 return PTR_ERR(un->filename);
3544 req->flags |= REQ_F_NEED_CLEANUP;
3548 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3550 struct io_unlink *un = &req->unlink;
3553 if (issue_flags & IO_URING_F_NONBLOCK)
3556 if (un->flags & AT_REMOVEDIR)
3557 ret = do_rmdir(un->dfd, un->filename);
3559 ret = do_unlinkat(un->dfd, un->filename);
3561 req->flags &= ~REQ_F_NEED_CLEANUP;
3563 req_set_fail_links(req);
3564 io_req_complete(req, ret);
3568 static int io_shutdown_prep(struct io_kiocb *req,
3569 const struct io_uring_sqe *sqe)
3571 #if defined(CONFIG_NET)
3572 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3574 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3578 req->shutdown.how = READ_ONCE(sqe->len);
3585 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3587 #if defined(CONFIG_NET)
3588 struct socket *sock;
3591 if (issue_flags & IO_URING_F_NONBLOCK)
3594 sock = sock_from_file(req->file);
3595 if (unlikely(!sock))
3598 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3600 req_set_fail_links(req);
3601 io_req_complete(req, ret);
3608 static int __io_splice_prep(struct io_kiocb *req,
3609 const struct io_uring_sqe *sqe)
3611 struct io_splice *sp = &req->splice;
3612 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3614 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3618 sp->len = READ_ONCE(sqe->len);
3619 sp->flags = READ_ONCE(sqe->splice_flags);
3621 if (unlikely(sp->flags & ~valid_flags))
3624 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3625 (sp->flags & SPLICE_F_FD_IN_FIXED));
3628 req->flags |= REQ_F_NEED_CLEANUP;
3632 static int io_tee_prep(struct io_kiocb *req,
3633 const struct io_uring_sqe *sqe)
3635 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3637 return __io_splice_prep(req, sqe);
3640 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3642 struct io_splice *sp = &req->splice;
3643 struct file *in = sp->file_in;
3644 struct file *out = sp->file_out;
3645 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3648 if (issue_flags & IO_URING_F_NONBLOCK)
3651 ret = do_tee(in, out, sp->len, flags);
3653 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3655 req->flags &= ~REQ_F_NEED_CLEANUP;
3658 req_set_fail_links(req);
3659 io_req_complete(req, ret);
3663 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3665 struct io_splice *sp = &req->splice;
3667 sp->off_in = READ_ONCE(sqe->splice_off_in);
3668 sp->off_out = READ_ONCE(sqe->off);
3669 return __io_splice_prep(req, sqe);
3672 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3674 struct io_splice *sp = &req->splice;
3675 struct file *in = sp->file_in;
3676 struct file *out = sp->file_out;
3677 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3678 loff_t *poff_in, *poff_out;
3681 if (issue_flags & IO_URING_F_NONBLOCK)
3684 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3685 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3688 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3690 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3692 req->flags &= ~REQ_F_NEED_CLEANUP;
3695 req_set_fail_links(req);
3696 io_req_complete(req, ret);
3701 * IORING_OP_NOP just posts a completion event, nothing else.
3703 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3705 struct io_ring_ctx *ctx = req->ctx;
3707 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3710 __io_req_complete(req, issue_flags, 0, 0);
3714 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3716 struct io_ring_ctx *ctx = req->ctx;
3721 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3723 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3726 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3727 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3730 req->sync.off = READ_ONCE(sqe->off);
3731 req->sync.len = READ_ONCE(sqe->len);
3735 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3737 loff_t end = req->sync.off + req->sync.len;
3740 /* fsync always requires a blocking context */
3741 if (issue_flags & IO_URING_F_NONBLOCK)
3744 ret = vfs_fsync_range(req->file, req->sync.off,
3745 end > 0 ? end : LLONG_MAX,
3746 req->sync.flags & IORING_FSYNC_DATASYNC);
3748 req_set_fail_links(req);
3749 io_req_complete(req, ret);
3753 static int io_fallocate_prep(struct io_kiocb *req,
3754 const struct io_uring_sqe *sqe)
3756 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3758 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3761 req->sync.off = READ_ONCE(sqe->off);
3762 req->sync.len = READ_ONCE(sqe->addr);
3763 req->sync.mode = READ_ONCE(sqe->len);
3767 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3771 /* fallocate always requiring blocking context */
3772 if (issue_flags & IO_URING_F_NONBLOCK)
3774 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3777 req_set_fail_links(req);
3778 io_req_complete(req, ret);
3782 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3784 const char __user *fname;
3787 if (unlikely(sqe->ioprio || sqe->buf_index))
3789 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3792 /* open.how should be already initialised */
3793 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3794 req->open.how.flags |= O_LARGEFILE;
3796 req->open.dfd = READ_ONCE(sqe->fd);
3797 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3798 req->open.filename = getname(fname);
3799 if (IS_ERR(req->open.filename)) {
3800 ret = PTR_ERR(req->open.filename);
3801 req->open.filename = NULL;
3804 req->open.nofile = rlimit(RLIMIT_NOFILE);
3805 req->flags |= REQ_F_NEED_CLEANUP;
3809 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3813 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3815 mode = READ_ONCE(sqe->len);
3816 flags = READ_ONCE(sqe->open_flags);
3817 req->open.how = build_open_how(flags, mode);
3818 return __io_openat_prep(req, sqe);
3821 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3823 struct open_how __user *how;
3827 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3829 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3830 len = READ_ONCE(sqe->len);
3831 if (len < OPEN_HOW_SIZE_VER0)
3834 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3839 return __io_openat_prep(req, sqe);
3842 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3844 struct open_flags op;
3847 bool resolve_nonblock;
3850 ret = build_open_flags(&req->open.how, &op);
3853 nonblock_set = op.open_flag & O_NONBLOCK;
3854 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3855 if (issue_flags & IO_URING_F_NONBLOCK) {
3857 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3858 * it'll always -EAGAIN
3860 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3862 op.lookup_flags |= LOOKUP_CACHED;
3863 op.open_flag |= O_NONBLOCK;
3866 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3870 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3871 /* only retry if RESOLVE_CACHED wasn't already set by application */
3872 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3873 file == ERR_PTR(-EAGAIN)) {
3875 * We could hang on to this 'fd', but seems like marginal
3876 * gain for something that is now known to be a slower path.
3877 * So just put it, and we'll get a new one when we retry.
3885 ret = PTR_ERR(file);
3887 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3888 file->f_flags &= ~O_NONBLOCK;
3889 fsnotify_open(file);
3890 fd_install(ret, file);
3893 putname(req->open.filename);
3894 req->flags &= ~REQ_F_NEED_CLEANUP;
3896 req_set_fail_links(req);
3897 __io_req_complete(req, issue_flags, ret, 0);
3901 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3903 return io_openat2(req, issue_flags);
3906 static int io_remove_buffers_prep(struct io_kiocb *req,
3907 const struct io_uring_sqe *sqe)
3909 struct io_provide_buf *p = &req->pbuf;
3912 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3915 tmp = READ_ONCE(sqe->fd);
3916 if (!tmp || tmp > USHRT_MAX)
3919 memset(p, 0, sizeof(*p));
3921 p->bgid = READ_ONCE(sqe->buf_group);
3925 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3926 int bgid, unsigned nbufs)
3930 /* shouldn't happen */
3934 /* the head kbuf is the list itself */
3935 while (!list_empty(&buf->list)) {
3936 struct io_buffer *nxt;
3938 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3939 list_del(&nxt->list);
3946 xa_erase(&ctx->io_buffers, bgid);
3951 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3953 struct io_provide_buf *p = &req->pbuf;
3954 struct io_ring_ctx *ctx = req->ctx;
3955 struct io_buffer *head;
3957 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3959 io_ring_submit_lock(ctx, !force_nonblock);
3961 lockdep_assert_held(&ctx->uring_lock);
3964 head = xa_load(&ctx->io_buffers, p->bgid);
3966 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3968 req_set_fail_links(req);
3970 /* complete before unlock, IOPOLL may need the lock */
3971 __io_req_complete(req, issue_flags, ret, 0);
3972 io_ring_submit_unlock(ctx, !force_nonblock);
3976 static int io_provide_buffers_prep(struct io_kiocb *req,
3977 const struct io_uring_sqe *sqe)
3979 unsigned long size, tmp_check;
3980 struct io_provide_buf *p = &req->pbuf;
3983 if (sqe->ioprio || sqe->rw_flags)
3986 tmp = READ_ONCE(sqe->fd);
3987 if (!tmp || tmp > USHRT_MAX)
3990 p->addr = READ_ONCE(sqe->addr);
3991 p->len = READ_ONCE(sqe->len);
3993 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3996 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3999 size = (unsigned long)p->len * p->nbufs;
4000 if (!access_ok(u64_to_user_ptr(p->addr), size))
4003 p->bgid = READ_ONCE(sqe->buf_group);
4004 tmp = READ_ONCE(sqe->off);
4005 if (tmp > USHRT_MAX)
4011 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4013 struct io_buffer *buf;
4014 u64 addr = pbuf->addr;
4015 int i, bid = pbuf->bid;
4017 for (i = 0; i < pbuf->nbufs; i++) {
4018 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4023 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4028 INIT_LIST_HEAD(&buf->list);
4031 list_add_tail(&buf->list, &(*head)->list);
4035 return i ? i : -ENOMEM;
4038 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4040 struct io_provide_buf *p = &req->pbuf;
4041 struct io_ring_ctx *ctx = req->ctx;
4042 struct io_buffer *head, *list;
4044 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4046 io_ring_submit_lock(ctx, !force_nonblock);
4048 lockdep_assert_held(&ctx->uring_lock);
4050 list = head = xa_load(&ctx->io_buffers, p->bgid);
4052 ret = io_add_buffers(p, &head);
4053 if (ret >= 0 && !list) {
4054 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4056 __io_remove_buffers(ctx, head, p->bgid, -1U);
4059 req_set_fail_links(req);
4060 /* complete before unlock, IOPOLL may need the lock */
4061 __io_req_complete(req, issue_flags, ret, 0);
4062 io_ring_submit_unlock(ctx, !force_nonblock);
4066 static int io_epoll_ctl_prep(struct io_kiocb *req,
4067 const struct io_uring_sqe *sqe)
4069 #if defined(CONFIG_EPOLL)
4070 if (sqe->ioprio || sqe->buf_index)
4072 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4075 req->epoll.epfd = READ_ONCE(sqe->fd);
4076 req->epoll.op = READ_ONCE(sqe->len);
4077 req->epoll.fd = READ_ONCE(sqe->off);
4079 if (ep_op_has_event(req->epoll.op)) {
4080 struct epoll_event __user *ev;
4082 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4083 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4093 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4095 #if defined(CONFIG_EPOLL)
4096 struct io_epoll *ie = &req->epoll;
4098 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4100 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4101 if (force_nonblock && ret == -EAGAIN)
4105 req_set_fail_links(req);
4106 __io_req_complete(req, issue_flags, ret, 0);
4113 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4115 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4116 if (sqe->ioprio || sqe->buf_index || sqe->off)
4118 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4121 req->madvise.addr = READ_ONCE(sqe->addr);
4122 req->madvise.len = READ_ONCE(sqe->len);
4123 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4130 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4132 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4133 struct io_madvise *ma = &req->madvise;
4136 if (issue_flags & IO_URING_F_NONBLOCK)
4139 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4141 req_set_fail_links(req);
4142 io_req_complete(req, ret);
4149 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4151 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4153 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4156 req->fadvise.offset = READ_ONCE(sqe->off);
4157 req->fadvise.len = READ_ONCE(sqe->len);
4158 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4162 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4164 struct io_fadvise *fa = &req->fadvise;
4167 if (issue_flags & IO_URING_F_NONBLOCK) {
4168 switch (fa->advice) {
4169 case POSIX_FADV_NORMAL:
4170 case POSIX_FADV_RANDOM:
4171 case POSIX_FADV_SEQUENTIAL:
4178 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4180 req_set_fail_links(req);
4181 __io_req_complete(req, issue_flags, ret, 0);
4185 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4187 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4189 if (sqe->ioprio || sqe->buf_index)
4191 if (req->flags & REQ_F_FIXED_FILE)
4194 req->statx.dfd = READ_ONCE(sqe->fd);
4195 req->statx.mask = READ_ONCE(sqe->len);
4196 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4197 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4198 req->statx.flags = READ_ONCE(sqe->statx_flags);
4203 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4205 struct io_statx *ctx = &req->statx;
4208 if (issue_flags & IO_URING_F_NONBLOCK)
4211 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4215 req_set_fail_links(req);
4216 io_req_complete(req, ret);
4220 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4222 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4224 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4225 sqe->rw_flags || sqe->buf_index)
4227 if (req->flags & REQ_F_FIXED_FILE)
4230 req->close.fd = READ_ONCE(sqe->fd);
4234 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4236 struct files_struct *files = current->files;
4237 struct io_close *close = &req->close;
4238 struct fdtable *fdt;
4239 struct file *file = NULL;
4242 spin_lock(&files->file_lock);
4243 fdt = files_fdtable(files);
4244 if (close->fd >= fdt->max_fds) {
4245 spin_unlock(&files->file_lock);
4248 file = fdt->fd[close->fd];
4249 if (!file || file->f_op == &io_uring_fops) {
4250 spin_unlock(&files->file_lock);
4255 /* if the file has a flush method, be safe and punt to async */
4256 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4257 spin_unlock(&files->file_lock);
4261 ret = __close_fd_get_file(close->fd, &file);
4262 spin_unlock(&files->file_lock);
4269 /* No ->flush() or already async, safely close from here */
4270 ret = filp_close(file, current->files);
4273 req_set_fail_links(req);
4276 __io_req_complete(req, issue_flags, ret, 0);
4280 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4282 struct io_ring_ctx *ctx = req->ctx;
4284 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4286 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4289 req->sync.off = READ_ONCE(sqe->off);
4290 req->sync.len = READ_ONCE(sqe->len);
4291 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4295 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4299 /* sync_file_range always requires a blocking context */
4300 if (issue_flags & IO_URING_F_NONBLOCK)
4303 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4306 req_set_fail_links(req);
4307 io_req_complete(req, ret);
4311 #if defined(CONFIG_NET)
4312 static int io_setup_async_msg(struct io_kiocb *req,
4313 struct io_async_msghdr *kmsg)
4315 struct io_async_msghdr *async_msg = req->async_data;
4319 if (io_alloc_async_data(req)) {
4320 kfree(kmsg->free_iov);
4323 async_msg = req->async_data;
4324 req->flags |= REQ_F_NEED_CLEANUP;
4325 memcpy(async_msg, kmsg, sizeof(*kmsg));
4326 async_msg->msg.msg_name = &async_msg->addr;
4327 /* if were using fast_iov, set it to the new one */
4328 if (!async_msg->free_iov)
4329 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4334 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4335 struct io_async_msghdr *iomsg)
4337 iomsg->msg.msg_name = &iomsg->addr;
4338 iomsg->free_iov = iomsg->fast_iov;
4339 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4340 req->sr_msg.msg_flags, &iomsg->free_iov);
4343 static int io_sendmsg_prep_async(struct io_kiocb *req)
4347 ret = io_sendmsg_copy_hdr(req, req->async_data);
4349 req->flags |= REQ_F_NEED_CLEANUP;
4353 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4355 struct io_sr_msg *sr = &req->sr_msg;
4357 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4360 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4361 sr->len = READ_ONCE(sqe->len);
4362 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4363 if (sr->msg_flags & MSG_DONTWAIT)
4364 req->flags |= REQ_F_NOWAIT;
4366 #ifdef CONFIG_COMPAT
4367 if (req->ctx->compat)
4368 sr->msg_flags |= MSG_CMSG_COMPAT;
4373 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4375 struct io_async_msghdr iomsg, *kmsg;
4376 struct socket *sock;
4381 sock = sock_from_file(req->file);
4382 if (unlikely(!sock))
4385 kmsg = req->async_data;
4387 ret = io_sendmsg_copy_hdr(req, &iomsg);
4393 flags = req->sr_msg.msg_flags;
4394 if (issue_flags & IO_URING_F_NONBLOCK)
4395 flags |= MSG_DONTWAIT;
4396 if (flags & MSG_WAITALL)
4397 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4399 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4400 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4401 return io_setup_async_msg(req, kmsg);
4402 if (ret == -ERESTARTSYS)
4405 /* fast path, check for non-NULL to avoid function call */
4407 kfree(kmsg->free_iov);
4408 req->flags &= ~REQ_F_NEED_CLEANUP;
4410 req_set_fail_links(req);
4411 __io_req_complete(req, issue_flags, ret, 0);
4415 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4417 struct io_sr_msg *sr = &req->sr_msg;
4420 struct socket *sock;
4425 sock = sock_from_file(req->file);
4426 if (unlikely(!sock))
4429 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4433 msg.msg_name = NULL;
4434 msg.msg_control = NULL;
4435 msg.msg_controllen = 0;
4436 msg.msg_namelen = 0;
4438 flags = req->sr_msg.msg_flags;
4439 if (issue_flags & IO_URING_F_NONBLOCK)
4440 flags |= MSG_DONTWAIT;
4441 if (flags & MSG_WAITALL)
4442 min_ret = iov_iter_count(&msg.msg_iter);
4444 msg.msg_flags = flags;
4445 ret = sock_sendmsg(sock, &msg);
4446 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4448 if (ret == -ERESTARTSYS)
4452 req_set_fail_links(req);
4453 __io_req_complete(req, issue_flags, ret, 0);
4457 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4458 struct io_async_msghdr *iomsg)
4460 struct io_sr_msg *sr = &req->sr_msg;
4461 struct iovec __user *uiov;
4465 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4466 &iomsg->uaddr, &uiov, &iov_len);
4470 if (req->flags & REQ_F_BUFFER_SELECT) {
4473 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4475 sr->len = iomsg->fast_iov[0].iov_len;
4476 iomsg->free_iov = NULL;
4478 iomsg->free_iov = iomsg->fast_iov;
4479 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4480 &iomsg->free_iov, &iomsg->msg.msg_iter,
4489 #ifdef CONFIG_COMPAT
4490 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4491 struct io_async_msghdr *iomsg)
4493 struct io_sr_msg *sr = &req->sr_msg;
4494 struct compat_iovec __user *uiov;
4499 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4504 uiov = compat_ptr(ptr);
4505 if (req->flags & REQ_F_BUFFER_SELECT) {
4506 compat_ssize_t clen;
4510 if (!access_ok(uiov, sizeof(*uiov)))
4512 if (__get_user(clen, &uiov->iov_len))
4517 iomsg->free_iov = NULL;
4519 iomsg->free_iov = iomsg->fast_iov;
4520 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4521 UIO_FASTIOV, &iomsg->free_iov,
4522 &iomsg->msg.msg_iter, true);
4531 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4532 struct io_async_msghdr *iomsg)
4534 iomsg->msg.msg_name = &iomsg->addr;
4536 #ifdef CONFIG_COMPAT
4537 if (req->ctx->compat)
4538 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4541 return __io_recvmsg_copy_hdr(req, iomsg);
4544 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4547 struct io_sr_msg *sr = &req->sr_msg;
4548 struct io_buffer *kbuf;
4550 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4555 req->flags |= REQ_F_BUFFER_SELECTED;
4559 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4561 return io_put_kbuf(req, req->sr_msg.kbuf);
4564 static int io_recvmsg_prep_async(struct io_kiocb *req)
4568 ret = io_recvmsg_copy_hdr(req, req->async_data);
4570 req->flags |= REQ_F_NEED_CLEANUP;
4574 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4576 struct io_sr_msg *sr = &req->sr_msg;
4578 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4581 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4582 sr->len = READ_ONCE(sqe->len);
4583 sr->bgid = READ_ONCE(sqe->buf_group);
4584 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4585 if (sr->msg_flags & MSG_DONTWAIT)
4586 req->flags |= REQ_F_NOWAIT;
4588 #ifdef CONFIG_COMPAT
4589 if (req->ctx->compat)
4590 sr->msg_flags |= MSG_CMSG_COMPAT;
4595 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4597 struct io_async_msghdr iomsg, *kmsg;
4598 struct socket *sock;
4599 struct io_buffer *kbuf;
4602 int ret, cflags = 0;
4603 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4605 sock = sock_from_file(req->file);
4606 if (unlikely(!sock))
4609 kmsg = req->async_data;
4611 ret = io_recvmsg_copy_hdr(req, &iomsg);
4617 if (req->flags & REQ_F_BUFFER_SELECT) {
4618 kbuf = io_recv_buffer_select(req, !force_nonblock);
4620 return PTR_ERR(kbuf);
4621 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4622 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4623 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4624 1, req->sr_msg.len);
4627 flags = req->sr_msg.msg_flags;
4629 flags |= MSG_DONTWAIT;
4630 if (flags & MSG_WAITALL)
4631 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4633 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4634 kmsg->uaddr, flags);
4635 if (force_nonblock && ret == -EAGAIN)
4636 return io_setup_async_msg(req, kmsg);
4637 if (ret == -ERESTARTSYS)
4640 if (req->flags & REQ_F_BUFFER_SELECTED)
4641 cflags = io_put_recv_kbuf(req);
4642 /* fast path, check for non-NULL to avoid function call */
4644 kfree(kmsg->free_iov);
4645 req->flags &= ~REQ_F_NEED_CLEANUP;
4646 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4647 req_set_fail_links(req);
4648 __io_req_complete(req, issue_flags, ret, cflags);
4652 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4654 struct io_buffer *kbuf;
4655 struct io_sr_msg *sr = &req->sr_msg;
4657 void __user *buf = sr->buf;
4658 struct socket *sock;
4662 int ret, cflags = 0;
4663 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4665 sock = sock_from_file(req->file);
4666 if (unlikely(!sock))
4669 if (req->flags & REQ_F_BUFFER_SELECT) {
4670 kbuf = io_recv_buffer_select(req, !force_nonblock);
4672 return PTR_ERR(kbuf);
4673 buf = u64_to_user_ptr(kbuf->addr);
4676 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4680 msg.msg_name = NULL;
4681 msg.msg_control = NULL;
4682 msg.msg_controllen = 0;
4683 msg.msg_namelen = 0;
4684 msg.msg_iocb = NULL;
4687 flags = req->sr_msg.msg_flags;
4689 flags |= MSG_DONTWAIT;
4690 if (flags & MSG_WAITALL)
4691 min_ret = iov_iter_count(&msg.msg_iter);
4693 ret = sock_recvmsg(sock, &msg, flags);
4694 if (force_nonblock && ret == -EAGAIN)
4696 if (ret == -ERESTARTSYS)
4699 if (req->flags & REQ_F_BUFFER_SELECTED)
4700 cflags = io_put_recv_kbuf(req);
4701 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4702 req_set_fail_links(req);
4703 __io_req_complete(req, issue_flags, ret, cflags);
4707 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4709 struct io_accept *accept = &req->accept;
4711 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4713 if (sqe->ioprio || sqe->len || sqe->buf_index)
4716 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4717 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4718 accept->flags = READ_ONCE(sqe->accept_flags);
4719 accept->nofile = rlimit(RLIMIT_NOFILE);
4723 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4725 struct io_accept *accept = &req->accept;
4726 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4727 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4730 if (req->file->f_flags & O_NONBLOCK)
4731 req->flags |= REQ_F_NOWAIT;
4733 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4734 accept->addr_len, accept->flags,
4736 if (ret == -EAGAIN && force_nonblock)
4739 if (ret == -ERESTARTSYS)
4741 req_set_fail_links(req);
4743 __io_req_complete(req, issue_flags, ret, 0);
4747 static int io_connect_prep_async(struct io_kiocb *req)
4749 struct io_async_connect *io = req->async_data;
4750 struct io_connect *conn = &req->connect;
4752 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4755 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4757 struct io_connect *conn = &req->connect;
4759 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4761 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4764 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4765 conn->addr_len = READ_ONCE(sqe->addr2);
4769 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4771 struct io_async_connect __io, *io;
4772 unsigned file_flags;
4774 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4776 if (req->async_data) {
4777 io = req->async_data;
4779 ret = move_addr_to_kernel(req->connect.addr,
4780 req->connect.addr_len,
4787 file_flags = force_nonblock ? O_NONBLOCK : 0;
4789 ret = __sys_connect_file(req->file, &io->address,
4790 req->connect.addr_len, file_flags);
4791 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4792 if (req->async_data)
4794 if (io_alloc_async_data(req)) {
4798 memcpy(req->async_data, &__io, sizeof(__io));
4801 if (ret == -ERESTARTSYS)
4805 req_set_fail_links(req);
4806 __io_req_complete(req, issue_flags, ret, 0);
4809 #else /* !CONFIG_NET */
4810 #define IO_NETOP_FN(op) \
4811 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4813 return -EOPNOTSUPP; \
4816 #define IO_NETOP_PREP(op) \
4818 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4820 return -EOPNOTSUPP; \
4823 #define IO_NETOP_PREP_ASYNC(op) \
4825 static int io_##op##_prep_async(struct io_kiocb *req) \
4827 return -EOPNOTSUPP; \
4830 IO_NETOP_PREP_ASYNC(sendmsg);
4831 IO_NETOP_PREP_ASYNC(recvmsg);
4832 IO_NETOP_PREP_ASYNC(connect);
4833 IO_NETOP_PREP(accept);
4836 #endif /* CONFIG_NET */
4838 struct io_poll_table {
4839 struct poll_table_struct pt;
4840 struct io_kiocb *req;
4845 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4846 __poll_t mask, task_work_func_t func)
4850 /* for instances that support it check for an event match first: */
4851 if (mask && !(mask & poll->events))
4854 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4856 list_del_init(&poll->wait.entry);
4859 req->task_work.func = func;
4862 * If this fails, then the task is exiting. When a task exits, the
4863 * work gets canceled, so just cancel this request as well instead
4864 * of executing it. We can't safely execute it anyway, as we may not
4865 * have the needed state needed for it anyway.
4867 ret = io_req_task_work_add(req);
4868 if (unlikely(ret)) {
4869 WRITE_ONCE(poll->canceled, true);
4870 io_req_task_work_add_fallback(req, func);
4875 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4876 __acquires(&req->ctx->completion_lock)
4878 struct io_ring_ctx *ctx = req->ctx;
4880 if (!req->result && !READ_ONCE(poll->canceled)) {
4881 struct poll_table_struct pt = { ._key = poll->events };
4883 req->result = vfs_poll(req->file, &pt) & poll->events;
4886 spin_lock_irq(&ctx->completion_lock);
4887 if (!req->result && !READ_ONCE(poll->canceled)) {
4888 add_wait_queue(poll->head, &poll->wait);
4895 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4897 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4898 if (req->opcode == IORING_OP_POLL_ADD)
4899 return req->async_data;
4900 return req->apoll->double_poll;
4903 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4905 if (req->opcode == IORING_OP_POLL_ADD)
4907 return &req->apoll->poll;
4910 static void io_poll_remove_double(struct io_kiocb *req)
4911 __must_hold(&req->ctx->completion_lock)
4913 struct io_poll_iocb *poll = io_poll_get_double(req);
4915 lockdep_assert_held(&req->ctx->completion_lock);
4917 if (poll && poll->head) {
4918 struct wait_queue_head *head = poll->head;
4920 spin_lock(&head->lock);
4921 list_del_init(&poll->wait.entry);
4922 if (poll->wait.private)
4925 spin_unlock(&head->lock);
4929 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4930 __must_hold(&req->ctx->completion_lock)
4932 struct io_ring_ctx *ctx = req->ctx;
4933 unsigned flags = IORING_CQE_F_MORE;
4936 if (READ_ONCE(req->poll.canceled)) {
4938 req->poll.events |= EPOLLONESHOT;
4940 error = mangle_poll(mask);
4942 if (req->poll.events & EPOLLONESHOT)
4944 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4945 req->poll.done = true;
4948 if (flags & IORING_CQE_F_MORE)
4951 io_commit_cqring(ctx);
4952 return !(flags & IORING_CQE_F_MORE);
4955 static void io_poll_task_func(struct callback_head *cb)
4957 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4958 struct io_ring_ctx *ctx = req->ctx;
4959 struct io_kiocb *nxt;
4961 if (io_poll_rewait(req, &req->poll)) {
4962 spin_unlock_irq(&ctx->completion_lock);
4966 done = io_poll_complete(req, req->result);
4968 io_poll_remove_double(req);
4969 hash_del(&req->hash_node);
4972 add_wait_queue(req->poll.head, &req->poll.wait);
4974 spin_unlock_irq(&ctx->completion_lock);
4975 io_cqring_ev_posted(ctx);
4978 nxt = io_put_req_find_next(req);
4980 __io_req_task_submit(nxt);
4985 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4986 int sync, void *key)
4988 struct io_kiocb *req = wait->private;
4989 struct io_poll_iocb *poll = io_poll_get_single(req);
4990 __poll_t mask = key_to_poll(key);
4992 /* for instances that support it check for an event match first: */
4993 if (mask && !(mask & poll->events))
4995 if (!(poll->events & EPOLLONESHOT))
4996 return poll->wait.func(&poll->wait, mode, sync, key);
4998 list_del_init(&wait->entry);
5000 if (poll && poll->head) {
5003 spin_lock(&poll->head->lock);
5004 done = list_empty(&poll->wait.entry);
5006 list_del_init(&poll->wait.entry);
5007 /* make sure double remove sees this as being gone */
5008 wait->private = NULL;
5009 spin_unlock(&poll->head->lock);
5011 /* use wait func handler, so it matches the rq type */
5012 poll->wait.func(&poll->wait, mode, sync, key);
5019 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5020 wait_queue_func_t wake_func)
5024 poll->canceled = false;
5025 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5026 /* mask in events that we always want/need */
5027 poll->events = events | IO_POLL_UNMASK;
5028 INIT_LIST_HEAD(&poll->wait.entry);
5029 init_waitqueue_func_entry(&poll->wait, wake_func);
5032 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5033 struct wait_queue_head *head,
5034 struct io_poll_iocb **poll_ptr)
5036 struct io_kiocb *req = pt->req;
5039 * The file being polled uses multiple waitqueues for poll handling
5040 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5043 if (unlikely(pt->nr_entries)) {
5044 struct io_poll_iocb *poll_one = poll;
5046 /* already have a 2nd entry, fail a third attempt */
5048 pt->error = -EINVAL;
5052 * Can't handle multishot for double wait for now, turn it
5053 * into one-shot mode.
5055 if (!(poll_one->events & EPOLLONESHOT))
5056 poll_one->events |= EPOLLONESHOT;
5057 /* double add on the same waitqueue head, ignore */
5058 if (poll_one->head == head)
5060 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5062 pt->error = -ENOMEM;
5065 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5067 poll->wait.private = req;
5074 if (poll->events & EPOLLEXCLUSIVE)
5075 add_wait_queue_exclusive(head, &poll->wait);
5077 add_wait_queue(head, &poll->wait);
5080 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5081 struct poll_table_struct *p)
5083 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5084 struct async_poll *apoll = pt->req->apoll;
5086 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5089 static void io_async_task_func(struct callback_head *cb)
5091 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5092 struct async_poll *apoll = req->apoll;
5093 struct io_ring_ctx *ctx = req->ctx;
5095 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5097 if (io_poll_rewait(req, &apoll->poll)) {
5098 spin_unlock_irq(&ctx->completion_lock);
5102 hash_del(&req->hash_node);
5103 io_poll_remove_double(req);
5104 spin_unlock_irq(&ctx->completion_lock);
5106 if (!READ_ONCE(apoll->poll.canceled))
5107 __io_req_task_submit(req);
5109 io_req_complete_failed(req, -ECANCELED);
5112 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5115 struct io_kiocb *req = wait->private;
5116 struct io_poll_iocb *poll = &req->apoll->poll;
5118 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5121 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5124 static void io_poll_req_insert(struct io_kiocb *req)
5126 struct io_ring_ctx *ctx = req->ctx;
5127 struct hlist_head *list;
5129 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5130 hlist_add_head(&req->hash_node, list);
5133 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5134 struct io_poll_iocb *poll,
5135 struct io_poll_table *ipt, __poll_t mask,
5136 wait_queue_func_t wake_func)
5137 __acquires(&ctx->completion_lock)
5139 struct io_ring_ctx *ctx = req->ctx;
5140 bool cancel = false;
5142 INIT_HLIST_NODE(&req->hash_node);
5143 io_init_poll_iocb(poll, mask, wake_func);
5144 poll->file = req->file;
5145 poll->wait.private = req;
5147 ipt->pt._key = mask;
5150 ipt->nr_entries = 0;
5152 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5153 if (unlikely(!ipt->nr_entries) && !ipt->error)
5154 ipt->error = -EINVAL;
5156 spin_lock_irq(&ctx->completion_lock);
5157 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5158 io_poll_remove_double(req);
5159 if (likely(poll->head)) {
5160 spin_lock(&poll->head->lock);
5161 if (unlikely(list_empty(&poll->wait.entry))) {
5167 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5168 list_del_init(&poll->wait.entry);
5170 WRITE_ONCE(poll->canceled, true);
5171 else if (!poll->done) /* actually waiting for an event */
5172 io_poll_req_insert(req);
5173 spin_unlock(&poll->head->lock);
5179 static bool io_arm_poll_handler(struct io_kiocb *req)
5181 const struct io_op_def *def = &io_op_defs[req->opcode];
5182 struct io_ring_ctx *ctx = req->ctx;
5183 struct async_poll *apoll;
5184 struct io_poll_table ipt;
5188 if (!req->file || !file_can_poll(req->file))
5190 if (req->flags & REQ_F_POLLED)
5194 else if (def->pollout)
5198 /* if we can't nonblock try, then no point in arming a poll handler */
5199 if (!io_file_supports_async(req, rw))
5202 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5203 if (unlikely(!apoll))
5205 apoll->double_poll = NULL;
5207 req->flags |= REQ_F_POLLED;
5210 mask = EPOLLONESHOT;
5212 mask |= POLLIN | POLLRDNORM;
5214 mask |= POLLOUT | POLLWRNORM;
5216 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5217 if ((req->opcode == IORING_OP_RECVMSG) &&
5218 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5221 mask |= POLLERR | POLLPRI;
5223 ipt.pt._qproc = io_async_queue_proc;
5225 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5227 if (ret || ipt.error) {
5228 spin_unlock_irq(&ctx->completion_lock);
5231 spin_unlock_irq(&ctx->completion_lock);
5232 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5233 apoll->poll.events);
5237 static bool __io_poll_remove_one(struct io_kiocb *req,
5238 struct io_poll_iocb *poll, bool do_cancel)
5239 __must_hold(&req->ctx->completion_lock)
5241 bool do_complete = false;
5245 spin_lock(&poll->head->lock);
5247 WRITE_ONCE(poll->canceled, true);
5248 if (!list_empty(&poll->wait.entry)) {
5249 list_del_init(&poll->wait.entry);
5252 spin_unlock(&poll->head->lock);
5253 hash_del(&req->hash_node);
5257 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5258 __must_hold(&req->ctx->completion_lock)
5262 io_poll_remove_double(req);
5263 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5265 if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
5266 /* non-poll requests have submit ref still */
5272 static bool io_poll_remove_one(struct io_kiocb *req)
5273 __must_hold(&req->ctx->completion_lock)
5277 do_complete = io_poll_remove_waitqs(req);
5279 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5280 io_commit_cqring(req->ctx);
5281 req_set_fail_links(req);
5282 io_put_req_deferred(req, 1);
5289 * Returns true if we found and killed one or more poll requests
5291 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5294 struct hlist_node *tmp;
5295 struct io_kiocb *req;
5298 spin_lock_irq(&ctx->completion_lock);
5299 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5300 struct hlist_head *list;
5302 list = &ctx->cancel_hash[i];
5303 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5304 if (io_match_task(req, tsk, cancel_all))
5305 posted += io_poll_remove_one(req);
5308 spin_unlock_irq(&ctx->completion_lock);
5311 io_cqring_ev_posted(ctx);
5316 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5318 __must_hold(&ctx->completion_lock)
5320 struct hlist_head *list;
5321 struct io_kiocb *req;
5323 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5324 hlist_for_each_entry(req, list, hash_node) {
5325 if (sqe_addr != req->user_data)
5327 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5334 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5336 __must_hold(&ctx->completion_lock)
5338 struct io_kiocb *req;
5340 req = io_poll_find(ctx, sqe_addr, poll_only);
5343 if (io_poll_remove_one(req))
5349 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5354 events = READ_ONCE(sqe->poll32_events);
5356 events = swahw32(events);
5358 if (!(flags & IORING_POLL_ADD_MULTI))
5359 events |= EPOLLONESHOT;
5360 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5363 static int io_poll_update_prep(struct io_kiocb *req,
5364 const struct io_uring_sqe *sqe)
5366 struct io_poll_update *upd = &req->poll_update;
5369 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5371 if (sqe->ioprio || sqe->buf_index)
5373 flags = READ_ONCE(sqe->len);
5374 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5375 IORING_POLL_ADD_MULTI))
5377 /* meaningless without update */
5378 if (flags == IORING_POLL_ADD_MULTI)
5381 upd->old_user_data = READ_ONCE(sqe->addr);
5382 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5383 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5385 upd->new_user_data = READ_ONCE(sqe->off);
5386 if (!upd->update_user_data && upd->new_user_data)
5388 if (upd->update_events)
5389 upd->events = io_poll_parse_events(sqe, flags);
5390 else if (sqe->poll32_events)
5396 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5399 struct io_kiocb *req = wait->private;
5400 struct io_poll_iocb *poll = &req->poll;
5402 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5405 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5406 struct poll_table_struct *p)
5408 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5410 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5413 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5415 struct io_poll_iocb *poll = &req->poll;
5418 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5420 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5422 flags = READ_ONCE(sqe->len);
5423 if (flags & ~IORING_POLL_ADD_MULTI)
5426 poll->events = io_poll_parse_events(sqe, flags);
5430 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5432 struct io_poll_iocb *poll = &req->poll;
5433 struct io_ring_ctx *ctx = req->ctx;
5434 struct io_poll_table ipt;
5437 ipt.pt._qproc = io_poll_queue_proc;
5439 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5442 if (mask) { /* no async, we'd stolen it */
5444 io_poll_complete(req, mask);
5446 spin_unlock_irq(&ctx->completion_lock);
5449 io_cqring_ev_posted(ctx);
5450 if (poll->events & EPOLLONESHOT)
5456 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5458 struct io_ring_ctx *ctx = req->ctx;
5459 struct io_kiocb *preq;
5463 spin_lock_irq(&ctx->completion_lock);
5464 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5470 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5472 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5477 * Don't allow racy completion with singleshot, as we cannot safely
5478 * update those. For multishot, if we're racing with completion, just
5479 * let completion re-add it.
5481 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5482 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5486 /* we now have a detached poll request. reissue. */
5490 spin_unlock_irq(&ctx->completion_lock);
5491 req_set_fail_links(req);
5492 io_req_complete(req, ret);
5495 /* only mask one event flags, keep behavior flags */
5496 if (req->poll_update.update_events) {
5497 preq->poll.events &= ~0xffff;
5498 preq->poll.events |= req->poll_update.events & 0xffff;
5499 preq->poll.events |= IO_POLL_UNMASK;
5501 if (req->poll_update.update_user_data)
5502 preq->user_data = req->poll_update.new_user_data;
5503 spin_unlock_irq(&ctx->completion_lock);
5505 /* complete update request, we're done with it */
5506 io_req_complete(req, ret);
5509 ret = io_poll_add(preq, issue_flags);
5511 req_set_fail_links(preq);
5512 io_req_complete(preq, ret);
5518 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5520 struct io_timeout_data *data = container_of(timer,
5521 struct io_timeout_data, timer);
5522 struct io_kiocb *req = data->req;
5523 struct io_ring_ctx *ctx = req->ctx;
5524 unsigned long flags;
5526 spin_lock_irqsave(&ctx->completion_lock, flags);
5527 list_del_init(&req->timeout.list);
5528 atomic_set(&req->ctx->cq_timeouts,
5529 atomic_read(&req->ctx->cq_timeouts) + 1);
5531 io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5532 io_commit_cqring(ctx);
5533 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5535 io_cqring_ev_posted(ctx);
5536 req_set_fail_links(req);
5538 return HRTIMER_NORESTART;
5541 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5543 __must_hold(&ctx->completion_lock)
5545 struct io_timeout_data *io;
5546 struct io_kiocb *req;
5549 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5550 found = user_data == req->user_data;
5555 return ERR_PTR(-ENOENT);
5557 io = req->async_data;
5558 if (hrtimer_try_to_cancel(&io->timer) == -1)
5559 return ERR_PTR(-EALREADY);
5560 list_del_init(&req->timeout.list);
5564 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5565 __must_hold(&ctx->completion_lock)
5567 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5570 return PTR_ERR(req);
5572 req_set_fail_links(req);
5573 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5574 io_put_req_deferred(req, 1);
5578 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5579 struct timespec64 *ts, enum hrtimer_mode mode)
5580 __must_hold(&ctx->completion_lock)
5582 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5583 struct io_timeout_data *data;
5586 return PTR_ERR(req);
5588 req->timeout.off = 0; /* noseq */
5589 data = req->async_data;
5590 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5591 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5592 data->timer.function = io_timeout_fn;
5593 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5597 static int io_timeout_remove_prep(struct io_kiocb *req,
5598 const struct io_uring_sqe *sqe)
5600 struct io_timeout_rem *tr = &req->timeout_rem;
5602 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5604 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5606 if (sqe->ioprio || sqe->buf_index || sqe->len)
5609 tr->addr = READ_ONCE(sqe->addr);
5610 tr->flags = READ_ONCE(sqe->timeout_flags);
5611 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5612 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5614 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5616 } else if (tr->flags) {
5617 /* timeout removal doesn't support flags */
5624 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5626 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5631 * Remove or update an existing timeout command
5633 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5635 struct io_timeout_rem *tr = &req->timeout_rem;
5636 struct io_ring_ctx *ctx = req->ctx;
5639 spin_lock_irq(&ctx->completion_lock);
5640 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5641 ret = io_timeout_cancel(ctx, tr->addr);
5643 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5644 io_translate_timeout_mode(tr->flags));
5646 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5647 io_commit_cqring(ctx);
5648 spin_unlock_irq(&ctx->completion_lock);
5649 io_cqring_ev_posted(ctx);
5651 req_set_fail_links(req);
5656 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5657 bool is_timeout_link)
5659 struct io_timeout_data *data;
5661 u32 off = READ_ONCE(sqe->off);
5663 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5665 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5667 if (off && is_timeout_link)
5669 flags = READ_ONCE(sqe->timeout_flags);
5670 if (flags & ~IORING_TIMEOUT_ABS)
5673 req->timeout.off = off;
5675 if (!req->async_data && io_alloc_async_data(req))
5678 data = req->async_data;
5681 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5684 data->mode = io_translate_timeout_mode(flags);
5685 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5686 if (is_timeout_link)
5687 io_req_track_inflight(req);
5691 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5693 struct io_ring_ctx *ctx = req->ctx;
5694 struct io_timeout_data *data = req->async_data;
5695 struct list_head *entry;
5696 u32 tail, off = req->timeout.off;
5698 spin_lock_irq(&ctx->completion_lock);
5701 * sqe->off holds how many events that need to occur for this
5702 * timeout event to be satisfied. If it isn't set, then this is
5703 * a pure timeout request, sequence isn't used.
5705 if (io_is_timeout_noseq(req)) {
5706 entry = ctx->timeout_list.prev;
5710 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5711 req->timeout.target_seq = tail + off;
5713 /* Update the last seq here in case io_flush_timeouts() hasn't.
5714 * This is safe because ->completion_lock is held, and submissions
5715 * and completions are never mixed in the same ->completion_lock section.
5717 ctx->cq_last_tm_flush = tail;
5720 * Insertion sort, ensuring the first entry in the list is always
5721 * the one we need first.
5723 list_for_each_prev(entry, &ctx->timeout_list) {
5724 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5727 if (io_is_timeout_noseq(nxt))
5729 /* nxt.seq is behind @tail, otherwise would've been completed */
5730 if (off >= nxt->timeout.target_seq - tail)
5734 list_add(&req->timeout.list, entry);
5735 data->timer.function = io_timeout_fn;
5736 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5737 spin_unlock_irq(&ctx->completion_lock);
5741 struct io_cancel_data {
5742 struct io_ring_ctx *ctx;
5746 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5748 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5749 struct io_cancel_data *cd = data;
5751 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5754 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5755 struct io_ring_ctx *ctx)
5757 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5758 enum io_wq_cancel cancel_ret;
5761 if (!tctx || !tctx->io_wq)
5764 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5765 switch (cancel_ret) {
5766 case IO_WQ_CANCEL_OK:
5769 case IO_WQ_CANCEL_RUNNING:
5772 case IO_WQ_CANCEL_NOTFOUND:
5780 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5781 struct io_kiocb *req, __u64 sqe_addr,
5784 unsigned long flags;
5787 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5788 spin_lock_irqsave(&ctx->completion_lock, flags);
5791 ret = io_timeout_cancel(ctx, sqe_addr);
5794 ret = io_poll_cancel(ctx, sqe_addr, false);
5798 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5799 io_commit_cqring(ctx);
5800 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5801 io_cqring_ev_posted(ctx);
5804 req_set_fail_links(req);
5807 static int io_async_cancel_prep(struct io_kiocb *req,
5808 const struct io_uring_sqe *sqe)
5810 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5812 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5814 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5817 req->cancel.addr = READ_ONCE(sqe->addr);
5821 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5823 struct io_ring_ctx *ctx = req->ctx;
5824 u64 sqe_addr = req->cancel.addr;
5825 struct io_tctx_node *node;
5828 /* tasks should wait for their io-wq threads, so safe w/o sync */
5829 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5830 spin_lock_irq(&ctx->completion_lock);
5833 ret = io_timeout_cancel(ctx, sqe_addr);
5836 ret = io_poll_cancel(ctx, sqe_addr, false);
5839 spin_unlock_irq(&ctx->completion_lock);
5841 /* slow path, try all io-wq's */
5842 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5844 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5845 struct io_uring_task *tctx = node->task->io_uring;
5847 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5851 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5853 spin_lock_irq(&ctx->completion_lock);
5855 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5856 io_commit_cqring(ctx);
5857 spin_unlock_irq(&ctx->completion_lock);
5858 io_cqring_ev_posted(ctx);
5861 req_set_fail_links(req);
5866 static int io_rsrc_update_prep(struct io_kiocb *req,
5867 const struct io_uring_sqe *sqe)
5869 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5871 if (sqe->ioprio || sqe->rw_flags)
5874 req->rsrc_update.offset = READ_ONCE(sqe->off);
5875 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5876 if (!req->rsrc_update.nr_args)
5878 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5882 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5884 struct io_ring_ctx *ctx = req->ctx;
5885 struct io_uring_rsrc_update2 up;
5888 if (issue_flags & IO_URING_F_NONBLOCK)
5891 up.offset = req->rsrc_update.offset;
5892 up.data = req->rsrc_update.arg;
5897 mutex_lock(&ctx->uring_lock);
5898 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5899 &up, req->rsrc_update.nr_args);
5900 mutex_unlock(&ctx->uring_lock);
5903 req_set_fail_links(req);
5904 __io_req_complete(req, issue_flags, ret, 0);
5908 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5910 switch (req->opcode) {
5913 case IORING_OP_READV:
5914 case IORING_OP_READ_FIXED:
5915 case IORING_OP_READ:
5916 return io_read_prep(req, sqe);
5917 case IORING_OP_WRITEV:
5918 case IORING_OP_WRITE_FIXED:
5919 case IORING_OP_WRITE:
5920 return io_write_prep(req, sqe);
5921 case IORING_OP_POLL_ADD:
5922 return io_poll_add_prep(req, sqe);
5923 case IORING_OP_POLL_REMOVE:
5924 return io_poll_update_prep(req, sqe);
5925 case IORING_OP_FSYNC:
5926 return io_fsync_prep(req, sqe);
5927 case IORING_OP_SYNC_FILE_RANGE:
5928 return io_sfr_prep(req, sqe);
5929 case IORING_OP_SENDMSG:
5930 case IORING_OP_SEND:
5931 return io_sendmsg_prep(req, sqe);
5932 case IORING_OP_RECVMSG:
5933 case IORING_OP_RECV:
5934 return io_recvmsg_prep(req, sqe);
5935 case IORING_OP_CONNECT:
5936 return io_connect_prep(req, sqe);
5937 case IORING_OP_TIMEOUT:
5938 return io_timeout_prep(req, sqe, false);
5939 case IORING_OP_TIMEOUT_REMOVE:
5940 return io_timeout_remove_prep(req, sqe);
5941 case IORING_OP_ASYNC_CANCEL:
5942 return io_async_cancel_prep(req, sqe);
5943 case IORING_OP_LINK_TIMEOUT:
5944 return io_timeout_prep(req, sqe, true);
5945 case IORING_OP_ACCEPT:
5946 return io_accept_prep(req, sqe);
5947 case IORING_OP_FALLOCATE:
5948 return io_fallocate_prep(req, sqe);
5949 case IORING_OP_OPENAT:
5950 return io_openat_prep(req, sqe);
5951 case IORING_OP_CLOSE:
5952 return io_close_prep(req, sqe);
5953 case IORING_OP_FILES_UPDATE:
5954 return io_rsrc_update_prep(req, sqe);
5955 case IORING_OP_STATX:
5956 return io_statx_prep(req, sqe);
5957 case IORING_OP_FADVISE:
5958 return io_fadvise_prep(req, sqe);
5959 case IORING_OP_MADVISE:
5960 return io_madvise_prep(req, sqe);
5961 case IORING_OP_OPENAT2:
5962 return io_openat2_prep(req, sqe);
5963 case IORING_OP_EPOLL_CTL:
5964 return io_epoll_ctl_prep(req, sqe);
5965 case IORING_OP_SPLICE:
5966 return io_splice_prep(req, sqe);
5967 case IORING_OP_PROVIDE_BUFFERS:
5968 return io_provide_buffers_prep(req, sqe);
5969 case IORING_OP_REMOVE_BUFFERS:
5970 return io_remove_buffers_prep(req, sqe);
5972 return io_tee_prep(req, sqe);
5973 case IORING_OP_SHUTDOWN:
5974 return io_shutdown_prep(req, sqe);
5975 case IORING_OP_RENAMEAT:
5976 return io_renameat_prep(req, sqe);
5977 case IORING_OP_UNLINKAT:
5978 return io_unlinkat_prep(req, sqe);
5981 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5986 static int io_req_prep_async(struct io_kiocb *req)
5988 if (!io_op_defs[req->opcode].needs_async_setup)
5990 if (WARN_ON_ONCE(req->async_data))
5992 if (io_alloc_async_data(req))
5995 switch (req->opcode) {
5996 case IORING_OP_READV:
5997 return io_rw_prep_async(req, READ);
5998 case IORING_OP_WRITEV:
5999 return io_rw_prep_async(req, WRITE);
6000 case IORING_OP_SENDMSG:
6001 return io_sendmsg_prep_async(req);
6002 case IORING_OP_RECVMSG:
6003 return io_recvmsg_prep_async(req);
6004 case IORING_OP_CONNECT:
6005 return io_connect_prep_async(req);
6007 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6012 static u32 io_get_sequence(struct io_kiocb *req)
6014 struct io_kiocb *pos;
6015 struct io_ring_ctx *ctx = req->ctx;
6016 u32 total_submitted, nr_reqs = 0;
6018 io_for_each_link(pos, req)
6021 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6022 return total_submitted - nr_reqs;
6025 static int io_req_defer(struct io_kiocb *req)
6027 struct io_ring_ctx *ctx = req->ctx;
6028 struct io_defer_entry *de;
6032 /* Still need defer if there is pending req in defer list. */
6033 if (likely(list_empty_careful(&ctx->defer_list) &&
6034 !(req->flags & REQ_F_IO_DRAIN)))
6037 seq = io_get_sequence(req);
6038 /* Still a chance to pass the sequence check */
6039 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6042 ret = io_req_prep_async(req);
6045 io_prep_async_link(req);
6046 de = kmalloc(sizeof(*de), GFP_KERNEL);
6050 spin_lock_irq(&ctx->completion_lock);
6051 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6052 spin_unlock_irq(&ctx->completion_lock);
6054 io_queue_async_work(req);
6055 return -EIOCBQUEUED;
6058 trace_io_uring_defer(ctx, req, req->user_data);
6061 list_add_tail(&de->list, &ctx->defer_list);
6062 spin_unlock_irq(&ctx->completion_lock);
6063 return -EIOCBQUEUED;
6066 static void io_clean_op(struct io_kiocb *req)
6068 if (req->flags & REQ_F_BUFFER_SELECTED) {
6069 switch (req->opcode) {
6070 case IORING_OP_READV:
6071 case IORING_OP_READ_FIXED:
6072 case IORING_OP_READ:
6073 kfree((void *)(unsigned long)req->rw.addr);
6075 case IORING_OP_RECVMSG:
6076 case IORING_OP_RECV:
6077 kfree(req->sr_msg.kbuf);
6080 req->flags &= ~REQ_F_BUFFER_SELECTED;
6083 if (req->flags & REQ_F_NEED_CLEANUP) {
6084 switch (req->opcode) {
6085 case IORING_OP_READV:
6086 case IORING_OP_READ_FIXED:
6087 case IORING_OP_READ:
6088 case IORING_OP_WRITEV:
6089 case IORING_OP_WRITE_FIXED:
6090 case IORING_OP_WRITE: {
6091 struct io_async_rw *io = req->async_data;
6093 kfree(io->free_iovec);
6096 case IORING_OP_RECVMSG:
6097 case IORING_OP_SENDMSG: {
6098 struct io_async_msghdr *io = req->async_data;
6100 kfree(io->free_iov);
6103 case IORING_OP_SPLICE:
6105 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6106 io_put_file(req->splice.file_in);
6108 case IORING_OP_OPENAT:
6109 case IORING_OP_OPENAT2:
6110 if (req->open.filename)
6111 putname(req->open.filename);
6113 case IORING_OP_RENAMEAT:
6114 putname(req->rename.oldpath);
6115 putname(req->rename.newpath);
6117 case IORING_OP_UNLINKAT:
6118 putname(req->unlink.filename);
6121 req->flags &= ~REQ_F_NEED_CLEANUP;
6123 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6124 kfree(req->apoll->double_poll);
6128 if (req->flags & REQ_F_INFLIGHT) {
6129 struct io_uring_task *tctx = req->task->io_uring;
6131 atomic_dec(&tctx->inflight_tracked);
6132 req->flags &= ~REQ_F_INFLIGHT;
6136 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6138 struct io_ring_ctx *ctx = req->ctx;
6139 const struct cred *creds = NULL;
6142 if (req->creds && req->creds != current_cred())
6143 creds = override_creds(req->creds);
6145 switch (req->opcode) {
6147 ret = io_nop(req, issue_flags);
6149 case IORING_OP_READV:
6150 case IORING_OP_READ_FIXED:
6151 case IORING_OP_READ:
6152 ret = io_read(req, issue_flags);
6154 case IORING_OP_WRITEV:
6155 case IORING_OP_WRITE_FIXED:
6156 case IORING_OP_WRITE:
6157 ret = io_write(req, issue_flags);
6159 case IORING_OP_FSYNC:
6160 ret = io_fsync(req, issue_flags);
6162 case IORING_OP_POLL_ADD:
6163 ret = io_poll_add(req, issue_flags);
6165 case IORING_OP_POLL_REMOVE:
6166 ret = io_poll_update(req, issue_flags);
6168 case IORING_OP_SYNC_FILE_RANGE:
6169 ret = io_sync_file_range(req, issue_flags);
6171 case IORING_OP_SENDMSG:
6172 ret = io_sendmsg(req, issue_flags);
6174 case IORING_OP_SEND:
6175 ret = io_send(req, issue_flags);
6177 case IORING_OP_RECVMSG:
6178 ret = io_recvmsg(req, issue_flags);
6180 case IORING_OP_RECV:
6181 ret = io_recv(req, issue_flags);
6183 case IORING_OP_TIMEOUT:
6184 ret = io_timeout(req, issue_flags);
6186 case IORING_OP_TIMEOUT_REMOVE:
6187 ret = io_timeout_remove(req, issue_flags);
6189 case IORING_OP_ACCEPT:
6190 ret = io_accept(req, issue_flags);
6192 case IORING_OP_CONNECT:
6193 ret = io_connect(req, issue_flags);
6195 case IORING_OP_ASYNC_CANCEL:
6196 ret = io_async_cancel(req, issue_flags);
6198 case IORING_OP_FALLOCATE:
6199 ret = io_fallocate(req, issue_flags);
6201 case IORING_OP_OPENAT:
6202 ret = io_openat(req, issue_flags);
6204 case IORING_OP_CLOSE:
6205 ret = io_close(req, issue_flags);
6207 case IORING_OP_FILES_UPDATE:
6208 ret = io_files_update(req, issue_flags);
6210 case IORING_OP_STATX:
6211 ret = io_statx(req, issue_flags);
6213 case IORING_OP_FADVISE:
6214 ret = io_fadvise(req, issue_flags);
6216 case IORING_OP_MADVISE:
6217 ret = io_madvise(req, issue_flags);
6219 case IORING_OP_OPENAT2:
6220 ret = io_openat2(req, issue_flags);
6222 case IORING_OP_EPOLL_CTL:
6223 ret = io_epoll_ctl(req, issue_flags);
6225 case IORING_OP_SPLICE:
6226 ret = io_splice(req, issue_flags);
6228 case IORING_OP_PROVIDE_BUFFERS:
6229 ret = io_provide_buffers(req, issue_flags);
6231 case IORING_OP_REMOVE_BUFFERS:
6232 ret = io_remove_buffers(req, issue_flags);
6235 ret = io_tee(req, issue_flags);
6237 case IORING_OP_SHUTDOWN:
6238 ret = io_shutdown(req, issue_flags);
6240 case IORING_OP_RENAMEAT:
6241 ret = io_renameat(req, issue_flags);
6243 case IORING_OP_UNLINKAT:
6244 ret = io_unlinkat(req, issue_flags);
6252 revert_creds(creds);
6257 /* If the op doesn't have a file, we're not polling for it */
6258 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6259 const bool in_async = io_wq_current_is_worker();
6261 /* workqueue context doesn't hold uring_lock, grab it now */
6263 mutex_lock(&ctx->uring_lock);
6265 io_iopoll_req_issued(req, in_async);
6268 mutex_unlock(&ctx->uring_lock);
6274 static void io_wq_submit_work(struct io_wq_work *work)
6276 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6277 struct io_kiocb *timeout;
6280 timeout = io_prep_linked_timeout(req);
6282 io_queue_linked_timeout(timeout);
6284 if (work->flags & IO_WQ_WORK_CANCEL)
6289 ret = io_issue_sqe(req, 0);
6291 * We can get EAGAIN for polled IO even though we're
6292 * forcing a sync submission from here, since we can't
6293 * wait for request slots on the block side.
6301 /* avoid locking problems by failing it from a clean context */
6303 /* io-wq is going to take one down */
6305 io_req_task_queue_fail(req, ret);
6309 #define FFS_ASYNC_READ 0x1UL
6310 #define FFS_ASYNC_WRITE 0x2UL
6312 #define FFS_ISREG 0x4UL
6314 #define FFS_ISREG 0x0UL
6316 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6318 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6321 struct io_fixed_file *table_l2;
6323 table_l2 = table->files[i >> IORING_FILE_TABLE_SHIFT];
6324 return &table_l2[i & IORING_FILE_TABLE_MASK];
6327 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6330 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6332 return (struct file *) (slot->file_ptr & FFS_MASK);
6335 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6337 unsigned long file_ptr = (unsigned long) file;
6339 if (__io_file_supports_async(file, READ))
6340 file_ptr |= FFS_ASYNC_READ;
6341 if (__io_file_supports_async(file, WRITE))
6342 file_ptr |= FFS_ASYNC_WRITE;
6343 if (S_ISREG(file_inode(file)->i_mode))
6344 file_ptr |= FFS_ISREG;
6345 file_slot->file_ptr = file_ptr;
6348 static struct file *io_file_get(struct io_submit_state *state,
6349 struct io_kiocb *req, int fd, bool fixed)
6351 struct io_ring_ctx *ctx = req->ctx;
6355 unsigned long file_ptr;
6357 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6359 fd = array_index_nospec(fd, ctx->nr_user_files);
6360 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6361 file = (struct file *) (file_ptr & FFS_MASK);
6362 file_ptr &= ~FFS_MASK;
6363 /* mask in overlapping REQ_F and FFS bits */
6364 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6365 io_req_set_rsrc_node(req);
6367 trace_io_uring_file_get(ctx, fd);
6368 file = __io_file_get(state, fd);
6370 /* we don't allow fixed io_uring files */
6371 if (file && unlikely(file->f_op == &io_uring_fops))
6372 io_req_track_inflight(req);
6378 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6380 struct io_timeout_data *data = container_of(timer,
6381 struct io_timeout_data, timer);
6382 struct io_kiocb *prev, *req = data->req;
6383 struct io_ring_ctx *ctx = req->ctx;
6384 unsigned long flags;
6386 spin_lock_irqsave(&ctx->completion_lock, flags);
6387 prev = req->timeout.head;
6388 req->timeout.head = NULL;
6391 * We don't expect the list to be empty, that will only happen if we
6392 * race with the completion of the linked work.
6395 io_remove_next_linked(prev);
6396 if (!req_ref_inc_not_zero(prev))
6399 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6402 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6403 io_put_req_deferred(prev, 1);
6404 io_put_req_deferred(req, 1);
6406 io_req_complete_post(req, -ETIME, 0);
6408 return HRTIMER_NORESTART;
6411 static void io_queue_linked_timeout(struct io_kiocb *req)
6413 struct io_ring_ctx *ctx = req->ctx;
6415 spin_lock_irq(&ctx->completion_lock);
6417 * If the back reference is NULL, then our linked request finished
6418 * before we got a chance to setup the timer
6420 if (req->timeout.head) {
6421 struct io_timeout_data *data = req->async_data;
6423 data->timer.function = io_link_timeout_fn;
6424 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6427 spin_unlock_irq(&ctx->completion_lock);
6428 /* drop submission reference */
6432 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6434 struct io_kiocb *nxt = req->link;
6436 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6437 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6440 nxt->timeout.head = req;
6441 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6442 req->flags |= REQ_F_LINK_TIMEOUT;
6446 static void __io_queue_sqe(struct io_kiocb *req)
6448 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6451 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6454 * We async punt it if the file wasn't marked NOWAIT, or if the file
6455 * doesn't support non-blocking read/write attempts
6458 /* drop submission reference */
6459 if (req->flags & REQ_F_COMPLETE_INLINE) {
6460 struct io_ring_ctx *ctx = req->ctx;
6461 struct io_comp_state *cs = &ctx->submit_state.comp;
6463 cs->reqs[cs->nr++] = req;
6464 if (cs->nr == ARRAY_SIZE(cs->reqs))
6465 io_submit_flush_completions(cs, ctx);
6469 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6470 if (!io_arm_poll_handler(req)) {
6472 * Queued up for async execution, worker will release
6473 * submit reference when the iocb is actually submitted.
6475 io_queue_async_work(req);
6478 io_req_complete_failed(req, ret);
6481 io_queue_linked_timeout(linked_timeout);
6484 static void io_queue_sqe(struct io_kiocb *req)
6488 ret = io_req_defer(req);
6490 if (ret != -EIOCBQUEUED) {
6492 io_req_complete_failed(req, ret);
6494 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6495 ret = io_req_prep_async(req);
6498 io_queue_async_work(req);
6500 __io_queue_sqe(req);
6505 * Check SQE restrictions (opcode and flags).
6507 * Returns 'true' if SQE is allowed, 'false' otherwise.
6509 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6510 struct io_kiocb *req,
6511 unsigned int sqe_flags)
6513 if (!ctx->restricted)
6516 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6519 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6520 ctx->restrictions.sqe_flags_required)
6523 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6524 ctx->restrictions.sqe_flags_required))
6530 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6531 const struct io_uring_sqe *sqe)
6533 struct io_submit_state *state;
6534 unsigned int sqe_flags;
6535 int personality, ret = 0;
6537 req->opcode = READ_ONCE(sqe->opcode);
6538 /* same numerical values with corresponding REQ_F_*, safe to copy */
6539 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6540 req->user_data = READ_ONCE(sqe->user_data);
6541 req->async_data = NULL;
6545 req->fixed_rsrc_refs = NULL;
6546 /* one is dropped after submission, the other at completion */
6547 atomic_set(&req->refs, 2);
6548 req->task = current;
6552 /* enforce forwards compatibility on users */
6553 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6555 if (unlikely(req->opcode >= IORING_OP_LAST))
6557 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6560 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6561 !io_op_defs[req->opcode].buffer_select)
6564 personality = READ_ONCE(sqe->personality);
6566 req->creds = xa_load(&ctx->personalities, personality);
6569 get_cred(req->creds);
6571 state = &ctx->submit_state;
6574 * Plug now if we have more than 1 IO left after this, and the target
6575 * is potentially a read/write to block based storage.
6577 if (!state->plug_started && state->ios_left > 1 &&
6578 io_op_defs[req->opcode].plug) {
6579 blk_start_plug(&state->plug);
6580 state->plug_started = true;
6583 if (io_op_defs[req->opcode].needs_file) {
6584 bool fixed = req->flags & REQ_F_FIXED_FILE;
6586 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6587 if (unlikely(!req->file))
6595 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6596 const struct io_uring_sqe *sqe)
6598 struct io_submit_link *link = &ctx->submit_state.link;
6601 ret = io_init_req(ctx, req, sqe);
6602 if (unlikely(ret)) {
6605 /* fail even hard links since we don't submit */
6606 link->head->flags |= REQ_F_FAIL_LINK;
6607 io_req_complete_failed(link->head, -ECANCELED);
6610 io_req_complete_failed(req, ret);
6613 ret = io_req_prep(req, sqe);
6617 /* don't need @sqe from now on */
6618 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6619 true, ctx->flags & IORING_SETUP_SQPOLL);
6622 * If we already have a head request, queue this one for async
6623 * submittal once the head completes. If we don't have a head but
6624 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6625 * submitted sync once the chain is complete. If none of those
6626 * conditions are true (normal request), then just queue it.
6629 struct io_kiocb *head = link->head;
6632 * Taking sequential execution of a link, draining both sides
6633 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6634 * requests in the link. So, it drains the head and the
6635 * next after the link request. The last one is done via
6636 * drain_next flag to persist the effect across calls.
6638 if (req->flags & REQ_F_IO_DRAIN) {
6639 head->flags |= REQ_F_IO_DRAIN;
6640 ctx->drain_next = 1;
6642 ret = io_req_prep_async(req);
6645 trace_io_uring_link(ctx, req, head);
6646 link->last->link = req;
6649 /* last request of a link, enqueue the link */
6650 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6655 if (unlikely(ctx->drain_next)) {
6656 req->flags |= REQ_F_IO_DRAIN;
6657 ctx->drain_next = 0;
6659 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6671 * Batched submission is done, ensure local IO is flushed out.
6673 static void io_submit_state_end(struct io_submit_state *state,
6674 struct io_ring_ctx *ctx)
6676 if (state->link.head)
6677 io_queue_sqe(state->link.head);
6679 io_submit_flush_completions(&state->comp, ctx);
6680 if (state->plug_started)
6681 blk_finish_plug(&state->plug);
6682 io_state_file_put(state);
6686 * Start submission side cache.
6688 static void io_submit_state_start(struct io_submit_state *state,
6689 unsigned int max_ios)
6691 state->plug_started = false;
6692 state->ios_left = max_ios;
6693 /* set only head, no need to init link_last in advance */
6694 state->link.head = NULL;
6697 static void io_commit_sqring(struct io_ring_ctx *ctx)
6699 struct io_rings *rings = ctx->rings;
6702 * Ensure any loads from the SQEs are done at this point,
6703 * since once we write the new head, the application could
6704 * write new data to them.
6706 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6710 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6711 * that is mapped by userspace. This means that care needs to be taken to
6712 * ensure that reads are stable, as we cannot rely on userspace always
6713 * being a good citizen. If members of the sqe are validated and then later
6714 * used, it's important that those reads are done through READ_ONCE() to
6715 * prevent a re-load down the line.
6717 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6719 u32 *sq_array = ctx->sq_array;
6723 * The cached sq head (or cq tail) serves two purposes:
6725 * 1) allows us to batch the cost of updating the user visible
6727 * 2) allows the kernel side to track the head on its own, even
6728 * though the application is the one updating it.
6730 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6731 if (likely(head < ctx->sq_entries))
6732 return &ctx->sq_sqes[head];
6734 /* drop invalid entries */
6735 ctx->cached_sq_dropped++;
6736 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6740 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6744 /* make sure SQ entry isn't read before tail */
6745 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6747 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6750 percpu_counter_add(¤t->io_uring->inflight, nr);
6751 refcount_add(nr, ¤t->usage);
6752 io_submit_state_start(&ctx->submit_state, nr);
6754 while (submitted < nr) {
6755 const struct io_uring_sqe *sqe;
6756 struct io_kiocb *req;
6758 req = io_alloc_req(ctx);
6759 if (unlikely(!req)) {
6761 submitted = -EAGAIN;
6764 sqe = io_get_sqe(ctx);
6765 if (unlikely(!sqe)) {
6766 kmem_cache_free(req_cachep, req);
6769 /* will complete beyond this point, count as submitted */
6771 if (io_submit_sqe(ctx, req, sqe))
6775 if (unlikely(submitted != nr)) {
6776 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6777 struct io_uring_task *tctx = current->io_uring;
6778 int unused = nr - ref_used;
6780 percpu_ref_put_many(&ctx->refs, unused);
6781 percpu_counter_sub(&tctx->inflight, unused);
6782 put_task_struct_many(current, unused);
6785 io_submit_state_end(&ctx->submit_state, ctx);
6786 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6787 io_commit_sqring(ctx);
6792 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6794 /* Tell userspace we may need a wakeup call */
6795 spin_lock_irq(&ctx->completion_lock);
6796 WRITE_ONCE(ctx->rings->sq_flags,
6797 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
6798 spin_unlock_irq(&ctx->completion_lock);
6801 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6803 spin_lock_irq(&ctx->completion_lock);
6804 WRITE_ONCE(ctx->rings->sq_flags,
6805 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
6806 spin_unlock_irq(&ctx->completion_lock);
6809 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6811 unsigned int to_submit;
6814 to_submit = io_sqring_entries(ctx);
6815 /* if we're handling multiple rings, cap submit size for fairness */
6816 if (cap_entries && to_submit > 8)
6819 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6820 unsigned nr_events = 0;
6822 mutex_lock(&ctx->uring_lock);
6823 if (!list_empty(&ctx->iopoll_list))
6824 io_do_iopoll(ctx, &nr_events, 0, true);
6827 * Don't submit if refs are dying, good for io_uring_register(),
6828 * but also it is relied upon by io_ring_exit_work()
6830 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6831 !(ctx->flags & IORING_SETUP_R_DISABLED))
6832 ret = io_submit_sqes(ctx, to_submit);
6833 mutex_unlock(&ctx->uring_lock);
6836 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6837 wake_up(&ctx->sqo_sq_wait);
6842 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6844 struct io_ring_ctx *ctx;
6845 unsigned sq_thread_idle = 0;
6847 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6848 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6849 sqd->sq_thread_idle = sq_thread_idle;
6852 static int io_sq_thread(void *data)
6854 struct io_sq_data *sqd = data;
6855 struct io_ring_ctx *ctx;
6856 unsigned long timeout = 0;
6857 char buf[TASK_COMM_LEN];
6860 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6861 set_task_comm(current, buf);
6863 if (sqd->sq_cpu != -1)
6864 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6866 set_cpus_allowed_ptr(current, cpu_online_mask);
6867 current->flags |= PF_NO_SETAFFINITY;
6869 mutex_lock(&sqd->lock);
6870 /* a user may had exited before the thread started */
6871 io_run_task_work_head(&sqd->park_task_work);
6873 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6875 bool cap_entries, sqt_spin, needs_sched;
6877 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6878 signal_pending(current)) {
6879 bool did_sig = false;
6881 mutex_unlock(&sqd->lock);
6882 if (signal_pending(current)) {
6883 struct ksignal ksig;
6885 did_sig = get_signal(&ksig);
6888 mutex_lock(&sqd->lock);
6890 io_run_task_work_head(&sqd->park_task_work);
6893 timeout = jiffies + sqd->sq_thread_idle;
6897 cap_entries = !list_is_singular(&sqd->ctx_list);
6898 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6899 const struct cred *creds = NULL;
6901 if (ctx->sq_creds != current_cred())
6902 creds = override_creds(ctx->sq_creds);
6903 ret = __io_sq_thread(ctx, cap_entries);
6905 revert_creds(creds);
6906 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6910 if (sqt_spin || !time_after(jiffies, timeout)) {
6914 timeout = jiffies + sqd->sq_thread_idle;
6918 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6919 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) &&
6920 !io_run_task_work()) {
6921 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6922 io_ring_set_wakeup_flag(ctx);
6925 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6926 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6927 !list_empty_careful(&ctx->iopoll_list)) {
6928 needs_sched = false;
6931 if (io_sqring_entries(ctx)) {
6932 needs_sched = false;
6938 mutex_unlock(&sqd->lock);
6940 mutex_lock(&sqd->lock);
6942 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6943 io_ring_clear_wakeup_flag(ctx);
6946 finish_wait(&sqd->wait, &wait);
6947 io_run_task_work_head(&sqd->park_task_work);
6948 timeout = jiffies + sqd->sq_thread_idle;
6951 io_uring_cancel_sqpoll(sqd);
6953 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6954 io_ring_set_wakeup_flag(ctx);
6956 io_run_task_work_head(&sqd->park_task_work);
6957 mutex_unlock(&sqd->lock);
6959 complete(&sqd->exited);
6963 struct io_wait_queue {
6964 struct wait_queue_entry wq;
6965 struct io_ring_ctx *ctx;
6967 unsigned nr_timeouts;
6970 static inline bool io_should_wake(struct io_wait_queue *iowq)
6972 struct io_ring_ctx *ctx = iowq->ctx;
6975 * Wake up if we have enough events, or if a timeout occurred since we
6976 * started waiting. For timeouts, we always want to return to userspace,
6977 * regardless of event count.
6979 return io_cqring_events(ctx) >= iowq->to_wait ||
6980 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6983 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6984 int wake_flags, void *key)
6986 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6990 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6991 * the task, and the next invocation will do it.
6993 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6994 return autoremove_wake_function(curr, mode, wake_flags, key);
6998 static int io_run_task_work_sig(void)
7000 if (io_run_task_work())
7002 if (!signal_pending(current))
7004 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7005 return -ERESTARTSYS;
7009 /* when returns >0, the caller should retry */
7010 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7011 struct io_wait_queue *iowq,
7012 signed long *timeout)
7016 /* make sure we run task_work before checking for signals */
7017 ret = io_run_task_work_sig();
7018 if (ret || io_should_wake(iowq))
7020 /* let the caller flush overflows, retry */
7021 if (test_bit(0, &ctx->cq_check_overflow))
7024 *timeout = schedule_timeout(*timeout);
7025 return !*timeout ? -ETIME : 1;
7029 * Wait until events become available, if we don't already have some. The
7030 * application must reap them itself, as they reside on the shared cq ring.
7032 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7033 const sigset_t __user *sig, size_t sigsz,
7034 struct __kernel_timespec __user *uts)
7036 struct io_wait_queue iowq = {
7039 .func = io_wake_function,
7040 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7043 .to_wait = min_events,
7045 struct io_rings *rings = ctx->rings;
7046 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7050 io_cqring_overflow_flush(ctx, false);
7051 if (io_cqring_events(ctx) >= min_events)
7053 if (!io_run_task_work())
7058 #ifdef CONFIG_COMPAT
7059 if (in_compat_syscall())
7060 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7064 ret = set_user_sigmask(sig, sigsz);
7071 struct timespec64 ts;
7073 if (get_timespec64(&ts, uts))
7075 timeout = timespec64_to_jiffies(&ts);
7078 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7079 trace_io_uring_cqring_wait(ctx, min_events);
7081 /* if we can't even flush overflow, don't wait for more */
7082 if (!io_cqring_overflow_flush(ctx, false)) {
7086 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7087 TASK_INTERRUPTIBLE);
7088 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7089 finish_wait(&ctx->wait, &iowq.wq);
7093 restore_saved_sigmask_unless(ret == -EINTR);
7095 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7098 static void io_free_file_tables(struct io_file_table *table, unsigned nr_files)
7100 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7102 for (i = 0; i < nr_tables; i++)
7103 kfree(table->files[i]);
7104 kfree(table->files);
7105 table->files = NULL;
7108 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7110 percpu_ref_exit(&ref_node->refs);
7114 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7115 struct io_rsrc_data *data_to_kill)
7117 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7118 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7121 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7123 rsrc_node->rsrc_data = data_to_kill;
7124 spin_lock_irq(&ctx->rsrc_ref_lock);
7125 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7126 spin_unlock_irq(&ctx->rsrc_ref_lock);
7128 atomic_inc(&data_to_kill->refs);
7129 percpu_ref_kill(&rsrc_node->refs);
7130 ctx->rsrc_node = NULL;
7133 if (!ctx->rsrc_node) {
7134 ctx->rsrc_node = ctx->rsrc_backup_node;
7135 ctx->rsrc_backup_node = NULL;
7139 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7141 if (ctx->rsrc_backup_node)
7143 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7144 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7147 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7151 /* As we may drop ->uring_lock, other task may have started quiesce */
7155 data->quiesce = true;
7157 ret = io_rsrc_node_switch_start(ctx);
7160 io_rsrc_node_switch(ctx, data);
7162 /* kill initial ref, already quiesced if zero */
7163 if (atomic_dec_and_test(&data->refs))
7165 mutex_unlock(&ctx->uring_lock);
7166 flush_delayed_work(&ctx->rsrc_put_work);
7167 ret = wait_for_completion_interruptible(&data->done);
7169 mutex_lock(&ctx->uring_lock);
7173 atomic_inc(&data->refs);
7174 /* wait for all works potentially completing data->done */
7175 flush_delayed_work(&ctx->rsrc_put_work);
7176 reinit_completion(&data->done);
7178 ret = io_run_task_work_sig();
7179 mutex_lock(&ctx->uring_lock);
7181 data->quiesce = false;
7186 static void io_rsrc_data_free(struct io_rsrc_data *data)
7192 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7193 rsrc_put_fn *do_put,
7196 struct io_rsrc_data *data;
7198 data = kzalloc(sizeof(*data), GFP_KERNEL);
7202 data->tags = kvcalloc(nr, sizeof(*data->tags), GFP_KERNEL);
7208 atomic_set(&data->refs, 1);
7210 data->do_put = do_put;
7211 init_completion(&data->done);
7215 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7217 #if defined(CONFIG_UNIX)
7218 if (ctx->ring_sock) {
7219 struct sock *sock = ctx->ring_sock->sk;
7220 struct sk_buff *skb;
7222 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7228 for (i = 0; i < ctx->nr_user_files; i++) {
7231 file = io_file_from_index(ctx, i);
7236 io_free_file_tables(&ctx->file_table, ctx->nr_user_files);
7237 io_rsrc_data_free(ctx->file_data);
7238 ctx->file_data = NULL;
7239 ctx->nr_user_files = 0;
7242 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7246 if (!ctx->file_data)
7248 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7250 __io_sqe_files_unregister(ctx);
7254 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7255 __releases(&sqd->lock)
7257 WARN_ON_ONCE(sqd->thread == current);
7260 * Do the dance but not conditional clear_bit() because it'd race with
7261 * other threads incrementing park_pending and setting the bit.
7263 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7264 if (atomic_dec_return(&sqd->park_pending))
7265 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7266 mutex_unlock(&sqd->lock);
7269 static void io_sq_thread_park(struct io_sq_data *sqd)
7270 __acquires(&sqd->lock)
7272 WARN_ON_ONCE(sqd->thread == current);
7274 atomic_inc(&sqd->park_pending);
7275 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7276 mutex_lock(&sqd->lock);
7278 wake_up_process(sqd->thread);
7281 static void io_sq_thread_stop(struct io_sq_data *sqd)
7283 WARN_ON_ONCE(sqd->thread == current);
7284 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7286 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7287 mutex_lock(&sqd->lock);
7289 wake_up_process(sqd->thread);
7290 mutex_unlock(&sqd->lock);
7291 wait_for_completion(&sqd->exited);
7294 static void io_put_sq_data(struct io_sq_data *sqd)
7296 if (refcount_dec_and_test(&sqd->refs)) {
7297 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7299 io_sq_thread_stop(sqd);
7304 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7306 struct io_sq_data *sqd = ctx->sq_data;
7309 io_sq_thread_park(sqd);
7310 list_del_init(&ctx->sqd_list);
7311 io_sqd_update_thread_idle(sqd);
7312 io_sq_thread_unpark(sqd);
7314 io_put_sq_data(sqd);
7315 ctx->sq_data = NULL;
7319 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7321 struct io_ring_ctx *ctx_attach;
7322 struct io_sq_data *sqd;
7325 f = fdget(p->wq_fd);
7327 return ERR_PTR(-ENXIO);
7328 if (f.file->f_op != &io_uring_fops) {
7330 return ERR_PTR(-EINVAL);
7333 ctx_attach = f.file->private_data;
7334 sqd = ctx_attach->sq_data;
7337 return ERR_PTR(-EINVAL);
7339 if (sqd->task_tgid != current->tgid) {
7341 return ERR_PTR(-EPERM);
7344 refcount_inc(&sqd->refs);
7349 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7352 struct io_sq_data *sqd;
7355 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7356 sqd = io_attach_sq_data(p);
7361 /* fall through for EPERM case, setup new sqd/task */
7362 if (PTR_ERR(sqd) != -EPERM)
7366 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7368 return ERR_PTR(-ENOMEM);
7370 atomic_set(&sqd->park_pending, 0);
7371 refcount_set(&sqd->refs, 1);
7372 INIT_LIST_HEAD(&sqd->ctx_list);
7373 mutex_init(&sqd->lock);
7374 init_waitqueue_head(&sqd->wait);
7375 init_completion(&sqd->exited);
7379 #if defined(CONFIG_UNIX)
7381 * Ensure the UNIX gc is aware of our file set, so we are certain that
7382 * the io_uring can be safely unregistered on process exit, even if we have
7383 * loops in the file referencing.
7385 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7387 struct sock *sk = ctx->ring_sock->sk;
7388 struct scm_fp_list *fpl;
7389 struct sk_buff *skb;
7392 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7396 skb = alloc_skb(0, GFP_KERNEL);
7405 fpl->user = get_uid(current_user());
7406 for (i = 0; i < nr; i++) {
7407 struct file *file = io_file_from_index(ctx, i + offset);
7411 fpl->fp[nr_files] = get_file(file);
7412 unix_inflight(fpl->user, fpl->fp[nr_files]);
7417 fpl->max = SCM_MAX_FD;
7418 fpl->count = nr_files;
7419 UNIXCB(skb).fp = fpl;
7420 skb->destructor = unix_destruct_scm;
7421 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7422 skb_queue_head(&sk->sk_receive_queue, skb);
7424 for (i = 0; i < nr_files; i++)
7435 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7436 * causes regular reference counting to break down. We rely on the UNIX
7437 * garbage collection to take care of this problem for us.
7439 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7441 unsigned left, total;
7445 left = ctx->nr_user_files;
7447 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7449 ret = __io_sqe_files_scm(ctx, this_files, total);
7453 total += this_files;
7459 while (total < ctx->nr_user_files) {
7460 struct file *file = io_file_from_index(ctx, total);
7470 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7476 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7478 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7480 table->files = kcalloc(nr_tables, sizeof(*table->files), GFP_KERNEL);
7484 for (i = 0; i < nr_tables; i++) {
7485 unsigned int this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7487 table->files[i] = kcalloc(this_files, sizeof(*table->files[i]),
7489 if (!table->files[i])
7491 nr_files -= this_files;
7497 io_free_file_tables(table, nr_tables * IORING_MAX_FILES_TABLE);
7501 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7503 struct file *file = prsrc->file;
7504 #if defined(CONFIG_UNIX)
7505 struct sock *sock = ctx->ring_sock->sk;
7506 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7507 struct sk_buff *skb;
7510 __skb_queue_head_init(&list);
7513 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7514 * remove this entry and rearrange the file array.
7516 skb = skb_dequeue(head);
7518 struct scm_fp_list *fp;
7520 fp = UNIXCB(skb).fp;
7521 for (i = 0; i < fp->count; i++) {
7524 if (fp->fp[i] != file)
7527 unix_notinflight(fp->user, fp->fp[i]);
7528 left = fp->count - 1 - i;
7530 memmove(&fp->fp[i], &fp->fp[i + 1],
7531 left * sizeof(struct file *));
7538 __skb_queue_tail(&list, skb);
7548 __skb_queue_tail(&list, skb);
7550 skb = skb_dequeue(head);
7553 if (skb_peek(&list)) {
7554 spin_lock_irq(&head->lock);
7555 while ((skb = __skb_dequeue(&list)) != NULL)
7556 __skb_queue_tail(head, skb);
7557 spin_unlock_irq(&head->lock);
7564 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7566 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7567 struct io_ring_ctx *ctx = rsrc_data->ctx;
7568 struct io_rsrc_put *prsrc, *tmp;
7570 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7571 list_del(&prsrc->list);
7574 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7575 unsigned long flags;
7577 io_ring_submit_lock(ctx, lock_ring);
7578 spin_lock_irqsave(&ctx->completion_lock, flags);
7579 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7581 io_commit_cqring(ctx);
7582 spin_unlock_irqrestore(&ctx->completion_lock, flags);
7583 io_cqring_ev_posted(ctx);
7584 io_ring_submit_unlock(ctx, lock_ring);
7587 rsrc_data->do_put(ctx, prsrc);
7591 io_rsrc_node_destroy(ref_node);
7592 if (atomic_dec_and_test(&rsrc_data->refs))
7593 complete(&rsrc_data->done);
7596 static void io_rsrc_put_work(struct work_struct *work)
7598 struct io_ring_ctx *ctx;
7599 struct llist_node *node;
7601 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7602 node = llist_del_all(&ctx->rsrc_put_llist);
7605 struct io_rsrc_node *ref_node;
7606 struct llist_node *next = node->next;
7608 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7609 __io_rsrc_put_work(ref_node);
7614 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7616 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7617 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7618 unsigned long flags;
7619 bool first_add = false;
7621 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7624 while (!list_empty(&ctx->rsrc_ref_list)) {
7625 node = list_first_entry(&ctx->rsrc_ref_list,
7626 struct io_rsrc_node, node);
7627 /* recycle ref nodes in order */
7630 list_del(&node->node);
7631 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7633 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7636 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7639 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7641 struct io_rsrc_node *ref_node;
7643 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7647 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7652 INIT_LIST_HEAD(&ref_node->node);
7653 INIT_LIST_HEAD(&ref_node->rsrc_list);
7654 ref_node->done = false;
7658 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7659 unsigned nr_args, u64 __user *tags)
7661 __s32 __user *fds = (__s32 __user *) arg;
7665 struct io_rsrc_data *file_data;
7671 if (nr_args > IORING_MAX_FIXED_FILES)
7673 ret = io_rsrc_node_switch_start(ctx);
7677 file_data = io_rsrc_data_alloc(ctx, io_rsrc_file_put, nr_args);
7680 ctx->file_data = file_data;
7682 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7685 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7688 if ((tags && copy_from_user(&tag, &tags[i], sizeof(tag))) ||
7689 copy_from_user(&fd, &fds[i], sizeof(fd))) {
7693 /* allow sparse sets */
7703 if (unlikely(!file))
7707 * Don't allow io_uring instances to be registered. If UNIX
7708 * isn't enabled, then this causes a reference cycle and this
7709 * instance can never get freed. If UNIX is enabled we'll
7710 * handle it just fine, but there's still no point in allowing
7711 * a ring fd as it doesn't support regular read/write anyway.
7713 if (file->f_op == &io_uring_fops) {
7717 ctx->file_data->tags[i] = tag;
7718 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7721 ret = io_sqe_files_scm(ctx);
7723 __io_sqe_files_unregister(ctx);
7727 io_rsrc_node_switch(ctx, NULL);
7730 for (i = 0; i < ctx->nr_user_files; i++) {
7731 file = io_file_from_index(ctx, i);
7735 io_free_file_tables(&ctx->file_table, nr_args);
7736 ctx->nr_user_files = 0;
7738 io_rsrc_data_free(ctx->file_data);
7739 ctx->file_data = NULL;
7743 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7746 #if defined(CONFIG_UNIX)
7747 struct sock *sock = ctx->ring_sock->sk;
7748 struct sk_buff_head *head = &sock->sk_receive_queue;
7749 struct sk_buff *skb;
7752 * See if we can merge this file into an existing skb SCM_RIGHTS
7753 * file set. If there's no room, fall back to allocating a new skb
7754 * and filling it in.
7756 spin_lock_irq(&head->lock);
7757 skb = skb_peek(head);
7759 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7761 if (fpl->count < SCM_MAX_FD) {
7762 __skb_unlink(skb, head);
7763 spin_unlock_irq(&head->lock);
7764 fpl->fp[fpl->count] = get_file(file);
7765 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7767 spin_lock_irq(&head->lock);
7768 __skb_queue_head(head, skb);
7773 spin_unlock_irq(&head->lock);
7780 return __io_sqe_files_scm(ctx, 1, index);
7786 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7787 struct io_rsrc_node *node, void *rsrc)
7789 struct io_rsrc_put *prsrc;
7791 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7795 prsrc->tag = data->tags[idx];
7797 list_add(&prsrc->list, &node->rsrc_list);
7801 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7802 struct io_uring_rsrc_update2 *up,
7805 u64 __user *tags = u64_to_user_ptr(up->tags);
7806 __s32 __user *fds = u64_to_user_ptr(up->data);
7807 struct io_rsrc_data *data = ctx->file_data;
7808 struct io_fixed_file *file_slot;
7812 bool needs_switch = false;
7814 if (!ctx->file_data)
7816 if (up->offset + nr_args > ctx->nr_user_files)
7819 for (done = 0; done < nr_args; done++) {
7822 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7823 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7827 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7831 if (fd == IORING_REGISTER_FILES_SKIP)
7834 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7835 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7837 if (file_slot->file_ptr) {
7838 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7839 err = io_queue_rsrc_removal(data, up->offset + done,
7840 ctx->rsrc_node, file);
7843 file_slot->file_ptr = 0;
7844 needs_switch = true;
7853 * Don't allow io_uring instances to be registered. If
7854 * UNIX isn't enabled, then this causes a reference
7855 * cycle and this instance can never get freed. If UNIX
7856 * is enabled we'll handle it just fine, but there's
7857 * still no point in allowing a ring fd as it doesn't
7858 * support regular read/write anyway.
7860 if (file->f_op == &io_uring_fops) {
7865 data->tags[up->offset + done] = tag;
7866 io_fixed_file_set(file_slot, file);
7867 err = io_sqe_file_register(ctx, file, i);
7869 file_slot->file_ptr = 0;
7877 io_rsrc_node_switch(ctx, data);
7878 return done ? done : err;
7881 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7883 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7885 req = io_put_req_find_next(req);
7886 return req ? &req->work : NULL;
7889 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7890 struct task_struct *task)
7892 struct io_wq_hash *hash;
7893 struct io_wq_data data;
7894 unsigned int concurrency;
7896 mutex_lock(&ctx->uring_lock);
7897 hash = ctx->hash_map;
7899 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7901 mutex_unlock(&ctx->uring_lock);
7902 return ERR_PTR(-ENOMEM);
7904 refcount_set(&hash->refs, 1);
7905 init_waitqueue_head(&hash->wait);
7906 ctx->hash_map = hash;
7908 mutex_unlock(&ctx->uring_lock);
7912 data.free_work = io_free_work;
7913 data.do_work = io_wq_submit_work;
7915 /* Do QD, or 4 * CPUS, whatever is smallest */
7916 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7918 return io_wq_create(concurrency, &data);
7921 static int io_uring_alloc_task_context(struct task_struct *task,
7922 struct io_ring_ctx *ctx)
7924 struct io_uring_task *tctx;
7927 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7928 if (unlikely(!tctx))
7931 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7932 if (unlikely(ret)) {
7937 tctx->io_wq = io_init_wq_offload(ctx, task);
7938 if (IS_ERR(tctx->io_wq)) {
7939 ret = PTR_ERR(tctx->io_wq);
7940 percpu_counter_destroy(&tctx->inflight);
7946 init_waitqueue_head(&tctx->wait);
7948 atomic_set(&tctx->in_idle, 0);
7949 atomic_set(&tctx->inflight_tracked, 0);
7950 task->io_uring = tctx;
7951 spin_lock_init(&tctx->task_lock);
7952 INIT_WQ_LIST(&tctx->task_list);
7953 tctx->task_state = 0;
7954 init_task_work(&tctx->task_work, tctx_task_work);
7958 void __io_uring_free(struct task_struct *tsk)
7960 struct io_uring_task *tctx = tsk->io_uring;
7962 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7963 WARN_ON_ONCE(tctx->io_wq);
7965 percpu_counter_destroy(&tctx->inflight);
7967 tsk->io_uring = NULL;
7970 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7971 struct io_uring_params *p)
7975 /* Retain compatibility with failing for an invalid attach attempt */
7976 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7977 IORING_SETUP_ATTACH_WQ) {
7980 f = fdget(p->wq_fd);
7983 if (f.file->f_op != &io_uring_fops) {
7989 if (ctx->flags & IORING_SETUP_SQPOLL) {
7990 struct task_struct *tsk;
7991 struct io_sq_data *sqd;
7994 sqd = io_get_sq_data(p, &attached);
8000 ctx->sq_creds = get_current_cred();
8002 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8003 if (!ctx->sq_thread_idle)
8004 ctx->sq_thread_idle = HZ;
8006 io_sq_thread_park(sqd);
8007 list_add(&ctx->sqd_list, &sqd->ctx_list);
8008 io_sqd_update_thread_idle(sqd);
8009 /* don't attach to a dying SQPOLL thread, would be racy */
8010 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8011 io_sq_thread_unpark(sqd);
8018 if (p->flags & IORING_SETUP_SQ_AFF) {
8019 int cpu = p->sq_thread_cpu;
8022 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8029 sqd->task_pid = current->pid;
8030 sqd->task_tgid = current->tgid;
8031 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8038 ret = io_uring_alloc_task_context(tsk, ctx);
8039 wake_up_new_task(tsk);
8042 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8043 /* Can't have SQ_AFF without SQPOLL */
8050 complete(&ctx->sq_data->exited);
8052 io_sq_thread_finish(ctx);
8056 static inline void __io_unaccount_mem(struct user_struct *user,
8057 unsigned long nr_pages)
8059 atomic_long_sub(nr_pages, &user->locked_vm);
8062 static inline int __io_account_mem(struct user_struct *user,
8063 unsigned long nr_pages)
8065 unsigned long page_limit, cur_pages, new_pages;
8067 /* Don't allow more pages than we can safely lock */
8068 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8071 cur_pages = atomic_long_read(&user->locked_vm);
8072 new_pages = cur_pages + nr_pages;
8073 if (new_pages > page_limit)
8075 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8076 new_pages) != cur_pages);
8081 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8084 __io_unaccount_mem(ctx->user, nr_pages);
8086 if (ctx->mm_account)
8087 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8090 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8095 ret = __io_account_mem(ctx->user, nr_pages);
8100 if (ctx->mm_account)
8101 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8106 static void io_mem_free(void *ptr)
8113 page = virt_to_head_page(ptr);
8114 if (put_page_testzero(page))
8115 free_compound_page(page);
8118 static void *io_mem_alloc(size_t size)
8120 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8121 __GFP_NORETRY | __GFP_ACCOUNT;
8123 return (void *) __get_free_pages(gfp_flags, get_order(size));
8126 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8129 struct io_rings *rings;
8130 size_t off, sq_array_size;
8132 off = struct_size(rings, cqes, cq_entries);
8133 if (off == SIZE_MAX)
8137 off = ALIGN(off, SMP_CACHE_BYTES);
8145 sq_array_size = array_size(sizeof(u32), sq_entries);
8146 if (sq_array_size == SIZE_MAX)
8149 if (check_add_overflow(off, sq_array_size, &off))
8155 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8157 struct io_mapped_ubuf *imu = *slot;
8160 if (imu != ctx->dummy_ubuf) {
8161 for (i = 0; i < imu->nr_bvecs; i++)
8162 unpin_user_page(imu->bvec[i].bv_page);
8163 if (imu->acct_pages)
8164 io_unaccount_mem(ctx, imu->acct_pages);
8170 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8172 io_buffer_unmap(ctx, &prsrc->buf);
8176 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8180 for (i = 0; i < ctx->nr_user_bufs; i++)
8181 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8182 kfree(ctx->user_bufs);
8183 io_rsrc_data_free(ctx->buf_data);
8184 ctx->user_bufs = NULL;
8185 ctx->buf_data = NULL;
8186 ctx->nr_user_bufs = 0;
8189 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8196 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8198 __io_sqe_buffers_unregister(ctx);
8202 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8203 void __user *arg, unsigned index)
8205 struct iovec __user *src;
8207 #ifdef CONFIG_COMPAT
8209 struct compat_iovec __user *ciovs;
8210 struct compat_iovec ciov;
8212 ciovs = (struct compat_iovec __user *) arg;
8213 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8216 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8217 dst->iov_len = ciov.iov_len;
8221 src = (struct iovec __user *) arg;
8222 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8228 * Not super efficient, but this is just a registration time. And we do cache
8229 * the last compound head, so generally we'll only do a full search if we don't
8232 * We check if the given compound head page has already been accounted, to
8233 * avoid double accounting it. This allows us to account the full size of the
8234 * page, not just the constituent pages of a huge page.
8236 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8237 int nr_pages, struct page *hpage)
8241 /* check current page array */
8242 for (i = 0; i < nr_pages; i++) {
8243 if (!PageCompound(pages[i]))
8245 if (compound_head(pages[i]) == hpage)
8249 /* check previously registered pages */
8250 for (i = 0; i < ctx->nr_user_bufs; i++) {
8251 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8253 for (j = 0; j < imu->nr_bvecs; j++) {
8254 if (!PageCompound(imu->bvec[j].bv_page))
8256 if (compound_head(imu->bvec[j].bv_page) == hpage)
8264 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8265 int nr_pages, struct io_mapped_ubuf *imu,
8266 struct page **last_hpage)
8270 imu->acct_pages = 0;
8271 for (i = 0; i < nr_pages; i++) {
8272 if (!PageCompound(pages[i])) {
8277 hpage = compound_head(pages[i]);
8278 if (hpage == *last_hpage)
8280 *last_hpage = hpage;
8281 if (headpage_already_acct(ctx, pages, i, hpage))
8283 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8287 if (!imu->acct_pages)
8290 ret = io_account_mem(ctx, imu->acct_pages);
8292 imu->acct_pages = 0;
8296 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8297 struct io_mapped_ubuf **pimu,
8298 struct page **last_hpage)
8300 struct io_mapped_ubuf *imu = NULL;
8301 struct vm_area_struct **vmas = NULL;
8302 struct page **pages = NULL;
8303 unsigned long off, start, end, ubuf;
8305 int ret, pret, nr_pages, i;
8307 if (!iov->iov_base) {
8308 *pimu = ctx->dummy_ubuf;
8312 ubuf = (unsigned long) iov->iov_base;
8313 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8314 start = ubuf >> PAGE_SHIFT;
8315 nr_pages = end - start;
8320 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8324 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8329 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8334 mmap_read_lock(current->mm);
8335 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8337 if (pret == nr_pages) {
8338 /* don't support file backed memory */
8339 for (i = 0; i < nr_pages; i++) {
8340 struct vm_area_struct *vma = vmas[i];
8343 !is_file_hugepages(vma->vm_file)) {
8349 ret = pret < 0 ? pret : -EFAULT;
8351 mmap_read_unlock(current->mm);
8354 * if we did partial map, or found file backed vmas,
8355 * release any pages we did get
8358 unpin_user_pages(pages, pret);
8362 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8364 unpin_user_pages(pages, pret);
8368 off = ubuf & ~PAGE_MASK;
8369 size = iov->iov_len;
8370 for (i = 0; i < nr_pages; i++) {
8373 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8374 imu->bvec[i].bv_page = pages[i];
8375 imu->bvec[i].bv_len = vec_len;
8376 imu->bvec[i].bv_offset = off;
8380 /* store original address for later verification */
8382 imu->ubuf_end = ubuf + iov->iov_len;
8383 imu->nr_bvecs = nr_pages;
8394 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8396 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8397 return ctx->user_bufs ? 0 : -ENOMEM;
8400 static int io_buffer_validate(struct iovec *iov)
8402 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8405 * Don't impose further limits on the size and buffer
8406 * constraints here, we'll -EINVAL later when IO is
8407 * submitted if they are wrong.
8410 return iov->iov_len ? -EFAULT : 0;
8414 /* arbitrary limit, but we need something */
8415 if (iov->iov_len > SZ_1G)
8418 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8424 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8425 unsigned int nr_args, u64 __user *tags)
8427 struct page *last_hpage = NULL;
8428 struct io_rsrc_data *data;
8434 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8436 ret = io_rsrc_node_switch_start(ctx);
8439 data = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, nr_args);
8442 ret = io_buffers_map_alloc(ctx, nr_args);
8444 io_rsrc_data_free(data);
8448 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8451 if (tags && copy_from_user(&tag, &tags[i], sizeof(tag))) {
8455 ret = io_copy_iov(ctx, &iov, arg, i);
8458 ret = io_buffer_validate(&iov);
8461 if (!iov.iov_base && tag) {
8466 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8470 data->tags[i] = tag;
8473 WARN_ON_ONCE(ctx->buf_data);
8475 ctx->buf_data = data;
8477 __io_sqe_buffers_unregister(ctx);
8479 io_rsrc_node_switch(ctx, NULL);
8483 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8484 struct io_uring_rsrc_update2 *up,
8485 unsigned int nr_args)
8487 u64 __user *tags = u64_to_user_ptr(up->tags);
8488 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8489 struct page *last_hpage = NULL;
8490 bool needs_switch = false;
8496 if (up->offset + nr_args > ctx->nr_user_bufs)
8499 for (done = 0; done < nr_args; done++) {
8500 struct io_mapped_ubuf *imu;
8501 int offset = up->offset + done;
8504 err = io_copy_iov(ctx, &iov, iovs, done);
8507 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8511 err = io_buffer_validate(&iov);
8514 if (!iov.iov_base && tag) {
8518 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8522 i = array_index_nospec(offset, ctx->nr_user_bufs);
8523 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8524 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8525 ctx->rsrc_node, ctx->user_bufs[i]);
8526 if (unlikely(err)) {
8527 io_buffer_unmap(ctx, &imu);
8530 ctx->user_bufs[i] = NULL;
8531 needs_switch = true;
8534 ctx->user_bufs[i] = imu;
8535 ctx->buf_data->tags[offset] = tag;
8539 io_rsrc_node_switch(ctx, ctx->buf_data);
8540 return done ? done : err;
8543 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8545 __s32 __user *fds = arg;
8551 if (copy_from_user(&fd, fds, sizeof(*fds)))
8554 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8555 if (IS_ERR(ctx->cq_ev_fd)) {
8556 int ret = PTR_ERR(ctx->cq_ev_fd);
8558 ctx->cq_ev_fd = NULL;
8565 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8567 if (ctx->cq_ev_fd) {
8568 eventfd_ctx_put(ctx->cq_ev_fd);
8569 ctx->cq_ev_fd = NULL;
8576 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8578 struct io_buffer *buf;
8579 unsigned long index;
8581 xa_for_each(&ctx->io_buffers, index, buf)
8582 __io_remove_buffers(ctx, buf, index, -1U);
8585 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8587 struct io_kiocb *req, *nxt;
8589 list_for_each_entry_safe(req, nxt, list, compl.list) {
8590 if (tsk && req->task != tsk)
8592 list_del(&req->compl.list);
8593 kmem_cache_free(req_cachep, req);
8597 static void io_req_caches_free(struct io_ring_ctx *ctx)
8599 struct io_submit_state *submit_state = &ctx->submit_state;
8600 struct io_comp_state *cs = &ctx->submit_state.comp;
8602 mutex_lock(&ctx->uring_lock);
8604 if (submit_state->free_reqs) {
8605 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8606 submit_state->reqs);
8607 submit_state->free_reqs = 0;
8610 io_flush_cached_locked_reqs(ctx, cs);
8611 io_req_cache_free(&cs->free_list, NULL);
8612 mutex_unlock(&ctx->uring_lock);
8615 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8617 if (data && !atomic_dec_and_test(&data->refs))
8618 wait_for_completion(&data->done);
8621 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8623 io_sq_thread_finish(ctx);
8625 if (ctx->mm_account) {
8626 mmdrop(ctx->mm_account);
8627 ctx->mm_account = NULL;
8630 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8631 io_wait_rsrc_data(ctx->buf_data);
8632 io_wait_rsrc_data(ctx->file_data);
8634 mutex_lock(&ctx->uring_lock);
8636 __io_sqe_buffers_unregister(ctx);
8638 __io_sqe_files_unregister(ctx);
8640 __io_cqring_overflow_flush(ctx, true);
8641 mutex_unlock(&ctx->uring_lock);
8642 io_eventfd_unregister(ctx);
8643 io_destroy_buffers(ctx);
8645 put_cred(ctx->sq_creds);
8647 /* there are no registered resources left, nobody uses it */
8649 io_rsrc_node_destroy(ctx->rsrc_node);
8650 if (ctx->rsrc_backup_node)
8651 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8652 flush_delayed_work(&ctx->rsrc_put_work);
8654 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8655 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8657 #if defined(CONFIG_UNIX)
8658 if (ctx->ring_sock) {
8659 ctx->ring_sock->file = NULL; /* so that iput() is called */
8660 sock_release(ctx->ring_sock);
8664 io_mem_free(ctx->rings);
8665 io_mem_free(ctx->sq_sqes);
8667 percpu_ref_exit(&ctx->refs);
8668 free_uid(ctx->user);
8669 io_req_caches_free(ctx);
8671 io_wq_put_hash(ctx->hash_map);
8672 kfree(ctx->cancel_hash);
8673 kfree(ctx->dummy_ubuf);
8677 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8679 struct io_ring_ctx *ctx = file->private_data;
8682 poll_wait(file, &ctx->cq_wait, wait);
8684 * synchronizes with barrier from wq_has_sleeper call in
8688 if (!io_sqring_full(ctx))
8689 mask |= EPOLLOUT | EPOLLWRNORM;
8692 * Don't flush cqring overflow list here, just do a simple check.
8693 * Otherwise there could possible be ABBA deadlock:
8696 * lock(&ctx->uring_lock);
8698 * lock(&ctx->uring_lock);
8701 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8702 * pushs them to do the flush.
8704 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8705 mask |= EPOLLIN | EPOLLRDNORM;
8710 static int io_uring_fasync(int fd, struct file *file, int on)
8712 struct io_ring_ctx *ctx = file->private_data;
8714 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8717 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8719 const struct cred *creds;
8721 creds = xa_erase(&ctx->personalities, id);
8730 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8732 return io_run_task_work_head(&ctx->exit_task_work);
8735 struct io_tctx_exit {
8736 struct callback_head task_work;
8737 struct completion completion;
8738 struct io_ring_ctx *ctx;
8741 static void io_tctx_exit_cb(struct callback_head *cb)
8743 struct io_uring_task *tctx = current->io_uring;
8744 struct io_tctx_exit *work;
8746 work = container_of(cb, struct io_tctx_exit, task_work);
8748 * When @in_idle, we're in cancellation and it's racy to remove the
8749 * node. It'll be removed by the end of cancellation, just ignore it.
8751 if (!atomic_read(&tctx->in_idle))
8752 io_uring_del_task_file((unsigned long)work->ctx);
8753 complete(&work->completion);
8756 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8758 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8760 return req->ctx == data;
8763 static void io_ring_exit_work(struct work_struct *work)
8765 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8766 unsigned long timeout = jiffies + HZ * 60 * 5;
8767 struct io_tctx_exit exit;
8768 struct io_tctx_node *node;
8772 * If we're doing polled IO and end up having requests being
8773 * submitted async (out-of-line), then completions can come in while
8774 * we're waiting for refs to drop. We need to reap these manually,
8775 * as nobody else will be looking for them.
8778 io_uring_try_cancel_requests(ctx, NULL, true);
8780 struct io_sq_data *sqd = ctx->sq_data;
8781 struct task_struct *tsk;
8783 io_sq_thread_park(sqd);
8785 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8786 io_wq_cancel_cb(tsk->io_uring->io_wq,
8787 io_cancel_ctx_cb, ctx, true);
8788 io_sq_thread_unpark(sqd);
8791 WARN_ON_ONCE(time_after(jiffies, timeout));
8792 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8794 init_completion(&exit.completion);
8795 init_task_work(&exit.task_work, io_tctx_exit_cb);
8798 * Some may use context even when all refs and requests have been put,
8799 * and they are free to do so while still holding uring_lock or
8800 * completion_lock, see __io_req_task_submit(). Apart from other work,
8801 * this lock/unlock section also waits them to finish.
8803 mutex_lock(&ctx->uring_lock);
8804 while (!list_empty(&ctx->tctx_list)) {
8805 WARN_ON_ONCE(time_after(jiffies, timeout));
8807 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8809 /* don't spin on a single task if cancellation failed */
8810 list_rotate_left(&ctx->tctx_list);
8811 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8812 if (WARN_ON_ONCE(ret))
8814 wake_up_process(node->task);
8816 mutex_unlock(&ctx->uring_lock);
8817 wait_for_completion(&exit.completion);
8818 mutex_lock(&ctx->uring_lock);
8820 mutex_unlock(&ctx->uring_lock);
8821 spin_lock_irq(&ctx->completion_lock);
8822 spin_unlock_irq(&ctx->completion_lock);
8824 io_ring_ctx_free(ctx);
8827 /* Returns true if we found and killed one or more timeouts */
8828 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8831 struct io_kiocb *req, *tmp;
8834 spin_lock_irq(&ctx->completion_lock);
8835 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8836 if (io_match_task(req, tsk, cancel_all)) {
8837 io_kill_timeout(req, -ECANCELED);
8842 io_commit_cqring(ctx);
8843 spin_unlock_irq(&ctx->completion_lock);
8845 io_cqring_ev_posted(ctx);
8846 return canceled != 0;
8849 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8851 unsigned long index;
8852 struct creds *creds;
8854 mutex_lock(&ctx->uring_lock);
8855 percpu_ref_kill(&ctx->refs);
8857 __io_cqring_overflow_flush(ctx, true);
8858 xa_for_each(&ctx->personalities, index, creds)
8859 io_unregister_personality(ctx, index);
8860 mutex_unlock(&ctx->uring_lock);
8862 io_kill_timeouts(ctx, NULL, true);
8863 io_poll_remove_all(ctx, NULL, true);
8865 /* if we failed setting up the ctx, we might not have any rings */
8866 io_iopoll_try_reap_events(ctx);
8868 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8870 * Use system_unbound_wq to avoid spawning tons of event kworkers
8871 * if we're exiting a ton of rings at the same time. It just adds
8872 * noise and overhead, there's no discernable change in runtime
8873 * over using system_wq.
8875 queue_work(system_unbound_wq, &ctx->exit_work);
8878 static int io_uring_release(struct inode *inode, struct file *file)
8880 struct io_ring_ctx *ctx = file->private_data;
8882 file->private_data = NULL;
8883 io_ring_ctx_wait_and_kill(ctx);
8887 struct io_task_cancel {
8888 struct task_struct *task;
8892 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8894 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8895 struct io_task_cancel *cancel = data;
8898 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
8899 unsigned long flags;
8900 struct io_ring_ctx *ctx = req->ctx;
8902 /* protect against races with linked timeouts */
8903 spin_lock_irqsave(&ctx->completion_lock, flags);
8904 ret = io_match_task(req, cancel->task, cancel->all);
8905 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8907 ret = io_match_task(req, cancel->task, cancel->all);
8912 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8913 struct task_struct *task, bool cancel_all)
8915 struct io_defer_entry *de;
8918 spin_lock_irq(&ctx->completion_lock);
8919 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8920 if (io_match_task(de->req, task, cancel_all)) {
8921 list_cut_position(&list, &ctx->defer_list, &de->list);
8925 spin_unlock_irq(&ctx->completion_lock);
8926 if (list_empty(&list))
8929 while (!list_empty(&list)) {
8930 de = list_first_entry(&list, struct io_defer_entry, list);
8931 list_del_init(&de->list);
8932 io_req_complete_failed(de->req, -ECANCELED);
8938 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8940 struct io_tctx_node *node;
8941 enum io_wq_cancel cret;
8944 mutex_lock(&ctx->uring_lock);
8945 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8946 struct io_uring_task *tctx = node->task->io_uring;
8949 * io_wq will stay alive while we hold uring_lock, because it's
8950 * killed after ctx nodes, which requires to take the lock.
8952 if (!tctx || !tctx->io_wq)
8954 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8955 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8957 mutex_unlock(&ctx->uring_lock);
8962 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8963 struct task_struct *task,
8966 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
8967 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8970 enum io_wq_cancel cret;
8974 ret |= io_uring_try_cancel_iowq(ctx);
8975 } else if (tctx && tctx->io_wq) {
8977 * Cancels requests of all rings, not only @ctx, but
8978 * it's fine as the task is in exit/exec.
8980 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8982 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8985 /* SQPOLL thread does its own polling */
8986 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
8987 (ctx->sq_data && ctx->sq_data->thread == current)) {
8988 while (!list_empty_careful(&ctx->iopoll_list)) {
8989 io_iopoll_try_reap_events(ctx);
8994 ret |= io_cancel_defer_files(ctx, task, cancel_all);
8995 ret |= io_poll_remove_all(ctx, task, cancel_all);
8996 ret |= io_kill_timeouts(ctx, task, cancel_all);
8998 ret |= io_run_task_work();
8999 ret |= io_run_ctx_fallback(ctx);
9006 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
9008 struct io_uring_task *tctx = current->io_uring;
9009 struct io_tctx_node *node;
9012 if (unlikely(!tctx)) {
9013 ret = io_uring_alloc_task_context(current, ctx);
9016 tctx = current->io_uring;
9018 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9019 node = kmalloc(sizeof(*node), GFP_KERNEL);
9023 node->task = current;
9025 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9032 mutex_lock(&ctx->uring_lock);
9033 list_add(&node->ctx_node, &ctx->tctx_list);
9034 mutex_unlock(&ctx->uring_lock);
9041 * Note that this task has used io_uring. We use it for cancelation purposes.
9043 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
9045 struct io_uring_task *tctx = current->io_uring;
9047 if (likely(tctx && tctx->last == ctx))
9049 return __io_uring_add_task_file(ctx);
9053 * Remove this io_uring_file -> task mapping.
9055 static void io_uring_del_task_file(unsigned long index)
9057 struct io_uring_task *tctx = current->io_uring;
9058 struct io_tctx_node *node;
9062 node = xa_erase(&tctx->xa, index);
9066 WARN_ON_ONCE(current != node->task);
9067 WARN_ON_ONCE(list_empty(&node->ctx_node));
9069 mutex_lock(&node->ctx->uring_lock);
9070 list_del(&node->ctx_node);
9071 mutex_unlock(&node->ctx->uring_lock);
9073 if (tctx->last == node->ctx)
9078 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9080 struct io_wq *wq = tctx->io_wq;
9081 struct io_tctx_node *node;
9082 unsigned long index;
9084 xa_for_each(&tctx->xa, index, node)
9085 io_uring_del_task_file(index);
9088 * Must be after io_uring_del_task_file() (removes nodes under
9089 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9092 io_wq_put_and_exit(wq);
9096 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9099 return atomic_read(&tctx->inflight_tracked);
9100 return percpu_counter_sum(&tctx->inflight);
9103 static void io_uring_try_cancel(bool cancel_all)
9105 struct io_uring_task *tctx = current->io_uring;
9106 struct io_tctx_node *node;
9107 unsigned long index;
9109 xa_for_each(&tctx->xa, index, node) {
9110 struct io_ring_ctx *ctx = node->ctx;
9112 /* sqpoll task will cancel all its requests */
9114 io_uring_try_cancel_requests(ctx, current, cancel_all);
9118 /* should only be called by SQPOLL task */
9119 static void io_uring_cancel_sqpoll(struct io_sq_data *sqd)
9121 struct io_uring_task *tctx = current->io_uring;
9122 struct io_ring_ctx *ctx;
9126 if (!current->io_uring)
9129 io_wq_exit_start(tctx->io_wq);
9131 WARN_ON_ONCE(!sqd || sqd->thread != current);
9133 atomic_inc(&tctx->in_idle);
9135 /* read completions before cancelations */
9136 inflight = tctx_inflight(tctx, false);
9139 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9140 io_uring_try_cancel_requests(ctx, current, true);
9142 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9144 * If we've seen completions, retry without waiting. This
9145 * avoids a race where a completion comes in before we did
9146 * prepare_to_wait().
9148 if (inflight == tctx_inflight(tctx, false))
9150 finish_wait(&tctx->wait, &wait);
9152 atomic_dec(&tctx->in_idle);
9156 * Find any io_uring fd that this task has registered or done IO on, and cancel
9159 void __io_uring_cancel(struct files_struct *files)
9161 struct io_uring_task *tctx = current->io_uring;
9164 bool cancel_all = !files;
9167 io_wq_exit_start(tctx->io_wq);
9169 /* make sure overflow events are dropped */
9170 atomic_inc(&tctx->in_idle);
9172 /* read completions before cancelations */
9173 inflight = tctx_inflight(tctx, !cancel_all);
9176 io_uring_try_cancel(cancel_all);
9177 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9180 * If we've seen completions, retry without waiting. This
9181 * avoids a race where a completion comes in before we did
9182 * prepare_to_wait().
9184 if (inflight == tctx_inflight(tctx, !cancel_all))
9186 finish_wait(&tctx->wait, &wait);
9188 atomic_dec(&tctx->in_idle);
9190 io_uring_clean_tctx(tctx);
9192 /* for exec all current's requests should be gone, kill tctx */
9193 __io_uring_free(current);
9197 static void *io_uring_validate_mmap_request(struct file *file,
9198 loff_t pgoff, size_t sz)
9200 struct io_ring_ctx *ctx = file->private_data;
9201 loff_t offset = pgoff << PAGE_SHIFT;
9206 case IORING_OFF_SQ_RING:
9207 case IORING_OFF_CQ_RING:
9210 case IORING_OFF_SQES:
9214 return ERR_PTR(-EINVAL);
9217 page = virt_to_head_page(ptr);
9218 if (sz > page_size(page))
9219 return ERR_PTR(-EINVAL);
9226 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9228 size_t sz = vma->vm_end - vma->vm_start;
9232 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9234 return PTR_ERR(ptr);
9236 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9237 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9240 #else /* !CONFIG_MMU */
9242 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9244 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9247 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9249 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9252 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9253 unsigned long addr, unsigned long len,
9254 unsigned long pgoff, unsigned long flags)
9258 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9260 return PTR_ERR(ptr);
9262 return (unsigned long) ptr;
9265 #endif /* !CONFIG_MMU */
9267 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9272 if (!io_sqring_full(ctx))
9274 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9276 if (!io_sqring_full(ctx))
9279 } while (!signal_pending(current));
9281 finish_wait(&ctx->sqo_sq_wait, &wait);
9285 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9286 struct __kernel_timespec __user **ts,
9287 const sigset_t __user **sig)
9289 struct io_uring_getevents_arg arg;
9292 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9293 * is just a pointer to the sigset_t.
9295 if (!(flags & IORING_ENTER_EXT_ARG)) {
9296 *sig = (const sigset_t __user *) argp;
9302 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9303 * timespec and sigset_t pointers if good.
9305 if (*argsz != sizeof(arg))
9307 if (copy_from_user(&arg, argp, sizeof(arg)))
9309 *sig = u64_to_user_ptr(arg.sigmask);
9310 *argsz = arg.sigmask_sz;
9311 *ts = u64_to_user_ptr(arg.ts);
9315 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9316 u32, min_complete, u32, flags, const void __user *, argp,
9319 struct io_ring_ctx *ctx;
9326 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9327 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9331 if (unlikely(!f.file))
9335 if (unlikely(f.file->f_op != &io_uring_fops))
9339 ctx = f.file->private_data;
9340 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9344 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9348 * For SQ polling, the thread will do all submissions and completions.
9349 * Just return the requested submit count, and wake the thread if
9353 if (ctx->flags & IORING_SETUP_SQPOLL) {
9354 io_cqring_overflow_flush(ctx, false);
9356 if (unlikely(ctx->sq_data->thread == NULL)) {
9360 if (flags & IORING_ENTER_SQ_WAKEUP)
9361 wake_up(&ctx->sq_data->wait);
9362 if (flags & IORING_ENTER_SQ_WAIT) {
9363 ret = io_sqpoll_wait_sq(ctx);
9367 submitted = to_submit;
9368 } else if (to_submit) {
9369 ret = io_uring_add_task_file(ctx);
9372 mutex_lock(&ctx->uring_lock);
9373 submitted = io_submit_sqes(ctx, to_submit);
9374 mutex_unlock(&ctx->uring_lock);
9376 if (submitted != to_submit)
9379 if (flags & IORING_ENTER_GETEVENTS) {
9380 const sigset_t __user *sig;
9381 struct __kernel_timespec __user *ts;
9383 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9387 min_complete = min(min_complete, ctx->cq_entries);
9390 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9391 * space applications don't need to do io completion events
9392 * polling again, they can rely on io_sq_thread to do polling
9393 * work, which can reduce cpu usage and uring_lock contention.
9395 if (ctx->flags & IORING_SETUP_IOPOLL &&
9396 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9397 ret = io_iopoll_check(ctx, min_complete);
9399 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9404 percpu_ref_put(&ctx->refs);
9407 return submitted ? submitted : ret;
9410 #ifdef CONFIG_PROC_FS
9411 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9412 const struct cred *cred)
9414 struct user_namespace *uns = seq_user_ns(m);
9415 struct group_info *gi;
9420 seq_printf(m, "%5d\n", id);
9421 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9422 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9423 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9424 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9425 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9426 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9427 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9428 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9429 seq_puts(m, "\n\tGroups:\t");
9430 gi = cred->group_info;
9431 for (g = 0; g < gi->ngroups; g++) {
9432 seq_put_decimal_ull(m, g ? " " : "",
9433 from_kgid_munged(uns, gi->gid[g]));
9435 seq_puts(m, "\n\tCapEff:\t");
9436 cap = cred->cap_effective;
9437 CAP_FOR_EACH_U32(__capi)
9438 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9443 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9445 struct io_sq_data *sq = NULL;
9450 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9451 * since fdinfo case grabs it in the opposite direction of normal use
9452 * cases. If we fail to get the lock, we just don't iterate any
9453 * structures that could be going away outside the io_uring mutex.
9455 has_lock = mutex_trylock(&ctx->uring_lock);
9457 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9463 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9464 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9465 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9466 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9467 struct file *f = io_file_from_index(ctx, i);
9470 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9472 seq_printf(m, "%5u: <none>\n", i);
9474 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9475 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9476 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9477 unsigned int len = buf->ubuf_end - buf->ubuf;
9479 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9481 if (has_lock && !xa_empty(&ctx->personalities)) {
9482 unsigned long index;
9483 const struct cred *cred;
9485 seq_printf(m, "Personalities:\n");
9486 xa_for_each(&ctx->personalities, index, cred)
9487 io_uring_show_cred(m, index, cred);
9489 seq_printf(m, "PollList:\n");
9490 spin_lock_irq(&ctx->completion_lock);
9491 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9492 struct hlist_head *list = &ctx->cancel_hash[i];
9493 struct io_kiocb *req;
9495 hlist_for_each_entry(req, list, hash_node)
9496 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9497 req->task->task_works != NULL);
9499 spin_unlock_irq(&ctx->completion_lock);
9501 mutex_unlock(&ctx->uring_lock);
9504 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9506 struct io_ring_ctx *ctx = f->private_data;
9508 if (percpu_ref_tryget(&ctx->refs)) {
9509 __io_uring_show_fdinfo(ctx, m);
9510 percpu_ref_put(&ctx->refs);
9515 static const struct file_operations io_uring_fops = {
9516 .release = io_uring_release,
9517 .mmap = io_uring_mmap,
9519 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9520 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9522 .poll = io_uring_poll,
9523 .fasync = io_uring_fasync,
9524 #ifdef CONFIG_PROC_FS
9525 .show_fdinfo = io_uring_show_fdinfo,
9529 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9530 struct io_uring_params *p)
9532 struct io_rings *rings;
9533 size_t size, sq_array_offset;
9535 /* make sure these are sane, as we already accounted them */
9536 ctx->sq_entries = p->sq_entries;
9537 ctx->cq_entries = p->cq_entries;
9539 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9540 if (size == SIZE_MAX)
9543 rings = io_mem_alloc(size);
9548 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9549 rings->sq_ring_mask = p->sq_entries - 1;
9550 rings->cq_ring_mask = p->cq_entries - 1;
9551 rings->sq_ring_entries = p->sq_entries;
9552 rings->cq_ring_entries = p->cq_entries;
9553 ctx->sq_mask = rings->sq_ring_mask;
9554 ctx->cq_mask = rings->cq_ring_mask;
9556 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9557 if (size == SIZE_MAX) {
9558 io_mem_free(ctx->rings);
9563 ctx->sq_sqes = io_mem_alloc(size);
9564 if (!ctx->sq_sqes) {
9565 io_mem_free(ctx->rings);
9573 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9577 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9581 ret = io_uring_add_task_file(ctx);
9586 fd_install(fd, file);
9591 * Allocate an anonymous fd, this is what constitutes the application
9592 * visible backing of an io_uring instance. The application mmaps this
9593 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9594 * we have to tie this fd to a socket for file garbage collection purposes.
9596 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9599 #if defined(CONFIG_UNIX)
9602 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9605 return ERR_PTR(ret);
9608 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9609 O_RDWR | O_CLOEXEC);
9610 #if defined(CONFIG_UNIX)
9612 sock_release(ctx->ring_sock);
9613 ctx->ring_sock = NULL;
9615 ctx->ring_sock->file = file;
9621 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9622 struct io_uring_params __user *params)
9624 struct io_ring_ctx *ctx;
9630 if (entries > IORING_MAX_ENTRIES) {
9631 if (!(p->flags & IORING_SETUP_CLAMP))
9633 entries = IORING_MAX_ENTRIES;
9637 * Use twice as many entries for the CQ ring. It's possible for the
9638 * application to drive a higher depth than the size of the SQ ring,
9639 * since the sqes are only used at submission time. This allows for
9640 * some flexibility in overcommitting a bit. If the application has
9641 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9642 * of CQ ring entries manually.
9644 p->sq_entries = roundup_pow_of_two(entries);
9645 if (p->flags & IORING_SETUP_CQSIZE) {
9647 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9648 * to a power-of-two, if it isn't already. We do NOT impose
9649 * any cq vs sq ring sizing.
9653 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9654 if (!(p->flags & IORING_SETUP_CLAMP))
9656 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9658 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9659 if (p->cq_entries < p->sq_entries)
9662 p->cq_entries = 2 * p->sq_entries;
9665 ctx = io_ring_ctx_alloc(p);
9668 ctx->compat = in_compat_syscall();
9669 if (!capable(CAP_IPC_LOCK))
9670 ctx->user = get_uid(current_user());
9673 * This is just grabbed for accounting purposes. When a process exits,
9674 * the mm is exited and dropped before the files, hence we need to hang
9675 * on to this mm purely for the purposes of being able to unaccount
9676 * memory (locked/pinned vm). It's not used for anything else.
9678 mmgrab(current->mm);
9679 ctx->mm_account = current->mm;
9681 ret = io_allocate_scq_urings(ctx, p);
9685 ret = io_sq_offload_create(ctx, p);
9688 /* always set a rsrc node */
9689 ret = io_rsrc_node_switch_start(ctx);
9692 io_rsrc_node_switch(ctx, NULL);
9694 memset(&p->sq_off, 0, sizeof(p->sq_off));
9695 p->sq_off.head = offsetof(struct io_rings, sq.head);
9696 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9697 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9698 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9699 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9700 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9701 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9703 memset(&p->cq_off, 0, sizeof(p->cq_off));
9704 p->cq_off.head = offsetof(struct io_rings, cq.head);
9705 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9706 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9707 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9708 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9709 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9710 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9712 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9713 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9714 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9715 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9716 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9717 IORING_FEAT_RSRC_TAGS;
9719 if (copy_to_user(params, p, sizeof(*p))) {
9724 file = io_uring_get_file(ctx);
9726 ret = PTR_ERR(file);
9731 * Install ring fd as the very last thing, so we don't risk someone
9732 * having closed it before we finish setup
9734 ret = io_uring_install_fd(ctx, file);
9736 /* fput will clean it up */
9741 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9744 io_ring_ctx_wait_and_kill(ctx);
9749 * Sets up an aio uring context, and returns the fd. Applications asks for a
9750 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9751 * params structure passed in.
9753 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9755 struct io_uring_params p;
9758 if (copy_from_user(&p, params, sizeof(p)))
9760 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9765 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9766 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9767 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9768 IORING_SETUP_R_DISABLED))
9771 return io_uring_create(entries, &p, params);
9774 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9775 struct io_uring_params __user *, params)
9777 return io_uring_setup(entries, params);
9780 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9782 struct io_uring_probe *p;
9786 size = struct_size(p, ops, nr_args);
9787 if (size == SIZE_MAX)
9789 p = kzalloc(size, GFP_KERNEL);
9794 if (copy_from_user(p, arg, size))
9797 if (memchr_inv(p, 0, size))
9800 p->last_op = IORING_OP_LAST - 1;
9801 if (nr_args > IORING_OP_LAST)
9802 nr_args = IORING_OP_LAST;
9804 for (i = 0; i < nr_args; i++) {
9806 if (!io_op_defs[i].not_supported)
9807 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9812 if (copy_to_user(arg, p, size))
9819 static int io_register_personality(struct io_ring_ctx *ctx)
9821 const struct cred *creds;
9825 creds = get_current_cred();
9827 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9828 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9836 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9837 unsigned int nr_args)
9839 struct io_uring_restriction *res;
9843 /* Restrictions allowed only if rings started disabled */
9844 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9847 /* We allow only a single restrictions registration */
9848 if (ctx->restrictions.registered)
9851 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9854 size = array_size(nr_args, sizeof(*res));
9855 if (size == SIZE_MAX)
9858 res = memdup_user(arg, size);
9860 return PTR_ERR(res);
9864 for (i = 0; i < nr_args; i++) {
9865 switch (res[i].opcode) {
9866 case IORING_RESTRICTION_REGISTER_OP:
9867 if (res[i].register_op >= IORING_REGISTER_LAST) {
9872 __set_bit(res[i].register_op,
9873 ctx->restrictions.register_op);
9875 case IORING_RESTRICTION_SQE_OP:
9876 if (res[i].sqe_op >= IORING_OP_LAST) {
9881 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9883 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9884 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9886 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9887 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9896 /* Reset all restrictions if an error happened */
9898 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9900 ctx->restrictions.registered = true;
9906 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9908 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9911 if (ctx->restrictions.registered)
9912 ctx->restricted = 1;
9914 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9915 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9916 wake_up(&ctx->sq_data->wait);
9920 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
9921 struct io_uring_rsrc_update2 *up,
9929 if (check_add_overflow(up->offset, nr_args, &tmp))
9931 err = io_rsrc_node_switch_start(ctx);
9936 case IORING_RSRC_FILE:
9937 return __io_sqe_files_update(ctx, up, nr_args);
9938 case IORING_RSRC_BUFFER:
9939 return __io_sqe_buffers_update(ctx, up, nr_args);
9944 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
9947 struct io_uring_rsrc_update2 up;
9951 memset(&up, 0, sizeof(up));
9952 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
9954 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
9957 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
9958 unsigned size, unsigned type)
9960 struct io_uring_rsrc_update2 up;
9962 if (size != sizeof(up))
9964 if (copy_from_user(&up, arg, sizeof(up)))
9966 if (!up.nr || up.resv)
9968 return __io_register_rsrc_update(ctx, type, &up, up.nr);
9971 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
9972 unsigned int size, unsigned int type)
9974 struct io_uring_rsrc_register rr;
9976 /* keep it extendible */
9977 if (size != sizeof(rr))
9980 memset(&rr, 0, sizeof(rr));
9981 if (copy_from_user(&rr, arg, size))
9983 if (!rr.nr || rr.resv || rr.resv2)
9987 case IORING_RSRC_FILE:
9988 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
9989 rr.nr, u64_to_user_ptr(rr.tags));
9990 case IORING_RSRC_BUFFER:
9991 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
9992 rr.nr, u64_to_user_ptr(rr.tags));
9997 static bool io_register_op_must_quiesce(int op)
10000 case IORING_REGISTER_BUFFERS:
10001 case IORING_UNREGISTER_BUFFERS:
10002 case IORING_REGISTER_FILES:
10003 case IORING_UNREGISTER_FILES:
10004 case IORING_REGISTER_FILES_UPDATE:
10005 case IORING_REGISTER_PROBE:
10006 case IORING_REGISTER_PERSONALITY:
10007 case IORING_UNREGISTER_PERSONALITY:
10008 case IORING_REGISTER_FILES2:
10009 case IORING_REGISTER_FILES_UPDATE2:
10010 case IORING_REGISTER_BUFFERS2:
10011 case IORING_REGISTER_BUFFERS_UPDATE:
10018 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10019 void __user *arg, unsigned nr_args)
10020 __releases(ctx->uring_lock)
10021 __acquires(ctx->uring_lock)
10026 * We're inside the ring mutex, if the ref is already dying, then
10027 * someone else killed the ctx or is already going through
10028 * io_uring_register().
10030 if (percpu_ref_is_dying(&ctx->refs))
10033 if (ctx->restricted) {
10034 if (opcode >= IORING_REGISTER_LAST)
10036 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10037 if (!test_bit(opcode, ctx->restrictions.register_op))
10041 if (io_register_op_must_quiesce(opcode)) {
10042 percpu_ref_kill(&ctx->refs);
10045 * Drop uring mutex before waiting for references to exit. If
10046 * another thread is currently inside io_uring_enter() it might
10047 * need to grab the uring_lock to make progress. If we hold it
10048 * here across the drain wait, then we can deadlock. It's safe
10049 * to drop the mutex here, since no new references will come in
10050 * after we've killed the percpu ref.
10052 mutex_unlock(&ctx->uring_lock);
10054 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10057 ret = io_run_task_work_sig();
10061 mutex_lock(&ctx->uring_lock);
10064 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10070 case IORING_REGISTER_BUFFERS:
10071 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10073 case IORING_UNREGISTER_BUFFERS:
10075 if (arg || nr_args)
10077 ret = io_sqe_buffers_unregister(ctx);
10079 case IORING_REGISTER_FILES:
10080 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10082 case IORING_UNREGISTER_FILES:
10084 if (arg || nr_args)
10086 ret = io_sqe_files_unregister(ctx);
10088 case IORING_REGISTER_FILES_UPDATE:
10089 ret = io_register_files_update(ctx, arg, nr_args);
10091 case IORING_REGISTER_EVENTFD:
10092 case IORING_REGISTER_EVENTFD_ASYNC:
10096 ret = io_eventfd_register(ctx, arg);
10099 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10100 ctx->eventfd_async = 1;
10102 ctx->eventfd_async = 0;
10104 case IORING_UNREGISTER_EVENTFD:
10106 if (arg || nr_args)
10108 ret = io_eventfd_unregister(ctx);
10110 case IORING_REGISTER_PROBE:
10112 if (!arg || nr_args > 256)
10114 ret = io_probe(ctx, arg, nr_args);
10116 case IORING_REGISTER_PERSONALITY:
10118 if (arg || nr_args)
10120 ret = io_register_personality(ctx);
10122 case IORING_UNREGISTER_PERSONALITY:
10126 ret = io_unregister_personality(ctx, nr_args);
10128 case IORING_REGISTER_ENABLE_RINGS:
10130 if (arg || nr_args)
10132 ret = io_register_enable_rings(ctx);
10134 case IORING_REGISTER_RESTRICTIONS:
10135 ret = io_register_restrictions(ctx, arg, nr_args);
10137 case IORING_REGISTER_FILES2:
10138 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10140 case IORING_REGISTER_FILES_UPDATE2:
10141 ret = io_register_rsrc_update(ctx, arg, nr_args,
10144 case IORING_REGISTER_BUFFERS2:
10145 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10147 case IORING_REGISTER_BUFFERS_UPDATE:
10148 ret = io_register_rsrc_update(ctx, arg, nr_args,
10149 IORING_RSRC_BUFFER);
10156 if (io_register_op_must_quiesce(opcode)) {
10157 /* bring the ctx back to life */
10158 percpu_ref_reinit(&ctx->refs);
10159 reinit_completion(&ctx->ref_comp);
10164 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10165 void __user *, arg, unsigned int, nr_args)
10167 struct io_ring_ctx *ctx;
10176 if (f.file->f_op != &io_uring_fops)
10179 ctx = f.file->private_data;
10181 io_run_task_work();
10183 mutex_lock(&ctx->uring_lock);
10184 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10185 mutex_unlock(&ctx->uring_lock);
10186 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10187 ctx->cq_ev_fd != NULL, ret);
10193 static int __init io_uring_init(void)
10195 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10196 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10197 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10200 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10201 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10202 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10203 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10204 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10205 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10206 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10207 BUILD_BUG_SQE_ELEM(8, __u64, off);
10208 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10209 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10210 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10211 BUILD_BUG_SQE_ELEM(24, __u32, len);
10212 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10213 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10214 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10215 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10216 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10217 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10218 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10219 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10220 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10221 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10222 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10223 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10224 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10225 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10226 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10227 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10228 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10229 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10230 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10232 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10233 sizeof(struct io_uring_rsrc_update));
10234 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10235 sizeof(struct io_uring_rsrc_update2));
10236 /* should fit into one byte */
10237 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10239 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10240 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10241 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10245 __initcall(io_uring_init);