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/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.h>
82 #include <linux/io_uring.h>
83 #include <linux/blk-cgroup.h>
84 #include <linux/audit.h>
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/io_uring.h>
89 #include <uapi/linux/io_uring.h>
94 #define IORING_MAX_ENTRIES 32768
95 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
98 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
100 #define IORING_FILE_TABLE_SHIFT 9
101 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
102 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
103 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
104 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
105 IORING_REGISTER_LAST + IORING_OP_LAST)
108 u32 head ____cacheline_aligned_in_smp;
109 u32 tail ____cacheline_aligned_in_smp;
113 * This data is shared with the application through the mmap at offsets
114 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
116 * The offsets to the member fields are published through struct
117 * io_sqring_offsets when calling io_uring_setup.
121 * Head and tail offsets into the ring; the offsets need to be
122 * masked to get valid indices.
124 * The kernel controls head of the sq ring and the tail of the cq ring,
125 * and the application controls tail of the sq ring and the head of the
128 struct io_uring sq, cq;
130 * Bitmasks to apply to head and tail offsets (constant, equals
133 u32 sq_ring_mask, cq_ring_mask;
134 /* Ring sizes (constant, power of 2) */
135 u32 sq_ring_entries, cq_ring_entries;
137 * Number of invalid entries dropped by the kernel due to
138 * invalid index stored in array
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
144 * After a new SQ head value was read by the application this
145 * counter includes all submissions that were dropped reaching
146 * the new SQ head (and possibly more).
152 * Written by the kernel, shouldn't be modified by the
155 * The application needs a full memory barrier before checking
156 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
162 * Written by the application, shouldn't be modified by the
167 * Number of completion events lost because the queue was full;
168 * this should be avoided by the application by making sure
169 * there are not more requests pending than there is space in
170 * the completion queue.
172 * Written by the kernel, shouldn't be modified by the
173 * application (i.e. get number of "new events" by comparing to
176 * As completion events come in out of order this counter is not
177 * ordered with any other data.
181 * Ring buffer of completion events.
183 * The kernel writes completion events fresh every time they are
184 * produced, so the application is allowed to modify pending
187 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
190 struct io_mapped_ubuf {
193 struct bio_vec *bvec;
194 unsigned int nr_bvecs;
195 unsigned long acct_pages;
198 struct fixed_file_table {
202 struct fixed_file_ref_node {
203 struct percpu_ref refs;
204 struct list_head node;
205 struct list_head file_list;
206 struct fixed_file_data *file_data;
207 struct llist_node llist;
211 struct fixed_file_data {
212 struct fixed_file_table *table;
213 struct io_ring_ctx *ctx;
215 struct fixed_file_ref_node *node;
216 struct percpu_ref refs;
217 struct completion done;
218 struct list_head ref_list;
223 struct list_head list;
229 struct io_restriction {
230 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
231 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
232 u8 sqe_flags_allowed;
233 u8 sqe_flags_required;
241 /* ctx's that are using this sqd */
242 struct list_head ctx_list;
243 struct list_head ctx_new_list;
244 struct mutex ctx_lock;
246 struct task_struct *thread;
247 struct wait_queue_head wait;
249 unsigned sq_thread_idle;
254 struct percpu_ref refs;
255 } ____cacheline_aligned_in_smp;
259 unsigned int compat: 1;
260 unsigned int limit_mem: 1;
261 unsigned int cq_overflow_flushed: 1;
262 unsigned int drain_next: 1;
263 unsigned int eventfd_async: 1;
264 unsigned int restricted: 1;
267 * Ring buffer of indices into array of io_uring_sqe, which is
268 * mmapped by the application using the IORING_OFF_SQES offset.
270 * This indirection could e.g. be used to assign fixed
271 * io_uring_sqe entries to operations and only submit them to
272 * the queue when needed.
274 * The kernel modifies neither the indices array nor the entries
278 unsigned cached_sq_head;
281 unsigned sq_thread_idle;
282 unsigned cached_sq_dropped;
283 unsigned cached_cq_overflow;
284 unsigned long sq_check_overflow;
286 struct list_head defer_list;
287 struct list_head timeout_list;
288 struct list_head cq_overflow_list;
290 struct io_uring_sqe *sq_sqes;
291 } ____cacheline_aligned_in_smp;
293 struct io_rings *rings;
299 * For SQPOLL usage - we hold a reference to the parent task, so we
300 * have access to the ->files
302 struct task_struct *sqo_task;
304 /* Only used for accounting purposes */
305 struct mm_struct *mm_account;
307 #ifdef CONFIG_BLK_CGROUP
308 struct cgroup_subsys_state *sqo_blkcg_css;
311 struct io_sq_data *sq_data; /* if using sq thread polling */
313 struct wait_queue_head sqo_sq_wait;
314 struct list_head sqd_list;
317 * If used, fixed file set. Writers must ensure that ->refs is dead,
318 * readers must ensure that ->refs is alive as long as the file* is
319 * used. Only updated through io_uring_register(2).
321 struct fixed_file_data *file_data;
322 unsigned nr_user_files;
324 /* if used, fixed mapped user buffers */
325 unsigned nr_user_bufs;
326 struct io_mapped_ubuf *user_bufs;
328 struct user_struct *user;
330 const struct cred *creds;
334 unsigned int sessionid;
337 struct completion ref_comp;
338 struct completion sq_thread_comp;
340 /* if all else fails... */
341 struct io_kiocb *fallback_req;
343 #if defined(CONFIG_UNIX)
344 struct socket *ring_sock;
347 struct idr io_buffer_idr;
349 struct idr personality_idr;
352 unsigned cached_cq_tail;
355 atomic_t cq_timeouts;
356 unsigned long cq_check_overflow;
357 struct wait_queue_head cq_wait;
358 struct fasync_struct *cq_fasync;
359 struct eventfd_ctx *cq_ev_fd;
360 } ____cacheline_aligned_in_smp;
363 struct mutex uring_lock;
364 wait_queue_head_t wait;
365 } ____cacheline_aligned_in_smp;
368 spinlock_t completion_lock;
371 * ->iopoll_list is protected by the ctx->uring_lock for
372 * io_uring instances that don't use IORING_SETUP_SQPOLL.
373 * For SQPOLL, only the single threaded io_sq_thread() will
374 * manipulate the list, hence no extra locking is needed there.
376 struct list_head iopoll_list;
377 struct hlist_head *cancel_hash;
378 unsigned cancel_hash_bits;
379 bool poll_multi_file;
381 spinlock_t inflight_lock;
382 struct list_head inflight_list;
383 } ____cacheline_aligned_in_smp;
385 struct delayed_work file_put_work;
386 struct llist_head file_put_llist;
388 struct work_struct exit_work;
389 struct io_restriction restrictions;
393 * First field must be the file pointer in all the
394 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
396 struct io_poll_iocb {
398 struct wait_queue_head *head;
402 struct wait_queue_entry wait;
405 struct io_poll_remove {
412 struct file *put_file;
416 struct io_timeout_data {
417 struct io_kiocb *req;
418 struct hrtimer timer;
419 struct timespec64 ts;
420 enum hrtimer_mode mode;
425 struct sockaddr __user *addr;
426 int __user *addr_len;
428 unsigned long nofile;
448 struct list_head list;
449 /* head of the link, used by linked timeouts only */
450 struct io_kiocb *head;
453 struct io_timeout_rem {
458 struct timespec64 ts;
463 /* NOTE: kiocb has the file as the first member, so don't do it here */
471 struct sockaddr __user *addr;
478 struct user_msghdr __user *umsg;
484 struct io_buffer *kbuf;
490 bool ignore_nonblock;
491 struct filename *filename;
493 unsigned long nofile;
496 struct io_files_update {
522 struct epoll_event event;
526 struct file *file_out;
527 struct file *file_in;
534 struct io_provide_buf {
548 const char __user *filename;
549 struct statx __user *buffer;
561 struct filename *oldpath;
562 struct filename *newpath;
570 struct filename *filename;
573 struct io_completion {
575 struct list_head list;
579 struct io_async_connect {
580 struct sockaddr_storage address;
583 struct io_async_msghdr {
584 struct iovec fast_iov[UIO_FASTIOV];
586 struct sockaddr __user *uaddr;
588 struct sockaddr_storage addr;
592 struct iovec fast_iov[UIO_FASTIOV];
593 const struct iovec *free_iovec;
594 struct iov_iter iter;
596 struct wait_page_queue wpq;
600 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
601 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
602 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
603 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
604 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
605 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
611 REQ_F_LINK_TIMEOUT_BIT,
613 REQ_F_NEED_CLEANUP_BIT,
615 REQ_F_BUFFER_SELECTED_BIT,
616 REQ_F_NO_FILE_TABLE_BIT,
617 REQ_F_WORK_INITIALIZED_BIT,
618 REQ_F_LTIMEOUT_ACTIVE_BIT,
620 /* not a real bit, just to check we're not overflowing the space */
626 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
627 /* drain existing IO first */
628 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
630 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
631 /* doesn't sever on completion < 0 */
632 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
634 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
635 /* IOSQE_BUFFER_SELECT */
636 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
638 /* fail rest of links */
639 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
640 /* on inflight list */
641 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
642 /* read/write uses file position */
643 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
644 /* must not punt to workers */
645 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
646 /* has or had linked timeout */
647 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
649 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
651 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
652 /* already went through poll handler */
653 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
654 /* buffer already selected */
655 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
656 /* doesn't need file table for this request */
657 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
658 /* io_wq_work is initialized */
659 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
660 /* linked timeout is active, i.e. prepared by link's head */
661 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
665 struct io_poll_iocb poll;
666 struct io_poll_iocb *double_poll;
670 * NOTE! Each of the iocb union members has the file pointer
671 * as the first entry in their struct definition. So you can
672 * access the file pointer through any of the sub-structs,
673 * or directly as just 'ki_filp' in this struct.
679 struct io_poll_iocb poll;
680 struct io_poll_remove poll_remove;
681 struct io_accept accept;
683 struct io_cancel cancel;
684 struct io_timeout timeout;
685 struct io_timeout_rem timeout_rem;
686 struct io_connect connect;
687 struct io_sr_msg sr_msg;
689 struct io_close close;
690 struct io_files_update files_update;
691 struct io_fadvise fadvise;
692 struct io_madvise madvise;
693 struct io_epoll epoll;
694 struct io_splice splice;
695 struct io_provide_buf pbuf;
696 struct io_statx statx;
697 struct io_shutdown shutdown;
698 struct io_rename rename;
699 struct io_unlink unlink;
700 /* use only after cleaning per-op data, see io_clean_op() */
701 struct io_completion compl;
704 /* opcode allocated if it needs to store data for async defer */
707 /* polled IO has completed */
713 struct io_ring_ctx *ctx;
716 struct task_struct *task;
719 struct io_kiocb *link;
720 struct percpu_ref *fixed_file_refs;
723 * 1. used with ctx->iopoll_list with reads/writes
724 * 2. to track reqs with ->files (see io_op_def::file_table)
726 struct list_head inflight_entry;
727 struct callback_head task_work;
728 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
729 struct hlist_node hash_node;
730 struct async_poll *apoll;
731 struct io_wq_work work;
734 struct io_defer_entry {
735 struct list_head list;
736 struct io_kiocb *req;
740 #define IO_IOPOLL_BATCH 8
742 struct io_comp_state {
744 struct list_head list;
745 struct io_ring_ctx *ctx;
748 struct io_submit_state {
749 struct blk_plug plug;
752 * io_kiocb alloc cache
754 void *reqs[IO_IOPOLL_BATCH];
755 unsigned int free_reqs;
760 * Batch completion logic
762 struct io_comp_state comp;
765 * File reference cache
769 unsigned int file_refs;
770 unsigned int ios_left;
774 /* needs req->file assigned */
775 unsigned needs_file : 1;
776 /* don't fail if file grab fails */
777 unsigned needs_file_no_error : 1;
778 /* hash wq insertion if file is a regular file */
779 unsigned hash_reg_file : 1;
780 /* unbound wq insertion if file is a non-regular file */
781 unsigned unbound_nonreg_file : 1;
782 /* opcode is not supported by this kernel */
783 unsigned not_supported : 1;
784 /* set if opcode supports polled "wait" */
786 unsigned pollout : 1;
787 /* op supports buffer selection */
788 unsigned buffer_select : 1;
789 /* must always have async data allocated */
790 unsigned needs_async_data : 1;
791 /* should block plug */
793 /* size of async data needed, if any */
794 unsigned short async_size;
798 static const struct io_op_def io_op_defs[] = {
799 [IORING_OP_NOP] = {},
800 [IORING_OP_READV] = {
802 .unbound_nonreg_file = 1,
805 .needs_async_data = 1,
807 .async_size = sizeof(struct io_async_rw),
808 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
810 [IORING_OP_WRITEV] = {
813 .unbound_nonreg_file = 1,
815 .needs_async_data = 1,
817 .async_size = sizeof(struct io_async_rw),
818 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
821 [IORING_OP_FSYNC] = {
823 .work_flags = IO_WQ_WORK_BLKCG,
825 [IORING_OP_READ_FIXED] = {
827 .unbound_nonreg_file = 1,
830 .async_size = sizeof(struct io_async_rw),
831 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
833 [IORING_OP_WRITE_FIXED] = {
836 .unbound_nonreg_file = 1,
839 .async_size = sizeof(struct io_async_rw),
840 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
843 [IORING_OP_POLL_ADD] = {
845 .unbound_nonreg_file = 1,
847 [IORING_OP_POLL_REMOVE] = {},
848 [IORING_OP_SYNC_FILE_RANGE] = {
850 .work_flags = IO_WQ_WORK_BLKCG,
852 [IORING_OP_SENDMSG] = {
854 .unbound_nonreg_file = 1,
856 .needs_async_data = 1,
857 .async_size = sizeof(struct io_async_msghdr),
858 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
860 [IORING_OP_RECVMSG] = {
862 .unbound_nonreg_file = 1,
865 .needs_async_data = 1,
866 .async_size = sizeof(struct io_async_msghdr),
867 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
869 [IORING_OP_TIMEOUT] = {
870 .needs_async_data = 1,
871 .async_size = sizeof(struct io_timeout_data),
872 .work_flags = IO_WQ_WORK_MM,
874 [IORING_OP_TIMEOUT_REMOVE] = {
875 /* used by timeout updates' prep() */
876 .work_flags = IO_WQ_WORK_MM,
878 [IORING_OP_ACCEPT] = {
880 .unbound_nonreg_file = 1,
882 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
884 [IORING_OP_ASYNC_CANCEL] = {},
885 [IORING_OP_LINK_TIMEOUT] = {
886 .needs_async_data = 1,
887 .async_size = sizeof(struct io_timeout_data),
888 .work_flags = IO_WQ_WORK_MM,
890 [IORING_OP_CONNECT] = {
892 .unbound_nonreg_file = 1,
894 .needs_async_data = 1,
895 .async_size = sizeof(struct io_async_connect),
896 .work_flags = IO_WQ_WORK_MM,
898 [IORING_OP_FALLOCATE] = {
900 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
902 [IORING_OP_OPENAT] = {
903 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
904 IO_WQ_WORK_FS | IO_WQ_WORK_MM,
906 [IORING_OP_CLOSE] = {
908 .needs_file_no_error = 1,
909 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
911 [IORING_OP_FILES_UPDATE] = {
912 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
914 [IORING_OP_STATX] = {
915 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
916 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
920 .unbound_nonreg_file = 1,
924 .async_size = sizeof(struct io_async_rw),
925 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
927 [IORING_OP_WRITE] = {
929 .unbound_nonreg_file = 1,
932 .async_size = sizeof(struct io_async_rw),
933 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
936 [IORING_OP_FADVISE] = {
938 .work_flags = IO_WQ_WORK_BLKCG,
940 [IORING_OP_MADVISE] = {
941 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
945 .unbound_nonreg_file = 1,
947 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
951 .unbound_nonreg_file = 1,
954 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
956 [IORING_OP_OPENAT2] = {
957 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
958 IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
960 [IORING_OP_EPOLL_CTL] = {
961 .unbound_nonreg_file = 1,
962 .work_flags = IO_WQ_WORK_FILES,
964 [IORING_OP_SPLICE] = {
967 .unbound_nonreg_file = 1,
968 .work_flags = IO_WQ_WORK_BLKCG,
970 [IORING_OP_PROVIDE_BUFFERS] = {},
971 [IORING_OP_REMOVE_BUFFERS] = {},
975 .unbound_nonreg_file = 1,
977 [IORING_OP_SHUTDOWN] = {
980 [IORING_OP_RENAMEAT] = {
981 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
982 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
984 [IORING_OP_UNLINKAT] = {
985 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
986 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
990 enum io_mem_account {
995 static void __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
996 struct task_struct *task);
998 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node);
999 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
1000 struct io_ring_ctx *ctx);
1002 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
1003 struct io_comp_state *cs);
1004 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1005 static void io_put_req(struct io_kiocb *req);
1006 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1007 static void io_double_put_req(struct io_kiocb *req);
1008 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1009 static void __io_queue_linked_timeout(struct io_kiocb *req);
1010 static void io_queue_linked_timeout(struct io_kiocb *req);
1011 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1012 struct io_uring_files_update *ip,
1014 static void __io_clean_op(struct io_kiocb *req);
1015 static struct file *io_file_get(struct io_submit_state *state,
1016 struct io_kiocb *req, int fd, bool fixed);
1017 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs);
1018 static void io_file_put_work(struct work_struct *work);
1020 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1021 struct iovec **iovec, struct iov_iter *iter,
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);
1027 static struct kmem_cache *req_cachep;
1029 static const struct file_operations io_uring_fops;
1031 struct sock *io_uring_get_socket(struct file *file)
1033 #if defined(CONFIG_UNIX)
1034 if (file->f_op == &io_uring_fops) {
1035 struct io_ring_ctx *ctx = file->private_data;
1037 return ctx->ring_sock->sk;
1042 EXPORT_SYMBOL(io_uring_get_socket);
1044 #define io_for_each_link(pos, head) \
1045 for (pos = (head); pos; pos = pos->link)
1047 static inline void io_clean_op(struct io_kiocb *req)
1049 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
1054 static inline void io_set_resource_node(struct io_kiocb *req)
1056 struct io_ring_ctx *ctx = req->ctx;
1058 if (!req->fixed_file_refs) {
1059 req->fixed_file_refs = &ctx->file_data->node->refs;
1060 percpu_ref_get(req->fixed_file_refs);
1064 static bool io_match_task(struct io_kiocb *head,
1065 struct task_struct *task,
1066 struct files_struct *files)
1068 struct io_kiocb *req;
1070 if (task && head->task != task)
1075 io_for_each_link(req, head) {
1076 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
1077 (req->work.flags & IO_WQ_WORK_FILES) &&
1078 req->work.identity->files == files)
1084 static void io_sq_thread_drop_mm_files(void)
1086 struct files_struct *files = current->files;
1087 struct mm_struct *mm = current->mm;
1090 kthread_unuse_mm(mm);
1095 struct nsproxy *nsproxy = current->nsproxy;
1098 current->files = NULL;
1099 current->nsproxy = NULL;
1100 task_unlock(current);
1101 put_files_struct(files);
1102 put_nsproxy(nsproxy);
1106 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1108 if (!current->files) {
1109 struct files_struct *files;
1110 struct nsproxy *nsproxy;
1112 task_lock(ctx->sqo_task);
1113 files = ctx->sqo_task->files;
1115 task_unlock(ctx->sqo_task);
1118 atomic_inc(&files->count);
1119 get_nsproxy(ctx->sqo_task->nsproxy);
1120 nsproxy = ctx->sqo_task->nsproxy;
1121 task_unlock(ctx->sqo_task);
1124 current->files = files;
1125 current->nsproxy = nsproxy;
1126 task_unlock(current);
1131 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1133 struct mm_struct *mm;
1138 /* Should never happen */
1139 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL)))
1142 task_lock(ctx->sqo_task);
1143 mm = ctx->sqo_task->mm;
1144 if (unlikely(!mm || !mmget_not_zero(mm)))
1146 task_unlock(ctx->sqo_task);
1156 static int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1157 struct io_kiocb *req)
1159 const struct io_op_def *def = &io_op_defs[req->opcode];
1162 if (def->work_flags & IO_WQ_WORK_MM) {
1163 ret = __io_sq_thread_acquire_mm(ctx);
1168 if (def->needs_file || (def->work_flags & IO_WQ_WORK_FILES)) {
1169 ret = __io_sq_thread_acquire_files(ctx);
1177 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1178 struct cgroup_subsys_state **cur_css)
1181 #ifdef CONFIG_BLK_CGROUP
1182 /* puts the old one when swapping */
1183 if (*cur_css != ctx->sqo_blkcg_css) {
1184 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1185 *cur_css = ctx->sqo_blkcg_css;
1190 static void io_sq_thread_unassociate_blkcg(void)
1192 #ifdef CONFIG_BLK_CGROUP
1193 kthread_associate_blkcg(NULL);
1197 static inline void req_set_fail_links(struct io_kiocb *req)
1199 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1200 req->flags |= REQ_F_FAIL_LINK;
1204 * None of these are dereferenced, they are simply used to check if any of
1205 * them have changed. If we're under current and check they are still the
1206 * same, we're fine to grab references to them for actual out-of-line use.
1208 static void io_init_identity(struct io_identity *id)
1210 id->files = current->files;
1211 id->mm = current->mm;
1212 #ifdef CONFIG_BLK_CGROUP
1214 id->blkcg_css = blkcg_css();
1217 id->creds = current_cred();
1218 id->nsproxy = current->nsproxy;
1219 id->fs = current->fs;
1220 id->fsize = rlimit(RLIMIT_FSIZE);
1222 id->loginuid = current->loginuid;
1223 id->sessionid = current->sessionid;
1225 refcount_set(&id->count, 1);
1228 static inline void __io_req_init_async(struct io_kiocb *req)
1230 memset(&req->work, 0, sizeof(req->work));
1231 req->flags |= REQ_F_WORK_INITIALIZED;
1235 * Note: must call io_req_init_async() for the first time you
1236 * touch any members of io_wq_work.
1238 static inline void io_req_init_async(struct io_kiocb *req)
1240 struct io_uring_task *tctx = current->io_uring;
1242 if (req->flags & REQ_F_WORK_INITIALIZED)
1245 __io_req_init_async(req);
1247 /* Grab a ref if this isn't our static identity */
1248 req->work.identity = tctx->identity;
1249 if (tctx->identity != &tctx->__identity)
1250 refcount_inc(&req->work.identity->count);
1253 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1255 return ctx->flags & IORING_SETUP_SQPOLL;
1258 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1260 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1262 complete(&ctx->ref_comp);
1265 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1267 return !req->timeout.off;
1270 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1272 struct io_ring_ctx *ctx;
1275 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1279 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1280 if (!ctx->fallback_req)
1284 * Use 5 bits less than the max cq entries, that should give us around
1285 * 32 entries per hash list if totally full and uniformly spread.
1287 hash_bits = ilog2(p->cq_entries);
1291 ctx->cancel_hash_bits = hash_bits;
1292 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1294 if (!ctx->cancel_hash)
1296 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1298 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1299 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1302 ctx->flags = p->flags;
1303 init_waitqueue_head(&ctx->sqo_sq_wait);
1304 INIT_LIST_HEAD(&ctx->sqd_list);
1305 init_waitqueue_head(&ctx->cq_wait);
1306 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1307 init_completion(&ctx->ref_comp);
1308 init_completion(&ctx->sq_thread_comp);
1309 idr_init(&ctx->io_buffer_idr);
1310 idr_init(&ctx->personality_idr);
1311 mutex_init(&ctx->uring_lock);
1312 init_waitqueue_head(&ctx->wait);
1313 spin_lock_init(&ctx->completion_lock);
1314 INIT_LIST_HEAD(&ctx->iopoll_list);
1315 INIT_LIST_HEAD(&ctx->defer_list);
1316 INIT_LIST_HEAD(&ctx->timeout_list);
1317 spin_lock_init(&ctx->inflight_lock);
1318 INIT_LIST_HEAD(&ctx->inflight_list);
1319 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1320 init_llist_head(&ctx->file_put_llist);
1323 if (ctx->fallback_req)
1324 kmem_cache_free(req_cachep, ctx->fallback_req);
1325 kfree(ctx->cancel_hash);
1330 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1332 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1333 struct io_ring_ctx *ctx = req->ctx;
1335 return seq != ctx->cached_cq_tail
1336 + READ_ONCE(ctx->cached_cq_overflow);
1342 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1344 struct io_rings *rings = ctx->rings;
1346 /* order cqe stores with ring update */
1347 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1350 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1352 if (req->work.identity == &tctx->__identity)
1354 if (refcount_dec_and_test(&req->work.identity->count))
1355 kfree(req->work.identity);
1358 static void io_req_clean_work(struct io_kiocb *req)
1360 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1363 req->flags &= ~REQ_F_WORK_INITIALIZED;
1365 if (req->work.flags & IO_WQ_WORK_MM) {
1366 mmdrop(req->work.identity->mm);
1367 req->work.flags &= ~IO_WQ_WORK_MM;
1369 #ifdef CONFIG_BLK_CGROUP
1370 if (req->work.flags & IO_WQ_WORK_BLKCG) {
1371 css_put(req->work.identity->blkcg_css);
1372 req->work.flags &= ~IO_WQ_WORK_BLKCG;
1375 if (req->work.flags & IO_WQ_WORK_CREDS) {
1376 put_cred(req->work.identity->creds);
1377 req->work.flags &= ~IO_WQ_WORK_CREDS;
1379 if (req->work.flags & IO_WQ_WORK_FS) {
1380 struct fs_struct *fs = req->work.identity->fs;
1382 spin_lock(&req->work.identity->fs->lock);
1385 spin_unlock(&req->work.identity->fs->lock);
1388 req->work.flags &= ~IO_WQ_WORK_FS;
1391 io_put_identity(req->task->io_uring, req);
1395 * Create a private copy of io_identity, since some fields don't match
1396 * the current context.
1398 static bool io_identity_cow(struct io_kiocb *req)
1400 struct io_uring_task *tctx = current->io_uring;
1401 const struct cred *creds = NULL;
1402 struct io_identity *id;
1404 if (req->work.flags & IO_WQ_WORK_CREDS)
1405 creds = req->work.identity->creds;
1407 id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1408 if (unlikely(!id)) {
1409 req->work.flags |= IO_WQ_WORK_CANCEL;
1414 * We can safely just re-init the creds we copied Either the field
1415 * matches the current one, or we haven't grabbed it yet. The only
1416 * exception is ->creds, through registered personalities, so handle
1417 * that one separately.
1419 io_init_identity(id);
1423 /* add one for this request */
1424 refcount_inc(&id->count);
1426 /* drop tctx and req identity references, if needed */
1427 if (tctx->identity != &tctx->__identity &&
1428 refcount_dec_and_test(&tctx->identity->count))
1429 kfree(tctx->identity);
1430 if (req->work.identity != &tctx->__identity &&
1431 refcount_dec_and_test(&req->work.identity->count))
1432 kfree(req->work.identity);
1434 req->work.identity = id;
1435 tctx->identity = id;
1439 static bool io_grab_identity(struct io_kiocb *req)
1441 const struct io_op_def *def = &io_op_defs[req->opcode];
1442 struct io_identity *id = req->work.identity;
1443 struct io_ring_ctx *ctx = req->ctx;
1445 if (def->work_flags & IO_WQ_WORK_FSIZE) {
1446 if (id->fsize != rlimit(RLIMIT_FSIZE))
1448 req->work.flags |= IO_WQ_WORK_FSIZE;
1450 #ifdef CONFIG_BLK_CGROUP
1451 if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1452 (def->work_flags & IO_WQ_WORK_BLKCG)) {
1454 if (id->blkcg_css != blkcg_css()) {
1459 * This should be rare, either the cgroup is dying or the task
1460 * is moving cgroups. Just punt to root for the handful of ios.
1462 if (css_tryget_online(id->blkcg_css))
1463 req->work.flags |= IO_WQ_WORK_BLKCG;
1467 if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1468 if (id->creds != current_cred())
1470 get_cred(id->creds);
1471 req->work.flags |= IO_WQ_WORK_CREDS;
1474 if (!uid_eq(current->loginuid, id->loginuid) ||
1475 current->sessionid != id->sessionid)
1478 if (!(req->work.flags & IO_WQ_WORK_FS) &&
1479 (def->work_flags & IO_WQ_WORK_FS)) {
1480 if (current->fs != id->fs)
1482 spin_lock(&id->fs->lock);
1483 if (!id->fs->in_exec) {
1485 req->work.flags |= IO_WQ_WORK_FS;
1487 req->work.flags |= IO_WQ_WORK_CANCEL;
1489 spin_unlock(¤t->fs->lock);
1491 if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1492 (def->work_flags & IO_WQ_WORK_FILES) &&
1493 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1494 if (id->files != current->files ||
1495 id->nsproxy != current->nsproxy)
1497 atomic_inc(&id->files->count);
1498 get_nsproxy(id->nsproxy);
1499 req->flags |= REQ_F_INFLIGHT;
1501 spin_lock_irq(&ctx->inflight_lock);
1502 list_add(&req->inflight_entry, &ctx->inflight_list);
1503 spin_unlock_irq(&ctx->inflight_lock);
1504 req->work.flags |= IO_WQ_WORK_FILES;
1506 if (!(req->work.flags & IO_WQ_WORK_MM) &&
1507 (def->work_flags & IO_WQ_WORK_MM)) {
1508 if (id->mm != current->mm)
1511 req->work.flags |= IO_WQ_WORK_MM;
1517 static void io_prep_async_work(struct io_kiocb *req)
1519 const struct io_op_def *def = &io_op_defs[req->opcode];
1520 struct io_ring_ctx *ctx = req->ctx;
1522 io_req_init_async(req);
1524 if (req->flags & REQ_F_FORCE_ASYNC)
1525 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1527 if (req->flags & REQ_F_ISREG) {
1528 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1529 io_wq_hash_work(&req->work, file_inode(req->file));
1531 if (def->unbound_nonreg_file)
1532 req->work.flags |= IO_WQ_WORK_UNBOUND;
1535 /* if we fail grabbing identity, we must COW, regrab, and retry */
1536 if (io_grab_identity(req))
1539 if (!io_identity_cow(req))
1542 /* can't fail at this point */
1543 if (!io_grab_identity(req))
1547 static void io_prep_async_link(struct io_kiocb *req)
1549 struct io_kiocb *cur;
1551 io_for_each_link(cur, req)
1552 io_prep_async_work(cur);
1555 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1557 struct io_ring_ctx *ctx = req->ctx;
1558 struct io_kiocb *link = io_prep_linked_timeout(req);
1560 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1561 &req->work, req->flags);
1562 io_wq_enqueue(ctx->io_wq, &req->work);
1566 static void io_queue_async_work(struct io_kiocb *req)
1568 struct io_kiocb *link;
1570 /* init ->work of the whole link before punting */
1571 io_prep_async_link(req);
1572 link = __io_queue_async_work(req);
1575 io_queue_linked_timeout(link);
1578 static void io_kill_timeout(struct io_kiocb *req)
1580 struct io_timeout_data *io = req->async_data;
1583 ret = hrtimer_try_to_cancel(&io->timer);
1585 atomic_set(&req->ctx->cq_timeouts,
1586 atomic_read(&req->ctx->cq_timeouts) + 1);
1587 list_del_init(&req->timeout.list);
1588 io_cqring_fill_event(req, 0);
1589 io_put_req_deferred(req, 1);
1594 * Returns true if we found and killed one or more timeouts
1596 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1597 struct files_struct *files)
1599 struct io_kiocb *req, *tmp;
1602 spin_lock_irq(&ctx->completion_lock);
1603 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1604 if (io_match_task(req, tsk, files)) {
1605 io_kill_timeout(req);
1609 spin_unlock_irq(&ctx->completion_lock);
1610 return canceled != 0;
1613 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1616 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1617 struct io_defer_entry, list);
1618 struct io_kiocb *link;
1620 if (req_need_defer(de->req, de->seq))
1622 list_del_init(&de->list);
1623 /* punt-init is done before queueing for defer */
1624 link = __io_queue_async_work(de->req);
1626 __io_queue_linked_timeout(link);
1627 /* drop submission reference */
1628 io_put_req_deferred(link, 1);
1631 } while (!list_empty(&ctx->defer_list));
1634 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1636 while (!list_empty(&ctx->timeout_list)) {
1637 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1638 struct io_kiocb, timeout.list);
1640 if (io_is_timeout_noseq(req))
1642 if (req->timeout.target_seq != ctx->cached_cq_tail
1643 - atomic_read(&ctx->cq_timeouts))
1646 list_del_init(&req->timeout.list);
1647 io_kill_timeout(req);
1651 static void io_commit_cqring(struct io_ring_ctx *ctx)
1653 io_flush_timeouts(ctx);
1654 __io_commit_cqring(ctx);
1656 if (unlikely(!list_empty(&ctx->defer_list)))
1657 __io_queue_deferred(ctx);
1660 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1662 struct io_rings *r = ctx->rings;
1664 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1667 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1669 struct io_rings *rings = ctx->rings;
1672 tail = ctx->cached_cq_tail;
1674 * writes to the cq entry need to come after reading head; the
1675 * control dependency is enough as we're using WRITE_ONCE to
1678 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1681 ctx->cached_cq_tail++;
1682 return &rings->cqes[tail & ctx->cq_mask];
1685 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1689 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1691 if (!ctx->eventfd_async)
1693 return io_wq_current_is_worker();
1696 static inline unsigned __io_cqring_events(struct io_ring_ctx *ctx)
1698 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1701 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1703 /* see waitqueue_active() comment */
1706 if (waitqueue_active(&ctx->wait))
1707 wake_up(&ctx->wait);
1708 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1709 wake_up(&ctx->sq_data->wait);
1710 if (io_should_trigger_evfd(ctx))
1711 eventfd_signal(ctx->cq_ev_fd, 1);
1712 if (waitqueue_active(&ctx->cq_wait)) {
1713 wake_up_interruptible(&ctx->cq_wait);
1714 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1718 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1720 /* see waitqueue_active() comment */
1723 if (ctx->flags & IORING_SETUP_SQPOLL) {
1724 if (waitqueue_active(&ctx->wait))
1725 wake_up(&ctx->wait);
1727 if (io_should_trigger_evfd(ctx))
1728 eventfd_signal(ctx->cq_ev_fd, 1);
1729 if (waitqueue_active(&ctx->cq_wait)) {
1730 wake_up_interruptible(&ctx->cq_wait);
1731 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1735 /* Returns true if there are no backlogged entries after the flush */
1736 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1737 struct task_struct *tsk,
1738 struct files_struct *files)
1740 struct io_rings *rings = ctx->rings;
1741 struct io_kiocb *req, *tmp;
1742 struct io_uring_cqe *cqe;
1743 unsigned long flags;
1747 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1750 spin_lock_irqsave(&ctx->completion_lock, flags);
1751 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1752 if (!io_match_task(req, tsk, files))
1755 cqe = io_get_cqring(ctx);
1759 list_move(&req->compl.list, &list);
1761 WRITE_ONCE(cqe->user_data, req->user_data);
1762 WRITE_ONCE(cqe->res, req->result);
1763 WRITE_ONCE(cqe->flags, req->compl.cflags);
1765 ctx->cached_cq_overflow++;
1766 WRITE_ONCE(ctx->rings->cq_overflow,
1767 ctx->cached_cq_overflow);
1771 all_flushed = list_empty(&ctx->cq_overflow_list);
1773 clear_bit(0, &ctx->sq_check_overflow);
1774 clear_bit(0, &ctx->cq_check_overflow);
1775 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1778 io_commit_cqring(ctx);
1779 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1780 io_cqring_ev_posted(ctx);
1782 while (!list_empty(&list)) {
1783 req = list_first_entry(&list, struct io_kiocb, compl.list);
1784 list_del(&req->compl.list);
1791 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1792 struct task_struct *tsk,
1793 struct files_struct *files)
1795 if (test_bit(0, &ctx->cq_check_overflow)) {
1796 /* iopoll syncs against uring_lock, not completion_lock */
1797 if (ctx->flags & IORING_SETUP_IOPOLL)
1798 mutex_lock(&ctx->uring_lock);
1799 __io_cqring_overflow_flush(ctx, force, tsk, files);
1800 if (ctx->flags & IORING_SETUP_IOPOLL)
1801 mutex_unlock(&ctx->uring_lock);
1805 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1807 struct io_ring_ctx *ctx = req->ctx;
1808 struct io_uring_cqe *cqe;
1810 trace_io_uring_complete(ctx, req->user_data, res);
1813 * If we can't get a cq entry, userspace overflowed the
1814 * submission (by quite a lot). Increment the overflow count in
1817 cqe = io_get_cqring(ctx);
1819 WRITE_ONCE(cqe->user_data, req->user_data);
1820 WRITE_ONCE(cqe->res, res);
1821 WRITE_ONCE(cqe->flags, cflags);
1822 } else if (ctx->cq_overflow_flushed ||
1823 atomic_read(&req->task->io_uring->in_idle)) {
1825 * If we're in ring overflow flush mode, or in task cancel mode,
1826 * then we cannot store the request for later flushing, we need
1827 * to drop it on the floor.
1829 ctx->cached_cq_overflow++;
1830 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1832 if (list_empty(&ctx->cq_overflow_list)) {
1833 set_bit(0, &ctx->sq_check_overflow);
1834 set_bit(0, &ctx->cq_check_overflow);
1835 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1839 req->compl.cflags = cflags;
1840 refcount_inc(&req->refs);
1841 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1845 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1847 __io_cqring_fill_event(req, res, 0);
1850 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1852 struct io_ring_ctx *ctx = req->ctx;
1853 unsigned long flags;
1855 spin_lock_irqsave(&ctx->completion_lock, flags);
1856 __io_cqring_fill_event(req, res, cflags);
1857 io_commit_cqring(ctx);
1858 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1860 io_cqring_ev_posted(ctx);
1863 static void io_submit_flush_completions(struct io_comp_state *cs)
1865 struct io_ring_ctx *ctx = cs->ctx;
1867 spin_lock_irq(&ctx->completion_lock);
1868 while (!list_empty(&cs->list)) {
1869 struct io_kiocb *req;
1871 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1872 list_del(&req->compl.list);
1873 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1876 * io_free_req() doesn't care about completion_lock unless one
1877 * of these flags is set. REQ_F_WORK_INITIALIZED is in the list
1878 * because of a potential deadlock with req->work.fs->lock
1880 if (req->flags & (REQ_F_FAIL_LINK|REQ_F_LINK_TIMEOUT
1881 |REQ_F_WORK_INITIALIZED)) {
1882 spin_unlock_irq(&ctx->completion_lock);
1884 spin_lock_irq(&ctx->completion_lock);
1889 io_commit_cqring(ctx);
1890 spin_unlock_irq(&ctx->completion_lock);
1892 io_cqring_ev_posted(ctx);
1896 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1897 struct io_comp_state *cs)
1900 io_cqring_add_event(req, res, cflags);
1905 req->compl.cflags = cflags;
1906 list_add_tail(&req->compl.list, &cs->list);
1908 io_submit_flush_completions(cs);
1912 static void io_req_complete(struct io_kiocb *req, long res)
1914 __io_req_complete(req, res, 0, NULL);
1917 static inline bool io_is_fallback_req(struct io_kiocb *req)
1919 return req == (struct io_kiocb *)
1920 ((unsigned long) req->ctx->fallback_req & ~1UL);
1923 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1925 struct io_kiocb *req;
1927 req = ctx->fallback_req;
1928 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1934 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1935 struct io_submit_state *state)
1937 if (!state->free_reqs) {
1938 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1942 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1943 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1946 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1947 * retry single alloc to be on the safe side.
1949 if (unlikely(ret <= 0)) {
1950 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1951 if (!state->reqs[0])
1955 state->free_reqs = ret;
1959 return state->reqs[state->free_reqs];
1961 return io_get_fallback_req(ctx);
1964 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1971 static void io_dismantle_req(struct io_kiocb *req)
1975 if (req->async_data)
1976 kfree(req->async_data);
1978 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1979 if (req->fixed_file_refs)
1980 percpu_ref_put(req->fixed_file_refs);
1981 io_req_clean_work(req);
1984 static void __io_free_req(struct io_kiocb *req)
1986 struct io_uring_task *tctx = req->task->io_uring;
1987 struct io_ring_ctx *ctx = req->ctx;
1989 io_dismantle_req(req);
1991 percpu_counter_dec(&tctx->inflight);
1992 if (atomic_read(&tctx->in_idle))
1993 wake_up(&tctx->wait);
1994 put_task_struct(req->task);
1996 if (likely(!io_is_fallback_req(req)))
1997 kmem_cache_free(req_cachep, req);
1999 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
2000 percpu_ref_put(&ctx->refs);
2003 static inline void io_remove_next_linked(struct io_kiocb *req)
2005 struct io_kiocb *nxt = req->link;
2007 req->link = nxt->link;
2011 static void io_kill_linked_timeout(struct io_kiocb *req)
2013 struct io_ring_ctx *ctx = req->ctx;
2014 struct io_kiocb *link;
2015 bool cancelled = false;
2016 unsigned long flags;
2018 spin_lock_irqsave(&ctx->completion_lock, flags);
2022 * Can happen if a linked timeout fired and link had been like
2023 * req -> link t-out -> link t-out [-> ...]
2025 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
2026 struct io_timeout_data *io = link->async_data;
2029 io_remove_next_linked(req);
2030 link->timeout.head = NULL;
2031 ret = hrtimer_try_to_cancel(&io->timer);
2033 io_cqring_fill_event(link, -ECANCELED);
2034 io_commit_cqring(ctx);
2038 req->flags &= ~REQ_F_LINK_TIMEOUT;
2039 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2042 io_cqring_ev_posted(ctx);
2048 static void io_fail_links(struct io_kiocb *req)
2050 struct io_kiocb *link, *nxt;
2051 struct io_ring_ctx *ctx = req->ctx;
2052 unsigned long flags;
2054 spin_lock_irqsave(&ctx->completion_lock, flags);
2062 trace_io_uring_fail_link(req, link);
2063 io_cqring_fill_event(link, -ECANCELED);
2066 * It's ok to free under spinlock as they're not linked anymore,
2067 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
2070 if (link->flags & REQ_F_WORK_INITIALIZED)
2071 io_put_req_deferred(link, 2);
2073 io_double_put_req(link);
2076 io_commit_cqring(ctx);
2077 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2079 io_cqring_ev_posted(ctx);
2082 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2084 if (req->flags & REQ_F_LINK_TIMEOUT)
2085 io_kill_linked_timeout(req);
2088 * If LINK is set, we have dependent requests in this chain. If we
2089 * didn't fail this request, queue the first one up, moving any other
2090 * dependencies to the next request. In case of failure, fail the rest
2093 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
2094 struct io_kiocb *nxt = req->link;
2103 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2105 if (likely(!(req->link) && !(req->flags & REQ_F_LINK_TIMEOUT)))
2107 return __io_req_find_next(req);
2110 static int io_req_task_work_add(struct io_kiocb *req)
2112 struct task_struct *tsk = req->task;
2113 struct io_ring_ctx *ctx = req->ctx;
2114 enum task_work_notify_mode notify;
2117 if (tsk->flags & PF_EXITING)
2121 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2122 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2123 * processing task_work. There's no reliable way to tell if TWA_RESUME
2127 if (!(ctx->flags & IORING_SETUP_SQPOLL))
2128 notify = TWA_SIGNAL;
2130 ret = task_work_add(tsk, &req->task_work, notify);
2132 wake_up_process(tsk);
2137 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2139 struct io_ring_ctx *ctx = req->ctx;
2141 spin_lock_irq(&ctx->completion_lock);
2142 io_cqring_fill_event(req, error);
2143 io_commit_cqring(ctx);
2144 spin_unlock_irq(&ctx->completion_lock);
2146 io_cqring_ev_posted(ctx);
2147 req_set_fail_links(req);
2148 io_double_put_req(req);
2151 static void io_req_task_cancel(struct callback_head *cb)
2153 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2154 struct io_ring_ctx *ctx = req->ctx;
2156 __io_req_task_cancel(req, -ECANCELED);
2157 percpu_ref_put(&ctx->refs);
2160 static void __io_req_task_submit(struct io_kiocb *req)
2162 struct io_ring_ctx *ctx = req->ctx;
2165 fail = __io_sq_thread_acquire_mm(ctx) ||
2166 __io_sq_thread_acquire_files(ctx);
2167 mutex_lock(&ctx->uring_lock);
2169 __io_queue_sqe(req, NULL);
2171 __io_req_task_cancel(req, -EFAULT);
2172 mutex_unlock(&ctx->uring_lock);
2175 static void io_req_task_submit(struct callback_head *cb)
2177 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2178 struct io_ring_ctx *ctx = req->ctx;
2180 __io_req_task_submit(req);
2181 percpu_ref_put(&ctx->refs);
2184 static void io_req_task_queue(struct io_kiocb *req)
2188 init_task_work(&req->task_work, io_req_task_submit);
2189 percpu_ref_get(&req->ctx->refs);
2191 ret = io_req_task_work_add(req);
2192 if (unlikely(ret)) {
2193 struct task_struct *tsk;
2195 init_task_work(&req->task_work, io_req_task_cancel);
2196 tsk = io_wq_get_task(req->ctx->io_wq);
2197 task_work_add(tsk, &req->task_work, TWA_NONE);
2198 wake_up_process(tsk);
2202 static inline void io_queue_next(struct io_kiocb *req)
2204 struct io_kiocb *nxt = io_req_find_next(req);
2207 io_req_task_queue(nxt);
2210 static void io_free_req(struct io_kiocb *req)
2217 void *reqs[IO_IOPOLL_BATCH];
2220 struct task_struct *task;
2224 static inline void io_init_req_batch(struct req_batch *rb)
2231 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
2232 struct req_batch *rb)
2234 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
2235 percpu_ref_put_many(&ctx->refs, rb->to_free);
2239 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2240 struct req_batch *rb)
2243 __io_req_free_batch_flush(ctx, rb);
2245 struct io_uring_task *tctx = rb->task->io_uring;
2247 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2248 put_task_struct_many(rb->task, rb->task_refs);
2253 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
2255 if (unlikely(io_is_fallback_req(req))) {
2261 if (req->task != rb->task) {
2263 struct io_uring_task *tctx = rb->task->io_uring;
2265 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2266 put_task_struct_many(rb->task, rb->task_refs);
2268 rb->task = req->task;
2273 io_dismantle_req(req);
2274 rb->reqs[rb->to_free++] = req;
2275 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
2276 __io_req_free_batch_flush(req->ctx, rb);
2280 * Drop reference to request, return next in chain (if there is one) if this
2281 * was the last reference to this request.
2283 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2285 struct io_kiocb *nxt = NULL;
2287 if (refcount_dec_and_test(&req->refs)) {
2288 nxt = io_req_find_next(req);
2294 static void io_put_req(struct io_kiocb *req)
2296 if (refcount_dec_and_test(&req->refs))
2300 static void io_put_req_deferred_cb(struct callback_head *cb)
2302 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2307 static void io_free_req_deferred(struct io_kiocb *req)
2311 init_task_work(&req->task_work, io_put_req_deferred_cb);
2312 ret = io_req_task_work_add(req);
2313 if (unlikely(ret)) {
2314 struct task_struct *tsk;
2316 tsk = io_wq_get_task(req->ctx->io_wq);
2317 task_work_add(tsk, &req->task_work, TWA_NONE);
2318 wake_up_process(tsk);
2322 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2324 if (refcount_sub_and_test(refs, &req->refs))
2325 io_free_req_deferred(req);
2328 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
2330 struct io_kiocb *nxt;
2333 * A ref is owned by io-wq in which context we're. So, if that's the
2334 * last one, it's safe to steal next work. False negatives are Ok,
2335 * it just will be re-punted async in io_put_work()
2337 if (refcount_read(&req->refs) != 1)
2340 nxt = io_req_find_next(req);
2341 return nxt ? &nxt->work : NULL;
2344 static void io_double_put_req(struct io_kiocb *req)
2346 /* drop both submit and complete references */
2347 if (refcount_sub_and_test(2, &req->refs))
2351 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2353 /* See comment at the top of this file */
2355 return __io_cqring_events(ctx);
2358 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2360 struct io_rings *rings = ctx->rings;
2362 /* make sure SQ entry isn't read before tail */
2363 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2366 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2368 unsigned int cflags;
2370 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2371 cflags |= IORING_CQE_F_BUFFER;
2372 req->flags &= ~REQ_F_BUFFER_SELECTED;
2377 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2379 struct io_buffer *kbuf;
2381 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2382 return io_put_kbuf(req, kbuf);
2385 static inline bool io_run_task_work(void)
2388 * Not safe to run on exiting task, and the task_work handling will
2389 * not add work to such a task.
2391 if (unlikely(current->flags & PF_EXITING))
2393 if (current->task_works) {
2394 __set_current_state(TASK_RUNNING);
2402 static void io_iopoll_queue(struct list_head *again)
2404 struct io_kiocb *req;
2407 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2408 list_del(&req->inflight_entry);
2409 __io_complete_rw(req, -EAGAIN, 0, NULL);
2410 } while (!list_empty(again));
2414 * Find and free completed poll iocbs
2416 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2417 struct list_head *done)
2419 struct req_batch rb;
2420 struct io_kiocb *req;
2423 /* order with ->result store in io_complete_rw_iopoll() */
2426 io_init_req_batch(&rb);
2427 while (!list_empty(done)) {
2430 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2431 if (READ_ONCE(req->result) == -EAGAIN) {
2433 req->iopoll_completed = 0;
2434 list_move_tail(&req->inflight_entry, &again);
2437 list_del(&req->inflight_entry);
2439 if (req->flags & REQ_F_BUFFER_SELECTED)
2440 cflags = io_put_rw_kbuf(req);
2442 __io_cqring_fill_event(req, req->result, cflags);
2445 if (refcount_dec_and_test(&req->refs))
2446 io_req_free_batch(&rb, req);
2449 io_commit_cqring(ctx);
2450 io_cqring_ev_posted_iopoll(ctx);
2451 io_req_free_batch_finish(ctx, &rb);
2453 if (!list_empty(&again))
2454 io_iopoll_queue(&again);
2457 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2460 struct io_kiocb *req, *tmp;
2466 * Only spin for completions if we don't have multiple devices hanging
2467 * off our complete list, and we're under the requested amount.
2469 spin = !ctx->poll_multi_file && *nr_events < min;
2472 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2473 struct kiocb *kiocb = &req->rw.kiocb;
2476 * Move completed and retryable entries to our local lists.
2477 * If we find a request that requires polling, break out
2478 * and complete those lists first, if we have entries there.
2480 if (READ_ONCE(req->iopoll_completed)) {
2481 list_move_tail(&req->inflight_entry, &done);
2484 if (!list_empty(&done))
2487 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2491 /* iopoll may have completed current req */
2492 if (READ_ONCE(req->iopoll_completed))
2493 list_move_tail(&req->inflight_entry, &done);
2500 if (!list_empty(&done))
2501 io_iopoll_complete(ctx, nr_events, &done);
2507 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2508 * non-spinning poll check - we'll still enter the driver poll loop, but only
2509 * as a non-spinning completion check.
2511 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2514 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2517 ret = io_do_iopoll(ctx, nr_events, min);
2520 if (*nr_events >= min)
2528 * We can't just wait for polled events to come to us, we have to actively
2529 * find and complete them.
2531 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2533 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2536 mutex_lock(&ctx->uring_lock);
2537 while (!list_empty(&ctx->iopoll_list)) {
2538 unsigned int nr_events = 0;
2540 io_do_iopoll(ctx, &nr_events, 0);
2542 /* let it sleep and repeat later if can't complete a request */
2546 * Ensure we allow local-to-the-cpu processing to take place,
2547 * in this case we need to ensure that we reap all events.
2548 * Also let task_work, etc. to progress by releasing the mutex
2550 if (need_resched()) {
2551 mutex_unlock(&ctx->uring_lock);
2553 mutex_lock(&ctx->uring_lock);
2556 mutex_unlock(&ctx->uring_lock);
2559 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2561 unsigned int nr_events = 0;
2562 int iters = 0, ret = 0;
2565 * We disallow the app entering submit/complete with polling, but we
2566 * still need to lock the ring to prevent racing with polled issue
2567 * that got punted to a workqueue.
2569 mutex_lock(&ctx->uring_lock);
2572 * Don't enter poll loop if we already have events pending.
2573 * If we do, we can potentially be spinning for commands that
2574 * already triggered a CQE (eg in error).
2576 if (test_bit(0, &ctx->cq_check_overflow))
2577 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2578 if (io_cqring_events(ctx))
2582 * If a submit got punted to a workqueue, we can have the
2583 * application entering polling for a command before it gets
2584 * issued. That app will hold the uring_lock for the duration
2585 * of the poll right here, so we need to take a breather every
2586 * now and then to ensure that the issue has a chance to add
2587 * the poll to the issued list. Otherwise we can spin here
2588 * forever, while the workqueue is stuck trying to acquire the
2591 if (!(++iters & 7)) {
2592 mutex_unlock(&ctx->uring_lock);
2594 mutex_lock(&ctx->uring_lock);
2597 ret = io_iopoll_getevents(ctx, &nr_events, min);
2601 } while (min && !nr_events && !need_resched());
2603 mutex_unlock(&ctx->uring_lock);
2607 static void kiocb_end_write(struct io_kiocb *req)
2610 * Tell lockdep we inherited freeze protection from submission
2613 if (req->flags & REQ_F_ISREG) {
2614 struct inode *inode = file_inode(req->file);
2616 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2618 file_end_write(req->file);
2621 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2622 struct io_comp_state *cs)
2624 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2627 if (kiocb->ki_flags & IOCB_WRITE)
2628 kiocb_end_write(req);
2630 if (res != req->result)
2631 req_set_fail_links(req);
2632 if (req->flags & REQ_F_BUFFER_SELECTED)
2633 cflags = io_put_rw_kbuf(req);
2634 __io_req_complete(req, res, cflags, cs);
2638 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2640 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2641 ssize_t ret = -ECANCELED;
2642 struct iov_iter iter;
2650 switch (req->opcode) {
2651 case IORING_OP_READV:
2652 case IORING_OP_READ_FIXED:
2653 case IORING_OP_READ:
2656 case IORING_OP_WRITEV:
2657 case IORING_OP_WRITE_FIXED:
2658 case IORING_OP_WRITE:
2662 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2667 if (!req->async_data) {
2668 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2671 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2679 req_set_fail_links(req);
2684 static bool io_rw_reissue(struct io_kiocb *req, long res)
2687 umode_t mode = file_inode(req->file)->i_mode;
2690 if (!S_ISBLK(mode) && !S_ISREG(mode))
2692 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2695 ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2697 if (io_resubmit_prep(req, ret)) {
2698 refcount_inc(&req->refs);
2699 io_queue_async_work(req);
2707 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2708 struct io_comp_state *cs)
2710 if (!io_rw_reissue(req, res))
2711 io_complete_rw_common(&req->rw.kiocb, res, cs);
2714 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2716 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2718 __io_complete_rw(req, res, res2, NULL);
2721 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2723 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2725 if (kiocb->ki_flags & IOCB_WRITE)
2726 kiocb_end_write(req);
2728 if (res != -EAGAIN && res != req->result)
2729 req_set_fail_links(req);
2731 WRITE_ONCE(req->result, res);
2732 /* order with io_poll_complete() checking ->result */
2734 WRITE_ONCE(req->iopoll_completed, 1);
2738 * After the iocb has been issued, it's safe to be found on the poll list.
2739 * Adding the kiocb to the list AFTER submission ensures that we don't
2740 * find it from a io_iopoll_getevents() thread before the issuer is done
2741 * accessing the kiocb cookie.
2743 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2745 struct io_ring_ctx *ctx = req->ctx;
2748 * Track whether we have multiple files in our lists. This will impact
2749 * how we do polling eventually, not spinning if we're on potentially
2750 * different devices.
2752 if (list_empty(&ctx->iopoll_list)) {
2753 ctx->poll_multi_file = false;
2754 } else if (!ctx->poll_multi_file) {
2755 struct io_kiocb *list_req;
2757 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2759 if (list_req->file != req->file)
2760 ctx->poll_multi_file = true;
2764 * For fast devices, IO may have already completed. If it has, add
2765 * it to the front so we find it first.
2767 if (READ_ONCE(req->iopoll_completed))
2768 list_add(&req->inflight_entry, &ctx->iopoll_list);
2770 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2773 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2774 * task context or in io worker task context. If current task context is
2775 * sq thread, we don't need to check whether should wake up sq thread.
2777 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2778 wq_has_sleeper(&ctx->sq_data->wait))
2779 wake_up(&ctx->sq_data->wait);
2782 static inline void __io_state_file_put(struct io_submit_state *state)
2784 fput_many(state->file, state->file_refs);
2785 state->file_refs = 0;
2788 static inline void io_state_file_put(struct io_submit_state *state)
2790 if (state->file_refs)
2791 __io_state_file_put(state);
2795 * Get as many references to a file as we have IOs left in this submission,
2796 * assuming most submissions are for one file, or at least that each file
2797 * has more than one submission.
2799 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2804 if (state->file_refs) {
2805 if (state->fd == fd) {
2809 __io_state_file_put(state);
2811 state->file = fget_many(fd, state->ios_left);
2812 if (unlikely(!state->file))
2816 state->file_refs = state->ios_left - 1;
2820 static bool io_bdev_nowait(struct block_device *bdev)
2822 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2826 * If we tracked the file through the SCM inflight mechanism, we could support
2827 * any file. For now, just ensure that anything potentially problematic is done
2830 static bool io_file_supports_async(struct file *file, int rw)
2832 umode_t mode = file_inode(file)->i_mode;
2834 if (S_ISBLK(mode)) {
2835 if (IS_ENABLED(CONFIG_BLOCK) &&
2836 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2840 if (S_ISCHR(mode) || S_ISSOCK(mode))
2842 if (S_ISREG(mode)) {
2843 if (IS_ENABLED(CONFIG_BLOCK) &&
2844 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2845 file->f_op != &io_uring_fops)
2850 /* any ->read/write should understand O_NONBLOCK */
2851 if (file->f_flags & O_NONBLOCK)
2854 if (!(file->f_mode & FMODE_NOWAIT))
2858 return file->f_op->read_iter != NULL;
2860 return file->f_op->write_iter != NULL;
2863 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2865 struct io_ring_ctx *ctx = req->ctx;
2866 struct kiocb *kiocb = &req->rw.kiocb;
2870 if (S_ISREG(file_inode(req->file)->i_mode))
2871 req->flags |= REQ_F_ISREG;
2873 kiocb->ki_pos = READ_ONCE(sqe->off);
2874 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2875 req->flags |= REQ_F_CUR_POS;
2876 kiocb->ki_pos = req->file->f_pos;
2878 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2879 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2880 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2884 ioprio = READ_ONCE(sqe->ioprio);
2886 ret = ioprio_check_cap(ioprio);
2890 kiocb->ki_ioprio = ioprio;
2892 kiocb->ki_ioprio = get_current_ioprio();
2894 /* don't allow async punt if RWF_NOWAIT was requested */
2895 if (kiocb->ki_flags & IOCB_NOWAIT)
2896 req->flags |= REQ_F_NOWAIT;
2898 if (ctx->flags & IORING_SETUP_IOPOLL) {
2899 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2900 !kiocb->ki_filp->f_op->iopoll)
2903 kiocb->ki_flags |= IOCB_HIPRI;
2904 kiocb->ki_complete = io_complete_rw_iopoll;
2905 req->iopoll_completed = 0;
2907 if (kiocb->ki_flags & IOCB_HIPRI)
2909 kiocb->ki_complete = io_complete_rw;
2912 req->rw.addr = READ_ONCE(sqe->addr);
2913 req->rw.len = READ_ONCE(sqe->len);
2914 req->buf_index = READ_ONCE(sqe->buf_index);
2918 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2924 case -ERESTARTNOINTR:
2925 case -ERESTARTNOHAND:
2926 case -ERESTART_RESTARTBLOCK:
2928 * We can't just restart the syscall, since previously
2929 * submitted sqes may already be in progress. Just fail this
2935 kiocb->ki_complete(kiocb, ret, 0);
2939 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2940 struct io_comp_state *cs)
2942 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2943 struct io_async_rw *io = req->async_data;
2945 /* add previously done IO, if any */
2946 if (io && io->bytes_done > 0) {
2948 ret = io->bytes_done;
2950 ret += io->bytes_done;
2953 if (req->flags & REQ_F_CUR_POS)
2954 req->file->f_pos = kiocb->ki_pos;
2955 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2956 __io_complete_rw(req, ret, 0, cs);
2958 io_rw_done(kiocb, ret);
2961 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2962 struct iov_iter *iter)
2964 struct io_ring_ctx *ctx = req->ctx;
2965 size_t len = req->rw.len;
2966 struct io_mapped_ubuf *imu;
2967 u16 index, buf_index = req->buf_index;
2971 if (unlikely(buf_index >= ctx->nr_user_bufs))
2973 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2974 imu = &ctx->user_bufs[index];
2975 buf_addr = req->rw.addr;
2978 if (buf_addr + len < buf_addr)
2980 /* not inside the mapped region */
2981 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2985 * May not be a start of buffer, set size appropriately
2986 * and advance us to the beginning.
2988 offset = buf_addr - imu->ubuf;
2989 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2993 * Don't use iov_iter_advance() here, as it's really slow for
2994 * using the latter parts of a big fixed buffer - it iterates
2995 * over each segment manually. We can cheat a bit here, because
2998 * 1) it's a BVEC iter, we set it up
2999 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3000 * first and last bvec
3002 * So just find our index, and adjust the iterator afterwards.
3003 * If the offset is within the first bvec (or the whole first
3004 * bvec, just use iov_iter_advance(). This makes it easier
3005 * since we can just skip the first segment, which may not
3006 * be PAGE_SIZE aligned.
3008 const struct bio_vec *bvec = imu->bvec;
3010 if (offset <= bvec->bv_len) {
3011 iov_iter_advance(iter, offset);
3013 unsigned long seg_skip;
3015 /* skip first vec */
3016 offset -= bvec->bv_len;
3017 seg_skip = 1 + (offset >> PAGE_SHIFT);
3019 iter->bvec = bvec + seg_skip;
3020 iter->nr_segs -= seg_skip;
3021 iter->count -= bvec->bv_len + offset;
3022 iter->iov_offset = offset & ~PAGE_MASK;
3029 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3032 mutex_unlock(&ctx->uring_lock);
3035 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3038 * "Normal" inline submissions always hold the uring_lock, since we
3039 * grab it from the system call. Same is true for the SQPOLL offload.
3040 * The only exception is when we've detached the request and issue it
3041 * from an async worker thread, grab the lock for that case.
3044 mutex_lock(&ctx->uring_lock);
3047 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3048 int bgid, struct io_buffer *kbuf,
3051 struct io_buffer *head;
3053 if (req->flags & REQ_F_BUFFER_SELECTED)
3056 io_ring_submit_lock(req->ctx, needs_lock);
3058 lockdep_assert_held(&req->ctx->uring_lock);
3060 head = idr_find(&req->ctx->io_buffer_idr, bgid);
3062 if (!list_empty(&head->list)) {
3063 kbuf = list_last_entry(&head->list, struct io_buffer,
3065 list_del(&kbuf->list);
3068 idr_remove(&req->ctx->io_buffer_idr, bgid);
3070 if (*len > kbuf->len)
3073 kbuf = ERR_PTR(-ENOBUFS);
3076 io_ring_submit_unlock(req->ctx, needs_lock);
3081 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3084 struct io_buffer *kbuf;
3087 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3088 bgid = req->buf_index;
3089 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3092 req->rw.addr = (u64) (unsigned long) kbuf;
3093 req->flags |= REQ_F_BUFFER_SELECTED;
3094 return u64_to_user_ptr(kbuf->addr);
3097 #ifdef CONFIG_COMPAT
3098 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3101 struct compat_iovec __user *uiov;
3102 compat_ssize_t clen;
3106 uiov = u64_to_user_ptr(req->rw.addr);
3107 if (!access_ok(uiov, sizeof(*uiov)))
3109 if (__get_user(clen, &uiov->iov_len))
3115 buf = io_rw_buffer_select(req, &len, needs_lock);
3117 return PTR_ERR(buf);
3118 iov[0].iov_base = buf;
3119 iov[0].iov_len = (compat_size_t) len;
3124 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3127 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3131 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3134 len = iov[0].iov_len;
3137 buf = io_rw_buffer_select(req, &len, needs_lock);
3139 return PTR_ERR(buf);
3140 iov[0].iov_base = buf;
3141 iov[0].iov_len = len;
3145 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3148 if (req->flags & REQ_F_BUFFER_SELECTED) {
3149 struct io_buffer *kbuf;
3151 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3152 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3153 iov[0].iov_len = kbuf->len;
3156 if (req->rw.len != 1)
3159 #ifdef CONFIG_COMPAT
3160 if (req->ctx->compat)
3161 return io_compat_import(req, iov, needs_lock);
3164 return __io_iov_buffer_select(req, iov, needs_lock);
3167 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
3168 struct iovec **iovec, struct iov_iter *iter,
3171 void __user *buf = u64_to_user_ptr(req->rw.addr);
3172 size_t sqe_len = req->rw.len;
3176 opcode = req->opcode;
3177 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3179 return io_import_fixed(req, rw, iter);
3182 /* buffer index only valid with fixed read/write, or buffer select */
3183 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3186 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3187 if (req->flags & REQ_F_BUFFER_SELECT) {
3188 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3190 return PTR_ERR(buf);
3191 req->rw.len = sqe_len;
3194 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3199 if (req->flags & REQ_F_BUFFER_SELECT) {
3200 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3202 ret = (*iovec)->iov_len;
3203 iov_iter_init(iter, rw, *iovec, 1, ret);
3209 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3213 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3215 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3219 * For files that don't have ->read_iter() and ->write_iter(), handle them
3220 * by looping over ->read() or ->write() manually.
3222 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3224 struct kiocb *kiocb = &req->rw.kiocb;
3225 struct file *file = req->file;
3229 * Don't support polled IO through this interface, and we can't
3230 * support non-blocking either. For the latter, this just causes
3231 * the kiocb to be handled from an async context.
3233 if (kiocb->ki_flags & IOCB_HIPRI)
3235 if (kiocb->ki_flags & IOCB_NOWAIT)
3238 while (iov_iter_count(iter)) {
3242 if (!iov_iter_is_bvec(iter)) {
3243 iovec = iov_iter_iovec(iter);
3245 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3246 iovec.iov_len = req->rw.len;
3250 nr = file->f_op->read(file, iovec.iov_base,
3251 iovec.iov_len, io_kiocb_ppos(kiocb));
3253 nr = file->f_op->write(file, iovec.iov_base,
3254 iovec.iov_len, io_kiocb_ppos(kiocb));
3263 if (nr != iovec.iov_len)
3267 iov_iter_advance(iter, nr);
3273 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3274 const struct iovec *fast_iov, struct iov_iter *iter)
3276 struct io_async_rw *rw = req->async_data;
3278 memcpy(&rw->iter, iter, sizeof(*iter));
3279 rw->free_iovec = iovec;
3281 /* can only be fixed buffers, no need to do anything */
3282 if (iov_iter_is_bvec(iter))
3285 unsigned iov_off = 0;
3287 rw->iter.iov = rw->fast_iov;
3288 if (iter->iov != fast_iov) {
3289 iov_off = iter->iov - fast_iov;
3290 rw->iter.iov += iov_off;
3292 if (rw->fast_iov != fast_iov)
3293 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3294 sizeof(struct iovec) * iter->nr_segs);
3296 req->flags |= REQ_F_NEED_CLEANUP;
3300 static inline int __io_alloc_async_data(struct io_kiocb *req)
3302 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3303 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3304 return req->async_data == NULL;
3307 static int io_alloc_async_data(struct io_kiocb *req)
3309 if (!io_op_defs[req->opcode].needs_async_data)
3312 return __io_alloc_async_data(req);
3315 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3316 const struct iovec *fast_iov,
3317 struct iov_iter *iter, bool force)
3319 if (!force && !io_op_defs[req->opcode].needs_async_data)
3321 if (!req->async_data) {
3322 if (__io_alloc_async_data(req))
3325 io_req_map_rw(req, iovec, fast_iov, iter);
3330 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3332 struct io_async_rw *iorw = req->async_data;
3333 struct iovec *iov = iorw->fast_iov;
3336 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3337 if (unlikely(ret < 0))
3340 iorw->bytes_done = 0;
3341 iorw->free_iovec = iov;
3343 req->flags |= REQ_F_NEED_CLEANUP;
3347 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3351 ret = io_prep_rw(req, sqe);
3355 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3358 /* either don't need iovec imported or already have it */
3359 if (!req->async_data)
3361 return io_rw_prep_async(req, READ);
3365 * This is our waitqueue callback handler, registered through lock_page_async()
3366 * when we initially tried to do the IO with the iocb armed our waitqueue.
3367 * This gets called when the page is unlocked, and we generally expect that to
3368 * happen when the page IO is completed and the page is now uptodate. This will
3369 * queue a task_work based retry of the operation, attempting to copy the data
3370 * again. If the latter fails because the page was NOT uptodate, then we will
3371 * do a thread based blocking retry of the operation. That's the unexpected
3374 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3375 int sync, void *arg)
3377 struct wait_page_queue *wpq;
3378 struct io_kiocb *req = wait->private;
3379 struct wait_page_key *key = arg;
3382 wpq = container_of(wait, struct wait_page_queue, wait);
3384 if (!wake_page_match(wpq, key))
3387 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3388 list_del_init(&wait->entry);
3390 init_task_work(&req->task_work, io_req_task_submit);
3391 percpu_ref_get(&req->ctx->refs);
3393 /* submit ref gets dropped, acquire a new one */
3394 refcount_inc(&req->refs);
3395 ret = io_req_task_work_add(req);
3396 if (unlikely(ret)) {
3397 struct task_struct *tsk;
3399 /* queue just for cancelation */
3400 init_task_work(&req->task_work, io_req_task_cancel);
3401 tsk = io_wq_get_task(req->ctx->io_wq);
3402 task_work_add(tsk, &req->task_work, TWA_NONE);
3403 wake_up_process(tsk);
3409 * This controls whether a given IO request should be armed for async page
3410 * based retry. If we return false here, the request is handed to the async
3411 * worker threads for retry. If we're doing buffered reads on a regular file,
3412 * we prepare a private wait_page_queue entry and retry the operation. This
3413 * will either succeed because the page is now uptodate and unlocked, or it
3414 * will register a callback when the page is unlocked at IO completion. Through
3415 * that callback, io_uring uses task_work to setup a retry of the operation.
3416 * That retry will attempt the buffered read again. The retry will generally
3417 * succeed, or in rare cases where it fails, we then fall back to using the
3418 * async worker threads for a blocking retry.
3420 static bool io_rw_should_retry(struct io_kiocb *req)
3422 struct io_async_rw *rw = req->async_data;
3423 struct wait_page_queue *wait = &rw->wpq;
3424 struct kiocb *kiocb = &req->rw.kiocb;
3426 /* never retry for NOWAIT, we just complete with -EAGAIN */
3427 if (req->flags & REQ_F_NOWAIT)
3430 /* Only for buffered IO */
3431 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3435 * just use poll if we can, and don't attempt if the fs doesn't
3436 * support callback based unlocks
3438 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3441 wait->wait.func = io_async_buf_func;
3442 wait->wait.private = req;
3443 wait->wait.flags = 0;
3444 INIT_LIST_HEAD(&wait->wait.entry);
3445 kiocb->ki_flags |= IOCB_WAITQ;
3446 kiocb->ki_flags &= ~IOCB_NOWAIT;
3447 kiocb->ki_waitq = wait;
3451 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3453 if (req->file->f_op->read_iter)
3454 return call_read_iter(req->file, &req->rw.kiocb, iter);
3455 else if (req->file->f_op->read)
3456 return loop_rw_iter(READ, req, iter);
3461 static int io_read(struct io_kiocb *req, bool force_nonblock,
3462 struct io_comp_state *cs)
3464 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3465 struct kiocb *kiocb = &req->rw.kiocb;
3466 struct iov_iter __iter, *iter = &__iter;
3467 struct io_async_rw *rw = req->async_data;
3468 ssize_t io_size, ret, ret2;
3475 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3479 io_size = iov_iter_count(iter);
3480 req->result = io_size;
3483 /* Ensure we clear previously set non-block flag */
3484 if (!force_nonblock)
3485 kiocb->ki_flags &= ~IOCB_NOWAIT;
3487 kiocb->ki_flags |= IOCB_NOWAIT;
3490 /* If the file doesn't support async, just async punt */
3491 no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3495 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3499 ret = io_iter_do_read(req, iter);
3503 } else if (ret == -EIOCBQUEUED) {
3506 } else if (ret == -EAGAIN) {
3507 /* IOPOLL retry should happen for io-wq threads */
3508 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3510 /* no retry on NONBLOCK marked file */
3511 if (req->file->f_flags & O_NONBLOCK)
3513 /* some cases will consume bytes even on error returns */
3514 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3517 } else if (ret < 0) {
3518 /* make sure -ERESTARTSYS -> -EINTR is done */
3522 /* read it all, or we did blocking attempt. no retry. */
3523 if (!iov_iter_count(iter) || !force_nonblock ||
3524 (req->file->f_flags & O_NONBLOCK))
3529 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3536 rw = req->async_data;
3537 /* it's copied and will be cleaned with ->io */
3539 /* now use our persistent iterator, if we aren't already */
3542 rw->bytes_done += ret;
3543 /* if we can retry, do so with the callbacks armed */
3544 if (!io_rw_should_retry(req)) {
3545 kiocb->ki_flags &= ~IOCB_WAITQ;
3550 * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3551 * get -EIOCBQUEUED, then we'll get a notification when the desired
3552 * page gets unlocked. We can also get a partial read here, and if we
3553 * do, then just retry at the new offset.
3555 ret = io_iter_do_read(req, iter);
3556 if (ret == -EIOCBQUEUED) {
3559 } else if (ret > 0 && ret < io_size) {
3560 /* we got some bytes, but not all. retry. */
3564 kiocb_done(kiocb, ret, cs);
3567 /* it's reportedly faster than delegating the null check to kfree() */
3573 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3577 ret = io_prep_rw(req, sqe);
3581 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3584 /* either don't need iovec imported or already have it */
3585 if (!req->async_data)
3587 return io_rw_prep_async(req, WRITE);
3590 static int io_write(struct io_kiocb *req, bool force_nonblock,
3591 struct io_comp_state *cs)
3593 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3594 struct kiocb *kiocb = &req->rw.kiocb;
3595 struct iov_iter __iter, *iter = &__iter;
3596 struct io_async_rw *rw = req->async_data;
3597 ssize_t ret, ret2, io_size;
3603 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3607 io_size = iov_iter_count(iter);
3608 req->result = io_size;
3610 /* Ensure we clear previously set non-block flag */
3611 if (!force_nonblock)
3612 kiocb->ki_flags &= ~IOCB_NOWAIT;
3614 kiocb->ki_flags |= IOCB_NOWAIT;
3616 /* If the file doesn't support async, just async punt */
3617 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3620 /* file path doesn't support NOWAIT for non-direct_IO */
3621 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3622 (req->flags & REQ_F_ISREG))
3625 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3630 * Open-code file_start_write here to grab freeze protection,
3631 * which will be released by another thread in
3632 * io_complete_rw(). Fool lockdep by telling it the lock got
3633 * released so that it doesn't complain about the held lock when
3634 * we return to userspace.
3636 if (req->flags & REQ_F_ISREG) {
3637 sb_start_write(file_inode(req->file)->i_sb);
3638 __sb_writers_release(file_inode(req->file)->i_sb,
3641 kiocb->ki_flags |= IOCB_WRITE;
3643 if (req->file->f_op->write_iter)
3644 ret2 = call_write_iter(req->file, kiocb, iter);
3645 else if (req->file->f_op->write)
3646 ret2 = loop_rw_iter(WRITE, req, iter);
3651 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3652 * retry them without IOCB_NOWAIT.
3654 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3656 /* no retry on NONBLOCK marked file */
3657 if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3659 if (!force_nonblock || ret2 != -EAGAIN) {
3660 /* IOPOLL retry should happen for io-wq threads */
3661 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3664 kiocb_done(kiocb, ret2, cs);
3667 /* some cases will consume bytes even on error returns */
3668 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3669 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3674 /* it's reportedly faster than delegating the null check to kfree() */
3680 static int io_renameat_prep(struct io_kiocb *req,
3681 const struct io_uring_sqe *sqe)
3683 struct io_rename *ren = &req->rename;
3684 const char __user *oldf, *newf;
3686 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3689 ren->old_dfd = READ_ONCE(sqe->fd);
3690 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3691 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3692 ren->new_dfd = READ_ONCE(sqe->len);
3693 ren->flags = READ_ONCE(sqe->rename_flags);
3695 ren->oldpath = getname(oldf);
3696 if (IS_ERR(ren->oldpath))
3697 return PTR_ERR(ren->oldpath);
3699 ren->newpath = getname(newf);
3700 if (IS_ERR(ren->newpath)) {
3701 putname(ren->oldpath);
3702 return PTR_ERR(ren->newpath);
3705 req->flags |= REQ_F_NEED_CLEANUP;
3709 static int io_renameat(struct io_kiocb *req, bool force_nonblock)
3711 struct io_rename *ren = &req->rename;
3717 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3718 ren->newpath, ren->flags);
3720 req->flags &= ~REQ_F_NEED_CLEANUP;
3722 req_set_fail_links(req);
3723 io_req_complete(req, ret);
3727 static int io_unlinkat_prep(struct io_kiocb *req,
3728 const struct io_uring_sqe *sqe)
3730 struct io_unlink *un = &req->unlink;
3731 const char __user *fname;
3733 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3736 un->dfd = READ_ONCE(sqe->fd);
3738 un->flags = READ_ONCE(sqe->unlink_flags);
3739 if (un->flags & ~AT_REMOVEDIR)
3742 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3743 un->filename = getname(fname);
3744 if (IS_ERR(un->filename))
3745 return PTR_ERR(un->filename);
3747 req->flags |= REQ_F_NEED_CLEANUP;
3751 static int io_unlinkat(struct io_kiocb *req, bool force_nonblock)
3753 struct io_unlink *un = &req->unlink;
3759 if (un->flags & AT_REMOVEDIR)
3760 ret = do_rmdir(un->dfd, un->filename);
3762 ret = do_unlinkat(un->dfd, un->filename);
3764 req->flags &= ~REQ_F_NEED_CLEANUP;
3766 req_set_fail_links(req);
3767 io_req_complete(req, ret);
3771 static int io_shutdown_prep(struct io_kiocb *req,
3772 const struct io_uring_sqe *sqe)
3774 #if defined(CONFIG_NET)
3775 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3777 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3781 req->shutdown.how = READ_ONCE(sqe->len);
3788 static int io_shutdown(struct io_kiocb *req, bool force_nonblock)
3790 #if defined(CONFIG_NET)
3791 struct socket *sock;
3797 sock = sock_from_file(req->file);
3798 if (unlikely(!sock))
3801 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3803 req_set_fail_links(req);
3804 io_req_complete(req, ret);
3811 static int __io_splice_prep(struct io_kiocb *req,
3812 const struct io_uring_sqe *sqe)
3814 struct io_splice* sp = &req->splice;
3815 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3817 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3821 sp->len = READ_ONCE(sqe->len);
3822 sp->flags = READ_ONCE(sqe->splice_flags);
3824 if (unlikely(sp->flags & ~valid_flags))
3827 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3828 (sp->flags & SPLICE_F_FD_IN_FIXED));
3831 req->flags |= REQ_F_NEED_CLEANUP;
3833 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3835 * Splice operation will be punted aync, and here need to
3836 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3838 io_req_init_async(req);
3839 req->work.flags |= IO_WQ_WORK_UNBOUND;
3845 static int io_tee_prep(struct io_kiocb *req,
3846 const struct io_uring_sqe *sqe)
3848 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3850 return __io_splice_prep(req, sqe);
3853 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3855 struct io_splice *sp = &req->splice;
3856 struct file *in = sp->file_in;
3857 struct file *out = sp->file_out;
3858 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3864 ret = do_tee(in, out, sp->len, flags);
3866 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3867 req->flags &= ~REQ_F_NEED_CLEANUP;
3870 req_set_fail_links(req);
3871 io_req_complete(req, ret);
3875 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3877 struct io_splice* sp = &req->splice;
3879 sp->off_in = READ_ONCE(sqe->splice_off_in);
3880 sp->off_out = READ_ONCE(sqe->off);
3881 return __io_splice_prep(req, sqe);
3884 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3886 struct io_splice *sp = &req->splice;
3887 struct file *in = sp->file_in;
3888 struct file *out = sp->file_out;
3889 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3890 loff_t *poff_in, *poff_out;
3896 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3897 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3900 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3902 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3903 req->flags &= ~REQ_F_NEED_CLEANUP;
3906 req_set_fail_links(req);
3907 io_req_complete(req, ret);
3912 * IORING_OP_NOP just posts a completion event, nothing else.
3914 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3916 struct io_ring_ctx *ctx = req->ctx;
3918 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3921 __io_req_complete(req, 0, 0, cs);
3925 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3927 struct io_ring_ctx *ctx = req->ctx;
3932 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3934 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3937 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3938 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3941 req->sync.off = READ_ONCE(sqe->off);
3942 req->sync.len = READ_ONCE(sqe->len);
3946 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3948 loff_t end = req->sync.off + req->sync.len;
3951 /* fsync always requires a blocking context */
3955 ret = vfs_fsync_range(req->file, req->sync.off,
3956 end > 0 ? end : LLONG_MAX,
3957 req->sync.flags & IORING_FSYNC_DATASYNC);
3959 req_set_fail_links(req);
3960 io_req_complete(req, ret);
3964 static int io_fallocate_prep(struct io_kiocb *req,
3965 const struct io_uring_sqe *sqe)
3967 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3969 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3972 req->sync.off = READ_ONCE(sqe->off);
3973 req->sync.len = READ_ONCE(sqe->addr);
3974 req->sync.mode = READ_ONCE(sqe->len);
3978 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3982 /* fallocate always requiring blocking context */
3985 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3988 req_set_fail_links(req);
3989 io_req_complete(req, ret);
3993 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3995 const char __user *fname;
3998 if (unlikely(sqe->ioprio || sqe->buf_index))
4000 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4003 /* open.how should be already initialised */
4004 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4005 req->open.how.flags |= O_LARGEFILE;
4007 req->open.dfd = READ_ONCE(sqe->fd);
4008 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4009 req->open.filename = getname(fname);
4010 if (IS_ERR(req->open.filename)) {
4011 ret = PTR_ERR(req->open.filename);
4012 req->open.filename = NULL;
4015 req->open.nofile = rlimit(RLIMIT_NOFILE);
4016 req->open.ignore_nonblock = false;
4017 req->flags |= REQ_F_NEED_CLEANUP;
4021 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4025 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4027 mode = READ_ONCE(sqe->len);
4028 flags = READ_ONCE(sqe->open_flags);
4029 req->open.how = build_open_how(flags, mode);
4030 return __io_openat_prep(req, sqe);
4033 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4035 struct open_how __user *how;
4039 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4041 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4042 len = READ_ONCE(sqe->len);
4043 if (len < OPEN_HOW_SIZE_VER0)
4046 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4051 return __io_openat_prep(req, sqe);
4054 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
4056 struct open_flags op;
4060 if (force_nonblock && !req->open.ignore_nonblock)
4063 ret = build_open_flags(&req->open.how, &op);
4067 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4071 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4074 ret = PTR_ERR(file);
4076 * A work-around to ensure that /proc/self works that way
4077 * that it should - if we get -EOPNOTSUPP back, then assume
4078 * that proc_self_get_link() failed us because we're in async
4079 * context. We should be safe to retry this from the task
4080 * itself with force_nonblock == false set, as it should not
4081 * block on lookup. Would be nice to know this upfront and
4082 * avoid the async dance, but doesn't seem feasible.
4084 if (ret == -EOPNOTSUPP && io_wq_current_is_worker()) {
4085 req->open.ignore_nonblock = true;
4086 refcount_inc(&req->refs);
4087 io_req_task_queue(req);
4091 fsnotify_open(file);
4092 fd_install(ret, file);
4095 putname(req->open.filename);
4096 req->flags &= ~REQ_F_NEED_CLEANUP;
4098 req_set_fail_links(req);
4099 io_req_complete(req, ret);
4103 static int io_openat(struct io_kiocb *req, bool force_nonblock)
4105 return io_openat2(req, force_nonblock);
4108 static int io_remove_buffers_prep(struct io_kiocb *req,
4109 const struct io_uring_sqe *sqe)
4111 struct io_provide_buf *p = &req->pbuf;
4114 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4117 tmp = READ_ONCE(sqe->fd);
4118 if (!tmp || tmp > USHRT_MAX)
4121 memset(p, 0, sizeof(*p));
4123 p->bgid = READ_ONCE(sqe->buf_group);
4127 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4128 int bgid, unsigned nbufs)
4132 /* shouldn't happen */
4136 /* the head kbuf is the list itself */
4137 while (!list_empty(&buf->list)) {
4138 struct io_buffer *nxt;
4140 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4141 list_del(&nxt->list);
4148 idr_remove(&ctx->io_buffer_idr, bgid);
4153 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
4154 struct io_comp_state *cs)
4156 struct io_provide_buf *p = &req->pbuf;
4157 struct io_ring_ctx *ctx = req->ctx;
4158 struct io_buffer *head;
4161 io_ring_submit_lock(ctx, !force_nonblock);
4163 lockdep_assert_held(&ctx->uring_lock);
4166 head = idr_find(&ctx->io_buffer_idr, p->bgid);
4168 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4170 req_set_fail_links(req);
4172 /* need to hold the lock to complete IOPOLL requests */
4173 if (ctx->flags & IORING_SETUP_IOPOLL) {
4174 __io_req_complete(req, ret, 0, cs);
4175 io_ring_submit_unlock(ctx, !force_nonblock);
4177 io_ring_submit_unlock(ctx, !force_nonblock);
4178 __io_req_complete(req, ret, 0, cs);
4183 static int io_provide_buffers_prep(struct io_kiocb *req,
4184 const struct io_uring_sqe *sqe)
4186 struct io_provide_buf *p = &req->pbuf;
4189 if (sqe->ioprio || sqe->rw_flags)
4192 tmp = READ_ONCE(sqe->fd);
4193 if (!tmp || tmp > USHRT_MAX)
4196 p->addr = READ_ONCE(sqe->addr);
4197 p->len = READ_ONCE(sqe->len);
4199 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4202 p->bgid = READ_ONCE(sqe->buf_group);
4203 tmp = READ_ONCE(sqe->off);
4204 if (tmp > USHRT_MAX)
4210 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4212 struct io_buffer *buf;
4213 u64 addr = pbuf->addr;
4214 int i, bid = pbuf->bid;
4216 for (i = 0; i < pbuf->nbufs; i++) {
4217 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4222 buf->len = pbuf->len;
4227 INIT_LIST_HEAD(&buf->list);
4230 list_add_tail(&buf->list, &(*head)->list);
4234 return i ? i : -ENOMEM;
4237 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
4238 struct io_comp_state *cs)
4240 struct io_provide_buf *p = &req->pbuf;
4241 struct io_ring_ctx *ctx = req->ctx;
4242 struct io_buffer *head, *list;
4245 io_ring_submit_lock(ctx, !force_nonblock);
4247 lockdep_assert_held(&ctx->uring_lock);
4249 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4251 ret = io_add_buffers(p, &head);
4256 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4259 __io_remove_buffers(ctx, head, p->bgid, -1U);
4265 req_set_fail_links(req);
4267 /* need to hold the lock to complete IOPOLL requests */
4268 if (ctx->flags & IORING_SETUP_IOPOLL) {
4269 __io_req_complete(req, ret, 0, cs);
4270 io_ring_submit_unlock(ctx, !force_nonblock);
4272 io_ring_submit_unlock(ctx, !force_nonblock);
4273 __io_req_complete(req, ret, 0, cs);
4278 static int io_epoll_ctl_prep(struct io_kiocb *req,
4279 const struct io_uring_sqe *sqe)
4281 #if defined(CONFIG_EPOLL)
4282 if (sqe->ioprio || sqe->buf_index)
4284 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4287 req->epoll.epfd = READ_ONCE(sqe->fd);
4288 req->epoll.op = READ_ONCE(sqe->len);
4289 req->epoll.fd = READ_ONCE(sqe->off);
4291 if (ep_op_has_event(req->epoll.op)) {
4292 struct epoll_event __user *ev;
4294 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4295 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4305 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
4306 struct io_comp_state *cs)
4308 #if defined(CONFIG_EPOLL)
4309 struct io_epoll *ie = &req->epoll;
4312 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4313 if (force_nonblock && ret == -EAGAIN)
4317 req_set_fail_links(req);
4318 __io_req_complete(req, ret, 0, cs);
4325 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4327 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4328 if (sqe->ioprio || sqe->buf_index || sqe->off)
4330 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4333 req->madvise.addr = READ_ONCE(sqe->addr);
4334 req->madvise.len = READ_ONCE(sqe->len);
4335 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4342 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
4344 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4345 struct io_madvise *ma = &req->madvise;
4351 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4353 req_set_fail_links(req);
4354 io_req_complete(req, ret);
4361 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4363 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4365 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4368 req->fadvise.offset = READ_ONCE(sqe->off);
4369 req->fadvise.len = READ_ONCE(sqe->len);
4370 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4374 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
4376 struct io_fadvise *fa = &req->fadvise;
4379 if (force_nonblock) {
4380 switch (fa->advice) {
4381 case POSIX_FADV_NORMAL:
4382 case POSIX_FADV_RANDOM:
4383 case POSIX_FADV_SEQUENTIAL:
4390 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4392 req_set_fail_links(req);
4393 io_req_complete(req, ret);
4397 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4399 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4401 if (sqe->ioprio || sqe->buf_index)
4403 if (req->flags & REQ_F_FIXED_FILE)
4406 req->statx.dfd = READ_ONCE(sqe->fd);
4407 req->statx.mask = READ_ONCE(sqe->len);
4408 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4409 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4410 req->statx.flags = READ_ONCE(sqe->statx_flags);
4415 static int io_statx(struct io_kiocb *req, bool force_nonblock)
4417 struct io_statx *ctx = &req->statx;
4420 if (force_nonblock) {
4421 /* only need file table for an actual valid fd */
4422 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4423 req->flags |= REQ_F_NO_FILE_TABLE;
4427 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4431 req_set_fail_links(req);
4432 io_req_complete(req, ret);
4436 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4439 * If we queue this for async, it must not be cancellable. That would
4440 * leave the 'file' in an undeterminate state, and here need to modify
4441 * io_wq_work.flags, so initialize io_wq_work firstly.
4443 io_req_init_async(req);
4444 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
4446 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4448 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4449 sqe->rw_flags || sqe->buf_index)
4451 if (req->flags & REQ_F_FIXED_FILE)
4454 req->close.fd = READ_ONCE(sqe->fd);
4455 if ((req->file && req->file->f_op == &io_uring_fops))
4458 req->close.put_file = NULL;
4462 static int io_close(struct io_kiocb *req, bool force_nonblock,
4463 struct io_comp_state *cs)
4465 struct io_close *close = &req->close;
4468 /* might be already done during nonblock submission */
4469 if (!close->put_file) {
4470 ret = close_fd_get_file(close->fd, &close->put_file);
4472 return (ret == -ENOENT) ? -EBADF : ret;
4475 /* if the file has a flush method, be safe and punt to async */
4476 if (close->put_file->f_op->flush && force_nonblock) {
4477 /* was never set, but play safe */
4478 req->flags &= ~REQ_F_NOWAIT;
4479 /* avoid grabbing files - we don't need the files */
4480 req->flags |= REQ_F_NO_FILE_TABLE;
4484 /* No ->flush() or already async, safely close from here */
4485 ret = filp_close(close->put_file, req->work.identity->files);
4487 req_set_fail_links(req);
4488 fput(close->put_file);
4489 close->put_file = NULL;
4490 __io_req_complete(req, ret, 0, cs);
4494 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4496 struct io_ring_ctx *ctx = req->ctx;
4501 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4503 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4506 req->sync.off = READ_ONCE(sqe->off);
4507 req->sync.len = READ_ONCE(sqe->len);
4508 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4512 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
4516 /* sync_file_range always requires a blocking context */
4520 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4523 req_set_fail_links(req);
4524 io_req_complete(req, ret);
4528 #if defined(CONFIG_NET)
4529 static int io_setup_async_msg(struct io_kiocb *req,
4530 struct io_async_msghdr *kmsg)
4532 struct io_async_msghdr *async_msg = req->async_data;
4536 if (io_alloc_async_data(req)) {
4537 if (kmsg->iov != kmsg->fast_iov)
4541 async_msg = req->async_data;
4542 req->flags |= REQ_F_NEED_CLEANUP;
4543 memcpy(async_msg, kmsg, sizeof(*kmsg));
4547 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4548 struct io_async_msghdr *iomsg)
4550 iomsg->iov = iomsg->fast_iov;
4551 iomsg->msg.msg_name = &iomsg->addr;
4552 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4553 req->sr_msg.msg_flags, &iomsg->iov);
4556 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4558 struct io_async_msghdr *async_msg = req->async_data;
4559 struct io_sr_msg *sr = &req->sr_msg;
4562 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4565 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4566 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4567 sr->len = READ_ONCE(sqe->len);
4569 #ifdef CONFIG_COMPAT
4570 if (req->ctx->compat)
4571 sr->msg_flags |= MSG_CMSG_COMPAT;
4574 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4576 ret = io_sendmsg_copy_hdr(req, async_msg);
4578 req->flags |= REQ_F_NEED_CLEANUP;
4582 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4583 struct io_comp_state *cs)
4585 struct io_async_msghdr iomsg, *kmsg;
4586 struct socket *sock;
4590 sock = sock_from_file(req->file);
4591 if (unlikely(!sock))
4594 if (req->async_data) {
4595 kmsg = req->async_data;
4596 kmsg->msg.msg_name = &kmsg->addr;
4597 /* if iov is set, it's allocated already */
4599 kmsg->iov = kmsg->fast_iov;
4600 kmsg->msg.msg_iter.iov = kmsg->iov;
4602 ret = io_sendmsg_copy_hdr(req, &iomsg);
4608 flags = req->sr_msg.msg_flags;
4609 if (flags & MSG_DONTWAIT)
4610 req->flags |= REQ_F_NOWAIT;
4611 else if (force_nonblock)
4612 flags |= MSG_DONTWAIT;
4614 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4615 if (force_nonblock && ret == -EAGAIN)
4616 return io_setup_async_msg(req, kmsg);
4617 if (ret == -ERESTARTSYS)
4620 if (kmsg->iov != kmsg->fast_iov)
4622 req->flags &= ~REQ_F_NEED_CLEANUP;
4624 req_set_fail_links(req);
4625 __io_req_complete(req, ret, 0, cs);
4629 static int io_send(struct io_kiocb *req, bool force_nonblock,
4630 struct io_comp_state *cs)
4632 struct io_sr_msg *sr = &req->sr_msg;
4635 struct socket *sock;
4639 sock = sock_from_file(req->file);
4640 if (unlikely(!sock))
4643 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4647 msg.msg_name = NULL;
4648 msg.msg_control = NULL;
4649 msg.msg_controllen = 0;
4650 msg.msg_namelen = 0;
4652 flags = req->sr_msg.msg_flags;
4653 if (flags & MSG_DONTWAIT)
4654 req->flags |= REQ_F_NOWAIT;
4655 else if (force_nonblock)
4656 flags |= MSG_DONTWAIT;
4658 msg.msg_flags = flags;
4659 ret = sock_sendmsg(sock, &msg);
4660 if (force_nonblock && ret == -EAGAIN)
4662 if (ret == -ERESTARTSYS)
4666 req_set_fail_links(req);
4667 __io_req_complete(req, ret, 0, cs);
4671 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4672 struct io_async_msghdr *iomsg)
4674 struct io_sr_msg *sr = &req->sr_msg;
4675 struct iovec __user *uiov;
4679 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4680 &iomsg->uaddr, &uiov, &iov_len);
4684 if (req->flags & REQ_F_BUFFER_SELECT) {
4687 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4689 sr->len = iomsg->iov[0].iov_len;
4690 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4694 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4695 &iomsg->iov, &iomsg->msg.msg_iter,
4704 #ifdef CONFIG_COMPAT
4705 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4706 struct io_async_msghdr *iomsg)
4708 struct compat_msghdr __user *msg_compat;
4709 struct io_sr_msg *sr = &req->sr_msg;
4710 struct compat_iovec __user *uiov;
4715 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4716 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4721 uiov = compat_ptr(ptr);
4722 if (req->flags & REQ_F_BUFFER_SELECT) {
4723 compat_ssize_t clen;
4727 if (!access_ok(uiov, sizeof(*uiov)))
4729 if (__get_user(clen, &uiov->iov_len))
4734 iomsg->iov[0].iov_len = clen;
4737 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4738 UIO_FASTIOV, &iomsg->iov,
4739 &iomsg->msg.msg_iter, true);
4748 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4749 struct io_async_msghdr *iomsg)
4751 iomsg->msg.msg_name = &iomsg->addr;
4752 iomsg->iov = iomsg->fast_iov;
4754 #ifdef CONFIG_COMPAT
4755 if (req->ctx->compat)
4756 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4759 return __io_recvmsg_copy_hdr(req, iomsg);
4762 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4765 struct io_sr_msg *sr = &req->sr_msg;
4766 struct io_buffer *kbuf;
4768 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4773 req->flags |= REQ_F_BUFFER_SELECTED;
4777 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4779 return io_put_kbuf(req, req->sr_msg.kbuf);
4782 static int io_recvmsg_prep(struct io_kiocb *req,
4783 const struct io_uring_sqe *sqe)
4785 struct io_async_msghdr *async_msg = req->async_data;
4786 struct io_sr_msg *sr = &req->sr_msg;
4789 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4792 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4793 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4794 sr->len = READ_ONCE(sqe->len);
4795 sr->bgid = READ_ONCE(sqe->buf_group);
4797 #ifdef CONFIG_COMPAT
4798 if (req->ctx->compat)
4799 sr->msg_flags |= MSG_CMSG_COMPAT;
4802 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4804 ret = io_recvmsg_copy_hdr(req, async_msg);
4806 req->flags |= REQ_F_NEED_CLEANUP;
4810 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4811 struct io_comp_state *cs)
4813 struct io_async_msghdr iomsg, *kmsg;
4814 struct socket *sock;
4815 struct io_buffer *kbuf;
4817 int ret, cflags = 0;
4819 sock = sock_from_file(req->file);
4820 if (unlikely(!sock))
4823 if (req->async_data) {
4824 kmsg = req->async_data;
4825 kmsg->msg.msg_name = &kmsg->addr;
4826 /* if iov is set, it's allocated already */
4828 kmsg->iov = kmsg->fast_iov;
4829 kmsg->msg.msg_iter.iov = kmsg->iov;
4831 ret = io_recvmsg_copy_hdr(req, &iomsg);
4837 if (req->flags & REQ_F_BUFFER_SELECT) {
4838 kbuf = io_recv_buffer_select(req, !force_nonblock);
4840 return PTR_ERR(kbuf);
4841 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4842 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4843 1, req->sr_msg.len);
4846 flags = req->sr_msg.msg_flags;
4847 if (flags & MSG_DONTWAIT)
4848 req->flags |= REQ_F_NOWAIT;
4849 else if (force_nonblock)
4850 flags |= MSG_DONTWAIT;
4852 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4853 kmsg->uaddr, flags);
4854 if (force_nonblock && ret == -EAGAIN)
4855 return io_setup_async_msg(req, kmsg);
4856 if (ret == -ERESTARTSYS)
4859 if (req->flags & REQ_F_BUFFER_SELECTED)
4860 cflags = io_put_recv_kbuf(req);
4861 if (kmsg->iov != kmsg->fast_iov)
4863 req->flags &= ~REQ_F_NEED_CLEANUP;
4865 req_set_fail_links(req);
4866 __io_req_complete(req, ret, cflags, cs);
4870 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4871 struct io_comp_state *cs)
4873 struct io_buffer *kbuf;
4874 struct io_sr_msg *sr = &req->sr_msg;
4876 void __user *buf = sr->buf;
4877 struct socket *sock;
4880 int ret, cflags = 0;
4882 sock = sock_from_file(req->file);
4883 if (unlikely(!sock))
4886 if (req->flags & REQ_F_BUFFER_SELECT) {
4887 kbuf = io_recv_buffer_select(req, !force_nonblock);
4889 return PTR_ERR(kbuf);
4890 buf = u64_to_user_ptr(kbuf->addr);
4893 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4897 msg.msg_name = NULL;
4898 msg.msg_control = NULL;
4899 msg.msg_controllen = 0;
4900 msg.msg_namelen = 0;
4901 msg.msg_iocb = NULL;
4904 flags = req->sr_msg.msg_flags;
4905 if (flags & MSG_DONTWAIT)
4906 req->flags |= REQ_F_NOWAIT;
4907 else if (force_nonblock)
4908 flags |= MSG_DONTWAIT;
4910 ret = sock_recvmsg(sock, &msg, flags);
4911 if (force_nonblock && ret == -EAGAIN)
4913 if (ret == -ERESTARTSYS)
4916 if (req->flags & REQ_F_BUFFER_SELECTED)
4917 cflags = io_put_recv_kbuf(req);
4919 req_set_fail_links(req);
4920 __io_req_complete(req, ret, cflags, cs);
4924 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4926 struct io_accept *accept = &req->accept;
4928 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4930 if (sqe->ioprio || sqe->len || sqe->buf_index)
4933 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4934 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4935 accept->flags = READ_ONCE(sqe->accept_flags);
4936 accept->nofile = rlimit(RLIMIT_NOFILE);
4940 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4941 struct io_comp_state *cs)
4943 struct io_accept *accept = &req->accept;
4944 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4947 if (req->file->f_flags & O_NONBLOCK)
4948 req->flags |= REQ_F_NOWAIT;
4950 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4951 accept->addr_len, accept->flags,
4953 if (ret == -EAGAIN && force_nonblock)
4956 if (ret == -ERESTARTSYS)
4958 req_set_fail_links(req);
4960 __io_req_complete(req, ret, 0, cs);
4964 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4966 struct io_connect *conn = &req->connect;
4967 struct io_async_connect *io = req->async_data;
4969 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4971 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4974 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4975 conn->addr_len = READ_ONCE(sqe->addr2);
4980 return move_addr_to_kernel(conn->addr, conn->addr_len,
4984 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4985 struct io_comp_state *cs)
4987 struct io_async_connect __io, *io;
4988 unsigned file_flags;
4991 if (req->async_data) {
4992 io = req->async_data;
4994 ret = move_addr_to_kernel(req->connect.addr,
4995 req->connect.addr_len,
5002 file_flags = force_nonblock ? O_NONBLOCK : 0;
5004 ret = __sys_connect_file(req->file, &io->address,
5005 req->connect.addr_len, file_flags);
5006 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5007 if (req->async_data)
5009 if (io_alloc_async_data(req)) {
5013 io = req->async_data;
5014 memcpy(req->async_data, &__io, sizeof(__io));
5017 if (ret == -ERESTARTSYS)
5021 req_set_fail_links(req);
5022 __io_req_complete(req, ret, 0, cs);
5025 #else /* !CONFIG_NET */
5026 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5031 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
5032 struct io_comp_state *cs)
5037 static int io_send(struct io_kiocb *req, bool force_nonblock,
5038 struct io_comp_state *cs)
5043 static int io_recvmsg_prep(struct io_kiocb *req,
5044 const struct io_uring_sqe *sqe)
5049 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
5050 struct io_comp_state *cs)
5055 static int io_recv(struct io_kiocb *req, bool force_nonblock,
5056 struct io_comp_state *cs)
5061 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5066 static int io_accept(struct io_kiocb *req, bool force_nonblock,
5067 struct io_comp_state *cs)
5072 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5077 static int io_connect(struct io_kiocb *req, bool force_nonblock,
5078 struct io_comp_state *cs)
5082 #endif /* CONFIG_NET */
5084 struct io_poll_table {
5085 struct poll_table_struct pt;
5086 struct io_kiocb *req;
5090 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5091 __poll_t mask, task_work_func_t func)
5095 /* for instances that support it check for an event match first: */
5096 if (mask && !(mask & poll->events))
5099 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5101 list_del_init(&poll->wait.entry);
5104 init_task_work(&req->task_work, func);
5105 percpu_ref_get(&req->ctx->refs);
5108 * If this fails, then the task is exiting. When a task exits, the
5109 * work gets canceled, so just cancel this request as well instead
5110 * of executing it. We can't safely execute it anyway, as we may not
5111 * have the needed state needed for it anyway.
5113 ret = io_req_task_work_add(req);
5114 if (unlikely(ret)) {
5115 struct task_struct *tsk;
5117 WRITE_ONCE(poll->canceled, true);
5118 tsk = io_wq_get_task(req->ctx->io_wq);
5119 task_work_add(tsk, &req->task_work, TWA_NONE);
5120 wake_up_process(tsk);
5125 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5126 __acquires(&req->ctx->completion_lock)
5128 struct io_ring_ctx *ctx = req->ctx;
5130 if (!req->result && !READ_ONCE(poll->canceled)) {
5131 struct poll_table_struct pt = { ._key = poll->events };
5133 req->result = vfs_poll(req->file, &pt) & poll->events;
5136 spin_lock_irq(&ctx->completion_lock);
5137 if (!req->result && !READ_ONCE(poll->canceled)) {
5138 add_wait_queue(poll->head, &poll->wait);
5145 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5147 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5148 if (req->opcode == IORING_OP_POLL_ADD)
5149 return req->async_data;
5150 return req->apoll->double_poll;
5153 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5155 if (req->opcode == IORING_OP_POLL_ADD)
5157 return &req->apoll->poll;
5160 static void io_poll_remove_double(struct io_kiocb *req)
5162 struct io_poll_iocb *poll = io_poll_get_double(req);
5164 lockdep_assert_held(&req->ctx->completion_lock);
5166 if (poll && poll->head) {
5167 struct wait_queue_head *head = poll->head;
5169 spin_lock(&head->lock);
5170 list_del_init(&poll->wait.entry);
5171 if (poll->wait.private)
5172 refcount_dec(&req->refs);
5174 spin_unlock(&head->lock);
5178 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5180 struct io_ring_ctx *ctx = req->ctx;
5182 io_poll_remove_double(req);
5183 req->poll.done = true;
5184 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5185 io_commit_cqring(ctx);
5188 static void io_poll_task_func(struct callback_head *cb)
5190 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5191 struct io_ring_ctx *ctx = req->ctx;
5192 struct io_kiocb *nxt;
5194 if (io_poll_rewait(req, &req->poll)) {
5195 spin_unlock_irq(&ctx->completion_lock);
5197 hash_del(&req->hash_node);
5198 io_poll_complete(req, req->result, 0);
5199 spin_unlock_irq(&ctx->completion_lock);
5201 nxt = io_put_req_find_next(req);
5202 io_cqring_ev_posted(ctx);
5204 __io_req_task_submit(nxt);
5207 percpu_ref_put(&ctx->refs);
5210 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5211 int sync, void *key)
5213 struct io_kiocb *req = wait->private;
5214 struct io_poll_iocb *poll = io_poll_get_single(req);
5215 __poll_t mask = key_to_poll(key);
5217 /* for instances that support it check for an event match first: */
5218 if (mask && !(mask & poll->events))
5221 list_del_init(&wait->entry);
5223 if (poll && poll->head) {
5226 spin_lock(&poll->head->lock);
5227 done = list_empty(&poll->wait.entry);
5229 list_del_init(&poll->wait.entry);
5230 /* make sure double remove sees this as being gone */
5231 wait->private = NULL;
5232 spin_unlock(&poll->head->lock);
5234 /* use wait func handler, so it matches the rq type */
5235 poll->wait.func(&poll->wait, mode, sync, key);
5238 refcount_dec(&req->refs);
5242 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5243 wait_queue_func_t wake_func)
5247 poll->canceled = false;
5248 poll->events = events;
5249 INIT_LIST_HEAD(&poll->wait.entry);
5250 init_waitqueue_func_entry(&poll->wait, wake_func);
5253 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5254 struct wait_queue_head *head,
5255 struct io_poll_iocb **poll_ptr)
5257 struct io_kiocb *req = pt->req;
5260 * If poll->head is already set, it's because the file being polled
5261 * uses multiple waitqueues for poll handling (eg one for read, one
5262 * for write). Setup a separate io_poll_iocb if this happens.
5264 if (unlikely(poll->head)) {
5265 struct io_poll_iocb *poll_one = poll;
5267 /* already have a 2nd entry, fail a third attempt */
5269 pt->error = -EINVAL;
5272 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5274 pt->error = -ENOMEM;
5277 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5278 refcount_inc(&req->refs);
5279 poll->wait.private = req;
5286 if (poll->events & EPOLLEXCLUSIVE)
5287 add_wait_queue_exclusive(head, &poll->wait);
5289 add_wait_queue(head, &poll->wait);
5292 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5293 struct poll_table_struct *p)
5295 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5296 struct async_poll *apoll = pt->req->apoll;
5298 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5301 static void io_async_task_func(struct callback_head *cb)
5303 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5304 struct async_poll *apoll = req->apoll;
5305 struct io_ring_ctx *ctx = req->ctx;
5307 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5309 if (io_poll_rewait(req, &apoll->poll)) {
5310 spin_unlock_irq(&ctx->completion_lock);
5311 percpu_ref_put(&ctx->refs);
5315 /* If req is still hashed, it cannot have been canceled. Don't check. */
5316 if (hash_hashed(&req->hash_node))
5317 hash_del(&req->hash_node);
5319 io_poll_remove_double(req);
5320 spin_unlock_irq(&ctx->completion_lock);
5322 if (!READ_ONCE(apoll->poll.canceled))
5323 __io_req_task_submit(req);
5325 __io_req_task_cancel(req, -ECANCELED);
5327 percpu_ref_put(&ctx->refs);
5328 kfree(apoll->double_poll);
5332 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5335 struct io_kiocb *req = wait->private;
5336 struct io_poll_iocb *poll = &req->apoll->poll;
5338 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5341 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5344 static void io_poll_req_insert(struct io_kiocb *req)
5346 struct io_ring_ctx *ctx = req->ctx;
5347 struct hlist_head *list;
5349 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5350 hlist_add_head(&req->hash_node, list);
5353 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5354 struct io_poll_iocb *poll,
5355 struct io_poll_table *ipt, __poll_t mask,
5356 wait_queue_func_t wake_func)
5357 __acquires(&ctx->completion_lock)
5359 struct io_ring_ctx *ctx = req->ctx;
5360 bool cancel = false;
5362 INIT_HLIST_NODE(&req->hash_node);
5363 io_init_poll_iocb(poll, mask, wake_func);
5364 poll->file = req->file;
5365 poll->wait.private = req;
5367 ipt->pt._key = mask;
5369 ipt->error = -EINVAL;
5371 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5373 spin_lock_irq(&ctx->completion_lock);
5374 if (likely(poll->head)) {
5375 spin_lock(&poll->head->lock);
5376 if (unlikely(list_empty(&poll->wait.entry))) {
5382 if (mask || ipt->error)
5383 list_del_init(&poll->wait.entry);
5385 WRITE_ONCE(poll->canceled, true);
5386 else if (!poll->done) /* actually waiting for an event */
5387 io_poll_req_insert(req);
5388 spin_unlock(&poll->head->lock);
5394 static bool io_arm_poll_handler(struct io_kiocb *req)
5396 const struct io_op_def *def = &io_op_defs[req->opcode];
5397 struct io_ring_ctx *ctx = req->ctx;
5398 struct async_poll *apoll;
5399 struct io_poll_table ipt;
5403 if (!req->file || !file_can_poll(req->file))
5405 if (req->flags & REQ_F_POLLED)
5409 else if (def->pollout)
5413 /* if we can't nonblock try, then no point in arming a poll handler */
5414 if (!io_file_supports_async(req->file, rw))
5417 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5418 if (unlikely(!apoll))
5420 apoll->double_poll = NULL;
5422 req->flags |= REQ_F_POLLED;
5427 mask |= POLLIN | POLLRDNORM;
5429 mask |= POLLOUT | POLLWRNORM;
5431 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5432 if ((req->opcode == IORING_OP_RECVMSG) &&
5433 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5436 mask |= POLLERR | POLLPRI;
5438 ipt.pt._qproc = io_async_queue_proc;
5440 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5442 if (ret || ipt.error) {
5443 io_poll_remove_double(req);
5444 spin_unlock_irq(&ctx->completion_lock);
5445 kfree(apoll->double_poll);
5449 spin_unlock_irq(&ctx->completion_lock);
5450 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5451 apoll->poll.events);
5455 static bool __io_poll_remove_one(struct io_kiocb *req,
5456 struct io_poll_iocb *poll)
5458 bool do_complete = false;
5460 spin_lock(&poll->head->lock);
5461 WRITE_ONCE(poll->canceled, true);
5462 if (!list_empty(&poll->wait.entry)) {
5463 list_del_init(&poll->wait.entry);
5466 spin_unlock(&poll->head->lock);
5467 hash_del(&req->hash_node);
5471 static bool io_poll_remove_one(struct io_kiocb *req)
5475 io_poll_remove_double(req);
5477 if (req->opcode == IORING_OP_POLL_ADD) {
5478 do_complete = __io_poll_remove_one(req, &req->poll);
5480 struct async_poll *apoll = req->apoll;
5482 /* non-poll requests have submit ref still */
5483 do_complete = __io_poll_remove_one(req, &apoll->poll);
5486 kfree(apoll->double_poll);
5492 io_cqring_fill_event(req, -ECANCELED);
5493 io_commit_cqring(req->ctx);
5494 req_set_fail_links(req);
5495 io_put_req_deferred(req, 1);
5502 * Returns true if we found and killed one or more poll requests
5504 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5505 struct files_struct *files)
5507 struct hlist_node *tmp;
5508 struct io_kiocb *req;
5511 spin_lock_irq(&ctx->completion_lock);
5512 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5513 struct hlist_head *list;
5515 list = &ctx->cancel_hash[i];
5516 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5517 if (io_match_task(req, tsk, files))
5518 posted += io_poll_remove_one(req);
5521 spin_unlock_irq(&ctx->completion_lock);
5524 io_cqring_ev_posted(ctx);
5529 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5531 struct hlist_head *list;
5532 struct io_kiocb *req;
5534 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5535 hlist_for_each_entry(req, list, hash_node) {
5536 if (sqe_addr != req->user_data)
5538 if (io_poll_remove_one(req))
5546 static int io_poll_remove_prep(struct io_kiocb *req,
5547 const struct io_uring_sqe *sqe)
5549 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5551 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5555 req->poll_remove.addr = READ_ONCE(sqe->addr);
5560 * Find a running poll command that matches one specified in sqe->addr,
5561 * and remove it if found.
5563 static int io_poll_remove(struct io_kiocb *req)
5565 struct io_ring_ctx *ctx = req->ctx;
5568 spin_lock_irq(&ctx->completion_lock);
5569 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5570 spin_unlock_irq(&ctx->completion_lock);
5573 req_set_fail_links(req);
5574 io_req_complete(req, ret);
5578 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5581 struct io_kiocb *req = wait->private;
5582 struct io_poll_iocb *poll = &req->poll;
5584 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5587 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5588 struct poll_table_struct *p)
5590 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5592 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5595 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5597 struct io_poll_iocb *poll = &req->poll;
5600 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5602 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5605 events = READ_ONCE(sqe->poll32_events);
5607 events = swahw32(events);
5609 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5610 (events & EPOLLEXCLUSIVE);
5614 static int io_poll_add(struct io_kiocb *req)
5616 struct io_poll_iocb *poll = &req->poll;
5617 struct io_ring_ctx *ctx = req->ctx;
5618 struct io_poll_table ipt;
5621 ipt.pt._qproc = io_poll_queue_proc;
5623 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5626 if (mask) { /* no async, we'd stolen it */
5628 io_poll_complete(req, mask, 0);
5630 spin_unlock_irq(&ctx->completion_lock);
5633 io_cqring_ev_posted(ctx);
5639 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5641 struct io_timeout_data *data = container_of(timer,
5642 struct io_timeout_data, timer);
5643 struct io_kiocb *req = data->req;
5644 struct io_ring_ctx *ctx = req->ctx;
5645 unsigned long flags;
5647 spin_lock_irqsave(&ctx->completion_lock, flags);
5648 list_del_init(&req->timeout.list);
5649 atomic_set(&req->ctx->cq_timeouts,
5650 atomic_read(&req->ctx->cq_timeouts) + 1);
5652 io_cqring_fill_event(req, -ETIME);
5653 io_commit_cqring(ctx);
5654 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5656 io_cqring_ev_posted(ctx);
5657 req_set_fail_links(req);
5659 return HRTIMER_NORESTART;
5662 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5665 struct io_timeout_data *io;
5666 struct io_kiocb *req;
5669 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5670 if (user_data == req->user_data) {
5677 return ERR_PTR(ret);
5679 io = req->async_data;
5680 ret = hrtimer_try_to_cancel(&io->timer);
5682 return ERR_PTR(-EALREADY);
5683 list_del_init(&req->timeout.list);
5687 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5689 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5692 return PTR_ERR(req);
5694 req_set_fail_links(req);
5695 io_cqring_fill_event(req, -ECANCELED);
5696 io_put_req_deferred(req, 1);
5700 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5701 struct timespec64 *ts, enum hrtimer_mode mode)
5703 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5704 struct io_timeout_data *data;
5707 return PTR_ERR(req);
5709 req->timeout.off = 0; /* noseq */
5710 data = req->async_data;
5711 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5712 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5713 data->timer.function = io_timeout_fn;
5714 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5718 static int io_timeout_remove_prep(struct io_kiocb *req,
5719 const struct io_uring_sqe *sqe)
5721 struct io_timeout_rem *tr = &req->timeout_rem;
5723 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5725 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5727 if (sqe->ioprio || sqe->buf_index || sqe->len)
5730 tr->addr = READ_ONCE(sqe->addr);
5731 tr->flags = READ_ONCE(sqe->timeout_flags);
5732 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5733 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5735 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5737 } else if (tr->flags) {
5738 /* timeout removal doesn't support flags */
5746 * Remove or update an existing timeout command
5748 static int io_timeout_remove(struct io_kiocb *req)
5750 struct io_timeout_rem *tr = &req->timeout_rem;
5751 struct io_ring_ctx *ctx = req->ctx;
5754 spin_lock_irq(&ctx->completion_lock);
5755 if (req->timeout_rem.flags & IORING_TIMEOUT_UPDATE) {
5756 enum hrtimer_mode mode = (tr->flags & IORING_TIMEOUT_ABS)
5757 ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL;
5759 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5761 ret = io_timeout_cancel(ctx, tr->addr);
5764 io_cqring_fill_event(req, ret);
5765 io_commit_cqring(ctx);
5766 spin_unlock_irq(&ctx->completion_lock);
5767 io_cqring_ev_posted(ctx);
5769 req_set_fail_links(req);
5774 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5775 bool is_timeout_link)
5777 struct io_timeout_data *data;
5779 u32 off = READ_ONCE(sqe->off);
5781 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5783 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5785 if (off && is_timeout_link)
5787 flags = READ_ONCE(sqe->timeout_flags);
5788 if (flags & ~IORING_TIMEOUT_ABS)
5791 req->timeout.off = off;
5793 if (!req->async_data && io_alloc_async_data(req))
5796 data = req->async_data;
5799 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5802 if (flags & IORING_TIMEOUT_ABS)
5803 data->mode = HRTIMER_MODE_ABS;
5805 data->mode = HRTIMER_MODE_REL;
5807 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5811 static int io_timeout(struct io_kiocb *req)
5813 struct io_ring_ctx *ctx = req->ctx;
5814 struct io_timeout_data *data = req->async_data;
5815 struct list_head *entry;
5816 u32 tail, off = req->timeout.off;
5818 spin_lock_irq(&ctx->completion_lock);
5821 * sqe->off holds how many events that need to occur for this
5822 * timeout event to be satisfied. If it isn't set, then this is
5823 * a pure timeout request, sequence isn't used.
5825 if (io_is_timeout_noseq(req)) {
5826 entry = ctx->timeout_list.prev;
5830 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5831 req->timeout.target_seq = tail + off;
5834 * Insertion sort, ensuring the first entry in the list is always
5835 * the one we need first.
5837 list_for_each_prev(entry, &ctx->timeout_list) {
5838 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5841 if (io_is_timeout_noseq(nxt))
5843 /* nxt.seq is behind @tail, otherwise would've been completed */
5844 if (off >= nxt->timeout.target_seq - tail)
5848 list_add(&req->timeout.list, entry);
5849 data->timer.function = io_timeout_fn;
5850 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5851 spin_unlock_irq(&ctx->completion_lock);
5855 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5857 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5859 return req->user_data == (unsigned long) data;
5862 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5864 enum io_wq_cancel cancel_ret;
5867 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5868 switch (cancel_ret) {
5869 case IO_WQ_CANCEL_OK:
5872 case IO_WQ_CANCEL_RUNNING:
5875 case IO_WQ_CANCEL_NOTFOUND:
5883 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5884 struct io_kiocb *req, __u64 sqe_addr,
5887 unsigned long flags;
5890 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5891 if (ret != -ENOENT) {
5892 spin_lock_irqsave(&ctx->completion_lock, flags);
5896 spin_lock_irqsave(&ctx->completion_lock, flags);
5897 ret = io_timeout_cancel(ctx, sqe_addr);
5900 ret = io_poll_cancel(ctx, sqe_addr);
5904 io_cqring_fill_event(req, ret);
5905 io_commit_cqring(ctx);
5906 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5907 io_cqring_ev_posted(ctx);
5910 req_set_fail_links(req);
5914 static int io_async_cancel_prep(struct io_kiocb *req,
5915 const struct io_uring_sqe *sqe)
5917 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5919 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5921 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5924 req->cancel.addr = READ_ONCE(sqe->addr);
5928 static int io_async_cancel(struct io_kiocb *req)
5930 struct io_ring_ctx *ctx = req->ctx;
5932 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5936 static int io_files_update_prep(struct io_kiocb *req,
5937 const struct io_uring_sqe *sqe)
5939 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5941 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5943 if (sqe->ioprio || sqe->rw_flags)
5946 req->files_update.offset = READ_ONCE(sqe->off);
5947 req->files_update.nr_args = READ_ONCE(sqe->len);
5948 if (!req->files_update.nr_args)
5950 req->files_update.arg = READ_ONCE(sqe->addr);
5954 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5955 struct io_comp_state *cs)
5957 struct io_ring_ctx *ctx = req->ctx;
5958 struct io_uring_files_update up;
5964 up.offset = req->files_update.offset;
5965 up.fds = req->files_update.arg;
5967 mutex_lock(&ctx->uring_lock);
5968 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5969 mutex_unlock(&ctx->uring_lock);
5972 req_set_fail_links(req);
5973 __io_req_complete(req, ret, 0, cs);
5977 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5979 switch (req->opcode) {
5982 case IORING_OP_READV:
5983 case IORING_OP_READ_FIXED:
5984 case IORING_OP_READ:
5985 return io_read_prep(req, sqe);
5986 case IORING_OP_WRITEV:
5987 case IORING_OP_WRITE_FIXED:
5988 case IORING_OP_WRITE:
5989 return io_write_prep(req, sqe);
5990 case IORING_OP_POLL_ADD:
5991 return io_poll_add_prep(req, sqe);
5992 case IORING_OP_POLL_REMOVE:
5993 return io_poll_remove_prep(req, sqe);
5994 case IORING_OP_FSYNC:
5995 return io_prep_fsync(req, sqe);
5996 case IORING_OP_SYNC_FILE_RANGE:
5997 return io_prep_sfr(req, sqe);
5998 case IORING_OP_SENDMSG:
5999 case IORING_OP_SEND:
6000 return io_sendmsg_prep(req, sqe);
6001 case IORING_OP_RECVMSG:
6002 case IORING_OP_RECV:
6003 return io_recvmsg_prep(req, sqe);
6004 case IORING_OP_CONNECT:
6005 return io_connect_prep(req, sqe);
6006 case IORING_OP_TIMEOUT:
6007 return io_timeout_prep(req, sqe, false);
6008 case IORING_OP_TIMEOUT_REMOVE:
6009 return io_timeout_remove_prep(req, sqe);
6010 case IORING_OP_ASYNC_CANCEL:
6011 return io_async_cancel_prep(req, sqe);
6012 case IORING_OP_LINK_TIMEOUT:
6013 return io_timeout_prep(req, sqe, true);
6014 case IORING_OP_ACCEPT:
6015 return io_accept_prep(req, sqe);
6016 case IORING_OP_FALLOCATE:
6017 return io_fallocate_prep(req, sqe);
6018 case IORING_OP_OPENAT:
6019 return io_openat_prep(req, sqe);
6020 case IORING_OP_CLOSE:
6021 return io_close_prep(req, sqe);
6022 case IORING_OP_FILES_UPDATE:
6023 return io_files_update_prep(req, sqe);
6024 case IORING_OP_STATX:
6025 return io_statx_prep(req, sqe);
6026 case IORING_OP_FADVISE:
6027 return io_fadvise_prep(req, sqe);
6028 case IORING_OP_MADVISE:
6029 return io_madvise_prep(req, sqe);
6030 case IORING_OP_OPENAT2:
6031 return io_openat2_prep(req, sqe);
6032 case IORING_OP_EPOLL_CTL:
6033 return io_epoll_ctl_prep(req, sqe);
6034 case IORING_OP_SPLICE:
6035 return io_splice_prep(req, sqe);
6036 case IORING_OP_PROVIDE_BUFFERS:
6037 return io_provide_buffers_prep(req, sqe);
6038 case IORING_OP_REMOVE_BUFFERS:
6039 return io_remove_buffers_prep(req, sqe);
6041 return io_tee_prep(req, sqe);
6042 case IORING_OP_SHUTDOWN:
6043 return io_shutdown_prep(req, sqe);
6044 case IORING_OP_RENAMEAT:
6045 return io_renameat_prep(req, sqe);
6046 case IORING_OP_UNLINKAT:
6047 return io_unlinkat_prep(req, sqe);
6050 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6055 static int io_req_defer_prep(struct io_kiocb *req,
6056 const struct io_uring_sqe *sqe)
6060 if (io_alloc_async_data(req))
6062 return io_req_prep(req, sqe);
6065 static u32 io_get_sequence(struct io_kiocb *req)
6067 struct io_kiocb *pos;
6068 struct io_ring_ctx *ctx = req->ctx;
6069 u32 total_submitted, nr_reqs = 0;
6071 io_for_each_link(pos, req)
6074 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6075 return total_submitted - nr_reqs;
6078 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6080 struct io_ring_ctx *ctx = req->ctx;
6081 struct io_defer_entry *de;
6085 /* Still need defer if there is pending req in defer list. */
6086 if (likely(list_empty_careful(&ctx->defer_list) &&
6087 !(req->flags & REQ_F_IO_DRAIN)))
6090 seq = io_get_sequence(req);
6091 /* Still a chance to pass the sequence check */
6092 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6095 if (!req->async_data) {
6096 ret = io_req_defer_prep(req, sqe);
6100 io_prep_async_link(req);
6101 de = kmalloc(sizeof(*de), GFP_KERNEL);
6105 spin_lock_irq(&ctx->completion_lock);
6106 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6107 spin_unlock_irq(&ctx->completion_lock);
6109 io_queue_async_work(req);
6110 return -EIOCBQUEUED;
6113 trace_io_uring_defer(ctx, req, req->user_data);
6116 list_add_tail(&de->list, &ctx->defer_list);
6117 spin_unlock_irq(&ctx->completion_lock);
6118 return -EIOCBQUEUED;
6121 static void io_req_drop_files(struct io_kiocb *req)
6123 struct io_ring_ctx *ctx = req->ctx;
6124 struct io_uring_task *tctx = req->task->io_uring;
6125 unsigned long flags;
6127 put_files_struct(req->work.identity->files);
6128 put_nsproxy(req->work.identity->nsproxy);
6129 spin_lock_irqsave(&ctx->inflight_lock, flags);
6130 list_del(&req->inflight_entry);
6131 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
6132 req->flags &= ~REQ_F_INFLIGHT;
6133 req->work.flags &= ~IO_WQ_WORK_FILES;
6134 if (atomic_read(&tctx->in_idle))
6135 wake_up(&tctx->wait);
6138 static void __io_clean_op(struct io_kiocb *req)
6140 if (req->flags & REQ_F_BUFFER_SELECTED) {
6141 switch (req->opcode) {
6142 case IORING_OP_READV:
6143 case IORING_OP_READ_FIXED:
6144 case IORING_OP_READ:
6145 kfree((void *)(unsigned long)req->rw.addr);
6147 case IORING_OP_RECVMSG:
6148 case IORING_OP_RECV:
6149 kfree(req->sr_msg.kbuf);
6152 req->flags &= ~REQ_F_BUFFER_SELECTED;
6155 if (req->flags & REQ_F_NEED_CLEANUP) {
6156 switch (req->opcode) {
6157 case IORING_OP_READV:
6158 case IORING_OP_READ_FIXED:
6159 case IORING_OP_READ:
6160 case IORING_OP_WRITEV:
6161 case IORING_OP_WRITE_FIXED:
6162 case IORING_OP_WRITE: {
6163 struct io_async_rw *io = req->async_data;
6165 kfree(io->free_iovec);
6168 case IORING_OP_RECVMSG:
6169 case IORING_OP_SENDMSG: {
6170 struct io_async_msghdr *io = req->async_data;
6171 if (io->iov != io->fast_iov)
6175 case IORING_OP_SPLICE:
6177 io_put_file(req, req->splice.file_in,
6178 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6180 case IORING_OP_OPENAT:
6181 case IORING_OP_OPENAT2:
6182 if (req->open.filename)
6183 putname(req->open.filename);
6185 case IORING_OP_RENAMEAT:
6186 putname(req->rename.oldpath);
6187 putname(req->rename.newpath);
6189 case IORING_OP_UNLINKAT:
6190 putname(req->unlink.filename);
6193 req->flags &= ~REQ_F_NEED_CLEANUP;
6196 if (req->flags & REQ_F_INFLIGHT)
6197 io_req_drop_files(req);
6200 static int io_issue_sqe(struct io_kiocb *req, bool force_nonblock,
6201 struct io_comp_state *cs)
6203 struct io_ring_ctx *ctx = req->ctx;
6206 switch (req->opcode) {
6208 ret = io_nop(req, cs);
6210 case IORING_OP_READV:
6211 case IORING_OP_READ_FIXED:
6212 case IORING_OP_READ:
6213 ret = io_read(req, force_nonblock, cs);
6215 case IORING_OP_WRITEV:
6216 case IORING_OP_WRITE_FIXED:
6217 case IORING_OP_WRITE:
6218 ret = io_write(req, force_nonblock, cs);
6220 case IORING_OP_FSYNC:
6221 ret = io_fsync(req, force_nonblock);
6223 case IORING_OP_POLL_ADD:
6224 ret = io_poll_add(req);
6226 case IORING_OP_POLL_REMOVE:
6227 ret = io_poll_remove(req);
6229 case IORING_OP_SYNC_FILE_RANGE:
6230 ret = io_sync_file_range(req, force_nonblock);
6232 case IORING_OP_SENDMSG:
6233 ret = io_sendmsg(req, force_nonblock, cs);
6235 case IORING_OP_SEND:
6236 ret = io_send(req, force_nonblock, cs);
6238 case IORING_OP_RECVMSG:
6239 ret = io_recvmsg(req, force_nonblock, cs);
6241 case IORING_OP_RECV:
6242 ret = io_recv(req, force_nonblock, cs);
6244 case IORING_OP_TIMEOUT:
6245 ret = io_timeout(req);
6247 case IORING_OP_TIMEOUT_REMOVE:
6248 ret = io_timeout_remove(req);
6250 case IORING_OP_ACCEPT:
6251 ret = io_accept(req, force_nonblock, cs);
6253 case IORING_OP_CONNECT:
6254 ret = io_connect(req, force_nonblock, cs);
6256 case IORING_OP_ASYNC_CANCEL:
6257 ret = io_async_cancel(req);
6259 case IORING_OP_FALLOCATE:
6260 ret = io_fallocate(req, force_nonblock);
6262 case IORING_OP_OPENAT:
6263 ret = io_openat(req, force_nonblock);
6265 case IORING_OP_CLOSE:
6266 ret = io_close(req, force_nonblock, cs);
6268 case IORING_OP_FILES_UPDATE:
6269 ret = io_files_update(req, force_nonblock, cs);
6271 case IORING_OP_STATX:
6272 ret = io_statx(req, force_nonblock);
6274 case IORING_OP_FADVISE:
6275 ret = io_fadvise(req, force_nonblock);
6277 case IORING_OP_MADVISE:
6278 ret = io_madvise(req, force_nonblock);
6280 case IORING_OP_OPENAT2:
6281 ret = io_openat2(req, force_nonblock);
6283 case IORING_OP_EPOLL_CTL:
6284 ret = io_epoll_ctl(req, force_nonblock, cs);
6286 case IORING_OP_SPLICE:
6287 ret = io_splice(req, force_nonblock);
6289 case IORING_OP_PROVIDE_BUFFERS:
6290 ret = io_provide_buffers(req, force_nonblock, cs);
6292 case IORING_OP_REMOVE_BUFFERS:
6293 ret = io_remove_buffers(req, force_nonblock, cs);
6296 ret = io_tee(req, force_nonblock);
6298 case IORING_OP_SHUTDOWN:
6299 ret = io_shutdown(req, force_nonblock);
6301 case IORING_OP_RENAMEAT:
6302 ret = io_renameat(req, force_nonblock);
6304 case IORING_OP_UNLINKAT:
6305 ret = io_unlinkat(req, force_nonblock);
6315 /* If the op doesn't have a file, we're not polling for it */
6316 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6317 const bool in_async = io_wq_current_is_worker();
6319 /* workqueue context doesn't hold uring_lock, grab it now */
6321 mutex_lock(&ctx->uring_lock);
6323 io_iopoll_req_issued(req, in_async);
6326 mutex_unlock(&ctx->uring_lock);
6332 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
6334 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6335 struct io_kiocb *timeout;
6338 timeout = io_prep_linked_timeout(req);
6340 io_queue_linked_timeout(timeout);
6342 /* if NO_CANCEL is set, we must still run the work */
6343 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
6344 IO_WQ_WORK_CANCEL) {
6350 ret = io_issue_sqe(req, false, NULL);
6352 * We can get EAGAIN for polled IO even though we're
6353 * forcing a sync submission from here, since we can't
6354 * wait for request slots on the block side.
6363 struct io_ring_ctx *lock_ctx = NULL;
6365 if (req->ctx->flags & IORING_SETUP_IOPOLL)
6366 lock_ctx = req->ctx;
6369 * io_iopoll_complete() does not hold completion_lock to
6370 * complete polled io, so here for polled io, we can not call
6371 * io_req_complete() directly, otherwise there maybe concurrent
6372 * access to cqring, defer_list, etc, which is not safe. Given
6373 * that io_iopoll_complete() is always called under uring_lock,
6374 * so here for polled io, we also get uring_lock to complete
6378 mutex_lock(&lock_ctx->uring_lock);
6380 req_set_fail_links(req);
6381 io_req_complete(req, ret);
6384 mutex_unlock(&lock_ctx->uring_lock);
6387 return io_steal_work(req);
6390 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6393 struct fixed_file_table *table;
6395 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6396 return table->files[index & IORING_FILE_TABLE_MASK];
6399 static struct file *io_file_get(struct io_submit_state *state,
6400 struct io_kiocb *req, int fd, bool fixed)
6402 struct io_ring_ctx *ctx = req->ctx;
6406 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6408 fd = array_index_nospec(fd, ctx->nr_user_files);
6409 file = io_file_from_index(ctx, fd);
6410 io_set_resource_node(req);
6412 trace_io_uring_file_get(ctx, fd);
6413 file = __io_file_get(state, fd);
6419 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6421 struct io_timeout_data *data = container_of(timer,
6422 struct io_timeout_data, timer);
6423 struct io_kiocb *prev, *req = data->req;
6424 struct io_ring_ctx *ctx = req->ctx;
6425 unsigned long flags;
6427 spin_lock_irqsave(&ctx->completion_lock, flags);
6428 prev = req->timeout.head;
6429 req->timeout.head = NULL;
6432 * We don't expect the list to be empty, that will only happen if we
6433 * race with the completion of the linked work.
6435 if (prev && refcount_inc_not_zero(&prev->refs))
6436 io_remove_next_linked(prev);
6439 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6442 req_set_fail_links(prev);
6443 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6446 io_req_complete(req, -ETIME);
6448 return HRTIMER_NORESTART;
6451 static void __io_queue_linked_timeout(struct io_kiocb *req)
6454 * If the back reference is NULL, then our linked request finished
6455 * before we got a chance to setup the timer
6457 if (req->timeout.head) {
6458 struct io_timeout_data *data = req->async_data;
6460 data->timer.function = io_link_timeout_fn;
6461 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6466 static void io_queue_linked_timeout(struct io_kiocb *req)
6468 struct io_ring_ctx *ctx = req->ctx;
6470 spin_lock_irq(&ctx->completion_lock);
6471 __io_queue_linked_timeout(req);
6472 spin_unlock_irq(&ctx->completion_lock);
6474 /* drop submission reference */
6478 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6480 struct io_kiocb *nxt = req->link;
6482 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6483 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6486 nxt->timeout.head = req;
6487 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6488 req->flags |= REQ_F_LINK_TIMEOUT;
6492 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs)
6494 struct io_kiocb *linked_timeout;
6495 const struct cred *old_creds = NULL;
6499 linked_timeout = io_prep_linked_timeout(req);
6501 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6502 (req->work.flags & IO_WQ_WORK_CREDS) &&
6503 req->work.identity->creds != current_cred()) {
6505 revert_creds(old_creds);
6506 if (old_creds == req->work.identity->creds)
6507 old_creds = NULL; /* restored original creds */
6509 old_creds = override_creds(req->work.identity->creds);
6512 ret = io_issue_sqe(req, true, cs);
6515 * We async punt it if the file wasn't marked NOWAIT, or if the file
6516 * doesn't support non-blocking read/write attempts
6518 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6519 if (!io_arm_poll_handler(req)) {
6521 * Queued up for async execution, worker will release
6522 * submit reference when the iocb is actually submitted.
6524 io_queue_async_work(req);
6528 io_queue_linked_timeout(linked_timeout);
6529 } else if (likely(!ret)) {
6530 /* drop submission reference */
6531 req = io_put_req_find_next(req);
6533 io_queue_linked_timeout(linked_timeout);
6536 if (!(req->flags & REQ_F_FORCE_ASYNC))
6538 io_queue_async_work(req);
6541 /* un-prep timeout, so it'll be killed as any other linked */
6542 req->flags &= ~REQ_F_LINK_TIMEOUT;
6543 req_set_fail_links(req);
6545 io_req_complete(req, ret);
6549 revert_creds(old_creds);
6552 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6553 struct io_comp_state *cs)
6557 ret = io_req_defer(req, sqe);
6559 if (ret != -EIOCBQUEUED) {
6561 req_set_fail_links(req);
6563 io_req_complete(req, ret);
6565 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6566 if (!req->async_data) {
6567 ret = io_req_defer_prep(req, sqe);
6571 io_queue_async_work(req);
6574 ret = io_req_prep(req, sqe);
6578 __io_queue_sqe(req, cs);
6582 static inline void io_queue_link_head(struct io_kiocb *req,
6583 struct io_comp_state *cs)
6585 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6587 io_req_complete(req, -ECANCELED);
6589 io_queue_sqe(req, NULL, cs);
6592 struct io_submit_link {
6593 struct io_kiocb *head;
6594 struct io_kiocb *last;
6597 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6598 struct io_submit_link *link, struct io_comp_state *cs)
6600 struct io_ring_ctx *ctx = req->ctx;
6604 * If we already have a head request, queue this one for async
6605 * submittal once the head completes. If we don't have a head but
6606 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6607 * submitted sync once the chain is complete. If none of those
6608 * conditions are true (normal request), then just queue it.
6611 struct io_kiocb *head = link->head;
6614 * Taking sequential execution of a link, draining both sides
6615 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6616 * requests in the link. So, it drains the head and the
6617 * next after the link request. The last one is done via
6618 * drain_next flag to persist the effect across calls.
6620 if (req->flags & REQ_F_IO_DRAIN) {
6621 head->flags |= REQ_F_IO_DRAIN;
6622 ctx->drain_next = 1;
6624 ret = io_req_defer_prep(req, sqe);
6625 if (unlikely(ret)) {
6626 /* fail even hard links since we don't submit */
6627 head->flags |= REQ_F_FAIL_LINK;
6630 trace_io_uring_link(ctx, req, head);
6631 link->last->link = req;
6634 /* last request of a link, enqueue the link */
6635 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6636 io_queue_link_head(head, cs);
6640 if (unlikely(ctx->drain_next)) {
6641 req->flags |= REQ_F_IO_DRAIN;
6642 ctx->drain_next = 0;
6644 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6645 ret = io_req_defer_prep(req, sqe);
6647 req->flags |= REQ_F_FAIL_LINK;
6651 io_queue_sqe(req, sqe, cs);
6659 * Batched submission is done, ensure local IO is flushed out.
6661 static void io_submit_state_end(struct io_submit_state *state)
6663 if (!list_empty(&state->comp.list))
6664 io_submit_flush_completions(&state->comp);
6665 if (state->plug_started)
6666 blk_finish_plug(&state->plug);
6667 io_state_file_put(state);
6668 if (state->free_reqs)
6669 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6673 * Start submission side cache.
6675 static void io_submit_state_start(struct io_submit_state *state,
6676 struct io_ring_ctx *ctx, unsigned int max_ios)
6678 state->plug_started = false;
6680 INIT_LIST_HEAD(&state->comp.list);
6681 state->comp.ctx = ctx;
6682 state->free_reqs = 0;
6683 state->file_refs = 0;
6684 state->ios_left = max_ios;
6687 static void io_commit_sqring(struct io_ring_ctx *ctx)
6689 struct io_rings *rings = ctx->rings;
6692 * Ensure any loads from the SQEs are done at this point,
6693 * since once we write the new head, the application could
6694 * write new data to them.
6696 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6700 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6701 * that is mapped by userspace. This means that care needs to be taken to
6702 * ensure that reads are stable, as we cannot rely on userspace always
6703 * being a good citizen. If members of the sqe are validated and then later
6704 * used, it's important that those reads are done through READ_ONCE() to
6705 * prevent a re-load down the line.
6707 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6709 u32 *sq_array = ctx->sq_array;
6713 * The cached sq head (or cq tail) serves two purposes:
6715 * 1) allows us to batch the cost of updating the user visible
6717 * 2) allows the kernel side to track the head on its own, even
6718 * though the application is the one updating it.
6720 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6721 if (likely(head < ctx->sq_entries))
6722 return &ctx->sq_sqes[head];
6724 /* drop invalid entries */
6725 ctx->cached_sq_dropped++;
6726 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6730 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6732 ctx->cached_sq_head++;
6736 * Check SQE restrictions (opcode and flags).
6738 * Returns 'true' if SQE is allowed, 'false' otherwise.
6740 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6741 struct io_kiocb *req,
6742 unsigned int sqe_flags)
6744 if (!ctx->restricted)
6747 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6750 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6751 ctx->restrictions.sqe_flags_required)
6754 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6755 ctx->restrictions.sqe_flags_required))
6761 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6762 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6763 IOSQE_BUFFER_SELECT)
6765 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6766 const struct io_uring_sqe *sqe,
6767 struct io_submit_state *state)
6769 unsigned int sqe_flags;
6772 req->opcode = READ_ONCE(sqe->opcode);
6773 req->user_data = READ_ONCE(sqe->user_data);
6774 req->async_data = NULL;
6779 req->fixed_file_refs = NULL;
6780 /* one is dropped after submission, the other at completion */
6781 refcount_set(&req->refs, 2);
6782 req->task = current;
6785 if (unlikely(req->opcode >= IORING_OP_LAST))
6788 if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6791 sqe_flags = READ_ONCE(sqe->flags);
6792 /* enforce forwards compatibility on users */
6793 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6796 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6799 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6800 !io_op_defs[req->opcode].buffer_select)
6803 id = READ_ONCE(sqe->personality);
6805 struct io_identity *iod;
6807 iod = idr_find(&ctx->personality_idr, id);
6810 refcount_inc(&iod->count);
6812 __io_req_init_async(req);
6813 get_cred(iod->creds);
6814 req->work.identity = iod;
6815 req->work.flags |= IO_WQ_WORK_CREDS;
6818 /* same numerical values with corresponding REQ_F_*, safe to copy */
6819 req->flags |= sqe_flags;
6822 * Plug now if we have more than 1 IO left after this, and the target
6823 * is potentially a read/write to block based storage.
6825 if (!state->plug_started && state->ios_left > 1 &&
6826 io_op_defs[req->opcode].plug) {
6827 blk_start_plug(&state->plug);
6828 state->plug_started = true;
6832 if (io_op_defs[req->opcode].needs_file) {
6833 bool fixed = req->flags & REQ_F_FIXED_FILE;
6835 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6836 if (unlikely(!req->file &&
6837 !io_op_defs[req->opcode].needs_file_no_error))
6845 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6847 struct io_submit_state state;
6848 struct io_submit_link link;
6849 int i, submitted = 0;
6851 /* if we have a backlog and couldn't flush it all, return BUSY */
6852 if (test_bit(0, &ctx->sq_check_overflow)) {
6853 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6857 /* make sure SQ entry isn't read before tail */
6858 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6860 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6863 percpu_counter_add(¤t->io_uring->inflight, nr);
6864 refcount_add(nr, ¤t->usage);
6866 io_submit_state_start(&state, ctx, nr);
6869 for (i = 0; i < nr; i++) {
6870 const struct io_uring_sqe *sqe;
6871 struct io_kiocb *req;
6874 sqe = io_get_sqe(ctx);
6875 if (unlikely(!sqe)) {
6876 io_consume_sqe(ctx);
6879 req = io_alloc_req(ctx, &state);
6880 if (unlikely(!req)) {
6882 submitted = -EAGAIN;
6885 io_consume_sqe(ctx);
6886 /* will complete beyond this point, count as submitted */
6889 err = io_init_req(ctx, req, sqe, &state);
6890 if (unlikely(err)) {
6893 io_req_complete(req, err);
6897 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6898 true, io_async_submit(ctx));
6899 err = io_submit_sqe(req, sqe, &link, &state.comp);
6904 if (unlikely(submitted != nr)) {
6905 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6906 struct io_uring_task *tctx = current->io_uring;
6907 int unused = nr - ref_used;
6909 percpu_ref_put_many(&ctx->refs, unused);
6910 percpu_counter_sub(&tctx->inflight, unused);
6911 put_task_struct_many(current, unused);
6914 io_queue_link_head(link.head, &state.comp);
6915 io_submit_state_end(&state);
6917 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6918 io_commit_sqring(ctx);
6923 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6925 /* Tell userspace we may need a wakeup call */
6926 spin_lock_irq(&ctx->completion_lock);
6927 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6928 spin_unlock_irq(&ctx->completion_lock);
6931 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6933 spin_lock_irq(&ctx->completion_lock);
6934 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6935 spin_unlock_irq(&ctx->completion_lock);
6938 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6940 unsigned int to_submit;
6943 to_submit = io_sqring_entries(ctx);
6944 /* if we're handling multiple rings, cap submit size for fairness */
6945 if (cap_entries && to_submit > 8)
6948 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6949 unsigned nr_events = 0;
6951 mutex_lock(&ctx->uring_lock);
6952 if (!list_empty(&ctx->iopoll_list))
6953 io_do_iopoll(ctx, &nr_events, 0);
6955 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)))
6956 ret = io_submit_sqes(ctx, to_submit);
6957 mutex_unlock(&ctx->uring_lock);
6960 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6961 wake_up(&ctx->sqo_sq_wait);
6966 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6968 struct io_ring_ctx *ctx;
6969 unsigned sq_thread_idle = 0;
6971 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6972 if (sq_thread_idle < ctx->sq_thread_idle)
6973 sq_thread_idle = ctx->sq_thread_idle;
6976 sqd->sq_thread_idle = sq_thread_idle;
6979 static void io_sqd_init_new(struct io_sq_data *sqd)
6981 struct io_ring_ctx *ctx;
6983 while (!list_empty(&sqd->ctx_new_list)) {
6984 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6985 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6986 complete(&ctx->sq_thread_comp);
6989 io_sqd_update_thread_idle(sqd);
6992 static int io_sq_thread(void *data)
6994 struct cgroup_subsys_state *cur_css = NULL;
6995 struct files_struct *old_files = current->files;
6996 struct nsproxy *old_nsproxy = current->nsproxy;
6997 const struct cred *old_cred = NULL;
6998 struct io_sq_data *sqd = data;
6999 struct io_ring_ctx *ctx;
7000 unsigned long timeout = 0;
7004 current->files = NULL;
7005 current->nsproxy = NULL;
7006 task_unlock(current);
7008 while (!kthread_should_stop()) {
7010 bool cap_entries, sqt_spin, needs_sched;
7013 * Any changes to the sqd lists are synchronized through the
7014 * kthread parking. This synchronizes the thread vs users,
7015 * the users are synchronized on the sqd->ctx_lock.
7017 if (kthread_should_park()) {
7020 * When sq thread is unparked, in case the previous park operation
7021 * comes from io_put_sq_data(), which means that sq thread is going
7022 * to be stopped, so here needs to have a check.
7024 if (kthread_should_stop())
7028 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
7029 io_sqd_init_new(sqd);
7030 timeout = jiffies + sqd->sq_thread_idle;
7034 cap_entries = !list_is_singular(&sqd->ctx_list);
7035 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7036 if (current->cred != ctx->creds) {
7038 revert_creds(old_cred);
7039 old_cred = override_creds(ctx->creds);
7041 io_sq_thread_associate_blkcg(ctx, &cur_css);
7043 current->loginuid = ctx->loginuid;
7044 current->sessionid = ctx->sessionid;
7047 ret = __io_sq_thread(ctx, cap_entries);
7048 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7051 io_sq_thread_drop_mm_files();
7054 if (sqt_spin || !time_after(jiffies, timeout)) {
7058 timeout = jiffies + sqd->sq_thread_idle;
7062 if (kthread_should_park())
7066 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7067 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7068 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7069 !list_empty_careful(&ctx->iopoll_list)) {
7070 needs_sched = false;
7073 if (io_sqring_entries(ctx)) {
7074 needs_sched = false;
7080 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7081 io_ring_set_wakeup_flag(ctx);
7084 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7085 io_ring_clear_wakeup_flag(ctx);
7088 finish_wait(&sqd->wait, &wait);
7089 timeout = jiffies + sqd->sq_thread_idle;
7095 io_sq_thread_unassociate_blkcg();
7097 revert_creds(old_cred);
7100 current->files = old_files;
7101 current->nsproxy = old_nsproxy;
7102 task_unlock(current);
7109 struct io_wait_queue {
7110 struct wait_queue_entry wq;
7111 struct io_ring_ctx *ctx;
7113 unsigned nr_timeouts;
7116 static inline bool io_should_wake(struct io_wait_queue *iowq)
7118 struct io_ring_ctx *ctx = iowq->ctx;
7121 * Wake up if we have enough events, or if a timeout occurred since we
7122 * started waiting. For timeouts, we always want to return to userspace,
7123 * regardless of event count.
7125 return io_cqring_events(ctx) >= iowq->to_wait ||
7126 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7129 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7130 int wake_flags, void *key)
7132 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7136 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7137 * the task, and the next invocation will do it.
7139 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
7140 return autoremove_wake_function(curr, mode, wake_flags, key);
7144 static int io_run_task_work_sig(void)
7146 if (io_run_task_work())
7148 if (!signal_pending(current))
7150 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
7151 return -ERESTARTSYS;
7156 * Wait until events become available, if we don't already have some. The
7157 * application must reap them itself, as they reside on the shared cq ring.
7159 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7160 const sigset_t __user *sig, size_t sigsz,
7161 struct __kernel_timespec __user *uts)
7163 struct io_wait_queue iowq = {
7166 .func = io_wake_function,
7167 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7170 .to_wait = min_events,
7172 struct io_rings *rings = ctx->rings;
7173 struct timespec64 ts;
7174 signed long timeout = 0;
7178 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7179 if (io_cqring_events(ctx) >= min_events)
7181 if (!io_run_task_work())
7186 #ifdef CONFIG_COMPAT
7187 if (in_compat_syscall())
7188 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7192 ret = set_user_sigmask(sig, sigsz);
7199 if (get_timespec64(&ts, uts))
7201 timeout = timespec64_to_jiffies(&ts);
7204 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7205 trace_io_uring_cqring_wait(ctx, min_events);
7207 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7208 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7209 TASK_INTERRUPTIBLE);
7210 /* make sure we run task_work before checking for signals */
7211 ret = io_run_task_work_sig();
7216 if (io_should_wake(&iowq))
7218 if (test_bit(0, &ctx->cq_check_overflow))
7221 timeout = schedule_timeout(timeout);
7230 finish_wait(&ctx->wait, &iowq.wq);
7232 restore_saved_sigmask_unless(ret == -EINTR);
7234 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7237 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7239 #if defined(CONFIG_UNIX)
7240 if (ctx->ring_sock) {
7241 struct sock *sock = ctx->ring_sock->sk;
7242 struct sk_buff *skb;
7244 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7250 for (i = 0; i < ctx->nr_user_files; i++) {
7253 file = io_file_from_index(ctx, i);
7260 static void io_file_ref_kill(struct percpu_ref *ref)
7262 struct fixed_file_data *data;
7264 data = container_of(ref, struct fixed_file_data, refs);
7265 complete(&data->done);
7268 static void io_sqe_files_set_node(struct fixed_file_data *file_data,
7269 struct fixed_file_ref_node *ref_node)
7271 spin_lock_bh(&file_data->lock);
7272 file_data->node = ref_node;
7273 list_add_tail(&ref_node->node, &file_data->ref_list);
7274 spin_unlock_bh(&file_data->lock);
7275 percpu_ref_get(&file_data->refs);
7278 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7280 struct fixed_file_data *data = ctx->file_data;
7281 struct fixed_file_ref_node *backup_node, *ref_node = NULL;
7282 unsigned nr_tables, i;
7287 backup_node = alloc_fixed_file_ref_node(ctx);
7291 spin_lock_bh(&data->lock);
7292 ref_node = data->node;
7293 spin_unlock_bh(&data->lock);
7295 percpu_ref_kill(&ref_node->refs);
7297 percpu_ref_kill(&data->refs);
7299 /* wait for all refs nodes to complete */
7300 flush_delayed_work(&ctx->file_put_work);
7302 ret = wait_for_completion_interruptible(&data->done);
7305 ret = io_run_task_work_sig();
7307 percpu_ref_resurrect(&data->refs);
7308 reinit_completion(&data->done);
7309 io_sqe_files_set_node(data, backup_node);
7314 __io_sqe_files_unregister(ctx);
7315 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7316 for (i = 0; i < nr_tables; i++)
7317 kfree(data->table[i].files);
7319 percpu_ref_exit(&data->refs);
7321 ctx->file_data = NULL;
7322 ctx->nr_user_files = 0;
7323 destroy_fixed_file_ref_node(backup_node);
7327 static void io_put_sq_data(struct io_sq_data *sqd)
7329 if (refcount_dec_and_test(&sqd->refs)) {
7331 * The park is a bit of a work-around, without it we get
7332 * warning spews on shutdown with SQPOLL set and affinity
7333 * set to a single CPU.
7336 kthread_park(sqd->thread);
7337 kthread_stop(sqd->thread);
7344 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7346 struct io_ring_ctx *ctx_attach;
7347 struct io_sq_data *sqd;
7350 f = fdget(p->wq_fd);
7352 return ERR_PTR(-ENXIO);
7353 if (f.file->f_op != &io_uring_fops) {
7355 return ERR_PTR(-EINVAL);
7358 ctx_attach = f.file->private_data;
7359 sqd = ctx_attach->sq_data;
7362 return ERR_PTR(-EINVAL);
7365 refcount_inc(&sqd->refs);
7370 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7372 struct io_sq_data *sqd;
7374 if (p->flags & IORING_SETUP_ATTACH_WQ)
7375 return io_attach_sq_data(p);
7377 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7379 return ERR_PTR(-ENOMEM);
7381 refcount_set(&sqd->refs, 1);
7382 INIT_LIST_HEAD(&sqd->ctx_list);
7383 INIT_LIST_HEAD(&sqd->ctx_new_list);
7384 mutex_init(&sqd->ctx_lock);
7385 mutex_init(&sqd->lock);
7386 init_waitqueue_head(&sqd->wait);
7390 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7391 __releases(&sqd->lock)
7395 kthread_unpark(sqd->thread);
7396 mutex_unlock(&sqd->lock);
7399 static void io_sq_thread_park(struct io_sq_data *sqd)
7400 __acquires(&sqd->lock)
7404 mutex_lock(&sqd->lock);
7405 kthread_park(sqd->thread);
7408 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7410 struct io_sq_data *sqd = ctx->sq_data;
7415 * We may arrive here from the error branch in
7416 * io_sq_offload_create() where the kthread is created
7417 * without being waked up, thus wake it up now to make
7418 * sure the wait will complete.
7420 wake_up_process(sqd->thread);
7421 wait_for_completion(&ctx->sq_thread_comp);
7423 io_sq_thread_park(sqd);
7426 mutex_lock(&sqd->ctx_lock);
7427 list_del(&ctx->sqd_list);
7428 io_sqd_update_thread_idle(sqd);
7429 mutex_unlock(&sqd->ctx_lock);
7432 io_sq_thread_unpark(sqd);
7434 io_put_sq_data(sqd);
7435 ctx->sq_data = NULL;
7439 static void io_finish_async(struct io_ring_ctx *ctx)
7441 io_sq_thread_stop(ctx);
7444 io_wq_destroy(ctx->io_wq);
7449 #if defined(CONFIG_UNIX)
7451 * Ensure the UNIX gc is aware of our file set, so we are certain that
7452 * the io_uring can be safely unregistered on process exit, even if we have
7453 * loops in the file referencing.
7455 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7457 struct sock *sk = ctx->ring_sock->sk;
7458 struct scm_fp_list *fpl;
7459 struct sk_buff *skb;
7462 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7466 skb = alloc_skb(0, GFP_KERNEL);
7475 fpl->user = get_uid(ctx->user);
7476 for (i = 0; i < nr; i++) {
7477 struct file *file = io_file_from_index(ctx, i + offset);
7481 fpl->fp[nr_files] = get_file(file);
7482 unix_inflight(fpl->user, fpl->fp[nr_files]);
7487 fpl->max = SCM_MAX_FD;
7488 fpl->count = nr_files;
7489 UNIXCB(skb).fp = fpl;
7490 skb->destructor = unix_destruct_scm;
7491 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7492 skb_queue_head(&sk->sk_receive_queue, skb);
7494 for (i = 0; i < nr_files; i++)
7505 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7506 * causes regular reference counting to break down. We rely on the UNIX
7507 * garbage collection to take care of this problem for us.
7509 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7511 unsigned left, total;
7515 left = ctx->nr_user_files;
7517 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7519 ret = __io_sqe_files_scm(ctx, this_files, total);
7523 total += this_files;
7529 while (total < ctx->nr_user_files) {
7530 struct file *file = io_file_from_index(ctx, total);
7540 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7546 static int io_sqe_alloc_file_tables(struct fixed_file_data *file_data,
7547 unsigned nr_tables, unsigned nr_files)
7551 for (i = 0; i < nr_tables; i++) {
7552 struct fixed_file_table *table = &file_data->table[i];
7553 unsigned this_files;
7555 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7556 table->files = kcalloc(this_files, sizeof(struct file *),
7560 nr_files -= this_files;
7566 for (i = 0; i < nr_tables; i++) {
7567 struct fixed_file_table *table = &file_data->table[i];
7568 kfree(table->files);
7573 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
7575 #if defined(CONFIG_UNIX)
7576 struct sock *sock = ctx->ring_sock->sk;
7577 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7578 struct sk_buff *skb;
7581 __skb_queue_head_init(&list);
7584 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7585 * remove this entry and rearrange the file array.
7587 skb = skb_dequeue(head);
7589 struct scm_fp_list *fp;
7591 fp = UNIXCB(skb).fp;
7592 for (i = 0; i < fp->count; i++) {
7595 if (fp->fp[i] != file)
7598 unix_notinflight(fp->user, fp->fp[i]);
7599 left = fp->count - 1 - i;
7601 memmove(&fp->fp[i], &fp->fp[i + 1],
7602 left * sizeof(struct file *));
7609 __skb_queue_tail(&list, skb);
7619 __skb_queue_tail(&list, skb);
7621 skb = skb_dequeue(head);
7624 if (skb_peek(&list)) {
7625 spin_lock_irq(&head->lock);
7626 while ((skb = __skb_dequeue(&list)) != NULL)
7627 __skb_queue_tail(head, skb);
7628 spin_unlock_irq(&head->lock);
7635 struct io_file_put {
7636 struct list_head list;
7640 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
7642 struct fixed_file_data *file_data = ref_node->file_data;
7643 struct io_ring_ctx *ctx = file_data->ctx;
7644 struct io_file_put *pfile, *tmp;
7646 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
7647 list_del(&pfile->list);
7648 io_ring_file_put(ctx, pfile->file);
7652 percpu_ref_exit(&ref_node->refs);
7654 percpu_ref_put(&file_data->refs);
7657 static void io_file_put_work(struct work_struct *work)
7659 struct io_ring_ctx *ctx;
7660 struct llist_node *node;
7662 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
7663 node = llist_del_all(&ctx->file_put_llist);
7666 struct fixed_file_ref_node *ref_node;
7667 struct llist_node *next = node->next;
7669 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
7670 __io_file_put_work(ref_node);
7675 static void io_file_data_ref_zero(struct percpu_ref *ref)
7677 struct fixed_file_ref_node *ref_node;
7678 struct fixed_file_data *data;
7679 struct io_ring_ctx *ctx;
7680 bool first_add = false;
7683 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
7684 data = ref_node->file_data;
7687 spin_lock_bh(&data->lock);
7688 ref_node->done = true;
7690 while (!list_empty(&data->ref_list)) {
7691 ref_node = list_first_entry(&data->ref_list,
7692 struct fixed_file_ref_node, node);
7693 /* recycle ref nodes in order */
7694 if (!ref_node->done)
7696 list_del(&ref_node->node);
7697 first_add |= llist_add(&ref_node->llist, &ctx->file_put_llist);
7699 spin_unlock_bh(&data->lock);
7701 if (percpu_ref_is_dying(&data->refs))
7705 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
7707 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
7710 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
7711 struct io_ring_ctx *ctx)
7713 struct fixed_file_ref_node *ref_node;
7715 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7719 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
7724 INIT_LIST_HEAD(&ref_node->node);
7725 INIT_LIST_HEAD(&ref_node->file_list);
7726 ref_node->file_data = ctx->file_data;
7727 ref_node->done = false;
7731 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
7733 percpu_ref_exit(&ref_node->refs);
7737 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7740 __s32 __user *fds = (__s32 __user *) arg;
7741 unsigned nr_tables, i;
7743 int fd, ret = -ENOMEM;
7744 struct fixed_file_ref_node *ref_node;
7745 struct fixed_file_data *file_data;
7751 if (nr_args > IORING_MAX_FIXED_FILES)
7754 file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
7757 file_data->ctx = ctx;
7758 init_completion(&file_data->done);
7759 INIT_LIST_HEAD(&file_data->ref_list);
7760 spin_lock_init(&file_data->lock);
7762 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7763 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7765 if (!file_data->table)
7768 if (percpu_ref_init(&file_data->refs, io_file_ref_kill,
7769 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
7772 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7774 ctx->file_data = file_data;
7776 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7777 struct fixed_file_table *table;
7780 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7784 /* allow sparse sets */
7794 * Don't allow io_uring instances to be registered. If UNIX
7795 * isn't enabled, then this causes a reference cycle and this
7796 * instance can never get freed. If UNIX is enabled we'll
7797 * handle it just fine, but there's still no point in allowing
7798 * a ring fd as it doesn't support regular read/write anyway.
7800 if (file->f_op == &io_uring_fops) {
7804 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7805 index = i & IORING_FILE_TABLE_MASK;
7806 table->files[index] = file;
7809 ret = io_sqe_files_scm(ctx);
7811 io_sqe_files_unregister(ctx);
7815 ref_node = alloc_fixed_file_ref_node(ctx);
7817 io_sqe_files_unregister(ctx);
7821 io_sqe_files_set_node(file_data, ref_node);
7824 for (i = 0; i < ctx->nr_user_files; i++) {
7825 file = io_file_from_index(ctx, i);
7829 for (i = 0; i < nr_tables; i++)
7830 kfree(file_data->table[i].files);
7831 ctx->nr_user_files = 0;
7833 percpu_ref_exit(&file_data->refs);
7835 kfree(file_data->table);
7837 ctx->file_data = NULL;
7841 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7844 #if defined(CONFIG_UNIX)
7845 struct sock *sock = ctx->ring_sock->sk;
7846 struct sk_buff_head *head = &sock->sk_receive_queue;
7847 struct sk_buff *skb;
7850 * See if we can merge this file into an existing skb SCM_RIGHTS
7851 * file set. If there's no room, fall back to allocating a new skb
7852 * and filling it in.
7854 spin_lock_irq(&head->lock);
7855 skb = skb_peek(head);
7857 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7859 if (fpl->count < SCM_MAX_FD) {
7860 __skb_unlink(skb, head);
7861 spin_unlock_irq(&head->lock);
7862 fpl->fp[fpl->count] = get_file(file);
7863 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7865 spin_lock_irq(&head->lock);
7866 __skb_queue_head(head, skb);
7871 spin_unlock_irq(&head->lock);
7878 return __io_sqe_files_scm(ctx, 1, index);
7884 static int io_queue_file_removal(struct fixed_file_data *data,
7887 struct io_file_put *pfile;
7888 struct fixed_file_ref_node *ref_node = data->node;
7890 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7895 list_add(&pfile->list, &ref_node->file_list);
7900 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7901 struct io_uring_files_update *up,
7904 struct fixed_file_data *data = ctx->file_data;
7905 struct fixed_file_ref_node *ref_node;
7910 bool needs_switch = false;
7912 if (check_add_overflow(up->offset, nr_args, &done))
7914 if (done > ctx->nr_user_files)
7917 ref_node = alloc_fixed_file_ref_node(ctx);
7922 fds = u64_to_user_ptr(up->fds);
7924 struct fixed_file_table *table;
7928 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7932 i = array_index_nospec(up->offset, ctx->nr_user_files);
7933 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7934 index = i & IORING_FILE_TABLE_MASK;
7935 if (table->files[index]) {
7936 file = table->files[index];
7937 err = io_queue_file_removal(data, file);
7940 table->files[index] = NULL;
7941 needs_switch = true;
7950 * Don't allow io_uring instances to be registered. If
7951 * UNIX isn't enabled, then this causes a reference
7952 * cycle and this instance can never get freed. If UNIX
7953 * is enabled we'll handle it just fine, but there's
7954 * still no point in allowing a ring fd as it doesn't
7955 * support regular read/write anyway.
7957 if (file->f_op == &io_uring_fops) {
7962 table->files[index] = file;
7963 err = io_sqe_file_register(ctx, file, i);
7965 table->files[index] = NULL;
7976 percpu_ref_kill(&data->node->refs);
7977 io_sqe_files_set_node(data, ref_node);
7979 destroy_fixed_file_ref_node(ref_node);
7981 return done ? done : err;
7984 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7987 struct io_uring_files_update up;
7989 if (!ctx->file_data)
7993 if (copy_from_user(&up, arg, sizeof(up)))
7998 return __io_sqe_files_update(ctx, &up, nr_args);
8001 static void io_free_work(struct io_wq_work *work)
8003 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8005 /* Consider that io_steal_work() relies on this ref */
8009 static int io_init_wq_offload(struct io_ring_ctx *ctx,
8010 struct io_uring_params *p)
8012 struct io_wq_data data;
8014 struct io_ring_ctx *ctx_attach;
8015 unsigned int concurrency;
8018 data.user = ctx->user;
8019 data.free_work = io_free_work;
8020 data.do_work = io_wq_submit_work;
8022 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
8023 /* Do QD, or 4 * CPUS, whatever is smallest */
8024 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8026 ctx->io_wq = io_wq_create(concurrency, &data);
8027 if (IS_ERR(ctx->io_wq)) {
8028 ret = PTR_ERR(ctx->io_wq);
8034 f = fdget(p->wq_fd);
8038 if (f.file->f_op != &io_uring_fops) {
8043 ctx_attach = f.file->private_data;
8044 /* @io_wq is protected by holding the fd */
8045 if (!io_wq_get(ctx_attach->io_wq, &data)) {
8050 ctx->io_wq = ctx_attach->io_wq;
8056 static int io_uring_alloc_task_context(struct task_struct *task)
8058 struct io_uring_task *tctx;
8061 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
8062 if (unlikely(!tctx))
8065 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8066 if (unlikely(ret)) {
8072 init_waitqueue_head(&tctx->wait);
8074 atomic_set(&tctx->in_idle, 0);
8075 tctx->sqpoll = false;
8076 io_init_identity(&tctx->__identity);
8077 tctx->identity = &tctx->__identity;
8078 task->io_uring = tctx;
8082 void __io_uring_free(struct task_struct *tsk)
8084 struct io_uring_task *tctx = tsk->io_uring;
8086 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8087 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
8088 if (tctx->identity != &tctx->__identity)
8089 kfree(tctx->identity);
8090 percpu_counter_destroy(&tctx->inflight);
8092 tsk->io_uring = NULL;
8095 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8096 struct io_uring_params *p)
8100 if (ctx->flags & IORING_SETUP_SQPOLL) {
8101 struct io_sq_data *sqd;
8104 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
8107 sqd = io_get_sq_data(p);
8114 io_sq_thread_park(sqd);
8115 mutex_lock(&sqd->ctx_lock);
8116 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
8117 mutex_unlock(&sqd->ctx_lock);
8118 io_sq_thread_unpark(sqd);
8120 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8121 if (!ctx->sq_thread_idle)
8122 ctx->sq_thread_idle = HZ;
8127 if (p->flags & IORING_SETUP_SQ_AFF) {
8128 int cpu = p->sq_thread_cpu;
8131 if (cpu >= nr_cpu_ids)
8133 if (!cpu_online(cpu))
8136 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8137 cpu, "io_uring-sq");
8139 sqd->thread = kthread_create(io_sq_thread, sqd,
8142 if (IS_ERR(sqd->thread)) {
8143 ret = PTR_ERR(sqd->thread);
8147 ret = io_uring_alloc_task_context(sqd->thread);
8150 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8151 /* Can't have SQ_AFF without SQPOLL */
8157 ret = io_init_wq_offload(ctx, p);
8163 io_finish_async(ctx);
8167 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8169 struct io_sq_data *sqd = ctx->sq_data;
8171 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8172 wake_up_process(sqd->thread);
8175 static inline void __io_unaccount_mem(struct user_struct *user,
8176 unsigned long nr_pages)
8178 atomic_long_sub(nr_pages, &user->locked_vm);
8181 static inline int __io_account_mem(struct user_struct *user,
8182 unsigned long nr_pages)
8184 unsigned long page_limit, cur_pages, new_pages;
8186 /* Don't allow more pages than we can safely lock */
8187 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8190 cur_pages = atomic_long_read(&user->locked_vm);
8191 new_pages = cur_pages + nr_pages;
8192 if (new_pages > page_limit)
8194 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8195 new_pages) != cur_pages);
8200 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8201 enum io_mem_account acct)
8204 __io_unaccount_mem(ctx->user, nr_pages);
8206 if (ctx->mm_account) {
8207 if (acct == ACCT_LOCKED) {
8208 mmap_write_lock(ctx->mm_account);
8209 ctx->mm_account->locked_vm -= nr_pages;
8210 mmap_write_unlock(ctx->mm_account);
8211 }else if (acct == ACCT_PINNED) {
8212 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8217 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8218 enum io_mem_account acct)
8222 if (ctx->limit_mem) {
8223 ret = __io_account_mem(ctx->user, nr_pages);
8228 if (ctx->mm_account) {
8229 if (acct == ACCT_LOCKED) {
8230 mmap_write_lock(ctx->mm_account);
8231 ctx->mm_account->locked_vm += nr_pages;
8232 mmap_write_unlock(ctx->mm_account);
8233 } else if (acct == ACCT_PINNED) {
8234 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8241 static void io_mem_free(void *ptr)
8248 page = virt_to_head_page(ptr);
8249 if (put_page_testzero(page))
8250 free_compound_page(page);
8253 static void *io_mem_alloc(size_t size)
8255 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8258 return (void *) __get_free_pages(gfp_flags, get_order(size));
8261 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8264 struct io_rings *rings;
8265 size_t off, sq_array_size;
8267 off = struct_size(rings, cqes, cq_entries);
8268 if (off == SIZE_MAX)
8272 off = ALIGN(off, SMP_CACHE_BYTES);
8280 sq_array_size = array_size(sizeof(u32), sq_entries);
8281 if (sq_array_size == SIZE_MAX)
8284 if (check_add_overflow(off, sq_array_size, &off))
8290 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
8294 pages = (size_t)1 << get_order(
8295 rings_size(sq_entries, cq_entries, NULL));
8296 pages += (size_t)1 << get_order(
8297 array_size(sizeof(struct io_uring_sqe), sq_entries));
8302 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
8306 if (!ctx->user_bufs)
8309 for (i = 0; i < ctx->nr_user_bufs; i++) {
8310 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8312 for (j = 0; j < imu->nr_bvecs; j++)
8313 unpin_user_page(imu->bvec[j].bv_page);
8315 if (imu->acct_pages)
8316 io_unaccount_mem(ctx, imu->acct_pages, ACCT_PINNED);
8321 kfree(ctx->user_bufs);
8322 ctx->user_bufs = NULL;
8323 ctx->nr_user_bufs = 0;
8327 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8328 void __user *arg, unsigned index)
8330 struct iovec __user *src;
8332 #ifdef CONFIG_COMPAT
8334 struct compat_iovec __user *ciovs;
8335 struct compat_iovec ciov;
8337 ciovs = (struct compat_iovec __user *) arg;
8338 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8341 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8342 dst->iov_len = ciov.iov_len;
8346 src = (struct iovec __user *) arg;
8347 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8353 * Not super efficient, but this is just a registration time. And we do cache
8354 * the last compound head, so generally we'll only do a full search if we don't
8357 * We check if the given compound head page has already been accounted, to
8358 * avoid double accounting it. This allows us to account the full size of the
8359 * page, not just the constituent pages of a huge page.
8361 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8362 int nr_pages, struct page *hpage)
8366 /* check current page array */
8367 for (i = 0; i < nr_pages; i++) {
8368 if (!PageCompound(pages[i]))
8370 if (compound_head(pages[i]) == hpage)
8374 /* check previously registered pages */
8375 for (i = 0; i < ctx->nr_user_bufs; i++) {
8376 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8378 for (j = 0; j < imu->nr_bvecs; j++) {
8379 if (!PageCompound(imu->bvec[j].bv_page))
8381 if (compound_head(imu->bvec[j].bv_page) == hpage)
8389 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8390 int nr_pages, struct io_mapped_ubuf *imu,
8391 struct page **last_hpage)
8395 for (i = 0; i < nr_pages; i++) {
8396 if (!PageCompound(pages[i])) {
8401 hpage = compound_head(pages[i]);
8402 if (hpage == *last_hpage)
8404 *last_hpage = hpage;
8405 if (headpage_already_acct(ctx, pages, i, hpage))
8407 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8411 if (!imu->acct_pages)
8414 ret = io_account_mem(ctx, imu->acct_pages, ACCT_PINNED);
8416 imu->acct_pages = 0;
8420 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
8423 struct vm_area_struct **vmas = NULL;
8424 struct page **pages = NULL;
8425 struct page *last_hpage = NULL;
8426 int i, j, got_pages = 0;
8431 if (!nr_args || nr_args > UIO_MAXIOV)
8434 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8436 if (!ctx->user_bufs)
8439 for (i = 0; i < nr_args; i++) {
8440 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8441 unsigned long off, start, end, ubuf;
8446 ret = io_copy_iov(ctx, &iov, arg, i);
8451 * Don't impose further limits on the size and buffer
8452 * constraints here, we'll -EINVAL later when IO is
8453 * submitted if they are wrong.
8456 if (!iov.iov_base || !iov.iov_len)
8459 /* arbitrary limit, but we need something */
8460 if (iov.iov_len > SZ_1G)
8463 ubuf = (unsigned long) iov.iov_base;
8464 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8465 start = ubuf >> PAGE_SHIFT;
8466 nr_pages = end - start;
8469 if (!pages || nr_pages > got_pages) {
8472 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
8474 vmas = kvmalloc_array(nr_pages,
8475 sizeof(struct vm_area_struct *),
8477 if (!pages || !vmas) {
8481 got_pages = nr_pages;
8484 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8491 mmap_read_lock(current->mm);
8492 pret = pin_user_pages(ubuf, nr_pages,
8493 FOLL_WRITE | FOLL_LONGTERM,
8495 if (pret == nr_pages) {
8496 /* don't support file backed memory */
8497 for (j = 0; j < nr_pages; j++) {
8498 struct vm_area_struct *vma = vmas[j];
8501 !is_file_hugepages(vma->vm_file)) {
8507 ret = pret < 0 ? pret : -EFAULT;
8509 mmap_read_unlock(current->mm);
8512 * if we did partial map, or found file backed vmas,
8513 * release any pages we did get
8516 unpin_user_pages(pages, pret);
8521 ret = io_buffer_account_pin(ctx, pages, pret, imu, &last_hpage);
8523 unpin_user_pages(pages, pret);
8528 off = ubuf & ~PAGE_MASK;
8530 for (j = 0; j < nr_pages; j++) {
8533 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8534 imu->bvec[j].bv_page = pages[j];
8535 imu->bvec[j].bv_len = vec_len;
8536 imu->bvec[j].bv_offset = off;
8540 /* store original address for later verification */
8542 imu->len = iov.iov_len;
8543 imu->nr_bvecs = nr_pages;
8545 ctx->nr_user_bufs++;
8553 io_sqe_buffer_unregister(ctx);
8557 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8559 __s32 __user *fds = arg;
8565 if (copy_from_user(&fd, fds, sizeof(*fds)))
8568 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8569 if (IS_ERR(ctx->cq_ev_fd)) {
8570 int ret = PTR_ERR(ctx->cq_ev_fd);
8571 ctx->cq_ev_fd = NULL;
8578 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8580 if (ctx->cq_ev_fd) {
8581 eventfd_ctx_put(ctx->cq_ev_fd);
8582 ctx->cq_ev_fd = NULL;
8589 static int __io_destroy_buffers(int id, void *p, void *data)
8591 struct io_ring_ctx *ctx = data;
8592 struct io_buffer *buf = p;
8594 __io_remove_buffers(ctx, buf, id, -1U);
8598 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8600 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8601 idr_destroy(&ctx->io_buffer_idr);
8604 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8606 io_finish_async(ctx);
8607 io_sqe_buffer_unregister(ctx);
8609 if (ctx->sqo_task) {
8610 put_task_struct(ctx->sqo_task);
8611 ctx->sqo_task = NULL;
8612 mmdrop(ctx->mm_account);
8613 ctx->mm_account = NULL;
8616 #ifdef CONFIG_BLK_CGROUP
8617 if (ctx->sqo_blkcg_css)
8618 css_put(ctx->sqo_blkcg_css);
8621 io_sqe_files_unregister(ctx);
8622 io_eventfd_unregister(ctx);
8623 io_destroy_buffers(ctx);
8624 idr_destroy(&ctx->personality_idr);
8626 #if defined(CONFIG_UNIX)
8627 if (ctx->ring_sock) {
8628 ctx->ring_sock->file = NULL; /* so that iput() is called */
8629 sock_release(ctx->ring_sock);
8633 io_mem_free(ctx->rings);
8634 io_mem_free(ctx->sq_sqes);
8636 percpu_ref_exit(&ctx->refs);
8637 free_uid(ctx->user);
8638 put_cred(ctx->creds);
8639 kfree(ctx->cancel_hash);
8640 kmem_cache_free(req_cachep, ctx->fallback_req);
8644 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8646 struct io_ring_ctx *ctx = file->private_data;
8649 poll_wait(file, &ctx->cq_wait, wait);
8651 * synchronizes with barrier from wq_has_sleeper call in
8655 if (!io_sqring_full(ctx))
8656 mask |= EPOLLOUT | EPOLLWRNORM;
8657 io_cqring_overflow_flush(ctx, false, NULL, NULL);
8658 if (io_cqring_events(ctx))
8659 mask |= EPOLLIN | EPOLLRDNORM;
8664 static int io_uring_fasync(int fd, struct file *file, int on)
8666 struct io_ring_ctx *ctx = file->private_data;
8668 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8671 static int io_remove_personalities(int id, void *p, void *data)
8673 struct io_ring_ctx *ctx = data;
8674 struct io_identity *iod;
8676 iod = idr_remove(&ctx->personality_idr, id);
8678 put_cred(iod->creds);
8679 if (refcount_dec_and_test(&iod->count))
8685 static void io_ring_exit_work(struct work_struct *work)
8687 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8691 * If we're doing polled IO and end up having requests being
8692 * submitted async (out-of-line), then completions can come in while
8693 * we're waiting for refs to drop. We need to reap these manually,
8694 * as nobody else will be looking for them.
8697 __io_uring_cancel_task_requests(ctx, NULL);
8698 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8699 io_ring_ctx_free(ctx);
8702 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8704 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8706 return req->ctx == data;
8709 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8711 mutex_lock(&ctx->uring_lock);
8712 percpu_ref_kill(&ctx->refs);
8713 /* if force is set, the ring is going away. always drop after that */
8714 ctx->cq_overflow_flushed = 1;
8716 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8717 mutex_unlock(&ctx->uring_lock);
8719 io_kill_timeouts(ctx, NULL, NULL);
8720 io_poll_remove_all(ctx, NULL, NULL);
8723 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8725 /* if we failed setting up the ctx, we might not have any rings */
8726 io_iopoll_try_reap_events(ctx);
8727 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8730 * Do this upfront, so we won't have a grace period where the ring
8731 * is closed but resources aren't reaped yet. This can cause
8732 * spurious failure in setting up a new ring.
8734 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
8737 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8739 * Use system_unbound_wq to avoid spawning tons of event kworkers
8740 * if we're exiting a ton of rings at the same time. It just adds
8741 * noise and overhead, there's no discernable change in runtime
8742 * over using system_wq.
8744 queue_work(system_unbound_wq, &ctx->exit_work);
8747 static int io_uring_release(struct inode *inode, struct file *file)
8749 struct io_ring_ctx *ctx = file->private_data;
8751 file->private_data = NULL;
8752 io_ring_ctx_wait_and_kill(ctx);
8756 struct io_task_cancel {
8757 struct task_struct *task;
8758 struct files_struct *files;
8761 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8763 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8764 struct io_task_cancel *cancel = data;
8767 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8768 unsigned long flags;
8769 struct io_ring_ctx *ctx = req->ctx;
8771 /* protect against races with linked timeouts */
8772 spin_lock_irqsave(&ctx->completion_lock, flags);
8773 ret = io_match_task(req, cancel->task, cancel->files);
8774 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8776 ret = io_match_task(req, cancel->task, cancel->files);
8781 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8782 struct task_struct *task,
8783 struct files_struct *files)
8785 struct io_defer_entry *de = NULL;
8788 spin_lock_irq(&ctx->completion_lock);
8789 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8790 if (io_match_task(de->req, task, files)) {
8791 list_cut_position(&list, &ctx->defer_list, &de->list);
8795 spin_unlock_irq(&ctx->completion_lock);
8797 while (!list_empty(&list)) {
8798 de = list_first_entry(&list, struct io_defer_entry, list);
8799 list_del_init(&de->list);
8800 req_set_fail_links(de->req);
8801 io_put_req(de->req);
8802 io_req_complete(de->req, -ECANCELED);
8807 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8808 struct task_struct *task,
8809 struct files_struct *files)
8811 while (!list_empty_careful(&ctx->inflight_list)) {
8812 struct io_task_cancel cancel = { .task = task, .files = files };
8813 struct io_kiocb *req;
8817 spin_lock_irq(&ctx->inflight_lock);
8818 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
8819 if (req->task != task ||
8820 req->work.identity->files != files)
8826 prepare_to_wait(&task->io_uring->wait, &wait,
8827 TASK_UNINTERRUPTIBLE);
8828 spin_unlock_irq(&ctx->inflight_lock);
8830 /* We need to keep going until we don't find a matching req */
8834 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, &cancel, true);
8835 io_poll_remove_all(ctx, task, files);
8836 io_kill_timeouts(ctx, task, files);
8837 /* cancellations _may_ trigger task work */
8840 finish_wait(&task->io_uring->wait, &wait);
8844 static void __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8845 struct task_struct *task)
8848 struct io_task_cancel cancel = { .task = task, .files = NULL, };
8849 enum io_wq_cancel cret;
8853 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb,
8855 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8858 /* SQPOLL thread does its own polling */
8859 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8860 while (!list_empty_careful(&ctx->iopoll_list)) {
8861 io_iopoll_try_reap_events(ctx);
8866 ret |= io_poll_remove_all(ctx, task, NULL);
8867 ret |= io_kill_timeouts(ctx, task, NULL);
8868 ret |= io_run_task_work();
8876 * We need to iteratively cancel requests, in case a request has dependent
8877 * hard links. These persist even for failure of cancelations, hence keep
8878 * looping until none are found.
8880 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8881 struct files_struct *files)
8883 struct task_struct *task = current;
8885 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8886 task = ctx->sq_data->thread;
8887 atomic_inc(&task->io_uring->in_idle);
8888 io_sq_thread_park(ctx->sq_data);
8891 io_cancel_defer_files(ctx, task, files);
8892 io_cqring_overflow_flush(ctx, true, task, files);
8895 __io_uring_cancel_task_requests(ctx, task);
8897 io_uring_cancel_files(ctx, task, files);
8899 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8900 atomic_dec(&task->io_uring->in_idle);
8902 * If the files that are going away are the ones in the thread
8903 * identity, clear them out.
8905 if (task->io_uring->identity->files == files)
8906 task->io_uring->identity->files = NULL;
8907 io_sq_thread_unpark(ctx->sq_data);
8912 * Note that this task has used io_uring. We use it for cancelation purposes.
8914 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8916 struct io_uring_task *tctx = current->io_uring;
8919 if (unlikely(!tctx)) {
8920 ret = io_uring_alloc_task_context(current);
8923 tctx = current->io_uring;
8925 if (tctx->last != file) {
8926 void *old = xa_load(&tctx->xa, (unsigned long)file);
8930 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8941 * This is race safe in that the task itself is doing this, hence it
8942 * cannot be going through the exit/cancel paths at the same time.
8943 * This cannot be modified while exit/cancel is running.
8945 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8946 tctx->sqpoll = true;
8952 * Remove this io_uring_file -> task mapping.
8954 static void io_uring_del_task_file(struct file *file)
8956 struct io_uring_task *tctx = current->io_uring;
8958 if (tctx->last == file)
8960 file = xa_erase(&tctx->xa, (unsigned long)file);
8966 * Drop task note for this file if we're the only ones that hold it after
8969 static void io_uring_attempt_task_drop(struct file *file)
8971 if (!current->io_uring)
8974 * fput() is pending, will be 2 if the only other ref is our potential
8975 * task file note. If the task is exiting, drop regardless of count.
8977 if (fatal_signal_pending(current) || (current->flags & PF_EXITING) ||
8978 atomic_long_read(&file->f_count) == 2)
8979 io_uring_del_task_file(file);
8982 static void io_uring_remove_task_files(struct io_uring_task *tctx)
8985 unsigned long index;
8987 xa_for_each(&tctx->xa, index, file)
8988 io_uring_del_task_file(file);
8991 void __io_uring_files_cancel(struct files_struct *files)
8993 struct io_uring_task *tctx = current->io_uring;
8995 unsigned long index;
8997 /* make sure overflow events are dropped */
8998 atomic_inc(&tctx->in_idle);
8999 xa_for_each(&tctx->xa, index, file)
9000 io_uring_cancel_task_requests(file->private_data, files);
9001 atomic_dec(&tctx->in_idle);
9004 io_uring_remove_task_files(tctx);
9007 static s64 tctx_inflight(struct io_uring_task *tctx)
9009 unsigned long index;
9013 inflight = percpu_counter_sum(&tctx->inflight);
9018 * If we have SQPOLL rings, then we need to iterate and find them, and
9019 * add the pending count for those.
9021 xa_for_each(&tctx->xa, index, file) {
9022 struct io_ring_ctx *ctx = file->private_data;
9024 if (ctx->flags & IORING_SETUP_SQPOLL) {
9025 struct io_uring_task *__tctx = ctx->sqo_task->io_uring;
9027 inflight += percpu_counter_sum(&__tctx->inflight);
9035 * Find any io_uring fd that this task has registered or done IO on, and cancel
9038 void __io_uring_task_cancel(void)
9040 struct io_uring_task *tctx = current->io_uring;
9044 /* make sure overflow events are dropped */
9045 atomic_inc(&tctx->in_idle);
9048 /* read completions before cancelations */
9049 inflight = tctx_inflight(tctx);
9052 __io_uring_files_cancel(NULL);
9054 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9057 * If we've seen completions, retry. This avoids a race where
9058 * a completion comes in before we did prepare_to_wait().
9060 if (inflight != tctx_inflight(tctx))
9063 finish_wait(&tctx->wait, &wait);
9066 atomic_dec(&tctx->in_idle);
9068 io_uring_remove_task_files(tctx);
9071 static int io_uring_flush(struct file *file, void *data)
9073 io_uring_attempt_task_drop(file);
9077 static void *io_uring_validate_mmap_request(struct file *file,
9078 loff_t pgoff, size_t sz)
9080 struct io_ring_ctx *ctx = file->private_data;
9081 loff_t offset = pgoff << PAGE_SHIFT;
9086 case IORING_OFF_SQ_RING:
9087 case IORING_OFF_CQ_RING:
9090 case IORING_OFF_SQES:
9094 return ERR_PTR(-EINVAL);
9097 page = virt_to_head_page(ptr);
9098 if (sz > page_size(page))
9099 return ERR_PTR(-EINVAL);
9106 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9108 size_t sz = vma->vm_end - vma->vm_start;
9112 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9114 return PTR_ERR(ptr);
9116 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9117 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9120 #else /* !CONFIG_MMU */
9122 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9124 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9127 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9129 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9132 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9133 unsigned long addr, unsigned long len,
9134 unsigned long pgoff, unsigned long flags)
9138 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9140 return PTR_ERR(ptr);
9142 return (unsigned long) ptr;
9145 #endif /* !CONFIG_MMU */
9147 static void io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9152 if (!io_sqring_full(ctx))
9155 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9157 if (!io_sqring_full(ctx))
9161 } while (!signal_pending(current));
9163 finish_wait(&ctx->sqo_sq_wait, &wait);
9166 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9167 struct __kernel_timespec __user **ts,
9168 const sigset_t __user **sig)
9170 struct io_uring_getevents_arg arg;
9173 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9174 * is just a pointer to the sigset_t.
9176 if (!(flags & IORING_ENTER_EXT_ARG)) {
9177 *sig = (const sigset_t __user *) argp;
9183 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9184 * timespec and sigset_t pointers if good.
9186 if (*argsz != sizeof(arg))
9188 if (copy_from_user(&arg, argp, sizeof(arg)))
9190 *sig = u64_to_user_ptr(arg.sigmask);
9191 *argsz = arg.sigmask_sz;
9192 *ts = u64_to_user_ptr(arg.ts);
9196 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9197 u32, min_complete, u32, flags, const void __user *, argp,
9200 struct io_ring_ctx *ctx;
9207 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9208 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9216 if (f.file->f_op != &io_uring_fops)
9220 ctx = f.file->private_data;
9221 if (!percpu_ref_tryget(&ctx->refs))
9225 if (ctx->flags & IORING_SETUP_R_DISABLED)
9229 * For SQ polling, the thread will do all submissions and completions.
9230 * Just return the requested submit count, and wake the thread if
9234 if (ctx->flags & IORING_SETUP_SQPOLL) {
9235 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9237 if (flags & IORING_ENTER_SQ_WAKEUP)
9238 wake_up(&ctx->sq_data->wait);
9239 if (flags & IORING_ENTER_SQ_WAIT)
9240 io_sqpoll_wait_sq(ctx);
9241 submitted = to_submit;
9242 } else if (to_submit) {
9243 ret = io_uring_add_task_file(ctx, f.file);
9246 mutex_lock(&ctx->uring_lock);
9247 submitted = io_submit_sqes(ctx, to_submit);
9248 mutex_unlock(&ctx->uring_lock);
9250 if (submitted != to_submit)
9253 if (flags & IORING_ENTER_GETEVENTS) {
9254 const sigset_t __user *sig;
9255 struct __kernel_timespec __user *ts;
9257 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9261 min_complete = min(min_complete, ctx->cq_entries);
9264 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9265 * space applications don't need to do io completion events
9266 * polling again, they can rely on io_sq_thread to do polling
9267 * work, which can reduce cpu usage and uring_lock contention.
9269 if (ctx->flags & IORING_SETUP_IOPOLL &&
9270 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9271 ret = io_iopoll_check(ctx, min_complete);
9273 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9278 percpu_ref_put(&ctx->refs);
9281 return submitted ? submitted : ret;
9284 #ifdef CONFIG_PROC_FS
9285 static int io_uring_show_cred(int id, void *p, void *data)
9287 struct io_identity *iod = p;
9288 const struct cred *cred = iod->creds;
9289 struct seq_file *m = data;
9290 struct user_namespace *uns = seq_user_ns(m);
9291 struct group_info *gi;
9296 seq_printf(m, "%5d\n", id);
9297 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9298 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9299 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9300 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9301 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9302 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9303 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9304 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9305 seq_puts(m, "\n\tGroups:\t");
9306 gi = cred->group_info;
9307 for (g = 0; g < gi->ngroups; g++) {
9308 seq_put_decimal_ull(m, g ? " " : "",
9309 from_kgid_munged(uns, gi->gid[g]));
9311 seq_puts(m, "\n\tCapEff:\t");
9312 cap = cred->cap_effective;
9313 CAP_FOR_EACH_U32(__capi)
9314 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9319 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9321 struct io_sq_data *sq = NULL;
9326 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9327 * since fdinfo case grabs it in the opposite direction of normal use
9328 * cases. If we fail to get the lock, we just don't iterate any
9329 * structures that could be going away outside the io_uring mutex.
9331 has_lock = mutex_trylock(&ctx->uring_lock);
9333 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9336 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9337 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9338 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9339 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9340 struct fixed_file_table *table;
9343 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
9344 f = table->files[i & IORING_FILE_TABLE_MASK];
9346 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9348 seq_printf(m, "%5u: <none>\n", i);
9350 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9351 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9352 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9354 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9355 (unsigned int) buf->len);
9357 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9358 seq_printf(m, "Personalities:\n");
9359 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9361 seq_printf(m, "PollList:\n");
9362 spin_lock_irq(&ctx->completion_lock);
9363 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9364 struct hlist_head *list = &ctx->cancel_hash[i];
9365 struct io_kiocb *req;
9367 hlist_for_each_entry(req, list, hash_node)
9368 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9369 req->task->task_works != NULL);
9371 spin_unlock_irq(&ctx->completion_lock);
9373 mutex_unlock(&ctx->uring_lock);
9376 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9378 struct io_ring_ctx *ctx = f->private_data;
9380 if (percpu_ref_tryget(&ctx->refs)) {
9381 __io_uring_show_fdinfo(ctx, m);
9382 percpu_ref_put(&ctx->refs);
9387 static const struct file_operations io_uring_fops = {
9388 .release = io_uring_release,
9389 .flush = io_uring_flush,
9390 .mmap = io_uring_mmap,
9392 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9393 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9395 .poll = io_uring_poll,
9396 .fasync = io_uring_fasync,
9397 #ifdef CONFIG_PROC_FS
9398 .show_fdinfo = io_uring_show_fdinfo,
9402 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9403 struct io_uring_params *p)
9405 struct io_rings *rings;
9406 size_t size, sq_array_offset;
9408 /* make sure these are sane, as we already accounted them */
9409 ctx->sq_entries = p->sq_entries;
9410 ctx->cq_entries = p->cq_entries;
9412 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9413 if (size == SIZE_MAX)
9416 rings = io_mem_alloc(size);
9421 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9422 rings->sq_ring_mask = p->sq_entries - 1;
9423 rings->cq_ring_mask = p->cq_entries - 1;
9424 rings->sq_ring_entries = p->sq_entries;
9425 rings->cq_ring_entries = p->cq_entries;
9426 ctx->sq_mask = rings->sq_ring_mask;
9427 ctx->cq_mask = rings->cq_ring_mask;
9429 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9430 if (size == SIZE_MAX) {
9431 io_mem_free(ctx->rings);
9436 ctx->sq_sqes = io_mem_alloc(size);
9437 if (!ctx->sq_sqes) {
9438 io_mem_free(ctx->rings);
9446 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9450 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9454 ret = io_uring_add_task_file(ctx, file);
9459 fd_install(fd, file);
9464 * Allocate an anonymous fd, this is what constitutes the application
9465 * visible backing of an io_uring instance. The application mmaps this
9466 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9467 * we have to tie this fd to a socket for file garbage collection purposes.
9469 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9472 #if defined(CONFIG_UNIX)
9475 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9478 return ERR_PTR(ret);
9481 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9482 O_RDWR | O_CLOEXEC);
9483 #if defined(CONFIG_UNIX)
9485 sock_release(ctx->ring_sock);
9486 ctx->ring_sock = NULL;
9488 ctx->ring_sock->file = file;
9494 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9495 struct io_uring_params __user *params)
9497 struct user_struct *user = NULL;
9498 struct io_ring_ctx *ctx;
9505 if (entries > IORING_MAX_ENTRIES) {
9506 if (!(p->flags & IORING_SETUP_CLAMP))
9508 entries = IORING_MAX_ENTRIES;
9512 * Use twice as many entries for the CQ ring. It's possible for the
9513 * application to drive a higher depth than the size of the SQ ring,
9514 * since the sqes are only used at submission time. This allows for
9515 * some flexibility in overcommitting a bit. If the application has
9516 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9517 * of CQ ring entries manually.
9519 p->sq_entries = roundup_pow_of_two(entries);
9520 if (p->flags & IORING_SETUP_CQSIZE) {
9522 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9523 * to a power-of-two, if it isn't already. We do NOT impose
9524 * any cq vs sq ring sizing.
9528 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9529 if (!(p->flags & IORING_SETUP_CLAMP))
9531 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9533 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9534 if (p->cq_entries < p->sq_entries)
9537 p->cq_entries = 2 * p->sq_entries;
9540 user = get_uid(current_user());
9541 limit_mem = !capable(CAP_IPC_LOCK);
9544 ret = __io_account_mem(user,
9545 ring_pages(p->sq_entries, p->cq_entries));
9552 ctx = io_ring_ctx_alloc(p);
9555 __io_unaccount_mem(user, ring_pages(p->sq_entries,
9560 ctx->compat = in_compat_syscall();
9562 ctx->creds = get_current_cred();
9564 ctx->loginuid = current->loginuid;
9565 ctx->sessionid = current->sessionid;
9567 ctx->sqo_task = get_task_struct(current);
9570 * This is just grabbed for accounting purposes. When a process exits,
9571 * the mm is exited and dropped before the files, hence we need to hang
9572 * on to this mm purely for the purposes of being able to unaccount
9573 * memory (locked/pinned vm). It's not used for anything else.
9575 mmgrab(current->mm);
9576 ctx->mm_account = current->mm;
9578 #ifdef CONFIG_BLK_CGROUP
9580 * The sq thread will belong to the original cgroup it was inited in.
9581 * If the cgroup goes offline (e.g. disabling the io controller), then
9582 * issued bios will be associated with the closest cgroup later in the
9586 ctx->sqo_blkcg_css = blkcg_css();
9587 ret = css_tryget_online(ctx->sqo_blkcg_css);
9590 /* don't init against a dying cgroup, have the user try again */
9591 ctx->sqo_blkcg_css = NULL;
9598 * Account memory _before_ installing the file descriptor. Once
9599 * the descriptor is installed, it can get closed at any time. Also
9600 * do this before hitting the general error path, as ring freeing
9601 * will un-account as well.
9603 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9605 ctx->limit_mem = limit_mem;
9607 ret = io_allocate_scq_urings(ctx, p);
9611 ret = io_sq_offload_create(ctx, p);
9615 if (!(p->flags & IORING_SETUP_R_DISABLED))
9616 io_sq_offload_start(ctx);
9618 memset(&p->sq_off, 0, sizeof(p->sq_off));
9619 p->sq_off.head = offsetof(struct io_rings, sq.head);
9620 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9621 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9622 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9623 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9624 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9625 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9627 memset(&p->cq_off, 0, sizeof(p->cq_off));
9628 p->cq_off.head = offsetof(struct io_rings, cq.head);
9629 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9630 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9631 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9632 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9633 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9634 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9636 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9637 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9638 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9639 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9640 IORING_FEAT_EXT_ARG;
9642 if (copy_to_user(params, p, sizeof(*p))) {
9647 file = io_uring_get_file(ctx);
9649 ret = PTR_ERR(file);
9654 * Install ring fd as the very last thing, so we don't risk someone
9655 * having closed it before we finish setup
9657 ret = io_uring_install_fd(ctx, file);
9659 /* fput will clean it up */
9664 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9667 io_ring_ctx_wait_and_kill(ctx);
9672 * Sets up an aio uring context, and returns the fd. Applications asks for a
9673 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9674 * params structure passed in.
9676 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9678 struct io_uring_params p;
9681 if (copy_from_user(&p, params, sizeof(p)))
9683 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9688 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9689 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9690 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9691 IORING_SETUP_R_DISABLED))
9694 return io_uring_create(entries, &p, params);
9697 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9698 struct io_uring_params __user *, params)
9700 return io_uring_setup(entries, params);
9703 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9705 struct io_uring_probe *p;
9709 size = struct_size(p, ops, nr_args);
9710 if (size == SIZE_MAX)
9712 p = kzalloc(size, GFP_KERNEL);
9717 if (copy_from_user(p, arg, size))
9720 if (memchr_inv(p, 0, size))
9723 p->last_op = IORING_OP_LAST - 1;
9724 if (nr_args > IORING_OP_LAST)
9725 nr_args = IORING_OP_LAST;
9727 for (i = 0; i < nr_args; i++) {
9729 if (!io_op_defs[i].not_supported)
9730 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9735 if (copy_to_user(arg, p, size))
9742 static int io_register_personality(struct io_ring_ctx *ctx)
9744 struct io_identity *id;
9747 id = kmalloc(sizeof(*id), GFP_KERNEL);
9751 io_init_identity(id);
9752 id->creds = get_current_cred();
9754 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9756 put_cred(id->creds);
9762 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9764 struct io_identity *iod;
9766 iod = idr_remove(&ctx->personality_idr, id);
9768 put_cred(iod->creds);
9769 if (refcount_dec_and_test(&iod->count))
9777 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9778 unsigned int nr_args)
9780 struct io_uring_restriction *res;
9784 /* Restrictions allowed only if rings started disabled */
9785 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9788 /* We allow only a single restrictions registration */
9789 if (ctx->restrictions.registered)
9792 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9795 size = array_size(nr_args, sizeof(*res));
9796 if (size == SIZE_MAX)
9799 res = memdup_user(arg, size);
9801 return PTR_ERR(res);
9805 for (i = 0; i < nr_args; i++) {
9806 switch (res[i].opcode) {
9807 case IORING_RESTRICTION_REGISTER_OP:
9808 if (res[i].register_op >= IORING_REGISTER_LAST) {
9813 __set_bit(res[i].register_op,
9814 ctx->restrictions.register_op);
9816 case IORING_RESTRICTION_SQE_OP:
9817 if (res[i].sqe_op >= IORING_OP_LAST) {
9822 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9824 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9825 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9827 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9828 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9837 /* Reset all restrictions if an error happened */
9839 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9841 ctx->restrictions.registered = true;
9847 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9849 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9852 if (ctx->restrictions.registered)
9853 ctx->restricted = 1;
9855 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9857 io_sq_offload_start(ctx);
9862 static bool io_register_op_must_quiesce(int op)
9865 case IORING_UNREGISTER_FILES:
9866 case IORING_REGISTER_FILES_UPDATE:
9867 case IORING_REGISTER_PROBE:
9868 case IORING_REGISTER_PERSONALITY:
9869 case IORING_UNREGISTER_PERSONALITY:
9876 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9877 void __user *arg, unsigned nr_args)
9878 __releases(ctx->uring_lock)
9879 __acquires(ctx->uring_lock)
9884 * We're inside the ring mutex, if the ref is already dying, then
9885 * someone else killed the ctx or is already going through
9886 * io_uring_register().
9888 if (percpu_ref_is_dying(&ctx->refs))
9891 if (io_register_op_must_quiesce(opcode)) {
9892 percpu_ref_kill(&ctx->refs);
9895 * Drop uring mutex before waiting for references to exit. If
9896 * another thread is currently inside io_uring_enter() it might
9897 * need to grab the uring_lock to make progress. If we hold it
9898 * here across the drain wait, then we can deadlock. It's safe
9899 * to drop the mutex here, since no new references will come in
9900 * after we've killed the percpu ref.
9902 mutex_unlock(&ctx->uring_lock);
9904 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9907 ret = io_run_task_work_sig();
9912 mutex_lock(&ctx->uring_lock);
9915 percpu_ref_resurrect(&ctx->refs);
9920 if (ctx->restricted) {
9921 if (opcode >= IORING_REGISTER_LAST) {
9926 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9933 case IORING_REGISTER_BUFFERS:
9934 ret = io_sqe_buffer_register(ctx, arg, nr_args);
9936 case IORING_UNREGISTER_BUFFERS:
9940 ret = io_sqe_buffer_unregister(ctx);
9942 case IORING_REGISTER_FILES:
9943 ret = io_sqe_files_register(ctx, arg, nr_args);
9945 case IORING_UNREGISTER_FILES:
9949 ret = io_sqe_files_unregister(ctx);
9951 case IORING_REGISTER_FILES_UPDATE:
9952 ret = io_sqe_files_update(ctx, arg, nr_args);
9954 case IORING_REGISTER_EVENTFD:
9955 case IORING_REGISTER_EVENTFD_ASYNC:
9959 ret = io_eventfd_register(ctx, arg);
9962 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9963 ctx->eventfd_async = 1;
9965 ctx->eventfd_async = 0;
9967 case IORING_UNREGISTER_EVENTFD:
9971 ret = io_eventfd_unregister(ctx);
9973 case IORING_REGISTER_PROBE:
9975 if (!arg || nr_args > 256)
9977 ret = io_probe(ctx, arg, nr_args);
9979 case IORING_REGISTER_PERSONALITY:
9983 ret = io_register_personality(ctx);
9985 case IORING_UNREGISTER_PERSONALITY:
9989 ret = io_unregister_personality(ctx, nr_args);
9991 case IORING_REGISTER_ENABLE_RINGS:
9995 ret = io_register_enable_rings(ctx);
9997 case IORING_REGISTER_RESTRICTIONS:
9998 ret = io_register_restrictions(ctx, arg, nr_args);
10006 if (io_register_op_must_quiesce(opcode)) {
10007 /* bring the ctx back to life */
10008 percpu_ref_reinit(&ctx->refs);
10010 reinit_completion(&ctx->ref_comp);
10015 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10016 void __user *, arg, unsigned int, nr_args)
10018 struct io_ring_ctx *ctx;
10027 if (f.file->f_op != &io_uring_fops)
10030 ctx = f.file->private_data;
10032 mutex_lock(&ctx->uring_lock);
10033 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10034 mutex_unlock(&ctx->uring_lock);
10035 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10036 ctx->cq_ev_fd != NULL, ret);
10042 static int __init io_uring_init(void)
10044 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10045 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10046 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10049 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10050 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10051 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10052 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10053 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10054 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10055 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10056 BUILD_BUG_SQE_ELEM(8, __u64, off);
10057 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10058 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10059 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10060 BUILD_BUG_SQE_ELEM(24, __u32, len);
10061 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10062 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10063 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10064 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10065 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10066 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10067 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10068 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10069 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10070 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10071 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10072 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10073 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10074 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10075 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10076 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10077 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10078 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10079 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10081 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10082 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10083 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
10086 __initcall(io_uring_init);