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>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
97 #define IORING_FILE_TABLE_SHIFT 9
98 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
99 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
100 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
103 u32 head ____cacheline_aligned_in_smp;
104 u32 tail ____cacheline_aligned_in_smp;
108 * This data is shared with the application through the mmap at offsets
109 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
111 * The offsets to the member fields are published through struct
112 * io_sqring_offsets when calling io_uring_setup.
116 * Head and tail offsets into the ring; the offsets need to be
117 * masked to get valid indices.
119 * The kernel controls head of the sq ring and the tail of the cq ring,
120 * and the application controls tail of the sq ring and the head of the
123 struct io_uring sq, cq;
125 * Bitmasks to apply to head and tail offsets (constant, equals
128 u32 sq_ring_mask, cq_ring_mask;
129 /* Ring sizes (constant, power of 2) */
130 u32 sq_ring_entries, cq_ring_entries;
132 * Number of invalid entries dropped by the kernel due to
133 * invalid index stored in array
135 * Written by the kernel, shouldn't be modified by the
136 * application (i.e. get number of "new events" by comparing to
139 * After a new SQ head value was read by the application this
140 * counter includes all submissions that were dropped reaching
141 * the new SQ head (and possibly more).
147 * Written by the kernel, shouldn't be modified by the
150 * The application needs a full memory barrier before checking
151 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
157 * Written by the application, shouldn't be modified by the
162 * Number of completion events lost because the queue was full;
163 * this should be avoided by the application by making sure
164 * there are not more requests pending than there is space in
165 * the completion queue.
167 * Written by the kernel, shouldn't be modified by the
168 * application (i.e. get number of "new events" by comparing to
171 * As completion events come in out of order this counter is not
172 * ordered with any other data.
176 * Ring buffer of completion events.
178 * The kernel writes completion events fresh every time they are
179 * produced, so the application is allowed to modify pending
182 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
185 struct io_mapped_ubuf {
188 struct bio_vec *bvec;
189 unsigned int nr_bvecs;
192 struct fixed_file_table {
196 struct fixed_file_ref_node {
197 struct percpu_ref refs;
198 struct list_head node;
199 struct list_head file_list;
200 struct fixed_file_data *file_data;
201 struct llist_node llist;
204 struct fixed_file_data {
205 struct fixed_file_table *table;
206 struct io_ring_ctx *ctx;
208 struct percpu_ref *cur_refs;
209 struct percpu_ref refs;
210 struct completion done;
211 struct list_head ref_list;
216 struct list_head list;
224 struct percpu_ref refs;
225 } ____cacheline_aligned_in_smp;
229 unsigned int compat: 1;
230 unsigned int limit_mem: 1;
231 unsigned int cq_overflow_flushed: 1;
232 unsigned int drain_next: 1;
233 unsigned int eventfd_async: 1;
236 * Ring buffer of indices into array of io_uring_sqe, which is
237 * mmapped by the application using the IORING_OFF_SQES offset.
239 * This indirection could e.g. be used to assign fixed
240 * io_uring_sqe entries to operations and only submit them to
241 * the queue when needed.
243 * The kernel modifies neither the indices array nor the entries
247 unsigned cached_sq_head;
250 unsigned sq_thread_idle;
251 unsigned cached_sq_dropped;
252 atomic_t cached_cq_overflow;
253 unsigned long sq_check_overflow;
255 struct list_head defer_list;
256 struct list_head timeout_list;
257 struct list_head cq_overflow_list;
259 wait_queue_head_t inflight_wait;
260 struct io_uring_sqe *sq_sqes;
261 } ____cacheline_aligned_in_smp;
263 struct io_rings *rings;
267 struct task_struct *sqo_thread; /* if using sq thread polling */
268 struct mm_struct *sqo_mm;
269 wait_queue_head_t sqo_wait;
272 * If used, fixed file set. Writers must ensure that ->refs is dead,
273 * readers must ensure that ->refs is alive as long as the file* is
274 * used. Only updated through io_uring_register(2).
276 struct fixed_file_data *file_data;
277 unsigned nr_user_files;
279 struct file *ring_file;
281 /* if used, fixed mapped user buffers */
282 unsigned nr_user_bufs;
283 struct io_mapped_ubuf *user_bufs;
285 struct user_struct *user;
287 const struct cred *creds;
289 struct completion ref_comp;
290 struct completion sq_thread_comp;
292 /* if all else fails... */
293 struct io_kiocb *fallback_req;
295 #if defined(CONFIG_UNIX)
296 struct socket *ring_sock;
299 struct idr io_buffer_idr;
301 struct idr personality_idr;
304 unsigned cached_cq_tail;
307 atomic_t cq_timeouts;
308 unsigned long cq_check_overflow;
309 struct wait_queue_head cq_wait;
310 struct fasync_struct *cq_fasync;
311 struct eventfd_ctx *cq_ev_fd;
312 } ____cacheline_aligned_in_smp;
315 struct mutex uring_lock;
316 wait_queue_head_t wait;
317 } ____cacheline_aligned_in_smp;
320 spinlock_t completion_lock;
323 * ->iopoll_list is protected by the ctx->uring_lock for
324 * io_uring instances that don't use IORING_SETUP_SQPOLL.
325 * For SQPOLL, only the single threaded io_sq_thread() will
326 * manipulate the list, hence no extra locking is needed there.
328 struct list_head iopoll_list;
329 struct hlist_head *cancel_hash;
330 unsigned cancel_hash_bits;
331 bool poll_multi_file;
333 spinlock_t inflight_lock;
334 struct list_head inflight_list;
335 } ____cacheline_aligned_in_smp;
337 struct delayed_work file_put_work;
338 struct llist_head file_put_llist;
340 struct work_struct exit_work;
344 * First field must be the file pointer in all the
345 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
347 struct io_poll_iocb {
350 struct wait_queue_head *head;
356 struct wait_queue_entry wait;
361 struct file *put_file;
365 struct io_timeout_data {
366 struct io_kiocb *req;
367 struct hrtimer timer;
368 struct timespec64 ts;
369 enum hrtimer_mode mode;
374 struct sockaddr __user *addr;
375 int __user *addr_len;
377 unsigned long nofile;
399 struct list_head list;
403 /* NOTE: kiocb has the file as the first member, so don't do it here */
411 struct sockaddr __user *addr;
418 struct user_msghdr __user *umsg;
424 struct io_buffer *kbuf;
430 struct filename *filename;
432 unsigned long nofile;
435 struct io_files_update {
461 struct epoll_event event;
465 struct file *file_out;
466 struct file *file_in;
473 struct io_provide_buf {
487 const char __user *filename;
488 struct statx __user *buffer;
491 struct io_completion {
493 struct list_head list;
497 struct io_async_connect {
498 struct sockaddr_storage address;
501 struct io_async_msghdr {
502 struct iovec fast_iov[UIO_FASTIOV];
504 struct sockaddr __user *uaddr;
506 struct sockaddr_storage addr;
510 struct iovec fast_iov[UIO_FASTIOV];
514 struct wait_page_queue wpq;
517 struct io_async_ctx {
519 struct io_async_rw rw;
520 struct io_async_msghdr msg;
521 struct io_async_connect connect;
522 struct io_timeout_data timeout;
527 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
528 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
529 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
530 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
531 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
532 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
539 REQ_F_LINK_TIMEOUT_BIT,
541 REQ_F_COMP_LOCKED_BIT,
542 REQ_F_NEED_CLEANUP_BIT,
545 REQ_F_BUFFER_SELECTED_BIT,
546 REQ_F_NO_FILE_TABLE_BIT,
547 REQ_F_WORK_INITIALIZED_BIT,
548 REQ_F_TASK_PINNED_BIT,
550 /* not a real bit, just to check we're not overflowing the space */
556 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
557 /* drain existing IO first */
558 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
560 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
561 /* doesn't sever on completion < 0 */
562 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
564 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
565 /* IOSQE_BUFFER_SELECT */
566 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
569 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
570 /* fail rest of links */
571 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
572 /* on inflight list */
573 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
574 /* read/write uses file position */
575 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
576 /* must not punt to workers */
577 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
578 /* has linked timeout */
579 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
581 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
582 /* completion under lock */
583 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
585 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
586 /* in overflow list */
587 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
588 /* already went through poll handler */
589 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
590 /* buffer already selected */
591 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
592 /* doesn't need file table for this request */
593 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
594 /* io_wq_work is initialized */
595 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
596 /* req->task is refcounted */
597 REQ_F_TASK_PINNED = BIT(REQ_F_TASK_PINNED_BIT),
601 struct io_poll_iocb poll;
602 struct io_poll_iocb *double_poll;
603 struct io_wq_work work;
607 * NOTE! Each of the iocb union members has the file pointer
608 * as the first entry in their struct definition. So you can
609 * access the file pointer through any of the sub-structs,
610 * or directly as just 'ki_filp' in this struct.
616 struct io_poll_iocb poll;
617 struct io_accept accept;
619 struct io_cancel cancel;
620 struct io_timeout timeout;
621 struct io_connect connect;
622 struct io_sr_msg sr_msg;
624 struct io_close close;
625 struct io_files_update files_update;
626 struct io_fadvise fadvise;
627 struct io_madvise madvise;
628 struct io_epoll epoll;
629 struct io_splice splice;
630 struct io_provide_buf pbuf;
631 struct io_statx statx;
632 /* use only after cleaning per-op data, see io_clean_op() */
633 struct io_completion compl;
636 struct io_async_ctx *io;
638 /* polled IO has completed */
644 struct io_ring_ctx *ctx;
647 struct task_struct *task;
650 struct list_head link_list;
653 * 1. used with ctx->iopoll_list with reads/writes
654 * 2. to track reqs with ->files (see io_op_def::file_table)
656 struct list_head inflight_entry;
658 struct percpu_ref *fixed_file_refs;
662 * Only commands that never go async can use the below fields,
663 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
664 * async armed poll handlers for regular commands. The latter
665 * restore the work, if needed.
668 struct hlist_node hash_node;
669 struct async_poll *apoll;
671 struct io_wq_work work;
673 struct callback_head task_work;
676 struct io_defer_entry {
677 struct list_head list;
678 struct io_kiocb *req;
682 #define IO_IOPOLL_BATCH 8
684 struct io_comp_state {
686 struct list_head list;
687 struct io_ring_ctx *ctx;
690 struct io_submit_state {
691 struct blk_plug plug;
694 * io_kiocb alloc cache
696 void *reqs[IO_IOPOLL_BATCH];
697 unsigned int free_reqs;
700 * Batch completion logic
702 struct io_comp_state comp;
705 * File reference cache
709 unsigned int has_refs;
710 unsigned int ios_left;
714 /* needs req->io allocated for deferral/async */
715 unsigned async_ctx : 1;
716 /* needs current->mm setup, does mm access */
717 unsigned needs_mm : 1;
718 /* needs req->file assigned */
719 unsigned needs_file : 1;
720 /* don't fail if file grab fails */
721 unsigned needs_file_no_error : 1;
722 /* hash wq insertion if file is a regular file */
723 unsigned hash_reg_file : 1;
724 /* unbound wq insertion if file is a non-regular file */
725 unsigned unbound_nonreg_file : 1;
726 /* opcode is not supported by this kernel */
727 unsigned not_supported : 1;
728 /* needs file table */
729 unsigned file_table : 1;
731 unsigned needs_fs : 1;
732 /* set if opcode supports polled "wait" */
734 unsigned pollout : 1;
735 /* op supports buffer selection */
736 unsigned buffer_select : 1;
737 unsigned needs_fsize : 1;
740 static const struct io_op_def io_op_defs[] = {
741 [IORING_OP_NOP] = {},
742 [IORING_OP_READV] = {
746 .unbound_nonreg_file = 1,
750 [IORING_OP_WRITEV] = {
755 .unbound_nonreg_file = 1,
759 [IORING_OP_FSYNC] = {
762 [IORING_OP_READ_FIXED] = {
764 .unbound_nonreg_file = 1,
767 [IORING_OP_WRITE_FIXED] = {
770 .unbound_nonreg_file = 1,
774 [IORING_OP_POLL_ADD] = {
776 .unbound_nonreg_file = 1,
778 [IORING_OP_POLL_REMOVE] = {},
779 [IORING_OP_SYNC_FILE_RANGE] = {
782 [IORING_OP_SENDMSG] = {
786 .unbound_nonreg_file = 1,
790 [IORING_OP_RECVMSG] = {
794 .unbound_nonreg_file = 1,
799 [IORING_OP_TIMEOUT] = {
803 [IORING_OP_TIMEOUT_REMOVE] = {},
804 [IORING_OP_ACCEPT] = {
807 .unbound_nonreg_file = 1,
811 [IORING_OP_ASYNC_CANCEL] = {},
812 [IORING_OP_LINK_TIMEOUT] = {
816 [IORING_OP_CONNECT] = {
820 .unbound_nonreg_file = 1,
823 [IORING_OP_FALLOCATE] = {
827 [IORING_OP_OPENAT] = {
831 [IORING_OP_CLOSE] = {
833 .needs_file_no_error = 1,
836 [IORING_OP_FILES_UPDATE] = {
840 [IORING_OP_STATX] = {
848 .unbound_nonreg_file = 1,
852 [IORING_OP_WRITE] = {
855 .unbound_nonreg_file = 1,
859 [IORING_OP_FADVISE] = {
862 [IORING_OP_MADVISE] = {
868 .unbound_nonreg_file = 1,
874 .unbound_nonreg_file = 1,
878 [IORING_OP_OPENAT2] = {
882 [IORING_OP_EPOLL_CTL] = {
883 .unbound_nonreg_file = 1,
886 [IORING_OP_SPLICE] = {
889 .unbound_nonreg_file = 1,
891 [IORING_OP_PROVIDE_BUFFERS] = {},
892 [IORING_OP_REMOVE_BUFFERS] = {},
896 .unbound_nonreg_file = 1,
900 enum io_mem_account {
905 static bool io_rw_reissue(struct io_kiocb *req, long res);
906 static void io_cqring_fill_event(struct io_kiocb *req, long res);
907 static void io_put_req(struct io_kiocb *req);
908 static void io_double_put_req(struct io_kiocb *req);
909 static void __io_double_put_req(struct io_kiocb *req);
910 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
911 static void io_queue_linked_timeout(struct io_kiocb *req);
912 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
913 struct io_uring_files_update *ip,
915 static int io_prep_work_files(struct io_kiocb *req);
916 static void io_complete_rw_common(struct kiocb *kiocb, long res,
917 struct io_comp_state *cs);
918 static void __io_clean_op(struct io_kiocb *req);
919 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
920 int fd, struct file **out_file, bool fixed);
921 static void __io_queue_sqe(struct io_kiocb *req,
922 const struct io_uring_sqe *sqe,
923 struct io_comp_state *cs);
924 static void io_file_put_work(struct work_struct *work);
926 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
927 struct iovec **iovec, struct iov_iter *iter,
929 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
930 struct iovec *iovec, struct iovec *fast_iov,
931 struct iov_iter *iter);
933 static struct kmem_cache *req_cachep;
935 static const struct file_operations io_uring_fops;
937 struct sock *io_uring_get_socket(struct file *file)
939 #if defined(CONFIG_UNIX)
940 if (file->f_op == &io_uring_fops) {
941 struct io_ring_ctx *ctx = file->private_data;
943 return ctx->ring_sock->sk;
948 EXPORT_SYMBOL(io_uring_get_socket);
950 static void io_get_req_task(struct io_kiocb *req)
952 if (req->flags & REQ_F_TASK_PINNED)
954 get_task_struct(req->task);
955 req->flags |= REQ_F_TASK_PINNED;
958 static inline void io_clean_op(struct io_kiocb *req)
960 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
964 /* not idempotent -- it doesn't clear REQ_F_TASK_PINNED */
965 static void __io_put_req_task(struct io_kiocb *req)
967 if (req->flags & REQ_F_TASK_PINNED)
968 put_task_struct(req->task);
971 static void io_sq_thread_drop_mm(void)
973 struct mm_struct *mm = current->mm;
976 kthread_unuse_mm(mm);
981 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
984 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL) ||
985 !mmget_not_zero(ctx->sqo_mm)))
987 kthread_use_mm(ctx->sqo_mm);
993 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
994 struct io_kiocb *req)
996 if (!io_op_defs[req->opcode].needs_mm)
998 return __io_sq_thread_acquire_mm(ctx);
1001 static inline void req_set_fail_links(struct io_kiocb *req)
1003 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1004 req->flags |= REQ_F_FAIL_LINK;
1008 * Note: must call io_req_init_async() for the first time you
1009 * touch any members of io_wq_work.
1011 static inline void io_req_init_async(struct io_kiocb *req)
1013 if (req->flags & REQ_F_WORK_INITIALIZED)
1016 memset(&req->work, 0, sizeof(req->work));
1017 req->flags |= REQ_F_WORK_INITIALIZED;
1020 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1022 return ctx->flags & IORING_SETUP_SQPOLL;
1025 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1027 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1029 complete(&ctx->ref_comp);
1032 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1034 return !req->timeout.off;
1037 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1039 struct io_ring_ctx *ctx;
1042 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1046 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1047 if (!ctx->fallback_req)
1051 * Use 5 bits less than the max cq entries, that should give us around
1052 * 32 entries per hash list if totally full and uniformly spread.
1054 hash_bits = ilog2(p->cq_entries);
1058 ctx->cancel_hash_bits = hash_bits;
1059 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1061 if (!ctx->cancel_hash)
1063 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1065 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1066 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1069 ctx->flags = p->flags;
1070 init_waitqueue_head(&ctx->sqo_wait);
1071 init_waitqueue_head(&ctx->cq_wait);
1072 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1073 init_completion(&ctx->ref_comp);
1074 init_completion(&ctx->sq_thread_comp);
1075 idr_init(&ctx->io_buffer_idr);
1076 idr_init(&ctx->personality_idr);
1077 mutex_init(&ctx->uring_lock);
1078 init_waitqueue_head(&ctx->wait);
1079 spin_lock_init(&ctx->completion_lock);
1080 INIT_LIST_HEAD(&ctx->iopoll_list);
1081 INIT_LIST_HEAD(&ctx->defer_list);
1082 INIT_LIST_HEAD(&ctx->timeout_list);
1083 init_waitqueue_head(&ctx->inflight_wait);
1084 spin_lock_init(&ctx->inflight_lock);
1085 INIT_LIST_HEAD(&ctx->inflight_list);
1086 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1087 init_llist_head(&ctx->file_put_llist);
1090 if (ctx->fallback_req)
1091 kmem_cache_free(req_cachep, ctx->fallback_req);
1092 kfree(ctx->cancel_hash);
1097 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1099 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1100 struct io_ring_ctx *ctx = req->ctx;
1102 return seq != ctx->cached_cq_tail
1103 + atomic_read(&ctx->cached_cq_overflow);
1109 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1111 struct io_rings *rings = ctx->rings;
1113 /* order cqe stores with ring update */
1114 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1116 if (wq_has_sleeper(&ctx->cq_wait)) {
1117 wake_up_interruptible(&ctx->cq_wait);
1118 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1122 static void io_req_clean_work(struct io_kiocb *req)
1124 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1128 mmdrop(req->work.mm);
1129 req->work.mm = NULL;
1131 if (req->work.creds) {
1132 put_cred(req->work.creds);
1133 req->work.creds = NULL;
1136 struct fs_struct *fs = req->work.fs;
1138 spin_lock(&req->work.fs->lock);
1141 spin_unlock(&req->work.fs->lock);
1144 req->work.fs = NULL;
1146 req->flags &= ~REQ_F_WORK_INITIALIZED;
1149 static void io_prep_async_work(struct io_kiocb *req)
1151 const struct io_op_def *def = &io_op_defs[req->opcode];
1153 io_req_init_async(req);
1155 if (req->flags & REQ_F_ISREG) {
1156 if (def->hash_reg_file)
1157 io_wq_hash_work(&req->work, file_inode(req->file));
1159 if (def->unbound_nonreg_file)
1160 req->work.flags |= IO_WQ_WORK_UNBOUND;
1162 if (!req->work.mm && def->needs_mm) {
1163 mmgrab(current->mm);
1164 req->work.mm = current->mm;
1166 if (!req->work.creds)
1167 req->work.creds = get_current_cred();
1168 if (!req->work.fs && def->needs_fs) {
1169 spin_lock(¤t->fs->lock);
1170 if (!current->fs->in_exec) {
1171 req->work.fs = current->fs;
1172 req->work.fs->users++;
1174 req->work.flags |= IO_WQ_WORK_CANCEL;
1176 spin_unlock(¤t->fs->lock);
1178 if (def->needs_fsize)
1179 req->work.fsize = rlimit(RLIMIT_FSIZE);
1181 req->work.fsize = RLIM_INFINITY;
1184 static void io_prep_async_link(struct io_kiocb *req)
1186 struct io_kiocb *cur;
1188 io_prep_async_work(req);
1189 if (req->flags & REQ_F_LINK_HEAD)
1190 list_for_each_entry(cur, &req->link_list, link_list)
1191 io_prep_async_work(cur);
1194 static void __io_queue_async_work(struct io_kiocb *req)
1196 struct io_ring_ctx *ctx = req->ctx;
1197 struct io_kiocb *link = io_prep_linked_timeout(req);
1199 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1200 &req->work, req->flags);
1201 io_wq_enqueue(ctx->io_wq, &req->work);
1204 io_queue_linked_timeout(link);
1207 static void io_queue_async_work(struct io_kiocb *req)
1209 /* init ->work of the whole link before punting */
1210 io_prep_async_link(req);
1211 __io_queue_async_work(req);
1214 static void io_kill_timeout(struct io_kiocb *req)
1218 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1220 atomic_inc(&req->ctx->cq_timeouts);
1221 list_del_init(&req->timeout.list);
1222 req->flags |= REQ_F_COMP_LOCKED;
1223 io_cqring_fill_event(req, 0);
1228 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1230 struct io_kiocb *req, *tmp;
1232 spin_lock_irq(&ctx->completion_lock);
1233 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list)
1234 io_kill_timeout(req);
1235 spin_unlock_irq(&ctx->completion_lock);
1238 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1241 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1242 struct io_defer_entry, list);
1244 if (req_need_defer(de->req, de->seq))
1246 list_del_init(&de->list);
1247 /* punt-init is done before queueing for defer */
1248 __io_queue_async_work(de->req);
1250 } while (!list_empty(&ctx->defer_list));
1253 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1255 while (!list_empty(&ctx->timeout_list)) {
1256 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1257 struct io_kiocb, timeout.list);
1259 if (io_is_timeout_noseq(req))
1261 if (req->timeout.target_seq != ctx->cached_cq_tail
1262 - atomic_read(&ctx->cq_timeouts))
1265 list_del_init(&req->timeout.list);
1266 io_kill_timeout(req);
1270 static void io_commit_cqring(struct io_ring_ctx *ctx)
1272 io_flush_timeouts(ctx);
1273 __io_commit_cqring(ctx);
1275 if (unlikely(!list_empty(&ctx->defer_list)))
1276 __io_queue_deferred(ctx);
1279 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1281 struct io_rings *rings = ctx->rings;
1284 tail = ctx->cached_cq_tail;
1286 * writes to the cq entry need to come after reading head; the
1287 * control dependency is enough as we're using WRITE_ONCE to
1290 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1293 ctx->cached_cq_tail++;
1294 return &rings->cqes[tail & ctx->cq_mask];
1297 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1301 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1303 if (!ctx->eventfd_async)
1305 return io_wq_current_is_worker();
1308 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1310 if (waitqueue_active(&ctx->wait))
1311 wake_up(&ctx->wait);
1312 if (waitqueue_active(&ctx->sqo_wait))
1313 wake_up(&ctx->sqo_wait);
1314 if (io_should_trigger_evfd(ctx))
1315 eventfd_signal(ctx->cq_ev_fd, 1);
1318 /* Returns true if there are no backlogged entries after the flush */
1319 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1321 struct io_rings *rings = ctx->rings;
1322 struct io_uring_cqe *cqe;
1323 struct io_kiocb *req;
1324 unsigned long flags;
1328 if (list_empty_careful(&ctx->cq_overflow_list))
1330 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1331 rings->cq_ring_entries))
1335 spin_lock_irqsave(&ctx->completion_lock, flags);
1337 /* if force is set, the ring is going away. always drop after that */
1339 ctx->cq_overflow_flushed = 1;
1342 while (!list_empty(&ctx->cq_overflow_list)) {
1343 cqe = io_get_cqring(ctx);
1347 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1349 list_move(&req->compl.list, &list);
1350 req->flags &= ~REQ_F_OVERFLOW;
1352 WRITE_ONCE(cqe->user_data, req->user_data);
1353 WRITE_ONCE(cqe->res, req->result);
1354 WRITE_ONCE(cqe->flags, req->compl.cflags);
1356 WRITE_ONCE(ctx->rings->cq_overflow,
1357 atomic_inc_return(&ctx->cached_cq_overflow));
1361 io_commit_cqring(ctx);
1363 clear_bit(0, &ctx->sq_check_overflow);
1364 clear_bit(0, &ctx->cq_check_overflow);
1365 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1367 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1368 io_cqring_ev_posted(ctx);
1370 while (!list_empty(&list)) {
1371 req = list_first_entry(&list, struct io_kiocb, compl.list);
1372 list_del(&req->compl.list);
1379 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1381 struct io_ring_ctx *ctx = req->ctx;
1382 struct io_uring_cqe *cqe;
1384 trace_io_uring_complete(ctx, req->user_data, res);
1387 * If we can't get a cq entry, userspace overflowed the
1388 * submission (by quite a lot). Increment the overflow count in
1391 cqe = io_get_cqring(ctx);
1393 WRITE_ONCE(cqe->user_data, req->user_data);
1394 WRITE_ONCE(cqe->res, res);
1395 WRITE_ONCE(cqe->flags, cflags);
1396 } else if (ctx->cq_overflow_flushed) {
1397 WRITE_ONCE(ctx->rings->cq_overflow,
1398 atomic_inc_return(&ctx->cached_cq_overflow));
1400 if (list_empty(&ctx->cq_overflow_list)) {
1401 set_bit(0, &ctx->sq_check_overflow);
1402 set_bit(0, &ctx->cq_check_overflow);
1403 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1406 req->flags |= REQ_F_OVERFLOW;
1408 req->compl.cflags = cflags;
1409 refcount_inc(&req->refs);
1410 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1414 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1416 __io_cqring_fill_event(req, res, 0);
1419 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1421 struct io_ring_ctx *ctx = req->ctx;
1422 unsigned long flags;
1424 spin_lock_irqsave(&ctx->completion_lock, flags);
1425 __io_cqring_fill_event(req, res, cflags);
1426 io_commit_cqring(ctx);
1427 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1429 io_cqring_ev_posted(ctx);
1432 static void io_submit_flush_completions(struct io_comp_state *cs)
1434 struct io_ring_ctx *ctx = cs->ctx;
1436 spin_lock_irq(&ctx->completion_lock);
1437 while (!list_empty(&cs->list)) {
1438 struct io_kiocb *req;
1440 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1441 list_del(&req->compl.list);
1442 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1443 if (!(req->flags & REQ_F_LINK_HEAD)) {
1444 req->flags |= REQ_F_COMP_LOCKED;
1447 spin_unlock_irq(&ctx->completion_lock);
1449 spin_lock_irq(&ctx->completion_lock);
1452 io_commit_cqring(ctx);
1453 spin_unlock_irq(&ctx->completion_lock);
1455 io_cqring_ev_posted(ctx);
1459 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1460 struct io_comp_state *cs)
1463 io_cqring_add_event(req, res, cflags);
1468 req->compl.cflags = cflags;
1469 list_add_tail(&req->compl.list, &cs->list);
1471 io_submit_flush_completions(cs);
1475 static void io_req_complete(struct io_kiocb *req, long res)
1477 __io_req_complete(req, res, 0, NULL);
1480 static inline bool io_is_fallback_req(struct io_kiocb *req)
1482 return req == (struct io_kiocb *)
1483 ((unsigned long) req->ctx->fallback_req & ~1UL);
1486 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1488 struct io_kiocb *req;
1490 req = ctx->fallback_req;
1491 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1497 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1498 struct io_submit_state *state)
1500 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1501 struct io_kiocb *req;
1503 if (!state->free_reqs) {
1507 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1508 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1511 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1512 * retry single alloc to be on the safe side.
1514 if (unlikely(ret <= 0)) {
1515 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1516 if (!state->reqs[0])
1520 state->free_reqs = ret - 1;
1521 req = state->reqs[ret - 1];
1524 req = state->reqs[state->free_reqs];
1529 return io_get_fallback_req(ctx);
1532 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1536 percpu_ref_put(req->fixed_file_refs);
1541 static void io_dismantle_req(struct io_kiocb *req)
1548 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1549 io_req_clean_work(req);
1551 if (req->flags & REQ_F_INFLIGHT) {
1552 struct io_ring_ctx *ctx = req->ctx;
1553 unsigned long flags;
1555 spin_lock_irqsave(&ctx->inflight_lock, flags);
1556 list_del(&req->inflight_entry);
1557 if (waitqueue_active(&ctx->inflight_wait))
1558 wake_up(&ctx->inflight_wait);
1559 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1563 static void __io_free_req(struct io_kiocb *req)
1565 struct io_ring_ctx *ctx;
1567 io_dismantle_req(req);
1568 __io_put_req_task(req);
1570 if (likely(!io_is_fallback_req(req)))
1571 kmem_cache_free(req_cachep, req);
1573 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
1574 percpu_ref_put(&ctx->refs);
1577 static bool io_link_cancel_timeout(struct io_kiocb *req)
1579 struct io_ring_ctx *ctx = req->ctx;
1582 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1584 io_cqring_fill_event(req, -ECANCELED);
1585 io_commit_cqring(ctx);
1586 req->flags &= ~REQ_F_LINK_HEAD;
1594 static bool __io_kill_linked_timeout(struct io_kiocb *req)
1596 struct io_kiocb *link;
1599 if (list_empty(&req->link_list))
1601 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1602 if (link->opcode != IORING_OP_LINK_TIMEOUT)
1605 list_del_init(&link->link_list);
1606 wake_ev = io_link_cancel_timeout(link);
1607 req->flags &= ~REQ_F_LINK_TIMEOUT;
1611 static void io_kill_linked_timeout(struct io_kiocb *req)
1613 struct io_ring_ctx *ctx = req->ctx;
1616 if (!(req->flags & REQ_F_COMP_LOCKED)) {
1617 unsigned long flags;
1619 spin_lock_irqsave(&ctx->completion_lock, flags);
1620 wake_ev = __io_kill_linked_timeout(req);
1621 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1623 wake_ev = __io_kill_linked_timeout(req);
1627 io_cqring_ev_posted(ctx);
1630 static struct io_kiocb *io_req_link_next(struct io_kiocb *req)
1632 struct io_kiocb *nxt;
1635 * The list should never be empty when we are called here. But could
1636 * potentially happen if the chain is messed up, check to be on the
1639 if (unlikely(list_empty(&req->link_list)))
1642 nxt = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1643 list_del_init(&req->link_list);
1644 if (!list_empty(&nxt->link_list))
1645 nxt->flags |= REQ_F_LINK_HEAD;
1650 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1652 static void __io_fail_links(struct io_kiocb *req)
1654 struct io_ring_ctx *ctx = req->ctx;
1656 while (!list_empty(&req->link_list)) {
1657 struct io_kiocb *link = list_first_entry(&req->link_list,
1658 struct io_kiocb, link_list);
1660 list_del_init(&link->link_list);
1661 trace_io_uring_fail_link(req, link);
1663 io_cqring_fill_event(link, -ECANCELED);
1664 __io_double_put_req(link);
1665 req->flags &= ~REQ_F_LINK_TIMEOUT;
1668 io_commit_cqring(ctx);
1669 io_cqring_ev_posted(ctx);
1672 static void io_fail_links(struct io_kiocb *req)
1674 struct io_ring_ctx *ctx = req->ctx;
1676 if (!(req->flags & REQ_F_COMP_LOCKED)) {
1677 unsigned long flags;
1679 spin_lock_irqsave(&ctx->completion_lock, flags);
1680 __io_fail_links(req);
1681 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1683 __io_fail_links(req);
1686 io_cqring_ev_posted(ctx);
1689 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1691 req->flags &= ~REQ_F_LINK_HEAD;
1692 if (req->flags & REQ_F_LINK_TIMEOUT)
1693 io_kill_linked_timeout(req);
1696 * If LINK is set, we have dependent requests in this chain. If we
1697 * didn't fail this request, queue the first one up, moving any other
1698 * dependencies to the next request. In case of failure, fail the rest
1701 if (likely(!(req->flags & REQ_F_FAIL_LINK)))
1702 return io_req_link_next(req);
1707 static struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1709 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1711 return __io_req_find_next(req);
1714 static int io_req_task_work_add(struct io_kiocb *req, struct callback_head *cb)
1716 struct task_struct *tsk = req->task;
1717 struct io_ring_ctx *ctx = req->ctx;
1718 int ret, notify = TWA_RESUME;
1721 * SQPOLL kernel thread doesn't need notification, just a wakeup.
1722 * If we're not using an eventfd, then TWA_RESUME is always fine,
1723 * as we won't have dependencies between request completions for
1724 * other kernel wait conditions.
1726 if (ctx->flags & IORING_SETUP_SQPOLL)
1728 else if (ctx->cq_ev_fd)
1729 notify = TWA_SIGNAL;
1731 ret = task_work_add(tsk, cb, notify);
1733 wake_up_process(tsk);
1737 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1739 struct io_ring_ctx *ctx = req->ctx;
1741 spin_lock_irq(&ctx->completion_lock);
1742 io_cqring_fill_event(req, error);
1743 io_commit_cqring(ctx);
1744 spin_unlock_irq(&ctx->completion_lock);
1746 io_cqring_ev_posted(ctx);
1747 req_set_fail_links(req);
1748 io_double_put_req(req);
1751 static void io_req_task_cancel(struct callback_head *cb)
1753 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1755 __io_req_task_cancel(req, -ECANCELED);
1758 static void __io_req_task_submit(struct io_kiocb *req)
1760 struct io_ring_ctx *ctx = req->ctx;
1762 if (!__io_sq_thread_acquire_mm(ctx)) {
1763 mutex_lock(&ctx->uring_lock);
1764 __io_queue_sqe(req, NULL, NULL);
1765 mutex_unlock(&ctx->uring_lock);
1767 __io_req_task_cancel(req, -EFAULT);
1771 static void io_req_task_submit(struct callback_head *cb)
1773 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1775 __io_req_task_submit(req);
1778 static void io_req_task_queue(struct io_kiocb *req)
1782 init_task_work(&req->task_work, io_req_task_submit);
1784 ret = io_req_task_work_add(req, &req->task_work);
1785 if (unlikely(ret)) {
1786 struct task_struct *tsk;
1788 init_task_work(&req->task_work, io_req_task_cancel);
1789 tsk = io_wq_get_task(req->ctx->io_wq);
1790 task_work_add(tsk, &req->task_work, 0);
1791 wake_up_process(tsk);
1795 static void io_queue_next(struct io_kiocb *req)
1797 struct io_kiocb *nxt = io_req_find_next(req);
1800 io_req_task_queue(nxt);
1803 static void io_free_req(struct io_kiocb *req)
1810 void *reqs[IO_IOPOLL_BATCH];
1813 struct task_struct *task;
1817 static inline void io_init_req_batch(struct req_batch *rb)
1824 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
1825 struct req_batch *rb)
1827 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1828 percpu_ref_put_many(&ctx->refs, rb->to_free);
1832 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
1833 struct req_batch *rb)
1836 __io_req_free_batch_flush(ctx, rb);
1838 put_task_struct_many(rb->task, rb->task_refs);
1843 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
1845 if (unlikely(io_is_fallback_req(req))) {
1849 if (req->flags & REQ_F_LINK_HEAD)
1852 if (req->flags & REQ_F_TASK_PINNED) {
1853 if (req->task != rb->task) {
1855 put_task_struct_many(rb->task, rb->task_refs);
1856 rb->task = req->task;
1860 req->flags &= ~REQ_F_TASK_PINNED;
1863 io_dismantle_req(req);
1864 rb->reqs[rb->to_free++] = req;
1865 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1866 __io_req_free_batch_flush(req->ctx, rb);
1870 * Drop reference to request, return next in chain (if there is one) if this
1871 * was the last reference to this request.
1873 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
1875 struct io_kiocb *nxt = NULL;
1877 if (refcount_dec_and_test(&req->refs)) {
1878 nxt = io_req_find_next(req);
1884 static void io_put_req(struct io_kiocb *req)
1886 if (refcount_dec_and_test(&req->refs))
1890 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
1892 struct io_kiocb *nxt;
1895 * A ref is owned by io-wq in which context we're. So, if that's the
1896 * last one, it's safe to steal next work. False negatives are Ok,
1897 * it just will be re-punted async in io_put_work()
1899 if (refcount_read(&req->refs) != 1)
1902 nxt = io_req_find_next(req);
1903 return nxt ? &nxt->work : NULL;
1907 * Must only be used if we don't need to care about links, usually from
1908 * within the completion handling itself.
1910 static void __io_double_put_req(struct io_kiocb *req)
1912 /* drop both submit and complete references */
1913 if (refcount_sub_and_test(2, &req->refs))
1917 static void io_double_put_req(struct io_kiocb *req)
1919 /* drop both submit and complete references */
1920 if (refcount_sub_and_test(2, &req->refs))
1924 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1926 struct io_rings *rings = ctx->rings;
1928 if (test_bit(0, &ctx->cq_check_overflow)) {
1930 * noflush == true is from the waitqueue handler, just ensure
1931 * we wake up the task, and the next invocation will flush the
1932 * entries. We cannot safely to it from here.
1934 if (noflush && !list_empty(&ctx->cq_overflow_list))
1937 io_cqring_overflow_flush(ctx, false);
1940 /* See comment at the top of this file */
1942 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1945 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1947 struct io_rings *rings = ctx->rings;
1949 /* make sure SQ entry isn't read before tail */
1950 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1953 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
1955 unsigned int cflags;
1957 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1958 cflags |= IORING_CQE_F_BUFFER;
1959 req->flags &= ~REQ_F_BUFFER_SELECTED;
1964 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
1966 struct io_buffer *kbuf;
1968 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1969 return io_put_kbuf(req, kbuf);
1972 static inline bool io_run_task_work(void)
1974 if (current->task_works) {
1975 __set_current_state(TASK_RUNNING);
1983 static void io_iopoll_queue(struct list_head *again)
1985 struct io_kiocb *req;
1988 req = list_first_entry(again, struct io_kiocb, inflight_entry);
1989 list_del(&req->inflight_entry);
1990 if (!io_rw_reissue(req, -EAGAIN))
1991 io_complete_rw_common(&req->rw.kiocb, -EAGAIN, NULL);
1992 } while (!list_empty(again));
1996 * Find and free completed poll iocbs
1998 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1999 struct list_head *done)
2001 struct req_batch rb;
2002 struct io_kiocb *req;
2005 /* order with ->result store in io_complete_rw_iopoll() */
2008 io_init_req_batch(&rb);
2009 while (!list_empty(done)) {
2012 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2013 if (READ_ONCE(req->result) == -EAGAIN) {
2014 req->iopoll_completed = 0;
2015 list_move_tail(&req->inflight_entry, &again);
2018 list_del(&req->inflight_entry);
2020 if (req->flags & REQ_F_BUFFER_SELECTED)
2021 cflags = io_put_rw_kbuf(req);
2023 __io_cqring_fill_event(req, req->result, cflags);
2026 if (refcount_dec_and_test(&req->refs))
2027 io_req_free_batch(&rb, req);
2030 io_commit_cqring(ctx);
2031 if (ctx->flags & IORING_SETUP_SQPOLL)
2032 io_cqring_ev_posted(ctx);
2033 io_req_free_batch_finish(ctx, &rb);
2035 if (!list_empty(&again))
2036 io_iopoll_queue(&again);
2039 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2042 struct io_kiocb *req, *tmp;
2048 * Only spin for completions if we don't have multiple devices hanging
2049 * off our complete list, and we're under the requested amount.
2051 spin = !ctx->poll_multi_file && *nr_events < min;
2054 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2055 struct kiocb *kiocb = &req->rw.kiocb;
2058 * Move completed and retryable entries to our local lists.
2059 * If we find a request that requires polling, break out
2060 * and complete those lists first, if we have entries there.
2062 if (READ_ONCE(req->iopoll_completed)) {
2063 list_move_tail(&req->inflight_entry, &done);
2066 if (!list_empty(&done))
2069 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2073 /* iopoll may have completed current req */
2074 if (READ_ONCE(req->iopoll_completed))
2075 list_move_tail(&req->inflight_entry, &done);
2082 if (!list_empty(&done))
2083 io_iopoll_complete(ctx, nr_events, &done);
2089 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2090 * non-spinning poll check - we'll still enter the driver poll loop, but only
2091 * as a non-spinning completion check.
2093 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2096 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2099 ret = io_do_iopoll(ctx, nr_events, min);
2102 if (*nr_events >= min)
2110 * We can't just wait for polled events to come to us, we have to actively
2111 * find and complete them.
2113 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2115 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2118 mutex_lock(&ctx->uring_lock);
2119 while (!list_empty(&ctx->iopoll_list)) {
2120 unsigned int nr_events = 0;
2122 io_do_iopoll(ctx, &nr_events, 0);
2124 /* let it sleep and repeat later if can't complete a request */
2128 * Ensure we allow local-to-the-cpu processing to take place,
2129 * in this case we need to ensure that we reap all events.
2130 * Also let task_work, etc. to progress by releasing the mutex
2132 if (need_resched()) {
2133 mutex_unlock(&ctx->uring_lock);
2135 mutex_lock(&ctx->uring_lock);
2138 mutex_unlock(&ctx->uring_lock);
2141 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2143 unsigned int nr_events = 0;
2144 int iters = 0, ret = 0;
2147 * We disallow the app entering submit/complete with polling, but we
2148 * still need to lock the ring to prevent racing with polled issue
2149 * that got punted to a workqueue.
2151 mutex_lock(&ctx->uring_lock);
2154 * Don't enter poll loop if we already have events pending.
2155 * If we do, we can potentially be spinning for commands that
2156 * already triggered a CQE (eg in error).
2158 if (io_cqring_events(ctx, false))
2162 * If a submit got punted to a workqueue, we can have the
2163 * application entering polling for a command before it gets
2164 * issued. That app will hold the uring_lock for the duration
2165 * of the poll right here, so we need to take a breather every
2166 * now and then to ensure that the issue has a chance to add
2167 * the poll to the issued list. Otherwise we can spin here
2168 * forever, while the workqueue is stuck trying to acquire the
2171 if (!(++iters & 7)) {
2172 mutex_unlock(&ctx->uring_lock);
2174 mutex_lock(&ctx->uring_lock);
2177 ret = io_iopoll_getevents(ctx, &nr_events, min);
2181 } while (min && !nr_events && !need_resched());
2183 mutex_unlock(&ctx->uring_lock);
2187 static void kiocb_end_write(struct io_kiocb *req)
2190 * Tell lockdep we inherited freeze protection from submission
2193 if (req->flags & REQ_F_ISREG) {
2194 struct inode *inode = file_inode(req->file);
2196 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2198 file_end_write(req->file);
2201 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2202 struct io_comp_state *cs)
2204 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2207 if (kiocb->ki_flags & IOCB_WRITE)
2208 kiocb_end_write(req);
2210 if (res != req->result)
2211 req_set_fail_links(req);
2212 if (req->flags & REQ_F_BUFFER_SELECTED)
2213 cflags = io_put_rw_kbuf(req);
2214 __io_req_complete(req, res, cflags, cs);
2218 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2220 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2221 ssize_t ret = -ECANCELED;
2222 struct iov_iter iter;
2230 switch (req->opcode) {
2231 case IORING_OP_READV:
2232 case IORING_OP_READ_FIXED:
2233 case IORING_OP_READ:
2236 case IORING_OP_WRITEV:
2237 case IORING_OP_WRITE_FIXED:
2238 case IORING_OP_WRITE:
2242 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2247 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2250 ret = io_setup_async_rw(req, ret, iovec, inline_vecs, &iter);
2255 req_set_fail_links(req);
2256 io_req_complete(req, ret);
2260 static void io_rw_resubmit(struct callback_head *cb)
2262 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2263 struct io_ring_ctx *ctx = req->ctx;
2266 err = io_sq_thread_acquire_mm(ctx, req);
2268 if (io_resubmit_prep(req, err)) {
2269 refcount_inc(&req->refs);
2270 io_queue_async_work(req);
2275 static bool io_rw_reissue(struct io_kiocb *req, long res)
2280 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2283 init_task_work(&req->task_work, io_rw_resubmit);
2284 ret = io_req_task_work_add(req, &req->task_work);
2291 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2292 struct io_comp_state *cs)
2294 if (!io_rw_reissue(req, res))
2295 io_complete_rw_common(&req->rw.kiocb, res, cs);
2298 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2300 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2302 __io_complete_rw(req, res, res2, NULL);
2305 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2307 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2309 if (kiocb->ki_flags & IOCB_WRITE)
2310 kiocb_end_write(req);
2312 if (res != -EAGAIN && res != req->result)
2313 req_set_fail_links(req);
2315 WRITE_ONCE(req->result, res);
2316 /* order with io_poll_complete() checking ->result */
2318 WRITE_ONCE(req->iopoll_completed, 1);
2322 * After the iocb has been issued, it's safe to be found on the poll list.
2323 * Adding the kiocb to the list AFTER submission ensures that we don't
2324 * find it from a io_iopoll_getevents() thread before the issuer is done
2325 * accessing the kiocb cookie.
2327 static void io_iopoll_req_issued(struct io_kiocb *req)
2329 struct io_ring_ctx *ctx = req->ctx;
2332 * Track whether we have multiple files in our lists. This will impact
2333 * how we do polling eventually, not spinning if we're on potentially
2334 * different devices.
2336 if (list_empty(&ctx->iopoll_list)) {
2337 ctx->poll_multi_file = false;
2338 } else if (!ctx->poll_multi_file) {
2339 struct io_kiocb *list_req;
2341 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2343 if (list_req->file != req->file)
2344 ctx->poll_multi_file = true;
2348 * For fast devices, IO may have already completed. If it has, add
2349 * it to the front so we find it first.
2351 if (READ_ONCE(req->iopoll_completed))
2352 list_add(&req->inflight_entry, &ctx->iopoll_list);
2354 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2356 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2357 wq_has_sleeper(&ctx->sqo_wait))
2358 wake_up(&ctx->sqo_wait);
2361 static void __io_state_file_put(struct io_submit_state *state)
2363 if (state->has_refs)
2364 fput_many(state->file, state->has_refs);
2368 static inline void io_state_file_put(struct io_submit_state *state)
2371 __io_state_file_put(state);
2375 * Get as many references to a file as we have IOs left in this submission,
2376 * assuming most submissions are for one file, or at least that each file
2377 * has more than one submission.
2379 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2385 if (state->fd == fd) {
2390 __io_state_file_put(state);
2392 state->file = fget_many(fd, state->ios_left);
2398 state->has_refs = state->ios_left;
2402 static bool io_bdev_nowait(struct block_device *bdev)
2405 return !bdev || queue_is_mq(bdev_get_queue(bdev));
2412 * If we tracked the file through the SCM inflight mechanism, we could support
2413 * any file. For now, just ensure that anything potentially problematic is done
2416 static bool io_file_supports_async(struct file *file, int rw)
2418 umode_t mode = file_inode(file)->i_mode;
2420 if (S_ISBLK(mode)) {
2421 if (io_bdev_nowait(file->f_inode->i_bdev))
2425 if (S_ISCHR(mode) || S_ISSOCK(mode))
2427 if (S_ISREG(mode)) {
2428 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2429 file->f_op != &io_uring_fops)
2434 /* any ->read/write should understand O_NONBLOCK */
2435 if (file->f_flags & O_NONBLOCK)
2438 if (!(file->f_mode & FMODE_NOWAIT))
2442 return file->f_op->read_iter != NULL;
2444 return file->f_op->write_iter != NULL;
2447 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2448 bool force_nonblock)
2450 struct io_ring_ctx *ctx = req->ctx;
2451 struct kiocb *kiocb = &req->rw.kiocb;
2455 if (S_ISREG(file_inode(req->file)->i_mode))
2456 req->flags |= REQ_F_ISREG;
2458 kiocb->ki_pos = READ_ONCE(sqe->off);
2459 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2460 req->flags |= REQ_F_CUR_POS;
2461 kiocb->ki_pos = req->file->f_pos;
2463 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2464 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2465 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2469 ioprio = READ_ONCE(sqe->ioprio);
2471 ret = ioprio_check_cap(ioprio);
2475 kiocb->ki_ioprio = ioprio;
2477 kiocb->ki_ioprio = get_current_ioprio();
2479 /* don't allow async punt if RWF_NOWAIT was requested */
2480 if (kiocb->ki_flags & IOCB_NOWAIT)
2481 req->flags |= REQ_F_NOWAIT;
2483 if (kiocb->ki_flags & IOCB_DIRECT)
2484 io_get_req_task(req);
2487 kiocb->ki_flags |= IOCB_NOWAIT;
2489 if (ctx->flags & IORING_SETUP_IOPOLL) {
2490 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2491 !kiocb->ki_filp->f_op->iopoll)
2494 kiocb->ki_flags |= IOCB_HIPRI;
2495 kiocb->ki_complete = io_complete_rw_iopoll;
2496 req->iopoll_completed = 0;
2497 io_get_req_task(req);
2499 if (kiocb->ki_flags & IOCB_HIPRI)
2501 kiocb->ki_complete = io_complete_rw;
2504 req->rw.addr = READ_ONCE(sqe->addr);
2505 req->rw.len = READ_ONCE(sqe->len);
2506 req->buf_index = READ_ONCE(sqe->buf_index);
2510 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2516 case -ERESTARTNOINTR:
2517 case -ERESTARTNOHAND:
2518 case -ERESTART_RESTARTBLOCK:
2520 * We can't just restart the syscall, since previously
2521 * submitted sqes may already be in progress. Just fail this
2527 kiocb->ki_complete(kiocb, ret, 0);
2531 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2532 struct io_comp_state *cs)
2534 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2536 if (req->flags & REQ_F_CUR_POS)
2537 req->file->f_pos = kiocb->ki_pos;
2538 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2539 __io_complete_rw(req, ret, 0, cs);
2541 io_rw_done(kiocb, ret);
2544 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2545 struct iov_iter *iter)
2547 struct io_ring_ctx *ctx = req->ctx;
2548 size_t len = req->rw.len;
2549 struct io_mapped_ubuf *imu;
2550 u16 index, buf_index;
2554 /* attempt to use fixed buffers without having provided iovecs */
2555 if (unlikely(!ctx->user_bufs))
2558 buf_index = req->buf_index;
2559 if (unlikely(buf_index >= ctx->nr_user_bufs))
2562 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2563 imu = &ctx->user_bufs[index];
2564 buf_addr = req->rw.addr;
2567 if (buf_addr + len < buf_addr)
2569 /* not inside the mapped region */
2570 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2574 * May not be a start of buffer, set size appropriately
2575 * and advance us to the beginning.
2577 offset = buf_addr - imu->ubuf;
2578 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2582 * Don't use iov_iter_advance() here, as it's really slow for
2583 * using the latter parts of a big fixed buffer - it iterates
2584 * over each segment manually. We can cheat a bit here, because
2587 * 1) it's a BVEC iter, we set it up
2588 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2589 * first and last bvec
2591 * So just find our index, and adjust the iterator afterwards.
2592 * If the offset is within the first bvec (or the whole first
2593 * bvec, just use iov_iter_advance(). This makes it easier
2594 * since we can just skip the first segment, which may not
2595 * be PAGE_SIZE aligned.
2597 const struct bio_vec *bvec = imu->bvec;
2599 if (offset <= bvec->bv_len) {
2600 iov_iter_advance(iter, offset);
2602 unsigned long seg_skip;
2604 /* skip first vec */
2605 offset -= bvec->bv_len;
2606 seg_skip = 1 + (offset >> PAGE_SHIFT);
2608 iter->bvec = bvec + seg_skip;
2609 iter->nr_segs -= seg_skip;
2610 iter->count -= bvec->bv_len + offset;
2611 iter->iov_offset = offset & ~PAGE_MASK;
2618 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2621 mutex_unlock(&ctx->uring_lock);
2624 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2627 * "Normal" inline submissions always hold the uring_lock, since we
2628 * grab it from the system call. Same is true for the SQPOLL offload.
2629 * The only exception is when we've detached the request and issue it
2630 * from an async worker thread, grab the lock for that case.
2633 mutex_lock(&ctx->uring_lock);
2636 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2637 int bgid, struct io_buffer *kbuf,
2640 struct io_buffer *head;
2642 if (req->flags & REQ_F_BUFFER_SELECTED)
2645 io_ring_submit_lock(req->ctx, needs_lock);
2647 lockdep_assert_held(&req->ctx->uring_lock);
2649 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2651 if (!list_empty(&head->list)) {
2652 kbuf = list_last_entry(&head->list, struct io_buffer,
2654 list_del(&kbuf->list);
2657 idr_remove(&req->ctx->io_buffer_idr, bgid);
2659 if (*len > kbuf->len)
2662 kbuf = ERR_PTR(-ENOBUFS);
2665 io_ring_submit_unlock(req->ctx, needs_lock);
2670 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2673 struct io_buffer *kbuf;
2676 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2677 bgid = req->buf_index;
2678 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2681 req->rw.addr = (u64) (unsigned long) kbuf;
2682 req->flags |= REQ_F_BUFFER_SELECTED;
2683 return u64_to_user_ptr(kbuf->addr);
2686 #ifdef CONFIG_COMPAT
2687 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2690 struct compat_iovec __user *uiov;
2691 compat_ssize_t clen;
2695 uiov = u64_to_user_ptr(req->rw.addr);
2696 if (!access_ok(uiov, sizeof(*uiov)))
2698 if (__get_user(clen, &uiov->iov_len))
2704 buf = io_rw_buffer_select(req, &len, needs_lock);
2706 return PTR_ERR(buf);
2707 iov[0].iov_base = buf;
2708 iov[0].iov_len = (compat_size_t) len;
2713 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2716 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2720 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2723 len = iov[0].iov_len;
2726 buf = io_rw_buffer_select(req, &len, needs_lock);
2728 return PTR_ERR(buf);
2729 iov[0].iov_base = buf;
2730 iov[0].iov_len = len;
2734 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2737 if (req->flags & REQ_F_BUFFER_SELECTED) {
2738 struct io_buffer *kbuf;
2740 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2741 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2742 iov[0].iov_len = kbuf->len;
2747 else if (req->rw.len > 1)
2750 #ifdef CONFIG_COMPAT
2751 if (req->ctx->compat)
2752 return io_compat_import(req, iov, needs_lock);
2755 return __io_iov_buffer_select(req, iov, needs_lock);
2758 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2759 struct iovec **iovec, struct iov_iter *iter,
2762 void __user *buf = u64_to_user_ptr(req->rw.addr);
2763 size_t sqe_len = req->rw.len;
2767 opcode = req->opcode;
2768 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2770 return io_import_fixed(req, rw, iter);
2773 /* buffer index only valid with fixed read/write, or buffer select */
2774 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2777 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2778 if (req->flags & REQ_F_BUFFER_SELECT) {
2779 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2782 return PTR_ERR(buf);
2784 req->rw.len = sqe_len;
2787 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2789 return ret < 0 ? ret : sqe_len;
2793 struct io_async_rw *iorw = &req->io->rw;
2795 iov_iter_init(iter, rw, iorw->iov, iorw->nr_segs, iorw->size);
2800 if (req->flags & REQ_F_BUFFER_SELECT) {
2801 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2803 ret = (*iovec)->iov_len;
2804 iov_iter_init(iter, rw, *iovec, 1, ret);
2810 #ifdef CONFIG_COMPAT
2811 if (req->ctx->compat)
2812 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2816 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2820 * For files that don't have ->read_iter() and ->write_iter(), handle them
2821 * by looping over ->read() or ->write() manually.
2823 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2824 struct iov_iter *iter)
2829 * Don't support polled IO through this interface, and we can't
2830 * support non-blocking either. For the latter, this just causes
2831 * the kiocb to be handled from an async context.
2833 if (kiocb->ki_flags & IOCB_HIPRI)
2835 if (kiocb->ki_flags & IOCB_NOWAIT)
2838 while (iov_iter_count(iter)) {
2842 if (!iov_iter_is_bvec(iter)) {
2843 iovec = iov_iter_iovec(iter);
2845 /* fixed buffers import bvec */
2846 iovec.iov_base = kmap(iter->bvec->bv_page)
2848 iovec.iov_len = min(iter->count,
2849 iter->bvec->bv_len - iter->iov_offset);
2853 nr = file->f_op->read(file, iovec.iov_base,
2854 iovec.iov_len, &kiocb->ki_pos);
2856 nr = file->f_op->write(file, iovec.iov_base,
2857 iovec.iov_len, &kiocb->ki_pos);
2860 if (iov_iter_is_bvec(iter))
2861 kunmap(iter->bvec->bv_page);
2869 if (nr != iovec.iov_len)
2871 iov_iter_advance(iter, nr);
2877 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2878 struct iovec *iovec, struct iovec *fast_iov,
2879 struct iov_iter *iter)
2881 struct io_async_rw *rw = &req->io->rw;
2883 rw->nr_segs = iter->nr_segs;
2886 rw->iov = rw->fast_iov;
2887 if (rw->iov != fast_iov)
2888 memcpy(rw->iov, fast_iov,
2889 sizeof(struct iovec) * iter->nr_segs);
2892 req->flags |= REQ_F_NEED_CLEANUP;
2896 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2898 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2899 return req->io == NULL;
2902 static int io_alloc_async_ctx(struct io_kiocb *req)
2904 if (!io_op_defs[req->opcode].async_ctx)
2907 return __io_alloc_async_ctx(req);
2910 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2911 struct iovec *iovec, struct iovec *fast_iov,
2912 struct iov_iter *iter)
2914 if (!io_op_defs[req->opcode].async_ctx)
2917 if (__io_alloc_async_ctx(req))
2920 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2925 static inline int io_rw_prep_async(struct io_kiocb *req, int rw,
2926 bool force_nonblock)
2928 struct io_async_ctx *io = req->io;
2929 struct iov_iter iter;
2932 io->rw.iov = io->rw.fast_iov;
2934 ret = io_import_iovec(rw, req, &io->rw.iov, &iter, !force_nonblock);
2936 if (unlikely(ret < 0))
2939 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2943 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2944 bool force_nonblock)
2948 ret = io_prep_rw(req, sqe, force_nonblock);
2952 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2955 /* either don't need iovec imported or already have it */
2956 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2958 return io_rw_prep_async(req, READ, force_nonblock);
2961 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2962 int sync, void *arg)
2964 struct wait_page_queue *wpq;
2965 struct io_kiocb *req = wait->private;
2966 struct wait_page_key *key = arg;
2969 wpq = container_of(wait, struct wait_page_queue, wait);
2971 ret = wake_page_match(wpq, key);
2975 list_del_init(&wait->entry);
2977 init_task_work(&req->task_work, io_req_task_submit);
2978 /* submit ref gets dropped, acquire a new one */
2979 refcount_inc(&req->refs);
2980 ret = io_req_task_work_add(req, &req->task_work);
2981 if (unlikely(ret)) {
2982 struct task_struct *tsk;
2984 /* queue just for cancelation */
2985 init_task_work(&req->task_work, io_req_task_cancel);
2986 tsk = io_wq_get_task(req->ctx->io_wq);
2987 task_work_add(tsk, &req->task_work, 0);
2988 wake_up_process(tsk);
2993 static bool io_rw_should_retry(struct io_kiocb *req)
2995 struct kiocb *kiocb = &req->rw.kiocb;
2998 /* never retry for NOWAIT, we just complete with -EAGAIN */
2999 if (req->flags & REQ_F_NOWAIT)
3002 /* already tried, or we're doing O_DIRECT */
3003 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_WAITQ))
3006 * just use poll if we can, and don't attempt if the fs doesn't
3007 * support callback based unlocks
3009 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3013 * If request type doesn't require req->io to defer in general,
3014 * we need to allocate it here
3016 if (!req->io && __io_alloc_async_ctx(req))
3019 ret = kiocb_wait_page_queue_init(kiocb, &req->io->rw.wpq,
3020 io_async_buf_func, req);
3022 io_get_req_task(req);
3029 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3031 if (req->file->f_op->read_iter)
3032 return call_read_iter(req->file, &req->rw.kiocb, iter);
3033 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
3036 static int io_read(struct io_kiocb *req, bool force_nonblock,
3037 struct io_comp_state *cs)
3039 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3040 struct kiocb *kiocb = &req->rw.kiocb;
3041 struct iov_iter iter;
3043 ssize_t io_size, ret;
3045 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
3049 /* Ensure we clear previously set non-block flag */
3050 if (!force_nonblock)
3051 kiocb->ki_flags &= ~IOCB_NOWAIT;
3054 req->result = io_size;
3056 /* If the file doesn't support async, just async punt */
3057 if (force_nonblock && !io_file_supports_async(req->file, READ))
3060 iov_count = iov_iter_count(&iter);
3061 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
3063 unsigned long nr_segs = iter.nr_segs;
3066 ret2 = io_iter_do_read(req, &iter);
3068 /* Catch -EAGAIN return for forced non-blocking submission */
3069 if (!force_nonblock || (ret2 != -EAGAIN && ret2 != -EIO)) {
3070 kiocb_done(kiocb, ret2, cs);
3072 iter.count = iov_count;
3073 iter.nr_segs = nr_segs;
3075 ret = io_setup_async_rw(req, io_size, iovec,
3076 inline_vecs, &iter);
3079 /* it's copied and will be cleaned with ->io */
3081 /* if we can retry, do so with the callbacks armed */
3082 if (io_rw_should_retry(req)) {
3083 ret2 = io_iter_do_read(req, &iter);
3084 if (ret2 == -EIOCBQUEUED) {
3086 } else if (ret2 != -EAGAIN) {
3087 kiocb_done(kiocb, ret2, cs);
3091 kiocb->ki_flags &= ~IOCB_WAITQ;
3101 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3102 bool force_nonblock)
3106 ret = io_prep_rw(req, sqe, force_nonblock);
3110 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3113 /* either don't need iovec imported or already have it */
3114 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3116 return io_rw_prep_async(req, WRITE, force_nonblock);
3119 static int io_write(struct io_kiocb *req, bool force_nonblock,
3120 struct io_comp_state *cs)
3122 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3123 struct kiocb *kiocb = &req->rw.kiocb;
3124 struct iov_iter iter;
3126 ssize_t ret, io_size;
3128 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
3132 /* Ensure we clear previously set non-block flag */
3133 if (!force_nonblock)
3134 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
3137 req->result = io_size;
3139 /* If the file doesn't support async, just async punt */
3140 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3143 /* file path doesn't support NOWAIT for non-direct_IO */
3144 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3145 (req->flags & REQ_F_ISREG))
3148 iov_count = iov_iter_count(&iter);
3149 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
3151 unsigned long nr_segs = iter.nr_segs;
3155 * Open-code file_start_write here to grab freeze protection,
3156 * which will be released by another thread in
3157 * io_complete_rw(). Fool lockdep by telling it the lock got
3158 * released so that it doesn't complain about the held lock when
3159 * we return to userspace.
3161 if (req->flags & REQ_F_ISREG) {
3162 __sb_start_write(file_inode(req->file)->i_sb,
3163 SB_FREEZE_WRITE, true);
3164 __sb_writers_release(file_inode(req->file)->i_sb,
3167 kiocb->ki_flags |= IOCB_WRITE;
3169 if (req->file->f_op->write_iter)
3170 ret2 = call_write_iter(req->file, kiocb, &iter);
3172 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
3175 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3176 * retry them without IOCB_NOWAIT.
3178 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3180 if (!force_nonblock || ret2 != -EAGAIN) {
3181 kiocb_done(kiocb, ret2, cs);
3183 iter.count = iov_count;
3184 iter.nr_segs = nr_segs;
3186 ret = io_setup_async_rw(req, io_size, iovec,
3187 inline_vecs, &iter);
3190 /* it's copied and will be cleaned with ->io */
3201 static int __io_splice_prep(struct io_kiocb *req,
3202 const struct io_uring_sqe *sqe)
3204 struct io_splice* sp = &req->splice;
3205 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3208 if (req->flags & REQ_F_NEED_CLEANUP)
3210 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3214 sp->len = READ_ONCE(sqe->len);
3215 sp->flags = READ_ONCE(sqe->splice_flags);
3217 if (unlikely(sp->flags & ~valid_flags))
3220 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
3221 (sp->flags & SPLICE_F_FD_IN_FIXED));
3224 req->flags |= REQ_F_NEED_CLEANUP;
3226 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3228 * Splice operation will be punted aync, and here need to
3229 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3231 io_req_init_async(req);
3232 req->work.flags |= IO_WQ_WORK_UNBOUND;
3238 static int io_tee_prep(struct io_kiocb *req,
3239 const struct io_uring_sqe *sqe)
3241 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3243 return __io_splice_prep(req, sqe);
3246 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3248 struct io_splice *sp = &req->splice;
3249 struct file *in = sp->file_in;
3250 struct file *out = sp->file_out;
3251 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3257 ret = do_tee(in, out, sp->len, flags);
3259 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3260 req->flags &= ~REQ_F_NEED_CLEANUP;
3263 req_set_fail_links(req);
3264 io_req_complete(req, ret);
3268 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3270 struct io_splice* sp = &req->splice;
3272 sp->off_in = READ_ONCE(sqe->splice_off_in);
3273 sp->off_out = READ_ONCE(sqe->off);
3274 return __io_splice_prep(req, sqe);
3277 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3279 struct io_splice *sp = &req->splice;
3280 struct file *in = sp->file_in;
3281 struct file *out = sp->file_out;
3282 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3283 loff_t *poff_in, *poff_out;
3289 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3290 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3293 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3295 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3296 req->flags &= ~REQ_F_NEED_CLEANUP;
3299 req_set_fail_links(req);
3300 io_req_complete(req, ret);
3305 * IORING_OP_NOP just posts a completion event, nothing else.
3307 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3309 struct io_ring_ctx *ctx = req->ctx;
3311 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3314 __io_req_complete(req, 0, 0, cs);
3318 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3320 struct io_ring_ctx *ctx = req->ctx;
3325 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3327 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3330 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3331 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3334 req->sync.off = READ_ONCE(sqe->off);
3335 req->sync.len = READ_ONCE(sqe->len);
3339 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3341 loff_t end = req->sync.off + req->sync.len;
3344 /* fsync always requires a blocking context */
3348 ret = vfs_fsync_range(req->file, req->sync.off,
3349 end > 0 ? end : LLONG_MAX,
3350 req->sync.flags & IORING_FSYNC_DATASYNC);
3352 req_set_fail_links(req);
3353 io_req_complete(req, ret);
3357 static int io_fallocate_prep(struct io_kiocb *req,
3358 const struct io_uring_sqe *sqe)
3360 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3362 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3365 req->sync.off = READ_ONCE(sqe->off);
3366 req->sync.len = READ_ONCE(sqe->addr);
3367 req->sync.mode = READ_ONCE(sqe->len);
3371 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3375 /* fallocate always requiring blocking context */
3378 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3381 req_set_fail_links(req);
3382 io_req_complete(req, ret);
3386 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3388 const char __user *fname;
3391 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3393 if (unlikely(sqe->ioprio || sqe->buf_index))
3395 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3398 /* open.how should be already initialised */
3399 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3400 req->open.how.flags |= O_LARGEFILE;
3402 req->open.dfd = READ_ONCE(sqe->fd);
3403 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3404 req->open.filename = getname(fname);
3405 if (IS_ERR(req->open.filename)) {
3406 ret = PTR_ERR(req->open.filename);
3407 req->open.filename = NULL;
3410 req->open.nofile = rlimit(RLIMIT_NOFILE);
3411 req->flags |= REQ_F_NEED_CLEANUP;
3415 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3419 if (req->flags & REQ_F_NEED_CLEANUP)
3421 mode = READ_ONCE(sqe->len);
3422 flags = READ_ONCE(sqe->open_flags);
3423 req->open.how = build_open_how(flags, mode);
3424 return __io_openat_prep(req, sqe);
3427 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3429 struct open_how __user *how;
3433 if (req->flags & REQ_F_NEED_CLEANUP)
3435 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3436 len = READ_ONCE(sqe->len);
3437 if (len < OPEN_HOW_SIZE_VER0)
3440 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3445 return __io_openat_prep(req, sqe);
3448 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3450 struct open_flags op;
3457 ret = build_open_flags(&req->open.how, &op);
3461 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3465 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3468 ret = PTR_ERR(file);
3470 fsnotify_open(file);
3471 fd_install(ret, file);
3474 putname(req->open.filename);
3475 req->flags &= ~REQ_F_NEED_CLEANUP;
3477 req_set_fail_links(req);
3478 io_req_complete(req, ret);
3482 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3484 return io_openat2(req, force_nonblock);
3487 static int io_remove_buffers_prep(struct io_kiocb *req,
3488 const struct io_uring_sqe *sqe)
3490 struct io_provide_buf *p = &req->pbuf;
3493 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3496 tmp = READ_ONCE(sqe->fd);
3497 if (!tmp || tmp > USHRT_MAX)
3500 memset(p, 0, sizeof(*p));
3502 p->bgid = READ_ONCE(sqe->buf_group);
3506 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3507 int bgid, unsigned nbufs)
3511 /* shouldn't happen */
3515 /* the head kbuf is the list itself */
3516 while (!list_empty(&buf->list)) {
3517 struct io_buffer *nxt;
3519 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3520 list_del(&nxt->list);
3527 idr_remove(&ctx->io_buffer_idr, bgid);
3532 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3533 struct io_comp_state *cs)
3535 struct io_provide_buf *p = &req->pbuf;
3536 struct io_ring_ctx *ctx = req->ctx;
3537 struct io_buffer *head;
3540 io_ring_submit_lock(ctx, !force_nonblock);
3542 lockdep_assert_held(&ctx->uring_lock);
3545 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3547 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3549 io_ring_submit_lock(ctx, !force_nonblock);
3551 req_set_fail_links(req);
3552 __io_req_complete(req, ret, 0, cs);
3556 static int io_provide_buffers_prep(struct io_kiocb *req,
3557 const struct io_uring_sqe *sqe)
3559 struct io_provide_buf *p = &req->pbuf;
3562 if (sqe->ioprio || sqe->rw_flags)
3565 tmp = READ_ONCE(sqe->fd);
3566 if (!tmp || tmp > USHRT_MAX)
3569 p->addr = READ_ONCE(sqe->addr);
3570 p->len = READ_ONCE(sqe->len);
3572 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3575 p->bgid = READ_ONCE(sqe->buf_group);
3576 tmp = READ_ONCE(sqe->off);
3577 if (tmp > USHRT_MAX)
3583 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3585 struct io_buffer *buf;
3586 u64 addr = pbuf->addr;
3587 int i, bid = pbuf->bid;
3589 for (i = 0; i < pbuf->nbufs; i++) {
3590 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3595 buf->len = pbuf->len;
3600 INIT_LIST_HEAD(&buf->list);
3603 list_add_tail(&buf->list, &(*head)->list);
3607 return i ? i : -ENOMEM;
3610 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3611 struct io_comp_state *cs)
3613 struct io_provide_buf *p = &req->pbuf;
3614 struct io_ring_ctx *ctx = req->ctx;
3615 struct io_buffer *head, *list;
3618 io_ring_submit_lock(ctx, !force_nonblock);
3620 lockdep_assert_held(&ctx->uring_lock);
3622 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3624 ret = io_add_buffers(p, &head);
3629 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3632 __io_remove_buffers(ctx, head, p->bgid, -1U);
3637 io_ring_submit_unlock(ctx, !force_nonblock);
3639 req_set_fail_links(req);
3640 __io_req_complete(req, ret, 0, cs);
3644 static int io_epoll_ctl_prep(struct io_kiocb *req,
3645 const struct io_uring_sqe *sqe)
3647 #if defined(CONFIG_EPOLL)
3648 if (sqe->ioprio || sqe->buf_index)
3650 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3653 req->epoll.epfd = READ_ONCE(sqe->fd);
3654 req->epoll.op = READ_ONCE(sqe->len);
3655 req->epoll.fd = READ_ONCE(sqe->off);
3657 if (ep_op_has_event(req->epoll.op)) {
3658 struct epoll_event __user *ev;
3660 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3661 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3671 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3672 struct io_comp_state *cs)
3674 #if defined(CONFIG_EPOLL)
3675 struct io_epoll *ie = &req->epoll;
3678 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3679 if (force_nonblock && ret == -EAGAIN)
3683 req_set_fail_links(req);
3684 __io_req_complete(req, ret, 0, cs);
3691 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3693 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3694 if (sqe->ioprio || sqe->buf_index || sqe->off)
3696 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3699 req->madvise.addr = READ_ONCE(sqe->addr);
3700 req->madvise.len = READ_ONCE(sqe->len);
3701 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3708 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3710 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3711 struct io_madvise *ma = &req->madvise;
3717 ret = do_madvise(ma->addr, ma->len, ma->advice);
3719 req_set_fail_links(req);
3720 io_req_complete(req, ret);
3727 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3729 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3731 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3734 req->fadvise.offset = READ_ONCE(sqe->off);
3735 req->fadvise.len = READ_ONCE(sqe->len);
3736 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3740 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3742 struct io_fadvise *fa = &req->fadvise;
3745 if (force_nonblock) {
3746 switch (fa->advice) {
3747 case POSIX_FADV_NORMAL:
3748 case POSIX_FADV_RANDOM:
3749 case POSIX_FADV_SEQUENTIAL:
3756 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3758 req_set_fail_links(req);
3759 io_req_complete(req, ret);
3763 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3765 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3767 if (sqe->ioprio || sqe->buf_index)
3769 if (req->flags & REQ_F_FIXED_FILE)
3772 req->statx.dfd = READ_ONCE(sqe->fd);
3773 req->statx.mask = READ_ONCE(sqe->len);
3774 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
3775 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3776 req->statx.flags = READ_ONCE(sqe->statx_flags);
3781 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3783 struct io_statx *ctx = &req->statx;
3786 if (force_nonblock) {
3787 /* only need file table for an actual valid fd */
3788 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3789 req->flags |= REQ_F_NO_FILE_TABLE;
3793 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3797 req_set_fail_links(req);
3798 io_req_complete(req, ret);
3802 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3805 * If we queue this for async, it must not be cancellable. That would
3806 * leave the 'file' in an undeterminate state, and here need to modify
3807 * io_wq_work.flags, so initialize io_wq_work firstly.
3809 io_req_init_async(req);
3810 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3812 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3814 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3815 sqe->rw_flags || sqe->buf_index)
3817 if (req->flags & REQ_F_FIXED_FILE)
3820 req->close.fd = READ_ONCE(sqe->fd);
3821 if ((req->file && req->file->f_op == &io_uring_fops) ||
3822 req->close.fd == req->ctx->ring_fd)
3825 req->close.put_file = NULL;
3829 static int io_close(struct io_kiocb *req, bool force_nonblock,
3830 struct io_comp_state *cs)
3832 struct io_close *close = &req->close;
3835 /* might be already done during nonblock submission */
3836 if (!close->put_file) {
3837 ret = __close_fd_get_file(close->fd, &close->put_file);
3839 return (ret == -ENOENT) ? -EBADF : ret;
3842 /* if the file has a flush method, be safe and punt to async */
3843 if (close->put_file->f_op->flush && force_nonblock) {
3844 /* was never set, but play safe */
3845 req->flags &= ~REQ_F_NOWAIT;
3846 /* avoid grabbing files - we don't need the files */
3847 req->flags |= REQ_F_NO_FILE_TABLE;
3851 /* No ->flush() or already async, safely close from here */
3852 ret = filp_close(close->put_file, req->work.files);
3854 req_set_fail_links(req);
3855 fput(close->put_file);
3856 close->put_file = NULL;
3857 __io_req_complete(req, ret, 0, cs);
3861 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3863 struct io_ring_ctx *ctx = req->ctx;
3868 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3870 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3873 req->sync.off = READ_ONCE(sqe->off);
3874 req->sync.len = READ_ONCE(sqe->len);
3875 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3879 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3883 /* sync_file_range always requires a blocking context */
3887 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3890 req_set_fail_links(req);
3891 io_req_complete(req, ret);
3895 #if defined(CONFIG_NET)
3896 static int io_setup_async_msg(struct io_kiocb *req,
3897 struct io_async_msghdr *kmsg)
3901 if (io_alloc_async_ctx(req)) {
3902 if (kmsg->iov != kmsg->fast_iov)
3906 req->flags |= REQ_F_NEED_CLEANUP;
3907 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3911 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
3912 struct io_async_msghdr *iomsg)
3914 iomsg->iov = iomsg->fast_iov;
3915 iomsg->msg.msg_name = &iomsg->addr;
3916 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
3917 req->sr_msg.msg_flags, &iomsg->iov);
3920 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3922 struct io_sr_msg *sr = &req->sr_msg;
3923 struct io_async_ctx *io = req->io;
3926 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3929 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3930 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3931 sr->len = READ_ONCE(sqe->len);
3933 #ifdef CONFIG_COMPAT
3934 if (req->ctx->compat)
3935 sr->msg_flags |= MSG_CMSG_COMPAT;
3938 if (!io || req->opcode == IORING_OP_SEND)
3940 /* iovec is already imported */
3941 if (req->flags & REQ_F_NEED_CLEANUP)
3944 ret = io_sendmsg_copy_hdr(req, &io->msg);
3946 req->flags |= REQ_F_NEED_CLEANUP;
3950 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
3951 struct io_comp_state *cs)
3953 struct io_async_msghdr iomsg, *kmsg;
3954 struct socket *sock;
3958 sock = sock_from_file(req->file, &ret);
3959 if (unlikely(!sock))
3963 kmsg = &req->io->msg;
3964 kmsg->msg.msg_name = &req->io->msg.addr;
3965 /* if iov is set, it's allocated already */
3967 kmsg->iov = kmsg->fast_iov;
3968 kmsg->msg.msg_iter.iov = kmsg->iov;
3970 ret = io_sendmsg_copy_hdr(req, &iomsg);
3976 flags = req->sr_msg.msg_flags;
3977 if (flags & MSG_DONTWAIT)
3978 req->flags |= REQ_F_NOWAIT;
3979 else if (force_nonblock)
3980 flags |= MSG_DONTWAIT;
3982 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3983 if (force_nonblock && ret == -EAGAIN)
3984 return io_setup_async_msg(req, kmsg);
3985 if (ret == -ERESTARTSYS)
3988 if (kmsg->iov != kmsg->fast_iov)
3990 req->flags &= ~REQ_F_NEED_CLEANUP;
3992 req_set_fail_links(req);
3993 __io_req_complete(req, ret, 0, cs);
3997 static int io_send(struct io_kiocb *req, bool force_nonblock,
3998 struct io_comp_state *cs)
4000 struct io_sr_msg *sr = &req->sr_msg;
4003 struct socket *sock;
4007 sock = sock_from_file(req->file, &ret);
4008 if (unlikely(!sock))
4011 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4015 msg.msg_name = NULL;
4016 msg.msg_control = NULL;
4017 msg.msg_controllen = 0;
4018 msg.msg_namelen = 0;
4020 flags = req->sr_msg.msg_flags;
4021 if (flags & MSG_DONTWAIT)
4022 req->flags |= REQ_F_NOWAIT;
4023 else if (force_nonblock)
4024 flags |= MSG_DONTWAIT;
4026 msg.msg_flags = flags;
4027 ret = sock_sendmsg(sock, &msg);
4028 if (force_nonblock && ret == -EAGAIN)
4030 if (ret == -ERESTARTSYS)
4034 req_set_fail_links(req);
4035 __io_req_complete(req, ret, 0, cs);
4039 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4040 struct io_async_msghdr *iomsg)
4042 struct io_sr_msg *sr = &req->sr_msg;
4043 struct iovec __user *uiov;
4047 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4048 &iomsg->uaddr, &uiov, &iov_len);
4052 if (req->flags & REQ_F_BUFFER_SELECT) {
4055 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4057 sr->len = iomsg->iov[0].iov_len;
4058 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4062 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4063 &iomsg->iov, &iomsg->msg.msg_iter);
4071 #ifdef CONFIG_COMPAT
4072 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4073 struct io_async_msghdr *iomsg)
4075 struct compat_msghdr __user *msg_compat;
4076 struct io_sr_msg *sr = &req->sr_msg;
4077 struct compat_iovec __user *uiov;
4082 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4083 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4088 uiov = compat_ptr(ptr);
4089 if (req->flags & REQ_F_BUFFER_SELECT) {
4090 compat_ssize_t clen;
4094 if (!access_ok(uiov, sizeof(*uiov)))
4096 if (__get_user(clen, &uiov->iov_len))
4100 sr->len = iomsg->iov[0].iov_len;
4103 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
4105 &iomsg->msg.msg_iter);
4114 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4115 struct io_async_msghdr *iomsg)
4117 iomsg->msg.msg_name = &iomsg->addr;
4118 iomsg->iov = iomsg->fast_iov;
4120 #ifdef CONFIG_COMPAT
4121 if (req->ctx->compat)
4122 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4125 return __io_recvmsg_copy_hdr(req, iomsg);
4128 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4131 struct io_sr_msg *sr = &req->sr_msg;
4132 struct io_buffer *kbuf;
4134 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4139 req->flags |= REQ_F_BUFFER_SELECTED;
4143 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4145 return io_put_kbuf(req, req->sr_msg.kbuf);
4148 static int io_recvmsg_prep(struct io_kiocb *req,
4149 const struct io_uring_sqe *sqe)
4151 struct io_sr_msg *sr = &req->sr_msg;
4152 struct io_async_ctx *io = req->io;
4155 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4158 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4159 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4160 sr->len = READ_ONCE(sqe->len);
4161 sr->bgid = READ_ONCE(sqe->buf_group);
4163 #ifdef CONFIG_COMPAT
4164 if (req->ctx->compat)
4165 sr->msg_flags |= MSG_CMSG_COMPAT;
4168 if (!io || req->opcode == IORING_OP_RECV)
4170 /* iovec is already imported */
4171 if (req->flags & REQ_F_NEED_CLEANUP)
4174 ret = io_recvmsg_copy_hdr(req, &io->msg);
4176 req->flags |= REQ_F_NEED_CLEANUP;
4180 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4181 struct io_comp_state *cs)
4183 struct io_async_msghdr iomsg, *kmsg;
4184 struct socket *sock;
4185 struct io_buffer *kbuf;
4187 int ret, cflags = 0;
4189 sock = sock_from_file(req->file, &ret);
4190 if (unlikely(!sock))
4194 kmsg = &req->io->msg;
4195 kmsg->msg.msg_name = &req->io->msg.addr;
4196 /* if iov is set, it's allocated already */
4198 kmsg->iov = kmsg->fast_iov;
4199 kmsg->msg.msg_iter.iov = kmsg->iov;
4201 ret = io_recvmsg_copy_hdr(req, &iomsg);
4207 if (req->flags & REQ_F_BUFFER_SELECT) {
4208 kbuf = io_recv_buffer_select(req, !force_nonblock);
4210 return PTR_ERR(kbuf);
4211 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4212 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4213 1, req->sr_msg.len);
4216 flags = req->sr_msg.msg_flags;
4217 if (flags & MSG_DONTWAIT)
4218 req->flags |= REQ_F_NOWAIT;
4219 else if (force_nonblock)
4220 flags |= MSG_DONTWAIT;
4222 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4223 kmsg->uaddr, flags);
4224 if (force_nonblock && ret == -EAGAIN)
4225 return io_setup_async_msg(req, kmsg);
4226 if (ret == -ERESTARTSYS)
4229 if (req->flags & REQ_F_BUFFER_SELECTED)
4230 cflags = io_put_recv_kbuf(req);
4231 if (kmsg->iov != kmsg->fast_iov)
4233 req->flags &= ~REQ_F_NEED_CLEANUP;
4235 req_set_fail_links(req);
4236 __io_req_complete(req, ret, cflags, cs);
4240 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4241 struct io_comp_state *cs)
4243 struct io_buffer *kbuf;
4244 struct io_sr_msg *sr = &req->sr_msg;
4246 void __user *buf = sr->buf;
4247 struct socket *sock;
4250 int ret, cflags = 0;
4252 sock = sock_from_file(req->file, &ret);
4253 if (unlikely(!sock))
4256 if (req->flags & REQ_F_BUFFER_SELECT) {
4257 kbuf = io_recv_buffer_select(req, !force_nonblock);
4259 return PTR_ERR(kbuf);
4260 buf = u64_to_user_ptr(kbuf->addr);
4263 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4267 msg.msg_name = NULL;
4268 msg.msg_control = NULL;
4269 msg.msg_controllen = 0;
4270 msg.msg_namelen = 0;
4271 msg.msg_iocb = NULL;
4274 flags = req->sr_msg.msg_flags;
4275 if (flags & MSG_DONTWAIT)
4276 req->flags |= REQ_F_NOWAIT;
4277 else if (force_nonblock)
4278 flags |= MSG_DONTWAIT;
4280 ret = sock_recvmsg(sock, &msg, flags);
4281 if (force_nonblock && ret == -EAGAIN)
4283 if (ret == -ERESTARTSYS)
4286 if (req->flags & REQ_F_BUFFER_SELECTED)
4287 cflags = io_put_recv_kbuf(req);
4289 req_set_fail_links(req);
4290 __io_req_complete(req, ret, cflags, cs);
4294 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4296 struct io_accept *accept = &req->accept;
4298 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4300 if (sqe->ioprio || sqe->len || sqe->buf_index)
4303 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4304 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4305 accept->flags = READ_ONCE(sqe->accept_flags);
4306 accept->nofile = rlimit(RLIMIT_NOFILE);
4310 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4311 struct io_comp_state *cs)
4313 struct io_accept *accept = &req->accept;
4314 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4317 if (req->file->f_flags & O_NONBLOCK)
4318 req->flags |= REQ_F_NOWAIT;
4320 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4321 accept->addr_len, accept->flags,
4323 if (ret == -EAGAIN && force_nonblock)
4326 if (ret == -ERESTARTSYS)
4328 req_set_fail_links(req);
4330 __io_req_complete(req, ret, 0, cs);
4334 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4336 struct io_connect *conn = &req->connect;
4337 struct io_async_ctx *io = req->io;
4339 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4341 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4344 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4345 conn->addr_len = READ_ONCE(sqe->addr2);
4350 return move_addr_to_kernel(conn->addr, conn->addr_len,
4351 &io->connect.address);
4354 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4355 struct io_comp_state *cs)
4357 struct io_async_ctx __io, *io;
4358 unsigned file_flags;
4364 ret = move_addr_to_kernel(req->connect.addr,
4365 req->connect.addr_len,
4366 &__io.connect.address);
4372 file_flags = force_nonblock ? O_NONBLOCK : 0;
4374 ret = __sys_connect_file(req->file, &io->connect.address,
4375 req->connect.addr_len, file_flags);
4376 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4379 if (io_alloc_async_ctx(req)) {
4383 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4386 if (ret == -ERESTARTSYS)
4390 req_set_fail_links(req);
4391 __io_req_complete(req, ret, 0, cs);
4394 #else /* !CONFIG_NET */
4395 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4400 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4401 struct io_comp_state *cs)
4406 static int io_send(struct io_kiocb *req, bool force_nonblock,
4407 struct io_comp_state *cs)
4412 static int io_recvmsg_prep(struct io_kiocb *req,
4413 const struct io_uring_sqe *sqe)
4418 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4419 struct io_comp_state *cs)
4424 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4425 struct io_comp_state *cs)
4430 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4435 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4436 struct io_comp_state *cs)
4441 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4446 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4447 struct io_comp_state *cs)
4451 #endif /* CONFIG_NET */
4453 struct io_poll_table {
4454 struct poll_table_struct pt;
4455 struct io_kiocb *req;
4459 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4460 __poll_t mask, task_work_func_t func)
4464 /* for instances that support it check for an event match first: */
4465 if (mask && !(mask & poll->events))
4468 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4470 list_del_init(&poll->wait.entry);
4473 init_task_work(&req->task_work, func);
4475 * If this fails, then the task is exiting. When a task exits, the
4476 * work gets canceled, so just cancel this request as well instead
4477 * of executing it. We can't safely execute it anyway, as we may not
4478 * have the needed state needed for it anyway.
4480 ret = io_req_task_work_add(req, &req->task_work);
4481 if (unlikely(ret)) {
4482 struct task_struct *tsk;
4484 WRITE_ONCE(poll->canceled, true);
4485 tsk = io_wq_get_task(req->ctx->io_wq);
4486 task_work_add(tsk, &req->task_work, 0);
4487 wake_up_process(tsk);
4492 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4493 __acquires(&req->ctx->completion_lock)
4495 struct io_ring_ctx *ctx = req->ctx;
4497 if (!req->result && !READ_ONCE(poll->canceled)) {
4498 struct poll_table_struct pt = { ._key = poll->events };
4500 req->result = vfs_poll(req->file, &pt) & poll->events;
4503 spin_lock_irq(&ctx->completion_lock);
4504 if (!req->result && !READ_ONCE(poll->canceled)) {
4505 add_wait_queue(poll->head, &poll->wait);
4512 static void io_poll_remove_double(struct io_kiocb *req, void *data)
4514 struct io_poll_iocb *poll = data;
4516 lockdep_assert_held(&req->ctx->completion_lock);
4518 if (poll && poll->head) {
4519 struct wait_queue_head *head = poll->head;
4521 spin_lock(&head->lock);
4522 list_del_init(&poll->wait.entry);
4523 if (poll->wait.private)
4524 refcount_dec(&req->refs);
4526 spin_unlock(&head->lock);
4530 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4532 struct io_ring_ctx *ctx = req->ctx;
4534 io_poll_remove_double(req, req->io);
4535 req->poll.done = true;
4536 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4537 io_commit_cqring(ctx);
4540 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4542 struct io_ring_ctx *ctx = req->ctx;
4544 if (io_poll_rewait(req, &req->poll)) {
4545 spin_unlock_irq(&ctx->completion_lock);
4549 hash_del(&req->hash_node);
4550 io_poll_complete(req, req->result, 0);
4551 req->flags |= REQ_F_COMP_LOCKED;
4552 *nxt = io_put_req_find_next(req);
4553 spin_unlock_irq(&ctx->completion_lock);
4555 io_cqring_ev_posted(ctx);
4558 static void io_poll_task_func(struct callback_head *cb)
4560 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4561 struct io_kiocb *nxt = NULL;
4563 io_poll_task_handler(req, &nxt);
4565 __io_req_task_submit(nxt);
4568 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4569 int sync, void *key)
4571 struct io_kiocb *req = wait->private;
4572 struct io_poll_iocb *poll = req->apoll->double_poll;
4573 __poll_t mask = key_to_poll(key);
4575 /* for instances that support it check for an event match first: */
4576 if (mask && !(mask & poll->events))
4579 if (poll && poll->head) {
4582 spin_lock(&poll->head->lock);
4583 done = list_empty(&poll->wait.entry);
4585 list_del_init(&poll->wait.entry);
4586 spin_unlock(&poll->head->lock);
4588 __io_async_wake(req, poll, mask, io_poll_task_func);
4590 refcount_dec(&req->refs);
4594 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4595 wait_queue_func_t wake_func)
4599 poll->canceled = false;
4600 poll->events = events;
4601 INIT_LIST_HEAD(&poll->wait.entry);
4602 init_waitqueue_func_entry(&poll->wait, wake_func);
4605 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4606 struct wait_queue_head *head,
4607 struct io_poll_iocb **poll_ptr)
4609 struct io_kiocb *req = pt->req;
4612 * If poll->head is already set, it's because the file being polled
4613 * uses multiple waitqueues for poll handling (eg one for read, one
4614 * for write). Setup a separate io_poll_iocb if this happens.
4616 if (unlikely(poll->head)) {
4617 /* already have a 2nd entry, fail a third attempt */
4619 pt->error = -EINVAL;
4622 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4624 pt->error = -ENOMEM;
4627 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4628 refcount_inc(&req->refs);
4629 poll->wait.private = req;
4636 if (poll->events & EPOLLEXCLUSIVE)
4637 add_wait_queue_exclusive(head, &poll->wait);
4639 add_wait_queue(head, &poll->wait);
4642 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4643 struct poll_table_struct *p)
4645 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4646 struct async_poll *apoll = pt->req->apoll;
4648 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
4651 static void io_async_task_func(struct callback_head *cb)
4653 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4654 struct async_poll *apoll = req->apoll;
4655 struct io_ring_ctx *ctx = req->ctx;
4657 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4659 if (io_poll_rewait(req, &apoll->poll)) {
4660 spin_unlock_irq(&ctx->completion_lock);
4664 /* If req is still hashed, it cannot have been canceled. Don't check. */
4665 if (hash_hashed(&req->hash_node))
4666 hash_del(&req->hash_node);
4668 io_poll_remove_double(req, apoll->double_poll);
4669 spin_unlock_irq(&ctx->completion_lock);
4671 /* restore ->work in case we need to retry again */
4672 if (req->flags & REQ_F_WORK_INITIALIZED)
4673 memcpy(&req->work, &apoll->work, sizeof(req->work));
4675 if (!READ_ONCE(apoll->poll.canceled))
4676 __io_req_task_submit(req);
4678 __io_req_task_cancel(req, -ECANCELED);
4680 kfree(apoll->double_poll);
4684 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4687 struct io_kiocb *req = wait->private;
4688 struct io_poll_iocb *poll = &req->apoll->poll;
4690 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4693 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4696 static void io_poll_req_insert(struct io_kiocb *req)
4698 struct io_ring_ctx *ctx = req->ctx;
4699 struct hlist_head *list;
4701 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4702 hlist_add_head(&req->hash_node, list);
4705 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4706 struct io_poll_iocb *poll,
4707 struct io_poll_table *ipt, __poll_t mask,
4708 wait_queue_func_t wake_func)
4709 __acquires(&ctx->completion_lock)
4711 struct io_ring_ctx *ctx = req->ctx;
4712 bool cancel = false;
4714 io_init_poll_iocb(poll, mask, wake_func);
4715 poll->file = req->file;
4716 poll->wait.private = req;
4718 ipt->pt._key = mask;
4720 ipt->error = -EINVAL;
4722 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4724 spin_lock_irq(&ctx->completion_lock);
4725 if (likely(poll->head)) {
4726 spin_lock(&poll->head->lock);
4727 if (unlikely(list_empty(&poll->wait.entry))) {
4733 if (mask || ipt->error)
4734 list_del_init(&poll->wait.entry);
4736 WRITE_ONCE(poll->canceled, true);
4737 else if (!poll->done) /* actually waiting for an event */
4738 io_poll_req_insert(req);
4739 spin_unlock(&poll->head->lock);
4745 static bool io_arm_poll_handler(struct io_kiocb *req)
4747 const struct io_op_def *def = &io_op_defs[req->opcode];
4748 struct io_ring_ctx *ctx = req->ctx;
4749 struct async_poll *apoll;
4750 struct io_poll_table ipt;
4753 if (!req->file || !file_can_poll(req->file))
4755 if (req->flags & REQ_F_POLLED)
4757 if (!def->pollin && !def->pollout)
4760 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4761 if (unlikely(!apoll))
4763 apoll->double_poll = NULL;
4765 req->flags |= REQ_F_POLLED;
4766 if (req->flags & REQ_F_WORK_INITIALIZED)
4767 memcpy(&apoll->work, &req->work, sizeof(req->work));
4769 io_get_req_task(req);
4771 INIT_HLIST_NODE(&req->hash_node);
4775 mask |= POLLIN | POLLRDNORM;
4777 mask |= POLLOUT | POLLWRNORM;
4778 mask |= POLLERR | POLLPRI;
4780 ipt.pt._qproc = io_async_queue_proc;
4782 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4785 io_poll_remove_double(req, apoll->double_poll);
4786 spin_unlock_irq(&ctx->completion_lock);
4787 if (req->flags & REQ_F_WORK_INITIALIZED)
4788 memcpy(&req->work, &apoll->work, sizeof(req->work));
4789 kfree(apoll->double_poll);
4793 spin_unlock_irq(&ctx->completion_lock);
4794 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4795 apoll->poll.events);
4799 static bool __io_poll_remove_one(struct io_kiocb *req,
4800 struct io_poll_iocb *poll)
4802 bool do_complete = false;
4804 spin_lock(&poll->head->lock);
4805 WRITE_ONCE(poll->canceled, true);
4806 if (!list_empty(&poll->wait.entry)) {
4807 list_del_init(&poll->wait.entry);
4810 spin_unlock(&poll->head->lock);
4811 hash_del(&req->hash_node);
4815 static bool io_poll_remove_one(struct io_kiocb *req)
4819 if (req->opcode == IORING_OP_POLL_ADD) {
4820 io_poll_remove_double(req, req->io);
4821 do_complete = __io_poll_remove_one(req, &req->poll);
4823 struct async_poll *apoll = req->apoll;
4825 io_poll_remove_double(req, apoll->double_poll);
4827 /* non-poll requests have submit ref still */
4828 do_complete = __io_poll_remove_one(req, &apoll->poll);
4832 * restore ->work because we will call
4833 * io_req_clean_work below when dropping the
4836 if (req->flags & REQ_F_WORK_INITIALIZED)
4837 memcpy(&req->work, &apoll->work,
4839 kfree(apoll->double_poll);
4845 io_cqring_fill_event(req, -ECANCELED);
4846 io_commit_cqring(req->ctx);
4847 req->flags |= REQ_F_COMP_LOCKED;
4854 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4856 struct hlist_node *tmp;
4857 struct io_kiocb *req;
4860 spin_lock_irq(&ctx->completion_lock);
4861 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4862 struct hlist_head *list;
4864 list = &ctx->cancel_hash[i];
4865 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4866 posted += io_poll_remove_one(req);
4868 spin_unlock_irq(&ctx->completion_lock);
4871 io_cqring_ev_posted(ctx);
4874 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4876 struct hlist_head *list;
4877 struct io_kiocb *req;
4879 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4880 hlist_for_each_entry(req, list, hash_node) {
4881 if (sqe_addr != req->user_data)
4883 if (io_poll_remove_one(req))
4891 static int io_poll_remove_prep(struct io_kiocb *req,
4892 const struct io_uring_sqe *sqe)
4894 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4896 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4900 req->poll.addr = READ_ONCE(sqe->addr);
4905 * Find a running poll command that matches one specified in sqe->addr,
4906 * and remove it if found.
4908 static int io_poll_remove(struct io_kiocb *req)
4910 struct io_ring_ctx *ctx = req->ctx;
4914 addr = req->poll.addr;
4915 spin_lock_irq(&ctx->completion_lock);
4916 ret = io_poll_cancel(ctx, addr);
4917 spin_unlock_irq(&ctx->completion_lock);
4920 req_set_fail_links(req);
4921 io_req_complete(req, ret);
4925 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4928 struct io_kiocb *req = wait->private;
4929 struct io_poll_iocb *poll = &req->poll;
4931 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4934 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4935 struct poll_table_struct *p)
4937 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4939 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->io);
4942 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4944 struct io_poll_iocb *poll = &req->poll;
4947 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4949 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4954 events = READ_ONCE(sqe->poll32_events);
4956 events = swahw32(events);
4958 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
4959 (events & EPOLLEXCLUSIVE);
4961 io_get_req_task(req);
4965 static int io_poll_add(struct io_kiocb *req)
4967 struct io_poll_iocb *poll = &req->poll;
4968 struct io_ring_ctx *ctx = req->ctx;
4969 struct io_poll_table ipt;
4972 /* ->work is in union with hash_node and others */
4973 io_req_clean_work(req);
4975 INIT_HLIST_NODE(&req->hash_node);
4976 ipt.pt._qproc = io_poll_queue_proc;
4978 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4981 if (mask) { /* no async, we'd stolen it */
4983 io_poll_complete(req, mask, 0);
4985 spin_unlock_irq(&ctx->completion_lock);
4988 io_cqring_ev_posted(ctx);
4994 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4996 struct io_timeout_data *data = container_of(timer,
4997 struct io_timeout_data, timer);
4998 struct io_kiocb *req = data->req;
4999 struct io_ring_ctx *ctx = req->ctx;
5000 unsigned long flags;
5002 atomic_inc(&ctx->cq_timeouts);
5004 spin_lock_irqsave(&ctx->completion_lock, flags);
5006 * We could be racing with timeout deletion. If the list is empty,
5007 * then timeout lookup already found it and will be handling it.
5009 if (!list_empty(&req->timeout.list))
5010 list_del_init(&req->timeout.list);
5012 io_cqring_fill_event(req, -ETIME);
5013 io_commit_cqring(ctx);
5014 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5016 io_cqring_ev_posted(ctx);
5017 req_set_fail_links(req);
5019 return HRTIMER_NORESTART;
5022 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5024 struct io_kiocb *req;
5027 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5028 if (user_data == req->user_data) {
5029 list_del_init(&req->timeout.list);
5038 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
5042 req_set_fail_links(req);
5043 io_cqring_fill_event(req, -ECANCELED);
5048 static int io_timeout_remove_prep(struct io_kiocb *req,
5049 const struct io_uring_sqe *sqe)
5051 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5053 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5055 if (sqe->ioprio || sqe->buf_index || sqe->len)
5058 req->timeout.addr = READ_ONCE(sqe->addr);
5059 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
5060 if (req->timeout.flags)
5067 * Remove or update an existing timeout command
5069 static int io_timeout_remove(struct io_kiocb *req)
5071 struct io_ring_ctx *ctx = req->ctx;
5074 spin_lock_irq(&ctx->completion_lock);
5075 ret = io_timeout_cancel(ctx, req->timeout.addr);
5077 io_cqring_fill_event(req, ret);
5078 io_commit_cqring(ctx);
5079 spin_unlock_irq(&ctx->completion_lock);
5080 io_cqring_ev_posted(ctx);
5082 req_set_fail_links(req);
5087 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5088 bool is_timeout_link)
5090 struct io_timeout_data *data;
5092 u32 off = READ_ONCE(sqe->off);
5094 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5096 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5098 if (off && is_timeout_link)
5100 flags = READ_ONCE(sqe->timeout_flags);
5101 if (flags & ~IORING_TIMEOUT_ABS)
5104 req->timeout.off = off;
5106 if (!req->io && io_alloc_async_ctx(req))
5109 data = &req->io->timeout;
5112 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5115 if (flags & IORING_TIMEOUT_ABS)
5116 data->mode = HRTIMER_MODE_ABS;
5118 data->mode = HRTIMER_MODE_REL;
5120 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5124 static int io_timeout(struct io_kiocb *req)
5126 struct io_ring_ctx *ctx = req->ctx;
5127 struct io_timeout_data *data = &req->io->timeout;
5128 struct list_head *entry;
5129 u32 tail, off = req->timeout.off;
5131 spin_lock_irq(&ctx->completion_lock);
5134 * sqe->off holds how many events that need to occur for this
5135 * timeout event to be satisfied. If it isn't set, then this is
5136 * a pure timeout request, sequence isn't used.
5138 if (io_is_timeout_noseq(req)) {
5139 entry = ctx->timeout_list.prev;
5143 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5144 req->timeout.target_seq = tail + off;
5147 * Insertion sort, ensuring the first entry in the list is always
5148 * the one we need first.
5150 list_for_each_prev(entry, &ctx->timeout_list) {
5151 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5154 if (io_is_timeout_noseq(nxt))
5156 /* nxt.seq is behind @tail, otherwise would've been completed */
5157 if (off >= nxt->timeout.target_seq - tail)
5161 list_add(&req->timeout.list, entry);
5162 data->timer.function = io_timeout_fn;
5163 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5164 spin_unlock_irq(&ctx->completion_lock);
5168 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5170 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5172 return req->user_data == (unsigned long) data;
5175 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5177 enum io_wq_cancel cancel_ret;
5180 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5181 switch (cancel_ret) {
5182 case IO_WQ_CANCEL_OK:
5185 case IO_WQ_CANCEL_RUNNING:
5188 case IO_WQ_CANCEL_NOTFOUND:
5196 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5197 struct io_kiocb *req, __u64 sqe_addr,
5200 unsigned long flags;
5203 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5204 if (ret != -ENOENT) {
5205 spin_lock_irqsave(&ctx->completion_lock, flags);
5209 spin_lock_irqsave(&ctx->completion_lock, flags);
5210 ret = io_timeout_cancel(ctx, sqe_addr);
5213 ret = io_poll_cancel(ctx, sqe_addr);
5217 io_cqring_fill_event(req, ret);
5218 io_commit_cqring(ctx);
5219 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5220 io_cqring_ev_posted(ctx);
5223 req_set_fail_links(req);
5227 static int io_async_cancel_prep(struct io_kiocb *req,
5228 const struct io_uring_sqe *sqe)
5230 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5232 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5234 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5237 req->cancel.addr = READ_ONCE(sqe->addr);
5241 static int io_async_cancel(struct io_kiocb *req)
5243 struct io_ring_ctx *ctx = req->ctx;
5245 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5249 static int io_files_update_prep(struct io_kiocb *req,
5250 const struct io_uring_sqe *sqe)
5252 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5254 if (sqe->ioprio || sqe->rw_flags)
5257 req->files_update.offset = READ_ONCE(sqe->off);
5258 req->files_update.nr_args = READ_ONCE(sqe->len);
5259 if (!req->files_update.nr_args)
5261 req->files_update.arg = READ_ONCE(sqe->addr);
5265 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5266 struct io_comp_state *cs)
5268 struct io_ring_ctx *ctx = req->ctx;
5269 struct io_uring_files_update up;
5275 up.offset = req->files_update.offset;
5276 up.fds = req->files_update.arg;
5278 mutex_lock(&ctx->uring_lock);
5279 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5280 mutex_unlock(&ctx->uring_lock);
5283 req_set_fail_links(req);
5284 __io_req_complete(req, ret, 0, cs);
5288 static int io_req_defer_prep(struct io_kiocb *req,
5289 const struct io_uring_sqe *sqe)
5296 if (io_alloc_async_ctx(req))
5298 ret = io_prep_work_files(req);
5302 switch (req->opcode) {
5305 case IORING_OP_READV:
5306 case IORING_OP_READ_FIXED:
5307 case IORING_OP_READ:
5308 ret = io_read_prep(req, sqe, true);
5310 case IORING_OP_WRITEV:
5311 case IORING_OP_WRITE_FIXED:
5312 case IORING_OP_WRITE:
5313 ret = io_write_prep(req, sqe, true);
5315 case IORING_OP_POLL_ADD:
5316 ret = io_poll_add_prep(req, sqe);
5318 case IORING_OP_POLL_REMOVE:
5319 ret = io_poll_remove_prep(req, sqe);
5321 case IORING_OP_FSYNC:
5322 ret = io_prep_fsync(req, sqe);
5324 case IORING_OP_SYNC_FILE_RANGE:
5325 ret = io_prep_sfr(req, sqe);
5327 case IORING_OP_SENDMSG:
5328 case IORING_OP_SEND:
5329 ret = io_sendmsg_prep(req, sqe);
5331 case IORING_OP_RECVMSG:
5332 case IORING_OP_RECV:
5333 ret = io_recvmsg_prep(req, sqe);
5335 case IORING_OP_CONNECT:
5336 ret = io_connect_prep(req, sqe);
5338 case IORING_OP_TIMEOUT:
5339 ret = io_timeout_prep(req, sqe, false);
5341 case IORING_OP_TIMEOUT_REMOVE:
5342 ret = io_timeout_remove_prep(req, sqe);
5344 case IORING_OP_ASYNC_CANCEL:
5345 ret = io_async_cancel_prep(req, sqe);
5347 case IORING_OP_LINK_TIMEOUT:
5348 ret = io_timeout_prep(req, sqe, true);
5350 case IORING_OP_ACCEPT:
5351 ret = io_accept_prep(req, sqe);
5353 case IORING_OP_FALLOCATE:
5354 ret = io_fallocate_prep(req, sqe);
5356 case IORING_OP_OPENAT:
5357 ret = io_openat_prep(req, sqe);
5359 case IORING_OP_CLOSE:
5360 ret = io_close_prep(req, sqe);
5362 case IORING_OP_FILES_UPDATE:
5363 ret = io_files_update_prep(req, sqe);
5365 case IORING_OP_STATX:
5366 ret = io_statx_prep(req, sqe);
5368 case IORING_OP_FADVISE:
5369 ret = io_fadvise_prep(req, sqe);
5371 case IORING_OP_MADVISE:
5372 ret = io_madvise_prep(req, sqe);
5374 case IORING_OP_OPENAT2:
5375 ret = io_openat2_prep(req, sqe);
5377 case IORING_OP_EPOLL_CTL:
5378 ret = io_epoll_ctl_prep(req, sqe);
5380 case IORING_OP_SPLICE:
5381 ret = io_splice_prep(req, sqe);
5383 case IORING_OP_PROVIDE_BUFFERS:
5384 ret = io_provide_buffers_prep(req, sqe);
5386 case IORING_OP_REMOVE_BUFFERS:
5387 ret = io_remove_buffers_prep(req, sqe);
5390 ret = io_tee_prep(req, sqe);
5393 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5402 static u32 io_get_sequence(struct io_kiocb *req)
5404 struct io_kiocb *pos;
5405 struct io_ring_ctx *ctx = req->ctx;
5406 u32 total_submitted, nr_reqs = 1;
5408 if (req->flags & REQ_F_LINK_HEAD)
5409 list_for_each_entry(pos, &req->link_list, link_list)
5412 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5413 return total_submitted - nr_reqs;
5416 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5418 struct io_ring_ctx *ctx = req->ctx;
5419 struct io_defer_entry *de;
5423 /* Still need defer if there is pending req in defer list. */
5424 if (likely(list_empty_careful(&ctx->defer_list) &&
5425 !(req->flags & REQ_F_IO_DRAIN)))
5428 seq = io_get_sequence(req);
5429 /* Still a chance to pass the sequence check */
5430 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5434 ret = io_req_defer_prep(req, sqe);
5438 io_prep_async_link(req);
5439 de = kmalloc(sizeof(*de), GFP_KERNEL);
5443 spin_lock_irq(&ctx->completion_lock);
5444 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5445 spin_unlock_irq(&ctx->completion_lock);
5447 io_queue_async_work(req);
5448 return -EIOCBQUEUED;
5451 trace_io_uring_defer(ctx, req, req->user_data);
5454 list_add_tail(&de->list, &ctx->defer_list);
5455 spin_unlock_irq(&ctx->completion_lock);
5456 return -EIOCBQUEUED;
5459 static void __io_clean_op(struct io_kiocb *req)
5461 struct io_async_ctx *io = req->io;
5463 if (req->flags & REQ_F_BUFFER_SELECTED) {
5464 switch (req->opcode) {
5465 case IORING_OP_READV:
5466 case IORING_OP_READ_FIXED:
5467 case IORING_OP_READ:
5468 kfree((void *)(unsigned long)req->rw.addr);
5470 case IORING_OP_RECVMSG:
5471 case IORING_OP_RECV:
5472 kfree(req->sr_msg.kbuf);
5475 req->flags &= ~REQ_F_BUFFER_SELECTED;
5478 if (req->flags & REQ_F_NEED_CLEANUP) {
5479 switch (req->opcode) {
5480 case IORING_OP_READV:
5481 case IORING_OP_READ_FIXED:
5482 case IORING_OP_READ:
5483 case IORING_OP_WRITEV:
5484 case IORING_OP_WRITE_FIXED:
5485 case IORING_OP_WRITE:
5486 if (io->rw.iov != io->rw.fast_iov)
5489 case IORING_OP_RECVMSG:
5490 case IORING_OP_SENDMSG:
5491 if (io->msg.iov != io->msg.fast_iov)
5494 case IORING_OP_SPLICE:
5496 io_put_file(req, req->splice.file_in,
5497 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5500 req->flags &= ~REQ_F_NEED_CLEANUP;
5504 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5505 bool force_nonblock, struct io_comp_state *cs)
5507 struct io_ring_ctx *ctx = req->ctx;
5510 switch (req->opcode) {
5512 ret = io_nop(req, cs);
5514 case IORING_OP_READV:
5515 case IORING_OP_READ_FIXED:
5516 case IORING_OP_READ:
5518 ret = io_read_prep(req, sqe, force_nonblock);
5522 ret = io_read(req, force_nonblock, cs);
5524 case IORING_OP_WRITEV:
5525 case IORING_OP_WRITE_FIXED:
5526 case IORING_OP_WRITE:
5528 ret = io_write_prep(req, sqe, force_nonblock);
5532 ret = io_write(req, force_nonblock, cs);
5534 case IORING_OP_FSYNC:
5536 ret = io_prep_fsync(req, sqe);
5540 ret = io_fsync(req, force_nonblock);
5542 case IORING_OP_POLL_ADD:
5544 ret = io_poll_add_prep(req, sqe);
5548 ret = io_poll_add(req);
5550 case IORING_OP_POLL_REMOVE:
5552 ret = io_poll_remove_prep(req, sqe);
5556 ret = io_poll_remove(req);
5558 case IORING_OP_SYNC_FILE_RANGE:
5560 ret = io_prep_sfr(req, sqe);
5564 ret = io_sync_file_range(req, force_nonblock);
5566 case IORING_OP_SENDMSG:
5567 case IORING_OP_SEND:
5569 ret = io_sendmsg_prep(req, sqe);
5573 if (req->opcode == IORING_OP_SENDMSG)
5574 ret = io_sendmsg(req, force_nonblock, cs);
5576 ret = io_send(req, force_nonblock, cs);
5578 case IORING_OP_RECVMSG:
5579 case IORING_OP_RECV:
5581 ret = io_recvmsg_prep(req, sqe);
5585 if (req->opcode == IORING_OP_RECVMSG)
5586 ret = io_recvmsg(req, force_nonblock, cs);
5588 ret = io_recv(req, force_nonblock, cs);
5590 case IORING_OP_TIMEOUT:
5592 ret = io_timeout_prep(req, sqe, false);
5596 ret = io_timeout(req);
5598 case IORING_OP_TIMEOUT_REMOVE:
5600 ret = io_timeout_remove_prep(req, sqe);
5604 ret = io_timeout_remove(req);
5606 case IORING_OP_ACCEPT:
5608 ret = io_accept_prep(req, sqe);
5612 ret = io_accept(req, force_nonblock, cs);
5614 case IORING_OP_CONNECT:
5616 ret = io_connect_prep(req, sqe);
5620 ret = io_connect(req, force_nonblock, cs);
5622 case IORING_OP_ASYNC_CANCEL:
5624 ret = io_async_cancel_prep(req, sqe);
5628 ret = io_async_cancel(req);
5630 case IORING_OP_FALLOCATE:
5632 ret = io_fallocate_prep(req, sqe);
5636 ret = io_fallocate(req, force_nonblock);
5638 case IORING_OP_OPENAT:
5640 ret = io_openat_prep(req, sqe);
5644 ret = io_openat(req, force_nonblock);
5646 case IORING_OP_CLOSE:
5648 ret = io_close_prep(req, sqe);
5652 ret = io_close(req, force_nonblock, cs);
5654 case IORING_OP_FILES_UPDATE:
5656 ret = io_files_update_prep(req, sqe);
5660 ret = io_files_update(req, force_nonblock, cs);
5662 case IORING_OP_STATX:
5664 ret = io_statx_prep(req, sqe);
5668 ret = io_statx(req, force_nonblock);
5670 case IORING_OP_FADVISE:
5672 ret = io_fadvise_prep(req, sqe);
5676 ret = io_fadvise(req, force_nonblock);
5678 case IORING_OP_MADVISE:
5680 ret = io_madvise_prep(req, sqe);
5684 ret = io_madvise(req, force_nonblock);
5686 case IORING_OP_OPENAT2:
5688 ret = io_openat2_prep(req, sqe);
5692 ret = io_openat2(req, force_nonblock);
5694 case IORING_OP_EPOLL_CTL:
5696 ret = io_epoll_ctl_prep(req, sqe);
5700 ret = io_epoll_ctl(req, force_nonblock, cs);
5702 case IORING_OP_SPLICE:
5704 ret = io_splice_prep(req, sqe);
5708 ret = io_splice(req, force_nonblock);
5710 case IORING_OP_PROVIDE_BUFFERS:
5712 ret = io_provide_buffers_prep(req, sqe);
5716 ret = io_provide_buffers(req, force_nonblock, cs);
5718 case IORING_OP_REMOVE_BUFFERS:
5720 ret = io_remove_buffers_prep(req, sqe);
5724 ret = io_remove_buffers(req, force_nonblock, cs);
5728 ret = io_tee_prep(req, sqe);
5732 ret = io_tee(req, force_nonblock);
5742 /* If the op doesn't have a file, we're not polling for it */
5743 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5744 const bool in_async = io_wq_current_is_worker();
5746 /* workqueue context doesn't hold uring_lock, grab it now */
5748 mutex_lock(&ctx->uring_lock);
5750 io_iopoll_req_issued(req);
5753 mutex_unlock(&ctx->uring_lock);
5759 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
5761 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5762 struct io_kiocb *timeout;
5765 timeout = io_prep_linked_timeout(req);
5767 io_queue_linked_timeout(timeout);
5769 /* if NO_CANCEL is set, we must still run the work */
5770 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5771 IO_WQ_WORK_CANCEL) {
5777 ret = io_issue_sqe(req, NULL, false, NULL);
5779 * We can get EAGAIN for polled IO even though we're
5780 * forcing a sync submission from here, since we can't
5781 * wait for request slots on the block side.
5790 req_set_fail_links(req);
5791 io_req_complete(req, ret);
5794 return io_steal_work(req);
5797 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5800 struct fixed_file_table *table;
5802 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5803 return table->files[index & IORING_FILE_TABLE_MASK];
5806 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5807 int fd, struct file **out_file, bool fixed)
5809 struct io_ring_ctx *ctx = req->ctx;
5813 if (unlikely(!ctx->file_data ||
5814 (unsigned) fd >= ctx->nr_user_files))
5816 fd = array_index_nospec(fd, ctx->nr_user_files);
5817 file = io_file_from_index(ctx, fd);
5819 req->fixed_file_refs = ctx->file_data->cur_refs;
5820 percpu_ref_get(req->fixed_file_refs);
5823 trace_io_uring_file_get(ctx, fd);
5824 file = __io_file_get(state, fd);
5827 if (file || io_op_defs[req->opcode].needs_file_no_error) {
5834 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5839 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5840 if (unlikely(!fixed && io_async_submit(req->ctx)))
5843 return io_file_get(state, req, fd, &req->file, fixed);
5846 static int io_grab_files(struct io_kiocb *req)
5849 struct io_ring_ctx *ctx = req->ctx;
5851 io_req_init_async(req);
5853 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5855 if (!ctx->ring_file)
5859 spin_lock_irq(&ctx->inflight_lock);
5861 * We use the f_ops->flush() handler to ensure that we can flush
5862 * out work accessing these files if the fd is closed. Check if
5863 * the fd has changed since we started down this path, and disallow
5864 * this operation if it has.
5866 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5867 list_add(&req->inflight_entry, &ctx->inflight_list);
5868 req->flags |= REQ_F_INFLIGHT;
5869 req->work.files = current->files;
5872 spin_unlock_irq(&ctx->inflight_lock);
5878 static inline int io_prep_work_files(struct io_kiocb *req)
5880 if (!io_op_defs[req->opcode].file_table)
5882 return io_grab_files(req);
5885 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5887 struct io_timeout_data *data = container_of(timer,
5888 struct io_timeout_data, timer);
5889 struct io_kiocb *req = data->req;
5890 struct io_ring_ctx *ctx = req->ctx;
5891 struct io_kiocb *prev = NULL;
5892 unsigned long flags;
5894 spin_lock_irqsave(&ctx->completion_lock, flags);
5897 * We don't expect the list to be empty, that will only happen if we
5898 * race with the completion of the linked work.
5900 if (!list_empty(&req->link_list)) {
5901 prev = list_entry(req->link_list.prev, struct io_kiocb,
5903 if (refcount_inc_not_zero(&prev->refs)) {
5904 list_del_init(&req->link_list);
5905 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5910 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5913 req_set_fail_links(prev);
5914 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5917 io_req_complete(req, -ETIME);
5919 return HRTIMER_NORESTART;
5922 static void io_queue_linked_timeout(struct io_kiocb *req)
5924 struct io_ring_ctx *ctx = req->ctx;
5927 * If the list is now empty, then our linked request finished before
5928 * we got a chance to setup the timer
5930 spin_lock_irq(&ctx->completion_lock);
5931 if (!list_empty(&req->link_list)) {
5932 struct io_timeout_data *data = &req->io->timeout;
5934 data->timer.function = io_link_timeout_fn;
5935 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5938 spin_unlock_irq(&ctx->completion_lock);
5940 /* drop submission reference */
5944 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5946 struct io_kiocb *nxt;
5948 if (!(req->flags & REQ_F_LINK_HEAD))
5950 if (req->flags & REQ_F_LINK_TIMEOUT)
5953 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5955 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5958 req->flags |= REQ_F_LINK_TIMEOUT;
5962 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5963 struct io_comp_state *cs)
5965 struct io_kiocb *linked_timeout;
5966 struct io_kiocb *nxt;
5967 const struct cred *old_creds = NULL;
5971 linked_timeout = io_prep_linked_timeout(req);
5973 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
5974 req->work.creds != current_cred()) {
5976 revert_creds(old_creds);
5977 if (old_creds == req->work.creds)
5978 old_creds = NULL; /* restored original creds */
5980 old_creds = override_creds(req->work.creds);
5983 ret = io_issue_sqe(req, sqe, true, cs);
5986 * We async punt it if the file wasn't marked NOWAIT, or if the file
5987 * doesn't support non-blocking read/write attempts
5989 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
5990 if (io_arm_poll_handler(req)) {
5992 io_queue_linked_timeout(linked_timeout);
5996 ret = io_prep_work_files(req);
6000 * Queued up for async execution, worker will release
6001 * submit reference when the iocb is actually submitted.
6003 io_queue_async_work(req);
6007 if (unlikely(ret)) {
6009 /* un-prep timeout, so it'll be killed as any other linked */
6010 req->flags &= ~REQ_F_LINK_TIMEOUT;
6011 req_set_fail_links(req);
6013 io_req_complete(req, ret);
6017 /* drop submission reference */
6018 nxt = io_put_req_find_next(req);
6020 io_queue_linked_timeout(linked_timeout);
6025 if (req->flags & REQ_F_FORCE_ASYNC)
6031 revert_creds(old_creds);
6034 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6035 struct io_comp_state *cs)
6039 ret = io_req_defer(req, sqe);
6041 if (ret != -EIOCBQUEUED) {
6043 req_set_fail_links(req);
6045 io_req_complete(req, ret);
6047 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6049 ret = io_req_defer_prep(req, sqe);
6055 * Never try inline submit of IOSQE_ASYNC is set, go straight
6056 * to async execution.
6058 io_req_init_async(req);
6059 req->work.flags |= IO_WQ_WORK_CONCURRENT;
6060 io_queue_async_work(req);
6062 __io_queue_sqe(req, sqe, cs);
6066 static inline void io_queue_link_head(struct io_kiocb *req,
6067 struct io_comp_state *cs)
6069 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6071 io_req_complete(req, -ECANCELED);
6073 io_queue_sqe(req, NULL, cs);
6076 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6077 struct io_kiocb **link, struct io_comp_state *cs)
6079 struct io_ring_ctx *ctx = req->ctx;
6083 * If we already have a head request, queue this one for async
6084 * submittal once the head completes. If we don't have a head but
6085 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6086 * submitted sync once the chain is complete. If none of those
6087 * conditions are true (normal request), then just queue it.
6090 struct io_kiocb *head = *link;
6093 * Taking sequential execution of a link, draining both sides
6094 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6095 * requests in the link. So, it drains the head and the
6096 * next after the link request. The last one is done via
6097 * drain_next flag to persist the effect across calls.
6099 if (req->flags & REQ_F_IO_DRAIN) {
6100 head->flags |= REQ_F_IO_DRAIN;
6101 ctx->drain_next = 1;
6103 ret = io_req_defer_prep(req, sqe);
6104 if (unlikely(ret)) {
6105 /* fail even hard links since we don't submit */
6106 head->flags |= REQ_F_FAIL_LINK;
6109 trace_io_uring_link(ctx, req, head);
6110 io_get_req_task(req);
6111 list_add_tail(&req->link_list, &head->link_list);
6113 /* last request of a link, enqueue the link */
6114 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6115 io_queue_link_head(head, cs);
6119 if (unlikely(ctx->drain_next)) {
6120 req->flags |= REQ_F_IO_DRAIN;
6121 ctx->drain_next = 0;
6123 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6124 req->flags |= REQ_F_LINK_HEAD;
6125 INIT_LIST_HEAD(&req->link_list);
6127 ret = io_req_defer_prep(req, sqe);
6129 req->flags |= REQ_F_FAIL_LINK;
6132 io_queue_sqe(req, sqe, cs);
6140 * Batched submission is done, ensure local IO is flushed out.
6142 static void io_submit_state_end(struct io_submit_state *state)
6144 if (!list_empty(&state->comp.list))
6145 io_submit_flush_completions(&state->comp);
6146 blk_finish_plug(&state->plug);
6147 io_state_file_put(state);
6148 if (state->free_reqs)
6149 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6153 * Start submission side cache.
6155 static void io_submit_state_start(struct io_submit_state *state,
6156 struct io_ring_ctx *ctx, unsigned int max_ios)
6158 blk_start_plug(&state->plug);
6160 state->plug.nowait = true;
6163 INIT_LIST_HEAD(&state->comp.list);
6164 state->comp.ctx = ctx;
6165 state->free_reqs = 0;
6167 state->ios_left = max_ios;
6170 static void io_commit_sqring(struct io_ring_ctx *ctx)
6172 struct io_rings *rings = ctx->rings;
6175 * Ensure any loads from the SQEs are done at this point,
6176 * since once we write the new head, the application could
6177 * write new data to them.
6179 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6183 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6184 * that is mapped by userspace. This means that care needs to be taken to
6185 * ensure that reads are stable, as we cannot rely on userspace always
6186 * being a good citizen. If members of the sqe are validated and then later
6187 * used, it's important that those reads are done through READ_ONCE() to
6188 * prevent a re-load down the line.
6190 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6192 u32 *sq_array = ctx->sq_array;
6196 * The cached sq head (or cq tail) serves two purposes:
6198 * 1) allows us to batch the cost of updating the user visible
6200 * 2) allows the kernel side to track the head on its own, even
6201 * though the application is the one updating it.
6203 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6204 if (likely(head < ctx->sq_entries))
6205 return &ctx->sq_sqes[head];
6207 /* drop invalid entries */
6208 ctx->cached_sq_dropped++;
6209 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6213 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6215 ctx->cached_sq_head++;
6218 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6219 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6220 IOSQE_BUFFER_SELECT)
6222 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6223 const struct io_uring_sqe *sqe,
6224 struct io_submit_state *state)
6226 unsigned int sqe_flags;
6229 req->opcode = READ_ONCE(sqe->opcode);
6230 req->user_data = READ_ONCE(sqe->user_data);
6235 /* one is dropped after submission, the other at completion */
6236 refcount_set(&req->refs, 2);
6237 req->task = current;
6240 if (unlikely(req->opcode >= IORING_OP_LAST))
6243 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6246 sqe_flags = READ_ONCE(sqe->flags);
6247 /* enforce forwards compatibility on users */
6248 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6251 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6252 !io_op_defs[req->opcode].buffer_select)
6255 id = READ_ONCE(sqe->personality);
6257 io_req_init_async(req);
6258 req->work.creds = idr_find(&ctx->personality_idr, id);
6259 if (unlikely(!req->work.creds))
6261 get_cred(req->work.creds);
6264 /* same numerical values with corresponding REQ_F_*, safe to copy */
6265 req->flags |= sqe_flags;
6267 if (!io_op_defs[req->opcode].needs_file)
6270 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
6273 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
6274 struct file *ring_file, int ring_fd)
6276 struct io_submit_state state;
6277 struct io_kiocb *link = NULL;
6278 int i, submitted = 0;
6280 /* if we have a backlog and couldn't flush it all, return BUSY */
6281 if (test_bit(0, &ctx->sq_check_overflow)) {
6282 if (!list_empty(&ctx->cq_overflow_list) &&
6283 !io_cqring_overflow_flush(ctx, false))
6287 /* make sure SQ entry isn't read before tail */
6288 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6290 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6293 io_submit_state_start(&state, ctx, nr);
6295 ctx->ring_fd = ring_fd;
6296 ctx->ring_file = ring_file;
6298 for (i = 0; i < nr; i++) {
6299 const struct io_uring_sqe *sqe;
6300 struct io_kiocb *req;
6303 sqe = io_get_sqe(ctx);
6304 if (unlikely(!sqe)) {
6305 io_consume_sqe(ctx);
6308 req = io_alloc_req(ctx, &state);
6309 if (unlikely(!req)) {
6311 submitted = -EAGAIN;
6315 err = io_init_req(ctx, req, sqe, &state);
6316 io_consume_sqe(ctx);
6317 /* will complete beyond this point, count as submitted */
6320 if (unlikely(err)) {
6323 io_req_complete(req, err);
6327 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6328 true, io_async_submit(ctx));
6329 err = io_submit_sqe(req, sqe, &link, &state.comp);
6334 if (unlikely(submitted != nr)) {
6335 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6337 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6340 io_queue_link_head(link, &state.comp);
6341 io_submit_state_end(&state);
6343 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6344 io_commit_sqring(ctx);
6349 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6351 /* Tell userspace we may need a wakeup call */
6352 spin_lock_irq(&ctx->completion_lock);
6353 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6354 spin_unlock_irq(&ctx->completion_lock);
6357 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6359 spin_lock_irq(&ctx->completion_lock);
6360 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6361 spin_unlock_irq(&ctx->completion_lock);
6364 static int io_sq_thread(void *data)
6366 struct io_ring_ctx *ctx = data;
6367 const struct cred *old_cred;
6369 unsigned long timeout;
6372 complete(&ctx->sq_thread_comp);
6374 old_cred = override_creds(ctx->creds);
6376 timeout = jiffies + ctx->sq_thread_idle;
6377 while (!kthread_should_park()) {
6378 unsigned int to_submit;
6380 if (!list_empty(&ctx->iopoll_list)) {
6381 unsigned nr_events = 0;
6383 mutex_lock(&ctx->uring_lock);
6384 if (!list_empty(&ctx->iopoll_list) && !need_resched())
6385 io_do_iopoll(ctx, &nr_events, 0);
6387 timeout = jiffies + ctx->sq_thread_idle;
6388 mutex_unlock(&ctx->uring_lock);
6391 to_submit = io_sqring_entries(ctx);
6394 * If submit got -EBUSY, flag us as needing the application
6395 * to enter the kernel to reap and flush events.
6397 if (!to_submit || ret == -EBUSY || need_resched()) {
6399 * Drop cur_mm before scheduling, we can't hold it for
6400 * long periods (or over schedule()). Do this before
6401 * adding ourselves to the waitqueue, as the unuse/drop
6404 io_sq_thread_drop_mm();
6407 * We're polling. If we're within the defined idle
6408 * period, then let us spin without work before going
6409 * to sleep. The exception is if we got EBUSY doing
6410 * more IO, we should wait for the application to
6411 * reap events and wake us up.
6413 if (!list_empty(&ctx->iopoll_list) || need_resched() ||
6414 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6415 !percpu_ref_is_dying(&ctx->refs))) {
6421 prepare_to_wait(&ctx->sqo_wait, &wait,
6422 TASK_INTERRUPTIBLE);
6425 * While doing polled IO, before going to sleep, we need
6426 * to check if there are new reqs added to iopoll_list,
6427 * it is because reqs may have been punted to io worker
6428 * and will be added to iopoll_list later, hence check
6429 * the iopoll_list again.
6431 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6432 !list_empty_careful(&ctx->iopoll_list)) {
6433 finish_wait(&ctx->sqo_wait, &wait);
6437 io_ring_set_wakeup_flag(ctx);
6439 to_submit = io_sqring_entries(ctx);
6440 if (!to_submit || ret == -EBUSY) {
6441 if (kthread_should_park()) {
6442 finish_wait(&ctx->sqo_wait, &wait);
6445 if (io_run_task_work()) {
6446 finish_wait(&ctx->sqo_wait, &wait);
6447 io_ring_clear_wakeup_flag(ctx);
6450 if (signal_pending(current))
6451 flush_signals(current);
6453 finish_wait(&ctx->sqo_wait, &wait);
6455 io_ring_clear_wakeup_flag(ctx);
6459 finish_wait(&ctx->sqo_wait, &wait);
6461 io_ring_clear_wakeup_flag(ctx);
6464 mutex_lock(&ctx->uring_lock);
6465 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6466 ret = io_submit_sqes(ctx, to_submit, NULL, -1);
6467 mutex_unlock(&ctx->uring_lock);
6468 timeout = jiffies + ctx->sq_thread_idle;
6473 io_sq_thread_drop_mm();
6474 revert_creds(old_cred);
6481 struct io_wait_queue {
6482 struct wait_queue_entry wq;
6483 struct io_ring_ctx *ctx;
6485 unsigned nr_timeouts;
6488 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6490 struct io_ring_ctx *ctx = iowq->ctx;
6493 * Wake up if we have enough events, or if a timeout occurred since we
6494 * started waiting. For timeouts, we always want to return to userspace,
6495 * regardless of event count.
6497 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6498 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6501 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6502 int wake_flags, void *key)
6504 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6507 /* use noflush == true, as we can't safely rely on locking context */
6508 if (!io_should_wake(iowq, true))
6511 return autoremove_wake_function(curr, mode, wake_flags, key);
6515 * Wait until events become available, if we don't already have some. The
6516 * application must reap them itself, as they reside on the shared cq ring.
6518 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6519 const sigset_t __user *sig, size_t sigsz)
6521 struct io_wait_queue iowq = {
6524 .func = io_wake_function,
6525 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6528 .to_wait = min_events,
6530 struct io_rings *rings = ctx->rings;
6534 if (io_cqring_events(ctx, false) >= min_events)
6536 if (!io_run_task_work())
6541 #ifdef CONFIG_COMPAT
6542 if (in_compat_syscall())
6543 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6547 ret = set_user_sigmask(sig, sigsz);
6553 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6554 trace_io_uring_cqring_wait(ctx, min_events);
6556 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6557 TASK_INTERRUPTIBLE);
6558 /* make sure we run task_work before checking for signals */
6559 if (io_run_task_work())
6561 if (signal_pending(current)) {
6562 if (current->jobctl & JOBCTL_TASK_WORK) {
6563 spin_lock_irq(¤t->sighand->siglock);
6564 current->jobctl &= ~JOBCTL_TASK_WORK;
6565 recalc_sigpending();
6566 spin_unlock_irq(¤t->sighand->siglock);
6572 if (io_should_wake(&iowq, false))
6576 finish_wait(&ctx->wait, &iowq.wq);
6578 restore_saved_sigmask_unless(ret == -EINTR);
6580 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6583 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6585 #if defined(CONFIG_UNIX)
6586 if (ctx->ring_sock) {
6587 struct sock *sock = ctx->ring_sock->sk;
6588 struct sk_buff *skb;
6590 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6596 for (i = 0; i < ctx->nr_user_files; i++) {
6599 file = io_file_from_index(ctx, i);
6606 static void io_file_ref_kill(struct percpu_ref *ref)
6608 struct fixed_file_data *data;
6610 data = container_of(ref, struct fixed_file_data, refs);
6611 complete(&data->done);
6614 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6616 struct fixed_file_data *data = ctx->file_data;
6617 struct fixed_file_ref_node *ref_node = NULL;
6618 unsigned nr_tables, i;
6623 spin_lock(&data->lock);
6624 if (!list_empty(&data->ref_list))
6625 ref_node = list_first_entry(&data->ref_list,
6626 struct fixed_file_ref_node, node);
6627 spin_unlock(&data->lock);
6629 percpu_ref_kill(&ref_node->refs);
6631 percpu_ref_kill(&data->refs);
6633 /* wait for all refs nodes to complete */
6634 flush_delayed_work(&ctx->file_put_work);
6635 wait_for_completion(&data->done);
6637 __io_sqe_files_unregister(ctx);
6638 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6639 for (i = 0; i < nr_tables; i++)
6640 kfree(data->table[i].files);
6642 percpu_ref_exit(&data->refs);
6644 ctx->file_data = NULL;
6645 ctx->nr_user_files = 0;
6649 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6651 if (ctx->sqo_thread) {
6652 wait_for_completion(&ctx->sq_thread_comp);
6654 * The park is a bit of a work-around, without it we get
6655 * warning spews on shutdown with SQPOLL set and affinity
6656 * set to a single CPU.
6658 kthread_park(ctx->sqo_thread);
6659 kthread_stop(ctx->sqo_thread);
6660 ctx->sqo_thread = NULL;
6664 static void io_finish_async(struct io_ring_ctx *ctx)
6666 io_sq_thread_stop(ctx);
6669 io_wq_destroy(ctx->io_wq);
6674 #if defined(CONFIG_UNIX)
6676 * Ensure the UNIX gc is aware of our file set, so we are certain that
6677 * the io_uring can be safely unregistered on process exit, even if we have
6678 * loops in the file referencing.
6680 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6682 struct sock *sk = ctx->ring_sock->sk;
6683 struct scm_fp_list *fpl;
6684 struct sk_buff *skb;
6687 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6691 skb = alloc_skb(0, GFP_KERNEL);
6700 fpl->user = get_uid(ctx->user);
6701 for (i = 0; i < nr; i++) {
6702 struct file *file = io_file_from_index(ctx, i + offset);
6706 fpl->fp[nr_files] = get_file(file);
6707 unix_inflight(fpl->user, fpl->fp[nr_files]);
6712 fpl->max = SCM_MAX_FD;
6713 fpl->count = nr_files;
6714 UNIXCB(skb).fp = fpl;
6715 skb->destructor = unix_destruct_scm;
6716 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6717 skb_queue_head(&sk->sk_receive_queue, skb);
6719 for (i = 0; i < nr_files; i++)
6730 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6731 * causes regular reference counting to break down. We rely on the UNIX
6732 * garbage collection to take care of this problem for us.
6734 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6736 unsigned left, total;
6740 left = ctx->nr_user_files;
6742 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6744 ret = __io_sqe_files_scm(ctx, this_files, total);
6748 total += this_files;
6754 while (total < ctx->nr_user_files) {
6755 struct file *file = io_file_from_index(ctx, total);
6765 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6771 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6776 for (i = 0; i < nr_tables; i++) {
6777 struct fixed_file_table *table = &ctx->file_data->table[i];
6778 unsigned this_files;
6780 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6781 table->files = kcalloc(this_files, sizeof(struct file *),
6785 nr_files -= this_files;
6791 for (i = 0; i < nr_tables; i++) {
6792 struct fixed_file_table *table = &ctx->file_data->table[i];
6793 kfree(table->files);
6798 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6800 #if defined(CONFIG_UNIX)
6801 struct sock *sock = ctx->ring_sock->sk;
6802 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6803 struct sk_buff *skb;
6806 __skb_queue_head_init(&list);
6809 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6810 * remove this entry and rearrange the file array.
6812 skb = skb_dequeue(head);
6814 struct scm_fp_list *fp;
6816 fp = UNIXCB(skb).fp;
6817 for (i = 0; i < fp->count; i++) {
6820 if (fp->fp[i] != file)
6823 unix_notinflight(fp->user, fp->fp[i]);
6824 left = fp->count - 1 - i;
6826 memmove(&fp->fp[i], &fp->fp[i + 1],
6827 left * sizeof(struct file *));
6834 __skb_queue_tail(&list, skb);
6844 __skb_queue_tail(&list, skb);
6846 skb = skb_dequeue(head);
6849 if (skb_peek(&list)) {
6850 spin_lock_irq(&head->lock);
6851 while ((skb = __skb_dequeue(&list)) != NULL)
6852 __skb_queue_tail(head, skb);
6853 spin_unlock_irq(&head->lock);
6860 struct io_file_put {
6861 struct list_head list;
6865 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
6867 struct fixed_file_data *file_data = ref_node->file_data;
6868 struct io_ring_ctx *ctx = file_data->ctx;
6869 struct io_file_put *pfile, *tmp;
6871 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6872 list_del(&pfile->list);
6873 io_ring_file_put(ctx, pfile->file);
6877 spin_lock(&file_data->lock);
6878 list_del(&ref_node->node);
6879 spin_unlock(&file_data->lock);
6881 percpu_ref_exit(&ref_node->refs);
6883 percpu_ref_put(&file_data->refs);
6886 static void io_file_put_work(struct work_struct *work)
6888 struct io_ring_ctx *ctx;
6889 struct llist_node *node;
6891 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
6892 node = llist_del_all(&ctx->file_put_llist);
6895 struct fixed_file_ref_node *ref_node;
6896 struct llist_node *next = node->next;
6898 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
6899 __io_file_put_work(ref_node);
6904 static void io_file_data_ref_zero(struct percpu_ref *ref)
6906 struct fixed_file_ref_node *ref_node;
6907 struct io_ring_ctx *ctx;
6911 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6912 ctx = ref_node->file_data->ctx;
6914 if (percpu_ref_is_dying(&ctx->file_data->refs))
6917 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
6919 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
6921 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
6924 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6925 struct io_ring_ctx *ctx)
6927 struct fixed_file_ref_node *ref_node;
6929 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6931 return ERR_PTR(-ENOMEM);
6933 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6936 return ERR_PTR(-ENOMEM);
6938 INIT_LIST_HEAD(&ref_node->node);
6939 INIT_LIST_HEAD(&ref_node->file_list);
6940 ref_node->file_data = ctx->file_data;
6944 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6946 percpu_ref_exit(&ref_node->refs);
6950 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6953 __s32 __user *fds = (__s32 __user *) arg;
6958 struct fixed_file_ref_node *ref_node;
6964 if (nr_args > IORING_MAX_FIXED_FILES)
6967 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6968 if (!ctx->file_data)
6970 ctx->file_data->ctx = ctx;
6971 init_completion(&ctx->file_data->done);
6972 INIT_LIST_HEAD(&ctx->file_data->ref_list);
6973 spin_lock_init(&ctx->file_data->lock);
6975 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6976 ctx->file_data->table = kcalloc(nr_tables,
6977 sizeof(struct fixed_file_table),
6979 if (!ctx->file_data->table) {
6980 kfree(ctx->file_data);
6981 ctx->file_data = NULL;
6985 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6986 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6987 kfree(ctx->file_data->table);
6988 kfree(ctx->file_data);
6989 ctx->file_data = NULL;
6993 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6994 percpu_ref_exit(&ctx->file_data->refs);
6995 kfree(ctx->file_data->table);
6996 kfree(ctx->file_data);
6997 ctx->file_data = NULL;
7001 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7002 struct fixed_file_table *table;
7006 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
7008 /* allow sparse sets */
7014 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7015 index = i & IORING_FILE_TABLE_MASK;
7023 * Don't allow io_uring instances to be registered. If UNIX
7024 * isn't enabled, then this causes a reference cycle and this
7025 * instance can never get freed. If UNIX is enabled we'll
7026 * handle it just fine, but there's still no point in allowing
7027 * a ring fd as it doesn't support regular read/write anyway.
7029 if (file->f_op == &io_uring_fops) {
7034 table->files[index] = file;
7038 for (i = 0; i < ctx->nr_user_files; i++) {
7039 file = io_file_from_index(ctx, i);
7043 for (i = 0; i < nr_tables; i++)
7044 kfree(ctx->file_data->table[i].files);
7046 percpu_ref_exit(&ctx->file_data->refs);
7047 kfree(ctx->file_data->table);
7048 kfree(ctx->file_data);
7049 ctx->file_data = NULL;
7050 ctx->nr_user_files = 0;
7054 ret = io_sqe_files_scm(ctx);
7056 io_sqe_files_unregister(ctx);
7060 ref_node = alloc_fixed_file_ref_node(ctx);
7061 if (IS_ERR(ref_node)) {
7062 io_sqe_files_unregister(ctx);
7063 return PTR_ERR(ref_node);
7066 ctx->file_data->cur_refs = &ref_node->refs;
7067 spin_lock(&ctx->file_data->lock);
7068 list_add(&ref_node->node, &ctx->file_data->ref_list);
7069 spin_unlock(&ctx->file_data->lock);
7070 percpu_ref_get(&ctx->file_data->refs);
7074 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7077 #if defined(CONFIG_UNIX)
7078 struct sock *sock = ctx->ring_sock->sk;
7079 struct sk_buff_head *head = &sock->sk_receive_queue;
7080 struct sk_buff *skb;
7083 * See if we can merge this file into an existing skb SCM_RIGHTS
7084 * file set. If there's no room, fall back to allocating a new skb
7085 * and filling it in.
7087 spin_lock_irq(&head->lock);
7088 skb = skb_peek(head);
7090 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7092 if (fpl->count < SCM_MAX_FD) {
7093 __skb_unlink(skb, head);
7094 spin_unlock_irq(&head->lock);
7095 fpl->fp[fpl->count] = get_file(file);
7096 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7098 spin_lock_irq(&head->lock);
7099 __skb_queue_head(head, skb);
7104 spin_unlock_irq(&head->lock);
7111 return __io_sqe_files_scm(ctx, 1, index);
7117 static int io_queue_file_removal(struct fixed_file_data *data,
7120 struct io_file_put *pfile;
7121 struct percpu_ref *refs = data->cur_refs;
7122 struct fixed_file_ref_node *ref_node;
7124 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7128 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
7130 list_add(&pfile->list, &ref_node->file_list);
7135 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7136 struct io_uring_files_update *up,
7139 struct fixed_file_data *data = ctx->file_data;
7140 struct fixed_file_ref_node *ref_node;
7145 bool needs_switch = false;
7147 if (check_add_overflow(up->offset, nr_args, &done))
7149 if (done > ctx->nr_user_files)
7152 ref_node = alloc_fixed_file_ref_node(ctx);
7153 if (IS_ERR(ref_node))
7154 return PTR_ERR(ref_node);
7157 fds = u64_to_user_ptr(up->fds);
7159 struct fixed_file_table *table;
7163 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7167 i = array_index_nospec(up->offset, ctx->nr_user_files);
7168 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7169 index = i & IORING_FILE_TABLE_MASK;
7170 if (table->files[index]) {
7171 file = io_file_from_index(ctx, index);
7172 err = io_queue_file_removal(data, file);
7175 table->files[index] = NULL;
7176 needs_switch = true;
7185 * Don't allow io_uring instances to be registered. If
7186 * UNIX isn't enabled, then this causes a reference
7187 * cycle and this instance can never get freed. If UNIX
7188 * is enabled we'll handle it just fine, but there's
7189 * still no point in allowing a ring fd as it doesn't
7190 * support regular read/write anyway.
7192 if (file->f_op == &io_uring_fops) {
7197 table->files[index] = file;
7198 err = io_sqe_file_register(ctx, file, i);
7210 percpu_ref_kill(data->cur_refs);
7211 spin_lock(&data->lock);
7212 list_add(&ref_node->node, &data->ref_list);
7213 data->cur_refs = &ref_node->refs;
7214 spin_unlock(&data->lock);
7215 percpu_ref_get(&ctx->file_data->refs);
7217 destroy_fixed_file_ref_node(ref_node);
7219 return done ? done : err;
7222 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7225 struct io_uring_files_update up;
7227 if (!ctx->file_data)
7231 if (copy_from_user(&up, arg, sizeof(up)))
7236 return __io_sqe_files_update(ctx, &up, nr_args);
7239 static void io_free_work(struct io_wq_work *work)
7241 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7243 /* Consider that io_steal_work() relies on this ref */
7247 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7248 struct io_uring_params *p)
7250 struct io_wq_data data;
7252 struct io_ring_ctx *ctx_attach;
7253 unsigned int concurrency;
7256 data.user = ctx->user;
7257 data.free_work = io_free_work;
7258 data.do_work = io_wq_submit_work;
7260 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7261 /* Do QD, or 4 * CPUS, whatever is smallest */
7262 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7264 ctx->io_wq = io_wq_create(concurrency, &data);
7265 if (IS_ERR(ctx->io_wq)) {
7266 ret = PTR_ERR(ctx->io_wq);
7272 f = fdget(p->wq_fd);
7276 if (f.file->f_op != &io_uring_fops) {
7281 ctx_attach = f.file->private_data;
7282 /* @io_wq is protected by holding the fd */
7283 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7288 ctx->io_wq = ctx_attach->io_wq;
7294 static int io_sq_offload_start(struct io_ring_ctx *ctx,
7295 struct io_uring_params *p)
7299 mmgrab(current->mm);
7300 ctx->sqo_mm = current->mm;
7302 if (ctx->flags & IORING_SETUP_SQPOLL) {
7304 if (!capable(CAP_SYS_ADMIN))
7307 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7308 if (!ctx->sq_thread_idle)
7309 ctx->sq_thread_idle = HZ;
7311 if (p->flags & IORING_SETUP_SQ_AFF) {
7312 int cpu = p->sq_thread_cpu;
7315 if (cpu >= nr_cpu_ids)
7317 if (!cpu_online(cpu))
7320 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
7324 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
7327 if (IS_ERR(ctx->sqo_thread)) {
7328 ret = PTR_ERR(ctx->sqo_thread);
7329 ctx->sqo_thread = NULL;
7332 wake_up_process(ctx->sqo_thread);
7333 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7334 /* Can't have SQ_AFF without SQPOLL */
7339 ret = io_init_wq_offload(ctx, p);
7345 io_finish_async(ctx);
7347 mmdrop(ctx->sqo_mm);
7353 static inline void __io_unaccount_mem(struct user_struct *user,
7354 unsigned long nr_pages)
7356 atomic_long_sub(nr_pages, &user->locked_vm);
7359 static inline int __io_account_mem(struct user_struct *user,
7360 unsigned long nr_pages)
7362 unsigned long page_limit, cur_pages, new_pages;
7364 /* Don't allow more pages than we can safely lock */
7365 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7368 cur_pages = atomic_long_read(&user->locked_vm);
7369 new_pages = cur_pages + nr_pages;
7370 if (new_pages > page_limit)
7372 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7373 new_pages) != cur_pages);
7378 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7379 enum io_mem_account acct)
7382 __io_unaccount_mem(ctx->user, nr_pages);
7385 if (acct == ACCT_LOCKED)
7386 ctx->sqo_mm->locked_vm -= nr_pages;
7387 else if (acct == ACCT_PINNED)
7388 atomic64_sub(nr_pages, &ctx->sqo_mm->pinned_vm);
7392 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7393 enum io_mem_account acct)
7397 if (ctx->limit_mem) {
7398 ret = __io_account_mem(ctx->user, nr_pages);
7404 if (acct == ACCT_LOCKED)
7405 ctx->sqo_mm->locked_vm += nr_pages;
7406 else if (acct == ACCT_PINNED)
7407 atomic64_add(nr_pages, &ctx->sqo_mm->pinned_vm);
7413 static void io_mem_free(void *ptr)
7420 page = virt_to_head_page(ptr);
7421 if (put_page_testzero(page))
7422 free_compound_page(page);
7425 static void *io_mem_alloc(size_t size)
7427 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7430 return (void *) __get_free_pages(gfp_flags, get_order(size));
7433 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7436 struct io_rings *rings;
7437 size_t off, sq_array_size;
7439 off = struct_size(rings, cqes, cq_entries);
7440 if (off == SIZE_MAX)
7444 off = ALIGN(off, SMP_CACHE_BYTES);
7452 sq_array_size = array_size(sizeof(u32), sq_entries);
7453 if (sq_array_size == SIZE_MAX)
7456 if (check_add_overflow(off, sq_array_size, &off))
7462 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7466 pages = (size_t)1 << get_order(
7467 rings_size(sq_entries, cq_entries, NULL));
7468 pages += (size_t)1 << get_order(
7469 array_size(sizeof(struct io_uring_sqe), sq_entries));
7474 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7478 if (!ctx->user_bufs)
7481 for (i = 0; i < ctx->nr_user_bufs; i++) {
7482 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7484 for (j = 0; j < imu->nr_bvecs; j++)
7485 unpin_user_page(imu->bvec[j].bv_page);
7487 io_unaccount_mem(ctx, imu->nr_bvecs, ACCT_PINNED);
7492 kfree(ctx->user_bufs);
7493 ctx->user_bufs = NULL;
7494 ctx->nr_user_bufs = 0;
7498 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7499 void __user *arg, unsigned index)
7501 struct iovec __user *src;
7503 #ifdef CONFIG_COMPAT
7505 struct compat_iovec __user *ciovs;
7506 struct compat_iovec ciov;
7508 ciovs = (struct compat_iovec __user *) arg;
7509 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7512 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7513 dst->iov_len = ciov.iov_len;
7517 src = (struct iovec __user *) arg;
7518 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7523 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7526 struct vm_area_struct **vmas = NULL;
7527 struct page **pages = NULL;
7528 int i, j, got_pages = 0;
7533 if (!nr_args || nr_args > UIO_MAXIOV)
7536 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7538 if (!ctx->user_bufs)
7541 for (i = 0; i < nr_args; i++) {
7542 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7543 unsigned long off, start, end, ubuf;
7548 ret = io_copy_iov(ctx, &iov, arg, i);
7553 * Don't impose further limits on the size and buffer
7554 * constraints here, we'll -EINVAL later when IO is
7555 * submitted if they are wrong.
7558 if (!iov.iov_base || !iov.iov_len)
7561 /* arbitrary limit, but we need something */
7562 if (iov.iov_len > SZ_1G)
7565 ubuf = (unsigned long) iov.iov_base;
7566 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7567 start = ubuf >> PAGE_SHIFT;
7568 nr_pages = end - start;
7570 ret = io_account_mem(ctx, nr_pages, ACCT_PINNED);
7575 if (!pages || nr_pages > got_pages) {
7578 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7580 vmas = kvmalloc_array(nr_pages,
7581 sizeof(struct vm_area_struct *),
7583 if (!pages || !vmas) {
7585 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7588 got_pages = nr_pages;
7591 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7595 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7600 mmap_read_lock(current->mm);
7601 pret = pin_user_pages(ubuf, nr_pages,
7602 FOLL_WRITE | FOLL_LONGTERM,
7604 if (pret == nr_pages) {
7605 /* don't support file backed memory */
7606 for (j = 0; j < nr_pages; j++) {
7607 struct vm_area_struct *vma = vmas[j];
7610 !is_file_hugepages(vma->vm_file)) {
7616 ret = pret < 0 ? pret : -EFAULT;
7618 mmap_read_unlock(current->mm);
7621 * if we did partial map, or found file backed vmas,
7622 * release any pages we did get
7625 unpin_user_pages(pages, pret);
7626 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7631 off = ubuf & ~PAGE_MASK;
7633 for (j = 0; j < nr_pages; j++) {
7636 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7637 imu->bvec[j].bv_page = pages[j];
7638 imu->bvec[j].bv_len = vec_len;
7639 imu->bvec[j].bv_offset = off;
7643 /* store original address for later verification */
7645 imu->len = iov.iov_len;
7646 imu->nr_bvecs = nr_pages;
7648 ctx->nr_user_bufs++;
7656 io_sqe_buffer_unregister(ctx);
7660 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7662 __s32 __user *fds = arg;
7668 if (copy_from_user(&fd, fds, sizeof(*fds)))
7671 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7672 if (IS_ERR(ctx->cq_ev_fd)) {
7673 int ret = PTR_ERR(ctx->cq_ev_fd);
7674 ctx->cq_ev_fd = NULL;
7681 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7683 if (ctx->cq_ev_fd) {
7684 eventfd_ctx_put(ctx->cq_ev_fd);
7685 ctx->cq_ev_fd = NULL;
7692 static int __io_destroy_buffers(int id, void *p, void *data)
7694 struct io_ring_ctx *ctx = data;
7695 struct io_buffer *buf = p;
7697 __io_remove_buffers(ctx, buf, id, -1U);
7701 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7703 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7704 idr_destroy(&ctx->io_buffer_idr);
7707 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7709 io_finish_async(ctx);
7710 io_sqe_buffer_unregister(ctx);
7712 mmdrop(ctx->sqo_mm);
7716 io_sqe_files_unregister(ctx);
7717 io_eventfd_unregister(ctx);
7718 io_destroy_buffers(ctx);
7719 idr_destroy(&ctx->personality_idr);
7721 #if defined(CONFIG_UNIX)
7722 if (ctx->ring_sock) {
7723 ctx->ring_sock->file = NULL; /* so that iput() is called */
7724 sock_release(ctx->ring_sock);
7728 io_mem_free(ctx->rings);
7729 io_mem_free(ctx->sq_sqes);
7731 percpu_ref_exit(&ctx->refs);
7732 free_uid(ctx->user);
7733 put_cred(ctx->creds);
7734 kfree(ctx->cancel_hash);
7735 kmem_cache_free(req_cachep, ctx->fallback_req);
7739 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7741 struct io_ring_ctx *ctx = file->private_data;
7744 poll_wait(file, &ctx->cq_wait, wait);
7746 * synchronizes with barrier from wq_has_sleeper call in
7750 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7751 ctx->rings->sq_ring_entries)
7752 mask |= EPOLLOUT | EPOLLWRNORM;
7753 if (io_cqring_events(ctx, false))
7754 mask |= EPOLLIN | EPOLLRDNORM;
7759 static int io_uring_fasync(int fd, struct file *file, int on)
7761 struct io_ring_ctx *ctx = file->private_data;
7763 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7766 static int io_remove_personalities(int id, void *p, void *data)
7768 struct io_ring_ctx *ctx = data;
7769 const struct cred *cred;
7771 cred = idr_remove(&ctx->personality_idr, id);
7777 static void io_ring_exit_work(struct work_struct *work)
7779 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
7783 * If we're doing polled IO and end up having requests being
7784 * submitted async (out-of-line), then completions can come in while
7785 * we're waiting for refs to drop. We need to reap these manually,
7786 * as nobody else will be looking for them.
7790 io_cqring_overflow_flush(ctx, true);
7791 io_iopoll_try_reap_events(ctx);
7792 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
7793 io_ring_ctx_free(ctx);
7796 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7798 mutex_lock(&ctx->uring_lock);
7799 percpu_ref_kill(&ctx->refs);
7800 mutex_unlock(&ctx->uring_lock);
7802 io_kill_timeouts(ctx);
7803 io_poll_remove_all(ctx);
7806 io_wq_cancel_all(ctx->io_wq);
7808 /* if we failed setting up the ctx, we might not have any rings */
7810 io_cqring_overflow_flush(ctx, true);
7811 io_iopoll_try_reap_events(ctx);
7812 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7815 * Do this upfront, so we won't have a grace period where the ring
7816 * is closed but resources aren't reaped yet. This can cause
7817 * spurious failure in setting up a new ring.
7819 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
7822 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7823 queue_work(system_wq, &ctx->exit_work);
7826 static int io_uring_release(struct inode *inode, struct file *file)
7828 struct io_ring_ctx *ctx = file->private_data;
7830 file->private_data = NULL;
7831 io_ring_ctx_wait_and_kill(ctx);
7835 static bool io_wq_files_match(struct io_wq_work *work, void *data)
7837 struct files_struct *files = data;
7839 return work->files == files;
7842 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7843 struct files_struct *files)
7845 if (list_empty_careful(&ctx->inflight_list))
7848 /* cancel all at once, should be faster than doing it one by one*/
7849 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
7851 while (!list_empty_careful(&ctx->inflight_list)) {
7852 struct io_kiocb *cancel_req = NULL, *req;
7855 spin_lock_irq(&ctx->inflight_lock);
7856 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7857 if (req->work.files != files)
7859 /* req is being completed, ignore */
7860 if (!refcount_inc_not_zero(&req->refs))
7866 prepare_to_wait(&ctx->inflight_wait, &wait,
7867 TASK_UNINTERRUPTIBLE);
7868 spin_unlock_irq(&ctx->inflight_lock);
7870 /* We need to keep going until we don't find a matching req */
7874 if (cancel_req->flags & REQ_F_OVERFLOW) {
7875 spin_lock_irq(&ctx->completion_lock);
7876 list_del(&cancel_req->compl.list);
7877 cancel_req->flags &= ~REQ_F_OVERFLOW;
7878 if (list_empty(&ctx->cq_overflow_list)) {
7879 clear_bit(0, &ctx->sq_check_overflow);
7880 clear_bit(0, &ctx->cq_check_overflow);
7881 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
7883 spin_unlock_irq(&ctx->completion_lock);
7885 WRITE_ONCE(ctx->rings->cq_overflow,
7886 atomic_inc_return(&ctx->cached_cq_overflow));
7889 * Put inflight ref and overflow ref. If that's
7890 * all we had, then we're done with this request.
7892 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7893 io_free_req(cancel_req);
7894 finish_wait(&ctx->inflight_wait, &wait);
7898 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7899 io_put_req(cancel_req);
7903 finish_wait(&ctx->inflight_wait, &wait);
7907 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
7909 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7910 struct task_struct *task = data;
7912 return req->task == task;
7915 static int io_uring_flush(struct file *file, void *data)
7917 struct io_ring_ctx *ctx = file->private_data;
7919 io_uring_cancel_files(ctx, data);
7922 * If the task is going away, cancel work it may have pending
7924 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7925 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, current, true);
7930 static void *io_uring_validate_mmap_request(struct file *file,
7931 loff_t pgoff, size_t sz)
7933 struct io_ring_ctx *ctx = file->private_data;
7934 loff_t offset = pgoff << PAGE_SHIFT;
7939 case IORING_OFF_SQ_RING:
7940 case IORING_OFF_CQ_RING:
7943 case IORING_OFF_SQES:
7947 return ERR_PTR(-EINVAL);
7950 page = virt_to_head_page(ptr);
7951 if (sz > page_size(page))
7952 return ERR_PTR(-EINVAL);
7959 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7961 size_t sz = vma->vm_end - vma->vm_start;
7965 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7967 return PTR_ERR(ptr);
7969 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7970 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7973 #else /* !CONFIG_MMU */
7975 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7977 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7980 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7982 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7985 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7986 unsigned long addr, unsigned long len,
7987 unsigned long pgoff, unsigned long flags)
7991 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7993 return PTR_ERR(ptr);
7995 return (unsigned long) ptr;
7998 #endif /* !CONFIG_MMU */
8000 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
8001 u32, min_complete, u32, flags, const sigset_t __user *, sig,
8004 struct io_ring_ctx *ctx;
8011 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
8019 if (f.file->f_op != &io_uring_fops)
8023 ctx = f.file->private_data;
8024 if (!percpu_ref_tryget(&ctx->refs))
8028 * For SQ polling, the thread will do all submissions and completions.
8029 * Just return the requested submit count, and wake the thread if
8033 if (ctx->flags & IORING_SETUP_SQPOLL) {
8034 if (!list_empty_careful(&ctx->cq_overflow_list))
8035 io_cqring_overflow_flush(ctx, false);
8036 if (flags & IORING_ENTER_SQ_WAKEUP)
8037 wake_up(&ctx->sqo_wait);
8038 submitted = to_submit;
8039 } else if (to_submit) {
8040 mutex_lock(&ctx->uring_lock);
8041 submitted = io_submit_sqes(ctx, to_submit, f.file, fd);
8042 mutex_unlock(&ctx->uring_lock);
8044 if (submitted != to_submit)
8047 if (flags & IORING_ENTER_GETEVENTS) {
8048 min_complete = min(min_complete, ctx->cq_entries);
8051 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
8052 * space applications don't need to do io completion events
8053 * polling again, they can rely on io_sq_thread to do polling
8054 * work, which can reduce cpu usage and uring_lock contention.
8056 if (ctx->flags & IORING_SETUP_IOPOLL &&
8057 !(ctx->flags & IORING_SETUP_SQPOLL)) {
8058 ret = io_iopoll_check(ctx, min_complete);
8060 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
8065 percpu_ref_put(&ctx->refs);
8068 return submitted ? submitted : ret;
8071 #ifdef CONFIG_PROC_FS
8072 static int io_uring_show_cred(int id, void *p, void *data)
8074 const struct cred *cred = p;
8075 struct seq_file *m = data;
8076 struct user_namespace *uns = seq_user_ns(m);
8077 struct group_info *gi;
8082 seq_printf(m, "%5d\n", id);
8083 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
8084 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
8085 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
8086 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
8087 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
8088 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
8089 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
8090 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
8091 seq_puts(m, "\n\tGroups:\t");
8092 gi = cred->group_info;
8093 for (g = 0; g < gi->ngroups; g++) {
8094 seq_put_decimal_ull(m, g ? " " : "",
8095 from_kgid_munged(uns, gi->gid[g]));
8097 seq_puts(m, "\n\tCapEff:\t");
8098 cap = cred->cap_effective;
8099 CAP_FOR_EACH_U32(__capi)
8100 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8105 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8109 mutex_lock(&ctx->uring_lock);
8110 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8111 for (i = 0; i < ctx->nr_user_files; i++) {
8112 struct fixed_file_table *table;
8115 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8116 f = table->files[i & IORING_FILE_TABLE_MASK];
8118 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8120 seq_printf(m, "%5u: <none>\n", i);
8122 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8123 for (i = 0; i < ctx->nr_user_bufs; i++) {
8124 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8126 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8127 (unsigned int) buf->len);
8129 if (!idr_is_empty(&ctx->personality_idr)) {
8130 seq_printf(m, "Personalities:\n");
8131 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8133 seq_printf(m, "PollList:\n");
8134 spin_lock_irq(&ctx->completion_lock);
8135 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8136 struct hlist_head *list = &ctx->cancel_hash[i];
8137 struct io_kiocb *req;
8139 hlist_for_each_entry(req, list, hash_node)
8140 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
8141 req->task->task_works != NULL);
8143 spin_unlock_irq(&ctx->completion_lock);
8144 mutex_unlock(&ctx->uring_lock);
8147 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8149 struct io_ring_ctx *ctx = f->private_data;
8151 if (percpu_ref_tryget(&ctx->refs)) {
8152 __io_uring_show_fdinfo(ctx, m);
8153 percpu_ref_put(&ctx->refs);
8158 static const struct file_operations io_uring_fops = {
8159 .release = io_uring_release,
8160 .flush = io_uring_flush,
8161 .mmap = io_uring_mmap,
8163 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8164 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8166 .poll = io_uring_poll,
8167 .fasync = io_uring_fasync,
8168 #ifdef CONFIG_PROC_FS
8169 .show_fdinfo = io_uring_show_fdinfo,
8173 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8174 struct io_uring_params *p)
8176 struct io_rings *rings;
8177 size_t size, sq_array_offset;
8179 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8180 if (size == SIZE_MAX)
8183 rings = io_mem_alloc(size);
8188 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8189 rings->sq_ring_mask = p->sq_entries - 1;
8190 rings->cq_ring_mask = p->cq_entries - 1;
8191 rings->sq_ring_entries = p->sq_entries;
8192 rings->cq_ring_entries = p->cq_entries;
8193 ctx->sq_mask = rings->sq_ring_mask;
8194 ctx->cq_mask = rings->cq_ring_mask;
8195 ctx->sq_entries = rings->sq_ring_entries;
8196 ctx->cq_entries = rings->cq_ring_entries;
8198 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8199 if (size == SIZE_MAX) {
8200 io_mem_free(ctx->rings);
8205 ctx->sq_sqes = io_mem_alloc(size);
8206 if (!ctx->sq_sqes) {
8207 io_mem_free(ctx->rings);
8216 * Allocate an anonymous fd, this is what constitutes the application
8217 * visible backing of an io_uring instance. The application mmaps this
8218 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8219 * we have to tie this fd to a socket for file garbage collection purposes.
8221 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8226 #if defined(CONFIG_UNIX)
8227 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8233 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8237 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8238 O_RDWR | O_CLOEXEC);
8241 ret = PTR_ERR(file);
8245 #if defined(CONFIG_UNIX)
8246 ctx->ring_sock->file = file;
8248 fd_install(ret, file);
8251 #if defined(CONFIG_UNIX)
8252 sock_release(ctx->ring_sock);
8253 ctx->ring_sock = NULL;
8258 static int io_uring_create(unsigned entries, struct io_uring_params *p,
8259 struct io_uring_params __user *params)
8261 struct user_struct *user = NULL;
8262 struct io_ring_ctx *ctx;
8268 if (entries > IORING_MAX_ENTRIES) {
8269 if (!(p->flags & IORING_SETUP_CLAMP))
8271 entries = IORING_MAX_ENTRIES;
8275 * Use twice as many entries for the CQ ring. It's possible for the
8276 * application to drive a higher depth than the size of the SQ ring,
8277 * since the sqes are only used at submission time. This allows for
8278 * some flexibility in overcommitting a bit. If the application has
8279 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
8280 * of CQ ring entries manually.
8282 p->sq_entries = roundup_pow_of_two(entries);
8283 if (p->flags & IORING_SETUP_CQSIZE) {
8285 * If IORING_SETUP_CQSIZE is set, we do the same roundup
8286 * to a power-of-two, if it isn't already. We do NOT impose
8287 * any cq vs sq ring sizing.
8289 if (p->cq_entries < p->sq_entries)
8291 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
8292 if (!(p->flags & IORING_SETUP_CLAMP))
8294 p->cq_entries = IORING_MAX_CQ_ENTRIES;
8296 p->cq_entries = roundup_pow_of_two(p->cq_entries);
8298 p->cq_entries = 2 * p->sq_entries;
8301 user = get_uid(current_user());
8302 limit_mem = !capable(CAP_IPC_LOCK);
8305 ret = __io_account_mem(user,
8306 ring_pages(p->sq_entries, p->cq_entries));
8313 ctx = io_ring_ctx_alloc(p);
8316 __io_unaccount_mem(user, ring_pages(p->sq_entries,
8321 ctx->compat = in_compat_syscall();
8323 ctx->creds = get_current_cred();
8325 ret = io_allocate_scq_urings(ctx, p);
8329 ret = io_sq_offload_start(ctx, p);
8333 memset(&p->sq_off, 0, sizeof(p->sq_off));
8334 p->sq_off.head = offsetof(struct io_rings, sq.head);
8335 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
8336 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
8337 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
8338 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
8339 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
8340 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
8342 memset(&p->cq_off, 0, sizeof(p->cq_off));
8343 p->cq_off.head = offsetof(struct io_rings, cq.head);
8344 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
8345 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
8346 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
8347 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
8348 p->cq_off.cqes = offsetof(struct io_rings, cqes);
8349 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
8351 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
8352 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
8353 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
8354 IORING_FEAT_POLL_32BITS;
8356 if (copy_to_user(params, p, sizeof(*p))) {
8361 * Install ring fd as the very last thing, so we don't risk someone
8362 * having closed it before we finish setup
8364 ret = io_uring_get_fd(ctx);
8368 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
8369 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
8371 ctx->limit_mem = limit_mem;
8374 io_ring_ctx_wait_and_kill(ctx);
8379 * Sets up an aio uring context, and returns the fd. Applications asks for a
8380 * ring size, we return the actual sq/cq ring sizes (among other things) in the
8381 * params structure passed in.
8383 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
8385 struct io_uring_params p;
8388 if (copy_from_user(&p, params, sizeof(p)))
8390 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
8395 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8396 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8397 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8400 return io_uring_create(entries, &p, params);
8403 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8404 struct io_uring_params __user *, params)
8406 return io_uring_setup(entries, params);
8409 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8411 struct io_uring_probe *p;
8415 size = struct_size(p, ops, nr_args);
8416 if (size == SIZE_MAX)
8418 p = kzalloc(size, GFP_KERNEL);
8423 if (copy_from_user(p, arg, size))
8426 if (memchr_inv(p, 0, size))
8429 p->last_op = IORING_OP_LAST - 1;
8430 if (nr_args > IORING_OP_LAST)
8431 nr_args = IORING_OP_LAST;
8433 for (i = 0; i < nr_args; i++) {
8435 if (!io_op_defs[i].not_supported)
8436 p->ops[i].flags = IO_URING_OP_SUPPORTED;
8441 if (copy_to_user(arg, p, size))
8448 static int io_register_personality(struct io_ring_ctx *ctx)
8450 const struct cred *creds = get_current_cred();
8453 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8454 USHRT_MAX, GFP_KERNEL);
8460 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8462 const struct cred *old_creds;
8464 old_creds = idr_remove(&ctx->personality_idr, id);
8466 put_cred(old_creds);
8473 static bool io_register_op_must_quiesce(int op)
8476 case IORING_UNREGISTER_FILES:
8477 case IORING_REGISTER_FILES_UPDATE:
8478 case IORING_REGISTER_PROBE:
8479 case IORING_REGISTER_PERSONALITY:
8480 case IORING_UNREGISTER_PERSONALITY:
8487 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8488 void __user *arg, unsigned nr_args)
8489 __releases(ctx->uring_lock)
8490 __acquires(ctx->uring_lock)
8495 * We're inside the ring mutex, if the ref is already dying, then
8496 * someone else killed the ctx or is already going through
8497 * io_uring_register().
8499 if (percpu_ref_is_dying(&ctx->refs))
8502 if (io_register_op_must_quiesce(opcode)) {
8503 percpu_ref_kill(&ctx->refs);
8506 * Drop uring mutex before waiting for references to exit. If
8507 * another thread is currently inside io_uring_enter() it might
8508 * need to grab the uring_lock to make progress. If we hold it
8509 * here across the drain wait, then we can deadlock. It's safe
8510 * to drop the mutex here, since no new references will come in
8511 * after we've killed the percpu ref.
8513 mutex_unlock(&ctx->uring_lock);
8514 ret = wait_for_completion_interruptible(&ctx->ref_comp);
8515 mutex_lock(&ctx->uring_lock);
8517 percpu_ref_resurrect(&ctx->refs);
8524 case IORING_REGISTER_BUFFERS:
8525 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8527 case IORING_UNREGISTER_BUFFERS:
8531 ret = io_sqe_buffer_unregister(ctx);
8533 case IORING_REGISTER_FILES:
8534 ret = io_sqe_files_register(ctx, arg, nr_args);
8536 case IORING_UNREGISTER_FILES:
8540 ret = io_sqe_files_unregister(ctx);
8542 case IORING_REGISTER_FILES_UPDATE:
8543 ret = io_sqe_files_update(ctx, arg, nr_args);
8545 case IORING_REGISTER_EVENTFD:
8546 case IORING_REGISTER_EVENTFD_ASYNC:
8550 ret = io_eventfd_register(ctx, arg);
8553 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8554 ctx->eventfd_async = 1;
8556 ctx->eventfd_async = 0;
8558 case IORING_UNREGISTER_EVENTFD:
8562 ret = io_eventfd_unregister(ctx);
8564 case IORING_REGISTER_PROBE:
8566 if (!arg || nr_args > 256)
8568 ret = io_probe(ctx, arg, nr_args);
8570 case IORING_REGISTER_PERSONALITY:
8574 ret = io_register_personality(ctx);
8576 case IORING_UNREGISTER_PERSONALITY:
8580 ret = io_unregister_personality(ctx, nr_args);
8587 if (io_register_op_must_quiesce(opcode)) {
8588 /* bring the ctx back to life */
8589 percpu_ref_reinit(&ctx->refs);
8591 reinit_completion(&ctx->ref_comp);
8596 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8597 void __user *, arg, unsigned int, nr_args)
8599 struct io_ring_ctx *ctx;
8608 if (f.file->f_op != &io_uring_fops)
8611 ctx = f.file->private_data;
8613 mutex_lock(&ctx->uring_lock);
8614 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8615 mutex_unlock(&ctx->uring_lock);
8616 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8617 ctx->cq_ev_fd != NULL, ret);
8623 static int __init io_uring_init(void)
8625 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8626 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8627 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8630 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8631 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8632 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8633 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8634 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8635 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8636 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8637 BUILD_BUG_SQE_ELEM(8, __u64, off);
8638 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8639 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8640 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8641 BUILD_BUG_SQE_ELEM(24, __u32, len);
8642 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8643 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8644 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8645 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8646 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
8647 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
8648 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8649 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8650 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8651 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8652 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8653 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8654 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8655 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8656 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8657 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8658 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8659 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8660 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8662 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8663 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8664 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8667 __initcall(io_uring_init);