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_req_aux_free(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);
1519 static void __io_free_req(struct io_kiocb *req)
1521 __io_req_aux_free(req);
1523 if (req->flags & REQ_F_INFLIGHT) {
1524 struct io_ring_ctx *ctx = req->ctx;
1525 unsigned long flags;
1527 spin_lock_irqsave(&ctx->inflight_lock, flags);
1528 list_del(&req->inflight_entry);
1529 if (waitqueue_active(&ctx->inflight_wait))
1530 wake_up(&ctx->inflight_wait);
1531 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1534 percpu_ref_put(&req->ctx->refs);
1535 if (likely(!io_is_fallback_req(req)))
1536 kmem_cache_free(req_cachep, req);
1538 clear_bit_unlock(0, (unsigned long *) &req->ctx->fallback_req);
1542 void *reqs[IO_IOPOLL_BATCH];
1547 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1551 if (rb->need_iter) {
1552 int i, inflight = 0;
1553 unsigned long flags;
1555 for (i = 0; i < rb->to_free; i++) {
1556 struct io_kiocb *req = rb->reqs[i];
1558 if (req->flags & REQ_F_INFLIGHT)
1560 __io_req_aux_free(req);
1565 spin_lock_irqsave(&ctx->inflight_lock, flags);
1566 for (i = 0; i < rb->to_free; i++) {
1567 struct io_kiocb *req = rb->reqs[i];
1569 if (req->flags & REQ_F_INFLIGHT) {
1570 list_del(&req->inflight_entry);
1575 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1577 if (waitqueue_active(&ctx->inflight_wait))
1578 wake_up(&ctx->inflight_wait);
1581 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1582 percpu_ref_put_many(&ctx->refs, rb->to_free);
1583 rb->to_free = rb->need_iter = 0;
1586 static bool io_link_cancel_timeout(struct io_kiocb *req)
1588 struct io_ring_ctx *ctx = req->ctx;
1591 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1593 io_cqring_fill_event(req, -ECANCELED);
1594 io_commit_cqring(ctx);
1595 req->flags &= ~REQ_F_LINK_HEAD;
1603 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1605 struct io_ring_ctx *ctx = req->ctx;
1606 bool wake_ev = false;
1608 /* Already got next link */
1609 if (req->flags & REQ_F_LINK_NEXT)
1613 * The list should never be empty when we are called here. But could
1614 * potentially happen if the chain is messed up, check to be on the
1617 while (!list_empty(&req->link_list)) {
1618 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1619 struct io_kiocb, link_list);
1621 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1622 (nxt->flags & REQ_F_TIMEOUT))) {
1623 list_del_init(&nxt->link_list);
1624 wake_ev |= io_link_cancel_timeout(nxt);
1625 req->flags &= ~REQ_F_LINK_TIMEOUT;
1629 list_del_init(&req->link_list);
1630 if (!list_empty(&nxt->link_list))
1631 nxt->flags |= REQ_F_LINK_HEAD;
1636 req->flags |= REQ_F_LINK_NEXT;
1638 io_cqring_ev_posted(ctx);
1642 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1644 static void io_fail_links(struct io_kiocb *req)
1646 struct io_ring_ctx *ctx = req->ctx;
1647 unsigned long flags;
1649 spin_lock_irqsave(&ctx->completion_lock, flags);
1651 while (!list_empty(&req->link_list)) {
1652 struct io_kiocb *link = list_first_entry(&req->link_list,
1653 struct io_kiocb, link_list);
1655 list_del_init(&link->link_list);
1656 trace_io_uring_fail_link(req, link);
1658 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1659 link->opcode == IORING_OP_LINK_TIMEOUT) {
1660 io_link_cancel_timeout(link);
1662 io_cqring_fill_event(link, -ECANCELED);
1663 __io_double_put_req(link);
1665 req->flags &= ~REQ_F_LINK_TIMEOUT;
1668 io_commit_cqring(ctx);
1669 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1670 io_cqring_ev_posted(ctx);
1673 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1675 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1679 * If LINK is set, we have dependent requests in this chain. If we
1680 * didn't fail this request, queue the first one up, moving any other
1681 * dependencies to the next request. In case of failure, fail the rest
1684 if (req->flags & REQ_F_FAIL_LINK) {
1686 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1687 REQ_F_LINK_TIMEOUT) {
1688 struct io_ring_ctx *ctx = req->ctx;
1689 unsigned long flags;
1692 * If this is a timeout link, we could be racing with the
1693 * timeout timer. Grab the completion lock for this case to
1694 * protect against that.
1696 spin_lock_irqsave(&ctx->completion_lock, flags);
1697 io_req_link_next(req, nxt);
1698 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1700 io_req_link_next(req, nxt);
1704 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1706 struct io_ring_ctx *ctx = req->ctx;
1708 spin_lock_irq(&ctx->completion_lock);
1709 io_cqring_fill_event(req, error);
1710 io_commit_cqring(ctx);
1711 spin_unlock_irq(&ctx->completion_lock);
1713 io_cqring_ev_posted(ctx);
1714 req_set_fail_links(req);
1715 io_double_put_req(req);
1718 static void io_req_task_cancel(struct callback_head *cb)
1720 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1722 __io_req_task_cancel(req, -ECANCELED);
1725 static void __io_req_task_submit(struct io_kiocb *req)
1727 struct io_ring_ctx *ctx = req->ctx;
1729 __set_current_state(TASK_RUNNING);
1730 if (!__io_sq_thread_acquire_mm(ctx)) {
1731 mutex_lock(&ctx->uring_lock);
1732 __io_queue_sqe(req, NULL, NULL);
1733 mutex_unlock(&ctx->uring_lock);
1735 __io_req_task_cancel(req, -EFAULT);
1739 static void io_req_task_submit(struct callback_head *cb)
1741 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1743 __io_req_task_submit(req);
1746 static void io_req_task_queue(struct io_kiocb *req)
1748 struct task_struct *tsk = req->task;
1751 init_task_work(&req->task_work, io_req_task_submit);
1753 ret = task_work_add(tsk, &req->task_work, true);
1754 if (unlikely(ret)) {
1755 init_task_work(&req->task_work, io_req_task_cancel);
1756 tsk = io_wq_get_task(req->ctx->io_wq);
1757 task_work_add(tsk, &req->task_work, true);
1759 wake_up_process(tsk);
1762 static void io_free_req(struct io_kiocb *req)
1764 struct io_kiocb *nxt = NULL;
1766 io_req_find_next(req, &nxt);
1770 io_req_task_queue(nxt);
1774 * Drop reference to request, return next in chain (if there is one) if this
1775 * was the last reference to this request.
1777 __attribute__((nonnull))
1778 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1780 if (refcount_dec_and_test(&req->refs)) {
1781 io_req_find_next(req, nxtptr);
1786 static void io_put_req(struct io_kiocb *req)
1788 if (refcount_dec_and_test(&req->refs))
1792 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
1794 struct io_kiocb *nxt = NULL;
1797 * A ref is owned by io-wq in which context we're. So, if that's the
1798 * last one, it's safe to steal next work. False negatives are Ok,
1799 * it just will be re-punted async in io_put_work()
1801 if (refcount_read(&req->refs) != 1)
1804 io_req_find_next(req, &nxt);
1808 if ((nxt->flags & REQ_F_ISREG) && io_op_defs[nxt->opcode].hash_reg_file)
1809 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1811 io_req_task_queue(nxt);
1813 * If we're going to return actual work, here should be timeout prep:
1815 * link = io_prep_linked_timeout(nxt);
1817 * nxt->flags |= REQ_F_QUEUE_TIMEOUT;
1823 * Must only be used if we don't need to care about links, usually from
1824 * within the completion handling itself.
1826 static void __io_double_put_req(struct io_kiocb *req)
1828 /* drop both submit and complete references */
1829 if (refcount_sub_and_test(2, &req->refs))
1833 static void io_double_put_req(struct io_kiocb *req)
1835 /* drop both submit and complete references */
1836 if (refcount_sub_and_test(2, &req->refs))
1840 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1842 struct io_rings *rings = ctx->rings;
1844 if (test_bit(0, &ctx->cq_check_overflow)) {
1846 * noflush == true is from the waitqueue handler, just ensure
1847 * we wake up the task, and the next invocation will flush the
1848 * entries. We cannot safely to it from here.
1850 if (noflush && !list_empty(&ctx->cq_overflow_list))
1853 io_cqring_overflow_flush(ctx, false);
1856 /* See comment at the top of this file */
1858 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1861 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1863 struct io_rings *rings = ctx->rings;
1865 /* make sure SQ entry isn't read before tail */
1866 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1869 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1871 if ((req->flags & REQ_F_LINK_HEAD) || io_is_fallback_req(req))
1874 if (req->file || req->io)
1877 rb->reqs[rb->to_free++] = req;
1878 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1879 io_free_req_many(req->ctx, rb);
1883 static int io_put_kbuf(struct io_kiocb *req)
1885 struct io_buffer *kbuf;
1888 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1889 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1890 cflags |= IORING_CQE_F_BUFFER;
1896 static void io_iopoll_queue(struct list_head *again)
1898 struct io_kiocb *req;
1901 req = list_first_entry(again, struct io_kiocb, list);
1902 list_del(&req->list);
1904 /* shouldn't happen unless io_uring is dying, cancel reqs */
1905 if (unlikely(!current->mm)) {
1906 io_complete_rw_common(&req->rw.kiocb, -EAGAIN, NULL);
1911 refcount_inc(&req->refs);
1912 io_queue_async_work(req);
1913 } while (!list_empty(again));
1917 * Find and free completed poll iocbs
1919 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1920 struct list_head *done)
1922 struct req_batch rb;
1923 struct io_kiocb *req;
1926 /* order with ->result store in io_complete_rw_iopoll() */
1929 rb.to_free = rb.need_iter = 0;
1930 while (!list_empty(done)) {
1933 req = list_first_entry(done, struct io_kiocb, list);
1934 if (READ_ONCE(req->result) == -EAGAIN) {
1935 req->iopoll_completed = 0;
1936 list_move_tail(&req->list, &again);
1939 list_del(&req->list);
1941 if (req->flags & REQ_F_BUFFER_SELECTED)
1942 cflags = io_put_kbuf(req);
1944 __io_cqring_fill_event(req, req->result, cflags);
1947 if (refcount_dec_and_test(&req->refs) &&
1948 !io_req_multi_free(&rb, req))
1952 io_commit_cqring(ctx);
1953 if (ctx->flags & IORING_SETUP_SQPOLL)
1954 io_cqring_ev_posted(ctx);
1955 io_free_req_many(ctx, &rb);
1957 if (!list_empty(&again))
1958 io_iopoll_queue(&again);
1961 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1964 struct io_kiocb *req, *tmp;
1970 * Only spin for completions if we don't have multiple devices hanging
1971 * off our complete list, and we're under the requested amount.
1973 spin = !ctx->poll_multi_file && *nr_events < min;
1976 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1977 struct kiocb *kiocb = &req->rw.kiocb;
1980 * Move completed and retryable entries to our local lists.
1981 * If we find a request that requires polling, break out
1982 * and complete those lists first, if we have entries there.
1984 if (READ_ONCE(req->iopoll_completed)) {
1985 list_move_tail(&req->list, &done);
1988 if (!list_empty(&done))
1991 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2000 if (!list_empty(&done))
2001 io_iopoll_complete(ctx, nr_events, &done);
2007 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2008 * non-spinning poll check - we'll still enter the driver poll loop, but only
2009 * as a non-spinning completion check.
2011 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2014 while (!list_empty(&ctx->poll_list) && !need_resched()) {
2017 ret = io_do_iopoll(ctx, nr_events, min);
2020 if (!min || *nr_events >= min)
2028 * We can't just wait for polled events to come to us, we have to actively
2029 * find and complete them.
2031 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
2033 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2036 mutex_lock(&ctx->uring_lock);
2037 while (!list_empty(&ctx->poll_list)) {
2038 unsigned int nr_events = 0;
2040 io_iopoll_getevents(ctx, &nr_events, 1);
2043 * Ensure we allow local-to-the-cpu processing to take place,
2044 * in this case we need to ensure that we reap all events.
2048 mutex_unlock(&ctx->uring_lock);
2051 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
2054 int iters = 0, ret = 0;
2057 * We disallow the app entering submit/complete with polling, but we
2058 * still need to lock the ring to prevent racing with polled issue
2059 * that got punted to a workqueue.
2061 mutex_lock(&ctx->uring_lock);
2066 * Don't enter poll loop if we already have events pending.
2067 * If we do, we can potentially be spinning for commands that
2068 * already triggered a CQE (eg in error).
2070 if (io_cqring_events(ctx, false))
2074 * If a submit got punted to a workqueue, we can have the
2075 * application entering polling for a command before it gets
2076 * issued. That app will hold the uring_lock for the duration
2077 * of the poll right here, so we need to take a breather every
2078 * now and then to ensure that the issue has a chance to add
2079 * the poll to the issued list. Otherwise we can spin here
2080 * forever, while the workqueue is stuck trying to acquire the
2083 if (!(++iters & 7)) {
2084 mutex_unlock(&ctx->uring_lock);
2085 mutex_lock(&ctx->uring_lock);
2088 if (*nr_events < min)
2089 tmin = min - *nr_events;
2091 ret = io_iopoll_getevents(ctx, nr_events, tmin);
2095 } while (min && !*nr_events && !need_resched());
2097 mutex_unlock(&ctx->uring_lock);
2101 static void kiocb_end_write(struct io_kiocb *req)
2104 * Tell lockdep we inherited freeze protection from submission
2107 if (req->flags & REQ_F_ISREG) {
2108 struct inode *inode = file_inode(req->file);
2110 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2112 file_end_write(req->file);
2115 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2116 struct io_comp_state *cs)
2118 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2121 if (kiocb->ki_flags & IOCB_WRITE)
2122 kiocb_end_write(req);
2124 if (res != req->result)
2125 req_set_fail_links(req);
2126 if (req->flags & REQ_F_BUFFER_SELECTED)
2127 cflags = io_put_kbuf(req);
2128 __io_req_complete(req, res, cflags, cs);
2132 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2134 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2135 ssize_t ret = -ECANCELED;
2136 struct iov_iter iter;
2144 switch (req->opcode) {
2145 case IORING_OP_READV:
2146 case IORING_OP_READ_FIXED:
2147 case IORING_OP_READ:
2150 case IORING_OP_WRITEV:
2151 case IORING_OP_WRITE_FIXED:
2152 case IORING_OP_WRITE:
2156 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2161 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2164 ret = io_setup_async_rw(req, ret, iovec, inline_vecs, &iter);
2169 req_set_fail_links(req);
2170 io_req_complete(req, ret);
2174 static void io_rw_resubmit(struct callback_head *cb)
2176 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2177 struct io_ring_ctx *ctx = req->ctx;
2180 __set_current_state(TASK_RUNNING);
2182 err = io_sq_thread_acquire_mm(ctx, req);
2184 if (io_resubmit_prep(req, err)) {
2185 refcount_inc(&req->refs);
2186 io_queue_async_work(req);
2191 static bool io_rw_reissue(struct io_kiocb *req, long res)
2194 struct task_struct *tsk;
2197 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2201 init_task_work(&req->task_work, io_rw_resubmit);
2202 ret = task_work_add(tsk, &req->task_work, true);
2209 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2210 struct io_comp_state *cs)
2212 if (!io_rw_reissue(req, res))
2213 io_complete_rw_common(&req->rw.kiocb, res, cs);
2216 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2218 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2220 __io_complete_rw(req, res, res2, NULL);
2223 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2225 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2227 if (kiocb->ki_flags & IOCB_WRITE)
2228 kiocb_end_write(req);
2230 if (res != -EAGAIN && res != req->result)
2231 req_set_fail_links(req);
2233 WRITE_ONCE(req->result, res);
2234 /* order with io_poll_complete() checking ->result */
2236 WRITE_ONCE(req->iopoll_completed, 1);
2240 * After the iocb has been issued, it's safe to be found on the poll list.
2241 * Adding the kiocb to the list AFTER submission ensures that we don't
2242 * find it from a io_iopoll_getevents() thread before the issuer is done
2243 * accessing the kiocb cookie.
2245 static void io_iopoll_req_issued(struct io_kiocb *req)
2247 struct io_ring_ctx *ctx = req->ctx;
2250 * Track whether we have multiple files in our lists. This will impact
2251 * how we do polling eventually, not spinning if we're on potentially
2252 * different devices.
2254 if (list_empty(&ctx->poll_list)) {
2255 ctx->poll_multi_file = false;
2256 } else if (!ctx->poll_multi_file) {
2257 struct io_kiocb *list_req;
2259 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
2261 if (list_req->file != req->file)
2262 ctx->poll_multi_file = true;
2266 * For fast devices, IO may have already completed. If it has, add
2267 * it to the front so we find it first.
2269 if (READ_ONCE(req->iopoll_completed))
2270 list_add(&req->list, &ctx->poll_list);
2272 list_add_tail(&req->list, &ctx->poll_list);
2274 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2275 wq_has_sleeper(&ctx->sqo_wait))
2276 wake_up(&ctx->sqo_wait);
2279 static void __io_state_file_put(struct io_submit_state *state)
2281 int diff = state->has_refs - state->used_refs;
2284 fput_many(state->file, diff);
2288 static inline void io_state_file_put(struct io_submit_state *state)
2291 __io_state_file_put(state);
2295 * Get as many references to a file as we have IOs left in this submission,
2296 * assuming most submissions are for one file, or at least that each file
2297 * has more than one submission.
2299 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2305 if (state->fd == fd) {
2310 __io_state_file_put(state);
2312 state->file = fget_many(fd, state->ios_left);
2317 state->has_refs = state->ios_left;
2318 state->used_refs = 1;
2323 static bool io_bdev_nowait(struct block_device *bdev)
2326 return !bdev || queue_is_mq(bdev_get_queue(bdev));
2333 * If we tracked the file through the SCM inflight mechanism, we could support
2334 * any file. For now, just ensure that anything potentially problematic is done
2337 static bool io_file_supports_async(struct file *file, int rw)
2339 umode_t mode = file_inode(file)->i_mode;
2341 if (S_ISBLK(mode)) {
2342 if (io_bdev_nowait(file->f_inode->i_bdev))
2346 if (S_ISCHR(mode) || S_ISSOCK(mode))
2348 if (S_ISREG(mode)) {
2349 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2350 file->f_op != &io_uring_fops)
2355 /* any ->read/write should understand O_NONBLOCK */
2356 if (file->f_flags & O_NONBLOCK)
2359 if (!(file->f_mode & FMODE_NOWAIT))
2363 return file->f_op->read_iter != NULL;
2365 return file->f_op->write_iter != NULL;
2368 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2369 bool force_nonblock)
2371 struct io_ring_ctx *ctx = req->ctx;
2372 struct kiocb *kiocb = &req->rw.kiocb;
2376 if (S_ISREG(file_inode(req->file)->i_mode))
2377 req->flags |= REQ_F_ISREG;
2379 kiocb->ki_pos = READ_ONCE(sqe->off);
2380 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2381 req->flags |= REQ_F_CUR_POS;
2382 kiocb->ki_pos = req->file->f_pos;
2384 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2385 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2386 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2390 ioprio = READ_ONCE(sqe->ioprio);
2392 ret = ioprio_check_cap(ioprio);
2396 kiocb->ki_ioprio = ioprio;
2398 kiocb->ki_ioprio = get_current_ioprio();
2400 /* don't allow async punt if RWF_NOWAIT was requested */
2401 if (kiocb->ki_flags & IOCB_NOWAIT)
2402 req->flags |= REQ_F_NOWAIT;
2404 if (kiocb->ki_flags & IOCB_DIRECT)
2405 io_get_req_task(req);
2408 kiocb->ki_flags |= IOCB_NOWAIT;
2410 if (ctx->flags & IORING_SETUP_IOPOLL) {
2411 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2412 !kiocb->ki_filp->f_op->iopoll)
2415 kiocb->ki_flags |= IOCB_HIPRI;
2416 kiocb->ki_complete = io_complete_rw_iopoll;
2418 req->iopoll_completed = 0;
2420 if (kiocb->ki_flags & IOCB_HIPRI)
2422 kiocb->ki_complete = io_complete_rw;
2425 req->rw.addr = READ_ONCE(sqe->addr);
2426 req->rw.len = READ_ONCE(sqe->len);
2427 req->buf_index = READ_ONCE(sqe->buf_index);
2431 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2437 case -ERESTARTNOINTR:
2438 case -ERESTARTNOHAND:
2439 case -ERESTART_RESTARTBLOCK:
2441 * We can't just restart the syscall, since previously
2442 * submitted sqes may already be in progress. Just fail this
2448 kiocb->ki_complete(kiocb, ret, 0);
2452 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2453 struct io_comp_state *cs)
2455 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2457 if (req->flags & REQ_F_CUR_POS)
2458 req->file->f_pos = kiocb->ki_pos;
2459 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2460 __io_complete_rw(req, ret, 0, cs);
2462 io_rw_done(kiocb, ret);
2465 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2466 struct iov_iter *iter)
2468 struct io_ring_ctx *ctx = req->ctx;
2469 size_t len = req->rw.len;
2470 struct io_mapped_ubuf *imu;
2471 u16 index, buf_index;
2475 /* attempt to use fixed buffers without having provided iovecs */
2476 if (unlikely(!ctx->user_bufs))
2479 buf_index = req->buf_index;
2480 if (unlikely(buf_index >= ctx->nr_user_bufs))
2483 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2484 imu = &ctx->user_bufs[index];
2485 buf_addr = req->rw.addr;
2488 if (buf_addr + len < buf_addr)
2490 /* not inside the mapped region */
2491 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2495 * May not be a start of buffer, set size appropriately
2496 * and advance us to the beginning.
2498 offset = buf_addr - imu->ubuf;
2499 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2503 * Don't use iov_iter_advance() here, as it's really slow for
2504 * using the latter parts of a big fixed buffer - it iterates
2505 * over each segment manually. We can cheat a bit here, because
2508 * 1) it's a BVEC iter, we set it up
2509 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2510 * first and last bvec
2512 * So just find our index, and adjust the iterator afterwards.
2513 * If the offset is within the first bvec (or the whole first
2514 * bvec, just use iov_iter_advance(). This makes it easier
2515 * since we can just skip the first segment, which may not
2516 * be PAGE_SIZE aligned.
2518 const struct bio_vec *bvec = imu->bvec;
2520 if (offset <= bvec->bv_len) {
2521 iov_iter_advance(iter, offset);
2523 unsigned long seg_skip;
2525 /* skip first vec */
2526 offset -= bvec->bv_len;
2527 seg_skip = 1 + (offset >> PAGE_SHIFT);
2529 iter->bvec = bvec + seg_skip;
2530 iter->nr_segs -= seg_skip;
2531 iter->count -= bvec->bv_len + offset;
2532 iter->iov_offset = offset & ~PAGE_MASK;
2539 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2542 mutex_unlock(&ctx->uring_lock);
2545 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2548 * "Normal" inline submissions always hold the uring_lock, since we
2549 * grab it from the system call. Same is true for the SQPOLL offload.
2550 * The only exception is when we've detached the request and issue it
2551 * from an async worker thread, grab the lock for that case.
2554 mutex_lock(&ctx->uring_lock);
2557 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2558 int bgid, struct io_buffer *kbuf,
2561 struct io_buffer *head;
2563 if (req->flags & REQ_F_BUFFER_SELECTED)
2566 io_ring_submit_lock(req->ctx, needs_lock);
2568 lockdep_assert_held(&req->ctx->uring_lock);
2570 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2572 if (!list_empty(&head->list)) {
2573 kbuf = list_last_entry(&head->list, struct io_buffer,
2575 list_del(&kbuf->list);
2578 idr_remove(&req->ctx->io_buffer_idr, bgid);
2580 if (*len > kbuf->len)
2583 kbuf = ERR_PTR(-ENOBUFS);
2586 io_ring_submit_unlock(req->ctx, needs_lock);
2591 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2594 struct io_buffer *kbuf;
2597 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2598 bgid = req->buf_index;
2599 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2602 req->rw.addr = (u64) (unsigned long) kbuf;
2603 req->flags |= REQ_F_BUFFER_SELECTED;
2604 return u64_to_user_ptr(kbuf->addr);
2607 #ifdef CONFIG_COMPAT
2608 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2611 struct compat_iovec __user *uiov;
2612 compat_ssize_t clen;
2616 uiov = u64_to_user_ptr(req->rw.addr);
2617 if (!access_ok(uiov, sizeof(*uiov)))
2619 if (__get_user(clen, &uiov->iov_len))
2625 buf = io_rw_buffer_select(req, &len, needs_lock);
2627 return PTR_ERR(buf);
2628 iov[0].iov_base = buf;
2629 iov[0].iov_len = (compat_size_t) len;
2634 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2637 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2641 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2644 len = iov[0].iov_len;
2647 buf = io_rw_buffer_select(req, &len, needs_lock);
2649 return PTR_ERR(buf);
2650 iov[0].iov_base = buf;
2651 iov[0].iov_len = len;
2655 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2658 if (req->flags & REQ_F_BUFFER_SELECTED) {
2659 struct io_buffer *kbuf;
2661 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2662 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2663 iov[0].iov_len = kbuf->len;
2668 else if (req->rw.len > 1)
2671 #ifdef CONFIG_COMPAT
2672 if (req->ctx->compat)
2673 return io_compat_import(req, iov, needs_lock);
2676 return __io_iov_buffer_select(req, iov, needs_lock);
2679 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2680 struct iovec **iovec, struct iov_iter *iter,
2683 void __user *buf = u64_to_user_ptr(req->rw.addr);
2684 size_t sqe_len = req->rw.len;
2688 opcode = req->opcode;
2689 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2691 return io_import_fixed(req, rw, iter);
2694 /* buffer index only valid with fixed read/write, or buffer select */
2695 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2698 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2699 if (req->flags & REQ_F_BUFFER_SELECT) {
2700 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2703 return PTR_ERR(buf);
2705 req->rw.len = sqe_len;
2708 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2710 return ret < 0 ? ret : sqe_len;
2714 struct io_async_rw *iorw = &req->io->rw;
2717 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2718 if (iorw->iov == iorw->fast_iov)
2723 if (req->flags & REQ_F_BUFFER_SELECT) {
2724 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2726 ret = (*iovec)->iov_len;
2727 iov_iter_init(iter, rw, *iovec, 1, ret);
2733 #ifdef CONFIG_COMPAT
2734 if (req->ctx->compat)
2735 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2739 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2743 * For files that don't have ->read_iter() and ->write_iter(), handle them
2744 * by looping over ->read() or ->write() manually.
2746 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2747 struct iov_iter *iter)
2752 * Don't support polled IO through this interface, and we can't
2753 * support non-blocking either. For the latter, this just causes
2754 * the kiocb to be handled from an async context.
2756 if (kiocb->ki_flags & IOCB_HIPRI)
2758 if (kiocb->ki_flags & IOCB_NOWAIT)
2761 while (iov_iter_count(iter)) {
2765 if (!iov_iter_is_bvec(iter)) {
2766 iovec = iov_iter_iovec(iter);
2768 /* fixed buffers import bvec */
2769 iovec.iov_base = kmap(iter->bvec->bv_page)
2771 iovec.iov_len = min(iter->count,
2772 iter->bvec->bv_len - iter->iov_offset);
2776 nr = file->f_op->read(file, iovec.iov_base,
2777 iovec.iov_len, &kiocb->ki_pos);
2779 nr = file->f_op->write(file, iovec.iov_base,
2780 iovec.iov_len, &kiocb->ki_pos);
2783 if (iov_iter_is_bvec(iter))
2784 kunmap(iter->bvec->bv_page);
2792 if (nr != iovec.iov_len)
2794 iov_iter_advance(iter, nr);
2800 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2801 struct iovec *iovec, struct iovec *fast_iov,
2802 struct iov_iter *iter)
2804 req->io->rw.nr_segs = iter->nr_segs;
2805 req->io->rw.size = io_size;
2806 req->io->rw.iov = iovec;
2807 if (!req->io->rw.iov) {
2808 req->io->rw.iov = req->io->rw.fast_iov;
2809 if (req->io->rw.iov != fast_iov)
2810 memcpy(req->io->rw.iov, fast_iov,
2811 sizeof(struct iovec) * iter->nr_segs);
2813 req->flags |= REQ_F_NEED_CLEANUP;
2817 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2819 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2820 return req->io == NULL;
2823 static int io_alloc_async_ctx(struct io_kiocb *req)
2825 if (!io_op_defs[req->opcode].async_ctx)
2828 return __io_alloc_async_ctx(req);
2831 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2832 struct iovec *iovec, struct iovec *fast_iov,
2833 struct iov_iter *iter)
2835 if (!io_op_defs[req->opcode].async_ctx)
2838 if (__io_alloc_async_ctx(req))
2841 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2846 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2847 bool force_nonblock)
2849 struct io_async_ctx *io;
2850 struct iov_iter iter;
2853 ret = io_prep_rw(req, sqe, force_nonblock);
2857 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2860 /* either don't need iovec imported or already have it */
2861 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2865 io->rw.iov = io->rw.fast_iov;
2867 ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2872 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2876 static void io_async_buf_cancel(struct callback_head *cb)
2878 struct io_async_rw *rw;
2879 struct io_kiocb *req;
2881 rw = container_of(cb, struct io_async_rw, task_work);
2882 req = rw->wpq.wait.private;
2883 __io_req_task_cancel(req, -ECANCELED);
2886 static void io_async_buf_retry(struct callback_head *cb)
2888 struct io_async_rw *rw;
2889 struct io_kiocb *req;
2891 rw = container_of(cb, struct io_async_rw, task_work);
2892 req = rw->wpq.wait.private;
2894 __io_req_task_submit(req);
2897 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2898 int sync, void *arg)
2900 struct wait_page_queue *wpq;
2901 struct io_kiocb *req = wait->private;
2902 struct io_async_rw *rw = &req->io->rw;
2903 struct wait_page_key *key = arg;
2904 struct task_struct *tsk;
2907 wpq = container_of(wait, struct wait_page_queue, wait);
2909 ret = wake_page_match(wpq, key);
2913 list_del_init(&wait->entry);
2915 init_task_work(&rw->task_work, io_async_buf_retry);
2916 /* submit ref gets dropped, acquire a new one */
2917 refcount_inc(&req->refs);
2919 ret = task_work_add(tsk, &rw->task_work, true);
2920 if (unlikely(ret)) {
2921 /* queue just for cancelation */
2922 init_task_work(&rw->task_work, io_async_buf_cancel);
2923 tsk = io_wq_get_task(req->ctx->io_wq);
2924 task_work_add(tsk, &rw->task_work, true);
2926 wake_up_process(tsk);
2930 static bool io_rw_should_retry(struct io_kiocb *req)
2932 struct kiocb *kiocb = &req->rw.kiocb;
2935 /* never retry for NOWAIT, we just complete with -EAGAIN */
2936 if (req->flags & REQ_F_NOWAIT)
2939 /* already tried, or we're doing O_DIRECT */
2940 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_WAITQ))
2943 * just use poll if we can, and don't attempt if the fs doesn't
2944 * support callback based unlocks
2946 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2950 * If request type doesn't require req->io to defer in general,
2951 * we need to allocate it here
2953 if (!req->io && __io_alloc_async_ctx(req))
2956 ret = kiocb_wait_page_queue_init(kiocb, &req->io->rw.wpq,
2957 io_async_buf_func, req);
2959 io_get_req_task(req);
2966 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
2968 if (req->file->f_op->read_iter)
2969 return call_read_iter(req->file, &req->rw.kiocb, iter);
2970 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
2973 static int io_read(struct io_kiocb *req, bool force_nonblock,
2974 struct io_comp_state *cs)
2976 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2977 struct kiocb *kiocb = &req->rw.kiocb;
2978 struct iov_iter iter;
2980 ssize_t io_size, ret;
2982 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2986 /* Ensure we clear previously set non-block flag */
2987 if (!force_nonblock)
2988 kiocb->ki_flags &= ~IOCB_NOWAIT;
2992 if (req->flags & REQ_F_LINK_HEAD)
2993 req->result = io_size;
2995 /* If the file doesn't support async, just async punt */
2996 if (force_nonblock && !io_file_supports_async(req->file, READ))
2999 iov_count = iov_iter_count(&iter);
3000 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
3002 unsigned long nr_segs = iter.nr_segs;
3005 ret2 = io_iter_do_read(req, &iter);
3007 /* Catch -EAGAIN return for forced non-blocking submission */
3008 if (!force_nonblock || (ret2 != -EAGAIN && ret2 != -EIO)) {
3009 kiocb_done(kiocb, ret2, cs);
3011 iter.count = iov_count;
3012 iter.nr_segs = nr_segs;
3014 ret = io_setup_async_rw(req, io_size, iovec,
3015 inline_vecs, &iter);
3018 /* if we can retry, do so with the callbacks armed */
3019 if (io_rw_should_retry(req)) {
3020 ret2 = io_iter_do_read(req, &iter);
3021 if (ret2 == -EIOCBQUEUED) {
3023 } else if (ret2 != -EAGAIN) {
3024 kiocb_done(kiocb, ret2, cs);
3028 kiocb->ki_flags &= ~IOCB_WAITQ;
3033 if (!(req->flags & REQ_F_NEED_CLEANUP))
3038 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3039 bool force_nonblock)
3041 struct io_async_ctx *io;
3042 struct iov_iter iter;
3045 ret = io_prep_rw(req, sqe, force_nonblock);
3049 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3052 req->fsize = rlimit(RLIMIT_FSIZE);
3054 /* either don't need iovec imported or already have it */
3055 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3059 io->rw.iov = io->rw.fast_iov;
3061 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
3066 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
3070 static int io_write(struct io_kiocb *req, bool force_nonblock,
3071 struct io_comp_state *cs)
3073 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3074 struct kiocb *kiocb = &req->rw.kiocb;
3075 struct iov_iter iter;
3077 ssize_t ret, io_size;
3079 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
3083 /* Ensure we clear previously set non-block flag */
3084 if (!force_nonblock)
3085 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
3089 if (req->flags & REQ_F_LINK_HEAD)
3090 req->result = io_size;
3092 /* If the file doesn't support async, just async punt */
3093 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3096 /* file path doesn't support NOWAIT for non-direct_IO */
3097 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3098 (req->flags & REQ_F_ISREG))
3101 iov_count = iov_iter_count(&iter);
3102 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
3104 unsigned long nr_segs = iter.nr_segs;
3108 * Open-code file_start_write here to grab freeze protection,
3109 * which will be released by another thread in
3110 * io_complete_rw(). Fool lockdep by telling it the lock got
3111 * released so that it doesn't complain about the held lock when
3112 * we return to userspace.
3114 if (req->flags & REQ_F_ISREG) {
3115 __sb_start_write(file_inode(req->file)->i_sb,
3116 SB_FREEZE_WRITE, true);
3117 __sb_writers_release(file_inode(req->file)->i_sb,
3120 kiocb->ki_flags |= IOCB_WRITE;
3122 if (!force_nonblock)
3123 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3125 if (req->file->f_op->write_iter)
3126 ret2 = call_write_iter(req->file, kiocb, &iter);
3128 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
3130 if (!force_nonblock)
3131 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3134 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3135 * retry them without IOCB_NOWAIT.
3137 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3139 if (!force_nonblock || ret2 != -EAGAIN) {
3140 kiocb_done(kiocb, ret2, cs);
3142 iter.count = iov_count;
3143 iter.nr_segs = nr_segs;
3145 ret = io_setup_async_rw(req, io_size, iovec,
3146 inline_vecs, &iter);
3153 if (!(req->flags & REQ_F_NEED_CLEANUP))
3158 static int __io_splice_prep(struct io_kiocb *req,
3159 const struct io_uring_sqe *sqe)
3161 struct io_splice* sp = &req->splice;
3162 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3165 if (req->flags & REQ_F_NEED_CLEANUP)
3167 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3171 sp->len = READ_ONCE(sqe->len);
3172 sp->flags = READ_ONCE(sqe->splice_flags);
3174 if (unlikely(sp->flags & ~valid_flags))
3177 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
3178 (sp->flags & SPLICE_F_FD_IN_FIXED));
3181 req->flags |= REQ_F_NEED_CLEANUP;
3183 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3185 * Splice operation will be punted aync, and here need to
3186 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3188 io_req_init_async(req);
3189 req->work.flags |= IO_WQ_WORK_UNBOUND;
3195 static int io_tee_prep(struct io_kiocb *req,
3196 const struct io_uring_sqe *sqe)
3198 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3200 return __io_splice_prep(req, sqe);
3203 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3205 struct io_splice *sp = &req->splice;
3206 struct file *in = sp->file_in;
3207 struct file *out = sp->file_out;
3208 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3214 ret = do_tee(in, out, sp->len, flags);
3216 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3217 req->flags &= ~REQ_F_NEED_CLEANUP;
3220 req_set_fail_links(req);
3221 io_req_complete(req, ret);
3225 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3227 struct io_splice* sp = &req->splice;
3229 sp->off_in = READ_ONCE(sqe->splice_off_in);
3230 sp->off_out = READ_ONCE(sqe->off);
3231 return __io_splice_prep(req, sqe);
3234 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3236 struct io_splice *sp = &req->splice;
3237 struct file *in = sp->file_in;
3238 struct file *out = sp->file_out;
3239 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3240 loff_t *poff_in, *poff_out;
3246 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3247 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3250 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3252 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3253 req->flags &= ~REQ_F_NEED_CLEANUP;
3256 req_set_fail_links(req);
3257 io_req_complete(req, ret);
3262 * IORING_OP_NOP just posts a completion event, nothing else.
3264 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3266 struct io_ring_ctx *ctx = req->ctx;
3268 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3271 __io_req_complete(req, 0, 0, cs);
3275 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3277 struct io_ring_ctx *ctx = req->ctx;
3282 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3284 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3287 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3288 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3291 req->sync.off = READ_ONCE(sqe->off);
3292 req->sync.len = READ_ONCE(sqe->len);
3296 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3298 loff_t end = req->sync.off + req->sync.len;
3301 /* fsync always requires a blocking context */
3305 ret = vfs_fsync_range(req->file, req->sync.off,
3306 end > 0 ? end : LLONG_MAX,
3307 req->sync.flags & IORING_FSYNC_DATASYNC);
3309 req_set_fail_links(req);
3310 io_req_complete(req, ret);
3314 static int io_fallocate_prep(struct io_kiocb *req,
3315 const struct io_uring_sqe *sqe)
3317 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3319 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3322 req->sync.off = READ_ONCE(sqe->off);
3323 req->sync.len = READ_ONCE(sqe->addr);
3324 req->sync.mode = READ_ONCE(sqe->len);
3325 req->fsize = rlimit(RLIMIT_FSIZE);
3329 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3333 /* fallocate always requiring blocking context */
3337 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3338 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3340 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3342 req_set_fail_links(req);
3343 io_req_complete(req, ret);
3347 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3349 const char __user *fname;
3352 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3354 if (unlikely(sqe->ioprio || sqe->buf_index))
3356 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3359 /* open.how should be already initialised */
3360 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3361 req->open.how.flags |= O_LARGEFILE;
3363 req->open.dfd = READ_ONCE(sqe->fd);
3364 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3365 req->open.filename = getname(fname);
3366 if (IS_ERR(req->open.filename)) {
3367 ret = PTR_ERR(req->open.filename);
3368 req->open.filename = NULL;
3371 req->open.nofile = rlimit(RLIMIT_NOFILE);
3372 req->flags |= REQ_F_NEED_CLEANUP;
3376 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3380 if (req->flags & REQ_F_NEED_CLEANUP)
3382 mode = READ_ONCE(sqe->len);
3383 flags = READ_ONCE(sqe->open_flags);
3384 req->open.how = build_open_how(flags, mode);
3385 return __io_openat_prep(req, sqe);
3388 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3390 struct open_how __user *how;
3394 if (req->flags & REQ_F_NEED_CLEANUP)
3396 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3397 len = READ_ONCE(sqe->len);
3398 if (len < OPEN_HOW_SIZE_VER0)
3401 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3406 return __io_openat_prep(req, sqe);
3409 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3411 struct open_flags op;
3418 ret = build_open_flags(&req->open.how, &op);
3422 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3426 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3429 ret = PTR_ERR(file);
3431 fsnotify_open(file);
3432 fd_install(ret, file);
3435 putname(req->open.filename);
3436 req->flags &= ~REQ_F_NEED_CLEANUP;
3438 req_set_fail_links(req);
3439 io_req_complete(req, ret);
3443 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3445 return io_openat2(req, force_nonblock);
3448 static int io_remove_buffers_prep(struct io_kiocb *req,
3449 const struct io_uring_sqe *sqe)
3451 struct io_provide_buf *p = &req->pbuf;
3454 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3457 tmp = READ_ONCE(sqe->fd);
3458 if (!tmp || tmp > USHRT_MAX)
3461 memset(p, 0, sizeof(*p));
3463 p->bgid = READ_ONCE(sqe->buf_group);
3467 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3468 int bgid, unsigned nbufs)
3472 /* shouldn't happen */
3476 /* the head kbuf is the list itself */
3477 while (!list_empty(&buf->list)) {
3478 struct io_buffer *nxt;
3480 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3481 list_del(&nxt->list);
3488 idr_remove(&ctx->io_buffer_idr, bgid);
3493 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3494 struct io_comp_state *cs)
3496 struct io_provide_buf *p = &req->pbuf;
3497 struct io_ring_ctx *ctx = req->ctx;
3498 struct io_buffer *head;
3501 io_ring_submit_lock(ctx, !force_nonblock);
3503 lockdep_assert_held(&ctx->uring_lock);
3506 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3508 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3510 io_ring_submit_lock(ctx, !force_nonblock);
3512 req_set_fail_links(req);
3513 __io_req_complete(req, ret, 0, cs);
3517 static int io_provide_buffers_prep(struct io_kiocb *req,
3518 const struct io_uring_sqe *sqe)
3520 struct io_provide_buf *p = &req->pbuf;
3523 if (sqe->ioprio || sqe->rw_flags)
3526 tmp = READ_ONCE(sqe->fd);
3527 if (!tmp || tmp > USHRT_MAX)
3530 p->addr = READ_ONCE(sqe->addr);
3531 p->len = READ_ONCE(sqe->len);
3533 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3536 p->bgid = READ_ONCE(sqe->buf_group);
3537 tmp = READ_ONCE(sqe->off);
3538 if (tmp > USHRT_MAX)
3544 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3546 struct io_buffer *buf;
3547 u64 addr = pbuf->addr;
3548 int i, bid = pbuf->bid;
3550 for (i = 0; i < pbuf->nbufs; i++) {
3551 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3556 buf->len = pbuf->len;
3561 INIT_LIST_HEAD(&buf->list);
3564 list_add_tail(&buf->list, &(*head)->list);
3568 return i ? i : -ENOMEM;
3571 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3572 struct io_comp_state *cs)
3574 struct io_provide_buf *p = &req->pbuf;
3575 struct io_ring_ctx *ctx = req->ctx;
3576 struct io_buffer *head, *list;
3579 io_ring_submit_lock(ctx, !force_nonblock);
3581 lockdep_assert_held(&ctx->uring_lock);
3583 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3585 ret = io_add_buffers(p, &head);
3590 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3593 __io_remove_buffers(ctx, head, p->bgid, -1U);
3598 io_ring_submit_unlock(ctx, !force_nonblock);
3600 req_set_fail_links(req);
3601 __io_req_complete(req, ret, 0, cs);
3605 static int io_epoll_ctl_prep(struct io_kiocb *req,
3606 const struct io_uring_sqe *sqe)
3608 #if defined(CONFIG_EPOLL)
3609 if (sqe->ioprio || sqe->buf_index)
3611 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3614 req->epoll.epfd = READ_ONCE(sqe->fd);
3615 req->epoll.op = READ_ONCE(sqe->len);
3616 req->epoll.fd = READ_ONCE(sqe->off);
3618 if (ep_op_has_event(req->epoll.op)) {
3619 struct epoll_event __user *ev;
3621 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3622 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3632 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3633 struct io_comp_state *cs)
3635 #if defined(CONFIG_EPOLL)
3636 struct io_epoll *ie = &req->epoll;
3639 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3640 if (force_nonblock && ret == -EAGAIN)
3644 req_set_fail_links(req);
3645 __io_req_complete(req, ret, 0, cs);
3652 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3654 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3655 if (sqe->ioprio || sqe->buf_index || sqe->off)
3657 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3660 req->madvise.addr = READ_ONCE(sqe->addr);
3661 req->madvise.len = READ_ONCE(sqe->len);
3662 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3669 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3671 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3672 struct io_madvise *ma = &req->madvise;
3678 ret = do_madvise(ma->addr, ma->len, ma->advice);
3680 req_set_fail_links(req);
3681 io_req_complete(req, ret);
3688 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3690 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3692 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3695 req->fadvise.offset = READ_ONCE(sqe->off);
3696 req->fadvise.len = READ_ONCE(sqe->len);
3697 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3701 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3703 struct io_fadvise *fa = &req->fadvise;
3706 if (force_nonblock) {
3707 switch (fa->advice) {
3708 case POSIX_FADV_NORMAL:
3709 case POSIX_FADV_RANDOM:
3710 case POSIX_FADV_SEQUENTIAL:
3717 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3719 req_set_fail_links(req);
3720 io_req_complete(req, ret);
3724 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3726 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3728 if (sqe->ioprio || sqe->buf_index)
3730 if (req->flags & REQ_F_FIXED_FILE)
3733 req->statx.dfd = READ_ONCE(sqe->fd);
3734 req->statx.mask = READ_ONCE(sqe->len);
3735 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
3736 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3737 req->statx.flags = READ_ONCE(sqe->statx_flags);
3742 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3744 struct io_statx *ctx = &req->statx;
3747 if (force_nonblock) {
3748 /* only need file table for an actual valid fd */
3749 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3750 req->flags |= REQ_F_NO_FILE_TABLE;
3754 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3758 req_set_fail_links(req);
3759 io_req_complete(req, ret);
3763 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3766 * If we queue this for async, it must not be cancellable. That would
3767 * leave the 'file' in an undeterminate state, and here need to modify
3768 * io_wq_work.flags, so initialize io_wq_work firstly.
3770 io_req_init_async(req);
3771 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3773 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3775 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3776 sqe->rw_flags || sqe->buf_index)
3778 if (req->flags & REQ_F_FIXED_FILE)
3781 req->close.fd = READ_ONCE(sqe->fd);
3782 if ((req->file && req->file->f_op == &io_uring_fops) ||
3783 req->close.fd == req->ctx->ring_fd)
3786 req->close.put_file = NULL;
3790 static int io_close(struct io_kiocb *req, bool force_nonblock,
3791 struct io_comp_state *cs)
3793 struct io_close *close = &req->close;
3796 /* might be already done during nonblock submission */
3797 if (!close->put_file) {
3798 ret = __close_fd_get_file(close->fd, &close->put_file);
3800 return (ret == -ENOENT) ? -EBADF : ret;
3803 /* if the file has a flush method, be safe and punt to async */
3804 if (close->put_file->f_op->flush && force_nonblock) {
3805 /* was never set, but play safe */
3806 req->flags &= ~REQ_F_NOWAIT;
3807 /* avoid grabbing files - we don't need the files */
3808 req->flags |= REQ_F_NO_FILE_TABLE;
3812 /* No ->flush() or already async, safely close from here */
3813 ret = filp_close(close->put_file, req->work.files);
3815 req_set_fail_links(req);
3816 fput(close->put_file);
3817 close->put_file = NULL;
3818 __io_req_complete(req, ret, 0, cs);
3822 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3824 struct io_ring_ctx *ctx = req->ctx;
3829 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3831 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3834 req->sync.off = READ_ONCE(sqe->off);
3835 req->sync.len = READ_ONCE(sqe->len);
3836 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3840 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3844 /* sync_file_range always requires a blocking context */
3848 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3851 req_set_fail_links(req);
3852 io_req_complete(req, ret);
3856 #if defined(CONFIG_NET)
3857 static int io_setup_async_msg(struct io_kiocb *req,
3858 struct io_async_msghdr *kmsg)
3862 if (io_alloc_async_ctx(req)) {
3863 if (kmsg->iov != kmsg->fast_iov)
3867 req->flags |= REQ_F_NEED_CLEANUP;
3868 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3872 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3874 struct io_sr_msg *sr = &req->sr_msg;
3875 struct io_async_ctx *io = req->io;
3878 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3881 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3882 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3883 sr->len = READ_ONCE(sqe->len);
3885 #ifdef CONFIG_COMPAT
3886 if (req->ctx->compat)
3887 sr->msg_flags |= MSG_CMSG_COMPAT;
3890 if (!io || req->opcode == IORING_OP_SEND)
3892 /* iovec is already imported */
3893 if (req->flags & REQ_F_NEED_CLEANUP)
3896 io->msg.iov = io->msg.fast_iov;
3897 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3900 req->flags |= REQ_F_NEED_CLEANUP;
3904 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
3905 struct io_comp_state *cs)
3907 struct io_async_msghdr *kmsg = NULL;
3908 struct socket *sock;
3911 sock = sock_from_file(req->file, &ret);
3913 struct io_async_ctx io;
3917 kmsg = &req->io->msg;
3918 kmsg->msg.msg_name = &req->io->msg.addr;
3919 /* if iov is set, it's allocated already */
3921 kmsg->iov = kmsg->fast_iov;
3922 kmsg->msg.msg_iter.iov = kmsg->iov;
3924 struct io_sr_msg *sr = &req->sr_msg;
3927 kmsg->msg.msg_name = &io.msg.addr;
3929 io.msg.iov = io.msg.fast_iov;
3930 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3931 sr->msg_flags, &io.msg.iov);
3936 flags = req->sr_msg.msg_flags;
3937 if (flags & MSG_DONTWAIT)
3938 req->flags |= REQ_F_NOWAIT;
3939 else if (force_nonblock)
3940 flags |= MSG_DONTWAIT;
3942 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3943 if (force_nonblock && ret == -EAGAIN)
3944 return io_setup_async_msg(req, kmsg);
3945 if (ret == -ERESTARTSYS)
3949 if (kmsg && kmsg->iov != kmsg->fast_iov)
3951 req->flags &= ~REQ_F_NEED_CLEANUP;
3953 req_set_fail_links(req);
3954 __io_req_complete(req, ret, 0, cs);
3958 static int io_send(struct io_kiocb *req, bool force_nonblock,
3959 struct io_comp_state *cs)
3961 struct socket *sock;
3964 sock = sock_from_file(req->file, &ret);
3966 struct io_sr_msg *sr = &req->sr_msg;
3971 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3976 msg.msg_name = NULL;
3977 msg.msg_control = NULL;
3978 msg.msg_controllen = 0;
3979 msg.msg_namelen = 0;
3981 flags = req->sr_msg.msg_flags;
3982 if (flags & MSG_DONTWAIT)
3983 req->flags |= REQ_F_NOWAIT;
3984 else if (force_nonblock)
3985 flags |= MSG_DONTWAIT;
3987 msg.msg_flags = flags;
3988 ret = sock_sendmsg(sock, &msg);
3989 if (force_nonblock && ret == -EAGAIN)
3991 if (ret == -ERESTARTSYS)
3996 req_set_fail_links(req);
3997 __io_req_complete(req, ret, 0, cs);
4001 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
4003 struct io_sr_msg *sr = &req->sr_msg;
4004 struct iovec __user *uiov;
4008 ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
4013 if (req->flags & REQ_F_BUFFER_SELECT) {
4016 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
4018 sr->len = io->msg.iov[0].iov_len;
4019 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
4023 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4024 &io->msg.iov, &io->msg.msg.msg_iter);
4032 #ifdef CONFIG_COMPAT
4033 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4034 struct io_async_ctx *io)
4036 struct compat_msghdr __user *msg_compat;
4037 struct io_sr_msg *sr = &req->sr_msg;
4038 struct compat_iovec __user *uiov;
4043 msg_compat = (struct compat_msghdr __user *) sr->msg;
4044 ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
4049 uiov = compat_ptr(ptr);
4050 if (req->flags & REQ_F_BUFFER_SELECT) {
4051 compat_ssize_t clen;
4055 if (!access_ok(uiov, sizeof(*uiov)))
4057 if (__get_user(clen, &uiov->iov_len))
4061 sr->len = io->msg.iov[0].iov_len;
4064 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
4066 &io->msg.msg.msg_iter);
4075 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
4077 io->msg.iov = io->msg.fast_iov;
4079 #ifdef CONFIG_COMPAT
4080 if (req->ctx->compat)
4081 return __io_compat_recvmsg_copy_hdr(req, io);
4084 return __io_recvmsg_copy_hdr(req, io);
4087 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4088 int *cflags, bool needs_lock)
4090 struct io_sr_msg *sr = &req->sr_msg;
4091 struct io_buffer *kbuf;
4093 if (!(req->flags & REQ_F_BUFFER_SELECT))
4096 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4101 req->flags |= REQ_F_BUFFER_SELECTED;
4103 *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
4104 *cflags |= IORING_CQE_F_BUFFER;
4108 static int io_recvmsg_prep(struct io_kiocb *req,
4109 const struct io_uring_sqe *sqe)
4111 struct io_sr_msg *sr = &req->sr_msg;
4112 struct io_async_ctx *io = req->io;
4115 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4118 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4119 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4120 sr->len = READ_ONCE(sqe->len);
4121 sr->bgid = READ_ONCE(sqe->buf_group);
4123 #ifdef CONFIG_COMPAT
4124 if (req->ctx->compat)
4125 sr->msg_flags |= MSG_CMSG_COMPAT;
4128 if (!io || req->opcode == IORING_OP_RECV)
4130 /* iovec is already imported */
4131 if (req->flags & REQ_F_NEED_CLEANUP)
4134 ret = io_recvmsg_copy_hdr(req, io);
4136 req->flags |= REQ_F_NEED_CLEANUP;
4140 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4141 struct io_comp_state *cs)
4143 struct io_async_msghdr *kmsg = NULL;
4144 struct socket *sock;
4145 int ret, cflags = 0;
4147 sock = sock_from_file(req->file, &ret);
4149 struct io_buffer *kbuf;
4150 struct io_async_ctx io;
4154 kmsg = &req->io->msg;
4155 kmsg->msg.msg_name = &req->io->msg.addr;
4156 /* if iov is set, it's allocated already */
4158 kmsg->iov = kmsg->fast_iov;
4159 kmsg->msg.msg_iter.iov = kmsg->iov;
4162 kmsg->msg.msg_name = &io.msg.addr;
4164 ret = io_recvmsg_copy_hdr(req, &io);
4169 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4171 return PTR_ERR(kbuf);
4173 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4174 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4175 1, req->sr_msg.len);
4178 flags = req->sr_msg.msg_flags;
4179 if (flags & MSG_DONTWAIT)
4180 req->flags |= REQ_F_NOWAIT;
4181 else if (force_nonblock)
4182 flags |= MSG_DONTWAIT;
4184 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
4185 kmsg->uaddr, flags);
4186 if (force_nonblock && ret == -EAGAIN)
4187 return io_setup_async_msg(req, kmsg);
4188 if (ret == -ERESTARTSYS)
4192 if (kmsg && kmsg->iov != kmsg->fast_iov)
4194 req->flags &= ~REQ_F_NEED_CLEANUP;
4196 req_set_fail_links(req);
4197 __io_req_complete(req, ret, cflags, cs);
4201 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4202 struct io_comp_state *cs)
4204 struct io_buffer *kbuf = NULL;
4205 struct socket *sock;
4206 int ret, cflags = 0;
4208 sock = sock_from_file(req->file, &ret);
4210 struct io_sr_msg *sr = &req->sr_msg;
4211 void __user *buf = sr->buf;
4216 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4218 return PTR_ERR(kbuf);
4220 buf = u64_to_user_ptr(kbuf->addr);
4222 ret = import_single_range(READ, buf, sr->len, &iov,
4229 req->flags |= REQ_F_NEED_CLEANUP;
4230 msg.msg_name = NULL;
4231 msg.msg_control = NULL;
4232 msg.msg_controllen = 0;
4233 msg.msg_namelen = 0;
4234 msg.msg_iocb = NULL;
4237 flags = req->sr_msg.msg_flags;
4238 if (flags & MSG_DONTWAIT)
4239 req->flags |= REQ_F_NOWAIT;
4240 else if (force_nonblock)
4241 flags |= MSG_DONTWAIT;
4243 ret = sock_recvmsg(sock, &msg, flags);
4244 if (force_nonblock && ret == -EAGAIN)
4246 if (ret == -ERESTARTSYS)
4251 req->flags &= ~REQ_F_NEED_CLEANUP;
4253 req_set_fail_links(req);
4254 __io_req_complete(req, ret, cflags, cs);
4258 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4260 struct io_accept *accept = &req->accept;
4262 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4264 if (sqe->ioprio || sqe->len || sqe->buf_index)
4267 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4268 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4269 accept->flags = READ_ONCE(sqe->accept_flags);
4270 accept->nofile = rlimit(RLIMIT_NOFILE);
4274 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4275 struct io_comp_state *cs)
4277 struct io_accept *accept = &req->accept;
4278 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4281 if (req->file->f_flags & O_NONBLOCK)
4282 req->flags |= REQ_F_NOWAIT;
4284 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4285 accept->addr_len, accept->flags,
4287 if (ret == -EAGAIN && force_nonblock)
4290 if (ret == -ERESTARTSYS)
4292 req_set_fail_links(req);
4294 __io_req_complete(req, ret, 0, cs);
4298 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4300 struct io_connect *conn = &req->connect;
4301 struct io_async_ctx *io = req->io;
4303 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4305 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4308 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4309 conn->addr_len = READ_ONCE(sqe->addr2);
4314 return move_addr_to_kernel(conn->addr, conn->addr_len,
4315 &io->connect.address);
4318 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4319 struct io_comp_state *cs)
4321 struct io_async_ctx __io, *io;
4322 unsigned file_flags;
4328 ret = move_addr_to_kernel(req->connect.addr,
4329 req->connect.addr_len,
4330 &__io.connect.address);
4336 file_flags = force_nonblock ? O_NONBLOCK : 0;
4338 ret = __sys_connect_file(req->file, &io->connect.address,
4339 req->connect.addr_len, file_flags);
4340 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4343 if (io_alloc_async_ctx(req)) {
4347 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4350 if (ret == -ERESTARTSYS)
4354 req_set_fail_links(req);
4355 __io_req_complete(req, ret, 0, cs);
4358 #else /* !CONFIG_NET */
4359 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4364 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4365 struct io_comp_state *cs)
4370 static int io_send(struct io_kiocb *req, bool force_nonblock,
4371 struct io_comp_state *cs)
4376 static int io_recvmsg_prep(struct io_kiocb *req,
4377 const struct io_uring_sqe *sqe)
4382 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4383 struct io_comp_state *cs)
4388 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4389 struct io_comp_state *cs)
4394 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4399 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4400 struct io_comp_state *cs)
4405 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4410 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4411 struct io_comp_state *cs)
4415 #endif /* CONFIG_NET */
4417 struct io_poll_table {
4418 struct poll_table_struct pt;
4419 struct io_kiocb *req;
4423 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4424 __poll_t mask, task_work_func_t func)
4426 struct task_struct *tsk;
4429 /* for instances that support it check for an event match first: */
4430 if (mask && !(mask & poll->events))
4433 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4435 list_del_init(&poll->wait.entry);
4439 init_task_work(&req->task_work, func);
4441 * If this fails, then the task is exiting. When a task exits, the
4442 * work gets canceled, so just cancel this request as well instead
4443 * of executing it. We can't safely execute it anyway, as we may not
4444 * have the needed state needed for it anyway.
4446 ret = task_work_add(tsk, &req->task_work, true);
4447 if (unlikely(ret)) {
4448 WRITE_ONCE(poll->canceled, true);
4449 tsk = io_wq_get_task(req->ctx->io_wq);
4450 task_work_add(tsk, &req->task_work, true);
4452 wake_up_process(tsk);
4456 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4457 __acquires(&req->ctx->completion_lock)
4459 struct io_ring_ctx *ctx = req->ctx;
4461 if (!req->result && !READ_ONCE(poll->canceled)) {
4462 struct poll_table_struct pt = { ._key = poll->events };
4464 req->result = vfs_poll(req->file, &pt) & poll->events;
4467 spin_lock_irq(&ctx->completion_lock);
4468 if (!req->result && !READ_ONCE(poll->canceled)) {
4469 add_wait_queue(poll->head, &poll->wait);
4476 static void io_poll_remove_double(struct io_kiocb *req)
4478 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4480 lockdep_assert_held(&req->ctx->completion_lock);
4482 if (poll && poll->head) {
4483 struct wait_queue_head *head = poll->head;
4485 spin_lock(&head->lock);
4486 list_del_init(&poll->wait.entry);
4487 if (poll->wait.private)
4488 refcount_dec(&req->refs);
4490 spin_unlock(&head->lock);
4494 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4496 struct io_ring_ctx *ctx = req->ctx;
4498 io_poll_remove_double(req);
4499 req->poll.done = true;
4500 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4501 io_commit_cqring(ctx);
4504 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4506 struct io_ring_ctx *ctx = req->ctx;
4508 if (io_poll_rewait(req, &req->poll)) {
4509 spin_unlock_irq(&ctx->completion_lock);
4513 hash_del(&req->hash_node);
4514 io_poll_complete(req, req->result, 0);
4515 req->flags |= REQ_F_COMP_LOCKED;
4516 io_put_req_find_next(req, nxt);
4517 spin_unlock_irq(&ctx->completion_lock);
4519 io_cqring_ev_posted(ctx);
4522 static void io_poll_task_func(struct callback_head *cb)
4524 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4525 struct io_kiocb *nxt = NULL;
4527 io_poll_task_handler(req, &nxt);
4529 struct io_ring_ctx *ctx = nxt->ctx;
4531 mutex_lock(&ctx->uring_lock);
4532 __io_queue_sqe(nxt, NULL, NULL);
4533 mutex_unlock(&ctx->uring_lock);
4537 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4538 int sync, void *key)
4540 struct io_kiocb *req = wait->private;
4541 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4542 __poll_t mask = key_to_poll(key);
4544 /* for instances that support it check for an event match first: */
4545 if (mask && !(mask & poll->events))
4548 if (req->poll.head) {
4551 spin_lock(&req->poll.head->lock);
4552 done = list_empty(&req->poll.wait.entry);
4554 list_del_init(&req->poll.wait.entry);
4555 spin_unlock(&req->poll.head->lock);
4557 __io_async_wake(req, poll, mask, io_poll_task_func);
4559 refcount_dec(&req->refs);
4563 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4564 wait_queue_func_t wake_func)
4568 poll->canceled = false;
4569 poll->events = events;
4570 INIT_LIST_HEAD(&poll->wait.entry);
4571 init_waitqueue_func_entry(&poll->wait, wake_func);
4574 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4575 struct wait_queue_head *head)
4577 struct io_kiocb *req = pt->req;
4580 * If poll->head is already set, it's because the file being polled
4581 * uses multiple waitqueues for poll handling (eg one for read, one
4582 * for write). Setup a separate io_poll_iocb if this happens.
4584 if (unlikely(poll->head)) {
4585 /* already have a 2nd entry, fail a third attempt */
4587 pt->error = -EINVAL;
4590 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4592 pt->error = -ENOMEM;
4595 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4596 refcount_inc(&req->refs);
4597 poll->wait.private = req;
4598 req->io = (void *) poll;
4604 if (poll->events & EPOLLEXCLUSIVE)
4605 add_wait_queue_exclusive(head, &poll->wait);
4607 add_wait_queue(head, &poll->wait);
4610 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4611 struct poll_table_struct *p)
4613 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4615 __io_queue_proc(&pt->req->apoll->poll, pt, head);
4618 static void io_async_task_func(struct callback_head *cb)
4620 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4621 struct async_poll *apoll = req->apoll;
4622 struct io_ring_ctx *ctx = req->ctx;
4623 bool canceled = false;
4625 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4627 if (io_poll_rewait(req, &apoll->poll)) {
4628 spin_unlock_irq(&ctx->completion_lock);
4632 /* If req is still hashed, it cannot have been canceled. Don't check. */
4633 if (hash_hashed(&req->hash_node)) {
4634 hash_del(&req->hash_node);
4636 canceled = READ_ONCE(apoll->poll.canceled);
4638 io_cqring_fill_event(req, -ECANCELED);
4639 io_commit_cqring(ctx);
4643 spin_unlock_irq(&ctx->completion_lock);
4645 /* restore ->work in case we need to retry again */
4646 if (req->flags & REQ_F_WORK_INITIALIZED)
4647 memcpy(&req->work, &apoll->work, sizeof(req->work));
4651 __set_current_state(TASK_RUNNING);
4652 if (io_sq_thread_acquire_mm(ctx, req)) {
4653 io_cqring_add_event(req, -EFAULT, 0);
4656 mutex_lock(&ctx->uring_lock);
4657 __io_queue_sqe(req, NULL, NULL);
4658 mutex_unlock(&ctx->uring_lock);
4660 io_cqring_ev_posted(ctx);
4662 req_set_fail_links(req);
4663 io_double_put_req(req);
4667 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4670 struct io_kiocb *req = wait->private;
4671 struct io_poll_iocb *poll = &req->apoll->poll;
4673 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4676 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4679 static void io_poll_req_insert(struct io_kiocb *req)
4681 struct io_ring_ctx *ctx = req->ctx;
4682 struct hlist_head *list;
4684 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4685 hlist_add_head(&req->hash_node, list);
4688 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4689 struct io_poll_iocb *poll,
4690 struct io_poll_table *ipt, __poll_t mask,
4691 wait_queue_func_t wake_func)
4692 __acquires(&ctx->completion_lock)
4694 struct io_ring_ctx *ctx = req->ctx;
4695 bool cancel = false;
4697 io_init_poll_iocb(poll, mask, wake_func);
4698 poll->file = req->file;
4699 poll->wait.private = req;
4701 ipt->pt._key = mask;
4703 ipt->error = -EINVAL;
4705 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4707 spin_lock_irq(&ctx->completion_lock);
4708 if (likely(poll->head)) {
4709 spin_lock(&poll->head->lock);
4710 if (unlikely(list_empty(&poll->wait.entry))) {
4716 if (mask || ipt->error)
4717 list_del_init(&poll->wait.entry);
4719 WRITE_ONCE(poll->canceled, true);
4720 else if (!poll->done) /* actually waiting for an event */
4721 io_poll_req_insert(req);
4722 spin_unlock(&poll->head->lock);
4728 static bool io_arm_poll_handler(struct io_kiocb *req)
4730 const struct io_op_def *def = &io_op_defs[req->opcode];
4731 struct io_ring_ctx *ctx = req->ctx;
4732 struct async_poll *apoll;
4733 struct io_poll_table ipt;
4737 if (!req->file || !file_can_poll(req->file))
4739 if (req->flags & REQ_F_POLLED)
4741 if (!def->pollin && !def->pollout)
4744 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4745 if (unlikely(!apoll))
4748 req->flags |= REQ_F_POLLED;
4749 if (req->flags & REQ_F_WORK_INITIALIZED)
4750 memcpy(&apoll->work, &req->work, sizeof(req->work));
4751 had_io = req->io != NULL;
4753 io_get_req_task(req);
4755 INIT_HLIST_NODE(&req->hash_node);
4759 mask |= POLLIN | POLLRDNORM;
4761 mask |= POLLOUT | POLLWRNORM;
4762 mask |= POLLERR | POLLPRI;
4764 ipt.pt._qproc = io_async_queue_proc;
4766 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4770 /* only remove double add if we did it here */
4772 io_poll_remove_double(req);
4773 spin_unlock_irq(&ctx->completion_lock);
4774 if (req->flags & REQ_F_WORK_INITIALIZED)
4775 memcpy(&req->work, &apoll->work, sizeof(req->work));
4779 spin_unlock_irq(&ctx->completion_lock);
4780 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4781 apoll->poll.events);
4785 static bool __io_poll_remove_one(struct io_kiocb *req,
4786 struct io_poll_iocb *poll)
4788 bool do_complete = false;
4790 spin_lock(&poll->head->lock);
4791 WRITE_ONCE(poll->canceled, true);
4792 if (!list_empty(&poll->wait.entry)) {
4793 list_del_init(&poll->wait.entry);
4796 spin_unlock(&poll->head->lock);
4797 hash_del(&req->hash_node);
4801 static bool io_poll_remove_one(struct io_kiocb *req)
4805 if (req->opcode == IORING_OP_POLL_ADD) {
4806 io_poll_remove_double(req);
4807 do_complete = __io_poll_remove_one(req, &req->poll);
4809 struct async_poll *apoll = req->apoll;
4811 /* non-poll requests have submit ref still */
4812 do_complete = __io_poll_remove_one(req, &apoll->poll);
4816 * restore ->work because we will call
4817 * io_req_work_drop_env below when dropping the
4820 if (req->flags & REQ_F_WORK_INITIALIZED)
4821 memcpy(&req->work, &apoll->work,
4828 io_cqring_fill_event(req, -ECANCELED);
4829 io_commit_cqring(req->ctx);
4830 req->flags |= REQ_F_COMP_LOCKED;
4837 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4839 struct hlist_node *tmp;
4840 struct io_kiocb *req;
4843 spin_lock_irq(&ctx->completion_lock);
4844 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4845 struct hlist_head *list;
4847 list = &ctx->cancel_hash[i];
4848 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4849 posted += io_poll_remove_one(req);
4851 spin_unlock_irq(&ctx->completion_lock);
4854 io_cqring_ev_posted(ctx);
4857 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4859 struct hlist_head *list;
4860 struct io_kiocb *req;
4862 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4863 hlist_for_each_entry(req, list, hash_node) {
4864 if (sqe_addr != req->user_data)
4866 if (io_poll_remove_one(req))
4874 static int io_poll_remove_prep(struct io_kiocb *req,
4875 const struct io_uring_sqe *sqe)
4877 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4879 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4883 req->poll.addr = READ_ONCE(sqe->addr);
4888 * Find a running poll command that matches one specified in sqe->addr,
4889 * and remove it if found.
4891 static int io_poll_remove(struct io_kiocb *req)
4893 struct io_ring_ctx *ctx = req->ctx;
4897 addr = req->poll.addr;
4898 spin_lock_irq(&ctx->completion_lock);
4899 ret = io_poll_cancel(ctx, addr);
4900 spin_unlock_irq(&ctx->completion_lock);
4903 req_set_fail_links(req);
4904 io_req_complete(req, ret);
4908 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4911 struct io_kiocb *req = wait->private;
4912 struct io_poll_iocb *poll = &req->poll;
4914 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4917 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4918 struct poll_table_struct *p)
4920 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4922 __io_queue_proc(&pt->req->poll, pt, head);
4925 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4927 struct io_poll_iocb *poll = &req->poll;
4930 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4932 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4937 events = READ_ONCE(sqe->poll32_events);
4939 events = swahw32(events);
4941 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
4942 (events & EPOLLEXCLUSIVE);
4944 io_get_req_task(req);
4948 static int io_poll_add(struct io_kiocb *req)
4950 struct io_poll_iocb *poll = &req->poll;
4951 struct io_ring_ctx *ctx = req->ctx;
4952 struct io_poll_table ipt;
4955 INIT_HLIST_NODE(&req->hash_node);
4956 INIT_LIST_HEAD(&req->list);
4957 ipt.pt._qproc = io_poll_queue_proc;
4959 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4962 if (mask) { /* no async, we'd stolen it */
4964 io_poll_complete(req, mask, 0);
4966 spin_unlock_irq(&ctx->completion_lock);
4969 io_cqring_ev_posted(ctx);
4975 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4977 struct io_timeout_data *data = container_of(timer,
4978 struct io_timeout_data, timer);
4979 struct io_kiocb *req = data->req;
4980 struct io_ring_ctx *ctx = req->ctx;
4981 unsigned long flags;
4983 atomic_inc(&ctx->cq_timeouts);
4985 spin_lock_irqsave(&ctx->completion_lock, flags);
4987 * We could be racing with timeout deletion. If the list is empty,
4988 * then timeout lookup already found it and will be handling it.
4990 if (!list_empty(&req->list))
4991 list_del_init(&req->list);
4993 io_cqring_fill_event(req, -ETIME);
4994 io_commit_cqring(ctx);
4995 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4997 io_cqring_ev_posted(ctx);
4998 req_set_fail_links(req);
5000 return HRTIMER_NORESTART;
5003 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5005 struct io_kiocb *req;
5008 list_for_each_entry(req, &ctx->timeout_list, list) {
5009 if (user_data == req->user_data) {
5010 list_del_init(&req->list);
5019 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
5023 req_set_fail_links(req);
5024 io_cqring_fill_event(req, -ECANCELED);
5029 static int io_timeout_remove_prep(struct io_kiocb *req,
5030 const struct io_uring_sqe *sqe)
5032 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5034 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
5037 req->timeout.addr = READ_ONCE(sqe->addr);
5038 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
5039 if (req->timeout.flags)
5046 * Remove or update an existing timeout command
5048 static int io_timeout_remove(struct io_kiocb *req)
5050 struct io_ring_ctx *ctx = req->ctx;
5053 spin_lock_irq(&ctx->completion_lock);
5054 ret = io_timeout_cancel(ctx, req->timeout.addr);
5056 io_cqring_fill_event(req, ret);
5057 io_commit_cqring(ctx);
5058 spin_unlock_irq(&ctx->completion_lock);
5059 io_cqring_ev_posted(ctx);
5061 req_set_fail_links(req);
5066 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5067 bool is_timeout_link)
5069 struct io_timeout_data *data;
5071 u32 off = READ_ONCE(sqe->off);
5073 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5075 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5077 if (off && is_timeout_link)
5079 flags = READ_ONCE(sqe->timeout_flags);
5080 if (flags & ~IORING_TIMEOUT_ABS)
5083 req->timeout.off = off;
5085 if (!req->io && io_alloc_async_ctx(req))
5088 data = &req->io->timeout;
5090 req->flags |= REQ_F_TIMEOUT;
5092 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5095 if (flags & IORING_TIMEOUT_ABS)
5096 data->mode = HRTIMER_MODE_ABS;
5098 data->mode = HRTIMER_MODE_REL;
5100 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5104 static int io_timeout(struct io_kiocb *req)
5106 struct io_ring_ctx *ctx = req->ctx;
5107 struct io_timeout_data *data = &req->io->timeout;
5108 struct list_head *entry;
5109 u32 tail, off = req->timeout.off;
5111 spin_lock_irq(&ctx->completion_lock);
5114 * sqe->off holds how many events that need to occur for this
5115 * timeout event to be satisfied. If it isn't set, then this is
5116 * a pure timeout request, sequence isn't used.
5119 req->flags |= REQ_F_TIMEOUT_NOSEQ;
5120 entry = ctx->timeout_list.prev;
5124 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5125 req->timeout.target_seq = tail + off;
5128 * Insertion sort, ensuring the first entry in the list is always
5129 * the one we need first.
5131 list_for_each_prev(entry, &ctx->timeout_list) {
5132 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5134 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
5136 /* nxt.seq is behind @tail, otherwise would've been completed */
5137 if (off >= nxt->timeout.target_seq - tail)
5141 list_add(&req->list, entry);
5142 data->timer.function = io_timeout_fn;
5143 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5144 spin_unlock_irq(&ctx->completion_lock);
5148 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5150 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5152 return req->user_data == (unsigned long) data;
5155 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5157 enum io_wq_cancel cancel_ret;
5160 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5161 switch (cancel_ret) {
5162 case IO_WQ_CANCEL_OK:
5165 case IO_WQ_CANCEL_RUNNING:
5168 case IO_WQ_CANCEL_NOTFOUND:
5176 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5177 struct io_kiocb *req, __u64 sqe_addr,
5180 unsigned long flags;
5183 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5184 if (ret != -ENOENT) {
5185 spin_lock_irqsave(&ctx->completion_lock, flags);
5189 spin_lock_irqsave(&ctx->completion_lock, flags);
5190 ret = io_timeout_cancel(ctx, sqe_addr);
5193 ret = io_poll_cancel(ctx, sqe_addr);
5197 io_cqring_fill_event(req, ret);
5198 io_commit_cqring(ctx);
5199 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5200 io_cqring_ev_posted(ctx);
5203 req_set_fail_links(req);
5207 static int io_async_cancel_prep(struct io_kiocb *req,
5208 const struct io_uring_sqe *sqe)
5210 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5212 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
5216 req->cancel.addr = READ_ONCE(sqe->addr);
5220 static int io_async_cancel(struct io_kiocb *req)
5222 struct io_ring_ctx *ctx = req->ctx;
5224 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5228 static int io_files_update_prep(struct io_kiocb *req,
5229 const struct io_uring_sqe *sqe)
5231 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
5234 req->files_update.offset = READ_ONCE(sqe->off);
5235 req->files_update.nr_args = READ_ONCE(sqe->len);
5236 if (!req->files_update.nr_args)
5238 req->files_update.arg = READ_ONCE(sqe->addr);
5242 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5243 struct io_comp_state *cs)
5245 struct io_ring_ctx *ctx = req->ctx;
5246 struct io_uring_files_update up;
5252 up.offset = req->files_update.offset;
5253 up.fds = req->files_update.arg;
5255 mutex_lock(&ctx->uring_lock);
5256 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5257 mutex_unlock(&ctx->uring_lock);
5260 req_set_fail_links(req);
5261 __io_req_complete(req, ret, 0, cs);
5265 static int io_req_defer_prep(struct io_kiocb *req,
5266 const struct io_uring_sqe *sqe, bool for_async)
5273 if (io_op_defs[req->opcode].file_table) {
5274 io_req_init_async(req);
5275 ret = io_grab_files(req);
5280 if (for_async || (req->flags & REQ_F_WORK_INITIALIZED)) {
5281 io_req_init_async(req);
5282 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
5285 switch (req->opcode) {
5288 case IORING_OP_READV:
5289 case IORING_OP_READ_FIXED:
5290 case IORING_OP_READ:
5291 ret = io_read_prep(req, sqe, true);
5293 case IORING_OP_WRITEV:
5294 case IORING_OP_WRITE_FIXED:
5295 case IORING_OP_WRITE:
5296 ret = io_write_prep(req, sqe, true);
5298 case IORING_OP_POLL_ADD:
5299 ret = io_poll_add_prep(req, sqe);
5301 case IORING_OP_POLL_REMOVE:
5302 ret = io_poll_remove_prep(req, sqe);
5304 case IORING_OP_FSYNC:
5305 ret = io_prep_fsync(req, sqe);
5307 case IORING_OP_SYNC_FILE_RANGE:
5308 ret = io_prep_sfr(req, sqe);
5310 case IORING_OP_SENDMSG:
5311 case IORING_OP_SEND:
5312 ret = io_sendmsg_prep(req, sqe);
5314 case IORING_OP_RECVMSG:
5315 case IORING_OP_RECV:
5316 ret = io_recvmsg_prep(req, sqe);
5318 case IORING_OP_CONNECT:
5319 ret = io_connect_prep(req, sqe);
5321 case IORING_OP_TIMEOUT:
5322 ret = io_timeout_prep(req, sqe, false);
5324 case IORING_OP_TIMEOUT_REMOVE:
5325 ret = io_timeout_remove_prep(req, sqe);
5327 case IORING_OP_ASYNC_CANCEL:
5328 ret = io_async_cancel_prep(req, sqe);
5330 case IORING_OP_LINK_TIMEOUT:
5331 ret = io_timeout_prep(req, sqe, true);
5333 case IORING_OP_ACCEPT:
5334 ret = io_accept_prep(req, sqe);
5336 case IORING_OP_FALLOCATE:
5337 ret = io_fallocate_prep(req, sqe);
5339 case IORING_OP_OPENAT:
5340 ret = io_openat_prep(req, sqe);
5342 case IORING_OP_CLOSE:
5343 ret = io_close_prep(req, sqe);
5345 case IORING_OP_FILES_UPDATE:
5346 ret = io_files_update_prep(req, sqe);
5348 case IORING_OP_STATX:
5349 ret = io_statx_prep(req, sqe);
5351 case IORING_OP_FADVISE:
5352 ret = io_fadvise_prep(req, sqe);
5354 case IORING_OP_MADVISE:
5355 ret = io_madvise_prep(req, sqe);
5357 case IORING_OP_OPENAT2:
5358 ret = io_openat2_prep(req, sqe);
5360 case IORING_OP_EPOLL_CTL:
5361 ret = io_epoll_ctl_prep(req, sqe);
5363 case IORING_OP_SPLICE:
5364 ret = io_splice_prep(req, sqe);
5366 case IORING_OP_PROVIDE_BUFFERS:
5367 ret = io_provide_buffers_prep(req, sqe);
5369 case IORING_OP_REMOVE_BUFFERS:
5370 ret = io_remove_buffers_prep(req, sqe);
5373 ret = io_tee_prep(req, sqe);
5376 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5385 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5387 struct io_ring_ctx *ctx = req->ctx;
5390 /* Still need defer if there is pending req in defer list. */
5391 if (!req_need_defer(req) && list_empty_careful(&ctx->defer_list))
5395 if (io_alloc_async_ctx(req))
5397 ret = io_req_defer_prep(req, sqe, true);
5402 spin_lock_irq(&ctx->completion_lock);
5403 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
5404 spin_unlock_irq(&ctx->completion_lock);
5408 trace_io_uring_defer(ctx, req, req->user_data);
5409 list_add_tail(&req->list, &ctx->defer_list);
5410 spin_unlock_irq(&ctx->completion_lock);
5411 return -EIOCBQUEUED;
5414 static void io_cleanup_req(struct io_kiocb *req)
5416 struct io_async_ctx *io = req->io;
5418 switch (req->opcode) {
5419 case IORING_OP_READV:
5420 case IORING_OP_READ_FIXED:
5421 case IORING_OP_READ:
5422 if (req->flags & REQ_F_BUFFER_SELECTED)
5423 kfree((void *)(unsigned long)req->rw.addr);
5425 case IORING_OP_WRITEV:
5426 case IORING_OP_WRITE_FIXED:
5427 case IORING_OP_WRITE:
5428 if (io->rw.iov != io->rw.fast_iov)
5431 case IORING_OP_RECVMSG:
5432 if (req->flags & REQ_F_BUFFER_SELECTED)
5433 kfree(req->sr_msg.kbuf);
5435 case IORING_OP_SENDMSG:
5436 if (io->msg.iov != io->msg.fast_iov)
5439 case IORING_OP_RECV:
5440 if (req->flags & REQ_F_BUFFER_SELECTED)
5441 kfree(req->sr_msg.kbuf);
5443 case IORING_OP_OPENAT:
5444 case IORING_OP_OPENAT2:
5446 case IORING_OP_SPLICE:
5448 io_put_file(req, req->splice.file_in,
5449 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5453 req->flags &= ~REQ_F_NEED_CLEANUP;
5456 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5457 bool force_nonblock, struct io_comp_state *cs)
5459 struct io_ring_ctx *ctx = req->ctx;
5462 switch (req->opcode) {
5464 ret = io_nop(req, cs);
5466 case IORING_OP_READV:
5467 case IORING_OP_READ_FIXED:
5468 case IORING_OP_READ:
5470 ret = io_read_prep(req, sqe, force_nonblock);
5474 ret = io_read(req, force_nonblock, cs);
5476 case IORING_OP_WRITEV:
5477 case IORING_OP_WRITE_FIXED:
5478 case IORING_OP_WRITE:
5480 ret = io_write_prep(req, sqe, force_nonblock);
5484 ret = io_write(req, force_nonblock, cs);
5486 case IORING_OP_FSYNC:
5488 ret = io_prep_fsync(req, sqe);
5492 ret = io_fsync(req, force_nonblock);
5494 case IORING_OP_POLL_ADD:
5496 ret = io_poll_add_prep(req, sqe);
5500 ret = io_poll_add(req);
5502 case IORING_OP_POLL_REMOVE:
5504 ret = io_poll_remove_prep(req, sqe);
5508 ret = io_poll_remove(req);
5510 case IORING_OP_SYNC_FILE_RANGE:
5512 ret = io_prep_sfr(req, sqe);
5516 ret = io_sync_file_range(req, force_nonblock);
5518 case IORING_OP_SENDMSG:
5519 case IORING_OP_SEND:
5521 ret = io_sendmsg_prep(req, sqe);
5525 if (req->opcode == IORING_OP_SENDMSG)
5526 ret = io_sendmsg(req, force_nonblock, cs);
5528 ret = io_send(req, force_nonblock, cs);
5530 case IORING_OP_RECVMSG:
5531 case IORING_OP_RECV:
5533 ret = io_recvmsg_prep(req, sqe);
5537 if (req->opcode == IORING_OP_RECVMSG)
5538 ret = io_recvmsg(req, force_nonblock, cs);
5540 ret = io_recv(req, force_nonblock, cs);
5542 case IORING_OP_TIMEOUT:
5544 ret = io_timeout_prep(req, sqe, false);
5548 ret = io_timeout(req);
5550 case IORING_OP_TIMEOUT_REMOVE:
5552 ret = io_timeout_remove_prep(req, sqe);
5556 ret = io_timeout_remove(req);
5558 case IORING_OP_ACCEPT:
5560 ret = io_accept_prep(req, sqe);
5564 ret = io_accept(req, force_nonblock, cs);
5566 case IORING_OP_CONNECT:
5568 ret = io_connect_prep(req, sqe);
5572 ret = io_connect(req, force_nonblock, cs);
5574 case IORING_OP_ASYNC_CANCEL:
5576 ret = io_async_cancel_prep(req, sqe);
5580 ret = io_async_cancel(req);
5582 case IORING_OP_FALLOCATE:
5584 ret = io_fallocate_prep(req, sqe);
5588 ret = io_fallocate(req, force_nonblock);
5590 case IORING_OP_OPENAT:
5592 ret = io_openat_prep(req, sqe);
5596 ret = io_openat(req, force_nonblock);
5598 case IORING_OP_CLOSE:
5600 ret = io_close_prep(req, sqe);
5604 ret = io_close(req, force_nonblock, cs);
5606 case IORING_OP_FILES_UPDATE:
5608 ret = io_files_update_prep(req, sqe);
5612 ret = io_files_update(req, force_nonblock, cs);
5614 case IORING_OP_STATX:
5616 ret = io_statx_prep(req, sqe);
5620 ret = io_statx(req, force_nonblock);
5622 case IORING_OP_FADVISE:
5624 ret = io_fadvise_prep(req, sqe);
5628 ret = io_fadvise(req, force_nonblock);
5630 case IORING_OP_MADVISE:
5632 ret = io_madvise_prep(req, sqe);
5636 ret = io_madvise(req, force_nonblock);
5638 case IORING_OP_OPENAT2:
5640 ret = io_openat2_prep(req, sqe);
5644 ret = io_openat2(req, force_nonblock);
5646 case IORING_OP_EPOLL_CTL:
5648 ret = io_epoll_ctl_prep(req, sqe);
5652 ret = io_epoll_ctl(req, force_nonblock, cs);
5654 case IORING_OP_SPLICE:
5656 ret = io_splice_prep(req, sqe);
5660 ret = io_splice(req, force_nonblock);
5662 case IORING_OP_PROVIDE_BUFFERS:
5664 ret = io_provide_buffers_prep(req, sqe);
5668 ret = io_provide_buffers(req, force_nonblock, cs);
5670 case IORING_OP_REMOVE_BUFFERS:
5672 ret = io_remove_buffers_prep(req, sqe);
5676 ret = io_remove_buffers(req, force_nonblock, cs);
5680 ret = io_tee_prep(req, sqe);
5684 ret = io_tee(req, force_nonblock);
5694 /* If the op doesn't have a file, we're not polling for it */
5695 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5696 const bool in_async = io_wq_current_is_worker();
5698 /* workqueue context doesn't hold uring_lock, grab it now */
5700 mutex_lock(&ctx->uring_lock);
5702 io_iopoll_req_issued(req);
5705 mutex_unlock(&ctx->uring_lock);
5711 static void io_arm_async_linked_timeout(struct io_kiocb *req)
5713 struct io_kiocb *link;
5715 /* link head's timeout is queued in io_queue_async_work() */
5716 if (!(req->flags & REQ_F_QUEUE_TIMEOUT))
5719 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
5720 io_queue_linked_timeout(link);
5723 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
5725 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5728 io_arm_async_linked_timeout(req);
5730 /* if NO_CANCEL is set, we must still run the work */
5731 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5732 IO_WQ_WORK_CANCEL) {
5738 ret = io_issue_sqe(req, NULL, false, NULL);
5740 * We can get EAGAIN for polled IO even though we're
5741 * forcing a sync submission from here, since we can't
5742 * wait for request slots on the block side.
5751 req_set_fail_links(req);
5752 io_req_complete(req, ret);
5755 return io_steal_work(req);
5758 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5761 struct fixed_file_table *table;
5763 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5764 return table->files[index & IORING_FILE_TABLE_MASK];
5767 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5768 int fd, struct file **out_file, bool fixed)
5770 struct io_ring_ctx *ctx = req->ctx;
5774 if (unlikely(!ctx->file_data ||
5775 (unsigned) fd >= ctx->nr_user_files))
5777 fd = array_index_nospec(fd, ctx->nr_user_files);
5778 file = io_file_from_index(ctx, fd);
5780 req->fixed_file_refs = ctx->file_data->cur_refs;
5781 percpu_ref_get(req->fixed_file_refs);
5784 trace_io_uring_file_get(ctx, fd);
5785 file = __io_file_get(state, fd);
5788 if (file || io_op_defs[req->opcode].needs_file_no_error) {
5795 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5800 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5801 if (unlikely(!fixed && io_async_submit(req->ctx)))
5804 return io_file_get(state, req, fd, &req->file, fixed);
5807 static int io_grab_files(struct io_kiocb *req)
5810 struct io_ring_ctx *ctx = req->ctx;
5812 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5814 if (!ctx->ring_file)
5818 spin_lock_irq(&ctx->inflight_lock);
5820 * We use the f_ops->flush() handler to ensure that we can flush
5821 * out work accessing these files if the fd is closed. Check if
5822 * the fd has changed since we started down this path, and disallow
5823 * this operation if it has.
5825 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5826 list_add(&req->inflight_entry, &ctx->inflight_list);
5827 req->flags |= REQ_F_INFLIGHT;
5828 req->work.files = current->files;
5831 spin_unlock_irq(&ctx->inflight_lock);
5837 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5839 struct io_timeout_data *data = container_of(timer,
5840 struct io_timeout_data, timer);
5841 struct io_kiocb *req = data->req;
5842 struct io_ring_ctx *ctx = req->ctx;
5843 struct io_kiocb *prev = NULL;
5844 unsigned long flags;
5846 spin_lock_irqsave(&ctx->completion_lock, flags);
5849 * We don't expect the list to be empty, that will only happen if we
5850 * race with the completion of the linked work.
5852 if (!list_empty(&req->link_list)) {
5853 prev = list_entry(req->link_list.prev, struct io_kiocb,
5855 if (refcount_inc_not_zero(&prev->refs)) {
5856 list_del_init(&req->link_list);
5857 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5862 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5865 req_set_fail_links(prev);
5866 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5869 io_req_complete(req, -ETIME);
5871 return HRTIMER_NORESTART;
5874 static void io_queue_linked_timeout(struct io_kiocb *req)
5876 struct io_ring_ctx *ctx = req->ctx;
5879 * If the list is now empty, then our linked request finished before
5880 * we got a chance to setup the timer
5882 spin_lock_irq(&ctx->completion_lock);
5883 if (!list_empty(&req->link_list)) {
5884 struct io_timeout_data *data = &req->io->timeout;
5886 data->timer.function = io_link_timeout_fn;
5887 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5890 spin_unlock_irq(&ctx->completion_lock);
5892 /* drop submission reference */
5896 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5898 struct io_kiocb *nxt;
5900 if (!(req->flags & REQ_F_LINK_HEAD))
5902 /* for polled retry, if flag is set, we already went through here */
5903 if (req->flags & REQ_F_POLLED)
5906 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5908 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5911 req->flags |= REQ_F_LINK_TIMEOUT;
5915 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5916 struct io_comp_state *cs)
5918 struct io_kiocb *linked_timeout;
5919 struct io_kiocb *nxt;
5920 const struct cred *old_creds = NULL;
5924 linked_timeout = io_prep_linked_timeout(req);
5926 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
5927 req->work.creds != current_cred()) {
5929 revert_creds(old_creds);
5930 if (old_creds == req->work.creds)
5931 old_creds = NULL; /* restored original creds */
5933 old_creds = override_creds(req->work.creds);
5936 ret = io_issue_sqe(req, sqe, true, cs);
5939 * We async punt it if the file wasn't marked NOWAIT, or if the file
5940 * doesn't support non-blocking read/write attempts
5942 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
5943 if (io_arm_poll_handler(req)) {
5945 io_queue_linked_timeout(linked_timeout);
5949 io_req_init_async(req);
5951 if (io_op_defs[req->opcode].file_table) {
5952 ret = io_grab_files(req);
5958 * Queued up for async execution, worker will release
5959 * submit reference when the iocb is actually submitted.
5961 io_queue_async_work(req);
5967 /* drop submission reference */
5968 io_put_req_find_next(req, &nxt);
5970 if (linked_timeout) {
5972 io_queue_linked_timeout(linked_timeout);
5974 io_put_req(linked_timeout);
5977 /* and drop final reference, if we failed */
5979 req_set_fail_links(req);
5980 io_req_complete(req, ret);
5985 if (req->flags & REQ_F_FORCE_ASYNC)
5991 revert_creds(old_creds);
5994 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5995 struct io_comp_state *cs)
5999 ret = io_req_defer(req, sqe);
6001 if (ret != -EIOCBQUEUED) {
6003 req_set_fail_links(req);
6005 io_req_complete(req, ret);
6007 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6010 if (io_alloc_async_ctx(req))
6012 ret = io_req_defer_prep(req, sqe, true);
6013 if (unlikely(ret < 0))
6018 * Never try inline submit of IOSQE_ASYNC is set, go straight
6019 * to async execution.
6021 req->work.flags |= IO_WQ_WORK_CONCURRENT;
6022 io_queue_async_work(req);
6024 __io_queue_sqe(req, sqe, cs);
6028 static inline void io_queue_link_head(struct io_kiocb *req,
6029 struct io_comp_state *cs)
6031 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6033 io_req_complete(req, -ECANCELED);
6035 io_queue_sqe(req, NULL, cs);
6038 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6039 struct io_kiocb **link, struct io_comp_state *cs)
6041 struct io_ring_ctx *ctx = req->ctx;
6045 * If we already have a head request, queue this one for async
6046 * submittal once the head completes. If we don't have a head but
6047 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6048 * submitted sync once the chain is complete. If none of those
6049 * conditions are true (normal request), then just queue it.
6052 struct io_kiocb *head = *link;
6055 * Taking sequential execution of a link, draining both sides
6056 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6057 * requests in the link. So, it drains the head and the
6058 * next after the link request. The last one is done via
6059 * drain_next flag to persist the effect across calls.
6061 if (req->flags & REQ_F_IO_DRAIN) {
6062 head->flags |= REQ_F_IO_DRAIN;
6063 ctx->drain_next = 1;
6065 if (io_alloc_async_ctx(req))
6068 ret = io_req_defer_prep(req, sqe, false);
6070 /* fail even hard links since we don't submit */
6071 head->flags |= REQ_F_FAIL_LINK;
6074 trace_io_uring_link(ctx, req, head);
6075 io_get_req_task(req);
6076 list_add_tail(&req->link_list, &head->link_list);
6078 /* last request of a link, enqueue the link */
6079 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6080 io_queue_link_head(head, cs);
6084 if (unlikely(ctx->drain_next)) {
6085 req->flags |= REQ_F_IO_DRAIN;
6086 ctx->drain_next = 0;
6088 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6089 req->flags |= REQ_F_LINK_HEAD;
6090 INIT_LIST_HEAD(&req->link_list);
6092 if (io_alloc_async_ctx(req))
6095 ret = io_req_defer_prep(req, sqe, false);
6097 req->flags |= REQ_F_FAIL_LINK;
6100 io_queue_sqe(req, sqe, cs);
6108 * Batched submission is done, ensure local IO is flushed out.
6110 static void io_submit_state_end(struct io_submit_state *state)
6112 if (!list_empty(&state->comp.list))
6113 io_submit_flush_completions(&state->comp);
6114 blk_finish_plug(&state->plug);
6115 io_state_file_put(state);
6116 if (state->free_reqs)
6117 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6121 * Start submission side cache.
6123 static void io_submit_state_start(struct io_submit_state *state,
6124 struct io_ring_ctx *ctx, unsigned int max_ios)
6126 blk_start_plug(&state->plug);
6128 state->plug.nowait = true;
6131 INIT_LIST_HEAD(&state->comp.list);
6132 state->comp.ctx = ctx;
6133 state->free_reqs = 0;
6135 state->ios_left = max_ios;
6138 static void io_commit_sqring(struct io_ring_ctx *ctx)
6140 struct io_rings *rings = ctx->rings;
6143 * Ensure any loads from the SQEs are done at this point,
6144 * since once we write the new head, the application could
6145 * write new data to them.
6147 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6151 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6152 * that is mapped by userspace. This means that care needs to be taken to
6153 * ensure that reads are stable, as we cannot rely on userspace always
6154 * being a good citizen. If members of the sqe are validated and then later
6155 * used, it's important that those reads are done through READ_ONCE() to
6156 * prevent a re-load down the line.
6158 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6160 u32 *sq_array = ctx->sq_array;
6164 * The cached sq head (or cq tail) serves two purposes:
6166 * 1) allows us to batch the cost of updating the user visible
6168 * 2) allows the kernel side to track the head on its own, even
6169 * though the application is the one updating it.
6171 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6172 if (likely(head < ctx->sq_entries))
6173 return &ctx->sq_sqes[head];
6175 /* drop invalid entries */
6176 ctx->cached_sq_dropped++;
6177 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6181 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6183 ctx->cached_sq_head++;
6186 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6187 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6188 IOSQE_BUFFER_SELECT)
6190 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6191 const struct io_uring_sqe *sqe,
6192 struct io_submit_state *state)
6194 unsigned int sqe_flags;
6198 * All io need record the previous position, if LINK vs DARIN,
6199 * it can be used to mark the position of the first IO in the
6202 req->sequence = ctx->cached_sq_head - ctx->cached_sq_dropped;
6203 req->opcode = READ_ONCE(sqe->opcode);
6204 req->user_data = READ_ONCE(sqe->user_data);
6209 /* one is dropped after submission, the other at completion */
6210 refcount_set(&req->refs, 2);
6211 req->task = current;
6214 if (unlikely(req->opcode >= IORING_OP_LAST))
6217 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6220 sqe_flags = READ_ONCE(sqe->flags);
6221 /* enforce forwards compatibility on users */
6222 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6225 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6226 !io_op_defs[req->opcode].buffer_select)
6229 id = READ_ONCE(sqe->personality);
6231 io_req_init_async(req);
6232 req->work.creds = idr_find(&ctx->personality_idr, id);
6233 if (unlikely(!req->work.creds))
6235 get_cred(req->work.creds);
6238 /* same numerical values with corresponding REQ_F_*, safe to copy */
6239 req->flags |= sqe_flags;
6241 if (!io_op_defs[req->opcode].needs_file)
6244 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
6247 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
6248 struct file *ring_file, int ring_fd)
6250 struct io_submit_state state;
6251 struct io_kiocb *link = NULL;
6252 int i, submitted = 0;
6254 /* if we have a backlog and couldn't flush it all, return BUSY */
6255 if (test_bit(0, &ctx->sq_check_overflow)) {
6256 if (!list_empty(&ctx->cq_overflow_list) &&
6257 !io_cqring_overflow_flush(ctx, false))
6261 /* make sure SQ entry isn't read before tail */
6262 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6264 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6267 io_submit_state_start(&state, ctx, nr);
6269 ctx->ring_fd = ring_fd;
6270 ctx->ring_file = ring_file;
6272 for (i = 0; i < nr; i++) {
6273 const struct io_uring_sqe *sqe;
6274 struct io_kiocb *req;
6277 sqe = io_get_sqe(ctx);
6278 if (unlikely(!sqe)) {
6279 io_consume_sqe(ctx);
6282 req = io_alloc_req(ctx, &state);
6283 if (unlikely(!req)) {
6285 submitted = -EAGAIN;
6289 err = io_init_req(ctx, req, sqe, &state);
6290 io_consume_sqe(ctx);
6291 /* will complete beyond this point, count as submitted */
6294 if (unlikely(err)) {
6297 io_req_complete(req, err);
6301 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6302 true, io_async_submit(ctx));
6303 err = io_submit_sqe(req, sqe, &link, &state.comp);
6308 if (unlikely(submitted != nr)) {
6309 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6311 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6314 io_queue_link_head(link, &state.comp);
6315 io_submit_state_end(&state);
6317 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6318 io_commit_sqring(ctx);
6323 static int io_sq_thread(void *data)
6325 struct io_ring_ctx *ctx = data;
6326 const struct cred *old_cred;
6328 unsigned long timeout;
6331 complete(&ctx->sq_thread_comp);
6333 old_cred = override_creds(ctx->creds);
6335 timeout = jiffies + ctx->sq_thread_idle;
6336 while (!kthread_should_park()) {
6337 unsigned int to_submit;
6339 if (!list_empty(&ctx->poll_list)) {
6340 unsigned nr_events = 0;
6342 mutex_lock(&ctx->uring_lock);
6343 if (!list_empty(&ctx->poll_list))
6344 io_iopoll_getevents(ctx, &nr_events, 0);
6346 timeout = jiffies + ctx->sq_thread_idle;
6347 mutex_unlock(&ctx->uring_lock);
6350 to_submit = io_sqring_entries(ctx);
6353 * If submit got -EBUSY, flag us as needing the application
6354 * to enter the kernel to reap and flush events.
6356 if (!to_submit || ret == -EBUSY || need_resched()) {
6358 * Drop cur_mm before scheduling, we can't hold it for
6359 * long periods (or over schedule()). Do this before
6360 * adding ourselves to the waitqueue, as the unuse/drop
6363 io_sq_thread_drop_mm(ctx);
6366 * We're polling. If we're within the defined idle
6367 * period, then let us spin without work before going
6368 * to sleep. The exception is if we got EBUSY doing
6369 * more IO, we should wait for the application to
6370 * reap events and wake us up.
6372 if (!list_empty(&ctx->poll_list) || need_resched() ||
6373 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6374 !percpu_ref_is_dying(&ctx->refs))) {
6375 if (current->task_works)
6381 prepare_to_wait(&ctx->sqo_wait, &wait,
6382 TASK_INTERRUPTIBLE);
6385 * While doing polled IO, before going to sleep, we need
6386 * to check if there are new reqs added to poll_list, it
6387 * is because reqs may have been punted to io worker and
6388 * will be added to poll_list later, hence check the
6391 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6392 !list_empty_careful(&ctx->poll_list)) {
6393 finish_wait(&ctx->sqo_wait, &wait);
6397 /* Tell userspace we may need a wakeup call */
6398 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6399 /* make sure to read SQ tail after writing flags */
6402 to_submit = io_sqring_entries(ctx);
6403 if (!to_submit || ret == -EBUSY) {
6404 if (kthread_should_park()) {
6405 finish_wait(&ctx->sqo_wait, &wait);
6408 if (current->task_works) {
6410 finish_wait(&ctx->sqo_wait, &wait);
6413 if (signal_pending(current))
6414 flush_signals(current);
6416 finish_wait(&ctx->sqo_wait, &wait);
6418 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6422 finish_wait(&ctx->sqo_wait, &wait);
6424 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6427 mutex_lock(&ctx->uring_lock);
6428 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6429 ret = io_submit_sqes(ctx, to_submit, NULL, -1);
6430 mutex_unlock(&ctx->uring_lock);
6431 timeout = jiffies + ctx->sq_thread_idle;
6434 if (current->task_works)
6437 io_sq_thread_drop_mm(ctx);
6438 revert_creds(old_cred);
6445 struct io_wait_queue {
6446 struct wait_queue_entry wq;
6447 struct io_ring_ctx *ctx;
6449 unsigned nr_timeouts;
6452 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6454 struct io_ring_ctx *ctx = iowq->ctx;
6457 * Wake up if we have enough events, or if a timeout occurred since we
6458 * started waiting. For timeouts, we always want to return to userspace,
6459 * regardless of event count.
6461 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6462 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6465 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6466 int wake_flags, void *key)
6468 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6471 /* use noflush == true, as we can't safely rely on locking context */
6472 if (!io_should_wake(iowq, true))
6475 return autoremove_wake_function(curr, mode, wake_flags, key);
6479 * Wait until events become available, if we don't already have some. The
6480 * application must reap them itself, as they reside on the shared cq ring.
6482 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6483 const sigset_t __user *sig, size_t sigsz)
6485 struct io_wait_queue iowq = {
6488 .func = io_wake_function,
6489 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6492 .to_wait = min_events,
6494 struct io_rings *rings = ctx->rings;
6498 if (io_cqring_events(ctx, false) >= min_events)
6500 if (!current->task_works)
6506 #ifdef CONFIG_COMPAT
6507 if (in_compat_syscall())
6508 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6512 ret = set_user_sigmask(sig, sigsz);
6518 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6519 trace_io_uring_cqring_wait(ctx, min_events);
6521 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6522 TASK_INTERRUPTIBLE);
6523 if (current->task_works)
6525 if (io_should_wake(&iowq, false))
6528 if (signal_pending(current)) {
6533 finish_wait(&ctx->wait, &iowq.wq);
6535 restore_saved_sigmask_unless(ret == -EINTR);
6537 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6540 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6542 #if defined(CONFIG_UNIX)
6543 if (ctx->ring_sock) {
6544 struct sock *sock = ctx->ring_sock->sk;
6545 struct sk_buff *skb;
6547 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6553 for (i = 0; i < ctx->nr_user_files; i++) {
6556 file = io_file_from_index(ctx, i);
6563 static void io_file_ref_kill(struct percpu_ref *ref)
6565 struct fixed_file_data *data;
6567 data = container_of(ref, struct fixed_file_data, refs);
6568 complete(&data->done);
6571 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6573 struct fixed_file_data *data = ctx->file_data;
6574 struct fixed_file_ref_node *ref_node = NULL;
6575 unsigned nr_tables, i;
6580 spin_lock(&data->lock);
6581 if (!list_empty(&data->ref_list))
6582 ref_node = list_first_entry(&data->ref_list,
6583 struct fixed_file_ref_node, node);
6584 spin_unlock(&data->lock);
6586 percpu_ref_kill(&ref_node->refs);
6588 percpu_ref_kill(&data->refs);
6590 /* wait for all refs nodes to complete */
6591 flush_delayed_work(&ctx->file_put_work);
6592 wait_for_completion(&data->done);
6594 __io_sqe_files_unregister(ctx);
6595 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6596 for (i = 0; i < nr_tables; i++)
6597 kfree(data->table[i].files);
6599 percpu_ref_exit(&data->refs);
6601 ctx->file_data = NULL;
6602 ctx->nr_user_files = 0;
6606 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6608 if (ctx->sqo_thread) {
6609 wait_for_completion(&ctx->sq_thread_comp);
6611 * The park is a bit of a work-around, without it we get
6612 * warning spews on shutdown with SQPOLL set and affinity
6613 * set to a single CPU.
6615 kthread_park(ctx->sqo_thread);
6616 kthread_stop(ctx->sqo_thread);
6617 ctx->sqo_thread = NULL;
6621 static void io_finish_async(struct io_ring_ctx *ctx)
6623 io_sq_thread_stop(ctx);
6626 io_wq_destroy(ctx->io_wq);
6631 #if defined(CONFIG_UNIX)
6633 * Ensure the UNIX gc is aware of our file set, so we are certain that
6634 * the io_uring can be safely unregistered on process exit, even if we have
6635 * loops in the file referencing.
6637 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6639 struct sock *sk = ctx->ring_sock->sk;
6640 struct scm_fp_list *fpl;
6641 struct sk_buff *skb;
6644 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6648 skb = alloc_skb(0, GFP_KERNEL);
6657 fpl->user = get_uid(ctx->user);
6658 for (i = 0; i < nr; i++) {
6659 struct file *file = io_file_from_index(ctx, i + offset);
6663 fpl->fp[nr_files] = get_file(file);
6664 unix_inflight(fpl->user, fpl->fp[nr_files]);
6669 fpl->max = SCM_MAX_FD;
6670 fpl->count = nr_files;
6671 UNIXCB(skb).fp = fpl;
6672 skb->destructor = unix_destruct_scm;
6673 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6674 skb_queue_head(&sk->sk_receive_queue, skb);
6676 for (i = 0; i < nr_files; i++)
6687 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6688 * causes regular reference counting to break down. We rely on the UNIX
6689 * garbage collection to take care of this problem for us.
6691 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6693 unsigned left, total;
6697 left = ctx->nr_user_files;
6699 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6701 ret = __io_sqe_files_scm(ctx, this_files, total);
6705 total += this_files;
6711 while (total < ctx->nr_user_files) {
6712 struct file *file = io_file_from_index(ctx, total);
6722 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6728 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6733 for (i = 0; i < nr_tables; i++) {
6734 struct fixed_file_table *table = &ctx->file_data->table[i];
6735 unsigned this_files;
6737 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6738 table->files = kcalloc(this_files, sizeof(struct file *),
6742 nr_files -= this_files;
6748 for (i = 0; i < nr_tables; i++) {
6749 struct fixed_file_table *table = &ctx->file_data->table[i];
6750 kfree(table->files);
6755 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6757 #if defined(CONFIG_UNIX)
6758 struct sock *sock = ctx->ring_sock->sk;
6759 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6760 struct sk_buff *skb;
6763 __skb_queue_head_init(&list);
6766 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6767 * remove this entry and rearrange the file array.
6769 skb = skb_dequeue(head);
6771 struct scm_fp_list *fp;
6773 fp = UNIXCB(skb).fp;
6774 for (i = 0; i < fp->count; i++) {
6777 if (fp->fp[i] != file)
6780 unix_notinflight(fp->user, fp->fp[i]);
6781 left = fp->count - 1 - i;
6783 memmove(&fp->fp[i], &fp->fp[i + 1],
6784 left * sizeof(struct file *));
6791 __skb_queue_tail(&list, skb);
6801 __skb_queue_tail(&list, skb);
6803 skb = skb_dequeue(head);
6806 if (skb_peek(&list)) {
6807 spin_lock_irq(&head->lock);
6808 while ((skb = __skb_dequeue(&list)) != NULL)
6809 __skb_queue_tail(head, skb);
6810 spin_unlock_irq(&head->lock);
6817 struct io_file_put {
6818 struct list_head list;
6822 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
6824 struct fixed_file_data *file_data = ref_node->file_data;
6825 struct io_ring_ctx *ctx = file_data->ctx;
6826 struct io_file_put *pfile, *tmp;
6828 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6829 list_del(&pfile->list);
6830 io_ring_file_put(ctx, pfile->file);
6834 spin_lock(&file_data->lock);
6835 list_del(&ref_node->node);
6836 spin_unlock(&file_data->lock);
6838 percpu_ref_exit(&ref_node->refs);
6840 percpu_ref_put(&file_data->refs);
6843 static void io_file_put_work(struct work_struct *work)
6845 struct io_ring_ctx *ctx;
6846 struct llist_node *node;
6848 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
6849 node = llist_del_all(&ctx->file_put_llist);
6852 struct fixed_file_ref_node *ref_node;
6853 struct llist_node *next = node->next;
6855 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
6856 __io_file_put_work(ref_node);
6861 static void io_file_data_ref_zero(struct percpu_ref *ref)
6863 struct fixed_file_ref_node *ref_node;
6864 struct io_ring_ctx *ctx;
6868 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6869 ctx = ref_node->file_data->ctx;
6871 if (percpu_ref_is_dying(&ctx->file_data->refs))
6874 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
6876 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
6878 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
6881 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6882 struct io_ring_ctx *ctx)
6884 struct fixed_file_ref_node *ref_node;
6886 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6888 return ERR_PTR(-ENOMEM);
6890 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6893 return ERR_PTR(-ENOMEM);
6895 INIT_LIST_HEAD(&ref_node->node);
6896 INIT_LIST_HEAD(&ref_node->file_list);
6897 ref_node->file_data = ctx->file_data;
6901 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6903 percpu_ref_exit(&ref_node->refs);
6907 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6910 __s32 __user *fds = (__s32 __user *) arg;
6915 struct fixed_file_ref_node *ref_node;
6921 if (nr_args > IORING_MAX_FIXED_FILES)
6924 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6925 if (!ctx->file_data)
6927 ctx->file_data->ctx = ctx;
6928 init_completion(&ctx->file_data->done);
6929 INIT_LIST_HEAD(&ctx->file_data->ref_list);
6930 spin_lock_init(&ctx->file_data->lock);
6932 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6933 ctx->file_data->table = kcalloc(nr_tables,
6934 sizeof(struct fixed_file_table),
6936 if (!ctx->file_data->table) {
6937 kfree(ctx->file_data);
6938 ctx->file_data = NULL;
6942 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6943 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6944 kfree(ctx->file_data->table);
6945 kfree(ctx->file_data);
6946 ctx->file_data = NULL;
6950 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6951 percpu_ref_exit(&ctx->file_data->refs);
6952 kfree(ctx->file_data->table);
6953 kfree(ctx->file_data);
6954 ctx->file_data = NULL;
6958 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6959 struct fixed_file_table *table;
6963 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6965 /* allow sparse sets */
6971 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6972 index = i & IORING_FILE_TABLE_MASK;
6980 * Don't allow io_uring instances to be registered. If UNIX
6981 * isn't enabled, then this causes a reference cycle and this
6982 * instance can never get freed. If UNIX is enabled we'll
6983 * handle it just fine, but there's still no point in allowing
6984 * a ring fd as it doesn't support regular read/write anyway.
6986 if (file->f_op == &io_uring_fops) {
6991 table->files[index] = file;
6995 for (i = 0; i < ctx->nr_user_files; i++) {
6996 file = io_file_from_index(ctx, i);
7000 for (i = 0; i < nr_tables; i++)
7001 kfree(ctx->file_data->table[i].files);
7003 kfree(ctx->file_data->table);
7004 kfree(ctx->file_data);
7005 ctx->file_data = NULL;
7006 ctx->nr_user_files = 0;
7010 ret = io_sqe_files_scm(ctx);
7012 io_sqe_files_unregister(ctx);
7016 ref_node = alloc_fixed_file_ref_node(ctx);
7017 if (IS_ERR(ref_node)) {
7018 io_sqe_files_unregister(ctx);
7019 return PTR_ERR(ref_node);
7022 ctx->file_data->cur_refs = &ref_node->refs;
7023 spin_lock(&ctx->file_data->lock);
7024 list_add(&ref_node->node, &ctx->file_data->ref_list);
7025 spin_unlock(&ctx->file_data->lock);
7026 percpu_ref_get(&ctx->file_data->refs);
7030 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7033 #if defined(CONFIG_UNIX)
7034 struct sock *sock = ctx->ring_sock->sk;
7035 struct sk_buff_head *head = &sock->sk_receive_queue;
7036 struct sk_buff *skb;
7039 * See if we can merge this file into an existing skb SCM_RIGHTS
7040 * file set. If there's no room, fall back to allocating a new skb
7041 * and filling it in.
7043 spin_lock_irq(&head->lock);
7044 skb = skb_peek(head);
7046 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7048 if (fpl->count < SCM_MAX_FD) {
7049 __skb_unlink(skb, head);
7050 spin_unlock_irq(&head->lock);
7051 fpl->fp[fpl->count] = get_file(file);
7052 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7054 spin_lock_irq(&head->lock);
7055 __skb_queue_head(head, skb);
7060 spin_unlock_irq(&head->lock);
7067 return __io_sqe_files_scm(ctx, 1, index);
7073 static int io_queue_file_removal(struct fixed_file_data *data,
7076 struct io_file_put *pfile;
7077 struct percpu_ref *refs = data->cur_refs;
7078 struct fixed_file_ref_node *ref_node;
7080 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7084 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
7086 list_add(&pfile->list, &ref_node->file_list);
7091 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7092 struct io_uring_files_update *up,
7095 struct fixed_file_data *data = ctx->file_data;
7096 struct fixed_file_ref_node *ref_node;
7101 bool needs_switch = false;
7103 if (check_add_overflow(up->offset, nr_args, &done))
7105 if (done > ctx->nr_user_files)
7108 ref_node = alloc_fixed_file_ref_node(ctx);
7109 if (IS_ERR(ref_node))
7110 return PTR_ERR(ref_node);
7113 fds = u64_to_user_ptr(up->fds);
7115 struct fixed_file_table *table;
7119 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7123 i = array_index_nospec(up->offset, ctx->nr_user_files);
7124 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7125 index = i & IORING_FILE_TABLE_MASK;
7126 if (table->files[index]) {
7127 file = io_file_from_index(ctx, index);
7128 err = io_queue_file_removal(data, file);
7131 table->files[index] = NULL;
7132 needs_switch = true;
7141 * Don't allow io_uring instances to be registered. If
7142 * UNIX isn't enabled, then this causes a reference
7143 * cycle and this instance can never get freed. If UNIX
7144 * is enabled we'll handle it just fine, but there's
7145 * still no point in allowing a ring fd as it doesn't
7146 * support regular read/write anyway.
7148 if (file->f_op == &io_uring_fops) {
7153 table->files[index] = file;
7154 err = io_sqe_file_register(ctx, file, i);
7164 percpu_ref_kill(data->cur_refs);
7165 spin_lock(&data->lock);
7166 list_add(&ref_node->node, &data->ref_list);
7167 data->cur_refs = &ref_node->refs;
7168 spin_unlock(&data->lock);
7169 percpu_ref_get(&ctx->file_data->refs);
7171 destroy_fixed_file_ref_node(ref_node);
7173 return done ? done : err;
7176 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7179 struct io_uring_files_update up;
7181 if (!ctx->file_data)
7185 if (copy_from_user(&up, arg, sizeof(up)))
7190 return __io_sqe_files_update(ctx, &up, nr_args);
7193 static void io_free_work(struct io_wq_work *work)
7195 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7197 /* Consider that io_steal_work() relies on this ref */
7201 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7202 struct io_uring_params *p)
7204 struct io_wq_data data;
7206 struct io_ring_ctx *ctx_attach;
7207 unsigned int concurrency;
7210 data.user = ctx->user;
7211 data.free_work = io_free_work;
7212 data.do_work = io_wq_submit_work;
7214 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7215 /* Do QD, or 4 * CPUS, whatever is smallest */
7216 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7218 ctx->io_wq = io_wq_create(concurrency, &data);
7219 if (IS_ERR(ctx->io_wq)) {
7220 ret = PTR_ERR(ctx->io_wq);
7226 f = fdget(p->wq_fd);
7230 if (f.file->f_op != &io_uring_fops) {
7235 ctx_attach = f.file->private_data;
7236 /* @io_wq is protected by holding the fd */
7237 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7242 ctx->io_wq = ctx_attach->io_wq;
7248 static int io_sq_offload_start(struct io_ring_ctx *ctx,
7249 struct io_uring_params *p)
7253 mmgrab(current->mm);
7254 ctx->sqo_mm = current->mm;
7256 if (ctx->flags & IORING_SETUP_SQPOLL) {
7258 if (!capable(CAP_SYS_ADMIN))
7261 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7262 if (!ctx->sq_thread_idle)
7263 ctx->sq_thread_idle = HZ;
7265 if (p->flags & IORING_SETUP_SQ_AFF) {
7266 int cpu = p->sq_thread_cpu;
7269 if (cpu >= nr_cpu_ids)
7271 if (!cpu_online(cpu))
7274 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
7278 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
7281 if (IS_ERR(ctx->sqo_thread)) {
7282 ret = PTR_ERR(ctx->sqo_thread);
7283 ctx->sqo_thread = NULL;
7286 wake_up_process(ctx->sqo_thread);
7287 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7288 /* Can't have SQ_AFF without SQPOLL */
7293 ret = io_init_wq_offload(ctx, p);
7299 io_finish_async(ctx);
7300 mmdrop(ctx->sqo_mm);
7305 static inline void __io_unaccount_mem(struct user_struct *user,
7306 unsigned long nr_pages)
7308 atomic_long_sub(nr_pages, &user->locked_vm);
7311 static inline int __io_account_mem(struct user_struct *user,
7312 unsigned long nr_pages)
7314 unsigned long page_limit, cur_pages, new_pages;
7316 /* Don't allow more pages than we can safely lock */
7317 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7320 cur_pages = atomic_long_read(&user->locked_vm);
7321 new_pages = cur_pages + nr_pages;
7322 if (new_pages > page_limit)
7324 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7325 new_pages) != cur_pages);
7330 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7331 enum io_mem_account acct)
7334 __io_unaccount_mem(ctx->user, nr_pages);
7337 if (acct == ACCT_LOCKED)
7338 ctx->sqo_mm->locked_vm -= nr_pages;
7339 else if (acct == ACCT_PINNED)
7340 atomic64_sub(nr_pages, &ctx->sqo_mm->pinned_vm);
7344 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7345 enum io_mem_account acct)
7349 if (ctx->limit_mem) {
7350 ret = __io_account_mem(ctx->user, nr_pages);
7356 if (acct == ACCT_LOCKED)
7357 ctx->sqo_mm->locked_vm += nr_pages;
7358 else if (acct == ACCT_PINNED)
7359 atomic64_add(nr_pages, &ctx->sqo_mm->pinned_vm);
7365 static void io_mem_free(void *ptr)
7372 page = virt_to_head_page(ptr);
7373 if (put_page_testzero(page))
7374 free_compound_page(page);
7377 static void *io_mem_alloc(size_t size)
7379 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7382 return (void *) __get_free_pages(gfp_flags, get_order(size));
7385 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7388 struct io_rings *rings;
7389 size_t off, sq_array_size;
7391 off = struct_size(rings, cqes, cq_entries);
7392 if (off == SIZE_MAX)
7396 off = ALIGN(off, SMP_CACHE_BYTES);
7401 sq_array_size = array_size(sizeof(u32), sq_entries);
7402 if (sq_array_size == SIZE_MAX)
7405 if (check_add_overflow(off, sq_array_size, &off))
7414 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7418 pages = (size_t)1 << get_order(
7419 rings_size(sq_entries, cq_entries, NULL));
7420 pages += (size_t)1 << get_order(
7421 array_size(sizeof(struct io_uring_sqe), sq_entries));
7426 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7430 if (!ctx->user_bufs)
7433 for (i = 0; i < ctx->nr_user_bufs; i++) {
7434 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7436 for (j = 0; j < imu->nr_bvecs; j++)
7437 unpin_user_page(imu->bvec[j].bv_page);
7439 io_unaccount_mem(ctx, imu->nr_bvecs, ACCT_PINNED);
7444 kfree(ctx->user_bufs);
7445 ctx->user_bufs = NULL;
7446 ctx->nr_user_bufs = 0;
7450 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7451 void __user *arg, unsigned index)
7453 struct iovec __user *src;
7455 #ifdef CONFIG_COMPAT
7457 struct compat_iovec __user *ciovs;
7458 struct compat_iovec ciov;
7460 ciovs = (struct compat_iovec __user *) arg;
7461 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7464 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7465 dst->iov_len = ciov.iov_len;
7469 src = (struct iovec __user *) arg;
7470 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7475 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7478 struct vm_area_struct **vmas = NULL;
7479 struct page **pages = NULL;
7480 int i, j, got_pages = 0;
7485 if (!nr_args || nr_args > UIO_MAXIOV)
7488 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7490 if (!ctx->user_bufs)
7493 for (i = 0; i < nr_args; i++) {
7494 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7495 unsigned long off, start, end, ubuf;
7500 ret = io_copy_iov(ctx, &iov, arg, i);
7505 * Don't impose further limits on the size and buffer
7506 * constraints here, we'll -EINVAL later when IO is
7507 * submitted if they are wrong.
7510 if (!iov.iov_base || !iov.iov_len)
7513 /* arbitrary limit, but we need something */
7514 if (iov.iov_len > SZ_1G)
7517 ubuf = (unsigned long) iov.iov_base;
7518 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7519 start = ubuf >> PAGE_SHIFT;
7520 nr_pages = end - start;
7522 ret = io_account_mem(ctx, nr_pages, ACCT_PINNED);
7527 if (!pages || nr_pages > got_pages) {
7530 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7532 vmas = kvmalloc_array(nr_pages,
7533 sizeof(struct vm_area_struct *),
7535 if (!pages || !vmas) {
7537 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7540 got_pages = nr_pages;
7543 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7547 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7552 mmap_read_lock(current->mm);
7553 pret = pin_user_pages(ubuf, nr_pages,
7554 FOLL_WRITE | FOLL_LONGTERM,
7556 if (pret == nr_pages) {
7557 /* don't support file backed memory */
7558 for (j = 0; j < nr_pages; j++) {
7559 struct vm_area_struct *vma = vmas[j];
7562 !is_file_hugepages(vma->vm_file)) {
7568 ret = pret < 0 ? pret : -EFAULT;
7570 mmap_read_unlock(current->mm);
7573 * if we did partial map, or found file backed vmas,
7574 * release any pages we did get
7577 unpin_user_pages(pages, pret);
7578 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7583 off = ubuf & ~PAGE_MASK;
7585 for (j = 0; j < nr_pages; j++) {
7588 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7589 imu->bvec[j].bv_page = pages[j];
7590 imu->bvec[j].bv_len = vec_len;
7591 imu->bvec[j].bv_offset = off;
7595 /* store original address for later verification */
7597 imu->len = iov.iov_len;
7598 imu->nr_bvecs = nr_pages;
7600 ctx->nr_user_bufs++;
7608 io_sqe_buffer_unregister(ctx);
7612 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7614 __s32 __user *fds = arg;
7620 if (copy_from_user(&fd, fds, sizeof(*fds)))
7623 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7624 if (IS_ERR(ctx->cq_ev_fd)) {
7625 int ret = PTR_ERR(ctx->cq_ev_fd);
7626 ctx->cq_ev_fd = NULL;
7633 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7635 if (ctx->cq_ev_fd) {
7636 eventfd_ctx_put(ctx->cq_ev_fd);
7637 ctx->cq_ev_fd = NULL;
7644 static int __io_destroy_buffers(int id, void *p, void *data)
7646 struct io_ring_ctx *ctx = data;
7647 struct io_buffer *buf = p;
7649 __io_remove_buffers(ctx, buf, id, -1U);
7653 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7655 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7656 idr_destroy(&ctx->io_buffer_idr);
7659 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7661 io_finish_async(ctx);
7663 mmdrop(ctx->sqo_mm);
7667 io_iopoll_reap_events(ctx);
7668 io_sqe_buffer_unregister(ctx);
7669 io_sqe_files_unregister(ctx);
7670 io_eventfd_unregister(ctx);
7671 io_destroy_buffers(ctx);
7672 idr_destroy(&ctx->personality_idr);
7674 #if defined(CONFIG_UNIX)
7675 if (ctx->ring_sock) {
7676 ctx->ring_sock->file = NULL; /* so that iput() is called */
7677 sock_release(ctx->ring_sock);
7681 io_mem_free(ctx->rings);
7682 io_mem_free(ctx->sq_sqes);
7684 percpu_ref_exit(&ctx->refs);
7685 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
7687 free_uid(ctx->user);
7688 put_cred(ctx->creds);
7689 kfree(ctx->cancel_hash);
7690 kmem_cache_free(req_cachep, ctx->fallback_req);
7694 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7696 struct io_ring_ctx *ctx = file->private_data;
7699 poll_wait(file, &ctx->cq_wait, wait);
7701 * synchronizes with barrier from wq_has_sleeper call in
7705 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7706 ctx->rings->sq_ring_entries)
7707 mask |= EPOLLOUT | EPOLLWRNORM;
7708 if (io_cqring_events(ctx, false))
7709 mask |= EPOLLIN | EPOLLRDNORM;
7714 static int io_uring_fasync(int fd, struct file *file, int on)
7716 struct io_ring_ctx *ctx = file->private_data;
7718 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7721 static int io_remove_personalities(int id, void *p, void *data)
7723 struct io_ring_ctx *ctx = data;
7724 const struct cred *cred;
7726 cred = idr_remove(&ctx->personality_idr, id);
7732 static void io_ring_exit_work(struct work_struct *work)
7734 struct io_ring_ctx *ctx;
7736 ctx = container_of(work, struct io_ring_ctx, exit_work);
7738 io_cqring_overflow_flush(ctx, true);
7741 * If we're doing polled IO and end up having requests being
7742 * submitted async (out-of-line), then completions can come in while
7743 * we're waiting for refs to drop. We need to reap these manually,
7744 * as nobody else will be looking for them.
7746 while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20)) {
7747 io_iopoll_reap_events(ctx);
7749 io_cqring_overflow_flush(ctx, true);
7751 io_ring_ctx_free(ctx);
7754 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7756 mutex_lock(&ctx->uring_lock);
7757 percpu_ref_kill(&ctx->refs);
7758 mutex_unlock(&ctx->uring_lock);
7760 io_kill_timeouts(ctx);
7761 io_poll_remove_all(ctx);
7764 io_wq_cancel_all(ctx->io_wq);
7766 io_iopoll_reap_events(ctx);
7767 /* if we failed setting up the ctx, we might not have any rings */
7769 io_cqring_overflow_flush(ctx, true);
7770 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7771 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7772 queue_work(system_wq, &ctx->exit_work);
7775 static int io_uring_release(struct inode *inode, struct file *file)
7777 struct io_ring_ctx *ctx = file->private_data;
7779 file->private_data = NULL;
7780 io_ring_ctx_wait_and_kill(ctx);
7784 static bool io_wq_files_match(struct io_wq_work *work, void *data)
7786 struct files_struct *files = data;
7788 return work->files == files;
7791 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7792 struct files_struct *files)
7794 if (list_empty_careful(&ctx->inflight_list))
7797 /* cancel all at once, should be faster than doing it one by one*/
7798 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
7800 while (!list_empty_careful(&ctx->inflight_list)) {
7801 struct io_kiocb *cancel_req = NULL, *req;
7804 spin_lock_irq(&ctx->inflight_lock);
7805 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7806 if (req->work.files != files)
7808 /* req is being completed, ignore */
7809 if (!refcount_inc_not_zero(&req->refs))
7815 prepare_to_wait(&ctx->inflight_wait, &wait,
7816 TASK_UNINTERRUPTIBLE);
7817 spin_unlock_irq(&ctx->inflight_lock);
7819 /* We need to keep going until we don't find a matching req */
7823 if (cancel_req->flags & REQ_F_OVERFLOW) {
7824 spin_lock_irq(&ctx->completion_lock);
7825 list_del(&cancel_req->list);
7826 cancel_req->flags &= ~REQ_F_OVERFLOW;
7827 if (list_empty(&ctx->cq_overflow_list)) {
7828 clear_bit(0, &ctx->sq_check_overflow);
7829 clear_bit(0, &ctx->cq_check_overflow);
7831 spin_unlock_irq(&ctx->completion_lock);
7833 WRITE_ONCE(ctx->rings->cq_overflow,
7834 atomic_inc_return(&ctx->cached_cq_overflow));
7837 * Put inflight ref and overflow ref. If that's
7838 * all we had, then we're done with this request.
7840 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7841 io_free_req(cancel_req);
7842 finish_wait(&ctx->inflight_wait, &wait);
7846 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7847 io_put_req(cancel_req);
7851 finish_wait(&ctx->inflight_wait, &wait);
7855 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
7857 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7858 struct task_struct *task = data;
7860 return req->task == task;
7863 static int io_uring_flush(struct file *file, void *data)
7865 struct io_ring_ctx *ctx = file->private_data;
7867 io_uring_cancel_files(ctx, data);
7870 * If the task is going away, cancel work it may have pending
7872 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7873 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, current, true);
7878 static void *io_uring_validate_mmap_request(struct file *file,
7879 loff_t pgoff, size_t sz)
7881 struct io_ring_ctx *ctx = file->private_data;
7882 loff_t offset = pgoff << PAGE_SHIFT;
7887 case IORING_OFF_SQ_RING:
7888 case IORING_OFF_CQ_RING:
7891 case IORING_OFF_SQES:
7895 return ERR_PTR(-EINVAL);
7898 page = virt_to_head_page(ptr);
7899 if (sz > page_size(page))
7900 return ERR_PTR(-EINVAL);
7907 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7909 size_t sz = vma->vm_end - vma->vm_start;
7913 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7915 return PTR_ERR(ptr);
7917 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7918 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7921 #else /* !CONFIG_MMU */
7923 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7925 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7928 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7930 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7933 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7934 unsigned long addr, unsigned long len,
7935 unsigned long pgoff, unsigned long flags)
7939 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7941 return PTR_ERR(ptr);
7943 return (unsigned long) ptr;
7946 #endif /* !CONFIG_MMU */
7948 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7949 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7952 struct io_ring_ctx *ctx;
7957 if (current->task_works)
7960 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7968 if (f.file->f_op != &io_uring_fops)
7972 ctx = f.file->private_data;
7973 if (!percpu_ref_tryget(&ctx->refs))
7977 * For SQ polling, the thread will do all submissions and completions.
7978 * Just return the requested submit count, and wake the thread if
7982 if (ctx->flags & IORING_SETUP_SQPOLL) {
7983 if (!list_empty_careful(&ctx->cq_overflow_list))
7984 io_cqring_overflow_flush(ctx, false);
7985 if (flags & IORING_ENTER_SQ_WAKEUP)
7986 wake_up(&ctx->sqo_wait);
7987 submitted = to_submit;
7988 } else if (to_submit) {
7989 mutex_lock(&ctx->uring_lock);
7990 submitted = io_submit_sqes(ctx, to_submit, f.file, fd);
7991 mutex_unlock(&ctx->uring_lock);
7993 if (submitted != to_submit)
7996 if (flags & IORING_ENTER_GETEVENTS) {
7997 unsigned nr_events = 0;
7999 min_complete = min(min_complete, ctx->cq_entries);
8002 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
8003 * space applications don't need to do io completion events
8004 * polling again, they can rely on io_sq_thread to do polling
8005 * work, which can reduce cpu usage and uring_lock contention.
8007 if (ctx->flags & IORING_SETUP_IOPOLL &&
8008 !(ctx->flags & IORING_SETUP_SQPOLL)) {
8009 ret = io_iopoll_check(ctx, &nr_events, min_complete);
8011 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
8016 percpu_ref_put(&ctx->refs);
8019 return submitted ? submitted : ret;
8022 #ifdef CONFIG_PROC_FS
8023 static int io_uring_show_cred(int id, void *p, void *data)
8025 const struct cred *cred = p;
8026 struct seq_file *m = data;
8027 struct user_namespace *uns = seq_user_ns(m);
8028 struct group_info *gi;
8033 seq_printf(m, "%5d\n", id);
8034 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
8035 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
8036 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
8037 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
8038 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
8039 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
8040 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
8041 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
8042 seq_puts(m, "\n\tGroups:\t");
8043 gi = cred->group_info;
8044 for (g = 0; g < gi->ngroups; g++) {
8045 seq_put_decimal_ull(m, g ? " " : "",
8046 from_kgid_munged(uns, gi->gid[g]));
8048 seq_puts(m, "\n\tCapEff:\t");
8049 cap = cred->cap_effective;
8050 CAP_FOR_EACH_U32(__capi)
8051 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8056 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8060 mutex_lock(&ctx->uring_lock);
8061 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8062 for (i = 0; i < ctx->nr_user_files; i++) {
8063 struct fixed_file_table *table;
8066 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8067 f = table->files[i & IORING_FILE_TABLE_MASK];
8069 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8071 seq_printf(m, "%5u: <none>\n", i);
8073 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8074 for (i = 0; i < ctx->nr_user_bufs; i++) {
8075 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8077 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8078 (unsigned int) buf->len);
8080 if (!idr_is_empty(&ctx->personality_idr)) {
8081 seq_printf(m, "Personalities:\n");
8082 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8084 seq_printf(m, "PollList:\n");
8085 spin_lock_irq(&ctx->completion_lock);
8086 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8087 struct hlist_head *list = &ctx->cancel_hash[i];
8088 struct io_kiocb *req;
8090 hlist_for_each_entry(req, list, hash_node)
8091 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
8092 req->task->task_works != NULL);
8094 spin_unlock_irq(&ctx->completion_lock);
8095 mutex_unlock(&ctx->uring_lock);
8098 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8100 struct io_ring_ctx *ctx = f->private_data;
8102 if (percpu_ref_tryget(&ctx->refs)) {
8103 __io_uring_show_fdinfo(ctx, m);
8104 percpu_ref_put(&ctx->refs);
8109 static const struct file_operations io_uring_fops = {
8110 .release = io_uring_release,
8111 .flush = io_uring_flush,
8112 .mmap = io_uring_mmap,
8114 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8115 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8117 .poll = io_uring_poll,
8118 .fasync = io_uring_fasync,
8119 #ifdef CONFIG_PROC_FS
8120 .show_fdinfo = io_uring_show_fdinfo,
8124 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8125 struct io_uring_params *p)
8127 struct io_rings *rings;
8128 size_t size, sq_array_offset;
8130 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8131 if (size == SIZE_MAX)
8134 rings = io_mem_alloc(size);
8139 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8140 rings->sq_ring_mask = p->sq_entries - 1;
8141 rings->cq_ring_mask = p->cq_entries - 1;
8142 rings->sq_ring_entries = p->sq_entries;
8143 rings->cq_ring_entries = p->cq_entries;
8144 ctx->sq_mask = rings->sq_ring_mask;
8145 ctx->cq_mask = rings->cq_ring_mask;
8146 ctx->sq_entries = rings->sq_ring_entries;
8147 ctx->cq_entries = rings->cq_ring_entries;
8149 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8150 if (size == SIZE_MAX) {
8151 io_mem_free(ctx->rings);
8156 ctx->sq_sqes = io_mem_alloc(size);
8157 if (!ctx->sq_sqes) {
8158 io_mem_free(ctx->rings);
8167 * Allocate an anonymous fd, this is what constitutes the application
8168 * visible backing of an io_uring instance. The application mmaps this
8169 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8170 * we have to tie this fd to a socket for file garbage collection purposes.
8172 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8177 #if defined(CONFIG_UNIX)
8178 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8184 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8188 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8189 O_RDWR | O_CLOEXEC);
8192 ret = PTR_ERR(file);
8196 #if defined(CONFIG_UNIX)
8197 ctx->ring_sock->file = file;
8199 fd_install(ret, file);
8202 #if defined(CONFIG_UNIX)
8203 sock_release(ctx->ring_sock);
8204 ctx->ring_sock = NULL;
8209 static int io_uring_create(unsigned entries, struct io_uring_params *p,
8210 struct io_uring_params __user *params)
8212 struct user_struct *user = NULL;
8213 struct io_ring_ctx *ctx;
8219 if (entries > IORING_MAX_ENTRIES) {
8220 if (!(p->flags & IORING_SETUP_CLAMP))
8222 entries = IORING_MAX_ENTRIES;
8226 * Use twice as many entries for the CQ ring. It's possible for the
8227 * application to drive a higher depth than the size of the SQ ring,
8228 * since the sqes are only used at submission time. This allows for
8229 * some flexibility in overcommitting a bit. If the application has
8230 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
8231 * of CQ ring entries manually.
8233 p->sq_entries = roundup_pow_of_two(entries);
8234 if (p->flags & IORING_SETUP_CQSIZE) {
8236 * If IORING_SETUP_CQSIZE is set, we do the same roundup
8237 * to a power-of-two, if it isn't already. We do NOT impose
8238 * any cq vs sq ring sizing.
8240 if (p->cq_entries < p->sq_entries)
8242 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
8243 if (!(p->flags & IORING_SETUP_CLAMP))
8245 p->cq_entries = IORING_MAX_CQ_ENTRIES;
8247 p->cq_entries = roundup_pow_of_two(p->cq_entries);
8249 p->cq_entries = 2 * p->sq_entries;
8252 user = get_uid(current_user());
8253 limit_mem = !capable(CAP_IPC_LOCK);
8256 ret = __io_account_mem(user,
8257 ring_pages(p->sq_entries, p->cq_entries));
8264 ctx = io_ring_ctx_alloc(p);
8267 __io_unaccount_mem(user, ring_pages(p->sq_entries,
8272 ctx->compat = in_compat_syscall();
8274 ctx->creds = get_current_cred();
8276 ret = io_allocate_scq_urings(ctx, p);
8280 ret = io_sq_offload_start(ctx, p);
8284 memset(&p->sq_off, 0, sizeof(p->sq_off));
8285 p->sq_off.head = offsetof(struct io_rings, sq.head);
8286 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
8287 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
8288 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
8289 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
8290 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
8291 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
8293 memset(&p->cq_off, 0, sizeof(p->cq_off));
8294 p->cq_off.head = offsetof(struct io_rings, cq.head);
8295 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
8296 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
8297 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
8298 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
8299 p->cq_off.cqes = offsetof(struct io_rings, cqes);
8300 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
8302 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
8303 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
8304 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
8305 IORING_FEAT_POLL_32BITS;
8307 if (copy_to_user(params, p, sizeof(*p))) {
8312 * Install ring fd as the very last thing, so we don't risk someone
8313 * having closed it before we finish setup
8315 ret = io_uring_get_fd(ctx);
8319 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
8320 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
8322 ctx->limit_mem = limit_mem;
8325 io_ring_ctx_wait_and_kill(ctx);
8330 * Sets up an aio uring context, and returns the fd. Applications asks for a
8331 * ring size, we return the actual sq/cq ring sizes (among other things) in the
8332 * params structure passed in.
8334 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
8336 struct io_uring_params p;
8339 if (copy_from_user(&p, params, sizeof(p)))
8341 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
8346 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8347 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8348 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8351 return io_uring_create(entries, &p, params);
8354 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8355 struct io_uring_params __user *, params)
8357 return io_uring_setup(entries, params);
8360 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8362 struct io_uring_probe *p;
8366 size = struct_size(p, ops, nr_args);
8367 if (size == SIZE_MAX)
8369 p = kzalloc(size, GFP_KERNEL);
8374 if (copy_from_user(p, arg, size))
8377 if (memchr_inv(p, 0, size))
8380 p->last_op = IORING_OP_LAST - 1;
8381 if (nr_args > IORING_OP_LAST)
8382 nr_args = IORING_OP_LAST;
8384 for (i = 0; i < nr_args; i++) {
8386 if (!io_op_defs[i].not_supported)
8387 p->ops[i].flags = IO_URING_OP_SUPPORTED;
8392 if (copy_to_user(arg, p, size))
8399 static int io_register_personality(struct io_ring_ctx *ctx)
8401 const struct cred *creds = get_current_cred();
8404 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8405 USHRT_MAX, GFP_KERNEL);
8411 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8413 const struct cred *old_creds;
8415 old_creds = idr_remove(&ctx->personality_idr, id);
8417 put_cred(old_creds);
8424 static bool io_register_op_must_quiesce(int op)
8427 case IORING_UNREGISTER_FILES:
8428 case IORING_REGISTER_FILES_UPDATE:
8429 case IORING_REGISTER_PROBE:
8430 case IORING_REGISTER_PERSONALITY:
8431 case IORING_UNREGISTER_PERSONALITY:
8438 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8439 void __user *arg, unsigned nr_args)
8440 __releases(ctx->uring_lock)
8441 __acquires(ctx->uring_lock)
8446 * We're inside the ring mutex, if the ref is already dying, then
8447 * someone else killed the ctx or is already going through
8448 * io_uring_register().
8450 if (percpu_ref_is_dying(&ctx->refs))
8453 if (io_register_op_must_quiesce(opcode)) {
8454 percpu_ref_kill(&ctx->refs);
8457 * Drop uring mutex before waiting for references to exit. If
8458 * another thread is currently inside io_uring_enter() it might
8459 * need to grab the uring_lock to make progress. If we hold it
8460 * here across the drain wait, then we can deadlock. It's safe
8461 * to drop the mutex here, since no new references will come in
8462 * after we've killed the percpu ref.
8464 mutex_unlock(&ctx->uring_lock);
8465 ret = wait_for_completion_interruptible(&ctx->ref_comp);
8466 mutex_lock(&ctx->uring_lock);
8468 percpu_ref_resurrect(&ctx->refs);
8475 case IORING_REGISTER_BUFFERS:
8476 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8478 case IORING_UNREGISTER_BUFFERS:
8482 ret = io_sqe_buffer_unregister(ctx);
8484 case IORING_REGISTER_FILES:
8485 ret = io_sqe_files_register(ctx, arg, nr_args);
8487 case IORING_UNREGISTER_FILES:
8491 ret = io_sqe_files_unregister(ctx);
8493 case IORING_REGISTER_FILES_UPDATE:
8494 ret = io_sqe_files_update(ctx, arg, nr_args);
8496 case IORING_REGISTER_EVENTFD:
8497 case IORING_REGISTER_EVENTFD_ASYNC:
8501 ret = io_eventfd_register(ctx, arg);
8504 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8505 ctx->eventfd_async = 1;
8507 ctx->eventfd_async = 0;
8509 case IORING_UNREGISTER_EVENTFD:
8513 ret = io_eventfd_unregister(ctx);
8515 case IORING_REGISTER_PROBE:
8517 if (!arg || nr_args > 256)
8519 ret = io_probe(ctx, arg, nr_args);
8521 case IORING_REGISTER_PERSONALITY:
8525 ret = io_register_personality(ctx);
8527 case IORING_UNREGISTER_PERSONALITY:
8531 ret = io_unregister_personality(ctx, nr_args);
8538 if (io_register_op_must_quiesce(opcode)) {
8539 /* bring the ctx back to life */
8540 percpu_ref_reinit(&ctx->refs);
8542 reinit_completion(&ctx->ref_comp);
8547 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8548 void __user *, arg, unsigned int, nr_args)
8550 struct io_ring_ctx *ctx;
8559 if (f.file->f_op != &io_uring_fops)
8562 ctx = f.file->private_data;
8564 mutex_lock(&ctx->uring_lock);
8565 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8566 mutex_unlock(&ctx->uring_lock);
8567 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8568 ctx->cq_ev_fd != NULL, ret);
8574 static int __init io_uring_init(void)
8576 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8577 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8578 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8581 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8582 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8583 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8584 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8585 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8586 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8587 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8588 BUILD_BUG_SQE_ELEM(8, __u64, off);
8589 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8590 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8591 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8592 BUILD_BUG_SQE_ELEM(24, __u32, len);
8593 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8594 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8595 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8596 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8597 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
8598 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
8599 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8600 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8601 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8602 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8603 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8604 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8605 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8606 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8607 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8608 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8609 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8610 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8611 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8613 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8614 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8615 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8618 __initcall(io_uring_init);