1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/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)
93 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
96 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
98 #define IORING_FILE_TABLE_SHIFT 9
99 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
100 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
101 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
102 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
103 IORING_REGISTER_LAST + IORING_OP_LAST)
105 #define IO_RSRC_TAG_TABLE_SHIFT 9
106 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
107 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
109 #define IORING_MAX_REG_BUFFERS (1U << 14)
111 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
112 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
114 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
115 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
117 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
120 u32 head ____cacheline_aligned_in_smp;
121 u32 tail ____cacheline_aligned_in_smp;
125 * This data is shared with the application through the mmap at offsets
126 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
128 * The offsets to the member fields are published through struct
129 * io_sqring_offsets when calling io_uring_setup.
133 * Head and tail offsets into the ring; the offsets need to be
134 * masked to get valid indices.
136 * The kernel controls head of the sq ring and the tail of the cq ring,
137 * and the application controls tail of the sq ring and the head of the
140 struct io_uring sq, cq;
142 * Bitmasks to apply to head and tail offsets (constant, equals
145 u32 sq_ring_mask, cq_ring_mask;
146 /* Ring sizes (constant, power of 2) */
147 u32 sq_ring_entries, cq_ring_entries;
149 * Number of invalid entries dropped by the kernel due to
150 * invalid index stored in array
152 * Written by the kernel, shouldn't be modified by the
153 * application (i.e. get number of "new events" by comparing to
156 * After a new SQ head value was read by the application this
157 * counter includes all submissions that were dropped reaching
158 * the new SQ head (and possibly more).
164 * Written by the kernel, shouldn't be modified by the
167 * The application needs a full memory barrier before checking
168 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
174 * Written by the application, shouldn't be modified by the
179 * Number of completion events lost because the queue was full;
180 * this should be avoided by the application by making sure
181 * there are not more requests pending than there is space in
182 * the completion queue.
184 * Written by the kernel, shouldn't be modified by the
185 * application (i.e. get number of "new events" by comparing to
188 * As completion events come in out of order this counter is not
189 * ordered with any other data.
193 * Ring buffer of completion events.
195 * The kernel writes completion events fresh every time they are
196 * produced, so the application is allowed to modify pending
199 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
202 enum io_uring_cmd_flags {
203 IO_URING_F_NONBLOCK = 1,
204 IO_URING_F_COMPLETE_DEFER = 2,
207 struct io_mapped_ubuf {
210 unsigned int nr_bvecs;
211 unsigned long acct_pages;
212 struct bio_vec bvec[];
217 struct io_overflow_cqe {
218 struct io_uring_cqe cqe;
219 struct list_head list;
222 struct io_fixed_file {
223 /* file * with additional FFS_* flags */
224 unsigned long file_ptr;
228 struct list_head list;
233 struct io_mapped_ubuf *buf;
237 struct io_file_table {
238 /* two level table */
239 struct io_fixed_file **files;
242 struct io_rsrc_node {
243 struct percpu_ref refs;
244 struct list_head node;
245 struct list_head rsrc_list;
246 struct io_rsrc_data *rsrc_data;
247 struct llist_node llist;
251 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
253 struct io_rsrc_data {
254 struct io_ring_ctx *ctx;
260 struct completion done;
265 struct list_head list;
271 struct io_restriction {
272 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
273 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
274 u8 sqe_flags_allowed;
275 u8 sqe_flags_required;
280 IO_SQ_THREAD_SHOULD_STOP = 0,
281 IO_SQ_THREAD_SHOULD_PARK,
286 atomic_t park_pending;
289 /* ctx's that are using this sqd */
290 struct list_head ctx_list;
292 struct task_struct *thread;
293 struct wait_queue_head wait;
295 unsigned sq_thread_idle;
301 struct completion exited;
304 #define IO_IOPOLL_BATCH 8
305 #define IO_COMPL_BATCH 32
306 #define IO_REQ_CACHE_SIZE 32
307 #define IO_REQ_ALLOC_BATCH 8
309 struct io_comp_state {
310 struct io_kiocb *reqs[IO_COMPL_BATCH];
312 /* inline/task_work completion list, under ->uring_lock */
313 struct list_head free_list;
316 struct io_submit_link {
317 struct io_kiocb *head;
318 struct io_kiocb *last;
321 struct io_submit_state {
322 struct blk_plug plug;
323 struct io_submit_link link;
326 * io_kiocb alloc cache
328 void *reqs[IO_REQ_CACHE_SIZE];
329 unsigned int free_reqs;
334 * Batch completion logic
336 struct io_comp_state comp;
339 * File reference cache
343 unsigned int file_refs;
344 unsigned int ios_left;
348 /* const or read-mostly hot data */
350 struct percpu_ref refs;
352 struct io_rings *rings;
354 unsigned int compat: 1;
355 unsigned int drain_next: 1;
356 unsigned int eventfd_async: 1;
357 unsigned int restricted: 1;
358 unsigned int off_timeout_used: 1;
359 unsigned int drain_active: 1;
360 } ____cacheline_aligned_in_smp;
362 /* submission data */
364 struct mutex uring_lock;
367 * Ring buffer of indices into array of io_uring_sqe, which is
368 * mmapped by the application using the IORING_OFF_SQES offset.
370 * This indirection could e.g. be used to assign fixed
371 * io_uring_sqe entries to operations and only submit them to
372 * the queue when needed.
374 * The kernel modifies neither the indices array nor the entries
378 struct io_uring_sqe *sq_sqes;
379 unsigned cached_sq_head;
381 struct list_head defer_list;
384 * Fixed resources fast path, should be accessed only under
385 * uring_lock, and updated through io_uring_register(2)
387 struct io_rsrc_node *rsrc_node;
388 struct io_file_table file_table;
389 unsigned nr_user_files;
390 unsigned nr_user_bufs;
391 struct io_mapped_ubuf **user_bufs;
393 struct io_submit_state submit_state;
394 struct list_head timeout_list;
395 struct list_head cq_overflow_list;
396 struct xarray io_buffers;
397 struct xarray personalities;
399 unsigned sq_thread_idle;
400 } ____cacheline_aligned_in_smp;
402 /* IRQ completion list, under ->completion_lock */
403 struct list_head locked_free_list;
404 unsigned int locked_free_nr;
406 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
407 struct io_sq_data *sq_data; /* if using sq thread polling */
409 struct wait_queue_head sqo_sq_wait;
410 struct list_head sqd_list;
412 unsigned long check_cq_overflow;
415 unsigned cached_cq_tail;
417 struct eventfd_ctx *cq_ev_fd;
418 struct wait_queue_head poll_wait;
419 struct wait_queue_head cq_wait;
421 atomic_t cq_timeouts;
422 struct fasync_struct *cq_fasync;
423 unsigned cq_last_tm_flush;
424 } ____cacheline_aligned_in_smp;
427 spinlock_t completion_lock;
430 * ->iopoll_list is protected by the ctx->uring_lock for
431 * io_uring instances that don't use IORING_SETUP_SQPOLL.
432 * For SQPOLL, only the single threaded io_sq_thread() will
433 * manipulate the list, hence no extra locking is needed there.
435 struct list_head iopoll_list;
436 struct hlist_head *cancel_hash;
437 unsigned cancel_hash_bits;
438 bool poll_multi_queue;
439 } ____cacheline_aligned_in_smp;
441 struct io_restriction restrictions;
443 /* slow path rsrc auxilary data, used by update/register */
445 struct io_rsrc_node *rsrc_backup_node;
446 struct io_mapped_ubuf *dummy_ubuf;
447 struct io_rsrc_data *file_data;
448 struct io_rsrc_data *buf_data;
450 struct delayed_work rsrc_put_work;
451 struct llist_head rsrc_put_llist;
452 struct list_head rsrc_ref_list;
453 spinlock_t rsrc_ref_lock;
456 /* Keep this last, we don't need it for the fast path */
458 #if defined(CONFIG_UNIX)
459 struct socket *ring_sock;
461 /* hashed buffered write serialization */
462 struct io_wq_hash *hash_map;
464 /* Only used for accounting purposes */
465 struct user_struct *user;
466 struct mm_struct *mm_account;
468 /* ctx exit and cancelation */
469 struct llist_head fallback_llist;
470 struct delayed_work fallback_work;
471 struct work_struct exit_work;
472 struct list_head tctx_list;
473 struct completion ref_comp;
477 struct io_uring_task {
478 /* submission side */
481 struct wait_queue_head wait;
482 const struct io_ring_ctx *last;
484 struct percpu_counter inflight;
485 atomic_t inflight_tracked;
488 spinlock_t task_lock;
489 struct io_wq_work_list task_list;
490 unsigned long task_state;
491 struct callback_head task_work;
495 * First field must be the file pointer in all the
496 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
498 struct io_poll_iocb {
500 struct wait_queue_head *head;
504 struct wait_queue_entry wait;
507 struct io_poll_update {
513 bool update_user_data;
521 struct io_timeout_data {
522 struct io_kiocb *req;
523 struct hrtimer timer;
524 struct timespec64 ts;
525 enum hrtimer_mode mode;
530 struct sockaddr __user *addr;
531 int __user *addr_len;
533 unsigned long nofile;
553 struct list_head list;
554 /* head of the link, used by linked timeouts only */
555 struct io_kiocb *head;
558 struct io_timeout_rem {
563 struct timespec64 ts;
568 /* NOTE: kiocb has the file as the first member, so don't do it here */
576 struct sockaddr __user *addr;
583 struct compat_msghdr __user *umsg_compat;
584 struct user_msghdr __user *umsg;
590 struct io_buffer *kbuf;
596 struct filename *filename;
598 unsigned long nofile;
601 struct io_rsrc_update {
627 struct epoll_event event;
631 struct file *file_out;
632 struct file *file_in;
639 struct io_provide_buf {
653 const char __user *filename;
654 struct statx __user *buffer;
666 struct filename *oldpath;
667 struct filename *newpath;
675 struct filename *filename;
678 struct io_completion {
680 struct list_head list;
684 struct io_async_connect {
685 struct sockaddr_storage address;
688 struct io_async_msghdr {
689 struct iovec fast_iov[UIO_FASTIOV];
690 /* points to an allocated iov, if NULL we use fast_iov instead */
691 struct iovec *free_iov;
692 struct sockaddr __user *uaddr;
694 struct sockaddr_storage addr;
698 struct iovec fast_iov[UIO_FASTIOV];
699 const struct iovec *free_iovec;
700 struct iov_iter iter;
702 struct wait_page_queue wpq;
706 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
707 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
708 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
709 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
710 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
711 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
713 /* first byte is taken by user flags, shift it to not overlap */
718 REQ_F_LINK_TIMEOUT_BIT,
719 REQ_F_NEED_CLEANUP_BIT,
721 REQ_F_BUFFER_SELECTED_BIT,
722 REQ_F_LTIMEOUT_ACTIVE_BIT,
723 REQ_F_COMPLETE_INLINE_BIT,
725 REQ_F_DONT_REISSUE_BIT,
727 /* keep async read/write and isreg together and in order */
728 REQ_F_ASYNC_READ_BIT,
729 REQ_F_ASYNC_WRITE_BIT,
732 /* not a real bit, just to check we're not overflowing the space */
738 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
739 /* drain existing IO first */
740 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
742 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
743 /* doesn't sever on completion < 0 */
744 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
746 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
747 /* IOSQE_BUFFER_SELECT */
748 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
750 /* fail rest of links */
751 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
752 /* on inflight list, should be cancelled and waited on exit reliably */
753 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
754 /* read/write uses file position */
755 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
756 /* must not punt to workers */
757 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
758 /* has or had linked timeout */
759 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
761 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
762 /* already went through poll handler */
763 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
764 /* buffer already selected */
765 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
766 /* linked timeout is active, i.e. prepared by link's head */
767 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
768 /* completion is deferred through io_comp_state */
769 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
770 /* caller should reissue async */
771 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
772 /* don't attempt request reissue, see io_rw_reissue() */
773 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
774 /* supports async reads */
775 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
776 /* supports async writes */
777 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
779 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
780 /* has creds assigned */
781 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
785 struct io_poll_iocb poll;
786 struct io_poll_iocb *double_poll;
789 typedef void (*io_req_tw_func_t)(struct io_kiocb *req);
791 struct io_task_work {
793 struct io_wq_work_node node;
794 struct llist_node fallback_node;
796 io_req_tw_func_t func;
800 IORING_RSRC_FILE = 0,
801 IORING_RSRC_BUFFER = 1,
805 * NOTE! Each of the iocb union members has the file pointer
806 * as the first entry in their struct definition. So you can
807 * access the file pointer through any of the sub-structs,
808 * or directly as just 'ki_filp' in this struct.
814 struct io_poll_iocb poll;
815 struct io_poll_update poll_update;
816 struct io_accept accept;
818 struct io_cancel cancel;
819 struct io_timeout timeout;
820 struct io_timeout_rem timeout_rem;
821 struct io_connect connect;
822 struct io_sr_msg sr_msg;
824 struct io_close close;
825 struct io_rsrc_update rsrc_update;
826 struct io_fadvise fadvise;
827 struct io_madvise madvise;
828 struct io_epoll epoll;
829 struct io_splice splice;
830 struct io_provide_buf pbuf;
831 struct io_statx statx;
832 struct io_shutdown shutdown;
833 struct io_rename rename;
834 struct io_unlink unlink;
835 /* use only after cleaning per-op data, see io_clean_op() */
836 struct io_completion compl;
839 /* opcode allocated if it needs to store data for async defer */
842 /* polled IO has completed */
848 struct io_ring_ctx *ctx;
851 struct task_struct *task;
854 struct io_kiocb *link;
855 struct percpu_ref *fixed_rsrc_refs;
857 /* used with ctx->iopoll_list with reads/writes */
858 struct list_head inflight_entry;
859 struct io_task_work io_task_work;
860 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
861 struct hlist_node hash_node;
862 struct async_poll *apoll;
863 struct io_wq_work work;
864 const struct cred *creds;
866 /* store used ubuf, so we can prevent reloading */
867 struct io_mapped_ubuf *imu;
870 struct io_tctx_node {
871 struct list_head ctx_node;
872 struct task_struct *task;
873 struct io_ring_ctx *ctx;
876 struct io_defer_entry {
877 struct list_head list;
878 struct io_kiocb *req;
883 /* needs req->file assigned */
884 unsigned needs_file : 1;
885 /* hash wq insertion if file is a regular file */
886 unsigned hash_reg_file : 1;
887 /* unbound wq insertion if file is a non-regular file */
888 unsigned unbound_nonreg_file : 1;
889 /* opcode is not supported by this kernel */
890 unsigned not_supported : 1;
891 /* set if opcode supports polled "wait" */
893 unsigned pollout : 1;
894 /* op supports buffer selection */
895 unsigned buffer_select : 1;
896 /* do prep async if is going to be punted */
897 unsigned needs_async_setup : 1;
898 /* should block plug */
900 /* size of async data needed, if any */
901 unsigned short async_size;
904 static const struct io_op_def io_op_defs[] = {
905 [IORING_OP_NOP] = {},
906 [IORING_OP_READV] = {
908 .unbound_nonreg_file = 1,
911 .needs_async_setup = 1,
913 .async_size = sizeof(struct io_async_rw),
915 [IORING_OP_WRITEV] = {
918 .unbound_nonreg_file = 1,
920 .needs_async_setup = 1,
922 .async_size = sizeof(struct io_async_rw),
924 [IORING_OP_FSYNC] = {
927 [IORING_OP_READ_FIXED] = {
929 .unbound_nonreg_file = 1,
932 .async_size = sizeof(struct io_async_rw),
934 [IORING_OP_WRITE_FIXED] = {
937 .unbound_nonreg_file = 1,
940 .async_size = sizeof(struct io_async_rw),
942 [IORING_OP_POLL_ADD] = {
944 .unbound_nonreg_file = 1,
946 [IORING_OP_POLL_REMOVE] = {},
947 [IORING_OP_SYNC_FILE_RANGE] = {
950 [IORING_OP_SENDMSG] = {
952 .unbound_nonreg_file = 1,
954 .needs_async_setup = 1,
955 .async_size = sizeof(struct io_async_msghdr),
957 [IORING_OP_RECVMSG] = {
959 .unbound_nonreg_file = 1,
962 .needs_async_setup = 1,
963 .async_size = sizeof(struct io_async_msghdr),
965 [IORING_OP_TIMEOUT] = {
966 .async_size = sizeof(struct io_timeout_data),
968 [IORING_OP_TIMEOUT_REMOVE] = {
969 /* used by timeout updates' prep() */
971 [IORING_OP_ACCEPT] = {
973 .unbound_nonreg_file = 1,
976 [IORING_OP_ASYNC_CANCEL] = {},
977 [IORING_OP_LINK_TIMEOUT] = {
978 .async_size = sizeof(struct io_timeout_data),
980 [IORING_OP_CONNECT] = {
982 .unbound_nonreg_file = 1,
984 .needs_async_setup = 1,
985 .async_size = sizeof(struct io_async_connect),
987 [IORING_OP_FALLOCATE] = {
990 [IORING_OP_OPENAT] = {},
991 [IORING_OP_CLOSE] = {},
992 [IORING_OP_FILES_UPDATE] = {},
993 [IORING_OP_STATX] = {},
996 .unbound_nonreg_file = 1,
1000 .async_size = sizeof(struct io_async_rw),
1002 [IORING_OP_WRITE] = {
1004 .unbound_nonreg_file = 1,
1007 .async_size = sizeof(struct io_async_rw),
1009 [IORING_OP_FADVISE] = {
1012 [IORING_OP_MADVISE] = {},
1013 [IORING_OP_SEND] = {
1015 .unbound_nonreg_file = 1,
1018 [IORING_OP_RECV] = {
1020 .unbound_nonreg_file = 1,
1024 [IORING_OP_OPENAT2] = {
1026 [IORING_OP_EPOLL_CTL] = {
1027 .unbound_nonreg_file = 1,
1029 [IORING_OP_SPLICE] = {
1032 .unbound_nonreg_file = 1,
1034 [IORING_OP_PROVIDE_BUFFERS] = {},
1035 [IORING_OP_REMOVE_BUFFERS] = {},
1039 .unbound_nonreg_file = 1,
1041 [IORING_OP_SHUTDOWN] = {
1044 [IORING_OP_RENAMEAT] = {},
1045 [IORING_OP_UNLINKAT] = {},
1048 static bool io_disarm_next(struct io_kiocb *req);
1049 static void io_uring_del_tctx_node(unsigned long index);
1050 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1051 struct task_struct *task,
1053 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1054 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1056 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1057 long res, unsigned int cflags);
1058 static void io_put_req(struct io_kiocb *req);
1059 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1060 static void io_dismantle_req(struct io_kiocb *req);
1061 static void io_put_task(struct task_struct *task, int nr);
1062 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1063 static void io_queue_linked_timeout(struct io_kiocb *req);
1064 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1065 struct io_uring_rsrc_update2 *up,
1067 static void io_clean_op(struct io_kiocb *req);
1068 static struct file *io_file_get(struct io_submit_state *state,
1069 struct io_kiocb *req, int fd, bool fixed);
1070 static void __io_queue_sqe(struct io_kiocb *req);
1071 static void io_rsrc_put_work(struct work_struct *work);
1073 static void io_req_task_queue(struct io_kiocb *req);
1074 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1075 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1076 static int io_req_prep_async(struct io_kiocb *req);
1078 static void io_fallback_req_func(struct work_struct *unused);
1080 static struct kmem_cache *req_cachep;
1082 static const struct file_operations io_uring_fops;
1084 struct sock *io_uring_get_socket(struct file *file)
1086 #if defined(CONFIG_UNIX)
1087 if (file->f_op == &io_uring_fops) {
1088 struct io_ring_ctx *ctx = file->private_data;
1090 return ctx->ring_sock->sk;
1095 EXPORT_SYMBOL(io_uring_get_socket);
1097 #define io_for_each_link(pos, head) \
1098 for (pos = (head); pos; pos = pos->link)
1100 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1102 struct io_ring_ctx *ctx = req->ctx;
1104 if (!req->fixed_rsrc_refs) {
1105 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1106 percpu_ref_get(req->fixed_rsrc_refs);
1110 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1112 bool got = percpu_ref_tryget(ref);
1114 /* already at zero, wait for ->release() */
1116 wait_for_completion(compl);
1117 percpu_ref_resurrect(ref);
1119 percpu_ref_put(ref);
1122 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1125 struct io_kiocb *req;
1127 if (task && head->task != task)
1132 io_for_each_link(req, head) {
1133 if (req->flags & REQ_F_INFLIGHT)
1139 static inline void req_set_fail(struct io_kiocb *req)
1141 req->flags |= REQ_F_FAIL;
1144 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1146 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1148 complete(&ctx->ref_comp);
1151 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1153 return !req->timeout.off;
1156 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1158 struct io_ring_ctx *ctx;
1161 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1166 * Use 5 bits less than the max cq entries, that should give us around
1167 * 32 entries per hash list if totally full and uniformly spread.
1169 hash_bits = ilog2(p->cq_entries);
1173 ctx->cancel_hash_bits = hash_bits;
1174 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1176 if (!ctx->cancel_hash)
1178 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1180 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1181 if (!ctx->dummy_ubuf)
1183 /* set invalid range, so io_import_fixed() fails meeting it */
1184 ctx->dummy_ubuf->ubuf = -1UL;
1186 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1187 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1190 ctx->flags = p->flags;
1191 init_waitqueue_head(&ctx->sqo_sq_wait);
1192 INIT_LIST_HEAD(&ctx->sqd_list);
1193 init_waitqueue_head(&ctx->poll_wait);
1194 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1195 init_completion(&ctx->ref_comp);
1196 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1197 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1198 mutex_init(&ctx->uring_lock);
1199 init_waitqueue_head(&ctx->cq_wait);
1200 spin_lock_init(&ctx->completion_lock);
1201 INIT_LIST_HEAD(&ctx->iopoll_list);
1202 INIT_LIST_HEAD(&ctx->defer_list);
1203 INIT_LIST_HEAD(&ctx->timeout_list);
1204 spin_lock_init(&ctx->rsrc_ref_lock);
1205 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1206 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1207 init_llist_head(&ctx->rsrc_put_llist);
1208 INIT_LIST_HEAD(&ctx->tctx_list);
1209 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1210 INIT_LIST_HEAD(&ctx->locked_free_list);
1211 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1214 kfree(ctx->dummy_ubuf);
1215 kfree(ctx->cancel_hash);
1220 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1222 struct io_rings *r = ctx->rings;
1224 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1228 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1230 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1231 struct io_ring_ctx *ctx = req->ctx;
1233 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1239 static void io_req_track_inflight(struct io_kiocb *req)
1241 if (!(req->flags & REQ_F_INFLIGHT)) {
1242 req->flags |= REQ_F_INFLIGHT;
1243 atomic_inc(¤t->io_uring->inflight_tracked);
1247 static void io_prep_async_work(struct io_kiocb *req)
1249 const struct io_op_def *def = &io_op_defs[req->opcode];
1250 struct io_ring_ctx *ctx = req->ctx;
1252 if (!(req->flags & REQ_F_CREDS)) {
1253 req->flags |= REQ_F_CREDS;
1254 req->creds = get_current_cred();
1257 req->work.list.next = NULL;
1258 req->work.flags = 0;
1259 if (req->flags & REQ_F_FORCE_ASYNC)
1260 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1262 if (req->flags & REQ_F_ISREG) {
1263 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1264 io_wq_hash_work(&req->work, file_inode(req->file));
1265 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1266 if (def->unbound_nonreg_file)
1267 req->work.flags |= IO_WQ_WORK_UNBOUND;
1270 switch (req->opcode) {
1271 case IORING_OP_SPLICE:
1273 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1274 req->work.flags |= IO_WQ_WORK_UNBOUND;
1279 static void io_prep_async_link(struct io_kiocb *req)
1281 struct io_kiocb *cur;
1283 if (req->flags & REQ_F_LINK_TIMEOUT) {
1284 struct io_ring_ctx *ctx = req->ctx;
1286 spin_lock_irq(&ctx->completion_lock);
1287 io_for_each_link(cur, req)
1288 io_prep_async_work(cur);
1289 spin_unlock_irq(&ctx->completion_lock);
1291 io_for_each_link(cur, req)
1292 io_prep_async_work(cur);
1296 static void io_queue_async_work(struct io_kiocb *req)
1298 struct io_ring_ctx *ctx = req->ctx;
1299 struct io_kiocb *link = io_prep_linked_timeout(req);
1300 struct io_uring_task *tctx = req->task->io_uring;
1303 BUG_ON(!tctx->io_wq);
1305 /* init ->work of the whole link before punting */
1306 io_prep_async_link(req);
1309 * Not expected to happen, but if we do have a bug where this _can_
1310 * happen, catch it here and ensure the request is marked as
1311 * canceled. That will make io-wq go through the usual work cancel
1312 * procedure rather than attempt to run this request (or create a new
1315 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1316 req->work.flags |= IO_WQ_WORK_CANCEL;
1318 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1319 &req->work, req->flags);
1320 io_wq_enqueue(tctx->io_wq, &req->work);
1322 io_queue_linked_timeout(link);
1325 static void io_kill_timeout(struct io_kiocb *req, int status)
1326 __must_hold(&req->ctx->completion_lock)
1328 struct io_timeout_data *io = req->async_data;
1330 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1331 atomic_set(&req->ctx->cq_timeouts,
1332 atomic_read(&req->ctx->cq_timeouts) + 1);
1333 list_del_init(&req->timeout.list);
1334 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1335 io_put_req_deferred(req, 1);
1339 static void io_queue_deferred(struct io_ring_ctx *ctx)
1341 while (!list_empty(&ctx->defer_list)) {
1342 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1343 struct io_defer_entry, list);
1345 if (req_need_defer(de->req, de->seq))
1347 list_del_init(&de->list);
1348 io_req_task_queue(de->req);
1353 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1355 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1357 while (!list_empty(&ctx->timeout_list)) {
1358 u32 events_needed, events_got;
1359 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1360 struct io_kiocb, timeout.list);
1362 if (io_is_timeout_noseq(req))
1366 * Since seq can easily wrap around over time, subtract
1367 * the last seq at which timeouts were flushed before comparing.
1368 * Assuming not more than 2^31-1 events have happened since,
1369 * these subtractions won't have wrapped, so we can check if
1370 * target is in [last_seq, current_seq] by comparing the two.
1372 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1373 events_got = seq - ctx->cq_last_tm_flush;
1374 if (events_got < events_needed)
1377 list_del_init(&req->timeout.list);
1378 io_kill_timeout(req, 0);
1380 ctx->cq_last_tm_flush = seq;
1383 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1385 if (ctx->off_timeout_used)
1386 io_flush_timeouts(ctx);
1387 if (ctx->drain_active)
1388 io_queue_deferred(ctx);
1391 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1393 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1394 __io_commit_cqring_flush(ctx);
1395 /* order cqe stores with ring update */
1396 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1399 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1401 struct io_rings *r = ctx->rings;
1403 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1406 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1408 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1411 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1413 struct io_rings *rings = ctx->rings;
1414 unsigned tail, mask = ctx->cq_entries - 1;
1417 * writes to the cq entry need to come after reading head; the
1418 * control dependency is enough as we're using WRITE_ONCE to
1421 if (__io_cqring_events(ctx) == ctx->cq_entries)
1424 tail = ctx->cached_cq_tail++;
1425 return &rings->cqes[tail & mask];
1428 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1430 if (likely(!ctx->cq_ev_fd))
1432 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1434 return !ctx->eventfd_async || io_wq_current_is_worker();
1437 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1439 /* see waitqueue_active() comment */
1442 if (waitqueue_active(&ctx->cq_wait))
1443 wake_up(&ctx->cq_wait);
1444 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1445 wake_up(&ctx->sq_data->wait);
1446 if (io_should_trigger_evfd(ctx))
1447 eventfd_signal(ctx->cq_ev_fd, 1);
1448 if (waitqueue_active(&ctx->poll_wait)) {
1449 wake_up_interruptible(&ctx->poll_wait);
1450 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1454 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1456 /* see waitqueue_active() comment */
1459 if (ctx->flags & IORING_SETUP_SQPOLL) {
1460 if (waitqueue_active(&ctx->cq_wait))
1461 wake_up(&ctx->cq_wait);
1463 if (io_should_trigger_evfd(ctx))
1464 eventfd_signal(ctx->cq_ev_fd, 1);
1465 if (waitqueue_active(&ctx->poll_wait)) {
1466 wake_up_interruptible(&ctx->poll_wait);
1467 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1471 /* Returns true if there are no backlogged entries after the flush */
1472 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1474 unsigned long flags;
1475 bool all_flushed, posted;
1477 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1481 spin_lock_irqsave(&ctx->completion_lock, flags);
1482 while (!list_empty(&ctx->cq_overflow_list)) {
1483 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1484 struct io_overflow_cqe *ocqe;
1488 ocqe = list_first_entry(&ctx->cq_overflow_list,
1489 struct io_overflow_cqe, list);
1491 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1493 io_account_cq_overflow(ctx);
1496 list_del(&ocqe->list);
1500 all_flushed = list_empty(&ctx->cq_overflow_list);
1502 clear_bit(0, &ctx->check_cq_overflow);
1503 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1507 io_commit_cqring(ctx);
1508 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1510 io_cqring_ev_posted(ctx);
1514 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1518 if (test_bit(0, &ctx->check_cq_overflow)) {
1519 /* iopoll syncs against uring_lock, not completion_lock */
1520 if (ctx->flags & IORING_SETUP_IOPOLL)
1521 mutex_lock(&ctx->uring_lock);
1522 ret = __io_cqring_overflow_flush(ctx, force);
1523 if (ctx->flags & IORING_SETUP_IOPOLL)
1524 mutex_unlock(&ctx->uring_lock);
1531 * Shamelessly stolen from the mm implementation of page reference checking,
1532 * see commit f958d7b528b1 for details.
1534 #define req_ref_zero_or_close_to_overflow(req) \
1535 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1537 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1539 return atomic_inc_not_zero(&req->refs);
1542 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1544 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1545 return atomic_sub_and_test(refs, &req->refs);
1548 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1550 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1551 return atomic_dec_and_test(&req->refs);
1554 static inline void req_ref_put(struct io_kiocb *req)
1556 WARN_ON_ONCE(req_ref_put_and_test(req));
1559 static inline void req_ref_get(struct io_kiocb *req)
1561 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1562 atomic_inc(&req->refs);
1565 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1566 long res, unsigned int cflags)
1568 struct io_overflow_cqe *ocqe;
1570 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1573 * If we're in ring overflow flush mode, or in task cancel mode,
1574 * or cannot allocate an overflow entry, then we need to drop it
1577 io_account_cq_overflow(ctx);
1580 if (list_empty(&ctx->cq_overflow_list)) {
1581 set_bit(0, &ctx->check_cq_overflow);
1582 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1584 ocqe->cqe.user_data = user_data;
1585 ocqe->cqe.res = res;
1586 ocqe->cqe.flags = cflags;
1587 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1591 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1592 long res, unsigned int cflags)
1594 struct io_uring_cqe *cqe;
1596 trace_io_uring_complete(ctx, user_data, res, cflags);
1599 * If we can't get a cq entry, userspace overflowed the
1600 * submission (by quite a lot). Increment the overflow count in
1603 cqe = io_get_cqe(ctx);
1605 WRITE_ONCE(cqe->user_data, user_data);
1606 WRITE_ONCE(cqe->res, res);
1607 WRITE_ONCE(cqe->flags, cflags);
1610 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1613 /* not as hot to bloat with inlining */
1614 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1615 long res, unsigned int cflags)
1617 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1620 static void io_req_complete_post(struct io_kiocb *req, long res,
1621 unsigned int cflags)
1623 struct io_ring_ctx *ctx = req->ctx;
1624 unsigned long flags;
1626 spin_lock_irqsave(&ctx->completion_lock, flags);
1627 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1629 * If we're the last reference to this request, add to our locked
1632 if (req_ref_put_and_test(req)) {
1633 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1634 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL))
1635 io_disarm_next(req);
1637 io_req_task_queue(req->link);
1641 io_dismantle_req(req);
1642 io_put_task(req->task, 1);
1643 list_add(&req->compl.list, &ctx->locked_free_list);
1644 ctx->locked_free_nr++;
1646 if (!percpu_ref_tryget(&ctx->refs))
1649 io_commit_cqring(ctx);
1650 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1653 io_cqring_ev_posted(ctx);
1654 percpu_ref_put(&ctx->refs);
1658 static inline bool io_req_needs_clean(struct io_kiocb *req)
1660 return req->flags & IO_REQ_CLEAN_FLAGS;
1663 static void io_req_complete_state(struct io_kiocb *req, long res,
1664 unsigned int cflags)
1666 if (io_req_needs_clean(req))
1669 req->compl.cflags = cflags;
1670 req->flags |= REQ_F_COMPLETE_INLINE;
1673 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1674 long res, unsigned cflags)
1676 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1677 io_req_complete_state(req, res, cflags);
1679 io_req_complete_post(req, res, cflags);
1682 static inline void io_req_complete(struct io_kiocb *req, long res)
1684 __io_req_complete(req, 0, res, 0);
1687 static void io_req_complete_failed(struct io_kiocb *req, long res)
1691 io_req_complete_post(req, res, 0);
1694 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1695 struct io_comp_state *cs)
1697 spin_lock_irq(&ctx->completion_lock);
1698 list_splice_init(&ctx->locked_free_list, &cs->free_list);
1699 ctx->locked_free_nr = 0;
1700 spin_unlock_irq(&ctx->completion_lock);
1703 /* Returns true IFF there are requests in the cache */
1704 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1706 struct io_submit_state *state = &ctx->submit_state;
1707 struct io_comp_state *cs = &state->comp;
1711 * If we have more than a batch's worth of requests in our IRQ side
1712 * locked cache, grab the lock and move them over to our submission
1715 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1716 io_flush_cached_locked_reqs(ctx, cs);
1718 nr = state->free_reqs;
1719 while (!list_empty(&cs->free_list)) {
1720 struct io_kiocb *req = list_first_entry(&cs->free_list,
1721 struct io_kiocb, compl.list);
1723 list_del(&req->compl.list);
1724 state->reqs[nr++] = req;
1725 if (nr == ARRAY_SIZE(state->reqs))
1729 state->free_reqs = nr;
1733 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1735 struct io_submit_state *state = &ctx->submit_state;
1737 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1739 if (!state->free_reqs) {
1740 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1743 if (io_flush_cached_reqs(ctx))
1746 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1750 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1751 * retry single alloc to be on the safe side.
1753 if (unlikely(ret <= 0)) {
1754 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1755 if (!state->reqs[0])
1761 * Don't initialise the fields below on every allocation, but
1762 * do that in advance and keep valid on free.
1764 for (i = 0; i < ret; i++) {
1765 struct io_kiocb *req = state->reqs[i];
1769 req->async_data = NULL;
1770 /* not necessary, but safer to zero */
1773 state->free_reqs = ret;
1777 return state->reqs[state->free_reqs];
1780 static inline void io_put_file(struct file *file)
1786 static void io_dismantle_req(struct io_kiocb *req)
1788 unsigned int flags = req->flags;
1790 if (io_req_needs_clean(req))
1792 if (!(flags & REQ_F_FIXED_FILE))
1793 io_put_file(req->file);
1794 if (req->fixed_rsrc_refs)
1795 percpu_ref_put(req->fixed_rsrc_refs);
1796 if (req->async_data) {
1797 kfree(req->async_data);
1798 req->async_data = NULL;
1802 /* must to be called somewhat shortly after putting a request */
1803 static inline void io_put_task(struct task_struct *task, int nr)
1805 struct io_uring_task *tctx = task->io_uring;
1807 percpu_counter_sub(&tctx->inflight, nr);
1808 if (unlikely(atomic_read(&tctx->in_idle)))
1809 wake_up(&tctx->wait);
1810 put_task_struct_many(task, nr);
1813 static void __io_free_req(struct io_kiocb *req)
1815 struct io_ring_ctx *ctx = req->ctx;
1817 io_dismantle_req(req);
1818 io_put_task(req->task, 1);
1820 kmem_cache_free(req_cachep, req);
1821 percpu_ref_put(&ctx->refs);
1824 static inline void io_remove_next_linked(struct io_kiocb *req)
1826 struct io_kiocb *nxt = req->link;
1828 req->link = nxt->link;
1832 static bool io_kill_linked_timeout(struct io_kiocb *req)
1833 __must_hold(&req->ctx->completion_lock)
1835 struct io_kiocb *link = req->link;
1838 * Can happen if a linked timeout fired and link had been like
1839 * req -> link t-out -> link t-out [-> ...]
1841 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1842 struct io_timeout_data *io = link->async_data;
1844 io_remove_next_linked(req);
1845 link->timeout.head = NULL;
1846 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1847 io_cqring_fill_event(link->ctx, link->user_data,
1849 io_put_req_deferred(link, 1);
1856 static void io_fail_links(struct io_kiocb *req)
1857 __must_hold(&req->ctx->completion_lock)
1859 struct io_kiocb *nxt, *link = req->link;
1866 trace_io_uring_fail_link(req, link);
1867 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1868 io_put_req_deferred(link, 2);
1873 static bool io_disarm_next(struct io_kiocb *req)
1874 __must_hold(&req->ctx->completion_lock)
1876 bool posted = false;
1878 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1879 posted = io_kill_linked_timeout(req);
1880 if (unlikely((req->flags & REQ_F_FAIL) &&
1881 !(req->flags & REQ_F_HARDLINK))) {
1882 posted |= (req->link != NULL);
1888 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1890 struct io_kiocb *nxt;
1893 * If LINK is set, we have dependent requests in this chain. If we
1894 * didn't fail this request, queue the first one up, moving any other
1895 * dependencies to the next request. In case of failure, fail the rest
1898 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL)) {
1899 struct io_ring_ctx *ctx = req->ctx;
1900 unsigned long flags;
1903 spin_lock_irqsave(&ctx->completion_lock, flags);
1904 posted = io_disarm_next(req);
1906 io_commit_cqring(req->ctx);
1907 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1909 io_cqring_ev_posted(ctx);
1916 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1918 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1920 return __io_req_find_next(req);
1923 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1927 if (ctx->submit_state.comp.nr) {
1928 mutex_lock(&ctx->uring_lock);
1929 io_submit_flush_completions(ctx);
1930 mutex_unlock(&ctx->uring_lock);
1932 percpu_ref_put(&ctx->refs);
1935 static void tctx_task_work(struct callback_head *cb)
1937 struct io_ring_ctx *ctx = NULL;
1938 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1942 struct io_wq_work_node *node;
1944 spin_lock_irq(&tctx->task_lock);
1945 node = tctx->task_list.first;
1946 INIT_WQ_LIST(&tctx->task_list);
1947 spin_unlock_irq(&tctx->task_lock);
1950 struct io_wq_work_node *next = node->next;
1951 struct io_kiocb *req = container_of(node, struct io_kiocb,
1954 if (req->ctx != ctx) {
1955 ctx_flush_and_put(ctx);
1957 percpu_ref_get(&ctx->refs);
1959 req->io_task_work.func(req);
1962 if (wq_list_empty(&tctx->task_list)) {
1963 spin_lock_irq(&tctx->task_lock);
1964 clear_bit(0, &tctx->task_state);
1965 if (wq_list_empty(&tctx->task_list)) {
1966 spin_unlock_irq(&tctx->task_lock);
1969 spin_unlock_irq(&tctx->task_lock);
1970 /* another tctx_task_work() is enqueued, yield */
1971 if (test_and_set_bit(0, &tctx->task_state))
1977 ctx_flush_and_put(ctx);
1980 static void io_req_task_work_add(struct io_kiocb *req)
1982 struct task_struct *tsk = req->task;
1983 struct io_uring_task *tctx = tsk->io_uring;
1984 enum task_work_notify_mode notify;
1985 struct io_wq_work_node *node;
1986 unsigned long flags;
1988 WARN_ON_ONCE(!tctx);
1990 spin_lock_irqsave(&tctx->task_lock, flags);
1991 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1992 spin_unlock_irqrestore(&tctx->task_lock, flags);
1994 /* task_work already pending, we're done */
1995 if (test_bit(0, &tctx->task_state) ||
1996 test_and_set_bit(0, &tctx->task_state))
1998 if (unlikely(tsk->flags & PF_EXITING))
2002 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2003 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2004 * processing task_work. There's no reliable way to tell if TWA_RESUME
2007 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2008 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2009 wake_up_process(tsk);
2013 clear_bit(0, &tctx->task_state);
2014 spin_lock_irqsave(&tctx->task_lock, flags);
2015 node = tctx->task_list.first;
2016 INIT_WQ_LIST(&tctx->task_list);
2017 spin_unlock_irqrestore(&tctx->task_lock, flags);
2020 req = container_of(node, struct io_kiocb, io_task_work.node);
2022 if (llist_add(&req->io_task_work.fallback_node,
2023 &req->ctx->fallback_llist))
2024 schedule_delayed_work(&req->ctx->fallback_work, 1);
2028 static void io_req_task_cancel(struct io_kiocb *req)
2030 struct io_ring_ctx *ctx = req->ctx;
2032 /* ctx is guaranteed to stay alive while we hold uring_lock */
2033 mutex_lock(&ctx->uring_lock);
2034 io_req_complete_failed(req, req->result);
2035 mutex_unlock(&ctx->uring_lock);
2038 static void io_req_task_submit(struct io_kiocb *req)
2040 struct io_ring_ctx *ctx = req->ctx;
2042 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2043 mutex_lock(&ctx->uring_lock);
2044 if (!(req->task->flags & PF_EXITING) && !req->task->in_execve)
2045 __io_queue_sqe(req);
2047 io_req_complete_failed(req, -EFAULT);
2048 mutex_unlock(&ctx->uring_lock);
2051 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2054 req->io_task_work.func = io_req_task_cancel;
2055 io_req_task_work_add(req);
2058 static void io_req_task_queue(struct io_kiocb *req)
2060 req->io_task_work.func = io_req_task_submit;
2061 io_req_task_work_add(req);
2064 static void io_req_task_queue_reissue(struct io_kiocb *req)
2066 req->io_task_work.func = io_queue_async_work;
2067 io_req_task_work_add(req);
2070 static inline void io_queue_next(struct io_kiocb *req)
2072 struct io_kiocb *nxt = io_req_find_next(req);
2075 io_req_task_queue(nxt);
2078 static void io_free_req(struct io_kiocb *req)
2085 struct task_struct *task;
2090 static inline void io_init_req_batch(struct req_batch *rb)
2097 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2098 struct req_batch *rb)
2101 io_put_task(rb->task, rb->task_refs);
2103 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2106 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2107 struct io_submit_state *state)
2110 io_dismantle_req(req);
2112 if (req->task != rb->task) {
2114 io_put_task(rb->task, rb->task_refs);
2115 rb->task = req->task;
2121 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2122 state->reqs[state->free_reqs++] = req;
2124 list_add(&req->compl.list, &state->comp.free_list);
2127 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2129 struct io_comp_state *cs = &ctx->submit_state.comp;
2131 struct req_batch rb;
2133 spin_lock_irq(&ctx->completion_lock);
2134 for (i = 0; i < nr; i++) {
2135 struct io_kiocb *req = cs->reqs[i];
2137 __io_cqring_fill_event(ctx, req->user_data, req->result,
2140 io_commit_cqring(ctx);
2141 spin_unlock_irq(&ctx->completion_lock);
2142 io_cqring_ev_posted(ctx);
2144 io_init_req_batch(&rb);
2145 for (i = 0; i < nr; i++) {
2146 struct io_kiocb *req = cs->reqs[i];
2148 /* submission and completion refs */
2149 if (req_ref_sub_and_test(req, 2))
2150 io_req_free_batch(&rb, req, &ctx->submit_state);
2153 io_req_free_batch_finish(ctx, &rb);
2158 * Drop reference to request, return next in chain (if there is one) if this
2159 * was the last reference to this request.
2161 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2163 struct io_kiocb *nxt = NULL;
2165 if (req_ref_put_and_test(req)) {
2166 nxt = io_req_find_next(req);
2172 static inline void io_put_req(struct io_kiocb *req)
2174 if (req_ref_put_and_test(req))
2178 static void io_free_req_deferred(struct io_kiocb *req)
2180 req->io_task_work.func = io_free_req;
2181 io_req_task_work_add(req);
2184 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2186 if (req_ref_sub_and_test(req, refs))
2187 io_free_req_deferred(req);
2190 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2192 /* See comment at the top of this file */
2194 return __io_cqring_events(ctx);
2197 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2199 struct io_rings *rings = ctx->rings;
2201 /* make sure SQ entry isn't read before tail */
2202 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2205 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2207 unsigned int cflags;
2209 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2210 cflags |= IORING_CQE_F_BUFFER;
2211 req->flags &= ~REQ_F_BUFFER_SELECTED;
2216 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2218 struct io_buffer *kbuf;
2220 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2221 return io_put_kbuf(req, kbuf);
2224 static inline bool io_run_task_work(void)
2226 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2227 __set_current_state(TASK_RUNNING);
2228 tracehook_notify_signal();
2236 * Find and free completed poll iocbs
2238 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2239 struct list_head *done, bool resubmit)
2241 struct req_batch rb;
2242 struct io_kiocb *req;
2244 /* order with ->result store in io_complete_rw_iopoll() */
2247 io_init_req_batch(&rb);
2248 while (!list_empty(done)) {
2251 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2252 list_del(&req->inflight_entry);
2254 if (READ_ONCE(req->result) == -EAGAIN && resubmit &&
2255 !(req->flags & REQ_F_DONT_REISSUE)) {
2256 req->iopoll_completed = 0;
2258 io_req_task_queue_reissue(req);
2262 if (req->flags & REQ_F_BUFFER_SELECTED)
2263 cflags = io_put_rw_kbuf(req);
2265 __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2268 if (req_ref_put_and_test(req))
2269 io_req_free_batch(&rb, req, &ctx->submit_state);
2272 io_commit_cqring(ctx);
2273 io_cqring_ev_posted_iopoll(ctx);
2274 io_req_free_batch_finish(ctx, &rb);
2277 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2278 long min, bool resubmit)
2280 struct io_kiocb *req, *tmp;
2286 * Only spin for completions if we don't have multiple devices hanging
2287 * off our complete list, and we're under the requested amount.
2289 spin = !ctx->poll_multi_queue && *nr_events < min;
2292 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2293 struct kiocb *kiocb = &req->rw.kiocb;
2296 * Move completed and retryable entries to our local lists.
2297 * If we find a request that requires polling, break out
2298 * and complete those lists first, if we have entries there.
2300 if (READ_ONCE(req->iopoll_completed)) {
2301 list_move_tail(&req->inflight_entry, &done);
2304 if (!list_empty(&done))
2307 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2311 /* iopoll may have completed current req */
2312 if (READ_ONCE(req->iopoll_completed))
2313 list_move_tail(&req->inflight_entry, &done);
2320 if (!list_empty(&done))
2321 io_iopoll_complete(ctx, nr_events, &done, resubmit);
2327 * We can't just wait for polled events to come to us, we have to actively
2328 * find and complete them.
2330 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2332 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2335 mutex_lock(&ctx->uring_lock);
2336 while (!list_empty(&ctx->iopoll_list)) {
2337 unsigned int nr_events = 0;
2339 io_do_iopoll(ctx, &nr_events, 0, false);
2341 /* let it sleep and repeat later if can't complete a request */
2345 * Ensure we allow local-to-the-cpu processing to take place,
2346 * in this case we need to ensure that we reap all events.
2347 * Also let task_work, etc. to progress by releasing the mutex
2349 if (need_resched()) {
2350 mutex_unlock(&ctx->uring_lock);
2352 mutex_lock(&ctx->uring_lock);
2355 mutex_unlock(&ctx->uring_lock);
2358 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2360 unsigned int nr_events = 0;
2364 * We disallow the app entering submit/complete with polling, but we
2365 * still need to lock the ring to prevent racing with polled issue
2366 * that got punted to a workqueue.
2368 mutex_lock(&ctx->uring_lock);
2370 * Don't enter poll loop if we already have events pending.
2371 * If we do, we can potentially be spinning for commands that
2372 * already triggered a CQE (eg in error).
2374 if (test_bit(0, &ctx->check_cq_overflow))
2375 __io_cqring_overflow_flush(ctx, false);
2376 if (io_cqring_events(ctx))
2380 * If a submit got punted to a workqueue, we can have the
2381 * application entering polling for a command before it gets
2382 * issued. That app will hold the uring_lock for the duration
2383 * of the poll right here, so we need to take a breather every
2384 * now and then to ensure that the issue has a chance to add
2385 * the poll to the issued list. Otherwise we can spin here
2386 * forever, while the workqueue is stuck trying to acquire the
2389 if (list_empty(&ctx->iopoll_list)) {
2390 u32 tail = ctx->cached_cq_tail;
2392 mutex_unlock(&ctx->uring_lock);
2394 mutex_lock(&ctx->uring_lock);
2396 /* some requests don't go through iopoll_list */
2397 if (tail != ctx->cached_cq_tail ||
2398 list_empty(&ctx->iopoll_list))
2401 ret = io_do_iopoll(ctx, &nr_events, min, true);
2402 } while (!ret && nr_events < min && !need_resched());
2404 mutex_unlock(&ctx->uring_lock);
2408 static void kiocb_end_write(struct io_kiocb *req)
2411 * Tell lockdep we inherited freeze protection from submission
2414 if (req->flags & REQ_F_ISREG) {
2415 struct super_block *sb = file_inode(req->file)->i_sb;
2417 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2423 static bool io_resubmit_prep(struct io_kiocb *req)
2425 struct io_async_rw *rw = req->async_data;
2428 return !io_req_prep_async(req);
2429 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2430 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2434 static bool io_rw_should_reissue(struct io_kiocb *req)
2436 umode_t mode = file_inode(req->file)->i_mode;
2437 struct io_ring_ctx *ctx = req->ctx;
2439 if (!S_ISBLK(mode) && !S_ISREG(mode))
2441 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2442 !(ctx->flags & IORING_SETUP_IOPOLL)))
2445 * If ref is dying, we might be running poll reap from the exit work.
2446 * Don't attempt to reissue from that path, just let it fail with
2449 if (percpu_ref_is_dying(&ctx->refs))
2452 * Play it safe and assume not safe to re-import and reissue if we're
2453 * not in the original thread group (or in task context).
2455 if (!same_thread_group(req->task, current) || !in_task())
2460 static bool io_resubmit_prep(struct io_kiocb *req)
2464 static bool io_rw_should_reissue(struct io_kiocb *req)
2470 static void io_fallback_req_func(struct work_struct *work)
2472 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
2473 fallback_work.work);
2474 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
2475 struct io_kiocb *req, *tmp;
2477 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
2478 req->io_task_work.func(req);
2481 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2482 unsigned int issue_flags)
2486 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2487 kiocb_end_write(req);
2488 if (res != req->result) {
2489 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2490 io_rw_should_reissue(req)) {
2491 req->flags |= REQ_F_REISSUE;
2496 if (req->flags & REQ_F_BUFFER_SELECTED)
2497 cflags = io_put_rw_kbuf(req);
2498 __io_req_complete(req, issue_flags, res, cflags);
2501 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2503 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2505 __io_complete_rw(req, res, res2, 0);
2508 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2510 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2512 if (kiocb->ki_flags & IOCB_WRITE)
2513 kiocb_end_write(req);
2514 if (unlikely(res != req->result)) {
2515 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2516 io_resubmit_prep(req))) {
2518 req->flags |= REQ_F_DONT_REISSUE;
2522 WRITE_ONCE(req->result, res);
2523 /* order with io_iopoll_complete() checking ->result */
2525 WRITE_ONCE(req->iopoll_completed, 1);
2529 * After the iocb has been issued, it's safe to be found on the poll list.
2530 * Adding the kiocb to the list AFTER submission ensures that we don't
2531 * find it from a io_do_iopoll() thread before the issuer is done
2532 * accessing the kiocb cookie.
2534 static void io_iopoll_req_issued(struct io_kiocb *req)
2536 struct io_ring_ctx *ctx = req->ctx;
2537 const bool in_async = io_wq_current_is_worker();
2539 /* workqueue context doesn't hold uring_lock, grab it now */
2540 if (unlikely(in_async))
2541 mutex_lock(&ctx->uring_lock);
2544 * Track whether we have multiple files in our lists. This will impact
2545 * how we do polling eventually, not spinning if we're on potentially
2546 * different devices.
2548 if (list_empty(&ctx->iopoll_list)) {
2549 ctx->poll_multi_queue = false;
2550 } else if (!ctx->poll_multi_queue) {
2551 struct io_kiocb *list_req;
2552 unsigned int queue_num0, queue_num1;
2554 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2557 if (list_req->file != req->file) {
2558 ctx->poll_multi_queue = true;
2560 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2561 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2562 if (queue_num0 != queue_num1)
2563 ctx->poll_multi_queue = true;
2568 * For fast devices, IO may have already completed. If it has, add
2569 * it to the front so we find it first.
2571 if (READ_ONCE(req->iopoll_completed))
2572 list_add(&req->inflight_entry, &ctx->iopoll_list);
2574 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2576 if (unlikely(in_async)) {
2578 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2579 * in sq thread task context or in io worker task context. If
2580 * current task context is sq thread, we don't need to check
2581 * whether should wake up sq thread.
2583 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2584 wq_has_sleeper(&ctx->sq_data->wait))
2585 wake_up(&ctx->sq_data->wait);
2587 mutex_unlock(&ctx->uring_lock);
2591 static inline void io_state_file_put(struct io_submit_state *state)
2593 if (state->file_refs) {
2594 fput_many(state->file, state->file_refs);
2595 state->file_refs = 0;
2600 * Get as many references to a file as we have IOs left in this submission,
2601 * assuming most submissions are for one file, or at least that each file
2602 * has more than one submission.
2604 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2609 if (state->file_refs) {
2610 if (state->fd == fd) {
2614 io_state_file_put(state);
2616 state->file = fget_many(fd, state->ios_left);
2617 if (unlikely(!state->file))
2621 state->file_refs = state->ios_left - 1;
2625 static bool io_bdev_nowait(struct block_device *bdev)
2627 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2631 * If we tracked the file through the SCM inflight mechanism, we could support
2632 * any file. For now, just ensure that anything potentially problematic is done
2635 static bool __io_file_supports_async(struct file *file, int rw)
2637 umode_t mode = file_inode(file)->i_mode;
2639 if (S_ISBLK(mode)) {
2640 if (IS_ENABLED(CONFIG_BLOCK) &&
2641 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2647 if (S_ISREG(mode)) {
2648 if (IS_ENABLED(CONFIG_BLOCK) &&
2649 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2650 file->f_op != &io_uring_fops)
2655 /* any ->read/write should understand O_NONBLOCK */
2656 if (file->f_flags & O_NONBLOCK)
2659 if (!(file->f_mode & FMODE_NOWAIT))
2663 return file->f_op->read_iter != NULL;
2665 return file->f_op->write_iter != NULL;
2668 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2670 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2672 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2675 return __io_file_supports_async(req->file, rw);
2678 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2680 struct io_ring_ctx *ctx = req->ctx;
2681 struct kiocb *kiocb = &req->rw.kiocb;
2682 struct file *file = req->file;
2686 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2687 req->flags |= REQ_F_ISREG;
2689 kiocb->ki_pos = READ_ONCE(sqe->off);
2690 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2691 req->flags |= REQ_F_CUR_POS;
2692 kiocb->ki_pos = file->f_pos;
2694 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2695 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2696 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2700 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2701 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2702 req->flags |= REQ_F_NOWAIT;
2704 ioprio = READ_ONCE(sqe->ioprio);
2706 ret = ioprio_check_cap(ioprio);
2710 kiocb->ki_ioprio = ioprio;
2712 kiocb->ki_ioprio = get_current_ioprio();
2714 if (ctx->flags & IORING_SETUP_IOPOLL) {
2715 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2716 !kiocb->ki_filp->f_op->iopoll)
2719 kiocb->ki_flags |= IOCB_HIPRI;
2720 kiocb->ki_complete = io_complete_rw_iopoll;
2721 req->iopoll_completed = 0;
2723 if (kiocb->ki_flags & IOCB_HIPRI)
2725 kiocb->ki_complete = io_complete_rw;
2728 if (req->opcode == IORING_OP_READ_FIXED ||
2729 req->opcode == IORING_OP_WRITE_FIXED) {
2731 io_req_set_rsrc_node(req);
2734 req->rw.addr = READ_ONCE(sqe->addr);
2735 req->rw.len = READ_ONCE(sqe->len);
2736 req->buf_index = READ_ONCE(sqe->buf_index);
2740 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2746 case -ERESTARTNOINTR:
2747 case -ERESTARTNOHAND:
2748 case -ERESTART_RESTARTBLOCK:
2750 * We can't just restart the syscall, since previously
2751 * submitted sqes may already be in progress. Just fail this
2757 kiocb->ki_complete(kiocb, ret, 0);
2761 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2762 unsigned int issue_flags)
2764 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2765 struct io_async_rw *io = req->async_data;
2766 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2768 /* add previously done IO, if any */
2769 if (io && io->bytes_done > 0) {
2771 ret = io->bytes_done;
2773 ret += io->bytes_done;
2776 if (req->flags & REQ_F_CUR_POS)
2777 req->file->f_pos = kiocb->ki_pos;
2778 if (ret >= 0 && check_reissue)
2779 __io_complete_rw(req, ret, 0, issue_flags);
2781 io_rw_done(kiocb, ret);
2783 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2784 req->flags &= ~REQ_F_REISSUE;
2785 if (io_resubmit_prep(req)) {
2787 io_req_task_queue_reissue(req);
2792 if (req->flags & REQ_F_BUFFER_SELECTED)
2793 cflags = io_put_rw_kbuf(req);
2794 __io_req_complete(req, issue_flags, ret, cflags);
2799 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2800 struct io_mapped_ubuf *imu)
2802 size_t len = req->rw.len;
2803 u64 buf_end, buf_addr = req->rw.addr;
2806 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2808 /* not inside the mapped region */
2809 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2813 * May not be a start of buffer, set size appropriately
2814 * and advance us to the beginning.
2816 offset = buf_addr - imu->ubuf;
2817 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2821 * Don't use iov_iter_advance() here, as it's really slow for
2822 * using the latter parts of a big fixed buffer - it iterates
2823 * over each segment manually. We can cheat a bit here, because
2826 * 1) it's a BVEC iter, we set it up
2827 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2828 * first and last bvec
2830 * So just find our index, and adjust the iterator afterwards.
2831 * If the offset is within the first bvec (or the whole first
2832 * bvec, just use iov_iter_advance(). This makes it easier
2833 * since we can just skip the first segment, which may not
2834 * be PAGE_SIZE aligned.
2836 const struct bio_vec *bvec = imu->bvec;
2838 if (offset <= bvec->bv_len) {
2839 iov_iter_advance(iter, offset);
2841 unsigned long seg_skip;
2843 /* skip first vec */
2844 offset -= bvec->bv_len;
2845 seg_skip = 1 + (offset >> PAGE_SHIFT);
2847 iter->bvec = bvec + seg_skip;
2848 iter->nr_segs -= seg_skip;
2849 iter->count -= bvec->bv_len + offset;
2850 iter->iov_offset = offset & ~PAGE_MASK;
2857 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2859 struct io_ring_ctx *ctx = req->ctx;
2860 struct io_mapped_ubuf *imu = req->imu;
2861 u16 index, buf_index = req->buf_index;
2864 if (unlikely(buf_index >= ctx->nr_user_bufs))
2866 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2867 imu = READ_ONCE(ctx->user_bufs[index]);
2870 return __io_import_fixed(req, rw, iter, imu);
2873 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2876 mutex_unlock(&ctx->uring_lock);
2879 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2882 * "Normal" inline submissions always hold the uring_lock, since we
2883 * grab it from the system call. Same is true for the SQPOLL offload.
2884 * The only exception is when we've detached the request and issue it
2885 * from an async worker thread, grab the lock for that case.
2888 mutex_lock(&ctx->uring_lock);
2891 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2892 int bgid, struct io_buffer *kbuf,
2895 struct io_buffer *head;
2897 if (req->flags & REQ_F_BUFFER_SELECTED)
2900 io_ring_submit_lock(req->ctx, needs_lock);
2902 lockdep_assert_held(&req->ctx->uring_lock);
2904 head = xa_load(&req->ctx->io_buffers, bgid);
2906 if (!list_empty(&head->list)) {
2907 kbuf = list_last_entry(&head->list, struct io_buffer,
2909 list_del(&kbuf->list);
2912 xa_erase(&req->ctx->io_buffers, bgid);
2914 if (*len > kbuf->len)
2917 kbuf = ERR_PTR(-ENOBUFS);
2920 io_ring_submit_unlock(req->ctx, needs_lock);
2925 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2928 struct io_buffer *kbuf;
2931 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2932 bgid = req->buf_index;
2933 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2936 req->rw.addr = (u64) (unsigned long) kbuf;
2937 req->flags |= REQ_F_BUFFER_SELECTED;
2938 return u64_to_user_ptr(kbuf->addr);
2941 #ifdef CONFIG_COMPAT
2942 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2945 struct compat_iovec __user *uiov;
2946 compat_ssize_t clen;
2950 uiov = u64_to_user_ptr(req->rw.addr);
2951 if (!access_ok(uiov, sizeof(*uiov)))
2953 if (__get_user(clen, &uiov->iov_len))
2959 buf = io_rw_buffer_select(req, &len, needs_lock);
2961 return PTR_ERR(buf);
2962 iov[0].iov_base = buf;
2963 iov[0].iov_len = (compat_size_t) len;
2968 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2971 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2975 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2978 len = iov[0].iov_len;
2981 buf = io_rw_buffer_select(req, &len, needs_lock);
2983 return PTR_ERR(buf);
2984 iov[0].iov_base = buf;
2985 iov[0].iov_len = len;
2989 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2992 if (req->flags & REQ_F_BUFFER_SELECTED) {
2993 struct io_buffer *kbuf;
2995 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2996 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2997 iov[0].iov_len = kbuf->len;
3000 if (req->rw.len != 1)
3003 #ifdef CONFIG_COMPAT
3004 if (req->ctx->compat)
3005 return io_compat_import(req, iov, needs_lock);
3008 return __io_iov_buffer_select(req, iov, needs_lock);
3011 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3012 struct iov_iter *iter, bool needs_lock)
3014 void __user *buf = u64_to_user_ptr(req->rw.addr);
3015 size_t sqe_len = req->rw.len;
3016 u8 opcode = req->opcode;
3019 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3021 return io_import_fixed(req, rw, iter);
3024 /* buffer index only valid with fixed read/write, or buffer select */
3025 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3028 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3029 if (req->flags & REQ_F_BUFFER_SELECT) {
3030 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3032 return PTR_ERR(buf);
3033 req->rw.len = sqe_len;
3036 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3041 if (req->flags & REQ_F_BUFFER_SELECT) {
3042 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3044 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3049 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3053 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3055 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3059 * For files that don't have ->read_iter() and ->write_iter(), handle them
3060 * by looping over ->read() or ->write() manually.
3062 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3064 struct kiocb *kiocb = &req->rw.kiocb;
3065 struct file *file = req->file;
3069 * Don't support polled IO through this interface, and we can't
3070 * support non-blocking either. For the latter, this just causes
3071 * the kiocb to be handled from an async context.
3073 if (kiocb->ki_flags & IOCB_HIPRI)
3075 if (kiocb->ki_flags & IOCB_NOWAIT)
3078 while (iov_iter_count(iter)) {
3082 if (!iov_iter_is_bvec(iter)) {
3083 iovec = iov_iter_iovec(iter);
3085 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3086 iovec.iov_len = req->rw.len;
3090 nr = file->f_op->read(file, iovec.iov_base,
3091 iovec.iov_len, io_kiocb_ppos(kiocb));
3093 nr = file->f_op->write(file, iovec.iov_base,
3094 iovec.iov_len, io_kiocb_ppos(kiocb));
3103 if (nr != iovec.iov_len)
3107 iov_iter_advance(iter, nr);
3113 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3114 const struct iovec *fast_iov, struct iov_iter *iter)
3116 struct io_async_rw *rw = req->async_data;
3118 memcpy(&rw->iter, iter, sizeof(*iter));
3119 rw->free_iovec = iovec;
3121 /* can only be fixed buffers, no need to do anything */
3122 if (iov_iter_is_bvec(iter))
3125 unsigned iov_off = 0;
3127 rw->iter.iov = rw->fast_iov;
3128 if (iter->iov != fast_iov) {
3129 iov_off = iter->iov - fast_iov;
3130 rw->iter.iov += iov_off;
3132 if (rw->fast_iov != fast_iov)
3133 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3134 sizeof(struct iovec) * iter->nr_segs);
3136 req->flags |= REQ_F_NEED_CLEANUP;
3140 static inline int io_alloc_async_data(struct io_kiocb *req)
3142 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3143 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3144 return req->async_data == NULL;
3147 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3148 const struct iovec *fast_iov,
3149 struct iov_iter *iter, bool force)
3151 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3153 if (!req->async_data) {
3154 if (io_alloc_async_data(req)) {
3159 io_req_map_rw(req, iovec, fast_iov, iter);
3164 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3166 struct io_async_rw *iorw = req->async_data;
3167 struct iovec *iov = iorw->fast_iov;
3170 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3171 if (unlikely(ret < 0))
3174 iorw->bytes_done = 0;
3175 iorw->free_iovec = iov;
3177 req->flags |= REQ_F_NEED_CLEANUP;
3181 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3183 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3185 return io_prep_rw(req, sqe);
3189 * This is our waitqueue callback handler, registered through lock_page_async()
3190 * when we initially tried to do the IO with the iocb armed our waitqueue.
3191 * This gets called when the page is unlocked, and we generally expect that to
3192 * happen when the page IO is completed and the page is now uptodate. This will
3193 * queue a task_work based retry of the operation, attempting to copy the data
3194 * again. If the latter fails because the page was NOT uptodate, then we will
3195 * do a thread based blocking retry of the operation. That's the unexpected
3198 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3199 int sync, void *arg)
3201 struct wait_page_queue *wpq;
3202 struct io_kiocb *req = wait->private;
3203 struct wait_page_key *key = arg;
3205 wpq = container_of(wait, struct wait_page_queue, wait);
3207 if (!wake_page_match(wpq, key))
3210 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3211 list_del_init(&wait->entry);
3213 /* submit ref gets dropped, acquire a new one */
3215 io_req_task_queue(req);
3220 * This controls whether a given IO request should be armed for async page
3221 * based retry. If we return false here, the request is handed to the async
3222 * worker threads for retry. If we're doing buffered reads on a regular file,
3223 * we prepare a private wait_page_queue entry and retry the operation. This
3224 * will either succeed because the page is now uptodate and unlocked, or it
3225 * will register a callback when the page is unlocked at IO completion. Through
3226 * that callback, io_uring uses task_work to setup a retry of the operation.
3227 * That retry will attempt the buffered read again. The retry will generally
3228 * succeed, or in rare cases where it fails, we then fall back to using the
3229 * async worker threads for a blocking retry.
3231 static bool io_rw_should_retry(struct io_kiocb *req)
3233 struct io_async_rw *rw = req->async_data;
3234 struct wait_page_queue *wait = &rw->wpq;
3235 struct kiocb *kiocb = &req->rw.kiocb;
3237 /* never retry for NOWAIT, we just complete with -EAGAIN */
3238 if (req->flags & REQ_F_NOWAIT)
3241 /* Only for buffered IO */
3242 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3246 * just use poll if we can, and don't attempt if the fs doesn't
3247 * support callback based unlocks
3249 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3252 wait->wait.func = io_async_buf_func;
3253 wait->wait.private = req;
3254 wait->wait.flags = 0;
3255 INIT_LIST_HEAD(&wait->wait.entry);
3256 kiocb->ki_flags |= IOCB_WAITQ;
3257 kiocb->ki_flags &= ~IOCB_NOWAIT;
3258 kiocb->ki_waitq = wait;
3262 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3264 if (req->file->f_op->read_iter)
3265 return call_read_iter(req->file, &req->rw.kiocb, iter);
3266 else if (req->file->f_op->read)
3267 return loop_rw_iter(READ, req, iter);
3272 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3274 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3275 struct kiocb *kiocb = &req->rw.kiocb;
3276 struct iov_iter __iter, *iter = &__iter;
3277 struct io_async_rw *rw = req->async_data;
3278 ssize_t io_size, ret, ret2;
3279 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3285 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3289 io_size = iov_iter_count(iter);
3290 req->result = io_size;
3292 /* Ensure we clear previously set non-block flag */
3293 if (!force_nonblock)
3294 kiocb->ki_flags &= ~IOCB_NOWAIT;
3296 kiocb->ki_flags |= IOCB_NOWAIT;
3298 /* If the file doesn't support async, just async punt */
3299 if (force_nonblock && !io_file_supports_async(req, READ)) {
3300 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3301 return ret ?: -EAGAIN;
3304 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3305 if (unlikely(ret)) {
3310 ret = io_iter_do_read(req, iter);
3312 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3313 req->flags &= ~REQ_F_REISSUE;
3314 /* IOPOLL retry should happen for io-wq threads */
3315 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3317 /* no retry on NONBLOCK nor RWF_NOWAIT */
3318 if (req->flags & REQ_F_NOWAIT)
3320 /* some cases will consume bytes even on error returns */
3321 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3323 } else if (ret == -EIOCBQUEUED) {
3325 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3326 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3327 /* read all, failed, already did sync or don't want to retry */
3331 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3336 rw = req->async_data;
3337 /* now use our persistent iterator, if we aren't already */
3342 rw->bytes_done += ret;
3343 /* if we can retry, do so with the callbacks armed */
3344 if (!io_rw_should_retry(req)) {
3345 kiocb->ki_flags &= ~IOCB_WAITQ;
3350 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3351 * we get -EIOCBQUEUED, then we'll get a notification when the
3352 * desired page gets unlocked. We can also get a partial read
3353 * here, and if we do, then just retry at the new offset.
3355 ret = io_iter_do_read(req, iter);
3356 if (ret == -EIOCBQUEUED)
3358 /* we got some bytes, but not all. retry. */
3359 kiocb->ki_flags &= ~IOCB_WAITQ;
3360 } while (ret > 0 && ret < io_size);
3362 kiocb_done(kiocb, ret, issue_flags);
3364 /* it's faster to check here then delegate to kfree */
3370 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3372 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3374 return io_prep_rw(req, sqe);
3377 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3379 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3380 struct kiocb *kiocb = &req->rw.kiocb;
3381 struct iov_iter __iter, *iter = &__iter;
3382 struct io_async_rw *rw = req->async_data;
3383 ssize_t ret, ret2, io_size;
3384 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3390 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3394 io_size = iov_iter_count(iter);
3395 req->result = io_size;
3397 /* Ensure we clear previously set non-block flag */
3398 if (!force_nonblock)
3399 kiocb->ki_flags &= ~IOCB_NOWAIT;
3401 kiocb->ki_flags |= IOCB_NOWAIT;
3403 /* If the file doesn't support async, just async punt */
3404 if (force_nonblock && !io_file_supports_async(req, WRITE))
3407 /* file path doesn't support NOWAIT for non-direct_IO */
3408 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3409 (req->flags & REQ_F_ISREG))
3412 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3417 * Open-code file_start_write here to grab freeze protection,
3418 * which will be released by another thread in
3419 * io_complete_rw(). Fool lockdep by telling it the lock got
3420 * released so that it doesn't complain about the held lock when
3421 * we return to userspace.
3423 if (req->flags & REQ_F_ISREG) {
3424 sb_start_write(file_inode(req->file)->i_sb);
3425 __sb_writers_release(file_inode(req->file)->i_sb,
3428 kiocb->ki_flags |= IOCB_WRITE;
3430 if (req->file->f_op->write_iter)
3431 ret2 = call_write_iter(req->file, kiocb, iter);
3432 else if (req->file->f_op->write)
3433 ret2 = loop_rw_iter(WRITE, req, iter);
3437 if (req->flags & REQ_F_REISSUE) {
3438 req->flags &= ~REQ_F_REISSUE;
3443 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3444 * retry them without IOCB_NOWAIT.
3446 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3448 /* no retry on NONBLOCK nor RWF_NOWAIT */
3449 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3451 if (!force_nonblock || ret2 != -EAGAIN) {
3452 /* IOPOLL retry should happen for io-wq threads */
3453 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3456 kiocb_done(kiocb, ret2, issue_flags);
3459 /* some cases will consume bytes even on error returns */
3460 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3461 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3462 return ret ?: -EAGAIN;
3465 /* it's reportedly faster than delegating the null check to kfree() */
3471 static int io_renameat_prep(struct io_kiocb *req,
3472 const struct io_uring_sqe *sqe)
3474 struct io_rename *ren = &req->rename;
3475 const char __user *oldf, *newf;
3477 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3479 if (sqe->ioprio || sqe->buf_index)
3481 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3484 ren->old_dfd = READ_ONCE(sqe->fd);
3485 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3486 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3487 ren->new_dfd = READ_ONCE(sqe->len);
3488 ren->flags = READ_ONCE(sqe->rename_flags);
3490 ren->oldpath = getname(oldf);
3491 if (IS_ERR(ren->oldpath))
3492 return PTR_ERR(ren->oldpath);
3494 ren->newpath = getname(newf);
3495 if (IS_ERR(ren->newpath)) {
3496 putname(ren->oldpath);
3497 return PTR_ERR(ren->newpath);
3500 req->flags |= REQ_F_NEED_CLEANUP;
3504 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3506 struct io_rename *ren = &req->rename;
3509 if (issue_flags & IO_URING_F_NONBLOCK)
3512 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3513 ren->newpath, ren->flags);
3515 req->flags &= ~REQ_F_NEED_CLEANUP;
3518 io_req_complete(req, ret);
3522 static int io_unlinkat_prep(struct io_kiocb *req,
3523 const struct io_uring_sqe *sqe)
3525 struct io_unlink *un = &req->unlink;
3526 const char __user *fname;
3528 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3530 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3532 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3535 un->dfd = READ_ONCE(sqe->fd);
3537 un->flags = READ_ONCE(sqe->unlink_flags);
3538 if (un->flags & ~AT_REMOVEDIR)
3541 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3542 un->filename = getname(fname);
3543 if (IS_ERR(un->filename))
3544 return PTR_ERR(un->filename);
3546 req->flags |= REQ_F_NEED_CLEANUP;
3550 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3552 struct io_unlink *un = &req->unlink;
3555 if (issue_flags & IO_URING_F_NONBLOCK)
3558 if (un->flags & AT_REMOVEDIR)
3559 ret = do_rmdir(un->dfd, un->filename);
3561 ret = do_unlinkat(un->dfd, un->filename);
3563 req->flags &= ~REQ_F_NEED_CLEANUP;
3566 io_req_complete(req, ret);
3570 static int io_shutdown_prep(struct io_kiocb *req,
3571 const struct io_uring_sqe *sqe)
3573 #if defined(CONFIG_NET)
3574 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3576 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3580 req->shutdown.how = READ_ONCE(sqe->len);
3587 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3589 #if defined(CONFIG_NET)
3590 struct socket *sock;
3593 if (issue_flags & IO_URING_F_NONBLOCK)
3596 sock = sock_from_file(req->file);
3597 if (unlikely(!sock))
3600 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3603 io_req_complete(req, ret);
3610 static int __io_splice_prep(struct io_kiocb *req,
3611 const struct io_uring_sqe *sqe)
3613 struct io_splice *sp = &req->splice;
3614 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3616 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3620 sp->len = READ_ONCE(sqe->len);
3621 sp->flags = READ_ONCE(sqe->splice_flags);
3623 if (unlikely(sp->flags & ~valid_flags))
3626 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3627 (sp->flags & SPLICE_F_FD_IN_FIXED));
3630 req->flags |= REQ_F_NEED_CLEANUP;
3634 static int io_tee_prep(struct io_kiocb *req,
3635 const struct io_uring_sqe *sqe)
3637 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3639 return __io_splice_prep(req, sqe);
3642 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3644 struct io_splice *sp = &req->splice;
3645 struct file *in = sp->file_in;
3646 struct file *out = sp->file_out;
3647 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3650 if (issue_flags & IO_URING_F_NONBLOCK)
3653 ret = do_tee(in, out, sp->len, flags);
3655 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3657 req->flags &= ~REQ_F_NEED_CLEANUP;
3661 io_req_complete(req, ret);
3665 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3667 struct io_splice *sp = &req->splice;
3669 sp->off_in = READ_ONCE(sqe->splice_off_in);
3670 sp->off_out = READ_ONCE(sqe->off);
3671 return __io_splice_prep(req, sqe);
3674 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3676 struct io_splice *sp = &req->splice;
3677 struct file *in = sp->file_in;
3678 struct file *out = sp->file_out;
3679 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3680 loff_t *poff_in, *poff_out;
3683 if (issue_flags & IO_URING_F_NONBLOCK)
3686 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3687 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3690 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3692 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3694 req->flags &= ~REQ_F_NEED_CLEANUP;
3698 io_req_complete(req, ret);
3703 * IORING_OP_NOP just posts a completion event, nothing else.
3705 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3707 struct io_ring_ctx *ctx = req->ctx;
3709 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3712 __io_req_complete(req, issue_flags, 0, 0);
3716 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3718 struct io_ring_ctx *ctx = req->ctx;
3723 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3725 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3728 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3729 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3732 req->sync.off = READ_ONCE(sqe->off);
3733 req->sync.len = READ_ONCE(sqe->len);
3737 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3739 loff_t end = req->sync.off + req->sync.len;
3742 /* fsync always requires a blocking context */
3743 if (issue_flags & IO_URING_F_NONBLOCK)
3746 ret = vfs_fsync_range(req->file, req->sync.off,
3747 end > 0 ? end : LLONG_MAX,
3748 req->sync.flags & IORING_FSYNC_DATASYNC);
3751 io_req_complete(req, ret);
3755 static int io_fallocate_prep(struct io_kiocb *req,
3756 const struct io_uring_sqe *sqe)
3758 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3760 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3763 req->sync.off = READ_ONCE(sqe->off);
3764 req->sync.len = READ_ONCE(sqe->addr);
3765 req->sync.mode = READ_ONCE(sqe->len);
3769 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3773 /* fallocate always requiring blocking context */
3774 if (issue_flags & IO_URING_F_NONBLOCK)
3776 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3780 io_req_complete(req, ret);
3784 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3786 const char __user *fname;
3789 if (unlikely(sqe->ioprio || sqe->buf_index))
3791 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3794 /* open.how should be already initialised */
3795 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3796 req->open.how.flags |= O_LARGEFILE;
3798 req->open.dfd = READ_ONCE(sqe->fd);
3799 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3800 req->open.filename = getname(fname);
3801 if (IS_ERR(req->open.filename)) {
3802 ret = PTR_ERR(req->open.filename);
3803 req->open.filename = NULL;
3806 req->open.nofile = rlimit(RLIMIT_NOFILE);
3807 req->flags |= REQ_F_NEED_CLEANUP;
3811 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3815 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3817 mode = READ_ONCE(sqe->len);
3818 flags = READ_ONCE(sqe->open_flags);
3819 req->open.how = build_open_how(flags, mode);
3820 return __io_openat_prep(req, sqe);
3823 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3825 struct open_how __user *how;
3829 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3831 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3832 len = READ_ONCE(sqe->len);
3833 if (len < OPEN_HOW_SIZE_VER0)
3836 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3841 return __io_openat_prep(req, sqe);
3844 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3846 struct open_flags op;
3849 bool resolve_nonblock;
3852 ret = build_open_flags(&req->open.how, &op);
3855 nonblock_set = op.open_flag & O_NONBLOCK;
3856 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3857 if (issue_flags & IO_URING_F_NONBLOCK) {
3859 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3860 * it'll always -EAGAIN
3862 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3864 op.lookup_flags |= LOOKUP_CACHED;
3865 op.open_flag |= O_NONBLOCK;
3868 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3872 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3875 * We could hang on to this 'fd' on retrying, but seems like
3876 * marginal gain for something that is now known to be a slower
3877 * path. So just put it, and we'll get a new one when we retry.
3881 ret = PTR_ERR(file);
3882 /* only retry if RESOLVE_CACHED wasn't already set by application */
3883 if (ret == -EAGAIN &&
3884 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
3889 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3890 file->f_flags &= ~O_NONBLOCK;
3891 fsnotify_open(file);
3892 fd_install(ret, file);
3894 putname(req->open.filename);
3895 req->flags &= ~REQ_F_NEED_CLEANUP;
3898 __io_req_complete(req, issue_flags, ret, 0);
3902 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3904 return io_openat2(req, issue_flags);
3907 static int io_remove_buffers_prep(struct io_kiocb *req,
3908 const struct io_uring_sqe *sqe)
3910 struct io_provide_buf *p = &req->pbuf;
3913 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3916 tmp = READ_ONCE(sqe->fd);
3917 if (!tmp || tmp > USHRT_MAX)
3920 memset(p, 0, sizeof(*p));
3922 p->bgid = READ_ONCE(sqe->buf_group);
3926 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3927 int bgid, unsigned nbufs)
3931 /* shouldn't happen */
3935 /* the head kbuf is the list itself */
3936 while (!list_empty(&buf->list)) {
3937 struct io_buffer *nxt;
3939 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3940 list_del(&nxt->list);
3947 xa_erase(&ctx->io_buffers, bgid);
3952 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3954 struct io_provide_buf *p = &req->pbuf;
3955 struct io_ring_ctx *ctx = req->ctx;
3956 struct io_buffer *head;
3958 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3960 io_ring_submit_lock(ctx, !force_nonblock);
3962 lockdep_assert_held(&ctx->uring_lock);
3965 head = xa_load(&ctx->io_buffers, p->bgid);
3967 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3971 /* complete before unlock, IOPOLL may need the lock */
3972 __io_req_complete(req, issue_flags, ret, 0);
3973 io_ring_submit_unlock(ctx, !force_nonblock);
3977 static int io_provide_buffers_prep(struct io_kiocb *req,
3978 const struct io_uring_sqe *sqe)
3980 unsigned long size, tmp_check;
3981 struct io_provide_buf *p = &req->pbuf;
3984 if (sqe->ioprio || sqe->rw_flags)
3987 tmp = READ_ONCE(sqe->fd);
3988 if (!tmp || tmp > USHRT_MAX)
3991 p->addr = READ_ONCE(sqe->addr);
3992 p->len = READ_ONCE(sqe->len);
3994 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3997 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4000 size = (unsigned long)p->len * p->nbufs;
4001 if (!access_ok(u64_to_user_ptr(p->addr), size))
4004 p->bgid = READ_ONCE(sqe->buf_group);
4005 tmp = READ_ONCE(sqe->off);
4006 if (tmp > USHRT_MAX)
4012 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4014 struct io_buffer *buf;
4015 u64 addr = pbuf->addr;
4016 int i, bid = pbuf->bid;
4018 for (i = 0; i < pbuf->nbufs; i++) {
4019 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4024 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4029 INIT_LIST_HEAD(&buf->list);
4032 list_add_tail(&buf->list, &(*head)->list);
4036 return i ? i : -ENOMEM;
4039 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4041 struct io_provide_buf *p = &req->pbuf;
4042 struct io_ring_ctx *ctx = req->ctx;
4043 struct io_buffer *head, *list;
4045 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4047 io_ring_submit_lock(ctx, !force_nonblock);
4049 lockdep_assert_held(&ctx->uring_lock);
4051 list = head = xa_load(&ctx->io_buffers, p->bgid);
4053 ret = io_add_buffers(p, &head);
4054 if (ret >= 0 && !list) {
4055 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4057 __io_remove_buffers(ctx, head, p->bgid, -1U);
4061 /* complete before unlock, IOPOLL may need the lock */
4062 __io_req_complete(req, issue_flags, ret, 0);
4063 io_ring_submit_unlock(ctx, !force_nonblock);
4067 static int io_epoll_ctl_prep(struct io_kiocb *req,
4068 const struct io_uring_sqe *sqe)
4070 #if defined(CONFIG_EPOLL)
4071 if (sqe->ioprio || sqe->buf_index)
4073 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4076 req->epoll.epfd = READ_ONCE(sqe->fd);
4077 req->epoll.op = READ_ONCE(sqe->len);
4078 req->epoll.fd = READ_ONCE(sqe->off);
4080 if (ep_op_has_event(req->epoll.op)) {
4081 struct epoll_event __user *ev;
4083 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4084 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4094 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4096 #if defined(CONFIG_EPOLL)
4097 struct io_epoll *ie = &req->epoll;
4099 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4101 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4102 if (force_nonblock && ret == -EAGAIN)
4107 __io_req_complete(req, issue_flags, ret, 0);
4114 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4116 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4117 if (sqe->ioprio || sqe->buf_index || sqe->off)
4119 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4122 req->madvise.addr = READ_ONCE(sqe->addr);
4123 req->madvise.len = READ_ONCE(sqe->len);
4124 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4131 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4133 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4134 struct io_madvise *ma = &req->madvise;
4137 if (issue_flags & IO_URING_F_NONBLOCK)
4140 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4143 io_req_complete(req, ret);
4150 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4152 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4154 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4157 req->fadvise.offset = READ_ONCE(sqe->off);
4158 req->fadvise.len = READ_ONCE(sqe->len);
4159 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4163 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4165 struct io_fadvise *fa = &req->fadvise;
4168 if (issue_flags & IO_URING_F_NONBLOCK) {
4169 switch (fa->advice) {
4170 case POSIX_FADV_NORMAL:
4171 case POSIX_FADV_RANDOM:
4172 case POSIX_FADV_SEQUENTIAL:
4179 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4182 __io_req_complete(req, issue_flags, ret, 0);
4186 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4188 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4190 if (sqe->ioprio || sqe->buf_index)
4192 if (req->flags & REQ_F_FIXED_FILE)
4195 req->statx.dfd = READ_ONCE(sqe->fd);
4196 req->statx.mask = READ_ONCE(sqe->len);
4197 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4198 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4199 req->statx.flags = READ_ONCE(sqe->statx_flags);
4204 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4206 struct io_statx *ctx = &req->statx;
4209 if (issue_flags & IO_URING_F_NONBLOCK)
4212 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4217 io_req_complete(req, ret);
4221 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4223 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4225 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4226 sqe->rw_flags || sqe->buf_index)
4228 if (req->flags & REQ_F_FIXED_FILE)
4231 req->close.fd = READ_ONCE(sqe->fd);
4235 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4237 struct files_struct *files = current->files;
4238 struct io_close *close = &req->close;
4239 struct fdtable *fdt;
4240 struct file *file = NULL;
4243 spin_lock(&files->file_lock);
4244 fdt = files_fdtable(files);
4245 if (close->fd >= fdt->max_fds) {
4246 spin_unlock(&files->file_lock);
4249 file = fdt->fd[close->fd];
4250 if (!file || file->f_op == &io_uring_fops) {
4251 spin_unlock(&files->file_lock);
4256 /* if the file has a flush method, be safe and punt to async */
4257 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4258 spin_unlock(&files->file_lock);
4262 ret = __close_fd_get_file(close->fd, &file);
4263 spin_unlock(&files->file_lock);
4270 /* No ->flush() or already async, safely close from here */
4271 ret = filp_close(file, current->files);
4277 __io_req_complete(req, issue_flags, ret, 0);
4281 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4283 struct io_ring_ctx *ctx = req->ctx;
4285 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4287 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4290 req->sync.off = READ_ONCE(sqe->off);
4291 req->sync.len = READ_ONCE(sqe->len);
4292 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4296 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4300 /* sync_file_range always requires a blocking context */
4301 if (issue_flags & IO_URING_F_NONBLOCK)
4304 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4308 io_req_complete(req, ret);
4312 #if defined(CONFIG_NET)
4313 static int io_setup_async_msg(struct io_kiocb *req,
4314 struct io_async_msghdr *kmsg)
4316 struct io_async_msghdr *async_msg = req->async_data;
4320 if (io_alloc_async_data(req)) {
4321 kfree(kmsg->free_iov);
4324 async_msg = req->async_data;
4325 req->flags |= REQ_F_NEED_CLEANUP;
4326 memcpy(async_msg, kmsg, sizeof(*kmsg));
4327 async_msg->msg.msg_name = &async_msg->addr;
4328 /* if were using fast_iov, set it to the new one */
4329 if (!async_msg->free_iov)
4330 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4335 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4336 struct io_async_msghdr *iomsg)
4338 iomsg->msg.msg_name = &iomsg->addr;
4339 iomsg->free_iov = iomsg->fast_iov;
4340 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4341 req->sr_msg.msg_flags, &iomsg->free_iov);
4344 static int io_sendmsg_prep_async(struct io_kiocb *req)
4348 ret = io_sendmsg_copy_hdr(req, req->async_data);
4350 req->flags |= REQ_F_NEED_CLEANUP;
4354 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4356 struct io_sr_msg *sr = &req->sr_msg;
4358 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4361 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4362 sr->len = READ_ONCE(sqe->len);
4363 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4364 if (sr->msg_flags & MSG_DONTWAIT)
4365 req->flags |= REQ_F_NOWAIT;
4367 #ifdef CONFIG_COMPAT
4368 if (req->ctx->compat)
4369 sr->msg_flags |= MSG_CMSG_COMPAT;
4374 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4376 struct io_async_msghdr iomsg, *kmsg;
4377 struct socket *sock;
4382 sock = sock_from_file(req->file);
4383 if (unlikely(!sock))
4386 kmsg = req->async_data;
4388 ret = io_sendmsg_copy_hdr(req, &iomsg);
4394 flags = req->sr_msg.msg_flags;
4395 if (issue_flags & IO_URING_F_NONBLOCK)
4396 flags |= MSG_DONTWAIT;
4397 if (flags & MSG_WAITALL)
4398 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4400 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4401 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4402 return io_setup_async_msg(req, kmsg);
4403 if (ret == -ERESTARTSYS)
4406 /* fast path, check for non-NULL to avoid function call */
4408 kfree(kmsg->free_iov);
4409 req->flags &= ~REQ_F_NEED_CLEANUP;
4412 __io_req_complete(req, issue_flags, ret, 0);
4416 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4418 struct io_sr_msg *sr = &req->sr_msg;
4421 struct socket *sock;
4426 sock = sock_from_file(req->file);
4427 if (unlikely(!sock))
4430 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4434 msg.msg_name = NULL;
4435 msg.msg_control = NULL;
4436 msg.msg_controllen = 0;
4437 msg.msg_namelen = 0;
4439 flags = req->sr_msg.msg_flags;
4440 if (issue_flags & IO_URING_F_NONBLOCK)
4441 flags |= MSG_DONTWAIT;
4442 if (flags & MSG_WAITALL)
4443 min_ret = iov_iter_count(&msg.msg_iter);
4445 msg.msg_flags = flags;
4446 ret = sock_sendmsg(sock, &msg);
4447 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4449 if (ret == -ERESTARTSYS)
4454 __io_req_complete(req, issue_flags, ret, 0);
4458 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4459 struct io_async_msghdr *iomsg)
4461 struct io_sr_msg *sr = &req->sr_msg;
4462 struct iovec __user *uiov;
4466 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4467 &iomsg->uaddr, &uiov, &iov_len);
4471 if (req->flags & REQ_F_BUFFER_SELECT) {
4474 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4476 sr->len = iomsg->fast_iov[0].iov_len;
4477 iomsg->free_iov = NULL;
4479 iomsg->free_iov = iomsg->fast_iov;
4480 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4481 &iomsg->free_iov, &iomsg->msg.msg_iter,
4490 #ifdef CONFIG_COMPAT
4491 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4492 struct io_async_msghdr *iomsg)
4494 struct io_sr_msg *sr = &req->sr_msg;
4495 struct compat_iovec __user *uiov;
4500 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4505 uiov = compat_ptr(ptr);
4506 if (req->flags & REQ_F_BUFFER_SELECT) {
4507 compat_ssize_t clen;
4511 if (!access_ok(uiov, sizeof(*uiov)))
4513 if (__get_user(clen, &uiov->iov_len))
4518 iomsg->free_iov = NULL;
4520 iomsg->free_iov = iomsg->fast_iov;
4521 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4522 UIO_FASTIOV, &iomsg->free_iov,
4523 &iomsg->msg.msg_iter, true);
4532 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4533 struct io_async_msghdr *iomsg)
4535 iomsg->msg.msg_name = &iomsg->addr;
4537 #ifdef CONFIG_COMPAT
4538 if (req->ctx->compat)
4539 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4542 return __io_recvmsg_copy_hdr(req, iomsg);
4545 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4548 struct io_sr_msg *sr = &req->sr_msg;
4549 struct io_buffer *kbuf;
4551 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4556 req->flags |= REQ_F_BUFFER_SELECTED;
4560 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4562 return io_put_kbuf(req, req->sr_msg.kbuf);
4565 static int io_recvmsg_prep_async(struct io_kiocb *req)
4569 ret = io_recvmsg_copy_hdr(req, req->async_data);
4571 req->flags |= REQ_F_NEED_CLEANUP;
4575 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4577 struct io_sr_msg *sr = &req->sr_msg;
4579 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4582 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4583 sr->len = READ_ONCE(sqe->len);
4584 sr->bgid = READ_ONCE(sqe->buf_group);
4585 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4586 if (sr->msg_flags & MSG_DONTWAIT)
4587 req->flags |= REQ_F_NOWAIT;
4589 #ifdef CONFIG_COMPAT
4590 if (req->ctx->compat)
4591 sr->msg_flags |= MSG_CMSG_COMPAT;
4596 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4598 struct io_async_msghdr iomsg, *kmsg;
4599 struct socket *sock;
4600 struct io_buffer *kbuf;
4603 int ret, cflags = 0;
4604 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4606 sock = sock_from_file(req->file);
4607 if (unlikely(!sock))
4610 kmsg = req->async_data;
4612 ret = io_recvmsg_copy_hdr(req, &iomsg);
4618 if (req->flags & REQ_F_BUFFER_SELECT) {
4619 kbuf = io_recv_buffer_select(req, !force_nonblock);
4621 return PTR_ERR(kbuf);
4622 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4623 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4624 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4625 1, req->sr_msg.len);
4628 flags = req->sr_msg.msg_flags;
4630 flags |= MSG_DONTWAIT;
4631 if (flags & MSG_WAITALL)
4632 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4634 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4635 kmsg->uaddr, flags);
4636 if (force_nonblock && ret == -EAGAIN)
4637 return io_setup_async_msg(req, kmsg);
4638 if (ret == -ERESTARTSYS)
4641 if (req->flags & REQ_F_BUFFER_SELECTED)
4642 cflags = io_put_recv_kbuf(req);
4643 /* fast path, check for non-NULL to avoid function call */
4645 kfree(kmsg->free_iov);
4646 req->flags &= ~REQ_F_NEED_CLEANUP;
4647 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4649 __io_req_complete(req, issue_flags, ret, cflags);
4653 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4655 struct io_buffer *kbuf;
4656 struct io_sr_msg *sr = &req->sr_msg;
4658 void __user *buf = sr->buf;
4659 struct socket *sock;
4663 int ret, cflags = 0;
4664 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4666 sock = sock_from_file(req->file);
4667 if (unlikely(!sock))
4670 if (req->flags & REQ_F_BUFFER_SELECT) {
4671 kbuf = io_recv_buffer_select(req, !force_nonblock);
4673 return PTR_ERR(kbuf);
4674 buf = u64_to_user_ptr(kbuf->addr);
4677 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4681 msg.msg_name = NULL;
4682 msg.msg_control = NULL;
4683 msg.msg_controllen = 0;
4684 msg.msg_namelen = 0;
4685 msg.msg_iocb = NULL;
4688 flags = req->sr_msg.msg_flags;
4690 flags |= MSG_DONTWAIT;
4691 if (flags & MSG_WAITALL)
4692 min_ret = iov_iter_count(&msg.msg_iter);
4694 ret = sock_recvmsg(sock, &msg, flags);
4695 if (force_nonblock && ret == -EAGAIN)
4697 if (ret == -ERESTARTSYS)
4700 if (req->flags & REQ_F_BUFFER_SELECTED)
4701 cflags = io_put_recv_kbuf(req);
4702 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4704 __io_req_complete(req, issue_flags, ret, cflags);
4708 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4710 struct io_accept *accept = &req->accept;
4712 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4714 if (sqe->ioprio || sqe->len || sqe->buf_index)
4717 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4718 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4719 accept->flags = READ_ONCE(sqe->accept_flags);
4720 accept->nofile = rlimit(RLIMIT_NOFILE);
4724 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4726 struct io_accept *accept = &req->accept;
4727 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4728 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4731 if (req->file->f_flags & O_NONBLOCK)
4732 req->flags |= REQ_F_NOWAIT;
4734 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4735 accept->addr_len, accept->flags,
4737 if (ret == -EAGAIN && force_nonblock)
4740 if (ret == -ERESTARTSYS)
4744 __io_req_complete(req, issue_flags, ret, 0);
4748 static int io_connect_prep_async(struct io_kiocb *req)
4750 struct io_async_connect *io = req->async_data;
4751 struct io_connect *conn = &req->connect;
4753 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4756 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4758 struct io_connect *conn = &req->connect;
4760 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4762 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4765 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4766 conn->addr_len = READ_ONCE(sqe->addr2);
4770 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4772 struct io_async_connect __io, *io;
4773 unsigned file_flags;
4775 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4777 if (req->async_data) {
4778 io = req->async_data;
4780 ret = move_addr_to_kernel(req->connect.addr,
4781 req->connect.addr_len,
4788 file_flags = force_nonblock ? O_NONBLOCK : 0;
4790 ret = __sys_connect_file(req->file, &io->address,
4791 req->connect.addr_len, file_flags);
4792 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4793 if (req->async_data)
4795 if (io_alloc_async_data(req)) {
4799 memcpy(req->async_data, &__io, sizeof(__io));
4802 if (ret == -ERESTARTSYS)
4807 __io_req_complete(req, issue_flags, ret, 0);
4810 #else /* !CONFIG_NET */
4811 #define IO_NETOP_FN(op) \
4812 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4814 return -EOPNOTSUPP; \
4817 #define IO_NETOP_PREP(op) \
4819 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4821 return -EOPNOTSUPP; \
4824 #define IO_NETOP_PREP_ASYNC(op) \
4826 static int io_##op##_prep_async(struct io_kiocb *req) \
4828 return -EOPNOTSUPP; \
4831 IO_NETOP_PREP_ASYNC(sendmsg);
4832 IO_NETOP_PREP_ASYNC(recvmsg);
4833 IO_NETOP_PREP_ASYNC(connect);
4834 IO_NETOP_PREP(accept);
4837 #endif /* CONFIG_NET */
4839 struct io_poll_table {
4840 struct poll_table_struct pt;
4841 struct io_kiocb *req;
4846 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4847 __poll_t mask, io_req_tw_func_t func)
4849 /* for instances that support it check for an event match first: */
4850 if (mask && !(mask & poll->events))
4853 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4855 list_del_init(&poll->wait.entry);
4858 req->io_task_work.func = func;
4861 * If this fails, then the task is exiting. When a task exits, the
4862 * work gets canceled, so just cancel this request as well instead
4863 * of executing it. We can't safely execute it anyway, as we may not
4864 * have the needed state needed for it anyway.
4866 io_req_task_work_add(req);
4870 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4871 __acquires(&req->ctx->completion_lock)
4873 struct io_ring_ctx *ctx = req->ctx;
4875 if (unlikely(req->task->flags & PF_EXITING))
4876 WRITE_ONCE(poll->canceled, true);
4878 if (!req->result && !READ_ONCE(poll->canceled)) {
4879 struct poll_table_struct pt = { ._key = poll->events };
4881 req->result = vfs_poll(req->file, &pt) & poll->events;
4884 spin_lock_irq(&ctx->completion_lock);
4885 if (!req->result && !READ_ONCE(poll->canceled)) {
4886 add_wait_queue(poll->head, &poll->wait);
4893 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4895 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4896 if (req->opcode == IORING_OP_POLL_ADD)
4897 return req->async_data;
4898 return req->apoll->double_poll;
4901 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4903 if (req->opcode == IORING_OP_POLL_ADD)
4905 return &req->apoll->poll;
4908 static void io_poll_remove_double(struct io_kiocb *req)
4909 __must_hold(&req->ctx->completion_lock)
4911 struct io_poll_iocb *poll = io_poll_get_double(req);
4913 lockdep_assert_held(&req->ctx->completion_lock);
4915 if (poll && poll->head) {
4916 struct wait_queue_head *head = poll->head;
4918 spin_lock(&head->lock);
4919 list_del_init(&poll->wait.entry);
4920 if (poll->wait.private)
4923 spin_unlock(&head->lock);
4927 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4928 __must_hold(&req->ctx->completion_lock)
4930 struct io_ring_ctx *ctx = req->ctx;
4931 unsigned flags = IORING_CQE_F_MORE;
4934 if (READ_ONCE(req->poll.canceled)) {
4936 req->poll.events |= EPOLLONESHOT;
4938 error = mangle_poll(mask);
4940 if (req->poll.events & EPOLLONESHOT)
4942 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4943 req->poll.done = true;
4946 if (flags & IORING_CQE_F_MORE)
4949 io_commit_cqring(ctx);
4950 return !(flags & IORING_CQE_F_MORE);
4953 static void io_poll_task_func(struct io_kiocb *req)
4955 struct io_ring_ctx *ctx = req->ctx;
4956 struct io_kiocb *nxt;
4958 if (io_poll_rewait(req, &req->poll)) {
4959 spin_unlock_irq(&ctx->completion_lock);
4963 done = io_poll_complete(req, req->result);
4965 io_poll_remove_double(req);
4966 hash_del(&req->hash_node);
4969 add_wait_queue(req->poll.head, &req->poll.wait);
4971 spin_unlock_irq(&ctx->completion_lock);
4972 io_cqring_ev_posted(ctx);
4975 nxt = io_put_req_find_next(req);
4977 io_req_task_submit(nxt);
4982 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4983 int sync, void *key)
4985 struct io_kiocb *req = wait->private;
4986 struct io_poll_iocb *poll = io_poll_get_single(req);
4987 __poll_t mask = key_to_poll(key);
4989 /* for instances that support it check for an event match first: */
4990 if (mask && !(mask & poll->events))
4992 if (!(poll->events & EPOLLONESHOT))
4993 return poll->wait.func(&poll->wait, mode, sync, key);
4995 list_del_init(&wait->entry);
5000 spin_lock(&poll->head->lock);
5001 done = list_empty(&poll->wait.entry);
5003 list_del_init(&poll->wait.entry);
5004 /* make sure double remove sees this as being gone */
5005 wait->private = NULL;
5006 spin_unlock(&poll->head->lock);
5008 /* use wait func handler, so it matches the rq type */
5009 poll->wait.func(&poll->wait, mode, sync, key);
5016 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5017 wait_queue_func_t wake_func)
5021 poll->canceled = false;
5022 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5023 /* mask in events that we always want/need */
5024 poll->events = events | IO_POLL_UNMASK;
5025 INIT_LIST_HEAD(&poll->wait.entry);
5026 init_waitqueue_func_entry(&poll->wait, wake_func);
5029 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5030 struct wait_queue_head *head,
5031 struct io_poll_iocb **poll_ptr)
5033 struct io_kiocb *req = pt->req;
5036 * The file being polled uses multiple waitqueues for poll handling
5037 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5040 if (unlikely(pt->nr_entries)) {
5041 struct io_poll_iocb *poll_one = poll;
5043 /* already have a 2nd entry, fail a third attempt */
5045 pt->error = -EINVAL;
5049 * Can't handle multishot for double wait for now, turn it
5050 * into one-shot mode.
5052 if (!(poll_one->events & EPOLLONESHOT))
5053 poll_one->events |= EPOLLONESHOT;
5054 /* double add on the same waitqueue head, ignore */
5055 if (poll_one->head == head)
5057 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5059 pt->error = -ENOMEM;
5062 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5064 poll->wait.private = req;
5071 if (poll->events & EPOLLEXCLUSIVE)
5072 add_wait_queue_exclusive(head, &poll->wait);
5074 add_wait_queue(head, &poll->wait);
5077 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5078 struct poll_table_struct *p)
5080 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5081 struct async_poll *apoll = pt->req->apoll;
5083 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5086 static void io_async_task_func(struct io_kiocb *req)
5088 struct async_poll *apoll = req->apoll;
5089 struct io_ring_ctx *ctx = req->ctx;
5091 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5093 if (io_poll_rewait(req, &apoll->poll)) {
5094 spin_unlock_irq(&ctx->completion_lock);
5098 hash_del(&req->hash_node);
5099 io_poll_remove_double(req);
5100 spin_unlock_irq(&ctx->completion_lock);
5102 if (!READ_ONCE(apoll->poll.canceled))
5103 io_req_task_submit(req);
5105 io_req_complete_failed(req, -ECANCELED);
5108 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5111 struct io_kiocb *req = wait->private;
5112 struct io_poll_iocb *poll = &req->apoll->poll;
5114 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5117 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5120 static void io_poll_req_insert(struct io_kiocb *req)
5122 struct io_ring_ctx *ctx = req->ctx;
5123 struct hlist_head *list;
5125 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5126 hlist_add_head(&req->hash_node, list);
5129 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5130 struct io_poll_iocb *poll,
5131 struct io_poll_table *ipt, __poll_t mask,
5132 wait_queue_func_t wake_func)
5133 __acquires(&ctx->completion_lock)
5135 struct io_ring_ctx *ctx = req->ctx;
5136 bool cancel = false;
5138 INIT_HLIST_NODE(&req->hash_node);
5139 io_init_poll_iocb(poll, mask, wake_func);
5140 poll->file = req->file;
5141 poll->wait.private = req;
5143 ipt->pt._key = mask;
5146 ipt->nr_entries = 0;
5148 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5149 if (unlikely(!ipt->nr_entries) && !ipt->error)
5150 ipt->error = -EINVAL;
5152 spin_lock_irq(&ctx->completion_lock);
5153 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5154 io_poll_remove_double(req);
5155 if (likely(poll->head)) {
5156 spin_lock(&poll->head->lock);
5157 if (unlikely(list_empty(&poll->wait.entry))) {
5163 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5164 list_del_init(&poll->wait.entry);
5166 WRITE_ONCE(poll->canceled, true);
5167 else if (!poll->done) /* actually waiting for an event */
5168 io_poll_req_insert(req);
5169 spin_unlock(&poll->head->lock);
5181 static int io_arm_poll_handler(struct io_kiocb *req)
5183 const struct io_op_def *def = &io_op_defs[req->opcode];
5184 struct io_ring_ctx *ctx = req->ctx;
5185 struct async_poll *apoll;
5186 struct io_poll_table ipt;
5187 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5190 if (!req->file || !file_can_poll(req->file))
5191 return IO_APOLL_ABORTED;
5192 if (req->flags & REQ_F_POLLED)
5193 return IO_APOLL_ABORTED;
5194 if (!def->pollin && !def->pollout)
5195 return IO_APOLL_ABORTED;
5199 mask |= POLLIN | POLLRDNORM;
5201 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5202 if ((req->opcode == IORING_OP_RECVMSG) &&
5203 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5207 mask |= POLLOUT | POLLWRNORM;
5210 /* if we can't nonblock try, then no point in arming a poll handler */
5211 if (!io_file_supports_async(req, rw))
5212 return IO_APOLL_ABORTED;
5214 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5215 if (unlikely(!apoll))
5216 return IO_APOLL_ABORTED;
5217 apoll->double_poll = NULL;
5219 req->flags |= REQ_F_POLLED;
5220 ipt.pt._qproc = io_async_queue_proc;
5222 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5224 if (ret || ipt.error) {
5225 spin_unlock_irq(&ctx->completion_lock);
5227 return IO_APOLL_READY;
5228 return IO_APOLL_ABORTED;
5230 spin_unlock_irq(&ctx->completion_lock);
5231 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5232 mask, apoll->poll.events);
5236 static bool __io_poll_remove_one(struct io_kiocb *req,
5237 struct io_poll_iocb *poll, bool do_cancel)
5238 __must_hold(&req->ctx->completion_lock)
5240 bool do_complete = false;
5244 spin_lock(&poll->head->lock);
5246 WRITE_ONCE(poll->canceled, true);
5247 if (!list_empty(&poll->wait.entry)) {
5248 list_del_init(&poll->wait.entry);
5251 spin_unlock(&poll->head->lock);
5252 hash_del(&req->hash_node);
5256 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5257 __must_hold(&req->ctx->completion_lock)
5261 io_poll_remove_double(req);
5262 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5264 if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
5265 /* non-poll requests have submit ref still */
5271 static bool io_poll_remove_one(struct io_kiocb *req)
5272 __must_hold(&req->ctx->completion_lock)
5276 do_complete = io_poll_remove_waitqs(req);
5278 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5279 io_commit_cqring(req->ctx);
5281 io_put_req_deferred(req, 1);
5288 * Returns true if we found and killed one or more poll requests
5290 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5293 struct hlist_node *tmp;
5294 struct io_kiocb *req;
5297 spin_lock_irq(&ctx->completion_lock);
5298 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5299 struct hlist_head *list;
5301 list = &ctx->cancel_hash[i];
5302 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5303 if (io_match_task(req, tsk, cancel_all))
5304 posted += io_poll_remove_one(req);
5307 spin_unlock_irq(&ctx->completion_lock);
5310 io_cqring_ev_posted(ctx);
5315 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5317 __must_hold(&ctx->completion_lock)
5319 struct hlist_head *list;
5320 struct io_kiocb *req;
5322 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5323 hlist_for_each_entry(req, list, hash_node) {
5324 if (sqe_addr != req->user_data)
5326 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5333 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5335 __must_hold(&ctx->completion_lock)
5337 struct io_kiocb *req;
5339 req = io_poll_find(ctx, sqe_addr, poll_only);
5342 if (io_poll_remove_one(req))
5348 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5353 events = READ_ONCE(sqe->poll32_events);
5355 events = swahw32(events);
5357 if (!(flags & IORING_POLL_ADD_MULTI))
5358 events |= EPOLLONESHOT;
5359 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5362 static int io_poll_update_prep(struct io_kiocb *req,
5363 const struct io_uring_sqe *sqe)
5365 struct io_poll_update *upd = &req->poll_update;
5368 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5370 if (sqe->ioprio || sqe->buf_index)
5372 flags = READ_ONCE(sqe->len);
5373 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5374 IORING_POLL_ADD_MULTI))
5376 /* meaningless without update */
5377 if (flags == IORING_POLL_ADD_MULTI)
5380 upd->old_user_data = READ_ONCE(sqe->addr);
5381 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5382 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5384 upd->new_user_data = READ_ONCE(sqe->off);
5385 if (!upd->update_user_data && upd->new_user_data)
5387 if (upd->update_events)
5388 upd->events = io_poll_parse_events(sqe, flags);
5389 else if (sqe->poll32_events)
5395 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5398 struct io_kiocb *req = wait->private;
5399 struct io_poll_iocb *poll = &req->poll;
5401 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5404 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5405 struct poll_table_struct *p)
5407 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5409 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5412 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5414 struct io_poll_iocb *poll = &req->poll;
5417 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5419 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5421 flags = READ_ONCE(sqe->len);
5422 if (flags & ~IORING_POLL_ADD_MULTI)
5425 poll->events = io_poll_parse_events(sqe, flags);
5429 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5431 struct io_poll_iocb *poll = &req->poll;
5432 struct io_ring_ctx *ctx = req->ctx;
5433 struct io_poll_table ipt;
5436 ipt.pt._qproc = io_poll_queue_proc;
5438 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5441 if (mask) { /* no async, we'd stolen it */
5443 io_poll_complete(req, mask);
5445 spin_unlock_irq(&ctx->completion_lock);
5448 io_cqring_ev_posted(ctx);
5449 if (poll->events & EPOLLONESHOT)
5455 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5457 struct io_ring_ctx *ctx = req->ctx;
5458 struct io_kiocb *preq;
5462 spin_lock_irq(&ctx->completion_lock);
5463 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5469 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5471 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5476 * Don't allow racy completion with singleshot, as we cannot safely
5477 * update those. For multishot, if we're racing with completion, just
5478 * let completion re-add it.
5480 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5481 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5485 /* we now have a detached poll request. reissue. */
5489 spin_unlock_irq(&ctx->completion_lock);
5491 io_req_complete(req, ret);
5494 /* only mask one event flags, keep behavior flags */
5495 if (req->poll_update.update_events) {
5496 preq->poll.events &= ~0xffff;
5497 preq->poll.events |= req->poll_update.events & 0xffff;
5498 preq->poll.events |= IO_POLL_UNMASK;
5500 if (req->poll_update.update_user_data)
5501 preq->user_data = req->poll_update.new_user_data;
5502 spin_unlock_irq(&ctx->completion_lock);
5504 /* complete update request, we're done with it */
5505 io_req_complete(req, ret);
5508 ret = io_poll_add(preq, issue_flags);
5511 io_req_complete(preq, ret);
5517 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5519 struct io_timeout_data *data = container_of(timer,
5520 struct io_timeout_data, timer);
5521 struct io_kiocb *req = data->req;
5522 struct io_ring_ctx *ctx = req->ctx;
5523 unsigned long flags;
5525 spin_lock_irqsave(&ctx->completion_lock, flags);
5526 list_del_init(&req->timeout.list);
5527 atomic_set(&req->ctx->cq_timeouts,
5528 atomic_read(&req->ctx->cq_timeouts) + 1);
5530 io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5531 io_commit_cqring(ctx);
5532 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5534 io_cqring_ev_posted(ctx);
5537 return HRTIMER_NORESTART;
5540 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5542 __must_hold(&ctx->completion_lock)
5544 struct io_timeout_data *io;
5545 struct io_kiocb *req;
5548 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5549 found = user_data == req->user_data;
5554 return ERR_PTR(-ENOENT);
5556 io = req->async_data;
5557 if (hrtimer_try_to_cancel(&io->timer) == -1)
5558 return ERR_PTR(-EALREADY);
5559 list_del_init(&req->timeout.list);
5563 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5564 __must_hold(&ctx->completion_lock)
5566 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5569 return PTR_ERR(req);
5572 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5573 io_put_req_deferred(req, 1);
5577 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5578 struct timespec64 *ts, enum hrtimer_mode mode)
5579 __must_hold(&ctx->completion_lock)
5581 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5582 struct io_timeout_data *data;
5585 return PTR_ERR(req);
5587 req->timeout.off = 0; /* noseq */
5588 data = req->async_data;
5589 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5590 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5591 data->timer.function = io_timeout_fn;
5592 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5596 static int io_timeout_remove_prep(struct io_kiocb *req,
5597 const struct io_uring_sqe *sqe)
5599 struct io_timeout_rem *tr = &req->timeout_rem;
5601 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5603 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5605 if (sqe->ioprio || sqe->buf_index || sqe->len)
5608 tr->addr = READ_ONCE(sqe->addr);
5609 tr->flags = READ_ONCE(sqe->timeout_flags);
5610 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5611 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5613 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5615 } else if (tr->flags) {
5616 /* timeout removal doesn't support flags */
5623 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5625 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5630 * Remove or update an existing timeout command
5632 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5634 struct io_timeout_rem *tr = &req->timeout_rem;
5635 struct io_ring_ctx *ctx = req->ctx;
5638 spin_lock_irq(&ctx->completion_lock);
5639 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5640 ret = io_timeout_cancel(ctx, tr->addr);
5642 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5643 io_translate_timeout_mode(tr->flags));
5645 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5646 io_commit_cqring(ctx);
5647 spin_unlock_irq(&ctx->completion_lock);
5648 io_cqring_ev_posted(ctx);
5655 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5656 bool is_timeout_link)
5658 struct io_timeout_data *data;
5660 u32 off = READ_ONCE(sqe->off);
5662 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5664 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5666 if (off && is_timeout_link)
5668 flags = READ_ONCE(sqe->timeout_flags);
5669 if (flags & ~IORING_TIMEOUT_ABS)
5672 req->timeout.off = off;
5673 if (unlikely(off && !req->ctx->off_timeout_used))
5674 req->ctx->off_timeout_used = true;
5676 if (!req->async_data && io_alloc_async_data(req))
5679 data = req->async_data;
5682 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5685 data->mode = io_translate_timeout_mode(flags);
5686 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5687 if (is_timeout_link)
5688 io_req_track_inflight(req);
5692 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5694 struct io_ring_ctx *ctx = req->ctx;
5695 struct io_timeout_data *data = req->async_data;
5696 struct list_head *entry;
5697 u32 tail, off = req->timeout.off;
5699 spin_lock_irq(&ctx->completion_lock);
5702 * sqe->off holds how many events that need to occur for this
5703 * timeout event to be satisfied. If it isn't set, then this is
5704 * a pure timeout request, sequence isn't used.
5706 if (io_is_timeout_noseq(req)) {
5707 entry = ctx->timeout_list.prev;
5711 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5712 req->timeout.target_seq = tail + off;
5714 /* Update the last seq here in case io_flush_timeouts() hasn't.
5715 * This is safe because ->completion_lock is held, and submissions
5716 * and completions are never mixed in the same ->completion_lock section.
5718 ctx->cq_last_tm_flush = tail;
5721 * Insertion sort, ensuring the first entry in the list is always
5722 * the one we need first.
5724 list_for_each_prev(entry, &ctx->timeout_list) {
5725 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5728 if (io_is_timeout_noseq(nxt))
5730 /* nxt.seq is behind @tail, otherwise would've been completed */
5731 if (off >= nxt->timeout.target_seq - tail)
5735 list_add(&req->timeout.list, entry);
5736 data->timer.function = io_timeout_fn;
5737 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5738 spin_unlock_irq(&ctx->completion_lock);
5742 struct io_cancel_data {
5743 struct io_ring_ctx *ctx;
5747 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5749 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5750 struct io_cancel_data *cd = data;
5752 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5755 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5756 struct io_ring_ctx *ctx)
5758 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5759 enum io_wq_cancel cancel_ret;
5762 if (!tctx || !tctx->io_wq)
5765 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5766 switch (cancel_ret) {
5767 case IO_WQ_CANCEL_OK:
5770 case IO_WQ_CANCEL_RUNNING:
5773 case IO_WQ_CANCEL_NOTFOUND:
5781 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5782 struct io_kiocb *req, __u64 sqe_addr,
5785 unsigned long flags;
5788 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5789 spin_lock_irqsave(&ctx->completion_lock, flags);
5792 ret = io_timeout_cancel(ctx, sqe_addr);
5795 ret = io_poll_cancel(ctx, sqe_addr, false);
5799 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5800 io_commit_cqring(ctx);
5801 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5802 io_cqring_ev_posted(ctx);
5808 static int io_async_cancel_prep(struct io_kiocb *req,
5809 const struct io_uring_sqe *sqe)
5811 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5813 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5815 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5818 req->cancel.addr = READ_ONCE(sqe->addr);
5822 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5824 struct io_ring_ctx *ctx = req->ctx;
5825 u64 sqe_addr = req->cancel.addr;
5826 struct io_tctx_node *node;
5829 /* tasks should wait for their io-wq threads, so safe w/o sync */
5830 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5831 spin_lock_irq(&ctx->completion_lock);
5834 ret = io_timeout_cancel(ctx, sqe_addr);
5837 ret = io_poll_cancel(ctx, sqe_addr, false);
5840 spin_unlock_irq(&ctx->completion_lock);
5842 /* slow path, try all io-wq's */
5843 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5845 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5846 struct io_uring_task *tctx = node->task->io_uring;
5848 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5852 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5854 spin_lock_irq(&ctx->completion_lock);
5856 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5857 io_commit_cqring(ctx);
5858 spin_unlock_irq(&ctx->completion_lock);
5859 io_cqring_ev_posted(ctx);
5867 static int io_rsrc_update_prep(struct io_kiocb *req,
5868 const struct io_uring_sqe *sqe)
5870 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5872 if (sqe->ioprio || sqe->rw_flags)
5875 req->rsrc_update.offset = READ_ONCE(sqe->off);
5876 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5877 if (!req->rsrc_update.nr_args)
5879 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5883 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5885 struct io_ring_ctx *ctx = req->ctx;
5886 struct io_uring_rsrc_update2 up;
5889 if (issue_flags & IO_URING_F_NONBLOCK)
5892 up.offset = req->rsrc_update.offset;
5893 up.data = req->rsrc_update.arg;
5898 mutex_lock(&ctx->uring_lock);
5899 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5900 &up, req->rsrc_update.nr_args);
5901 mutex_unlock(&ctx->uring_lock);
5905 __io_req_complete(req, issue_flags, ret, 0);
5909 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5911 switch (req->opcode) {
5914 case IORING_OP_READV:
5915 case IORING_OP_READ_FIXED:
5916 case IORING_OP_READ:
5917 return io_read_prep(req, sqe);
5918 case IORING_OP_WRITEV:
5919 case IORING_OP_WRITE_FIXED:
5920 case IORING_OP_WRITE:
5921 return io_write_prep(req, sqe);
5922 case IORING_OP_POLL_ADD:
5923 return io_poll_add_prep(req, sqe);
5924 case IORING_OP_POLL_REMOVE:
5925 return io_poll_update_prep(req, sqe);
5926 case IORING_OP_FSYNC:
5927 return io_fsync_prep(req, sqe);
5928 case IORING_OP_SYNC_FILE_RANGE:
5929 return io_sfr_prep(req, sqe);
5930 case IORING_OP_SENDMSG:
5931 case IORING_OP_SEND:
5932 return io_sendmsg_prep(req, sqe);
5933 case IORING_OP_RECVMSG:
5934 case IORING_OP_RECV:
5935 return io_recvmsg_prep(req, sqe);
5936 case IORING_OP_CONNECT:
5937 return io_connect_prep(req, sqe);
5938 case IORING_OP_TIMEOUT:
5939 return io_timeout_prep(req, sqe, false);
5940 case IORING_OP_TIMEOUT_REMOVE:
5941 return io_timeout_remove_prep(req, sqe);
5942 case IORING_OP_ASYNC_CANCEL:
5943 return io_async_cancel_prep(req, sqe);
5944 case IORING_OP_LINK_TIMEOUT:
5945 return io_timeout_prep(req, sqe, true);
5946 case IORING_OP_ACCEPT:
5947 return io_accept_prep(req, sqe);
5948 case IORING_OP_FALLOCATE:
5949 return io_fallocate_prep(req, sqe);
5950 case IORING_OP_OPENAT:
5951 return io_openat_prep(req, sqe);
5952 case IORING_OP_CLOSE:
5953 return io_close_prep(req, sqe);
5954 case IORING_OP_FILES_UPDATE:
5955 return io_rsrc_update_prep(req, sqe);
5956 case IORING_OP_STATX:
5957 return io_statx_prep(req, sqe);
5958 case IORING_OP_FADVISE:
5959 return io_fadvise_prep(req, sqe);
5960 case IORING_OP_MADVISE:
5961 return io_madvise_prep(req, sqe);
5962 case IORING_OP_OPENAT2:
5963 return io_openat2_prep(req, sqe);
5964 case IORING_OP_EPOLL_CTL:
5965 return io_epoll_ctl_prep(req, sqe);
5966 case IORING_OP_SPLICE:
5967 return io_splice_prep(req, sqe);
5968 case IORING_OP_PROVIDE_BUFFERS:
5969 return io_provide_buffers_prep(req, sqe);
5970 case IORING_OP_REMOVE_BUFFERS:
5971 return io_remove_buffers_prep(req, sqe);
5973 return io_tee_prep(req, sqe);
5974 case IORING_OP_SHUTDOWN:
5975 return io_shutdown_prep(req, sqe);
5976 case IORING_OP_RENAMEAT:
5977 return io_renameat_prep(req, sqe);
5978 case IORING_OP_UNLINKAT:
5979 return io_unlinkat_prep(req, sqe);
5982 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5987 static int io_req_prep_async(struct io_kiocb *req)
5989 if (!io_op_defs[req->opcode].needs_async_setup)
5991 if (WARN_ON_ONCE(req->async_data))
5993 if (io_alloc_async_data(req))
5996 switch (req->opcode) {
5997 case IORING_OP_READV:
5998 return io_rw_prep_async(req, READ);
5999 case IORING_OP_WRITEV:
6000 return io_rw_prep_async(req, WRITE);
6001 case IORING_OP_SENDMSG:
6002 return io_sendmsg_prep_async(req);
6003 case IORING_OP_RECVMSG:
6004 return io_recvmsg_prep_async(req);
6005 case IORING_OP_CONNECT:
6006 return io_connect_prep_async(req);
6008 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6013 static u32 io_get_sequence(struct io_kiocb *req)
6015 u32 seq = req->ctx->cached_sq_head;
6017 /* need original cached_sq_head, but it was increased for each req */
6018 io_for_each_link(req, req)
6023 static bool io_drain_req(struct io_kiocb *req)
6025 struct io_kiocb *pos;
6026 struct io_ring_ctx *ctx = req->ctx;
6027 struct io_defer_entry *de;
6032 * If we need to drain a request in the middle of a link, drain the
6033 * head request and the next request/link after the current link.
6034 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6035 * maintained for every request of our link.
6037 if (ctx->drain_next) {
6038 req->flags |= REQ_F_IO_DRAIN;
6039 ctx->drain_next = false;
6041 /* not interested in head, start from the first linked */
6042 io_for_each_link(pos, req->link) {
6043 if (pos->flags & REQ_F_IO_DRAIN) {
6044 ctx->drain_next = true;
6045 req->flags |= REQ_F_IO_DRAIN;
6050 /* Still need defer if there is pending req in defer list. */
6051 if (likely(list_empty_careful(&ctx->defer_list) &&
6052 !(req->flags & REQ_F_IO_DRAIN))) {
6053 ctx->drain_active = false;
6057 seq = io_get_sequence(req);
6058 /* Still a chance to pass the sequence check */
6059 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6062 ret = io_req_prep_async(req);
6065 io_prep_async_link(req);
6066 de = kmalloc(sizeof(*de), GFP_KERNEL);
6070 io_req_complete_failed(req, ret);
6074 spin_lock_irq(&ctx->completion_lock);
6075 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6076 spin_unlock_irq(&ctx->completion_lock);
6078 io_queue_async_work(req);
6082 trace_io_uring_defer(ctx, req, req->user_data);
6085 list_add_tail(&de->list, &ctx->defer_list);
6086 spin_unlock_irq(&ctx->completion_lock);
6090 static void io_clean_op(struct io_kiocb *req)
6092 if (req->flags & REQ_F_BUFFER_SELECTED) {
6093 switch (req->opcode) {
6094 case IORING_OP_READV:
6095 case IORING_OP_READ_FIXED:
6096 case IORING_OP_READ:
6097 kfree((void *)(unsigned long)req->rw.addr);
6099 case IORING_OP_RECVMSG:
6100 case IORING_OP_RECV:
6101 kfree(req->sr_msg.kbuf);
6106 if (req->flags & REQ_F_NEED_CLEANUP) {
6107 switch (req->opcode) {
6108 case IORING_OP_READV:
6109 case IORING_OP_READ_FIXED:
6110 case IORING_OP_READ:
6111 case IORING_OP_WRITEV:
6112 case IORING_OP_WRITE_FIXED:
6113 case IORING_OP_WRITE: {
6114 struct io_async_rw *io = req->async_data;
6116 kfree(io->free_iovec);
6119 case IORING_OP_RECVMSG:
6120 case IORING_OP_SENDMSG: {
6121 struct io_async_msghdr *io = req->async_data;
6123 kfree(io->free_iov);
6126 case IORING_OP_SPLICE:
6128 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6129 io_put_file(req->splice.file_in);
6131 case IORING_OP_OPENAT:
6132 case IORING_OP_OPENAT2:
6133 if (req->open.filename)
6134 putname(req->open.filename);
6136 case IORING_OP_RENAMEAT:
6137 putname(req->rename.oldpath);
6138 putname(req->rename.newpath);
6140 case IORING_OP_UNLINKAT:
6141 putname(req->unlink.filename);
6145 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6146 kfree(req->apoll->double_poll);
6150 if (req->flags & REQ_F_INFLIGHT) {
6151 struct io_uring_task *tctx = req->task->io_uring;
6153 atomic_dec(&tctx->inflight_tracked);
6155 if (req->flags & REQ_F_CREDS)
6156 put_cred(req->creds);
6158 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6161 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6163 struct io_ring_ctx *ctx = req->ctx;
6164 const struct cred *creds = NULL;
6167 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6168 creds = override_creds(req->creds);
6170 switch (req->opcode) {
6172 ret = io_nop(req, issue_flags);
6174 case IORING_OP_READV:
6175 case IORING_OP_READ_FIXED:
6176 case IORING_OP_READ:
6177 ret = io_read(req, issue_flags);
6179 case IORING_OP_WRITEV:
6180 case IORING_OP_WRITE_FIXED:
6181 case IORING_OP_WRITE:
6182 ret = io_write(req, issue_flags);
6184 case IORING_OP_FSYNC:
6185 ret = io_fsync(req, issue_flags);
6187 case IORING_OP_POLL_ADD:
6188 ret = io_poll_add(req, issue_flags);
6190 case IORING_OP_POLL_REMOVE:
6191 ret = io_poll_update(req, issue_flags);
6193 case IORING_OP_SYNC_FILE_RANGE:
6194 ret = io_sync_file_range(req, issue_flags);
6196 case IORING_OP_SENDMSG:
6197 ret = io_sendmsg(req, issue_flags);
6199 case IORING_OP_SEND:
6200 ret = io_send(req, issue_flags);
6202 case IORING_OP_RECVMSG:
6203 ret = io_recvmsg(req, issue_flags);
6205 case IORING_OP_RECV:
6206 ret = io_recv(req, issue_flags);
6208 case IORING_OP_TIMEOUT:
6209 ret = io_timeout(req, issue_flags);
6211 case IORING_OP_TIMEOUT_REMOVE:
6212 ret = io_timeout_remove(req, issue_flags);
6214 case IORING_OP_ACCEPT:
6215 ret = io_accept(req, issue_flags);
6217 case IORING_OP_CONNECT:
6218 ret = io_connect(req, issue_flags);
6220 case IORING_OP_ASYNC_CANCEL:
6221 ret = io_async_cancel(req, issue_flags);
6223 case IORING_OP_FALLOCATE:
6224 ret = io_fallocate(req, issue_flags);
6226 case IORING_OP_OPENAT:
6227 ret = io_openat(req, issue_flags);
6229 case IORING_OP_CLOSE:
6230 ret = io_close(req, issue_flags);
6232 case IORING_OP_FILES_UPDATE:
6233 ret = io_files_update(req, issue_flags);
6235 case IORING_OP_STATX:
6236 ret = io_statx(req, issue_flags);
6238 case IORING_OP_FADVISE:
6239 ret = io_fadvise(req, issue_flags);
6241 case IORING_OP_MADVISE:
6242 ret = io_madvise(req, issue_flags);
6244 case IORING_OP_OPENAT2:
6245 ret = io_openat2(req, issue_flags);
6247 case IORING_OP_EPOLL_CTL:
6248 ret = io_epoll_ctl(req, issue_flags);
6250 case IORING_OP_SPLICE:
6251 ret = io_splice(req, issue_flags);
6253 case IORING_OP_PROVIDE_BUFFERS:
6254 ret = io_provide_buffers(req, issue_flags);
6256 case IORING_OP_REMOVE_BUFFERS:
6257 ret = io_remove_buffers(req, issue_flags);
6260 ret = io_tee(req, issue_flags);
6262 case IORING_OP_SHUTDOWN:
6263 ret = io_shutdown(req, issue_flags);
6265 case IORING_OP_RENAMEAT:
6266 ret = io_renameat(req, issue_flags);
6268 case IORING_OP_UNLINKAT:
6269 ret = io_unlinkat(req, issue_flags);
6277 revert_creds(creds);
6280 /* If the op doesn't have a file, we're not polling for it */
6281 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6282 io_iopoll_req_issued(req);
6287 static void io_wq_submit_work(struct io_wq_work *work)
6289 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6290 struct io_kiocb *timeout;
6293 timeout = io_prep_linked_timeout(req);
6295 io_queue_linked_timeout(timeout);
6297 if (work->flags & IO_WQ_WORK_CANCEL)
6302 ret = io_issue_sqe(req, 0);
6304 * We can get EAGAIN for polled IO even though we're
6305 * forcing a sync submission from here, since we can't
6306 * wait for request slots on the block side.
6314 /* avoid locking problems by failing it from a clean context */
6316 /* io-wq is going to take one down */
6318 io_req_task_queue_fail(req, ret);
6322 #define FFS_ASYNC_READ 0x1UL
6323 #define FFS_ASYNC_WRITE 0x2UL
6325 #define FFS_ISREG 0x4UL
6327 #define FFS_ISREG 0x0UL
6329 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6331 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6334 struct io_fixed_file *table_l2;
6336 table_l2 = table->files[i >> IORING_FILE_TABLE_SHIFT];
6337 return &table_l2[i & IORING_FILE_TABLE_MASK];
6340 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6343 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6345 return (struct file *) (slot->file_ptr & FFS_MASK);
6348 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6350 unsigned long file_ptr = (unsigned long) file;
6352 if (__io_file_supports_async(file, READ))
6353 file_ptr |= FFS_ASYNC_READ;
6354 if (__io_file_supports_async(file, WRITE))
6355 file_ptr |= FFS_ASYNC_WRITE;
6356 if (S_ISREG(file_inode(file)->i_mode))
6357 file_ptr |= FFS_ISREG;
6358 file_slot->file_ptr = file_ptr;
6361 static struct file *io_file_get(struct io_submit_state *state,
6362 struct io_kiocb *req, int fd, bool fixed)
6364 struct io_ring_ctx *ctx = req->ctx;
6368 unsigned long file_ptr;
6370 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6372 fd = array_index_nospec(fd, ctx->nr_user_files);
6373 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6374 file = (struct file *) (file_ptr & FFS_MASK);
6375 file_ptr &= ~FFS_MASK;
6376 /* mask in overlapping REQ_F and FFS bits */
6377 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6378 io_req_set_rsrc_node(req);
6380 trace_io_uring_file_get(ctx, fd);
6381 file = __io_file_get(state, fd);
6383 /* we don't allow fixed io_uring files */
6384 if (file && unlikely(file->f_op == &io_uring_fops))
6385 io_req_track_inflight(req);
6391 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6393 struct io_timeout_data *data = container_of(timer,
6394 struct io_timeout_data, timer);
6395 struct io_kiocb *prev, *req = data->req;
6396 struct io_ring_ctx *ctx = req->ctx;
6397 unsigned long flags;
6399 spin_lock_irqsave(&ctx->completion_lock, flags);
6400 prev = req->timeout.head;
6401 req->timeout.head = NULL;
6404 * We don't expect the list to be empty, that will only happen if we
6405 * race with the completion of the linked work.
6408 io_remove_next_linked(prev);
6409 if (!req_ref_inc_not_zero(prev))
6412 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6415 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6416 io_put_req_deferred(prev, 1);
6417 io_put_req_deferred(req, 1);
6419 io_req_complete_post(req, -ETIME, 0);
6421 return HRTIMER_NORESTART;
6424 static void io_queue_linked_timeout(struct io_kiocb *req)
6426 struct io_ring_ctx *ctx = req->ctx;
6428 spin_lock_irq(&ctx->completion_lock);
6430 * If the back reference is NULL, then our linked request finished
6431 * before we got a chance to setup the timer
6433 if (req->timeout.head) {
6434 struct io_timeout_data *data = req->async_data;
6436 data->timer.function = io_link_timeout_fn;
6437 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6440 spin_unlock_irq(&ctx->completion_lock);
6441 /* drop submission reference */
6445 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6447 struct io_kiocb *nxt = req->link;
6449 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6450 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6453 nxt->timeout.head = req;
6454 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6455 req->flags |= REQ_F_LINK_TIMEOUT;
6459 static void __io_queue_sqe(struct io_kiocb *req)
6461 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6465 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6468 * We async punt it if the file wasn't marked NOWAIT, or if the file
6469 * doesn't support non-blocking read/write attempts
6472 /* drop submission reference */
6473 if (req->flags & REQ_F_COMPLETE_INLINE) {
6474 struct io_ring_ctx *ctx = req->ctx;
6475 struct io_comp_state *cs = &ctx->submit_state.comp;
6477 cs->reqs[cs->nr++] = req;
6478 if (cs->nr == ARRAY_SIZE(cs->reqs))
6479 io_submit_flush_completions(ctx);
6483 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6484 switch (io_arm_poll_handler(req)) {
6485 case IO_APOLL_READY:
6487 case IO_APOLL_ABORTED:
6489 * Queued up for async execution, worker will release
6490 * submit reference when the iocb is actually submitted.
6492 io_queue_async_work(req);
6496 io_req_complete_failed(req, ret);
6499 io_queue_linked_timeout(linked_timeout);
6502 static inline void io_queue_sqe(struct io_kiocb *req)
6504 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6507 if (likely(!(req->flags & REQ_F_FORCE_ASYNC))) {
6508 __io_queue_sqe(req);
6510 int ret = io_req_prep_async(req);
6513 io_req_complete_failed(req, ret);
6515 io_queue_async_work(req);
6520 * Check SQE restrictions (opcode and flags).
6522 * Returns 'true' if SQE is allowed, 'false' otherwise.
6524 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6525 struct io_kiocb *req,
6526 unsigned int sqe_flags)
6528 if (likely(!ctx->restricted))
6531 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6534 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6535 ctx->restrictions.sqe_flags_required)
6538 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6539 ctx->restrictions.sqe_flags_required))
6545 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6546 const struct io_uring_sqe *sqe)
6548 struct io_submit_state *state;
6549 unsigned int sqe_flags;
6550 int personality, ret = 0;
6552 req->opcode = READ_ONCE(sqe->opcode);
6553 /* same numerical values with corresponding REQ_F_*, safe to copy */
6554 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6555 req->user_data = READ_ONCE(sqe->user_data);
6557 req->fixed_rsrc_refs = NULL;
6558 /* one is dropped after submission, the other at completion */
6559 atomic_set(&req->refs, 2);
6560 req->task = current;
6562 /* enforce forwards compatibility on users */
6563 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6565 if (unlikely(req->opcode >= IORING_OP_LAST))
6567 if (!io_check_restriction(ctx, req, sqe_flags))
6570 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6571 !io_op_defs[req->opcode].buffer_select)
6573 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6574 ctx->drain_active = true;
6576 personality = READ_ONCE(sqe->personality);
6578 req->creds = xa_load(&ctx->personalities, personality);
6581 get_cred(req->creds);
6582 req->flags |= REQ_F_CREDS;
6584 state = &ctx->submit_state;
6587 * Plug now if we have more than 1 IO left after this, and the target
6588 * is potentially a read/write to block based storage.
6590 if (!state->plug_started && state->ios_left > 1 &&
6591 io_op_defs[req->opcode].plug) {
6592 blk_start_plug(&state->plug);
6593 state->plug_started = true;
6596 if (io_op_defs[req->opcode].needs_file) {
6597 bool fixed = req->flags & REQ_F_FIXED_FILE;
6599 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6600 if (unlikely(!req->file))
6608 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6609 const struct io_uring_sqe *sqe)
6611 struct io_submit_link *link = &ctx->submit_state.link;
6614 ret = io_init_req(ctx, req, sqe);
6615 if (unlikely(ret)) {
6618 /* fail even hard links since we don't submit */
6619 req_set_fail(link->head);
6620 io_req_complete_failed(link->head, -ECANCELED);
6623 io_req_complete_failed(req, ret);
6627 ret = io_req_prep(req, sqe);
6631 /* don't need @sqe from now on */
6632 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6634 ctx->flags & IORING_SETUP_SQPOLL);
6637 * If we already have a head request, queue this one for async
6638 * submittal once the head completes. If we don't have a head but
6639 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6640 * submitted sync once the chain is complete. If none of those
6641 * conditions are true (normal request), then just queue it.
6644 struct io_kiocb *head = link->head;
6646 ret = io_req_prep_async(req);
6649 trace_io_uring_link(ctx, req, head);
6650 link->last->link = req;
6653 /* last request of a link, enqueue the link */
6654 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
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(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 this returns a pointer 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 unsigned head, mask = ctx->sq_entries - 1;
6720 unsigned sq_idx = ctx->cached_sq_head++ & mask;
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(ctx->sq_array[sq_idx]);
6731 if (likely(head < ctx->sq_entries))
6732 return &ctx->sq_sqes[head];
6734 /* drop invalid entries */
6736 WRITE_ONCE(ctx->rings->sq_dropped,
6737 READ_ONCE(ctx->rings->sq_dropped) + 1);
6741 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6743 struct io_uring_task *tctx;
6746 /* make sure SQ entry isn't read before tail */
6747 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6748 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6751 tctx = current->io_uring;
6752 tctx->cached_refs -= nr;
6753 if (unlikely(tctx->cached_refs < 0)) {
6754 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
6756 percpu_counter_add(&tctx->inflight, refill);
6757 refcount_add(refill, ¤t->usage);
6758 tctx->cached_refs += refill;
6760 io_submit_state_start(&ctx->submit_state, nr);
6762 while (submitted < nr) {
6763 const struct io_uring_sqe *sqe;
6764 struct io_kiocb *req;
6766 req = io_alloc_req(ctx);
6767 if (unlikely(!req)) {
6769 submitted = -EAGAIN;
6772 sqe = io_get_sqe(ctx);
6773 if (unlikely(!sqe)) {
6774 kmem_cache_free(req_cachep, req);
6777 /* will complete beyond this point, count as submitted */
6779 if (io_submit_sqe(ctx, req, sqe))
6783 if (unlikely(submitted != nr)) {
6784 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6785 int unused = nr - ref_used;
6787 current->io_uring->cached_refs += unused;
6788 percpu_ref_put_many(&ctx->refs, unused);
6791 io_submit_state_end(&ctx->submit_state, ctx);
6792 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6793 io_commit_sqring(ctx);
6798 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
6800 return READ_ONCE(sqd->state);
6803 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6805 /* Tell userspace we may need a wakeup call */
6806 spin_lock_irq(&ctx->completion_lock);
6807 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6808 spin_unlock_irq(&ctx->completion_lock);
6811 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6813 spin_lock_irq(&ctx->completion_lock);
6814 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6815 spin_unlock_irq(&ctx->completion_lock);
6818 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6820 unsigned int to_submit;
6823 to_submit = io_sqring_entries(ctx);
6824 /* if we're handling multiple rings, cap submit size for fairness */
6825 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
6826 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
6828 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6829 unsigned nr_events = 0;
6830 const struct cred *creds = NULL;
6832 if (ctx->sq_creds != current_cred())
6833 creds = override_creds(ctx->sq_creds);
6835 mutex_lock(&ctx->uring_lock);
6836 if (!list_empty(&ctx->iopoll_list))
6837 io_do_iopoll(ctx, &nr_events, 0, true);
6840 * Don't submit if refs are dying, good for io_uring_register(),
6841 * but also it is relied upon by io_ring_exit_work()
6843 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6844 !(ctx->flags & IORING_SETUP_R_DISABLED))
6845 ret = io_submit_sqes(ctx, to_submit);
6846 mutex_unlock(&ctx->uring_lock);
6848 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
6849 wake_up(&ctx->sqo_sq_wait);
6851 revert_creds(creds);
6857 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6859 struct io_ring_ctx *ctx;
6860 unsigned sq_thread_idle = 0;
6862 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6863 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6864 sqd->sq_thread_idle = sq_thread_idle;
6867 static bool io_sqd_handle_event(struct io_sq_data *sqd)
6869 bool did_sig = false;
6870 struct ksignal ksig;
6872 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6873 signal_pending(current)) {
6874 mutex_unlock(&sqd->lock);
6875 if (signal_pending(current))
6876 did_sig = get_signal(&ksig);
6878 mutex_lock(&sqd->lock);
6880 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6883 static int io_sq_thread(void *data)
6885 struct io_sq_data *sqd = data;
6886 struct io_ring_ctx *ctx;
6887 unsigned long timeout = 0;
6888 char buf[TASK_COMM_LEN];
6891 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6892 set_task_comm(current, buf);
6894 if (sqd->sq_cpu != -1)
6895 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6897 set_cpus_allowed_ptr(current, cpu_online_mask);
6898 current->flags |= PF_NO_SETAFFINITY;
6900 mutex_lock(&sqd->lock);
6902 bool cap_entries, sqt_spin = false;
6904 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
6905 if (io_sqd_handle_event(sqd))
6907 timeout = jiffies + sqd->sq_thread_idle;
6910 cap_entries = !list_is_singular(&sqd->ctx_list);
6911 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6912 int ret = __io_sq_thread(ctx, cap_entries);
6914 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6917 if (io_run_task_work())
6920 if (sqt_spin || !time_after(jiffies, timeout)) {
6923 timeout = jiffies + sqd->sq_thread_idle;
6927 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6928 if (!io_sqd_events_pending(sqd) && !current->task_works) {
6929 bool needs_sched = true;
6931 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6932 io_ring_set_wakeup_flag(ctx);
6934 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6935 !list_empty_careful(&ctx->iopoll_list)) {
6936 needs_sched = false;
6939 if (io_sqring_entries(ctx)) {
6940 needs_sched = false;
6946 mutex_unlock(&sqd->lock);
6948 mutex_lock(&sqd->lock);
6950 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6951 io_ring_clear_wakeup_flag(ctx);
6954 finish_wait(&sqd->wait, &wait);
6955 timeout = jiffies + sqd->sq_thread_idle;
6958 io_uring_cancel_generic(true, sqd);
6960 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6961 io_ring_set_wakeup_flag(ctx);
6963 mutex_unlock(&sqd->lock);
6965 complete(&sqd->exited);
6969 struct io_wait_queue {
6970 struct wait_queue_entry wq;
6971 struct io_ring_ctx *ctx;
6973 unsigned nr_timeouts;
6976 static inline bool io_should_wake(struct io_wait_queue *iowq)
6978 struct io_ring_ctx *ctx = iowq->ctx;
6981 * Wake up if we have enough events, or if a timeout occurred since we
6982 * started waiting. For timeouts, we always want to return to userspace,
6983 * regardless of event count.
6985 return io_cqring_events(ctx) >= iowq->to_wait ||
6986 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6989 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6990 int wake_flags, void *key)
6992 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6996 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6997 * the task, and the next invocation will do it.
6999 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7000 return autoremove_wake_function(curr, mode, wake_flags, key);
7004 static int io_run_task_work_sig(void)
7006 if (io_run_task_work())
7008 if (!signal_pending(current))
7010 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7011 return -ERESTARTSYS;
7015 /* when returns >0, the caller should retry */
7016 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7017 struct io_wait_queue *iowq,
7018 signed long *timeout)
7022 /* make sure we run task_work before checking for signals */
7023 ret = io_run_task_work_sig();
7024 if (ret || io_should_wake(iowq))
7026 /* let the caller flush overflows, retry */
7027 if (test_bit(0, &ctx->check_cq_overflow))
7030 *timeout = schedule_timeout(*timeout);
7031 return !*timeout ? -ETIME : 1;
7035 * Wait until events become available, if we don't already have some. The
7036 * application must reap them itself, as they reside on the shared cq ring.
7038 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7039 const sigset_t __user *sig, size_t sigsz,
7040 struct __kernel_timespec __user *uts)
7042 struct io_wait_queue iowq = {
7045 .func = io_wake_function,
7046 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7049 .to_wait = min_events,
7051 struct io_rings *rings = ctx->rings;
7052 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7056 io_cqring_overflow_flush(ctx, false);
7057 if (io_cqring_events(ctx) >= min_events)
7059 if (!io_run_task_work())
7064 #ifdef CONFIG_COMPAT
7065 if (in_compat_syscall())
7066 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7070 ret = set_user_sigmask(sig, sigsz);
7077 struct timespec64 ts;
7079 if (get_timespec64(&ts, uts))
7081 timeout = timespec64_to_jiffies(&ts);
7084 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7085 trace_io_uring_cqring_wait(ctx, min_events);
7087 /* if we can't even flush overflow, don't wait for more */
7088 if (!io_cqring_overflow_flush(ctx, false)) {
7092 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7093 TASK_INTERRUPTIBLE);
7094 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7095 finish_wait(&ctx->cq_wait, &iowq.wq);
7099 restore_saved_sigmask_unless(ret == -EINTR);
7101 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7104 static void io_free_page_table(void **table, size_t size)
7106 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7108 for (i = 0; i < nr_tables; i++)
7113 static void **io_alloc_page_table(size_t size)
7115 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7116 size_t init_size = size;
7119 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL);
7123 for (i = 0; i < nr_tables; i++) {
7124 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7126 table[i] = kzalloc(this_size, GFP_KERNEL);
7128 io_free_page_table(table, init_size);
7136 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7138 spin_lock_bh(&ctx->rsrc_ref_lock);
7141 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7143 spin_unlock_bh(&ctx->rsrc_ref_lock);
7146 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7148 percpu_ref_exit(&ref_node->refs);
7152 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7153 struct io_rsrc_data *data_to_kill)
7155 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7156 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7159 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7161 rsrc_node->rsrc_data = data_to_kill;
7162 io_rsrc_ref_lock(ctx);
7163 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7164 io_rsrc_ref_unlock(ctx);
7166 atomic_inc(&data_to_kill->refs);
7167 percpu_ref_kill(&rsrc_node->refs);
7168 ctx->rsrc_node = NULL;
7171 if (!ctx->rsrc_node) {
7172 ctx->rsrc_node = ctx->rsrc_backup_node;
7173 ctx->rsrc_backup_node = NULL;
7177 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7179 if (ctx->rsrc_backup_node)
7181 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7182 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7185 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7189 /* As we may drop ->uring_lock, other task may have started quiesce */
7193 data->quiesce = true;
7195 ret = io_rsrc_node_switch_start(ctx);
7198 io_rsrc_node_switch(ctx, data);
7200 /* kill initial ref, already quiesced if zero */
7201 if (atomic_dec_and_test(&data->refs))
7203 flush_delayed_work(&ctx->rsrc_put_work);
7204 ret = wait_for_completion_interruptible(&data->done);
7208 atomic_inc(&data->refs);
7209 /* wait for all works potentially completing data->done */
7210 flush_delayed_work(&ctx->rsrc_put_work);
7211 reinit_completion(&data->done);
7213 mutex_unlock(&ctx->uring_lock);
7214 ret = io_run_task_work_sig();
7215 mutex_lock(&ctx->uring_lock);
7217 data->quiesce = false;
7222 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7224 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7225 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7227 return &data->tags[table_idx][off];
7230 static void io_rsrc_data_free(struct io_rsrc_data *data)
7232 size_t size = data->nr * sizeof(data->tags[0][0]);
7235 io_free_page_table((void **)data->tags, size);
7239 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7240 u64 __user *utags, unsigned nr,
7241 struct io_rsrc_data **pdata)
7243 struct io_rsrc_data *data;
7247 data = kzalloc(sizeof(*data), GFP_KERNEL);
7250 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7258 data->do_put = do_put;
7261 for (i = 0; i < nr; i++) {
7262 u64 *tag_slot = io_get_tag_slot(data, i);
7264 if (copy_from_user(tag_slot, &utags[i],
7270 atomic_set(&data->refs, 1);
7271 init_completion(&data->done);
7275 io_rsrc_data_free(data);
7279 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7281 size_t size = nr_files * sizeof(struct io_fixed_file);
7283 table->files = (struct io_fixed_file **)io_alloc_page_table(size);
7284 return !!table->files;
7287 static void io_free_file_tables(struct io_file_table *table, unsigned nr_files)
7289 size_t size = nr_files * sizeof(struct io_fixed_file);
7291 io_free_page_table((void **)table->files, size);
7292 table->files = NULL;
7295 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7297 #if defined(CONFIG_UNIX)
7298 if (ctx->ring_sock) {
7299 struct sock *sock = ctx->ring_sock->sk;
7300 struct sk_buff *skb;
7302 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7308 for (i = 0; i < ctx->nr_user_files; i++) {
7311 file = io_file_from_index(ctx, i);
7316 io_free_file_tables(&ctx->file_table, ctx->nr_user_files);
7317 io_rsrc_data_free(ctx->file_data);
7318 ctx->file_data = NULL;
7319 ctx->nr_user_files = 0;
7322 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7326 if (!ctx->file_data)
7328 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7330 __io_sqe_files_unregister(ctx);
7334 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7335 __releases(&sqd->lock)
7337 WARN_ON_ONCE(sqd->thread == current);
7340 * Do the dance but not conditional clear_bit() because it'd race with
7341 * other threads incrementing park_pending and setting the bit.
7343 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7344 if (atomic_dec_return(&sqd->park_pending))
7345 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7346 mutex_unlock(&sqd->lock);
7349 static void io_sq_thread_park(struct io_sq_data *sqd)
7350 __acquires(&sqd->lock)
7352 WARN_ON_ONCE(sqd->thread == current);
7354 atomic_inc(&sqd->park_pending);
7355 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7356 mutex_lock(&sqd->lock);
7358 wake_up_process(sqd->thread);
7361 static void io_sq_thread_stop(struct io_sq_data *sqd)
7363 WARN_ON_ONCE(sqd->thread == current);
7364 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7366 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7367 mutex_lock(&sqd->lock);
7369 wake_up_process(sqd->thread);
7370 mutex_unlock(&sqd->lock);
7371 wait_for_completion(&sqd->exited);
7374 static void io_put_sq_data(struct io_sq_data *sqd)
7376 if (refcount_dec_and_test(&sqd->refs)) {
7377 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7379 io_sq_thread_stop(sqd);
7384 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7386 struct io_sq_data *sqd = ctx->sq_data;
7389 io_sq_thread_park(sqd);
7390 list_del_init(&ctx->sqd_list);
7391 io_sqd_update_thread_idle(sqd);
7392 io_sq_thread_unpark(sqd);
7394 io_put_sq_data(sqd);
7395 ctx->sq_data = NULL;
7399 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7401 struct io_ring_ctx *ctx_attach;
7402 struct io_sq_data *sqd;
7405 f = fdget(p->wq_fd);
7407 return ERR_PTR(-ENXIO);
7408 if (f.file->f_op != &io_uring_fops) {
7410 return ERR_PTR(-EINVAL);
7413 ctx_attach = f.file->private_data;
7414 sqd = ctx_attach->sq_data;
7417 return ERR_PTR(-EINVAL);
7419 if (sqd->task_tgid != current->tgid) {
7421 return ERR_PTR(-EPERM);
7424 refcount_inc(&sqd->refs);
7429 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7432 struct io_sq_data *sqd;
7435 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7436 sqd = io_attach_sq_data(p);
7441 /* fall through for EPERM case, setup new sqd/task */
7442 if (PTR_ERR(sqd) != -EPERM)
7446 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7448 return ERR_PTR(-ENOMEM);
7450 atomic_set(&sqd->park_pending, 0);
7451 refcount_set(&sqd->refs, 1);
7452 INIT_LIST_HEAD(&sqd->ctx_list);
7453 mutex_init(&sqd->lock);
7454 init_waitqueue_head(&sqd->wait);
7455 init_completion(&sqd->exited);
7459 #if defined(CONFIG_UNIX)
7461 * Ensure the UNIX gc is aware of our file set, so we are certain that
7462 * the io_uring can be safely unregistered on process exit, even if we have
7463 * loops in the file referencing.
7465 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7467 struct sock *sk = ctx->ring_sock->sk;
7468 struct scm_fp_list *fpl;
7469 struct sk_buff *skb;
7472 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7476 skb = alloc_skb(0, GFP_KERNEL);
7485 fpl->user = get_uid(current_user());
7486 for (i = 0; i < nr; i++) {
7487 struct file *file = io_file_from_index(ctx, i + offset);
7491 fpl->fp[nr_files] = get_file(file);
7492 unix_inflight(fpl->user, fpl->fp[nr_files]);
7497 fpl->max = SCM_MAX_FD;
7498 fpl->count = nr_files;
7499 UNIXCB(skb).fp = fpl;
7500 skb->destructor = unix_destruct_scm;
7501 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7502 skb_queue_head(&sk->sk_receive_queue, skb);
7504 for (i = 0; i < nr_files; i++)
7515 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7516 * causes regular reference counting to break down. We rely on the UNIX
7517 * garbage collection to take care of this problem for us.
7519 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7521 unsigned left, total;
7525 left = ctx->nr_user_files;
7527 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7529 ret = __io_sqe_files_scm(ctx, this_files, total);
7533 total += this_files;
7539 while (total < ctx->nr_user_files) {
7540 struct file *file = io_file_from_index(ctx, total);
7550 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7556 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7558 struct file *file = prsrc->file;
7559 #if defined(CONFIG_UNIX)
7560 struct sock *sock = ctx->ring_sock->sk;
7561 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7562 struct sk_buff *skb;
7565 __skb_queue_head_init(&list);
7568 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7569 * remove this entry and rearrange the file array.
7571 skb = skb_dequeue(head);
7573 struct scm_fp_list *fp;
7575 fp = UNIXCB(skb).fp;
7576 for (i = 0; i < fp->count; i++) {
7579 if (fp->fp[i] != file)
7582 unix_notinflight(fp->user, fp->fp[i]);
7583 left = fp->count - 1 - i;
7585 memmove(&fp->fp[i], &fp->fp[i + 1],
7586 left * sizeof(struct file *));
7593 __skb_queue_tail(&list, skb);
7603 __skb_queue_tail(&list, skb);
7605 skb = skb_dequeue(head);
7608 if (skb_peek(&list)) {
7609 spin_lock_irq(&head->lock);
7610 while ((skb = __skb_dequeue(&list)) != NULL)
7611 __skb_queue_tail(head, skb);
7612 spin_unlock_irq(&head->lock);
7619 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7621 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7622 struct io_ring_ctx *ctx = rsrc_data->ctx;
7623 struct io_rsrc_put *prsrc, *tmp;
7625 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7626 list_del(&prsrc->list);
7629 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7631 io_ring_submit_lock(ctx, lock_ring);
7632 spin_lock_irq(&ctx->completion_lock);
7633 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7635 io_commit_cqring(ctx);
7636 spin_unlock_irq(&ctx->completion_lock);
7637 io_cqring_ev_posted(ctx);
7638 io_ring_submit_unlock(ctx, lock_ring);
7641 rsrc_data->do_put(ctx, prsrc);
7645 io_rsrc_node_destroy(ref_node);
7646 if (atomic_dec_and_test(&rsrc_data->refs))
7647 complete(&rsrc_data->done);
7650 static void io_rsrc_put_work(struct work_struct *work)
7652 struct io_ring_ctx *ctx;
7653 struct llist_node *node;
7655 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7656 node = llist_del_all(&ctx->rsrc_put_llist);
7659 struct io_rsrc_node *ref_node;
7660 struct llist_node *next = node->next;
7662 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7663 __io_rsrc_put_work(ref_node);
7668 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7670 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7671 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7672 bool first_add = false;
7674 io_rsrc_ref_lock(ctx);
7677 while (!list_empty(&ctx->rsrc_ref_list)) {
7678 node = list_first_entry(&ctx->rsrc_ref_list,
7679 struct io_rsrc_node, node);
7680 /* recycle ref nodes in order */
7683 list_del(&node->node);
7684 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7686 io_rsrc_ref_unlock(ctx);
7689 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7692 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7694 struct io_rsrc_node *ref_node;
7696 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7700 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7705 INIT_LIST_HEAD(&ref_node->node);
7706 INIT_LIST_HEAD(&ref_node->rsrc_list);
7707 ref_node->done = false;
7711 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7712 unsigned nr_args, u64 __user *tags)
7714 __s32 __user *fds = (__s32 __user *) arg;
7723 if (nr_args > IORING_MAX_FIXED_FILES)
7725 ret = io_rsrc_node_switch_start(ctx);
7728 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7734 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7737 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7738 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7742 /* allow sparse sets */
7745 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7752 if (unlikely(!file))
7756 * Don't allow io_uring instances to be registered. If UNIX
7757 * isn't enabled, then this causes a reference cycle and this
7758 * instance can never get freed. If UNIX is enabled we'll
7759 * handle it just fine, but there's still no point in allowing
7760 * a ring fd as it doesn't support regular read/write anyway.
7762 if (file->f_op == &io_uring_fops) {
7766 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7769 ret = io_sqe_files_scm(ctx);
7771 __io_sqe_files_unregister(ctx);
7775 io_rsrc_node_switch(ctx, NULL);
7778 for (i = 0; i < ctx->nr_user_files; i++) {
7779 file = io_file_from_index(ctx, i);
7783 io_free_file_tables(&ctx->file_table, nr_args);
7784 ctx->nr_user_files = 0;
7786 io_rsrc_data_free(ctx->file_data);
7787 ctx->file_data = NULL;
7791 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7794 #if defined(CONFIG_UNIX)
7795 struct sock *sock = ctx->ring_sock->sk;
7796 struct sk_buff_head *head = &sock->sk_receive_queue;
7797 struct sk_buff *skb;
7800 * See if we can merge this file into an existing skb SCM_RIGHTS
7801 * file set. If there's no room, fall back to allocating a new skb
7802 * and filling it in.
7804 spin_lock_irq(&head->lock);
7805 skb = skb_peek(head);
7807 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7809 if (fpl->count < SCM_MAX_FD) {
7810 __skb_unlink(skb, head);
7811 spin_unlock_irq(&head->lock);
7812 fpl->fp[fpl->count] = get_file(file);
7813 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7815 spin_lock_irq(&head->lock);
7816 __skb_queue_head(head, skb);
7821 spin_unlock_irq(&head->lock);
7828 return __io_sqe_files_scm(ctx, 1, index);
7834 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7835 struct io_rsrc_node *node, void *rsrc)
7837 struct io_rsrc_put *prsrc;
7839 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7843 prsrc->tag = *io_get_tag_slot(data, idx);
7845 list_add(&prsrc->list, &node->rsrc_list);
7849 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7850 struct io_uring_rsrc_update2 *up,
7853 u64 __user *tags = u64_to_user_ptr(up->tags);
7854 __s32 __user *fds = u64_to_user_ptr(up->data);
7855 struct io_rsrc_data *data = ctx->file_data;
7856 struct io_fixed_file *file_slot;
7860 bool needs_switch = false;
7862 if (!ctx->file_data)
7864 if (up->offset + nr_args > ctx->nr_user_files)
7867 for (done = 0; done < nr_args; done++) {
7870 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7871 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7875 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7879 if (fd == IORING_REGISTER_FILES_SKIP)
7882 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7883 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7885 if (file_slot->file_ptr) {
7886 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7887 err = io_queue_rsrc_removal(data, up->offset + done,
7888 ctx->rsrc_node, file);
7891 file_slot->file_ptr = 0;
7892 needs_switch = true;
7901 * Don't allow io_uring instances to be registered. If
7902 * UNIX isn't enabled, then this causes a reference
7903 * cycle and this instance can never get freed. If UNIX
7904 * is enabled we'll handle it just fine, but there's
7905 * still no point in allowing a ring fd as it doesn't
7906 * support regular read/write anyway.
7908 if (file->f_op == &io_uring_fops) {
7913 *io_get_tag_slot(data, up->offset + done) = tag;
7914 io_fixed_file_set(file_slot, file);
7915 err = io_sqe_file_register(ctx, file, i);
7917 file_slot->file_ptr = 0;
7925 io_rsrc_node_switch(ctx, data);
7926 return done ? done : err;
7929 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7931 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7933 req = io_put_req_find_next(req);
7934 return req ? &req->work : NULL;
7937 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7938 struct task_struct *task)
7940 struct io_wq_hash *hash;
7941 struct io_wq_data data;
7942 unsigned int concurrency;
7944 mutex_lock(&ctx->uring_lock);
7945 hash = ctx->hash_map;
7947 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7949 mutex_unlock(&ctx->uring_lock);
7950 return ERR_PTR(-ENOMEM);
7952 refcount_set(&hash->refs, 1);
7953 init_waitqueue_head(&hash->wait);
7954 ctx->hash_map = hash;
7956 mutex_unlock(&ctx->uring_lock);
7960 data.free_work = io_free_work;
7961 data.do_work = io_wq_submit_work;
7963 /* Do QD, or 4 * CPUS, whatever is smallest */
7964 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7966 return io_wq_create(concurrency, &data);
7969 static int io_uring_alloc_task_context(struct task_struct *task,
7970 struct io_ring_ctx *ctx)
7972 struct io_uring_task *tctx;
7975 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
7976 if (unlikely(!tctx))
7979 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7980 if (unlikely(ret)) {
7985 tctx->io_wq = io_init_wq_offload(ctx, task);
7986 if (IS_ERR(tctx->io_wq)) {
7987 ret = PTR_ERR(tctx->io_wq);
7988 percpu_counter_destroy(&tctx->inflight);
7994 init_waitqueue_head(&tctx->wait);
7995 atomic_set(&tctx->in_idle, 0);
7996 atomic_set(&tctx->inflight_tracked, 0);
7997 task->io_uring = tctx;
7998 spin_lock_init(&tctx->task_lock);
7999 INIT_WQ_LIST(&tctx->task_list);
8000 init_task_work(&tctx->task_work, tctx_task_work);
8004 void __io_uring_free(struct task_struct *tsk)
8006 struct io_uring_task *tctx = tsk->io_uring;
8008 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8009 WARN_ON_ONCE(tctx->io_wq);
8010 WARN_ON_ONCE(tctx->cached_refs);
8012 percpu_counter_destroy(&tctx->inflight);
8014 tsk->io_uring = NULL;
8017 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8018 struct io_uring_params *p)
8022 /* Retain compatibility with failing for an invalid attach attempt */
8023 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8024 IORING_SETUP_ATTACH_WQ) {
8027 f = fdget(p->wq_fd);
8030 if (f.file->f_op != &io_uring_fops) {
8036 if (ctx->flags & IORING_SETUP_SQPOLL) {
8037 struct task_struct *tsk;
8038 struct io_sq_data *sqd;
8041 sqd = io_get_sq_data(p, &attached);
8047 ctx->sq_creds = get_current_cred();
8049 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8050 if (!ctx->sq_thread_idle)
8051 ctx->sq_thread_idle = HZ;
8053 io_sq_thread_park(sqd);
8054 list_add(&ctx->sqd_list, &sqd->ctx_list);
8055 io_sqd_update_thread_idle(sqd);
8056 /* don't attach to a dying SQPOLL thread, would be racy */
8057 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8058 io_sq_thread_unpark(sqd);
8065 if (p->flags & IORING_SETUP_SQ_AFF) {
8066 int cpu = p->sq_thread_cpu;
8069 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8076 sqd->task_pid = current->pid;
8077 sqd->task_tgid = current->tgid;
8078 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8085 ret = io_uring_alloc_task_context(tsk, ctx);
8086 wake_up_new_task(tsk);
8089 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8090 /* Can't have SQ_AFF without SQPOLL */
8097 complete(&ctx->sq_data->exited);
8099 io_sq_thread_finish(ctx);
8103 static inline void __io_unaccount_mem(struct user_struct *user,
8104 unsigned long nr_pages)
8106 atomic_long_sub(nr_pages, &user->locked_vm);
8109 static inline int __io_account_mem(struct user_struct *user,
8110 unsigned long nr_pages)
8112 unsigned long page_limit, cur_pages, new_pages;
8114 /* Don't allow more pages than we can safely lock */
8115 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8118 cur_pages = atomic_long_read(&user->locked_vm);
8119 new_pages = cur_pages + nr_pages;
8120 if (new_pages > page_limit)
8122 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8123 new_pages) != cur_pages);
8128 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8131 __io_unaccount_mem(ctx->user, nr_pages);
8133 if (ctx->mm_account)
8134 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8137 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8142 ret = __io_account_mem(ctx->user, nr_pages);
8147 if (ctx->mm_account)
8148 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8153 static void io_mem_free(void *ptr)
8160 page = virt_to_head_page(ptr);
8161 if (put_page_testzero(page))
8162 free_compound_page(page);
8165 static void *io_mem_alloc(size_t size)
8167 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8168 __GFP_NORETRY | __GFP_ACCOUNT;
8170 return (void *) __get_free_pages(gfp_flags, get_order(size));
8173 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8176 struct io_rings *rings;
8177 size_t off, sq_array_size;
8179 off = struct_size(rings, cqes, cq_entries);
8180 if (off == SIZE_MAX)
8184 off = ALIGN(off, SMP_CACHE_BYTES);
8192 sq_array_size = array_size(sizeof(u32), sq_entries);
8193 if (sq_array_size == SIZE_MAX)
8196 if (check_add_overflow(off, sq_array_size, &off))
8202 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8204 struct io_mapped_ubuf *imu = *slot;
8207 if (imu != ctx->dummy_ubuf) {
8208 for (i = 0; i < imu->nr_bvecs; i++)
8209 unpin_user_page(imu->bvec[i].bv_page);
8210 if (imu->acct_pages)
8211 io_unaccount_mem(ctx, imu->acct_pages);
8217 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8219 io_buffer_unmap(ctx, &prsrc->buf);
8223 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8227 for (i = 0; i < ctx->nr_user_bufs; i++)
8228 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8229 kfree(ctx->user_bufs);
8230 io_rsrc_data_free(ctx->buf_data);
8231 ctx->user_bufs = NULL;
8232 ctx->buf_data = NULL;
8233 ctx->nr_user_bufs = 0;
8236 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8243 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8245 __io_sqe_buffers_unregister(ctx);
8249 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8250 void __user *arg, unsigned index)
8252 struct iovec __user *src;
8254 #ifdef CONFIG_COMPAT
8256 struct compat_iovec __user *ciovs;
8257 struct compat_iovec ciov;
8259 ciovs = (struct compat_iovec __user *) arg;
8260 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8263 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8264 dst->iov_len = ciov.iov_len;
8268 src = (struct iovec __user *) arg;
8269 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8275 * Not super efficient, but this is just a registration time. And we do cache
8276 * the last compound head, so generally we'll only do a full search if we don't
8279 * We check if the given compound head page has already been accounted, to
8280 * avoid double accounting it. This allows us to account the full size of the
8281 * page, not just the constituent pages of a huge page.
8283 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8284 int nr_pages, struct page *hpage)
8288 /* check current page array */
8289 for (i = 0; i < nr_pages; i++) {
8290 if (!PageCompound(pages[i]))
8292 if (compound_head(pages[i]) == hpage)
8296 /* check previously registered pages */
8297 for (i = 0; i < ctx->nr_user_bufs; i++) {
8298 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8300 for (j = 0; j < imu->nr_bvecs; j++) {
8301 if (!PageCompound(imu->bvec[j].bv_page))
8303 if (compound_head(imu->bvec[j].bv_page) == hpage)
8311 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8312 int nr_pages, struct io_mapped_ubuf *imu,
8313 struct page **last_hpage)
8317 imu->acct_pages = 0;
8318 for (i = 0; i < nr_pages; i++) {
8319 if (!PageCompound(pages[i])) {
8324 hpage = compound_head(pages[i]);
8325 if (hpage == *last_hpage)
8327 *last_hpage = hpage;
8328 if (headpage_already_acct(ctx, pages, i, hpage))
8330 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8334 if (!imu->acct_pages)
8337 ret = io_account_mem(ctx, imu->acct_pages);
8339 imu->acct_pages = 0;
8343 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8344 struct io_mapped_ubuf **pimu,
8345 struct page **last_hpage)
8347 struct io_mapped_ubuf *imu = NULL;
8348 struct vm_area_struct **vmas = NULL;
8349 struct page **pages = NULL;
8350 unsigned long off, start, end, ubuf;
8352 int ret, pret, nr_pages, i;
8354 if (!iov->iov_base) {
8355 *pimu = ctx->dummy_ubuf;
8359 ubuf = (unsigned long) iov->iov_base;
8360 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8361 start = ubuf >> PAGE_SHIFT;
8362 nr_pages = end - start;
8367 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8371 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8376 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8381 mmap_read_lock(current->mm);
8382 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8384 if (pret == nr_pages) {
8385 /* don't support file backed memory */
8386 for (i = 0; i < nr_pages; i++) {
8387 struct vm_area_struct *vma = vmas[i];
8389 if (vma_is_shmem(vma))
8392 !is_file_hugepages(vma->vm_file)) {
8398 ret = pret < 0 ? pret : -EFAULT;
8400 mmap_read_unlock(current->mm);
8403 * if we did partial map, or found file backed vmas,
8404 * release any pages we did get
8407 unpin_user_pages(pages, pret);
8411 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8413 unpin_user_pages(pages, pret);
8417 off = ubuf & ~PAGE_MASK;
8418 size = iov->iov_len;
8419 for (i = 0; i < nr_pages; i++) {
8422 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8423 imu->bvec[i].bv_page = pages[i];
8424 imu->bvec[i].bv_len = vec_len;
8425 imu->bvec[i].bv_offset = off;
8429 /* store original address for later verification */
8431 imu->ubuf_end = ubuf + iov->iov_len;
8432 imu->nr_bvecs = nr_pages;
8443 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8445 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8446 return ctx->user_bufs ? 0 : -ENOMEM;
8449 static int io_buffer_validate(struct iovec *iov)
8451 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8454 * Don't impose further limits on the size and buffer
8455 * constraints here, we'll -EINVAL later when IO is
8456 * submitted if they are wrong.
8459 return iov->iov_len ? -EFAULT : 0;
8463 /* arbitrary limit, but we need something */
8464 if (iov->iov_len > SZ_1G)
8467 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8473 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8474 unsigned int nr_args, u64 __user *tags)
8476 struct page *last_hpage = NULL;
8477 struct io_rsrc_data *data;
8483 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8485 ret = io_rsrc_node_switch_start(ctx);
8488 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8491 ret = io_buffers_map_alloc(ctx, nr_args);
8493 io_rsrc_data_free(data);
8497 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8498 ret = io_copy_iov(ctx, &iov, arg, i);
8501 ret = io_buffer_validate(&iov);
8504 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8509 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8515 WARN_ON_ONCE(ctx->buf_data);
8517 ctx->buf_data = data;
8519 __io_sqe_buffers_unregister(ctx);
8521 io_rsrc_node_switch(ctx, NULL);
8525 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8526 struct io_uring_rsrc_update2 *up,
8527 unsigned int nr_args)
8529 u64 __user *tags = u64_to_user_ptr(up->tags);
8530 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8531 struct page *last_hpage = NULL;
8532 bool needs_switch = false;
8538 if (up->offset + nr_args > ctx->nr_user_bufs)
8541 for (done = 0; done < nr_args; done++) {
8542 struct io_mapped_ubuf *imu;
8543 int offset = up->offset + done;
8546 err = io_copy_iov(ctx, &iov, iovs, done);
8549 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8553 err = io_buffer_validate(&iov);
8556 if (!iov.iov_base && tag) {
8560 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8564 i = array_index_nospec(offset, ctx->nr_user_bufs);
8565 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8566 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8567 ctx->rsrc_node, ctx->user_bufs[i]);
8568 if (unlikely(err)) {
8569 io_buffer_unmap(ctx, &imu);
8572 ctx->user_bufs[i] = NULL;
8573 needs_switch = true;
8576 ctx->user_bufs[i] = imu;
8577 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8581 io_rsrc_node_switch(ctx, ctx->buf_data);
8582 return done ? done : err;
8585 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8587 __s32 __user *fds = arg;
8593 if (copy_from_user(&fd, fds, sizeof(*fds)))
8596 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8597 if (IS_ERR(ctx->cq_ev_fd)) {
8598 int ret = PTR_ERR(ctx->cq_ev_fd);
8600 ctx->cq_ev_fd = NULL;
8607 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8609 if (ctx->cq_ev_fd) {
8610 eventfd_ctx_put(ctx->cq_ev_fd);
8611 ctx->cq_ev_fd = NULL;
8618 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8620 struct io_buffer *buf;
8621 unsigned long index;
8623 xa_for_each(&ctx->io_buffers, index, buf)
8624 __io_remove_buffers(ctx, buf, index, -1U);
8627 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8629 struct io_kiocb *req, *nxt;
8631 list_for_each_entry_safe(req, nxt, list, compl.list) {
8632 if (tsk && req->task != tsk)
8634 list_del(&req->compl.list);
8635 kmem_cache_free(req_cachep, req);
8639 static void io_req_caches_free(struct io_ring_ctx *ctx)
8641 struct io_submit_state *submit_state = &ctx->submit_state;
8642 struct io_comp_state *cs = &ctx->submit_state.comp;
8644 mutex_lock(&ctx->uring_lock);
8646 if (submit_state->free_reqs) {
8647 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8648 submit_state->reqs);
8649 submit_state->free_reqs = 0;
8652 io_flush_cached_locked_reqs(ctx, cs);
8653 io_req_cache_free(&cs->free_list, NULL);
8654 mutex_unlock(&ctx->uring_lock);
8657 static bool io_wait_rsrc_data(struct io_rsrc_data *data)
8661 if (!atomic_dec_and_test(&data->refs))
8662 wait_for_completion(&data->done);
8666 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8668 io_sq_thread_finish(ctx);
8670 if (ctx->mm_account) {
8671 mmdrop(ctx->mm_account);
8672 ctx->mm_account = NULL;
8675 mutex_lock(&ctx->uring_lock);
8676 if (io_wait_rsrc_data(ctx->buf_data))
8677 __io_sqe_buffers_unregister(ctx);
8678 if (io_wait_rsrc_data(ctx->file_data))
8679 __io_sqe_files_unregister(ctx);
8681 __io_cqring_overflow_flush(ctx, true);
8682 mutex_unlock(&ctx->uring_lock);
8683 io_eventfd_unregister(ctx);
8684 io_destroy_buffers(ctx);
8686 put_cred(ctx->sq_creds);
8688 /* there are no registered resources left, nobody uses it */
8690 io_rsrc_node_destroy(ctx->rsrc_node);
8691 if (ctx->rsrc_backup_node)
8692 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8693 flush_delayed_work(&ctx->rsrc_put_work);
8695 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8696 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8698 #if defined(CONFIG_UNIX)
8699 if (ctx->ring_sock) {
8700 ctx->ring_sock->file = NULL; /* so that iput() is called */
8701 sock_release(ctx->ring_sock);
8705 io_mem_free(ctx->rings);
8706 io_mem_free(ctx->sq_sqes);
8708 percpu_ref_exit(&ctx->refs);
8709 free_uid(ctx->user);
8710 io_req_caches_free(ctx);
8712 io_wq_put_hash(ctx->hash_map);
8713 kfree(ctx->cancel_hash);
8714 kfree(ctx->dummy_ubuf);
8718 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8720 struct io_ring_ctx *ctx = file->private_data;
8723 poll_wait(file, &ctx->poll_wait, wait);
8725 * synchronizes with barrier from wq_has_sleeper call in
8729 if (!io_sqring_full(ctx))
8730 mask |= EPOLLOUT | EPOLLWRNORM;
8733 * Don't flush cqring overflow list here, just do a simple check.
8734 * Otherwise there could possible be ABBA deadlock:
8737 * lock(&ctx->uring_lock);
8739 * lock(&ctx->uring_lock);
8742 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8743 * pushs them to do the flush.
8745 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8746 mask |= EPOLLIN | EPOLLRDNORM;
8751 static int io_uring_fasync(int fd, struct file *file, int on)
8753 struct io_ring_ctx *ctx = file->private_data;
8755 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8758 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8760 const struct cred *creds;
8762 creds = xa_erase(&ctx->personalities, id);
8771 struct io_tctx_exit {
8772 struct callback_head task_work;
8773 struct completion completion;
8774 struct io_ring_ctx *ctx;
8777 static void io_tctx_exit_cb(struct callback_head *cb)
8779 struct io_uring_task *tctx = current->io_uring;
8780 struct io_tctx_exit *work;
8782 work = container_of(cb, struct io_tctx_exit, task_work);
8784 * When @in_idle, we're in cancellation and it's racy to remove the
8785 * node. It'll be removed by the end of cancellation, just ignore it.
8787 if (!atomic_read(&tctx->in_idle))
8788 io_uring_del_tctx_node((unsigned long)work->ctx);
8789 complete(&work->completion);
8792 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8794 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8796 return req->ctx == data;
8799 static void io_ring_exit_work(struct work_struct *work)
8801 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8802 unsigned long timeout = jiffies + HZ * 60 * 5;
8803 struct io_tctx_exit exit;
8804 struct io_tctx_node *node;
8808 * If we're doing polled IO and end up having requests being
8809 * submitted async (out-of-line), then completions can come in while
8810 * we're waiting for refs to drop. We need to reap these manually,
8811 * as nobody else will be looking for them.
8814 io_uring_try_cancel_requests(ctx, NULL, true);
8816 struct io_sq_data *sqd = ctx->sq_data;
8817 struct task_struct *tsk;
8819 io_sq_thread_park(sqd);
8821 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8822 io_wq_cancel_cb(tsk->io_uring->io_wq,
8823 io_cancel_ctx_cb, ctx, true);
8824 io_sq_thread_unpark(sqd);
8827 WARN_ON_ONCE(time_after(jiffies, timeout));
8828 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8830 init_completion(&exit.completion);
8831 init_task_work(&exit.task_work, io_tctx_exit_cb);
8834 * Some may use context even when all refs and requests have been put,
8835 * and they are free to do so while still holding uring_lock or
8836 * completion_lock, see io_req_task_submit(). Apart from other work,
8837 * this lock/unlock section also waits them to finish.
8839 mutex_lock(&ctx->uring_lock);
8840 while (!list_empty(&ctx->tctx_list)) {
8841 WARN_ON_ONCE(time_after(jiffies, timeout));
8843 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8845 /* don't spin on a single task if cancellation failed */
8846 list_rotate_left(&ctx->tctx_list);
8847 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8848 if (WARN_ON_ONCE(ret))
8850 wake_up_process(node->task);
8852 mutex_unlock(&ctx->uring_lock);
8853 wait_for_completion(&exit.completion);
8854 mutex_lock(&ctx->uring_lock);
8856 mutex_unlock(&ctx->uring_lock);
8857 spin_lock_irq(&ctx->completion_lock);
8858 spin_unlock_irq(&ctx->completion_lock);
8860 io_ring_ctx_free(ctx);
8863 /* Returns true if we found and killed one or more timeouts */
8864 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8867 struct io_kiocb *req, *tmp;
8870 spin_lock_irq(&ctx->completion_lock);
8871 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8872 if (io_match_task(req, tsk, cancel_all)) {
8873 io_kill_timeout(req, -ECANCELED);
8878 io_commit_cqring(ctx);
8879 spin_unlock_irq(&ctx->completion_lock);
8881 io_cqring_ev_posted(ctx);
8882 return canceled != 0;
8885 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8887 unsigned long index;
8888 struct creds *creds;
8890 mutex_lock(&ctx->uring_lock);
8891 percpu_ref_kill(&ctx->refs);
8893 __io_cqring_overflow_flush(ctx, true);
8894 xa_for_each(&ctx->personalities, index, creds)
8895 io_unregister_personality(ctx, index);
8896 mutex_unlock(&ctx->uring_lock);
8898 io_kill_timeouts(ctx, NULL, true);
8899 io_poll_remove_all(ctx, NULL, true);
8901 /* if we failed setting up the ctx, we might not have any rings */
8902 io_iopoll_try_reap_events(ctx);
8904 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8906 * Use system_unbound_wq to avoid spawning tons of event kworkers
8907 * if we're exiting a ton of rings at the same time. It just adds
8908 * noise and overhead, there's no discernable change in runtime
8909 * over using system_wq.
8911 queue_work(system_unbound_wq, &ctx->exit_work);
8914 static int io_uring_release(struct inode *inode, struct file *file)
8916 struct io_ring_ctx *ctx = file->private_data;
8918 file->private_data = NULL;
8919 io_ring_ctx_wait_and_kill(ctx);
8923 struct io_task_cancel {
8924 struct task_struct *task;
8928 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8930 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8931 struct io_task_cancel *cancel = data;
8934 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
8935 unsigned long flags;
8936 struct io_ring_ctx *ctx = req->ctx;
8938 /* protect against races with linked timeouts */
8939 spin_lock_irqsave(&ctx->completion_lock, flags);
8940 ret = io_match_task(req, cancel->task, cancel->all);
8941 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8943 ret = io_match_task(req, cancel->task, cancel->all);
8948 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8949 struct task_struct *task, bool cancel_all)
8951 struct io_defer_entry *de;
8954 spin_lock_irq(&ctx->completion_lock);
8955 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8956 if (io_match_task(de->req, task, cancel_all)) {
8957 list_cut_position(&list, &ctx->defer_list, &de->list);
8961 spin_unlock_irq(&ctx->completion_lock);
8962 if (list_empty(&list))
8965 while (!list_empty(&list)) {
8966 de = list_first_entry(&list, struct io_defer_entry, list);
8967 list_del_init(&de->list);
8968 io_req_complete_failed(de->req, -ECANCELED);
8974 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8976 struct io_tctx_node *node;
8977 enum io_wq_cancel cret;
8980 mutex_lock(&ctx->uring_lock);
8981 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8982 struct io_uring_task *tctx = node->task->io_uring;
8985 * io_wq will stay alive while we hold uring_lock, because it's
8986 * killed after ctx nodes, which requires to take the lock.
8988 if (!tctx || !tctx->io_wq)
8990 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8991 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8993 mutex_unlock(&ctx->uring_lock);
8998 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8999 struct task_struct *task,
9002 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9003 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9006 enum io_wq_cancel cret;
9010 ret |= io_uring_try_cancel_iowq(ctx);
9011 } else if (tctx && tctx->io_wq) {
9013 * Cancels requests of all rings, not only @ctx, but
9014 * it's fine as the task is in exit/exec.
9016 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9018 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9021 /* SQPOLL thread does its own polling */
9022 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9023 (ctx->sq_data && ctx->sq_data->thread == current)) {
9024 while (!list_empty_careful(&ctx->iopoll_list)) {
9025 io_iopoll_try_reap_events(ctx);
9030 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9031 ret |= io_poll_remove_all(ctx, task, cancel_all);
9032 ret |= io_kill_timeouts(ctx, task, cancel_all);
9034 ret |= io_run_task_work();
9041 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9043 struct io_uring_task *tctx = current->io_uring;
9044 struct io_tctx_node *node;
9047 if (unlikely(!tctx)) {
9048 ret = io_uring_alloc_task_context(current, ctx);
9051 tctx = current->io_uring;
9053 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9054 node = kmalloc(sizeof(*node), GFP_KERNEL);
9058 node->task = current;
9060 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9067 mutex_lock(&ctx->uring_lock);
9068 list_add(&node->ctx_node, &ctx->tctx_list);
9069 mutex_unlock(&ctx->uring_lock);
9076 * Note that this task has used io_uring. We use it for cancelation purposes.
9078 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9080 struct io_uring_task *tctx = current->io_uring;
9082 if (likely(tctx && tctx->last == ctx))
9084 return __io_uring_add_tctx_node(ctx);
9088 * Remove this io_uring_file -> task mapping.
9090 static void io_uring_del_tctx_node(unsigned long index)
9092 struct io_uring_task *tctx = current->io_uring;
9093 struct io_tctx_node *node;
9097 node = xa_erase(&tctx->xa, index);
9101 WARN_ON_ONCE(current != node->task);
9102 WARN_ON_ONCE(list_empty(&node->ctx_node));
9104 mutex_lock(&node->ctx->uring_lock);
9105 list_del(&node->ctx_node);
9106 mutex_unlock(&node->ctx->uring_lock);
9108 if (tctx->last == node->ctx)
9113 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9115 struct io_wq *wq = tctx->io_wq;
9116 struct io_tctx_node *node;
9117 unsigned long index;
9119 xa_for_each(&tctx->xa, index, node)
9120 io_uring_del_tctx_node(index);
9123 * Must be after io_uring_del_task_file() (removes nodes under
9124 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9127 io_wq_put_and_exit(wq);
9131 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9134 return atomic_read(&tctx->inflight_tracked);
9135 return percpu_counter_sum(&tctx->inflight);
9138 static void io_uring_drop_tctx_refs(struct task_struct *task)
9140 struct io_uring_task *tctx = task->io_uring;
9141 unsigned int refs = tctx->cached_refs;
9143 tctx->cached_refs = 0;
9144 percpu_counter_sub(&tctx->inflight, refs);
9145 put_task_struct_many(task, refs);
9149 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9150 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9152 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9154 struct io_uring_task *tctx = current->io_uring;
9155 struct io_ring_ctx *ctx;
9159 WARN_ON_ONCE(sqd && sqd->thread != current);
9161 if (!current->io_uring)
9164 io_wq_exit_start(tctx->io_wq);
9166 io_uring_drop_tctx_refs(current);
9167 atomic_inc(&tctx->in_idle);
9169 /* read completions before cancelations */
9170 inflight = tctx_inflight(tctx, !cancel_all);
9175 struct io_tctx_node *node;
9176 unsigned long index;
9178 xa_for_each(&tctx->xa, index, node) {
9179 /* sqpoll task will cancel all its requests */
9180 if (node->ctx->sq_data)
9182 io_uring_try_cancel_requests(node->ctx, current,
9186 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9187 io_uring_try_cancel_requests(ctx, current,
9191 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9193 * If we've seen completions, retry without waiting. This
9194 * avoids a race where a completion comes in before we did
9195 * prepare_to_wait().
9197 if (inflight == tctx_inflight(tctx, !cancel_all))
9199 finish_wait(&tctx->wait, &wait);
9201 atomic_dec(&tctx->in_idle);
9203 io_uring_clean_tctx(tctx);
9205 /* for exec all current's requests should be gone, kill tctx */
9206 __io_uring_free(current);
9210 void __io_uring_cancel(struct files_struct *files)
9212 io_uring_cancel_generic(!files, NULL);
9215 static void *io_uring_validate_mmap_request(struct file *file,
9216 loff_t pgoff, size_t sz)
9218 struct io_ring_ctx *ctx = file->private_data;
9219 loff_t offset = pgoff << PAGE_SHIFT;
9224 case IORING_OFF_SQ_RING:
9225 case IORING_OFF_CQ_RING:
9228 case IORING_OFF_SQES:
9232 return ERR_PTR(-EINVAL);
9235 page = virt_to_head_page(ptr);
9236 if (sz > page_size(page))
9237 return ERR_PTR(-EINVAL);
9244 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9246 size_t sz = vma->vm_end - vma->vm_start;
9250 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9252 return PTR_ERR(ptr);
9254 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9255 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9258 #else /* !CONFIG_MMU */
9260 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9262 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9265 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9267 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9270 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9271 unsigned long addr, unsigned long len,
9272 unsigned long pgoff, unsigned long flags)
9276 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9278 return PTR_ERR(ptr);
9280 return (unsigned long) ptr;
9283 #endif /* !CONFIG_MMU */
9285 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9290 if (!io_sqring_full(ctx))
9292 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9294 if (!io_sqring_full(ctx))
9297 } while (!signal_pending(current));
9299 finish_wait(&ctx->sqo_sq_wait, &wait);
9303 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9304 struct __kernel_timespec __user **ts,
9305 const sigset_t __user **sig)
9307 struct io_uring_getevents_arg arg;
9310 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9311 * is just a pointer to the sigset_t.
9313 if (!(flags & IORING_ENTER_EXT_ARG)) {
9314 *sig = (const sigset_t __user *) argp;
9320 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9321 * timespec and sigset_t pointers if good.
9323 if (*argsz != sizeof(arg))
9325 if (copy_from_user(&arg, argp, sizeof(arg)))
9327 *sig = u64_to_user_ptr(arg.sigmask);
9328 *argsz = arg.sigmask_sz;
9329 *ts = u64_to_user_ptr(arg.ts);
9333 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9334 u32, min_complete, u32, flags, const void __user *, argp,
9337 struct io_ring_ctx *ctx;
9344 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9345 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9349 if (unlikely(!f.file))
9353 if (unlikely(f.file->f_op != &io_uring_fops))
9357 ctx = f.file->private_data;
9358 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9362 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9366 * For SQ polling, the thread will do all submissions and completions.
9367 * Just return the requested submit count, and wake the thread if
9371 if (ctx->flags & IORING_SETUP_SQPOLL) {
9372 io_cqring_overflow_flush(ctx, false);
9375 if (unlikely(ctx->sq_data->thread == NULL))
9377 if (flags & IORING_ENTER_SQ_WAKEUP)
9378 wake_up(&ctx->sq_data->wait);
9379 if (flags & IORING_ENTER_SQ_WAIT) {
9380 ret = io_sqpoll_wait_sq(ctx);
9384 submitted = to_submit;
9385 } else if (to_submit) {
9386 ret = io_uring_add_tctx_node(ctx);
9389 mutex_lock(&ctx->uring_lock);
9390 submitted = io_submit_sqes(ctx, to_submit);
9391 mutex_unlock(&ctx->uring_lock);
9393 if (submitted != to_submit)
9396 if (flags & IORING_ENTER_GETEVENTS) {
9397 const sigset_t __user *sig;
9398 struct __kernel_timespec __user *ts;
9400 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9404 min_complete = min(min_complete, ctx->cq_entries);
9407 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9408 * space applications don't need to do io completion events
9409 * polling again, they can rely on io_sq_thread to do polling
9410 * work, which can reduce cpu usage and uring_lock contention.
9412 if (ctx->flags & IORING_SETUP_IOPOLL &&
9413 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9414 ret = io_iopoll_check(ctx, min_complete);
9416 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9421 percpu_ref_put(&ctx->refs);
9424 return submitted ? submitted : ret;
9427 #ifdef CONFIG_PROC_FS
9428 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9429 const struct cred *cred)
9431 struct user_namespace *uns = seq_user_ns(m);
9432 struct group_info *gi;
9437 seq_printf(m, "%5d\n", id);
9438 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9439 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9440 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9441 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9442 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9443 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9444 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9445 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9446 seq_puts(m, "\n\tGroups:\t");
9447 gi = cred->group_info;
9448 for (g = 0; g < gi->ngroups; g++) {
9449 seq_put_decimal_ull(m, g ? " " : "",
9450 from_kgid_munged(uns, gi->gid[g]));
9452 seq_puts(m, "\n\tCapEff:\t");
9453 cap = cred->cap_effective;
9454 CAP_FOR_EACH_U32(__capi)
9455 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9460 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9462 struct io_sq_data *sq = NULL;
9467 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9468 * since fdinfo case grabs it in the opposite direction of normal use
9469 * cases. If we fail to get the lock, we just don't iterate any
9470 * structures that could be going away outside the io_uring mutex.
9472 has_lock = mutex_trylock(&ctx->uring_lock);
9474 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9480 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9481 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9482 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9483 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9484 struct file *f = io_file_from_index(ctx, i);
9487 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9489 seq_printf(m, "%5u: <none>\n", i);
9491 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9492 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9493 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9494 unsigned int len = buf->ubuf_end - buf->ubuf;
9496 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9498 if (has_lock && !xa_empty(&ctx->personalities)) {
9499 unsigned long index;
9500 const struct cred *cred;
9502 seq_printf(m, "Personalities:\n");
9503 xa_for_each(&ctx->personalities, index, cred)
9504 io_uring_show_cred(m, index, cred);
9506 seq_printf(m, "PollList:\n");
9507 spin_lock_irq(&ctx->completion_lock);
9508 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9509 struct hlist_head *list = &ctx->cancel_hash[i];
9510 struct io_kiocb *req;
9512 hlist_for_each_entry(req, list, hash_node)
9513 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9514 req->task->task_works != NULL);
9516 spin_unlock_irq(&ctx->completion_lock);
9518 mutex_unlock(&ctx->uring_lock);
9521 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9523 struct io_ring_ctx *ctx = f->private_data;
9525 if (percpu_ref_tryget(&ctx->refs)) {
9526 __io_uring_show_fdinfo(ctx, m);
9527 percpu_ref_put(&ctx->refs);
9532 static const struct file_operations io_uring_fops = {
9533 .release = io_uring_release,
9534 .mmap = io_uring_mmap,
9536 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9537 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9539 .poll = io_uring_poll,
9540 .fasync = io_uring_fasync,
9541 #ifdef CONFIG_PROC_FS
9542 .show_fdinfo = io_uring_show_fdinfo,
9546 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9547 struct io_uring_params *p)
9549 struct io_rings *rings;
9550 size_t size, sq_array_offset;
9552 /* make sure these are sane, as we already accounted them */
9553 ctx->sq_entries = p->sq_entries;
9554 ctx->cq_entries = p->cq_entries;
9556 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9557 if (size == SIZE_MAX)
9560 rings = io_mem_alloc(size);
9565 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9566 rings->sq_ring_mask = p->sq_entries - 1;
9567 rings->cq_ring_mask = p->cq_entries - 1;
9568 rings->sq_ring_entries = p->sq_entries;
9569 rings->cq_ring_entries = p->cq_entries;
9571 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9572 if (size == SIZE_MAX) {
9573 io_mem_free(ctx->rings);
9578 ctx->sq_sqes = io_mem_alloc(size);
9579 if (!ctx->sq_sqes) {
9580 io_mem_free(ctx->rings);
9588 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9592 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9596 ret = io_uring_add_tctx_node(ctx);
9601 fd_install(fd, file);
9606 * Allocate an anonymous fd, this is what constitutes the application
9607 * visible backing of an io_uring instance. The application mmaps this
9608 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9609 * we have to tie this fd to a socket for file garbage collection purposes.
9611 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9614 #if defined(CONFIG_UNIX)
9617 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9620 return ERR_PTR(ret);
9623 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9624 O_RDWR | O_CLOEXEC);
9625 #if defined(CONFIG_UNIX)
9627 sock_release(ctx->ring_sock);
9628 ctx->ring_sock = NULL;
9630 ctx->ring_sock->file = file;
9636 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9637 struct io_uring_params __user *params)
9639 struct io_ring_ctx *ctx;
9645 if (entries > IORING_MAX_ENTRIES) {
9646 if (!(p->flags & IORING_SETUP_CLAMP))
9648 entries = IORING_MAX_ENTRIES;
9652 * Use twice as many entries for the CQ ring. It's possible for the
9653 * application to drive a higher depth than the size of the SQ ring,
9654 * since the sqes are only used at submission time. This allows for
9655 * some flexibility in overcommitting a bit. If the application has
9656 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9657 * of CQ ring entries manually.
9659 p->sq_entries = roundup_pow_of_two(entries);
9660 if (p->flags & IORING_SETUP_CQSIZE) {
9662 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9663 * to a power-of-two, if it isn't already. We do NOT impose
9664 * any cq vs sq ring sizing.
9668 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9669 if (!(p->flags & IORING_SETUP_CLAMP))
9671 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9673 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9674 if (p->cq_entries < p->sq_entries)
9677 p->cq_entries = 2 * p->sq_entries;
9680 ctx = io_ring_ctx_alloc(p);
9683 ctx->compat = in_compat_syscall();
9684 if (!capable(CAP_IPC_LOCK))
9685 ctx->user = get_uid(current_user());
9688 * This is just grabbed for accounting purposes. When a process exits,
9689 * the mm is exited and dropped before the files, hence we need to hang
9690 * on to this mm purely for the purposes of being able to unaccount
9691 * memory (locked/pinned vm). It's not used for anything else.
9693 mmgrab(current->mm);
9694 ctx->mm_account = current->mm;
9696 ret = io_allocate_scq_urings(ctx, p);
9700 ret = io_sq_offload_create(ctx, p);
9703 /* always set a rsrc node */
9704 ret = io_rsrc_node_switch_start(ctx);
9707 io_rsrc_node_switch(ctx, NULL);
9709 memset(&p->sq_off, 0, sizeof(p->sq_off));
9710 p->sq_off.head = offsetof(struct io_rings, sq.head);
9711 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9712 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9713 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9714 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9715 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9716 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9718 memset(&p->cq_off, 0, sizeof(p->cq_off));
9719 p->cq_off.head = offsetof(struct io_rings, cq.head);
9720 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9721 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9722 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9723 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9724 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9725 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9727 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9728 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9729 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9730 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9731 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9732 IORING_FEAT_RSRC_TAGS;
9734 if (copy_to_user(params, p, sizeof(*p))) {
9739 file = io_uring_get_file(ctx);
9741 ret = PTR_ERR(file);
9746 * Install ring fd as the very last thing, so we don't risk someone
9747 * having closed it before we finish setup
9749 ret = io_uring_install_fd(ctx, file);
9751 /* fput will clean it up */
9756 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9759 io_ring_ctx_wait_and_kill(ctx);
9764 * Sets up an aio uring context, and returns the fd. Applications asks for a
9765 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9766 * params structure passed in.
9768 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9770 struct io_uring_params p;
9773 if (copy_from_user(&p, params, sizeof(p)))
9775 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9780 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9781 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9782 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9783 IORING_SETUP_R_DISABLED))
9786 return io_uring_create(entries, &p, params);
9789 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9790 struct io_uring_params __user *, params)
9792 return io_uring_setup(entries, params);
9795 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9797 struct io_uring_probe *p;
9801 size = struct_size(p, ops, nr_args);
9802 if (size == SIZE_MAX)
9804 p = kzalloc(size, GFP_KERNEL);
9809 if (copy_from_user(p, arg, size))
9812 if (memchr_inv(p, 0, size))
9815 p->last_op = IORING_OP_LAST - 1;
9816 if (nr_args > IORING_OP_LAST)
9817 nr_args = IORING_OP_LAST;
9819 for (i = 0; i < nr_args; i++) {
9821 if (!io_op_defs[i].not_supported)
9822 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9827 if (copy_to_user(arg, p, size))
9834 static int io_register_personality(struct io_ring_ctx *ctx)
9836 const struct cred *creds;
9840 creds = get_current_cred();
9842 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9843 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9850 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9851 unsigned int nr_args)
9853 struct io_uring_restriction *res;
9857 /* Restrictions allowed only if rings started disabled */
9858 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9861 /* We allow only a single restrictions registration */
9862 if (ctx->restrictions.registered)
9865 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9868 size = array_size(nr_args, sizeof(*res));
9869 if (size == SIZE_MAX)
9872 res = memdup_user(arg, size);
9874 return PTR_ERR(res);
9878 for (i = 0; i < nr_args; i++) {
9879 switch (res[i].opcode) {
9880 case IORING_RESTRICTION_REGISTER_OP:
9881 if (res[i].register_op >= IORING_REGISTER_LAST) {
9886 __set_bit(res[i].register_op,
9887 ctx->restrictions.register_op);
9889 case IORING_RESTRICTION_SQE_OP:
9890 if (res[i].sqe_op >= IORING_OP_LAST) {
9895 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9897 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9898 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9900 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9901 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9910 /* Reset all restrictions if an error happened */
9912 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9914 ctx->restrictions.registered = true;
9920 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9922 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9925 if (ctx->restrictions.registered)
9926 ctx->restricted = 1;
9928 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9929 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9930 wake_up(&ctx->sq_data->wait);
9934 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
9935 struct io_uring_rsrc_update2 *up,
9943 if (check_add_overflow(up->offset, nr_args, &tmp))
9945 err = io_rsrc_node_switch_start(ctx);
9950 case IORING_RSRC_FILE:
9951 return __io_sqe_files_update(ctx, up, nr_args);
9952 case IORING_RSRC_BUFFER:
9953 return __io_sqe_buffers_update(ctx, up, nr_args);
9958 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
9961 struct io_uring_rsrc_update2 up;
9965 memset(&up, 0, sizeof(up));
9966 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
9968 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
9971 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
9972 unsigned size, unsigned type)
9974 struct io_uring_rsrc_update2 up;
9976 if (size != sizeof(up))
9978 if (copy_from_user(&up, arg, sizeof(up)))
9980 if (!up.nr || up.resv)
9982 return __io_register_rsrc_update(ctx, type, &up, up.nr);
9985 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
9986 unsigned int size, unsigned int type)
9988 struct io_uring_rsrc_register rr;
9990 /* keep it extendible */
9991 if (size != sizeof(rr))
9994 memset(&rr, 0, sizeof(rr));
9995 if (copy_from_user(&rr, arg, size))
9997 if (!rr.nr || rr.resv || rr.resv2)
10001 case IORING_RSRC_FILE:
10002 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10003 rr.nr, u64_to_user_ptr(rr.tags));
10004 case IORING_RSRC_BUFFER:
10005 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10006 rr.nr, u64_to_user_ptr(rr.tags));
10011 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10014 struct io_uring_task *tctx = current->io_uring;
10015 cpumask_var_t new_mask;
10018 if (!tctx || !tctx->io_wq)
10021 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10024 cpumask_clear(new_mask);
10025 if (len > cpumask_size())
10026 len = cpumask_size();
10028 if (copy_from_user(new_mask, arg, len)) {
10029 free_cpumask_var(new_mask);
10033 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10034 free_cpumask_var(new_mask);
10038 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10040 struct io_uring_task *tctx = current->io_uring;
10042 if (!tctx || !tctx->io_wq)
10045 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10048 static bool io_register_op_must_quiesce(int op)
10051 case IORING_REGISTER_BUFFERS:
10052 case IORING_UNREGISTER_BUFFERS:
10053 case IORING_REGISTER_FILES:
10054 case IORING_UNREGISTER_FILES:
10055 case IORING_REGISTER_FILES_UPDATE:
10056 case IORING_REGISTER_PROBE:
10057 case IORING_REGISTER_PERSONALITY:
10058 case IORING_UNREGISTER_PERSONALITY:
10059 case IORING_REGISTER_FILES2:
10060 case IORING_REGISTER_FILES_UPDATE2:
10061 case IORING_REGISTER_BUFFERS2:
10062 case IORING_REGISTER_BUFFERS_UPDATE:
10063 case IORING_REGISTER_IOWQ_AFF:
10064 case IORING_UNREGISTER_IOWQ_AFF:
10071 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10072 void __user *arg, unsigned nr_args)
10073 __releases(ctx->uring_lock)
10074 __acquires(ctx->uring_lock)
10079 * We're inside the ring mutex, if the ref is already dying, then
10080 * someone else killed the ctx or is already going through
10081 * io_uring_register().
10083 if (percpu_ref_is_dying(&ctx->refs))
10086 if (ctx->restricted) {
10087 if (opcode >= IORING_REGISTER_LAST)
10089 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10090 if (!test_bit(opcode, ctx->restrictions.register_op))
10094 if (io_register_op_must_quiesce(opcode)) {
10095 percpu_ref_kill(&ctx->refs);
10098 * Drop uring mutex before waiting for references to exit. If
10099 * another thread is currently inside io_uring_enter() it might
10100 * need to grab the uring_lock to make progress. If we hold it
10101 * here across the drain wait, then we can deadlock. It's safe
10102 * to drop the mutex here, since no new references will come in
10103 * after we've killed the percpu ref.
10105 mutex_unlock(&ctx->uring_lock);
10107 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10110 ret = io_run_task_work_sig();
10114 mutex_lock(&ctx->uring_lock);
10117 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10123 case IORING_REGISTER_BUFFERS:
10124 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10126 case IORING_UNREGISTER_BUFFERS:
10128 if (arg || nr_args)
10130 ret = io_sqe_buffers_unregister(ctx);
10132 case IORING_REGISTER_FILES:
10133 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10135 case IORING_UNREGISTER_FILES:
10137 if (arg || nr_args)
10139 ret = io_sqe_files_unregister(ctx);
10141 case IORING_REGISTER_FILES_UPDATE:
10142 ret = io_register_files_update(ctx, arg, nr_args);
10144 case IORING_REGISTER_EVENTFD:
10145 case IORING_REGISTER_EVENTFD_ASYNC:
10149 ret = io_eventfd_register(ctx, arg);
10152 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10153 ctx->eventfd_async = 1;
10155 ctx->eventfd_async = 0;
10157 case IORING_UNREGISTER_EVENTFD:
10159 if (arg || nr_args)
10161 ret = io_eventfd_unregister(ctx);
10163 case IORING_REGISTER_PROBE:
10165 if (!arg || nr_args > 256)
10167 ret = io_probe(ctx, arg, nr_args);
10169 case IORING_REGISTER_PERSONALITY:
10171 if (arg || nr_args)
10173 ret = io_register_personality(ctx);
10175 case IORING_UNREGISTER_PERSONALITY:
10179 ret = io_unregister_personality(ctx, nr_args);
10181 case IORING_REGISTER_ENABLE_RINGS:
10183 if (arg || nr_args)
10185 ret = io_register_enable_rings(ctx);
10187 case IORING_REGISTER_RESTRICTIONS:
10188 ret = io_register_restrictions(ctx, arg, nr_args);
10190 case IORING_REGISTER_FILES2:
10191 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10193 case IORING_REGISTER_FILES_UPDATE2:
10194 ret = io_register_rsrc_update(ctx, arg, nr_args,
10197 case IORING_REGISTER_BUFFERS2:
10198 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10200 case IORING_REGISTER_BUFFERS_UPDATE:
10201 ret = io_register_rsrc_update(ctx, arg, nr_args,
10202 IORING_RSRC_BUFFER);
10204 case IORING_REGISTER_IOWQ_AFF:
10206 if (!arg || !nr_args)
10208 ret = io_register_iowq_aff(ctx, arg, nr_args);
10210 case IORING_UNREGISTER_IOWQ_AFF:
10212 if (arg || nr_args)
10214 ret = io_unregister_iowq_aff(ctx);
10221 if (io_register_op_must_quiesce(opcode)) {
10222 /* bring the ctx back to life */
10223 percpu_ref_reinit(&ctx->refs);
10224 reinit_completion(&ctx->ref_comp);
10229 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10230 void __user *, arg, unsigned int, nr_args)
10232 struct io_ring_ctx *ctx;
10241 if (f.file->f_op != &io_uring_fops)
10244 ctx = f.file->private_data;
10246 io_run_task_work();
10248 mutex_lock(&ctx->uring_lock);
10249 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10250 mutex_unlock(&ctx->uring_lock);
10251 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10252 ctx->cq_ev_fd != NULL, ret);
10258 static int __init io_uring_init(void)
10260 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10261 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10262 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10265 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10266 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10267 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10268 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10269 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10270 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10271 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10272 BUILD_BUG_SQE_ELEM(8, __u64, off);
10273 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10274 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10275 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10276 BUILD_BUG_SQE_ELEM(24, __u32, len);
10277 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10278 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10279 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10280 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10281 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10282 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10283 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10284 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10285 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10286 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10287 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10288 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10289 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10290 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10291 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10292 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10293 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10294 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10295 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10296 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10298 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10299 sizeof(struct io_uring_rsrc_update));
10300 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10301 sizeof(struct io_uring_rsrc_update2));
10302 /* should fit into one byte */
10303 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10305 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10306 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10308 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10312 __initcall(io_uring_init);