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>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
97 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
99 #define IORING_FILE_TABLE_SHIFT 9
100 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
101 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
102 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
103 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
104 IORING_REGISTER_LAST + IORING_OP_LAST)
107 u32 head ____cacheline_aligned_in_smp;
108 u32 tail ____cacheline_aligned_in_smp;
112 * This data is shared with the application through the mmap at offsets
113 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
115 * The offsets to the member fields are published through struct
116 * io_sqring_offsets when calling io_uring_setup.
120 * Head and tail offsets into the ring; the offsets need to be
121 * masked to get valid indices.
123 * The kernel controls head of the sq ring and the tail of the cq ring,
124 * and the application controls tail of the sq ring and the head of the
127 struct io_uring sq, cq;
129 * Bitmasks to apply to head and tail offsets (constant, equals
132 u32 sq_ring_mask, cq_ring_mask;
133 /* Ring sizes (constant, power of 2) */
134 u32 sq_ring_entries, cq_ring_entries;
136 * Number of invalid entries dropped by the kernel due to
137 * invalid index stored in array
139 * Written by the kernel, shouldn't be modified by the
140 * application (i.e. get number of "new events" by comparing to
143 * After a new SQ head value was read by the application this
144 * counter includes all submissions that were dropped reaching
145 * the new SQ head (and possibly more).
151 * Written by the kernel, shouldn't be modified by the
154 * The application needs a full memory barrier before checking
155 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
161 * Written by the application, shouldn't be modified by the
166 * Number of completion events lost because the queue was full;
167 * this should be avoided by the application by making sure
168 * there are not more requests pending than there is space in
169 * the completion queue.
171 * Written by the kernel, shouldn't be modified by the
172 * application (i.e. get number of "new events" by comparing to
175 * As completion events come in out of order this counter is not
176 * ordered with any other data.
180 * Ring buffer of completion events.
182 * The kernel writes completion events fresh every time they are
183 * produced, so the application is allowed to modify pending
186 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
189 struct io_mapped_ubuf {
192 struct bio_vec *bvec;
193 unsigned int nr_bvecs;
194 unsigned long acct_pages;
197 struct fixed_file_table {
201 struct fixed_file_ref_node {
202 struct percpu_ref refs;
203 struct list_head node;
204 struct list_head file_list;
205 struct fixed_file_data *file_data;
206 struct llist_node llist;
209 struct fixed_file_data {
210 struct fixed_file_table *table;
211 struct io_ring_ctx *ctx;
213 struct fixed_file_ref_node *node;
214 struct percpu_ref refs;
215 struct completion done;
216 struct list_head ref_list;
221 struct list_head list;
227 struct io_restriction {
228 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
229 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
230 u8 sqe_flags_allowed;
231 u8 sqe_flags_required;
239 /* ctx's that are using this sqd */
240 struct list_head ctx_list;
241 struct list_head ctx_new_list;
242 struct mutex ctx_lock;
244 struct task_struct *thread;
245 struct wait_queue_head wait;
250 struct percpu_ref refs;
251 } ____cacheline_aligned_in_smp;
255 unsigned int compat: 1;
256 unsigned int limit_mem: 1;
257 unsigned int cq_overflow_flushed: 1;
258 unsigned int drain_next: 1;
259 unsigned int eventfd_async: 1;
260 unsigned int restricted: 1;
263 * Ring buffer of indices into array of io_uring_sqe, which is
264 * mmapped by the application using the IORING_OFF_SQES offset.
266 * This indirection could e.g. be used to assign fixed
267 * io_uring_sqe entries to operations and only submit them to
268 * the queue when needed.
270 * The kernel modifies neither the indices array nor the entries
274 unsigned cached_sq_head;
277 unsigned sq_thread_idle;
278 unsigned cached_sq_dropped;
279 atomic_t cached_cq_overflow;
280 unsigned long sq_check_overflow;
282 struct list_head defer_list;
283 struct list_head timeout_list;
284 struct list_head cq_overflow_list;
286 wait_queue_head_t inflight_wait;
287 struct io_uring_sqe *sq_sqes;
288 } ____cacheline_aligned_in_smp;
290 struct io_rings *rings;
296 * For SQPOLL usage - we hold a reference to the parent task, so we
297 * have access to the ->files
299 struct task_struct *sqo_task;
301 /* Only used for accounting purposes */
302 struct mm_struct *mm_account;
304 #ifdef CONFIG_BLK_CGROUP
305 struct cgroup_subsys_state *sqo_blkcg_css;
308 struct io_sq_data *sq_data; /* if using sq thread polling */
310 struct wait_queue_head sqo_sq_wait;
311 struct wait_queue_entry sqo_wait_entry;
312 struct list_head sqd_list;
315 * If used, fixed file set. Writers must ensure that ->refs is dead,
316 * readers must ensure that ->refs is alive as long as the file* is
317 * used. Only updated through io_uring_register(2).
319 struct fixed_file_data *file_data;
320 unsigned nr_user_files;
322 /* if used, fixed mapped user buffers */
323 unsigned nr_user_bufs;
324 struct io_mapped_ubuf *user_bufs;
326 struct user_struct *user;
328 const struct cred *creds;
330 struct completion ref_comp;
331 struct completion sq_thread_comp;
333 /* if all else fails... */
334 struct io_kiocb *fallback_req;
336 #if defined(CONFIG_UNIX)
337 struct socket *ring_sock;
340 struct idr io_buffer_idr;
342 struct idr personality_idr;
345 unsigned cached_cq_tail;
348 atomic_t cq_timeouts;
349 unsigned long cq_check_overflow;
350 struct wait_queue_head cq_wait;
351 struct fasync_struct *cq_fasync;
352 struct eventfd_ctx *cq_ev_fd;
353 } ____cacheline_aligned_in_smp;
356 struct mutex uring_lock;
357 wait_queue_head_t wait;
358 } ____cacheline_aligned_in_smp;
361 spinlock_t completion_lock;
364 * ->iopoll_list is protected by the ctx->uring_lock for
365 * io_uring instances that don't use IORING_SETUP_SQPOLL.
366 * For SQPOLL, only the single threaded io_sq_thread() will
367 * manipulate the list, hence no extra locking is needed there.
369 struct list_head iopoll_list;
370 struct hlist_head *cancel_hash;
371 unsigned cancel_hash_bits;
372 bool poll_multi_file;
374 spinlock_t inflight_lock;
375 struct list_head inflight_list;
376 } ____cacheline_aligned_in_smp;
378 struct delayed_work file_put_work;
379 struct llist_head file_put_llist;
381 struct work_struct exit_work;
382 struct io_restriction restrictions;
386 * First field must be the file pointer in all the
387 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
389 struct io_poll_iocb {
392 struct wait_queue_head *head;
398 struct wait_queue_entry wait;
403 struct file *put_file;
407 struct io_timeout_data {
408 struct io_kiocb *req;
409 struct hrtimer timer;
410 struct timespec64 ts;
411 enum hrtimer_mode mode;
416 struct sockaddr __user *addr;
417 int __user *addr_len;
419 unsigned long nofile;
439 struct list_head list;
442 struct io_timeout_rem {
448 /* NOTE: kiocb has the file as the first member, so don't do it here */
456 struct sockaddr __user *addr;
463 struct user_msghdr __user *umsg;
469 struct io_buffer *kbuf;
475 struct filename *filename;
477 unsigned long nofile;
480 struct io_files_update {
506 struct epoll_event event;
510 struct file *file_out;
511 struct file *file_in;
518 struct io_provide_buf {
532 const char __user *filename;
533 struct statx __user *buffer;
536 struct io_completion {
538 struct list_head list;
542 struct io_async_connect {
543 struct sockaddr_storage address;
546 struct io_async_msghdr {
547 struct iovec fast_iov[UIO_FASTIOV];
549 struct sockaddr __user *uaddr;
551 struct sockaddr_storage addr;
555 struct iovec fast_iov[UIO_FASTIOV];
556 const struct iovec *free_iovec;
557 struct iov_iter iter;
559 struct wait_page_queue wpq;
563 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
564 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
565 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
566 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
567 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
568 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
575 REQ_F_LINK_TIMEOUT_BIT,
577 REQ_F_NEED_CLEANUP_BIT,
579 REQ_F_BUFFER_SELECTED_BIT,
580 REQ_F_NO_FILE_TABLE_BIT,
581 REQ_F_WORK_INITIALIZED_BIT,
583 /* not a real bit, just to check we're not overflowing the space */
589 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
590 /* drain existing IO first */
591 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
593 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
594 /* doesn't sever on completion < 0 */
595 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
597 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
598 /* IOSQE_BUFFER_SELECT */
599 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
602 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
603 /* fail rest of links */
604 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
605 /* on inflight list */
606 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
607 /* read/write uses file position */
608 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
609 /* must not punt to workers */
610 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
611 /* has linked timeout */
612 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
614 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
616 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
617 /* already went through poll handler */
618 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
619 /* buffer already selected */
620 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
621 /* doesn't need file table for this request */
622 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
623 /* io_wq_work is initialized */
624 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
628 struct io_poll_iocb poll;
629 struct io_poll_iocb *double_poll;
633 * NOTE! Each of the iocb union members has the file pointer
634 * as the first entry in their struct definition. So you can
635 * access the file pointer through any of the sub-structs,
636 * or directly as just 'ki_filp' in this struct.
642 struct io_poll_iocb poll;
643 struct io_accept accept;
645 struct io_cancel cancel;
646 struct io_timeout timeout;
647 struct io_timeout_rem timeout_rem;
648 struct io_connect connect;
649 struct io_sr_msg sr_msg;
651 struct io_close close;
652 struct io_files_update files_update;
653 struct io_fadvise fadvise;
654 struct io_madvise madvise;
655 struct io_epoll epoll;
656 struct io_splice splice;
657 struct io_provide_buf pbuf;
658 struct io_statx statx;
659 /* use only after cleaning per-op data, see io_clean_op() */
660 struct io_completion compl;
663 /* opcode allocated if it needs to store data for async defer */
666 /* polled IO has completed */
672 struct io_ring_ctx *ctx;
675 struct task_struct *task;
678 struct list_head link_list;
681 * 1. used with ctx->iopoll_list with reads/writes
682 * 2. to track reqs with ->files (see io_op_def::file_table)
684 struct list_head inflight_entry;
686 struct percpu_ref *fixed_file_refs;
687 struct callback_head task_work;
688 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
689 struct hlist_node hash_node;
690 struct async_poll *apoll;
691 struct io_wq_work work;
694 struct io_defer_entry {
695 struct list_head list;
696 struct io_kiocb *req;
700 #define IO_IOPOLL_BATCH 8
702 struct io_comp_state {
704 struct list_head list;
705 struct io_ring_ctx *ctx;
708 struct io_submit_state {
709 struct blk_plug plug;
712 * io_kiocb alloc cache
714 void *reqs[IO_IOPOLL_BATCH];
715 unsigned int free_reqs;
718 * Batch completion logic
720 struct io_comp_state comp;
723 * File reference cache
727 unsigned int has_refs;
728 unsigned int ios_left;
732 /* needs current->mm setup, does mm access */
733 unsigned needs_mm : 1;
734 /* needs req->file assigned */
735 unsigned needs_file : 1;
736 /* don't fail if file grab fails */
737 unsigned needs_file_no_error : 1;
738 /* hash wq insertion if file is a regular file */
739 unsigned hash_reg_file : 1;
740 /* unbound wq insertion if file is a non-regular file */
741 unsigned unbound_nonreg_file : 1;
742 /* opcode is not supported by this kernel */
743 unsigned not_supported : 1;
744 /* needs file table */
745 unsigned file_table : 1;
747 unsigned needs_fs : 1;
748 /* set if opcode supports polled "wait" */
750 unsigned pollout : 1;
751 /* op supports buffer selection */
752 unsigned buffer_select : 1;
753 /* needs rlimit(RLIMIT_FSIZE) assigned */
754 unsigned needs_fsize : 1;
755 /* must always have async data allocated */
756 unsigned needs_async_data : 1;
757 /* needs blkcg context, issues async io potentially */
758 unsigned needs_blkcg : 1;
759 /* size of async data needed, if any */
760 unsigned short async_size;
763 static const struct io_op_def io_op_defs[] = {
764 [IORING_OP_NOP] = {},
765 [IORING_OP_READV] = {
768 .unbound_nonreg_file = 1,
771 .needs_async_data = 1,
773 .async_size = sizeof(struct io_async_rw),
775 [IORING_OP_WRITEV] = {
779 .unbound_nonreg_file = 1,
782 .needs_async_data = 1,
784 .async_size = sizeof(struct io_async_rw),
786 [IORING_OP_FSYNC] = {
790 [IORING_OP_READ_FIXED] = {
792 .unbound_nonreg_file = 1,
795 .async_size = sizeof(struct io_async_rw),
797 [IORING_OP_WRITE_FIXED] = {
800 .unbound_nonreg_file = 1,
804 .async_size = sizeof(struct io_async_rw),
806 [IORING_OP_POLL_ADD] = {
808 .unbound_nonreg_file = 1,
810 [IORING_OP_POLL_REMOVE] = {},
811 [IORING_OP_SYNC_FILE_RANGE] = {
815 [IORING_OP_SENDMSG] = {
818 .unbound_nonreg_file = 1,
821 .needs_async_data = 1,
823 .async_size = sizeof(struct io_async_msghdr),
825 [IORING_OP_RECVMSG] = {
828 .unbound_nonreg_file = 1,
832 .needs_async_data = 1,
834 .async_size = sizeof(struct io_async_msghdr),
836 [IORING_OP_TIMEOUT] = {
838 .needs_async_data = 1,
839 .async_size = sizeof(struct io_timeout_data),
841 [IORING_OP_TIMEOUT_REMOVE] = {},
842 [IORING_OP_ACCEPT] = {
845 .unbound_nonreg_file = 1,
849 [IORING_OP_ASYNC_CANCEL] = {},
850 [IORING_OP_LINK_TIMEOUT] = {
852 .needs_async_data = 1,
853 .async_size = sizeof(struct io_timeout_data),
855 [IORING_OP_CONNECT] = {
858 .unbound_nonreg_file = 1,
860 .needs_async_data = 1,
861 .async_size = sizeof(struct io_async_connect),
863 [IORING_OP_FALLOCATE] = {
868 [IORING_OP_OPENAT] = {
873 [IORING_OP_CLOSE] = {
875 .needs_file_no_error = 1,
879 [IORING_OP_FILES_UPDATE] = {
883 [IORING_OP_STATX] = {
892 .unbound_nonreg_file = 1,
896 .async_size = sizeof(struct io_async_rw),
898 [IORING_OP_WRITE] = {
901 .unbound_nonreg_file = 1,
905 .async_size = sizeof(struct io_async_rw),
907 [IORING_OP_FADVISE] = {
911 [IORING_OP_MADVISE] = {
918 .unbound_nonreg_file = 1,
925 .unbound_nonreg_file = 1,
930 [IORING_OP_OPENAT2] = {
935 [IORING_OP_EPOLL_CTL] = {
936 .unbound_nonreg_file = 1,
939 [IORING_OP_SPLICE] = {
942 .unbound_nonreg_file = 1,
945 [IORING_OP_PROVIDE_BUFFERS] = {},
946 [IORING_OP_REMOVE_BUFFERS] = {},
950 .unbound_nonreg_file = 1,
954 enum io_mem_account {
959 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
960 struct io_comp_state *cs);
961 static void io_cqring_fill_event(struct io_kiocb *req, long res);
962 static void io_put_req(struct io_kiocb *req);
963 static void io_put_req_deferred(struct io_kiocb *req, int nr);
964 static void io_double_put_req(struct io_kiocb *req);
965 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
966 static void __io_queue_linked_timeout(struct io_kiocb *req);
967 static void io_queue_linked_timeout(struct io_kiocb *req);
968 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
969 struct io_uring_files_update *ip,
971 static void __io_clean_op(struct io_kiocb *req);
972 static struct file *io_file_get(struct io_submit_state *state,
973 struct io_kiocb *req, int fd, bool fixed);
974 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs);
975 static void io_file_put_work(struct work_struct *work);
977 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
978 struct iovec **iovec, struct iov_iter *iter,
980 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
981 const struct iovec *fast_iov,
982 struct iov_iter *iter, bool force);
984 static struct kmem_cache *req_cachep;
986 static const struct file_operations io_uring_fops;
988 struct sock *io_uring_get_socket(struct file *file)
990 #if defined(CONFIG_UNIX)
991 if (file->f_op == &io_uring_fops) {
992 struct io_ring_ctx *ctx = file->private_data;
994 return ctx->ring_sock->sk;
999 EXPORT_SYMBOL(io_uring_get_socket);
1001 static inline void io_clean_op(struct io_kiocb *req)
1003 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
1008 static void io_sq_thread_drop_mm(void)
1010 struct mm_struct *mm = current->mm;
1013 kthread_unuse_mm(mm);
1018 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1021 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL) ||
1022 !ctx->sqo_task->mm ||
1023 !mmget_not_zero(ctx->sqo_task->mm)))
1025 kthread_use_mm(ctx->sqo_task->mm);
1031 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
1032 struct io_kiocb *req)
1034 if (!io_op_defs[req->opcode].needs_mm)
1036 return __io_sq_thread_acquire_mm(ctx);
1039 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1040 struct cgroup_subsys_state **cur_css)
1043 #ifdef CONFIG_BLK_CGROUP
1044 /* puts the old one when swapping */
1045 if (*cur_css != ctx->sqo_blkcg_css) {
1046 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1047 *cur_css = ctx->sqo_blkcg_css;
1052 static void io_sq_thread_unassociate_blkcg(void)
1054 #ifdef CONFIG_BLK_CGROUP
1055 kthread_associate_blkcg(NULL);
1059 static inline void req_set_fail_links(struct io_kiocb *req)
1061 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1062 req->flags |= REQ_F_FAIL_LINK;
1066 * Note: must call io_req_init_async() for the first time you
1067 * touch any members of io_wq_work.
1069 static inline void io_req_init_async(struct io_kiocb *req)
1071 if (req->flags & REQ_F_WORK_INITIALIZED)
1074 memset(&req->work, 0, sizeof(req->work));
1075 req->flags |= REQ_F_WORK_INITIALIZED;
1078 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1080 return ctx->flags & IORING_SETUP_SQPOLL;
1083 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1085 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1087 complete(&ctx->ref_comp);
1090 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1092 return !req->timeout.off;
1095 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1097 struct io_ring_ctx *ctx;
1100 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1104 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1105 if (!ctx->fallback_req)
1109 * Use 5 bits less than the max cq entries, that should give us around
1110 * 32 entries per hash list if totally full and uniformly spread.
1112 hash_bits = ilog2(p->cq_entries);
1116 ctx->cancel_hash_bits = hash_bits;
1117 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1119 if (!ctx->cancel_hash)
1121 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1123 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1124 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1127 ctx->flags = p->flags;
1128 init_waitqueue_head(&ctx->sqo_sq_wait);
1129 INIT_LIST_HEAD(&ctx->sqd_list);
1130 init_waitqueue_head(&ctx->cq_wait);
1131 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1132 init_completion(&ctx->ref_comp);
1133 init_completion(&ctx->sq_thread_comp);
1134 idr_init(&ctx->io_buffer_idr);
1135 idr_init(&ctx->personality_idr);
1136 mutex_init(&ctx->uring_lock);
1137 init_waitqueue_head(&ctx->wait);
1138 spin_lock_init(&ctx->completion_lock);
1139 INIT_LIST_HEAD(&ctx->iopoll_list);
1140 INIT_LIST_HEAD(&ctx->defer_list);
1141 INIT_LIST_HEAD(&ctx->timeout_list);
1142 init_waitqueue_head(&ctx->inflight_wait);
1143 spin_lock_init(&ctx->inflight_lock);
1144 INIT_LIST_HEAD(&ctx->inflight_list);
1145 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1146 init_llist_head(&ctx->file_put_llist);
1149 if (ctx->fallback_req)
1150 kmem_cache_free(req_cachep, ctx->fallback_req);
1151 kfree(ctx->cancel_hash);
1156 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1158 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1159 struct io_ring_ctx *ctx = req->ctx;
1161 return seq != ctx->cached_cq_tail
1162 + atomic_read(&ctx->cached_cq_overflow);
1168 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1170 struct io_rings *rings = ctx->rings;
1172 /* order cqe stores with ring update */
1173 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1175 if (wq_has_sleeper(&ctx->cq_wait)) {
1176 wake_up_interruptible(&ctx->cq_wait);
1177 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1181 static void io_req_clean_work(struct io_kiocb *req)
1183 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1186 req->flags &= ~REQ_F_WORK_INITIALIZED;
1189 mmdrop(req->work.mm);
1190 req->work.mm = NULL;
1192 #ifdef CONFIG_BLK_CGROUP
1193 if (req->work.blkcg_css)
1194 css_put(req->work.blkcg_css);
1196 if (req->work.creds) {
1197 put_cred(req->work.creds);
1198 req->work.creds = NULL;
1201 struct fs_struct *fs = req->work.fs;
1203 spin_lock(&req->work.fs->lock);
1206 spin_unlock(&req->work.fs->lock);
1209 req->work.fs = NULL;
1213 static void io_prep_async_work(struct io_kiocb *req)
1215 const struct io_op_def *def = &io_op_defs[req->opcode];
1216 struct io_ring_ctx *ctx = req->ctx;
1218 io_req_init_async(req);
1220 if (req->flags & REQ_F_ISREG) {
1221 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1222 io_wq_hash_work(&req->work, file_inode(req->file));
1224 if (def->unbound_nonreg_file)
1225 req->work.flags |= IO_WQ_WORK_UNBOUND;
1227 if (!req->work.files && io_op_defs[req->opcode].file_table &&
1228 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1229 req->work.files = get_files_struct(current);
1230 get_nsproxy(current->nsproxy);
1231 req->work.nsproxy = current->nsproxy;
1232 req->flags |= REQ_F_INFLIGHT;
1234 spin_lock_irq(&ctx->inflight_lock);
1235 list_add(&req->inflight_entry, &ctx->inflight_list);
1236 spin_unlock_irq(&ctx->inflight_lock);
1238 if (!req->work.mm && def->needs_mm) {
1239 mmgrab(current->mm);
1240 req->work.mm = current->mm;
1242 #ifdef CONFIG_BLK_CGROUP
1243 if (!req->work.blkcg_css && def->needs_blkcg) {
1245 req->work.blkcg_css = blkcg_css();
1247 * This should be rare, either the cgroup is dying or the task
1248 * is moving cgroups. Just punt to root for the handful of ios.
1250 if (!css_tryget_online(req->work.blkcg_css))
1251 req->work.blkcg_css = NULL;
1255 if (!req->work.creds)
1256 req->work.creds = get_current_cred();
1257 if (!req->work.fs && def->needs_fs) {
1258 spin_lock(¤t->fs->lock);
1259 if (!current->fs->in_exec) {
1260 req->work.fs = current->fs;
1261 req->work.fs->users++;
1263 req->work.flags |= IO_WQ_WORK_CANCEL;
1265 spin_unlock(¤t->fs->lock);
1267 if (def->needs_fsize)
1268 req->work.fsize = rlimit(RLIMIT_FSIZE);
1270 req->work.fsize = RLIM_INFINITY;
1273 static void io_prep_async_link(struct io_kiocb *req)
1275 struct io_kiocb *cur;
1277 io_prep_async_work(req);
1278 if (req->flags & REQ_F_LINK_HEAD)
1279 list_for_each_entry(cur, &req->link_list, link_list)
1280 io_prep_async_work(cur);
1283 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1285 struct io_ring_ctx *ctx = req->ctx;
1286 struct io_kiocb *link = io_prep_linked_timeout(req);
1288 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1289 &req->work, req->flags);
1290 io_wq_enqueue(ctx->io_wq, &req->work);
1294 static void io_queue_async_work(struct io_kiocb *req)
1296 struct io_kiocb *link;
1298 /* init ->work of the whole link before punting */
1299 io_prep_async_link(req);
1300 link = __io_queue_async_work(req);
1303 io_queue_linked_timeout(link);
1306 static void io_kill_timeout(struct io_kiocb *req)
1308 struct io_timeout_data *io = req->async_data;
1311 ret = hrtimer_try_to_cancel(&io->timer);
1313 atomic_set(&req->ctx->cq_timeouts,
1314 atomic_read(&req->ctx->cq_timeouts) + 1);
1315 list_del_init(&req->timeout.list);
1316 io_cqring_fill_event(req, 0);
1317 io_put_req_deferred(req, 1);
1321 static bool io_task_match(struct io_kiocb *req, struct task_struct *tsk)
1323 struct io_ring_ctx *ctx = req->ctx;
1325 if (!tsk || req->task == tsk)
1327 if (ctx->flags & IORING_SETUP_SQPOLL) {
1328 if (ctx->sq_data && req->task == ctx->sq_data->thread)
1335 * Returns true if we found and killed one or more timeouts
1337 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk)
1339 struct io_kiocb *req, *tmp;
1342 spin_lock_irq(&ctx->completion_lock);
1343 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1344 if (io_task_match(req, tsk)) {
1345 io_kill_timeout(req);
1349 spin_unlock_irq(&ctx->completion_lock);
1350 return canceled != 0;
1353 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1356 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1357 struct io_defer_entry, list);
1358 struct io_kiocb *link;
1360 if (req_need_defer(de->req, de->seq))
1362 list_del_init(&de->list);
1363 /* punt-init is done before queueing for defer */
1364 link = __io_queue_async_work(de->req);
1366 __io_queue_linked_timeout(link);
1367 /* drop submission reference */
1368 io_put_req_deferred(link, 1);
1371 } while (!list_empty(&ctx->defer_list));
1374 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1376 while (!list_empty(&ctx->timeout_list)) {
1377 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1378 struct io_kiocb, timeout.list);
1380 if (io_is_timeout_noseq(req))
1382 if (req->timeout.target_seq != ctx->cached_cq_tail
1383 - atomic_read(&ctx->cq_timeouts))
1386 list_del_init(&req->timeout.list);
1387 io_kill_timeout(req);
1391 static void io_commit_cqring(struct io_ring_ctx *ctx)
1393 io_flush_timeouts(ctx);
1394 __io_commit_cqring(ctx);
1396 if (unlikely(!list_empty(&ctx->defer_list)))
1397 __io_queue_deferred(ctx);
1400 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1402 struct io_rings *r = ctx->rings;
1404 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1407 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1409 struct io_rings *rings = ctx->rings;
1412 tail = ctx->cached_cq_tail;
1414 * writes to the cq entry need to come after reading head; the
1415 * control dependency is enough as we're using WRITE_ONCE to
1418 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1421 ctx->cached_cq_tail++;
1422 return &rings->cqes[tail & ctx->cq_mask];
1425 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1429 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1431 if (!ctx->eventfd_async)
1433 return io_wq_current_is_worker();
1436 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1438 if (waitqueue_active(&ctx->wait))
1439 wake_up(&ctx->wait);
1440 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1441 wake_up(&ctx->sq_data->wait);
1442 if (io_should_trigger_evfd(ctx))
1443 eventfd_signal(ctx->cq_ev_fd, 1);
1446 static void io_cqring_mark_overflow(struct io_ring_ctx *ctx)
1448 if (list_empty(&ctx->cq_overflow_list)) {
1449 clear_bit(0, &ctx->sq_check_overflow);
1450 clear_bit(0, &ctx->cq_check_overflow);
1451 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1455 static inline bool io_match_files(struct io_kiocb *req,
1456 struct files_struct *files)
1460 if (req->flags & REQ_F_WORK_INITIALIZED)
1461 return req->work.files == files;
1465 /* Returns true if there are no backlogged entries after the flush */
1466 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1467 struct task_struct *tsk,
1468 struct files_struct *files)
1470 struct io_rings *rings = ctx->rings;
1471 struct io_kiocb *req, *tmp;
1472 struct io_uring_cqe *cqe;
1473 unsigned long flags;
1477 if (list_empty_careful(&ctx->cq_overflow_list))
1479 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1480 rings->cq_ring_entries))
1484 spin_lock_irqsave(&ctx->completion_lock, flags);
1486 /* if force is set, the ring is going away. always drop after that */
1488 ctx->cq_overflow_flushed = 1;
1491 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1492 if (tsk && req->task != tsk)
1494 if (!io_match_files(req, files))
1497 cqe = io_get_cqring(ctx);
1501 list_move(&req->compl.list, &list);
1503 WRITE_ONCE(cqe->user_data, req->user_data);
1504 WRITE_ONCE(cqe->res, req->result);
1505 WRITE_ONCE(cqe->flags, req->compl.cflags);
1507 WRITE_ONCE(ctx->rings->cq_overflow,
1508 atomic_inc_return(&ctx->cached_cq_overflow));
1512 io_commit_cqring(ctx);
1513 io_cqring_mark_overflow(ctx);
1515 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1516 io_cqring_ev_posted(ctx);
1518 while (!list_empty(&list)) {
1519 req = list_first_entry(&list, struct io_kiocb, compl.list);
1520 list_del(&req->compl.list);
1527 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1529 struct io_ring_ctx *ctx = req->ctx;
1530 struct io_uring_cqe *cqe;
1532 trace_io_uring_complete(ctx, req->user_data, res);
1535 * If we can't get a cq entry, userspace overflowed the
1536 * submission (by quite a lot). Increment the overflow count in
1539 cqe = io_get_cqring(ctx);
1541 WRITE_ONCE(cqe->user_data, req->user_data);
1542 WRITE_ONCE(cqe->res, res);
1543 WRITE_ONCE(cqe->flags, cflags);
1544 } else if (ctx->cq_overflow_flushed || req->task->io_uring->in_idle) {
1546 * If we're in ring overflow flush mode, or in task cancel mode,
1547 * then we cannot store the request for later flushing, we need
1548 * to drop it on the floor.
1550 WRITE_ONCE(ctx->rings->cq_overflow,
1551 atomic_inc_return(&ctx->cached_cq_overflow));
1553 if (list_empty(&ctx->cq_overflow_list)) {
1554 set_bit(0, &ctx->sq_check_overflow);
1555 set_bit(0, &ctx->cq_check_overflow);
1556 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1560 req->compl.cflags = cflags;
1561 refcount_inc(&req->refs);
1562 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1566 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1568 __io_cqring_fill_event(req, res, 0);
1571 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1573 struct io_ring_ctx *ctx = req->ctx;
1574 unsigned long flags;
1576 spin_lock_irqsave(&ctx->completion_lock, flags);
1577 __io_cqring_fill_event(req, res, cflags);
1578 io_commit_cqring(ctx);
1579 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1581 io_cqring_ev_posted(ctx);
1584 static void io_submit_flush_completions(struct io_comp_state *cs)
1586 struct io_ring_ctx *ctx = cs->ctx;
1588 spin_lock_irq(&ctx->completion_lock);
1589 while (!list_empty(&cs->list)) {
1590 struct io_kiocb *req;
1592 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1593 list_del(&req->compl.list);
1594 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1597 * io_free_req() doesn't care about completion_lock unless one
1598 * of these flags is set. REQ_F_WORK_INITIALIZED is in the list
1599 * because of a potential deadlock with req->work.fs->lock
1601 if (req->flags & (REQ_F_FAIL_LINK|REQ_F_LINK_TIMEOUT
1602 |REQ_F_WORK_INITIALIZED)) {
1603 spin_unlock_irq(&ctx->completion_lock);
1605 spin_lock_irq(&ctx->completion_lock);
1610 io_commit_cqring(ctx);
1611 spin_unlock_irq(&ctx->completion_lock);
1613 io_cqring_ev_posted(ctx);
1617 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1618 struct io_comp_state *cs)
1621 io_cqring_add_event(req, res, cflags);
1626 req->compl.cflags = cflags;
1627 list_add_tail(&req->compl.list, &cs->list);
1629 io_submit_flush_completions(cs);
1633 static void io_req_complete(struct io_kiocb *req, long res)
1635 __io_req_complete(req, res, 0, NULL);
1638 static inline bool io_is_fallback_req(struct io_kiocb *req)
1640 return req == (struct io_kiocb *)
1641 ((unsigned long) req->ctx->fallback_req & ~1UL);
1644 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1646 struct io_kiocb *req;
1648 req = ctx->fallback_req;
1649 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1655 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1656 struct io_submit_state *state)
1658 if (!state->free_reqs) {
1659 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1663 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1664 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1667 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1668 * retry single alloc to be on the safe side.
1670 if (unlikely(ret <= 0)) {
1671 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1672 if (!state->reqs[0])
1676 state->free_reqs = ret;
1680 return state->reqs[state->free_reqs];
1682 return io_get_fallback_req(ctx);
1685 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1689 percpu_ref_put(req->fixed_file_refs);
1694 static void io_dismantle_req(struct io_kiocb *req)
1698 if (req->async_data)
1699 kfree(req->async_data);
1701 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1703 io_req_clean_work(req);
1706 static void __io_free_req(struct io_kiocb *req)
1708 struct io_uring_task *tctx;
1709 struct io_ring_ctx *ctx;
1711 io_dismantle_req(req);
1712 tctx = req->task->io_uring;
1715 atomic_long_inc(&tctx->req_complete);
1717 wake_up(&tctx->wait);
1718 put_task_struct(req->task);
1720 if (likely(!io_is_fallback_req(req)))
1721 kmem_cache_free(req_cachep, req);
1723 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
1724 percpu_ref_put(&ctx->refs);
1727 static bool io_link_cancel_timeout(struct io_kiocb *req)
1729 struct io_timeout_data *io = req->async_data;
1730 struct io_ring_ctx *ctx = req->ctx;
1733 ret = hrtimer_try_to_cancel(&io->timer);
1735 io_cqring_fill_event(req, -ECANCELED);
1736 io_commit_cqring(ctx);
1737 req->flags &= ~REQ_F_LINK_HEAD;
1738 io_put_req_deferred(req, 1);
1745 static bool __io_kill_linked_timeout(struct io_kiocb *req)
1747 struct io_kiocb *link;
1750 if (list_empty(&req->link_list))
1752 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1753 if (link->opcode != IORING_OP_LINK_TIMEOUT)
1756 list_del_init(&link->link_list);
1757 wake_ev = io_link_cancel_timeout(link);
1758 req->flags &= ~REQ_F_LINK_TIMEOUT;
1762 static void io_kill_linked_timeout(struct io_kiocb *req)
1764 struct io_ring_ctx *ctx = req->ctx;
1765 unsigned long flags;
1768 spin_lock_irqsave(&ctx->completion_lock, flags);
1769 wake_ev = __io_kill_linked_timeout(req);
1770 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1773 io_cqring_ev_posted(ctx);
1776 static struct io_kiocb *io_req_link_next(struct io_kiocb *req)
1778 struct io_kiocb *nxt;
1781 * The list should never be empty when we are called here. But could
1782 * potentially happen if the chain is messed up, check to be on the
1785 if (unlikely(list_empty(&req->link_list)))
1788 nxt = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1789 list_del_init(&req->link_list);
1790 if (!list_empty(&nxt->link_list))
1791 nxt->flags |= REQ_F_LINK_HEAD;
1796 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1798 static void __io_fail_links(struct io_kiocb *req)
1800 struct io_ring_ctx *ctx = req->ctx;
1802 while (!list_empty(&req->link_list)) {
1803 struct io_kiocb *link = list_first_entry(&req->link_list,
1804 struct io_kiocb, link_list);
1806 list_del_init(&link->link_list);
1807 trace_io_uring_fail_link(req, link);
1809 io_cqring_fill_event(link, -ECANCELED);
1812 * It's ok to free under spinlock as they're not linked anymore,
1813 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
1816 if (link->flags & REQ_F_WORK_INITIALIZED)
1817 io_put_req_deferred(link, 2);
1819 io_double_put_req(link);
1822 io_commit_cqring(ctx);
1825 static void io_fail_links(struct io_kiocb *req)
1827 struct io_ring_ctx *ctx = req->ctx;
1828 unsigned long flags;
1830 spin_lock_irqsave(&ctx->completion_lock, flags);
1831 __io_fail_links(req);
1832 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1834 io_cqring_ev_posted(ctx);
1837 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1839 req->flags &= ~REQ_F_LINK_HEAD;
1840 if (req->flags & REQ_F_LINK_TIMEOUT)
1841 io_kill_linked_timeout(req);
1844 * If LINK is set, we have dependent requests in this chain. If we
1845 * didn't fail this request, queue the first one up, moving any other
1846 * dependencies to the next request. In case of failure, fail the rest
1849 if (likely(!(req->flags & REQ_F_FAIL_LINK)))
1850 return io_req_link_next(req);
1855 static struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1857 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1859 return __io_req_find_next(req);
1862 static int io_req_task_work_add(struct io_kiocb *req, bool twa_signal_ok)
1864 struct task_struct *tsk = req->task;
1865 struct io_ring_ctx *ctx = req->ctx;
1868 if (tsk->flags & PF_EXITING)
1872 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1873 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1874 * processing task_work. There's no reliable way to tell if TWA_RESUME
1878 if (!(ctx->flags & IORING_SETUP_SQPOLL) && twa_signal_ok)
1879 notify = TWA_SIGNAL;
1881 ret = task_work_add(tsk, &req->task_work, notify);
1883 wake_up_process(tsk);
1888 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1890 struct io_ring_ctx *ctx = req->ctx;
1892 spin_lock_irq(&ctx->completion_lock);
1893 io_cqring_fill_event(req, error);
1894 io_commit_cqring(ctx);
1895 spin_unlock_irq(&ctx->completion_lock);
1897 io_cqring_ev_posted(ctx);
1898 req_set_fail_links(req);
1899 io_double_put_req(req);
1902 static void io_req_task_cancel(struct callback_head *cb)
1904 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1905 struct io_ring_ctx *ctx = req->ctx;
1907 __io_req_task_cancel(req, -ECANCELED);
1908 percpu_ref_put(&ctx->refs);
1911 static void __io_req_task_submit(struct io_kiocb *req)
1913 struct io_ring_ctx *ctx = req->ctx;
1915 if (!__io_sq_thread_acquire_mm(ctx)) {
1916 mutex_lock(&ctx->uring_lock);
1917 __io_queue_sqe(req, NULL);
1918 mutex_unlock(&ctx->uring_lock);
1920 __io_req_task_cancel(req, -EFAULT);
1924 static void io_req_task_submit(struct callback_head *cb)
1926 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1927 struct io_ring_ctx *ctx = req->ctx;
1929 __io_req_task_submit(req);
1930 percpu_ref_put(&ctx->refs);
1933 static void io_req_task_queue(struct io_kiocb *req)
1937 init_task_work(&req->task_work, io_req_task_submit);
1938 percpu_ref_get(&req->ctx->refs);
1940 ret = io_req_task_work_add(req, true);
1941 if (unlikely(ret)) {
1942 struct task_struct *tsk;
1944 init_task_work(&req->task_work, io_req_task_cancel);
1945 tsk = io_wq_get_task(req->ctx->io_wq);
1946 task_work_add(tsk, &req->task_work, 0);
1947 wake_up_process(tsk);
1951 static void io_queue_next(struct io_kiocb *req)
1953 struct io_kiocb *nxt = io_req_find_next(req);
1956 io_req_task_queue(nxt);
1959 static void io_free_req(struct io_kiocb *req)
1966 void *reqs[IO_IOPOLL_BATCH];
1969 struct task_struct *task;
1973 static inline void io_init_req_batch(struct req_batch *rb)
1980 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
1981 struct req_batch *rb)
1983 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1984 percpu_ref_put_many(&ctx->refs, rb->to_free);
1988 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
1989 struct req_batch *rb)
1992 __io_req_free_batch_flush(ctx, rb);
1994 atomic_long_add(rb->task_refs, &rb->task->io_uring->req_complete);
1995 put_task_struct_many(rb->task, rb->task_refs);
2000 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
2002 if (unlikely(io_is_fallback_req(req))) {
2006 if (req->flags & REQ_F_LINK_HEAD)
2009 if (req->task != rb->task) {
2011 atomic_long_add(rb->task_refs, &rb->task->io_uring->req_complete);
2012 put_task_struct_many(rb->task, rb->task_refs);
2014 rb->task = req->task;
2019 io_dismantle_req(req);
2020 rb->reqs[rb->to_free++] = req;
2021 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
2022 __io_req_free_batch_flush(req->ctx, rb);
2026 * Drop reference to request, return next in chain (if there is one) if this
2027 * was the last reference to this request.
2029 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2031 struct io_kiocb *nxt = NULL;
2033 if (refcount_dec_and_test(&req->refs)) {
2034 nxt = io_req_find_next(req);
2040 static void io_put_req(struct io_kiocb *req)
2042 if (refcount_dec_and_test(&req->refs))
2046 static void io_put_req_deferred_cb(struct callback_head *cb)
2048 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2053 static void io_free_req_deferred(struct io_kiocb *req)
2057 init_task_work(&req->task_work, io_put_req_deferred_cb);
2058 ret = io_req_task_work_add(req, true);
2059 if (unlikely(ret)) {
2060 struct task_struct *tsk;
2062 tsk = io_wq_get_task(req->ctx->io_wq);
2063 task_work_add(tsk, &req->task_work, 0);
2064 wake_up_process(tsk);
2068 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2070 if (refcount_sub_and_test(refs, &req->refs))
2071 io_free_req_deferred(req);
2074 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
2076 struct io_kiocb *nxt;
2079 * A ref is owned by io-wq in which context we're. So, if that's the
2080 * last one, it's safe to steal next work. False negatives are Ok,
2081 * it just will be re-punted async in io_put_work()
2083 if (refcount_read(&req->refs) != 1)
2086 nxt = io_req_find_next(req);
2087 return nxt ? &nxt->work : NULL;
2090 static void io_double_put_req(struct io_kiocb *req)
2092 /* drop both submit and complete references */
2093 if (refcount_sub_and_test(2, &req->refs))
2097 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
2099 struct io_rings *rings = ctx->rings;
2101 if (test_bit(0, &ctx->cq_check_overflow)) {
2103 * noflush == true is from the waitqueue handler, just ensure
2104 * we wake up the task, and the next invocation will flush the
2105 * entries. We cannot safely to it from here.
2107 if (noflush && !list_empty(&ctx->cq_overflow_list))
2110 io_cqring_overflow_flush(ctx, false, NULL, NULL);
2113 /* See comment at the top of this file */
2115 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
2118 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2120 struct io_rings *rings = ctx->rings;
2122 /* make sure SQ entry isn't read before tail */
2123 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2126 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2128 unsigned int cflags;
2130 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2131 cflags |= IORING_CQE_F_BUFFER;
2132 req->flags &= ~REQ_F_BUFFER_SELECTED;
2137 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2139 struct io_buffer *kbuf;
2141 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2142 return io_put_kbuf(req, kbuf);
2145 static inline bool io_run_task_work(void)
2148 * Not safe to run on exiting task, and the task_work handling will
2149 * not add work to such a task.
2151 if (unlikely(current->flags & PF_EXITING))
2153 if (current->task_works) {
2154 __set_current_state(TASK_RUNNING);
2162 static void io_iopoll_queue(struct list_head *again)
2164 struct io_kiocb *req;
2167 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2168 list_del(&req->inflight_entry);
2169 __io_complete_rw(req, -EAGAIN, 0, NULL);
2170 } while (!list_empty(again));
2174 * Find and free completed poll iocbs
2176 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2177 struct list_head *done)
2179 struct req_batch rb;
2180 struct io_kiocb *req;
2183 /* order with ->result store in io_complete_rw_iopoll() */
2186 io_init_req_batch(&rb);
2187 while (!list_empty(done)) {
2190 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2191 if (READ_ONCE(req->result) == -EAGAIN) {
2193 req->iopoll_completed = 0;
2194 list_move_tail(&req->inflight_entry, &again);
2197 list_del(&req->inflight_entry);
2199 if (req->flags & REQ_F_BUFFER_SELECTED)
2200 cflags = io_put_rw_kbuf(req);
2202 __io_cqring_fill_event(req, req->result, cflags);
2205 if (refcount_dec_and_test(&req->refs))
2206 io_req_free_batch(&rb, req);
2209 io_commit_cqring(ctx);
2210 if (ctx->flags & IORING_SETUP_SQPOLL)
2211 io_cqring_ev_posted(ctx);
2212 io_req_free_batch_finish(ctx, &rb);
2214 if (!list_empty(&again))
2215 io_iopoll_queue(&again);
2218 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2221 struct io_kiocb *req, *tmp;
2227 * Only spin for completions if we don't have multiple devices hanging
2228 * off our complete list, and we're under the requested amount.
2230 spin = !ctx->poll_multi_file && *nr_events < min;
2233 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2234 struct kiocb *kiocb = &req->rw.kiocb;
2237 * Move completed and retryable entries to our local lists.
2238 * If we find a request that requires polling, break out
2239 * and complete those lists first, if we have entries there.
2241 if (READ_ONCE(req->iopoll_completed)) {
2242 list_move_tail(&req->inflight_entry, &done);
2245 if (!list_empty(&done))
2248 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2252 /* iopoll may have completed current req */
2253 if (READ_ONCE(req->iopoll_completed))
2254 list_move_tail(&req->inflight_entry, &done);
2261 if (!list_empty(&done))
2262 io_iopoll_complete(ctx, nr_events, &done);
2268 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2269 * non-spinning poll check - we'll still enter the driver poll loop, but only
2270 * as a non-spinning completion check.
2272 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2275 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2278 ret = io_do_iopoll(ctx, nr_events, min);
2281 if (*nr_events >= min)
2289 * We can't just wait for polled events to come to us, we have to actively
2290 * find and complete them.
2292 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2294 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2297 mutex_lock(&ctx->uring_lock);
2298 while (!list_empty(&ctx->iopoll_list)) {
2299 unsigned int nr_events = 0;
2301 io_do_iopoll(ctx, &nr_events, 0);
2303 /* let it sleep and repeat later if can't complete a request */
2307 * Ensure we allow local-to-the-cpu processing to take place,
2308 * in this case we need to ensure that we reap all events.
2309 * Also let task_work, etc. to progress by releasing the mutex
2311 if (need_resched()) {
2312 mutex_unlock(&ctx->uring_lock);
2314 mutex_lock(&ctx->uring_lock);
2317 mutex_unlock(&ctx->uring_lock);
2320 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2322 unsigned int nr_events = 0;
2323 int iters = 0, ret = 0;
2326 * We disallow the app entering submit/complete with polling, but we
2327 * still need to lock the ring to prevent racing with polled issue
2328 * that got punted to a workqueue.
2330 mutex_lock(&ctx->uring_lock);
2333 * Don't enter poll loop if we already have events pending.
2334 * If we do, we can potentially be spinning for commands that
2335 * already triggered a CQE (eg in error).
2337 if (io_cqring_events(ctx, false))
2341 * If a submit got punted to a workqueue, we can have the
2342 * application entering polling for a command before it gets
2343 * issued. That app will hold the uring_lock for the duration
2344 * of the poll right here, so we need to take a breather every
2345 * now and then to ensure that the issue has a chance to add
2346 * the poll to the issued list. Otherwise we can spin here
2347 * forever, while the workqueue is stuck trying to acquire the
2350 if (!(++iters & 7)) {
2351 mutex_unlock(&ctx->uring_lock);
2353 mutex_lock(&ctx->uring_lock);
2356 ret = io_iopoll_getevents(ctx, &nr_events, min);
2360 } while (min && !nr_events && !need_resched());
2362 mutex_unlock(&ctx->uring_lock);
2366 static void kiocb_end_write(struct io_kiocb *req)
2369 * Tell lockdep we inherited freeze protection from submission
2372 if (req->flags & REQ_F_ISREG) {
2373 struct inode *inode = file_inode(req->file);
2375 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2377 file_end_write(req->file);
2380 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2381 struct io_comp_state *cs)
2383 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2386 if (kiocb->ki_flags & IOCB_WRITE)
2387 kiocb_end_write(req);
2389 if (res != req->result)
2390 req_set_fail_links(req);
2391 if (req->flags & REQ_F_BUFFER_SELECTED)
2392 cflags = io_put_rw_kbuf(req);
2393 __io_req_complete(req, res, cflags, cs);
2397 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2399 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2400 ssize_t ret = -ECANCELED;
2401 struct iov_iter iter;
2409 switch (req->opcode) {
2410 case IORING_OP_READV:
2411 case IORING_OP_READ_FIXED:
2412 case IORING_OP_READ:
2415 case IORING_OP_WRITEV:
2416 case IORING_OP_WRITE_FIXED:
2417 case IORING_OP_WRITE:
2421 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2426 if (!req->async_data) {
2427 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2430 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2438 req_set_fail_links(req);
2439 io_req_complete(req, ret);
2444 static bool io_rw_reissue(struct io_kiocb *req, long res)
2447 umode_t mode = file_inode(req->file)->i_mode;
2450 if (!S_ISBLK(mode) && !S_ISREG(mode))
2452 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2455 ret = io_sq_thread_acquire_mm(req->ctx, req);
2457 if (io_resubmit_prep(req, ret)) {
2458 refcount_inc(&req->refs);
2459 io_queue_async_work(req);
2467 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2468 struct io_comp_state *cs)
2470 if (!io_rw_reissue(req, res))
2471 io_complete_rw_common(&req->rw.kiocb, res, cs);
2474 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2476 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2478 __io_complete_rw(req, res, res2, NULL);
2481 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2483 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2485 if (kiocb->ki_flags & IOCB_WRITE)
2486 kiocb_end_write(req);
2488 if (res != -EAGAIN && res != req->result)
2489 req_set_fail_links(req);
2491 WRITE_ONCE(req->result, res);
2492 /* order with io_poll_complete() checking ->result */
2494 WRITE_ONCE(req->iopoll_completed, 1);
2498 * After the iocb has been issued, it's safe to be found on the poll list.
2499 * Adding the kiocb to the list AFTER submission ensures that we don't
2500 * find it from a io_iopoll_getevents() thread before the issuer is done
2501 * accessing the kiocb cookie.
2503 static void io_iopoll_req_issued(struct io_kiocb *req)
2505 struct io_ring_ctx *ctx = req->ctx;
2508 * Track whether we have multiple files in our lists. This will impact
2509 * how we do polling eventually, not spinning if we're on potentially
2510 * different devices.
2512 if (list_empty(&ctx->iopoll_list)) {
2513 ctx->poll_multi_file = false;
2514 } else if (!ctx->poll_multi_file) {
2515 struct io_kiocb *list_req;
2517 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2519 if (list_req->file != req->file)
2520 ctx->poll_multi_file = true;
2524 * For fast devices, IO may have already completed. If it has, add
2525 * it to the front so we find it first.
2527 if (READ_ONCE(req->iopoll_completed))
2528 list_add(&req->inflight_entry, &ctx->iopoll_list);
2530 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2532 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2533 wq_has_sleeper(&ctx->sq_data->wait))
2534 wake_up(&ctx->sq_data->wait);
2537 static void __io_state_file_put(struct io_submit_state *state)
2539 if (state->has_refs)
2540 fput_many(state->file, state->has_refs);
2544 static inline void io_state_file_put(struct io_submit_state *state)
2547 __io_state_file_put(state);
2551 * Get as many references to a file as we have IOs left in this submission,
2552 * assuming most submissions are for one file, or at least that each file
2553 * has more than one submission.
2555 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2561 if (state->fd == fd) {
2565 __io_state_file_put(state);
2567 state->file = fget_many(fd, state->ios_left);
2572 state->has_refs = state->ios_left - 1;
2576 static bool io_bdev_nowait(struct block_device *bdev)
2579 return !bdev || queue_is_mq(bdev_get_queue(bdev));
2586 * If we tracked the file through the SCM inflight mechanism, we could support
2587 * any file. For now, just ensure that anything potentially problematic is done
2590 static bool io_file_supports_async(struct file *file, int rw)
2592 umode_t mode = file_inode(file)->i_mode;
2594 if (S_ISBLK(mode)) {
2595 if (io_bdev_nowait(file->f_inode->i_bdev))
2599 if (S_ISCHR(mode) || S_ISSOCK(mode))
2601 if (S_ISREG(mode)) {
2602 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2603 file->f_op != &io_uring_fops)
2608 /* any ->read/write should understand O_NONBLOCK */
2609 if (file->f_flags & O_NONBLOCK)
2612 if (!(file->f_mode & FMODE_NOWAIT))
2616 return file->f_op->read_iter != NULL;
2618 return file->f_op->write_iter != NULL;
2621 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2623 struct io_ring_ctx *ctx = req->ctx;
2624 struct kiocb *kiocb = &req->rw.kiocb;
2628 if (S_ISREG(file_inode(req->file)->i_mode))
2629 req->flags |= REQ_F_ISREG;
2631 kiocb->ki_pos = READ_ONCE(sqe->off);
2632 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2633 req->flags |= REQ_F_CUR_POS;
2634 kiocb->ki_pos = req->file->f_pos;
2636 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2637 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2638 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2642 ioprio = READ_ONCE(sqe->ioprio);
2644 ret = ioprio_check_cap(ioprio);
2648 kiocb->ki_ioprio = ioprio;
2650 kiocb->ki_ioprio = get_current_ioprio();
2652 /* don't allow async punt if RWF_NOWAIT was requested */
2653 if (kiocb->ki_flags & IOCB_NOWAIT)
2654 req->flags |= REQ_F_NOWAIT;
2656 if (ctx->flags & IORING_SETUP_IOPOLL) {
2657 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2658 !kiocb->ki_filp->f_op->iopoll)
2661 kiocb->ki_flags |= IOCB_HIPRI;
2662 kiocb->ki_complete = io_complete_rw_iopoll;
2663 req->iopoll_completed = 0;
2665 if (kiocb->ki_flags & IOCB_HIPRI)
2667 kiocb->ki_complete = io_complete_rw;
2670 req->rw.addr = READ_ONCE(sqe->addr);
2671 req->rw.len = READ_ONCE(sqe->len);
2672 req->buf_index = READ_ONCE(sqe->buf_index);
2676 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2682 case -ERESTARTNOINTR:
2683 case -ERESTARTNOHAND:
2684 case -ERESTART_RESTARTBLOCK:
2686 * We can't just restart the syscall, since previously
2687 * submitted sqes may already be in progress. Just fail this
2693 kiocb->ki_complete(kiocb, ret, 0);
2697 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2698 struct io_comp_state *cs)
2700 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2701 struct io_async_rw *io = req->async_data;
2703 /* add previously done IO, if any */
2704 if (io && io->bytes_done > 0) {
2706 ret = io->bytes_done;
2708 ret += io->bytes_done;
2711 if (req->flags & REQ_F_CUR_POS)
2712 req->file->f_pos = kiocb->ki_pos;
2713 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2714 __io_complete_rw(req, ret, 0, cs);
2716 io_rw_done(kiocb, ret);
2719 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2720 struct iov_iter *iter)
2722 struct io_ring_ctx *ctx = req->ctx;
2723 size_t len = req->rw.len;
2724 struct io_mapped_ubuf *imu;
2725 u16 index, buf_index = req->buf_index;
2729 if (unlikely(buf_index >= ctx->nr_user_bufs))
2731 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2732 imu = &ctx->user_bufs[index];
2733 buf_addr = req->rw.addr;
2736 if (buf_addr + len < buf_addr)
2738 /* not inside the mapped region */
2739 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2743 * May not be a start of buffer, set size appropriately
2744 * and advance us to the beginning.
2746 offset = buf_addr - imu->ubuf;
2747 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2751 * Don't use iov_iter_advance() here, as it's really slow for
2752 * using the latter parts of a big fixed buffer - it iterates
2753 * over each segment manually. We can cheat a bit here, because
2756 * 1) it's a BVEC iter, we set it up
2757 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2758 * first and last bvec
2760 * So just find our index, and adjust the iterator afterwards.
2761 * If the offset is within the first bvec (or the whole first
2762 * bvec, just use iov_iter_advance(). This makes it easier
2763 * since we can just skip the first segment, which may not
2764 * be PAGE_SIZE aligned.
2766 const struct bio_vec *bvec = imu->bvec;
2768 if (offset <= bvec->bv_len) {
2769 iov_iter_advance(iter, offset);
2771 unsigned long seg_skip;
2773 /* skip first vec */
2774 offset -= bvec->bv_len;
2775 seg_skip = 1 + (offset >> PAGE_SHIFT);
2777 iter->bvec = bvec + seg_skip;
2778 iter->nr_segs -= seg_skip;
2779 iter->count -= bvec->bv_len + offset;
2780 iter->iov_offset = offset & ~PAGE_MASK;
2787 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2790 mutex_unlock(&ctx->uring_lock);
2793 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2796 * "Normal" inline submissions always hold the uring_lock, since we
2797 * grab it from the system call. Same is true for the SQPOLL offload.
2798 * The only exception is when we've detached the request and issue it
2799 * from an async worker thread, grab the lock for that case.
2802 mutex_lock(&ctx->uring_lock);
2805 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2806 int bgid, struct io_buffer *kbuf,
2809 struct io_buffer *head;
2811 if (req->flags & REQ_F_BUFFER_SELECTED)
2814 io_ring_submit_lock(req->ctx, needs_lock);
2816 lockdep_assert_held(&req->ctx->uring_lock);
2818 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2820 if (!list_empty(&head->list)) {
2821 kbuf = list_last_entry(&head->list, struct io_buffer,
2823 list_del(&kbuf->list);
2826 idr_remove(&req->ctx->io_buffer_idr, bgid);
2828 if (*len > kbuf->len)
2831 kbuf = ERR_PTR(-ENOBUFS);
2834 io_ring_submit_unlock(req->ctx, needs_lock);
2839 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2842 struct io_buffer *kbuf;
2845 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2846 bgid = req->buf_index;
2847 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2850 req->rw.addr = (u64) (unsigned long) kbuf;
2851 req->flags |= REQ_F_BUFFER_SELECTED;
2852 return u64_to_user_ptr(kbuf->addr);
2855 #ifdef CONFIG_COMPAT
2856 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2859 struct compat_iovec __user *uiov;
2860 compat_ssize_t clen;
2864 uiov = u64_to_user_ptr(req->rw.addr);
2865 if (!access_ok(uiov, sizeof(*uiov)))
2867 if (__get_user(clen, &uiov->iov_len))
2873 buf = io_rw_buffer_select(req, &len, needs_lock);
2875 return PTR_ERR(buf);
2876 iov[0].iov_base = buf;
2877 iov[0].iov_len = (compat_size_t) len;
2882 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2885 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2889 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2892 len = iov[0].iov_len;
2895 buf = io_rw_buffer_select(req, &len, needs_lock);
2897 return PTR_ERR(buf);
2898 iov[0].iov_base = buf;
2899 iov[0].iov_len = len;
2903 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2906 if (req->flags & REQ_F_BUFFER_SELECTED) {
2907 struct io_buffer *kbuf;
2909 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2910 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2911 iov[0].iov_len = kbuf->len;
2916 else if (req->rw.len > 1)
2919 #ifdef CONFIG_COMPAT
2920 if (req->ctx->compat)
2921 return io_compat_import(req, iov, needs_lock);
2924 return __io_iov_buffer_select(req, iov, needs_lock);
2927 static ssize_t __io_import_iovec(int rw, struct io_kiocb *req,
2928 struct iovec **iovec, struct iov_iter *iter,
2931 void __user *buf = u64_to_user_ptr(req->rw.addr);
2932 size_t sqe_len = req->rw.len;
2936 opcode = req->opcode;
2937 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2939 return io_import_fixed(req, rw, iter);
2942 /* buffer index only valid with fixed read/write, or buffer select */
2943 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2946 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2947 if (req->flags & REQ_F_BUFFER_SELECT) {
2948 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2950 return PTR_ERR(buf);
2951 req->rw.len = sqe_len;
2954 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2956 return ret < 0 ? ret : sqe_len;
2959 if (req->flags & REQ_F_BUFFER_SELECT) {
2960 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2962 ret = (*iovec)->iov_len;
2963 iov_iter_init(iter, rw, *iovec, 1, ret);
2969 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
2973 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2974 struct iovec **iovec, struct iov_iter *iter,
2977 struct io_async_rw *iorw = req->async_data;
2980 return __io_import_iovec(rw, req, iovec, iter, needs_lock);
2982 return iov_iter_count(&iorw->iter);
2985 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2987 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2991 * For files that don't have ->read_iter() and ->write_iter(), handle them
2992 * by looping over ->read() or ->write() manually.
2994 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2995 struct iov_iter *iter)
3000 * Don't support polled IO through this interface, and we can't
3001 * support non-blocking either. For the latter, this just causes
3002 * the kiocb to be handled from an async context.
3004 if (kiocb->ki_flags & IOCB_HIPRI)
3006 if (kiocb->ki_flags & IOCB_NOWAIT)
3009 while (iov_iter_count(iter)) {
3013 if (!iov_iter_is_bvec(iter)) {
3014 iovec = iov_iter_iovec(iter);
3016 /* fixed buffers import bvec */
3017 iovec.iov_base = kmap(iter->bvec->bv_page)
3019 iovec.iov_len = min(iter->count,
3020 iter->bvec->bv_len - iter->iov_offset);
3024 nr = file->f_op->read(file, iovec.iov_base,
3025 iovec.iov_len, io_kiocb_ppos(kiocb));
3027 nr = file->f_op->write(file, iovec.iov_base,
3028 iovec.iov_len, io_kiocb_ppos(kiocb));
3031 if (iov_iter_is_bvec(iter))
3032 kunmap(iter->bvec->bv_page);
3040 if (nr != iovec.iov_len)
3042 iov_iter_advance(iter, nr);
3048 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3049 const struct iovec *fast_iov, struct iov_iter *iter)
3051 struct io_async_rw *rw = req->async_data;
3053 memcpy(&rw->iter, iter, sizeof(*iter));
3054 rw->free_iovec = iovec;
3056 /* can only be fixed buffers, no need to do anything */
3057 if (iter->type == ITER_BVEC)
3060 unsigned iov_off = 0;
3062 rw->iter.iov = rw->fast_iov;
3063 if (iter->iov != fast_iov) {
3064 iov_off = iter->iov - fast_iov;
3065 rw->iter.iov += iov_off;
3067 if (rw->fast_iov != fast_iov)
3068 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3069 sizeof(struct iovec) * iter->nr_segs);
3071 req->flags |= REQ_F_NEED_CLEANUP;
3075 static inline int __io_alloc_async_data(struct io_kiocb *req)
3077 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3078 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3079 return req->async_data == NULL;
3082 static int io_alloc_async_data(struct io_kiocb *req)
3084 if (!io_op_defs[req->opcode].needs_async_data)
3087 return __io_alloc_async_data(req);
3090 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3091 const struct iovec *fast_iov,
3092 struct iov_iter *iter, bool force)
3094 if (!force && !io_op_defs[req->opcode].needs_async_data)
3096 if (!req->async_data) {
3097 if (__io_alloc_async_data(req))
3100 io_req_map_rw(req, iovec, fast_iov, iter);
3105 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3107 struct io_async_rw *iorw = req->async_data;
3108 struct iovec *iov = iorw->fast_iov;
3111 ret = __io_import_iovec(rw, req, &iov, &iorw->iter, false);
3112 if (unlikely(ret < 0))
3115 iorw->bytes_done = 0;
3116 iorw->free_iovec = iov;
3118 req->flags |= REQ_F_NEED_CLEANUP;
3122 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3126 ret = io_prep_rw(req, sqe);
3130 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3133 /* either don't need iovec imported or already have it */
3134 if (!req->async_data)
3136 return io_rw_prep_async(req, READ);
3140 * This is our waitqueue callback handler, registered through lock_page_async()
3141 * when we initially tried to do the IO with the iocb armed our waitqueue.
3142 * This gets called when the page is unlocked, and we generally expect that to
3143 * happen when the page IO is completed and the page is now uptodate. This will
3144 * queue a task_work based retry of the operation, attempting to copy the data
3145 * again. If the latter fails because the page was NOT uptodate, then we will
3146 * do a thread based blocking retry of the operation. That's the unexpected
3149 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3150 int sync, void *arg)
3152 struct wait_page_queue *wpq;
3153 struct io_kiocb *req = wait->private;
3154 struct wait_page_key *key = arg;
3157 wpq = container_of(wait, struct wait_page_queue, wait);
3159 if (!wake_page_match(wpq, key))
3162 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3163 list_del_init(&wait->entry);
3165 init_task_work(&req->task_work, io_req_task_submit);
3166 percpu_ref_get(&req->ctx->refs);
3168 /* submit ref gets dropped, acquire a new one */
3169 refcount_inc(&req->refs);
3170 ret = io_req_task_work_add(req, true);
3171 if (unlikely(ret)) {
3172 struct task_struct *tsk;
3174 /* queue just for cancelation */
3175 init_task_work(&req->task_work, io_req_task_cancel);
3176 tsk = io_wq_get_task(req->ctx->io_wq);
3177 task_work_add(tsk, &req->task_work, 0);
3178 wake_up_process(tsk);
3184 * This controls whether a given IO request should be armed for async page
3185 * based retry. If we return false here, the request is handed to the async
3186 * worker threads for retry. If we're doing buffered reads on a regular file,
3187 * we prepare a private wait_page_queue entry and retry the operation. This
3188 * will either succeed because the page is now uptodate and unlocked, or it
3189 * will register a callback when the page is unlocked at IO completion. Through
3190 * that callback, io_uring uses task_work to setup a retry of the operation.
3191 * That retry will attempt the buffered read again. The retry will generally
3192 * succeed, or in rare cases where it fails, we then fall back to using the
3193 * async worker threads for a blocking retry.
3195 static bool io_rw_should_retry(struct io_kiocb *req)
3197 struct io_async_rw *rw = req->async_data;
3198 struct wait_page_queue *wait = &rw->wpq;
3199 struct kiocb *kiocb = &req->rw.kiocb;
3201 /* never retry for NOWAIT, we just complete with -EAGAIN */
3202 if (req->flags & REQ_F_NOWAIT)
3205 /* Only for buffered IO */
3206 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3210 * just use poll if we can, and don't attempt if the fs doesn't
3211 * support callback based unlocks
3213 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3216 wait->wait.func = io_async_buf_func;
3217 wait->wait.private = req;
3218 wait->wait.flags = 0;
3219 INIT_LIST_HEAD(&wait->wait.entry);
3220 kiocb->ki_flags |= IOCB_WAITQ;
3221 kiocb->ki_flags &= ~IOCB_NOWAIT;
3222 kiocb->ki_waitq = wait;
3226 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3228 if (req->file->f_op->read_iter)
3229 return call_read_iter(req->file, &req->rw.kiocb, iter);
3230 else if (req->file->f_op->read)
3231 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
3236 static int io_read(struct io_kiocb *req, bool force_nonblock,
3237 struct io_comp_state *cs)
3239 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3240 struct kiocb *kiocb = &req->rw.kiocb;
3241 struct iov_iter __iter, *iter = &__iter;
3242 struct io_async_rw *rw = req->async_data;
3243 ssize_t io_size, ret, ret2;
3250 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3253 iov_count = iov_iter_count(iter);
3255 req->result = io_size;
3258 /* Ensure we clear previously set non-block flag */
3259 if (!force_nonblock)
3260 kiocb->ki_flags &= ~IOCB_NOWAIT;
3262 kiocb->ki_flags |= IOCB_NOWAIT;
3265 /* If the file doesn't support async, just async punt */
3266 no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3270 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), iov_count);
3274 ret = io_iter_do_read(req, iter);
3278 } else if (ret == -EIOCBQUEUED) {
3281 } else if (ret == -EAGAIN) {
3282 /* IOPOLL retry should happen for io-wq threads */
3283 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3285 /* no retry on NONBLOCK marked file */
3286 if (req->file->f_flags & O_NONBLOCK)
3288 /* some cases will consume bytes even on error returns */
3289 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
3292 } else if (ret < 0) {
3293 /* make sure -ERESTARTSYS -> -EINTR is done */
3297 /* read it all, or we did blocking attempt. no retry. */
3298 if (!iov_iter_count(iter) || !force_nonblock ||
3299 (req->file->f_flags & O_NONBLOCK))
3304 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3311 rw = req->async_data;
3312 /* it's copied and will be cleaned with ->io */
3314 /* now use our persistent iterator, if we aren't already */
3317 rw->bytes_done += ret;
3318 /* if we can retry, do so with the callbacks armed */
3319 if (!io_rw_should_retry(req)) {
3320 kiocb->ki_flags &= ~IOCB_WAITQ;
3325 * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3326 * get -EIOCBQUEUED, then we'll get a notification when the desired
3327 * page gets unlocked. We can also get a partial read here, and if we
3328 * do, then just retry at the new offset.
3330 ret = io_iter_do_read(req, iter);
3331 if (ret == -EIOCBQUEUED) {
3334 } else if (ret > 0 && ret < io_size) {
3335 /* we got some bytes, but not all. retry. */
3339 kiocb_done(kiocb, ret, cs);
3342 /* it's reportedly faster than delegating the null check to kfree() */
3348 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3352 ret = io_prep_rw(req, sqe);
3356 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3359 /* either don't need iovec imported or already have it */
3360 if (!req->async_data)
3362 return io_rw_prep_async(req, WRITE);
3365 static int io_write(struct io_kiocb *req, bool force_nonblock,
3366 struct io_comp_state *cs)
3368 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3369 struct kiocb *kiocb = &req->rw.kiocb;
3370 struct iov_iter __iter, *iter = &__iter;
3371 struct io_async_rw *rw = req->async_data;
3373 ssize_t ret, ret2, io_size;
3378 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3381 iov_count = iov_iter_count(iter);
3383 req->result = io_size;
3385 /* Ensure we clear previously set non-block flag */
3386 if (!force_nonblock)
3387 kiocb->ki_flags &= ~IOCB_NOWAIT;
3389 kiocb->ki_flags |= IOCB_NOWAIT;
3391 /* If the file doesn't support async, just async punt */
3392 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3395 /* file path doesn't support NOWAIT for non-direct_IO */
3396 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3397 (req->flags & REQ_F_ISREG))
3400 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), iov_count);
3405 * Open-code file_start_write here to grab freeze protection,
3406 * which will be released by another thread in
3407 * io_complete_rw(). Fool lockdep by telling it the lock got
3408 * released so that it doesn't complain about the held lock when
3409 * we return to userspace.
3411 if (req->flags & REQ_F_ISREG) {
3412 __sb_start_write(file_inode(req->file)->i_sb,
3413 SB_FREEZE_WRITE, true);
3414 __sb_writers_release(file_inode(req->file)->i_sb,
3417 kiocb->ki_flags |= IOCB_WRITE;
3419 if (req->file->f_op->write_iter)
3420 ret2 = call_write_iter(req->file, kiocb, iter);
3421 else if (req->file->f_op->write)
3422 ret2 = loop_rw_iter(WRITE, req->file, kiocb, iter);
3427 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3428 * retry them without IOCB_NOWAIT.
3430 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3432 /* no retry on NONBLOCK marked file */
3433 if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3435 if (!force_nonblock || ret2 != -EAGAIN) {
3436 /* IOPOLL retry should happen for io-wq threads */
3437 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3440 kiocb_done(kiocb, ret2, cs);
3443 /* some cases will consume bytes even on error returns */
3444 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
3445 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3450 /* it's reportedly faster than delegating the null check to kfree() */
3456 static int __io_splice_prep(struct io_kiocb *req,
3457 const struct io_uring_sqe *sqe)
3459 struct io_splice* sp = &req->splice;
3460 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3462 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3466 sp->len = READ_ONCE(sqe->len);
3467 sp->flags = READ_ONCE(sqe->splice_flags);
3469 if (unlikely(sp->flags & ~valid_flags))
3472 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3473 (sp->flags & SPLICE_F_FD_IN_FIXED));
3476 req->flags |= REQ_F_NEED_CLEANUP;
3478 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3480 * Splice operation will be punted aync, and here need to
3481 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3483 io_req_init_async(req);
3484 req->work.flags |= IO_WQ_WORK_UNBOUND;
3490 static int io_tee_prep(struct io_kiocb *req,
3491 const struct io_uring_sqe *sqe)
3493 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3495 return __io_splice_prep(req, sqe);
3498 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3500 struct io_splice *sp = &req->splice;
3501 struct file *in = sp->file_in;
3502 struct file *out = sp->file_out;
3503 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3509 ret = do_tee(in, out, sp->len, flags);
3511 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3512 req->flags &= ~REQ_F_NEED_CLEANUP;
3515 req_set_fail_links(req);
3516 io_req_complete(req, ret);
3520 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3522 struct io_splice* sp = &req->splice;
3524 sp->off_in = READ_ONCE(sqe->splice_off_in);
3525 sp->off_out = READ_ONCE(sqe->off);
3526 return __io_splice_prep(req, sqe);
3529 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3531 struct io_splice *sp = &req->splice;
3532 struct file *in = sp->file_in;
3533 struct file *out = sp->file_out;
3534 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3535 loff_t *poff_in, *poff_out;
3541 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3542 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3545 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3547 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3548 req->flags &= ~REQ_F_NEED_CLEANUP;
3551 req_set_fail_links(req);
3552 io_req_complete(req, ret);
3557 * IORING_OP_NOP just posts a completion event, nothing else.
3559 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3561 struct io_ring_ctx *ctx = req->ctx;
3563 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3566 __io_req_complete(req, 0, 0, cs);
3570 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3572 struct io_ring_ctx *ctx = req->ctx;
3577 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3579 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3582 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3583 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3586 req->sync.off = READ_ONCE(sqe->off);
3587 req->sync.len = READ_ONCE(sqe->len);
3591 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3593 loff_t end = req->sync.off + req->sync.len;
3596 /* fsync always requires a blocking context */
3600 ret = vfs_fsync_range(req->file, req->sync.off,
3601 end > 0 ? end : LLONG_MAX,
3602 req->sync.flags & IORING_FSYNC_DATASYNC);
3604 req_set_fail_links(req);
3605 io_req_complete(req, ret);
3609 static int io_fallocate_prep(struct io_kiocb *req,
3610 const struct io_uring_sqe *sqe)
3612 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3614 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3617 req->sync.off = READ_ONCE(sqe->off);
3618 req->sync.len = READ_ONCE(sqe->addr);
3619 req->sync.mode = READ_ONCE(sqe->len);
3623 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3627 /* fallocate always requiring blocking context */
3630 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3633 req_set_fail_links(req);
3634 io_req_complete(req, ret);
3638 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3640 const char __user *fname;
3643 if (unlikely(sqe->ioprio || sqe->buf_index))
3645 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3648 /* open.how should be already initialised */
3649 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3650 req->open.how.flags |= O_LARGEFILE;
3652 req->open.dfd = READ_ONCE(sqe->fd);
3653 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3654 req->open.filename = getname(fname);
3655 if (IS_ERR(req->open.filename)) {
3656 ret = PTR_ERR(req->open.filename);
3657 req->open.filename = NULL;
3660 req->open.nofile = rlimit(RLIMIT_NOFILE);
3661 req->flags |= REQ_F_NEED_CLEANUP;
3665 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3669 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3671 mode = READ_ONCE(sqe->len);
3672 flags = READ_ONCE(sqe->open_flags);
3673 req->open.how = build_open_how(flags, mode);
3674 return __io_openat_prep(req, sqe);
3677 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3679 struct open_how __user *how;
3683 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3685 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3686 len = READ_ONCE(sqe->len);
3687 if (len < OPEN_HOW_SIZE_VER0)
3690 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3695 return __io_openat_prep(req, sqe);
3698 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3700 struct open_flags op;
3707 ret = build_open_flags(&req->open.how, &op);
3711 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3715 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3718 ret = PTR_ERR(file);
3720 fsnotify_open(file);
3721 fd_install(ret, file);
3724 putname(req->open.filename);
3725 req->flags &= ~REQ_F_NEED_CLEANUP;
3727 req_set_fail_links(req);
3728 io_req_complete(req, ret);
3732 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3734 return io_openat2(req, force_nonblock);
3737 static int io_remove_buffers_prep(struct io_kiocb *req,
3738 const struct io_uring_sqe *sqe)
3740 struct io_provide_buf *p = &req->pbuf;
3743 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3746 tmp = READ_ONCE(sqe->fd);
3747 if (!tmp || tmp > USHRT_MAX)
3750 memset(p, 0, sizeof(*p));
3752 p->bgid = READ_ONCE(sqe->buf_group);
3756 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3757 int bgid, unsigned nbufs)
3761 /* shouldn't happen */
3765 /* the head kbuf is the list itself */
3766 while (!list_empty(&buf->list)) {
3767 struct io_buffer *nxt;
3769 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3770 list_del(&nxt->list);
3777 idr_remove(&ctx->io_buffer_idr, bgid);
3782 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3783 struct io_comp_state *cs)
3785 struct io_provide_buf *p = &req->pbuf;
3786 struct io_ring_ctx *ctx = req->ctx;
3787 struct io_buffer *head;
3790 io_ring_submit_lock(ctx, !force_nonblock);
3792 lockdep_assert_held(&ctx->uring_lock);
3795 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3797 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3799 io_ring_submit_lock(ctx, !force_nonblock);
3801 req_set_fail_links(req);
3802 __io_req_complete(req, ret, 0, cs);
3806 static int io_provide_buffers_prep(struct io_kiocb *req,
3807 const struct io_uring_sqe *sqe)
3809 struct io_provide_buf *p = &req->pbuf;
3812 if (sqe->ioprio || sqe->rw_flags)
3815 tmp = READ_ONCE(sqe->fd);
3816 if (!tmp || tmp > USHRT_MAX)
3819 p->addr = READ_ONCE(sqe->addr);
3820 p->len = READ_ONCE(sqe->len);
3822 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3825 p->bgid = READ_ONCE(sqe->buf_group);
3826 tmp = READ_ONCE(sqe->off);
3827 if (tmp > USHRT_MAX)
3833 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3835 struct io_buffer *buf;
3836 u64 addr = pbuf->addr;
3837 int i, bid = pbuf->bid;
3839 for (i = 0; i < pbuf->nbufs; i++) {
3840 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3845 buf->len = pbuf->len;
3850 INIT_LIST_HEAD(&buf->list);
3853 list_add_tail(&buf->list, &(*head)->list);
3857 return i ? i : -ENOMEM;
3860 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3861 struct io_comp_state *cs)
3863 struct io_provide_buf *p = &req->pbuf;
3864 struct io_ring_ctx *ctx = req->ctx;
3865 struct io_buffer *head, *list;
3868 io_ring_submit_lock(ctx, !force_nonblock);
3870 lockdep_assert_held(&ctx->uring_lock);
3872 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3874 ret = io_add_buffers(p, &head);
3879 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3882 __io_remove_buffers(ctx, head, p->bgid, -1U);
3887 io_ring_submit_unlock(ctx, !force_nonblock);
3889 req_set_fail_links(req);
3890 __io_req_complete(req, ret, 0, cs);
3894 static int io_epoll_ctl_prep(struct io_kiocb *req,
3895 const struct io_uring_sqe *sqe)
3897 #if defined(CONFIG_EPOLL)
3898 if (sqe->ioprio || sqe->buf_index)
3900 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
3903 req->epoll.epfd = READ_ONCE(sqe->fd);
3904 req->epoll.op = READ_ONCE(sqe->len);
3905 req->epoll.fd = READ_ONCE(sqe->off);
3907 if (ep_op_has_event(req->epoll.op)) {
3908 struct epoll_event __user *ev;
3910 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3911 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3921 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3922 struct io_comp_state *cs)
3924 #if defined(CONFIG_EPOLL)
3925 struct io_epoll *ie = &req->epoll;
3928 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3929 if (force_nonblock && ret == -EAGAIN)
3933 req_set_fail_links(req);
3934 __io_req_complete(req, ret, 0, cs);
3941 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3943 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3944 if (sqe->ioprio || sqe->buf_index || sqe->off)
3946 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3949 req->madvise.addr = READ_ONCE(sqe->addr);
3950 req->madvise.len = READ_ONCE(sqe->len);
3951 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3958 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3960 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3961 struct io_madvise *ma = &req->madvise;
3967 ret = do_madvise(ma->addr, ma->len, ma->advice);
3969 req_set_fail_links(req);
3970 io_req_complete(req, ret);
3977 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3979 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3981 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3984 req->fadvise.offset = READ_ONCE(sqe->off);
3985 req->fadvise.len = READ_ONCE(sqe->len);
3986 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3990 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3992 struct io_fadvise *fa = &req->fadvise;
3995 if (force_nonblock) {
3996 switch (fa->advice) {
3997 case POSIX_FADV_NORMAL:
3998 case POSIX_FADV_RANDOM:
3999 case POSIX_FADV_SEQUENTIAL:
4006 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4008 req_set_fail_links(req);
4009 io_req_complete(req, ret);
4013 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4015 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4017 if (sqe->ioprio || sqe->buf_index)
4019 if (req->flags & REQ_F_FIXED_FILE)
4022 req->statx.dfd = READ_ONCE(sqe->fd);
4023 req->statx.mask = READ_ONCE(sqe->len);
4024 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4025 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4026 req->statx.flags = READ_ONCE(sqe->statx_flags);
4031 static int io_statx(struct io_kiocb *req, bool force_nonblock)
4033 struct io_statx *ctx = &req->statx;
4036 if (force_nonblock) {
4037 /* only need file table for an actual valid fd */
4038 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4039 req->flags |= REQ_F_NO_FILE_TABLE;
4043 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4047 req_set_fail_links(req);
4048 io_req_complete(req, ret);
4052 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4055 * If we queue this for async, it must not be cancellable. That would
4056 * leave the 'file' in an undeterminate state, and here need to modify
4057 * io_wq_work.flags, so initialize io_wq_work firstly.
4059 io_req_init_async(req);
4060 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
4062 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4064 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4065 sqe->rw_flags || sqe->buf_index)
4067 if (req->flags & REQ_F_FIXED_FILE)
4070 req->close.fd = READ_ONCE(sqe->fd);
4071 if ((req->file && req->file->f_op == &io_uring_fops))
4074 req->close.put_file = NULL;
4078 static int io_close(struct io_kiocb *req, bool force_nonblock,
4079 struct io_comp_state *cs)
4081 struct io_close *close = &req->close;
4084 /* might be already done during nonblock submission */
4085 if (!close->put_file) {
4086 ret = __close_fd_get_file(close->fd, &close->put_file);
4088 return (ret == -ENOENT) ? -EBADF : ret;
4091 /* if the file has a flush method, be safe and punt to async */
4092 if (close->put_file->f_op->flush && force_nonblock) {
4093 /* was never set, but play safe */
4094 req->flags &= ~REQ_F_NOWAIT;
4095 /* avoid grabbing files - we don't need the files */
4096 req->flags |= REQ_F_NO_FILE_TABLE;
4100 /* No ->flush() or already async, safely close from here */
4101 ret = filp_close(close->put_file, req->work.files);
4103 req_set_fail_links(req);
4104 fput(close->put_file);
4105 close->put_file = NULL;
4106 __io_req_complete(req, ret, 0, cs);
4110 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4112 struct io_ring_ctx *ctx = req->ctx;
4117 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4119 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4122 req->sync.off = READ_ONCE(sqe->off);
4123 req->sync.len = READ_ONCE(sqe->len);
4124 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4128 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
4132 /* sync_file_range always requires a blocking context */
4136 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4139 req_set_fail_links(req);
4140 io_req_complete(req, ret);
4144 #if defined(CONFIG_NET)
4145 static int io_setup_async_msg(struct io_kiocb *req,
4146 struct io_async_msghdr *kmsg)
4148 struct io_async_msghdr *async_msg = req->async_data;
4152 if (io_alloc_async_data(req)) {
4153 if (kmsg->iov != kmsg->fast_iov)
4157 async_msg = req->async_data;
4158 req->flags |= REQ_F_NEED_CLEANUP;
4159 memcpy(async_msg, kmsg, sizeof(*kmsg));
4163 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4164 struct io_async_msghdr *iomsg)
4166 iomsg->iov = iomsg->fast_iov;
4167 iomsg->msg.msg_name = &iomsg->addr;
4168 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4169 req->sr_msg.msg_flags, &iomsg->iov);
4172 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4174 struct io_async_msghdr *async_msg = req->async_data;
4175 struct io_sr_msg *sr = &req->sr_msg;
4178 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4181 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4182 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4183 sr->len = READ_ONCE(sqe->len);
4185 #ifdef CONFIG_COMPAT
4186 if (req->ctx->compat)
4187 sr->msg_flags |= MSG_CMSG_COMPAT;
4190 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4192 ret = io_sendmsg_copy_hdr(req, async_msg);
4194 req->flags |= REQ_F_NEED_CLEANUP;
4198 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4199 struct io_comp_state *cs)
4201 struct io_async_msghdr iomsg, *kmsg;
4202 struct socket *sock;
4206 sock = sock_from_file(req->file, &ret);
4207 if (unlikely(!sock))
4210 if (req->async_data) {
4211 kmsg = req->async_data;
4212 kmsg->msg.msg_name = &kmsg->addr;
4213 /* if iov is set, it's allocated already */
4215 kmsg->iov = kmsg->fast_iov;
4216 kmsg->msg.msg_iter.iov = kmsg->iov;
4218 ret = io_sendmsg_copy_hdr(req, &iomsg);
4224 flags = req->sr_msg.msg_flags;
4225 if (flags & MSG_DONTWAIT)
4226 req->flags |= REQ_F_NOWAIT;
4227 else if (force_nonblock)
4228 flags |= MSG_DONTWAIT;
4230 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4231 if (force_nonblock && ret == -EAGAIN)
4232 return io_setup_async_msg(req, kmsg);
4233 if (ret == -ERESTARTSYS)
4236 if (kmsg->iov != kmsg->fast_iov)
4238 req->flags &= ~REQ_F_NEED_CLEANUP;
4240 req_set_fail_links(req);
4241 __io_req_complete(req, ret, 0, cs);
4245 static int io_send(struct io_kiocb *req, bool force_nonblock,
4246 struct io_comp_state *cs)
4248 struct io_sr_msg *sr = &req->sr_msg;
4251 struct socket *sock;
4255 sock = sock_from_file(req->file, &ret);
4256 if (unlikely(!sock))
4259 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4263 msg.msg_name = NULL;
4264 msg.msg_control = NULL;
4265 msg.msg_controllen = 0;
4266 msg.msg_namelen = 0;
4268 flags = req->sr_msg.msg_flags;
4269 if (flags & MSG_DONTWAIT)
4270 req->flags |= REQ_F_NOWAIT;
4271 else if (force_nonblock)
4272 flags |= MSG_DONTWAIT;
4274 msg.msg_flags = flags;
4275 ret = sock_sendmsg(sock, &msg);
4276 if (force_nonblock && ret == -EAGAIN)
4278 if (ret == -ERESTARTSYS)
4282 req_set_fail_links(req);
4283 __io_req_complete(req, ret, 0, cs);
4287 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4288 struct io_async_msghdr *iomsg)
4290 struct io_sr_msg *sr = &req->sr_msg;
4291 struct iovec __user *uiov;
4295 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4296 &iomsg->uaddr, &uiov, &iov_len);
4300 if (req->flags & REQ_F_BUFFER_SELECT) {
4303 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4305 sr->len = iomsg->iov[0].iov_len;
4306 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4310 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4311 &iomsg->iov, &iomsg->msg.msg_iter,
4320 #ifdef CONFIG_COMPAT
4321 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4322 struct io_async_msghdr *iomsg)
4324 struct compat_msghdr __user *msg_compat;
4325 struct io_sr_msg *sr = &req->sr_msg;
4326 struct compat_iovec __user *uiov;
4331 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4332 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4337 uiov = compat_ptr(ptr);
4338 if (req->flags & REQ_F_BUFFER_SELECT) {
4339 compat_ssize_t clen;
4343 if (!access_ok(uiov, sizeof(*uiov)))
4345 if (__get_user(clen, &uiov->iov_len))
4349 sr->len = iomsg->iov[0].iov_len;
4352 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4353 UIO_FASTIOV, &iomsg->iov,
4354 &iomsg->msg.msg_iter, true);
4363 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4364 struct io_async_msghdr *iomsg)
4366 iomsg->msg.msg_name = &iomsg->addr;
4367 iomsg->iov = iomsg->fast_iov;
4369 #ifdef CONFIG_COMPAT
4370 if (req->ctx->compat)
4371 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4374 return __io_recvmsg_copy_hdr(req, iomsg);
4377 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4380 struct io_sr_msg *sr = &req->sr_msg;
4381 struct io_buffer *kbuf;
4383 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4388 req->flags |= REQ_F_BUFFER_SELECTED;
4392 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4394 return io_put_kbuf(req, req->sr_msg.kbuf);
4397 static int io_recvmsg_prep(struct io_kiocb *req,
4398 const struct io_uring_sqe *sqe)
4400 struct io_async_msghdr *async_msg = req->async_data;
4401 struct io_sr_msg *sr = &req->sr_msg;
4404 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4407 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4408 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4409 sr->len = READ_ONCE(sqe->len);
4410 sr->bgid = READ_ONCE(sqe->buf_group);
4412 #ifdef CONFIG_COMPAT
4413 if (req->ctx->compat)
4414 sr->msg_flags |= MSG_CMSG_COMPAT;
4417 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4419 ret = io_recvmsg_copy_hdr(req, async_msg);
4421 req->flags |= REQ_F_NEED_CLEANUP;
4425 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4426 struct io_comp_state *cs)
4428 struct io_async_msghdr iomsg, *kmsg;
4429 struct socket *sock;
4430 struct io_buffer *kbuf;
4432 int ret, cflags = 0;
4434 sock = sock_from_file(req->file, &ret);
4435 if (unlikely(!sock))
4438 if (req->async_data) {
4439 kmsg = req->async_data;
4440 kmsg->msg.msg_name = &kmsg->addr;
4441 /* if iov is set, it's allocated already */
4443 kmsg->iov = kmsg->fast_iov;
4444 kmsg->msg.msg_iter.iov = kmsg->iov;
4446 ret = io_recvmsg_copy_hdr(req, &iomsg);
4452 if (req->flags & REQ_F_BUFFER_SELECT) {
4453 kbuf = io_recv_buffer_select(req, !force_nonblock);
4455 return PTR_ERR(kbuf);
4456 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4457 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4458 1, req->sr_msg.len);
4461 flags = req->sr_msg.msg_flags;
4462 if (flags & MSG_DONTWAIT)
4463 req->flags |= REQ_F_NOWAIT;
4464 else if (force_nonblock)
4465 flags |= MSG_DONTWAIT;
4467 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4468 kmsg->uaddr, flags);
4469 if (force_nonblock && ret == -EAGAIN)
4470 return io_setup_async_msg(req, kmsg);
4471 if (ret == -ERESTARTSYS)
4474 if (req->flags & REQ_F_BUFFER_SELECTED)
4475 cflags = io_put_recv_kbuf(req);
4476 if (kmsg->iov != kmsg->fast_iov)
4478 req->flags &= ~REQ_F_NEED_CLEANUP;
4480 req_set_fail_links(req);
4481 __io_req_complete(req, ret, cflags, cs);
4485 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4486 struct io_comp_state *cs)
4488 struct io_buffer *kbuf;
4489 struct io_sr_msg *sr = &req->sr_msg;
4491 void __user *buf = sr->buf;
4492 struct socket *sock;
4495 int ret, cflags = 0;
4497 sock = sock_from_file(req->file, &ret);
4498 if (unlikely(!sock))
4501 if (req->flags & REQ_F_BUFFER_SELECT) {
4502 kbuf = io_recv_buffer_select(req, !force_nonblock);
4504 return PTR_ERR(kbuf);
4505 buf = u64_to_user_ptr(kbuf->addr);
4508 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4512 msg.msg_name = NULL;
4513 msg.msg_control = NULL;
4514 msg.msg_controllen = 0;
4515 msg.msg_namelen = 0;
4516 msg.msg_iocb = NULL;
4519 flags = req->sr_msg.msg_flags;
4520 if (flags & MSG_DONTWAIT)
4521 req->flags |= REQ_F_NOWAIT;
4522 else if (force_nonblock)
4523 flags |= MSG_DONTWAIT;
4525 ret = sock_recvmsg(sock, &msg, flags);
4526 if (force_nonblock && ret == -EAGAIN)
4528 if (ret == -ERESTARTSYS)
4531 if (req->flags & REQ_F_BUFFER_SELECTED)
4532 cflags = io_put_recv_kbuf(req);
4534 req_set_fail_links(req);
4535 __io_req_complete(req, ret, cflags, cs);
4539 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4541 struct io_accept *accept = &req->accept;
4543 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4545 if (sqe->ioprio || sqe->len || sqe->buf_index)
4548 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4549 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4550 accept->flags = READ_ONCE(sqe->accept_flags);
4551 accept->nofile = rlimit(RLIMIT_NOFILE);
4555 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4556 struct io_comp_state *cs)
4558 struct io_accept *accept = &req->accept;
4559 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4562 if (req->file->f_flags & O_NONBLOCK)
4563 req->flags |= REQ_F_NOWAIT;
4565 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4566 accept->addr_len, accept->flags,
4568 if (ret == -EAGAIN && force_nonblock)
4571 if (ret == -ERESTARTSYS)
4573 req_set_fail_links(req);
4575 __io_req_complete(req, ret, 0, cs);
4579 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4581 struct io_connect *conn = &req->connect;
4582 struct io_async_connect *io = req->async_data;
4584 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4586 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4589 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4590 conn->addr_len = READ_ONCE(sqe->addr2);
4595 return move_addr_to_kernel(conn->addr, conn->addr_len,
4599 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4600 struct io_comp_state *cs)
4602 struct io_async_connect __io, *io;
4603 unsigned file_flags;
4606 if (req->async_data) {
4607 io = req->async_data;
4609 ret = move_addr_to_kernel(req->connect.addr,
4610 req->connect.addr_len,
4617 file_flags = force_nonblock ? O_NONBLOCK : 0;
4619 ret = __sys_connect_file(req->file, &io->address,
4620 req->connect.addr_len, file_flags);
4621 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4622 if (req->async_data)
4624 if (io_alloc_async_data(req)) {
4628 io = req->async_data;
4629 memcpy(req->async_data, &__io, sizeof(__io));
4632 if (ret == -ERESTARTSYS)
4636 req_set_fail_links(req);
4637 __io_req_complete(req, ret, 0, cs);
4640 #else /* !CONFIG_NET */
4641 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4646 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4647 struct io_comp_state *cs)
4652 static int io_send(struct io_kiocb *req, bool force_nonblock,
4653 struct io_comp_state *cs)
4658 static int io_recvmsg_prep(struct io_kiocb *req,
4659 const struct io_uring_sqe *sqe)
4664 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4665 struct io_comp_state *cs)
4670 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4671 struct io_comp_state *cs)
4676 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4681 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4682 struct io_comp_state *cs)
4687 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4692 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4693 struct io_comp_state *cs)
4697 #endif /* CONFIG_NET */
4699 struct io_poll_table {
4700 struct poll_table_struct pt;
4701 struct io_kiocb *req;
4705 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4706 __poll_t mask, task_work_func_t func)
4711 /* for instances that support it check for an event match first: */
4712 if (mask && !(mask & poll->events))
4715 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4717 list_del_init(&poll->wait.entry);
4720 init_task_work(&req->task_work, func);
4721 percpu_ref_get(&req->ctx->refs);
4724 * If we using the signalfd wait_queue_head for this wakeup, then
4725 * it's not safe to use TWA_SIGNAL as we could be recursing on the
4726 * tsk->sighand->siglock on doing the wakeup. Should not be needed
4727 * either, as the normal wakeup will suffice.
4729 twa_signal_ok = (poll->head != &req->task->sighand->signalfd_wqh);
4732 * If this fails, then the task is exiting. When a task exits, the
4733 * work gets canceled, so just cancel this request as well instead
4734 * of executing it. We can't safely execute it anyway, as we may not
4735 * have the needed state needed for it anyway.
4737 ret = io_req_task_work_add(req, twa_signal_ok);
4738 if (unlikely(ret)) {
4739 struct task_struct *tsk;
4741 WRITE_ONCE(poll->canceled, true);
4742 tsk = io_wq_get_task(req->ctx->io_wq);
4743 task_work_add(tsk, &req->task_work, 0);
4744 wake_up_process(tsk);
4749 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4750 __acquires(&req->ctx->completion_lock)
4752 struct io_ring_ctx *ctx = req->ctx;
4754 if (!req->result && !READ_ONCE(poll->canceled)) {
4755 struct poll_table_struct pt = { ._key = poll->events };
4757 req->result = vfs_poll(req->file, &pt) & poll->events;
4760 spin_lock_irq(&ctx->completion_lock);
4761 if (!req->result && !READ_ONCE(poll->canceled)) {
4762 add_wait_queue(poll->head, &poll->wait);
4769 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4771 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4772 if (req->opcode == IORING_OP_POLL_ADD)
4773 return req->async_data;
4774 return req->apoll->double_poll;
4777 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4779 if (req->opcode == IORING_OP_POLL_ADD)
4781 return &req->apoll->poll;
4784 static void io_poll_remove_double(struct io_kiocb *req)
4786 struct io_poll_iocb *poll = io_poll_get_double(req);
4788 lockdep_assert_held(&req->ctx->completion_lock);
4790 if (poll && poll->head) {
4791 struct wait_queue_head *head = poll->head;
4793 spin_lock(&head->lock);
4794 list_del_init(&poll->wait.entry);
4795 if (poll->wait.private)
4796 refcount_dec(&req->refs);
4798 spin_unlock(&head->lock);
4802 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4804 struct io_ring_ctx *ctx = req->ctx;
4806 io_poll_remove_double(req);
4807 req->poll.done = true;
4808 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4809 io_commit_cqring(ctx);
4812 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4814 struct io_ring_ctx *ctx = req->ctx;
4816 if (io_poll_rewait(req, &req->poll)) {
4817 spin_unlock_irq(&ctx->completion_lock);
4821 hash_del(&req->hash_node);
4822 io_poll_complete(req, req->result, 0);
4823 spin_unlock_irq(&ctx->completion_lock);
4825 *nxt = io_put_req_find_next(req);
4826 io_cqring_ev_posted(ctx);
4829 static void io_poll_task_func(struct callback_head *cb)
4831 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4832 struct io_ring_ctx *ctx = req->ctx;
4833 struct io_kiocb *nxt = NULL;
4835 io_poll_task_handler(req, &nxt);
4837 __io_req_task_submit(nxt);
4838 percpu_ref_put(&ctx->refs);
4841 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4842 int sync, void *key)
4844 struct io_kiocb *req = wait->private;
4845 struct io_poll_iocb *poll = io_poll_get_single(req);
4846 __poll_t mask = key_to_poll(key);
4848 /* for instances that support it check for an event match first: */
4849 if (mask && !(mask & poll->events))
4852 list_del_init(&wait->entry);
4854 if (poll && poll->head) {
4857 spin_lock(&poll->head->lock);
4858 done = list_empty(&poll->wait.entry);
4860 list_del_init(&poll->wait.entry);
4861 /* make sure double remove sees this as being gone */
4862 wait->private = NULL;
4863 spin_unlock(&poll->head->lock);
4865 __io_async_wake(req, poll, mask, io_poll_task_func);
4867 refcount_dec(&req->refs);
4871 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4872 wait_queue_func_t wake_func)
4876 poll->canceled = false;
4877 poll->events = events;
4878 INIT_LIST_HEAD(&poll->wait.entry);
4879 init_waitqueue_func_entry(&poll->wait, wake_func);
4882 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4883 struct wait_queue_head *head,
4884 struct io_poll_iocb **poll_ptr)
4886 struct io_kiocb *req = pt->req;
4889 * If poll->head is already set, it's because the file being polled
4890 * uses multiple waitqueues for poll handling (eg one for read, one
4891 * for write). Setup a separate io_poll_iocb if this happens.
4893 if (unlikely(poll->head)) {
4894 /* already have a 2nd entry, fail a third attempt */
4896 pt->error = -EINVAL;
4899 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4901 pt->error = -ENOMEM;
4904 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4905 refcount_inc(&req->refs);
4906 poll->wait.private = req;
4913 if (poll->events & EPOLLEXCLUSIVE)
4914 add_wait_queue_exclusive(head, &poll->wait);
4916 add_wait_queue(head, &poll->wait);
4919 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4920 struct poll_table_struct *p)
4922 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4923 struct async_poll *apoll = pt->req->apoll;
4925 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
4928 static void io_async_task_func(struct callback_head *cb)
4930 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4931 struct async_poll *apoll = req->apoll;
4932 struct io_ring_ctx *ctx = req->ctx;
4934 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4936 if (io_poll_rewait(req, &apoll->poll)) {
4937 spin_unlock_irq(&ctx->completion_lock);
4938 percpu_ref_put(&ctx->refs);
4942 /* If req is still hashed, it cannot have been canceled. Don't check. */
4943 if (hash_hashed(&req->hash_node))
4944 hash_del(&req->hash_node);
4946 io_poll_remove_double(req);
4947 spin_unlock_irq(&ctx->completion_lock);
4949 if (!READ_ONCE(apoll->poll.canceled))
4950 __io_req_task_submit(req);
4952 __io_req_task_cancel(req, -ECANCELED);
4954 percpu_ref_put(&ctx->refs);
4955 kfree(apoll->double_poll);
4959 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4962 struct io_kiocb *req = wait->private;
4963 struct io_poll_iocb *poll = &req->apoll->poll;
4965 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4968 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4971 static void io_poll_req_insert(struct io_kiocb *req)
4973 struct io_ring_ctx *ctx = req->ctx;
4974 struct hlist_head *list;
4976 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4977 hlist_add_head(&req->hash_node, list);
4980 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4981 struct io_poll_iocb *poll,
4982 struct io_poll_table *ipt, __poll_t mask,
4983 wait_queue_func_t wake_func)
4984 __acquires(&ctx->completion_lock)
4986 struct io_ring_ctx *ctx = req->ctx;
4987 bool cancel = false;
4989 io_init_poll_iocb(poll, mask, wake_func);
4990 poll->file = req->file;
4991 poll->wait.private = req;
4993 ipt->pt._key = mask;
4995 ipt->error = -EINVAL;
4997 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4999 spin_lock_irq(&ctx->completion_lock);
5000 if (likely(poll->head)) {
5001 spin_lock(&poll->head->lock);
5002 if (unlikely(list_empty(&poll->wait.entry))) {
5008 if (mask || ipt->error)
5009 list_del_init(&poll->wait.entry);
5011 WRITE_ONCE(poll->canceled, true);
5012 else if (!poll->done) /* actually waiting for an event */
5013 io_poll_req_insert(req);
5014 spin_unlock(&poll->head->lock);
5020 static bool io_arm_poll_handler(struct io_kiocb *req)
5022 const struct io_op_def *def = &io_op_defs[req->opcode];
5023 struct io_ring_ctx *ctx = req->ctx;
5024 struct async_poll *apoll;
5025 struct io_poll_table ipt;
5029 if (!req->file || !file_can_poll(req->file))
5031 if (req->flags & REQ_F_POLLED)
5035 else if (def->pollout)
5039 /* if we can't nonblock try, then no point in arming a poll handler */
5040 if (!io_file_supports_async(req->file, rw))
5043 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5044 if (unlikely(!apoll))
5046 apoll->double_poll = NULL;
5048 req->flags |= REQ_F_POLLED;
5050 INIT_HLIST_NODE(&req->hash_node);
5054 mask |= POLLIN | POLLRDNORM;
5056 mask |= POLLOUT | POLLWRNORM;
5058 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5059 if ((req->opcode == IORING_OP_RECVMSG) &&
5060 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5063 mask |= POLLERR | POLLPRI;
5065 ipt.pt._qproc = io_async_queue_proc;
5067 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5069 if (ret || ipt.error) {
5070 io_poll_remove_double(req);
5071 spin_unlock_irq(&ctx->completion_lock);
5072 kfree(apoll->double_poll);
5076 spin_unlock_irq(&ctx->completion_lock);
5077 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5078 apoll->poll.events);
5082 static bool __io_poll_remove_one(struct io_kiocb *req,
5083 struct io_poll_iocb *poll)
5085 bool do_complete = false;
5087 spin_lock(&poll->head->lock);
5088 WRITE_ONCE(poll->canceled, true);
5089 if (!list_empty(&poll->wait.entry)) {
5090 list_del_init(&poll->wait.entry);
5093 spin_unlock(&poll->head->lock);
5094 hash_del(&req->hash_node);
5098 static bool io_poll_remove_one(struct io_kiocb *req)
5102 io_poll_remove_double(req);
5104 if (req->opcode == IORING_OP_POLL_ADD) {
5105 do_complete = __io_poll_remove_one(req, &req->poll);
5107 struct async_poll *apoll = req->apoll;
5109 /* non-poll requests have submit ref still */
5110 do_complete = __io_poll_remove_one(req, &apoll->poll);
5113 kfree(apoll->double_poll);
5119 io_cqring_fill_event(req, -ECANCELED);
5120 io_commit_cqring(req->ctx);
5121 req_set_fail_links(req);
5122 io_put_req_deferred(req, 1);
5129 * Returns true if we found and killed one or more poll requests
5131 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk)
5133 struct hlist_node *tmp;
5134 struct io_kiocb *req;
5137 spin_lock_irq(&ctx->completion_lock);
5138 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5139 struct hlist_head *list;
5141 list = &ctx->cancel_hash[i];
5142 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5143 if (io_task_match(req, tsk))
5144 posted += io_poll_remove_one(req);
5147 spin_unlock_irq(&ctx->completion_lock);
5150 io_cqring_ev_posted(ctx);
5155 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5157 struct hlist_head *list;
5158 struct io_kiocb *req;
5160 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5161 hlist_for_each_entry(req, list, hash_node) {
5162 if (sqe_addr != req->user_data)
5164 if (io_poll_remove_one(req))
5172 static int io_poll_remove_prep(struct io_kiocb *req,
5173 const struct io_uring_sqe *sqe)
5175 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5177 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5181 req->poll.addr = READ_ONCE(sqe->addr);
5186 * Find a running poll command that matches one specified in sqe->addr,
5187 * and remove it if found.
5189 static int io_poll_remove(struct io_kiocb *req)
5191 struct io_ring_ctx *ctx = req->ctx;
5195 addr = req->poll.addr;
5196 spin_lock_irq(&ctx->completion_lock);
5197 ret = io_poll_cancel(ctx, addr);
5198 spin_unlock_irq(&ctx->completion_lock);
5201 req_set_fail_links(req);
5202 io_req_complete(req, ret);
5206 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5209 struct io_kiocb *req = wait->private;
5210 struct io_poll_iocb *poll = &req->poll;
5212 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5215 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5216 struct poll_table_struct *p)
5218 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5220 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5223 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5225 struct io_poll_iocb *poll = &req->poll;
5228 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5230 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5235 events = READ_ONCE(sqe->poll32_events);
5237 events = swahw32(events);
5239 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5240 (events & EPOLLEXCLUSIVE);
5244 static int io_poll_add(struct io_kiocb *req)
5246 struct io_poll_iocb *poll = &req->poll;
5247 struct io_ring_ctx *ctx = req->ctx;
5248 struct io_poll_table ipt;
5251 INIT_HLIST_NODE(&req->hash_node);
5252 ipt.pt._qproc = io_poll_queue_proc;
5254 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5257 if (mask) { /* no async, we'd stolen it */
5259 io_poll_complete(req, mask, 0);
5261 spin_unlock_irq(&ctx->completion_lock);
5264 io_cqring_ev_posted(ctx);
5270 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5272 struct io_timeout_data *data = container_of(timer,
5273 struct io_timeout_data, timer);
5274 struct io_kiocb *req = data->req;
5275 struct io_ring_ctx *ctx = req->ctx;
5276 unsigned long flags;
5278 spin_lock_irqsave(&ctx->completion_lock, flags);
5279 list_del_init(&req->timeout.list);
5280 atomic_set(&req->ctx->cq_timeouts,
5281 atomic_read(&req->ctx->cq_timeouts) + 1);
5283 io_cqring_fill_event(req, -ETIME);
5284 io_commit_cqring(ctx);
5285 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5287 io_cqring_ev_posted(ctx);
5288 req_set_fail_links(req);
5290 return HRTIMER_NORESTART;
5293 static int __io_timeout_cancel(struct io_kiocb *req)
5295 struct io_timeout_data *io = req->async_data;
5298 ret = hrtimer_try_to_cancel(&io->timer);
5301 list_del_init(&req->timeout.list);
5303 req_set_fail_links(req);
5304 io_cqring_fill_event(req, -ECANCELED);
5305 io_put_req_deferred(req, 1);
5309 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5311 struct io_kiocb *req;
5314 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5315 if (user_data == req->user_data) {
5324 return __io_timeout_cancel(req);
5327 static int io_timeout_remove_prep(struct io_kiocb *req,
5328 const struct io_uring_sqe *sqe)
5330 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5332 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5334 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->timeout_flags)
5337 req->timeout_rem.addr = READ_ONCE(sqe->addr);
5342 * Remove or update an existing timeout command
5344 static int io_timeout_remove(struct io_kiocb *req)
5346 struct io_ring_ctx *ctx = req->ctx;
5349 spin_lock_irq(&ctx->completion_lock);
5350 ret = io_timeout_cancel(ctx, req->timeout_rem.addr);
5352 io_cqring_fill_event(req, ret);
5353 io_commit_cqring(ctx);
5354 spin_unlock_irq(&ctx->completion_lock);
5355 io_cqring_ev_posted(ctx);
5357 req_set_fail_links(req);
5362 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5363 bool is_timeout_link)
5365 struct io_timeout_data *data;
5367 u32 off = READ_ONCE(sqe->off);
5369 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5371 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5373 if (off && is_timeout_link)
5375 flags = READ_ONCE(sqe->timeout_flags);
5376 if (flags & ~IORING_TIMEOUT_ABS)
5379 req->timeout.off = off;
5381 if (!req->async_data && io_alloc_async_data(req))
5384 data = req->async_data;
5387 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5390 if (flags & IORING_TIMEOUT_ABS)
5391 data->mode = HRTIMER_MODE_ABS;
5393 data->mode = HRTIMER_MODE_REL;
5395 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5399 static int io_timeout(struct io_kiocb *req)
5401 struct io_ring_ctx *ctx = req->ctx;
5402 struct io_timeout_data *data = req->async_data;
5403 struct list_head *entry;
5404 u32 tail, off = req->timeout.off;
5406 spin_lock_irq(&ctx->completion_lock);
5409 * sqe->off holds how many events that need to occur for this
5410 * timeout event to be satisfied. If it isn't set, then this is
5411 * a pure timeout request, sequence isn't used.
5413 if (io_is_timeout_noseq(req)) {
5414 entry = ctx->timeout_list.prev;
5418 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5419 req->timeout.target_seq = tail + off;
5422 * Insertion sort, ensuring the first entry in the list is always
5423 * the one we need first.
5425 list_for_each_prev(entry, &ctx->timeout_list) {
5426 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5429 if (io_is_timeout_noseq(nxt))
5431 /* nxt.seq is behind @tail, otherwise would've been completed */
5432 if (off >= nxt->timeout.target_seq - tail)
5436 list_add(&req->timeout.list, entry);
5437 data->timer.function = io_timeout_fn;
5438 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5439 spin_unlock_irq(&ctx->completion_lock);
5443 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5445 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5447 return req->user_data == (unsigned long) data;
5450 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5452 enum io_wq_cancel cancel_ret;
5455 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5456 switch (cancel_ret) {
5457 case IO_WQ_CANCEL_OK:
5460 case IO_WQ_CANCEL_RUNNING:
5463 case IO_WQ_CANCEL_NOTFOUND:
5471 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5472 struct io_kiocb *req, __u64 sqe_addr,
5475 unsigned long flags;
5478 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5479 if (ret != -ENOENT) {
5480 spin_lock_irqsave(&ctx->completion_lock, flags);
5484 spin_lock_irqsave(&ctx->completion_lock, flags);
5485 ret = io_timeout_cancel(ctx, sqe_addr);
5488 ret = io_poll_cancel(ctx, sqe_addr);
5492 io_cqring_fill_event(req, ret);
5493 io_commit_cqring(ctx);
5494 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5495 io_cqring_ev_posted(ctx);
5498 req_set_fail_links(req);
5502 static int io_async_cancel_prep(struct io_kiocb *req,
5503 const struct io_uring_sqe *sqe)
5505 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5507 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5509 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5512 req->cancel.addr = READ_ONCE(sqe->addr);
5516 static int io_async_cancel(struct io_kiocb *req)
5518 struct io_ring_ctx *ctx = req->ctx;
5520 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5524 static int io_files_update_prep(struct io_kiocb *req,
5525 const struct io_uring_sqe *sqe)
5527 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5529 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5531 if (sqe->ioprio || sqe->rw_flags)
5534 req->files_update.offset = READ_ONCE(sqe->off);
5535 req->files_update.nr_args = READ_ONCE(sqe->len);
5536 if (!req->files_update.nr_args)
5538 req->files_update.arg = READ_ONCE(sqe->addr);
5542 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5543 struct io_comp_state *cs)
5545 struct io_ring_ctx *ctx = req->ctx;
5546 struct io_uring_files_update up;
5552 up.offset = req->files_update.offset;
5553 up.fds = req->files_update.arg;
5555 mutex_lock(&ctx->uring_lock);
5556 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5557 mutex_unlock(&ctx->uring_lock);
5560 req_set_fail_links(req);
5561 __io_req_complete(req, ret, 0, cs);
5565 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5567 switch (req->opcode) {
5570 case IORING_OP_READV:
5571 case IORING_OP_READ_FIXED:
5572 case IORING_OP_READ:
5573 return io_read_prep(req, sqe);
5574 case IORING_OP_WRITEV:
5575 case IORING_OP_WRITE_FIXED:
5576 case IORING_OP_WRITE:
5577 return io_write_prep(req, sqe);
5578 case IORING_OP_POLL_ADD:
5579 return io_poll_add_prep(req, sqe);
5580 case IORING_OP_POLL_REMOVE:
5581 return io_poll_remove_prep(req, sqe);
5582 case IORING_OP_FSYNC:
5583 return io_prep_fsync(req, sqe);
5584 case IORING_OP_SYNC_FILE_RANGE:
5585 return io_prep_sfr(req, sqe);
5586 case IORING_OP_SENDMSG:
5587 case IORING_OP_SEND:
5588 return io_sendmsg_prep(req, sqe);
5589 case IORING_OP_RECVMSG:
5590 case IORING_OP_RECV:
5591 return io_recvmsg_prep(req, sqe);
5592 case IORING_OP_CONNECT:
5593 return io_connect_prep(req, sqe);
5594 case IORING_OP_TIMEOUT:
5595 return io_timeout_prep(req, sqe, false);
5596 case IORING_OP_TIMEOUT_REMOVE:
5597 return io_timeout_remove_prep(req, sqe);
5598 case IORING_OP_ASYNC_CANCEL:
5599 return io_async_cancel_prep(req, sqe);
5600 case IORING_OP_LINK_TIMEOUT:
5601 return io_timeout_prep(req, sqe, true);
5602 case IORING_OP_ACCEPT:
5603 return io_accept_prep(req, sqe);
5604 case IORING_OP_FALLOCATE:
5605 return io_fallocate_prep(req, sqe);
5606 case IORING_OP_OPENAT:
5607 return io_openat_prep(req, sqe);
5608 case IORING_OP_CLOSE:
5609 return io_close_prep(req, sqe);
5610 case IORING_OP_FILES_UPDATE:
5611 return io_files_update_prep(req, sqe);
5612 case IORING_OP_STATX:
5613 return io_statx_prep(req, sqe);
5614 case IORING_OP_FADVISE:
5615 return io_fadvise_prep(req, sqe);
5616 case IORING_OP_MADVISE:
5617 return io_madvise_prep(req, sqe);
5618 case IORING_OP_OPENAT2:
5619 return io_openat2_prep(req, sqe);
5620 case IORING_OP_EPOLL_CTL:
5621 return io_epoll_ctl_prep(req, sqe);
5622 case IORING_OP_SPLICE:
5623 return io_splice_prep(req, sqe);
5624 case IORING_OP_PROVIDE_BUFFERS:
5625 return io_provide_buffers_prep(req, sqe);
5626 case IORING_OP_REMOVE_BUFFERS:
5627 return io_remove_buffers_prep(req, sqe);
5629 return io_tee_prep(req, sqe);
5632 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5637 static int io_req_defer_prep(struct io_kiocb *req,
5638 const struct io_uring_sqe *sqe)
5642 if (io_alloc_async_data(req))
5644 return io_req_prep(req, sqe);
5647 static u32 io_get_sequence(struct io_kiocb *req)
5649 struct io_kiocb *pos;
5650 struct io_ring_ctx *ctx = req->ctx;
5651 u32 total_submitted, nr_reqs = 1;
5653 if (req->flags & REQ_F_LINK_HEAD)
5654 list_for_each_entry(pos, &req->link_list, link_list)
5657 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5658 return total_submitted - nr_reqs;
5661 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5663 struct io_ring_ctx *ctx = req->ctx;
5664 struct io_defer_entry *de;
5668 /* Still need defer if there is pending req in defer list. */
5669 if (likely(list_empty_careful(&ctx->defer_list) &&
5670 !(req->flags & REQ_F_IO_DRAIN)))
5673 seq = io_get_sequence(req);
5674 /* Still a chance to pass the sequence check */
5675 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5678 if (!req->async_data) {
5679 ret = io_req_defer_prep(req, sqe);
5683 io_prep_async_link(req);
5684 de = kmalloc(sizeof(*de), GFP_KERNEL);
5688 spin_lock_irq(&ctx->completion_lock);
5689 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5690 spin_unlock_irq(&ctx->completion_lock);
5692 io_queue_async_work(req);
5693 return -EIOCBQUEUED;
5696 trace_io_uring_defer(ctx, req, req->user_data);
5699 list_add_tail(&de->list, &ctx->defer_list);
5700 spin_unlock_irq(&ctx->completion_lock);
5701 return -EIOCBQUEUED;
5704 static void io_req_drop_files(struct io_kiocb *req)
5706 struct io_ring_ctx *ctx = req->ctx;
5707 unsigned long flags;
5709 spin_lock_irqsave(&ctx->inflight_lock, flags);
5710 list_del(&req->inflight_entry);
5711 if (waitqueue_active(&ctx->inflight_wait))
5712 wake_up(&ctx->inflight_wait);
5713 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
5714 req->flags &= ~REQ_F_INFLIGHT;
5715 put_files_struct(req->work.files);
5716 put_nsproxy(req->work.nsproxy);
5717 req->work.files = NULL;
5720 static void __io_clean_op(struct io_kiocb *req)
5722 if (req->flags & REQ_F_BUFFER_SELECTED) {
5723 switch (req->opcode) {
5724 case IORING_OP_READV:
5725 case IORING_OP_READ_FIXED:
5726 case IORING_OP_READ:
5727 kfree((void *)(unsigned long)req->rw.addr);
5729 case IORING_OP_RECVMSG:
5730 case IORING_OP_RECV:
5731 kfree(req->sr_msg.kbuf);
5734 req->flags &= ~REQ_F_BUFFER_SELECTED;
5737 if (req->flags & REQ_F_NEED_CLEANUP) {
5738 switch (req->opcode) {
5739 case IORING_OP_READV:
5740 case IORING_OP_READ_FIXED:
5741 case IORING_OP_READ:
5742 case IORING_OP_WRITEV:
5743 case IORING_OP_WRITE_FIXED:
5744 case IORING_OP_WRITE: {
5745 struct io_async_rw *io = req->async_data;
5747 kfree(io->free_iovec);
5750 case IORING_OP_RECVMSG:
5751 case IORING_OP_SENDMSG: {
5752 struct io_async_msghdr *io = req->async_data;
5753 if (io->iov != io->fast_iov)
5757 case IORING_OP_SPLICE:
5759 io_put_file(req, req->splice.file_in,
5760 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5762 case IORING_OP_OPENAT:
5763 case IORING_OP_OPENAT2:
5764 if (req->open.filename)
5765 putname(req->open.filename);
5768 req->flags &= ~REQ_F_NEED_CLEANUP;
5771 if (req->flags & REQ_F_INFLIGHT)
5772 io_req_drop_files(req);
5775 static int io_issue_sqe(struct io_kiocb *req, bool force_nonblock,
5776 struct io_comp_state *cs)
5778 struct io_ring_ctx *ctx = req->ctx;
5781 switch (req->opcode) {
5783 ret = io_nop(req, cs);
5785 case IORING_OP_READV:
5786 case IORING_OP_READ_FIXED:
5787 case IORING_OP_READ:
5788 ret = io_read(req, force_nonblock, cs);
5790 case IORING_OP_WRITEV:
5791 case IORING_OP_WRITE_FIXED:
5792 case IORING_OP_WRITE:
5793 ret = io_write(req, force_nonblock, cs);
5795 case IORING_OP_FSYNC:
5796 ret = io_fsync(req, force_nonblock);
5798 case IORING_OP_POLL_ADD:
5799 ret = io_poll_add(req);
5801 case IORING_OP_POLL_REMOVE:
5802 ret = io_poll_remove(req);
5804 case IORING_OP_SYNC_FILE_RANGE:
5805 ret = io_sync_file_range(req, force_nonblock);
5807 case IORING_OP_SENDMSG:
5808 ret = io_sendmsg(req, force_nonblock, cs);
5810 case IORING_OP_SEND:
5811 ret = io_send(req, force_nonblock, cs);
5813 case IORING_OP_RECVMSG:
5814 ret = io_recvmsg(req, force_nonblock, cs);
5816 case IORING_OP_RECV:
5817 ret = io_recv(req, force_nonblock, cs);
5819 case IORING_OP_TIMEOUT:
5820 ret = io_timeout(req);
5822 case IORING_OP_TIMEOUT_REMOVE:
5823 ret = io_timeout_remove(req);
5825 case IORING_OP_ACCEPT:
5826 ret = io_accept(req, force_nonblock, cs);
5828 case IORING_OP_CONNECT:
5829 ret = io_connect(req, force_nonblock, cs);
5831 case IORING_OP_ASYNC_CANCEL:
5832 ret = io_async_cancel(req);
5834 case IORING_OP_FALLOCATE:
5835 ret = io_fallocate(req, force_nonblock);
5837 case IORING_OP_OPENAT:
5838 ret = io_openat(req, force_nonblock);
5840 case IORING_OP_CLOSE:
5841 ret = io_close(req, force_nonblock, cs);
5843 case IORING_OP_FILES_UPDATE:
5844 ret = io_files_update(req, force_nonblock, cs);
5846 case IORING_OP_STATX:
5847 ret = io_statx(req, force_nonblock);
5849 case IORING_OP_FADVISE:
5850 ret = io_fadvise(req, force_nonblock);
5852 case IORING_OP_MADVISE:
5853 ret = io_madvise(req, force_nonblock);
5855 case IORING_OP_OPENAT2:
5856 ret = io_openat2(req, force_nonblock);
5858 case IORING_OP_EPOLL_CTL:
5859 ret = io_epoll_ctl(req, force_nonblock, cs);
5861 case IORING_OP_SPLICE:
5862 ret = io_splice(req, force_nonblock);
5864 case IORING_OP_PROVIDE_BUFFERS:
5865 ret = io_provide_buffers(req, force_nonblock, cs);
5867 case IORING_OP_REMOVE_BUFFERS:
5868 ret = io_remove_buffers(req, force_nonblock, cs);
5871 ret = io_tee(req, force_nonblock);
5881 /* If the op doesn't have a file, we're not polling for it */
5882 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5883 const bool in_async = io_wq_current_is_worker();
5885 /* workqueue context doesn't hold uring_lock, grab it now */
5887 mutex_lock(&ctx->uring_lock);
5889 io_iopoll_req_issued(req);
5892 mutex_unlock(&ctx->uring_lock);
5898 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
5900 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5901 struct io_kiocb *timeout;
5904 timeout = io_prep_linked_timeout(req);
5906 io_queue_linked_timeout(timeout);
5908 /* if NO_CANCEL is set, we must still run the work */
5909 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5910 IO_WQ_WORK_CANCEL) {
5916 ret = io_issue_sqe(req, false, NULL);
5918 * We can get EAGAIN for polled IO even though we're
5919 * forcing a sync submission from here, since we can't
5920 * wait for request slots on the block side.
5929 req_set_fail_links(req);
5930 io_req_complete(req, ret);
5933 return io_steal_work(req);
5936 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5939 struct fixed_file_table *table;
5941 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5942 return table->files[index & IORING_FILE_TABLE_MASK];
5945 static struct file *io_file_get(struct io_submit_state *state,
5946 struct io_kiocb *req, int fd, bool fixed)
5948 struct io_ring_ctx *ctx = req->ctx;
5952 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
5954 fd = array_index_nospec(fd, ctx->nr_user_files);
5955 file = io_file_from_index(ctx, fd);
5957 req->fixed_file_refs = &ctx->file_data->node->refs;
5958 percpu_ref_get(req->fixed_file_refs);
5961 trace_io_uring_file_get(ctx, fd);
5962 file = __io_file_get(state, fd);
5968 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5973 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5974 if (unlikely(!fixed && io_async_submit(req->ctx)))
5977 req->file = io_file_get(state, req, fd, fixed);
5978 if (req->file || io_op_defs[req->opcode].needs_file_no_error)
5983 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5985 struct io_timeout_data *data = container_of(timer,
5986 struct io_timeout_data, timer);
5987 struct io_kiocb *req = data->req;
5988 struct io_ring_ctx *ctx = req->ctx;
5989 struct io_kiocb *prev = NULL;
5990 unsigned long flags;
5992 spin_lock_irqsave(&ctx->completion_lock, flags);
5995 * We don't expect the list to be empty, that will only happen if we
5996 * race with the completion of the linked work.
5998 if (!list_empty(&req->link_list)) {
5999 prev = list_entry(req->link_list.prev, struct io_kiocb,
6001 if (refcount_inc_not_zero(&prev->refs)) {
6002 list_del_init(&req->link_list);
6003 prev->flags &= ~REQ_F_LINK_TIMEOUT;
6008 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6011 req_set_fail_links(prev);
6012 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6015 io_req_complete(req, -ETIME);
6017 return HRTIMER_NORESTART;
6020 static void __io_queue_linked_timeout(struct io_kiocb *req)
6023 * If the list is now empty, then our linked request finished before
6024 * we got a chance to setup the timer
6026 if (!list_empty(&req->link_list)) {
6027 struct io_timeout_data *data = req->async_data;
6029 data->timer.function = io_link_timeout_fn;
6030 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6035 static void io_queue_linked_timeout(struct io_kiocb *req)
6037 struct io_ring_ctx *ctx = req->ctx;
6039 spin_lock_irq(&ctx->completion_lock);
6040 __io_queue_linked_timeout(req);
6041 spin_unlock_irq(&ctx->completion_lock);
6043 /* drop submission reference */
6047 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6049 struct io_kiocb *nxt;
6051 if (!(req->flags & REQ_F_LINK_HEAD))
6053 if (req->flags & REQ_F_LINK_TIMEOUT)
6056 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
6058 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
6061 req->flags |= REQ_F_LINK_TIMEOUT;
6065 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs)
6067 struct io_kiocb *linked_timeout;
6068 struct io_kiocb *nxt;
6069 const struct cred *old_creds = NULL;
6073 linked_timeout = io_prep_linked_timeout(req);
6075 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
6076 req->work.creds != current_cred()) {
6078 revert_creds(old_creds);
6079 if (old_creds == req->work.creds)
6080 old_creds = NULL; /* restored original creds */
6082 old_creds = override_creds(req->work.creds);
6085 ret = io_issue_sqe(req, true, cs);
6088 * We async punt it if the file wasn't marked NOWAIT, or if the file
6089 * doesn't support non-blocking read/write attempts
6091 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6092 if (!io_arm_poll_handler(req)) {
6095 * Queued up for async execution, worker will release
6096 * submit reference when the iocb is actually submitted.
6098 io_queue_async_work(req);
6102 io_queue_linked_timeout(linked_timeout);
6106 if (unlikely(ret)) {
6107 /* un-prep timeout, so it'll be killed as any other linked */
6108 req->flags &= ~REQ_F_LINK_TIMEOUT;
6109 req_set_fail_links(req);
6111 io_req_complete(req, ret);
6115 /* drop submission reference */
6116 nxt = io_put_req_find_next(req);
6118 io_queue_linked_timeout(linked_timeout);
6123 if (req->flags & REQ_F_FORCE_ASYNC)
6129 revert_creds(old_creds);
6132 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6133 struct io_comp_state *cs)
6137 ret = io_req_defer(req, sqe);
6139 if (ret != -EIOCBQUEUED) {
6141 req_set_fail_links(req);
6143 io_req_complete(req, ret);
6145 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6146 if (!req->async_data) {
6147 ret = io_req_defer_prep(req, sqe);
6153 * Never try inline submit of IOSQE_ASYNC is set, go straight
6154 * to async execution.
6156 io_req_init_async(req);
6157 req->work.flags |= IO_WQ_WORK_CONCURRENT;
6158 io_queue_async_work(req);
6161 ret = io_req_prep(req, sqe);
6165 __io_queue_sqe(req, cs);
6169 static inline void io_queue_link_head(struct io_kiocb *req,
6170 struct io_comp_state *cs)
6172 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6174 io_req_complete(req, -ECANCELED);
6176 io_queue_sqe(req, NULL, cs);
6179 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6180 struct io_kiocb **link, struct io_comp_state *cs)
6182 struct io_ring_ctx *ctx = req->ctx;
6186 * If we already have a head request, queue this one for async
6187 * submittal once the head completes. If we don't have a head but
6188 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6189 * submitted sync once the chain is complete. If none of those
6190 * conditions are true (normal request), then just queue it.
6193 struct io_kiocb *head = *link;
6196 * Taking sequential execution of a link, draining both sides
6197 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6198 * requests in the link. So, it drains the head and the
6199 * next after the link request. The last one is done via
6200 * drain_next flag to persist the effect across calls.
6202 if (req->flags & REQ_F_IO_DRAIN) {
6203 head->flags |= REQ_F_IO_DRAIN;
6204 ctx->drain_next = 1;
6206 ret = io_req_defer_prep(req, sqe);
6207 if (unlikely(ret)) {
6208 /* fail even hard links since we don't submit */
6209 head->flags |= REQ_F_FAIL_LINK;
6212 trace_io_uring_link(ctx, req, head);
6213 list_add_tail(&req->link_list, &head->link_list);
6215 /* last request of a link, enqueue the link */
6216 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6217 io_queue_link_head(head, cs);
6221 if (unlikely(ctx->drain_next)) {
6222 req->flags |= REQ_F_IO_DRAIN;
6223 ctx->drain_next = 0;
6225 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6226 req->flags |= REQ_F_LINK_HEAD;
6227 INIT_LIST_HEAD(&req->link_list);
6229 ret = io_req_defer_prep(req, sqe);
6231 req->flags |= REQ_F_FAIL_LINK;
6234 io_queue_sqe(req, sqe, cs);
6242 * Batched submission is done, ensure local IO is flushed out.
6244 static void io_submit_state_end(struct io_submit_state *state)
6246 if (!list_empty(&state->comp.list))
6247 io_submit_flush_completions(&state->comp);
6248 blk_finish_plug(&state->plug);
6249 io_state_file_put(state);
6250 if (state->free_reqs)
6251 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6255 * Start submission side cache.
6257 static void io_submit_state_start(struct io_submit_state *state,
6258 struct io_ring_ctx *ctx, unsigned int max_ios)
6260 blk_start_plug(&state->plug);
6262 INIT_LIST_HEAD(&state->comp.list);
6263 state->comp.ctx = ctx;
6264 state->free_reqs = 0;
6266 state->ios_left = max_ios;
6269 static void io_commit_sqring(struct io_ring_ctx *ctx)
6271 struct io_rings *rings = ctx->rings;
6274 * Ensure any loads from the SQEs are done at this point,
6275 * since once we write the new head, the application could
6276 * write new data to them.
6278 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6282 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6283 * that is mapped by userspace. This means that care needs to be taken to
6284 * ensure that reads are stable, as we cannot rely on userspace always
6285 * being a good citizen. If members of the sqe are validated and then later
6286 * used, it's important that those reads are done through READ_ONCE() to
6287 * prevent a re-load down the line.
6289 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6291 u32 *sq_array = ctx->sq_array;
6295 * The cached sq head (or cq tail) serves two purposes:
6297 * 1) allows us to batch the cost of updating the user visible
6299 * 2) allows the kernel side to track the head on its own, even
6300 * though the application is the one updating it.
6302 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6303 if (likely(head < ctx->sq_entries))
6304 return &ctx->sq_sqes[head];
6306 /* drop invalid entries */
6307 ctx->cached_sq_dropped++;
6308 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6312 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6314 ctx->cached_sq_head++;
6318 * Check SQE restrictions (opcode and flags).
6320 * Returns 'true' if SQE is allowed, 'false' otherwise.
6322 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6323 struct io_kiocb *req,
6324 unsigned int sqe_flags)
6326 if (!ctx->restricted)
6329 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6332 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6333 ctx->restrictions.sqe_flags_required)
6336 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6337 ctx->restrictions.sqe_flags_required))
6343 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6344 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6345 IOSQE_BUFFER_SELECT)
6347 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6348 const struct io_uring_sqe *sqe,
6349 struct io_submit_state *state)
6351 unsigned int sqe_flags;
6354 req->opcode = READ_ONCE(sqe->opcode);
6355 req->user_data = READ_ONCE(sqe->user_data);
6356 req->async_data = NULL;
6360 /* one is dropped after submission, the other at completion */
6361 refcount_set(&req->refs, 2);
6362 req->task = current;
6365 if (unlikely(req->opcode >= IORING_OP_LAST))
6368 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6371 sqe_flags = READ_ONCE(sqe->flags);
6372 /* enforce forwards compatibility on users */
6373 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6376 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6379 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6380 !io_op_defs[req->opcode].buffer_select)
6383 id = READ_ONCE(sqe->personality);
6385 io_req_init_async(req);
6386 req->work.creds = idr_find(&ctx->personality_idr, id);
6387 if (unlikely(!req->work.creds))
6389 get_cred(req->work.creds);
6392 /* same numerical values with corresponding REQ_F_*, safe to copy */
6393 req->flags |= sqe_flags;
6395 if (!io_op_defs[req->opcode].needs_file)
6398 ret = io_req_set_file(state, req, READ_ONCE(sqe->fd));
6403 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6405 struct io_submit_state state;
6406 struct io_kiocb *link = NULL;
6407 int i, submitted = 0;
6409 /* if we have a backlog and couldn't flush it all, return BUSY */
6410 if (test_bit(0, &ctx->sq_check_overflow)) {
6411 if (!list_empty(&ctx->cq_overflow_list) &&
6412 !io_cqring_overflow_flush(ctx, false, NULL, NULL))
6416 /* make sure SQ entry isn't read before tail */
6417 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6419 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6422 atomic_long_add(nr, ¤t->io_uring->req_issue);
6423 refcount_add(nr, ¤t->usage);
6425 io_submit_state_start(&state, ctx, nr);
6427 for (i = 0; i < nr; i++) {
6428 const struct io_uring_sqe *sqe;
6429 struct io_kiocb *req;
6432 sqe = io_get_sqe(ctx);
6433 if (unlikely(!sqe)) {
6434 io_consume_sqe(ctx);
6437 req = io_alloc_req(ctx, &state);
6438 if (unlikely(!req)) {
6440 submitted = -EAGAIN;
6443 io_consume_sqe(ctx);
6444 /* will complete beyond this point, count as submitted */
6447 err = io_init_req(ctx, req, sqe, &state);
6448 if (unlikely(err)) {
6451 io_req_complete(req, err);
6455 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6456 true, io_async_submit(ctx));
6457 err = io_submit_sqe(req, sqe, &link, &state.comp);
6462 if (unlikely(submitted != nr)) {
6463 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6465 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6466 atomic_long_sub(nr - ref_used, ¤t->io_uring->req_issue);
6467 put_task_struct_many(current, nr - ref_used);
6470 io_queue_link_head(link, &state.comp);
6471 io_submit_state_end(&state);
6473 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6474 io_commit_sqring(ctx);
6479 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6481 /* Tell userspace we may need a wakeup call */
6482 spin_lock_irq(&ctx->completion_lock);
6483 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6484 spin_unlock_irq(&ctx->completion_lock);
6487 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6489 spin_lock_irq(&ctx->completion_lock);
6490 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6491 spin_unlock_irq(&ctx->completion_lock);
6494 static int io_sq_wake_function(struct wait_queue_entry *wqe, unsigned mode,
6495 int sync, void *key)
6497 struct io_ring_ctx *ctx = container_of(wqe, struct io_ring_ctx, sqo_wait_entry);
6500 ret = autoremove_wake_function(wqe, mode, sync, key);
6502 unsigned long flags;
6504 spin_lock_irqsave(&ctx->completion_lock, flags);
6505 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6506 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6517 static enum sq_ret __io_sq_thread(struct io_ring_ctx *ctx,
6518 unsigned long start_jiffies, bool cap_entries)
6520 unsigned long timeout = start_jiffies + ctx->sq_thread_idle;
6521 struct io_sq_data *sqd = ctx->sq_data;
6522 unsigned int to_submit;
6526 if (!list_empty(&ctx->iopoll_list)) {
6527 unsigned nr_events = 0;
6529 mutex_lock(&ctx->uring_lock);
6530 if (!list_empty(&ctx->iopoll_list) && !need_resched())
6531 io_do_iopoll(ctx, &nr_events, 0);
6532 mutex_unlock(&ctx->uring_lock);
6535 to_submit = io_sqring_entries(ctx);
6538 * If submit got -EBUSY, flag us as needing the application
6539 * to enter the kernel to reap and flush events.
6541 if (!to_submit || ret == -EBUSY || need_resched()) {
6543 * Drop cur_mm before scheduling, we can't hold it for
6544 * long periods (or over schedule()). Do this before
6545 * adding ourselves to the waitqueue, as the unuse/drop
6548 io_sq_thread_drop_mm();
6551 * We're polling. If we're within the defined idle
6552 * period, then let us spin without work before going
6553 * to sleep. The exception is if we got EBUSY doing
6554 * more IO, we should wait for the application to
6555 * reap events and wake us up.
6557 if (!list_empty(&ctx->iopoll_list) || need_resched() ||
6558 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6559 !percpu_ref_is_dying(&ctx->refs)))
6562 prepare_to_wait(&sqd->wait, &ctx->sqo_wait_entry,
6563 TASK_INTERRUPTIBLE);
6566 * While doing polled IO, before going to sleep, we need
6567 * to check if there are new reqs added to iopoll_list,
6568 * it is because reqs may have been punted to io worker
6569 * and will be added to iopoll_list later, hence check
6570 * the iopoll_list again.
6572 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6573 !list_empty_careful(&ctx->iopoll_list)) {
6574 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6578 to_submit = io_sqring_entries(ctx);
6579 if (!to_submit || ret == -EBUSY)
6583 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6584 io_ring_clear_wakeup_flag(ctx);
6586 /* if we're handling multiple rings, cap submit size for fairness */
6587 if (cap_entries && to_submit > 8)
6590 mutex_lock(&ctx->uring_lock);
6591 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6592 ret = io_submit_sqes(ctx, to_submit);
6593 mutex_unlock(&ctx->uring_lock);
6595 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6596 wake_up(&ctx->sqo_sq_wait);
6598 return SQT_DID_WORK;
6601 static void io_sqd_init_new(struct io_sq_data *sqd)
6603 struct io_ring_ctx *ctx;
6605 while (!list_empty(&sqd->ctx_new_list)) {
6606 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6607 init_wait(&ctx->sqo_wait_entry);
6608 ctx->sqo_wait_entry.func = io_sq_wake_function;
6609 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6610 complete(&ctx->sq_thread_comp);
6614 static int io_sq_thread(void *data)
6616 struct cgroup_subsys_state *cur_css = NULL;
6617 const struct cred *old_cred = NULL;
6618 struct io_sq_data *sqd = data;
6619 struct io_ring_ctx *ctx;
6620 unsigned long start_jiffies;
6622 start_jiffies = jiffies;
6623 while (!kthread_should_stop()) {
6624 enum sq_ret ret = 0;
6628 * Any changes to the sqd lists are synchronized through the
6629 * kthread parking. This synchronizes the thread vs users,
6630 * the users are synchronized on the sqd->ctx_lock.
6632 if (kthread_should_park())
6635 if (unlikely(!list_empty(&sqd->ctx_new_list)))
6636 io_sqd_init_new(sqd);
6638 cap_entries = !list_is_singular(&sqd->ctx_list);
6640 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6641 if (current->cred != ctx->creds) {
6643 revert_creds(old_cred);
6644 old_cred = override_creds(ctx->creds);
6646 io_sq_thread_associate_blkcg(ctx, &cur_css);
6648 ret |= __io_sq_thread(ctx, start_jiffies, cap_entries);
6650 io_sq_thread_drop_mm();
6653 if (ret & SQT_SPIN) {
6656 } else if (ret == SQT_IDLE) {
6657 if (kthread_should_park())
6659 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6660 io_ring_set_wakeup_flag(ctx);
6662 start_jiffies = jiffies;
6663 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6664 io_ring_clear_wakeup_flag(ctx);
6671 io_sq_thread_unassociate_blkcg();
6673 revert_creds(old_cred);
6680 struct io_wait_queue {
6681 struct wait_queue_entry wq;
6682 struct io_ring_ctx *ctx;
6684 unsigned nr_timeouts;
6687 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6689 struct io_ring_ctx *ctx = iowq->ctx;
6692 * Wake up if we have enough events, or if a timeout occurred since we
6693 * started waiting. For timeouts, we always want to return to userspace,
6694 * regardless of event count.
6696 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6697 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6700 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6701 int wake_flags, void *key)
6703 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6706 /* use noflush == true, as we can't safely rely on locking context */
6707 if (!io_should_wake(iowq, true))
6710 return autoremove_wake_function(curr, mode, wake_flags, key);
6713 static int io_run_task_work_sig(void)
6715 if (io_run_task_work())
6717 if (!signal_pending(current))
6719 if (current->jobctl & JOBCTL_TASK_WORK) {
6720 spin_lock_irq(¤t->sighand->siglock);
6721 current->jobctl &= ~JOBCTL_TASK_WORK;
6722 recalc_sigpending();
6723 spin_unlock_irq(¤t->sighand->siglock);
6730 * Wait until events become available, if we don't already have some. The
6731 * application must reap them itself, as they reside on the shared cq ring.
6733 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6734 const sigset_t __user *sig, size_t sigsz)
6736 struct io_wait_queue iowq = {
6739 .func = io_wake_function,
6740 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6743 .to_wait = min_events,
6745 struct io_rings *rings = ctx->rings;
6749 if (io_cqring_events(ctx, false) >= min_events)
6751 if (!io_run_task_work())
6756 #ifdef CONFIG_COMPAT
6757 if (in_compat_syscall())
6758 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6762 ret = set_user_sigmask(sig, sigsz);
6768 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6769 trace_io_uring_cqring_wait(ctx, min_events);
6771 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6772 TASK_INTERRUPTIBLE);
6773 /* make sure we run task_work before checking for signals */
6774 ret = io_run_task_work_sig();
6779 if (io_should_wake(&iowq, false))
6783 finish_wait(&ctx->wait, &iowq.wq);
6785 restore_saved_sigmask_unless(ret == -EINTR);
6787 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6790 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6792 #if defined(CONFIG_UNIX)
6793 if (ctx->ring_sock) {
6794 struct sock *sock = ctx->ring_sock->sk;
6795 struct sk_buff *skb;
6797 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6803 for (i = 0; i < ctx->nr_user_files; i++) {
6806 file = io_file_from_index(ctx, i);
6813 static void io_file_ref_kill(struct percpu_ref *ref)
6815 struct fixed_file_data *data;
6817 data = container_of(ref, struct fixed_file_data, refs);
6818 complete(&data->done);
6821 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6823 struct fixed_file_data *data = ctx->file_data;
6824 struct fixed_file_ref_node *ref_node = NULL;
6825 unsigned nr_tables, i;
6830 spin_lock(&data->lock);
6831 if (!list_empty(&data->ref_list))
6832 ref_node = list_first_entry(&data->ref_list,
6833 struct fixed_file_ref_node, node);
6834 spin_unlock(&data->lock);
6836 percpu_ref_kill(&ref_node->refs);
6838 percpu_ref_kill(&data->refs);
6840 /* wait for all refs nodes to complete */
6841 flush_delayed_work(&ctx->file_put_work);
6842 wait_for_completion(&data->done);
6844 __io_sqe_files_unregister(ctx);
6845 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6846 for (i = 0; i < nr_tables; i++)
6847 kfree(data->table[i].files);
6849 percpu_ref_exit(&data->refs);
6851 ctx->file_data = NULL;
6852 ctx->nr_user_files = 0;
6856 static void io_put_sq_data(struct io_sq_data *sqd)
6858 if (refcount_dec_and_test(&sqd->refs)) {
6860 * The park is a bit of a work-around, without it we get
6861 * warning spews on shutdown with SQPOLL set and affinity
6862 * set to a single CPU.
6865 kthread_park(sqd->thread);
6866 kthread_stop(sqd->thread);
6873 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
6875 struct io_ring_ctx *ctx_attach;
6876 struct io_sq_data *sqd;
6879 f = fdget(p->wq_fd);
6881 return ERR_PTR(-ENXIO);
6882 if (f.file->f_op != &io_uring_fops) {
6884 return ERR_PTR(-EINVAL);
6887 ctx_attach = f.file->private_data;
6888 sqd = ctx_attach->sq_data;
6891 return ERR_PTR(-EINVAL);
6894 refcount_inc(&sqd->refs);
6899 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
6901 struct io_sq_data *sqd;
6903 if (p->flags & IORING_SETUP_ATTACH_WQ)
6904 return io_attach_sq_data(p);
6906 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
6908 return ERR_PTR(-ENOMEM);
6910 refcount_set(&sqd->refs, 1);
6911 INIT_LIST_HEAD(&sqd->ctx_list);
6912 INIT_LIST_HEAD(&sqd->ctx_new_list);
6913 mutex_init(&sqd->ctx_lock);
6914 mutex_init(&sqd->lock);
6915 init_waitqueue_head(&sqd->wait);
6919 static void io_sq_thread_unpark(struct io_sq_data *sqd)
6920 __releases(&sqd->lock)
6924 kthread_unpark(sqd->thread);
6925 mutex_unlock(&sqd->lock);
6928 static void io_sq_thread_park(struct io_sq_data *sqd)
6929 __acquires(&sqd->lock)
6933 mutex_lock(&sqd->lock);
6934 kthread_park(sqd->thread);
6937 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6939 struct io_sq_data *sqd = ctx->sq_data;
6944 * We may arrive here from the error branch in
6945 * io_sq_offload_create() where the kthread is created
6946 * without being waked up, thus wake it up now to make
6947 * sure the wait will complete.
6949 wake_up_process(sqd->thread);
6950 wait_for_completion(&ctx->sq_thread_comp);
6952 io_sq_thread_park(sqd);
6955 mutex_lock(&sqd->ctx_lock);
6956 list_del(&ctx->sqd_list);
6957 mutex_unlock(&sqd->ctx_lock);
6960 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6961 io_sq_thread_unpark(sqd);
6964 io_put_sq_data(sqd);
6965 ctx->sq_data = NULL;
6969 static void io_finish_async(struct io_ring_ctx *ctx)
6971 io_sq_thread_stop(ctx);
6974 io_wq_destroy(ctx->io_wq);
6979 #if defined(CONFIG_UNIX)
6981 * Ensure the UNIX gc is aware of our file set, so we are certain that
6982 * the io_uring can be safely unregistered on process exit, even if we have
6983 * loops in the file referencing.
6985 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6987 struct sock *sk = ctx->ring_sock->sk;
6988 struct scm_fp_list *fpl;
6989 struct sk_buff *skb;
6992 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6996 skb = alloc_skb(0, GFP_KERNEL);
7005 fpl->user = get_uid(ctx->user);
7006 for (i = 0; i < nr; i++) {
7007 struct file *file = io_file_from_index(ctx, i + offset);
7011 fpl->fp[nr_files] = get_file(file);
7012 unix_inflight(fpl->user, fpl->fp[nr_files]);
7017 fpl->max = SCM_MAX_FD;
7018 fpl->count = nr_files;
7019 UNIXCB(skb).fp = fpl;
7020 skb->destructor = unix_destruct_scm;
7021 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7022 skb_queue_head(&sk->sk_receive_queue, skb);
7024 for (i = 0; i < nr_files; i++)
7035 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7036 * causes regular reference counting to break down. We rely on the UNIX
7037 * garbage collection to take care of this problem for us.
7039 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7041 unsigned left, total;
7045 left = ctx->nr_user_files;
7047 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7049 ret = __io_sqe_files_scm(ctx, this_files, total);
7053 total += this_files;
7059 while (total < ctx->nr_user_files) {
7060 struct file *file = io_file_from_index(ctx, total);
7070 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7076 static int io_sqe_alloc_file_tables(struct fixed_file_data *file_data,
7077 unsigned nr_tables, unsigned nr_files)
7081 for (i = 0; i < nr_tables; i++) {
7082 struct fixed_file_table *table = &file_data->table[i];
7083 unsigned this_files;
7085 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7086 table->files = kcalloc(this_files, sizeof(struct file *),
7090 nr_files -= this_files;
7096 for (i = 0; i < nr_tables; i++) {
7097 struct fixed_file_table *table = &file_data->table[i];
7098 kfree(table->files);
7103 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
7105 #if defined(CONFIG_UNIX)
7106 struct sock *sock = ctx->ring_sock->sk;
7107 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7108 struct sk_buff *skb;
7111 __skb_queue_head_init(&list);
7114 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7115 * remove this entry and rearrange the file array.
7117 skb = skb_dequeue(head);
7119 struct scm_fp_list *fp;
7121 fp = UNIXCB(skb).fp;
7122 for (i = 0; i < fp->count; i++) {
7125 if (fp->fp[i] != file)
7128 unix_notinflight(fp->user, fp->fp[i]);
7129 left = fp->count - 1 - i;
7131 memmove(&fp->fp[i], &fp->fp[i + 1],
7132 left * sizeof(struct file *));
7139 __skb_queue_tail(&list, skb);
7149 __skb_queue_tail(&list, skb);
7151 skb = skb_dequeue(head);
7154 if (skb_peek(&list)) {
7155 spin_lock_irq(&head->lock);
7156 while ((skb = __skb_dequeue(&list)) != NULL)
7157 __skb_queue_tail(head, skb);
7158 spin_unlock_irq(&head->lock);
7165 struct io_file_put {
7166 struct list_head list;
7170 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
7172 struct fixed_file_data *file_data = ref_node->file_data;
7173 struct io_ring_ctx *ctx = file_data->ctx;
7174 struct io_file_put *pfile, *tmp;
7176 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
7177 list_del(&pfile->list);
7178 io_ring_file_put(ctx, pfile->file);
7182 spin_lock(&file_data->lock);
7183 list_del(&ref_node->node);
7184 spin_unlock(&file_data->lock);
7186 percpu_ref_exit(&ref_node->refs);
7188 percpu_ref_put(&file_data->refs);
7191 static void io_file_put_work(struct work_struct *work)
7193 struct io_ring_ctx *ctx;
7194 struct llist_node *node;
7196 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
7197 node = llist_del_all(&ctx->file_put_llist);
7200 struct fixed_file_ref_node *ref_node;
7201 struct llist_node *next = node->next;
7203 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
7204 __io_file_put_work(ref_node);
7209 static void io_file_data_ref_zero(struct percpu_ref *ref)
7211 struct fixed_file_ref_node *ref_node;
7212 struct io_ring_ctx *ctx;
7216 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
7217 ctx = ref_node->file_data->ctx;
7219 if (percpu_ref_is_dying(&ctx->file_data->refs))
7222 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
7224 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
7226 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
7229 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
7230 struct io_ring_ctx *ctx)
7232 struct fixed_file_ref_node *ref_node;
7234 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7236 return ERR_PTR(-ENOMEM);
7238 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
7241 return ERR_PTR(-ENOMEM);
7243 INIT_LIST_HEAD(&ref_node->node);
7244 INIT_LIST_HEAD(&ref_node->file_list);
7245 ref_node->file_data = ctx->file_data;
7249 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
7251 percpu_ref_exit(&ref_node->refs);
7255 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7258 __s32 __user *fds = (__s32 __user *) arg;
7259 unsigned nr_tables, i;
7261 int fd, ret = -ENOMEM;
7262 struct fixed_file_ref_node *ref_node;
7263 struct fixed_file_data *file_data;
7269 if (nr_args > IORING_MAX_FIXED_FILES)
7272 file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
7275 file_data->ctx = ctx;
7276 init_completion(&file_data->done);
7277 INIT_LIST_HEAD(&file_data->ref_list);
7278 spin_lock_init(&file_data->lock);
7280 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7281 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7283 if (!file_data->table)
7286 if (percpu_ref_init(&file_data->refs, io_file_ref_kill,
7287 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
7290 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7293 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7294 struct fixed_file_table *table;
7297 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7301 /* allow sparse sets */
7311 * Don't allow io_uring instances to be registered. If UNIX
7312 * isn't enabled, then this causes a reference cycle and this
7313 * instance can never get freed. If UNIX is enabled we'll
7314 * handle it just fine, but there's still no point in allowing
7315 * a ring fd as it doesn't support regular read/write anyway.
7317 if (file->f_op == &io_uring_fops) {
7321 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7322 index = i & IORING_FILE_TABLE_MASK;
7323 table->files[index] = file;
7326 ctx->file_data = file_data;
7327 ret = io_sqe_files_scm(ctx);
7329 io_sqe_files_unregister(ctx);
7333 ref_node = alloc_fixed_file_ref_node(ctx);
7334 if (IS_ERR(ref_node)) {
7335 io_sqe_files_unregister(ctx);
7336 return PTR_ERR(ref_node);
7339 file_data->node = ref_node;
7340 spin_lock(&file_data->lock);
7341 list_add(&ref_node->node, &file_data->ref_list);
7342 spin_unlock(&file_data->lock);
7343 percpu_ref_get(&file_data->refs);
7346 for (i = 0; i < ctx->nr_user_files; i++) {
7347 file = io_file_from_index(ctx, i);
7351 for (i = 0; i < nr_tables; i++)
7352 kfree(file_data->table[i].files);
7353 ctx->nr_user_files = 0;
7355 percpu_ref_exit(&file_data->refs);
7357 kfree(file_data->table);
7362 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7365 #if defined(CONFIG_UNIX)
7366 struct sock *sock = ctx->ring_sock->sk;
7367 struct sk_buff_head *head = &sock->sk_receive_queue;
7368 struct sk_buff *skb;
7371 * See if we can merge this file into an existing skb SCM_RIGHTS
7372 * file set. If there's no room, fall back to allocating a new skb
7373 * and filling it in.
7375 spin_lock_irq(&head->lock);
7376 skb = skb_peek(head);
7378 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7380 if (fpl->count < SCM_MAX_FD) {
7381 __skb_unlink(skb, head);
7382 spin_unlock_irq(&head->lock);
7383 fpl->fp[fpl->count] = get_file(file);
7384 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7386 spin_lock_irq(&head->lock);
7387 __skb_queue_head(head, skb);
7392 spin_unlock_irq(&head->lock);
7399 return __io_sqe_files_scm(ctx, 1, index);
7405 static int io_queue_file_removal(struct fixed_file_data *data,
7408 struct io_file_put *pfile;
7409 struct fixed_file_ref_node *ref_node = data->node;
7411 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7416 list_add(&pfile->list, &ref_node->file_list);
7421 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7422 struct io_uring_files_update *up,
7425 struct fixed_file_data *data = ctx->file_data;
7426 struct fixed_file_ref_node *ref_node;
7431 bool needs_switch = false;
7433 if (check_add_overflow(up->offset, nr_args, &done))
7435 if (done > ctx->nr_user_files)
7438 ref_node = alloc_fixed_file_ref_node(ctx);
7439 if (IS_ERR(ref_node))
7440 return PTR_ERR(ref_node);
7443 fds = u64_to_user_ptr(up->fds);
7445 struct fixed_file_table *table;
7449 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7453 i = array_index_nospec(up->offset, ctx->nr_user_files);
7454 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7455 index = i & IORING_FILE_TABLE_MASK;
7456 if (table->files[index]) {
7457 file = table->files[index];
7458 err = io_queue_file_removal(data, file);
7461 table->files[index] = NULL;
7462 needs_switch = true;
7471 * Don't allow io_uring instances to be registered. If
7472 * UNIX isn't enabled, then this causes a reference
7473 * cycle and this instance can never get freed. If UNIX
7474 * is enabled we'll handle it just fine, but there's
7475 * still no point in allowing a ring fd as it doesn't
7476 * support regular read/write anyway.
7478 if (file->f_op == &io_uring_fops) {
7483 table->files[index] = file;
7484 err = io_sqe_file_register(ctx, file, i);
7486 table->files[index] = NULL;
7497 percpu_ref_kill(&data->node->refs);
7498 spin_lock(&data->lock);
7499 list_add(&ref_node->node, &data->ref_list);
7500 data->node = ref_node;
7501 spin_unlock(&data->lock);
7502 percpu_ref_get(&ctx->file_data->refs);
7504 destroy_fixed_file_ref_node(ref_node);
7506 return done ? done : err;
7509 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7512 struct io_uring_files_update up;
7514 if (!ctx->file_data)
7518 if (copy_from_user(&up, arg, sizeof(up)))
7523 return __io_sqe_files_update(ctx, &up, nr_args);
7526 static void io_free_work(struct io_wq_work *work)
7528 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7530 /* Consider that io_steal_work() relies on this ref */
7534 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7535 struct io_uring_params *p)
7537 struct io_wq_data data;
7539 struct io_ring_ctx *ctx_attach;
7540 unsigned int concurrency;
7543 data.user = ctx->user;
7544 data.free_work = io_free_work;
7545 data.do_work = io_wq_submit_work;
7547 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7548 /* Do QD, or 4 * CPUS, whatever is smallest */
7549 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7551 ctx->io_wq = io_wq_create(concurrency, &data);
7552 if (IS_ERR(ctx->io_wq)) {
7553 ret = PTR_ERR(ctx->io_wq);
7559 f = fdget(p->wq_fd);
7563 if (f.file->f_op != &io_uring_fops) {
7568 ctx_attach = f.file->private_data;
7569 /* @io_wq is protected by holding the fd */
7570 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7575 ctx->io_wq = ctx_attach->io_wq;
7581 static int io_uring_alloc_task_context(struct task_struct *task)
7583 struct io_uring_task *tctx;
7585 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7586 if (unlikely(!tctx))
7590 init_waitqueue_head(&tctx->wait);
7593 atomic_long_set(&tctx->req_issue, 0);
7594 atomic_long_set(&tctx->req_complete, 0);
7595 task->io_uring = tctx;
7599 void __io_uring_free(struct task_struct *tsk)
7601 struct io_uring_task *tctx = tsk->io_uring;
7603 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7605 tsk->io_uring = NULL;
7608 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7609 struct io_uring_params *p)
7613 if (ctx->flags & IORING_SETUP_SQPOLL) {
7614 struct io_sq_data *sqd;
7617 if (!capable(CAP_SYS_ADMIN))
7620 sqd = io_get_sq_data(p);
7627 io_sq_thread_park(sqd);
7628 mutex_lock(&sqd->ctx_lock);
7629 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7630 mutex_unlock(&sqd->ctx_lock);
7631 io_sq_thread_unpark(sqd);
7633 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7634 if (!ctx->sq_thread_idle)
7635 ctx->sq_thread_idle = HZ;
7640 if (p->flags & IORING_SETUP_SQ_AFF) {
7641 int cpu = p->sq_thread_cpu;
7644 if (cpu >= nr_cpu_ids)
7646 if (!cpu_online(cpu))
7649 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
7650 cpu, "io_uring-sq");
7652 sqd->thread = kthread_create(io_sq_thread, sqd,
7655 if (IS_ERR(sqd->thread)) {
7656 ret = PTR_ERR(sqd->thread);
7660 ret = io_uring_alloc_task_context(sqd->thread);
7663 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7664 /* Can't have SQ_AFF without SQPOLL */
7670 ret = io_init_wq_offload(ctx, p);
7676 io_finish_async(ctx);
7680 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7682 struct io_sq_data *sqd = ctx->sq_data;
7684 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
7685 wake_up_process(sqd->thread);
7688 static inline void __io_unaccount_mem(struct user_struct *user,
7689 unsigned long nr_pages)
7691 atomic_long_sub(nr_pages, &user->locked_vm);
7694 static inline int __io_account_mem(struct user_struct *user,
7695 unsigned long nr_pages)
7697 unsigned long page_limit, cur_pages, new_pages;
7699 /* Don't allow more pages than we can safely lock */
7700 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7703 cur_pages = atomic_long_read(&user->locked_vm);
7704 new_pages = cur_pages + nr_pages;
7705 if (new_pages > page_limit)
7707 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7708 new_pages) != cur_pages);
7713 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7714 enum io_mem_account acct)
7717 __io_unaccount_mem(ctx->user, nr_pages);
7719 if (ctx->mm_account) {
7720 if (acct == ACCT_LOCKED)
7721 ctx->mm_account->locked_vm -= nr_pages;
7722 else if (acct == ACCT_PINNED)
7723 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
7727 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7728 enum io_mem_account acct)
7732 if (ctx->limit_mem) {
7733 ret = __io_account_mem(ctx->user, nr_pages);
7738 if (ctx->mm_account) {
7739 if (acct == ACCT_LOCKED)
7740 ctx->mm_account->locked_vm += nr_pages;
7741 else if (acct == ACCT_PINNED)
7742 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
7748 static void io_mem_free(void *ptr)
7755 page = virt_to_head_page(ptr);
7756 if (put_page_testzero(page))
7757 free_compound_page(page);
7760 static void *io_mem_alloc(size_t size)
7762 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7765 return (void *) __get_free_pages(gfp_flags, get_order(size));
7768 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7771 struct io_rings *rings;
7772 size_t off, sq_array_size;
7774 off = struct_size(rings, cqes, cq_entries);
7775 if (off == SIZE_MAX)
7779 off = ALIGN(off, SMP_CACHE_BYTES);
7787 sq_array_size = array_size(sizeof(u32), sq_entries);
7788 if (sq_array_size == SIZE_MAX)
7791 if (check_add_overflow(off, sq_array_size, &off))
7797 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7801 pages = (size_t)1 << get_order(
7802 rings_size(sq_entries, cq_entries, NULL));
7803 pages += (size_t)1 << get_order(
7804 array_size(sizeof(struct io_uring_sqe), sq_entries));
7809 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7813 if (!ctx->user_bufs)
7816 for (i = 0; i < ctx->nr_user_bufs; i++) {
7817 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7819 for (j = 0; j < imu->nr_bvecs; j++)
7820 unpin_user_page(imu->bvec[j].bv_page);
7822 if (imu->acct_pages)
7823 io_unaccount_mem(ctx, imu->acct_pages, ACCT_PINNED);
7828 kfree(ctx->user_bufs);
7829 ctx->user_bufs = NULL;
7830 ctx->nr_user_bufs = 0;
7834 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7835 void __user *arg, unsigned index)
7837 struct iovec __user *src;
7839 #ifdef CONFIG_COMPAT
7841 struct compat_iovec __user *ciovs;
7842 struct compat_iovec ciov;
7844 ciovs = (struct compat_iovec __user *) arg;
7845 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7848 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7849 dst->iov_len = ciov.iov_len;
7853 src = (struct iovec __user *) arg;
7854 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7860 * Not super efficient, but this is just a registration time. And we do cache
7861 * the last compound head, so generally we'll only do a full search if we don't
7864 * We check if the given compound head page has already been accounted, to
7865 * avoid double accounting it. This allows us to account the full size of the
7866 * page, not just the constituent pages of a huge page.
7868 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
7869 int nr_pages, struct page *hpage)
7873 /* check current page array */
7874 for (i = 0; i < nr_pages; i++) {
7875 if (!PageCompound(pages[i]))
7877 if (compound_head(pages[i]) == hpage)
7881 /* check previously registered pages */
7882 for (i = 0; i < ctx->nr_user_bufs; i++) {
7883 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7885 for (j = 0; j < imu->nr_bvecs; j++) {
7886 if (!PageCompound(imu->bvec[j].bv_page))
7888 if (compound_head(imu->bvec[j].bv_page) == hpage)
7896 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
7897 int nr_pages, struct io_mapped_ubuf *imu,
7898 struct page **last_hpage)
7902 for (i = 0; i < nr_pages; i++) {
7903 if (!PageCompound(pages[i])) {
7908 hpage = compound_head(pages[i]);
7909 if (hpage == *last_hpage)
7911 *last_hpage = hpage;
7912 if (headpage_already_acct(ctx, pages, i, hpage))
7914 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
7918 if (!imu->acct_pages)
7921 ret = io_account_mem(ctx, imu->acct_pages, ACCT_PINNED);
7923 imu->acct_pages = 0;
7927 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7930 struct vm_area_struct **vmas = NULL;
7931 struct page **pages = NULL;
7932 struct page *last_hpage = NULL;
7933 int i, j, got_pages = 0;
7938 if (!nr_args || nr_args > UIO_MAXIOV)
7941 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7943 if (!ctx->user_bufs)
7946 for (i = 0; i < nr_args; i++) {
7947 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7948 unsigned long off, start, end, ubuf;
7953 ret = io_copy_iov(ctx, &iov, arg, i);
7958 * Don't impose further limits on the size and buffer
7959 * constraints here, we'll -EINVAL later when IO is
7960 * submitted if they are wrong.
7963 if (!iov.iov_base || !iov.iov_len)
7966 /* arbitrary limit, but we need something */
7967 if (iov.iov_len > SZ_1G)
7970 ubuf = (unsigned long) iov.iov_base;
7971 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7972 start = ubuf >> PAGE_SHIFT;
7973 nr_pages = end - start;
7976 if (!pages || nr_pages > got_pages) {
7979 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7981 vmas = kvmalloc_array(nr_pages,
7982 sizeof(struct vm_area_struct *),
7984 if (!pages || !vmas) {
7988 got_pages = nr_pages;
7991 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7998 mmap_read_lock(current->mm);
7999 pret = pin_user_pages(ubuf, nr_pages,
8000 FOLL_WRITE | FOLL_LONGTERM,
8002 if (pret == nr_pages) {
8003 /* don't support file backed memory */
8004 for (j = 0; j < nr_pages; j++) {
8005 struct vm_area_struct *vma = vmas[j];
8008 !is_file_hugepages(vma->vm_file)) {
8014 ret = pret < 0 ? pret : -EFAULT;
8016 mmap_read_unlock(current->mm);
8019 * if we did partial map, or found file backed vmas,
8020 * release any pages we did get
8023 unpin_user_pages(pages, pret);
8028 ret = io_buffer_account_pin(ctx, pages, pret, imu, &last_hpage);
8030 unpin_user_pages(pages, pret);
8035 off = ubuf & ~PAGE_MASK;
8037 for (j = 0; j < nr_pages; j++) {
8040 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8041 imu->bvec[j].bv_page = pages[j];
8042 imu->bvec[j].bv_len = vec_len;
8043 imu->bvec[j].bv_offset = off;
8047 /* store original address for later verification */
8049 imu->len = iov.iov_len;
8050 imu->nr_bvecs = nr_pages;
8052 ctx->nr_user_bufs++;
8060 io_sqe_buffer_unregister(ctx);
8064 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8066 __s32 __user *fds = arg;
8072 if (copy_from_user(&fd, fds, sizeof(*fds)))
8075 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8076 if (IS_ERR(ctx->cq_ev_fd)) {
8077 int ret = PTR_ERR(ctx->cq_ev_fd);
8078 ctx->cq_ev_fd = NULL;
8085 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8087 if (ctx->cq_ev_fd) {
8088 eventfd_ctx_put(ctx->cq_ev_fd);
8089 ctx->cq_ev_fd = NULL;
8096 static int __io_destroy_buffers(int id, void *p, void *data)
8098 struct io_ring_ctx *ctx = data;
8099 struct io_buffer *buf = p;
8101 __io_remove_buffers(ctx, buf, id, -1U);
8105 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8107 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8108 idr_destroy(&ctx->io_buffer_idr);
8111 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8113 io_finish_async(ctx);
8114 io_sqe_buffer_unregister(ctx);
8116 if (ctx->sqo_task) {
8117 put_task_struct(ctx->sqo_task);
8118 ctx->sqo_task = NULL;
8119 mmdrop(ctx->mm_account);
8120 ctx->mm_account = NULL;
8123 #ifdef CONFIG_BLK_CGROUP
8124 if (ctx->sqo_blkcg_css)
8125 css_put(ctx->sqo_blkcg_css);
8128 io_sqe_files_unregister(ctx);
8129 io_eventfd_unregister(ctx);
8130 io_destroy_buffers(ctx);
8131 idr_destroy(&ctx->personality_idr);
8133 #if defined(CONFIG_UNIX)
8134 if (ctx->ring_sock) {
8135 ctx->ring_sock->file = NULL; /* so that iput() is called */
8136 sock_release(ctx->ring_sock);
8140 io_mem_free(ctx->rings);
8141 io_mem_free(ctx->sq_sqes);
8143 percpu_ref_exit(&ctx->refs);
8144 free_uid(ctx->user);
8145 put_cred(ctx->creds);
8146 kfree(ctx->cancel_hash);
8147 kmem_cache_free(req_cachep, ctx->fallback_req);
8151 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8153 struct io_ring_ctx *ctx = file->private_data;
8156 poll_wait(file, &ctx->cq_wait, wait);
8158 * synchronizes with barrier from wq_has_sleeper call in
8162 if (!io_sqring_full(ctx))
8163 mask |= EPOLLOUT | EPOLLWRNORM;
8164 if (io_cqring_events(ctx, false))
8165 mask |= EPOLLIN | EPOLLRDNORM;
8170 static int io_uring_fasync(int fd, struct file *file, int on)
8172 struct io_ring_ctx *ctx = file->private_data;
8174 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8177 static int io_remove_personalities(int id, void *p, void *data)
8179 struct io_ring_ctx *ctx = data;
8180 const struct cred *cred;
8182 cred = idr_remove(&ctx->personality_idr, id);
8188 static void io_ring_exit_work(struct work_struct *work)
8190 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8194 * If we're doing polled IO and end up having requests being
8195 * submitted async (out-of-line), then completions can come in while
8196 * we're waiting for refs to drop. We need to reap these manually,
8197 * as nobody else will be looking for them.
8201 io_cqring_overflow_flush(ctx, true, NULL, NULL);
8202 io_iopoll_try_reap_events(ctx);
8203 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8204 io_ring_ctx_free(ctx);
8207 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8209 mutex_lock(&ctx->uring_lock);
8210 percpu_ref_kill(&ctx->refs);
8211 mutex_unlock(&ctx->uring_lock);
8213 io_kill_timeouts(ctx, NULL);
8214 io_poll_remove_all(ctx, NULL);
8217 io_wq_cancel_all(ctx->io_wq);
8219 /* if we failed setting up the ctx, we might not have any rings */
8221 io_cqring_overflow_flush(ctx, true, NULL, NULL);
8222 io_iopoll_try_reap_events(ctx);
8223 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8226 * Do this upfront, so we won't have a grace period where the ring
8227 * is closed but resources aren't reaped yet. This can cause
8228 * spurious failure in setting up a new ring.
8230 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
8233 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8235 * Use system_unbound_wq to avoid spawning tons of event kworkers
8236 * if we're exiting a ton of rings at the same time. It just adds
8237 * noise and overhead, there's no discernable change in runtime
8238 * over using system_wq.
8240 queue_work(system_unbound_wq, &ctx->exit_work);
8243 static int io_uring_release(struct inode *inode, struct file *file)
8245 struct io_ring_ctx *ctx = file->private_data;
8247 file->private_data = NULL;
8248 io_ring_ctx_wait_and_kill(ctx);
8252 static bool io_wq_files_match(struct io_wq_work *work, void *data)
8254 struct files_struct *files = data;
8256 return !files || work->files == files;
8260 * Returns true if 'preq' is the link parent of 'req'
8262 static bool io_match_link(struct io_kiocb *preq, struct io_kiocb *req)
8264 struct io_kiocb *link;
8266 if (!(preq->flags & REQ_F_LINK_HEAD))
8269 list_for_each_entry(link, &preq->link_list, link_list) {
8277 static bool io_match_link_files(struct io_kiocb *req,
8278 struct files_struct *files)
8280 struct io_kiocb *link;
8282 if (io_match_files(req, files))
8284 if (req->flags & REQ_F_LINK_HEAD) {
8285 list_for_each_entry(link, &req->link_list, link_list) {
8286 if (io_match_files(link, files))
8294 * We're looking to cancel 'req' because it's holding on to our files, but
8295 * 'req' could be a link to another request. See if it is, and cancel that
8296 * parent request if so.
8298 static bool io_poll_remove_link(struct io_ring_ctx *ctx, struct io_kiocb *req)
8300 struct hlist_node *tmp;
8301 struct io_kiocb *preq;
8305 spin_lock_irq(&ctx->completion_lock);
8306 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8307 struct hlist_head *list;
8309 list = &ctx->cancel_hash[i];
8310 hlist_for_each_entry_safe(preq, tmp, list, hash_node) {
8311 found = io_match_link(preq, req);
8313 io_poll_remove_one(preq);
8318 spin_unlock_irq(&ctx->completion_lock);
8322 static bool io_timeout_remove_link(struct io_ring_ctx *ctx,
8323 struct io_kiocb *req)
8325 struct io_kiocb *preq;
8328 spin_lock_irq(&ctx->completion_lock);
8329 list_for_each_entry(preq, &ctx->timeout_list, timeout.list) {
8330 found = io_match_link(preq, req);
8332 __io_timeout_cancel(preq);
8336 spin_unlock_irq(&ctx->completion_lock);
8340 static bool io_cancel_link_cb(struct io_wq_work *work, void *data)
8342 return io_match_link(container_of(work, struct io_kiocb, work), data);
8345 static void io_attempt_cancel(struct io_ring_ctx *ctx, struct io_kiocb *req)
8347 enum io_wq_cancel cret;
8349 /* cancel this particular work, if it's running */
8350 cret = io_wq_cancel_work(ctx->io_wq, &req->work);
8351 if (cret != IO_WQ_CANCEL_NOTFOUND)
8354 /* find links that hold this pending, cancel those */
8355 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_link_cb, req, true);
8356 if (cret != IO_WQ_CANCEL_NOTFOUND)
8359 /* if we have a poll link holding this pending, cancel that */
8360 if (io_poll_remove_link(ctx, req))
8363 /* final option, timeout link is holding this req pending */
8364 io_timeout_remove_link(ctx, req);
8367 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8368 struct files_struct *files)
8370 struct io_defer_entry *de = NULL;
8373 spin_lock_irq(&ctx->completion_lock);
8374 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8375 if (io_match_link_files(de->req, files)) {
8376 list_cut_position(&list, &ctx->defer_list, &de->list);
8380 spin_unlock_irq(&ctx->completion_lock);
8382 while (!list_empty(&list)) {
8383 de = list_first_entry(&list, struct io_defer_entry, list);
8384 list_del_init(&de->list);
8385 req_set_fail_links(de->req);
8386 io_put_req(de->req);
8387 io_req_complete(de->req, -ECANCELED);
8393 * Returns true if we found and killed one or more files pinning requests
8395 static bool io_uring_cancel_files(struct io_ring_ctx *ctx,
8396 struct files_struct *files)
8398 if (list_empty_careful(&ctx->inflight_list))
8401 io_cancel_defer_files(ctx, files);
8402 /* cancel all at once, should be faster than doing it one by one*/
8403 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
8405 while (!list_empty_careful(&ctx->inflight_list)) {
8406 struct io_kiocb *cancel_req = NULL, *req;
8409 spin_lock_irq(&ctx->inflight_lock);
8410 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
8411 if (files && req->work.files != files)
8413 /* req is being completed, ignore */
8414 if (!refcount_inc_not_zero(&req->refs))
8420 prepare_to_wait(&ctx->inflight_wait, &wait,
8421 TASK_UNINTERRUPTIBLE);
8422 spin_unlock_irq(&ctx->inflight_lock);
8424 /* We need to keep going until we don't find a matching req */
8427 /* cancel this request, or head link requests */
8428 io_attempt_cancel(ctx, cancel_req);
8429 io_put_req(cancel_req);
8430 /* cancellations _may_ trigger task work */
8433 finish_wait(&ctx->inflight_wait, &wait);
8439 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8441 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8442 struct task_struct *task = data;
8444 return io_task_match(req, task);
8447 static bool __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8448 struct task_struct *task,
8449 struct files_struct *files)
8453 ret = io_uring_cancel_files(ctx, files);
8455 enum io_wq_cancel cret;
8457 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, task, true);
8458 if (cret != IO_WQ_CANCEL_NOTFOUND)
8461 /* SQPOLL thread does its own polling */
8462 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8463 while (!list_empty_careful(&ctx->iopoll_list)) {
8464 io_iopoll_try_reap_events(ctx);
8469 ret |= io_poll_remove_all(ctx, task);
8470 ret |= io_kill_timeouts(ctx, task);
8477 * We need to iteratively cancel requests, in case a request has dependent
8478 * hard links. These persist even for failure of cancelations, hence keep
8479 * looping until none are found.
8481 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8482 struct files_struct *files)
8484 struct task_struct *task = current;
8486 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data)
8487 task = ctx->sq_data->thread;
8489 io_cqring_overflow_flush(ctx, true, task, files);
8491 while (__io_uring_cancel_task_requests(ctx, task, files)) {
8498 * Note that this task has used io_uring. We use it for cancelation purposes.
8500 static int io_uring_add_task_file(struct file *file)
8502 struct io_uring_task *tctx = current->io_uring;
8504 if (unlikely(!tctx)) {
8507 ret = io_uring_alloc_task_context(current);
8510 tctx = current->io_uring;
8512 if (tctx->last != file) {
8513 void *old = xa_load(&tctx->xa, (unsigned long)file);
8517 xa_store(&tctx->xa, (unsigned long)file, file, GFP_KERNEL);
8526 * Remove this io_uring_file -> task mapping.
8528 static void io_uring_del_task_file(struct file *file)
8530 struct io_uring_task *tctx = current->io_uring;
8532 if (tctx->last == file)
8534 file = xa_erase(&tctx->xa, (unsigned long)file);
8539 static void __io_uring_attempt_task_drop(struct file *file)
8541 struct file *old = xa_load(¤t->io_uring->xa, (unsigned long)file);
8544 io_uring_del_task_file(file);
8548 * Drop task note for this file if we're the only ones that hold it after
8551 static void io_uring_attempt_task_drop(struct file *file, bool exiting)
8553 if (!current->io_uring)
8556 * fput() is pending, will be 2 if the only other ref is our potential
8557 * task file note. If the task is exiting, drop regardless of count.
8559 if (!exiting && atomic_long_read(&file->f_count) != 2)
8562 __io_uring_attempt_task_drop(file);
8565 void __io_uring_files_cancel(struct files_struct *files)
8567 struct io_uring_task *tctx = current->io_uring;
8569 unsigned long index;
8571 /* make sure overflow events are dropped */
8572 tctx->in_idle = true;
8574 xa_for_each(&tctx->xa, index, file) {
8575 struct io_ring_ctx *ctx = file->private_data;
8577 io_uring_cancel_task_requests(ctx, files);
8579 io_uring_del_task_file(file);
8583 static inline bool io_uring_task_idle(struct io_uring_task *tctx)
8585 return atomic_long_read(&tctx->req_issue) ==
8586 atomic_long_read(&tctx->req_complete);
8590 * Find any io_uring fd that this task has registered or done IO on, and cancel
8593 void __io_uring_task_cancel(void)
8595 struct io_uring_task *tctx = current->io_uring;
8599 /* make sure overflow events are dropped */
8600 tctx->in_idle = true;
8602 while (!io_uring_task_idle(tctx)) {
8603 /* read completions before cancelations */
8604 completions = atomic_long_read(&tctx->req_complete);
8605 __io_uring_files_cancel(NULL);
8607 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8610 * If we've seen completions, retry. This avoids a race where
8611 * a completion comes in before we did prepare_to_wait().
8613 if (completions != atomic_long_read(&tctx->req_complete))
8615 if (io_uring_task_idle(tctx))
8620 finish_wait(&tctx->wait, &wait);
8621 tctx->in_idle = false;
8624 static int io_uring_flush(struct file *file, void *data)
8626 struct io_ring_ctx *ctx = file->private_data;
8629 * If the task is going away, cancel work it may have pending
8631 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
8634 io_uring_cancel_task_requests(ctx, data);
8635 io_uring_attempt_task_drop(file, !data);
8639 static void *io_uring_validate_mmap_request(struct file *file,
8640 loff_t pgoff, size_t sz)
8642 struct io_ring_ctx *ctx = file->private_data;
8643 loff_t offset = pgoff << PAGE_SHIFT;
8648 case IORING_OFF_SQ_RING:
8649 case IORING_OFF_CQ_RING:
8652 case IORING_OFF_SQES:
8656 return ERR_PTR(-EINVAL);
8659 page = virt_to_head_page(ptr);
8660 if (sz > page_size(page))
8661 return ERR_PTR(-EINVAL);
8668 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8670 size_t sz = vma->vm_end - vma->vm_start;
8674 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
8676 return PTR_ERR(ptr);
8678 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
8679 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
8682 #else /* !CONFIG_MMU */
8684 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8686 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
8689 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
8691 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
8694 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
8695 unsigned long addr, unsigned long len,
8696 unsigned long pgoff, unsigned long flags)
8700 ptr = io_uring_validate_mmap_request(file, pgoff, len);
8702 return PTR_ERR(ptr);
8704 return (unsigned long) ptr;
8707 #endif /* !CONFIG_MMU */
8709 static void io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
8714 if (!io_sqring_full(ctx))
8717 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
8719 if (!io_sqring_full(ctx))
8723 } while (!signal_pending(current));
8725 finish_wait(&ctx->sqo_sq_wait, &wait);
8728 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
8729 u32, min_complete, u32, flags, const sigset_t __user *, sig,
8732 struct io_ring_ctx *ctx;
8739 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
8740 IORING_ENTER_SQ_WAIT))
8748 if (f.file->f_op != &io_uring_fops)
8752 ctx = f.file->private_data;
8753 if (!percpu_ref_tryget(&ctx->refs))
8757 if (ctx->flags & IORING_SETUP_R_DISABLED)
8761 * For SQ polling, the thread will do all submissions and completions.
8762 * Just return the requested submit count, and wake the thread if
8766 if (ctx->flags & IORING_SETUP_SQPOLL) {
8767 if (!list_empty_careful(&ctx->cq_overflow_list))
8768 io_cqring_overflow_flush(ctx, false, NULL, NULL);
8769 if (flags & IORING_ENTER_SQ_WAKEUP)
8770 wake_up(&ctx->sq_data->wait);
8771 if (flags & IORING_ENTER_SQ_WAIT)
8772 io_sqpoll_wait_sq(ctx);
8773 submitted = to_submit;
8774 } else if (to_submit) {
8775 ret = io_uring_add_task_file(f.file);
8778 mutex_lock(&ctx->uring_lock);
8779 submitted = io_submit_sqes(ctx, to_submit);
8780 mutex_unlock(&ctx->uring_lock);
8782 if (submitted != to_submit)
8785 if (flags & IORING_ENTER_GETEVENTS) {
8786 min_complete = min(min_complete, ctx->cq_entries);
8789 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
8790 * space applications don't need to do io completion events
8791 * polling again, they can rely on io_sq_thread to do polling
8792 * work, which can reduce cpu usage and uring_lock contention.
8794 if (ctx->flags & IORING_SETUP_IOPOLL &&
8795 !(ctx->flags & IORING_SETUP_SQPOLL)) {
8796 ret = io_iopoll_check(ctx, min_complete);
8798 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
8803 percpu_ref_put(&ctx->refs);
8806 return submitted ? submitted : ret;
8809 #ifdef CONFIG_PROC_FS
8810 static int io_uring_show_cred(int id, void *p, void *data)
8812 const struct cred *cred = p;
8813 struct seq_file *m = data;
8814 struct user_namespace *uns = seq_user_ns(m);
8815 struct group_info *gi;
8820 seq_printf(m, "%5d\n", id);
8821 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
8822 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
8823 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
8824 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
8825 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
8826 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
8827 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
8828 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
8829 seq_puts(m, "\n\tGroups:\t");
8830 gi = cred->group_info;
8831 for (g = 0; g < gi->ngroups; g++) {
8832 seq_put_decimal_ull(m, g ? " " : "",
8833 from_kgid_munged(uns, gi->gid[g]));
8835 seq_puts(m, "\n\tCapEff:\t");
8836 cap = cred->cap_effective;
8837 CAP_FOR_EACH_U32(__capi)
8838 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8843 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8845 struct io_sq_data *sq = NULL;
8850 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
8851 * since fdinfo case grabs it in the opposite direction of normal use
8852 * cases. If we fail to get the lock, we just don't iterate any
8853 * structures that could be going away outside the io_uring mutex.
8855 has_lock = mutex_trylock(&ctx->uring_lock);
8857 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
8860 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
8861 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
8862 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8863 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
8864 struct fixed_file_table *table;
8867 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8868 f = table->files[i & IORING_FILE_TABLE_MASK];
8870 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8872 seq_printf(m, "%5u: <none>\n", i);
8874 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8875 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
8876 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8878 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8879 (unsigned int) buf->len);
8881 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
8882 seq_printf(m, "Personalities:\n");
8883 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8885 seq_printf(m, "PollList:\n");
8886 spin_lock_irq(&ctx->completion_lock);
8887 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8888 struct hlist_head *list = &ctx->cancel_hash[i];
8889 struct io_kiocb *req;
8891 hlist_for_each_entry(req, list, hash_node)
8892 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
8893 req->task->task_works != NULL);
8895 spin_unlock_irq(&ctx->completion_lock);
8897 mutex_unlock(&ctx->uring_lock);
8900 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8902 struct io_ring_ctx *ctx = f->private_data;
8904 if (percpu_ref_tryget(&ctx->refs)) {
8905 __io_uring_show_fdinfo(ctx, m);
8906 percpu_ref_put(&ctx->refs);
8911 static const struct file_operations io_uring_fops = {
8912 .release = io_uring_release,
8913 .flush = io_uring_flush,
8914 .mmap = io_uring_mmap,
8916 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8917 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8919 .poll = io_uring_poll,
8920 .fasync = io_uring_fasync,
8921 #ifdef CONFIG_PROC_FS
8922 .show_fdinfo = io_uring_show_fdinfo,
8926 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8927 struct io_uring_params *p)
8929 struct io_rings *rings;
8930 size_t size, sq_array_offset;
8932 /* make sure these are sane, as we already accounted them */
8933 ctx->sq_entries = p->sq_entries;
8934 ctx->cq_entries = p->cq_entries;
8936 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8937 if (size == SIZE_MAX)
8940 rings = io_mem_alloc(size);
8945 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8946 rings->sq_ring_mask = p->sq_entries - 1;
8947 rings->cq_ring_mask = p->cq_entries - 1;
8948 rings->sq_ring_entries = p->sq_entries;
8949 rings->cq_ring_entries = p->cq_entries;
8950 ctx->sq_mask = rings->sq_ring_mask;
8951 ctx->cq_mask = rings->cq_ring_mask;
8953 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8954 if (size == SIZE_MAX) {
8955 io_mem_free(ctx->rings);
8960 ctx->sq_sqes = io_mem_alloc(size);
8961 if (!ctx->sq_sqes) {
8962 io_mem_free(ctx->rings);
8971 * Allocate an anonymous fd, this is what constitutes the application
8972 * visible backing of an io_uring instance. The application mmaps this
8973 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8974 * we have to tie this fd to a socket for file garbage collection purposes.
8976 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8981 #if defined(CONFIG_UNIX)
8982 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8988 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8992 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8993 O_RDWR | O_CLOEXEC);
8997 ret = PTR_ERR(file);
9001 #if defined(CONFIG_UNIX)
9002 ctx->ring_sock->file = file;
9004 if (unlikely(io_uring_add_task_file(file))) {
9005 file = ERR_PTR(-ENOMEM);
9008 fd_install(ret, file);
9011 #if defined(CONFIG_UNIX)
9012 sock_release(ctx->ring_sock);
9013 ctx->ring_sock = NULL;
9018 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9019 struct io_uring_params __user *params)
9021 struct user_struct *user = NULL;
9022 struct io_ring_ctx *ctx;
9028 if (entries > IORING_MAX_ENTRIES) {
9029 if (!(p->flags & IORING_SETUP_CLAMP))
9031 entries = IORING_MAX_ENTRIES;
9035 * Use twice as many entries for the CQ ring. It's possible for the
9036 * application to drive a higher depth than the size of the SQ ring,
9037 * since the sqes are only used at submission time. This allows for
9038 * some flexibility in overcommitting a bit. If the application has
9039 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9040 * of CQ ring entries manually.
9042 p->sq_entries = roundup_pow_of_two(entries);
9043 if (p->flags & IORING_SETUP_CQSIZE) {
9045 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9046 * to a power-of-two, if it isn't already. We do NOT impose
9047 * any cq vs sq ring sizing.
9049 if (p->cq_entries < p->sq_entries)
9051 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9052 if (!(p->flags & IORING_SETUP_CLAMP))
9054 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9056 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9058 p->cq_entries = 2 * p->sq_entries;
9061 user = get_uid(current_user());
9062 limit_mem = !capable(CAP_IPC_LOCK);
9065 ret = __io_account_mem(user,
9066 ring_pages(p->sq_entries, p->cq_entries));
9073 ctx = io_ring_ctx_alloc(p);
9076 __io_unaccount_mem(user, ring_pages(p->sq_entries,
9081 ctx->compat = in_compat_syscall();
9083 ctx->creds = get_current_cred();
9085 ctx->sqo_task = get_task_struct(current);
9088 * This is just grabbed for accounting purposes. When a process exits,
9089 * the mm is exited and dropped before the files, hence we need to hang
9090 * on to this mm purely for the purposes of being able to unaccount
9091 * memory (locked/pinned vm). It's not used for anything else.
9093 mmgrab(current->mm);
9094 ctx->mm_account = current->mm;
9096 #ifdef CONFIG_BLK_CGROUP
9098 * The sq thread will belong to the original cgroup it was inited in.
9099 * If the cgroup goes offline (e.g. disabling the io controller), then
9100 * issued bios will be associated with the closest cgroup later in the
9104 ctx->sqo_blkcg_css = blkcg_css();
9105 ret = css_tryget_online(ctx->sqo_blkcg_css);
9108 /* don't init against a dying cgroup, have the user try again */
9109 ctx->sqo_blkcg_css = NULL;
9116 * Account memory _before_ installing the file descriptor. Once
9117 * the descriptor is installed, it can get closed at any time. Also
9118 * do this before hitting the general error path, as ring freeing
9119 * will un-account as well.
9121 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9123 ctx->limit_mem = limit_mem;
9125 ret = io_allocate_scq_urings(ctx, p);
9129 ret = io_sq_offload_create(ctx, p);
9133 if (!(p->flags & IORING_SETUP_R_DISABLED))
9134 io_sq_offload_start(ctx);
9136 memset(&p->sq_off, 0, sizeof(p->sq_off));
9137 p->sq_off.head = offsetof(struct io_rings, sq.head);
9138 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9139 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9140 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9141 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9142 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9143 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9145 memset(&p->cq_off, 0, sizeof(p->cq_off));
9146 p->cq_off.head = offsetof(struct io_rings, cq.head);
9147 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9148 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9149 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9150 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9151 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9152 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9154 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9155 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9156 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9157 IORING_FEAT_POLL_32BITS;
9159 if (copy_to_user(params, p, sizeof(*p))) {
9165 * Install ring fd as the very last thing, so we don't risk someone
9166 * having closed it before we finish setup
9168 ret = io_uring_get_fd(ctx);
9172 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9175 io_ring_ctx_wait_and_kill(ctx);
9180 * Sets up an aio uring context, and returns the fd. Applications asks for a
9181 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9182 * params structure passed in.
9184 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9186 struct io_uring_params p;
9189 if (copy_from_user(&p, params, sizeof(p)))
9191 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9196 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9197 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9198 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9199 IORING_SETUP_R_DISABLED))
9202 return io_uring_create(entries, &p, params);
9205 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9206 struct io_uring_params __user *, params)
9208 return io_uring_setup(entries, params);
9211 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9213 struct io_uring_probe *p;
9217 size = struct_size(p, ops, nr_args);
9218 if (size == SIZE_MAX)
9220 p = kzalloc(size, GFP_KERNEL);
9225 if (copy_from_user(p, arg, size))
9228 if (memchr_inv(p, 0, size))
9231 p->last_op = IORING_OP_LAST - 1;
9232 if (nr_args > IORING_OP_LAST)
9233 nr_args = IORING_OP_LAST;
9235 for (i = 0; i < nr_args; i++) {
9237 if (!io_op_defs[i].not_supported)
9238 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9243 if (copy_to_user(arg, p, size))
9250 static int io_register_personality(struct io_ring_ctx *ctx)
9252 const struct cred *creds = get_current_cred();
9255 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9256 USHRT_MAX, GFP_KERNEL);
9262 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9264 const struct cred *old_creds;
9266 old_creds = idr_remove(&ctx->personality_idr, id);
9268 put_cred(old_creds);
9275 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9276 unsigned int nr_args)
9278 struct io_uring_restriction *res;
9282 /* Restrictions allowed only if rings started disabled */
9283 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9286 /* We allow only a single restrictions registration */
9287 if (ctx->restrictions.registered)
9290 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9293 size = array_size(nr_args, sizeof(*res));
9294 if (size == SIZE_MAX)
9297 res = memdup_user(arg, size);
9299 return PTR_ERR(res);
9303 for (i = 0; i < nr_args; i++) {
9304 switch (res[i].opcode) {
9305 case IORING_RESTRICTION_REGISTER_OP:
9306 if (res[i].register_op >= IORING_REGISTER_LAST) {
9311 __set_bit(res[i].register_op,
9312 ctx->restrictions.register_op);
9314 case IORING_RESTRICTION_SQE_OP:
9315 if (res[i].sqe_op >= IORING_OP_LAST) {
9320 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9322 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9323 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9325 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9326 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9335 /* Reset all restrictions if an error happened */
9337 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9339 ctx->restrictions.registered = true;
9345 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9347 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9350 if (ctx->restrictions.registered)
9351 ctx->restricted = 1;
9353 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9355 io_sq_offload_start(ctx);
9360 static bool io_register_op_must_quiesce(int op)
9363 case IORING_UNREGISTER_FILES:
9364 case IORING_REGISTER_FILES_UPDATE:
9365 case IORING_REGISTER_PROBE:
9366 case IORING_REGISTER_PERSONALITY:
9367 case IORING_UNREGISTER_PERSONALITY:
9374 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9375 void __user *arg, unsigned nr_args)
9376 __releases(ctx->uring_lock)
9377 __acquires(ctx->uring_lock)
9382 * We're inside the ring mutex, if the ref is already dying, then
9383 * someone else killed the ctx or is already going through
9384 * io_uring_register().
9386 if (percpu_ref_is_dying(&ctx->refs))
9389 if (io_register_op_must_quiesce(opcode)) {
9390 percpu_ref_kill(&ctx->refs);
9393 * Drop uring mutex before waiting for references to exit. If
9394 * another thread is currently inside io_uring_enter() it might
9395 * need to grab the uring_lock to make progress. If we hold it
9396 * here across the drain wait, then we can deadlock. It's safe
9397 * to drop the mutex here, since no new references will come in
9398 * after we've killed the percpu ref.
9400 mutex_unlock(&ctx->uring_lock);
9402 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9405 ret = io_run_task_work_sig();
9410 mutex_lock(&ctx->uring_lock);
9413 percpu_ref_resurrect(&ctx->refs);
9418 if (ctx->restricted) {
9419 if (opcode >= IORING_REGISTER_LAST) {
9424 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9431 case IORING_REGISTER_BUFFERS:
9432 ret = io_sqe_buffer_register(ctx, arg, nr_args);
9434 case IORING_UNREGISTER_BUFFERS:
9438 ret = io_sqe_buffer_unregister(ctx);
9440 case IORING_REGISTER_FILES:
9441 ret = io_sqe_files_register(ctx, arg, nr_args);
9443 case IORING_UNREGISTER_FILES:
9447 ret = io_sqe_files_unregister(ctx);
9449 case IORING_REGISTER_FILES_UPDATE:
9450 ret = io_sqe_files_update(ctx, arg, nr_args);
9452 case IORING_REGISTER_EVENTFD:
9453 case IORING_REGISTER_EVENTFD_ASYNC:
9457 ret = io_eventfd_register(ctx, arg);
9460 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9461 ctx->eventfd_async = 1;
9463 ctx->eventfd_async = 0;
9465 case IORING_UNREGISTER_EVENTFD:
9469 ret = io_eventfd_unregister(ctx);
9471 case IORING_REGISTER_PROBE:
9473 if (!arg || nr_args > 256)
9475 ret = io_probe(ctx, arg, nr_args);
9477 case IORING_REGISTER_PERSONALITY:
9481 ret = io_register_personality(ctx);
9483 case IORING_UNREGISTER_PERSONALITY:
9487 ret = io_unregister_personality(ctx, nr_args);
9489 case IORING_REGISTER_ENABLE_RINGS:
9493 ret = io_register_enable_rings(ctx);
9495 case IORING_REGISTER_RESTRICTIONS:
9496 ret = io_register_restrictions(ctx, arg, nr_args);
9504 if (io_register_op_must_quiesce(opcode)) {
9505 /* bring the ctx back to life */
9506 percpu_ref_reinit(&ctx->refs);
9508 reinit_completion(&ctx->ref_comp);
9513 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9514 void __user *, arg, unsigned int, nr_args)
9516 struct io_ring_ctx *ctx;
9525 if (f.file->f_op != &io_uring_fops)
9528 ctx = f.file->private_data;
9530 mutex_lock(&ctx->uring_lock);
9531 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9532 mutex_unlock(&ctx->uring_lock);
9533 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9534 ctx->cq_ev_fd != NULL, ret);
9540 static int __init io_uring_init(void)
9542 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9543 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9544 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9547 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9548 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9549 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9550 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9551 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9552 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9553 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9554 BUILD_BUG_SQE_ELEM(8, __u64, off);
9555 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9556 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9557 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9558 BUILD_BUG_SQE_ELEM(24, __u32, len);
9559 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9560 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9561 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9562 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9563 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9564 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9565 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9566 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9567 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9568 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9569 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9570 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9571 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9572 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9573 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9574 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9575 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9576 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9577 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9579 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9580 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9581 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
9584 __initcall(io_uring_init);