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;
252 struct percpu_ref refs;
253 } ____cacheline_aligned_in_smp;
257 unsigned int compat: 1;
258 unsigned int limit_mem: 1;
259 unsigned int cq_overflow_flushed: 1;
260 unsigned int drain_next: 1;
261 unsigned int eventfd_async: 1;
262 unsigned int restricted: 1;
263 unsigned int sqo_dead: 1;
266 * Ring buffer of indices into array of io_uring_sqe, which is
267 * mmapped by the application using the IORING_OFF_SQES offset.
269 * This indirection could e.g. be used to assign fixed
270 * io_uring_sqe entries to operations and only submit them to
271 * the queue when needed.
273 * The kernel modifies neither the indices array nor the entries
277 unsigned cached_sq_head;
280 unsigned sq_thread_idle;
281 unsigned cached_sq_dropped;
282 unsigned cached_cq_overflow;
283 unsigned long sq_check_overflow;
285 struct list_head defer_list;
286 struct list_head timeout_list;
287 struct list_head cq_overflow_list;
289 struct io_uring_sqe *sq_sqes;
290 } ____cacheline_aligned_in_smp;
292 struct io_rings *rings;
298 * For SQPOLL usage - we hold a reference to the parent task, so we
299 * have access to the ->files
301 struct task_struct *sqo_task;
303 /* Only used for accounting purposes */
304 struct mm_struct *mm_account;
306 #ifdef CONFIG_BLK_CGROUP
307 struct cgroup_subsys_state *sqo_blkcg_css;
310 struct io_sq_data *sq_data; /* if using sq thread polling */
312 struct wait_queue_head sqo_sq_wait;
313 struct wait_queue_entry sqo_wait_entry;
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 cq_last_tm_flush;
357 unsigned long cq_check_overflow;
358 struct wait_queue_head cq_wait;
359 struct fasync_struct *cq_fasync;
360 struct eventfd_ctx *cq_ev_fd;
361 } ____cacheline_aligned_in_smp;
364 struct mutex uring_lock;
365 wait_queue_head_t wait;
366 } ____cacheline_aligned_in_smp;
369 spinlock_t completion_lock;
372 * ->iopoll_list is protected by the ctx->uring_lock for
373 * io_uring instances that don't use IORING_SETUP_SQPOLL.
374 * For SQPOLL, only the single threaded io_sq_thread() will
375 * manipulate the list, hence no extra locking is needed there.
377 struct list_head iopoll_list;
378 struct hlist_head *cancel_hash;
379 unsigned cancel_hash_bits;
380 bool poll_multi_file;
382 spinlock_t inflight_lock;
383 struct list_head inflight_list;
384 } ____cacheline_aligned_in_smp;
386 struct delayed_work file_put_work;
387 struct llist_head file_put_llist;
389 struct work_struct exit_work;
390 struct io_restriction restrictions;
394 * First field must be the file pointer in all the
395 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
397 struct io_poll_iocb {
400 struct wait_queue_head *head;
406 struct wait_queue_entry wait;
411 struct file *put_file;
415 struct io_timeout_data {
416 struct io_kiocb *req;
417 struct hrtimer timer;
418 struct timespec64 ts;
419 enum hrtimer_mode mode;
424 struct sockaddr __user *addr;
425 int __user *addr_len;
427 unsigned long nofile;
447 struct list_head list;
450 struct io_timeout_rem {
456 /* NOTE: kiocb has the file as the first member, so don't do it here */
464 struct sockaddr __user *addr;
471 struct user_msghdr __user *umsg;
477 struct io_buffer *kbuf;
483 bool ignore_nonblock;
484 struct filename *filename;
486 unsigned long nofile;
489 struct io_files_update {
515 struct epoll_event event;
519 struct file *file_out;
520 struct file *file_in;
527 struct io_provide_buf {
541 const char __user *filename;
542 struct statx __user *buffer;
545 struct io_completion {
547 struct list_head list;
551 struct io_async_connect {
552 struct sockaddr_storage address;
555 struct io_async_msghdr {
556 struct iovec fast_iov[UIO_FASTIOV];
558 struct sockaddr __user *uaddr;
560 struct sockaddr_storage addr;
564 struct iovec fast_iov[UIO_FASTIOV];
565 const struct iovec *free_iovec;
566 struct iov_iter iter;
568 struct wait_page_queue wpq;
572 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
573 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
574 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
575 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
576 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
577 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
584 REQ_F_LINK_TIMEOUT_BIT,
586 REQ_F_NEED_CLEANUP_BIT,
588 REQ_F_BUFFER_SELECTED_BIT,
589 REQ_F_NO_FILE_TABLE_BIT,
590 REQ_F_WORK_INITIALIZED_BIT,
591 REQ_F_LTIMEOUT_ACTIVE_BIT,
593 /* not a real bit, just to check we're not overflowing the space */
599 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
600 /* drain existing IO first */
601 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
603 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
604 /* doesn't sever on completion < 0 */
605 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
607 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
608 /* IOSQE_BUFFER_SELECT */
609 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
612 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
613 /* fail rest of links */
614 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
615 /* on inflight list */
616 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
617 /* read/write uses file position */
618 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
619 /* must not punt to workers */
620 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
621 /* has or had linked timeout */
622 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
624 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
626 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
627 /* already went through poll handler */
628 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
629 /* buffer already selected */
630 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
631 /* doesn't need file table for this request */
632 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
633 /* io_wq_work is initialized */
634 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
635 /* linked timeout is active, i.e. prepared by link's head */
636 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
640 struct io_poll_iocb poll;
641 struct io_poll_iocb *double_poll;
645 * NOTE! Each of the iocb union members has the file pointer
646 * as the first entry in their struct definition. So you can
647 * access the file pointer through any of the sub-structs,
648 * or directly as just 'ki_filp' in this struct.
654 struct io_poll_iocb poll;
655 struct io_accept accept;
657 struct io_cancel cancel;
658 struct io_timeout timeout;
659 struct io_timeout_rem timeout_rem;
660 struct io_connect connect;
661 struct io_sr_msg sr_msg;
663 struct io_close close;
664 struct io_files_update files_update;
665 struct io_fadvise fadvise;
666 struct io_madvise madvise;
667 struct io_epoll epoll;
668 struct io_splice splice;
669 struct io_provide_buf pbuf;
670 struct io_statx statx;
671 /* use only after cleaning per-op data, see io_clean_op() */
672 struct io_completion compl;
675 /* opcode allocated if it needs to store data for async defer */
678 /* polled IO has completed */
684 struct io_ring_ctx *ctx;
687 struct task_struct *task;
690 struct list_head link_list;
693 * 1. used with ctx->iopoll_list with reads/writes
694 * 2. to track reqs with ->files (see io_op_def::file_table)
696 struct list_head inflight_entry;
698 struct percpu_ref *fixed_file_refs;
699 struct callback_head task_work;
700 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
701 struct hlist_node hash_node;
702 struct async_poll *apoll;
703 struct io_wq_work work;
706 struct io_defer_entry {
707 struct list_head list;
708 struct io_kiocb *req;
712 #define IO_IOPOLL_BATCH 8
714 struct io_comp_state {
716 struct list_head list;
717 struct io_ring_ctx *ctx;
720 struct io_submit_state {
721 struct blk_plug plug;
724 * io_kiocb alloc cache
726 void *reqs[IO_IOPOLL_BATCH];
727 unsigned int free_reqs;
730 * Batch completion logic
732 struct io_comp_state comp;
735 * File reference cache
739 unsigned int has_refs;
740 unsigned int ios_left;
744 /* needs req->file assigned */
745 unsigned needs_file : 1;
746 /* don't fail if file grab fails */
747 unsigned needs_file_no_error : 1;
748 /* hash wq insertion if file is a regular file */
749 unsigned hash_reg_file : 1;
750 /* unbound wq insertion if file is a non-regular file */
751 unsigned unbound_nonreg_file : 1;
752 /* opcode is not supported by this kernel */
753 unsigned not_supported : 1;
754 /* set if opcode supports polled "wait" */
756 unsigned pollout : 1;
757 /* op supports buffer selection */
758 unsigned buffer_select : 1;
759 /* must always have async data allocated */
760 unsigned needs_async_data : 1;
761 /* size of async data needed, if any */
762 unsigned short async_size;
766 static const struct io_op_def io_op_defs[] = {
767 [IORING_OP_NOP] = {},
768 [IORING_OP_READV] = {
770 .unbound_nonreg_file = 1,
773 .needs_async_data = 1,
774 .async_size = sizeof(struct io_async_rw),
775 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
777 [IORING_OP_WRITEV] = {
780 .unbound_nonreg_file = 1,
782 .needs_async_data = 1,
783 .async_size = sizeof(struct io_async_rw),
784 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
787 [IORING_OP_FSYNC] = {
789 .work_flags = IO_WQ_WORK_BLKCG,
791 [IORING_OP_READ_FIXED] = {
793 .unbound_nonreg_file = 1,
795 .async_size = sizeof(struct io_async_rw),
796 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
798 [IORING_OP_WRITE_FIXED] = {
801 .unbound_nonreg_file = 1,
803 .async_size = sizeof(struct io_async_rw),
804 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
807 [IORING_OP_POLL_ADD] = {
809 .unbound_nonreg_file = 1,
811 [IORING_OP_POLL_REMOVE] = {},
812 [IORING_OP_SYNC_FILE_RANGE] = {
814 .work_flags = IO_WQ_WORK_BLKCG,
816 [IORING_OP_SENDMSG] = {
818 .unbound_nonreg_file = 1,
820 .needs_async_data = 1,
821 .async_size = sizeof(struct io_async_msghdr),
822 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
825 [IORING_OP_RECVMSG] = {
827 .unbound_nonreg_file = 1,
830 .needs_async_data = 1,
831 .async_size = sizeof(struct io_async_msghdr),
832 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
835 [IORING_OP_TIMEOUT] = {
836 .needs_async_data = 1,
837 .async_size = sizeof(struct io_timeout_data),
838 .work_flags = IO_WQ_WORK_MM,
840 [IORING_OP_TIMEOUT_REMOVE] = {},
841 [IORING_OP_ACCEPT] = {
843 .unbound_nonreg_file = 1,
845 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
847 [IORING_OP_ASYNC_CANCEL] = {},
848 [IORING_OP_LINK_TIMEOUT] = {
849 .needs_async_data = 1,
850 .async_size = sizeof(struct io_timeout_data),
851 .work_flags = IO_WQ_WORK_MM,
853 [IORING_OP_CONNECT] = {
855 .unbound_nonreg_file = 1,
857 .needs_async_data = 1,
858 .async_size = sizeof(struct io_async_connect),
859 .work_flags = IO_WQ_WORK_MM,
861 [IORING_OP_FALLOCATE] = {
863 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
865 [IORING_OP_OPENAT] = {
866 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
869 [IORING_OP_CLOSE] = {
871 .needs_file_no_error = 1,
872 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
874 [IORING_OP_FILES_UPDATE] = {
875 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
877 [IORING_OP_STATX] = {
878 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
879 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
883 .unbound_nonreg_file = 1,
886 .async_size = sizeof(struct io_async_rw),
887 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
889 [IORING_OP_WRITE] = {
891 .unbound_nonreg_file = 1,
893 .async_size = sizeof(struct io_async_rw),
894 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
897 [IORING_OP_FADVISE] = {
899 .work_flags = IO_WQ_WORK_BLKCG,
901 [IORING_OP_MADVISE] = {
902 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
906 .unbound_nonreg_file = 1,
908 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
912 .unbound_nonreg_file = 1,
915 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
917 [IORING_OP_OPENAT2] = {
918 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
921 [IORING_OP_EPOLL_CTL] = {
922 .unbound_nonreg_file = 1,
923 .work_flags = IO_WQ_WORK_FILES,
925 [IORING_OP_SPLICE] = {
928 .unbound_nonreg_file = 1,
929 .work_flags = IO_WQ_WORK_BLKCG,
931 [IORING_OP_PROVIDE_BUFFERS] = {},
932 [IORING_OP_REMOVE_BUFFERS] = {},
936 .unbound_nonreg_file = 1,
940 enum io_mem_account {
945 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node);
946 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
947 struct io_ring_ctx *ctx);
949 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
950 struct io_comp_state *cs);
951 static void io_cqring_fill_event(struct io_kiocb *req, long res);
952 static void io_put_req(struct io_kiocb *req);
953 static void io_put_req_deferred(struct io_kiocb *req, int nr);
954 static void io_double_put_req(struct io_kiocb *req);
955 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
956 static void __io_queue_linked_timeout(struct io_kiocb *req);
957 static void io_queue_linked_timeout(struct io_kiocb *req);
958 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
959 struct io_uring_files_update *ip,
961 static void __io_clean_op(struct io_kiocb *req);
962 static struct file *io_file_get(struct io_submit_state *state,
963 struct io_kiocb *req, int fd, bool fixed);
964 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs);
965 static void io_file_put_work(struct work_struct *work);
967 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
968 struct iovec **iovec, struct iov_iter *iter,
970 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
971 const struct iovec *fast_iov,
972 struct iov_iter *iter, bool force);
973 static void io_req_drop_files(struct io_kiocb *req);
974 static void io_req_task_queue(struct io_kiocb *req);
976 static struct kmem_cache *req_cachep;
978 static const struct file_operations io_uring_fops;
980 struct sock *io_uring_get_socket(struct file *file)
982 #if defined(CONFIG_UNIX)
983 if (file->f_op == &io_uring_fops) {
984 struct io_ring_ctx *ctx = file->private_data;
986 return ctx->ring_sock->sk;
991 EXPORT_SYMBOL(io_uring_get_socket);
993 static inline void io_clean_op(struct io_kiocb *req)
995 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
999 static inline bool __io_match_files(struct io_kiocb *req,
1000 struct files_struct *files)
1002 if (req->file && req->file->f_op == &io_uring_fops)
1005 return ((req->flags & REQ_F_WORK_INITIALIZED) &&
1006 (req->work.flags & IO_WQ_WORK_FILES)) &&
1007 req->work.identity->files == files;
1010 static bool io_match_task(struct io_kiocb *head,
1011 struct task_struct *task,
1012 struct files_struct *files)
1014 struct io_kiocb *link;
1016 if (task && head->task != task) {
1017 /* in terms of cancelation, always match if req task is dead */
1018 if (head->task->flags & PF_EXITING)
1024 if (__io_match_files(head, files))
1026 if (head->flags & REQ_F_LINK_HEAD) {
1027 list_for_each_entry(link, &head->link_list, link_list) {
1028 if (__io_match_files(link, files))
1036 static void io_sq_thread_drop_mm(void)
1038 struct mm_struct *mm = current->mm;
1041 kthread_unuse_mm(mm);
1047 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1049 struct mm_struct *mm;
1051 if (current->flags & PF_EXITING)
1056 /* Should never happen */
1057 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL)))
1060 task_lock(ctx->sqo_task);
1061 mm = ctx->sqo_task->mm;
1062 if (unlikely(!mm || !mmget_not_zero(mm)))
1064 task_unlock(ctx->sqo_task);
1074 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
1075 struct io_kiocb *req)
1077 if (!(io_op_defs[req->opcode].work_flags & IO_WQ_WORK_MM))
1079 return __io_sq_thread_acquire_mm(ctx);
1082 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1083 struct cgroup_subsys_state **cur_css)
1086 #ifdef CONFIG_BLK_CGROUP
1087 /* puts the old one when swapping */
1088 if (*cur_css != ctx->sqo_blkcg_css) {
1089 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1090 *cur_css = ctx->sqo_blkcg_css;
1095 static void io_sq_thread_unassociate_blkcg(void)
1097 #ifdef CONFIG_BLK_CGROUP
1098 kthread_associate_blkcg(NULL);
1102 static inline void req_set_fail_links(struct io_kiocb *req)
1104 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1105 req->flags |= REQ_F_FAIL_LINK;
1109 * None of these are dereferenced, they are simply used to check if any of
1110 * them have changed. If we're under current and check they are still the
1111 * same, we're fine to grab references to them for actual out-of-line use.
1113 static void io_init_identity(struct io_identity *id)
1115 id->files = current->files;
1116 id->mm = current->mm;
1117 #ifdef CONFIG_BLK_CGROUP
1119 id->blkcg_css = blkcg_css();
1122 id->creds = current_cred();
1123 id->nsproxy = current->nsproxy;
1124 id->fs = current->fs;
1125 id->fsize = rlimit(RLIMIT_FSIZE);
1127 id->loginuid = current->loginuid;
1128 id->sessionid = current->sessionid;
1130 refcount_set(&id->count, 1);
1133 static inline void __io_req_init_async(struct io_kiocb *req)
1135 memset(&req->work, 0, sizeof(req->work));
1136 req->flags |= REQ_F_WORK_INITIALIZED;
1140 * Note: must call io_req_init_async() for the first time you
1141 * touch any members of io_wq_work.
1143 static inline void io_req_init_async(struct io_kiocb *req)
1145 struct io_uring_task *tctx = current->io_uring;
1147 if (req->flags & REQ_F_WORK_INITIALIZED)
1150 __io_req_init_async(req);
1152 /* Grab a ref if this isn't our static identity */
1153 req->work.identity = tctx->identity;
1154 if (tctx->identity != &tctx->__identity)
1155 refcount_inc(&req->work.identity->count);
1158 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1160 return ctx->flags & IORING_SETUP_SQPOLL;
1163 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1165 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1167 complete(&ctx->ref_comp);
1170 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1172 return !req->timeout.off;
1175 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1177 struct io_ring_ctx *ctx;
1180 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1184 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1185 if (!ctx->fallback_req)
1189 * Use 5 bits less than the max cq entries, that should give us around
1190 * 32 entries per hash list if totally full and uniformly spread.
1192 hash_bits = ilog2(p->cq_entries);
1196 ctx->cancel_hash_bits = hash_bits;
1197 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1199 if (!ctx->cancel_hash)
1201 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1203 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1204 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1207 ctx->flags = p->flags;
1208 init_waitqueue_head(&ctx->sqo_sq_wait);
1209 INIT_LIST_HEAD(&ctx->sqd_list);
1210 init_waitqueue_head(&ctx->cq_wait);
1211 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1212 init_completion(&ctx->ref_comp);
1213 init_completion(&ctx->sq_thread_comp);
1214 idr_init(&ctx->io_buffer_idr);
1215 idr_init(&ctx->personality_idr);
1216 mutex_init(&ctx->uring_lock);
1217 init_waitqueue_head(&ctx->wait);
1218 spin_lock_init(&ctx->completion_lock);
1219 INIT_LIST_HEAD(&ctx->iopoll_list);
1220 INIT_LIST_HEAD(&ctx->defer_list);
1221 INIT_LIST_HEAD(&ctx->timeout_list);
1222 spin_lock_init(&ctx->inflight_lock);
1223 INIT_LIST_HEAD(&ctx->inflight_list);
1224 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1225 init_llist_head(&ctx->file_put_llist);
1228 if (ctx->fallback_req)
1229 kmem_cache_free(req_cachep, ctx->fallback_req);
1230 kfree(ctx->cancel_hash);
1235 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1237 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1238 struct io_ring_ctx *ctx = req->ctx;
1240 return seq != ctx->cached_cq_tail
1241 + READ_ONCE(ctx->cached_cq_overflow);
1247 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1249 struct io_rings *rings = ctx->rings;
1251 /* order cqe stores with ring update */
1252 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1255 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1257 if (req->work.identity == &tctx->__identity)
1259 if (refcount_dec_and_test(&req->work.identity->count))
1260 kfree(req->work.identity);
1263 static void io_req_clean_work(struct io_kiocb *req)
1265 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1268 req->flags &= ~REQ_F_WORK_INITIALIZED;
1270 if (req->work.flags & IO_WQ_WORK_MM) {
1271 mmdrop(req->work.identity->mm);
1272 req->work.flags &= ~IO_WQ_WORK_MM;
1274 #ifdef CONFIG_BLK_CGROUP
1275 if (req->work.flags & IO_WQ_WORK_BLKCG) {
1276 css_put(req->work.identity->blkcg_css);
1277 req->work.flags &= ~IO_WQ_WORK_BLKCG;
1280 if (req->work.flags & IO_WQ_WORK_CREDS) {
1281 put_cred(req->work.identity->creds);
1282 req->work.flags &= ~IO_WQ_WORK_CREDS;
1284 if (req->work.flags & IO_WQ_WORK_FS) {
1285 struct fs_struct *fs = req->work.identity->fs;
1287 spin_lock(&req->work.identity->fs->lock);
1290 spin_unlock(&req->work.identity->fs->lock);
1293 req->work.flags &= ~IO_WQ_WORK_FS;
1295 if (req->flags & REQ_F_INFLIGHT)
1296 io_req_drop_files(req);
1298 io_put_identity(req->task->io_uring, req);
1302 * Create a private copy of io_identity, since some fields don't match
1303 * the current context.
1305 static bool io_identity_cow(struct io_kiocb *req)
1307 struct io_uring_task *tctx = current->io_uring;
1308 const struct cred *creds = NULL;
1309 struct io_identity *id;
1311 if (req->work.flags & IO_WQ_WORK_CREDS)
1312 creds = req->work.identity->creds;
1314 id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1315 if (unlikely(!id)) {
1316 req->work.flags |= IO_WQ_WORK_CANCEL;
1321 * We can safely just re-init the creds we copied Either the field
1322 * matches the current one, or we haven't grabbed it yet. The only
1323 * exception is ->creds, through registered personalities, so handle
1324 * that one separately.
1326 io_init_identity(id);
1330 /* add one for this request */
1331 refcount_inc(&id->count);
1333 /* drop tctx and req identity references, if needed */
1334 if (tctx->identity != &tctx->__identity &&
1335 refcount_dec_and_test(&tctx->identity->count))
1336 kfree(tctx->identity);
1337 if (req->work.identity != &tctx->__identity &&
1338 refcount_dec_and_test(&req->work.identity->count))
1339 kfree(req->work.identity);
1341 req->work.identity = id;
1342 tctx->identity = id;
1346 static bool io_grab_identity(struct io_kiocb *req)
1348 const struct io_op_def *def = &io_op_defs[req->opcode];
1349 struct io_identity *id = req->work.identity;
1350 struct io_ring_ctx *ctx = req->ctx;
1352 if (def->work_flags & IO_WQ_WORK_FSIZE) {
1353 if (id->fsize != rlimit(RLIMIT_FSIZE))
1355 req->work.flags |= IO_WQ_WORK_FSIZE;
1357 #ifdef CONFIG_BLK_CGROUP
1358 if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1359 (def->work_flags & IO_WQ_WORK_BLKCG)) {
1361 if (id->blkcg_css != blkcg_css()) {
1366 * This should be rare, either the cgroup is dying or the task
1367 * is moving cgroups. Just punt to root for the handful of ios.
1369 if (css_tryget_online(id->blkcg_css))
1370 req->work.flags |= IO_WQ_WORK_BLKCG;
1374 if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1375 if (id->creds != current_cred())
1377 get_cred(id->creds);
1378 req->work.flags |= IO_WQ_WORK_CREDS;
1381 if (!uid_eq(current->loginuid, id->loginuid) ||
1382 current->sessionid != id->sessionid)
1385 if (!(req->work.flags & IO_WQ_WORK_FS) &&
1386 (def->work_flags & IO_WQ_WORK_FS)) {
1387 if (current->fs != id->fs)
1389 spin_lock(&id->fs->lock);
1390 if (!id->fs->in_exec) {
1392 req->work.flags |= IO_WQ_WORK_FS;
1394 req->work.flags |= IO_WQ_WORK_CANCEL;
1396 spin_unlock(¤t->fs->lock);
1398 if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1399 (def->work_flags & IO_WQ_WORK_FILES) &&
1400 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1401 if (id->files != current->files ||
1402 id->nsproxy != current->nsproxy)
1404 atomic_inc(&id->files->count);
1405 get_nsproxy(id->nsproxy);
1407 if (!(req->flags & REQ_F_INFLIGHT)) {
1408 req->flags |= REQ_F_INFLIGHT;
1410 spin_lock_irq(&ctx->inflight_lock);
1411 list_add(&req->inflight_entry, &ctx->inflight_list);
1412 spin_unlock_irq(&ctx->inflight_lock);
1414 req->work.flags |= IO_WQ_WORK_FILES;
1416 if (!(req->work.flags & IO_WQ_WORK_MM) &&
1417 (def->work_flags & IO_WQ_WORK_MM)) {
1418 if (id->mm != current->mm)
1421 req->work.flags |= IO_WQ_WORK_MM;
1427 static void io_prep_async_work(struct io_kiocb *req)
1429 const struct io_op_def *def = &io_op_defs[req->opcode];
1430 struct io_ring_ctx *ctx = req->ctx;
1431 struct io_identity *id;
1433 io_req_init_async(req);
1434 id = req->work.identity;
1436 if (req->flags & REQ_F_FORCE_ASYNC)
1437 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1439 if (req->flags & REQ_F_ISREG) {
1440 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1441 io_wq_hash_work(&req->work, file_inode(req->file));
1443 if (def->unbound_nonreg_file)
1444 req->work.flags |= IO_WQ_WORK_UNBOUND;
1447 /* if we fail grabbing identity, we must COW, regrab, and retry */
1448 if (io_grab_identity(req))
1451 if (!io_identity_cow(req))
1454 /* can't fail at this point */
1455 if (!io_grab_identity(req))
1459 static void io_prep_async_link(struct io_kiocb *req)
1461 struct io_kiocb *cur;
1463 io_prep_async_work(req);
1464 if (req->flags & REQ_F_LINK_HEAD)
1465 list_for_each_entry(cur, &req->link_list, link_list)
1466 io_prep_async_work(cur);
1469 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1471 struct io_ring_ctx *ctx = req->ctx;
1472 struct io_kiocb *link = io_prep_linked_timeout(req);
1474 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1475 &req->work, req->flags);
1476 io_wq_enqueue(ctx->io_wq, &req->work);
1480 static void io_queue_async_work(struct io_kiocb *req)
1482 struct io_kiocb *link;
1484 /* init ->work of the whole link before punting */
1485 io_prep_async_link(req);
1486 link = __io_queue_async_work(req);
1489 io_queue_linked_timeout(link);
1492 static void io_kill_timeout(struct io_kiocb *req)
1494 struct io_timeout_data *io = req->async_data;
1497 ret = hrtimer_try_to_cancel(&io->timer);
1499 atomic_set(&req->ctx->cq_timeouts,
1500 atomic_read(&req->ctx->cq_timeouts) + 1);
1501 list_del_init(&req->timeout.list);
1502 io_cqring_fill_event(req, 0);
1503 io_put_req_deferred(req, 1);
1508 * Returns true if we found and killed one or more timeouts
1510 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1511 struct files_struct *files)
1513 struct io_kiocb *req, *tmp;
1516 spin_lock_irq(&ctx->completion_lock);
1517 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1518 if (io_match_task(req, tsk, files)) {
1519 io_kill_timeout(req);
1523 spin_unlock_irq(&ctx->completion_lock);
1524 return canceled != 0;
1527 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1530 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1531 struct io_defer_entry, list);
1533 if (req_need_defer(de->req, de->seq))
1535 list_del_init(&de->list);
1536 io_req_task_queue(de->req);
1538 } while (!list_empty(&ctx->defer_list));
1541 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1545 if (list_empty(&ctx->timeout_list))
1548 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1551 u32 events_needed, events_got;
1552 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1553 struct io_kiocb, timeout.list);
1555 if (io_is_timeout_noseq(req))
1559 * Since seq can easily wrap around over time, subtract
1560 * the last seq at which timeouts were flushed before comparing.
1561 * Assuming not more than 2^31-1 events have happened since,
1562 * these subtractions won't have wrapped, so we can check if
1563 * target is in [last_seq, current_seq] by comparing the two.
1565 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1566 events_got = seq - ctx->cq_last_tm_flush;
1567 if (events_got < events_needed)
1570 list_del_init(&req->timeout.list);
1571 io_kill_timeout(req);
1572 } while (!list_empty(&ctx->timeout_list));
1574 ctx->cq_last_tm_flush = seq;
1577 static void io_commit_cqring(struct io_ring_ctx *ctx)
1579 io_flush_timeouts(ctx);
1580 __io_commit_cqring(ctx);
1582 if (unlikely(!list_empty(&ctx->defer_list)))
1583 __io_queue_deferred(ctx);
1586 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1588 struct io_rings *r = ctx->rings;
1590 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1593 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1595 struct io_rings *rings = ctx->rings;
1598 tail = ctx->cached_cq_tail;
1600 * writes to the cq entry need to come after reading head; the
1601 * control dependency is enough as we're using WRITE_ONCE to
1604 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1607 ctx->cached_cq_tail++;
1608 return &rings->cqes[tail & ctx->cq_mask];
1611 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1615 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1617 if (!ctx->eventfd_async)
1619 return io_wq_current_is_worker();
1622 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1624 if (wq_has_sleeper(&ctx->cq_wait)) {
1625 wake_up_interruptible(&ctx->cq_wait);
1626 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1628 if (waitqueue_active(&ctx->wait))
1629 wake_up(&ctx->wait);
1630 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1631 wake_up(&ctx->sq_data->wait);
1632 if (io_should_trigger_evfd(ctx))
1633 eventfd_signal(ctx->cq_ev_fd, 1);
1636 static void io_cqring_mark_overflow(struct io_ring_ctx *ctx)
1638 if (list_empty(&ctx->cq_overflow_list)) {
1639 clear_bit(0, &ctx->sq_check_overflow);
1640 clear_bit(0, &ctx->cq_check_overflow);
1641 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1645 /* Returns true if there are no backlogged entries after the flush */
1646 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1647 struct task_struct *tsk,
1648 struct files_struct *files)
1650 struct io_rings *rings = ctx->rings;
1651 struct io_kiocb *req, *tmp;
1652 struct io_uring_cqe *cqe;
1653 unsigned long flags;
1657 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1658 rings->cq_ring_entries))
1662 spin_lock_irqsave(&ctx->completion_lock, flags);
1665 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1666 if (!io_match_task(req, tsk, files))
1669 cqe = io_get_cqring(ctx);
1673 list_move(&req->compl.list, &list);
1675 WRITE_ONCE(cqe->user_data, req->user_data);
1676 WRITE_ONCE(cqe->res, req->result);
1677 WRITE_ONCE(cqe->flags, req->compl.cflags);
1679 ctx->cached_cq_overflow++;
1680 WRITE_ONCE(ctx->rings->cq_overflow,
1681 ctx->cached_cq_overflow);
1685 io_commit_cqring(ctx);
1686 io_cqring_mark_overflow(ctx);
1688 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1689 io_cqring_ev_posted(ctx);
1691 while (!list_empty(&list)) {
1692 req = list_first_entry(&list, struct io_kiocb, compl.list);
1693 list_del(&req->compl.list);
1700 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1701 struct task_struct *tsk,
1702 struct files_struct *files)
1704 if (test_bit(0, &ctx->cq_check_overflow)) {
1705 /* iopoll syncs against uring_lock, not completion_lock */
1706 if (ctx->flags & IORING_SETUP_IOPOLL)
1707 mutex_lock(&ctx->uring_lock);
1708 __io_cqring_overflow_flush(ctx, force, tsk, files);
1709 if (ctx->flags & IORING_SETUP_IOPOLL)
1710 mutex_unlock(&ctx->uring_lock);
1714 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1716 struct io_ring_ctx *ctx = req->ctx;
1717 struct io_uring_cqe *cqe;
1719 trace_io_uring_complete(ctx, req->user_data, res);
1722 * If we can't get a cq entry, userspace overflowed the
1723 * submission (by quite a lot). Increment the overflow count in
1726 cqe = io_get_cqring(ctx);
1728 WRITE_ONCE(cqe->user_data, req->user_data);
1729 WRITE_ONCE(cqe->res, res);
1730 WRITE_ONCE(cqe->flags, cflags);
1731 } else if (ctx->cq_overflow_flushed ||
1732 atomic_read(&req->task->io_uring->in_idle)) {
1734 * If we're in ring overflow flush mode, or in task cancel mode,
1735 * then we cannot store the request for later flushing, we need
1736 * to drop it on the floor.
1738 ctx->cached_cq_overflow++;
1739 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1741 if (list_empty(&ctx->cq_overflow_list)) {
1742 set_bit(0, &ctx->sq_check_overflow);
1743 set_bit(0, &ctx->cq_check_overflow);
1744 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1748 req->compl.cflags = cflags;
1749 refcount_inc(&req->refs);
1750 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1754 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1756 __io_cqring_fill_event(req, res, 0);
1759 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1761 struct io_ring_ctx *ctx = req->ctx;
1762 unsigned long flags;
1764 spin_lock_irqsave(&ctx->completion_lock, flags);
1765 __io_cqring_fill_event(req, res, cflags);
1766 io_commit_cqring(ctx);
1767 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1769 io_cqring_ev_posted(ctx);
1772 static void io_submit_flush_completions(struct io_comp_state *cs)
1774 struct io_ring_ctx *ctx = cs->ctx;
1776 spin_lock_irq(&ctx->completion_lock);
1777 while (!list_empty(&cs->list)) {
1778 struct io_kiocb *req;
1780 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1781 list_del(&req->compl.list);
1782 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1785 * io_free_req() doesn't care about completion_lock unless one
1786 * of these flags is set. REQ_F_WORK_INITIALIZED is in the list
1787 * because of a potential deadlock with req->work.fs->lock
1789 if (req->flags & (REQ_F_FAIL_LINK|REQ_F_LINK_TIMEOUT
1790 |REQ_F_WORK_INITIALIZED)) {
1791 spin_unlock_irq(&ctx->completion_lock);
1793 spin_lock_irq(&ctx->completion_lock);
1798 io_commit_cqring(ctx);
1799 spin_unlock_irq(&ctx->completion_lock);
1801 io_cqring_ev_posted(ctx);
1805 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1806 struct io_comp_state *cs)
1809 io_cqring_add_event(req, res, cflags);
1814 req->compl.cflags = cflags;
1815 list_add_tail(&req->compl.list, &cs->list);
1817 io_submit_flush_completions(cs);
1821 static void io_req_complete(struct io_kiocb *req, long res)
1823 __io_req_complete(req, res, 0, NULL);
1826 static inline bool io_is_fallback_req(struct io_kiocb *req)
1828 return req == (struct io_kiocb *)
1829 ((unsigned long) req->ctx->fallback_req & ~1UL);
1832 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1834 struct io_kiocb *req;
1836 req = ctx->fallback_req;
1837 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1843 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1844 struct io_submit_state *state)
1846 if (!state->free_reqs) {
1847 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1851 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1852 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1855 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1856 * retry single alloc to be on the safe side.
1858 if (unlikely(ret <= 0)) {
1859 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1860 if (!state->reqs[0])
1864 state->free_reqs = ret;
1868 return state->reqs[state->free_reqs];
1870 return io_get_fallback_req(ctx);
1873 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1877 percpu_ref_put(req->fixed_file_refs);
1882 static void io_dismantle_req(struct io_kiocb *req)
1886 if (req->async_data)
1887 kfree(req->async_data);
1889 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1891 io_req_clean_work(req);
1894 static void __io_free_req(struct io_kiocb *req)
1896 struct io_uring_task *tctx = req->task->io_uring;
1897 struct io_ring_ctx *ctx = req->ctx;
1899 io_dismantle_req(req);
1901 percpu_counter_dec(&tctx->inflight);
1902 if (atomic_read(&tctx->in_idle))
1903 wake_up(&tctx->wait);
1904 put_task_struct(req->task);
1906 if (likely(!io_is_fallback_req(req)))
1907 kmem_cache_free(req_cachep, req);
1909 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
1910 percpu_ref_put(&ctx->refs);
1913 static void io_kill_linked_timeout(struct io_kiocb *req)
1915 struct io_ring_ctx *ctx = req->ctx;
1916 struct io_kiocb *link;
1917 bool cancelled = false;
1918 unsigned long flags;
1920 spin_lock_irqsave(&ctx->completion_lock, flags);
1921 link = list_first_entry_or_null(&req->link_list, struct io_kiocb,
1924 * Can happen if a linked timeout fired and link had been like
1925 * req -> link t-out -> link t-out [-> ...]
1927 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1928 struct io_timeout_data *io = link->async_data;
1931 list_del_init(&link->link_list);
1932 ret = hrtimer_try_to_cancel(&io->timer);
1934 io_cqring_fill_event(link, -ECANCELED);
1935 io_commit_cqring(ctx);
1939 req->flags &= ~REQ_F_LINK_TIMEOUT;
1940 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1943 io_cqring_ev_posted(ctx);
1948 static struct io_kiocb *io_req_link_next(struct io_kiocb *req)
1950 struct io_kiocb *nxt;
1953 * The list should never be empty when we are called here. But could
1954 * potentially happen if the chain is messed up, check to be on the
1957 if (unlikely(list_empty(&req->link_list)))
1960 nxt = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1961 list_del_init(&req->link_list);
1962 if (!list_empty(&nxt->link_list))
1963 nxt->flags |= REQ_F_LINK_HEAD;
1968 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1970 static void io_fail_links(struct io_kiocb *req)
1972 struct io_ring_ctx *ctx = req->ctx;
1973 unsigned long flags;
1975 spin_lock_irqsave(&ctx->completion_lock, flags);
1976 while (!list_empty(&req->link_list)) {
1977 struct io_kiocb *link = list_first_entry(&req->link_list,
1978 struct io_kiocb, link_list);
1980 list_del_init(&link->link_list);
1981 trace_io_uring_fail_link(req, link);
1983 io_cqring_fill_event(link, -ECANCELED);
1986 * It's ok to free under spinlock as they're not linked anymore,
1987 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
1990 if (link->flags & REQ_F_WORK_INITIALIZED)
1991 io_put_req_deferred(link, 2);
1993 io_double_put_req(link);
1996 io_commit_cqring(ctx);
1997 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1999 io_cqring_ev_posted(ctx);
2002 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2004 req->flags &= ~REQ_F_LINK_HEAD;
2005 if (req->flags & REQ_F_LINK_TIMEOUT)
2006 io_kill_linked_timeout(req);
2009 * If LINK is set, we have dependent requests in this chain. If we
2010 * didn't fail this request, queue the first one up, moving any other
2011 * dependencies to the next request. In case of failure, fail the rest
2014 if (likely(!(req->flags & REQ_F_FAIL_LINK)))
2015 return io_req_link_next(req);
2020 static struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2022 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
2024 return __io_req_find_next(req);
2027 static int io_req_task_work_add(struct io_kiocb *req, bool twa_signal_ok)
2029 struct task_struct *tsk = req->task;
2030 struct io_ring_ctx *ctx = req->ctx;
2031 enum task_work_notify_mode notify;
2034 if (tsk->flags & PF_EXITING)
2038 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2039 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2040 * processing task_work. There's no reliable way to tell if TWA_RESUME
2044 if (!(ctx->flags & IORING_SETUP_SQPOLL) && twa_signal_ok)
2045 notify = TWA_SIGNAL;
2047 ret = task_work_add(tsk, &req->task_work, notify);
2049 wake_up_process(tsk);
2054 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2056 struct io_ring_ctx *ctx = req->ctx;
2058 spin_lock_irq(&ctx->completion_lock);
2059 io_cqring_fill_event(req, error);
2060 io_commit_cqring(ctx);
2061 spin_unlock_irq(&ctx->completion_lock);
2063 io_cqring_ev_posted(ctx);
2064 req_set_fail_links(req);
2065 io_double_put_req(req);
2068 static void io_req_task_cancel(struct callback_head *cb)
2070 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2071 struct io_ring_ctx *ctx = req->ctx;
2073 __io_req_task_cancel(req, -ECANCELED);
2074 percpu_ref_put(&ctx->refs);
2077 static void __io_req_task_submit(struct io_kiocb *req)
2079 struct io_ring_ctx *ctx = req->ctx;
2081 mutex_lock(&ctx->uring_lock);
2082 if (!ctx->sqo_dead && !__io_sq_thread_acquire_mm(ctx))
2083 __io_queue_sqe(req, NULL);
2085 __io_req_task_cancel(req, -EFAULT);
2086 mutex_unlock(&ctx->uring_lock);
2088 if (ctx->flags & IORING_SETUP_SQPOLL)
2089 io_sq_thread_drop_mm();
2092 static void io_req_task_submit(struct callback_head *cb)
2094 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2095 struct io_ring_ctx *ctx = req->ctx;
2097 __io_req_task_submit(req);
2098 percpu_ref_put(&ctx->refs);
2101 static void io_req_task_queue(struct io_kiocb *req)
2105 init_task_work(&req->task_work, io_req_task_submit);
2106 percpu_ref_get(&req->ctx->refs);
2108 ret = io_req_task_work_add(req, true);
2109 if (unlikely(ret)) {
2110 struct task_struct *tsk;
2112 init_task_work(&req->task_work, io_req_task_cancel);
2113 tsk = io_wq_get_task(req->ctx->io_wq);
2114 task_work_add(tsk, &req->task_work, TWA_NONE);
2115 wake_up_process(tsk);
2119 static void io_queue_next(struct io_kiocb *req)
2121 struct io_kiocb *nxt = io_req_find_next(req);
2124 io_req_task_queue(nxt);
2127 static void io_free_req(struct io_kiocb *req)
2134 void *reqs[IO_IOPOLL_BATCH];
2137 struct task_struct *task;
2141 static inline void io_init_req_batch(struct req_batch *rb)
2148 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
2149 struct req_batch *rb)
2151 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
2152 percpu_ref_put_many(&ctx->refs, rb->to_free);
2156 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2157 struct req_batch *rb)
2160 __io_req_free_batch_flush(ctx, rb);
2162 struct io_uring_task *tctx = rb->task->io_uring;
2164 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2165 if (atomic_read(&tctx->in_idle))
2166 wake_up(&tctx->wait);
2167 put_task_struct_many(rb->task, rb->task_refs);
2172 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
2174 if (unlikely(io_is_fallback_req(req))) {
2178 if (req->flags & REQ_F_LINK_HEAD)
2181 if (req->task != rb->task) {
2183 struct io_uring_task *tctx = rb->task->io_uring;
2185 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2186 if (atomic_read(&tctx->in_idle))
2187 wake_up(&tctx->wait);
2188 put_task_struct_many(rb->task, rb->task_refs);
2190 rb->task = req->task;
2195 io_dismantle_req(req);
2196 rb->reqs[rb->to_free++] = req;
2197 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
2198 __io_req_free_batch_flush(req->ctx, rb);
2202 * Drop reference to request, return next in chain (if there is one) if this
2203 * was the last reference to this request.
2205 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2207 struct io_kiocb *nxt = NULL;
2209 if (refcount_dec_and_test(&req->refs)) {
2210 nxt = io_req_find_next(req);
2216 static void io_put_req(struct io_kiocb *req)
2218 if (refcount_dec_and_test(&req->refs))
2222 static void io_put_req_deferred_cb(struct callback_head *cb)
2224 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2229 static void io_free_req_deferred(struct io_kiocb *req)
2233 init_task_work(&req->task_work, io_put_req_deferred_cb);
2234 ret = io_req_task_work_add(req, true);
2235 if (unlikely(ret)) {
2236 struct task_struct *tsk;
2238 tsk = io_wq_get_task(req->ctx->io_wq);
2239 task_work_add(tsk, &req->task_work, TWA_NONE);
2240 wake_up_process(tsk);
2244 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2246 if (refcount_sub_and_test(refs, &req->refs))
2247 io_free_req_deferred(req);
2250 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
2252 struct io_kiocb *nxt;
2255 * A ref is owned by io-wq in which context we're. So, if that's the
2256 * last one, it's safe to steal next work. False negatives are Ok,
2257 * it just will be re-punted async in io_put_work()
2259 if (refcount_read(&req->refs) != 1)
2262 nxt = io_req_find_next(req);
2263 return nxt ? &nxt->work : NULL;
2266 static void io_double_put_req(struct io_kiocb *req)
2268 /* drop both submit and complete references */
2269 if (refcount_sub_and_test(2, &req->refs))
2273 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2275 struct io_rings *rings = ctx->rings;
2277 /* See comment at the top of this file */
2279 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
2282 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2284 struct io_rings *rings = ctx->rings;
2286 /* make sure SQ entry isn't read before tail */
2287 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2290 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2292 unsigned int cflags;
2294 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2295 cflags |= IORING_CQE_F_BUFFER;
2296 req->flags &= ~REQ_F_BUFFER_SELECTED;
2301 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2303 struct io_buffer *kbuf;
2305 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2306 return io_put_kbuf(req, kbuf);
2309 static inline bool io_run_task_work(void)
2312 * Not safe to run on exiting task, and the task_work handling will
2313 * not add work to such a task.
2315 if (unlikely(current->flags & PF_EXITING))
2317 if (current->task_works) {
2318 __set_current_state(TASK_RUNNING);
2326 static void io_iopoll_queue(struct list_head *again)
2328 struct io_kiocb *req;
2331 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2332 list_del(&req->inflight_entry);
2333 __io_complete_rw(req, -EAGAIN, 0, NULL);
2334 } while (!list_empty(again));
2338 * Find and free completed poll iocbs
2340 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2341 struct list_head *done)
2343 struct req_batch rb;
2344 struct io_kiocb *req;
2347 /* order with ->result store in io_complete_rw_iopoll() */
2350 io_init_req_batch(&rb);
2351 while (!list_empty(done)) {
2354 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2355 if (READ_ONCE(req->result) == -EAGAIN) {
2357 req->iopoll_completed = 0;
2358 list_move_tail(&req->inflight_entry, &again);
2361 list_del(&req->inflight_entry);
2363 if (req->flags & REQ_F_BUFFER_SELECTED)
2364 cflags = io_put_rw_kbuf(req);
2366 __io_cqring_fill_event(req, req->result, cflags);
2369 if (refcount_dec_and_test(&req->refs))
2370 io_req_free_batch(&rb, req);
2373 io_commit_cqring(ctx);
2374 if (ctx->flags & IORING_SETUP_SQPOLL)
2375 io_cqring_ev_posted(ctx);
2376 io_req_free_batch_finish(ctx, &rb);
2378 if (!list_empty(&again))
2379 io_iopoll_queue(&again);
2382 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2385 struct io_kiocb *req, *tmp;
2391 * Only spin for completions if we don't have multiple devices hanging
2392 * off our complete list, and we're under the requested amount.
2394 spin = !ctx->poll_multi_file && *nr_events < min;
2397 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2398 struct kiocb *kiocb = &req->rw.kiocb;
2401 * Move completed and retryable entries to our local lists.
2402 * If we find a request that requires polling, break out
2403 * and complete those lists first, if we have entries there.
2405 if (READ_ONCE(req->iopoll_completed)) {
2406 list_move_tail(&req->inflight_entry, &done);
2409 if (!list_empty(&done))
2412 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2416 /* iopoll may have completed current req */
2417 if (READ_ONCE(req->iopoll_completed))
2418 list_move_tail(&req->inflight_entry, &done);
2425 if (!list_empty(&done))
2426 io_iopoll_complete(ctx, nr_events, &done);
2432 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2433 * non-spinning poll check - we'll still enter the driver poll loop, but only
2434 * as a non-spinning completion check.
2436 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2439 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2442 ret = io_do_iopoll(ctx, nr_events, min);
2445 if (*nr_events >= min)
2453 * We can't just wait for polled events to come to us, we have to actively
2454 * find and complete them.
2456 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2458 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2461 mutex_lock(&ctx->uring_lock);
2462 while (!list_empty(&ctx->iopoll_list)) {
2463 unsigned int nr_events = 0;
2465 io_do_iopoll(ctx, &nr_events, 0);
2467 /* let it sleep and repeat later if can't complete a request */
2471 * Ensure we allow local-to-the-cpu processing to take place,
2472 * in this case we need to ensure that we reap all events.
2473 * Also let task_work, etc. to progress by releasing the mutex
2475 if (need_resched()) {
2476 mutex_unlock(&ctx->uring_lock);
2478 mutex_lock(&ctx->uring_lock);
2481 mutex_unlock(&ctx->uring_lock);
2484 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2486 unsigned int nr_events = 0;
2487 int iters = 0, ret = 0;
2490 * We disallow the app entering submit/complete with polling, but we
2491 * still need to lock the ring to prevent racing with polled issue
2492 * that got punted to a workqueue.
2494 mutex_lock(&ctx->uring_lock);
2497 * Don't enter poll loop if we already have events pending.
2498 * If we do, we can potentially be spinning for commands that
2499 * already triggered a CQE (eg in error).
2501 if (test_bit(0, &ctx->cq_check_overflow))
2502 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2503 if (io_cqring_events(ctx))
2507 * If a submit got punted to a workqueue, we can have the
2508 * application entering polling for a command before it gets
2509 * issued. That app will hold the uring_lock for the duration
2510 * of the poll right here, so we need to take a breather every
2511 * now and then to ensure that the issue has a chance to add
2512 * the poll to the issued list. Otherwise we can spin here
2513 * forever, while the workqueue is stuck trying to acquire the
2516 if (!(++iters & 7)) {
2517 mutex_unlock(&ctx->uring_lock);
2519 mutex_lock(&ctx->uring_lock);
2522 ret = io_iopoll_getevents(ctx, &nr_events, min);
2526 } while (min && !nr_events && !need_resched());
2528 mutex_unlock(&ctx->uring_lock);
2532 static void kiocb_end_write(struct io_kiocb *req)
2535 * Tell lockdep we inherited freeze protection from submission
2538 if (req->flags & REQ_F_ISREG) {
2539 struct inode *inode = file_inode(req->file);
2541 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2543 file_end_write(req->file);
2546 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2547 struct io_comp_state *cs)
2549 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2552 if (kiocb->ki_flags & IOCB_WRITE)
2553 kiocb_end_write(req);
2555 if (res != req->result)
2556 req_set_fail_links(req);
2557 if (req->flags & REQ_F_BUFFER_SELECTED)
2558 cflags = io_put_rw_kbuf(req);
2559 __io_req_complete(req, res, cflags, cs);
2563 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2565 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2566 ssize_t ret = -ECANCELED;
2567 struct iov_iter iter;
2575 switch (req->opcode) {
2576 case IORING_OP_READV:
2577 case IORING_OP_READ_FIXED:
2578 case IORING_OP_READ:
2581 case IORING_OP_WRITEV:
2582 case IORING_OP_WRITE_FIXED:
2583 case IORING_OP_WRITE:
2587 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2592 if (!req->async_data) {
2593 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2596 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2604 req_set_fail_links(req);
2609 static bool io_rw_reissue(struct io_kiocb *req, long res)
2612 umode_t mode = file_inode(req->file)->i_mode;
2615 if (!S_ISBLK(mode) && !S_ISREG(mode))
2617 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2620 ret = io_sq_thread_acquire_mm(req->ctx, req);
2622 if (io_resubmit_prep(req, ret)) {
2623 refcount_inc(&req->refs);
2624 io_queue_async_work(req);
2632 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2633 struct io_comp_state *cs)
2635 if (!io_rw_reissue(req, res))
2636 io_complete_rw_common(&req->rw.kiocb, res, cs);
2639 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2641 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2643 __io_complete_rw(req, res, res2, NULL);
2646 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2648 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2650 if (kiocb->ki_flags & IOCB_WRITE)
2651 kiocb_end_write(req);
2653 if (res != -EAGAIN && res != req->result)
2654 req_set_fail_links(req);
2656 WRITE_ONCE(req->result, res);
2657 /* order with io_poll_complete() checking ->result */
2659 WRITE_ONCE(req->iopoll_completed, 1);
2663 * After the iocb has been issued, it's safe to be found on the poll list.
2664 * Adding the kiocb to the list AFTER submission ensures that we don't
2665 * find it from a io_iopoll_getevents() thread before the issuer is done
2666 * accessing the kiocb cookie.
2668 static void io_iopoll_req_issued(struct io_kiocb *req)
2670 struct io_ring_ctx *ctx = req->ctx;
2673 * Track whether we have multiple files in our lists. This will impact
2674 * how we do polling eventually, not spinning if we're on potentially
2675 * different devices.
2677 if (list_empty(&ctx->iopoll_list)) {
2678 ctx->poll_multi_file = false;
2679 } else if (!ctx->poll_multi_file) {
2680 struct io_kiocb *list_req;
2682 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2684 if (list_req->file != req->file)
2685 ctx->poll_multi_file = true;
2689 * For fast devices, IO may have already completed. If it has, add
2690 * it to the front so we find it first.
2692 if (READ_ONCE(req->iopoll_completed))
2693 list_add(&req->inflight_entry, &ctx->iopoll_list);
2695 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2697 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2698 wq_has_sleeper(&ctx->sq_data->wait))
2699 wake_up(&ctx->sq_data->wait);
2702 static void __io_state_file_put(struct io_submit_state *state)
2704 if (state->has_refs)
2705 fput_many(state->file, state->has_refs);
2709 static inline void io_state_file_put(struct io_submit_state *state)
2712 __io_state_file_put(state);
2716 * Get as many references to a file as we have IOs left in this submission,
2717 * assuming most submissions are for one file, or at least that each file
2718 * has more than one submission.
2720 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2726 if (state->fd == fd) {
2730 __io_state_file_put(state);
2732 state->file = fget_many(fd, state->ios_left);
2737 state->has_refs = state->ios_left - 1;
2741 static bool io_bdev_nowait(struct block_device *bdev)
2744 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2751 * If we tracked the file through the SCM inflight mechanism, we could support
2752 * any file. For now, just ensure that anything potentially problematic is done
2755 static bool io_file_supports_async(struct file *file, int rw)
2757 umode_t mode = file_inode(file)->i_mode;
2759 if (S_ISBLK(mode)) {
2760 if (io_bdev_nowait(file->f_inode->i_bdev))
2764 if (S_ISCHR(mode) || S_ISSOCK(mode))
2766 if (S_ISREG(mode)) {
2767 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2768 file->f_op != &io_uring_fops)
2773 /* any ->read/write should understand O_NONBLOCK */
2774 if (file->f_flags & O_NONBLOCK)
2777 if (!(file->f_mode & FMODE_NOWAIT))
2781 return file->f_op->read_iter != NULL;
2783 return file->f_op->write_iter != NULL;
2786 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2788 struct io_ring_ctx *ctx = req->ctx;
2789 struct kiocb *kiocb = &req->rw.kiocb;
2793 if (S_ISREG(file_inode(req->file)->i_mode))
2794 req->flags |= REQ_F_ISREG;
2796 kiocb->ki_pos = READ_ONCE(sqe->off);
2797 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2798 req->flags |= REQ_F_CUR_POS;
2799 kiocb->ki_pos = req->file->f_pos;
2801 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2802 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2803 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2807 ioprio = READ_ONCE(sqe->ioprio);
2809 ret = ioprio_check_cap(ioprio);
2813 kiocb->ki_ioprio = ioprio;
2815 kiocb->ki_ioprio = get_current_ioprio();
2817 /* don't allow async punt if RWF_NOWAIT was requested */
2818 if (kiocb->ki_flags & IOCB_NOWAIT)
2819 req->flags |= REQ_F_NOWAIT;
2821 if (ctx->flags & IORING_SETUP_IOPOLL) {
2822 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2823 !kiocb->ki_filp->f_op->iopoll)
2826 kiocb->ki_flags |= IOCB_HIPRI;
2827 kiocb->ki_complete = io_complete_rw_iopoll;
2828 req->iopoll_completed = 0;
2830 if (kiocb->ki_flags & IOCB_HIPRI)
2832 kiocb->ki_complete = io_complete_rw;
2835 req->rw.addr = READ_ONCE(sqe->addr);
2836 req->rw.len = READ_ONCE(sqe->len);
2837 req->buf_index = READ_ONCE(sqe->buf_index);
2841 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2847 case -ERESTARTNOINTR:
2848 case -ERESTARTNOHAND:
2849 case -ERESTART_RESTARTBLOCK:
2851 * We can't just restart the syscall, since previously
2852 * submitted sqes may already be in progress. Just fail this
2858 kiocb->ki_complete(kiocb, ret, 0);
2862 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2863 struct io_comp_state *cs)
2865 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2866 struct io_async_rw *io = req->async_data;
2868 /* add previously done IO, if any */
2869 if (io && io->bytes_done > 0) {
2871 ret = io->bytes_done;
2873 ret += io->bytes_done;
2876 if (req->flags & REQ_F_CUR_POS)
2877 req->file->f_pos = kiocb->ki_pos;
2878 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2879 __io_complete_rw(req, ret, 0, cs);
2881 io_rw_done(kiocb, ret);
2884 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2885 struct iov_iter *iter)
2887 struct io_ring_ctx *ctx = req->ctx;
2888 size_t len = req->rw.len;
2889 struct io_mapped_ubuf *imu;
2890 u16 index, buf_index = req->buf_index;
2894 if (unlikely(buf_index >= ctx->nr_user_bufs))
2896 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2897 imu = &ctx->user_bufs[index];
2898 buf_addr = req->rw.addr;
2901 if (buf_addr + len < buf_addr)
2903 /* not inside the mapped region */
2904 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2908 * May not be a start of buffer, set size appropriately
2909 * and advance us to the beginning.
2911 offset = buf_addr - imu->ubuf;
2912 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2916 * Don't use iov_iter_advance() here, as it's really slow for
2917 * using the latter parts of a big fixed buffer - it iterates
2918 * over each segment manually. We can cheat a bit here, because
2921 * 1) it's a BVEC iter, we set it up
2922 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2923 * first and last bvec
2925 * So just find our index, and adjust the iterator afterwards.
2926 * If the offset is within the first bvec (or the whole first
2927 * bvec, just use iov_iter_advance(). This makes it easier
2928 * since we can just skip the first segment, which may not
2929 * be PAGE_SIZE aligned.
2931 const struct bio_vec *bvec = imu->bvec;
2933 if (offset <= bvec->bv_len) {
2934 iov_iter_advance(iter, offset);
2936 unsigned long seg_skip;
2938 /* skip first vec */
2939 offset -= bvec->bv_len;
2940 seg_skip = 1 + (offset >> PAGE_SHIFT);
2942 iter->bvec = bvec + seg_skip;
2943 iter->nr_segs -= seg_skip;
2944 iter->count -= bvec->bv_len + offset;
2945 iter->iov_offset = offset & ~PAGE_MASK;
2952 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2955 mutex_unlock(&ctx->uring_lock);
2958 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2961 * "Normal" inline submissions always hold the uring_lock, since we
2962 * grab it from the system call. Same is true for the SQPOLL offload.
2963 * The only exception is when we've detached the request and issue it
2964 * from an async worker thread, grab the lock for that case.
2967 mutex_lock(&ctx->uring_lock);
2970 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2971 int bgid, struct io_buffer *kbuf,
2974 struct io_buffer *head;
2976 if (req->flags & REQ_F_BUFFER_SELECTED)
2979 io_ring_submit_lock(req->ctx, needs_lock);
2981 lockdep_assert_held(&req->ctx->uring_lock);
2983 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2985 if (!list_empty(&head->list)) {
2986 kbuf = list_last_entry(&head->list, struct io_buffer,
2988 list_del(&kbuf->list);
2991 idr_remove(&req->ctx->io_buffer_idr, bgid);
2993 if (*len > kbuf->len)
2996 kbuf = ERR_PTR(-ENOBUFS);
2999 io_ring_submit_unlock(req->ctx, needs_lock);
3004 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3007 struct io_buffer *kbuf;
3010 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3011 bgid = req->buf_index;
3012 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3015 req->rw.addr = (u64) (unsigned long) kbuf;
3016 req->flags |= REQ_F_BUFFER_SELECTED;
3017 return u64_to_user_ptr(kbuf->addr);
3020 #ifdef CONFIG_COMPAT
3021 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3024 struct compat_iovec __user *uiov;
3025 compat_ssize_t clen;
3029 uiov = u64_to_user_ptr(req->rw.addr);
3030 if (!access_ok(uiov, sizeof(*uiov)))
3032 if (__get_user(clen, &uiov->iov_len))
3038 buf = io_rw_buffer_select(req, &len, needs_lock);
3040 return PTR_ERR(buf);
3041 iov[0].iov_base = buf;
3042 iov[0].iov_len = (compat_size_t) len;
3047 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3050 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3054 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3057 len = iov[0].iov_len;
3060 buf = io_rw_buffer_select(req, &len, needs_lock);
3062 return PTR_ERR(buf);
3063 iov[0].iov_base = buf;
3064 iov[0].iov_len = len;
3068 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3071 if (req->flags & REQ_F_BUFFER_SELECTED) {
3072 struct io_buffer *kbuf;
3074 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3075 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3076 iov[0].iov_len = kbuf->len;
3079 if (req->rw.len != 1)
3082 #ifdef CONFIG_COMPAT
3083 if (req->ctx->compat)
3084 return io_compat_import(req, iov, needs_lock);
3087 return __io_iov_buffer_select(req, iov, needs_lock);
3090 static ssize_t __io_import_iovec(int rw, struct io_kiocb *req,
3091 struct iovec **iovec, struct iov_iter *iter,
3094 void __user *buf = u64_to_user_ptr(req->rw.addr);
3095 size_t sqe_len = req->rw.len;
3099 opcode = req->opcode;
3100 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3102 return io_import_fixed(req, rw, iter);
3105 /* buffer index only valid with fixed read/write, or buffer select */
3106 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3109 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3110 if (req->flags & REQ_F_BUFFER_SELECT) {
3111 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3113 return PTR_ERR(buf);
3114 req->rw.len = sqe_len;
3117 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3119 return ret < 0 ? ret : sqe_len;
3122 if (req->flags & REQ_F_BUFFER_SELECT) {
3123 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3125 ret = (*iovec)->iov_len;
3126 iov_iter_init(iter, rw, *iovec, 1, ret);
3132 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3136 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
3137 struct iovec **iovec, struct iov_iter *iter,
3140 struct io_async_rw *iorw = req->async_data;
3143 return __io_import_iovec(rw, req, iovec, iter, needs_lock);
3145 return iov_iter_count(&iorw->iter);
3148 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3150 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3154 * For files that don't have ->read_iter() and ->write_iter(), handle them
3155 * by looping over ->read() or ->write() manually.
3157 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3159 struct kiocb *kiocb = &req->rw.kiocb;
3160 struct file *file = req->file;
3164 * Don't support polled IO through this interface, and we can't
3165 * support non-blocking either. For the latter, this just causes
3166 * the kiocb to be handled from an async context.
3168 if (kiocb->ki_flags & IOCB_HIPRI)
3170 if (kiocb->ki_flags & IOCB_NOWAIT)
3173 while (iov_iter_count(iter)) {
3177 if (!iov_iter_is_bvec(iter)) {
3178 iovec = iov_iter_iovec(iter);
3180 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3181 iovec.iov_len = req->rw.len;
3185 nr = file->f_op->read(file, iovec.iov_base,
3186 iovec.iov_len, io_kiocb_ppos(kiocb));
3188 nr = file->f_op->write(file, iovec.iov_base,
3189 iovec.iov_len, io_kiocb_ppos(kiocb));
3198 if (nr != iovec.iov_len)
3202 iov_iter_advance(iter, nr);
3208 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3209 const struct iovec *fast_iov, struct iov_iter *iter)
3211 struct io_async_rw *rw = req->async_data;
3213 memcpy(&rw->iter, iter, sizeof(*iter));
3214 rw->free_iovec = iovec;
3216 /* can only be fixed buffers, no need to do anything */
3217 if (iov_iter_is_bvec(iter))
3220 unsigned iov_off = 0;
3222 rw->iter.iov = rw->fast_iov;
3223 if (iter->iov != fast_iov) {
3224 iov_off = iter->iov - fast_iov;
3225 rw->iter.iov += iov_off;
3227 if (rw->fast_iov != fast_iov)
3228 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3229 sizeof(struct iovec) * iter->nr_segs);
3231 req->flags |= REQ_F_NEED_CLEANUP;
3235 static inline int __io_alloc_async_data(struct io_kiocb *req)
3237 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3238 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3239 return req->async_data == NULL;
3242 static int io_alloc_async_data(struct io_kiocb *req)
3244 if (!io_op_defs[req->opcode].needs_async_data)
3247 return __io_alloc_async_data(req);
3250 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3251 const struct iovec *fast_iov,
3252 struct iov_iter *iter, bool force)
3254 if (!force && !io_op_defs[req->opcode].needs_async_data)
3256 if (!req->async_data) {
3257 if (__io_alloc_async_data(req))
3260 io_req_map_rw(req, iovec, fast_iov, iter);
3265 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3267 struct io_async_rw *iorw = req->async_data;
3268 struct iovec *iov = iorw->fast_iov;
3271 ret = __io_import_iovec(rw, req, &iov, &iorw->iter, false);
3272 if (unlikely(ret < 0))
3275 iorw->bytes_done = 0;
3276 iorw->free_iovec = iov;
3278 req->flags |= REQ_F_NEED_CLEANUP;
3282 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3286 ret = io_prep_rw(req, sqe);
3290 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3293 /* either don't need iovec imported or already have it */
3294 if (!req->async_data)
3296 return io_rw_prep_async(req, READ);
3300 * This is our waitqueue callback handler, registered through lock_page_async()
3301 * when we initially tried to do the IO with the iocb armed our waitqueue.
3302 * This gets called when the page is unlocked, and we generally expect that to
3303 * happen when the page IO is completed and the page is now uptodate. This will
3304 * queue a task_work based retry of the operation, attempting to copy the data
3305 * again. If the latter fails because the page was NOT uptodate, then we will
3306 * do a thread based blocking retry of the operation. That's the unexpected
3309 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3310 int sync, void *arg)
3312 struct wait_page_queue *wpq;
3313 struct io_kiocb *req = wait->private;
3314 struct wait_page_key *key = arg;
3317 wpq = container_of(wait, struct wait_page_queue, wait);
3319 if (!wake_page_match(wpq, key))
3322 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3323 list_del_init(&wait->entry);
3325 init_task_work(&req->task_work, io_req_task_submit);
3326 percpu_ref_get(&req->ctx->refs);
3328 /* submit ref gets dropped, acquire a new one */
3329 refcount_inc(&req->refs);
3330 ret = io_req_task_work_add(req, true);
3331 if (unlikely(ret)) {
3332 struct task_struct *tsk;
3334 /* queue just for cancelation */
3335 init_task_work(&req->task_work, io_req_task_cancel);
3336 tsk = io_wq_get_task(req->ctx->io_wq);
3337 task_work_add(tsk, &req->task_work, TWA_NONE);
3338 wake_up_process(tsk);
3344 * This controls whether a given IO request should be armed for async page
3345 * based retry. If we return false here, the request is handed to the async
3346 * worker threads for retry. If we're doing buffered reads on a regular file,
3347 * we prepare a private wait_page_queue entry and retry the operation. This
3348 * will either succeed because the page is now uptodate and unlocked, or it
3349 * will register a callback when the page is unlocked at IO completion. Through
3350 * that callback, io_uring uses task_work to setup a retry of the operation.
3351 * That retry will attempt the buffered read again. The retry will generally
3352 * succeed, or in rare cases where it fails, we then fall back to using the
3353 * async worker threads for a blocking retry.
3355 static bool io_rw_should_retry(struct io_kiocb *req)
3357 struct io_async_rw *rw = req->async_data;
3358 struct wait_page_queue *wait = &rw->wpq;
3359 struct kiocb *kiocb = &req->rw.kiocb;
3361 /* never retry for NOWAIT, we just complete with -EAGAIN */
3362 if (req->flags & REQ_F_NOWAIT)
3365 /* Only for buffered IO */
3366 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3370 * just use poll if we can, and don't attempt if the fs doesn't
3371 * support callback based unlocks
3373 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3376 wait->wait.func = io_async_buf_func;
3377 wait->wait.private = req;
3378 wait->wait.flags = 0;
3379 INIT_LIST_HEAD(&wait->wait.entry);
3380 kiocb->ki_flags |= IOCB_WAITQ;
3381 kiocb->ki_flags &= ~IOCB_NOWAIT;
3382 kiocb->ki_waitq = wait;
3386 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3388 if (req->file->f_op->read_iter)
3389 return call_read_iter(req->file, &req->rw.kiocb, iter);
3390 else if (req->file->f_op->read)
3391 return loop_rw_iter(READ, req, iter);
3396 static int io_read(struct io_kiocb *req, bool force_nonblock,
3397 struct io_comp_state *cs)
3399 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3400 struct kiocb *kiocb = &req->rw.kiocb;
3401 struct iov_iter __iter, *iter = &__iter;
3402 struct io_async_rw *rw = req->async_data;
3403 ssize_t io_size, ret, ret2;
3410 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3413 iov_count = iov_iter_count(iter);
3415 req->result = io_size;
3418 /* Ensure we clear previously set non-block flag */
3419 if (!force_nonblock)
3420 kiocb->ki_flags &= ~IOCB_NOWAIT;
3422 kiocb->ki_flags |= IOCB_NOWAIT;
3425 /* If the file doesn't support async, just async punt */
3426 no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3430 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), iov_count);
3434 ret = io_iter_do_read(req, iter);
3438 } else if (ret == -EIOCBQUEUED) {
3441 } else if (ret == -EAGAIN) {
3442 /* IOPOLL retry should happen for io-wq threads */
3443 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3445 /* no retry on NONBLOCK marked file */
3446 if (req->file->f_flags & O_NONBLOCK)
3448 /* some cases will consume bytes even on error returns */
3449 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
3452 } else if (ret < 0) {
3453 /* make sure -ERESTARTSYS -> -EINTR is done */
3457 /* read it all, or we did blocking attempt. no retry. */
3458 if (!iov_iter_count(iter) || !force_nonblock ||
3459 (req->file->f_flags & O_NONBLOCK) || !(req->flags & REQ_F_ISREG))
3464 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3471 rw = req->async_data;
3472 /* it's copied and will be cleaned with ->io */
3474 /* now use our persistent iterator, if we aren't already */
3477 rw->bytes_done += ret;
3478 /* if we can retry, do so with the callbacks armed */
3479 if (!io_rw_should_retry(req)) {
3480 kiocb->ki_flags &= ~IOCB_WAITQ;
3485 * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3486 * get -EIOCBQUEUED, then we'll get a notification when the desired
3487 * page gets unlocked. We can also get a partial read here, and if we
3488 * do, then just retry at the new offset.
3490 ret = io_iter_do_read(req, iter);
3491 if (ret == -EIOCBQUEUED) {
3494 } else if (ret > 0 && ret < io_size) {
3495 /* we got some bytes, but not all. retry. */
3499 kiocb_done(kiocb, ret, cs);
3502 /* it's reportedly faster than delegating the null check to kfree() */
3508 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3512 ret = io_prep_rw(req, sqe);
3516 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3519 /* either don't need iovec imported or already have it */
3520 if (!req->async_data)
3522 return io_rw_prep_async(req, WRITE);
3525 static int io_write(struct io_kiocb *req, bool force_nonblock,
3526 struct io_comp_state *cs)
3528 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3529 struct kiocb *kiocb = &req->rw.kiocb;
3530 struct iov_iter __iter, *iter = &__iter;
3531 struct io_async_rw *rw = req->async_data;
3533 ssize_t ret, ret2, io_size;
3538 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3541 iov_count = iov_iter_count(iter);
3543 req->result = io_size;
3545 /* Ensure we clear previously set non-block flag */
3546 if (!force_nonblock)
3547 kiocb->ki_flags &= ~IOCB_NOWAIT;
3549 kiocb->ki_flags |= IOCB_NOWAIT;
3551 /* If the file doesn't support async, just async punt */
3552 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3555 /* file path doesn't support NOWAIT for non-direct_IO */
3556 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3557 (req->flags & REQ_F_ISREG))
3560 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), iov_count);
3565 * Open-code file_start_write here to grab freeze protection,
3566 * which will be released by another thread in
3567 * io_complete_rw(). Fool lockdep by telling it the lock got
3568 * released so that it doesn't complain about the held lock when
3569 * we return to userspace.
3571 if (req->flags & REQ_F_ISREG) {
3572 sb_start_write(file_inode(req->file)->i_sb);
3573 __sb_writers_release(file_inode(req->file)->i_sb,
3576 kiocb->ki_flags |= IOCB_WRITE;
3578 if (req->file->f_op->write_iter)
3579 ret2 = call_write_iter(req->file, kiocb, iter);
3580 else if (req->file->f_op->write)
3581 ret2 = loop_rw_iter(WRITE, req, iter);
3586 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3587 * retry them without IOCB_NOWAIT.
3589 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3591 /* no retry on NONBLOCK marked file */
3592 if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3594 if (!force_nonblock || ret2 != -EAGAIN) {
3595 /* IOPOLL retry should happen for io-wq threads */
3596 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3599 kiocb_done(kiocb, ret2, cs);
3602 /* some cases will consume bytes even on error returns */
3603 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
3604 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3609 /* it's reportedly faster than delegating the null check to kfree() */
3615 static int __io_splice_prep(struct io_kiocb *req,
3616 const struct io_uring_sqe *sqe)
3618 struct io_splice* sp = &req->splice;
3619 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3621 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3625 sp->len = READ_ONCE(sqe->len);
3626 sp->flags = READ_ONCE(sqe->splice_flags);
3628 if (unlikely(sp->flags & ~valid_flags))
3631 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3632 (sp->flags & SPLICE_F_FD_IN_FIXED));
3635 req->flags |= REQ_F_NEED_CLEANUP;
3637 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3639 * Splice operation will be punted aync, and here need to
3640 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3642 io_req_init_async(req);
3643 req->work.flags |= IO_WQ_WORK_UNBOUND;
3649 static int io_tee_prep(struct io_kiocb *req,
3650 const struct io_uring_sqe *sqe)
3652 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3654 return __io_splice_prep(req, sqe);
3657 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3659 struct io_splice *sp = &req->splice;
3660 struct file *in = sp->file_in;
3661 struct file *out = sp->file_out;
3662 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3668 ret = do_tee(in, out, sp->len, flags);
3670 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3671 req->flags &= ~REQ_F_NEED_CLEANUP;
3674 req_set_fail_links(req);
3675 io_req_complete(req, ret);
3679 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3681 struct io_splice* sp = &req->splice;
3683 sp->off_in = READ_ONCE(sqe->splice_off_in);
3684 sp->off_out = READ_ONCE(sqe->off);
3685 return __io_splice_prep(req, sqe);
3688 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3690 struct io_splice *sp = &req->splice;
3691 struct file *in = sp->file_in;
3692 struct file *out = sp->file_out;
3693 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3694 loff_t *poff_in, *poff_out;
3700 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3701 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3704 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3706 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3707 req->flags &= ~REQ_F_NEED_CLEANUP;
3710 req_set_fail_links(req);
3711 io_req_complete(req, ret);
3716 * IORING_OP_NOP just posts a completion event, nothing else.
3718 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3720 struct io_ring_ctx *ctx = req->ctx;
3722 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3725 __io_req_complete(req, 0, 0, cs);
3729 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3731 struct io_ring_ctx *ctx = req->ctx;
3736 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3738 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3741 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3742 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3745 req->sync.off = READ_ONCE(sqe->off);
3746 req->sync.len = READ_ONCE(sqe->len);
3750 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3752 loff_t end = req->sync.off + req->sync.len;
3755 /* fsync always requires a blocking context */
3759 ret = vfs_fsync_range(req->file, req->sync.off,
3760 end > 0 ? end : LLONG_MAX,
3761 req->sync.flags & IORING_FSYNC_DATASYNC);
3763 req_set_fail_links(req);
3764 io_req_complete(req, ret);
3768 static int io_fallocate_prep(struct io_kiocb *req,
3769 const struct io_uring_sqe *sqe)
3771 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3773 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3776 req->sync.off = READ_ONCE(sqe->off);
3777 req->sync.len = READ_ONCE(sqe->addr);
3778 req->sync.mode = READ_ONCE(sqe->len);
3782 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3786 /* fallocate always requiring blocking context */
3789 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3792 req_set_fail_links(req);
3793 io_req_complete(req, ret);
3797 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3799 const char __user *fname;
3802 if (unlikely(sqe->ioprio || sqe->buf_index))
3804 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3807 /* open.how should be already initialised */
3808 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3809 req->open.how.flags |= O_LARGEFILE;
3811 req->open.dfd = READ_ONCE(sqe->fd);
3812 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3813 req->open.filename = getname(fname);
3814 if (IS_ERR(req->open.filename)) {
3815 ret = PTR_ERR(req->open.filename);
3816 req->open.filename = NULL;
3819 req->open.nofile = rlimit(RLIMIT_NOFILE);
3820 req->open.ignore_nonblock = false;
3821 req->flags |= REQ_F_NEED_CLEANUP;
3825 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3829 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3831 mode = READ_ONCE(sqe->len);
3832 flags = READ_ONCE(sqe->open_flags);
3833 req->open.how = build_open_how(flags, mode);
3834 return __io_openat_prep(req, sqe);
3837 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3839 struct open_how __user *how;
3843 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3845 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3846 len = READ_ONCE(sqe->len);
3847 if (len < OPEN_HOW_SIZE_VER0)
3850 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3855 return __io_openat_prep(req, sqe);
3858 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3860 struct open_flags op;
3864 if (force_nonblock && !req->open.ignore_nonblock)
3867 ret = build_open_flags(&req->open.how, &op);
3871 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3875 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3878 ret = PTR_ERR(file);
3880 * A work-around to ensure that /proc/self works that way
3881 * that it should - if we get -EOPNOTSUPP back, then assume
3882 * that proc_self_get_link() failed us because we're in async
3883 * context. We should be safe to retry this from the task
3884 * itself with force_nonblock == false set, as it should not
3885 * block on lookup. Would be nice to know this upfront and
3886 * avoid the async dance, but doesn't seem feasible.
3888 if (ret == -EOPNOTSUPP && io_wq_current_is_worker()) {
3889 req->open.ignore_nonblock = true;
3890 refcount_inc(&req->refs);
3891 io_req_task_queue(req);
3895 fsnotify_open(file);
3896 fd_install(ret, file);
3899 putname(req->open.filename);
3900 req->flags &= ~REQ_F_NEED_CLEANUP;
3902 req_set_fail_links(req);
3903 io_req_complete(req, ret);
3907 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3909 return io_openat2(req, force_nonblock);
3912 static int io_remove_buffers_prep(struct io_kiocb *req,
3913 const struct io_uring_sqe *sqe)
3915 struct io_provide_buf *p = &req->pbuf;
3918 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3921 tmp = READ_ONCE(sqe->fd);
3922 if (!tmp || tmp > USHRT_MAX)
3925 memset(p, 0, sizeof(*p));
3927 p->bgid = READ_ONCE(sqe->buf_group);
3931 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3932 int bgid, unsigned nbufs)
3936 /* shouldn't happen */
3940 /* the head kbuf is the list itself */
3941 while (!list_empty(&buf->list)) {
3942 struct io_buffer *nxt;
3944 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3945 list_del(&nxt->list);
3952 idr_remove(&ctx->io_buffer_idr, bgid);
3957 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3958 struct io_comp_state *cs)
3960 struct io_provide_buf *p = &req->pbuf;
3961 struct io_ring_ctx *ctx = req->ctx;
3962 struct io_buffer *head;
3965 io_ring_submit_lock(ctx, !force_nonblock);
3967 lockdep_assert_held(&ctx->uring_lock);
3970 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3972 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3974 req_set_fail_links(req);
3976 /* need to hold the lock to complete IOPOLL requests */
3977 if (ctx->flags & IORING_SETUP_IOPOLL) {
3978 __io_req_complete(req, ret, 0, cs);
3979 io_ring_submit_unlock(ctx, !force_nonblock);
3981 io_ring_submit_unlock(ctx, !force_nonblock);
3982 __io_req_complete(req, ret, 0, cs);
3987 static int io_provide_buffers_prep(struct io_kiocb *req,
3988 const struct io_uring_sqe *sqe)
3990 struct io_provide_buf *p = &req->pbuf;
3993 if (sqe->ioprio || sqe->rw_flags)
3996 tmp = READ_ONCE(sqe->fd);
3997 if (!tmp || tmp > USHRT_MAX)
4000 p->addr = READ_ONCE(sqe->addr);
4001 p->len = READ_ONCE(sqe->len);
4003 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4006 p->bgid = READ_ONCE(sqe->buf_group);
4007 tmp = READ_ONCE(sqe->off);
4008 if (tmp > USHRT_MAX)
4014 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4016 struct io_buffer *buf;
4017 u64 addr = pbuf->addr;
4018 int i, bid = pbuf->bid;
4020 for (i = 0; i < pbuf->nbufs; i++) {
4021 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4026 buf->len = pbuf->len;
4031 INIT_LIST_HEAD(&buf->list);
4034 list_add_tail(&buf->list, &(*head)->list);
4038 return i ? i : -ENOMEM;
4041 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
4042 struct io_comp_state *cs)
4044 struct io_provide_buf *p = &req->pbuf;
4045 struct io_ring_ctx *ctx = req->ctx;
4046 struct io_buffer *head, *list;
4049 io_ring_submit_lock(ctx, !force_nonblock);
4051 lockdep_assert_held(&ctx->uring_lock);
4053 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4055 ret = io_add_buffers(p, &head);
4060 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4063 __io_remove_buffers(ctx, head, p->bgid, -1U);
4069 req_set_fail_links(req);
4071 /* need to hold the lock to complete IOPOLL requests */
4072 if (ctx->flags & IORING_SETUP_IOPOLL) {
4073 __io_req_complete(req, ret, 0, cs);
4074 io_ring_submit_unlock(ctx, !force_nonblock);
4076 io_ring_submit_unlock(ctx, !force_nonblock);
4077 __io_req_complete(req, ret, 0, cs);
4082 static int io_epoll_ctl_prep(struct io_kiocb *req,
4083 const struct io_uring_sqe *sqe)
4085 #if defined(CONFIG_EPOLL)
4086 if (sqe->ioprio || sqe->buf_index)
4088 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4091 req->epoll.epfd = READ_ONCE(sqe->fd);
4092 req->epoll.op = READ_ONCE(sqe->len);
4093 req->epoll.fd = READ_ONCE(sqe->off);
4095 if (ep_op_has_event(req->epoll.op)) {
4096 struct epoll_event __user *ev;
4098 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4099 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4109 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
4110 struct io_comp_state *cs)
4112 #if defined(CONFIG_EPOLL)
4113 struct io_epoll *ie = &req->epoll;
4116 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4117 if (force_nonblock && ret == -EAGAIN)
4121 req_set_fail_links(req);
4122 __io_req_complete(req, ret, 0, cs);
4129 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4131 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4132 if (sqe->ioprio || sqe->buf_index || sqe->off)
4134 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4137 req->madvise.addr = READ_ONCE(sqe->addr);
4138 req->madvise.len = READ_ONCE(sqe->len);
4139 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4146 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
4148 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4149 struct io_madvise *ma = &req->madvise;
4155 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4157 req_set_fail_links(req);
4158 io_req_complete(req, ret);
4165 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4167 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4169 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4172 req->fadvise.offset = READ_ONCE(sqe->off);
4173 req->fadvise.len = READ_ONCE(sqe->len);
4174 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4178 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
4180 struct io_fadvise *fa = &req->fadvise;
4183 if (force_nonblock) {
4184 switch (fa->advice) {
4185 case POSIX_FADV_NORMAL:
4186 case POSIX_FADV_RANDOM:
4187 case POSIX_FADV_SEQUENTIAL:
4194 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4196 req_set_fail_links(req);
4197 io_req_complete(req, ret);
4201 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4203 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4205 if (sqe->ioprio || sqe->buf_index)
4207 if (req->flags & REQ_F_FIXED_FILE)
4210 req->statx.dfd = READ_ONCE(sqe->fd);
4211 req->statx.mask = READ_ONCE(sqe->len);
4212 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4213 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4214 req->statx.flags = READ_ONCE(sqe->statx_flags);
4219 static int io_statx(struct io_kiocb *req, bool force_nonblock)
4221 struct io_statx *ctx = &req->statx;
4224 if (force_nonblock) {
4225 /* only need file table for an actual valid fd */
4226 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4227 req->flags |= REQ_F_NO_FILE_TABLE;
4231 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4235 req_set_fail_links(req);
4236 io_req_complete(req, ret);
4240 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4243 * If we queue this for async, it must not be cancellable. That would
4244 * leave the 'file' in an undeterminate state, and here need to modify
4245 * io_wq_work.flags, so initialize io_wq_work firstly.
4247 io_req_init_async(req);
4249 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4251 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4252 sqe->rw_flags || sqe->buf_index)
4254 if (req->flags & REQ_F_FIXED_FILE)
4257 req->close.fd = READ_ONCE(sqe->fd);
4258 if ((req->file && req->file->f_op == &io_uring_fops))
4261 req->close.put_file = NULL;
4265 static int io_close(struct io_kiocb *req, bool force_nonblock,
4266 struct io_comp_state *cs)
4268 struct io_close *close = &req->close;
4271 /* might be already done during nonblock submission */
4272 if (!close->put_file) {
4273 ret = __close_fd_get_file(close->fd, &close->put_file);
4275 return (ret == -ENOENT) ? -EBADF : ret;
4278 /* if the file has a flush method, be safe and punt to async */
4279 if (close->put_file->f_op->flush && force_nonblock) {
4280 /* not safe to cancel at this point */
4281 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
4282 /* was never set, but play safe */
4283 req->flags &= ~REQ_F_NOWAIT;
4284 /* avoid grabbing files - we don't need the files */
4285 req->flags |= REQ_F_NO_FILE_TABLE;
4289 /* No ->flush() or already async, safely close from here */
4290 ret = filp_close(close->put_file, req->work.identity->files);
4292 req_set_fail_links(req);
4293 fput(close->put_file);
4294 close->put_file = NULL;
4295 __io_req_complete(req, ret, 0, cs);
4299 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4301 struct io_ring_ctx *ctx = req->ctx;
4306 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4308 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4311 req->sync.off = READ_ONCE(sqe->off);
4312 req->sync.len = READ_ONCE(sqe->len);
4313 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4317 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
4321 /* sync_file_range always requires a blocking context */
4325 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4328 req_set_fail_links(req);
4329 io_req_complete(req, ret);
4333 #if defined(CONFIG_NET)
4334 static int io_setup_async_msg(struct io_kiocb *req,
4335 struct io_async_msghdr *kmsg)
4337 struct io_async_msghdr *async_msg = req->async_data;
4341 if (io_alloc_async_data(req)) {
4342 if (kmsg->iov != kmsg->fast_iov)
4346 async_msg = req->async_data;
4347 req->flags |= REQ_F_NEED_CLEANUP;
4348 memcpy(async_msg, kmsg, sizeof(*kmsg));
4352 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4353 struct io_async_msghdr *iomsg)
4355 iomsg->iov = iomsg->fast_iov;
4356 iomsg->msg.msg_name = &iomsg->addr;
4357 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4358 req->sr_msg.msg_flags, &iomsg->iov);
4361 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4363 struct io_async_msghdr *async_msg = req->async_data;
4364 struct io_sr_msg *sr = &req->sr_msg;
4367 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4370 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4371 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4372 sr->len = READ_ONCE(sqe->len);
4374 #ifdef CONFIG_COMPAT
4375 if (req->ctx->compat)
4376 sr->msg_flags |= MSG_CMSG_COMPAT;
4379 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4381 ret = io_sendmsg_copy_hdr(req, async_msg);
4383 req->flags |= REQ_F_NEED_CLEANUP;
4387 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4388 struct io_comp_state *cs)
4390 struct io_async_msghdr iomsg, *kmsg;
4391 struct socket *sock;
4395 sock = sock_from_file(req->file, &ret);
4396 if (unlikely(!sock))
4399 if (req->async_data) {
4400 kmsg = req->async_data;
4401 kmsg->msg.msg_name = &kmsg->addr;
4402 /* if iov is set, it's allocated already */
4404 kmsg->iov = kmsg->fast_iov;
4405 kmsg->msg.msg_iter.iov = kmsg->iov;
4407 ret = io_sendmsg_copy_hdr(req, &iomsg);
4413 flags = req->sr_msg.msg_flags;
4414 if (flags & MSG_DONTWAIT)
4415 req->flags |= REQ_F_NOWAIT;
4416 else if (force_nonblock)
4417 flags |= MSG_DONTWAIT;
4419 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4420 if (force_nonblock && ret == -EAGAIN)
4421 return io_setup_async_msg(req, kmsg);
4422 if (ret == -ERESTARTSYS)
4425 if (kmsg->iov != kmsg->fast_iov)
4427 req->flags &= ~REQ_F_NEED_CLEANUP;
4429 req_set_fail_links(req);
4430 __io_req_complete(req, ret, 0, cs);
4434 static int io_send(struct io_kiocb *req, bool force_nonblock,
4435 struct io_comp_state *cs)
4437 struct io_sr_msg *sr = &req->sr_msg;
4440 struct socket *sock;
4444 sock = sock_from_file(req->file, &ret);
4445 if (unlikely(!sock))
4448 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4452 msg.msg_name = NULL;
4453 msg.msg_control = NULL;
4454 msg.msg_controllen = 0;
4455 msg.msg_namelen = 0;
4457 flags = req->sr_msg.msg_flags;
4458 if (flags & MSG_DONTWAIT)
4459 req->flags |= REQ_F_NOWAIT;
4460 else if (force_nonblock)
4461 flags |= MSG_DONTWAIT;
4463 msg.msg_flags = flags;
4464 ret = sock_sendmsg(sock, &msg);
4465 if (force_nonblock && ret == -EAGAIN)
4467 if (ret == -ERESTARTSYS)
4471 req_set_fail_links(req);
4472 __io_req_complete(req, ret, 0, cs);
4476 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4477 struct io_async_msghdr *iomsg)
4479 struct io_sr_msg *sr = &req->sr_msg;
4480 struct iovec __user *uiov;
4484 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4485 &iomsg->uaddr, &uiov, &iov_len);
4489 if (req->flags & REQ_F_BUFFER_SELECT) {
4492 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4494 sr->len = iomsg->iov[0].iov_len;
4495 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4499 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4500 &iomsg->iov, &iomsg->msg.msg_iter,
4509 #ifdef CONFIG_COMPAT
4510 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4511 struct io_async_msghdr *iomsg)
4513 struct compat_msghdr __user *msg_compat;
4514 struct io_sr_msg *sr = &req->sr_msg;
4515 struct compat_iovec __user *uiov;
4520 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4521 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4526 uiov = compat_ptr(ptr);
4527 if (req->flags & REQ_F_BUFFER_SELECT) {
4528 compat_ssize_t clen;
4532 if (!access_ok(uiov, sizeof(*uiov)))
4534 if (__get_user(clen, &uiov->iov_len))
4539 iomsg->iov[0].iov_len = clen;
4542 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4543 UIO_FASTIOV, &iomsg->iov,
4544 &iomsg->msg.msg_iter, true);
4553 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4554 struct io_async_msghdr *iomsg)
4556 iomsg->msg.msg_name = &iomsg->addr;
4557 iomsg->iov = iomsg->fast_iov;
4559 #ifdef CONFIG_COMPAT
4560 if (req->ctx->compat)
4561 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4564 return __io_recvmsg_copy_hdr(req, iomsg);
4567 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4570 struct io_sr_msg *sr = &req->sr_msg;
4571 struct io_buffer *kbuf;
4573 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4578 req->flags |= REQ_F_BUFFER_SELECTED;
4582 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4584 return io_put_kbuf(req, req->sr_msg.kbuf);
4587 static int io_recvmsg_prep(struct io_kiocb *req,
4588 const struct io_uring_sqe *sqe)
4590 struct io_async_msghdr *async_msg = req->async_data;
4591 struct io_sr_msg *sr = &req->sr_msg;
4594 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4597 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4598 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4599 sr->len = READ_ONCE(sqe->len);
4600 sr->bgid = READ_ONCE(sqe->buf_group);
4602 #ifdef CONFIG_COMPAT
4603 if (req->ctx->compat)
4604 sr->msg_flags |= MSG_CMSG_COMPAT;
4607 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4609 ret = io_recvmsg_copy_hdr(req, async_msg);
4611 req->flags |= REQ_F_NEED_CLEANUP;
4615 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4616 struct io_comp_state *cs)
4618 struct io_async_msghdr iomsg, *kmsg;
4619 struct socket *sock;
4620 struct io_buffer *kbuf;
4622 int ret, cflags = 0;
4624 sock = sock_from_file(req->file, &ret);
4625 if (unlikely(!sock))
4628 if (req->async_data) {
4629 kmsg = req->async_data;
4630 kmsg->msg.msg_name = &kmsg->addr;
4631 /* if iov is set, it's allocated already */
4633 kmsg->iov = kmsg->fast_iov;
4634 kmsg->msg.msg_iter.iov = kmsg->iov;
4636 ret = io_recvmsg_copy_hdr(req, &iomsg);
4642 if (req->flags & REQ_F_BUFFER_SELECT) {
4643 kbuf = io_recv_buffer_select(req, !force_nonblock);
4645 return PTR_ERR(kbuf);
4646 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4647 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4648 1, req->sr_msg.len);
4651 flags = req->sr_msg.msg_flags;
4652 if (flags & MSG_DONTWAIT)
4653 req->flags |= REQ_F_NOWAIT;
4654 else if (force_nonblock)
4655 flags |= MSG_DONTWAIT;
4657 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4658 kmsg->uaddr, flags);
4659 if (force_nonblock && ret == -EAGAIN)
4660 return io_setup_async_msg(req, kmsg);
4661 if (ret == -ERESTARTSYS)
4664 if (req->flags & REQ_F_BUFFER_SELECTED)
4665 cflags = io_put_recv_kbuf(req);
4666 if (kmsg->iov != kmsg->fast_iov)
4668 req->flags &= ~REQ_F_NEED_CLEANUP;
4670 req_set_fail_links(req);
4671 __io_req_complete(req, ret, cflags, cs);
4675 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4676 struct io_comp_state *cs)
4678 struct io_buffer *kbuf;
4679 struct io_sr_msg *sr = &req->sr_msg;
4681 void __user *buf = sr->buf;
4682 struct socket *sock;
4685 int ret, cflags = 0;
4687 sock = sock_from_file(req->file, &ret);
4688 if (unlikely(!sock))
4691 if (req->flags & REQ_F_BUFFER_SELECT) {
4692 kbuf = io_recv_buffer_select(req, !force_nonblock);
4694 return PTR_ERR(kbuf);
4695 buf = u64_to_user_ptr(kbuf->addr);
4698 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4702 msg.msg_name = NULL;
4703 msg.msg_control = NULL;
4704 msg.msg_controllen = 0;
4705 msg.msg_namelen = 0;
4706 msg.msg_iocb = NULL;
4709 flags = req->sr_msg.msg_flags;
4710 if (flags & MSG_DONTWAIT)
4711 req->flags |= REQ_F_NOWAIT;
4712 else if (force_nonblock)
4713 flags |= MSG_DONTWAIT;
4715 ret = sock_recvmsg(sock, &msg, flags);
4716 if (force_nonblock && ret == -EAGAIN)
4718 if (ret == -ERESTARTSYS)
4721 if (req->flags & REQ_F_BUFFER_SELECTED)
4722 cflags = io_put_recv_kbuf(req);
4724 req_set_fail_links(req);
4725 __io_req_complete(req, ret, cflags, cs);
4729 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4731 struct io_accept *accept = &req->accept;
4733 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4735 if (sqe->ioprio || sqe->len || sqe->buf_index)
4738 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4739 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4740 accept->flags = READ_ONCE(sqe->accept_flags);
4741 accept->nofile = rlimit(RLIMIT_NOFILE);
4745 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4746 struct io_comp_state *cs)
4748 struct io_accept *accept = &req->accept;
4749 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4752 if (req->file->f_flags & O_NONBLOCK)
4753 req->flags |= REQ_F_NOWAIT;
4755 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4756 accept->addr_len, accept->flags,
4758 if (ret == -EAGAIN && force_nonblock)
4761 if (ret == -ERESTARTSYS)
4763 req_set_fail_links(req);
4765 __io_req_complete(req, ret, 0, cs);
4769 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4771 struct io_connect *conn = &req->connect;
4772 struct io_async_connect *io = req->async_data;
4774 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4776 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4779 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4780 conn->addr_len = READ_ONCE(sqe->addr2);
4785 return move_addr_to_kernel(conn->addr, conn->addr_len,
4789 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4790 struct io_comp_state *cs)
4792 struct io_async_connect __io, *io;
4793 unsigned file_flags;
4796 if (req->async_data) {
4797 io = req->async_data;
4799 ret = move_addr_to_kernel(req->connect.addr,
4800 req->connect.addr_len,
4807 file_flags = force_nonblock ? O_NONBLOCK : 0;
4809 ret = __sys_connect_file(req->file, &io->address,
4810 req->connect.addr_len, file_flags);
4811 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4812 if (req->async_data)
4814 if (io_alloc_async_data(req)) {
4818 io = req->async_data;
4819 memcpy(req->async_data, &__io, sizeof(__io));
4822 if (ret == -ERESTARTSYS)
4826 req_set_fail_links(req);
4827 __io_req_complete(req, ret, 0, cs);
4830 #else /* !CONFIG_NET */
4831 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4836 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4837 struct io_comp_state *cs)
4842 static int io_send(struct io_kiocb *req, bool force_nonblock,
4843 struct io_comp_state *cs)
4848 static int io_recvmsg_prep(struct io_kiocb *req,
4849 const struct io_uring_sqe *sqe)
4854 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4855 struct io_comp_state *cs)
4860 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4861 struct io_comp_state *cs)
4866 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4871 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4872 struct io_comp_state *cs)
4877 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4882 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4883 struct io_comp_state *cs)
4887 #endif /* CONFIG_NET */
4889 struct io_poll_table {
4890 struct poll_table_struct pt;
4891 struct io_kiocb *req;
4895 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4896 __poll_t mask, task_work_func_t func)
4901 /* for instances that support it check for an event match first: */
4902 if (mask && !(mask & poll->events))
4905 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4907 list_del_init(&poll->wait.entry);
4910 init_task_work(&req->task_work, func);
4911 percpu_ref_get(&req->ctx->refs);
4914 * If we using the signalfd wait_queue_head for this wakeup, then
4915 * it's not safe to use TWA_SIGNAL as we could be recursing on the
4916 * tsk->sighand->siglock on doing the wakeup. Should not be needed
4917 * either, as the normal wakeup will suffice.
4919 twa_signal_ok = (poll->head != &req->task->sighand->signalfd_wqh);
4922 * If this fails, then the task is exiting. When a task exits, the
4923 * work gets canceled, so just cancel this request as well instead
4924 * of executing it. We can't safely execute it anyway, as we may not
4925 * have the needed state needed for it anyway.
4927 ret = io_req_task_work_add(req, twa_signal_ok);
4928 if (unlikely(ret)) {
4929 struct task_struct *tsk;
4931 WRITE_ONCE(poll->canceled, true);
4932 tsk = io_wq_get_task(req->ctx->io_wq);
4933 task_work_add(tsk, &req->task_work, TWA_NONE);
4934 wake_up_process(tsk);
4939 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4940 __acquires(&req->ctx->completion_lock)
4942 struct io_ring_ctx *ctx = req->ctx;
4944 if (!req->result && !READ_ONCE(poll->canceled)) {
4945 struct poll_table_struct pt = { ._key = poll->events };
4947 req->result = vfs_poll(req->file, &pt) & poll->events;
4950 spin_lock_irq(&ctx->completion_lock);
4951 if (!req->result && !READ_ONCE(poll->canceled)) {
4952 add_wait_queue(poll->head, &poll->wait);
4959 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4961 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4962 if (req->opcode == IORING_OP_POLL_ADD)
4963 return req->async_data;
4964 return req->apoll->double_poll;
4967 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4969 if (req->opcode == IORING_OP_POLL_ADD)
4971 return &req->apoll->poll;
4974 static void io_poll_remove_double(struct io_kiocb *req)
4976 struct io_poll_iocb *poll = io_poll_get_double(req);
4978 lockdep_assert_held(&req->ctx->completion_lock);
4980 if (poll && poll->head) {
4981 struct wait_queue_head *head = poll->head;
4983 spin_lock(&head->lock);
4984 list_del_init(&poll->wait.entry);
4985 if (poll->wait.private)
4986 refcount_dec(&req->refs);
4988 spin_unlock(&head->lock);
4992 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4994 struct io_ring_ctx *ctx = req->ctx;
4996 io_poll_remove_double(req);
4997 req->poll.done = true;
4998 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4999 io_commit_cqring(ctx);
5002 static void io_poll_task_func(struct callback_head *cb)
5004 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5005 struct io_ring_ctx *ctx = req->ctx;
5006 struct io_kiocb *nxt;
5008 if (io_poll_rewait(req, &req->poll)) {
5009 spin_unlock_irq(&ctx->completion_lock);
5011 hash_del(&req->hash_node);
5012 io_poll_complete(req, req->result, 0);
5013 spin_unlock_irq(&ctx->completion_lock);
5015 nxt = io_put_req_find_next(req);
5016 io_cqring_ev_posted(ctx);
5018 __io_req_task_submit(nxt);
5021 percpu_ref_put(&ctx->refs);
5024 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5025 int sync, void *key)
5027 struct io_kiocb *req = wait->private;
5028 struct io_poll_iocb *poll = io_poll_get_single(req);
5029 __poll_t mask = key_to_poll(key);
5031 /* for instances that support it check for an event match first: */
5032 if (mask && !(mask & poll->events))
5035 list_del_init(&wait->entry);
5037 if (poll && poll->head) {
5040 spin_lock(&poll->head->lock);
5041 done = list_empty(&poll->wait.entry);
5043 list_del_init(&poll->wait.entry);
5044 /* make sure double remove sees this as being gone */
5045 wait->private = NULL;
5046 spin_unlock(&poll->head->lock);
5048 /* use wait func handler, so it matches the rq type */
5049 poll->wait.func(&poll->wait, mode, sync, key);
5052 refcount_dec(&req->refs);
5056 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5057 wait_queue_func_t wake_func)
5061 poll->canceled = false;
5062 poll->events = events;
5063 INIT_LIST_HEAD(&poll->wait.entry);
5064 init_waitqueue_func_entry(&poll->wait, wake_func);
5067 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5068 struct wait_queue_head *head,
5069 struct io_poll_iocb **poll_ptr)
5071 struct io_kiocb *req = pt->req;
5074 * If poll->head is already set, it's because the file being polled
5075 * uses multiple waitqueues for poll handling (eg one for read, one
5076 * for write). Setup a separate io_poll_iocb if this happens.
5078 if (unlikely(poll->head)) {
5079 struct io_poll_iocb *poll_one = poll;
5081 /* already have a 2nd entry, fail a third attempt */
5083 pt->error = -EINVAL;
5086 /* double add on the same waitqueue head, ignore */
5087 if (poll->head == head)
5089 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5091 pt->error = -ENOMEM;
5094 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5095 refcount_inc(&req->refs);
5096 poll->wait.private = req;
5103 if (poll->events & EPOLLEXCLUSIVE)
5104 add_wait_queue_exclusive(head, &poll->wait);
5106 add_wait_queue(head, &poll->wait);
5109 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5110 struct poll_table_struct *p)
5112 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5113 struct async_poll *apoll = pt->req->apoll;
5115 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5118 static void io_async_task_func(struct callback_head *cb)
5120 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5121 struct async_poll *apoll = req->apoll;
5122 struct io_ring_ctx *ctx = req->ctx;
5124 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5126 if (io_poll_rewait(req, &apoll->poll)) {
5127 spin_unlock_irq(&ctx->completion_lock);
5128 percpu_ref_put(&ctx->refs);
5132 /* If req is still hashed, it cannot have been canceled. Don't check. */
5133 if (hash_hashed(&req->hash_node))
5134 hash_del(&req->hash_node);
5136 io_poll_remove_double(req);
5137 spin_unlock_irq(&ctx->completion_lock);
5139 if (!READ_ONCE(apoll->poll.canceled))
5140 __io_req_task_submit(req);
5142 __io_req_task_cancel(req, -ECANCELED);
5144 percpu_ref_put(&ctx->refs);
5145 kfree(apoll->double_poll);
5149 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5152 struct io_kiocb *req = wait->private;
5153 struct io_poll_iocb *poll = &req->apoll->poll;
5155 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5158 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5161 static void io_poll_req_insert(struct io_kiocb *req)
5163 struct io_ring_ctx *ctx = req->ctx;
5164 struct hlist_head *list;
5166 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5167 hlist_add_head(&req->hash_node, list);
5170 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5171 struct io_poll_iocb *poll,
5172 struct io_poll_table *ipt, __poll_t mask,
5173 wait_queue_func_t wake_func)
5174 __acquires(&ctx->completion_lock)
5176 struct io_ring_ctx *ctx = req->ctx;
5177 bool cancel = false;
5179 INIT_HLIST_NODE(&req->hash_node);
5180 io_init_poll_iocb(poll, mask, wake_func);
5181 poll->file = req->file;
5182 poll->wait.private = req;
5184 ipt->pt._key = mask;
5186 ipt->error = -EINVAL;
5188 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5190 spin_lock_irq(&ctx->completion_lock);
5191 if (likely(poll->head)) {
5192 spin_lock(&poll->head->lock);
5193 if (unlikely(list_empty(&poll->wait.entry))) {
5199 if (mask || ipt->error)
5200 list_del_init(&poll->wait.entry);
5202 WRITE_ONCE(poll->canceled, true);
5203 else if (!poll->done) /* actually waiting for an event */
5204 io_poll_req_insert(req);
5205 spin_unlock(&poll->head->lock);
5211 static bool io_arm_poll_handler(struct io_kiocb *req)
5213 const struct io_op_def *def = &io_op_defs[req->opcode];
5214 struct io_ring_ctx *ctx = req->ctx;
5215 struct async_poll *apoll;
5216 struct io_poll_table ipt;
5220 if (!req->file || !file_can_poll(req->file))
5222 if (req->flags & REQ_F_POLLED)
5226 else if (def->pollout)
5230 /* if we can't nonblock try, then no point in arming a poll handler */
5231 if (!io_file_supports_async(req->file, rw))
5234 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5235 if (unlikely(!apoll))
5237 apoll->double_poll = NULL;
5239 req->flags |= REQ_F_POLLED;
5244 mask |= POLLIN | POLLRDNORM;
5246 mask |= POLLOUT | POLLWRNORM;
5248 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5249 if ((req->opcode == IORING_OP_RECVMSG) &&
5250 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5253 mask |= POLLERR | POLLPRI;
5255 ipt.pt._qproc = io_async_queue_proc;
5257 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5259 if (ret || ipt.error) {
5260 io_poll_remove_double(req);
5261 spin_unlock_irq(&ctx->completion_lock);
5262 kfree(apoll->double_poll);
5266 spin_unlock_irq(&ctx->completion_lock);
5267 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5268 apoll->poll.events);
5272 static bool __io_poll_remove_one(struct io_kiocb *req,
5273 struct io_poll_iocb *poll)
5275 bool do_complete = false;
5277 spin_lock(&poll->head->lock);
5278 WRITE_ONCE(poll->canceled, true);
5279 if (!list_empty(&poll->wait.entry)) {
5280 list_del_init(&poll->wait.entry);
5283 spin_unlock(&poll->head->lock);
5284 hash_del(&req->hash_node);
5288 static bool io_poll_remove_one(struct io_kiocb *req)
5292 io_poll_remove_double(req);
5294 if (req->opcode == IORING_OP_POLL_ADD) {
5295 do_complete = __io_poll_remove_one(req, &req->poll);
5297 struct async_poll *apoll = req->apoll;
5299 /* non-poll requests have submit ref still */
5300 do_complete = __io_poll_remove_one(req, &apoll->poll);
5303 kfree(apoll->double_poll);
5309 io_cqring_fill_event(req, -ECANCELED);
5310 io_commit_cqring(req->ctx);
5311 req_set_fail_links(req);
5312 io_put_req_deferred(req, 1);
5319 * Returns true if we found and killed one or more poll requests
5321 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5322 struct files_struct *files)
5324 struct hlist_node *tmp;
5325 struct io_kiocb *req;
5328 spin_lock_irq(&ctx->completion_lock);
5329 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5330 struct hlist_head *list;
5332 list = &ctx->cancel_hash[i];
5333 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5334 if (io_match_task(req, tsk, files))
5335 posted += io_poll_remove_one(req);
5338 spin_unlock_irq(&ctx->completion_lock);
5341 io_cqring_ev_posted(ctx);
5346 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5348 struct hlist_head *list;
5349 struct io_kiocb *req;
5351 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5352 hlist_for_each_entry(req, list, hash_node) {
5353 if (sqe_addr != req->user_data)
5355 if (io_poll_remove_one(req))
5363 static int io_poll_remove_prep(struct io_kiocb *req,
5364 const struct io_uring_sqe *sqe)
5366 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5368 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5372 req->poll.addr = READ_ONCE(sqe->addr);
5377 * Find a running poll command that matches one specified in sqe->addr,
5378 * and remove it if found.
5380 static int io_poll_remove(struct io_kiocb *req)
5382 struct io_ring_ctx *ctx = req->ctx;
5386 addr = req->poll.addr;
5387 spin_lock_irq(&ctx->completion_lock);
5388 ret = io_poll_cancel(ctx, addr);
5389 spin_unlock_irq(&ctx->completion_lock);
5392 req_set_fail_links(req);
5393 io_req_complete(req, ret);
5397 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5400 struct io_kiocb *req = wait->private;
5401 struct io_poll_iocb *poll = &req->poll;
5403 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5406 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5407 struct poll_table_struct *p)
5409 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5411 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5414 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5416 struct io_poll_iocb *poll = &req->poll;
5419 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5421 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5424 events = READ_ONCE(sqe->poll32_events);
5426 events = swahw32(events);
5428 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5429 (events & EPOLLEXCLUSIVE);
5433 static int io_poll_add(struct io_kiocb *req)
5435 struct io_poll_iocb *poll = &req->poll;
5436 struct io_ring_ctx *ctx = req->ctx;
5437 struct io_poll_table ipt;
5440 ipt.pt._qproc = io_poll_queue_proc;
5442 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5445 if (mask) { /* no async, we'd stolen it */
5447 io_poll_complete(req, mask, 0);
5449 spin_unlock_irq(&ctx->completion_lock);
5452 io_cqring_ev_posted(ctx);
5458 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5460 struct io_timeout_data *data = container_of(timer,
5461 struct io_timeout_data, timer);
5462 struct io_kiocb *req = data->req;
5463 struct io_ring_ctx *ctx = req->ctx;
5464 unsigned long flags;
5466 spin_lock_irqsave(&ctx->completion_lock, flags);
5467 list_del_init(&req->timeout.list);
5468 atomic_set(&req->ctx->cq_timeouts,
5469 atomic_read(&req->ctx->cq_timeouts) + 1);
5471 io_cqring_fill_event(req, -ETIME);
5472 io_commit_cqring(ctx);
5473 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5475 io_cqring_ev_posted(ctx);
5476 req_set_fail_links(req);
5478 return HRTIMER_NORESTART;
5481 static int __io_timeout_cancel(struct io_kiocb *req)
5483 struct io_timeout_data *io = req->async_data;
5486 ret = hrtimer_try_to_cancel(&io->timer);
5489 list_del_init(&req->timeout.list);
5491 req_set_fail_links(req);
5492 io_cqring_fill_event(req, -ECANCELED);
5493 io_put_req_deferred(req, 1);
5497 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5499 struct io_kiocb *req;
5502 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5503 if (user_data == req->user_data) {
5512 return __io_timeout_cancel(req);
5515 static int io_timeout_remove_prep(struct io_kiocb *req,
5516 const struct io_uring_sqe *sqe)
5518 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5520 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5522 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->timeout_flags)
5525 req->timeout_rem.addr = READ_ONCE(sqe->addr);
5530 * Remove or update an existing timeout command
5532 static int io_timeout_remove(struct io_kiocb *req)
5534 struct io_ring_ctx *ctx = req->ctx;
5537 spin_lock_irq(&ctx->completion_lock);
5538 ret = io_timeout_cancel(ctx, req->timeout_rem.addr);
5540 io_cqring_fill_event(req, ret);
5541 io_commit_cqring(ctx);
5542 spin_unlock_irq(&ctx->completion_lock);
5543 io_cqring_ev_posted(ctx);
5545 req_set_fail_links(req);
5550 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5551 bool is_timeout_link)
5553 struct io_timeout_data *data;
5555 u32 off = READ_ONCE(sqe->off);
5557 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5559 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5561 if (off && is_timeout_link)
5563 flags = READ_ONCE(sqe->timeout_flags);
5564 if (flags & ~IORING_TIMEOUT_ABS)
5567 req->timeout.off = off;
5569 if (!req->async_data && io_alloc_async_data(req))
5572 data = req->async_data;
5575 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5578 if (flags & IORING_TIMEOUT_ABS)
5579 data->mode = HRTIMER_MODE_ABS;
5581 data->mode = HRTIMER_MODE_REL;
5583 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5587 static int io_timeout(struct io_kiocb *req)
5589 struct io_ring_ctx *ctx = req->ctx;
5590 struct io_timeout_data *data = req->async_data;
5591 struct list_head *entry;
5592 u32 tail, off = req->timeout.off;
5594 spin_lock_irq(&ctx->completion_lock);
5597 * sqe->off holds how many events that need to occur for this
5598 * timeout event to be satisfied. If it isn't set, then this is
5599 * a pure timeout request, sequence isn't used.
5601 if (io_is_timeout_noseq(req)) {
5602 entry = ctx->timeout_list.prev;
5606 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5607 req->timeout.target_seq = tail + off;
5609 /* Update the last seq here in case io_flush_timeouts() hasn't.
5610 * This is safe because ->completion_lock is held, and submissions
5611 * and completions are never mixed in the same ->completion_lock section.
5613 ctx->cq_last_tm_flush = tail;
5616 * Insertion sort, ensuring the first entry in the list is always
5617 * the one we need first.
5619 list_for_each_prev(entry, &ctx->timeout_list) {
5620 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5623 if (io_is_timeout_noseq(nxt))
5625 /* nxt.seq is behind @tail, otherwise would've been completed */
5626 if (off >= nxt->timeout.target_seq - tail)
5630 list_add(&req->timeout.list, entry);
5631 data->timer.function = io_timeout_fn;
5632 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5633 spin_unlock_irq(&ctx->completion_lock);
5637 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5639 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5641 return req->user_data == (unsigned long) data;
5644 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5646 enum io_wq_cancel cancel_ret;
5649 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5650 switch (cancel_ret) {
5651 case IO_WQ_CANCEL_OK:
5654 case IO_WQ_CANCEL_RUNNING:
5657 case IO_WQ_CANCEL_NOTFOUND:
5665 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5666 struct io_kiocb *req, __u64 sqe_addr,
5669 unsigned long flags;
5672 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5673 if (ret != -ENOENT) {
5674 spin_lock_irqsave(&ctx->completion_lock, flags);
5678 spin_lock_irqsave(&ctx->completion_lock, flags);
5679 ret = io_timeout_cancel(ctx, sqe_addr);
5682 ret = io_poll_cancel(ctx, sqe_addr);
5686 io_cqring_fill_event(req, ret);
5687 io_commit_cqring(ctx);
5688 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5689 io_cqring_ev_posted(ctx);
5692 req_set_fail_links(req);
5696 static int io_async_cancel_prep(struct io_kiocb *req,
5697 const struct io_uring_sqe *sqe)
5699 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5701 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5703 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5706 req->cancel.addr = READ_ONCE(sqe->addr);
5710 static int io_async_cancel(struct io_kiocb *req)
5712 struct io_ring_ctx *ctx = req->ctx;
5714 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5718 static int io_files_update_prep(struct io_kiocb *req,
5719 const struct io_uring_sqe *sqe)
5721 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5723 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5725 if (sqe->ioprio || sqe->rw_flags)
5728 req->files_update.offset = READ_ONCE(sqe->off);
5729 req->files_update.nr_args = READ_ONCE(sqe->len);
5730 if (!req->files_update.nr_args)
5732 req->files_update.arg = READ_ONCE(sqe->addr);
5736 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5737 struct io_comp_state *cs)
5739 struct io_ring_ctx *ctx = req->ctx;
5740 struct io_uring_files_update up;
5746 up.offset = req->files_update.offset;
5747 up.fds = req->files_update.arg;
5749 mutex_lock(&ctx->uring_lock);
5750 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5751 mutex_unlock(&ctx->uring_lock);
5754 req_set_fail_links(req);
5755 __io_req_complete(req, ret, 0, cs);
5759 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5761 switch (req->opcode) {
5764 case IORING_OP_READV:
5765 case IORING_OP_READ_FIXED:
5766 case IORING_OP_READ:
5767 return io_read_prep(req, sqe);
5768 case IORING_OP_WRITEV:
5769 case IORING_OP_WRITE_FIXED:
5770 case IORING_OP_WRITE:
5771 return io_write_prep(req, sqe);
5772 case IORING_OP_POLL_ADD:
5773 return io_poll_add_prep(req, sqe);
5774 case IORING_OP_POLL_REMOVE:
5775 return io_poll_remove_prep(req, sqe);
5776 case IORING_OP_FSYNC:
5777 return io_prep_fsync(req, sqe);
5778 case IORING_OP_SYNC_FILE_RANGE:
5779 return io_prep_sfr(req, sqe);
5780 case IORING_OP_SENDMSG:
5781 case IORING_OP_SEND:
5782 return io_sendmsg_prep(req, sqe);
5783 case IORING_OP_RECVMSG:
5784 case IORING_OP_RECV:
5785 return io_recvmsg_prep(req, sqe);
5786 case IORING_OP_CONNECT:
5787 return io_connect_prep(req, sqe);
5788 case IORING_OP_TIMEOUT:
5789 return io_timeout_prep(req, sqe, false);
5790 case IORING_OP_TIMEOUT_REMOVE:
5791 return io_timeout_remove_prep(req, sqe);
5792 case IORING_OP_ASYNC_CANCEL:
5793 return io_async_cancel_prep(req, sqe);
5794 case IORING_OP_LINK_TIMEOUT:
5795 return io_timeout_prep(req, sqe, true);
5796 case IORING_OP_ACCEPT:
5797 return io_accept_prep(req, sqe);
5798 case IORING_OP_FALLOCATE:
5799 return io_fallocate_prep(req, sqe);
5800 case IORING_OP_OPENAT:
5801 return io_openat_prep(req, sqe);
5802 case IORING_OP_CLOSE:
5803 return io_close_prep(req, sqe);
5804 case IORING_OP_FILES_UPDATE:
5805 return io_files_update_prep(req, sqe);
5806 case IORING_OP_STATX:
5807 return io_statx_prep(req, sqe);
5808 case IORING_OP_FADVISE:
5809 return io_fadvise_prep(req, sqe);
5810 case IORING_OP_MADVISE:
5811 return io_madvise_prep(req, sqe);
5812 case IORING_OP_OPENAT2:
5813 return io_openat2_prep(req, sqe);
5814 case IORING_OP_EPOLL_CTL:
5815 return io_epoll_ctl_prep(req, sqe);
5816 case IORING_OP_SPLICE:
5817 return io_splice_prep(req, sqe);
5818 case IORING_OP_PROVIDE_BUFFERS:
5819 return io_provide_buffers_prep(req, sqe);
5820 case IORING_OP_REMOVE_BUFFERS:
5821 return io_remove_buffers_prep(req, sqe);
5823 return io_tee_prep(req, sqe);
5826 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5831 static int io_req_defer_prep(struct io_kiocb *req,
5832 const struct io_uring_sqe *sqe)
5836 if (io_alloc_async_data(req))
5838 return io_req_prep(req, sqe);
5841 static u32 io_get_sequence(struct io_kiocb *req)
5843 struct io_kiocb *pos;
5844 struct io_ring_ctx *ctx = req->ctx;
5845 u32 total_submitted, nr_reqs = 1;
5847 if (req->flags & REQ_F_LINK_HEAD)
5848 list_for_each_entry(pos, &req->link_list, link_list)
5851 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5852 return total_submitted - nr_reqs;
5855 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5857 struct io_ring_ctx *ctx = req->ctx;
5858 struct io_defer_entry *de;
5862 /* Still need defer if there is pending req in defer list. */
5863 if (likely(list_empty_careful(&ctx->defer_list) &&
5864 !(req->flags & REQ_F_IO_DRAIN)))
5867 seq = io_get_sequence(req);
5868 /* Still a chance to pass the sequence check */
5869 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5872 if (!req->async_data) {
5873 ret = io_req_defer_prep(req, sqe);
5877 io_prep_async_link(req);
5878 de = kmalloc(sizeof(*de), GFP_KERNEL);
5882 spin_lock_irq(&ctx->completion_lock);
5883 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5884 spin_unlock_irq(&ctx->completion_lock);
5886 io_queue_async_work(req);
5887 return -EIOCBQUEUED;
5890 trace_io_uring_defer(ctx, req, req->user_data);
5893 list_add_tail(&de->list, &ctx->defer_list);
5894 spin_unlock_irq(&ctx->completion_lock);
5895 return -EIOCBQUEUED;
5898 static void io_req_drop_files(struct io_kiocb *req)
5900 struct io_ring_ctx *ctx = req->ctx;
5901 struct io_uring_task *tctx = req->task->io_uring;
5902 unsigned long flags;
5904 if (req->work.flags & IO_WQ_WORK_FILES) {
5905 put_files_struct(req->work.identity->files);
5906 put_nsproxy(req->work.identity->nsproxy);
5908 spin_lock_irqsave(&ctx->inflight_lock, flags);
5909 list_del(&req->inflight_entry);
5910 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
5911 req->flags &= ~REQ_F_INFLIGHT;
5912 req->work.flags &= ~IO_WQ_WORK_FILES;
5913 if (atomic_read(&tctx->in_idle))
5914 wake_up(&tctx->wait);
5917 static void __io_clean_op(struct io_kiocb *req)
5919 if (req->flags & REQ_F_BUFFER_SELECTED) {
5920 switch (req->opcode) {
5921 case IORING_OP_READV:
5922 case IORING_OP_READ_FIXED:
5923 case IORING_OP_READ:
5924 kfree((void *)(unsigned long)req->rw.addr);
5926 case IORING_OP_RECVMSG:
5927 case IORING_OP_RECV:
5928 kfree(req->sr_msg.kbuf);
5931 req->flags &= ~REQ_F_BUFFER_SELECTED;
5934 if (req->flags & REQ_F_NEED_CLEANUP) {
5935 switch (req->opcode) {
5936 case IORING_OP_READV:
5937 case IORING_OP_READ_FIXED:
5938 case IORING_OP_READ:
5939 case IORING_OP_WRITEV:
5940 case IORING_OP_WRITE_FIXED:
5941 case IORING_OP_WRITE: {
5942 struct io_async_rw *io = req->async_data;
5944 kfree(io->free_iovec);
5947 case IORING_OP_RECVMSG:
5948 case IORING_OP_SENDMSG: {
5949 struct io_async_msghdr *io = req->async_data;
5950 if (io->iov != io->fast_iov)
5954 case IORING_OP_SPLICE:
5956 io_put_file(req, req->splice.file_in,
5957 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5959 case IORING_OP_OPENAT:
5960 case IORING_OP_OPENAT2:
5961 if (req->open.filename)
5962 putname(req->open.filename);
5965 req->flags &= ~REQ_F_NEED_CLEANUP;
5969 static int io_issue_sqe(struct io_kiocb *req, bool force_nonblock,
5970 struct io_comp_state *cs)
5972 struct io_ring_ctx *ctx = req->ctx;
5975 switch (req->opcode) {
5977 ret = io_nop(req, cs);
5979 case IORING_OP_READV:
5980 case IORING_OP_READ_FIXED:
5981 case IORING_OP_READ:
5982 ret = io_read(req, force_nonblock, cs);
5984 case IORING_OP_WRITEV:
5985 case IORING_OP_WRITE_FIXED:
5986 case IORING_OP_WRITE:
5987 ret = io_write(req, force_nonblock, cs);
5989 case IORING_OP_FSYNC:
5990 ret = io_fsync(req, force_nonblock);
5992 case IORING_OP_POLL_ADD:
5993 ret = io_poll_add(req);
5995 case IORING_OP_POLL_REMOVE:
5996 ret = io_poll_remove(req);
5998 case IORING_OP_SYNC_FILE_RANGE:
5999 ret = io_sync_file_range(req, force_nonblock);
6001 case IORING_OP_SENDMSG:
6002 ret = io_sendmsg(req, force_nonblock, cs);
6004 case IORING_OP_SEND:
6005 ret = io_send(req, force_nonblock, cs);
6007 case IORING_OP_RECVMSG:
6008 ret = io_recvmsg(req, force_nonblock, cs);
6010 case IORING_OP_RECV:
6011 ret = io_recv(req, force_nonblock, cs);
6013 case IORING_OP_TIMEOUT:
6014 ret = io_timeout(req);
6016 case IORING_OP_TIMEOUT_REMOVE:
6017 ret = io_timeout_remove(req);
6019 case IORING_OP_ACCEPT:
6020 ret = io_accept(req, force_nonblock, cs);
6022 case IORING_OP_CONNECT:
6023 ret = io_connect(req, force_nonblock, cs);
6025 case IORING_OP_ASYNC_CANCEL:
6026 ret = io_async_cancel(req);
6028 case IORING_OP_FALLOCATE:
6029 ret = io_fallocate(req, force_nonblock);
6031 case IORING_OP_OPENAT:
6032 ret = io_openat(req, force_nonblock);
6034 case IORING_OP_CLOSE:
6035 ret = io_close(req, force_nonblock, cs);
6037 case IORING_OP_FILES_UPDATE:
6038 ret = io_files_update(req, force_nonblock, cs);
6040 case IORING_OP_STATX:
6041 ret = io_statx(req, force_nonblock);
6043 case IORING_OP_FADVISE:
6044 ret = io_fadvise(req, force_nonblock);
6046 case IORING_OP_MADVISE:
6047 ret = io_madvise(req, force_nonblock);
6049 case IORING_OP_OPENAT2:
6050 ret = io_openat2(req, force_nonblock);
6052 case IORING_OP_EPOLL_CTL:
6053 ret = io_epoll_ctl(req, force_nonblock, cs);
6055 case IORING_OP_SPLICE:
6056 ret = io_splice(req, force_nonblock);
6058 case IORING_OP_PROVIDE_BUFFERS:
6059 ret = io_provide_buffers(req, force_nonblock, cs);
6061 case IORING_OP_REMOVE_BUFFERS:
6062 ret = io_remove_buffers(req, force_nonblock, cs);
6065 ret = io_tee(req, force_nonblock);
6075 /* If the op doesn't have a file, we're not polling for it */
6076 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6077 const bool in_async = io_wq_current_is_worker();
6079 /* workqueue context doesn't hold uring_lock, grab it now */
6081 mutex_lock(&ctx->uring_lock);
6083 io_iopoll_req_issued(req);
6086 mutex_unlock(&ctx->uring_lock);
6092 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
6094 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6095 struct io_kiocb *timeout;
6098 timeout = io_prep_linked_timeout(req);
6100 io_queue_linked_timeout(timeout);
6102 /* if NO_CANCEL is set, we must still run the work */
6103 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
6104 IO_WQ_WORK_CANCEL) {
6110 ret = io_issue_sqe(req, false, NULL);
6112 * We can get EAGAIN for polled IO even though we're
6113 * forcing a sync submission from here, since we can't
6114 * wait for request slots on the block side.
6123 struct io_ring_ctx *lock_ctx = NULL;
6125 if (req->ctx->flags & IORING_SETUP_IOPOLL)
6126 lock_ctx = req->ctx;
6129 * io_iopoll_complete() does not hold completion_lock to
6130 * complete polled io, so here for polled io, we can not call
6131 * io_req_complete() directly, otherwise there maybe concurrent
6132 * access to cqring, defer_list, etc, which is not safe. Given
6133 * that io_iopoll_complete() is always called under uring_lock,
6134 * so here for polled io, we also get uring_lock to complete
6138 mutex_lock(&lock_ctx->uring_lock);
6140 req_set_fail_links(req);
6141 io_req_complete(req, ret);
6144 mutex_unlock(&lock_ctx->uring_lock);
6147 return io_steal_work(req);
6150 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6153 struct fixed_file_table *table;
6155 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6156 return table->files[index & IORING_FILE_TABLE_MASK];
6159 static struct file *io_file_get(struct io_submit_state *state,
6160 struct io_kiocb *req, int fd, bool fixed)
6162 struct io_ring_ctx *ctx = req->ctx;
6166 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6168 fd = array_index_nospec(fd, ctx->nr_user_files);
6169 file = io_file_from_index(ctx, fd);
6171 req->fixed_file_refs = &ctx->file_data->node->refs;
6172 percpu_ref_get(req->fixed_file_refs);
6175 trace_io_uring_file_get(ctx, fd);
6176 file = __io_file_get(state, fd);
6179 if (file && file->f_op == &io_uring_fops &&
6180 !(req->flags & REQ_F_INFLIGHT)) {
6181 io_req_init_async(req);
6182 req->flags |= REQ_F_INFLIGHT;
6184 spin_lock_irq(&ctx->inflight_lock);
6185 list_add(&req->inflight_entry, &ctx->inflight_list);
6186 spin_unlock_irq(&ctx->inflight_lock);
6192 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
6197 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
6198 if (unlikely(!fixed && io_async_submit(req->ctx)))
6201 req->file = io_file_get(state, req, fd, fixed);
6202 if (req->file || io_op_defs[req->opcode].needs_file_no_error)
6207 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6209 struct io_timeout_data *data = container_of(timer,
6210 struct io_timeout_data, timer);
6211 struct io_kiocb *req = data->req;
6212 struct io_ring_ctx *ctx = req->ctx;
6213 struct io_kiocb *prev = NULL;
6214 unsigned long flags;
6216 spin_lock_irqsave(&ctx->completion_lock, flags);
6219 * We don't expect the list to be empty, that will only happen if we
6220 * race with the completion of the linked work.
6222 if (!list_empty(&req->link_list)) {
6223 prev = list_entry(req->link_list.prev, struct io_kiocb,
6225 if (refcount_inc_not_zero(&prev->refs))
6226 list_del_init(&req->link_list);
6231 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6234 req_set_fail_links(prev);
6235 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6238 io_req_complete(req, -ETIME);
6240 return HRTIMER_NORESTART;
6243 static void __io_queue_linked_timeout(struct io_kiocb *req)
6246 * If the list is now empty, then our linked request finished before
6247 * we got a chance to setup the timer
6249 if (!list_empty(&req->link_list)) {
6250 struct io_timeout_data *data = req->async_data;
6252 data->timer.function = io_link_timeout_fn;
6253 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6258 static void io_queue_linked_timeout(struct io_kiocb *req)
6260 struct io_ring_ctx *ctx = req->ctx;
6262 spin_lock_irq(&ctx->completion_lock);
6263 __io_queue_linked_timeout(req);
6264 spin_unlock_irq(&ctx->completion_lock);
6266 /* drop submission reference */
6270 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6272 struct io_kiocb *nxt;
6274 if (!(req->flags & REQ_F_LINK_HEAD))
6276 if (req->flags & REQ_F_LINK_TIMEOUT)
6279 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
6281 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
6284 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6285 req->flags |= REQ_F_LINK_TIMEOUT;
6289 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs)
6291 struct io_kiocb *linked_timeout;
6292 const struct cred *old_creds = NULL;
6296 linked_timeout = io_prep_linked_timeout(req);
6298 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6299 (req->work.flags & IO_WQ_WORK_CREDS) &&
6300 req->work.identity->creds != current_cred()) {
6302 revert_creds(old_creds);
6303 if (old_creds == req->work.identity->creds)
6304 old_creds = NULL; /* restored original creds */
6306 old_creds = override_creds(req->work.identity->creds);
6309 ret = io_issue_sqe(req, true, cs);
6312 * We async punt it if the file wasn't marked NOWAIT, or if the file
6313 * doesn't support non-blocking read/write attempts
6315 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6316 if (!io_arm_poll_handler(req)) {
6318 * Queued up for async execution, worker will release
6319 * submit reference when the iocb is actually submitted.
6321 io_queue_async_work(req);
6325 io_queue_linked_timeout(linked_timeout);
6326 } else if (likely(!ret)) {
6327 /* drop submission reference */
6328 req = io_put_req_find_next(req);
6330 io_queue_linked_timeout(linked_timeout);
6333 if (!(req->flags & REQ_F_FORCE_ASYNC))
6335 io_queue_async_work(req);
6338 /* un-prep timeout, so it'll be killed as any other linked */
6339 req->flags &= ~REQ_F_LINK_TIMEOUT;
6340 req_set_fail_links(req);
6342 io_req_complete(req, ret);
6346 revert_creds(old_creds);
6349 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6350 struct io_comp_state *cs)
6354 ret = io_req_defer(req, sqe);
6356 if (ret != -EIOCBQUEUED) {
6358 req_set_fail_links(req);
6360 io_req_complete(req, ret);
6362 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6363 if (!req->async_data) {
6364 ret = io_req_defer_prep(req, sqe);
6368 io_queue_async_work(req);
6371 ret = io_req_prep(req, sqe);
6375 __io_queue_sqe(req, cs);
6379 static inline void io_queue_link_head(struct io_kiocb *req,
6380 struct io_comp_state *cs)
6382 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6384 io_req_complete(req, -ECANCELED);
6386 io_queue_sqe(req, NULL, cs);
6389 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6390 struct io_kiocb **link, struct io_comp_state *cs)
6392 struct io_ring_ctx *ctx = req->ctx;
6396 * If we already have a head request, queue this one for async
6397 * submittal once the head completes. If we don't have a head but
6398 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6399 * submitted sync once the chain is complete. If none of those
6400 * conditions are true (normal request), then just queue it.
6403 struct io_kiocb *head = *link;
6406 * Taking sequential execution of a link, draining both sides
6407 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6408 * requests in the link. So, it drains the head and the
6409 * next after the link request. The last one is done via
6410 * drain_next flag to persist the effect across calls.
6412 if (req->flags & REQ_F_IO_DRAIN) {
6413 head->flags |= REQ_F_IO_DRAIN;
6414 ctx->drain_next = 1;
6416 ret = io_req_defer_prep(req, sqe);
6417 if (unlikely(ret)) {
6418 /* fail even hard links since we don't submit */
6419 head->flags |= REQ_F_FAIL_LINK;
6422 trace_io_uring_link(ctx, req, head);
6423 list_add_tail(&req->link_list, &head->link_list);
6425 /* last request of a link, enqueue the link */
6426 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6427 io_queue_link_head(head, cs);
6431 if (unlikely(ctx->drain_next)) {
6432 req->flags |= REQ_F_IO_DRAIN;
6433 ctx->drain_next = 0;
6435 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6436 req->flags |= REQ_F_LINK_HEAD;
6437 INIT_LIST_HEAD(&req->link_list);
6439 ret = io_req_defer_prep(req, sqe);
6441 req->flags |= REQ_F_FAIL_LINK;
6444 io_queue_sqe(req, sqe, cs);
6452 * Batched submission is done, ensure local IO is flushed out.
6454 static void io_submit_state_end(struct io_submit_state *state)
6456 if (!list_empty(&state->comp.list))
6457 io_submit_flush_completions(&state->comp);
6458 blk_finish_plug(&state->plug);
6459 io_state_file_put(state);
6460 if (state->free_reqs)
6461 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6465 * Start submission side cache.
6467 static void io_submit_state_start(struct io_submit_state *state,
6468 struct io_ring_ctx *ctx, unsigned int max_ios)
6470 blk_start_plug(&state->plug);
6472 INIT_LIST_HEAD(&state->comp.list);
6473 state->comp.ctx = ctx;
6474 state->free_reqs = 0;
6476 state->ios_left = max_ios;
6479 static void io_commit_sqring(struct io_ring_ctx *ctx)
6481 struct io_rings *rings = ctx->rings;
6484 * Ensure any loads from the SQEs are done at this point,
6485 * since once we write the new head, the application could
6486 * write new data to them.
6488 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6492 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6493 * that is mapped by userspace. This means that care needs to be taken to
6494 * ensure that reads are stable, as we cannot rely on userspace always
6495 * being a good citizen. If members of the sqe are validated and then later
6496 * used, it's important that those reads are done through READ_ONCE() to
6497 * prevent a re-load down the line.
6499 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6501 u32 *sq_array = ctx->sq_array;
6505 * The cached sq head (or cq tail) serves two purposes:
6507 * 1) allows us to batch the cost of updating the user visible
6509 * 2) allows the kernel side to track the head on its own, even
6510 * though the application is the one updating it.
6512 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6513 if (likely(head < ctx->sq_entries))
6514 return &ctx->sq_sqes[head];
6516 /* drop invalid entries */
6517 ctx->cached_sq_dropped++;
6518 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6522 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6524 ctx->cached_sq_head++;
6528 * Check SQE restrictions (opcode and flags).
6530 * Returns 'true' if SQE is allowed, 'false' otherwise.
6532 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6533 struct io_kiocb *req,
6534 unsigned int sqe_flags)
6536 if (!ctx->restricted)
6539 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6542 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6543 ctx->restrictions.sqe_flags_required)
6546 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6547 ctx->restrictions.sqe_flags_required))
6553 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6554 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6555 IOSQE_BUFFER_SELECT)
6557 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6558 const struct io_uring_sqe *sqe,
6559 struct io_submit_state *state)
6561 unsigned int sqe_flags;
6564 req->opcode = READ_ONCE(sqe->opcode);
6565 req->user_data = READ_ONCE(sqe->user_data);
6566 req->async_data = NULL;
6570 /* one is dropped after submission, the other at completion */
6571 refcount_set(&req->refs, 2);
6572 req->task = current;
6575 if (unlikely(req->opcode >= IORING_OP_LAST))
6578 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6581 sqe_flags = READ_ONCE(sqe->flags);
6582 /* enforce forwards compatibility on users */
6583 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6586 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6589 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6590 !io_op_defs[req->opcode].buffer_select)
6593 id = READ_ONCE(sqe->personality);
6595 struct io_identity *iod;
6597 iod = idr_find(&ctx->personality_idr, id);
6600 refcount_inc(&iod->count);
6602 __io_req_init_async(req);
6603 get_cred(iod->creds);
6604 req->work.identity = iod;
6605 req->work.flags |= IO_WQ_WORK_CREDS;
6608 /* same numerical values with corresponding REQ_F_*, safe to copy */
6609 req->flags |= sqe_flags;
6611 if (!io_op_defs[req->opcode].needs_file)
6614 ret = io_req_set_file(state, req, READ_ONCE(sqe->fd));
6619 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6621 struct io_submit_state state;
6622 struct io_kiocb *link = NULL;
6623 int i, submitted = 0;
6625 /* if we have a backlog and couldn't flush it all, return BUSY */
6626 if (test_bit(0, &ctx->sq_check_overflow)) {
6627 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6631 /* make sure SQ entry isn't read before tail */
6632 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6634 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6637 percpu_counter_add(¤t->io_uring->inflight, nr);
6638 refcount_add(nr, ¤t->usage);
6640 io_submit_state_start(&state, ctx, nr);
6642 for (i = 0; i < nr; i++) {
6643 const struct io_uring_sqe *sqe;
6644 struct io_kiocb *req;
6647 sqe = io_get_sqe(ctx);
6648 if (unlikely(!sqe)) {
6649 io_consume_sqe(ctx);
6652 req = io_alloc_req(ctx, &state);
6653 if (unlikely(!req)) {
6655 submitted = -EAGAIN;
6658 io_consume_sqe(ctx);
6659 /* will complete beyond this point, count as submitted */
6662 err = io_init_req(ctx, req, sqe, &state);
6663 if (unlikely(err)) {
6666 io_req_complete(req, err);
6670 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6671 true, io_async_submit(ctx));
6672 err = io_submit_sqe(req, sqe, &link, &state.comp);
6677 if (unlikely(submitted != nr)) {
6678 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6679 struct io_uring_task *tctx = current->io_uring;
6680 int unused = nr - ref_used;
6682 percpu_ref_put_many(&ctx->refs, unused);
6683 percpu_counter_sub(&tctx->inflight, unused);
6684 put_task_struct_many(current, unused);
6687 io_queue_link_head(link, &state.comp);
6688 io_submit_state_end(&state);
6690 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6691 io_commit_sqring(ctx);
6696 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6698 /* Tell userspace we may need a wakeup call */
6699 spin_lock_irq(&ctx->completion_lock);
6700 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6701 spin_unlock_irq(&ctx->completion_lock);
6704 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6706 spin_lock_irq(&ctx->completion_lock);
6707 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6708 spin_unlock_irq(&ctx->completion_lock);
6711 static int io_sq_wake_function(struct wait_queue_entry *wqe, unsigned mode,
6712 int sync, void *key)
6714 struct io_ring_ctx *ctx = container_of(wqe, struct io_ring_ctx, sqo_wait_entry);
6717 ret = autoremove_wake_function(wqe, mode, sync, key);
6719 unsigned long flags;
6721 spin_lock_irqsave(&ctx->completion_lock, flags);
6722 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6723 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6734 static enum sq_ret __io_sq_thread(struct io_ring_ctx *ctx,
6735 unsigned long start_jiffies, bool cap_entries)
6737 unsigned long timeout = start_jiffies + ctx->sq_thread_idle;
6738 struct io_sq_data *sqd = ctx->sq_data;
6739 unsigned int to_submit;
6743 if (!list_empty(&ctx->iopoll_list)) {
6744 unsigned nr_events = 0;
6746 mutex_lock(&ctx->uring_lock);
6747 if (!list_empty(&ctx->iopoll_list) && !need_resched())
6748 io_do_iopoll(ctx, &nr_events, 0);
6749 mutex_unlock(&ctx->uring_lock);
6752 to_submit = io_sqring_entries(ctx);
6755 * If submit got -EBUSY, flag us as needing the application
6756 * to enter the kernel to reap and flush events.
6758 if (!to_submit || ret == -EBUSY || need_resched()) {
6760 * Drop cur_mm before scheduling, we can't hold it for
6761 * long periods (or over schedule()). Do this before
6762 * adding ourselves to the waitqueue, as the unuse/drop
6765 io_sq_thread_drop_mm();
6768 * We're polling. If we're within the defined idle
6769 * period, then let us spin without work before going
6770 * to sleep. The exception is if we got EBUSY doing
6771 * more IO, we should wait for the application to
6772 * reap events and wake us up.
6774 if (!list_empty(&ctx->iopoll_list) || need_resched() ||
6775 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6776 !percpu_ref_is_dying(&ctx->refs)))
6779 prepare_to_wait(&sqd->wait, &ctx->sqo_wait_entry,
6780 TASK_INTERRUPTIBLE);
6783 * While doing polled IO, before going to sleep, we need
6784 * to check if there are new reqs added to iopoll_list,
6785 * it is because reqs may have been punted to io worker
6786 * and will be added to iopoll_list later, hence check
6787 * the iopoll_list again.
6789 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6790 !list_empty_careful(&ctx->iopoll_list)) {
6791 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6795 to_submit = io_sqring_entries(ctx);
6796 if (!to_submit || ret == -EBUSY)
6800 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6801 io_ring_clear_wakeup_flag(ctx);
6803 /* if we're handling multiple rings, cap submit size for fairness */
6804 if (cap_entries && to_submit > 8)
6807 mutex_lock(&ctx->uring_lock);
6808 if (likely(!percpu_ref_is_dying(&ctx->refs) && !ctx->sqo_dead))
6809 ret = io_submit_sqes(ctx, to_submit);
6810 mutex_unlock(&ctx->uring_lock);
6812 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6813 wake_up(&ctx->sqo_sq_wait);
6815 return SQT_DID_WORK;
6818 static void io_sqd_init_new(struct io_sq_data *sqd)
6820 struct io_ring_ctx *ctx;
6822 while (!list_empty(&sqd->ctx_new_list)) {
6823 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6824 init_wait(&ctx->sqo_wait_entry);
6825 ctx->sqo_wait_entry.func = io_sq_wake_function;
6826 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6827 complete(&ctx->sq_thread_comp);
6831 static int io_sq_thread(void *data)
6833 struct cgroup_subsys_state *cur_css = NULL;
6834 const struct cred *old_cred = NULL;
6835 struct io_sq_data *sqd = data;
6836 struct io_ring_ctx *ctx;
6837 unsigned long start_jiffies;
6839 start_jiffies = jiffies;
6840 while (!kthread_should_stop()) {
6841 enum sq_ret ret = 0;
6845 * Any changes to the sqd lists are synchronized through the
6846 * kthread parking. This synchronizes the thread vs users,
6847 * the users are synchronized on the sqd->ctx_lock.
6849 if (kthread_should_park()) {
6852 * When sq thread is unparked, in case the previous park operation
6853 * comes from io_put_sq_data(), which means that sq thread is going
6854 * to be stopped, so here needs to have a check.
6856 if (kthread_should_stop())
6860 if (unlikely(!list_empty(&sqd->ctx_new_list)))
6861 io_sqd_init_new(sqd);
6863 cap_entries = !list_is_singular(&sqd->ctx_list);
6865 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6866 if (current->cred != ctx->creds) {
6868 revert_creds(old_cred);
6869 old_cred = override_creds(ctx->creds);
6871 io_sq_thread_associate_blkcg(ctx, &cur_css);
6873 current->loginuid = ctx->loginuid;
6874 current->sessionid = ctx->sessionid;
6877 ret |= __io_sq_thread(ctx, start_jiffies, cap_entries);
6879 io_sq_thread_drop_mm();
6882 if (ret & SQT_SPIN) {
6884 io_sq_thread_drop_mm();
6886 } else if (ret == SQT_IDLE) {
6887 if (kthread_should_park())
6889 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6890 io_ring_set_wakeup_flag(ctx);
6892 start_jiffies = jiffies;
6893 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6894 io_ring_clear_wakeup_flag(ctx);
6899 io_sq_thread_drop_mm();
6902 io_sq_thread_unassociate_blkcg();
6904 revert_creds(old_cred);
6911 struct io_wait_queue {
6912 struct wait_queue_entry wq;
6913 struct io_ring_ctx *ctx;
6915 unsigned nr_timeouts;
6918 static inline bool io_should_wake(struct io_wait_queue *iowq)
6920 struct io_ring_ctx *ctx = iowq->ctx;
6923 * Wake up if we have enough events, or if a timeout occurred since we
6924 * started waiting. For timeouts, we always want to return to userspace,
6925 * regardless of event count.
6927 return io_cqring_events(ctx) >= iowq->to_wait ||
6928 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6931 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6932 int wake_flags, void *key)
6934 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6938 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6939 * the task, and the next invocation will do it.
6941 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6942 return autoremove_wake_function(curr, mode, wake_flags, key);
6946 static int io_run_task_work_sig(void)
6948 if (io_run_task_work())
6950 if (!signal_pending(current))
6952 if (current->jobctl & JOBCTL_TASK_WORK) {
6953 spin_lock_irq(¤t->sighand->siglock);
6954 current->jobctl &= ~JOBCTL_TASK_WORK;
6955 recalc_sigpending();
6956 spin_unlock_irq(¤t->sighand->siglock);
6963 * Wait until events become available, if we don't already have some. The
6964 * application must reap them itself, as they reside on the shared cq ring.
6966 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6967 const sigset_t __user *sig, size_t sigsz)
6969 struct io_wait_queue iowq = {
6972 .func = io_wake_function,
6973 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6976 .to_wait = min_events,
6978 struct io_rings *rings = ctx->rings;
6982 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6983 if (io_cqring_events(ctx) >= min_events)
6985 if (!io_run_task_work())
6990 #ifdef CONFIG_COMPAT
6991 if (in_compat_syscall())
6992 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6996 ret = set_user_sigmask(sig, sigsz);
7002 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7003 trace_io_uring_cqring_wait(ctx, min_events);
7005 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7006 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7007 TASK_INTERRUPTIBLE);
7008 /* make sure we run task_work before checking for signals */
7009 ret = io_run_task_work_sig();
7011 finish_wait(&ctx->wait, &iowq.wq);
7016 if (io_should_wake(&iowq))
7018 if (test_bit(0, &ctx->cq_check_overflow)) {
7019 finish_wait(&ctx->wait, &iowq.wq);
7024 finish_wait(&ctx->wait, &iowq.wq);
7026 restore_saved_sigmask_unless(ret == -EINTR);
7028 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7031 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7033 #if defined(CONFIG_UNIX)
7034 if (ctx->ring_sock) {
7035 struct sock *sock = ctx->ring_sock->sk;
7036 struct sk_buff *skb;
7038 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7044 for (i = 0; i < ctx->nr_user_files; i++) {
7047 file = io_file_from_index(ctx, i);
7054 static void io_file_ref_kill(struct percpu_ref *ref)
7056 struct fixed_file_data *data;
7058 data = container_of(ref, struct fixed_file_data, refs);
7059 complete(&data->done);
7062 static void io_sqe_files_set_node(struct fixed_file_data *file_data,
7063 struct fixed_file_ref_node *ref_node)
7065 spin_lock_bh(&file_data->lock);
7066 file_data->node = ref_node;
7067 list_add_tail(&ref_node->node, &file_data->ref_list);
7068 spin_unlock_bh(&file_data->lock);
7069 percpu_ref_get(&file_data->refs);
7072 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7074 struct fixed_file_data *data = ctx->file_data;
7075 struct fixed_file_ref_node *backup_node, *ref_node = NULL;
7076 unsigned nr_tables, i;
7081 backup_node = alloc_fixed_file_ref_node(ctx);
7085 spin_lock_bh(&data->lock);
7086 ref_node = data->node;
7087 spin_unlock_bh(&data->lock);
7089 percpu_ref_kill(&ref_node->refs);
7091 percpu_ref_kill(&data->refs);
7093 /* wait for all refs nodes to complete */
7094 flush_delayed_work(&ctx->file_put_work);
7096 ret = wait_for_completion_interruptible(&data->done);
7099 ret = io_run_task_work_sig();
7101 percpu_ref_resurrect(&data->refs);
7102 reinit_completion(&data->done);
7103 io_sqe_files_set_node(data, backup_node);
7108 __io_sqe_files_unregister(ctx);
7109 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7110 for (i = 0; i < nr_tables; i++)
7111 kfree(data->table[i].files);
7113 percpu_ref_exit(&data->refs);
7115 ctx->file_data = NULL;
7116 ctx->nr_user_files = 0;
7117 destroy_fixed_file_ref_node(backup_node);
7121 static void io_put_sq_data(struct io_sq_data *sqd)
7123 if (refcount_dec_and_test(&sqd->refs)) {
7125 * The park is a bit of a work-around, without it we get
7126 * warning spews on shutdown with SQPOLL set and affinity
7127 * set to a single CPU.
7130 kthread_park(sqd->thread);
7131 kthread_stop(sqd->thread);
7138 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7140 struct io_ring_ctx *ctx_attach;
7141 struct io_sq_data *sqd;
7144 f = fdget(p->wq_fd);
7146 return ERR_PTR(-ENXIO);
7147 if (f.file->f_op != &io_uring_fops) {
7149 return ERR_PTR(-EINVAL);
7152 ctx_attach = f.file->private_data;
7153 sqd = ctx_attach->sq_data;
7156 return ERR_PTR(-EINVAL);
7159 refcount_inc(&sqd->refs);
7164 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7166 struct io_sq_data *sqd;
7168 if (p->flags & IORING_SETUP_ATTACH_WQ)
7169 return io_attach_sq_data(p);
7171 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7173 return ERR_PTR(-ENOMEM);
7175 refcount_set(&sqd->refs, 1);
7176 INIT_LIST_HEAD(&sqd->ctx_list);
7177 INIT_LIST_HEAD(&sqd->ctx_new_list);
7178 mutex_init(&sqd->ctx_lock);
7179 mutex_init(&sqd->lock);
7180 init_waitqueue_head(&sqd->wait);
7184 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7185 __releases(&sqd->lock)
7189 kthread_unpark(sqd->thread);
7190 mutex_unlock(&sqd->lock);
7193 static void io_sq_thread_park(struct io_sq_data *sqd)
7194 __acquires(&sqd->lock)
7198 mutex_lock(&sqd->lock);
7199 kthread_park(sqd->thread);
7202 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7204 struct io_sq_data *sqd = ctx->sq_data;
7209 * We may arrive here from the error branch in
7210 * io_sq_offload_create() where the kthread is created
7211 * without being waked up, thus wake it up now to make
7212 * sure the wait will complete.
7214 wake_up_process(sqd->thread);
7215 wait_for_completion(&ctx->sq_thread_comp);
7217 io_sq_thread_park(sqd);
7220 mutex_lock(&sqd->ctx_lock);
7221 list_del(&ctx->sqd_list);
7222 mutex_unlock(&sqd->ctx_lock);
7225 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
7226 io_sq_thread_unpark(sqd);
7229 io_put_sq_data(sqd);
7230 ctx->sq_data = NULL;
7234 static void io_finish_async(struct io_ring_ctx *ctx)
7236 io_sq_thread_stop(ctx);
7239 io_wq_destroy(ctx->io_wq);
7244 #if defined(CONFIG_UNIX)
7246 * Ensure the UNIX gc is aware of our file set, so we are certain that
7247 * the io_uring can be safely unregistered on process exit, even if we have
7248 * loops in the file referencing.
7250 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7252 struct sock *sk = ctx->ring_sock->sk;
7253 struct scm_fp_list *fpl;
7254 struct sk_buff *skb;
7257 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7261 skb = alloc_skb(0, GFP_KERNEL);
7270 fpl->user = get_uid(ctx->user);
7271 for (i = 0; i < nr; i++) {
7272 struct file *file = io_file_from_index(ctx, i + offset);
7276 fpl->fp[nr_files] = get_file(file);
7277 unix_inflight(fpl->user, fpl->fp[nr_files]);
7282 fpl->max = SCM_MAX_FD;
7283 fpl->count = nr_files;
7284 UNIXCB(skb).fp = fpl;
7285 skb->destructor = unix_destruct_scm;
7286 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7287 skb_queue_head(&sk->sk_receive_queue, skb);
7289 for (i = 0; i < nr_files; i++)
7300 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7301 * causes regular reference counting to break down. We rely on the UNIX
7302 * garbage collection to take care of this problem for us.
7304 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7306 unsigned left, total;
7310 left = ctx->nr_user_files;
7312 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7314 ret = __io_sqe_files_scm(ctx, this_files, total);
7318 total += this_files;
7324 while (total < ctx->nr_user_files) {
7325 struct file *file = io_file_from_index(ctx, total);
7335 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7341 static int io_sqe_alloc_file_tables(struct fixed_file_data *file_data,
7342 unsigned nr_tables, unsigned nr_files)
7346 for (i = 0; i < nr_tables; i++) {
7347 struct fixed_file_table *table = &file_data->table[i];
7348 unsigned this_files;
7350 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7351 table->files = kcalloc(this_files, sizeof(struct file *),
7355 nr_files -= this_files;
7361 for (i = 0; i < nr_tables; i++) {
7362 struct fixed_file_table *table = &file_data->table[i];
7363 kfree(table->files);
7368 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
7370 #if defined(CONFIG_UNIX)
7371 struct sock *sock = ctx->ring_sock->sk;
7372 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7373 struct sk_buff *skb;
7376 __skb_queue_head_init(&list);
7379 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7380 * remove this entry and rearrange the file array.
7382 skb = skb_dequeue(head);
7384 struct scm_fp_list *fp;
7386 fp = UNIXCB(skb).fp;
7387 for (i = 0; i < fp->count; i++) {
7390 if (fp->fp[i] != file)
7393 unix_notinflight(fp->user, fp->fp[i]);
7394 left = fp->count - 1 - i;
7396 memmove(&fp->fp[i], &fp->fp[i + 1],
7397 left * sizeof(struct file *));
7404 __skb_queue_tail(&list, skb);
7414 __skb_queue_tail(&list, skb);
7416 skb = skb_dequeue(head);
7419 if (skb_peek(&list)) {
7420 spin_lock_irq(&head->lock);
7421 while ((skb = __skb_dequeue(&list)) != NULL)
7422 __skb_queue_tail(head, skb);
7423 spin_unlock_irq(&head->lock);
7430 struct io_file_put {
7431 struct list_head list;
7435 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
7437 struct fixed_file_data *file_data = ref_node->file_data;
7438 struct io_ring_ctx *ctx = file_data->ctx;
7439 struct io_file_put *pfile, *tmp;
7441 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
7442 list_del(&pfile->list);
7443 io_ring_file_put(ctx, pfile->file);
7447 percpu_ref_exit(&ref_node->refs);
7449 percpu_ref_put(&file_data->refs);
7452 static void io_file_put_work(struct work_struct *work)
7454 struct io_ring_ctx *ctx;
7455 struct llist_node *node;
7457 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
7458 node = llist_del_all(&ctx->file_put_llist);
7461 struct fixed_file_ref_node *ref_node;
7462 struct llist_node *next = node->next;
7464 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
7465 __io_file_put_work(ref_node);
7470 static void io_file_data_ref_zero(struct percpu_ref *ref)
7472 struct fixed_file_ref_node *ref_node;
7473 struct fixed_file_data *data;
7474 struct io_ring_ctx *ctx;
7475 bool first_add = false;
7478 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
7479 data = ref_node->file_data;
7482 spin_lock_bh(&data->lock);
7483 ref_node->done = true;
7485 while (!list_empty(&data->ref_list)) {
7486 ref_node = list_first_entry(&data->ref_list,
7487 struct fixed_file_ref_node, node);
7488 /* recycle ref nodes in order */
7489 if (!ref_node->done)
7491 list_del(&ref_node->node);
7492 first_add |= llist_add(&ref_node->llist, &ctx->file_put_llist);
7494 spin_unlock_bh(&data->lock);
7496 if (percpu_ref_is_dying(&data->refs))
7500 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
7502 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
7505 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
7506 struct io_ring_ctx *ctx)
7508 struct fixed_file_ref_node *ref_node;
7510 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7514 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
7519 INIT_LIST_HEAD(&ref_node->node);
7520 INIT_LIST_HEAD(&ref_node->file_list);
7521 ref_node->file_data = ctx->file_data;
7522 ref_node->done = false;
7526 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
7528 percpu_ref_exit(&ref_node->refs);
7532 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7535 __s32 __user *fds = (__s32 __user *) arg;
7536 unsigned nr_tables, i;
7538 int fd, ret = -ENOMEM;
7539 struct fixed_file_ref_node *ref_node;
7540 struct fixed_file_data *file_data;
7546 if (nr_args > IORING_MAX_FIXED_FILES)
7549 file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
7552 file_data->ctx = ctx;
7553 init_completion(&file_data->done);
7554 INIT_LIST_HEAD(&file_data->ref_list);
7555 spin_lock_init(&file_data->lock);
7557 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7558 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7560 if (!file_data->table)
7563 if (percpu_ref_init(&file_data->refs, io_file_ref_kill,
7564 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
7567 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7569 ctx->file_data = file_data;
7571 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7572 struct fixed_file_table *table;
7575 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7579 /* allow sparse sets */
7589 * Don't allow io_uring instances to be registered. If UNIX
7590 * isn't enabled, then this causes a reference cycle and this
7591 * instance can never get freed. If UNIX is enabled we'll
7592 * handle it just fine, but there's still no point in allowing
7593 * a ring fd as it doesn't support regular read/write anyway.
7595 if (file->f_op == &io_uring_fops) {
7599 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7600 index = i & IORING_FILE_TABLE_MASK;
7601 table->files[index] = file;
7604 ret = io_sqe_files_scm(ctx);
7606 io_sqe_files_unregister(ctx);
7610 ref_node = alloc_fixed_file_ref_node(ctx);
7612 io_sqe_files_unregister(ctx);
7616 io_sqe_files_set_node(file_data, ref_node);
7619 for (i = 0; i < ctx->nr_user_files; i++) {
7620 file = io_file_from_index(ctx, i);
7624 for (i = 0; i < nr_tables; i++)
7625 kfree(file_data->table[i].files);
7626 ctx->nr_user_files = 0;
7628 percpu_ref_exit(&file_data->refs);
7630 kfree(file_data->table);
7632 ctx->file_data = NULL;
7636 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7639 #if defined(CONFIG_UNIX)
7640 struct sock *sock = ctx->ring_sock->sk;
7641 struct sk_buff_head *head = &sock->sk_receive_queue;
7642 struct sk_buff *skb;
7645 * See if we can merge this file into an existing skb SCM_RIGHTS
7646 * file set. If there's no room, fall back to allocating a new skb
7647 * and filling it in.
7649 spin_lock_irq(&head->lock);
7650 skb = skb_peek(head);
7652 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7654 if (fpl->count < SCM_MAX_FD) {
7655 __skb_unlink(skb, head);
7656 spin_unlock_irq(&head->lock);
7657 fpl->fp[fpl->count] = get_file(file);
7658 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7660 spin_lock_irq(&head->lock);
7661 __skb_queue_head(head, skb);
7666 spin_unlock_irq(&head->lock);
7673 return __io_sqe_files_scm(ctx, 1, index);
7679 static int io_queue_file_removal(struct fixed_file_data *data,
7682 struct io_file_put *pfile;
7683 struct fixed_file_ref_node *ref_node = data->node;
7685 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7690 list_add(&pfile->list, &ref_node->file_list);
7695 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7696 struct io_uring_files_update *up,
7699 struct fixed_file_data *data = ctx->file_data;
7700 struct fixed_file_ref_node *ref_node;
7705 bool needs_switch = false;
7707 if (check_add_overflow(up->offset, nr_args, &done))
7709 if (done > ctx->nr_user_files)
7712 ref_node = alloc_fixed_file_ref_node(ctx);
7717 fds = u64_to_user_ptr(up->fds);
7719 struct fixed_file_table *table;
7723 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7727 i = array_index_nospec(up->offset, ctx->nr_user_files);
7728 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7729 index = i & IORING_FILE_TABLE_MASK;
7730 if (table->files[index]) {
7731 file = table->files[index];
7732 err = io_queue_file_removal(data, file);
7735 table->files[index] = NULL;
7736 needs_switch = true;
7745 * Don't allow io_uring instances to be registered. If
7746 * UNIX isn't enabled, then this causes a reference
7747 * cycle and this instance can never get freed. If UNIX
7748 * is enabled we'll handle it just fine, but there's
7749 * still no point in allowing a ring fd as it doesn't
7750 * support regular read/write anyway.
7752 if (file->f_op == &io_uring_fops) {
7757 table->files[index] = file;
7758 err = io_sqe_file_register(ctx, file, i);
7760 table->files[index] = NULL;
7771 percpu_ref_kill(&data->node->refs);
7772 io_sqe_files_set_node(data, ref_node);
7774 destroy_fixed_file_ref_node(ref_node);
7776 return done ? done : err;
7779 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7782 struct io_uring_files_update up;
7784 if (!ctx->file_data)
7788 if (copy_from_user(&up, arg, sizeof(up)))
7793 return __io_sqe_files_update(ctx, &up, nr_args);
7796 static void io_free_work(struct io_wq_work *work)
7798 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7800 /* Consider that io_steal_work() relies on this ref */
7804 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7805 struct io_uring_params *p)
7807 struct io_wq_data data;
7809 struct io_ring_ctx *ctx_attach;
7810 unsigned int concurrency;
7813 data.user = ctx->user;
7814 data.free_work = io_free_work;
7815 data.do_work = io_wq_submit_work;
7817 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7818 /* Do QD, or 4 * CPUS, whatever is smallest */
7819 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7821 ctx->io_wq = io_wq_create(concurrency, &data);
7822 if (IS_ERR(ctx->io_wq)) {
7823 ret = PTR_ERR(ctx->io_wq);
7829 f = fdget(p->wq_fd);
7833 if (f.file->f_op != &io_uring_fops) {
7838 ctx_attach = f.file->private_data;
7839 /* @io_wq is protected by holding the fd */
7840 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7845 ctx->io_wq = ctx_attach->io_wq;
7851 static int io_uring_alloc_task_context(struct task_struct *task)
7853 struct io_uring_task *tctx;
7856 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7857 if (unlikely(!tctx))
7860 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7861 if (unlikely(ret)) {
7867 init_waitqueue_head(&tctx->wait);
7869 atomic_set(&tctx->in_idle, 0);
7870 tctx->sqpoll = false;
7871 io_init_identity(&tctx->__identity);
7872 tctx->identity = &tctx->__identity;
7873 task->io_uring = tctx;
7877 void __io_uring_free(struct task_struct *tsk)
7879 struct io_uring_task *tctx = tsk->io_uring;
7881 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7882 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
7883 if (tctx->identity != &tctx->__identity)
7884 kfree(tctx->identity);
7885 percpu_counter_destroy(&tctx->inflight);
7887 tsk->io_uring = NULL;
7890 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7891 struct io_uring_params *p)
7895 if (ctx->flags & IORING_SETUP_SQPOLL) {
7896 struct io_sq_data *sqd;
7899 if (!capable(CAP_SYS_ADMIN))
7902 sqd = io_get_sq_data(p);
7909 io_sq_thread_park(sqd);
7910 mutex_lock(&sqd->ctx_lock);
7911 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7912 mutex_unlock(&sqd->ctx_lock);
7913 io_sq_thread_unpark(sqd);
7915 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7916 if (!ctx->sq_thread_idle)
7917 ctx->sq_thread_idle = HZ;
7922 if (p->flags & IORING_SETUP_SQ_AFF) {
7923 int cpu = p->sq_thread_cpu;
7926 if (cpu >= nr_cpu_ids)
7928 if (!cpu_online(cpu))
7931 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
7932 cpu, "io_uring-sq");
7934 sqd->thread = kthread_create(io_sq_thread, sqd,
7937 if (IS_ERR(sqd->thread)) {
7938 ret = PTR_ERR(sqd->thread);
7942 ret = io_uring_alloc_task_context(sqd->thread);
7945 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7946 /* Can't have SQ_AFF without SQPOLL */
7952 ret = io_init_wq_offload(ctx, p);
7958 io_finish_async(ctx);
7962 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7964 struct io_sq_data *sqd = ctx->sq_data;
7966 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
7967 wake_up_process(sqd->thread);
7970 static inline void __io_unaccount_mem(struct user_struct *user,
7971 unsigned long nr_pages)
7973 atomic_long_sub(nr_pages, &user->locked_vm);
7976 static inline int __io_account_mem(struct user_struct *user,
7977 unsigned long nr_pages)
7979 unsigned long page_limit, cur_pages, new_pages;
7981 /* Don't allow more pages than we can safely lock */
7982 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7985 cur_pages = atomic_long_read(&user->locked_vm);
7986 new_pages = cur_pages + nr_pages;
7987 if (new_pages > page_limit)
7989 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7990 new_pages) != cur_pages);
7995 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7996 enum io_mem_account acct)
7999 __io_unaccount_mem(ctx->user, nr_pages);
8001 if (ctx->mm_account) {
8002 if (acct == ACCT_LOCKED)
8003 ctx->mm_account->locked_vm -= nr_pages;
8004 else if (acct == ACCT_PINNED)
8005 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8009 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8010 enum io_mem_account acct)
8014 if (ctx->limit_mem) {
8015 ret = __io_account_mem(ctx->user, nr_pages);
8020 if (ctx->mm_account) {
8021 if (acct == ACCT_LOCKED)
8022 ctx->mm_account->locked_vm += nr_pages;
8023 else if (acct == ACCT_PINNED)
8024 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8030 static void io_mem_free(void *ptr)
8037 page = virt_to_head_page(ptr);
8038 if (put_page_testzero(page))
8039 free_compound_page(page);
8042 static void *io_mem_alloc(size_t size)
8044 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8047 return (void *) __get_free_pages(gfp_flags, get_order(size));
8050 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8053 struct io_rings *rings;
8054 size_t off, sq_array_size;
8056 off = struct_size(rings, cqes, cq_entries);
8057 if (off == SIZE_MAX)
8061 off = ALIGN(off, SMP_CACHE_BYTES);
8069 sq_array_size = array_size(sizeof(u32), sq_entries);
8070 if (sq_array_size == SIZE_MAX)
8073 if (check_add_overflow(off, sq_array_size, &off))
8079 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
8083 pages = (size_t)1 << get_order(
8084 rings_size(sq_entries, cq_entries, NULL));
8085 pages += (size_t)1 << get_order(
8086 array_size(sizeof(struct io_uring_sqe), sq_entries));
8091 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
8095 if (!ctx->user_bufs)
8098 for (i = 0; i < ctx->nr_user_bufs; i++) {
8099 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8101 for (j = 0; j < imu->nr_bvecs; j++)
8102 unpin_user_page(imu->bvec[j].bv_page);
8104 if (imu->acct_pages)
8105 io_unaccount_mem(ctx, imu->acct_pages, ACCT_PINNED);
8110 kfree(ctx->user_bufs);
8111 ctx->user_bufs = NULL;
8112 ctx->nr_user_bufs = 0;
8116 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8117 void __user *arg, unsigned index)
8119 struct iovec __user *src;
8121 #ifdef CONFIG_COMPAT
8123 struct compat_iovec __user *ciovs;
8124 struct compat_iovec ciov;
8126 ciovs = (struct compat_iovec __user *) arg;
8127 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8130 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8131 dst->iov_len = ciov.iov_len;
8135 src = (struct iovec __user *) arg;
8136 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8142 * Not super efficient, but this is just a registration time. And we do cache
8143 * the last compound head, so generally we'll only do a full search if we don't
8146 * We check if the given compound head page has already been accounted, to
8147 * avoid double accounting it. This allows us to account the full size of the
8148 * page, not just the constituent pages of a huge page.
8150 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8151 int nr_pages, struct page *hpage)
8155 /* check current page array */
8156 for (i = 0; i < nr_pages; i++) {
8157 if (!PageCompound(pages[i]))
8159 if (compound_head(pages[i]) == hpage)
8163 /* check previously registered pages */
8164 for (i = 0; i < ctx->nr_user_bufs; i++) {
8165 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8167 for (j = 0; j < imu->nr_bvecs; j++) {
8168 if (!PageCompound(imu->bvec[j].bv_page))
8170 if (compound_head(imu->bvec[j].bv_page) == hpage)
8178 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8179 int nr_pages, struct io_mapped_ubuf *imu,
8180 struct page **last_hpage)
8184 for (i = 0; i < nr_pages; i++) {
8185 if (!PageCompound(pages[i])) {
8190 hpage = compound_head(pages[i]);
8191 if (hpage == *last_hpage)
8193 *last_hpage = hpage;
8194 if (headpage_already_acct(ctx, pages, i, hpage))
8196 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8200 if (!imu->acct_pages)
8203 ret = io_account_mem(ctx, imu->acct_pages, ACCT_PINNED);
8205 imu->acct_pages = 0;
8209 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
8212 struct vm_area_struct **vmas = NULL;
8213 struct page **pages = NULL;
8214 struct page *last_hpage = NULL;
8215 int i, j, got_pages = 0;
8220 if (!nr_args || nr_args > UIO_MAXIOV)
8223 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8225 if (!ctx->user_bufs)
8228 for (i = 0; i < nr_args; i++) {
8229 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8230 unsigned long off, start, end, ubuf;
8235 ret = io_copy_iov(ctx, &iov, arg, i);
8240 * Don't impose further limits on the size and buffer
8241 * constraints here, we'll -EINVAL later when IO is
8242 * submitted if they are wrong.
8245 if (!iov.iov_base || !iov.iov_len)
8248 /* arbitrary limit, but we need something */
8249 if (iov.iov_len > SZ_1G)
8252 ubuf = (unsigned long) iov.iov_base;
8253 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8254 start = ubuf >> PAGE_SHIFT;
8255 nr_pages = end - start;
8258 if (!pages || nr_pages > got_pages) {
8261 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
8263 vmas = kvmalloc_array(nr_pages,
8264 sizeof(struct vm_area_struct *),
8266 if (!pages || !vmas) {
8270 got_pages = nr_pages;
8273 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8280 mmap_read_lock(current->mm);
8281 pret = pin_user_pages(ubuf, nr_pages,
8282 FOLL_WRITE | FOLL_LONGTERM,
8284 if (pret == nr_pages) {
8285 /* don't support file backed memory */
8286 for (j = 0; j < nr_pages; j++) {
8287 struct vm_area_struct *vma = vmas[j];
8290 !is_file_hugepages(vma->vm_file)) {
8296 ret = pret < 0 ? pret : -EFAULT;
8298 mmap_read_unlock(current->mm);
8301 * if we did partial map, or found file backed vmas,
8302 * release any pages we did get
8305 unpin_user_pages(pages, pret);
8310 ret = io_buffer_account_pin(ctx, pages, pret, imu, &last_hpage);
8312 unpin_user_pages(pages, pret);
8317 off = ubuf & ~PAGE_MASK;
8319 for (j = 0; j < nr_pages; j++) {
8322 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8323 imu->bvec[j].bv_page = pages[j];
8324 imu->bvec[j].bv_len = vec_len;
8325 imu->bvec[j].bv_offset = off;
8329 /* store original address for later verification */
8331 imu->len = iov.iov_len;
8332 imu->nr_bvecs = nr_pages;
8334 ctx->nr_user_bufs++;
8342 io_sqe_buffer_unregister(ctx);
8346 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8348 __s32 __user *fds = arg;
8354 if (copy_from_user(&fd, fds, sizeof(*fds)))
8357 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8358 if (IS_ERR(ctx->cq_ev_fd)) {
8359 int ret = PTR_ERR(ctx->cq_ev_fd);
8360 ctx->cq_ev_fd = NULL;
8367 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8369 if (ctx->cq_ev_fd) {
8370 eventfd_ctx_put(ctx->cq_ev_fd);
8371 ctx->cq_ev_fd = NULL;
8378 static int __io_destroy_buffers(int id, void *p, void *data)
8380 struct io_ring_ctx *ctx = data;
8381 struct io_buffer *buf = p;
8383 __io_remove_buffers(ctx, buf, id, -1U);
8387 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8389 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8390 idr_destroy(&ctx->io_buffer_idr);
8393 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8395 io_finish_async(ctx);
8396 io_sqe_buffer_unregister(ctx);
8398 if (ctx->sqo_task) {
8399 put_task_struct(ctx->sqo_task);
8400 ctx->sqo_task = NULL;
8401 mmdrop(ctx->mm_account);
8402 ctx->mm_account = NULL;
8405 #ifdef CONFIG_BLK_CGROUP
8406 if (ctx->sqo_blkcg_css)
8407 css_put(ctx->sqo_blkcg_css);
8410 io_sqe_files_unregister(ctx);
8411 io_eventfd_unregister(ctx);
8412 io_destroy_buffers(ctx);
8413 idr_destroy(&ctx->personality_idr);
8415 #if defined(CONFIG_UNIX)
8416 if (ctx->ring_sock) {
8417 ctx->ring_sock->file = NULL; /* so that iput() is called */
8418 sock_release(ctx->ring_sock);
8422 io_mem_free(ctx->rings);
8423 io_mem_free(ctx->sq_sqes);
8425 percpu_ref_exit(&ctx->refs);
8426 free_uid(ctx->user);
8427 put_cred(ctx->creds);
8428 kfree(ctx->cancel_hash);
8429 kmem_cache_free(req_cachep, ctx->fallback_req);
8433 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8435 struct io_ring_ctx *ctx = file->private_data;
8438 poll_wait(file, &ctx->cq_wait, wait);
8440 * synchronizes with barrier from wq_has_sleeper call in
8444 if (!io_sqring_full(ctx))
8445 mask |= EPOLLOUT | EPOLLWRNORM;
8448 * Don't flush cqring overflow list here, just do a simple check.
8449 * Otherwise there could possible be ABBA deadlock:
8452 * lock(&ctx->uring_lock);
8454 * lock(&ctx->uring_lock);
8457 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8458 * pushs them to do the flush.
8460 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8461 mask |= EPOLLIN | EPOLLRDNORM;
8466 static int io_uring_fasync(int fd, struct file *file, int on)
8468 struct io_ring_ctx *ctx = file->private_data;
8470 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8473 static int io_remove_personalities(int id, void *p, void *data)
8475 struct io_ring_ctx *ctx = data;
8476 struct io_identity *iod;
8478 iod = idr_remove(&ctx->personality_idr, id);
8480 put_cred(iod->creds);
8481 if (refcount_dec_and_test(&iod->count))
8487 static void io_ring_exit_work(struct work_struct *work)
8489 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8493 * If we're doing polled IO and end up having requests being
8494 * submitted async (out-of-line), then completions can come in while
8495 * we're waiting for refs to drop. We need to reap these manually,
8496 * as nobody else will be looking for them.
8499 io_iopoll_try_reap_events(ctx);
8500 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8501 io_ring_ctx_free(ctx);
8504 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8506 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8508 return req->ctx == data;
8511 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8513 mutex_lock(&ctx->uring_lock);
8514 percpu_ref_kill(&ctx->refs);
8515 /* if force is set, the ring is going away. always drop after that */
8517 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8520 ctx->cq_overflow_flushed = 1;
8522 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8523 mutex_unlock(&ctx->uring_lock);
8525 io_kill_timeouts(ctx, NULL, NULL);
8526 io_poll_remove_all(ctx, NULL, NULL);
8529 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8531 /* if we failed setting up the ctx, we might not have any rings */
8532 io_iopoll_try_reap_events(ctx);
8533 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8536 * Do this upfront, so we won't have a grace period where the ring
8537 * is closed but resources aren't reaped yet. This can cause
8538 * spurious failure in setting up a new ring.
8540 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
8543 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8545 * Use system_unbound_wq to avoid spawning tons of event kworkers
8546 * if we're exiting a ton of rings at the same time. It just adds
8547 * noise and overhead, there's no discernable change in runtime
8548 * over using system_wq.
8550 queue_work(system_unbound_wq, &ctx->exit_work);
8553 static int io_uring_release(struct inode *inode, struct file *file)
8555 struct io_ring_ctx *ctx = file->private_data;
8557 file->private_data = NULL;
8558 io_ring_ctx_wait_and_kill(ctx);
8562 struct io_task_cancel {
8563 struct task_struct *task;
8564 struct files_struct *files;
8567 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8569 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8570 struct io_task_cancel *cancel = data;
8573 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8574 unsigned long flags;
8575 struct io_ring_ctx *ctx = req->ctx;
8577 /* protect against races with linked timeouts */
8578 spin_lock_irqsave(&ctx->completion_lock, flags);
8579 ret = io_match_task(req, cancel->task, cancel->files);
8580 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8582 ret = io_match_task(req, cancel->task, cancel->files);
8587 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8588 struct task_struct *task,
8589 struct files_struct *files)
8591 struct io_defer_entry *de = NULL;
8594 spin_lock_irq(&ctx->completion_lock);
8595 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8596 if (io_match_task(de->req, task, files)) {
8597 list_cut_position(&list, &ctx->defer_list, &de->list);
8601 spin_unlock_irq(&ctx->completion_lock);
8603 while (!list_empty(&list)) {
8604 de = list_first_entry(&list, struct io_defer_entry, list);
8605 list_del_init(&de->list);
8606 req_set_fail_links(de->req);
8607 io_put_req(de->req);
8608 io_req_complete(de->req, -ECANCELED);
8613 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8614 struct task_struct *task,
8615 struct files_struct *files)
8617 struct io_kiocb *req;
8620 spin_lock_irq(&ctx->inflight_lock);
8621 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8622 cnt += io_match_task(req, task, files);
8623 spin_unlock_irq(&ctx->inflight_lock);
8627 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8628 struct task_struct *task,
8629 struct files_struct *files)
8631 while (!list_empty_careful(&ctx->inflight_list)) {
8632 struct io_task_cancel cancel = { .task = task, .files = files };
8636 inflight = io_uring_count_inflight(ctx, task, files);
8640 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, &cancel, true);
8641 io_poll_remove_all(ctx, task, files);
8642 io_kill_timeouts(ctx, task, files);
8643 /* cancellations _may_ trigger task work */
8646 prepare_to_wait(&task->io_uring->wait, &wait,
8647 TASK_UNINTERRUPTIBLE);
8648 if (inflight == io_uring_count_inflight(ctx, task, files))
8650 finish_wait(&task->io_uring->wait, &wait);
8654 static void __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8655 struct task_struct *task)
8658 struct io_task_cancel cancel = { .task = task, .files = NULL, };
8659 enum io_wq_cancel cret;
8662 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, &cancel, true);
8663 if (cret != IO_WQ_CANCEL_NOTFOUND)
8666 /* SQPOLL thread does its own polling */
8667 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8668 while (!list_empty_careful(&ctx->iopoll_list)) {
8669 io_iopoll_try_reap_events(ctx);
8674 ret |= io_poll_remove_all(ctx, task, NULL);
8675 ret |= io_kill_timeouts(ctx, task, NULL);
8683 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
8685 mutex_lock(&ctx->uring_lock);
8687 mutex_unlock(&ctx->uring_lock);
8689 /* make sure callers enter the ring to get error */
8691 io_ring_set_wakeup_flag(ctx);
8695 * We need to iteratively cancel requests, in case a request has dependent
8696 * hard links. These persist even for failure of cancelations, hence keep
8697 * looping until none are found.
8699 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8700 struct files_struct *files)
8702 struct task_struct *task = current;
8704 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8705 io_disable_sqo_submit(ctx);
8706 task = ctx->sq_data->thread;
8707 atomic_inc(&task->io_uring->in_idle);
8708 io_sq_thread_park(ctx->sq_data);
8711 io_cancel_defer_files(ctx, task, files);
8712 io_cqring_overflow_flush(ctx, true, task, files);
8714 io_uring_cancel_files(ctx, task, files);
8716 __io_uring_cancel_task_requests(ctx, task);
8718 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8719 atomic_dec(&task->io_uring->in_idle);
8720 io_sq_thread_unpark(ctx->sq_data);
8725 * Note that this task has used io_uring. We use it for cancelation purposes.
8727 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8729 struct io_uring_task *tctx = current->io_uring;
8732 if (unlikely(!tctx)) {
8733 ret = io_uring_alloc_task_context(current);
8736 tctx = current->io_uring;
8738 if (tctx->last != file) {
8739 void *old = xa_load(&tctx->xa, (unsigned long)file);
8743 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8754 * This is race safe in that the task itself is doing this, hence it
8755 * cannot be going through the exit/cancel paths at the same time.
8756 * This cannot be modified while exit/cancel is running.
8758 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8759 tctx->sqpoll = true;
8765 * Remove this io_uring_file -> task mapping.
8767 static void io_uring_del_task_file(struct file *file)
8769 struct io_uring_task *tctx = current->io_uring;
8771 if (tctx->last == file)
8773 file = xa_erase(&tctx->xa, (unsigned long)file);
8778 static void io_uring_remove_task_files(struct io_uring_task *tctx)
8781 unsigned long index;
8783 xa_for_each(&tctx->xa, index, file)
8784 io_uring_del_task_file(file);
8787 void __io_uring_files_cancel(struct files_struct *files)
8789 struct io_uring_task *tctx = current->io_uring;
8791 unsigned long index;
8793 /* make sure overflow events are dropped */
8794 atomic_inc(&tctx->in_idle);
8795 xa_for_each(&tctx->xa, index, file)
8796 io_uring_cancel_task_requests(file->private_data, files);
8797 atomic_dec(&tctx->in_idle);
8800 io_uring_remove_task_files(tctx);
8803 static s64 tctx_inflight(struct io_uring_task *tctx)
8805 unsigned long index;
8809 inflight = percpu_counter_sum(&tctx->inflight);
8814 * If we have SQPOLL rings, then we need to iterate and find them, and
8815 * add the pending count for those.
8817 xa_for_each(&tctx->xa, index, file) {
8818 struct io_ring_ctx *ctx = file->private_data;
8820 if (ctx->flags & IORING_SETUP_SQPOLL) {
8821 struct io_uring_task *__tctx = ctx->sqo_task->io_uring;
8823 inflight += percpu_counter_sum(&__tctx->inflight);
8831 * Find any io_uring fd that this task has registered or done IO on, and cancel
8834 void __io_uring_task_cancel(void)
8836 struct io_uring_task *tctx = current->io_uring;
8840 /* make sure overflow events are dropped */
8841 atomic_inc(&tctx->in_idle);
8843 /* trigger io_disable_sqo_submit() */
8845 __io_uring_files_cancel(NULL);
8848 /* read completions before cancelations */
8849 inflight = tctx_inflight(tctx);
8852 __io_uring_files_cancel(NULL);
8854 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8857 * If we've seen completions, retry without waiting. This
8858 * avoids a race where a completion comes in before we did
8859 * prepare_to_wait().
8861 if (inflight == tctx_inflight(tctx))
8863 finish_wait(&tctx->wait, &wait);
8866 atomic_dec(&tctx->in_idle);
8868 io_uring_remove_task_files(tctx);
8871 static int io_uring_flush(struct file *file, void *data)
8873 struct io_uring_task *tctx = current->io_uring;
8874 struct io_ring_ctx *ctx = file->private_data;
8876 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
8877 io_uring_cancel_task_requests(ctx, NULL);
8882 /* we should have cancelled and erased it before PF_EXITING */
8883 WARN_ON_ONCE((current->flags & PF_EXITING) &&
8884 xa_load(&tctx->xa, (unsigned long)file));
8887 * fput() is pending, will be 2 if the only other ref is our potential
8888 * task file note. If the task is exiting, drop regardless of count.
8890 if (atomic_long_read(&file->f_count) != 2)
8893 if (ctx->flags & IORING_SETUP_SQPOLL) {
8894 /* there is only one file note, which is owned by sqo_task */
8895 WARN_ON_ONCE(ctx->sqo_task != current &&
8896 xa_load(&tctx->xa, (unsigned long)file));
8897 /* sqo_dead check is for when this happens after cancellation */
8898 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
8899 !xa_load(&tctx->xa, (unsigned long)file));
8901 io_disable_sqo_submit(ctx);
8904 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
8905 io_uring_del_task_file(file);
8909 static void *io_uring_validate_mmap_request(struct file *file,
8910 loff_t pgoff, size_t sz)
8912 struct io_ring_ctx *ctx = file->private_data;
8913 loff_t offset = pgoff << PAGE_SHIFT;
8918 case IORING_OFF_SQ_RING:
8919 case IORING_OFF_CQ_RING:
8922 case IORING_OFF_SQES:
8926 return ERR_PTR(-EINVAL);
8929 page = virt_to_head_page(ptr);
8930 if (sz > page_size(page))
8931 return ERR_PTR(-EINVAL);
8938 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8940 size_t sz = vma->vm_end - vma->vm_start;
8944 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
8946 return PTR_ERR(ptr);
8948 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
8949 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
8952 #else /* !CONFIG_MMU */
8954 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8956 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
8959 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
8961 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
8964 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
8965 unsigned long addr, unsigned long len,
8966 unsigned long pgoff, unsigned long flags)
8970 ptr = io_uring_validate_mmap_request(file, pgoff, len);
8972 return PTR_ERR(ptr);
8974 return (unsigned long) ptr;
8977 #endif /* !CONFIG_MMU */
8979 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
8985 if (!io_sqring_full(ctx))
8988 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
8990 if (unlikely(ctx->sqo_dead)) {
8995 if (!io_sqring_full(ctx))
8999 } while (!signal_pending(current));
9001 finish_wait(&ctx->sqo_sq_wait, &wait);
9006 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9007 u32, min_complete, u32, flags, const sigset_t __user *, sig,
9010 struct io_ring_ctx *ctx;
9017 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9018 IORING_ENTER_SQ_WAIT))
9026 if (f.file->f_op != &io_uring_fops)
9030 ctx = f.file->private_data;
9031 if (!percpu_ref_tryget(&ctx->refs))
9035 if (ctx->flags & IORING_SETUP_R_DISABLED)
9039 * For SQ polling, the thread will do all submissions and completions.
9040 * Just return the requested submit count, and wake the thread if
9044 if (ctx->flags & IORING_SETUP_SQPOLL) {
9045 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9048 if (unlikely(ctx->sqo_dead))
9050 if (flags & IORING_ENTER_SQ_WAKEUP)
9051 wake_up(&ctx->sq_data->wait);
9052 if (flags & IORING_ENTER_SQ_WAIT) {
9053 ret = io_sqpoll_wait_sq(ctx);
9057 submitted = to_submit;
9058 } else if (to_submit) {
9059 ret = io_uring_add_task_file(ctx, f.file);
9062 mutex_lock(&ctx->uring_lock);
9063 submitted = io_submit_sqes(ctx, to_submit);
9064 mutex_unlock(&ctx->uring_lock);
9066 if (submitted != to_submit)
9069 if (flags & IORING_ENTER_GETEVENTS) {
9070 min_complete = min(min_complete, ctx->cq_entries);
9073 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9074 * space applications don't need to do io completion events
9075 * polling again, they can rely on io_sq_thread to do polling
9076 * work, which can reduce cpu usage and uring_lock contention.
9078 if (ctx->flags & IORING_SETUP_IOPOLL &&
9079 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9080 ret = io_iopoll_check(ctx, min_complete);
9082 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
9087 percpu_ref_put(&ctx->refs);
9090 return submitted ? submitted : ret;
9093 #ifdef CONFIG_PROC_FS
9094 static int io_uring_show_cred(int id, void *p, void *data)
9096 struct io_identity *iod = p;
9097 const struct cred *cred = iod->creds;
9098 struct seq_file *m = data;
9099 struct user_namespace *uns = seq_user_ns(m);
9100 struct group_info *gi;
9105 seq_printf(m, "%5d\n", id);
9106 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9107 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9108 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9109 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9110 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9111 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9112 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9113 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9114 seq_puts(m, "\n\tGroups:\t");
9115 gi = cred->group_info;
9116 for (g = 0; g < gi->ngroups; g++) {
9117 seq_put_decimal_ull(m, g ? " " : "",
9118 from_kgid_munged(uns, gi->gid[g]));
9120 seq_puts(m, "\n\tCapEff:\t");
9121 cap = cred->cap_effective;
9122 CAP_FOR_EACH_U32(__capi)
9123 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9128 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9130 struct io_sq_data *sq = NULL;
9135 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9136 * since fdinfo case grabs it in the opposite direction of normal use
9137 * cases. If we fail to get the lock, we just don't iterate any
9138 * structures that could be going away outside the io_uring mutex.
9140 has_lock = mutex_trylock(&ctx->uring_lock);
9142 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9145 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9146 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9147 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9148 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9149 struct fixed_file_table *table;
9152 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
9153 f = table->files[i & IORING_FILE_TABLE_MASK];
9155 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9157 seq_printf(m, "%5u: <none>\n", i);
9159 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9160 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9161 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9163 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9164 (unsigned int) buf->len);
9166 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9167 seq_printf(m, "Personalities:\n");
9168 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9170 seq_printf(m, "PollList:\n");
9171 spin_lock_irq(&ctx->completion_lock);
9172 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9173 struct hlist_head *list = &ctx->cancel_hash[i];
9174 struct io_kiocb *req;
9176 hlist_for_each_entry(req, list, hash_node)
9177 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9178 req->task->task_works != NULL);
9180 spin_unlock_irq(&ctx->completion_lock);
9182 mutex_unlock(&ctx->uring_lock);
9185 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9187 struct io_ring_ctx *ctx = f->private_data;
9189 if (percpu_ref_tryget(&ctx->refs)) {
9190 __io_uring_show_fdinfo(ctx, m);
9191 percpu_ref_put(&ctx->refs);
9196 static const struct file_operations io_uring_fops = {
9197 .release = io_uring_release,
9198 .flush = io_uring_flush,
9199 .mmap = io_uring_mmap,
9201 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9202 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9204 .poll = io_uring_poll,
9205 .fasync = io_uring_fasync,
9206 #ifdef CONFIG_PROC_FS
9207 .show_fdinfo = io_uring_show_fdinfo,
9211 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9212 struct io_uring_params *p)
9214 struct io_rings *rings;
9215 size_t size, sq_array_offset;
9217 /* make sure these are sane, as we already accounted them */
9218 ctx->sq_entries = p->sq_entries;
9219 ctx->cq_entries = p->cq_entries;
9221 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9222 if (size == SIZE_MAX)
9225 rings = io_mem_alloc(size);
9230 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9231 rings->sq_ring_mask = p->sq_entries - 1;
9232 rings->cq_ring_mask = p->cq_entries - 1;
9233 rings->sq_ring_entries = p->sq_entries;
9234 rings->cq_ring_entries = p->cq_entries;
9235 ctx->sq_mask = rings->sq_ring_mask;
9236 ctx->cq_mask = rings->cq_ring_mask;
9238 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9239 if (size == SIZE_MAX) {
9240 io_mem_free(ctx->rings);
9245 ctx->sq_sqes = io_mem_alloc(size);
9246 if (!ctx->sq_sqes) {
9247 io_mem_free(ctx->rings);
9255 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9259 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9263 ret = io_uring_add_task_file(ctx, file);
9268 fd_install(fd, file);
9273 * Allocate an anonymous fd, this is what constitutes the application
9274 * visible backing of an io_uring instance. The application mmaps this
9275 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9276 * we have to tie this fd to a socket for file garbage collection purposes.
9278 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9281 #if defined(CONFIG_UNIX)
9284 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9287 return ERR_PTR(ret);
9290 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9291 O_RDWR | O_CLOEXEC);
9292 #if defined(CONFIG_UNIX)
9294 sock_release(ctx->ring_sock);
9295 ctx->ring_sock = NULL;
9297 ctx->ring_sock->file = file;
9303 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9304 struct io_uring_params __user *params)
9306 struct user_struct *user = NULL;
9307 struct io_ring_ctx *ctx;
9314 if (entries > IORING_MAX_ENTRIES) {
9315 if (!(p->flags & IORING_SETUP_CLAMP))
9317 entries = IORING_MAX_ENTRIES;
9321 * Use twice as many entries for the CQ ring. It's possible for the
9322 * application to drive a higher depth than the size of the SQ ring,
9323 * since the sqes are only used at submission time. This allows for
9324 * some flexibility in overcommitting a bit. If the application has
9325 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9326 * of CQ ring entries manually.
9328 p->sq_entries = roundup_pow_of_two(entries);
9329 if (p->flags & IORING_SETUP_CQSIZE) {
9331 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9332 * to a power-of-two, if it isn't already. We do NOT impose
9333 * any cq vs sq ring sizing.
9337 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9338 if (!(p->flags & IORING_SETUP_CLAMP))
9340 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9342 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9343 if (p->cq_entries < p->sq_entries)
9346 p->cq_entries = 2 * p->sq_entries;
9349 user = get_uid(current_user());
9350 limit_mem = !capable(CAP_IPC_LOCK);
9353 ret = __io_account_mem(user,
9354 ring_pages(p->sq_entries, p->cq_entries));
9361 ctx = io_ring_ctx_alloc(p);
9364 __io_unaccount_mem(user, ring_pages(p->sq_entries,
9369 ctx->compat = in_compat_syscall();
9371 ctx->creds = get_current_cred();
9373 ctx->loginuid = current->loginuid;
9374 ctx->sessionid = current->sessionid;
9376 ctx->sqo_task = get_task_struct(current);
9379 * This is just grabbed for accounting purposes. When a process exits,
9380 * the mm is exited and dropped before the files, hence we need to hang
9381 * on to this mm purely for the purposes of being able to unaccount
9382 * memory (locked/pinned vm). It's not used for anything else.
9384 mmgrab(current->mm);
9385 ctx->mm_account = current->mm;
9387 #ifdef CONFIG_BLK_CGROUP
9389 * The sq thread will belong to the original cgroup it was inited in.
9390 * If the cgroup goes offline (e.g. disabling the io controller), then
9391 * issued bios will be associated with the closest cgroup later in the
9395 ctx->sqo_blkcg_css = blkcg_css();
9396 ret = css_tryget_online(ctx->sqo_blkcg_css);
9399 /* don't init against a dying cgroup, have the user try again */
9400 ctx->sqo_blkcg_css = NULL;
9407 * Account memory _before_ installing the file descriptor. Once
9408 * the descriptor is installed, it can get closed at any time. Also
9409 * do this before hitting the general error path, as ring freeing
9410 * will un-account as well.
9412 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9414 ctx->limit_mem = limit_mem;
9416 ret = io_allocate_scq_urings(ctx, p);
9420 ret = io_sq_offload_create(ctx, p);
9424 if (!(p->flags & IORING_SETUP_R_DISABLED))
9425 io_sq_offload_start(ctx);
9427 memset(&p->sq_off, 0, sizeof(p->sq_off));
9428 p->sq_off.head = offsetof(struct io_rings, sq.head);
9429 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9430 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9431 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9432 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9433 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9434 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9436 memset(&p->cq_off, 0, sizeof(p->cq_off));
9437 p->cq_off.head = offsetof(struct io_rings, cq.head);
9438 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9439 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9440 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9441 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9442 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9443 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9445 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9446 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9447 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9448 IORING_FEAT_POLL_32BITS;
9450 if (copy_to_user(params, p, sizeof(*p))) {
9455 file = io_uring_get_file(ctx);
9457 ret = PTR_ERR(file);
9462 * Install ring fd as the very last thing, so we don't risk someone
9463 * having closed it before we finish setup
9465 ret = io_uring_install_fd(ctx, file);
9467 io_disable_sqo_submit(ctx);
9468 /* fput will clean it up */
9473 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9476 io_disable_sqo_submit(ctx);
9477 io_ring_ctx_wait_and_kill(ctx);
9482 * Sets up an aio uring context, and returns the fd. Applications asks for a
9483 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9484 * params structure passed in.
9486 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9488 struct io_uring_params p;
9491 if (copy_from_user(&p, params, sizeof(p)))
9493 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9498 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9499 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9500 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9501 IORING_SETUP_R_DISABLED))
9504 return io_uring_create(entries, &p, params);
9507 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9508 struct io_uring_params __user *, params)
9510 return io_uring_setup(entries, params);
9513 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9515 struct io_uring_probe *p;
9519 size = struct_size(p, ops, nr_args);
9520 if (size == SIZE_MAX)
9522 p = kzalloc(size, GFP_KERNEL);
9527 if (copy_from_user(p, arg, size))
9530 if (memchr_inv(p, 0, size))
9533 p->last_op = IORING_OP_LAST - 1;
9534 if (nr_args > IORING_OP_LAST)
9535 nr_args = IORING_OP_LAST;
9537 for (i = 0; i < nr_args; i++) {
9539 if (!io_op_defs[i].not_supported)
9540 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9545 if (copy_to_user(arg, p, size))
9552 static int io_register_personality(struct io_ring_ctx *ctx)
9554 struct io_identity *id;
9557 id = kmalloc(sizeof(*id), GFP_KERNEL);
9561 io_init_identity(id);
9562 id->creds = get_current_cred();
9564 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9566 put_cred(id->creds);
9572 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9574 struct io_identity *iod;
9576 iod = idr_remove(&ctx->personality_idr, id);
9578 put_cred(iod->creds);
9579 if (refcount_dec_and_test(&iod->count))
9587 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9588 unsigned int nr_args)
9590 struct io_uring_restriction *res;
9594 /* Restrictions allowed only if rings started disabled */
9595 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9598 /* We allow only a single restrictions registration */
9599 if (ctx->restrictions.registered)
9602 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9605 size = array_size(nr_args, sizeof(*res));
9606 if (size == SIZE_MAX)
9609 res = memdup_user(arg, size);
9611 return PTR_ERR(res);
9615 for (i = 0; i < nr_args; i++) {
9616 switch (res[i].opcode) {
9617 case IORING_RESTRICTION_REGISTER_OP:
9618 if (res[i].register_op >= IORING_REGISTER_LAST) {
9623 __set_bit(res[i].register_op,
9624 ctx->restrictions.register_op);
9626 case IORING_RESTRICTION_SQE_OP:
9627 if (res[i].sqe_op >= IORING_OP_LAST) {
9632 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9634 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9635 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9637 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9638 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9647 /* Reset all restrictions if an error happened */
9649 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9651 ctx->restrictions.registered = true;
9657 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9659 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9662 if (ctx->restrictions.registered)
9663 ctx->restricted = 1;
9665 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9667 io_sq_offload_start(ctx);
9672 static bool io_register_op_must_quiesce(int op)
9675 case IORING_UNREGISTER_FILES:
9676 case IORING_REGISTER_FILES_UPDATE:
9677 case IORING_REGISTER_PROBE:
9678 case IORING_REGISTER_PERSONALITY:
9679 case IORING_UNREGISTER_PERSONALITY:
9686 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9687 void __user *arg, unsigned nr_args)
9688 __releases(ctx->uring_lock)
9689 __acquires(ctx->uring_lock)
9694 * We're inside the ring mutex, if the ref is already dying, then
9695 * someone else killed the ctx or is already going through
9696 * io_uring_register().
9698 if (percpu_ref_is_dying(&ctx->refs))
9701 if (io_register_op_must_quiesce(opcode)) {
9702 percpu_ref_kill(&ctx->refs);
9705 * Drop uring mutex before waiting for references to exit. If
9706 * another thread is currently inside io_uring_enter() it might
9707 * need to grab the uring_lock to make progress. If we hold it
9708 * here across the drain wait, then we can deadlock. It's safe
9709 * to drop the mutex here, since no new references will come in
9710 * after we've killed the percpu ref.
9712 mutex_unlock(&ctx->uring_lock);
9714 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9717 ret = io_run_task_work_sig();
9722 mutex_lock(&ctx->uring_lock);
9725 percpu_ref_resurrect(&ctx->refs);
9730 if (ctx->restricted) {
9731 if (opcode >= IORING_REGISTER_LAST) {
9736 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9743 case IORING_REGISTER_BUFFERS:
9744 ret = io_sqe_buffer_register(ctx, arg, nr_args);
9746 case IORING_UNREGISTER_BUFFERS:
9750 ret = io_sqe_buffer_unregister(ctx);
9752 case IORING_REGISTER_FILES:
9753 ret = io_sqe_files_register(ctx, arg, nr_args);
9755 case IORING_UNREGISTER_FILES:
9759 ret = io_sqe_files_unregister(ctx);
9761 case IORING_REGISTER_FILES_UPDATE:
9762 ret = io_sqe_files_update(ctx, arg, nr_args);
9764 case IORING_REGISTER_EVENTFD:
9765 case IORING_REGISTER_EVENTFD_ASYNC:
9769 ret = io_eventfd_register(ctx, arg);
9772 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9773 ctx->eventfd_async = 1;
9775 ctx->eventfd_async = 0;
9777 case IORING_UNREGISTER_EVENTFD:
9781 ret = io_eventfd_unregister(ctx);
9783 case IORING_REGISTER_PROBE:
9785 if (!arg || nr_args > 256)
9787 ret = io_probe(ctx, arg, nr_args);
9789 case IORING_REGISTER_PERSONALITY:
9793 ret = io_register_personality(ctx);
9795 case IORING_UNREGISTER_PERSONALITY:
9799 ret = io_unregister_personality(ctx, nr_args);
9801 case IORING_REGISTER_ENABLE_RINGS:
9805 ret = io_register_enable_rings(ctx);
9807 case IORING_REGISTER_RESTRICTIONS:
9808 ret = io_register_restrictions(ctx, arg, nr_args);
9816 if (io_register_op_must_quiesce(opcode)) {
9817 /* bring the ctx back to life */
9818 percpu_ref_reinit(&ctx->refs);
9820 reinit_completion(&ctx->ref_comp);
9825 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9826 void __user *, arg, unsigned int, nr_args)
9828 struct io_ring_ctx *ctx;
9837 if (f.file->f_op != &io_uring_fops)
9840 ctx = f.file->private_data;
9842 mutex_lock(&ctx->uring_lock);
9843 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9844 mutex_unlock(&ctx->uring_lock);
9845 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9846 ctx->cq_ev_fd != NULL, ret);
9852 static int __init io_uring_init(void)
9854 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9855 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9856 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9859 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9860 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9861 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9862 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9863 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9864 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9865 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9866 BUILD_BUG_SQE_ELEM(8, __u64, off);
9867 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9868 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9869 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9870 BUILD_BUG_SQE_ELEM(24, __u32, len);
9871 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9872 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9873 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9874 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9875 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9876 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9877 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9878 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9879 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9880 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9881 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9882 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9883 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9884 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9885 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9886 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9887 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9888 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9889 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9891 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9892 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9893 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
9896 __initcall(io_uring_init);