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 * ->poll_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 poll_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;
402 /* NOTE: kiocb has the file as the first member, so don't do it here */
410 struct sockaddr __user *addr;
417 struct user_msghdr __user *msg;
423 struct io_buffer *kbuf;
429 struct filename *filename;
431 unsigned long nofile;
434 struct io_files_update {
460 struct epoll_event event;
464 struct file *file_out;
465 struct file *file_in;
472 struct io_provide_buf {
486 const char __user *filename;
487 struct statx __user *buffer;
490 struct io_async_connect {
491 struct sockaddr_storage address;
494 struct io_async_msghdr {
495 struct iovec fast_iov[UIO_FASTIOV];
497 struct sockaddr __user *uaddr;
499 struct sockaddr_storage addr;
503 struct iovec fast_iov[UIO_FASTIOV];
507 struct wait_page_queue wpq;
508 struct callback_head task_work;
511 struct io_async_ctx {
513 struct io_async_rw rw;
514 struct io_async_msghdr msg;
515 struct io_async_connect connect;
516 struct io_timeout_data timeout;
521 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
522 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
523 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
524 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
525 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
526 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
534 REQ_F_LINK_TIMEOUT_BIT,
537 REQ_F_TIMEOUT_NOSEQ_BIT,
538 REQ_F_COMP_LOCKED_BIT,
539 REQ_F_NEED_CLEANUP_BIT,
542 REQ_F_BUFFER_SELECTED_BIT,
543 REQ_F_NO_FILE_TABLE_BIT,
544 REQ_F_QUEUE_TIMEOUT_BIT,
545 REQ_F_WORK_INITIALIZED_BIT,
546 REQ_F_TASK_PINNED_BIT,
548 /* not a real bit, just to check we're not overflowing the space */
554 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
555 /* drain existing IO first */
556 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
558 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
559 /* doesn't sever on completion < 0 */
560 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
562 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
563 /* IOSQE_BUFFER_SELECT */
564 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
567 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
568 /* already grabbed next link */
569 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_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),
580 /* timeout request */
581 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
583 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
584 /* no timeout sequence */
585 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
586 /* completion under lock */
587 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
589 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
590 /* in overflow list */
591 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
592 /* already went through poll handler */
593 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
594 /* buffer already selected */
595 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
596 /* doesn't need file table for this request */
597 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
598 /* needs to queue linked timeout */
599 REQ_F_QUEUE_TIMEOUT = BIT(REQ_F_QUEUE_TIMEOUT_BIT),
600 /* io_wq_work is initialized */
601 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
602 /* req->task is refcounted */
603 REQ_F_TASK_PINNED = BIT(REQ_F_TASK_PINNED_BIT),
607 struct io_poll_iocb poll;
608 struct io_wq_work work;
612 * NOTE! Each of the iocb union members has the file pointer
613 * as the first entry in their struct definition. So you can
614 * access the file pointer through any of the sub-structs,
615 * or directly as just 'ki_filp' in this struct.
621 struct io_poll_iocb poll;
622 struct io_accept accept;
624 struct io_cancel cancel;
625 struct io_timeout timeout;
626 struct io_connect connect;
627 struct io_sr_msg sr_msg;
629 struct io_close close;
630 struct io_files_update files_update;
631 struct io_fadvise fadvise;
632 struct io_madvise madvise;
633 struct io_epoll epoll;
634 struct io_splice splice;
635 struct io_provide_buf pbuf;
636 struct io_statx statx;
639 struct io_async_ctx *io;
642 /* polled IO has completed */
647 struct io_ring_ctx *ctx;
648 struct list_head list;
651 struct task_struct *task;
657 struct list_head link_list;
659 struct list_head inflight_entry;
661 struct percpu_ref *fixed_file_refs;
665 * Only commands that never go async can use the below fields,
666 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
667 * async armed poll handlers for regular commands. The latter
668 * restore the work, if needed.
671 struct hlist_node hash_node;
672 struct async_poll *apoll;
674 struct io_wq_work work;
676 struct callback_head task_work;
679 #define IO_IOPOLL_BATCH 8
681 struct io_comp_state {
683 struct list_head list;
684 struct io_ring_ctx *ctx;
687 struct io_submit_state {
688 struct blk_plug plug;
691 * io_kiocb alloc cache
693 void *reqs[IO_IOPOLL_BATCH];
694 unsigned int free_reqs;
697 * Batch completion logic
699 struct io_comp_state comp;
702 * File reference cache
706 unsigned int has_refs;
707 unsigned int used_refs;
708 unsigned int ios_left;
712 /* needs req->io allocated for deferral/async */
713 unsigned async_ctx : 1;
714 /* needs current->mm setup, does mm access */
715 unsigned needs_mm : 1;
716 /* needs req->file assigned */
717 unsigned needs_file : 1;
718 /* don't fail if file grab fails */
719 unsigned needs_file_no_error : 1;
720 /* hash wq insertion if file is a regular file */
721 unsigned hash_reg_file : 1;
722 /* unbound wq insertion if file is a non-regular file */
723 unsigned unbound_nonreg_file : 1;
724 /* opcode is not supported by this kernel */
725 unsigned not_supported : 1;
726 /* needs file table */
727 unsigned file_table : 1;
729 unsigned needs_fs : 1;
730 /* set if opcode supports polled "wait" */
732 unsigned pollout : 1;
733 /* op supports buffer selection */
734 unsigned buffer_select : 1;
737 static const struct io_op_def io_op_defs[] = {
738 [IORING_OP_NOP] = {},
739 [IORING_OP_READV] = {
743 .unbound_nonreg_file = 1,
747 [IORING_OP_WRITEV] = {
752 .unbound_nonreg_file = 1,
755 [IORING_OP_FSYNC] = {
758 [IORING_OP_READ_FIXED] = {
760 .unbound_nonreg_file = 1,
763 [IORING_OP_WRITE_FIXED] = {
766 .unbound_nonreg_file = 1,
769 [IORING_OP_POLL_ADD] = {
771 .unbound_nonreg_file = 1,
773 [IORING_OP_POLL_REMOVE] = {},
774 [IORING_OP_SYNC_FILE_RANGE] = {
777 [IORING_OP_SENDMSG] = {
781 .unbound_nonreg_file = 1,
785 [IORING_OP_RECVMSG] = {
789 .unbound_nonreg_file = 1,
794 [IORING_OP_TIMEOUT] = {
798 [IORING_OP_TIMEOUT_REMOVE] = {},
799 [IORING_OP_ACCEPT] = {
802 .unbound_nonreg_file = 1,
806 [IORING_OP_ASYNC_CANCEL] = {},
807 [IORING_OP_LINK_TIMEOUT] = {
811 [IORING_OP_CONNECT] = {
815 .unbound_nonreg_file = 1,
818 [IORING_OP_FALLOCATE] = {
821 [IORING_OP_OPENAT] = {
825 [IORING_OP_CLOSE] = {
827 .needs_file_no_error = 1,
830 [IORING_OP_FILES_UPDATE] = {
834 [IORING_OP_STATX] = {
842 .unbound_nonreg_file = 1,
846 [IORING_OP_WRITE] = {
849 .unbound_nonreg_file = 1,
852 [IORING_OP_FADVISE] = {
855 [IORING_OP_MADVISE] = {
861 .unbound_nonreg_file = 1,
867 .unbound_nonreg_file = 1,
871 [IORING_OP_OPENAT2] = {
875 [IORING_OP_EPOLL_CTL] = {
876 .unbound_nonreg_file = 1,
879 [IORING_OP_SPLICE] = {
882 .unbound_nonreg_file = 1,
884 [IORING_OP_PROVIDE_BUFFERS] = {},
885 [IORING_OP_REMOVE_BUFFERS] = {},
889 .unbound_nonreg_file = 1,
893 enum io_mem_account {
898 static void io_cqring_fill_event(struct io_kiocb *req, long res);
899 static void io_put_req(struct io_kiocb *req);
900 static void io_double_put_req(struct io_kiocb *req);
901 static void __io_double_put_req(struct io_kiocb *req);
902 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
903 static void io_queue_linked_timeout(struct io_kiocb *req);
904 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
905 struct io_uring_files_update *ip,
907 static int io_grab_files(struct io_kiocb *req);
908 static void io_complete_rw_common(struct kiocb *kiocb, long res,
909 struct io_comp_state *cs);
910 static void io_cleanup_req(struct io_kiocb *req);
911 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
912 int fd, struct file **out_file, bool fixed);
913 static void __io_queue_sqe(struct io_kiocb *req,
914 const struct io_uring_sqe *sqe,
915 struct io_comp_state *cs);
917 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
918 struct iovec **iovec, struct iov_iter *iter,
920 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
921 struct iovec *iovec, struct iovec *fast_iov,
922 struct iov_iter *iter);
924 static struct kmem_cache *req_cachep;
926 static const struct file_operations io_uring_fops;
928 struct sock *io_uring_get_socket(struct file *file)
930 #if defined(CONFIG_UNIX)
931 if (file->f_op == &io_uring_fops) {
932 struct io_ring_ctx *ctx = file->private_data;
934 return ctx->ring_sock->sk;
939 EXPORT_SYMBOL(io_uring_get_socket);
941 static void io_get_req_task(struct io_kiocb *req)
943 if (req->flags & REQ_F_TASK_PINNED)
945 get_task_struct(req->task);
946 req->flags |= REQ_F_TASK_PINNED;
949 /* not idempotent -- it doesn't clear REQ_F_TASK_PINNED */
950 static void __io_put_req_task(struct io_kiocb *req)
952 if (req->flags & REQ_F_TASK_PINNED)
953 put_task_struct(req->task);
956 static void io_sq_thread_drop_mm(struct io_ring_ctx *ctx)
958 struct mm_struct *mm = current->mm;
961 kthread_unuse_mm(mm);
966 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
969 if (unlikely(!mmget_not_zero(ctx->sqo_mm)))
971 kthread_use_mm(ctx->sqo_mm);
977 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
978 struct io_kiocb *req)
980 if (!io_op_defs[req->opcode].needs_mm)
982 return __io_sq_thread_acquire_mm(ctx);
985 static inline void req_set_fail_links(struct io_kiocb *req)
987 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
988 req->flags |= REQ_F_FAIL_LINK;
991 static void io_file_put_work(struct work_struct *work);
994 * Note: must call io_req_init_async() for the first time you
995 * touch any members of io_wq_work.
997 static inline void io_req_init_async(struct io_kiocb *req)
999 if (req->flags & REQ_F_WORK_INITIALIZED)
1002 memset(&req->work, 0, sizeof(req->work));
1003 req->flags |= REQ_F_WORK_INITIALIZED;
1006 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1008 return ctx->flags & IORING_SETUP_SQPOLL;
1011 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1013 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1015 complete(&ctx->ref_comp);
1018 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1020 struct io_ring_ctx *ctx;
1023 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1027 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1028 if (!ctx->fallback_req)
1032 * Use 5 bits less than the max cq entries, that should give us around
1033 * 32 entries per hash list if totally full and uniformly spread.
1035 hash_bits = ilog2(p->cq_entries);
1039 ctx->cancel_hash_bits = hash_bits;
1040 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1042 if (!ctx->cancel_hash)
1044 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1046 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1047 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1050 ctx->flags = p->flags;
1051 init_waitqueue_head(&ctx->sqo_wait);
1052 init_waitqueue_head(&ctx->cq_wait);
1053 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1054 init_completion(&ctx->ref_comp);
1055 init_completion(&ctx->sq_thread_comp);
1056 idr_init(&ctx->io_buffer_idr);
1057 idr_init(&ctx->personality_idr);
1058 mutex_init(&ctx->uring_lock);
1059 init_waitqueue_head(&ctx->wait);
1060 spin_lock_init(&ctx->completion_lock);
1061 INIT_LIST_HEAD(&ctx->poll_list);
1062 INIT_LIST_HEAD(&ctx->defer_list);
1063 INIT_LIST_HEAD(&ctx->timeout_list);
1064 init_waitqueue_head(&ctx->inflight_wait);
1065 spin_lock_init(&ctx->inflight_lock);
1066 INIT_LIST_HEAD(&ctx->inflight_list);
1067 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1068 init_llist_head(&ctx->file_put_llist);
1071 if (ctx->fallback_req)
1072 kmem_cache_free(req_cachep, ctx->fallback_req);
1073 kfree(ctx->cancel_hash);
1078 static inline bool __req_need_defer(struct io_kiocb *req)
1080 struct io_ring_ctx *ctx = req->ctx;
1082 return req->sequence != ctx->cached_cq_tail
1083 + atomic_read(&ctx->cached_cq_overflow);
1086 static inline bool req_need_defer(struct io_kiocb *req)
1088 if (unlikely(req->flags & REQ_F_IO_DRAIN))
1089 return __req_need_defer(req);
1094 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1096 struct io_rings *rings = ctx->rings;
1098 /* order cqe stores with ring update */
1099 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1101 if (wq_has_sleeper(&ctx->cq_wait)) {
1102 wake_up_interruptible(&ctx->cq_wait);
1103 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1107 static inline void io_req_work_grab_env(struct io_kiocb *req,
1108 const struct io_op_def *def)
1110 if (!req->work.mm && def->needs_mm) {
1111 mmgrab(current->mm);
1112 req->work.mm = current->mm;
1114 if (!req->work.creds)
1115 req->work.creds = get_current_cred();
1116 if (!req->work.fs && def->needs_fs) {
1117 spin_lock(¤t->fs->lock);
1118 if (!current->fs->in_exec) {
1119 req->work.fs = current->fs;
1120 req->work.fs->users++;
1122 req->work.flags |= IO_WQ_WORK_CANCEL;
1124 spin_unlock(¤t->fs->lock);
1128 static inline void io_req_work_drop_env(struct io_kiocb *req)
1130 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1134 mmdrop(req->work.mm);
1135 req->work.mm = NULL;
1137 if (req->work.creds) {
1138 put_cred(req->work.creds);
1139 req->work.creds = NULL;
1142 struct fs_struct *fs = req->work.fs;
1144 spin_lock(&req->work.fs->lock);
1147 spin_unlock(&req->work.fs->lock);
1153 static inline void io_prep_async_work(struct io_kiocb *req,
1154 struct io_kiocb **link)
1156 const struct io_op_def *def = &io_op_defs[req->opcode];
1158 if (req->flags & REQ_F_ISREG) {
1159 if (def->hash_reg_file)
1160 io_wq_hash_work(&req->work, file_inode(req->file));
1162 if (def->unbound_nonreg_file)
1163 req->work.flags |= IO_WQ_WORK_UNBOUND;
1166 io_req_init_async(req);
1167 io_req_work_grab_env(req, def);
1169 *link = io_prep_linked_timeout(req);
1172 static inline void io_queue_async_work(struct io_kiocb *req)
1174 struct io_ring_ctx *ctx = req->ctx;
1175 struct io_kiocb *link;
1177 io_prep_async_work(req, &link);
1179 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1180 &req->work, req->flags);
1181 io_wq_enqueue(ctx->io_wq, &req->work);
1184 io_queue_linked_timeout(link);
1187 static void io_kill_timeout(struct io_kiocb *req)
1191 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1193 atomic_inc(&req->ctx->cq_timeouts);
1194 list_del_init(&req->list);
1195 req->flags |= REQ_F_COMP_LOCKED;
1196 io_cqring_fill_event(req, 0);
1201 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1203 struct io_kiocb *req, *tmp;
1205 spin_lock_irq(&ctx->completion_lock);
1206 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1207 io_kill_timeout(req);
1208 spin_unlock_irq(&ctx->completion_lock);
1211 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1214 struct io_kiocb *req = list_first_entry(&ctx->defer_list,
1215 struct io_kiocb, list);
1217 if (req_need_defer(req))
1219 list_del_init(&req->list);
1220 io_queue_async_work(req);
1221 } while (!list_empty(&ctx->defer_list));
1224 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1226 while (!list_empty(&ctx->timeout_list)) {
1227 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1228 struct io_kiocb, list);
1230 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
1232 if (req->timeout.target_seq != ctx->cached_cq_tail
1233 - atomic_read(&ctx->cq_timeouts))
1236 list_del_init(&req->list);
1237 io_kill_timeout(req);
1241 static void io_commit_cqring(struct io_ring_ctx *ctx)
1243 io_flush_timeouts(ctx);
1244 __io_commit_cqring(ctx);
1246 if (unlikely(!list_empty(&ctx->defer_list)))
1247 __io_queue_deferred(ctx);
1250 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1252 struct io_rings *rings = ctx->rings;
1255 tail = ctx->cached_cq_tail;
1257 * writes to the cq entry need to come after reading head; the
1258 * control dependency is enough as we're using WRITE_ONCE to
1261 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1264 ctx->cached_cq_tail++;
1265 return &rings->cqes[tail & ctx->cq_mask];
1268 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1272 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1274 if (!ctx->eventfd_async)
1276 return io_wq_current_is_worker();
1279 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1281 if (waitqueue_active(&ctx->wait))
1282 wake_up(&ctx->wait);
1283 if (waitqueue_active(&ctx->sqo_wait))
1284 wake_up(&ctx->sqo_wait);
1285 if (io_should_trigger_evfd(ctx))
1286 eventfd_signal(ctx->cq_ev_fd, 1);
1289 /* Returns true if there are no backlogged entries after the flush */
1290 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1292 struct io_rings *rings = ctx->rings;
1293 struct io_uring_cqe *cqe;
1294 struct io_kiocb *req;
1295 unsigned long flags;
1299 if (list_empty_careful(&ctx->cq_overflow_list))
1301 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1302 rings->cq_ring_entries))
1306 spin_lock_irqsave(&ctx->completion_lock, flags);
1308 /* if force is set, the ring is going away. always drop after that */
1310 ctx->cq_overflow_flushed = 1;
1313 while (!list_empty(&ctx->cq_overflow_list)) {
1314 cqe = io_get_cqring(ctx);
1318 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1320 list_move(&req->list, &list);
1321 req->flags &= ~REQ_F_OVERFLOW;
1323 WRITE_ONCE(cqe->user_data, req->user_data);
1324 WRITE_ONCE(cqe->res, req->result);
1325 WRITE_ONCE(cqe->flags, req->cflags);
1327 WRITE_ONCE(ctx->rings->cq_overflow,
1328 atomic_inc_return(&ctx->cached_cq_overflow));
1332 io_commit_cqring(ctx);
1334 clear_bit(0, &ctx->sq_check_overflow);
1335 clear_bit(0, &ctx->cq_check_overflow);
1337 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1338 io_cqring_ev_posted(ctx);
1340 while (!list_empty(&list)) {
1341 req = list_first_entry(&list, struct io_kiocb, list);
1342 list_del(&req->list);
1349 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1351 struct io_ring_ctx *ctx = req->ctx;
1352 struct io_uring_cqe *cqe;
1354 trace_io_uring_complete(ctx, req->user_data, res);
1357 * If we can't get a cq entry, userspace overflowed the
1358 * submission (by quite a lot). Increment the overflow count in
1361 cqe = io_get_cqring(ctx);
1363 WRITE_ONCE(cqe->user_data, req->user_data);
1364 WRITE_ONCE(cqe->res, res);
1365 WRITE_ONCE(cqe->flags, cflags);
1366 } else if (ctx->cq_overflow_flushed) {
1367 WRITE_ONCE(ctx->rings->cq_overflow,
1368 atomic_inc_return(&ctx->cached_cq_overflow));
1370 if (list_empty(&ctx->cq_overflow_list)) {
1371 set_bit(0, &ctx->sq_check_overflow);
1372 set_bit(0, &ctx->cq_check_overflow);
1374 req->flags |= REQ_F_OVERFLOW;
1375 refcount_inc(&req->refs);
1377 req->cflags = cflags;
1378 list_add_tail(&req->list, &ctx->cq_overflow_list);
1382 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1384 __io_cqring_fill_event(req, res, 0);
1387 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1389 struct io_ring_ctx *ctx = req->ctx;
1390 unsigned long flags;
1392 spin_lock_irqsave(&ctx->completion_lock, flags);
1393 __io_cqring_fill_event(req, res, cflags);
1394 io_commit_cqring(ctx);
1395 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1397 io_cqring_ev_posted(ctx);
1400 static void io_submit_flush_completions(struct io_comp_state *cs)
1402 struct io_ring_ctx *ctx = cs->ctx;
1404 spin_lock_irq(&ctx->completion_lock);
1405 while (!list_empty(&cs->list)) {
1406 struct io_kiocb *req;
1408 req = list_first_entry(&cs->list, struct io_kiocb, list);
1409 list_del(&req->list);
1410 io_cqring_fill_event(req, req->result);
1411 if (!(req->flags & REQ_F_LINK_HEAD)) {
1412 req->flags |= REQ_F_COMP_LOCKED;
1415 spin_unlock_irq(&ctx->completion_lock);
1417 spin_lock_irq(&ctx->completion_lock);
1420 io_commit_cqring(ctx);
1421 spin_unlock_irq(&ctx->completion_lock);
1423 io_cqring_ev_posted(ctx);
1427 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1428 struct io_comp_state *cs)
1431 io_cqring_add_event(req, res, cflags);
1435 list_add_tail(&req->list, &cs->list);
1437 io_submit_flush_completions(cs);
1441 static void io_req_complete(struct io_kiocb *req, long res)
1443 __io_req_complete(req, res, 0, NULL);
1446 static inline bool io_is_fallback_req(struct io_kiocb *req)
1448 return req == (struct io_kiocb *)
1449 ((unsigned long) req->ctx->fallback_req & ~1UL);
1452 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1454 struct io_kiocb *req;
1456 req = ctx->fallback_req;
1457 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1463 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1464 struct io_submit_state *state)
1466 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1467 struct io_kiocb *req;
1469 if (!state->free_reqs) {
1473 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1474 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1477 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1478 * retry single alloc to be on the safe side.
1480 if (unlikely(ret <= 0)) {
1481 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1482 if (!state->reqs[0])
1486 state->free_reqs = ret - 1;
1487 req = state->reqs[ret - 1];
1490 req = state->reqs[state->free_reqs];
1495 return io_get_fallback_req(ctx);
1498 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1502 percpu_ref_put(req->fixed_file_refs);
1507 static void io_dismantle_req(struct io_kiocb *req)
1509 if (req->flags & REQ_F_NEED_CLEANUP)
1510 io_cleanup_req(req);
1514 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1515 __io_put_req_task(req);
1516 io_req_work_drop_env(req);
1518 if (req->flags & REQ_F_INFLIGHT) {
1519 struct io_ring_ctx *ctx = req->ctx;
1520 unsigned long flags;
1522 spin_lock_irqsave(&ctx->inflight_lock, flags);
1523 list_del(&req->inflight_entry);
1524 if (waitqueue_active(&ctx->inflight_wait))
1525 wake_up(&ctx->inflight_wait);
1526 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1530 static void __io_free_req(struct io_kiocb *req)
1532 io_dismantle_req(req);
1533 percpu_ref_put(&req->ctx->refs);
1534 if (likely(!io_is_fallback_req(req)))
1535 kmem_cache_free(req_cachep, req);
1537 clear_bit_unlock(0, (unsigned long *) &req->ctx->fallback_req);
1541 void *reqs[IO_IOPOLL_BATCH];
1545 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1550 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1551 percpu_ref_put_many(&ctx->refs, rb->to_free);
1555 static bool io_link_cancel_timeout(struct io_kiocb *req)
1557 struct io_ring_ctx *ctx = req->ctx;
1560 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1562 io_cqring_fill_event(req, -ECANCELED);
1563 io_commit_cqring(ctx);
1564 req->flags &= ~REQ_F_LINK_HEAD;
1572 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1574 struct io_ring_ctx *ctx = req->ctx;
1575 bool wake_ev = false;
1577 /* Already got next link */
1578 if (req->flags & REQ_F_LINK_NEXT)
1582 * The list should never be empty when we are called here. But could
1583 * potentially happen if the chain is messed up, check to be on the
1586 while (!list_empty(&req->link_list)) {
1587 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1588 struct io_kiocb, link_list);
1590 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1591 (nxt->flags & REQ_F_TIMEOUT))) {
1592 list_del_init(&nxt->link_list);
1593 wake_ev |= io_link_cancel_timeout(nxt);
1594 req->flags &= ~REQ_F_LINK_TIMEOUT;
1598 list_del_init(&req->link_list);
1599 if (!list_empty(&nxt->link_list))
1600 nxt->flags |= REQ_F_LINK_HEAD;
1605 req->flags |= REQ_F_LINK_NEXT;
1607 io_cqring_ev_posted(ctx);
1611 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1613 static void io_fail_links(struct io_kiocb *req)
1615 struct io_ring_ctx *ctx = req->ctx;
1616 unsigned long flags;
1618 spin_lock_irqsave(&ctx->completion_lock, flags);
1620 while (!list_empty(&req->link_list)) {
1621 struct io_kiocb *link = list_first_entry(&req->link_list,
1622 struct io_kiocb, link_list);
1624 list_del_init(&link->link_list);
1625 trace_io_uring_fail_link(req, link);
1627 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1628 link->opcode == IORING_OP_LINK_TIMEOUT) {
1629 io_link_cancel_timeout(link);
1631 io_cqring_fill_event(link, -ECANCELED);
1632 __io_double_put_req(link);
1634 req->flags &= ~REQ_F_LINK_TIMEOUT;
1637 io_commit_cqring(ctx);
1638 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1639 io_cqring_ev_posted(ctx);
1642 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1644 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1648 * If LINK is set, we have dependent requests in this chain. If we
1649 * didn't fail this request, queue the first one up, moving any other
1650 * dependencies to the next request. In case of failure, fail the rest
1653 if (req->flags & REQ_F_FAIL_LINK) {
1655 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1656 REQ_F_LINK_TIMEOUT) {
1657 struct io_ring_ctx *ctx = req->ctx;
1658 unsigned long flags;
1661 * If this is a timeout link, we could be racing with the
1662 * timeout timer. Grab the completion lock for this case to
1663 * protect against that.
1665 spin_lock_irqsave(&ctx->completion_lock, flags);
1666 io_req_link_next(req, nxt);
1667 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1669 io_req_link_next(req, nxt);
1673 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1675 struct io_ring_ctx *ctx = req->ctx;
1677 spin_lock_irq(&ctx->completion_lock);
1678 io_cqring_fill_event(req, error);
1679 io_commit_cqring(ctx);
1680 spin_unlock_irq(&ctx->completion_lock);
1682 io_cqring_ev_posted(ctx);
1683 req_set_fail_links(req);
1684 io_double_put_req(req);
1687 static void io_req_task_cancel(struct callback_head *cb)
1689 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1691 __io_req_task_cancel(req, -ECANCELED);
1694 static void __io_req_task_submit(struct io_kiocb *req)
1696 struct io_ring_ctx *ctx = req->ctx;
1698 __set_current_state(TASK_RUNNING);
1699 if (!__io_sq_thread_acquire_mm(ctx)) {
1700 mutex_lock(&ctx->uring_lock);
1701 __io_queue_sqe(req, NULL, NULL);
1702 mutex_unlock(&ctx->uring_lock);
1704 __io_req_task_cancel(req, -EFAULT);
1708 static void io_req_task_submit(struct callback_head *cb)
1710 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1712 __io_req_task_submit(req);
1715 static void io_req_task_queue(struct io_kiocb *req)
1717 struct task_struct *tsk = req->task;
1720 init_task_work(&req->task_work, io_req_task_submit);
1722 ret = task_work_add(tsk, &req->task_work, true);
1723 if (unlikely(ret)) {
1724 init_task_work(&req->task_work, io_req_task_cancel);
1725 tsk = io_wq_get_task(req->ctx->io_wq);
1726 task_work_add(tsk, &req->task_work, true);
1728 wake_up_process(tsk);
1731 static void io_queue_next(struct io_kiocb *req)
1733 struct io_kiocb *nxt = NULL;
1735 io_req_find_next(req, &nxt);
1737 io_req_task_queue(nxt);
1740 static void io_free_req(struct io_kiocb *req)
1747 * Drop reference to request, return next in chain (if there is one) if this
1748 * was the last reference to this request.
1750 __attribute__((nonnull))
1751 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1753 if (refcount_dec_and_test(&req->refs)) {
1754 io_req_find_next(req, nxtptr);
1759 static void io_put_req(struct io_kiocb *req)
1761 if (refcount_dec_and_test(&req->refs))
1765 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
1767 struct io_kiocb *nxt = NULL;
1770 * A ref is owned by io-wq in which context we're. So, if that's the
1771 * last one, it's safe to steal next work. False negatives are Ok,
1772 * it just will be re-punted async in io_put_work()
1774 if (refcount_read(&req->refs) != 1)
1777 io_req_find_next(req, &nxt);
1781 if ((nxt->flags & REQ_F_ISREG) && io_op_defs[nxt->opcode].hash_reg_file)
1782 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1784 io_req_task_queue(nxt);
1786 * If we're going to return actual work, here should be timeout prep:
1788 * link = io_prep_linked_timeout(nxt);
1790 * nxt->flags |= REQ_F_QUEUE_TIMEOUT;
1796 * Must only be used if we don't need to care about links, usually from
1797 * within the completion handling itself.
1799 static void __io_double_put_req(struct io_kiocb *req)
1801 /* drop both submit and complete references */
1802 if (refcount_sub_and_test(2, &req->refs))
1806 static void io_double_put_req(struct io_kiocb *req)
1808 /* drop both submit and complete references */
1809 if (refcount_sub_and_test(2, &req->refs))
1813 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1815 struct io_rings *rings = ctx->rings;
1817 if (test_bit(0, &ctx->cq_check_overflow)) {
1819 * noflush == true is from the waitqueue handler, just ensure
1820 * we wake up the task, and the next invocation will flush the
1821 * entries. We cannot safely to it from here.
1823 if (noflush && !list_empty(&ctx->cq_overflow_list))
1826 io_cqring_overflow_flush(ctx, false);
1829 /* See comment at the top of this file */
1831 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1834 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1836 struct io_rings *rings = ctx->rings;
1838 /* make sure SQ entry isn't read before tail */
1839 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1842 static inline void io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1844 if (unlikely(io_is_fallback_req(req))) {
1848 if (req->flags & REQ_F_LINK_HEAD)
1851 io_dismantle_req(req);
1852 rb->reqs[rb->to_free++] = req;
1853 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1854 io_free_req_many(req->ctx, rb);
1857 static int io_put_kbuf(struct io_kiocb *req)
1859 struct io_buffer *kbuf;
1862 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1863 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1864 cflags |= IORING_CQE_F_BUFFER;
1870 static void io_iopoll_queue(struct list_head *again)
1872 struct io_kiocb *req;
1875 req = list_first_entry(again, struct io_kiocb, list);
1876 list_del(&req->list);
1878 /* shouldn't happen unless io_uring is dying, cancel reqs */
1879 if (unlikely(!current->mm)) {
1880 io_complete_rw_common(&req->rw.kiocb, -EAGAIN, NULL);
1884 refcount_inc(&req->refs);
1885 io_queue_async_work(req);
1886 } while (!list_empty(again));
1890 * Find and free completed poll iocbs
1892 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1893 struct list_head *done)
1895 struct req_batch rb;
1896 struct io_kiocb *req;
1899 /* order with ->result store in io_complete_rw_iopoll() */
1903 while (!list_empty(done)) {
1906 req = list_first_entry(done, struct io_kiocb, list);
1907 if (READ_ONCE(req->result) == -EAGAIN) {
1908 req->iopoll_completed = 0;
1909 list_move_tail(&req->list, &again);
1912 list_del(&req->list);
1914 if (req->flags & REQ_F_BUFFER_SELECTED)
1915 cflags = io_put_kbuf(req);
1917 __io_cqring_fill_event(req, req->result, cflags);
1920 if (refcount_dec_and_test(&req->refs))
1921 io_req_multi_free(&rb, req);
1924 io_commit_cqring(ctx);
1925 if (ctx->flags & IORING_SETUP_SQPOLL)
1926 io_cqring_ev_posted(ctx);
1927 io_free_req_many(ctx, &rb);
1929 if (!list_empty(&again))
1930 io_iopoll_queue(&again);
1933 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1936 struct io_kiocb *req, *tmp;
1942 * Only spin for completions if we don't have multiple devices hanging
1943 * off our complete list, and we're under the requested amount.
1945 spin = !ctx->poll_multi_file && *nr_events < min;
1948 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1949 struct kiocb *kiocb = &req->rw.kiocb;
1952 * Move completed and retryable entries to our local lists.
1953 * If we find a request that requires polling, break out
1954 * and complete those lists first, if we have entries there.
1956 if (READ_ONCE(req->iopoll_completed)) {
1957 list_move_tail(&req->list, &done);
1960 if (!list_empty(&done))
1963 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1972 if (!list_empty(&done))
1973 io_iopoll_complete(ctx, nr_events, &done);
1979 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1980 * non-spinning poll check - we'll still enter the driver poll loop, but only
1981 * as a non-spinning completion check.
1983 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1986 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1989 ret = io_do_iopoll(ctx, nr_events, min);
1992 if (!min || *nr_events >= min)
2000 * We can't just wait for polled events to come to us, we have to actively
2001 * find and complete them.
2003 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
2005 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2008 mutex_lock(&ctx->uring_lock);
2009 while (!list_empty(&ctx->poll_list)) {
2010 unsigned int nr_events = 0;
2012 io_iopoll_getevents(ctx, &nr_events, 1);
2015 * Ensure we allow local-to-the-cpu processing to take place,
2016 * in this case we need to ensure that we reap all events.
2020 mutex_unlock(&ctx->uring_lock);
2023 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
2026 int iters = 0, ret = 0;
2029 * We disallow the app entering submit/complete with polling, but we
2030 * still need to lock the ring to prevent racing with polled issue
2031 * that got punted to a workqueue.
2033 mutex_lock(&ctx->uring_lock);
2038 * Don't enter poll loop if we already have events pending.
2039 * If we do, we can potentially be spinning for commands that
2040 * already triggered a CQE (eg in error).
2042 if (io_cqring_events(ctx, false))
2046 * If a submit got punted to a workqueue, we can have the
2047 * application entering polling for a command before it gets
2048 * issued. That app will hold the uring_lock for the duration
2049 * of the poll right here, so we need to take a breather every
2050 * now and then to ensure that the issue has a chance to add
2051 * the poll to the issued list. Otherwise we can spin here
2052 * forever, while the workqueue is stuck trying to acquire the
2055 if (!(++iters & 7)) {
2056 mutex_unlock(&ctx->uring_lock);
2057 mutex_lock(&ctx->uring_lock);
2060 if (*nr_events < min)
2061 tmin = min - *nr_events;
2063 ret = io_iopoll_getevents(ctx, nr_events, tmin);
2067 } while (min && !*nr_events && !need_resched());
2069 mutex_unlock(&ctx->uring_lock);
2073 static void kiocb_end_write(struct io_kiocb *req)
2076 * Tell lockdep we inherited freeze protection from submission
2079 if (req->flags & REQ_F_ISREG) {
2080 struct inode *inode = file_inode(req->file);
2082 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2084 file_end_write(req->file);
2087 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2088 struct io_comp_state *cs)
2090 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2093 if (kiocb->ki_flags & IOCB_WRITE)
2094 kiocb_end_write(req);
2096 if (res != req->result)
2097 req_set_fail_links(req);
2098 if (req->flags & REQ_F_BUFFER_SELECTED)
2099 cflags = io_put_kbuf(req);
2100 __io_req_complete(req, res, cflags, cs);
2104 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2106 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2107 ssize_t ret = -ECANCELED;
2108 struct iov_iter iter;
2116 switch (req->opcode) {
2117 case IORING_OP_READV:
2118 case IORING_OP_READ_FIXED:
2119 case IORING_OP_READ:
2122 case IORING_OP_WRITEV:
2123 case IORING_OP_WRITE_FIXED:
2124 case IORING_OP_WRITE:
2128 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2133 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2136 ret = io_setup_async_rw(req, ret, iovec, inline_vecs, &iter);
2141 req_set_fail_links(req);
2142 io_req_complete(req, ret);
2146 static void io_rw_resubmit(struct callback_head *cb)
2148 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2149 struct io_ring_ctx *ctx = req->ctx;
2152 __set_current_state(TASK_RUNNING);
2154 err = io_sq_thread_acquire_mm(ctx, req);
2156 if (io_resubmit_prep(req, err)) {
2157 refcount_inc(&req->refs);
2158 io_queue_async_work(req);
2163 static bool io_rw_reissue(struct io_kiocb *req, long res)
2166 struct task_struct *tsk;
2169 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2173 init_task_work(&req->task_work, io_rw_resubmit);
2174 ret = task_work_add(tsk, &req->task_work, true);
2181 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2182 struct io_comp_state *cs)
2184 if (!io_rw_reissue(req, res))
2185 io_complete_rw_common(&req->rw.kiocb, res, cs);
2188 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2190 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2192 __io_complete_rw(req, res, res2, NULL);
2195 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2197 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2199 if (kiocb->ki_flags & IOCB_WRITE)
2200 kiocb_end_write(req);
2202 if (res != -EAGAIN && res != req->result)
2203 req_set_fail_links(req);
2205 WRITE_ONCE(req->result, res);
2206 /* order with io_poll_complete() checking ->result */
2208 WRITE_ONCE(req->iopoll_completed, 1);
2212 * After the iocb has been issued, it's safe to be found on the poll list.
2213 * Adding the kiocb to the list AFTER submission ensures that we don't
2214 * find it from a io_iopoll_getevents() thread before the issuer is done
2215 * accessing the kiocb cookie.
2217 static void io_iopoll_req_issued(struct io_kiocb *req)
2219 struct io_ring_ctx *ctx = req->ctx;
2222 * Track whether we have multiple files in our lists. This will impact
2223 * how we do polling eventually, not spinning if we're on potentially
2224 * different devices.
2226 if (list_empty(&ctx->poll_list)) {
2227 ctx->poll_multi_file = false;
2228 } else if (!ctx->poll_multi_file) {
2229 struct io_kiocb *list_req;
2231 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
2233 if (list_req->file != req->file)
2234 ctx->poll_multi_file = true;
2238 * For fast devices, IO may have already completed. If it has, add
2239 * it to the front so we find it first.
2241 if (READ_ONCE(req->iopoll_completed))
2242 list_add(&req->list, &ctx->poll_list);
2244 list_add_tail(&req->list, &ctx->poll_list);
2246 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2247 wq_has_sleeper(&ctx->sqo_wait))
2248 wake_up(&ctx->sqo_wait);
2251 static void __io_state_file_put(struct io_submit_state *state)
2253 int diff = state->has_refs - state->used_refs;
2256 fput_many(state->file, diff);
2260 static inline void io_state_file_put(struct io_submit_state *state)
2263 __io_state_file_put(state);
2267 * Get as many references to a file as we have IOs left in this submission,
2268 * assuming most submissions are for one file, or at least that each file
2269 * has more than one submission.
2271 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2277 if (state->fd == fd) {
2282 __io_state_file_put(state);
2284 state->file = fget_many(fd, state->ios_left);
2289 state->has_refs = state->ios_left;
2290 state->used_refs = 1;
2295 static bool io_bdev_nowait(struct block_device *bdev)
2298 return !bdev || queue_is_mq(bdev_get_queue(bdev));
2305 * If we tracked the file through the SCM inflight mechanism, we could support
2306 * any file. For now, just ensure that anything potentially problematic is done
2309 static bool io_file_supports_async(struct file *file, int rw)
2311 umode_t mode = file_inode(file)->i_mode;
2313 if (S_ISBLK(mode)) {
2314 if (io_bdev_nowait(file->f_inode->i_bdev))
2318 if (S_ISCHR(mode) || S_ISSOCK(mode))
2320 if (S_ISREG(mode)) {
2321 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2322 file->f_op != &io_uring_fops)
2327 /* any ->read/write should understand O_NONBLOCK */
2328 if (file->f_flags & O_NONBLOCK)
2331 if (!(file->f_mode & FMODE_NOWAIT))
2335 return file->f_op->read_iter != NULL;
2337 return file->f_op->write_iter != NULL;
2340 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2341 bool force_nonblock)
2343 struct io_ring_ctx *ctx = req->ctx;
2344 struct kiocb *kiocb = &req->rw.kiocb;
2348 if (S_ISREG(file_inode(req->file)->i_mode))
2349 req->flags |= REQ_F_ISREG;
2351 kiocb->ki_pos = READ_ONCE(sqe->off);
2352 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2353 req->flags |= REQ_F_CUR_POS;
2354 kiocb->ki_pos = req->file->f_pos;
2356 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2357 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2358 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2362 ioprio = READ_ONCE(sqe->ioprio);
2364 ret = ioprio_check_cap(ioprio);
2368 kiocb->ki_ioprio = ioprio;
2370 kiocb->ki_ioprio = get_current_ioprio();
2372 /* don't allow async punt if RWF_NOWAIT was requested */
2373 if (kiocb->ki_flags & IOCB_NOWAIT)
2374 req->flags |= REQ_F_NOWAIT;
2376 if (kiocb->ki_flags & IOCB_DIRECT)
2377 io_get_req_task(req);
2380 kiocb->ki_flags |= IOCB_NOWAIT;
2382 if (ctx->flags & IORING_SETUP_IOPOLL) {
2383 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2384 !kiocb->ki_filp->f_op->iopoll)
2387 kiocb->ki_flags |= IOCB_HIPRI;
2388 kiocb->ki_complete = io_complete_rw_iopoll;
2390 req->iopoll_completed = 0;
2392 if (kiocb->ki_flags & IOCB_HIPRI)
2394 kiocb->ki_complete = io_complete_rw;
2397 req->rw.addr = READ_ONCE(sqe->addr);
2398 req->rw.len = READ_ONCE(sqe->len);
2399 req->buf_index = READ_ONCE(sqe->buf_index);
2403 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2409 case -ERESTARTNOINTR:
2410 case -ERESTARTNOHAND:
2411 case -ERESTART_RESTARTBLOCK:
2413 * We can't just restart the syscall, since previously
2414 * submitted sqes may already be in progress. Just fail this
2420 kiocb->ki_complete(kiocb, ret, 0);
2424 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2425 struct io_comp_state *cs)
2427 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2429 if (req->flags & REQ_F_CUR_POS)
2430 req->file->f_pos = kiocb->ki_pos;
2431 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2432 __io_complete_rw(req, ret, 0, cs);
2434 io_rw_done(kiocb, ret);
2437 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2438 struct iov_iter *iter)
2440 struct io_ring_ctx *ctx = req->ctx;
2441 size_t len = req->rw.len;
2442 struct io_mapped_ubuf *imu;
2443 u16 index, buf_index;
2447 /* attempt to use fixed buffers without having provided iovecs */
2448 if (unlikely(!ctx->user_bufs))
2451 buf_index = req->buf_index;
2452 if (unlikely(buf_index >= ctx->nr_user_bufs))
2455 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2456 imu = &ctx->user_bufs[index];
2457 buf_addr = req->rw.addr;
2460 if (buf_addr + len < buf_addr)
2462 /* not inside the mapped region */
2463 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2467 * May not be a start of buffer, set size appropriately
2468 * and advance us to the beginning.
2470 offset = buf_addr - imu->ubuf;
2471 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2475 * Don't use iov_iter_advance() here, as it's really slow for
2476 * using the latter parts of a big fixed buffer - it iterates
2477 * over each segment manually. We can cheat a bit here, because
2480 * 1) it's a BVEC iter, we set it up
2481 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2482 * first and last bvec
2484 * So just find our index, and adjust the iterator afterwards.
2485 * If the offset is within the first bvec (or the whole first
2486 * bvec, just use iov_iter_advance(). This makes it easier
2487 * since we can just skip the first segment, which may not
2488 * be PAGE_SIZE aligned.
2490 const struct bio_vec *bvec = imu->bvec;
2492 if (offset <= bvec->bv_len) {
2493 iov_iter_advance(iter, offset);
2495 unsigned long seg_skip;
2497 /* skip first vec */
2498 offset -= bvec->bv_len;
2499 seg_skip = 1 + (offset >> PAGE_SHIFT);
2501 iter->bvec = bvec + seg_skip;
2502 iter->nr_segs -= seg_skip;
2503 iter->count -= bvec->bv_len + offset;
2504 iter->iov_offset = offset & ~PAGE_MASK;
2511 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2514 mutex_unlock(&ctx->uring_lock);
2517 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2520 * "Normal" inline submissions always hold the uring_lock, since we
2521 * grab it from the system call. Same is true for the SQPOLL offload.
2522 * The only exception is when we've detached the request and issue it
2523 * from an async worker thread, grab the lock for that case.
2526 mutex_lock(&ctx->uring_lock);
2529 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2530 int bgid, struct io_buffer *kbuf,
2533 struct io_buffer *head;
2535 if (req->flags & REQ_F_BUFFER_SELECTED)
2538 io_ring_submit_lock(req->ctx, needs_lock);
2540 lockdep_assert_held(&req->ctx->uring_lock);
2542 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2544 if (!list_empty(&head->list)) {
2545 kbuf = list_last_entry(&head->list, struct io_buffer,
2547 list_del(&kbuf->list);
2550 idr_remove(&req->ctx->io_buffer_idr, bgid);
2552 if (*len > kbuf->len)
2555 kbuf = ERR_PTR(-ENOBUFS);
2558 io_ring_submit_unlock(req->ctx, needs_lock);
2563 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2566 struct io_buffer *kbuf;
2569 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2570 bgid = req->buf_index;
2571 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2574 req->rw.addr = (u64) (unsigned long) kbuf;
2575 req->flags |= REQ_F_BUFFER_SELECTED;
2576 return u64_to_user_ptr(kbuf->addr);
2579 #ifdef CONFIG_COMPAT
2580 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2583 struct compat_iovec __user *uiov;
2584 compat_ssize_t clen;
2588 uiov = u64_to_user_ptr(req->rw.addr);
2589 if (!access_ok(uiov, sizeof(*uiov)))
2591 if (__get_user(clen, &uiov->iov_len))
2597 buf = io_rw_buffer_select(req, &len, needs_lock);
2599 return PTR_ERR(buf);
2600 iov[0].iov_base = buf;
2601 iov[0].iov_len = (compat_size_t) len;
2606 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2609 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2613 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2616 len = iov[0].iov_len;
2619 buf = io_rw_buffer_select(req, &len, needs_lock);
2621 return PTR_ERR(buf);
2622 iov[0].iov_base = buf;
2623 iov[0].iov_len = len;
2627 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2630 if (req->flags & REQ_F_BUFFER_SELECTED) {
2631 struct io_buffer *kbuf;
2633 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2634 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2635 iov[0].iov_len = kbuf->len;
2640 else if (req->rw.len > 1)
2643 #ifdef CONFIG_COMPAT
2644 if (req->ctx->compat)
2645 return io_compat_import(req, iov, needs_lock);
2648 return __io_iov_buffer_select(req, iov, needs_lock);
2651 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2652 struct iovec **iovec, struct iov_iter *iter,
2655 void __user *buf = u64_to_user_ptr(req->rw.addr);
2656 size_t sqe_len = req->rw.len;
2660 opcode = req->opcode;
2661 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2663 return io_import_fixed(req, rw, iter);
2666 /* buffer index only valid with fixed read/write, or buffer select */
2667 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2670 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2671 if (req->flags & REQ_F_BUFFER_SELECT) {
2672 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2675 return PTR_ERR(buf);
2677 req->rw.len = sqe_len;
2680 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2682 return ret < 0 ? ret : sqe_len;
2686 struct io_async_rw *iorw = &req->io->rw;
2689 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2690 if (iorw->iov == iorw->fast_iov)
2695 if (req->flags & REQ_F_BUFFER_SELECT) {
2696 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2698 ret = (*iovec)->iov_len;
2699 iov_iter_init(iter, rw, *iovec, 1, ret);
2705 #ifdef CONFIG_COMPAT
2706 if (req->ctx->compat)
2707 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2711 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2715 * For files that don't have ->read_iter() and ->write_iter(), handle them
2716 * by looping over ->read() or ->write() manually.
2718 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2719 struct iov_iter *iter)
2724 * Don't support polled IO through this interface, and we can't
2725 * support non-blocking either. For the latter, this just causes
2726 * the kiocb to be handled from an async context.
2728 if (kiocb->ki_flags & IOCB_HIPRI)
2730 if (kiocb->ki_flags & IOCB_NOWAIT)
2733 while (iov_iter_count(iter)) {
2737 if (!iov_iter_is_bvec(iter)) {
2738 iovec = iov_iter_iovec(iter);
2740 /* fixed buffers import bvec */
2741 iovec.iov_base = kmap(iter->bvec->bv_page)
2743 iovec.iov_len = min(iter->count,
2744 iter->bvec->bv_len - iter->iov_offset);
2748 nr = file->f_op->read(file, iovec.iov_base,
2749 iovec.iov_len, &kiocb->ki_pos);
2751 nr = file->f_op->write(file, iovec.iov_base,
2752 iovec.iov_len, &kiocb->ki_pos);
2755 if (iov_iter_is_bvec(iter))
2756 kunmap(iter->bvec->bv_page);
2764 if (nr != iovec.iov_len)
2766 iov_iter_advance(iter, nr);
2772 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2773 struct iovec *iovec, struct iovec *fast_iov,
2774 struct iov_iter *iter)
2776 req->io->rw.nr_segs = iter->nr_segs;
2777 req->io->rw.size = io_size;
2778 req->io->rw.iov = iovec;
2779 if (!req->io->rw.iov) {
2780 req->io->rw.iov = req->io->rw.fast_iov;
2781 if (req->io->rw.iov != fast_iov)
2782 memcpy(req->io->rw.iov, fast_iov,
2783 sizeof(struct iovec) * iter->nr_segs);
2785 req->flags |= REQ_F_NEED_CLEANUP;
2789 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2791 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2792 return req->io == NULL;
2795 static int io_alloc_async_ctx(struct io_kiocb *req)
2797 if (!io_op_defs[req->opcode].async_ctx)
2800 return __io_alloc_async_ctx(req);
2803 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2804 struct iovec *iovec, struct iovec *fast_iov,
2805 struct iov_iter *iter)
2807 if (!io_op_defs[req->opcode].async_ctx)
2810 if (__io_alloc_async_ctx(req))
2813 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2818 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2819 bool force_nonblock)
2821 struct io_async_ctx *io;
2822 struct iov_iter iter;
2825 ret = io_prep_rw(req, sqe, force_nonblock);
2829 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2832 /* either don't need iovec imported or already have it */
2833 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2837 io->rw.iov = io->rw.fast_iov;
2839 ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2844 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2848 static void io_async_buf_cancel(struct callback_head *cb)
2850 struct io_async_rw *rw;
2851 struct io_kiocb *req;
2853 rw = container_of(cb, struct io_async_rw, task_work);
2854 req = rw->wpq.wait.private;
2855 __io_req_task_cancel(req, -ECANCELED);
2858 static void io_async_buf_retry(struct callback_head *cb)
2860 struct io_async_rw *rw;
2861 struct io_kiocb *req;
2863 rw = container_of(cb, struct io_async_rw, task_work);
2864 req = rw->wpq.wait.private;
2866 __io_req_task_submit(req);
2869 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2870 int sync, void *arg)
2872 struct wait_page_queue *wpq;
2873 struct io_kiocb *req = wait->private;
2874 struct io_async_rw *rw = &req->io->rw;
2875 struct wait_page_key *key = arg;
2876 struct task_struct *tsk;
2879 wpq = container_of(wait, struct wait_page_queue, wait);
2881 ret = wake_page_match(wpq, key);
2885 list_del_init(&wait->entry);
2887 init_task_work(&rw->task_work, io_async_buf_retry);
2888 /* submit ref gets dropped, acquire a new one */
2889 refcount_inc(&req->refs);
2891 ret = task_work_add(tsk, &rw->task_work, true);
2892 if (unlikely(ret)) {
2893 /* queue just for cancelation */
2894 init_task_work(&rw->task_work, io_async_buf_cancel);
2895 tsk = io_wq_get_task(req->ctx->io_wq);
2896 task_work_add(tsk, &rw->task_work, true);
2898 wake_up_process(tsk);
2902 static bool io_rw_should_retry(struct io_kiocb *req)
2904 struct kiocb *kiocb = &req->rw.kiocb;
2907 /* never retry for NOWAIT, we just complete with -EAGAIN */
2908 if (req->flags & REQ_F_NOWAIT)
2911 /* already tried, or we're doing O_DIRECT */
2912 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_WAITQ))
2915 * just use poll if we can, and don't attempt if the fs doesn't
2916 * support callback based unlocks
2918 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2922 * If request type doesn't require req->io to defer in general,
2923 * we need to allocate it here
2925 if (!req->io && __io_alloc_async_ctx(req))
2928 ret = kiocb_wait_page_queue_init(kiocb, &req->io->rw.wpq,
2929 io_async_buf_func, req);
2931 io_get_req_task(req);
2938 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
2940 if (req->file->f_op->read_iter)
2941 return call_read_iter(req->file, &req->rw.kiocb, iter);
2942 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
2945 static int io_read(struct io_kiocb *req, bool force_nonblock,
2946 struct io_comp_state *cs)
2948 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2949 struct kiocb *kiocb = &req->rw.kiocb;
2950 struct iov_iter iter;
2952 ssize_t io_size, ret;
2954 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2958 /* Ensure we clear previously set non-block flag */
2959 if (!force_nonblock)
2960 kiocb->ki_flags &= ~IOCB_NOWAIT;
2964 if (req->flags & REQ_F_LINK_HEAD)
2965 req->result = io_size;
2967 /* If the file doesn't support async, just async punt */
2968 if (force_nonblock && !io_file_supports_async(req->file, READ))
2971 iov_count = iov_iter_count(&iter);
2972 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2974 unsigned long nr_segs = iter.nr_segs;
2977 ret2 = io_iter_do_read(req, &iter);
2979 /* Catch -EAGAIN return for forced non-blocking submission */
2980 if (!force_nonblock || (ret2 != -EAGAIN && ret2 != -EIO)) {
2981 kiocb_done(kiocb, ret2, cs);
2983 iter.count = iov_count;
2984 iter.nr_segs = nr_segs;
2986 ret = io_setup_async_rw(req, io_size, iovec,
2987 inline_vecs, &iter);
2990 /* if we can retry, do so with the callbacks armed */
2991 if (io_rw_should_retry(req)) {
2992 ret2 = io_iter_do_read(req, &iter);
2993 if (ret2 == -EIOCBQUEUED) {
2995 } else if (ret2 != -EAGAIN) {
2996 kiocb_done(kiocb, ret2, cs);
3000 kiocb->ki_flags &= ~IOCB_WAITQ;
3005 if (!(req->flags & REQ_F_NEED_CLEANUP))
3010 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3011 bool force_nonblock)
3013 struct io_async_ctx *io;
3014 struct iov_iter iter;
3017 ret = io_prep_rw(req, sqe, force_nonblock);
3021 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3024 req->fsize = rlimit(RLIMIT_FSIZE);
3026 /* either don't need iovec imported or already have it */
3027 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3031 io->rw.iov = io->rw.fast_iov;
3033 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
3038 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
3042 static int io_write(struct io_kiocb *req, bool force_nonblock,
3043 struct io_comp_state *cs)
3045 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3046 struct kiocb *kiocb = &req->rw.kiocb;
3047 struct iov_iter iter;
3049 ssize_t ret, io_size;
3051 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
3055 /* Ensure we clear previously set non-block flag */
3056 if (!force_nonblock)
3057 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
3061 if (req->flags & REQ_F_LINK_HEAD)
3062 req->result = io_size;
3064 /* If the file doesn't support async, just async punt */
3065 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3068 /* file path doesn't support NOWAIT for non-direct_IO */
3069 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3070 (req->flags & REQ_F_ISREG))
3073 iov_count = iov_iter_count(&iter);
3074 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
3076 unsigned long nr_segs = iter.nr_segs;
3080 * Open-code file_start_write here to grab freeze protection,
3081 * which will be released by another thread in
3082 * io_complete_rw(). Fool lockdep by telling it the lock got
3083 * released so that it doesn't complain about the held lock when
3084 * we return to userspace.
3086 if (req->flags & REQ_F_ISREG) {
3087 __sb_start_write(file_inode(req->file)->i_sb,
3088 SB_FREEZE_WRITE, true);
3089 __sb_writers_release(file_inode(req->file)->i_sb,
3092 kiocb->ki_flags |= IOCB_WRITE;
3094 if (!force_nonblock)
3095 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3097 if (req->file->f_op->write_iter)
3098 ret2 = call_write_iter(req->file, kiocb, &iter);
3100 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
3102 if (!force_nonblock)
3103 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3106 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3107 * retry them without IOCB_NOWAIT.
3109 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3111 if (!force_nonblock || ret2 != -EAGAIN) {
3112 kiocb_done(kiocb, ret2, cs);
3114 iter.count = iov_count;
3115 iter.nr_segs = nr_segs;
3117 ret = io_setup_async_rw(req, io_size, iovec,
3118 inline_vecs, &iter);
3125 if (!(req->flags & REQ_F_NEED_CLEANUP))
3130 static int __io_splice_prep(struct io_kiocb *req,
3131 const struct io_uring_sqe *sqe)
3133 struct io_splice* sp = &req->splice;
3134 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3137 if (req->flags & REQ_F_NEED_CLEANUP)
3139 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3143 sp->len = READ_ONCE(sqe->len);
3144 sp->flags = READ_ONCE(sqe->splice_flags);
3146 if (unlikely(sp->flags & ~valid_flags))
3149 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
3150 (sp->flags & SPLICE_F_FD_IN_FIXED));
3153 req->flags |= REQ_F_NEED_CLEANUP;
3155 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3157 * Splice operation will be punted aync, and here need to
3158 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3160 io_req_init_async(req);
3161 req->work.flags |= IO_WQ_WORK_UNBOUND;
3167 static int io_tee_prep(struct io_kiocb *req,
3168 const struct io_uring_sqe *sqe)
3170 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3172 return __io_splice_prep(req, sqe);
3175 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3177 struct io_splice *sp = &req->splice;
3178 struct file *in = sp->file_in;
3179 struct file *out = sp->file_out;
3180 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3186 ret = do_tee(in, out, sp->len, flags);
3188 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3189 req->flags &= ~REQ_F_NEED_CLEANUP;
3192 req_set_fail_links(req);
3193 io_req_complete(req, ret);
3197 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3199 struct io_splice* sp = &req->splice;
3201 sp->off_in = READ_ONCE(sqe->splice_off_in);
3202 sp->off_out = READ_ONCE(sqe->off);
3203 return __io_splice_prep(req, sqe);
3206 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3208 struct io_splice *sp = &req->splice;
3209 struct file *in = sp->file_in;
3210 struct file *out = sp->file_out;
3211 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3212 loff_t *poff_in, *poff_out;
3218 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3219 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3222 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3224 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3225 req->flags &= ~REQ_F_NEED_CLEANUP;
3228 req_set_fail_links(req);
3229 io_req_complete(req, ret);
3234 * IORING_OP_NOP just posts a completion event, nothing else.
3236 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3238 struct io_ring_ctx *ctx = req->ctx;
3240 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3243 __io_req_complete(req, 0, 0, cs);
3247 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3249 struct io_ring_ctx *ctx = req->ctx;
3254 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3256 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3259 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3260 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3263 req->sync.off = READ_ONCE(sqe->off);
3264 req->sync.len = READ_ONCE(sqe->len);
3268 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3270 loff_t end = req->sync.off + req->sync.len;
3273 /* fsync always requires a blocking context */
3277 ret = vfs_fsync_range(req->file, req->sync.off,
3278 end > 0 ? end : LLONG_MAX,
3279 req->sync.flags & IORING_FSYNC_DATASYNC);
3281 req_set_fail_links(req);
3282 io_req_complete(req, ret);
3286 static int io_fallocate_prep(struct io_kiocb *req,
3287 const struct io_uring_sqe *sqe)
3289 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3291 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3294 req->sync.off = READ_ONCE(sqe->off);
3295 req->sync.len = READ_ONCE(sqe->addr);
3296 req->sync.mode = READ_ONCE(sqe->len);
3297 req->fsize = rlimit(RLIMIT_FSIZE);
3301 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3305 /* fallocate always requiring blocking context */
3309 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3310 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3312 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3314 req_set_fail_links(req);
3315 io_req_complete(req, ret);
3319 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3321 const char __user *fname;
3324 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3326 if (unlikely(sqe->ioprio || sqe->buf_index))
3328 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3331 /* open.how should be already initialised */
3332 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3333 req->open.how.flags |= O_LARGEFILE;
3335 req->open.dfd = READ_ONCE(sqe->fd);
3336 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3337 req->open.filename = getname(fname);
3338 if (IS_ERR(req->open.filename)) {
3339 ret = PTR_ERR(req->open.filename);
3340 req->open.filename = NULL;
3343 req->open.nofile = rlimit(RLIMIT_NOFILE);
3344 req->flags |= REQ_F_NEED_CLEANUP;
3348 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3352 if (req->flags & REQ_F_NEED_CLEANUP)
3354 mode = READ_ONCE(sqe->len);
3355 flags = READ_ONCE(sqe->open_flags);
3356 req->open.how = build_open_how(flags, mode);
3357 return __io_openat_prep(req, sqe);
3360 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3362 struct open_how __user *how;
3366 if (req->flags & REQ_F_NEED_CLEANUP)
3368 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3369 len = READ_ONCE(sqe->len);
3370 if (len < OPEN_HOW_SIZE_VER0)
3373 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3378 return __io_openat_prep(req, sqe);
3381 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3383 struct open_flags op;
3390 ret = build_open_flags(&req->open.how, &op);
3394 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3398 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3401 ret = PTR_ERR(file);
3403 fsnotify_open(file);
3404 fd_install(ret, file);
3407 putname(req->open.filename);
3408 req->flags &= ~REQ_F_NEED_CLEANUP;
3410 req_set_fail_links(req);
3411 io_req_complete(req, ret);
3415 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3417 return io_openat2(req, force_nonblock);
3420 static int io_remove_buffers_prep(struct io_kiocb *req,
3421 const struct io_uring_sqe *sqe)
3423 struct io_provide_buf *p = &req->pbuf;
3426 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3429 tmp = READ_ONCE(sqe->fd);
3430 if (!tmp || tmp > USHRT_MAX)
3433 memset(p, 0, sizeof(*p));
3435 p->bgid = READ_ONCE(sqe->buf_group);
3439 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3440 int bgid, unsigned nbufs)
3444 /* shouldn't happen */
3448 /* the head kbuf is the list itself */
3449 while (!list_empty(&buf->list)) {
3450 struct io_buffer *nxt;
3452 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3453 list_del(&nxt->list);
3460 idr_remove(&ctx->io_buffer_idr, bgid);
3465 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3466 struct io_comp_state *cs)
3468 struct io_provide_buf *p = &req->pbuf;
3469 struct io_ring_ctx *ctx = req->ctx;
3470 struct io_buffer *head;
3473 io_ring_submit_lock(ctx, !force_nonblock);
3475 lockdep_assert_held(&ctx->uring_lock);
3478 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3480 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3482 io_ring_submit_lock(ctx, !force_nonblock);
3484 req_set_fail_links(req);
3485 __io_req_complete(req, ret, 0, cs);
3489 static int io_provide_buffers_prep(struct io_kiocb *req,
3490 const struct io_uring_sqe *sqe)
3492 struct io_provide_buf *p = &req->pbuf;
3495 if (sqe->ioprio || sqe->rw_flags)
3498 tmp = READ_ONCE(sqe->fd);
3499 if (!tmp || tmp > USHRT_MAX)
3502 p->addr = READ_ONCE(sqe->addr);
3503 p->len = READ_ONCE(sqe->len);
3505 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3508 p->bgid = READ_ONCE(sqe->buf_group);
3509 tmp = READ_ONCE(sqe->off);
3510 if (tmp > USHRT_MAX)
3516 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3518 struct io_buffer *buf;
3519 u64 addr = pbuf->addr;
3520 int i, bid = pbuf->bid;
3522 for (i = 0; i < pbuf->nbufs; i++) {
3523 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3528 buf->len = pbuf->len;
3533 INIT_LIST_HEAD(&buf->list);
3536 list_add_tail(&buf->list, &(*head)->list);
3540 return i ? i : -ENOMEM;
3543 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3544 struct io_comp_state *cs)
3546 struct io_provide_buf *p = &req->pbuf;
3547 struct io_ring_ctx *ctx = req->ctx;
3548 struct io_buffer *head, *list;
3551 io_ring_submit_lock(ctx, !force_nonblock);
3553 lockdep_assert_held(&ctx->uring_lock);
3555 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3557 ret = io_add_buffers(p, &head);
3562 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3565 __io_remove_buffers(ctx, head, p->bgid, -1U);
3570 io_ring_submit_unlock(ctx, !force_nonblock);
3572 req_set_fail_links(req);
3573 __io_req_complete(req, ret, 0, cs);
3577 static int io_epoll_ctl_prep(struct io_kiocb *req,
3578 const struct io_uring_sqe *sqe)
3580 #if defined(CONFIG_EPOLL)
3581 if (sqe->ioprio || sqe->buf_index)
3583 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3586 req->epoll.epfd = READ_ONCE(sqe->fd);
3587 req->epoll.op = READ_ONCE(sqe->len);
3588 req->epoll.fd = READ_ONCE(sqe->off);
3590 if (ep_op_has_event(req->epoll.op)) {
3591 struct epoll_event __user *ev;
3593 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3594 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3604 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3605 struct io_comp_state *cs)
3607 #if defined(CONFIG_EPOLL)
3608 struct io_epoll *ie = &req->epoll;
3611 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3612 if (force_nonblock && ret == -EAGAIN)
3616 req_set_fail_links(req);
3617 __io_req_complete(req, ret, 0, cs);
3624 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3626 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3627 if (sqe->ioprio || sqe->buf_index || sqe->off)
3629 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3632 req->madvise.addr = READ_ONCE(sqe->addr);
3633 req->madvise.len = READ_ONCE(sqe->len);
3634 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3641 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3643 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3644 struct io_madvise *ma = &req->madvise;
3650 ret = do_madvise(ma->addr, ma->len, ma->advice);
3652 req_set_fail_links(req);
3653 io_req_complete(req, ret);
3660 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3662 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3664 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3667 req->fadvise.offset = READ_ONCE(sqe->off);
3668 req->fadvise.len = READ_ONCE(sqe->len);
3669 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3673 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3675 struct io_fadvise *fa = &req->fadvise;
3678 if (force_nonblock) {
3679 switch (fa->advice) {
3680 case POSIX_FADV_NORMAL:
3681 case POSIX_FADV_RANDOM:
3682 case POSIX_FADV_SEQUENTIAL:
3689 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3691 req_set_fail_links(req);
3692 io_req_complete(req, ret);
3696 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3698 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3700 if (sqe->ioprio || sqe->buf_index)
3702 if (req->flags & REQ_F_FIXED_FILE)
3705 req->statx.dfd = READ_ONCE(sqe->fd);
3706 req->statx.mask = READ_ONCE(sqe->len);
3707 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
3708 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3709 req->statx.flags = READ_ONCE(sqe->statx_flags);
3714 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3716 struct io_statx *ctx = &req->statx;
3719 if (force_nonblock) {
3720 /* only need file table for an actual valid fd */
3721 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3722 req->flags |= REQ_F_NO_FILE_TABLE;
3726 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3730 req_set_fail_links(req);
3731 io_req_complete(req, ret);
3735 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3738 * If we queue this for async, it must not be cancellable. That would
3739 * leave the 'file' in an undeterminate state, and here need to modify
3740 * io_wq_work.flags, so initialize io_wq_work firstly.
3742 io_req_init_async(req);
3743 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3745 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3747 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3748 sqe->rw_flags || sqe->buf_index)
3750 if (req->flags & REQ_F_FIXED_FILE)
3753 req->close.fd = READ_ONCE(sqe->fd);
3754 if ((req->file && req->file->f_op == &io_uring_fops) ||
3755 req->close.fd == req->ctx->ring_fd)
3758 req->close.put_file = NULL;
3762 static int io_close(struct io_kiocb *req, bool force_nonblock,
3763 struct io_comp_state *cs)
3765 struct io_close *close = &req->close;
3768 /* might be already done during nonblock submission */
3769 if (!close->put_file) {
3770 ret = __close_fd_get_file(close->fd, &close->put_file);
3772 return (ret == -ENOENT) ? -EBADF : ret;
3775 /* if the file has a flush method, be safe and punt to async */
3776 if (close->put_file->f_op->flush && force_nonblock) {
3777 /* was never set, but play safe */
3778 req->flags &= ~REQ_F_NOWAIT;
3779 /* avoid grabbing files - we don't need the files */
3780 req->flags |= REQ_F_NO_FILE_TABLE;
3784 /* No ->flush() or already async, safely close from here */
3785 ret = filp_close(close->put_file, req->work.files);
3787 req_set_fail_links(req);
3788 fput(close->put_file);
3789 close->put_file = NULL;
3790 __io_req_complete(req, ret, 0, cs);
3794 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3796 struct io_ring_ctx *ctx = req->ctx;
3801 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3803 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3806 req->sync.off = READ_ONCE(sqe->off);
3807 req->sync.len = READ_ONCE(sqe->len);
3808 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3812 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3816 /* sync_file_range always requires a blocking context */
3820 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3823 req_set_fail_links(req);
3824 io_req_complete(req, ret);
3828 #if defined(CONFIG_NET)
3829 static int io_setup_async_msg(struct io_kiocb *req,
3830 struct io_async_msghdr *kmsg)
3834 if (io_alloc_async_ctx(req)) {
3835 if (kmsg->iov != kmsg->fast_iov)
3839 req->flags |= REQ_F_NEED_CLEANUP;
3840 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3844 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3846 struct io_sr_msg *sr = &req->sr_msg;
3847 struct io_async_ctx *io = req->io;
3850 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3853 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3854 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3855 sr->len = READ_ONCE(sqe->len);
3857 #ifdef CONFIG_COMPAT
3858 if (req->ctx->compat)
3859 sr->msg_flags |= MSG_CMSG_COMPAT;
3862 if (!io || req->opcode == IORING_OP_SEND)
3864 /* iovec is already imported */
3865 if (req->flags & REQ_F_NEED_CLEANUP)
3868 io->msg.iov = io->msg.fast_iov;
3869 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3872 req->flags |= REQ_F_NEED_CLEANUP;
3876 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
3877 struct io_comp_state *cs)
3879 struct io_async_msghdr *kmsg = NULL;
3880 struct socket *sock;
3883 sock = sock_from_file(req->file, &ret);
3885 struct io_async_ctx io;
3889 kmsg = &req->io->msg;
3890 kmsg->msg.msg_name = &req->io->msg.addr;
3891 /* if iov is set, it's allocated already */
3893 kmsg->iov = kmsg->fast_iov;
3894 kmsg->msg.msg_iter.iov = kmsg->iov;
3896 struct io_sr_msg *sr = &req->sr_msg;
3899 kmsg->msg.msg_name = &io.msg.addr;
3901 io.msg.iov = io.msg.fast_iov;
3902 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3903 sr->msg_flags, &io.msg.iov);
3908 flags = req->sr_msg.msg_flags;
3909 if (flags & MSG_DONTWAIT)
3910 req->flags |= REQ_F_NOWAIT;
3911 else if (force_nonblock)
3912 flags |= MSG_DONTWAIT;
3914 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3915 if (force_nonblock && ret == -EAGAIN)
3916 return io_setup_async_msg(req, kmsg);
3917 if (ret == -ERESTARTSYS)
3921 if (kmsg && kmsg->iov != kmsg->fast_iov)
3923 req->flags &= ~REQ_F_NEED_CLEANUP;
3925 req_set_fail_links(req);
3926 __io_req_complete(req, ret, 0, cs);
3930 static int io_send(struct io_kiocb *req, bool force_nonblock,
3931 struct io_comp_state *cs)
3933 struct socket *sock;
3936 sock = sock_from_file(req->file, &ret);
3938 struct io_sr_msg *sr = &req->sr_msg;
3943 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3948 msg.msg_name = NULL;
3949 msg.msg_control = NULL;
3950 msg.msg_controllen = 0;
3951 msg.msg_namelen = 0;
3953 flags = req->sr_msg.msg_flags;
3954 if (flags & MSG_DONTWAIT)
3955 req->flags |= REQ_F_NOWAIT;
3956 else if (force_nonblock)
3957 flags |= MSG_DONTWAIT;
3959 msg.msg_flags = flags;
3960 ret = sock_sendmsg(sock, &msg);
3961 if (force_nonblock && ret == -EAGAIN)
3963 if (ret == -ERESTARTSYS)
3968 req_set_fail_links(req);
3969 __io_req_complete(req, ret, 0, cs);
3973 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3975 struct io_sr_msg *sr = &req->sr_msg;
3976 struct iovec __user *uiov;
3980 ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
3985 if (req->flags & REQ_F_BUFFER_SELECT) {
3988 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
3990 sr->len = io->msg.iov[0].iov_len;
3991 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
3995 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
3996 &io->msg.iov, &io->msg.msg.msg_iter);
4004 #ifdef CONFIG_COMPAT
4005 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4006 struct io_async_ctx *io)
4008 struct compat_msghdr __user *msg_compat;
4009 struct io_sr_msg *sr = &req->sr_msg;
4010 struct compat_iovec __user *uiov;
4015 msg_compat = (struct compat_msghdr __user *) sr->msg;
4016 ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
4021 uiov = compat_ptr(ptr);
4022 if (req->flags & REQ_F_BUFFER_SELECT) {
4023 compat_ssize_t clen;
4027 if (!access_ok(uiov, sizeof(*uiov)))
4029 if (__get_user(clen, &uiov->iov_len))
4033 sr->len = io->msg.iov[0].iov_len;
4036 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
4038 &io->msg.msg.msg_iter);
4047 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
4049 io->msg.iov = io->msg.fast_iov;
4051 #ifdef CONFIG_COMPAT
4052 if (req->ctx->compat)
4053 return __io_compat_recvmsg_copy_hdr(req, io);
4056 return __io_recvmsg_copy_hdr(req, io);
4059 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4060 int *cflags, bool needs_lock)
4062 struct io_sr_msg *sr = &req->sr_msg;
4063 struct io_buffer *kbuf;
4065 if (!(req->flags & REQ_F_BUFFER_SELECT))
4068 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4073 req->flags |= REQ_F_BUFFER_SELECTED;
4075 *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
4076 *cflags |= IORING_CQE_F_BUFFER;
4080 static int io_recvmsg_prep(struct io_kiocb *req,
4081 const struct io_uring_sqe *sqe)
4083 struct io_sr_msg *sr = &req->sr_msg;
4084 struct io_async_ctx *io = req->io;
4087 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4090 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4091 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4092 sr->len = READ_ONCE(sqe->len);
4093 sr->bgid = READ_ONCE(sqe->buf_group);
4095 #ifdef CONFIG_COMPAT
4096 if (req->ctx->compat)
4097 sr->msg_flags |= MSG_CMSG_COMPAT;
4100 if (!io || req->opcode == IORING_OP_RECV)
4102 /* iovec is already imported */
4103 if (req->flags & REQ_F_NEED_CLEANUP)
4106 ret = io_recvmsg_copy_hdr(req, io);
4108 req->flags |= REQ_F_NEED_CLEANUP;
4112 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4113 struct io_comp_state *cs)
4115 struct io_async_msghdr *kmsg = NULL;
4116 struct socket *sock;
4117 int ret, cflags = 0;
4119 sock = sock_from_file(req->file, &ret);
4121 struct io_buffer *kbuf;
4122 struct io_async_ctx io;
4126 kmsg = &req->io->msg;
4127 kmsg->msg.msg_name = &req->io->msg.addr;
4128 /* if iov is set, it's allocated already */
4130 kmsg->iov = kmsg->fast_iov;
4131 kmsg->msg.msg_iter.iov = kmsg->iov;
4134 kmsg->msg.msg_name = &io.msg.addr;
4136 ret = io_recvmsg_copy_hdr(req, &io);
4141 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4143 return PTR_ERR(kbuf);
4145 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4146 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4147 1, req->sr_msg.len);
4150 flags = req->sr_msg.msg_flags;
4151 if (flags & MSG_DONTWAIT)
4152 req->flags |= REQ_F_NOWAIT;
4153 else if (force_nonblock)
4154 flags |= MSG_DONTWAIT;
4156 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
4157 kmsg->uaddr, flags);
4158 if (force_nonblock && ret == -EAGAIN)
4159 return io_setup_async_msg(req, kmsg);
4160 if (ret == -ERESTARTSYS)
4164 if (kmsg && kmsg->iov != kmsg->fast_iov)
4166 req->flags &= ~REQ_F_NEED_CLEANUP;
4168 req_set_fail_links(req);
4169 __io_req_complete(req, ret, cflags, cs);
4173 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4174 struct io_comp_state *cs)
4176 struct io_buffer *kbuf = NULL;
4177 struct socket *sock;
4178 int ret, cflags = 0;
4180 sock = sock_from_file(req->file, &ret);
4182 struct io_sr_msg *sr = &req->sr_msg;
4183 void __user *buf = sr->buf;
4188 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4190 return PTR_ERR(kbuf);
4192 buf = u64_to_user_ptr(kbuf->addr);
4194 ret = import_single_range(READ, buf, sr->len, &iov,
4201 req->flags |= REQ_F_NEED_CLEANUP;
4202 msg.msg_name = NULL;
4203 msg.msg_control = NULL;
4204 msg.msg_controllen = 0;
4205 msg.msg_namelen = 0;
4206 msg.msg_iocb = NULL;
4209 flags = req->sr_msg.msg_flags;
4210 if (flags & MSG_DONTWAIT)
4211 req->flags |= REQ_F_NOWAIT;
4212 else if (force_nonblock)
4213 flags |= MSG_DONTWAIT;
4215 ret = sock_recvmsg(sock, &msg, flags);
4216 if (force_nonblock && ret == -EAGAIN)
4218 if (ret == -ERESTARTSYS)
4223 req->flags &= ~REQ_F_NEED_CLEANUP;
4225 req_set_fail_links(req);
4226 __io_req_complete(req, ret, cflags, cs);
4230 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4232 struct io_accept *accept = &req->accept;
4234 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4236 if (sqe->ioprio || sqe->len || sqe->buf_index)
4239 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4240 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4241 accept->flags = READ_ONCE(sqe->accept_flags);
4242 accept->nofile = rlimit(RLIMIT_NOFILE);
4246 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4247 struct io_comp_state *cs)
4249 struct io_accept *accept = &req->accept;
4250 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4253 if (req->file->f_flags & O_NONBLOCK)
4254 req->flags |= REQ_F_NOWAIT;
4256 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4257 accept->addr_len, accept->flags,
4259 if (ret == -EAGAIN && force_nonblock)
4262 if (ret == -ERESTARTSYS)
4264 req_set_fail_links(req);
4266 __io_req_complete(req, ret, 0, cs);
4270 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4272 struct io_connect *conn = &req->connect;
4273 struct io_async_ctx *io = req->io;
4275 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4277 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4280 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4281 conn->addr_len = READ_ONCE(sqe->addr2);
4286 return move_addr_to_kernel(conn->addr, conn->addr_len,
4287 &io->connect.address);
4290 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4291 struct io_comp_state *cs)
4293 struct io_async_ctx __io, *io;
4294 unsigned file_flags;
4300 ret = move_addr_to_kernel(req->connect.addr,
4301 req->connect.addr_len,
4302 &__io.connect.address);
4308 file_flags = force_nonblock ? O_NONBLOCK : 0;
4310 ret = __sys_connect_file(req->file, &io->connect.address,
4311 req->connect.addr_len, file_flags);
4312 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4315 if (io_alloc_async_ctx(req)) {
4319 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4322 if (ret == -ERESTARTSYS)
4326 req_set_fail_links(req);
4327 __io_req_complete(req, ret, 0, cs);
4330 #else /* !CONFIG_NET */
4331 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4336 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4337 struct io_comp_state *cs)
4342 static int io_send(struct io_kiocb *req, bool force_nonblock,
4343 struct io_comp_state *cs)
4348 static int io_recvmsg_prep(struct io_kiocb *req,
4349 const struct io_uring_sqe *sqe)
4354 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4355 struct io_comp_state *cs)
4360 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4361 struct io_comp_state *cs)
4366 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4371 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4372 struct io_comp_state *cs)
4377 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4382 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4383 struct io_comp_state *cs)
4387 #endif /* CONFIG_NET */
4389 struct io_poll_table {
4390 struct poll_table_struct pt;
4391 struct io_kiocb *req;
4395 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4396 __poll_t mask, task_work_func_t func)
4398 struct task_struct *tsk;
4401 /* for instances that support it check for an event match first: */
4402 if (mask && !(mask & poll->events))
4405 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4407 list_del_init(&poll->wait.entry);
4411 init_task_work(&req->task_work, func);
4413 * If this fails, then the task is exiting. When a task exits, the
4414 * work gets canceled, so just cancel this request as well instead
4415 * of executing it. We can't safely execute it anyway, as we may not
4416 * have the needed state needed for it anyway.
4418 ret = task_work_add(tsk, &req->task_work, true);
4419 if (unlikely(ret)) {
4420 WRITE_ONCE(poll->canceled, true);
4421 tsk = io_wq_get_task(req->ctx->io_wq);
4422 task_work_add(tsk, &req->task_work, true);
4424 wake_up_process(tsk);
4428 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4429 __acquires(&req->ctx->completion_lock)
4431 struct io_ring_ctx *ctx = req->ctx;
4433 if (!req->result && !READ_ONCE(poll->canceled)) {
4434 struct poll_table_struct pt = { ._key = poll->events };
4436 req->result = vfs_poll(req->file, &pt) & poll->events;
4439 spin_lock_irq(&ctx->completion_lock);
4440 if (!req->result && !READ_ONCE(poll->canceled)) {
4441 add_wait_queue(poll->head, &poll->wait);
4448 static void io_poll_remove_double(struct io_kiocb *req)
4450 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4452 lockdep_assert_held(&req->ctx->completion_lock);
4454 if (poll && poll->head) {
4455 struct wait_queue_head *head = poll->head;
4457 spin_lock(&head->lock);
4458 list_del_init(&poll->wait.entry);
4459 if (poll->wait.private)
4460 refcount_dec(&req->refs);
4462 spin_unlock(&head->lock);
4466 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4468 struct io_ring_ctx *ctx = req->ctx;
4470 io_poll_remove_double(req);
4471 req->poll.done = true;
4472 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4473 io_commit_cqring(ctx);
4476 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4478 struct io_ring_ctx *ctx = req->ctx;
4480 if (io_poll_rewait(req, &req->poll)) {
4481 spin_unlock_irq(&ctx->completion_lock);
4485 hash_del(&req->hash_node);
4486 io_poll_complete(req, req->result, 0);
4487 req->flags |= REQ_F_COMP_LOCKED;
4488 io_put_req_find_next(req, nxt);
4489 spin_unlock_irq(&ctx->completion_lock);
4491 io_cqring_ev_posted(ctx);
4494 static void io_poll_task_func(struct callback_head *cb)
4496 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4497 struct io_kiocb *nxt = NULL;
4499 io_poll_task_handler(req, &nxt);
4501 struct io_ring_ctx *ctx = nxt->ctx;
4503 mutex_lock(&ctx->uring_lock);
4504 __io_queue_sqe(nxt, NULL, NULL);
4505 mutex_unlock(&ctx->uring_lock);
4509 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4510 int sync, void *key)
4512 struct io_kiocb *req = wait->private;
4513 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4514 __poll_t mask = key_to_poll(key);
4516 /* for instances that support it check for an event match first: */
4517 if (mask && !(mask & poll->events))
4520 if (req->poll.head) {
4523 spin_lock(&req->poll.head->lock);
4524 done = list_empty(&req->poll.wait.entry);
4526 list_del_init(&req->poll.wait.entry);
4527 spin_unlock(&req->poll.head->lock);
4529 __io_async_wake(req, poll, mask, io_poll_task_func);
4531 refcount_dec(&req->refs);
4535 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4536 wait_queue_func_t wake_func)
4540 poll->canceled = false;
4541 poll->events = events;
4542 INIT_LIST_HEAD(&poll->wait.entry);
4543 init_waitqueue_func_entry(&poll->wait, wake_func);
4546 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4547 struct wait_queue_head *head)
4549 struct io_kiocb *req = pt->req;
4552 * If poll->head is already set, it's because the file being polled
4553 * uses multiple waitqueues for poll handling (eg one for read, one
4554 * for write). Setup a separate io_poll_iocb if this happens.
4556 if (unlikely(poll->head)) {
4557 /* already have a 2nd entry, fail a third attempt */
4559 pt->error = -EINVAL;
4562 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4564 pt->error = -ENOMEM;
4567 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4568 refcount_inc(&req->refs);
4569 poll->wait.private = req;
4570 req->io = (void *) poll;
4576 if (poll->events & EPOLLEXCLUSIVE)
4577 add_wait_queue_exclusive(head, &poll->wait);
4579 add_wait_queue(head, &poll->wait);
4582 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4583 struct poll_table_struct *p)
4585 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4587 __io_queue_proc(&pt->req->apoll->poll, pt, head);
4590 static void io_async_task_func(struct callback_head *cb)
4592 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4593 struct async_poll *apoll = req->apoll;
4594 struct io_ring_ctx *ctx = req->ctx;
4595 bool canceled = false;
4597 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4599 if (io_poll_rewait(req, &apoll->poll)) {
4600 spin_unlock_irq(&ctx->completion_lock);
4604 /* If req is still hashed, it cannot have been canceled. Don't check. */
4605 if (hash_hashed(&req->hash_node)) {
4606 hash_del(&req->hash_node);
4608 canceled = READ_ONCE(apoll->poll.canceled);
4610 io_cqring_fill_event(req, -ECANCELED);
4611 io_commit_cqring(ctx);
4615 spin_unlock_irq(&ctx->completion_lock);
4617 /* restore ->work in case we need to retry again */
4618 if (req->flags & REQ_F_WORK_INITIALIZED)
4619 memcpy(&req->work, &apoll->work, sizeof(req->work));
4623 __set_current_state(TASK_RUNNING);
4624 if (io_sq_thread_acquire_mm(ctx, req)) {
4625 io_cqring_add_event(req, -EFAULT, 0);
4628 mutex_lock(&ctx->uring_lock);
4629 __io_queue_sqe(req, NULL, NULL);
4630 mutex_unlock(&ctx->uring_lock);
4632 io_cqring_ev_posted(ctx);
4634 req_set_fail_links(req);
4635 io_double_put_req(req);
4639 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4642 struct io_kiocb *req = wait->private;
4643 struct io_poll_iocb *poll = &req->apoll->poll;
4645 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4648 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4651 static void io_poll_req_insert(struct io_kiocb *req)
4653 struct io_ring_ctx *ctx = req->ctx;
4654 struct hlist_head *list;
4656 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4657 hlist_add_head(&req->hash_node, list);
4660 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4661 struct io_poll_iocb *poll,
4662 struct io_poll_table *ipt, __poll_t mask,
4663 wait_queue_func_t wake_func)
4664 __acquires(&ctx->completion_lock)
4666 struct io_ring_ctx *ctx = req->ctx;
4667 bool cancel = false;
4669 io_init_poll_iocb(poll, mask, wake_func);
4670 poll->file = req->file;
4671 poll->wait.private = req;
4673 ipt->pt._key = mask;
4675 ipt->error = -EINVAL;
4677 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4679 spin_lock_irq(&ctx->completion_lock);
4680 if (likely(poll->head)) {
4681 spin_lock(&poll->head->lock);
4682 if (unlikely(list_empty(&poll->wait.entry))) {
4688 if (mask || ipt->error)
4689 list_del_init(&poll->wait.entry);
4691 WRITE_ONCE(poll->canceled, true);
4692 else if (!poll->done) /* actually waiting for an event */
4693 io_poll_req_insert(req);
4694 spin_unlock(&poll->head->lock);
4700 static bool io_arm_poll_handler(struct io_kiocb *req)
4702 const struct io_op_def *def = &io_op_defs[req->opcode];
4703 struct io_ring_ctx *ctx = req->ctx;
4704 struct async_poll *apoll;
4705 struct io_poll_table ipt;
4709 if (!req->file || !file_can_poll(req->file))
4711 if (req->flags & REQ_F_POLLED)
4713 if (!def->pollin && !def->pollout)
4716 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4717 if (unlikely(!apoll))
4720 req->flags |= REQ_F_POLLED;
4721 if (req->flags & REQ_F_WORK_INITIALIZED)
4722 memcpy(&apoll->work, &req->work, sizeof(req->work));
4723 had_io = req->io != NULL;
4725 io_get_req_task(req);
4727 INIT_HLIST_NODE(&req->hash_node);
4731 mask |= POLLIN | POLLRDNORM;
4733 mask |= POLLOUT | POLLWRNORM;
4734 mask |= POLLERR | POLLPRI;
4736 ipt.pt._qproc = io_async_queue_proc;
4738 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4742 /* only remove double add if we did it here */
4744 io_poll_remove_double(req);
4745 spin_unlock_irq(&ctx->completion_lock);
4746 if (req->flags & REQ_F_WORK_INITIALIZED)
4747 memcpy(&req->work, &apoll->work, sizeof(req->work));
4751 spin_unlock_irq(&ctx->completion_lock);
4752 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4753 apoll->poll.events);
4757 static bool __io_poll_remove_one(struct io_kiocb *req,
4758 struct io_poll_iocb *poll)
4760 bool do_complete = false;
4762 spin_lock(&poll->head->lock);
4763 WRITE_ONCE(poll->canceled, true);
4764 if (!list_empty(&poll->wait.entry)) {
4765 list_del_init(&poll->wait.entry);
4768 spin_unlock(&poll->head->lock);
4769 hash_del(&req->hash_node);
4773 static bool io_poll_remove_one(struct io_kiocb *req)
4777 if (req->opcode == IORING_OP_POLL_ADD) {
4778 io_poll_remove_double(req);
4779 do_complete = __io_poll_remove_one(req, &req->poll);
4781 struct async_poll *apoll = req->apoll;
4783 /* non-poll requests have submit ref still */
4784 do_complete = __io_poll_remove_one(req, &apoll->poll);
4788 * restore ->work because we will call
4789 * io_req_work_drop_env below when dropping the
4792 if (req->flags & REQ_F_WORK_INITIALIZED)
4793 memcpy(&req->work, &apoll->work,
4800 io_cqring_fill_event(req, -ECANCELED);
4801 io_commit_cqring(req->ctx);
4802 req->flags |= REQ_F_COMP_LOCKED;
4809 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4811 struct hlist_node *tmp;
4812 struct io_kiocb *req;
4815 spin_lock_irq(&ctx->completion_lock);
4816 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4817 struct hlist_head *list;
4819 list = &ctx->cancel_hash[i];
4820 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4821 posted += io_poll_remove_one(req);
4823 spin_unlock_irq(&ctx->completion_lock);
4826 io_cqring_ev_posted(ctx);
4829 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4831 struct hlist_head *list;
4832 struct io_kiocb *req;
4834 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4835 hlist_for_each_entry(req, list, hash_node) {
4836 if (sqe_addr != req->user_data)
4838 if (io_poll_remove_one(req))
4846 static int io_poll_remove_prep(struct io_kiocb *req,
4847 const struct io_uring_sqe *sqe)
4849 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4851 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4855 req->poll.addr = READ_ONCE(sqe->addr);
4860 * Find a running poll command that matches one specified in sqe->addr,
4861 * and remove it if found.
4863 static int io_poll_remove(struct io_kiocb *req)
4865 struct io_ring_ctx *ctx = req->ctx;
4869 addr = req->poll.addr;
4870 spin_lock_irq(&ctx->completion_lock);
4871 ret = io_poll_cancel(ctx, addr);
4872 spin_unlock_irq(&ctx->completion_lock);
4875 req_set_fail_links(req);
4876 io_req_complete(req, ret);
4880 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4883 struct io_kiocb *req = wait->private;
4884 struct io_poll_iocb *poll = &req->poll;
4886 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4889 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4890 struct poll_table_struct *p)
4892 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4894 __io_queue_proc(&pt->req->poll, pt, head);
4897 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4899 struct io_poll_iocb *poll = &req->poll;
4902 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4904 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4909 events = READ_ONCE(sqe->poll32_events);
4911 events = swahw32(events);
4913 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
4914 (events & EPOLLEXCLUSIVE);
4916 io_get_req_task(req);
4920 static int io_poll_add(struct io_kiocb *req)
4922 struct io_poll_iocb *poll = &req->poll;
4923 struct io_ring_ctx *ctx = req->ctx;
4924 struct io_poll_table ipt;
4927 INIT_HLIST_NODE(&req->hash_node);
4928 INIT_LIST_HEAD(&req->list);
4929 ipt.pt._qproc = io_poll_queue_proc;
4931 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4934 if (mask) { /* no async, we'd stolen it */
4936 io_poll_complete(req, mask, 0);
4938 spin_unlock_irq(&ctx->completion_lock);
4941 io_cqring_ev_posted(ctx);
4947 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4949 struct io_timeout_data *data = container_of(timer,
4950 struct io_timeout_data, timer);
4951 struct io_kiocb *req = data->req;
4952 struct io_ring_ctx *ctx = req->ctx;
4953 unsigned long flags;
4955 atomic_inc(&ctx->cq_timeouts);
4957 spin_lock_irqsave(&ctx->completion_lock, flags);
4959 * We could be racing with timeout deletion. If the list is empty,
4960 * then timeout lookup already found it and will be handling it.
4962 if (!list_empty(&req->list))
4963 list_del_init(&req->list);
4965 io_cqring_fill_event(req, -ETIME);
4966 io_commit_cqring(ctx);
4967 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4969 io_cqring_ev_posted(ctx);
4970 req_set_fail_links(req);
4972 return HRTIMER_NORESTART;
4975 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4977 struct io_kiocb *req;
4980 list_for_each_entry(req, &ctx->timeout_list, list) {
4981 if (user_data == req->user_data) {
4982 list_del_init(&req->list);
4991 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
4995 req_set_fail_links(req);
4996 io_cqring_fill_event(req, -ECANCELED);
5001 static int io_timeout_remove_prep(struct io_kiocb *req,
5002 const struct io_uring_sqe *sqe)
5004 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5006 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
5009 req->timeout.addr = READ_ONCE(sqe->addr);
5010 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
5011 if (req->timeout.flags)
5018 * Remove or update an existing timeout command
5020 static int io_timeout_remove(struct io_kiocb *req)
5022 struct io_ring_ctx *ctx = req->ctx;
5025 spin_lock_irq(&ctx->completion_lock);
5026 ret = io_timeout_cancel(ctx, req->timeout.addr);
5028 io_cqring_fill_event(req, ret);
5029 io_commit_cqring(ctx);
5030 spin_unlock_irq(&ctx->completion_lock);
5031 io_cqring_ev_posted(ctx);
5033 req_set_fail_links(req);
5038 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5039 bool is_timeout_link)
5041 struct io_timeout_data *data;
5043 u32 off = READ_ONCE(sqe->off);
5045 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5047 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5049 if (off && is_timeout_link)
5051 flags = READ_ONCE(sqe->timeout_flags);
5052 if (flags & ~IORING_TIMEOUT_ABS)
5055 req->timeout.off = off;
5057 if (!req->io && io_alloc_async_ctx(req))
5060 data = &req->io->timeout;
5062 req->flags |= REQ_F_TIMEOUT;
5064 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5067 if (flags & IORING_TIMEOUT_ABS)
5068 data->mode = HRTIMER_MODE_ABS;
5070 data->mode = HRTIMER_MODE_REL;
5072 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5076 static int io_timeout(struct io_kiocb *req)
5078 struct io_ring_ctx *ctx = req->ctx;
5079 struct io_timeout_data *data = &req->io->timeout;
5080 struct list_head *entry;
5081 u32 tail, off = req->timeout.off;
5083 spin_lock_irq(&ctx->completion_lock);
5086 * sqe->off holds how many events that need to occur for this
5087 * timeout event to be satisfied. If it isn't set, then this is
5088 * a pure timeout request, sequence isn't used.
5091 req->flags |= REQ_F_TIMEOUT_NOSEQ;
5092 entry = ctx->timeout_list.prev;
5096 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5097 req->timeout.target_seq = tail + off;
5100 * Insertion sort, ensuring the first entry in the list is always
5101 * the one we need first.
5103 list_for_each_prev(entry, &ctx->timeout_list) {
5104 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5106 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
5108 /* nxt.seq is behind @tail, otherwise would've been completed */
5109 if (off >= nxt->timeout.target_seq - tail)
5113 list_add(&req->list, entry);
5114 data->timer.function = io_timeout_fn;
5115 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5116 spin_unlock_irq(&ctx->completion_lock);
5120 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5122 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5124 return req->user_data == (unsigned long) data;
5127 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5129 enum io_wq_cancel cancel_ret;
5132 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5133 switch (cancel_ret) {
5134 case IO_WQ_CANCEL_OK:
5137 case IO_WQ_CANCEL_RUNNING:
5140 case IO_WQ_CANCEL_NOTFOUND:
5148 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5149 struct io_kiocb *req, __u64 sqe_addr,
5152 unsigned long flags;
5155 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5156 if (ret != -ENOENT) {
5157 spin_lock_irqsave(&ctx->completion_lock, flags);
5161 spin_lock_irqsave(&ctx->completion_lock, flags);
5162 ret = io_timeout_cancel(ctx, sqe_addr);
5165 ret = io_poll_cancel(ctx, sqe_addr);
5169 io_cqring_fill_event(req, ret);
5170 io_commit_cqring(ctx);
5171 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5172 io_cqring_ev_posted(ctx);
5175 req_set_fail_links(req);
5179 static int io_async_cancel_prep(struct io_kiocb *req,
5180 const struct io_uring_sqe *sqe)
5182 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5184 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
5188 req->cancel.addr = READ_ONCE(sqe->addr);
5192 static int io_async_cancel(struct io_kiocb *req)
5194 struct io_ring_ctx *ctx = req->ctx;
5196 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5200 static int io_files_update_prep(struct io_kiocb *req,
5201 const struct io_uring_sqe *sqe)
5203 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
5206 req->files_update.offset = READ_ONCE(sqe->off);
5207 req->files_update.nr_args = READ_ONCE(sqe->len);
5208 if (!req->files_update.nr_args)
5210 req->files_update.arg = READ_ONCE(sqe->addr);
5214 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5215 struct io_comp_state *cs)
5217 struct io_ring_ctx *ctx = req->ctx;
5218 struct io_uring_files_update up;
5224 up.offset = req->files_update.offset;
5225 up.fds = req->files_update.arg;
5227 mutex_lock(&ctx->uring_lock);
5228 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5229 mutex_unlock(&ctx->uring_lock);
5232 req_set_fail_links(req);
5233 __io_req_complete(req, ret, 0, cs);
5237 static int io_req_defer_prep(struct io_kiocb *req,
5238 const struct io_uring_sqe *sqe, bool for_async)
5245 if (io_op_defs[req->opcode].file_table) {
5246 io_req_init_async(req);
5247 ret = io_grab_files(req);
5252 if (for_async || (req->flags & REQ_F_WORK_INITIALIZED)) {
5253 io_req_init_async(req);
5254 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
5257 switch (req->opcode) {
5260 case IORING_OP_READV:
5261 case IORING_OP_READ_FIXED:
5262 case IORING_OP_READ:
5263 ret = io_read_prep(req, sqe, true);
5265 case IORING_OP_WRITEV:
5266 case IORING_OP_WRITE_FIXED:
5267 case IORING_OP_WRITE:
5268 ret = io_write_prep(req, sqe, true);
5270 case IORING_OP_POLL_ADD:
5271 ret = io_poll_add_prep(req, sqe);
5273 case IORING_OP_POLL_REMOVE:
5274 ret = io_poll_remove_prep(req, sqe);
5276 case IORING_OP_FSYNC:
5277 ret = io_prep_fsync(req, sqe);
5279 case IORING_OP_SYNC_FILE_RANGE:
5280 ret = io_prep_sfr(req, sqe);
5282 case IORING_OP_SENDMSG:
5283 case IORING_OP_SEND:
5284 ret = io_sendmsg_prep(req, sqe);
5286 case IORING_OP_RECVMSG:
5287 case IORING_OP_RECV:
5288 ret = io_recvmsg_prep(req, sqe);
5290 case IORING_OP_CONNECT:
5291 ret = io_connect_prep(req, sqe);
5293 case IORING_OP_TIMEOUT:
5294 ret = io_timeout_prep(req, sqe, false);
5296 case IORING_OP_TIMEOUT_REMOVE:
5297 ret = io_timeout_remove_prep(req, sqe);
5299 case IORING_OP_ASYNC_CANCEL:
5300 ret = io_async_cancel_prep(req, sqe);
5302 case IORING_OP_LINK_TIMEOUT:
5303 ret = io_timeout_prep(req, sqe, true);
5305 case IORING_OP_ACCEPT:
5306 ret = io_accept_prep(req, sqe);
5308 case IORING_OP_FALLOCATE:
5309 ret = io_fallocate_prep(req, sqe);
5311 case IORING_OP_OPENAT:
5312 ret = io_openat_prep(req, sqe);
5314 case IORING_OP_CLOSE:
5315 ret = io_close_prep(req, sqe);
5317 case IORING_OP_FILES_UPDATE:
5318 ret = io_files_update_prep(req, sqe);
5320 case IORING_OP_STATX:
5321 ret = io_statx_prep(req, sqe);
5323 case IORING_OP_FADVISE:
5324 ret = io_fadvise_prep(req, sqe);
5326 case IORING_OP_MADVISE:
5327 ret = io_madvise_prep(req, sqe);
5329 case IORING_OP_OPENAT2:
5330 ret = io_openat2_prep(req, sqe);
5332 case IORING_OP_EPOLL_CTL:
5333 ret = io_epoll_ctl_prep(req, sqe);
5335 case IORING_OP_SPLICE:
5336 ret = io_splice_prep(req, sqe);
5338 case IORING_OP_PROVIDE_BUFFERS:
5339 ret = io_provide_buffers_prep(req, sqe);
5341 case IORING_OP_REMOVE_BUFFERS:
5342 ret = io_remove_buffers_prep(req, sqe);
5345 ret = io_tee_prep(req, sqe);
5348 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5357 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5359 struct io_ring_ctx *ctx = req->ctx;
5362 /* Still need defer if there is pending req in defer list. */
5363 if (!req_need_defer(req) && list_empty_careful(&ctx->defer_list))
5367 if (io_alloc_async_ctx(req))
5369 ret = io_req_defer_prep(req, sqe, true);
5374 spin_lock_irq(&ctx->completion_lock);
5375 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
5376 spin_unlock_irq(&ctx->completion_lock);
5380 trace_io_uring_defer(ctx, req, req->user_data);
5381 list_add_tail(&req->list, &ctx->defer_list);
5382 spin_unlock_irq(&ctx->completion_lock);
5383 return -EIOCBQUEUED;
5386 static void io_cleanup_req(struct io_kiocb *req)
5388 struct io_async_ctx *io = req->io;
5390 switch (req->opcode) {
5391 case IORING_OP_READV:
5392 case IORING_OP_READ_FIXED:
5393 case IORING_OP_READ:
5394 if (req->flags & REQ_F_BUFFER_SELECTED)
5395 kfree((void *)(unsigned long)req->rw.addr);
5397 case IORING_OP_WRITEV:
5398 case IORING_OP_WRITE_FIXED:
5399 case IORING_OP_WRITE:
5400 if (io->rw.iov != io->rw.fast_iov)
5403 case IORING_OP_RECVMSG:
5404 if (req->flags & REQ_F_BUFFER_SELECTED)
5405 kfree(req->sr_msg.kbuf);
5407 case IORING_OP_SENDMSG:
5408 if (io->msg.iov != io->msg.fast_iov)
5411 case IORING_OP_RECV:
5412 if (req->flags & REQ_F_BUFFER_SELECTED)
5413 kfree(req->sr_msg.kbuf);
5415 case IORING_OP_OPENAT:
5416 case IORING_OP_OPENAT2:
5418 case IORING_OP_SPLICE:
5420 io_put_file(req, req->splice.file_in,
5421 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5425 req->flags &= ~REQ_F_NEED_CLEANUP;
5428 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5429 bool force_nonblock, struct io_comp_state *cs)
5431 struct io_ring_ctx *ctx = req->ctx;
5434 switch (req->opcode) {
5436 ret = io_nop(req, cs);
5438 case IORING_OP_READV:
5439 case IORING_OP_READ_FIXED:
5440 case IORING_OP_READ:
5442 ret = io_read_prep(req, sqe, force_nonblock);
5446 ret = io_read(req, force_nonblock, cs);
5448 case IORING_OP_WRITEV:
5449 case IORING_OP_WRITE_FIXED:
5450 case IORING_OP_WRITE:
5452 ret = io_write_prep(req, sqe, force_nonblock);
5456 ret = io_write(req, force_nonblock, cs);
5458 case IORING_OP_FSYNC:
5460 ret = io_prep_fsync(req, sqe);
5464 ret = io_fsync(req, force_nonblock);
5466 case IORING_OP_POLL_ADD:
5468 ret = io_poll_add_prep(req, sqe);
5472 ret = io_poll_add(req);
5474 case IORING_OP_POLL_REMOVE:
5476 ret = io_poll_remove_prep(req, sqe);
5480 ret = io_poll_remove(req);
5482 case IORING_OP_SYNC_FILE_RANGE:
5484 ret = io_prep_sfr(req, sqe);
5488 ret = io_sync_file_range(req, force_nonblock);
5490 case IORING_OP_SENDMSG:
5491 case IORING_OP_SEND:
5493 ret = io_sendmsg_prep(req, sqe);
5497 if (req->opcode == IORING_OP_SENDMSG)
5498 ret = io_sendmsg(req, force_nonblock, cs);
5500 ret = io_send(req, force_nonblock, cs);
5502 case IORING_OP_RECVMSG:
5503 case IORING_OP_RECV:
5505 ret = io_recvmsg_prep(req, sqe);
5509 if (req->opcode == IORING_OP_RECVMSG)
5510 ret = io_recvmsg(req, force_nonblock, cs);
5512 ret = io_recv(req, force_nonblock, cs);
5514 case IORING_OP_TIMEOUT:
5516 ret = io_timeout_prep(req, sqe, false);
5520 ret = io_timeout(req);
5522 case IORING_OP_TIMEOUT_REMOVE:
5524 ret = io_timeout_remove_prep(req, sqe);
5528 ret = io_timeout_remove(req);
5530 case IORING_OP_ACCEPT:
5532 ret = io_accept_prep(req, sqe);
5536 ret = io_accept(req, force_nonblock, cs);
5538 case IORING_OP_CONNECT:
5540 ret = io_connect_prep(req, sqe);
5544 ret = io_connect(req, force_nonblock, cs);
5546 case IORING_OP_ASYNC_CANCEL:
5548 ret = io_async_cancel_prep(req, sqe);
5552 ret = io_async_cancel(req);
5554 case IORING_OP_FALLOCATE:
5556 ret = io_fallocate_prep(req, sqe);
5560 ret = io_fallocate(req, force_nonblock);
5562 case IORING_OP_OPENAT:
5564 ret = io_openat_prep(req, sqe);
5568 ret = io_openat(req, force_nonblock);
5570 case IORING_OP_CLOSE:
5572 ret = io_close_prep(req, sqe);
5576 ret = io_close(req, force_nonblock, cs);
5578 case IORING_OP_FILES_UPDATE:
5580 ret = io_files_update_prep(req, sqe);
5584 ret = io_files_update(req, force_nonblock, cs);
5586 case IORING_OP_STATX:
5588 ret = io_statx_prep(req, sqe);
5592 ret = io_statx(req, force_nonblock);
5594 case IORING_OP_FADVISE:
5596 ret = io_fadvise_prep(req, sqe);
5600 ret = io_fadvise(req, force_nonblock);
5602 case IORING_OP_MADVISE:
5604 ret = io_madvise_prep(req, sqe);
5608 ret = io_madvise(req, force_nonblock);
5610 case IORING_OP_OPENAT2:
5612 ret = io_openat2_prep(req, sqe);
5616 ret = io_openat2(req, force_nonblock);
5618 case IORING_OP_EPOLL_CTL:
5620 ret = io_epoll_ctl_prep(req, sqe);
5624 ret = io_epoll_ctl(req, force_nonblock, cs);
5626 case IORING_OP_SPLICE:
5628 ret = io_splice_prep(req, sqe);
5632 ret = io_splice(req, force_nonblock);
5634 case IORING_OP_PROVIDE_BUFFERS:
5636 ret = io_provide_buffers_prep(req, sqe);
5640 ret = io_provide_buffers(req, force_nonblock, cs);
5642 case IORING_OP_REMOVE_BUFFERS:
5644 ret = io_remove_buffers_prep(req, sqe);
5648 ret = io_remove_buffers(req, force_nonblock, cs);
5652 ret = io_tee_prep(req, sqe);
5656 ret = io_tee(req, force_nonblock);
5666 /* If the op doesn't have a file, we're not polling for it */
5667 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5668 const bool in_async = io_wq_current_is_worker();
5670 /* workqueue context doesn't hold uring_lock, grab it now */
5672 mutex_lock(&ctx->uring_lock);
5674 io_iopoll_req_issued(req);
5677 mutex_unlock(&ctx->uring_lock);
5683 static void io_arm_async_linked_timeout(struct io_kiocb *req)
5685 struct io_kiocb *link;
5687 /* link head's timeout is queued in io_queue_async_work() */
5688 if (!(req->flags & REQ_F_QUEUE_TIMEOUT))
5691 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
5692 io_queue_linked_timeout(link);
5695 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
5697 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5700 io_arm_async_linked_timeout(req);
5702 /* if NO_CANCEL is set, we must still run the work */
5703 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5704 IO_WQ_WORK_CANCEL) {
5710 ret = io_issue_sqe(req, NULL, false, NULL);
5712 * We can get EAGAIN for polled IO even though we're
5713 * forcing a sync submission from here, since we can't
5714 * wait for request slots on the block side.
5723 req_set_fail_links(req);
5724 io_req_complete(req, ret);
5727 return io_steal_work(req);
5730 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5733 struct fixed_file_table *table;
5735 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5736 return table->files[index & IORING_FILE_TABLE_MASK];
5739 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5740 int fd, struct file **out_file, bool fixed)
5742 struct io_ring_ctx *ctx = req->ctx;
5746 if (unlikely(!ctx->file_data ||
5747 (unsigned) fd >= ctx->nr_user_files))
5749 fd = array_index_nospec(fd, ctx->nr_user_files);
5750 file = io_file_from_index(ctx, fd);
5752 req->fixed_file_refs = ctx->file_data->cur_refs;
5753 percpu_ref_get(req->fixed_file_refs);
5756 trace_io_uring_file_get(ctx, fd);
5757 file = __io_file_get(state, fd);
5760 if (file || io_op_defs[req->opcode].needs_file_no_error) {
5767 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5772 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5773 if (unlikely(!fixed && io_async_submit(req->ctx)))
5776 return io_file_get(state, req, fd, &req->file, fixed);
5779 static int io_grab_files(struct io_kiocb *req)
5782 struct io_ring_ctx *ctx = req->ctx;
5784 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5786 if (!ctx->ring_file)
5790 spin_lock_irq(&ctx->inflight_lock);
5792 * We use the f_ops->flush() handler to ensure that we can flush
5793 * out work accessing these files if the fd is closed. Check if
5794 * the fd has changed since we started down this path, and disallow
5795 * this operation if it has.
5797 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5798 list_add(&req->inflight_entry, &ctx->inflight_list);
5799 req->flags |= REQ_F_INFLIGHT;
5800 req->work.files = current->files;
5803 spin_unlock_irq(&ctx->inflight_lock);
5809 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5811 struct io_timeout_data *data = container_of(timer,
5812 struct io_timeout_data, timer);
5813 struct io_kiocb *req = data->req;
5814 struct io_ring_ctx *ctx = req->ctx;
5815 struct io_kiocb *prev = NULL;
5816 unsigned long flags;
5818 spin_lock_irqsave(&ctx->completion_lock, flags);
5821 * We don't expect the list to be empty, that will only happen if we
5822 * race with the completion of the linked work.
5824 if (!list_empty(&req->link_list)) {
5825 prev = list_entry(req->link_list.prev, struct io_kiocb,
5827 if (refcount_inc_not_zero(&prev->refs)) {
5828 list_del_init(&req->link_list);
5829 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5834 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5837 req_set_fail_links(prev);
5838 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5841 io_req_complete(req, -ETIME);
5843 return HRTIMER_NORESTART;
5846 static void io_queue_linked_timeout(struct io_kiocb *req)
5848 struct io_ring_ctx *ctx = req->ctx;
5851 * If the list is now empty, then our linked request finished before
5852 * we got a chance to setup the timer
5854 spin_lock_irq(&ctx->completion_lock);
5855 if (!list_empty(&req->link_list)) {
5856 struct io_timeout_data *data = &req->io->timeout;
5858 data->timer.function = io_link_timeout_fn;
5859 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5862 spin_unlock_irq(&ctx->completion_lock);
5864 /* drop submission reference */
5868 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5870 struct io_kiocb *nxt;
5872 if (!(req->flags & REQ_F_LINK_HEAD))
5874 /* for polled retry, if flag is set, we already went through here */
5875 if (req->flags & REQ_F_POLLED)
5878 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5880 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5883 req->flags |= REQ_F_LINK_TIMEOUT;
5887 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5888 struct io_comp_state *cs)
5890 struct io_kiocb *linked_timeout;
5891 struct io_kiocb *nxt;
5892 const struct cred *old_creds = NULL;
5896 linked_timeout = io_prep_linked_timeout(req);
5898 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
5899 req->work.creds != current_cred()) {
5901 revert_creds(old_creds);
5902 if (old_creds == req->work.creds)
5903 old_creds = NULL; /* restored original creds */
5905 old_creds = override_creds(req->work.creds);
5908 ret = io_issue_sqe(req, sqe, true, cs);
5911 * We async punt it if the file wasn't marked NOWAIT, or if the file
5912 * doesn't support non-blocking read/write attempts
5914 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
5915 if (io_arm_poll_handler(req)) {
5917 io_queue_linked_timeout(linked_timeout);
5921 io_req_init_async(req);
5923 if (io_op_defs[req->opcode].file_table) {
5924 ret = io_grab_files(req);
5930 * Queued up for async execution, worker will release
5931 * submit reference when the iocb is actually submitted.
5933 io_queue_async_work(req);
5939 /* drop submission reference */
5940 io_put_req_find_next(req, &nxt);
5942 if (linked_timeout) {
5944 io_queue_linked_timeout(linked_timeout);
5946 io_put_req(linked_timeout);
5949 /* and drop final reference, if we failed */
5951 req_set_fail_links(req);
5952 io_req_complete(req, ret);
5957 if (req->flags & REQ_F_FORCE_ASYNC)
5963 revert_creds(old_creds);
5966 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5967 struct io_comp_state *cs)
5971 ret = io_req_defer(req, sqe);
5973 if (ret != -EIOCBQUEUED) {
5975 req_set_fail_links(req);
5977 io_req_complete(req, ret);
5979 } else if (req->flags & REQ_F_FORCE_ASYNC) {
5982 if (io_alloc_async_ctx(req))
5984 ret = io_req_defer_prep(req, sqe, true);
5985 if (unlikely(ret < 0))
5990 * Never try inline submit of IOSQE_ASYNC is set, go straight
5991 * to async execution.
5993 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5994 io_queue_async_work(req);
5996 __io_queue_sqe(req, sqe, cs);
6000 static inline void io_queue_link_head(struct io_kiocb *req,
6001 struct io_comp_state *cs)
6003 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6005 io_req_complete(req, -ECANCELED);
6007 io_queue_sqe(req, NULL, cs);
6010 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6011 struct io_kiocb **link, struct io_comp_state *cs)
6013 struct io_ring_ctx *ctx = req->ctx;
6017 * If we already have a head request, queue this one for async
6018 * submittal once the head completes. If we don't have a head but
6019 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6020 * submitted sync once the chain is complete. If none of those
6021 * conditions are true (normal request), then just queue it.
6024 struct io_kiocb *head = *link;
6027 * Taking sequential execution of a link, draining both sides
6028 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6029 * requests in the link. So, it drains the head and the
6030 * next after the link request. The last one is done via
6031 * drain_next flag to persist the effect across calls.
6033 if (req->flags & REQ_F_IO_DRAIN) {
6034 head->flags |= REQ_F_IO_DRAIN;
6035 ctx->drain_next = 1;
6037 if (io_alloc_async_ctx(req))
6040 ret = io_req_defer_prep(req, sqe, false);
6042 /* fail even hard links since we don't submit */
6043 head->flags |= REQ_F_FAIL_LINK;
6046 trace_io_uring_link(ctx, req, head);
6047 io_get_req_task(req);
6048 list_add_tail(&req->link_list, &head->link_list);
6050 /* last request of a link, enqueue the link */
6051 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6052 io_queue_link_head(head, cs);
6056 if (unlikely(ctx->drain_next)) {
6057 req->flags |= REQ_F_IO_DRAIN;
6058 ctx->drain_next = 0;
6060 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6061 req->flags |= REQ_F_LINK_HEAD;
6062 INIT_LIST_HEAD(&req->link_list);
6064 if (io_alloc_async_ctx(req))
6067 ret = io_req_defer_prep(req, sqe, false);
6069 req->flags |= REQ_F_FAIL_LINK;
6072 io_queue_sqe(req, sqe, cs);
6080 * Batched submission is done, ensure local IO is flushed out.
6082 static void io_submit_state_end(struct io_submit_state *state)
6084 if (!list_empty(&state->comp.list))
6085 io_submit_flush_completions(&state->comp);
6086 blk_finish_plug(&state->plug);
6087 io_state_file_put(state);
6088 if (state->free_reqs)
6089 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6093 * Start submission side cache.
6095 static void io_submit_state_start(struct io_submit_state *state,
6096 struct io_ring_ctx *ctx, unsigned int max_ios)
6098 blk_start_plug(&state->plug);
6100 state->plug.nowait = true;
6103 INIT_LIST_HEAD(&state->comp.list);
6104 state->comp.ctx = ctx;
6105 state->free_reqs = 0;
6107 state->ios_left = max_ios;
6110 static void io_commit_sqring(struct io_ring_ctx *ctx)
6112 struct io_rings *rings = ctx->rings;
6115 * Ensure any loads from the SQEs are done at this point,
6116 * since once we write the new head, the application could
6117 * write new data to them.
6119 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6123 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6124 * that is mapped by userspace. This means that care needs to be taken to
6125 * ensure that reads are stable, as we cannot rely on userspace always
6126 * being a good citizen. If members of the sqe are validated and then later
6127 * used, it's important that those reads are done through READ_ONCE() to
6128 * prevent a re-load down the line.
6130 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6132 u32 *sq_array = ctx->sq_array;
6136 * The cached sq head (or cq tail) serves two purposes:
6138 * 1) allows us to batch the cost of updating the user visible
6140 * 2) allows the kernel side to track the head on its own, even
6141 * though the application is the one updating it.
6143 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6144 if (likely(head < ctx->sq_entries))
6145 return &ctx->sq_sqes[head];
6147 /* drop invalid entries */
6148 ctx->cached_sq_dropped++;
6149 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6153 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6155 ctx->cached_sq_head++;
6158 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6159 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6160 IOSQE_BUFFER_SELECT)
6162 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6163 const struct io_uring_sqe *sqe,
6164 struct io_submit_state *state)
6166 unsigned int sqe_flags;
6170 * All io need record the previous position, if LINK vs DARIN,
6171 * it can be used to mark the position of the first IO in the
6174 req->sequence = ctx->cached_sq_head - ctx->cached_sq_dropped;
6175 req->opcode = READ_ONCE(sqe->opcode);
6176 req->user_data = READ_ONCE(sqe->user_data);
6181 /* one is dropped after submission, the other at completion */
6182 refcount_set(&req->refs, 2);
6183 req->task = current;
6186 if (unlikely(req->opcode >= IORING_OP_LAST))
6189 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6192 sqe_flags = READ_ONCE(sqe->flags);
6193 /* enforce forwards compatibility on users */
6194 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6197 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6198 !io_op_defs[req->opcode].buffer_select)
6201 id = READ_ONCE(sqe->personality);
6203 io_req_init_async(req);
6204 req->work.creds = idr_find(&ctx->personality_idr, id);
6205 if (unlikely(!req->work.creds))
6207 get_cred(req->work.creds);
6210 /* same numerical values with corresponding REQ_F_*, safe to copy */
6211 req->flags |= sqe_flags;
6213 if (!io_op_defs[req->opcode].needs_file)
6216 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
6219 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
6220 struct file *ring_file, int ring_fd)
6222 struct io_submit_state state;
6223 struct io_kiocb *link = NULL;
6224 int i, submitted = 0;
6226 /* if we have a backlog and couldn't flush it all, return BUSY */
6227 if (test_bit(0, &ctx->sq_check_overflow)) {
6228 if (!list_empty(&ctx->cq_overflow_list) &&
6229 !io_cqring_overflow_flush(ctx, false))
6233 /* make sure SQ entry isn't read before tail */
6234 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6236 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6239 io_submit_state_start(&state, ctx, nr);
6241 ctx->ring_fd = ring_fd;
6242 ctx->ring_file = ring_file;
6244 for (i = 0; i < nr; i++) {
6245 const struct io_uring_sqe *sqe;
6246 struct io_kiocb *req;
6249 sqe = io_get_sqe(ctx);
6250 if (unlikely(!sqe)) {
6251 io_consume_sqe(ctx);
6254 req = io_alloc_req(ctx, &state);
6255 if (unlikely(!req)) {
6257 submitted = -EAGAIN;
6261 err = io_init_req(ctx, req, sqe, &state);
6262 io_consume_sqe(ctx);
6263 /* will complete beyond this point, count as submitted */
6266 if (unlikely(err)) {
6269 io_req_complete(req, err);
6273 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6274 true, io_async_submit(ctx));
6275 err = io_submit_sqe(req, sqe, &link, &state.comp);
6280 if (unlikely(submitted != nr)) {
6281 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6283 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6286 io_queue_link_head(link, &state.comp);
6287 io_submit_state_end(&state);
6289 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6290 io_commit_sqring(ctx);
6295 static int io_sq_thread(void *data)
6297 struct io_ring_ctx *ctx = data;
6298 const struct cred *old_cred;
6300 unsigned long timeout;
6303 complete(&ctx->sq_thread_comp);
6305 old_cred = override_creds(ctx->creds);
6307 timeout = jiffies + ctx->sq_thread_idle;
6308 while (!kthread_should_park()) {
6309 unsigned int to_submit;
6311 if (!list_empty(&ctx->poll_list)) {
6312 unsigned nr_events = 0;
6314 mutex_lock(&ctx->uring_lock);
6315 if (!list_empty(&ctx->poll_list))
6316 io_iopoll_getevents(ctx, &nr_events, 0);
6318 timeout = jiffies + ctx->sq_thread_idle;
6319 mutex_unlock(&ctx->uring_lock);
6322 to_submit = io_sqring_entries(ctx);
6325 * If submit got -EBUSY, flag us as needing the application
6326 * to enter the kernel to reap and flush events.
6328 if (!to_submit || ret == -EBUSY || need_resched()) {
6330 * Drop cur_mm before scheduling, we can't hold it for
6331 * long periods (or over schedule()). Do this before
6332 * adding ourselves to the waitqueue, as the unuse/drop
6335 io_sq_thread_drop_mm(ctx);
6338 * We're polling. If we're within the defined idle
6339 * period, then let us spin without work before going
6340 * to sleep. The exception is if we got EBUSY doing
6341 * more IO, we should wait for the application to
6342 * reap events and wake us up.
6344 if (!list_empty(&ctx->poll_list) || need_resched() ||
6345 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6346 !percpu_ref_is_dying(&ctx->refs))) {
6347 if (current->task_works)
6353 prepare_to_wait(&ctx->sqo_wait, &wait,
6354 TASK_INTERRUPTIBLE);
6357 * While doing polled IO, before going to sleep, we need
6358 * to check if there are new reqs added to poll_list, it
6359 * is because reqs may have been punted to io worker and
6360 * will be added to poll_list later, hence check the
6363 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6364 !list_empty_careful(&ctx->poll_list)) {
6365 finish_wait(&ctx->sqo_wait, &wait);
6369 /* Tell userspace we may need a wakeup call */
6370 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6371 /* make sure to read SQ tail after writing flags */
6374 to_submit = io_sqring_entries(ctx);
6375 if (!to_submit || ret == -EBUSY) {
6376 if (kthread_should_park()) {
6377 finish_wait(&ctx->sqo_wait, &wait);
6380 if (current->task_works) {
6382 finish_wait(&ctx->sqo_wait, &wait);
6385 if (signal_pending(current))
6386 flush_signals(current);
6388 finish_wait(&ctx->sqo_wait, &wait);
6390 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6394 finish_wait(&ctx->sqo_wait, &wait);
6396 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6399 mutex_lock(&ctx->uring_lock);
6400 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6401 ret = io_submit_sqes(ctx, to_submit, NULL, -1);
6402 mutex_unlock(&ctx->uring_lock);
6403 timeout = jiffies + ctx->sq_thread_idle;
6406 if (current->task_works)
6409 io_sq_thread_drop_mm(ctx);
6410 revert_creds(old_cred);
6417 struct io_wait_queue {
6418 struct wait_queue_entry wq;
6419 struct io_ring_ctx *ctx;
6421 unsigned nr_timeouts;
6424 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6426 struct io_ring_ctx *ctx = iowq->ctx;
6429 * Wake up if we have enough events, or if a timeout occurred since we
6430 * started waiting. For timeouts, we always want to return to userspace,
6431 * regardless of event count.
6433 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6434 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6437 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6438 int wake_flags, void *key)
6440 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6443 /* use noflush == true, as we can't safely rely on locking context */
6444 if (!io_should_wake(iowq, true))
6447 return autoremove_wake_function(curr, mode, wake_flags, key);
6451 * Wait until events become available, if we don't already have some. The
6452 * application must reap them itself, as they reside on the shared cq ring.
6454 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6455 const sigset_t __user *sig, size_t sigsz)
6457 struct io_wait_queue iowq = {
6460 .func = io_wake_function,
6461 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6464 .to_wait = min_events,
6466 struct io_rings *rings = ctx->rings;
6470 if (io_cqring_events(ctx, false) >= min_events)
6472 if (!current->task_works)
6478 #ifdef CONFIG_COMPAT
6479 if (in_compat_syscall())
6480 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6484 ret = set_user_sigmask(sig, sigsz);
6490 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6491 trace_io_uring_cqring_wait(ctx, min_events);
6493 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6494 TASK_INTERRUPTIBLE);
6495 if (current->task_works)
6497 if (io_should_wake(&iowq, false))
6500 if (signal_pending(current)) {
6505 finish_wait(&ctx->wait, &iowq.wq);
6507 restore_saved_sigmask_unless(ret == -EINTR);
6509 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6512 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6514 #if defined(CONFIG_UNIX)
6515 if (ctx->ring_sock) {
6516 struct sock *sock = ctx->ring_sock->sk;
6517 struct sk_buff *skb;
6519 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6525 for (i = 0; i < ctx->nr_user_files; i++) {
6528 file = io_file_from_index(ctx, i);
6535 static void io_file_ref_kill(struct percpu_ref *ref)
6537 struct fixed_file_data *data;
6539 data = container_of(ref, struct fixed_file_data, refs);
6540 complete(&data->done);
6543 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6545 struct fixed_file_data *data = ctx->file_data;
6546 struct fixed_file_ref_node *ref_node = NULL;
6547 unsigned nr_tables, i;
6552 spin_lock(&data->lock);
6553 if (!list_empty(&data->ref_list))
6554 ref_node = list_first_entry(&data->ref_list,
6555 struct fixed_file_ref_node, node);
6556 spin_unlock(&data->lock);
6558 percpu_ref_kill(&ref_node->refs);
6560 percpu_ref_kill(&data->refs);
6562 /* wait for all refs nodes to complete */
6563 flush_delayed_work(&ctx->file_put_work);
6564 wait_for_completion(&data->done);
6566 __io_sqe_files_unregister(ctx);
6567 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6568 for (i = 0; i < nr_tables; i++)
6569 kfree(data->table[i].files);
6571 percpu_ref_exit(&data->refs);
6573 ctx->file_data = NULL;
6574 ctx->nr_user_files = 0;
6578 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6580 if (ctx->sqo_thread) {
6581 wait_for_completion(&ctx->sq_thread_comp);
6583 * The park is a bit of a work-around, without it we get
6584 * warning spews on shutdown with SQPOLL set and affinity
6585 * set to a single CPU.
6587 kthread_park(ctx->sqo_thread);
6588 kthread_stop(ctx->sqo_thread);
6589 ctx->sqo_thread = NULL;
6593 static void io_finish_async(struct io_ring_ctx *ctx)
6595 io_sq_thread_stop(ctx);
6598 io_wq_destroy(ctx->io_wq);
6603 #if defined(CONFIG_UNIX)
6605 * Ensure the UNIX gc is aware of our file set, so we are certain that
6606 * the io_uring can be safely unregistered on process exit, even if we have
6607 * loops in the file referencing.
6609 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6611 struct sock *sk = ctx->ring_sock->sk;
6612 struct scm_fp_list *fpl;
6613 struct sk_buff *skb;
6616 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6620 skb = alloc_skb(0, GFP_KERNEL);
6629 fpl->user = get_uid(ctx->user);
6630 for (i = 0; i < nr; i++) {
6631 struct file *file = io_file_from_index(ctx, i + offset);
6635 fpl->fp[nr_files] = get_file(file);
6636 unix_inflight(fpl->user, fpl->fp[nr_files]);
6641 fpl->max = SCM_MAX_FD;
6642 fpl->count = nr_files;
6643 UNIXCB(skb).fp = fpl;
6644 skb->destructor = unix_destruct_scm;
6645 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6646 skb_queue_head(&sk->sk_receive_queue, skb);
6648 for (i = 0; i < nr_files; i++)
6659 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6660 * causes regular reference counting to break down. We rely on the UNIX
6661 * garbage collection to take care of this problem for us.
6663 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6665 unsigned left, total;
6669 left = ctx->nr_user_files;
6671 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6673 ret = __io_sqe_files_scm(ctx, this_files, total);
6677 total += this_files;
6683 while (total < ctx->nr_user_files) {
6684 struct file *file = io_file_from_index(ctx, total);
6694 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6700 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6705 for (i = 0; i < nr_tables; i++) {
6706 struct fixed_file_table *table = &ctx->file_data->table[i];
6707 unsigned this_files;
6709 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6710 table->files = kcalloc(this_files, sizeof(struct file *),
6714 nr_files -= this_files;
6720 for (i = 0; i < nr_tables; i++) {
6721 struct fixed_file_table *table = &ctx->file_data->table[i];
6722 kfree(table->files);
6727 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6729 #if defined(CONFIG_UNIX)
6730 struct sock *sock = ctx->ring_sock->sk;
6731 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6732 struct sk_buff *skb;
6735 __skb_queue_head_init(&list);
6738 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6739 * remove this entry and rearrange the file array.
6741 skb = skb_dequeue(head);
6743 struct scm_fp_list *fp;
6745 fp = UNIXCB(skb).fp;
6746 for (i = 0; i < fp->count; i++) {
6749 if (fp->fp[i] != file)
6752 unix_notinflight(fp->user, fp->fp[i]);
6753 left = fp->count - 1 - i;
6755 memmove(&fp->fp[i], &fp->fp[i + 1],
6756 left * sizeof(struct file *));
6763 __skb_queue_tail(&list, skb);
6773 __skb_queue_tail(&list, skb);
6775 skb = skb_dequeue(head);
6778 if (skb_peek(&list)) {
6779 spin_lock_irq(&head->lock);
6780 while ((skb = __skb_dequeue(&list)) != NULL)
6781 __skb_queue_tail(head, skb);
6782 spin_unlock_irq(&head->lock);
6789 struct io_file_put {
6790 struct list_head list;
6794 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
6796 struct fixed_file_data *file_data = ref_node->file_data;
6797 struct io_ring_ctx *ctx = file_data->ctx;
6798 struct io_file_put *pfile, *tmp;
6800 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6801 list_del(&pfile->list);
6802 io_ring_file_put(ctx, pfile->file);
6806 spin_lock(&file_data->lock);
6807 list_del(&ref_node->node);
6808 spin_unlock(&file_data->lock);
6810 percpu_ref_exit(&ref_node->refs);
6812 percpu_ref_put(&file_data->refs);
6815 static void io_file_put_work(struct work_struct *work)
6817 struct io_ring_ctx *ctx;
6818 struct llist_node *node;
6820 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
6821 node = llist_del_all(&ctx->file_put_llist);
6824 struct fixed_file_ref_node *ref_node;
6825 struct llist_node *next = node->next;
6827 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
6828 __io_file_put_work(ref_node);
6833 static void io_file_data_ref_zero(struct percpu_ref *ref)
6835 struct fixed_file_ref_node *ref_node;
6836 struct io_ring_ctx *ctx;
6840 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6841 ctx = ref_node->file_data->ctx;
6843 if (percpu_ref_is_dying(&ctx->file_data->refs))
6846 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
6848 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
6850 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
6853 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6854 struct io_ring_ctx *ctx)
6856 struct fixed_file_ref_node *ref_node;
6858 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6860 return ERR_PTR(-ENOMEM);
6862 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6865 return ERR_PTR(-ENOMEM);
6867 INIT_LIST_HEAD(&ref_node->node);
6868 INIT_LIST_HEAD(&ref_node->file_list);
6869 ref_node->file_data = ctx->file_data;
6873 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6875 percpu_ref_exit(&ref_node->refs);
6879 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6882 __s32 __user *fds = (__s32 __user *) arg;
6887 struct fixed_file_ref_node *ref_node;
6893 if (nr_args > IORING_MAX_FIXED_FILES)
6896 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6897 if (!ctx->file_data)
6899 ctx->file_data->ctx = ctx;
6900 init_completion(&ctx->file_data->done);
6901 INIT_LIST_HEAD(&ctx->file_data->ref_list);
6902 spin_lock_init(&ctx->file_data->lock);
6904 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6905 ctx->file_data->table = kcalloc(nr_tables,
6906 sizeof(struct fixed_file_table),
6908 if (!ctx->file_data->table) {
6909 kfree(ctx->file_data);
6910 ctx->file_data = NULL;
6914 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6915 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6916 kfree(ctx->file_data->table);
6917 kfree(ctx->file_data);
6918 ctx->file_data = NULL;
6922 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6923 percpu_ref_exit(&ctx->file_data->refs);
6924 kfree(ctx->file_data->table);
6925 kfree(ctx->file_data);
6926 ctx->file_data = NULL;
6930 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6931 struct fixed_file_table *table;
6935 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6937 /* allow sparse sets */
6943 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6944 index = i & IORING_FILE_TABLE_MASK;
6952 * Don't allow io_uring instances to be registered. If UNIX
6953 * isn't enabled, then this causes a reference cycle and this
6954 * instance can never get freed. If UNIX is enabled we'll
6955 * handle it just fine, but there's still no point in allowing
6956 * a ring fd as it doesn't support regular read/write anyway.
6958 if (file->f_op == &io_uring_fops) {
6963 table->files[index] = file;
6967 for (i = 0; i < ctx->nr_user_files; i++) {
6968 file = io_file_from_index(ctx, i);
6972 for (i = 0; i < nr_tables; i++)
6973 kfree(ctx->file_data->table[i].files);
6975 kfree(ctx->file_data->table);
6976 kfree(ctx->file_data);
6977 ctx->file_data = NULL;
6978 ctx->nr_user_files = 0;
6982 ret = io_sqe_files_scm(ctx);
6984 io_sqe_files_unregister(ctx);
6988 ref_node = alloc_fixed_file_ref_node(ctx);
6989 if (IS_ERR(ref_node)) {
6990 io_sqe_files_unregister(ctx);
6991 return PTR_ERR(ref_node);
6994 ctx->file_data->cur_refs = &ref_node->refs;
6995 spin_lock(&ctx->file_data->lock);
6996 list_add(&ref_node->node, &ctx->file_data->ref_list);
6997 spin_unlock(&ctx->file_data->lock);
6998 percpu_ref_get(&ctx->file_data->refs);
7002 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7005 #if defined(CONFIG_UNIX)
7006 struct sock *sock = ctx->ring_sock->sk;
7007 struct sk_buff_head *head = &sock->sk_receive_queue;
7008 struct sk_buff *skb;
7011 * See if we can merge this file into an existing skb SCM_RIGHTS
7012 * file set. If there's no room, fall back to allocating a new skb
7013 * and filling it in.
7015 spin_lock_irq(&head->lock);
7016 skb = skb_peek(head);
7018 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7020 if (fpl->count < SCM_MAX_FD) {
7021 __skb_unlink(skb, head);
7022 spin_unlock_irq(&head->lock);
7023 fpl->fp[fpl->count] = get_file(file);
7024 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7026 spin_lock_irq(&head->lock);
7027 __skb_queue_head(head, skb);
7032 spin_unlock_irq(&head->lock);
7039 return __io_sqe_files_scm(ctx, 1, index);
7045 static int io_queue_file_removal(struct fixed_file_data *data,
7048 struct io_file_put *pfile;
7049 struct percpu_ref *refs = data->cur_refs;
7050 struct fixed_file_ref_node *ref_node;
7052 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7056 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
7058 list_add(&pfile->list, &ref_node->file_list);
7063 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7064 struct io_uring_files_update *up,
7067 struct fixed_file_data *data = ctx->file_data;
7068 struct fixed_file_ref_node *ref_node;
7073 bool needs_switch = false;
7075 if (check_add_overflow(up->offset, nr_args, &done))
7077 if (done > ctx->nr_user_files)
7080 ref_node = alloc_fixed_file_ref_node(ctx);
7081 if (IS_ERR(ref_node))
7082 return PTR_ERR(ref_node);
7085 fds = u64_to_user_ptr(up->fds);
7087 struct fixed_file_table *table;
7091 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7095 i = array_index_nospec(up->offset, ctx->nr_user_files);
7096 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7097 index = i & IORING_FILE_TABLE_MASK;
7098 if (table->files[index]) {
7099 file = io_file_from_index(ctx, index);
7100 err = io_queue_file_removal(data, file);
7103 table->files[index] = NULL;
7104 needs_switch = true;
7113 * Don't allow io_uring instances to be registered. If
7114 * UNIX isn't enabled, then this causes a reference
7115 * cycle and this instance can never get freed. If UNIX
7116 * is enabled we'll handle it just fine, but there's
7117 * still no point in allowing a ring fd as it doesn't
7118 * support regular read/write anyway.
7120 if (file->f_op == &io_uring_fops) {
7125 table->files[index] = file;
7126 err = io_sqe_file_register(ctx, file, i);
7136 percpu_ref_kill(data->cur_refs);
7137 spin_lock(&data->lock);
7138 list_add(&ref_node->node, &data->ref_list);
7139 data->cur_refs = &ref_node->refs;
7140 spin_unlock(&data->lock);
7141 percpu_ref_get(&ctx->file_data->refs);
7143 destroy_fixed_file_ref_node(ref_node);
7145 return done ? done : err;
7148 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7151 struct io_uring_files_update up;
7153 if (!ctx->file_data)
7157 if (copy_from_user(&up, arg, sizeof(up)))
7162 return __io_sqe_files_update(ctx, &up, nr_args);
7165 static void io_free_work(struct io_wq_work *work)
7167 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7169 /* Consider that io_steal_work() relies on this ref */
7173 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7174 struct io_uring_params *p)
7176 struct io_wq_data data;
7178 struct io_ring_ctx *ctx_attach;
7179 unsigned int concurrency;
7182 data.user = ctx->user;
7183 data.free_work = io_free_work;
7184 data.do_work = io_wq_submit_work;
7186 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7187 /* Do QD, or 4 * CPUS, whatever is smallest */
7188 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7190 ctx->io_wq = io_wq_create(concurrency, &data);
7191 if (IS_ERR(ctx->io_wq)) {
7192 ret = PTR_ERR(ctx->io_wq);
7198 f = fdget(p->wq_fd);
7202 if (f.file->f_op != &io_uring_fops) {
7207 ctx_attach = f.file->private_data;
7208 /* @io_wq is protected by holding the fd */
7209 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7214 ctx->io_wq = ctx_attach->io_wq;
7220 static int io_sq_offload_start(struct io_ring_ctx *ctx,
7221 struct io_uring_params *p)
7225 mmgrab(current->mm);
7226 ctx->sqo_mm = current->mm;
7228 if (ctx->flags & IORING_SETUP_SQPOLL) {
7230 if (!capable(CAP_SYS_ADMIN))
7233 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7234 if (!ctx->sq_thread_idle)
7235 ctx->sq_thread_idle = HZ;
7237 if (p->flags & IORING_SETUP_SQ_AFF) {
7238 int cpu = p->sq_thread_cpu;
7241 if (cpu >= nr_cpu_ids)
7243 if (!cpu_online(cpu))
7246 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
7250 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
7253 if (IS_ERR(ctx->sqo_thread)) {
7254 ret = PTR_ERR(ctx->sqo_thread);
7255 ctx->sqo_thread = NULL;
7258 wake_up_process(ctx->sqo_thread);
7259 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7260 /* Can't have SQ_AFF without SQPOLL */
7265 ret = io_init_wq_offload(ctx, p);
7271 io_finish_async(ctx);
7272 mmdrop(ctx->sqo_mm);
7277 static inline void __io_unaccount_mem(struct user_struct *user,
7278 unsigned long nr_pages)
7280 atomic_long_sub(nr_pages, &user->locked_vm);
7283 static inline int __io_account_mem(struct user_struct *user,
7284 unsigned long nr_pages)
7286 unsigned long page_limit, cur_pages, new_pages;
7288 /* Don't allow more pages than we can safely lock */
7289 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7292 cur_pages = atomic_long_read(&user->locked_vm);
7293 new_pages = cur_pages + nr_pages;
7294 if (new_pages > page_limit)
7296 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7297 new_pages) != cur_pages);
7302 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7303 enum io_mem_account acct)
7306 __io_unaccount_mem(ctx->user, nr_pages);
7309 if (acct == ACCT_LOCKED)
7310 ctx->sqo_mm->locked_vm -= nr_pages;
7311 else if (acct == ACCT_PINNED)
7312 atomic64_sub(nr_pages, &ctx->sqo_mm->pinned_vm);
7316 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7317 enum io_mem_account acct)
7321 if (ctx->limit_mem) {
7322 ret = __io_account_mem(ctx->user, nr_pages);
7328 if (acct == ACCT_LOCKED)
7329 ctx->sqo_mm->locked_vm += nr_pages;
7330 else if (acct == ACCT_PINNED)
7331 atomic64_add(nr_pages, &ctx->sqo_mm->pinned_vm);
7337 static void io_mem_free(void *ptr)
7344 page = virt_to_head_page(ptr);
7345 if (put_page_testzero(page))
7346 free_compound_page(page);
7349 static void *io_mem_alloc(size_t size)
7351 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7354 return (void *) __get_free_pages(gfp_flags, get_order(size));
7357 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7360 struct io_rings *rings;
7361 size_t off, sq_array_size;
7363 off = struct_size(rings, cqes, cq_entries);
7364 if (off == SIZE_MAX)
7368 off = ALIGN(off, SMP_CACHE_BYTES);
7373 sq_array_size = array_size(sizeof(u32), sq_entries);
7374 if (sq_array_size == SIZE_MAX)
7377 if (check_add_overflow(off, sq_array_size, &off))
7386 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7390 pages = (size_t)1 << get_order(
7391 rings_size(sq_entries, cq_entries, NULL));
7392 pages += (size_t)1 << get_order(
7393 array_size(sizeof(struct io_uring_sqe), sq_entries));
7398 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7402 if (!ctx->user_bufs)
7405 for (i = 0; i < ctx->nr_user_bufs; i++) {
7406 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7408 for (j = 0; j < imu->nr_bvecs; j++)
7409 unpin_user_page(imu->bvec[j].bv_page);
7411 io_unaccount_mem(ctx, imu->nr_bvecs, ACCT_PINNED);
7416 kfree(ctx->user_bufs);
7417 ctx->user_bufs = NULL;
7418 ctx->nr_user_bufs = 0;
7422 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7423 void __user *arg, unsigned index)
7425 struct iovec __user *src;
7427 #ifdef CONFIG_COMPAT
7429 struct compat_iovec __user *ciovs;
7430 struct compat_iovec ciov;
7432 ciovs = (struct compat_iovec __user *) arg;
7433 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7436 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7437 dst->iov_len = ciov.iov_len;
7441 src = (struct iovec __user *) arg;
7442 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7447 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7450 struct vm_area_struct **vmas = NULL;
7451 struct page **pages = NULL;
7452 int i, j, got_pages = 0;
7457 if (!nr_args || nr_args > UIO_MAXIOV)
7460 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7462 if (!ctx->user_bufs)
7465 for (i = 0; i < nr_args; i++) {
7466 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7467 unsigned long off, start, end, ubuf;
7472 ret = io_copy_iov(ctx, &iov, arg, i);
7477 * Don't impose further limits on the size and buffer
7478 * constraints here, we'll -EINVAL later when IO is
7479 * submitted if they are wrong.
7482 if (!iov.iov_base || !iov.iov_len)
7485 /* arbitrary limit, but we need something */
7486 if (iov.iov_len > SZ_1G)
7489 ubuf = (unsigned long) iov.iov_base;
7490 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7491 start = ubuf >> PAGE_SHIFT;
7492 nr_pages = end - start;
7494 ret = io_account_mem(ctx, nr_pages, ACCT_PINNED);
7499 if (!pages || nr_pages > got_pages) {
7502 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7504 vmas = kvmalloc_array(nr_pages,
7505 sizeof(struct vm_area_struct *),
7507 if (!pages || !vmas) {
7509 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7512 got_pages = nr_pages;
7515 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7519 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7524 mmap_read_lock(current->mm);
7525 pret = pin_user_pages(ubuf, nr_pages,
7526 FOLL_WRITE | FOLL_LONGTERM,
7528 if (pret == nr_pages) {
7529 /* don't support file backed memory */
7530 for (j = 0; j < nr_pages; j++) {
7531 struct vm_area_struct *vma = vmas[j];
7534 !is_file_hugepages(vma->vm_file)) {
7540 ret = pret < 0 ? pret : -EFAULT;
7542 mmap_read_unlock(current->mm);
7545 * if we did partial map, or found file backed vmas,
7546 * release any pages we did get
7549 unpin_user_pages(pages, pret);
7550 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7555 off = ubuf & ~PAGE_MASK;
7557 for (j = 0; j < nr_pages; j++) {
7560 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7561 imu->bvec[j].bv_page = pages[j];
7562 imu->bvec[j].bv_len = vec_len;
7563 imu->bvec[j].bv_offset = off;
7567 /* store original address for later verification */
7569 imu->len = iov.iov_len;
7570 imu->nr_bvecs = nr_pages;
7572 ctx->nr_user_bufs++;
7580 io_sqe_buffer_unregister(ctx);
7584 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7586 __s32 __user *fds = arg;
7592 if (copy_from_user(&fd, fds, sizeof(*fds)))
7595 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7596 if (IS_ERR(ctx->cq_ev_fd)) {
7597 int ret = PTR_ERR(ctx->cq_ev_fd);
7598 ctx->cq_ev_fd = NULL;
7605 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7607 if (ctx->cq_ev_fd) {
7608 eventfd_ctx_put(ctx->cq_ev_fd);
7609 ctx->cq_ev_fd = NULL;
7616 static int __io_destroy_buffers(int id, void *p, void *data)
7618 struct io_ring_ctx *ctx = data;
7619 struct io_buffer *buf = p;
7621 __io_remove_buffers(ctx, buf, id, -1U);
7625 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7627 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7628 idr_destroy(&ctx->io_buffer_idr);
7631 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7633 io_finish_async(ctx);
7635 mmdrop(ctx->sqo_mm);
7639 io_iopoll_reap_events(ctx);
7640 io_sqe_buffer_unregister(ctx);
7641 io_sqe_files_unregister(ctx);
7642 io_eventfd_unregister(ctx);
7643 io_destroy_buffers(ctx);
7644 idr_destroy(&ctx->personality_idr);
7646 #if defined(CONFIG_UNIX)
7647 if (ctx->ring_sock) {
7648 ctx->ring_sock->file = NULL; /* so that iput() is called */
7649 sock_release(ctx->ring_sock);
7653 io_mem_free(ctx->rings);
7654 io_mem_free(ctx->sq_sqes);
7656 percpu_ref_exit(&ctx->refs);
7657 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
7659 free_uid(ctx->user);
7660 put_cred(ctx->creds);
7661 kfree(ctx->cancel_hash);
7662 kmem_cache_free(req_cachep, ctx->fallback_req);
7666 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7668 struct io_ring_ctx *ctx = file->private_data;
7671 poll_wait(file, &ctx->cq_wait, wait);
7673 * synchronizes with barrier from wq_has_sleeper call in
7677 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7678 ctx->rings->sq_ring_entries)
7679 mask |= EPOLLOUT | EPOLLWRNORM;
7680 if (io_cqring_events(ctx, false))
7681 mask |= EPOLLIN | EPOLLRDNORM;
7686 static int io_uring_fasync(int fd, struct file *file, int on)
7688 struct io_ring_ctx *ctx = file->private_data;
7690 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7693 static int io_remove_personalities(int id, void *p, void *data)
7695 struct io_ring_ctx *ctx = data;
7696 const struct cred *cred;
7698 cred = idr_remove(&ctx->personality_idr, id);
7704 static void io_ring_exit_work(struct work_struct *work)
7706 struct io_ring_ctx *ctx;
7708 ctx = container_of(work, struct io_ring_ctx, exit_work);
7710 io_cqring_overflow_flush(ctx, true);
7713 * If we're doing polled IO and end up having requests being
7714 * submitted async (out-of-line), then completions can come in while
7715 * we're waiting for refs to drop. We need to reap these manually,
7716 * as nobody else will be looking for them.
7718 while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20)) {
7719 io_iopoll_reap_events(ctx);
7721 io_cqring_overflow_flush(ctx, true);
7723 io_ring_ctx_free(ctx);
7726 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7728 mutex_lock(&ctx->uring_lock);
7729 percpu_ref_kill(&ctx->refs);
7730 mutex_unlock(&ctx->uring_lock);
7732 io_kill_timeouts(ctx);
7733 io_poll_remove_all(ctx);
7736 io_wq_cancel_all(ctx->io_wq);
7738 io_iopoll_reap_events(ctx);
7739 /* if we failed setting up the ctx, we might not have any rings */
7741 io_cqring_overflow_flush(ctx, true);
7742 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7743 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7744 queue_work(system_wq, &ctx->exit_work);
7747 static int io_uring_release(struct inode *inode, struct file *file)
7749 struct io_ring_ctx *ctx = file->private_data;
7751 file->private_data = NULL;
7752 io_ring_ctx_wait_and_kill(ctx);
7756 static bool io_wq_files_match(struct io_wq_work *work, void *data)
7758 struct files_struct *files = data;
7760 return work->files == files;
7763 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7764 struct files_struct *files)
7766 if (list_empty_careful(&ctx->inflight_list))
7769 /* cancel all at once, should be faster than doing it one by one*/
7770 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
7772 while (!list_empty_careful(&ctx->inflight_list)) {
7773 struct io_kiocb *cancel_req = NULL, *req;
7776 spin_lock_irq(&ctx->inflight_lock);
7777 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7778 if (req->work.files != files)
7780 /* req is being completed, ignore */
7781 if (!refcount_inc_not_zero(&req->refs))
7787 prepare_to_wait(&ctx->inflight_wait, &wait,
7788 TASK_UNINTERRUPTIBLE);
7789 spin_unlock_irq(&ctx->inflight_lock);
7791 /* We need to keep going until we don't find a matching req */
7795 if (cancel_req->flags & REQ_F_OVERFLOW) {
7796 spin_lock_irq(&ctx->completion_lock);
7797 list_del(&cancel_req->list);
7798 cancel_req->flags &= ~REQ_F_OVERFLOW;
7799 if (list_empty(&ctx->cq_overflow_list)) {
7800 clear_bit(0, &ctx->sq_check_overflow);
7801 clear_bit(0, &ctx->cq_check_overflow);
7803 spin_unlock_irq(&ctx->completion_lock);
7805 WRITE_ONCE(ctx->rings->cq_overflow,
7806 atomic_inc_return(&ctx->cached_cq_overflow));
7809 * Put inflight ref and overflow ref. If that's
7810 * all we had, then we're done with this request.
7812 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7813 io_free_req(cancel_req);
7814 finish_wait(&ctx->inflight_wait, &wait);
7818 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7819 io_put_req(cancel_req);
7823 finish_wait(&ctx->inflight_wait, &wait);
7827 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
7829 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7830 struct task_struct *task = data;
7832 return req->task == task;
7835 static int io_uring_flush(struct file *file, void *data)
7837 struct io_ring_ctx *ctx = file->private_data;
7839 io_uring_cancel_files(ctx, data);
7842 * If the task is going away, cancel work it may have pending
7844 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7845 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, current, true);
7850 static void *io_uring_validate_mmap_request(struct file *file,
7851 loff_t pgoff, size_t sz)
7853 struct io_ring_ctx *ctx = file->private_data;
7854 loff_t offset = pgoff << PAGE_SHIFT;
7859 case IORING_OFF_SQ_RING:
7860 case IORING_OFF_CQ_RING:
7863 case IORING_OFF_SQES:
7867 return ERR_PTR(-EINVAL);
7870 page = virt_to_head_page(ptr);
7871 if (sz > page_size(page))
7872 return ERR_PTR(-EINVAL);
7879 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7881 size_t sz = vma->vm_end - vma->vm_start;
7885 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7887 return PTR_ERR(ptr);
7889 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7890 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7893 #else /* !CONFIG_MMU */
7895 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7897 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7900 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7902 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7905 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7906 unsigned long addr, unsigned long len,
7907 unsigned long pgoff, unsigned long flags)
7911 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7913 return PTR_ERR(ptr);
7915 return (unsigned long) ptr;
7918 #endif /* !CONFIG_MMU */
7920 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7921 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7924 struct io_ring_ctx *ctx;
7929 if (current->task_works)
7932 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7940 if (f.file->f_op != &io_uring_fops)
7944 ctx = f.file->private_data;
7945 if (!percpu_ref_tryget(&ctx->refs))
7949 * For SQ polling, the thread will do all submissions and completions.
7950 * Just return the requested submit count, and wake the thread if
7954 if (ctx->flags & IORING_SETUP_SQPOLL) {
7955 if (!list_empty_careful(&ctx->cq_overflow_list))
7956 io_cqring_overflow_flush(ctx, false);
7957 if (flags & IORING_ENTER_SQ_WAKEUP)
7958 wake_up(&ctx->sqo_wait);
7959 submitted = to_submit;
7960 } else if (to_submit) {
7961 mutex_lock(&ctx->uring_lock);
7962 submitted = io_submit_sqes(ctx, to_submit, f.file, fd);
7963 mutex_unlock(&ctx->uring_lock);
7965 if (submitted != to_submit)
7968 if (flags & IORING_ENTER_GETEVENTS) {
7969 unsigned nr_events = 0;
7971 min_complete = min(min_complete, ctx->cq_entries);
7974 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
7975 * space applications don't need to do io completion events
7976 * polling again, they can rely on io_sq_thread to do polling
7977 * work, which can reduce cpu usage and uring_lock contention.
7979 if (ctx->flags & IORING_SETUP_IOPOLL &&
7980 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7981 ret = io_iopoll_check(ctx, &nr_events, min_complete);
7983 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
7988 percpu_ref_put(&ctx->refs);
7991 return submitted ? submitted : ret;
7994 #ifdef CONFIG_PROC_FS
7995 static int io_uring_show_cred(int id, void *p, void *data)
7997 const struct cred *cred = p;
7998 struct seq_file *m = data;
7999 struct user_namespace *uns = seq_user_ns(m);
8000 struct group_info *gi;
8005 seq_printf(m, "%5d\n", id);
8006 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
8007 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
8008 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
8009 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
8010 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
8011 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
8012 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
8013 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
8014 seq_puts(m, "\n\tGroups:\t");
8015 gi = cred->group_info;
8016 for (g = 0; g < gi->ngroups; g++) {
8017 seq_put_decimal_ull(m, g ? " " : "",
8018 from_kgid_munged(uns, gi->gid[g]));
8020 seq_puts(m, "\n\tCapEff:\t");
8021 cap = cred->cap_effective;
8022 CAP_FOR_EACH_U32(__capi)
8023 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8028 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8032 mutex_lock(&ctx->uring_lock);
8033 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8034 for (i = 0; i < ctx->nr_user_files; i++) {
8035 struct fixed_file_table *table;
8038 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8039 f = table->files[i & IORING_FILE_TABLE_MASK];
8041 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8043 seq_printf(m, "%5u: <none>\n", i);
8045 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8046 for (i = 0; i < ctx->nr_user_bufs; i++) {
8047 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8049 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8050 (unsigned int) buf->len);
8052 if (!idr_is_empty(&ctx->personality_idr)) {
8053 seq_printf(m, "Personalities:\n");
8054 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8056 seq_printf(m, "PollList:\n");
8057 spin_lock_irq(&ctx->completion_lock);
8058 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8059 struct hlist_head *list = &ctx->cancel_hash[i];
8060 struct io_kiocb *req;
8062 hlist_for_each_entry(req, list, hash_node)
8063 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
8064 req->task->task_works != NULL);
8066 spin_unlock_irq(&ctx->completion_lock);
8067 mutex_unlock(&ctx->uring_lock);
8070 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8072 struct io_ring_ctx *ctx = f->private_data;
8074 if (percpu_ref_tryget(&ctx->refs)) {
8075 __io_uring_show_fdinfo(ctx, m);
8076 percpu_ref_put(&ctx->refs);
8081 static const struct file_operations io_uring_fops = {
8082 .release = io_uring_release,
8083 .flush = io_uring_flush,
8084 .mmap = io_uring_mmap,
8086 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8087 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8089 .poll = io_uring_poll,
8090 .fasync = io_uring_fasync,
8091 #ifdef CONFIG_PROC_FS
8092 .show_fdinfo = io_uring_show_fdinfo,
8096 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8097 struct io_uring_params *p)
8099 struct io_rings *rings;
8100 size_t size, sq_array_offset;
8102 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8103 if (size == SIZE_MAX)
8106 rings = io_mem_alloc(size);
8111 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8112 rings->sq_ring_mask = p->sq_entries - 1;
8113 rings->cq_ring_mask = p->cq_entries - 1;
8114 rings->sq_ring_entries = p->sq_entries;
8115 rings->cq_ring_entries = p->cq_entries;
8116 ctx->sq_mask = rings->sq_ring_mask;
8117 ctx->cq_mask = rings->cq_ring_mask;
8118 ctx->sq_entries = rings->sq_ring_entries;
8119 ctx->cq_entries = rings->cq_ring_entries;
8121 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8122 if (size == SIZE_MAX) {
8123 io_mem_free(ctx->rings);
8128 ctx->sq_sqes = io_mem_alloc(size);
8129 if (!ctx->sq_sqes) {
8130 io_mem_free(ctx->rings);
8139 * Allocate an anonymous fd, this is what constitutes the application
8140 * visible backing of an io_uring instance. The application mmaps this
8141 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8142 * we have to tie this fd to a socket for file garbage collection purposes.
8144 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8149 #if defined(CONFIG_UNIX)
8150 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8156 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8160 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8161 O_RDWR | O_CLOEXEC);
8164 ret = PTR_ERR(file);
8168 #if defined(CONFIG_UNIX)
8169 ctx->ring_sock->file = file;
8171 fd_install(ret, file);
8174 #if defined(CONFIG_UNIX)
8175 sock_release(ctx->ring_sock);
8176 ctx->ring_sock = NULL;
8181 static int io_uring_create(unsigned entries, struct io_uring_params *p,
8182 struct io_uring_params __user *params)
8184 struct user_struct *user = NULL;
8185 struct io_ring_ctx *ctx;
8191 if (entries > IORING_MAX_ENTRIES) {
8192 if (!(p->flags & IORING_SETUP_CLAMP))
8194 entries = IORING_MAX_ENTRIES;
8198 * Use twice as many entries for the CQ ring. It's possible for the
8199 * application to drive a higher depth than the size of the SQ ring,
8200 * since the sqes are only used at submission time. This allows for
8201 * some flexibility in overcommitting a bit. If the application has
8202 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
8203 * of CQ ring entries manually.
8205 p->sq_entries = roundup_pow_of_two(entries);
8206 if (p->flags & IORING_SETUP_CQSIZE) {
8208 * If IORING_SETUP_CQSIZE is set, we do the same roundup
8209 * to a power-of-two, if it isn't already. We do NOT impose
8210 * any cq vs sq ring sizing.
8212 if (p->cq_entries < p->sq_entries)
8214 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
8215 if (!(p->flags & IORING_SETUP_CLAMP))
8217 p->cq_entries = IORING_MAX_CQ_ENTRIES;
8219 p->cq_entries = roundup_pow_of_two(p->cq_entries);
8221 p->cq_entries = 2 * p->sq_entries;
8224 user = get_uid(current_user());
8225 limit_mem = !capable(CAP_IPC_LOCK);
8228 ret = __io_account_mem(user,
8229 ring_pages(p->sq_entries, p->cq_entries));
8236 ctx = io_ring_ctx_alloc(p);
8239 __io_unaccount_mem(user, ring_pages(p->sq_entries,
8244 ctx->compat = in_compat_syscall();
8246 ctx->creds = get_current_cred();
8248 ret = io_allocate_scq_urings(ctx, p);
8252 ret = io_sq_offload_start(ctx, p);
8256 memset(&p->sq_off, 0, sizeof(p->sq_off));
8257 p->sq_off.head = offsetof(struct io_rings, sq.head);
8258 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
8259 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
8260 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
8261 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
8262 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
8263 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
8265 memset(&p->cq_off, 0, sizeof(p->cq_off));
8266 p->cq_off.head = offsetof(struct io_rings, cq.head);
8267 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
8268 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
8269 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
8270 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
8271 p->cq_off.cqes = offsetof(struct io_rings, cqes);
8272 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
8274 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
8275 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
8276 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
8277 IORING_FEAT_POLL_32BITS;
8279 if (copy_to_user(params, p, sizeof(*p))) {
8284 * Install ring fd as the very last thing, so we don't risk someone
8285 * having closed it before we finish setup
8287 ret = io_uring_get_fd(ctx);
8291 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
8292 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
8294 ctx->limit_mem = limit_mem;
8297 io_ring_ctx_wait_and_kill(ctx);
8302 * Sets up an aio uring context, and returns the fd. Applications asks for a
8303 * ring size, we return the actual sq/cq ring sizes (among other things) in the
8304 * params structure passed in.
8306 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
8308 struct io_uring_params p;
8311 if (copy_from_user(&p, params, sizeof(p)))
8313 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
8318 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8319 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8320 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8323 return io_uring_create(entries, &p, params);
8326 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8327 struct io_uring_params __user *, params)
8329 return io_uring_setup(entries, params);
8332 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8334 struct io_uring_probe *p;
8338 size = struct_size(p, ops, nr_args);
8339 if (size == SIZE_MAX)
8341 p = kzalloc(size, GFP_KERNEL);
8346 if (copy_from_user(p, arg, size))
8349 if (memchr_inv(p, 0, size))
8352 p->last_op = IORING_OP_LAST - 1;
8353 if (nr_args > IORING_OP_LAST)
8354 nr_args = IORING_OP_LAST;
8356 for (i = 0; i < nr_args; i++) {
8358 if (!io_op_defs[i].not_supported)
8359 p->ops[i].flags = IO_URING_OP_SUPPORTED;
8364 if (copy_to_user(arg, p, size))
8371 static int io_register_personality(struct io_ring_ctx *ctx)
8373 const struct cred *creds = get_current_cred();
8376 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8377 USHRT_MAX, GFP_KERNEL);
8383 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8385 const struct cred *old_creds;
8387 old_creds = idr_remove(&ctx->personality_idr, id);
8389 put_cred(old_creds);
8396 static bool io_register_op_must_quiesce(int op)
8399 case IORING_UNREGISTER_FILES:
8400 case IORING_REGISTER_FILES_UPDATE:
8401 case IORING_REGISTER_PROBE:
8402 case IORING_REGISTER_PERSONALITY:
8403 case IORING_UNREGISTER_PERSONALITY:
8410 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8411 void __user *arg, unsigned nr_args)
8412 __releases(ctx->uring_lock)
8413 __acquires(ctx->uring_lock)
8418 * We're inside the ring mutex, if the ref is already dying, then
8419 * someone else killed the ctx or is already going through
8420 * io_uring_register().
8422 if (percpu_ref_is_dying(&ctx->refs))
8425 if (io_register_op_must_quiesce(opcode)) {
8426 percpu_ref_kill(&ctx->refs);
8429 * Drop uring mutex before waiting for references to exit. If
8430 * another thread is currently inside io_uring_enter() it might
8431 * need to grab the uring_lock to make progress. If we hold it
8432 * here across the drain wait, then we can deadlock. It's safe
8433 * to drop the mutex here, since no new references will come in
8434 * after we've killed the percpu ref.
8436 mutex_unlock(&ctx->uring_lock);
8437 ret = wait_for_completion_interruptible(&ctx->ref_comp);
8438 mutex_lock(&ctx->uring_lock);
8440 percpu_ref_resurrect(&ctx->refs);
8447 case IORING_REGISTER_BUFFERS:
8448 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8450 case IORING_UNREGISTER_BUFFERS:
8454 ret = io_sqe_buffer_unregister(ctx);
8456 case IORING_REGISTER_FILES:
8457 ret = io_sqe_files_register(ctx, arg, nr_args);
8459 case IORING_UNREGISTER_FILES:
8463 ret = io_sqe_files_unregister(ctx);
8465 case IORING_REGISTER_FILES_UPDATE:
8466 ret = io_sqe_files_update(ctx, arg, nr_args);
8468 case IORING_REGISTER_EVENTFD:
8469 case IORING_REGISTER_EVENTFD_ASYNC:
8473 ret = io_eventfd_register(ctx, arg);
8476 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8477 ctx->eventfd_async = 1;
8479 ctx->eventfd_async = 0;
8481 case IORING_UNREGISTER_EVENTFD:
8485 ret = io_eventfd_unregister(ctx);
8487 case IORING_REGISTER_PROBE:
8489 if (!arg || nr_args > 256)
8491 ret = io_probe(ctx, arg, nr_args);
8493 case IORING_REGISTER_PERSONALITY:
8497 ret = io_register_personality(ctx);
8499 case IORING_UNREGISTER_PERSONALITY:
8503 ret = io_unregister_personality(ctx, nr_args);
8510 if (io_register_op_must_quiesce(opcode)) {
8511 /* bring the ctx back to life */
8512 percpu_ref_reinit(&ctx->refs);
8514 reinit_completion(&ctx->ref_comp);
8519 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8520 void __user *, arg, unsigned int, nr_args)
8522 struct io_ring_ctx *ctx;
8531 if (f.file->f_op != &io_uring_fops)
8534 ctx = f.file->private_data;
8536 mutex_lock(&ctx->uring_lock);
8537 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8538 mutex_unlock(&ctx->uring_lock);
8539 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8540 ctx->cq_ev_fd != NULL, ret);
8546 static int __init io_uring_init(void)
8548 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8549 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8550 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8553 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8554 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8555 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8556 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8557 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8558 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8559 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8560 BUILD_BUG_SQE_ELEM(8, __u64, off);
8561 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8562 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8563 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8564 BUILD_BUG_SQE_ELEM(24, __u32, len);
8565 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8566 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8567 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8568 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8569 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
8570 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
8571 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8572 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8573 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8574 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8575 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8576 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8577 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8578 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8579 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8580 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8581 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8582 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8583 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8585 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8586 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8587 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8590 __initcall(io_uring_init);