1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/fs_struct.h>
78 #include <linux/splice.h>
79 #include <linux/task_work.h>
80 #include <linux/pagemap.h>
81 #include <linux/io_uring.h>
82 #include <linux/blk-cgroup.h>
83 #include <linux/audit.h>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
97 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
99 #define IORING_FILE_TABLE_SHIFT 9
100 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
101 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
102 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
103 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
104 IORING_REGISTER_LAST + IORING_OP_LAST)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
111 u32 head ____cacheline_aligned_in_smp;
112 u32 tail ____cacheline_aligned_in_smp;
116 * This data is shared with the application through the mmap at offsets
117 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
119 * The offsets to the member fields are published through struct
120 * io_sqring_offsets when calling io_uring_setup.
124 * Head and tail offsets into the ring; the offsets need to be
125 * masked to get valid indices.
127 * The kernel controls head of the sq ring and the tail of the cq ring,
128 * and the application controls tail of the sq ring and the head of the
131 struct io_uring sq, cq;
133 * Bitmasks to apply to head and tail offsets (constant, equals
136 u32 sq_ring_mask, cq_ring_mask;
137 /* Ring sizes (constant, power of 2) */
138 u32 sq_ring_entries, cq_ring_entries;
140 * Number of invalid entries dropped by the kernel due to
141 * invalid index stored in array
143 * Written by the kernel, shouldn't be modified by the
144 * application (i.e. get number of "new events" by comparing to
147 * After a new SQ head value was read by the application this
148 * counter includes all submissions that were dropped reaching
149 * the new SQ head (and possibly more).
155 * Written by the kernel, shouldn't be modified by the
158 * The application needs a full memory barrier before checking
159 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
165 * Written by the application, shouldn't be modified by the
170 * Number of completion events lost because the queue was full;
171 * this should be avoided by the application by making sure
172 * there are not more requests pending than there is space in
173 * the completion queue.
175 * Written by the kernel, shouldn't be modified by the
176 * application (i.e. get number of "new events" by comparing to
179 * As completion events come in out of order this counter is not
180 * ordered with any other data.
184 * Ring buffer of completion events.
186 * The kernel writes completion events fresh every time they are
187 * produced, so the application is allowed to modify pending
190 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
193 enum io_uring_cmd_flags {
194 IO_URING_F_NONBLOCK = 1,
195 IO_URING_F_COMPLETE_DEFER = 2,
198 struct io_mapped_ubuf {
201 struct bio_vec *bvec;
202 unsigned int nr_bvecs;
203 unsigned long acct_pages;
209 struct list_head list;
216 struct fixed_rsrc_table {
220 struct fixed_rsrc_ref_node {
221 struct percpu_ref refs;
222 struct list_head node;
223 struct list_head rsrc_list;
224 struct fixed_rsrc_data *rsrc_data;
225 void (*rsrc_put)(struct io_ring_ctx *ctx,
226 struct io_rsrc_put *prsrc);
227 struct llist_node llist;
231 struct fixed_rsrc_data {
232 struct fixed_rsrc_table *table;
233 struct io_ring_ctx *ctx;
235 struct fixed_rsrc_ref_node *node;
236 struct percpu_ref refs;
237 struct completion done;
242 struct list_head list;
248 struct io_restriction {
249 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
250 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
251 u8 sqe_flags_allowed;
252 u8 sqe_flags_required;
257 IO_SQ_THREAD_SHOULD_STOP = 0,
258 IO_SQ_THREAD_SHOULD_PARK,
265 /* ctx's that are using this sqd */
266 struct list_head ctx_list;
267 struct list_head ctx_new_list;
268 struct mutex ctx_lock;
270 struct task_struct *thread;
271 struct wait_queue_head wait;
273 unsigned sq_thread_idle;
278 struct completion startup;
279 struct completion completion;
280 struct completion exited;
283 #define IO_IOPOLL_BATCH 8
284 #define IO_COMPL_BATCH 32
285 #define IO_REQ_CACHE_SIZE 32
286 #define IO_REQ_ALLOC_BATCH 8
288 struct io_comp_state {
289 struct io_kiocb *reqs[IO_COMPL_BATCH];
291 unsigned int locked_free_nr;
292 /* inline/task_work completion list, under ->uring_lock */
293 struct list_head free_list;
294 /* IRQ completion list, under ->completion_lock */
295 struct list_head locked_free_list;
298 struct io_submit_link {
299 struct io_kiocb *head;
300 struct io_kiocb *last;
303 struct io_submit_state {
304 struct blk_plug plug;
305 struct io_submit_link link;
308 * io_kiocb alloc cache
310 void *reqs[IO_REQ_CACHE_SIZE];
311 unsigned int free_reqs;
316 * Batch completion logic
318 struct io_comp_state comp;
321 * File reference cache
325 unsigned int file_refs;
326 unsigned int ios_left;
331 struct percpu_ref refs;
332 } ____cacheline_aligned_in_smp;
336 unsigned int compat: 1;
337 unsigned int cq_overflow_flushed: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
341 unsigned int sqo_dead: 1;
344 * Ring buffer of indices into array of io_uring_sqe, which is
345 * mmapped by the application using the IORING_OFF_SQES offset.
347 * This indirection could e.g. be used to assign fixed
348 * io_uring_sqe entries to operations and only submit them to
349 * the queue when needed.
351 * The kernel modifies neither the indices array nor the entries
355 unsigned cached_sq_head;
358 unsigned sq_thread_idle;
359 unsigned cached_sq_dropped;
360 unsigned cached_cq_overflow;
361 unsigned long sq_check_overflow;
363 /* hashed buffered write serialization */
364 struct io_wq_hash *hash_map;
366 struct list_head defer_list;
367 struct list_head timeout_list;
368 struct list_head cq_overflow_list;
370 struct io_uring_sqe *sq_sqes;
371 } ____cacheline_aligned_in_smp;
374 struct mutex uring_lock;
375 wait_queue_head_t wait;
376 } ____cacheline_aligned_in_smp;
378 struct io_submit_state submit_state;
380 struct io_rings *rings;
385 struct task_struct *sqo_task;
387 /* Only used for accounting purposes */
388 struct mm_struct *mm_account;
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
396 * If used, fixed file set. Writers must ensure that ->refs is dead,
397 * readers must ensure that ->refs is alive as long as the file* is
398 * used. Only updated through io_uring_register(2).
400 struct fixed_rsrc_data *file_data;
401 unsigned nr_user_files;
403 /* if used, fixed mapped user buffers */
404 unsigned nr_user_bufs;
405 struct io_mapped_ubuf *user_bufs;
407 struct user_struct *user;
409 struct completion ref_comp;
410 struct completion sq_thread_comp;
412 #if defined(CONFIG_UNIX)
413 struct socket *ring_sock;
416 struct idr io_buffer_idr;
418 struct idr personality_idr;
421 unsigned cached_cq_tail;
424 atomic_t cq_timeouts;
425 unsigned cq_last_tm_flush;
426 unsigned long cq_check_overflow;
427 struct wait_queue_head cq_wait;
428 struct fasync_struct *cq_fasync;
429 struct eventfd_ctx *cq_ev_fd;
430 } ____cacheline_aligned_in_smp;
433 spinlock_t completion_lock;
436 * ->iopoll_list is protected by the ctx->uring_lock for
437 * io_uring instances that don't use IORING_SETUP_SQPOLL.
438 * For SQPOLL, only the single threaded io_sq_thread() will
439 * manipulate the list, hence no extra locking is needed there.
441 struct list_head iopoll_list;
442 struct hlist_head *cancel_hash;
443 unsigned cancel_hash_bits;
444 bool poll_multi_file;
446 spinlock_t inflight_lock;
447 struct list_head inflight_list;
448 } ____cacheline_aligned_in_smp;
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;
455 struct io_restriction restrictions;
458 struct callback_head *exit_task_work;
460 struct wait_queue_head hash_wait;
462 /* Keep this last, we don't need it for the fast path */
463 struct work_struct exit_work;
467 * First field must be the file pointer in all the
468 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
470 struct io_poll_iocb {
472 struct wait_queue_head *head;
476 struct wait_queue_entry wait;
479 struct io_poll_remove {
489 struct io_timeout_data {
490 struct io_kiocb *req;
491 struct hrtimer timer;
492 struct timespec64 ts;
493 enum hrtimer_mode mode;
498 struct sockaddr __user *addr;
499 int __user *addr_len;
501 unsigned long nofile;
521 struct list_head list;
522 /* head of the link, used by linked timeouts only */
523 struct io_kiocb *head;
526 struct io_timeout_rem {
531 struct timespec64 ts;
536 /* NOTE: kiocb has the file as the first member, so don't do it here */
544 struct sockaddr __user *addr;
551 struct user_msghdr __user *umsg;
557 struct io_buffer *kbuf;
563 struct filename *filename;
565 unsigned long nofile;
568 struct io_rsrc_update {
594 struct epoll_event event;
598 struct file *file_out;
599 struct file *file_in;
606 struct io_provide_buf {
620 const char __user *filename;
621 struct statx __user *buffer;
633 struct filename *oldpath;
634 struct filename *newpath;
642 struct filename *filename;
645 struct io_completion {
647 struct list_head list;
651 struct io_async_connect {
652 struct sockaddr_storage address;
655 struct io_async_msghdr {
656 struct iovec fast_iov[UIO_FASTIOV];
657 /* points to an allocated iov, if NULL we use fast_iov instead */
658 struct iovec *free_iov;
659 struct sockaddr __user *uaddr;
661 struct sockaddr_storage addr;
665 struct iovec fast_iov[UIO_FASTIOV];
666 const struct iovec *free_iovec;
667 struct iov_iter iter;
669 struct wait_page_queue wpq;
673 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
674 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
675 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
676 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
677 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
678 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
684 REQ_F_LINK_TIMEOUT_BIT,
686 REQ_F_NEED_CLEANUP_BIT,
688 REQ_F_BUFFER_SELECTED_BIT,
689 REQ_F_NO_FILE_TABLE_BIT,
690 REQ_F_WORK_INITIALIZED_BIT,
691 REQ_F_LTIMEOUT_ACTIVE_BIT,
692 REQ_F_COMPLETE_INLINE_BIT,
694 /* not a real bit, just to check we're not overflowing the space */
700 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
701 /* drain existing IO first */
702 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
704 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
705 /* doesn't sever on completion < 0 */
706 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
708 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
709 /* IOSQE_BUFFER_SELECT */
710 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
712 /* fail rest of links */
713 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
714 /* on inflight list */
715 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
716 /* read/write uses file position */
717 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
718 /* must not punt to workers */
719 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
720 /* has or had linked timeout */
721 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
723 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
725 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
726 /* already went through poll handler */
727 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
728 /* buffer already selected */
729 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
730 /* doesn't need file table for this request */
731 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
732 /* io_wq_work is initialized */
733 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
734 /* linked timeout is active, i.e. prepared by link's head */
735 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
736 /* completion is deferred through io_comp_state */
737 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
741 struct io_poll_iocb poll;
742 struct io_poll_iocb *double_poll;
745 struct io_task_work {
746 struct io_wq_work_node node;
747 task_work_func_t func;
751 * NOTE! Each of the iocb union members has the file pointer
752 * as the first entry in their struct definition. So you can
753 * access the file pointer through any of the sub-structs,
754 * or directly as just 'ki_filp' in this struct.
760 struct io_poll_iocb poll;
761 struct io_poll_remove poll_remove;
762 struct io_accept accept;
764 struct io_cancel cancel;
765 struct io_timeout timeout;
766 struct io_timeout_rem timeout_rem;
767 struct io_connect connect;
768 struct io_sr_msg sr_msg;
770 struct io_close close;
771 struct io_rsrc_update rsrc_update;
772 struct io_fadvise fadvise;
773 struct io_madvise madvise;
774 struct io_epoll epoll;
775 struct io_splice splice;
776 struct io_provide_buf pbuf;
777 struct io_statx statx;
778 struct io_shutdown shutdown;
779 struct io_rename rename;
780 struct io_unlink unlink;
781 /* use only after cleaning per-op data, see io_clean_op() */
782 struct io_completion compl;
785 /* opcode allocated if it needs to store data for async defer */
788 /* polled IO has completed */
794 struct io_ring_ctx *ctx;
797 struct task_struct *task;
800 struct io_kiocb *link;
801 struct percpu_ref *fixed_rsrc_refs;
804 * 1. used with ctx->iopoll_list with reads/writes
805 * 2. to track reqs with ->files (see io_op_def::file_table)
807 struct list_head inflight_entry;
809 struct io_task_work io_task_work;
810 struct callback_head task_work;
812 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
813 struct hlist_node hash_node;
814 struct async_poll *apoll;
815 struct io_wq_work work;
818 struct io_defer_entry {
819 struct list_head list;
820 struct io_kiocb *req;
825 /* needs req->file assigned */
826 unsigned needs_file : 1;
827 /* hash wq insertion if file is a regular file */
828 unsigned hash_reg_file : 1;
829 /* unbound wq insertion if file is a non-regular file */
830 unsigned unbound_nonreg_file : 1;
831 /* opcode is not supported by this kernel */
832 unsigned not_supported : 1;
833 /* set if opcode supports polled "wait" */
835 unsigned pollout : 1;
836 /* op supports buffer selection */
837 unsigned buffer_select : 1;
838 /* must always have async data allocated */
839 unsigned needs_async_data : 1;
840 /* should block plug */
842 /* size of async data needed, if any */
843 unsigned short async_size;
846 static const struct io_op_def io_op_defs[] = {
847 [IORING_OP_NOP] = {},
848 [IORING_OP_READV] = {
850 .unbound_nonreg_file = 1,
853 .needs_async_data = 1,
855 .async_size = sizeof(struct io_async_rw),
857 [IORING_OP_WRITEV] = {
860 .unbound_nonreg_file = 1,
862 .needs_async_data = 1,
864 .async_size = sizeof(struct io_async_rw),
866 [IORING_OP_FSYNC] = {
869 [IORING_OP_READ_FIXED] = {
871 .unbound_nonreg_file = 1,
874 .async_size = sizeof(struct io_async_rw),
876 [IORING_OP_WRITE_FIXED] = {
879 .unbound_nonreg_file = 1,
882 .async_size = sizeof(struct io_async_rw),
884 [IORING_OP_POLL_ADD] = {
886 .unbound_nonreg_file = 1,
888 [IORING_OP_POLL_REMOVE] = {},
889 [IORING_OP_SYNC_FILE_RANGE] = {
892 [IORING_OP_SENDMSG] = {
894 .unbound_nonreg_file = 1,
896 .needs_async_data = 1,
897 .async_size = sizeof(struct io_async_msghdr),
899 [IORING_OP_RECVMSG] = {
901 .unbound_nonreg_file = 1,
904 .needs_async_data = 1,
905 .async_size = sizeof(struct io_async_msghdr),
907 [IORING_OP_TIMEOUT] = {
908 .needs_async_data = 1,
909 .async_size = sizeof(struct io_timeout_data),
911 [IORING_OP_TIMEOUT_REMOVE] = {
912 /* used by timeout updates' prep() */
914 [IORING_OP_ACCEPT] = {
916 .unbound_nonreg_file = 1,
919 [IORING_OP_ASYNC_CANCEL] = {},
920 [IORING_OP_LINK_TIMEOUT] = {
921 .needs_async_data = 1,
922 .async_size = sizeof(struct io_timeout_data),
924 [IORING_OP_CONNECT] = {
926 .unbound_nonreg_file = 1,
928 .needs_async_data = 1,
929 .async_size = sizeof(struct io_async_connect),
931 [IORING_OP_FALLOCATE] = {
934 [IORING_OP_OPENAT] = {},
935 [IORING_OP_CLOSE] = {},
936 [IORING_OP_FILES_UPDATE] = {},
937 [IORING_OP_STATX] = {},
940 .unbound_nonreg_file = 1,
944 .async_size = sizeof(struct io_async_rw),
946 [IORING_OP_WRITE] = {
948 .unbound_nonreg_file = 1,
951 .async_size = sizeof(struct io_async_rw),
953 [IORING_OP_FADVISE] = {
956 [IORING_OP_MADVISE] = {},
959 .unbound_nonreg_file = 1,
964 .unbound_nonreg_file = 1,
968 [IORING_OP_OPENAT2] = {
970 [IORING_OP_EPOLL_CTL] = {
971 .unbound_nonreg_file = 1,
973 [IORING_OP_SPLICE] = {
976 .unbound_nonreg_file = 1,
978 [IORING_OP_PROVIDE_BUFFERS] = {},
979 [IORING_OP_REMOVE_BUFFERS] = {},
983 .unbound_nonreg_file = 1,
985 [IORING_OP_SHUTDOWN] = {
988 [IORING_OP_RENAMEAT] = {},
989 [IORING_OP_UNLINKAT] = {},
992 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
993 struct task_struct *task,
994 struct files_struct *files);
995 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
996 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
997 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
998 struct io_ring_ctx *ctx);
999 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
1001 static bool io_rw_reissue(struct io_kiocb *req);
1002 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1003 static void io_put_req(struct io_kiocb *req);
1004 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1005 static void io_double_put_req(struct io_kiocb *req);
1006 static void io_dismantle_req(struct io_kiocb *req);
1007 static void io_put_task(struct task_struct *task, int nr);
1008 static void io_queue_next(struct io_kiocb *req);
1009 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1010 static void __io_queue_linked_timeout(struct io_kiocb *req);
1011 static void io_queue_linked_timeout(struct io_kiocb *req);
1012 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1013 struct io_uring_rsrc_update *ip,
1015 static void __io_clean_op(struct io_kiocb *req);
1016 static struct file *io_file_get(struct io_submit_state *state,
1017 struct io_kiocb *req, int fd, bool fixed);
1018 static void __io_queue_sqe(struct io_kiocb *req);
1019 static void io_rsrc_put_work(struct work_struct *work);
1021 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1022 struct iov_iter *iter, bool needs_lock);
1023 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1024 const struct iovec *fast_iov,
1025 struct iov_iter *iter, bool force);
1026 static void io_req_task_queue(struct io_kiocb *req);
1027 static void io_submit_flush_completions(struct io_comp_state *cs,
1028 struct io_ring_ctx *ctx);
1030 static struct kmem_cache *req_cachep;
1032 static const struct file_operations io_uring_fops;
1034 struct sock *io_uring_get_socket(struct file *file)
1036 #if defined(CONFIG_UNIX)
1037 if (file->f_op == &io_uring_fops) {
1038 struct io_ring_ctx *ctx = file->private_data;
1040 return ctx->ring_sock->sk;
1045 EXPORT_SYMBOL(io_uring_get_socket);
1047 #define io_for_each_link(pos, head) \
1048 for (pos = (head); pos; pos = pos->link)
1050 static inline void io_clean_op(struct io_kiocb *req)
1052 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1056 static inline void io_set_resource_node(struct io_kiocb *req)
1058 struct io_ring_ctx *ctx = req->ctx;
1060 if (!req->fixed_rsrc_refs) {
1061 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1062 percpu_ref_get(req->fixed_rsrc_refs);
1066 static bool io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1068 if (!percpu_ref_tryget(ref)) {
1069 /* already at zero, wait for ->release() */
1070 if (!try_wait_for_completion(compl))
1075 percpu_ref_resurrect(ref);
1076 reinit_completion(compl);
1077 percpu_ref_put(ref);
1081 static bool io_match_task(struct io_kiocb *head,
1082 struct task_struct *task,
1083 struct files_struct *files)
1085 struct io_kiocb *req;
1087 if (task && head->task != task) {
1088 /* in terms of cancelation, always match if req task is dead */
1089 if (head->task->flags & PF_EXITING)
1096 io_for_each_link(req, head) {
1097 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1099 if (req->file && req->file->f_op == &io_uring_fops)
1101 if (req->task->files == files)
1107 static inline void req_set_fail_links(struct io_kiocb *req)
1109 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1110 req->flags |= REQ_F_FAIL_LINK;
1113 static inline void __io_req_init_async(struct io_kiocb *req)
1115 memset(&req->work, 0, sizeof(req->work));
1116 req->flags |= REQ_F_WORK_INITIALIZED;
1120 * Note: must call io_req_init_async() for the first time you
1121 * touch any members of io_wq_work.
1123 static inline void io_req_init_async(struct io_kiocb *req)
1125 if (req->flags & REQ_F_WORK_INITIALIZED)
1128 __io_req_init_async(req);
1131 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1133 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1135 complete(&ctx->ref_comp);
1138 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1140 return !req->timeout.off;
1143 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1145 struct io_ring_ctx *ctx;
1148 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1153 * Use 5 bits less than the max cq entries, that should give us around
1154 * 32 entries per hash list if totally full and uniformly spread.
1156 hash_bits = ilog2(p->cq_entries);
1160 ctx->cancel_hash_bits = hash_bits;
1161 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1163 if (!ctx->cancel_hash)
1165 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1167 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1168 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1171 ctx->flags = p->flags;
1172 init_waitqueue_head(&ctx->sqo_sq_wait);
1173 INIT_LIST_HEAD(&ctx->sqd_list);
1174 init_waitqueue_head(&ctx->cq_wait);
1175 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1176 init_completion(&ctx->ref_comp);
1177 init_completion(&ctx->sq_thread_comp);
1178 idr_init(&ctx->io_buffer_idr);
1179 idr_init(&ctx->personality_idr);
1180 mutex_init(&ctx->uring_lock);
1181 init_waitqueue_head(&ctx->wait);
1182 spin_lock_init(&ctx->completion_lock);
1183 INIT_LIST_HEAD(&ctx->iopoll_list);
1184 INIT_LIST_HEAD(&ctx->defer_list);
1185 INIT_LIST_HEAD(&ctx->timeout_list);
1186 spin_lock_init(&ctx->inflight_lock);
1187 INIT_LIST_HEAD(&ctx->inflight_list);
1188 spin_lock_init(&ctx->rsrc_ref_lock);
1189 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1190 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1191 init_llist_head(&ctx->rsrc_put_llist);
1192 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1193 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1196 kfree(ctx->cancel_hash);
1201 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1203 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1204 struct io_ring_ctx *ctx = req->ctx;
1206 return seq != ctx->cached_cq_tail
1207 + READ_ONCE(ctx->cached_cq_overflow);
1213 static void io_req_clean_work(struct io_kiocb *req)
1215 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1218 if (req->work.creds) {
1219 put_cred(req->work.creds);
1220 req->work.creds = NULL;
1222 if (req->flags & REQ_F_INFLIGHT) {
1223 struct io_ring_ctx *ctx = req->ctx;
1224 struct io_uring_task *tctx = req->task->io_uring;
1225 unsigned long flags;
1227 spin_lock_irqsave(&ctx->inflight_lock, flags);
1228 list_del(&req->inflight_entry);
1229 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1230 req->flags &= ~REQ_F_INFLIGHT;
1231 if (atomic_read(&tctx->in_idle))
1232 wake_up(&tctx->wait);
1235 req->flags &= ~REQ_F_WORK_INITIALIZED;
1238 static void io_req_track_inflight(struct io_kiocb *req)
1240 struct io_ring_ctx *ctx = req->ctx;
1242 if (!(req->flags & REQ_F_INFLIGHT)) {
1243 io_req_init_async(req);
1244 req->flags |= REQ_F_INFLIGHT;
1246 spin_lock_irq(&ctx->inflight_lock);
1247 list_add(&req->inflight_entry, &ctx->inflight_list);
1248 spin_unlock_irq(&ctx->inflight_lock);
1252 static void io_prep_async_work(struct io_kiocb *req)
1254 const struct io_op_def *def = &io_op_defs[req->opcode];
1255 struct io_ring_ctx *ctx = req->ctx;
1257 io_req_init_async(req);
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));
1266 if (def->unbound_nonreg_file)
1267 req->work.flags |= IO_WQ_WORK_UNBOUND;
1269 if (!req->work.creds)
1270 req->work.creds = get_current_cred();
1273 static void io_prep_async_link(struct io_kiocb *req)
1275 struct io_kiocb *cur;
1277 io_for_each_link(cur, req)
1278 io_prep_async_work(cur);
1281 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1283 struct io_ring_ctx *ctx = req->ctx;
1284 struct io_kiocb *link = io_prep_linked_timeout(req);
1285 struct io_uring_task *tctx = req->task->io_uring;
1288 BUG_ON(!tctx->io_wq);
1290 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1291 &req->work, req->flags);
1292 io_wq_enqueue(tctx->io_wq, &req->work);
1296 static void io_queue_async_work(struct io_kiocb *req)
1298 struct io_kiocb *link;
1300 /* init ->work of the whole link before punting */
1301 io_prep_async_link(req);
1302 link = __io_queue_async_work(req);
1305 io_queue_linked_timeout(link);
1308 static void io_kill_timeout(struct io_kiocb *req)
1310 struct io_timeout_data *io = req->async_data;
1313 ret = hrtimer_try_to_cancel(&io->timer);
1315 atomic_set(&req->ctx->cq_timeouts,
1316 atomic_read(&req->ctx->cq_timeouts) + 1);
1317 list_del_init(&req->timeout.list);
1318 io_cqring_fill_event(req, 0);
1319 io_put_req_deferred(req, 1);
1324 * Returns true if we found and killed one or more timeouts
1326 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1327 struct files_struct *files)
1329 struct io_kiocb *req, *tmp;
1332 spin_lock_irq(&ctx->completion_lock);
1333 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1334 if (io_match_task(req, tsk, files)) {
1335 io_kill_timeout(req);
1339 spin_unlock_irq(&ctx->completion_lock);
1340 return canceled != 0;
1343 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1346 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1347 struct io_defer_entry, list);
1349 if (req_need_defer(de->req, de->seq))
1351 list_del_init(&de->list);
1352 io_req_task_queue(de->req);
1354 } while (!list_empty(&ctx->defer_list));
1357 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1361 if (list_empty(&ctx->timeout_list))
1364 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1367 u32 events_needed, events_got;
1368 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1369 struct io_kiocb, timeout.list);
1371 if (io_is_timeout_noseq(req))
1375 * Since seq can easily wrap around over time, subtract
1376 * the last seq at which timeouts were flushed before comparing.
1377 * Assuming not more than 2^31-1 events have happened since,
1378 * these subtractions won't have wrapped, so we can check if
1379 * target is in [last_seq, current_seq] by comparing the two.
1381 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1382 events_got = seq - ctx->cq_last_tm_flush;
1383 if (events_got < events_needed)
1386 list_del_init(&req->timeout.list);
1387 io_kill_timeout(req);
1388 } while (!list_empty(&ctx->timeout_list));
1390 ctx->cq_last_tm_flush = seq;
1393 static void io_commit_cqring(struct io_ring_ctx *ctx)
1395 io_flush_timeouts(ctx);
1397 /* order cqe stores with ring update */
1398 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1400 if (unlikely(!list_empty(&ctx->defer_list)))
1401 __io_queue_deferred(ctx);
1404 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1406 struct io_rings *r = ctx->rings;
1408 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1411 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1413 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1416 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1418 struct io_rings *rings = ctx->rings;
1422 * writes to the cq entry need to come after reading head; the
1423 * control dependency is enough as we're using WRITE_ONCE to
1426 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1429 tail = ctx->cached_cq_tail++;
1430 return &rings->cqes[tail & ctx->cq_mask];
1433 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1437 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1439 if (!ctx->eventfd_async)
1441 return io_wq_current_is_worker();
1444 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1446 /* see waitqueue_active() comment */
1449 if (waitqueue_active(&ctx->wait))
1450 wake_up(&ctx->wait);
1451 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1452 wake_up(&ctx->sq_data->wait);
1453 if (io_should_trigger_evfd(ctx))
1454 eventfd_signal(ctx->cq_ev_fd, 1);
1455 if (waitqueue_active(&ctx->cq_wait)) {
1456 wake_up_interruptible(&ctx->cq_wait);
1457 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1461 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1463 /* see waitqueue_active() comment */
1466 if (ctx->flags & IORING_SETUP_SQPOLL) {
1467 if (waitqueue_active(&ctx->wait))
1468 wake_up(&ctx->wait);
1470 if (io_should_trigger_evfd(ctx))
1471 eventfd_signal(ctx->cq_ev_fd, 1);
1472 if (waitqueue_active(&ctx->cq_wait)) {
1473 wake_up_interruptible(&ctx->cq_wait);
1474 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1478 /* Returns true if there are no backlogged entries after the flush */
1479 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1480 struct task_struct *tsk,
1481 struct files_struct *files)
1483 struct io_rings *rings = ctx->rings;
1484 struct io_kiocb *req, *tmp;
1485 struct io_uring_cqe *cqe;
1486 unsigned long flags;
1487 bool all_flushed, posted;
1490 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1494 spin_lock_irqsave(&ctx->completion_lock, flags);
1495 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1496 if (!io_match_task(req, tsk, files))
1499 cqe = io_get_cqring(ctx);
1503 list_move(&req->compl.list, &list);
1505 WRITE_ONCE(cqe->user_data, req->user_data);
1506 WRITE_ONCE(cqe->res, req->result);
1507 WRITE_ONCE(cqe->flags, req->compl.cflags);
1509 ctx->cached_cq_overflow++;
1510 WRITE_ONCE(ctx->rings->cq_overflow,
1511 ctx->cached_cq_overflow);
1516 all_flushed = list_empty(&ctx->cq_overflow_list);
1518 clear_bit(0, &ctx->sq_check_overflow);
1519 clear_bit(0, &ctx->cq_check_overflow);
1520 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1524 io_commit_cqring(ctx);
1525 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1527 io_cqring_ev_posted(ctx);
1529 while (!list_empty(&list)) {
1530 req = list_first_entry(&list, struct io_kiocb, compl.list);
1531 list_del(&req->compl.list);
1538 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1539 struct task_struct *tsk,
1540 struct files_struct *files)
1542 if (test_bit(0, &ctx->cq_check_overflow)) {
1543 /* iopoll syncs against uring_lock, not completion_lock */
1544 if (ctx->flags & IORING_SETUP_IOPOLL)
1545 mutex_lock(&ctx->uring_lock);
1546 __io_cqring_overflow_flush(ctx, force, tsk, files);
1547 if (ctx->flags & IORING_SETUP_IOPOLL)
1548 mutex_unlock(&ctx->uring_lock);
1552 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1554 struct io_ring_ctx *ctx = req->ctx;
1555 struct io_uring_cqe *cqe;
1557 trace_io_uring_complete(ctx, req->user_data, res);
1560 * If we can't get a cq entry, userspace overflowed the
1561 * submission (by quite a lot). Increment the overflow count in
1564 cqe = io_get_cqring(ctx);
1566 WRITE_ONCE(cqe->user_data, req->user_data);
1567 WRITE_ONCE(cqe->res, res);
1568 WRITE_ONCE(cqe->flags, cflags);
1569 } else if (ctx->cq_overflow_flushed ||
1570 atomic_read(&req->task->io_uring->in_idle)) {
1572 * If we're in ring overflow flush mode, or in task cancel mode,
1573 * then we cannot store the request for later flushing, we need
1574 * to drop it on the floor.
1576 ctx->cached_cq_overflow++;
1577 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1579 if (list_empty(&ctx->cq_overflow_list)) {
1580 set_bit(0, &ctx->sq_check_overflow);
1581 set_bit(0, &ctx->cq_check_overflow);
1582 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1586 req->compl.cflags = cflags;
1587 refcount_inc(&req->refs);
1588 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1592 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1594 __io_cqring_fill_event(req, res, 0);
1597 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1598 unsigned int cflags)
1600 struct io_ring_ctx *ctx = req->ctx;
1601 unsigned long flags;
1603 spin_lock_irqsave(&ctx->completion_lock, flags);
1604 __io_cqring_fill_event(req, res, cflags);
1605 io_commit_cqring(ctx);
1607 * If we're the last reference to this request, add to our locked
1610 if (refcount_dec_and_test(&req->refs)) {
1611 struct io_comp_state *cs = &ctx->submit_state.comp;
1613 io_dismantle_req(req);
1614 io_put_task(req->task, 1);
1615 list_add(&req->compl.list, &cs->locked_free_list);
1616 cs->locked_free_nr++;
1619 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1621 io_cqring_ev_posted(ctx);
1624 percpu_ref_put(&ctx->refs);
1628 static void io_req_complete_state(struct io_kiocb *req, long res,
1629 unsigned int cflags)
1633 req->compl.cflags = cflags;
1634 req->flags |= REQ_F_COMPLETE_INLINE;
1637 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1638 long res, unsigned cflags)
1640 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1641 io_req_complete_state(req, res, cflags);
1643 io_req_complete_post(req, res, cflags);
1646 static inline void io_req_complete(struct io_kiocb *req, long res)
1648 __io_req_complete(req, 0, res, 0);
1651 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1653 struct io_submit_state *state = &ctx->submit_state;
1654 struct io_comp_state *cs = &state->comp;
1655 struct io_kiocb *req = NULL;
1658 * If we have more than a batch's worth of requests in our IRQ side
1659 * locked cache, grab the lock and move them over to our submission
1662 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1663 spin_lock_irq(&ctx->completion_lock);
1664 list_splice_init(&cs->locked_free_list, &cs->free_list);
1665 cs->locked_free_nr = 0;
1666 spin_unlock_irq(&ctx->completion_lock);
1669 while (!list_empty(&cs->free_list)) {
1670 req = list_first_entry(&cs->free_list, struct io_kiocb,
1672 list_del(&req->compl.list);
1673 state->reqs[state->free_reqs++] = req;
1674 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1681 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1683 struct io_submit_state *state = &ctx->submit_state;
1685 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1687 if (!state->free_reqs) {
1688 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1691 if (io_flush_cached_reqs(ctx))
1694 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1698 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1699 * retry single alloc to be on the safe side.
1701 if (unlikely(ret <= 0)) {
1702 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1703 if (!state->reqs[0])
1707 state->free_reqs = ret;
1711 return state->reqs[state->free_reqs];
1714 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1721 static void io_dismantle_req(struct io_kiocb *req)
1725 if (req->async_data)
1726 kfree(req->async_data);
1728 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1729 if (req->fixed_rsrc_refs)
1730 percpu_ref_put(req->fixed_rsrc_refs);
1731 io_req_clean_work(req);
1734 static inline void io_put_task(struct task_struct *task, int nr)
1736 struct io_uring_task *tctx = task->io_uring;
1738 percpu_counter_sub(&tctx->inflight, nr);
1739 if (unlikely(atomic_read(&tctx->in_idle)))
1740 wake_up(&tctx->wait);
1741 put_task_struct_many(task, nr);
1744 static void __io_free_req(struct io_kiocb *req)
1746 struct io_ring_ctx *ctx = req->ctx;
1748 io_dismantle_req(req);
1749 io_put_task(req->task, 1);
1751 kmem_cache_free(req_cachep, req);
1752 percpu_ref_put(&ctx->refs);
1755 static inline void io_remove_next_linked(struct io_kiocb *req)
1757 struct io_kiocb *nxt = req->link;
1759 req->link = nxt->link;
1763 static void io_kill_linked_timeout(struct io_kiocb *req)
1765 struct io_ring_ctx *ctx = req->ctx;
1766 struct io_kiocb *link;
1767 bool cancelled = false;
1768 unsigned long flags;
1770 spin_lock_irqsave(&ctx->completion_lock, flags);
1774 * Can happen if a linked timeout fired and link had been like
1775 * req -> link t-out -> link t-out [-> ...]
1777 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1778 struct io_timeout_data *io = link->async_data;
1781 io_remove_next_linked(req);
1782 link->timeout.head = NULL;
1783 ret = hrtimer_try_to_cancel(&io->timer);
1785 io_cqring_fill_event(link, -ECANCELED);
1786 io_commit_cqring(ctx);
1790 req->flags &= ~REQ_F_LINK_TIMEOUT;
1791 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1794 io_cqring_ev_posted(ctx);
1800 static void io_fail_links(struct io_kiocb *req)
1802 struct io_kiocb *link, *nxt;
1803 struct io_ring_ctx *ctx = req->ctx;
1804 unsigned long flags;
1806 spin_lock_irqsave(&ctx->completion_lock, flags);
1814 trace_io_uring_fail_link(req, link);
1815 io_cqring_fill_event(link, -ECANCELED);
1818 * It's ok to free under spinlock as they're not linked anymore,
1819 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
1822 if (link->flags & REQ_F_WORK_INITIALIZED)
1823 io_put_req_deferred(link, 2);
1825 io_double_put_req(link);
1828 io_commit_cqring(ctx);
1829 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1831 io_cqring_ev_posted(ctx);
1834 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1836 if (req->flags & REQ_F_LINK_TIMEOUT)
1837 io_kill_linked_timeout(req);
1840 * If LINK is set, we have dependent requests in this chain. If we
1841 * didn't fail this request, queue the first one up, moving any other
1842 * dependencies to the next request. In case of failure, fail the rest
1845 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
1846 struct io_kiocb *nxt = req->link;
1855 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1857 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1859 return __io_req_find_next(req);
1862 static bool __tctx_task_work(struct io_uring_task *tctx)
1864 struct io_ring_ctx *ctx = NULL;
1865 struct io_wq_work_list list;
1866 struct io_wq_work_node *node;
1868 if (wq_list_empty(&tctx->task_list))
1871 spin_lock_irq(&tctx->task_lock);
1872 list = tctx->task_list;
1873 INIT_WQ_LIST(&tctx->task_list);
1874 spin_unlock_irq(&tctx->task_lock);
1878 struct io_wq_work_node *next = node->next;
1879 struct io_ring_ctx *this_ctx;
1880 struct io_kiocb *req;
1882 req = container_of(node, struct io_kiocb, io_task_work.node);
1883 this_ctx = req->ctx;
1884 req->task_work.func(&req->task_work);
1889 } else if (ctx != this_ctx) {
1890 mutex_lock(&ctx->uring_lock);
1891 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1892 mutex_unlock(&ctx->uring_lock);
1897 if (ctx && ctx->submit_state.comp.nr) {
1898 mutex_lock(&ctx->uring_lock);
1899 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1900 mutex_unlock(&ctx->uring_lock);
1903 return list.first != NULL;
1906 static void tctx_task_work(struct callback_head *cb)
1908 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1910 while (__tctx_task_work(tctx))
1913 clear_bit(0, &tctx->task_state);
1916 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
1917 enum task_work_notify_mode notify)
1919 struct io_uring_task *tctx = tsk->io_uring;
1920 struct io_wq_work_node *node, *prev;
1921 unsigned long flags;
1924 WARN_ON_ONCE(!tctx);
1926 spin_lock_irqsave(&tctx->task_lock, flags);
1927 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1928 spin_unlock_irqrestore(&tctx->task_lock, flags);
1930 /* task_work already pending, we're done */
1931 if (test_bit(0, &tctx->task_state) ||
1932 test_and_set_bit(0, &tctx->task_state))
1935 if (!task_work_add(tsk, &tctx->task_work, notify))
1939 * Slow path - we failed, find and delete work. if the work is not
1940 * in the list, it got run and we're fine.
1943 spin_lock_irqsave(&tctx->task_lock, flags);
1944 wq_list_for_each(node, prev, &tctx->task_list) {
1945 if (&req->io_task_work.node == node) {
1946 wq_list_del(&tctx->task_list, node, prev);
1951 spin_unlock_irqrestore(&tctx->task_lock, flags);
1952 clear_bit(0, &tctx->task_state);
1956 static int io_req_task_work_add(struct io_kiocb *req)
1958 struct task_struct *tsk = req->task;
1959 struct io_ring_ctx *ctx = req->ctx;
1960 enum task_work_notify_mode notify;
1963 if (tsk->flags & PF_EXITING)
1967 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1968 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1969 * processing task_work. There's no reliable way to tell if TWA_RESUME
1973 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1974 notify = TWA_SIGNAL;
1976 ret = io_task_work_add(tsk, req, notify);
1978 wake_up_process(tsk);
1983 static void io_req_task_work_add_fallback(struct io_kiocb *req,
1984 task_work_func_t cb)
1986 struct io_ring_ctx *ctx = req->ctx;
1987 struct callback_head *head;
1989 init_task_work(&req->task_work, cb);
1991 head = READ_ONCE(ctx->exit_task_work);
1992 req->task_work.next = head;
1993 } while (cmpxchg(&ctx->exit_task_work, head, &req->task_work) != head);
1996 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1998 struct io_ring_ctx *ctx = req->ctx;
2000 spin_lock_irq(&ctx->completion_lock);
2001 io_cqring_fill_event(req, error);
2002 io_commit_cqring(ctx);
2003 spin_unlock_irq(&ctx->completion_lock);
2005 io_cqring_ev_posted(ctx);
2006 req_set_fail_links(req);
2007 io_double_put_req(req);
2010 static void io_req_task_cancel(struct callback_head *cb)
2012 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2013 struct io_ring_ctx *ctx = req->ctx;
2015 mutex_lock(&ctx->uring_lock);
2016 __io_req_task_cancel(req, req->result);
2017 mutex_unlock(&ctx->uring_lock);
2018 percpu_ref_put(&ctx->refs);
2021 static void __io_req_task_submit(struct io_kiocb *req)
2023 struct io_ring_ctx *ctx = req->ctx;
2025 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2026 mutex_lock(&ctx->uring_lock);
2027 if (!ctx->sqo_dead && !(current->flags & PF_EXITING))
2028 __io_queue_sqe(req);
2030 __io_req_task_cancel(req, -EFAULT);
2031 mutex_unlock(&ctx->uring_lock);
2034 static void io_req_task_submit(struct callback_head *cb)
2036 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2038 __io_req_task_submit(req);
2041 static void io_req_task_queue(struct io_kiocb *req)
2045 req->task_work.func = io_req_task_submit;
2046 ret = io_req_task_work_add(req);
2047 if (unlikely(ret)) {
2048 req->result = -ECANCELED;
2049 percpu_ref_get(&req->ctx->refs);
2050 io_req_task_work_add_fallback(req, io_req_task_cancel);
2054 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2056 percpu_ref_get(&req->ctx->refs);
2058 req->task_work.func = io_req_task_cancel;
2060 if (unlikely(io_req_task_work_add(req)))
2061 io_req_task_work_add_fallback(req, io_req_task_cancel);
2064 static inline void io_queue_next(struct io_kiocb *req)
2066 struct io_kiocb *nxt = io_req_find_next(req);
2069 io_req_task_queue(nxt);
2072 static void io_free_req(struct io_kiocb *req)
2079 struct task_struct *task;
2084 static inline void io_init_req_batch(struct req_batch *rb)
2091 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2092 struct req_batch *rb)
2095 io_put_task(rb->task, rb->task_refs);
2097 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2100 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2101 struct io_submit_state *state)
2105 if (req->task != rb->task) {
2107 io_put_task(rb->task, rb->task_refs);
2108 rb->task = req->task;
2114 io_dismantle_req(req);
2115 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2116 state->reqs[state->free_reqs++] = req;
2118 list_add(&req->compl.list, &state->comp.free_list);
2121 static void io_submit_flush_completions(struct io_comp_state *cs,
2122 struct io_ring_ctx *ctx)
2125 struct io_kiocb *req;
2126 struct req_batch rb;
2128 io_init_req_batch(&rb);
2129 spin_lock_irq(&ctx->completion_lock);
2130 for (i = 0; i < nr; i++) {
2132 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2134 io_commit_cqring(ctx);
2135 spin_unlock_irq(&ctx->completion_lock);
2137 io_cqring_ev_posted(ctx);
2138 for (i = 0; i < nr; i++) {
2141 /* submission and completion refs */
2142 if (refcount_sub_and_test(2, &req->refs))
2143 io_req_free_batch(&rb, req, &ctx->submit_state);
2146 io_req_free_batch_finish(ctx, &rb);
2151 * Drop reference to request, return next in chain (if there is one) if this
2152 * was the last reference to this request.
2154 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2156 struct io_kiocb *nxt = NULL;
2158 if (refcount_dec_and_test(&req->refs)) {
2159 nxt = io_req_find_next(req);
2165 static void io_put_req(struct io_kiocb *req)
2167 if (refcount_dec_and_test(&req->refs))
2171 static void io_put_req_deferred_cb(struct callback_head *cb)
2173 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2178 static void io_free_req_deferred(struct io_kiocb *req)
2182 req->task_work.func = io_put_req_deferred_cb;
2183 ret = io_req_task_work_add(req);
2185 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2188 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2190 if (refcount_sub_and_test(refs, &req->refs))
2191 io_free_req_deferred(req);
2194 static void io_double_put_req(struct io_kiocb *req)
2196 /* drop both submit and complete references */
2197 if (refcount_sub_and_test(2, &req->refs))
2201 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2203 /* See comment at the top of this file */
2205 return __io_cqring_events(ctx);
2208 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2210 struct io_rings *rings = ctx->rings;
2212 /* make sure SQ entry isn't read before tail */
2213 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2216 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2218 unsigned int cflags;
2220 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2221 cflags |= IORING_CQE_F_BUFFER;
2222 req->flags &= ~REQ_F_BUFFER_SELECTED;
2227 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2229 struct io_buffer *kbuf;
2231 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2232 return io_put_kbuf(req, kbuf);
2235 static inline bool io_run_task_work(void)
2238 * Not safe to run on exiting task, and the task_work handling will
2239 * not add work to such a task.
2241 if (unlikely(current->flags & PF_EXITING))
2243 if (current->task_works) {
2244 __set_current_state(TASK_RUNNING);
2253 * Find and free completed poll iocbs
2255 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2256 struct list_head *done)
2258 struct req_batch rb;
2259 struct io_kiocb *req;
2261 /* order with ->result store in io_complete_rw_iopoll() */
2264 io_init_req_batch(&rb);
2265 while (!list_empty(done)) {
2268 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2269 list_del(&req->inflight_entry);
2271 if (READ_ONCE(req->result) == -EAGAIN) {
2272 req->iopoll_completed = 0;
2273 if (io_rw_reissue(req))
2277 if (req->flags & REQ_F_BUFFER_SELECTED)
2278 cflags = io_put_rw_kbuf(req);
2280 __io_cqring_fill_event(req, req->result, cflags);
2283 if (refcount_dec_and_test(&req->refs))
2284 io_req_free_batch(&rb, req, &ctx->submit_state);
2287 io_commit_cqring(ctx);
2288 io_cqring_ev_posted_iopoll(ctx);
2289 io_req_free_batch_finish(ctx, &rb);
2292 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2295 struct io_kiocb *req, *tmp;
2301 * Only spin for completions if we don't have multiple devices hanging
2302 * off our complete list, and we're under the requested amount.
2304 spin = !ctx->poll_multi_file && *nr_events < min;
2307 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2308 struct kiocb *kiocb = &req->rw.kiocb;
2311 * Move completed and retryable entries to our local lists.
2312 * If we find a request that requires polling, break out
2313 * and complete those lists first, if we have entries there.
2315 if (READ_ONCE(req->iopoll_completed)) {
2316 list_move_tail(&req->inflight_entry, &done);
2319 if (!list_empty(&done))
2322 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2326 /* iopoll may have completed current req */
2327 if (READ_ONCE(req->iopoll_completed))
2328 list_move_tail(&req->inflight_entry, &done);
2335 if (!list_empty(&done))
2336 io_iopoll_complete(ctx, nr_events, &done);
2342 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2343 * non-spinning poll check - we'll still enter the driver poll loop, but only
2344 * as a non-spinning completion check.
2346 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2349 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2352 ret = io_do_iopoll(ctx, nr_events, min);
2355 if (*nr_events >= min)
2363 * We can't just wait for polled events to come to us, we have to actively
2364 * find and complete them.
2366 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2368 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2371 mutex_lock(&ctx->uring_lock);
2372 while (!list_empty(&ctx->iopoll_list)) {
2373 unsigned int nr_events = 0;
2375 io_do_iopoll(ctx, &nr_events, 0);
2377 /* let it sleep and repeat later if can't complete a request */
2381 * Ensure we allow local-to-the-cpu processing to take place,
2382 * in this case we need to ensure that we reap all events.
2383 * Also let task_work, etc. to progress by releasing the mutex
2385 if (need_resched()) {
2386 mutex_unlock(&ctx->uring_lock);
2388 mutex_lock(&ctx->uring_lock);
2391 mutex_unlock(&ctx->uring_lock);
2394 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2396 unsigned int nr_events = 0;
2397 int iters = 0, ret = 0;
2400 * We disallow the app entering submit/complete with polling, but we
2401 * still need to lock the ring to prevent racing with polled issue
2402 * that got punted to a workqueue.
2404 mutex_lock(&ctx->uring_lock);
2407 * Don't enter poll loop if we already have events pending.
2408 * If we do, we can potentially be spinning for commands that
2409 * already triggered a CQE (eg in error).
2411 if (test_bit(0, &ctx->cq_check_overflow))
2412 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2413 if (io_cqring_events(ctx))
2417 * If a submit got punted to a workqueue, we can have the
2418 * application entering polling for a command before it gets
2419 * issued. That app will hold the uring_lock for the duration
2420 * of the poll right here, so we need to take a breather every
2421 * now and then to ensure that the issue has a chance to add
2422 * the poll to the issued list. Otherwise we can spin here
2423 * forever, while the workqueue is stuck trying to acquire the
2426 if (!(++iters & 7)) {
2427 mutex_unlock(&ctx->uring_lock);
2429 mutex_lock(&ctx->uring_lock);
2432 ret = io_iopoll_getevents(ctx, &nr_events, min);
2436 } while (min && !nr_events && !need_resched());
2438 mutex_unlock(&ctx->uring_lock);
2442 static void kiocb_end_write(struct io_kiocb *req)
2445 * Tell lockdep we inherited freeze protection from submission
2448 if (req->flags & REQ_F_ISREG) {
2449 struct inode *inode = file_inode(req->file);
2451 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2453 file_end_write(req->file);
2457 static bool io_resubmit_prep(struct io_kiocb *req)
2459 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2461 struct iov_iter iter;
2463 /* already prepared */
2464 if (req->async_data)
2467 switch (req->opcode) {
2468 case IORING_OP_READV:
2469 case IORING_OP_READ_FIXED:
2470 case IORING_OP_READ:
2473 case IORING_OP_WRITEV:
2474 case IORING_OP_WRITE_FIXED:
2475 case IORING_OP_WRITE:
2479 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2484 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2487 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2491 static bool io_rw_reissue(struct io_kiocb *req)
2494 umode_t mode = file_inode(req->file)->i_mode;
2496 if (!S_ISBLK(mode) && !S_ISREG(mode))
2498 if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2501 lockdep_assert_held(&req->ctx->uring_lock);
2503 if (io_resubmit_prep(req)) {
2504 refcount_inc(&req->refs);
2505 io_queue_async_work(req);
2508 req_set_fail_links(req);
2513 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2514 unsigned int issue_flags)
2518 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2520 if (res != req->result)
2521 req_set_fail_links(req);
2523 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2524 kiocb_end_write(req);
2525 if (req->flags & REQ_F_BUFFER_SELECTED)
2526 cflags = io_put_rw_kbuf(req);
2527 __io_req_complete(req, issue_flags, res, cflags);
2530 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2532 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2534 __io_complete_rw(req, res, res2, 0);
2537 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2539 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2541 if (kiocb->ki_flags & IOCB_WRITE)
2542 kiocb_end_write(req);
2544 if (res != -EAGAIN && res != req->result)
2545 req_set_fail_links(req);
2547 WRITE_ONCE(req->result, res);
2548 /* order with io_poll_complete() checking ->result */
2550 WRITE_ONCE(req->iopoll_completed, 1);
2554 * After the iocb has been issued, it's safe to be found on the poll list.
2555 * Adding the kiocb to the list AFTER submission ensures that we don't
2556 * find it from a io_iopoll_getevents() thread before the issuer is done
2557 * accessing the kiocb cookie.
2559 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2561 struct io_ring_ctx *ctx = req->ctx;
2564 * Track whether we have multiple files in our lists. This will impact
2565 * how we do polling eventually, not spinning if we're on potentially
2566 * different devices.
2568 if (list_empty(&ctx->iopoll_list)) {
2569 ctx->poll_multi_file = false;
2570 } else if (!ctx->poll_multi_file) {
2571 struct io_kiocb *list_req;
2573 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2575 if (list_req->file != req->file)
2576 ctx->poll_multi_file = true;
2580 * For fast devices, IO may have already completed. If it has, add
2581 * it to the front so we find it first.
2583 if (READ_ONCE(req->iopoll_completed))
2584 list_add(&req->inflight_entry, &ctx->iopoll_list);
2586 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2589 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2590 * task context or in io worker task context. If current task context is
2591 * sq thread, we don't need to check whether should wake up sq thread.
2593 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2594 wq_has_sleeper(&ctx->sq_data->wait))
2595 wake_up(&ctx->sq_data->wait);
2598 static inline void io_state_file_put(struct io_submit_state *state)
2600 if (state->file_refs) {
2601 fput_many(state->file, state->file_refs);
2602 state->file_refs = 0;
2607 * Get as many references to a file as we have IOs left in this submission,
2608 * assuming most submissions are for one file, or at least that each file
2609 * has more than one submission.
2611 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2616 if (state->file_refs) {
2617 if (state->fd == fd) {
2621 io_state_file_put(state);
2623 state->file = fget_many(fd, state->ios_left);
2624 if (unlikely(!state->file))
2628 state->file_refs = state->ios_left - 1;
2632 static bool io_bdev_nowait(struct block_device *bdev)
2634 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2638 * If we tracked the file through the SCM inflight mechanism, we could support
2639 * any file. For now, just ensure that anything potentially problematic is done
2642 static bool io_file_supports_async(struct file *file, int rw)
2644 umode_t mode = file_inode(file)->i_mode;
2646 if (S_ISBLK(mode)) {
2647 if (IS_ENABLED(CONFIG_BLOCK) &&
2648 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2652 if (S_ISCHR(mode) || S_ISSOCK(mode))
2654 if (S_ISREG(mode)) {
2655 if (IS_ENABLED(CONFIG_BLOCK) &&
2656 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2657 file->f_op != &io_uring_fops)
2662 /* any ->read/write should understand O_NONBLOCK */
2663 if (file->f_flags & O_NONBLOCK)
2666 if (!(file->f_mode & FMODE_NOWAIT))
2670 return file->f_op->read_iter != NULL;
2672 return file->f_op->write_iter != NULL;
2675 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2677 struct io_ring_ctx *ctx = req->ctx;
2678 struct kiocb *kiocb = &req->rw.kiocb;
2679 struct file *file = req->file;
2683 if (S_ISREG(file_inode(file)->i_mode))
2684 req->flags |= REQ_F_ISREG;
2686 kiocb->ki_pos = READ_ONCE(sqe->off);
2687 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2688 req->flags |= REQ_F_CUR_POS;
2689 kiocb->ki_pos = file->f_pos;
2691 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2692 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2693 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2697 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2698 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2699 req->flags |= REQ_F_NOWAIT;
2701 ioprio = READ_ONCE(sqe->ioprio);
2703 ret = ioprio_check_cap(ioprio);
2707 kiocb->ki_ioprio = ioprio;
2709 kiocb->ki_ioprio = get_current_ioprio();
2711 if (ctx->flags & IORING_SETUP_IOPOLL) {
2712 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2713 !kiocb->ki_filp->f_op->iopoll)
2716 kiocb->ki_flags |= IOCB_HIPRI;
2717 kiocb->ki_complete = io_complete_rw_iopoll;
2718 req->iopoll_completed = 0;
2720 if (kiocb->ki_flags & IOCB_HIPRI)
2722 kiocb->ki_complete = io_complete_rw;
2725 req->rw.addr = READ_ONCE(sqe->addr);
2726 req->rw.len = READ_ONCE(sqe->len);
2727 req->buf_index = READ_ONCE(sqe->buf_index);
2731 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2737 case -ERESTARTNOINTR:
2738 case -ERESTARTNOHAND:
2739 case -ERESTART_RESTARTBLOCK:
2741 * We can't just restart the syscall, since previously
2742 * submitted sqes may already be in progress. Just fail this
2748 kiocb->ki_complete(kiocb, ret, 0);
2752 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2753 unsigned int issue_flags)
2755 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2756 struct io_async_rw *io = req->async_data;
2758 /* add previously done IO, if any */
2759 if (io && io->bytes_done > 0) {
2761 ret = io->bytes_done;
2763 ret += io->bytes_done;
2766 if (req->flags & REQ_F_CUR_POS)
2767 req->file->f_pos = kiocb->ki_pos;
2768 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2769 __io_complete_rw(req, ret, 0, issue_flags);
2771 io_rw_done(kiocb, ret);
2774 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2776 struct io_ring_ctx *ctx = req->ctx;
2777 size_t len = req->rw.len;
2778 struct io_mapped_ubuf *imu;
2779 u16 index, buf_index = req->buf_index;
2783 if (unlikely(buf_index >= ctx->nr_user_bufs))
2785 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2786 imu = &ctx->user_bufs[index];
2787 buf_addr = req->rw.addr;
2790 if (buf_addr + len < buf_addr)
2792 /* not inside the mapped region */
2793 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2797 * May not be a start of buffer, set size appropriately
2798 * and advance us to the beginning.
2800 offset = buf_addr - imu->ubuf;
2801 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2805 * Don't use iov_iter_advance() here, as it's really slow for
2806 * using the latter parts of a big fixed buffer - it iterates
2807 * over each segment manually. We can cheat a bit here, because
2810 * 1) it's a BVEC iter, we set it up
2811 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2812 * first and last bvec
2814 * So just find our index, and adjust the iterator afterwards.
2815 * If the offset is within the first bvec (or the whole first
2816 * bvec, just use iov_iter_advance(). This makes it easier
2817 * since we can just skip the first segment, which may not
2818 * be PAGE_SIZE aligned.
2820 const struct bio_vec *bvec = imu->bvec;
2822 if (offset <= bvec->bv_len) {
2823 iov_iter_advance(iter, offset);
2825 unsigned long seg_skip;
2827 /* skip first vec */
2828 offset -= bvec->bv_len;
2829 seg_skip = 1 + (offset >> PAGE_SHIFT);
2831 iter->bvec = bvec + seg_skip;
2832 iter->nr_segs -= seg_skip;
2833 iter->count -= bvec->bv_len + offset;
2834 iter->iov_offset = offset & ~PAGE_MASK;
2841 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2844 mutex_unlock(&ctx->uring_lock);
2847 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2850 * "Normal" inline submissions always hold the uring_lock, since we
2851 * grab it from the system call. Same is true for the SQPOLL offload.
2852 * The only exception is when we've detached the request and issue it
2853 * from an async worker thread, grab the lock for that case.
2856 mutex_lock(&ctx->uring_lock);
2859 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2860 int bgid, struct io_buffer *kbuf,
2863 struct io_buffer *head;
2865 if (req->flags & REQ_F_BUFFER_SELECTED)
2868 io_ring_submit_lock(req->ctx, needs_lock);
2870 lockdep_assert_held(&req->ctx->uring_lock);
2872 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2874 if (!list_empty(&head->list)) {
2875 kbuf = list_last_entry(&head->list, struct io_buffer,
2877 list_del(&kbuf->list);
2880 idr_remove(&req->ctx->io_buffer_idr, bgid);
2882 if (*len > kbuf->len)
2885 kbuf = ERR_PTR(-ENOBUFS);
2888 io_ring_submit_unlock(req->ctx, needs_lock);
2893 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2896 struct io_buffer *kbuf;
2899 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2900 bgid = req->buf_index;
2901 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2904 req->rw.addr = (u64) (unsigned long) kbuf;
2905 req->flags |= REQ_F_BUFFER_SELECTED;
2906 return u64_to_user_ptr(kbuf->addr);
2909 #ifdef CONFIG_COMPAT
2910 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2913 struct compat_iovec __user *uiov;
2914 compat_ssize_t clen;
2918 uiov = u64_to_user_ptr(req->rw.addr);
2919 if (!access_ok(uiov, sizeof(*uiov)))
2921 if (__get_user(clen, &uiov->iov_len))
2927 buf = io_rw_buffer_select(req, &len, needs_lock);
2929 return PTR_ERR(buf);
2930 iov[0].iov_base = buf;
2931 iov[0].iov_len = (compat_size_t) len;
2936 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2939 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2943 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2946 len = iov[0].iov_len;
2949 buf = io_rw_buffer_select(req, &len, needs_lock);
2951 return PTR_ERR(buf);
2952 iov[0].iov_base = buf;
2953 iov[0].iov_len = len;
2957 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2960 if (req->flags & REQ_F_BUFFER_SELECTED) {
2961 struct io_buffer *kbuf;
2963 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2964 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2965 iov[0].iov_len = kbuf->len;
2968 if (req->rw.len != 1)
2971 #ifdef CONFIG_COMPAT
2972 if (req->ctx->compat)
2973 return io_compat_import(req, iov, needs_lock);
2976 return __io_iov_buffer_select(req, iov, needs_lock);
2979 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2980 struct iov_iter *iter, bool needs_lock)
2982 void __user *buf = u64_to_user_ptr(req->rw.addr);
2983 size_t sqe_len = req->rw.len;
2984 u8 opcode = req->opcode;
2987 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2989 return io_import_fixed(req, rw, iter);
2992 /* buffer index only valid with fixed read/write, or buffer select */
2993 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2996 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2997 if (req->flags & REQ_F_BUFFER_SELECT) {
2998 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3000 return PTR_ERR(buf);
3001 req->rw.len = sqe_len;
3004 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3009 if (req->flags & REQ_F_BUFFER_SELECT) {
3010 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3012 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3017 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3021 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3023 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3027 * For files that don't have ->read_iter() and ->write_iter(), handle them
3028 * by looping over ->read() or ->write() manually.
3030 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3032 struct kiocb *kiocb = &req->rw.kiocb;
3033 struct file *file = req->file;
3037 * Don't support polled IO through this interface, and we can't
3038 * support non-blocking either. For the latter, this just causes
3039 * the kiocb to be handled from an async context.
3041 if (kiocb->ki_flags & IOCB_HIPRI)
3043 if (kiocb->ki_flags & IOCB_NOWAIT)
3046 while (iov_iter_count(iter)) {
3050 if (!iov_iter_is_bvec(iter)) {
3051 iovec = iov_iter_iovec(iter);
3053 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3054 iovec.iov_len = req->rw.len;
3058 nr = file->f_op->read(file, iovec.iov_base,
3059 iovec.iov_len, io_kiocb_ppos(kiocb));
3061 nr = file->f_op->write(file, iovec.iov_base,
3062 iovec.iov_len, io_kiocb_ppos(kiocb));
3071 if (nr != iovec.iov_len)
3075 iov_iter_advance(iter, nr);
3081 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3082 const struct iovec *fast_iov, struct iov_iter *iter)
3084 struct io_async_rw *rw = req->async_data;
3086 memcpy(&rw->iter, iter, sizeof(*iter));
3087 rw->free_iovec = iovec;
3089 /* can only be fixed buffers, no need to do anything */
3090 if (iov_iter_is_bvec(iter))
3093 unsigned iov_off = 0;
3095 rw->iter.iov = rw->fast_iov;
3096 if (iter->iov != fast_iov) {
3097 iov_off = iter->iov - fast_iov;
3098 rw->iter.iov += iov_off;
3100 if (rw->fast_iov != fast_iov)
3101 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3102 sizeof(struct iovec) * iter->nr_segs);
3104 req->flags |= REQ_F_NEED_CLEANUP;
3108 static inline int __io_alloc_async_data(struct io_kiocb *req)
3110 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3111 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3112 return req->async_data == NULL;
3115 static int io_alloc_async_data(struct io_kiocb *req)
3117 if (!io_op_defs[req->opcode].needs_async_data)
3120 return __io_alloc_async_data(req);
3123 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3124 const struct iovec *fast_iov,
3125 struct iov_iter *iter, bool force)
3127 if (!force && !io_op_defs[req->opcode].needs_async_data)
3129 if (!req->async_data) {
3130 if (__io_alloc_async_data(req)) {
3135 io_req_map_rw(req, iovec, fast_iov, iter);
3140 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3142 struct io_async_rw *iorw = req->async_data;
3143 struct iovec *iov = iorw->fast_iov;
3146 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3147 if (unlikely(ret < 0))
3150 iorw->bytes_done = 0;
3151 iorw->free_iovec = iov;
3153 req->flags |= REQ_F_NEED_CLEANUP;
3157 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3159 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3161 return io_prep_rw(req, sqe);
3165 * This is our waitqueue callback handler, registered through lock_page_async()
3166 * when we initially tried to do the IO with the iocb armed our waitqueue.
3167 * This gets called when the page is unlocked, and we generally expect that to
3168 * happen when the page IO is completed and the page is now uptodate. This will
3169 * queue a task_work based retry of the operation, attempting to copy the data
3170 * again. If the latter fails because the page was NOT uptodate, then we will
3171 * do a thread based blocking retry of the operation. That's the unexpected
3174 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3175 int sync, void *arg)
3177 struct wait_page_queue *wpq;
3178 struct io_kiocb *req = wait->private;
3179 struct wait_page_key *key = arg;
3181 wpq = container_of(wait, struct wait_page_queue, wait);
3183 if (!wake_page_match(wpq, key))
3186 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3187 list_del_init(&wait->entry);
3189 /* submit ref gets dropped, acquire a new one */
3190 refcount_inc(&req->refs);
3191 io_req_task_queue(req);
3196 * This controls whether a given IO request should be armed for async page
3197 * based retry. If we return false here, the request is handed to the async
3198 * worker threads for retry. If we're doing buffered reads on a regular file,
3199 * we prepare a private wait_page_queue entry and retry the operation. This
3200 * will either succeed because the page is now uptodate and unlocked, or it
3201 * will register a callback when the page is unlocked at IO completion. Through
3202 * that callback, io_uring uses task_work to setup a retry of the operation.
3203 * That retry will attempt the buffered read again. The retry will generally
3204 * succeed, or in rare cases where it fails, we then fall back to using the
3205 * async worker threads for a blocking retry.
3207 static bool io_rw_should_retry(struct io_kiocb *req)
3209 struct io_async_rw *rw = req->async_data;
3210 struct wait_page_queue *wait = &rw->wpq;
3211 struct kiocb *kiocb = &req->rw.kiocb;
3213 /* never retry for NOWAIT, we just complete with -EAGAIN */
3214 if (req->flags & REQ_F_NOWAIT)
3217 /* Only for buffered IO */
3218 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3222 * just use poll if we can, and don't attempt if the fs doesn't
3223 * support callback based unlocks
3225 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3228 wait->wait.func = io_async_buf_func;
3229 wait->wait.private = req;
3230 wait->wait.flags = 0;
3231 INIT_LIST_HEAD(&wait->wait.entry);
3232 kiocb->ki_flags |= IOCB_WAITQ;
3233 kiocb->ki_flags &= ~IOCB_NOWAIT;
3234 kiocb->ki_waitq = wait;
3238 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3240 if (req->file->f_op->read_iter)
3241 return call_read_iter(req->file, &req->rw.kiocb, iter);
3242 else if (req->file->f_op->read)
3243 return loop_rw_iter(READ, req, iter);
3248 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3250 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3251 struct kiocb *kiocb = &req->rw.kiocb;
3252 struct iov_iter __iter, *iter = &__iter;
3253 struct io_async_rw *rw = req->async_data;
3254 ssize_t io_size, ret, ret2;
3255 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3261 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3265 io_size = iov_iter_count(iter);
3266 req->result = io_size;
3268 /* Ensure we clear previously set non-block flag */
3269 if (!force_nonblock)
3270 kiocb->ki_flags &= ~IOCB_NOWAIT;
3272 kiocb->ki_flags |= IOCB_NOWAIT;
3274 /* If the file doesn't support async, just async punt */
3275 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3276 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3277 return ret ?: -EAGAIN;
3280 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3281 if (unlikely(ret)) {
3286 ret = io_iter_do_read(req, iter);
3288 if (ret == -EIOCBQUEUED) {
3290 } else if (ret == -EAGAIN) {
3291 /* IOPOLL retry should happen for io-wq threads */
3292 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3294 /* no retry on NONBLOCK nor RWF_NOWAIT */
3295 if (req->flags & REQ_F_NOWAIT)
3297 /* some cases will consume bytes even on error returns */
3298 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3300 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3301 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3302 /* read all, failed, already did sync or don't want to retry */
3306 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3311 rw = req->async_data;
3312 /* now use our persistent iterator, if we aren't already */
3317 rw->bytes_done += ret;
3318 /* if we can retry, do so with the callbacks armed */
3319 if (!io_rw_should_retry(req)) {
3320 kiocb->ki_flags &= ~IOCB_WAITQ;
3325 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3326 * we get -EIOCBQUEUED, then we'll get a notification when the
3327 * desired page gets unlocked. We can also get a partial read
3328 * here, and if we do, then just retry at the new offset.
3330 ret = io_iter_do_read(req, iter);
3331 if (ret == -EIOCBQUEUED)
3333 /* we got some bytes, but not all. retry. */
3334 } while (ret > 0 && ret < io_size);
3336 kiocb_done(kiocb, ret, issue_flags);
3338 /* it's faster to check here then delegate to kfree */
3344 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3346 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3348 return io_prep_rw(req, sqe);
3351 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3353 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3354 struct kiocb *kiocb = &req->rw.kiocb;
3355 struct iov_iter __iter, *iter = &__iter;
3356 struct io_async_rw *rw = req->async_data;
3357 ssize_t ret, ret2, io_size;
3358 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3364 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3368 io_size = iov_iter_count(iter);
3369 req->result = io_size;
3371 /* Ensure we clear previously set non-block flag */
3372 if (!force_nonblock)
3373 kiocb->ki_flags &= ~IOCB_NOWAIT;
3375 kiocb->ki_flags |= IOCB_NOWAIT;
3377 /* If the file doesn't support async, just async punt */
3378 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3381 /* file path doesn't support NOWAIT for non-direct_IO */
3382 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3383 (req->flags & REQ_F_ISREG))
3386 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3391 * Open-code file_start_write here to grab freeze protection,
3392 * which will be released by another thread in
3393 * io_complete_rw(). Fool lockdep by telling it the lock got
3394 * released so that it doesn't complain about the held lock when
3395 * we return to userspace.
3397 if (req->flags & REQ_F_ISREG) {
3398 sb_start_write(file_inode(req->file)->i_sb);
3399 __sb_writers_release(file_inode(req->file)->i_sb,
3402 kiocb->ki_flags |= IOCB_WRITE;
3404 if (req->file->f_op->write_iter)
3405 ret2 = call_write_iter(req->file, kiocb, iter);
3406 else if (req->file->f_op->write)
3407 ret2 = loop_rw_iter(WRITE, req, iter);
3412 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3413 * retry them without IOCB_NOWAIT.
3415 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3417 /* no retry on NONBLOCK nor RWF_NOWAIT */
3418 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3420 if (!force_nonblock || ret2 != -EAGAIN) {
3421 /* IOPOLL retry should happen for io-wq threads */
3422 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3425 kiocb_done(kiocb, ret2, issue_flags);
3428 /* some cases will consume bytes even on error returns */
3429 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3430 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3431 return ret ?: -EAGAIN;
3434 /* it's reportedly faster than delegating the null check to kfree() */
3440 static int io_renameat_prep(struct io_kiocb *req,
3441 const struct io_uring_sqe *sqe)
3443 struct io_rename *ren = &req->rename;
3444 const char __user *oldf, *newf;
3446 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3449 ren->old_dfd = READ_ONCE(sqe->fd);
3450 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3451 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3452 ren->new_dfd = READ_ONCE(sqe->len);
3453 ren->flags = READ_ONCE(sqe->rename_flags);
3455 ren->oldpath = getname(oldf);
3456 if (IS_ERR(ren->oldpath))
3457 return PTR_ERR(ren->oldpath);
3459 ren->newpath = getname(newf);
3460 if (IS_ERR(ren->newpath)) {
3461 putname(ren->oldpath);
3462 return PTR_ERR(ren->newpath);
3465 req->flags |= REQ_F_NEED_CLEANUP;
3469 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3471 struct io_rename *ren = &req->rename;
3474 if (issue_flags & IO_URING_F_NONBLOCK)
3477 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3478 ren->newpath, ren->flags);
3480 req->flags &= ~REQ_F_NEED_CLEANUP;
3482 req_set_fail_links(req);
3483 io_req_complete(req, ret);
3487 static int io_unlinkat_prep(struct io_kiocb *req,
3488 const struct io_uring_sqe *sqe)
3490 struct io_unlink *un = &req->unlink;
3491 const char __user *fname;
3493 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3496 un->dfd = READ_ONCE(sqe->fd);
3498 un->flags = READ_ONCE(sqe->unlink_flags);
3499 if (un->flags & ~AT_REMOVEDIR)
3502 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3503 un->filename = getname(fname);
3504 if (IS_ERR(un->filename))
3505 return PTR_ERR(un->filename);
3507 req->flags |= REQ_F_NEED_CLEANUP;
3511 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3513 struct io_unlink *un = &req->unlink;
3516 if (issue_flags & IO_URING_F_NONBLOCK)
3519 if (un->flags & AT_REMOVEDIR)
3520 ret = do_rmdir(un->dfd, un->filename);
3522 ret = do_unlinkat(un->dfd, un->filename);
3524 req->flags &= ~REQ_F_NEED_CLEANUP;
3526 req_set_fail_links(req);
3527 io_req_complete(req, ret);
3531 static int io_shutdown_prep(struct io_kiocb *req,
3532 const struct io_uring_sqe *sqe)
3534 #if defined(CONFIG_NET)
3535 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3537 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3541 req->shutdown.how = READ_ONCE(sqe->len);
3548 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3550 #if defined(CONFIG_NET)
3551 struct socket *sock;
3554 if (issue_flags & IO_URING_F_NONBLOCK)
3557 sock = sock_from_file(req->file);
3558 if (unlikely(!sock))
3561 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3563 req_set_fail_links(req);
3564 io_req_complete(req, ret);
3571 static int __io_splice_prep(struct io_kiocb *req,
3572 const struct io_uring_sqe *sqe)
3574 struct io_splice* sp = &req->splice;
3575 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3577 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3581 sp->len = READ_ONCE(sqe->len);
3582 sp->flags = READ_ONCE(sqe->splice_flags);
3584 if (unlikely(sp->flags & ~valid_flags))
3587 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3588 (sp->flags & SPLICE_F_FD_IN_FIXED));
3591 req->flags |= REQ_F_NEED_CLEANUP;
3593 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3595 * Splice operation will be punted aync, and here need to
3596 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3598 io_req_init_async(req);
3599 req->work.flags |= IO_WQ_WORK_UNBOUND;
3605 static int io_tee_prep(struct io_kiocb *req,
3606 const struct io_uring_sqe *sqe)
3608 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3610 return __io_splice_prep(req, sqe);
3613 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3615 struct io_splice *sp = &req->splice;
3616 struct file *in = sp->file_in;
3617 struct file *out = sp->file_out;
3618 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3621 if (issue_flags & IO_URING_F_NONBLOCK)
3624 ret = do_tee(in, out, sp->len, flags);
3626 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3627 req->flags &= ~REQ_F_NEED_CLEANUP;
3630 req_set_fail_links(req);
3631 io_req_complete(req, ret);
3635 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3637 struct io_splice* sp = &req->splice;
3639 sp->off_in = READ_ONCE(sqe->splice_off_in);
3640 sp->off_out = READ_ONCE(sqe->off);
3641 return __io_splice_prep(req, sqe);
3644 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3646 struct io_splice *sp = &req->splice;
3647 struct file *in = sp->file_in;
3648 struct file *out = sp->file_out;
3649 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3650 loff_t *poff_in, *poff_out;
3653 if (issue_flags & IO_URING_F_NONBLOCK)
3656 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3657 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3660 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3662 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3663 req->flags &= ~REQ_F_NEED_CLEANUP;
3666 req_set_fail_links(req);
3667 io_req_complete(req, ret);
3672 * IORING_OP_NOP just posts a completion event, nothing else.
3674 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3676 struct io_ring_ctx *ctx = req->ctx;
3678 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3681 __io_req_complete(req, issue_flags, 0, 0);
3685 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3687 struct io_ring_ctx *ctx = req->ctx;
3692 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3694 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3697 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3698 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3701 req->sync.off = READ_ONCE(sqe->off);
3702 req->sync.len = READ_ONCE(sqe->len);
3706 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3708 loff_t end = req->sync.off + req->sync.len;
3711 /* fsync always requires a blocking context */
3712 if (issue_flags & IO_URING_F_NONBLOCK)
3715 ret = vfs_fsync_range(req->file, req->sync.off,
3716 end > 0 ? end : LLONG_MAX,
3717 req->sync.flags & IORING_FSYNC_DATASYNC);
3719 req_set_fail_links(req);
3720 io_req_complete(req, ret);
3724 static int io_fallocate_prep(struct io_kiocb *req,
3725 const struct io_uring_sqe *sqe)
3727 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3729 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3732 req->sync.off = READ_ONCE(sqe->off);
3733 req->sync.len = READ_ONCE(sqe->addr);
3734 req->sync.mode = READ_ONCE(sqe->len);
3738 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3742 /* fallocate always requiring blocking context */
3743 if (issue_flags & IO_URING_F_NONBLOCK)
3745 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3748 req_set_fail_links(req);
3749 io_req_complete(req, ret);
3753 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3755 const char __user *fname;
3758 if (unlikely(sqe->ioprio || sqe->buf_index))
3760 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3763 /* open.how should be already initialised */
3764 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3765 req->open.how.flags |= O_LARGEFILE;
3767 req->open.dfd = READ_ONCE(sqe->fd);
3768 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3769 req->open.filename = getname(fname);
3770 if (IS_ERR(req->open.filename)) {
3771 ret = PTR_ERR(req->open.filename);
3772 req->open.filename = NULL;
3775 req->open.nofile = rlimit(RLIMIT_NOFILE);
3776 req->flags |= REQ_F_NEED_CLEANUP;
3780 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3784 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3786 mode = READ_ONCE(sqe->len);
3787 flags = READ_ONCE(sqe->open_flags);
3788 req->open.how = build_open_how(flags, mode);
3789 return __io_openat_prep(req, sqe);
3792 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3794 struct open_how __user *how;
3798 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3800 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3801 len = READ_ONCE(sqe->len);
3802 if (len < OPEN_HOW_SIZE_VER0)
3805 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3810 return __io_openat_prep(req, sqe);
3813 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3815 struct open_flags op;
3818 bool resolve_nonblock;
3821 ret = build_open_flags(&req->open.how, &op);
3824 nonblock_set = op.open_flag & O_NONBLOCK;
3825 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3826 if (issue_flags & IO_URING_F_NONBLOCK) {
3828 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3829 * it'll always -EAGAIN
3831 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3833 op.lookup_flags |= LOOKUP_CACHED;
3834 op.open_flag |= O_NONBLOCK;
3837 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3841 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3842 /* only retry if RESOLVE_CACHED wasn't already set by application */
3843 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3844 file == ERR_PTR(-EAGAIN)) {
3846 * We could hang on to this 'fd', but seems like marginal
3847 * gain for something that is now known to be a slower path.
3848 * So just put it, and we'll get a new one when we retry.
3856 ret = PTR_ERR(file);
3858 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3859 file->f_flags &= ~O_NONBLOCK;
3860 fsnotify_open(file);
3861 fd_install(ret, file);
3864 putname(req->open.filename);
3865 req->flags &= ~REQ_F_NEED_CLEANUP;
3867 req_set_fail_links(req);
3868 io_req_complete(req, ret);
3872 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3874 return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
3877 static int io_remove_buffers_prep(struct io_kiocb *req,
3878 const struct io_uring_sqe *sqe)
3880 struct io_provide_buf *p = &req->pbuf;
3883 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3886 tmp = READ_ONCE(sqe->fd);
3887 if (!tmp || tmp > USHRT_MAX)
3890 memset(p, 0, sizeof(*p));
3892 p->bgid = READ_ONCE(sqe->buf_group);
3896 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3897 int bgid, unsigned nbufs)
3901 /* shouldn't happen */
3905 /* the head kbuf is the list itself */
3906 while (!list_empty(&buf->list)) {
3907 struct io_buffer *nxt;
3909 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3910 list_del(&nxt->list);
3917 idr_remove(&ctx->io_buffer_idr, bgid);
3922 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3924 struct io_provide_buf *p = &req->pbuf;
3925 struct io_ring_ctx *ctx = req->ctx;
3926 struct io_buffer *head;
3928 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3930 io_ring_submit_lock(ctx, !force_nonblock);
3932 lockdep_assert_held(&ctx->uring_lock);
3935 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3937 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3939 req_set_fail_links(req);
3941 /* need to hold the lock to complete IOPOLL requests */
3942 if (ctx->flags & IORING_SETUP_IOPOLL) {
3943 __io_req_complete(req, issue_flags, ret, 0);
3944 io_ring_submit_unlock(ctx, !force_nonblock);
3946 io_ring_submit_unlock(ctx, !force_nonblock);
3947 __io_req_complete(req, issue_flags, ret, 0);
3952 static int io_provide_buffers_prep(struct io_kiocb *req,
3953 const struct io_uring_sqe *sqe)
3955 struct io_provide_buf *p = &req->pbuf;
3958 if (sqe->ioprio || sqe->rw_flags)
3961 tmp = READ_ONCE(sqe->fd);
3962 if (!tmp || tmp > USHRT_MAX)
3965 p->addr = READ_ONCE(sqe->addr);
3966 p->len = READ_ONCE(sqe->len);
3968 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3971 p->bgid = READ_ONCE(sqe->buf_group);
3972 tmp = READ_ONCE(sqe->off);
3973 if (tmp > USHRT_MAX)
3979 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3981 struct io_buffer *buf;
3982 u64 addr = pbuf->addr;
3983 int i, bid = pbuf->bid;
3985 for (i = 0; i < pbuf->nbufs; i++) {
3986 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3991 buf->len = pbuf->len;
3996 INIT_LIST_HEAD(&buf->list);
3999 list_add_tail(&buf->list, &(*head)->list);
4003 return i ? i : -ENOMEM;
4006 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4008 struct io_provide_buf *p = &req->pbuf;
4009 struct io_ring_ctx *ctx = req->ctx;
4010 struct io_buffer *head, *list;
4012 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4014 io_ring_submit_lock(ctx, !force_nonblock);
4016 lockdep_assert_held(&ctx->uring_lock);
4018 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4020 ret = io_add_buffers(p, &head);
4025 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4028 __io_remove_buffers(ctx, head, p->bgid, -1U);
4034 req_set_fail_links(req);
4036 /* need to hold the lock to complete IOPOLL requests */
4037 if (ctx->flags & IORING_SETUP_IOPOLL) {
4038 __io_req_complete(req, issue_flags, ret, 0);
4039 io_ring_submit_unlock(ctx, !force_nonblock);
4041 io_ring_submit_unlock(ctx, !force_nonblock);
4042 __io_req_complete(req, issue_flags, ret, 0);
4047 static int io_epoll_ctl_prep(struct io_kiocb *req,
4048 const struct io_uring_sqe *sqe)
4050 #if defined(CONFIG_EPOLL)
4051 if (sqe->ioprio || sqe->buf_index)
4053 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4056 req->epoll.epfd = READ_ONCE(sqe->fd);
4057 req->epoll.op = READ_ONCE(sqe->len);
4058 req->epoll.fd = READ_ONCE(sqe->off);
4060 if (ep_op_has_event(req->epoll.op)) {
4061 struct epoll_event __user *ev;
4063 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4064 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4074 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4076 #if defined(CONFIG_EPOLL)
4077 struct io_epoll *ie = &req->epoll;
4079 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4081 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4082 if (force_nonblock && ret == -EAGAIN)
4086 req_set_fail_links(req);
4087 __io_req_complete(req, issue_flags, ret, 0);
4094 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4096 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4097 if (sqe->ioprio || sqe->buf_index || sqe->off)
4099 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4102 req->madvise.addr = READ_ONCE(sqe->addr);
4103 req->madvise.len = READ_ONCE(sqe->len);
4104 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4111 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4113 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4114 struct io_madvise *ma = &req->madvise;
4117 if (issue_flags & IO_URING_F_NONBLOCK)
4120 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4122 req_set_fail_links(req);
4123 io_req_complete(req, ret);
4130 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4132 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4134 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4137 req->fadvise.offset = READ_ONCE(sqe->off);
4138 req->fadvise.len = READ_ONCE(sqe->len);
4139 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4143 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4145 struct io_fadvise *fa = &req->fadvise;
4148 if (issue_flags & IO_URING_F_NONBLOCK) {
4149 switch (fa->advice) {
4150 case POSIX_FADV_NORMAL:
4151 case POSIX_FADV_RANDOM:
4152 case POSIX_FADV_SEQUENTIAL:
4159 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4161 req_set_fail_links(req);
4162 io_req_complete(req, ret);
4166 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4168 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4170 if (sqe->ioprio || sqe->buf_index)
4172 if (req->flags & REQ_F_FIXED_FILE)
4175 req->statx.dfd = READ_ONCE(sqe->fd);
4176 req->statx.mask = READ_ONCE(sqe->len);
4177 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4178 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4179 req->statx.flags = READ_ONCE(sqe->statx_flags);
4184 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4186 struct io_statx *ctx = &req->statx;
4189 if (issue_flags & IO_URING_F_NONBLOCK) {
4190 /* only need file table for an actual valid fd */
4191 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4192 req->flags |= REQ_F_NO_FILE_TABLE;
4196 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4200 req_set_fail_links(req);
4201 io_req_complete(req, ret);
4205 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4207 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4209 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4210 sqe->rw_flags || sqe->buf_index)
4212 if (req->flags & REQ_F_FIXED_FILE)
4215 req->close.fd = READ_ONCE(sqe->fd);
4219 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4221 struct files_struct *files = current->files;
4222 struct io_close *close = &req->close;
4223 struct fdtable *fdt;
4229 spin_lock(&files->file_lock);
4230 fdt = files_fdtable(files);
4231 if (close->fd >= fdt->max_fds) {
4232 spin_unlock(&files->file_lock);
4235 file = fdt->fd[close->fd];
4237 spin_unlock(&files->file_lock);
4241 if (file->f_op == &io_uring_fops) {
4242 spin_unlock(&files->file_lock);
4247 /* if the file has a flush method, be safe and punt to async */
4248 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4249 spin_unlock(&files->file_lock);
4253 ret = __close_fd_get_file(close->fd, &file);
4254 spin_unlock(&files->file_lock);
4261 /* No ->flush() or already async, safely close from here */
4262 ret = filp_close(file, current->files);
4265 req_set_fail_links(req);
4268 __io_req_complete(req, issue_flags, ret, 0);
4272 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4274 struct io_ring_ctx *ctx = req->ctx;
4276 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4278 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4281 req->sync.off = READ_ONCE(sqe->off);
4282 req->sync.len = READ_ONCE(sqe->len);
4283 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4287 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4291 /* sync_file_range always requires a blocking context */
4292 if (issue_flags & IO_URING_F_NONBLOCK)
4295 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4298 req_set_fail_links(req);
4299 io_req_complete(req, ret);
4303 #if defined(CONFIG_NET)
4304 static int io_setup_async_msg(struct io_kiocb *req,
4305 struct io_async_msghdr *kmsg)
4307 struct io_async_msghdr *async_msg = req->async_data;
4311 if (io_alloc_async_data(req)) {
4312 kfree(kmsg->free_iov);
4315 async_msg = req->async_data;
4316 req->flags |= REQ_F_NEED_CLEANUP;
4317 memcpy(async_msg, kmsg, sizeof(*kmsg));
4318 async_msg->msg.msg_name = &async_msg->addr;
4319 /* if were using fast_iov, set it to the new one */
4320 if (!async_msg->free_iov)
4321 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4326 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4327 struct io_async_msghdr *iomsg)
4329 iomsg->msg.msg_name = &iomsg->addr;
4330 iomsg->free_iov = iomsg->fast_iov;
4331 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4332 req->sr_msg.msg_flags, &iomsg->free_iov);
4335 static int io_sendmsg_prep_async(struct io_kiocb *req)
4339 if (!io_op_defs[req->opcode].needs_async_data)
4341 ret = io_sendmsg_copy_hdr(req, req->async_data);
4343 req->flags |= REQ_F_NEED_CLEANUP;
4347 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4349 struct io_sr_msg *sr = &req->sr_msg;
4351 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4354 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4355 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4356 sr->len = READ_ONCE(sqe->len);
4358 #ifdef CONFIG_COMPAT
4359 if (req->ctx->compat)
4360 sr->msg_flags |= MSG_CMSG_COMPAT;
4365 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4367 struct io_async_msghdr iomsg, *kmsg;
4368 struct socket *sock;
4372 sock = sock_from_file(req->file);
4373 if (unlikely(!sock))
4376 kmsg = req->async_data;
4378 ret = io_sendmsg_copy_hdr(req, &iomsg);
4384 flags = req->sr_msg.msg_flags;
4385 if (flags & MSG_DONTWAIT)
4386 req->flags |= REQ_F_NOWAIT;
4387 else if (issue_flags & IO_URING_F_NONBLOCK)
4388 flags |= MSG_DONTWAIT;
4390 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4391 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4392 return io_setup_async_msg(req, kmsg);
4393 if (ret == -ERESTARTSYS)
4396 /* fast path, check for non-NULL to avoid function call */
4398 kfree(kmsg->free_iov);
4399 req->flags &= ~REQ_F_NEED_CLEANUP;
4401 req_set_fail_links(req);
4402 __io_req_complete(req, issue_flags, ret, 0);
4406 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4408 struct io_sr_msg *sr = &req->sr_msg;
4411 struct socket *sock;
4415 sock = sock_from_file(req->file);
4416 if (unlikely(!sock))
4419 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4423 msg.msg_name = NULL;
4424 msg.msg_control = NULL;
4425 msg.msg_controllen = 0;
4426 msg.msg_namelen = 0;
4428 flags = req->sr_msg.msg_flags;
4429 if (flags & MSG_DONTWAIT)
4430 req->flags |= REQ_F_NOWAIT;
4431 else if (issue_flags & IO_URING_F_NONBLOCK)
4432 flags |= MSG_DONTWAIT;
4434 msg.msg_flags = flags;
4435 ret = sock_sendmsg(sock, &msg);
4436 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4438 if (ret == -ERESTARTSYS)
4442 req_set_fail_links(req);
4443 __io_req_complete(req, issue_flags, ret, 0);
4447 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4448 struct io_async_msghdr *iomsg)
4450 struct io_sr_msg *sr = &req->sr_msg;
4451 struct iovec __user *uiov;
4455 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4456 &iomsg->uaddr, &uiov, &iov_len);
4460 if (req->flags & REQ_F_BUFFER_SELECT) {
4463 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4465 sr->len = iomsg->fast_iov[0].iov_len;
4466 iomsg->free_iov = NULL;
4468 iomsg->free_iov = iomsg->fast_iov;
4469 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4470 &iomsg->free_iov, &iomsg->msg.msg_iter,
4479 #ifdef CONFIG_COMPAT
4480 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4481 struct io_async_msghdr *iomsg)
4483 struct compat_msghdr __user *msg_compat;
4484 struct io_sr_msg *sr = &req->sr_msg;
4485 struct compat_iovec __user *uiov;
4490 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4491 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4496 uiov = compat_ptr(ptr);
4497 if (req->flags & REQ_F_BUFFER_SELECT) {
4498 compat_ssize_t clen;
4502 if (!access_ok(uiov, sizeof(*uiov)))
4504 if (__get_user(clen, &uiov->iov_len))
4509 iomsg->free_iov = NULL;
4511 iomsg->free_iov = iomsg->fast_iov;
4512 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4513 UIO_FASTIOV, &iomsg->free_iov,
4514 &iomsg->msg.msg_iter, true);
4523 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4524 struct io_async_msghdr *iomsg)
4526 iomsg->msg.msg_name = &iomsg->addr;
4528 #ifdef CONFIG_COMPAT
4529 if (req->ctx->compat)
4530 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4533 return __io_recvmsg_copy_hdr(req, iomsg);
4536 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4539 struct io_sr_msg *sr = &req->sr_msg;
4540 struct io_buffer *kbuf;
4542 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4547 req->flags |= REQ_F_BUFFER_SELECTED;
4551 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4553 return io_put_kbuf(req, req->sr_msg.kbuf);
4556 static int io_recvmsg_prep_async(struct io_kiocb *req)
4560 if (!io_op_defs[req->opcode].needs_async_data)
4562 ret = io_recvmsg_copy_hdr(req, req->async_data);
4564 req->flags |= REQ_F_NEED_CLEANUP;
4568 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4570 struct io_sr_msg *sr = &req->sr_msg;
4572 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4575 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4576 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4577 sr->len = READ_ONCE(sqe->len);
4578 sr->bgid = READ_ONCE(sqe->buf_group);
4580 #ifdef CONFIG_COMPAT
4581 if (req->ctx->compat)
4582 sr->msg_flags |= MSG_CMSG_COMPAT;
4587 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4589 struct io_async_msghdr iomsg, *kmsg;
4590 struct socket *sock;
4591 struct io_buffer *kbuf;
4593 int ret, cflags = 0;
4594 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4596 sock = sock_from_file(req->file);
4597 if (unlikely(!sock))
4600 kmsg = req->async_data;
4602 ret = io_recvmsg_copy_hdr(req, &iomsg);
4608 if (req->flags & REQ_F_BUFFER_SELECT) {
4609 kbuf = io_recv_buffer_select(req, !force_nonblock);
4611 return PTR_ERR(kbuf);
4612 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4613 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4614 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4615 1, req->sr_msg.len);
4618 flags = req->sr_msg.msg_flags;
4619 if (flags & MSG_DONTWAIT)
4620 req->flags |= REQ_F_NOWAIT;
4621 else if (force_nonblock)
4622 flags |= MSG_DONTWAIT;
4624 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4625 kmsg->uaddr, flags);
4626 if (force_nonblock && ret == -EAGAIN)
4627 return io_setup_async_msg(req, kmsg);
4628 if (ret == -ERESTARTSYS)
4631 if (req->flags & REQ_F_BUFFER_SELECTED)
4632 cflags = io_put_recv_kbuf(req);
4633 /* fast path, check for non-NULL to avoid function call */
4635 kfree(kmsg->free_iov);
4636 req->flags &= ~REQ_F_NEED_CLEANUP;
4638 req_set_fail_links(req);
4639 __io_req_complete(req, issue_flags, ret, cflags);
4643 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4645 struct io_buffer *kbuf;
4646 struct io_sr_msg *sr = &req->sr_msg;
4648 void __user *buf = sr->buf;
4649 struct socket *sock;
4652 int ret, cflags = 0;
4653 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4655 sock = sock_from_file(req->file);
4656 if (unlikely(!sock))
4659 if (req->flags & REQ_F_BUFFER_SELECT) {
4660 kbuf = io_recv_buffer_select(req, !force_nonblock);
4662 return PTR_ERR(kbuf);
4663 buf = u64_to_user_ptr(kbuf->addr);
4666 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4670 msg.msg_name = NULL;
4671 msg.msg_control = NULL;
4672 msg.msg_controllen = 0;
4673 msg.msg_namelen = 0;
4674 msg.msg_iocb = NULL;
4677 flags = req->sr_msg.msg_flags;
4678 if (flags & MSG_DONTWAIT)
4679 req->flags |= REQ_F_NOWAIT;
4680 else if (force_nonblock)
4681 flags |= MSG_DONTWAIT;
4683 ret = sock_recvmsg(sock, &msg, flags);
4684 if (force_nonblock && ret == -EAGAIN)
4686 if (ret == -ERESTARTSYS)
4689 if (req->flags & REQ_F_BUFFER_SELECTED)
4690 cflags = io_put_recv_kbuf(req);
4692 req_set_fail_links(req);
4693 __io_req_complete(req, issue_flags, ret, cflags);
4697 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4699 struct io_accept *accept = &req->accept;
4701 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4703 if (sqe->ioprio || sqe->len || sqe->buf_index)
4706 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4707 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4708 accept->flags = READ_ONCE(sqe->accept_flags);
4709 accept->nofile = rlimit(RLIMIT_NOFILE);
4713 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4715 struct io_accept *accept = &req->accept;
4716 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4717 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4720 if (req->file->f_flags & O_NONBLOCK)
4721 req->flags |= REQ_F_NOWAIT;
4723 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4724 accept->addr_len, accept->flags,
4726 if (ret == -EAGAIN && force_nonblock)
4729 if (ret == -ERESTARTSYS)
4731 req_set_fail_links(req);
4733 __io_req_complete(req, issue_flags, ret, 0);
4737 static int io_connect_prep_async(struct io_kiocb *req)
4739 struct io_async_connect *io = req->async_data;
4740 struct io_connect *conn = &req->connect;
4742 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4745 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4747 struct io_connect *conn = &req->connect;
4749 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4751 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4754 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4755 conn->addr_len = READ_ONCE(sqe->addr2);
4759 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4761 struct io_async_connect __io, *io;
4762 unsigned file_flags;
4764 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4766 if (req->async_data) {
4767 io = req->async_data;
4769 ret = move_addr_to_kernel(req->connect.addr,
4770 req->connect.addr_len,
4777 file_flags = force_nonblock ? O_NONBLOCK : 0;
4779 ret = __sys_connect_file(req->file, &io->address,
4780 req->connect.addr_len, file_flags);
4781 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4782 if (req->async_data)
4784 if (io_alloc_async_data(req)) {
4788 io = req->async_data;
4789 memcpy(req->async_data, &__io, sizeof(__io));
4792 if (ret == -ERESTARTSYS)
4796 req_set_fail_links(req);
4797 __io_req_complete(req, issue_flags, ret, 0);
4800 #else /* !CONFIG_NET */
4801 #define IO_NETOP_FN(op) \
4802 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4804 return -EOPNOTSUPP; \
4807 #define IO_NETOP_PREP(op) \
4809 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4811 return -EOPNOTSUPP; \
4814 #define IO_NETOP_PREP_ASYNC(op) \
4816 static int io_##op##_prep_async(struct io_kiocb *req) \
4818 return -EOPNOTSUPP; \
4821 IO_NETOP_PREP_ASYNC(sendmsg);
4822 IO_NETOP_PREP_ASYNC(recvmsg);
4823 IO_NETOP_PREP_ASYNC(connect);
4824 IO_NETOP_PREP(accept);
4827 #endif /* CONFIG_NET */
4829 struct io_poll_table {
4830 struct poll_table_struct pt;
4831 struct io_kiocb *req;
4835 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4836 __poll_t mask, task_work_func_t func)
4840 /* for instances that support it check for an event match first: */
4841 if (mask && !(mask & poll->events))
4844 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4846 list_del_init(&poll->wait.entry);
4849 req->task_work.func = func;
4850 percpu_ref_get(&req->ctx->refs);
4853 * If this fails, then the task is exiting. When a task exits, the
4854 * work gets canceled, so just cancel this request as well instead
4855 * of executing it. We can't safely execute it anyway, as we may not
4856 * have the needed state needed for it anyway.
4858 ret = io_req_task_work_add(req);
4859 if (unlikely(ret)) {
4860 WRITE_ONCE(poll->canceled, true);
4861 io_req_task_work_add_fallback(req, func);
4866 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4867 __acquires(&req->ctx->completion_lock)
4869 struct io_ring_ctx *ctx = req->ctx;
4871 if (!req->result && !READ_ONCE(poll->canceled)) {
4872 struct poll_table_struct pt = { ._key = poll->events };
4874 req->result = vfs_poll(req->file, &pt) & poll->events;
4877 spin_lock_irq(&ctx->completion_lock);
4878 if (!req->result && !READ_ONCE(poll->canceled)) {
4879 add_wait_queue(poll->head, &poll->wait);
4886 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4888 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4889 if (req->opcode == IORING_OP_POLL_ADD)
4890 return req->async_data;
4891 return req->apoll->double_poll;
4894 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4896 if (req->opcode == IORING_OP_POLL_ADD)
4898 return &req->apoll->poll;
4901 static void io_poll_remove_double(struct io_kiocb *req)
4903 struct io_poll_iocb *poll = io_poll_get_double(req);
4905 lockdep_assert_held(&req->ctx->completion_lock);
4907 if (poll && poll->head) {
4908 struct wait_queue_head *head = poll->head;
4910 spin_lock(&head->lock);
4911 list_del_init(&poll->wait.entry);
4912 if (poll->wait.private)
4913 refcount_dec(&req->refs);
4915 spin_unlock(&head->lock);
4919 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4921 struct io_ring_ctx *ctx = req->ctx;
4923 io_poll_remove_double(req);
4924 req->poll.done = true;
4925 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4926 io_commit_cqring(ctx);
4929 static void io_poll_task_func(struct callback_head *cb)
4931 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4932 struct io_ring_ctx *ctx = req->ctx;
4933 struct io_kiocb *nxt;
4935 if (io_poll_rewait(req, &req->poll)) {
4936 spin_unlock_irq(&ctx->completion_lock);
4938 hash_del(&req->hash_node);
4939 io_poll_complete(req, req->result, 0);
4940 spin_unlock_irq(&ctx->completion_lock);
4942 nxt = io_put_req_find_next(req);
4943 io_cqring_ev_posted(ctx);
4945 __io_req_task_submit(nxt);
4948 percpu_ref_put(&ctx->refs);
4951 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4952 int sync, void *key)
4954 struct io_kiocb *req = wait->private;
4955 struct io_poll_iocb *poll = io_poll_get_single(req);
4956 __poll_t mask = key_to_poll(key);
4958 /* for instances that support it check for an event match first: */
4959 if (mask && !(mask & poll->events))
4962 list_del_init(&wait->entry);
4964 if (poll && poll->head) {
4967 spin_lock(&poll->head->lock);
4968 done = list_empty(&poll->wait.entry);
4970 list_del_init(&poll->wait.entry);
4971 /* make sure double remove sees this as being gone */
4972 wait->private = NULL;
4973 spin_unlock(&poll->head->lock);
4975 /* use wait func handler, so it matches the rq type */
4976 poll->wait.func(&poll->wait, mode, sync, key);
4979 refcount_dec(&req->refs);
4983 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4984 wait_queue_func_t wake_func)
4988 poll->canceled = false;
4989 poll->events = events;
4990 INIT_LIST_HEAD(&poll->wait.entry);
4991 init_waitqueue_func_entry(&poll->wait, wake_func);
4994 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4995 struct wait_queue_head *head,
4996 struct io_poll_iocb **poll_ptr)
4998 struct io_kiocb *req = pt->req;
5001 * If poll->head is already set, it's because the file being polled
5002 * uses multiple waitqueues for poll handling (eg one for read, one
5003 * for write). Setup a separate io_poll_iocb if this happens.
5005 if (unlikely(poll->head)) {
5006 struct io_poll_iocb *poll_one = poll;
5008 /* already have a 2nd entry, fail a third attempt */
5010 pt->error = -EINVAL;
5013 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5015 pt->error = -ENOMEM;
5018 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5019 refcount_inc(&req->refs);
5020 poll->wait.private = req;
5027 if (poll->events & EPOLLEXCLUSIVE)
5028 add_wait_queue_exclusive(head, &poll->wait);
5030 add_wait_queue(head, &poll->wait);
5033 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5034 struct poll_table_struct *p)
5036 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5037 struct async_poll *apoll = pt->req->apoll;
5039 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5042 static void io_async_task_func(struct callback_head *cb)
5044 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5045 struct async_poll *apoll = req->apoll;
5046 struct io_ring_ctx *ctx = req->ctx;
5048 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5050 if (io_poll_rewait(req, &apoll->poll)) {
5051 spin_unlock_irq(&ctx->completion_lock);
5052 percpu_ref_put(&ctx->refs);
5056 /* If req is still hashed, it cannot have been canceled. Don't check. */
5057 if (hash_hashed(&req->hash_node))
5058 hash_del(&req->hash_node);
5060 io_poll_remove_double(req);
5061 spin_unlock_irq(&ctx->completion_lock);
5063 if (!READ_ONCE(apoll->poll.canceled))
5064 __io_req_task_submit(req);
5066 __io_req_task_cancel(req, -ECANCELED);
5068 percpu_ref_put(&ctx->refs);
5069 kfree(apoll->double_poll);
5073 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5076 struct io_kiocb *req = wait->private;
5077 struct io_poll_iocb *poll = &req->apoll->poll;
5079 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5082 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5085 static void io_poll_req_insert(struct io_kiocb *req)
5087 struct io_ring_ctx *ctx = req->ctx;
5088 struct hlist_head *list;
5090 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5091 hlist_add_head(&req->hash_node, list);
5094 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5095 struct io_poll_iocb *poll,
5096 struct io_poll_table *ipt, __poll_t mask,
5097 wait_queue_func_t wake_func)
5098 __acquires(&ctx->completion_lock)
5100 struct io_ring_ctx *ctx = req->ctx;
5101 bool cancel = false;
5103 INIT_HLIST_NODE(&req->hash_node);
5104 io_init_poll_iocb(poll, mask, wake_func);
5105 poll->file = req->file;
5106 poll->wait.private = req;
5108 ipt->pt._key = mask;
5110 ipt->error = -EINVAL;
5112 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5114 spin_lock_irq(&ctx->completion_lock);
5115 if (likely(poll->head)) {
5116 spin_lock(&poll->head->lock);
5117 if (unlikely(list_empty(&poll->wait.entry))) {
5123 if (mask || ipt->error)
5124 list_del_init(&poll->wait.entry);
5126 WRITE_ONCE(poll->canceled, true);
5127 else if (!poll->done) /* actually waiting for an event */
5128 io_poll_req_insert(req);
5129 spin_unlock(&poll->head->lock);
5135 static bool io_arm_poll_handler(struct io_kiocb *req)
5137 const struct io_op_def *def = &io_op_defs[req->opcode];
5138 struct io_ring_ctx *ctx = req->ctx;
5139 struct async_poll *apoll;
5140 struct io_poll_table ipt;
5144 if (!req->file || !file_can_poll(req->file))
5146 if (req->flags & REQ_F_POLLED)
5150 else if (def->pollout)
5154 /* if we can't nonblock try, then no point in arming a poll handler */
5155 if (!io_file_supports_async(req->file, rw))
5158 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5159 if (unlikely(!apoll))
5161 apoll->double_poll = NULL;
5163 req->flags |= REQ_F_POLLED;
5168 mask |= POLLIN | POLLRDNORM;
5170 mask |= POLLOUT | POLLWRNORM;
5172 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5173 if ((req->opcode == IORING_OP_RECVMSG) &&
5174 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5177 mask |= POLLERR | POLLPRI;
5179 ipt.pt._qproc = io_async_queue_proc;
5181 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5183 if (ret || ipt.error) {
5184 io_poll_remove_double(req);
5185 spin_unlock_irq(&ctx->completion_lock);
5186 kfree(apoll->double_poll);
5190 spin_unlock_irq(&ctx->completion_lock);
5191 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5192 apoll->poll.events);
5196 static bool __io_poll_remove_one(struct io_kiocb *req,
5197 struct io_poll_iocb *poll)
5199 bool do_complete = false;
5201 spin_lock(&poll->head->lock);
5202 WRITE_ONCE(poll->canceled, true);
5203 if (!list_empty(&poll->wait.entry)) {
5204 list_del_init(&poll->wait.entry);
5207 spin_unlock(&poll->head->lock);
5208 hash_del(&req->hash_node);
5212 static bool io_poll_remove_one(struct io_kiocb *req)
5216 io_poll_remove_double(req);
5218 if (req->opcode == IORING_OP_POLL_ADD) {
5219 do_complete = __io_poll_remove_one(req, &req->poll);
5221 struct async_poll *apoll = req->apoll;
5223 /* non-poll requests have submit ref still */
5224 do_complete = __io_poll_remove_one(req, &apoll->poll);
5227 kfree(apoll->double_poll);
5233 io_cqring_fill_event(req, -ECANCELED);
5234 io_commit_cqring(req->ctx);
5235 req_set_fail_links(req);
5236 io_put_req_deferred(req, 1);
5243 * Returns true if we found and killed one or more poll requests
5245 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5246 struct files_struct *files)
5248 struct hlist_node *tmp;
5249 struct io_kiocb *req;
5252 spin_lock_irq(&ctx->completion_lock);
5253 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5254 struct hlist_head *list;
5256 list = &ctx->cancel_hash[i];
5257 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5258 if (io_match_task(req, tsk, files))
5259 posted += io_poll_remove_one(req);
5262 spin_unlock_irq(&ctx->completion_lock);
5265 io_cqring_ev_posted(ctx);
5270 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5272 struct hlist_head *list;
5273 struct io_kiocb *req;
5275 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5276 hlist_for_each_entry(req, list, hash_node) {
5277 if (sqe_addr != req->user_data)
5279 if (io_poll_remove_one(req))
5287 static int io_poll_remove_prep(struct io_kiocb *req,
5288 const struct io_uring_sqe *sqe)
5290 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5292 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5296 req->poll_remove.addr = READ_ONCE(sqe->addr);
5301 * Find a running poll command that matches one specified in sqe->addr,
5302 * and remove it if found.
5304 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5306 struct io_ring_ctx *ctx = req->ctx;
5309 spin_lock_irq(&ctx->completion_lock);
5310 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5311 spin_unlock_irq(&ctx->completion_lock);
5314 req_set_fail_links(req);
5315 io_req_complete(req, ret);
5319 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5322 struct io_kiocb *req = wait->private;
5323 struct io_poll_iocb *poll = &req->poll;
5325 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5328 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5329 struct poll_table_struct *p)
5331 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5333 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5336 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5338 struct io_poll_iocb *poll = &req->poll;
5341 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5343 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5346 events = READ_ONCE(sqe->poll32_events);
5348 events = swahw32(events);
5350 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5351 (events & EPOLLEXCLUSIVE);
5355 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5357 struct io_poll_iocb *poll = &req->poll;
5358 struct io_ring_ctx *ctx = req->ctx;
5359 struct io_poll_table ipt;
5362 ipt.pt._qproc = io_poll_queue_proc;
5364 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5367 if (mask) { /* no async, we'd stolen it */
5369 io_poll_complete(req, mask, 0);
5371 spin_unlock_irq(&ctx->completion_lock);
5374 io_cqring_ev_posted(ctx);
5380 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5382 struct io_timeout_data *data = container_of(timer,
5383 struct io_timeout_data, timer);
5384 struct io_kiocb *req = data->req;
5385 struct io_ring_ctx *ctx = req->ctx;
5386 unsigned long flags;
5388 spin_lock_irqsave(&ctx->completion_lock, flags);
5389 list_del_init(&req->timeout.list);
5390 atomic_set(&req->ctx->cq_timeouts,
5391 atomic_read(&req->ctx->cq_timeouts) + 1);
5393 io_cqring_fill_event(req, -ETIME);
5394 io_commit_cqring(ctx);
5395 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5397 io_cqring_ev_posted(ctx);
5398 req_set_fail_links(req);
5400 return HRTIMER_NORESTART;
5403 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5406 struct io_timeout_data *io;
5407 struct io_kiocb *req;
5410 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5411 if (user_data == req->user_data) {
5418 return ERR_PTR(ret);
5420 io = req->async_data;
5421 ret = hrtimer_try_to_cancel(&io->timer);
5423 return ERR_PTR(-EALREADY);
5424 list_del_init(&req->timeout.list);
5428 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5430 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5433 return PTR_ERR(req);
5435 req_set_fail_links(req);
5436 io_cqring_fill_event(req, -ECANCELED);
5437 io_put_req_deferred(req, 1);
5441 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5442 struct timespec64 *ts, enum hrtimer_mode mode)
5444 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5445 struct io_timeout_data *data;
5448 return PTR_ERR(req);
5450 req->timeout.off = 0; /* noseq */
5451 data = req->async_data;
5452 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5453 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5454 data->timer.function = io_timeout_fn;
5455 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5459 static int io_timeout_remove_prep(struct io_kiocb *req,
5460 const struct io_uring_sqe *sqe)
5462 struct io_timeout_rem *tr = &req->timeout_rem;
5464 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5466 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5468 if (sqe->ioprio || sqe->buf_index || sqe->len)
5471 tr->addr = READ_ONCE(sqe->addr);
5472 tr->flags = READ_ONCE(sqe->timeout_flags);
5473 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5474 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5476 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5478 } else if (tr->flags) {
5479 /* timeout removal doesn't support flags */
5486 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5488 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5493 * Remove or update an existing timeout command
5495 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5497 struct io_timeout_rem *tr = &req->timeout_rem;
5498 struct io_ring_ctx *ctx = req->ctx;
5501 spin_lock_irq(&ctx->completion_lock);
5502 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5503 ret = io_timeout_cancel(ctx, tr->addr);
5505 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5506 io_translate_timeout_mode(tr->flags));
5508 io_cqring_fill_event(req, ret);
5509 io_commit_cqring(ctx);
5510 spin_unlock_irq(&ctx->completion_lock);
5511 io_cqring_ev_posted(ctx);
5513 req_set_fail_links(req);
5518 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5519 bool is_timeout_link)
5521 struct io_timeout_data *data;
5523 u32 off = READ_ONCE(sqe->off);
5525 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5527 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5529 if (off && is_timeout_link)
5531 flags = READ_ONCE(sqe->timeout_flags);
5532 if (flags & ~IORING_TIMEOUT_ABS)
5535 req->timeout.off = off;
5537 if (!req->async_data && io_alloc_async_data(req))
5540 data = req->async_data;
5543 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5546 data->mode = io_translate_timeout_mode(flags);
5547 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5551 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5553 struct io_ring_ctx *ctx = req->ctx;
5554 struct io_timeout_data *data = req->async_data;
5555 struct list_head *entry;
5556 u32 tail, off = req->timeout.off;
5558 spin_lock_irq(&ctx->completion_lock);
5561 * sqe->off holds how many events that need to occur for this
5562 * timeout event to be satisfied. If it isn't set, then this is
5563 * a pure timeout request, sequence isn't used.
5565 if (io_is_timeout_noseq(req)) {
5566 entry = ctx->timeout_list.prev;
5570 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5571 req->timeout.target_seq = tail + off;
5573 /* Update the last seq here in case io_flush_timeouts() hasn't.
5574 * This is safe because ->completion_lock is held, and submissions
5575 * and completions are never mixed in the same ->completion_lock section.
5577 ctx->cq_last_tm_flush = tail;
5580 * Insertion sort, ensuring the first entry in the list is always
5581 * the one we need first.
5583 list_for_each_prev(entry, &ctx->timeout_list) {
5584 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5587 if (io_is_timeout_noseq(nxt))
5589 /* nxt.seq is behind @tail, otherwise would've been completed */
5590 if (off >= nxt->timeout.target_seq - tail)
5594 list_add(&req->timeout.list, entry);
5595 data->timer.function = io_timeout_fn;
5596 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5597 spin_unlock_irq(&ctx->completion_lock);
5601 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5603 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5605 return req->user_data == (unsigned long) data;
5608 static int io_async_cancel_one(struct io_uring_task *tctx, void *sqe_addr)
5610 enum io_wq_cancel cancel_ret;
5616 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, sqe_addr, false);
5617 switch (cancel_ret) {
5618 case IO_WQ_CANCEL_OK:
5621 case IO_WQ_CANCEL_RUNNING:
5624 case IO_WQ_CANCEL_NOTFOUND:
5632 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5633 struct io_kiocb *req, __u64 sqe_addr,
5636 unsigned long flags;
5639 ret = io_async_cancel_one(req->task->io_uring,
5640 (void *) (unsigned long) sqe_addr);
5641 if (ret != -ENOENT) {
5642 spin_lock_irqsave(&ctx->completion_lock, flags);
5646 spin_lock_irqsave(&ctx->completion_lock, flags);
5647 ret = io_timeout_cancel(ctx, sqe_addr);
5650 ret = io_poll_cancel(ctx, sqe_addr);
5654 io_cqring_fill_event(req, ret);
5655 io_commit_cqring(ctx);
5656 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5657 io_cqring_ev_posted(ctx);
5660 req_set_fail_links(req);
5664 static int io_async_cancel_prep(struct io_kiocb *req,
5665 const struct io_uring_sqe *sqe)
5667 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5669 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5671 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5674 req->cancel.addr = READ_ONCE(sqe->addr);
5678 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5680 struct io_ring_ctx *ctx = req->ctx;
5682 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5686 static int io_rsrc_update_prep(struct io_kiocb *req,
5687 const struct io_uring_sqe *sqe)
5689 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5691 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5693 if (sqe->ioprio || sqe->rw_flags)
5696 req->rsrc_update.offset = READ_ONCE(sqe->off);
5697 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5698 if (!req->rsrc_update.nr_args)
5700 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5704 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5706 struct io_ring_ctx *ctx = req->ctx;
5707 struct io_uring_rsrc_update up;
5710 if (issue_flags & IO_URING_F_NONBLOCK)
5713 up.offset = req->rsrc_update.offset;
5714 up.data = req->rsrc_update.arg;
5716 mutex_lock(&ctx->uring_lock);
5717 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5718 mutex_unlock(&ctx->uring_lock);
5721 req_set_fail_links(req);
5722 __io_req_complete(req, issue_flags, ret, 0);
5726 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5728 switch (req->opcode) {
5731 case IORING_OP_READV:
5732 case IORING_OP_READ_FIXED:
5733 case IORING_OP_READ:
5734 return io_read_prep(req, sqe);
5735 case IORING_OP_WRITEV:
5736 case IORING_OP_WRITE_FIXED:
5737 case IORING_OP_WRITE:
5738 return io_write_prep(req, sqe);
5739 case IORING_OP_POLL_ADD:
5740 return io_poll_add_prep(req, sqe);
5741 case IORING_OP_POLL_REMOVE:
5742 return io_poll_remove_prep(req, sqe);
5743 case IORING_OP_FSYNC:
5744 return io_fsync_prep(req, sqe);
5745 case IORING_OP_SYNC_FILE_RANGE:
5746 return io_sfr_prep(req, sqe);
5747 case IORING_OP_SENDMSG:
5748 case IORING_OP_SEND:
5749 return io_sendmsg_prep(req, sqe);
5750 case IORING_OP_RECVMSG:
5751 case IORING_OP_RECV:
5752 return io_recvmsg_prep(req, sqe);
5753 case IORING_OP_CONNECT:
5754 return io_connect_prep(req, sqe);
5755 case IORING_OP_TIMEOUT:
5756 return io_timeout_prep(req, sqe, false);
5757 case IORING_OP_TIMEOUT_REMOVE:
5758 return io_timeout_remove_prep(req, sqe);
5759 case IORING_OP_ASYNC_CANCEL:
5760 return io_async_cancel_prep(req, sqe);
5761 case IORING_OP_LINK_TIMEOUT:
5762 return io_timeout_prep(req, sqe, true);
5763 case IORING_OP_ACCEPT:
5764 return io_accept_prep(req, sqe);
5765 case IORING_OP_FALLOCATE:
5766 return io_fallocate_prep(req, sqe);
5767 case IORING_OP_OPENAT:
5768 return io_openat_prep(req, sqe);
5769 case IORING_OP_CLOSE:
5770 return io_close_prep(req, sqe);
5771 case IORING_OP_FILES_UPDATE:
5772 return io_rsrc_update_prep(req, sqe);
5773 case IORING_OP_STATX:
5774 return io_statx_prep(req, sqe);
5775 case IORING_OP_FADVISE:
5776 return io_fadvise_prep(req, sqe);
5777 case IORING_OP_MADVISE:
5778 return io_madvise_prep(req, sqe);
5779 case IORING_OP_OPENAT2:
5780 return io_openat2_prep(req, sqe);
5781 case IORING_OP_EPOLL_CTL:
5782 return io_epoll_ctl_prep(req, sqe);
5783 case IORING_OP_SPLICE:
5784 return io_splice_prep(req, sqe);
5785 case IORING_OP_PROVIDE_BUFFERS:
5786 return io_provide_buffers_prep(req, sqe);
5787 case IORING_OP_REMOVE_BUFFERS:
5788 return io_remove_buffers_prep(req, sqe);
5790 return io_tee_prep(req, sqe);
5791 case IORING_OP_SHUTDOWN:
5792 return io_shutdown_prep(req, sqe);
5793 case IORING_OP_RENAMEAT:
5794 return io_renameat_prep(req, sqe);
5795 case IORING_OP_UNLINKAT:
5796 return io_unlinkat_prep(req, sqe);
5799 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5804 static int io_req_prep_async(struct io_kiocb *req)
5806 switch (req->opcode) {
5807 case IORING_OP_READV:
5808 case IORING_OP_READ_FIXED:
5809 case IORING_OP_READ:
5810 return io_rw_prep_async(req, READ);
5811 case IORING_OP_WRITEV:
5812 case IORING_OP_WRITE_FIXED:
5813 case IORING_OP_WRITE:
5814 return io_rw_prep_async(req, WRITE);
5815 case IORING_OP_SENDMSG:
5816 case IORING_OP_SEND:
5817 return io_sendmsg_prep_async(req);
5818 case IORING_OP_RECVMSG:
5819 case IORING_OP_RECV:
5820 return io_recvmsg_prep_async(req);
5821 case IORING_OP_CONNECT:
5822 return io_connect_prep_async(req);
5827 static int io_req_defer_prep(struct io_kiocb *req)
5829 if (!io_op_defs[req->opcode].needs_async_data)
5831 /* some opcodes init it during the inital prep */
5832 if (req->async_data)
5834 if (__io_alloc_async_data(req))
5836 return io_req_prep_async(req);
5839 static u32 io_get_sequence(struct io_kiocb *req)
5841 struct io_kiocb *pos;
5842 struct io_ring_ctx *ctx = req->ctx;
5843 u32 total_submitted, nr_reqs = 0;
5845 io_for_each_link(pos, req)
5848 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5849 return total_submitted - nr_reqs;
5852 static int io_req_defer(struct io_kiocb *req)
5854 struct io_ring_ctx *ctx = req->ctx;
5855 struct io_defer_entry *de;
5859 /* Still need defer if there is pending req in defer list. */
5860 if (likely(list_empty_careful(&ctx->defer_list) &&
5861 !(req->flags & REQ_F_IO_DRAIN)))
5864 seq = io_get_sequence(req);
5865 /* Still a chance to pass the sequence check */
5866 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5869 ret = io_req_defer_prep(req);
5872 io_prep_async_link(req);
5873 de = kmalloc(sizeof(*de), GFP_KERNEL);
5877 spin_lock_irq(&ctx->completion_lock);
5878 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5879 spin_unlock_irq(&ctx->completion_lock);
5881 io_queue_async_work(req);
5882 return -EIOCBQUEUED;
5885 trace_io_uring_defer(ctx, req, req->user_data);
5888 list_add_tail(&de->list, &ctx->defer_list);
5889 spin_unlock_irq(&ctx->completion_lock);
5890 return -EIOCBQUEUED;
5893 static void __io_clean_op(struct io_kiocb *req)
5895 if (req->flags & REQ_F_BUFFER_SELECTED) {
5896 switch (req->opcode) {
5897 case IORING_OP_READV:
5898 case IORING_OP_READ_FIXED:
5899 case IORING_OP_READ:
5900 kfree((void *)(unsigned long)req->rw.addr);
5902 case IORING_OP_RECVMSG:
5903 case IORING_OP_RECV:
5904 kfree(req->sr_msg.kbuf);
5907 req->flags &= ~REQ_F_BUFFER_SELECTED;
5910 if (req->flags & REQ_F_NEED_CLEANUP) {
5911 switch (req->opcode) {
5912 case IORING_OP_READV:
5913 case IORING_OP_READ_FIXED:
5914 case IORING_OP_READ:
5915 case IORING_OP_WRITEV:
5916 case IORING_OP_WRITE_FIXED:
5917 case IORING_OP_WRITE: {
5918 struct io_async_rw *io = req->async_data;
5920 kfree(io->free_iovec);
5923 case IORING_OP_RECVMSG:
5924 case IORING_OP_SENDMSG: {
5925 struct io_async_msghdr *io = req->async_data;
5927 kfree(io->free_iov);
5930 case IORING_OP_SPLICE:
5932 io_put_file(req, req->splice.file_in,
5933 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5935 case IORING_OP_OPENAT:
5936 case IORING_OP_OPENAT2:
5937 if (req->open.filename)
5938 putname(req->open.filename);
5940 case IORING_OP_RENAMEAT:
5941 putname(req->rename.oldpath);
5942 putname(req->rename.newpath);
5944 case IORING_OP_UNLINKAT:
5945 putname(req->unlink.filename);
5948 req->flags &= ~REQ_F_NEED_CLEANUP;
5952 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
5954 struct io_ring_ctx *ctx = req->ctx;
5957 switch (req->opcode) {
5959 ret = io_nop(req, issue_flags);
5961 case IORING_OP_READV:
5962 case IORING_OP_READ_FIXED:
5963 case IORING_OP_READ:
5964 ret = io_read(req, issue_flags);
5966 case IORING_OP_WRITEV:
5967 case IORING_OP_WRITE_FIXED:
5968 case IORING_OP_WRITE:
5969 ret = io_write(req, issue_flags);
5971 case IORING_OP_FSYNC:
5972 ret = io_fsync(req, issue_flags);
5974 case IORING_OP_POLL_ADD:
5975 ret = io_poll_add(req, issue_flags);
5977 case IORING_OP_POLL_REMOVE:
5978 ret = io_poll_remove(req, issue_flags);
5980 case IORING_OP_SYNC_FILE_RANGE:
5981 ret = io_sync_file_range(req, issue_flags);
5983 case IORING_OP_SENDMSG:
5984 ret = io_sendmsg(req, issue_flags);
5986 case IORING_OP_SEND:
5987 ret = io_send(req, issue_flags);
5989 case IORING_OP_RECVMSG:
5990 ret = io_recvmsg(req, issue_flags);
5992 case IORING_OP_RECV:
5993 ret = io_recv(req, issue_flags);
5995 case IORING_OP_TIMEOUT:
5996 ret = io_timeout(req, issue_flags);
5998 case IORING_OP_TIMEOUT_REMOVE:
5999 ret = io_timeout_remove(req, issue_flags);
6001 case IORING_OP_ACCEPT:
6002 ret = io_accept(req, issue_flags);
6004 case IORING_OP_CONNECT:
6005 ret = io_connect(req, issue_flags);
6007 case IORING_OP_ASYNC_CANCEL:
6008 ret = io_async_cancel(req, issue_flags);
6010 case IORING_OP_FALLOCATE:
6011 ret = io_fallocate(req, issue_flags);
6013 case IORING_OP_OPENAT:
6014 ret = io_openat(req, issue_flags);
6016 case IORING_OP_CLOSE:
6017 ret = io_close(req, issue_flags);
6019 case IORING_OP_FILES_UPDATE:
6020 ret = io_files_update(req, issue_flags);
6022 case IORING_OP_STATX:
6023 ret = io_statx(req, issue_flags);
6025 case IORING_OP_FADVISE:
6026 ret = io_fadvise(req, issue_flags);
6028 case IORING_OP_MADVISE:
6029 ret = io_madvise(req, issue_flags);
6031 case IORING_OP_OPENAT2:
6032 ret = io_openat2(req, issue_flags);
6034 case IORING_OP_EPOLL_CTL:
6035 ret = io_epoll_ctl(req, issue_flags);
6037 case IORING_OP_SPLICE:
6038 ret = io_splice(req, issue_flags);
6040 case IORING_OP_PROVIDE_BUFFERS:
6041 ret = io_provide_buffers(req, issue_flags);
6043 case IORING_OP_REMOVE_BUFFERS:
6044 ret = io_remove_buffers(req, issue_flags);
6047 ret = io_tee(req, issue_flags);
6049 case IORING_OP_SHUTDOWN:
6050 ret = io_shutdown(req, issue_flags);
6052 case IORING_OP_RENAMEAT:
6053 ret = io_renameat(req, issue_flags);
6055 case IORING_OP_UNLINKAT:
6056 ret = io_unlinkat(req, issue_flags);
6066 /* If the op doesn't have a file, we're not polling for it */
6067 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6068 const bool in_async = io_wq_current_is_worker();
6070 /* workqueue context doesn't hold uring_lock, grab it now */
6072 mutex_lock(&ctx->uring_lock);
6074 io_iopoll_req_issued(req, in_async);
6077 mutex_unlock(&ctx->uring_lock);
6083 static void io_wq_submit_work(struct io_wq_work *work)
6085 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6086 struct io_kiocb *timeout;
6089 timeout = io_prep_linked_timeout(req);
6091 io_queue_linked_timeout(timeout);
6093 if (work->flags & IO_WQ_WORK_CANCEL)
6098 ret = io_issue_sqe(req, 0);
6100 * We can get EAGAIN for polled IO even though we're
6101 * forcing a sync submission from here, since we can't
6102 * wait for request slots on the block side.
6110 /* avoid locking problems by failing it from a clean context */
6112 /* io-wq is going to take one down */
6113 refcount_inc(&req->refs);
6114 io_req_task_queue_fail(req, ret);
6118 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6121 struct fixed_rsrc_table *table;
6123 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6124 return table->files[index & IORING_FILE_TABLE_MASK];
6127 static struct file *io_file_get(struct io_submit_state *state,
6128 struct io_kiocb *req, int fd, bool fixed)
6130 struct io_ring_ctx *ctx = req->ctx;
6134 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6136 fd = array_index_nospec(fd, ctx->nr_user_files);
6137 file = io_file_from_index(ctx, fd);
6138 io_set_resource_node(req);
6140 trace_io_uring_file_get(ctx, fd);
6141 file = __io_file_get(state, fd);
6144 if (file && unlikely(file->f_op == &io_uring_fops))
6145 io_req_track_inflight(req);
6149 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6151 struct io_timeout_data *data = container_of(timer,
6152 struct io_timeout_data, timer);
6153 struct io_kiocb *prev, *req = data->req;
6154 struct io_ring_ctx *ctx = req->ctx;
6155 unsigned long flags;
6157 spin_lock_irqsave(&ctx->completion_lock, flags);
6158 prev = req->timeout.head;
6159 req->timeout.head = NULL;
6162 * We don't expect the list to be empty, that will only happen if we
6163 * race with the completion of the linked work.
6165 if (prev && refcount_inc_not_zero(&prev->refs))
6166 io_remove_next_linked(prev);
6169 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6172 req_set_fail_links(prev);
6173 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6174 io_put_req_deferred(prev, 1);
6176 io_req_complete_post(req, -ETIME, 0);
6177 io_put_req_deferred(req, 1);
6179 return HRTIMER_NORESTART;
6182 static void __io_queue_linked_timeout(struct io_kiocb *req)
6185 * If the back reference is NULL, then our linked request finished
6186 * before we got a chance to setup the timer
6188 if (req->timeout.head) {
6189 struct io_timeout_data *data = req->async_data;
6191 data->timer.function = io_link_timeout_fn;
6192 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6197 static void io_queue_linked_timeout(struct io_kiocb *req)
6199 struct io_ring_ctx *ctx = req->ctx;
6201 spin_lock_irq(&ctx->completion_lock);
6202 __io_queue_linked_timeout(req);
6203 spin_unlock_irq(&ctx->completion_lock);
6205 /* drop submission reference */
6209 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6211 struct io_kiocb *nxt = req->link;
6213 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6214 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6217 nxt->timeout.head = req;
6218 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6219 req->flags |= REQ_F_LINK_TIMEOUT;
6223 static void __io_queue_sqe(struct io_kiocb *req)
6225 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6226 const struct cred *old_creds = NULL;
6229 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
6230 req->work.creds != current_cred())
6231 old_creds = override_creds(req->work.creds);
6233 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6236 revert_creds(old_creds);
6239 * We async punt it if the file wasn't marked NOWAIT, or if the file
6240 * doesn't support non-blocking read/write attempts
6242 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6243 if (!io_arm_poll_handler(req)) {
6245 * Queued up for async execution, worker will release
6246 * submit reference when the iocb is actually submitted.
6248 io_queue_async_work(req);
6250 } else if (likely(!ret)) {
6251 /* drop submission reference */
6252 if (req->flags & REQ_F_COMPLETE_INLINE) {
6253 struct io_ring_ctx *ctx = req->ctx;
6254 struct io_comp_state *cs = &ctx->submit_state.comp;
6256 cs->reqs[cs->nr++] = req;
6257 if (cs->nr == ARRAY_SIZE(cs->reqs))
6258 io_submit_flush_completions(cs, ctx);
6263 req_set_fail_links(req);
6265 io_req_complete(req, ret);
6268 io_queue_linked_timeout(linked_timeout);
6271 static void io_queue_sqe(struct io_kiocb *req)
6275 ret = io_req_defer(req);
6277 if (ret != -EIOCBQUEUED) {
6279 req_set_fail_links(req);
6281 io_req_complete(req, ret);
6283 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6284 ret = io_req_defer_prep(req);
6287 io_queue_async_work(req);
6289 __io_queue_sqe(req);
6294 * Check SQE restrictions (opcode and flags).
6296 * Returns 'true' if SQE is allowed, 'false' otherwise.
6298 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6299 struct io_kiocb *req,
6300 unsigned int sqe_flags)
6302 if (!ctx->restricted)
6305 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6308 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6309 ctx->restrictions.sqe_flags_required)
6312 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6313 ctx->restrictions.sqe_flags_required))
6319 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6320 const struct io_uring_sqe *sqe)
6322 struct io_submit_state *state;
6323 unsigned int sqe_flags;
6326 req->opcode = READ_ONCE(sqe->opcode);
6327 /* same numerical values with corresponding REQ_F_*, safe to copy */
6328 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6329 req->user_data = READ_ONCE(sqe->user_data);
6330 req->async_data = NULL;
6334 req->fixed_rsrc_refs = NULL;
6335 /* one is dropped after submission, the other at completion */
6336 refcount_set(&req->refs, 2);
6337 req->task = current;
6340 /* enforce forwards compatibility on users */
6341 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6346 if (unlikely(req->opcode >= IORING_OP_LAST))
6349 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6352 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6353 !io_op_defs[req->opcode].buffer_select)
6356 id = READ_ONCE(sqe->personality);
6358 __io_req_init_async(req);
6359 req->work.creds = idr_find(&ctx->personality_idr, id);
6360 if (unlikely(!req->work.creds))
6362 get_cred(req->work.creds);
6365 state = &ctx->submit_state;
6368 * Plug now if we have more than 1 IO left after this, and the target
6369 * is potentially a read/write to block based storage.
6371 if (!state->plug_started && state->ios_left > 1 &&
6372 io_op_defs[req->opcode].plug) {
6373 blk_start_plug(&state->plug);
6374 state->plug_started = true;
6377 if (io_op_defs[req->opcode].needs_file) {
6378 bool fixed = req->flags & REQ_F_FIXED_FILE;
6380 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6381 if (unlikely(!req->file))
6389 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6390 const struct io_uring_sqe *sqe)
6392 struct io_submit_link *link = &ctx->submit_state.link;
6395 ret = io_init_req(ctx, req, sqe);
6396 if (unlikely(ret)) {
6399 io_req_complete(req, ret);
6401 /* fail even hard links since we don't submit */
6402 link->head->flags |= REQ_F_FAIL_LINK;
6403 io_put_req(link->head);
6404 io_req_complete(link->head, -ECANCELED);
6409 ret = io_req_prep(req, sqe);
6413 /* don't need @sqe from now on */
6414 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6415 true, ctx->flags & IORING_SETUP_SQPOLL);
6418 * If we already have a head request, queue this one for async
6419 * submittal once the head completes. If we don't have a head but
6420 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6421 * submitted sync once the chain is complete. If none of those
6422 * conditions are true (normal request), then just queue it.
6425 struct io_kiocb *head = link->head;
6428 * Taking sequential execution of a link, draining both sides
6429 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6430 * requests in the link. So, it drains the head and the
6431 * next after the link request. The last one is done via
6432 * drain_next flag to persist the effect across calls.
6434 if (req->flags & REQ_F_IO_DRAIN) {
6435 head->flags |= REQ_F_IO_DRAIN;
6436 ctx->drain_next = 1;
6438 ret = io_req_defer_prep(req);
6441 trace_io_uring_link(ctx, req, head);
6442 link->last->link = req;
6445 /* last request of a link, enqueue the link */
6446 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6451 if (unlikely(ctx->drain_next)) {
6452 req->flags |= REQ_F_IO_DRAIN;
6453 ctx->drain_next = 0;
6455 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6467 * Batched submission is done, ensure local IO is flushed out.
6469 static void io_submit_state_end(struct io_submit_state *state,
6470 struct io_ring_ctx *ctx)
6472 if (state->link.head)
6473 io_queue_sqe(state->link.head);
6475 io_submit_flush_completions(&state->comp, ctx);
6476 if (state->plug_started)
6477 blk_finish_plug(&state->plug);
6478 io_state_file_put(state);
6482 * Start submission side cache.
6484 static void io_submit_state_start(struct io_submit_state *state,
6485 unsigned int max_ios)
6487 state->plug_started = false;
6488 state->ios_left = max_ios;
6489 /* set only head, no need to init link_last in advance */
6490 state->link.head = NULL;
6493 static void io_commit_sqring(struct io_ring_ctx *ctx)
6495 struct io_rings *rings = ctx->rings;
6498 * Ensure any loads from the SQEs are done at this point,
6499 * since once we write the new head, the application could
6500 * write new data to them.
6502 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6506 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6507 * that is mapped by userspace. This means that care needs to be taken to
6508 * ensure that reads are stable, as we cannot rely on userspace always
6509 * being a good citizen. If members of the sqe are validated and then later
6510 * used, it's important that those reads are done through READ_ONCE() to
6511 * prevent a re-load down the line.
6513 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6515 u32 *sq_array = ctx->sq_array;
6519 * The cached sq head (or cq tail) serves two purposes:
6521 * 1) allows us to batch the cost of updating the user visible
6523 * 2) allows the kernel side to track the head on its own, even
6524 * though the application is the one updating it.
6526 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6527 if (likely(head < ctx->sq_entries))
6528 return &ctx->sq_sqes[head];
6530 /* drop invalid entries */
6531 ctx->cached_sq_dropped++;
6532 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6536 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6540 /* if we have a backlog and couldn't flush it all, return BUSY */
6541 if (test_bit(0, &ctx->sq_check_overflow)) {
6542 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6546 /* make sure SQ entry isn't read before tail */
6547 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6549 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6552 percpu_counter_add(¤t->io_uring->inflight, nr);
6553 refcount_add(nr, ¤t->usage);
6554 io_submit_state_start(&ctx->submit_state, nr);
6556 while (submitted < nr) {
6557 const struct io_uring_sqe *sqe;
6558 struct io_kiocb *req;
6560 req = io_alloc_req(ctx);
6561 if (unlikely(!req)) {
6563 submitted = -EAGAIN;
6566 sqe = io_get_sqe(ctx);
6567 if (unlikely(!sqe)) {
6568 kmem_cache_free(req_cachep, req);
6571 /* will complete beyond this point, count as submitted */
6573 if (io_submit_sqe(ctx, req, sqe))
6577 if (unlikely(submitted != nr)) {
6578 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6579 struct io_uring_task *tctx = current->io_uring;
6580 int unused = nr - ref_used;
6582 percpu_ref_put_many(&ctx->refs, unused);
6583 percpu_counter_sub(&tctx->inflight, unused);
6584 put_task_struct_many(current, unused);
6587 io_submit_state_end(&ctx->submit_state, ctx);
6588 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6589 io_commit_sqring(ctx);
6594 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6596 /* Tell userspace we may need a wakeup call */
6597 spin_lock_irq(&ctx->completion_lock);
6598 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6599 spin_unlock_irq(&ctx->completion_lock);
6602 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6604 spin_lock_irq(&ctx->completion_lock);
6605 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6606 spin_unlock_irq(&ctx->completion_lock);
6609 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6611 unsigned int to_submit;
6614 to_submit = io_sqring_entries(ctx);
6615 /* if we're handling multiple rings, cap submit size for fairness */
6616 if (cap_entries && to_submit > 8)
6619 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6620 unsigned nr_events = 0;
6622 mutex_lock(&ctx->uring_lock);
6623 if (!list_empty(&ctx->iopoll_list))
6624 io_do_iopoll(ctx, &nr_events, 0);
6626 if (to_submit && !ctx->sqo_dead &&
6627 likely(!percpu_ref_is_dying(&ctx->refs)))
6628 ret = io_submit_sqes(ctx, to_submit);
6629 mutex_unlock(&ctx->uring_lock);
6632 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6633 wake_up(&ctx->sqo_sq_wait);
6638 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6640 struct io_ring_ctx *ctx;
6641 unsigned sq_thread_idle = 0;
6643 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6644 if (sq_thread_idle < ctx->sq_thread_idle)
6645 sq_thread_idle = ctx->sq_thread_idle;
6648 sqd->sq_thread_idle = sq_thread_idle;
6651 static void io_sqd_init_new(struct io_sq_data *sqd)
6653 struct io_ring_ctx *ctx;
6655 while (!list_empty(&sqd->ctx_new_list)) {
6656 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6657 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6658 complete(&ctx->sq_thread_comp);
6661 io_sqd_update_thread_idle(sqd);
6664 static bool io_sq_thread_should_stop(struct io_sq_data *sqd)
6666 return test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6669 static bool io_sq_thread_should_park(struct io_sq_data *sqd)
6671 return test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
6674 static void io_sq_thread_parkme(struct io_sq_data *sqd)
6678 * TASK_PARKED is a special state; we must serialize against
6679 * possible pending wakeups to avoid store-store collisions on
6682 * Such a collision might possibly result in the task state
6683 * changin from TASK_PARKED and us failing the
6684 * wait_task_inactive() in kthread_park().
6686 set_special_state(TASK_PARKED);
6687 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state))
6691 * Thread is going to call schedule(), do not preempt it,
6692 * or the caller of kthread_park() may spend more time in
6693 * wait_task_inactive().
6696 complete(&sqd->completion);
6697 schedule_preempt_disabled();
6700 __set_current_state(TASK_RUNNING);
6703 static int io_sq_thread(void *data)
6705 struct io_sq_data *sqd = data;
6706 struct io_ring_ctx *ctx;
6707 unsigned long timeout = 0;
6708 char buf[TASK_COMM_LEN];
6711 sprintf(buf, "iou-sqp-%d", sqd->task_pid);
6712 set_task_comm(current, buf);
6713 sqd->thread = current;
6714 current->pf_io_worker = NULL;
6716 if (sqd->sq_cpu != -1)
6717 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6719 set_cpus_allowed_ptr(current, cpu_online_mask);
6720 current->flags |= PF_NO_SETAFFINITY;
6722 complete(&sqd->completion);
6724 wait_for_completion(&sqd->startup);
6726 while (!io_sq_thread_should_stop(sqd)) {
6728 bool cap_entries, sqt_spin, needs_sched;
6731 * Any changes to the sqd lists are synchronized through the
6732 * thread parking. This synchronizes the thread vs users,
6733 * the users are synchronized on the sqd->ctx_lock.
6735 if (io_sq_thread_should_park(sqd)) {
6736 io_sq_thread_parkme(sqd);
6739 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
6740 io_sqd_init_new(sqd);
6741 timeout = jiffies + sqd->sq_thread_idle;
6743 if (fatal_signal_pending(current))
6746 cap_entries = !list_is_singular(&sqd->ctx_list);
6747 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6748 ret = __io_sq_thread(ctx, cap_entries);
6749 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6753 if (sqt_spin || !time_after(jiffies, timeout)) {
6757 timeout = jiffies + sqd->sq_thread_idle;
6762 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6763 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6764 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6765 !list_empty_careful(&ctx->iopoll_list)) {
6766 needs_sched = false;
6769 if (io_sqring_entries(ctx)) {
6770 needs_sched = false;
6775 if (needs_sched && !io_sq_thread_should_park(sqd)) {
6776 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6777 io_ring_set_wakeup_flag(ctx);
6780 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6781 io_ring_clear_wakeup_flag(ctx);
6784 finish_wait(&sqd->wait, &wait);
6785 timeout = jiffies + sqd->sq_thread_idle;
6788 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6789 io_uring_cancel_sqpoll(ctx);
6794 * Clear thread under lock so that concurrent parks work correctly
6796 complete_all(&sqd->completion);
6797 mutex_lock(&sqd->lock);
6799 mutex_unlock(&sqd->lock);
6801 complete(&sqd->exited);
6805 struct io_wait_queue {
6806 struct wait_queue_entry wq;
6807 struct io_ring_ctx *ctx;
6809 unsigned nr_timeouts;
6812 static inline bool io_should_wake(struct io_wait_queue *iowq)
6814 struct io_ring_ctx *ctx = iowq->ctx;
6817 * Wake up if we have enough events, or if a timeout occurred since we
6818 * started waiting. For timeouts, we always want to return to userspace,
6819 * regardless of event count.
6821 return io_cqring_events(ctx) >= iowq->to_wait ||
6822 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6825 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6826 int wake_flags, void *key)
6828 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6832 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6833 * the task, and the next invocation will do it.
6835 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6836 return autoremove_wake_function(curr, mode, wake_flags, key);
6840 static int io_run_task_work_sig(void)
6842 if (io_run_task_work())
6844 if (!signal_pending(current))
6846 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
6847 return -ERESTARTSYS;
6851 /* when returns >0, the caller should retry */
6852 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6853 struct io_wait_queue *iowq,
6854 signed long *timeout)
6858 /* make sure we run task_work before checking for signals */
6859 ret = io_run_task_work_sig();
6860 if (ret || io_should_wake(iowq))
6862 /* let the caller flush overflows, retry */
6863 if (test_bit(0, &ctx->cq_check_overflow))
6866 *timeout = schedule_timeout(*timeout);
6867 return !*timeout ? -ETIME : 1;
6871 * Wait until events become available, if we don't already have some. The
6872 * application must reap them itself, as they reside on the shared cq ring.
6874 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6875 const sigset_t __user *sig, size_t sigsz,
6876 struct __kernel_timespec __user *uts)
6878 struct io_wait_queue iowq = {
6881 .func = io_wake_function,
6882 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6885 .to_wait = min_events,
6887 struct io_rings *rings = ctx->rings;
6888 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6892 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6893 if (io_cqring_events(ctx) >= min_events)
6895 if (!io_run_task_work())
6900 #ifdef CONFIG_COMPAT
6901 if (in_compat_syscall())
6902 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6906 ret = set_user_sigmask(sig, sigsz);
6913 struct timespec64 ts;
6915 if (get_timespec64(&ts, uts))
6917 timeout = timespec64_to_jiffies(&ts);
6920 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6921 trace_io_uring_cqring_wait(ctx, min_events);
6923 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6924 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6925 TASK_INTERRUPTIBLE);
6926 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
6927 finish_wait(&ctx->wait, &iowq.wq);
6930 restore_saved_sigmask_unless(ret == -EINTR);
6932 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6935 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6937 #if defined(CONFIG_UNIX)
6938 if (ctx->ring_sock) {
6939 struct sock *sock = ctx->ring_sock->sk;
6940 struct sk_buff *skb;
6942 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6948 for (i = 0; i < ctx->nr_user_files; i++) {
6951 file = io_file_from_index(ctx, i);
6958 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
6960 struct fixed_rsrc_data *data;
6962 data = container_of(ref, struct fixed_rsrc_data, refs);
6963 complete(&data->done);
6966 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
6968 spin_lock_bh(&ctx->rsrc_ref_lock);
6971 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
6973 spin_unlock_bh(&ctx->rsrc_ref_lock);
6976 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
6977 struct fixed_rsrc_data *rsrc_data,
6978 struct fixed_rsrc_ref_node *ref_node)
6980 io_rsrc_ref_lock(ctx);
6981 rsrc_data->node = ref_node;
6982 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
6983 io_rsrc_ref_unlock(ctx);
6984 percpu_ref_get(&rsrc_data->refs);
6987 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
6989 struct fixed_rsrc_ref_node *ref_node = NULL;
6991 io_rsrc_ref_lock(ctx);
6992 ref_node = data->node;
6994 io_rsrc_ref_unlock(ctx);
6996 percpu_ref_kill(&ref_node->refs);
6999 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
7000 struct io_ring_ctx *ctx,
7001 void (*rsrc_put)(struct io_ring_ctx *ctx,
7002 struct io_rsrc_put *prsrc))
7004 struct fixed_rsrc_ref_node *backup_node;
7010 data->quiesce = true;
7013 backup_node = alloc_fixed_rsrc_ref_node(ctx);
7016 backup_node->rsrc_data = data;
7017 backup_node->rsrc_put = rsrc_put;
7019 io_sqe_rsrc_kill_node(ctx, data);
7020 percpu_ref_kill(&data->refs);
7021 flush_delayed_work(&ctx->rsrc_put_work);
7023 ret = wait_for_completion_interruptible(&data->done);
7024 if (!ret || !io_refs_resurrect(&data->refs, &data->done))
7027 io_sqe_rsrc_set_node(ctx, data, backup_node);
7029 mutex_unlock(&ctx->uring_lock);
7030 ret = io_run_task_work_sig();
7031 mutex_lock(&ctx->uring_lock);
7033 data->quiesce = false;
7036 destroy_fixed_rsrc_ref_node(backup_node);
7040 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7042 struct fixed_rsrc_data *data;
7044 data = kzalloc(sizeof(*data), GFP_KERNEL);
7048 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7049 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7054 init_completion(&data->done);
7058 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7060 percpu_ref_exit(&data->refs);
7065 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7067 struct fixed_rsrc_data *data = ctx->file_data;
7068 unsigned nr_tables, i;
7072 * percpu_ref_is_dying() is to stop parallel files unregister
7073 * Since we possibly drop uring lock later in this function to
7076 if (!data || percpu_ref_is_dying(&data->refs))
7078 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7082 __io_sqe_files_unregister(ctx);
7083 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7084 for (i = 0; i < nr_tables; i++)
7085 kfree(data->table[i].files);
7086 free_fixed_rsrc_data(data);
7087 ctx->file_data = NULL;
7088 ctx->nr_user_files = 0;
7092 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7093 __releases(&sqd->lock)
7097 if (sqd->thread == current)
7099 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7100 wake_up_state(sqd->thread, TASK_PARKED);
7101 mutex_unlock(&sqd->lock);
7104 static bool io_sq_thread_park(struct io_sq_data *sqd)
7105 __acquires(&sqd->lock)
7107 if (sqd->thread == current)
7109 mutex_lock(&sqd->lock);
7111 mutex_unlock(&sqd->lock);
7114 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7115 wake_up_process(sqd->thread);
7116 wait_for_completion(&sqd->completion);
7120 static void io_sq_thread_stop(struct io_sq_data *sqd)
7125 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7126 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state));
7127 wake_up_process(sqd->thread);
7128 wait_for_completion(&sqd->exited);
7131 static void io_put_sq_data(struct io_sq_data *sqd)
7133 if (refcount_dec_and_test(&sqd->refs)) {
7134 io_sq_thread_stop(sqd);
7139 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7141 struct io_sq_data *sqd = ctx->sq_data;
7145 wait_for_completion(&ctx->sq_thread_comp);
7146 io_sq_thread_park(sqd);
7149 mutex_lock(&sqd->ctx_lock);
7150 list_del(&ctx->sqd_list);
7151 io_sqd_update_thread_idle(sqd);
7152 mutex_unlock(&sqd->ctx_lock);
7155 io_sq_thread_unpark(sqd);
7157 io_put_sq_data(sqd);
7158 ctx->sq_data = NULL;
7162 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7164 struct io_ring_ctx *ctx_attach;
7165 struct io_sq_data *sqd;
7168 f = fdget(p->wq_fd);
7170 return ERR_PTR(-ENXIO);
7171 if (f.file->f_op != &io_uring_fops) {
7173 return ERR_PTR(-EINVAL);
7176 ctx_attach = f.file->private_data;
7177 sqd = ctx_attach->sq_data;
7180 return ERR_PTR(-EINVAL);
7183 refcount_inc(&sqd->refs);
7188 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7190 struct io_sq_data *sqd;
7192 if (p->flags & IORING_SETUP_ATTACH_WQ)
7193 return io_attach_sq_data(p);
7195 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7197 return ERR_PTR(-ENOMEM);
7199 refcount_set(&sqd->refs, 1);
7200 INIT_LIST_HEAD(&sqd->ctx_list);
7201 INIT_LIST_HEAD(&sqd->ctx_new_list);
7202 mutex_init(&sqd->ctx_lock);
7203 mutex_init(&sqd->lock);
7204 init_waitqueue_head(&sqd->wait);
7205 init_completion(&sqd->startup);
7206 init_completion(&sqd->completion);
7207 init_completion(&sqd->exited);
7211 #if defined(CONFIG_UNIX)
7213 * Ensure the UNIX gc is aware of our file set, so we are certain that
7214 * the io_uring can be safely unregistered on process exit, even if we have
7215 * loops in the file referencing.
7217 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7219 struct sock *sk = ctx->ring_sock->sk;
7220 struct scm_fp_list *fpl;
7221 struct sk_buff *skb;
7224 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7228 skb = alloc_skb(0, GFP_KERNEL);
7237 fpl->user = get_uid(current_user());
7238 for (i = 0; i < nr; i++) {
7239 struct file *file = io_file_from_index(ctx, i + offset);
7243 fpl->fp[nr_files] = get_file(file);
7244 unix_inflight(fpl->user, fpl->fp[nr_files]);
7249 fpl->max = SCM_MAX_FD;
7250 fpl->count = nr_files;
7251 UNIXCB(skb).fp = fpl;
7252 skb->destructor = unix_destruct_scm;
7253 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7254 skb_queue_head(&sk->sk_receive_queue, skb);
7256 for (i = 0; i < nr_files; i++)
7267 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7268 * causes regular reference counting to break down. We rely on the UNIX
7269 * garbage collection to take care of this problem for us.
7271 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7273 unsigned left, total;
7277 left = ctx->nr_user_files;
7279 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7281 ret = __io_sqe_files_scm(ctx, this_files, total);
7285 total += this_files;
7291 while (total < ctx->nr_user_files) {
7292 struct file *file = io_file_from_index(ctx, total);
7302 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7308 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7309 unsigned nr_tables, unsigned nr_files)
7313 for (i = 0; i < nr_tables; i++) {
7314 struct fixed_rsrc_table *table = &file_data->table[i];
7315 unsigned this_files;
7317 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7318 table->files = kcalloc(this_files, sizeof(struct file *),
7322 nr_files -= this_files;
7328 for (i = 0; i < nr_tables; i++) {
7329 struct fixed_rsrc_table *table = &file_data->table[i];
7330 kfree(table->files);
7335 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7337 struct file *file = prsrc->file;
7338 #if defined(CONFIG_UNIX)
7339 struct sock *sock = ctx->ring_sock->sk;
7340 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7341 struct sk_buff *skb;
7344 __skb_queue_head_init(&list);
7347 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7348 * remove this entry and rearrange the file array.
7350 skb = skb_dequeue(head);
7352 struct scm_fp_list *fp;
7354 fp = UNIXCB(skb).fp;
7355 for (i = 0; i < fp->count; i++) {
7358 if (fp->fp[i] != file)
7361 unix_notinflight(fp->user, fp->fp[i]);
7362 left = fp->count - 1 - i;
7364 memmove(&fp->fp[i], &fp->fp[i + 1],
7365 left * sizeof(struct file *));
7372 __skb_queue_tail(&list, skb);
7382 __skb_queue_tail(&list, skb);
7384 skb = skb_dequeue(head);
7387 if (skb_peek(&list)) {
7388 spin_lock_irq(&head->lock);
7389 while ((skb = __skb_dequeue(&list)) != NULL)
7390 __skb_queue_tail(head, skb);
7391 spin_unlock_irq(&head->lock);
7398 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7400 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7401 struct io_ring_ctx *ctx = rsrc_data->ctx;
7402 struct io_rsrc_put *prsrc, *tmp;
7404 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7405 list_del(&prsrc->list);
7406 ref_node->rsrc_put(ctx, prsrc);
7410 percpu_ref_exit(&ref_node->refs);
7412 percpu_ref_put(&rsrc_data->refs);
7415 static void io_rsrc_put_work(struct work_struct *work)
7417 struct io_ring_ctx *ctx;
7418 struct llist_node *node;
7420 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7421 node = llist_del_all(&ctx->rsrc_put_llist);
7424 struct fixed_rsrc_ref_node *ref_node;
7425 struct llist_node *next = node->next;
7427 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7428 __io_rsrc_put_work(ref_node);
7433 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7436 struct fixed_rsrc_table *table;
7438 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7439 return &table->files[i & IORING_FILE_TABLE_MASK];
7442 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7444 struct fixed_rsrc_ref_node *ref_node;
7445 struct fixed_rsrc_data *data;
7446 struct io_ring_ctx *ctx;
7447 bool first_add = false;
7450 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7451 data = ref_node->rsrc_data;
7454 io_rsrc_ref_lock(ctx);
7455 ref_node->done = true;
7457 while (!list_empty(&ctx->rsrc_ref_list)) {
7458 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7459 struct fixed_rsrc_ref_node, node);
7460 /* recycle ref nodes in order */
7461 if (!ref_node->done)
7463 list_del(&ref_node->node);
7464 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7466 io_rsrc_ref_unlock(ctx);
7468 if (percpu_ref_is_dying(&data->refs))
7472 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7474 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7477 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7478 struct io_ring_ctx *ctx)
7480 struct fixed_rsrc_ref_node *ref_node;
7482 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7486 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7491 INIT_LIST_HEAD(&ref_node->node);
7492 INIT_LIST_HEAD(&ref_node->rsrc_list);
7493 ref_node->done = false;
7497 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7498 struct fixed_rsrc_ref_node *ref_node)
7500 ref_node->rsrc_data = ctx->file_data;
7501 ref_node->rsrc_put = io_ring_file_put;
7504 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7506 percpu_ref_exit(&ref_node->refs);
7511 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7514 __s32 __user *fds = (__s32 __user *) arg;
7515 unsigned nr_tables, i;
7517 int fd, ret = -ENOMEM;
7518 struct fixed_rsrc_ref_node *ref_node;
7519 struct fixed_rsrc_data *file_data;
7525 if (nr_args > IORING_MAX_FIXED_FILES)
7528 file_data = alloc_fixed_rsrc_data(ctx);
7531 ctx->file_data = file_data;
7533 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7534 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7536 if (!file_data->table)
7539 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7542 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7543 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7547 /* allow sparse sets */
7557 * Don't allow io_uring instances to be registered. If UNIX
7558 * isn't enabled, then this causes a reference cycle and this
7559 * instance can never get freed. If UNIX is enabled we'll
7560 * handle it just fine, but there's still no point in allowing
7561 * a ring fd as it doesn't support regular read/write anyway.
7563 if (file->f_op == &io_uring_fops) {
7567 *io_fixed_file_slot(file_data, i) = file;
7570 ret = io_sqe_files_scm(ctx);
7572 io_sqe_files_unregister(ctx);
7576 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7578 io_sqe_files_unregister(ctx);
7581 init_fixed_file_ref_node(ctx, ref_node);
7583 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7586 for (i = 0; i < ctx->nr_user_files; i++) {
7587 file = io_file_from_index(ctx, i);
7591 for (i = 0; i < nr_tables; i++)
7592 kfree(file_data->table[i].files);
7593 ctx->nr_user_files = 0;
7595 free_fixed_rsrc_data(ctx->file_data);
7596 ctx->file_data = NULL;
7600 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7603 #if defined(CONFIG_UNIX)
7604 struct sock *sock = ctx->ring_sock->sk;
7605 struct sk_buff_head *head = &sock->sk_receive_queue;
7606 struct sk_buff *skb;
7609 * See if we can merge this file into an existing skb SCM_RIGHTS
7610 * file set. If there's no room, fall back to allocating a new skb
7611 * and filling it in.
7613 spin_lock_irq(&head->lock);
7614 skb = skb_peek(head);
7616 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7618 if (fpl->count < SCM_MAX_FD) {
7619 __skb_unlink(skb, head);
7620 spin_unlock_irq(&head->lock);
7621 fpl->fp[fpl->count] = get_file(file);
7622 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7624 spin_lock_irq(&head->lock);
7625 __skb_queue_head(head, skb);
7630 spin_unlock_irq(&head->lock);
7637 return __io_sqe_files_scm(ctx, 1, index);
7643 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7645 struct io_rsrc_put *prsrc;
7646 struct fixed_rsrc_ref_node *ref_node = data->node;
7648 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7653 list_add(&prsrc->list, &ref_node->rsrc_list);
7658 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7661 return io_queue_rsrc_removal(data, (void *)file);
7664 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7665 struct io_uring_rsrc_update *up,
7668 struct fixed_rsrc_data *data = ctx->file_data;
7669 struct fixed_rsrc_ref_node *ref_node;
7670 struct file *file, **file_slot;
7674 bool needs_switch = false;
7676 if (check_add_overflow(up->offset, nr_args, &done))
7678 if (done > ctx->nr_user_files)
7681 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7684 init_fixed_file_ref_node(ctx, ref_node);
7686 fds = u64_to_user_ptr(up->data);
7687 for (done = 0; done < nr_args; done++) {
7689 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7693 if (fd == IORING_REGISTER_FILES_SKIP)
7696 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7697 file_slot = io_fixed_file_slot(ctx->file_data, i);
7700 err = io_queue_file_removal(data, *file_slot);
7704 needs_switch = true;
7713 * Don't allow io_uring instances to be registered. If
7714 * UNIX isn't enabled, then this causes a reference
7715 * cycle and this instance can never get freed. If UNIX
7716 * is enabled we'll handle it just fine, but there's
7717 * still no point in allowing a ring fd as it doesn't
7718 * support regular read/write anyway.
7720 if (file->f_op == &io_uring_fops) {
7726 err = io_sqe_file_register(ctx, file, i);
7736 percpu_ref_kill(&data->node->refs);
7737 io_sqe_rsrc_set_node(ctx, data, ref_node);
7739 destroy_fixed_rsrc_ref_node(ref_node);
7741 return done ? done : err;
7744 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7747 struct io_uring_rsrc_update up;
7749 if (!ctx->file_data)
7753 if (copy_from_user(&up, arg, sizeof(up)))
7758 return __io_sqe_files_update(ctx, &up, nr_args);
7761 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7763 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7765 req = io_put_req_find_next(req);
7766 return req ? &req->work : NULL;
7769 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx)
7771 struct io_wq_hash *hash;
7772 struct io_wq_data data;
7773 unsigned int concurrency;
7775 hash = ctx->hash_map;
7777 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7779 return ERR_PTR(-ENOMEM);
7780 refcount_set(&hash->refs, 1);
7781 init_waitqueue_head(&hash->wait);
7782 ctx->hash_map = hash;
7786 data.free_work = io_free_work;
7787 data.do_work = io_wq_submit_work;
7789 /* Do QD, or 4 * CPUS, whatever is smallest */
7790 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7792 return io_wq_create(concurrency, &data);
7795 static int io_uring_alloc_task_context(struct task_struct *task,
7796 struct io_ring_ctx *ctx)
7798 struct io_uring_task *tctx;
7801 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7802 if (unlikely(!tctx))
7805 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7806 if (unlikely(ret)) {
7811 tctx->io_wq = io_init_wq_offload(ctx);
7812 if (IS_ERR(tctx->io_wq)) {
7813 ret = PTR_ERR(tctx->io_wq);
7814 percpu_counter_destroy(&tctx->inflight);
7820 init_waitqueue_head(&tctx->wait);
7822 atomic_set(&tctx->in_idle, 0);
7823 tctx->sqpoll = false;
7824 task->io_uring = tctx;
7825 spin_lock_init(&tctx->task_lock);
7826 INIT_WQ_LIST(&tctx->task_list);
7827 tctx->task_state = 0;
7828 init_task_work(&tctx->task_work, tctx_task_work);
7832 void __io_uring_free(struct task_struct *tsk)
7834 struct io_uring_task *tctx = tsk->io_uring;
7836 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7837 percpu_counter_destroy(&tctx->inflight);
7839 tsk->io_uring = NULL;
7842 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7843 struct io_uring_params *p)
7847 /* Retain compatibility with failing for an invalid attach attempt */
7848 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7849 IORING_SETUP_ATTACH_WQ) {
7852 f = fdget(p->wq_fd);
7855 if (f.file->f_op != &io_uring_fops) {
7861 if (ctx->flags & IORING_SETUP_SQPOLL) {
7862 struct io_sq_data *sqd;
7865 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
7868 sqd = io_get_sq_data(p);
7875 io_sq_thread_park(sqd);
7876 mutex_lock(&sqd->ctx_lock);
7877 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7878 mutex_unlock(&sqd->ctx_lock);
7879 io_sq_thread_unpark(sqd);
7881 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7882 if (!ctx->sq_thread_idle)
7883 ctx->sq_thread_idle = HZ;
7888 if (p->flags & IORING_SETUP_SQ_AFF) {
7889 int cpu = p->sq_thread_cpu;
7892 if (cpu >= nr_cpu_ids)
7894 if (!cpu_online(cpu))
7902 sqd->task_pid = current->pid;
7903 current->flags |= PF_IO_WORKER;
7904 ret = io_wq_fork_thread(io_sq_thread, sqd);
7905 current->flags &= ~PF_IO_WORKER;
7910 wait_for_completion(&sqd->completion);
7911 ret = io_uring_alloc_task_context(sqd->thread, ctx);
7914 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7915 /* Can't have SQ_AFF without SQPOLL */
7922 io_sq_thread_finish(ctx);
7926 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7928 struct io_sq_data *sqd = ctx->sq_data;
7930 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
7931 complete(&sqd->startup);
7934 static inline void __io_unaccount_mem(struct user_struct *user,
7935 unsigned long nr_pages)
7937 atomic_long_sub(nr_pages, &user->locked_vm);
7940 static inline int __io_account_mem(struct user_struct *user,
7941 unsigned long nr_pages)
7943 unsigned long page_limit, cur_pages, new_pages;
7945 /* Don't allow more pages than we can safely lock */
7946 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7949 cur_pages = atomic_long_read(&user->locked_vm);
7950 new_pages = cur_pages + nr_pages;
7951 if (new_pages > page_limit)
7953 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7954 new_pages) != cur_pages);
7959 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7962 __io_unaccount_mem(ctx->user, nr_pages);
7964 if (ctx->mm_account)
7965 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
7968 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7973 ret = __io_account_mem(ctx->user, nr_pages);
7978 if (ctx->mm_account)
7979 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
7984 static void io_mem_free(void *ptr)
7991 page = virt_to_head_page(ptr);
7992 if (put_page_testzero(page))
7993 free_compound_page(page);
7996 static void *io_mem_alloc(size_t size)
7998 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7999 __GFP_NORETRY | __GFP_ACCOUNT;
8001 return (void *) __get_free_pages(gfp_flags, get_order(size));
8004 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8007 struct io_rings *rings;
8008 size_t off, sq_array_size;
8010 off = struct_size(rings, cqes, cq_entries);
8011 if (off == SIZE_MAX)
8015 off = ALIGN(off, SMP_CACHE_BYTES);
8023 sq_array_size = array_size(sizeof(u32), sq_entries);
8024 if (sq_array_size == SIZE_MAX)
8027 if (check_add_overflow(off, sq_array_size, &off))
8033 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8037 if (!ctx->user_bufs)
8040 for (i = 0; i < ctx->nr_user_bufs; i++) {
8041 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8043 for (j = 0; j < imu->nr_bvecs; j++)
8044 unpin_user_page(imu->bvec[j].bv_page);
8046 if (imu->acct_pages)
8047 io_unaccount_mem(ctx, imu->acct_pages);
8052 kfree(ctx->user_bufs);
8053 ctx->user_bufs = NULL;
8054 ctx->nr_user_bufs = 0;
8058 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8059 void __user *arg, unsigned index)
8061 struct iovec __user *src;
8063 #ifdef CONFIG_COMPAT
8065 struct compat_iovec __user *ciovs;
8066 struct compat_iovec ciov;
8068 ciovs = (struct compat_iovec __user *) arg;
8069 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8072 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8073 dst->iov_len = ciov.iov_len;
8077 src = (struct iovec __user *) arg;
8078 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8084 * Not super efficient, but this is just a registration time. And we do cache
8085 * the last compound head, so generally we'll only do a full search if we don't
8088 * We check if the given compound head page has already been accounted, to
8089 * avoid double accounting it. This allows us to account the full size of the
8090 * page, not just the constituent pages of a huge page.
8092 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8093 int nr_pages, struct page *hpage)
8097 /* check current page array */
8098 for (i = 0; i < nr_pages; i++) {
8099 if (!PageCompound(pages[i]))
8101 if (compound_head(pages[i]) == hpage)
8105 /* check previously registered pages */
8106 for (i = 0; i < ctx->nr_user_bufs; i++) {
8107 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8109 for (j = 0; j < imu->nr_bvecs; j++) {
8110 if (!PageCompound(imu->bvec[j].bv_page))
8112 if (compound_head(imu->bvec[j].bv_page) == hpage)
8120 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8121 int nr_pages, struct io_mapped_ubuf *imu,
8122 struct page **last_hpage)
8126 for (i = 0; i < nr_pages; i++) {
8127 if (!PageCompound(pages[i])) {
8132 hpage = compound_head(pages[i]);
8133 if (hpage == *last_hpage)
8135 *last_hpage = hpage;
8136 if (headpage_already_acct(ctx, pages, i, hpage))
8138 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8142 if (!imu->acct_pages)
8145 ret = io_account_mem(ctx, imu->acct_pages);
8147 imu->acct_pages = 0;
8151 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8152 struct io_mapped_ubuf *imu,
8153 struct page **last_hpage)
8155 struct vm_area_struct **vmas = NULL;
8156 struct page **pages = NULL;
8157 unsigned long off, start, end, ubuf;
8159 int ret, pret, nr_pages, i;
8161 ubuf = (unsigned long) iov->iov_base;
8162 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8163 start = ubuf >> PAGE_SHIFT;
8164 nr_pages = end - start;
8168 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8172 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8177 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8183 mmap_read_lock(current->mm);
8184 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8186 if (pret == nr_pages) {
8187 /* don't support file backed memory */
8188 for (i = 0; i < nr_pages; i++) {
8189 struct vm_area_struct *vma = vmas[i];
8192 !is_file_hugepages(vma->vm_file)) {
8198 ret = pret < 0 ? pret : -EFAULT;
8200 mmap_read_unlock(current->mm);
8203 * if we did partial map, or found file backed vmas,
8204 * release any pages we did get
8207 unpin_user_pages(pages, pret);
8212 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8214 unpin_user_pages(pages, pret);
8219 off = ubuf & ~PAGE_MASK;
8220 size = iov->iov_len;
8221 for (i = 0; i < nr_pages; i++) {
8224 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8225 imu->bvec[i].bv_page = pages[i];
8226 imu->bvec[i].bv_len = vec_len;
8227 imu->bvec[i].bv_offset = off;
8231 /* store original address for later verification */
8233 imu->len = iov->iov_len;
8234 imu->nr_bvecs = nr_pages;
8242 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8246 if (!nr_args || nr_args > UIO_MAXIOV)
8249 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8251 if (!ctx->user_bufs)
8257 static int io_buffer_validate(struct iovec *iov)
8260 * Don't impose further limits on the size and buffer
8261 * constraints here, we'll -EINVAL later when IO is
8262 * submitted if they are wrong.
8264 if (!iov->iov_base || !iov->iov_len)
8267 /* arbitrary limit, but we need something */
8268 if (iov->iov_len > SZ_1G)
8274 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8275 unsigned int nr_args)
8279 struct page *last_hpage = NULL;
8281 ret = io_buffers_map_alloc(ctx, nr_args);
8285 for (i = 0; i < nr_args; i++) {
8286 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8288 ret = io_copy_iov(ctx, &iov, arg, i);
8292 ret = io_buffer_validate(&iov);
8296 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8300 ctx->nr_user_bufs++;
8304 io_sqe_buffers_unregister(ctx);
8309 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8311 __s32 __user *fds = arg;
8317 if (copy_from_user(&fd, fds, sizeof(*fds)))
8320 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8321 if (IS_ERR(ctx->cq_ev_fd)) {
8322 int ret = PTR_ERR(ctx->cq_ev_fd);
8323 ctx->cq_ev_fd = NULL;
8330 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8332 if (ctx->cq_ev_fd) {
8333 eventfd_ctx_put(ctx->cq_ev_fd);
8334 ctx->cq_ev_fd = NULL;
8341 static int __io_destroy_buffers(int id, void *p, void *data)
8343 struct io_ring_ctx *ctx = data;
8344 struct io_buffer *buf = p;
8346 __io_remove_buffers(ctx, buf, id, -1U);
8350 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8352 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8353 idr_destroy(&ctx->io_buffer_idr);
8356 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8358 struct io_kiocb *req, *nxt;
8360 list_for_each_entry_safe(req, nxt, list, compl.list) {
8361 if (tsk && req->task != tsk)
8363 list_del(&req->compl.list);
8364 kmem_cache_free(req_cachep, req);
8368 static void io_req_caches_free(struct io_ring_ctx *ctx, struct task_struct *tsk)
8370 struct io_submit_state *submit_state = &ctx->submit_state;
8372 mutex_lock(&ctx->uring_lock);
8374 if (submit_state->free_reqs)
8375 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8376 submit_state->reqs);
8378 io_req_cache_free(&submit_state->comp.free_list, NULL);
8380 spin_lock_irq(&ctx->completion_lock);
8381 io_req_cache_free(&submit_state->comp.locked_free_list, NULL);
8382 spin_unlock_irq(&ctx->completion_lock);
8384 mutex_unlock(&ctx->uring_lock);
8387 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8390 * Some may use context even when all refs and requests have been put,
8391 * and they are free to do so while still holding uring_lock, see
8392 * __io_req_task_submit(). Wait for them to finish.
8394 mutex_lock(&ctx->uring_lock);
8395 mutex_unlock(&ctx->uring_lock);
8397 io_sq_thread_finish(ctx);
8398 io_sqe_buffers_unregister(ctx);
8400 if (ctx->mm_account) {
8401 mmdrop(ctx->mm_account);
8402 ctx->mm_account = NULL;
8405 mutex_lock(&ctx->uring_lock);
8406 io_sqe_files_unregister(ctx);
8407 mutex_unlock(&ctx->uring_lock);
8408 io_eventfd_unregister(ctx);
8409 io_destroy_buffers(ctx);
8410 idr_destroy(&ctx->personality_idr);
8412 #if defined(CONFIG_UNIX)
8413 if (ctx->ring_sock) {
8414 ctx->ring_sock->file = NULL; /* so that iput() is called */
8415 sock_release(ctx->ring_sock);
8419 io_mem_free(ctx->rings);
8420 io_mem_free(ctx->sq_sqes);
8422 percpu_ref_exit(&ctx->refs);
8423 free_uid(ctx->user);
8424 io_req_caches_free(ctx, NULL);
8426 io_wq_put_hash(ctx->hash_map);
8427 kfree(ctx->cancel_hash);
8431 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8433 struct io_ring_ctx *ctx = file->private_data;
8436 poll_wait(file, &ctx->cq_wait, wait);
8438 * synchronizes with barrier from wq_has_sleeper call in
8442 if (!io_sqring_full(ctx))
8443 mask |= EPOLLOUT | EPOLLWRNORM;
8446 * Don't flush cqring overflow list here, just do a simple check.
8447 * Otherwise there could possible be ABBA deadlock:
8450 * lock(&ctx->uring_lock);
8452 * lock(&ctx->uring_lock);
8455 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8456 * pushs them to do the flush.
8458 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8459 mask |= EPOLLIN | EPOLLRDNORM;
8464 static int io_uring_fasync(int fd, struct file *file, int on)
8466 struct io_ring_ctx *ctx = file->private_data;
8468 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8471 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8473 const struct cred *creds;
8475 creds = idr_remove(&ctx->personality_idr, id);
8484 static int io_remove_personalities(int id, void *p, void *data)
8486 struct io_ring_ctx *ctx = data;
8488 io_unregister_personality(ctx, id);
8492 static void io_run_ctx_fallback(struct io_ring_ctx *ctx)
8494 struct callback_head *work, *head, *next;
8499 work = READ_ONCE(ctx->exit_task_work);
8500 } while (cmpxchg(&ctx->exit_task_work, work, head) != work);
8514 static void io_ring_exit_work(struct work_struct *work)
8516 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8520 * If we're doing polled IO and end up having requests being
8521 * submitted async (out-of-line), then completions can come in while
8522 * we're waiting for refs to drop. We need to reap these manually,
8523 * as nobody else will be looking for them.
8526 io_uring_try_cancel_requests(ctx, NULL, NULL);
8527 io_run_ctx_fallback(ctx);
8528 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8529 io_ring_ctx_free(ctx);
8532 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8534 mutex_lock(&ctx->uring_lock);
8535 percpu_ref_kill(&ctx->refs);
8537 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8540 /* if force is set, the ring is going away. always drop after that */
8541 ctx->cq_overflow_flushed = 1;
8543 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8544 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8545 mutex_unlock(&ctx->uring_lock);
8547 io_kill_timeouts(ctx, NULL, NULL);
8548 io_poll_remove_all(ctx, NULL, NULL);
8550 /* if we failed setting up the ctx, we might not have any rings */
8551 io_iopoll_try_reap_events(ctx);
8553 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8555 * Use system_unbound_wq to avoid spawning tons of event kworkers
8556 * if we're exiting a ton of rings at the same time. It just adds
8557 * noise and overhead, there's no discernable change in runtime
8558 * over using system_wq.
8560 queue_work(system_unbound_wq, &ctx->exit_work);
8563 static int io_uring_release(struct inode *inode, struct file *file)
8565 struct io_ring_ctx *ctx = file->private_data;
8567 file->private_data = NULL;
8568 io_ring_ctx_wait_and_kill(ctx);
8572 struct io_task_cancel {
8573 struct task_struct *task;
8574 struct files_struct *files;
8577 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8579 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8580 struct io_task_cancel *cancel = data;
8583 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8584 unsigned long flags;
8585 struct io_ring_ctx *ctx = req->ctx;
8587 /* protect against races with linked timeouts */
8588 spin_lock_irqsave(&ctx->completion_lock, flags);
8589 ret = io_match_task(req, cancel->task, cancel->files);
8590 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8592 ret = io_match_task(req, cancel->task, cancel->files);
8597 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8598 struct task_struct *task,
8599 struct files_struct *files)
8601 struct io_defer_entry *de = NULL;
8604 spin_lock_irq(&ctx->completion_lock);
8605 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8606 if (io_match_task(de->req, task, files)) {
8607 list_cut_position(&list, &ctx->defer_list, &de->list);
8611 spin_unlock_irq(&ctx->completion_lock);
8613 while (!list_empty(&list)) {
8614 de = list_first_entry(&list, struct io_defer_entry, list);
8615 list_del_init(&de->list);
8616 req_set_fail_links(de->req);
8617 io_put_req(de->req);
8618 io_req_complete(de->req, -ECANCELED);
8623 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8624 struct task_struct *task,
8625 struct files_struct *files)
8627 struct io_task_cancel cancel = { .task = task, .files = files, };
8628 struct io_uring_task *tctx = current->io_uring;
8631 enum io_wq_cancel cret;
8634 if (tctx && tctx->io_wq) {
8635 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8637 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8640 /* SQPOLL thread does its own polling */
8641 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8642 while (!list_empty_careful(&ctx->iopoll_list)) {
8643 io_iopoll_try_reap_events(ctx);
8648 ret |= io_poll_remove_all(ctx, task, files);
8649 ret |= io_kill_timeouts(ctx, task, files);
8650 ret |= io_run_task_work();
8651 io_cqring_overflow_flush(ctx, true, task, files);
8658 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8659 struct task_struct *task,
8660 struct files_struct *files)
8662 struct io_kiocb *req;
8665 spin_lock_irq(&ctx->inflight_lock);
8666 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8667 cnt += io_match_task(req, task, files);
8668 spin_unlock_irq(&ctx->inflight_lock);
8672 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8673 struct task_struct *task,
8674 struct files_struct *files)
8676 while (!list_empty_careful(&ctx->inflight_list)) {
8680 inflight = io_uring_count_inflight(ctx, task, files);
8684 io_uring_try_cancel_requests(ctx, task, files);
8687 io_sq_thread_unpark(ctx->sq_data);
8688 prepare_to_wait(&task->io_uring->wait, &wait,
8689 TASK_UNINTERRUPTIBLE);
8690 if (inflight == io_uring_count_inflight(ctx, task, files))
8692 finish_wait(&task->io_uring->wait, &wait);
8694 io_sq_thread_park(ctx->sq_data);
8698 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
8700 mutex_lock(&ctx->uring_lock);
8702 mutex_unlock(&ctx->uring_lock);
8704 /* make sure callers enter the ring to get error */
8706 io_ring_set_wakeup_flag(ctx);
8710 * We need to iteratively cancel requests, in case a request has dependent
8711 * hard links. These persist even for failure of cancelations, hence keep
8712 * looping until none are found.
8714 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8715 struct files_struct *files)
8717 struct task_struct *task = current;
8718 bool did_park = false;
8720 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8721 io_disable_sqo_submit(ctx);
8722 did_park = io_sq_thread_park(ctx->sq_data);
8724 task = ctx->sq_data->thread;
8725 atomic_inc(&task->io_uring->in_idle);
8729 io_cancel_defer_files(ctx, task, files);
8731 io_uring_cancel_files(ctx, task, files);
8733 io_uring_try_cancel_requests(ctx, task, NULL);
8736 atomic_dec(&task->io_uring->in_idle);
8737 io_sq_thread_unpark(ctx->sq_data);
8742 * Note that this task has used io_uring. We use it for cancelation purposes.
8744 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8746 struct io_uring_task *tctx = current->io_uring;
8749 if (unlikely(!tctx)) {
8750 ret = io_uring_alloc_task_context(current, ctx);
8753 tctx = current->io_uring;
8755 if (tctx->last != file) {
8756 void *old = xa_load(&tctx->xa, (unsigned long)file);
8760 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8767 /* one and only SQPOLL file note, held by sqo_task */
8768 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
8769 current != ctx->sqo_task);
8775 * This is race safe in that the task itself is doing this, hence it
8776 * cannot be going through the exit/cancel paths at the same time.
8777 * This cannot be modified while exit/cancel is running.
8779 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8780 tctx->sqpoll = true;
8786 * Remove this io_uring_file -> task mapping.
8788 static void io_uring_del_task_file(struct file *file)
8790 struct io_uring_task *tctx = current->io_uring;
8792 if (tctx->last == file)
8794 file = xa_erase(&tctx->xa, (unsigned long)file);
8799 static void io_uring_remove_task_files(struct io_uring_task *tctx)
8802 unsigned long index;
8804 xa_for_each(&tctx->xa, index, file)
8805 io_uring_del_task_file(file);
8808 void __io_uring_files_cancel(struct files_struct *files)
8810 struct io_uring_task *tctx = current->io_uring;
8812 unsigned long index;
8814 /* make sure overflow events are dropped */
8815 atomic_inc(&tctx->in_idle);
8816 xa_for_each(&tctx->xa, index, file)
8817 io_uring_cancel_task_requests(file->private_data, files);
8818 atomic_dec(&tctx->in_idle);
8821 io_uring_remove_task_files(tctx);
8823 io_wq_destroy(tctx->io_wq);
8829 static s64 tctx_inflight(struct io_uring_task *tctx)
8831 return percpu_counter_sum(&tctx->inflight);
8834 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8836 struct io_sq_data *sqd = ctx->sq_data;
8837 struct io_uring_task *tctx;
8843 io_disable_sqo_submit(ctx);
8844 if (!io_sq_thread_park(sqd))
8846 tctx = ctx->sq_data->thread->io_uring;
8848 atomic_inc(&tctx->in_idle);
8850 /* read completions before cancelations */
8851 inflight = tctx_inflight(tctx);
8854 io_uring_cancel_task_requests(ctx, NULL);
8856 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8858 * If we've seen completions, retry without waiting. This
8859 * avoids a race where a completion comes in before we did
8860 * prepare_to_wait().
8862 if (inflight == tctx_inflight(tctx))
8864 finish_wait(&tctx->wait, &wait);
8866 atomic_dec(&tctx->in_idle);
8867 io_sq_thread_unpark(sqd);
8871 * Find any io_uring fd that this task has registered or done IO on, and cancel
8874 void __io_uring_task_cancel(void)
8876 struct io_uring_task *tctx = current->io_uring;
8880 /* make sure overflow events are dropped */
8881 atomic_inc(&tctx->in_idle);
8883 /* trigger io_disable_sqo_submit() */
8886 unsigned long index;
8888 xa_for_each(&tctx->xa, index, file)
8889 io_uring_cancel_sqpoll(file->private_data);
8893 /* read completions before cancelations */
8894 inflight = tctx_inflight(tctx);
8897 __io_uring_files_cancel(NULL);
8899 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8902 * If we've seen completions, retry without waiting. This
8903 * avoids a race where a completion comes in before we did
8904 * prepare_to_wait().
8906 if (inflight == tctx_inflight(tctx))
8908 finish_wait(&tctx->wait, &wait);
8911 atomic_dec(&tctx->in_idle);
8913 io_uring_remove_task_files(tctx);
8916 static int io_uring_flush(struct file *file, void *data)
8918 struct io_uring_task *tctx = current->io_uring;
8919 struct io_ring_ctx *ctx = file->private_data;
8921 /* Ignore helper thread files exit */
8922 if (current->flags & PF_IO_WORKER)
8925 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
8926 io_uring_cancel_task_requests(ctx, NULL);
8927 io_req_caches_free(ctx, current);
8930 io_run_ctx_fallback(ctx);
8935 /* we should have cancelled and erased it before PF_EXITING */
8936 WARN_ON_ONCE((current->flags & PF_EXITING) &&
8937 xa_load(&tctx->xa, (unsigned long)file));
8940 * fput() is pending, will be 2 if the only other ref is our potential
8941 * task file note. If the task is exiting, drop regardless of count.
8943 if (atomic_long_read(&file->f_count) != 2)
8946 if (ctx->flags & IORING_SETUP_SQPOLL) {
8947 /* there is only one file note, which is owned by sqo_task */
8948 WARN_ON_ONCE(ctx->sqo_task != current &&
8949 xa_load(&tctx->xa, (unsigned long)file));
8950 /* sqo_dead check is for when this happens after cancellation */
8951 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
8952 !xa_load(&tctx->xa, (unsigned long)file));
8954 io_disable_sqo_submit(ctx);
8957 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
8958 io_uring_del_task_file(file);
8962 static void *io_uring_validate_mmap_request(struct file *file,
8963 loff_t pgoff, size_t sz)
8965 struct io_ring_ctx *ctx = file->private_data;
8966 loff_t offset = pgoff << PAGE_SHIFT;
8971 case IORING_OFF_SQ_RING:
8972 case IORING_OFF_CQ_RING:
8975 case IORING_OFF_SQES:
8979 return ERR_PTR(-EINVAL);
8982 page = virt_to_head_page(ptr);
8983 if (sz > page_size(page))
8984 return ERR_PTR(-EINVAL);
8991 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8993 size_t sz = vma->vm_end - vma->vm_start;
8997 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
8999 return PTR_ERR(ptr);
9001 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9002 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9005 #else /* !CONFIG_MMU */
9007 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9009 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9012 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9014 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9017 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9018 unsigned long addr, unsigned long len,
9019 unsigned long pgoff, unsigned long flags)
9023 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9025 return PTR_ERR(ptr);
9027 return (unsigned long) ptr;
9030 #endif /* !CONFIG_MMU */
9032 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9038 if (!io_sqring_full(ctx))
9041 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9043 if (unlikely(ctx->sqo_dead)) {
9048 if (!io_sqring_full(ctx))
9052 } while (!signal_pending(current));
9054 finish_wait(&ctx->sqo_sq_wait, &wait);
9059 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9060 struct __kernel_timespec __user **ts,
9061 const sigset_t __user **sig)
9063 struct io_uring_getevents_arg arg;
9066 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9067 * is just a pointer to the sigset_t.
9069 if (!(flags & IORING_ENTER_EXT_ARG)) {
9070 *sig = (const sigset_t __user *) argp;
9076 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9077 * timespec and sigset_t pointers if good.
9079 if (*argsz != sizeof(arg))
9081 if (copy_from_user(&arg, argp, sizeof(arg)))
9083 *sig = u64_to_user_ptr(arg.sigmask);
9084 *argsz = arg.sigmask_sz;
9085 *ts = u64_to_user_ptr(arg.ts);
9089 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9090 u32, min_complete, u32, flags, const void __user *, argp,
9093 struct io_ring_ctx *ctx;
9100 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9101 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9109 if (f.file->f_op != &io_uring_fops)
9113 ctx = f.file->private_data;
9114 if (!percpu_ref_tryget(&ctx->refs))
9118 if (ctx->flags & IORING_SETUP_R_DISABLED)
9122 * For SQ polling, the thread will do all submissions and completions.
9123 * Just return the requested submit count, and wake the thread if
9127 if (ctx->flags & IORING_SETUP_SQPOLL) {
9128 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9131 if (unlikely(ctx->sqo_dead))
9133 if (flags & IORING_ENTER_SQ_WAKEUP)
9134 wake_up(&ctx->sq_data->wait);
9135 if (flags & IORING_ENTER_SQ_WAIT) {
9136 ret = io_sqpoll_wait_sq(ctx);
9140 submitted = to_submit;
9141 } else if (to_submit) {
9142 ret = io_uring_add_task_file(ctx, f.file);
9145 mutex_lock(&ctx->uring_lock);
9146 submitted = io_submit_sqes(ctx, to_submit);
9147 mutex_unlock(&ctx->uring_lock);
9149 if (submitted != to_submit)
9152 if (flags & IORING_ENTER_GETEVENTS) {
9153 const sigset_t __user *sig;
9154 struct __kernel_timespec __user *ts;
9156 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9160 min_complete = min(min_complete, ctx->cq_entries);
9163 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9164 * space applications don't need to do io completion events
9165 * polling again, they can rely on io_sq_thread to do polling
9166 * work, which can reduce cpu usage and uring_lock contention.
9168 if (ctx->flags & IORING_SETUP_IOPOLL &&
9169 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9170 ret = io_iopoll_check(ctx, min_complete);
9172 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9177 percpu_ref_put(&ctx->refs);
9180 return submitted ? submitted : ret;
9183 #ifdef CONFIG_PROC_FS
9184 static int io_uring_show_cred(int id, void *p, void *data)
9186 const struct cred *cred = p;
9187 struct seq_file *m = data;
9188 struct user_namespace *uns = seq_user_ns(m);
9189 struct group_info *gi;
9194 seq_printf(m, "%5d\n", id);
9195 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9196 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9197 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9198 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9199 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9200 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9201 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9202 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9203 seq_puts(m, "\n\tGroups:\t");
9204 gi = cred->group_info;
9205 for (g = 0; g < gi->ngroups; g++) {
9206 seq_put_decimal_ull(m, g ? " " : "",
9207 from_kgid_munged(uns, gi->gid[g]));
9209 seq_puts(m, "\n\tCapEff:\t");
9210 cap = cred->cap_effective;
9211 CAP_FOR_EACH_U32(__capi)
9212 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9217 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9219 struct io_sq_data *sq = NULL;
9224 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9225 * since fdinfo case grabs it in the opposite direction of normal use
9226 * cases. If we fail to get the lock, we just don't iterate any
9227 * structures that could be going away outside the io_uring mutex.
9229 has_lock = mutex_trylock(&ctx->uring_lock);
9231 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9234 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9235 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9236 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9237 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9238 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9241 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9243 seq_printf(m, "%5u: <none>\n", i);
9245 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9246 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9247 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9249 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9250 (unsigned int) buf->len);
9252 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9253 seq_printf(m, "Personalities:\n");
9254 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9256 seq_printf(m, "PollList:\n");
9257 spin_lock_irq(&ctx->completion_lock);
9258 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9259 struct hlist_head *list = &ctx->cancel_hash[i];
9260 struct io_kiocb *req;
9262 hlist_for_each_entry(req, list, hash_node)
9263 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9264 req->task->task_works != NULL);
9266 spin_unlock_irq(&ctx->completion_lock);
9268 mutex_unlock(&ctx->uring_lock);
9271 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9273 struct io_ring_ctx *ctx = f->private_data;
9275 if (percpu_ref_tryget(&ctx->refs)) {
9276 __io_uring_show_fdinfo(ctx, m);
9277 percpu_ref_put(&ctx->refs);
9282 static const struct file_operations io_uring_fops = {
9283 .release = io_uring_release,
9284 .flush = io_uring_flush,
9285 .mmap = io_uring_mmap,
9287 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9288 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9290 .poll = io_uring_poll,
9291 .fasync = io_uring_fasync,
9292 #ifdef CONFIG_PROC_FS
9293 .show_fdinfo = io_uring_show_fdinfo,
9297 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9298 struct io_uring_params *p)
9300 struct io_rings *rings;
9301 size_t size, sq_array_offset;
9303 /* make sure these are sane, as we already accounted them */
9304 ctx->sq_entries = p->sq_entries;
9305 ctx->cq_entries = p->cq_entries;
9307 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9308 if (size == SIZE_MAX)
9311 rings = io_mem_alloc(size);
9316 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9317 rings->sq_ring_mask = p->sq_entries - 1;
9318 rings->cq_ring_mask = p->cq_entries - 1;
9319 rings->sq_ring_entries = p->sq_entries;
9320 rings->cq_ring_entries = p->cq_entries;
9321 ctx->sq_mask = rings->sq_ring_mask;
9322 ctx->cq_mask = rings->cq_ring_mask;
9324 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9325 if (size == SIZE_MAX) {
9326 io_mem_free(ctx->rings);
9331 ctx->sq_sqes = io_mem_alloc(size);
9332 if (!ctx->sq_sqes) {
9333 io_mem_free(ctx->rings);
9341 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9345 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9349 ret = io_uring_add_task_file(ctx, file);
9354 fd_install(fd, file);
9359 * Allocate an anonymous fd, this is what constitutes the application
9360 * visible backing of an io_uring instance. The application mmaps this
9361 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9362 * we have to tie this fd to a socket for file garbage collection purposes.
9364 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9367 #if defined(CONFIG_UNIX)
9370 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9373 return ERR_PTR(ret);
9376 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9377 O_RDWR | O_CLOEXEC);
9378 #if defined(CONFIG_UNIX)
9380 sock_release(ctx->ring_sock);
9381 ctx->ring_sock = NULL;
9383 ctx->ring_sock->file = file;
9389 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9390 struct io_uring_params __user *params)
9392 struct io_ring_ctx *ctx;
9398 if (entries > IORING_MAX_ENTRIES) {
9399 if (!(p->flags & IORING_SETUP_CLAMP))
9401 entries = IORING_MAX_ENTRIES;
9405 * Use twice as many entries for the CQ ring. It's possible for the
9406 * application to drive a higher depth than the size of the SQ ring,
9407 * since the sqes are only used at submission time. This allows for
9408 * some flexibility in overcommitting a bit. If the application has
9409 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9410 * of CQ ring entries manually.
9412 p->sq_entries = roundup_pow_of_two(entries);
9413 if (p->flags & IORING_SETUP_CQSIZE) {
9415 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9416 * to a power-of-two, if it isn't already. We do NOT impose
9417 * any cq vs sq ring sizing.
9421 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9422 if (!(p->flags & IORING_SETUP_CLAMP))
9424 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9426 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9427 if (p->cq_entries < p->sq_entries)
9430 p->cq_entries = 2 * p->sq_entries;
9433 ctx = io_ring_ctx_alloc(p);
9436 ctx->compat = in_compat_syscall();
9437 if (!capable(CAP_IPC_LOCK))
9438 ctx->user = get_uid(current_user());
9439 ctx->sqo_task = current;
9442 * This is just grabbed for accounting purposes. When a process exits,
9443 * the mm is exited and dropped before the files, hence we need to hang
9444 * on to this mm purely for the purposes of being able to unaccount
9445 * memory (locked/pinned vm). It's not used for anything else.
9447 mmgrab(current->mm);
9448 ctx->mm_account = current->mm;
9450 ret = io_allocate_scq_urings(ctx, p);
9454 ret = io_sq_offload_create(ctx, p);
9458 if (!(p->flags & IORING_SETUP_R_DISABLED))
9459 io_sq_offload_start(ctx);
9461 memset(&p->sq_off, 0, sizeof(p->sq_off));
9462 p->sq_off.head = offsetof(struct io_rings, sq.head);
9463 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9464 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9465 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9466 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9467 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9468 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9470 memset(&p->cq_off, 0, sizeof(p->cq_off));
9471 p->cq_off.head = offsetof(struct io_rings, cq.head);
9472 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9473 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9474 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9475 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9476 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9477 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9479 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9480 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9481 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9482 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9483 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9485 if (copy_to_user(params, p, sizeof(*p))) {
9490 file = io_uring_get_file(ctx);
9492 ret = PTR_ERR(file);
9497 * Install ring fd as the very last thing, so we don't risk someone
9498 * having closed it before we finish setup
9500 ret = io_uring_install_fd(ctx, file);
9502 io_disable_sqo_submit(ctx);
9503 /* fput will clean it up */
9508 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9511 io_disable_sqo_submit(ctx);
9512 io_ring_ctx_wait_and_kill(ctx);
9517 * Sets up an aio uring context, and returns the fd. Applications asks for a
9518 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9519 * params structure passed in.
9521 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9523 struct io_uring_params p;
9526 if (copy_from_user(&p, params, sizeof(p)))
9528 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9533 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9534 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9535 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9536 IORING_SETUP_R_DISABLED))
9539 return io_uring_create(entries, &p, params);
9542 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9543 struct io_uring_params __user *, params)
9545 return io_uring_setup(entries, params);
9548 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9550 struct io_uring_probe *p;
9554 size = struct_size(p, ops, nr_args);
9555 if (size == SIZE_MAX)
9557 p = kzalloc(size, GFP_KERNEL);
9562 if (copy_from_user(p, arg, size))
9565 if (memchr_inv(p, 0, size))
9568 p->last_op = IORING_OP_LAST - 1;
9569 if (nr_args > IORING_OP_LAST)
9570 nr_args = IORING_OP_LAST;
9572 for (i = 0; i < nr_args; i++) {
9574 if (!io_op_defs[i].not_supported)
9575 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9580 if (copy_to_user(arg, p, size))
9587 static int io_register_personality(struct io_ring_ctx *ctx)
9589 const struct cred *creds;
9592 creds = get_current_cred();
9594 ret = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9595 USHRT_MAX, GFP_KERNEL);
9601 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9602 unsigned int nr_args)
9604 struct io_uring_restriction *res;
9608 /* Restrictions allowed only if rings started disabled */
9609 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9612 /* We allow only a single restrictions registration */
9613 if (ctx->restrictions.registered)
9616 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9619 size = array_size(nr_args, sizeof(*res));
9620 if (size == SIZE_MAX)
9623 res = memdup_user(arg, size);
9625 return PTR_ERR(res);
9629 for (i = 0; i < nr_args; i++) {
9630 switch (res[i].opcode) {
9631 case IORING_RESTRICTION_REGISTER_OP:
9632 if (res[i].register_op >= IORING_REGISTER_LAST) {
9637 __set_bit(res[i].register_op,
9638 ctx->restrictions.register_op);
9640 case IORING_RESTRICTION_SQE_OP:
9641 if (res[i].sqe_op >= IORING_OP_LAST) {
9646 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9648 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9649 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9651 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9652 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9661 /* Reset all restrictions if an error happened */
9663 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9665 ctx->restrictions.registered = true;
9671 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9673 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9676 if (ctx->restrictions.registered)
9677 ctx->restricted = 1;
9679 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9681 io_sq_offload_start(ctx);
9686 static bool io_register_op_must_quiesce(int op)
9689 case IORING_UNREGISTER_FILES:
9690 case IORING_REGISTER_FILES_UPDATE:
9691 case IORING_REGISTER_PROBE:
9692 case IORING_REGISTER_PERSONALITY:
9693 case IORING_UNREGISTER_PERSONALITY:
9700 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9701 void __user *arg, unsigned nr_args)
9702 __releases(ctx->uring_lock)
9703 __acquires(ctx->uring_lock)
9708 * We're inside the ring mutex, if the ref is already dying, then
9709 * someone else killed the ctx or is already going through
9710 * io_uring_register().
9712 if (percpu_ref_is_dying(&ctx->refs))
9715 if (io_register_op_must_quiesce(opcode)) {
9716 percpu_ref_kill(&ctx->refs);
9719 * Drop uring mutex before waiting for references to exit. If
9720 * another thread is currently inside io_uring_enter() it might
9721 * need to grab the uring_lock to make progress. If we hold it
9722 * here across the drain wait, then we can deadlock. It's safe
9723 * to drop the mutex here, since no new references will come in
9724 * after we've killed the percpu ref.
9726 mutex_unlock(&ctx->uring_lock);
9728 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9731 ret = io_run_task_work_sig();
9736 mutex_lock(&ctx->uring_lock);
9738 if (ret && io_refs_resurrect(&ctx->refs, &ctx->ref_comp))
9742 if (ctx->restricted) {
9743 if (opcode >= IORING_REGISTER_LAST) {
9748 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9755 case IORING_REGISTER_BUFFERS:
9756 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9758 case IORING_UNREGISTER_BUFFERS:
9762 ret = io_sqe_buffers_unregister(ctx);
9764 case IORING_REGISTER_FILES:
9765 ret = io_sqe_files_register(ctx, arg, nr_args);
9767 case IORING_UNREGISTER_FILES:
9771 ret = io_sqe_files_unregister(ctx);
9773 case IORING_REGISTER_FILES_UPDATE:
9774 ret = io_sqe_files_update(ctx, arg, nr_args);
9776 case IORING_REGISTER_EVENTFD:
9777 case IORING_REGISTER_EVENTFD_ASYNC:
9781 ret = io_eventfd_register(ctx, arg);
9784 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9785 ctx->eventfd_async = 1;
9787 ctx->eventfd_async = 0;
9789 case IORING_UNREGISTER_EVENTFD:
9793 ret = io_eventfd_unregister(ctx);
9795 case IORING_REGISTER_PROBE:
9797 if (!arg || nr_args > 256)
9799 ret = io_probe(ctx, arg, nr_args);
9801 case IORING_REGISTER_PERSONALITY:
9805 ret = io_register_personality(ctx);
9807 case IORING_UNREGISTER_PERSONALITY:
9811 ret = io_unregister_personality(ctx, nr_args);
9813 case IORING_REGISTER_ENABLE_RINGS:
9817 ret = io_register_enable_rings(ctx);
9819 case IORING_REGISTER_RESTRICTIONS:
9820 ret = io_register_restrictions(ctx, arg, nr_args);
9828 if (io_register_op_must_quiesce(opcode)) {
9829 /* bring the ctx back to life */
9830 percpu_ref_reinit(&ctx->refs);
9831 reinit_completion(&ctx->ref_comp);
9836 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9837 void __user *, arg, unsigned int, nr_args)
9839 struct io_ring_ctx *ctx;
9848 if (f.file->f_op != &io_uring_fops)
9851 ctx = f.file->private_data;
9855 mutex_lock(&ctx->uring_lock);
9856 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9857 mutex_unlock(&ctx->uring_lock);
9858 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9859 ctx->cq_ev_fd != NULL, ret);
9865 static int __init io_uring_init(void)
9867 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9868 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9869 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9872 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9873 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9874 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9875 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9876 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9877 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9878 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9879 BUILD_BUG_SQE_ELEM(8, __u64, off);
9880 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9881 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9882 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9883 BUILD_BUG_SQE_ELEM(24, __u32, len);
9884 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9885 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9886 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9887 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9888 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9889 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9890 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9891 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9892 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9893 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9894 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9895 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9896 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9897 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9898 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9899 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9900 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9901 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9902 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9904 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9905 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9906 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
9910 __initcall(io_uring_init);