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 <linux/refcount.h>
48 #include <linux/uio.h>
50 #include <linux/sched/signal.h>
52 #include <linux/file.h>
53 #include <linux/fdtable.h>
55 #include <linux/mman.h>
56 #include <linux/mmu_context.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/kthread.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
77 #define CREATE_TRACE_POINTS
78 #include <trace/events/io_uring.h>
80 #include <uapi/linux/io_uring.h>
85 #define IORING_MAX_ENTRIES 32768
86 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
89 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
91 #define IORING_FILE_TABLE_SHIFT 9
92 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
93 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
94 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
97 u32 head ____cacheline_aligned_in_smp;
98 u32 tail ____cacheline_aligned_in_smp;
102 * This data is shared with the application through the mmap at offsets
103 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
105 * The offsets to the member fields are published through struct
106 * io_sqring_offsets when calling io_uring_setup.
110 * Head and tail offsets into the ring; the offsets need to be
111 * masked to get valid indices.
113 * The kernel controls head of the sq ring and the tail of the cq ring,
114 * and the application controls tail of the sq ring and the head of the
117 struct io_uring sq, cq;
119 * Bitmasks to apply to head and tail offsets (constant, equals
122 u32 sq_ring_mask, cq_ring_mask;
123 /* Ring sizes (constant, power of 2) */
124 u32 sq_ring_entries, cq_ring_entries;
126 * Number of invalid entries dropped by the kernel due to
127 * invalid index stored in array
129 * Written by the kernel, shouldn't be modified by the
130 * application (i.e. get number of "new events" by comparing to
133 * After a new SQ head value was read by the application this
134 * counter includes all submissions that were dropped reaching
135 * the new SQ head (and possibly more).
141 * Written by the kernel, shouldn't be modified by the
144 * The application needs a full memory barrier before checking
145 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
149 * Number of completion events lost because the queue was full;
150 * this should be avoided by the application by making sure
151 * there are not more requests pending than there is space in
152 * the completion queue.
154 * Written by the kernel, shouldn't be modified by the
155 * application (i.e. get number of "new events" by comparing to
158 * As completion events come in out of order this counter is not
159 * ordered with any other data.
163 * Ring buffer of completion events.
165 * The kernel writes completion events fresh every time they are
166 * produced, so the application is allowed to modify pending
169 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
172 struct io_mapped_ubuf {
175 struct bio_vec *bvec;
176 unsigned int nr_bvecs;
179 struct fixed_file_table {
187 struct fixed_file_data {
188 struct fixed_file_table *table;
189 struct io_ring_ctx *ctx;
191 struct percpu_ref refs;
192 struct llist_head put_llist;
194 struct work_struct ref_work;
195 struct completion done;
200 struct percpu_ref refs;
201 } ____cacheline_aligned_in_smp;
207 int cq_overflow_flushed: 1;
209 int eventfd_async: 1;
212 * Ring buffer of indices into array of io_uring_sqe, which is
213 * mmapped by the application using the IORING_OFF_SQES offset.
215 * This indirection could e.g. be used to assign fixed
216 * io_uring_sqe entries to operations and only submit them to
217 * the queue when needed.
219 * The kernel modifies neither the indices array nor the entries
223 unsigned cached_sq_head;
226 unsigned sq_thread_idle;
227 unsigned cached_sq_dropped;
228 atomic_t cached_cq_overflow;
229 unsigned long sq_check_overflow;
231 struct list_head defer_list;
232 struct list_head timeout_list;
233 struct list_head cq_overflow_list;
235 wait_queue_head_t inflight_wait;
236 struct io_uring_sqe *sq_sqes;
237 } ____cacheline_aligned_in_smp;
239 struct io_rings *rings;
243 struct task_struct *sqo_thread; /* if using sq thread polling */
244 struct mm_struct *sqo_mm;
245 wait_queue_head_t sqo_wait;
248 * If used, fixed file set. Writers must ensure that ->refs is dead,
249 * readers must ensure that ->refs is alive as long as the file* is
250 * used. Only updated through io_uring_register(2).
252 struct fixed_file_data *file_data;
253 unsigned nr_user_files;
255 struct file *ring_file;
257 /* if used, fixed mapped user buffers */
258 unsigned nr_user_bufs;
259 struct io_mapped_ubuf *user_bufs;
261 struct user_struct *user;
263 const struct cred *creds;
265 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
266 struct completion *completions;
268 /* if all else fails... */
269 struct io_kiocb *fallback_req;
271 #if defined(CONFIG_UNIX)
272 struct socket *ring_sock;
276 unsigned cached_cq_tail;
279 atomic_t cq_timeouts;
280 unsigned long cq_check_overflow;
281 struct wait_queue_head cq_wait;
282 struct fasync_struct *cq_fasync;
283 struct eventfd_ctx *cq_ev_fd;
284 } ____cacheline_aligned_in_smp;
287 struct mutex uring_lock;
288 wait_queue_head_t wait;
289 } ____cacheline_aligned_in_smp;
292 spinlock_t completion_lock;
293 struct llist_head poll_llist;
296 * ->poll_list is protected by the ctx->uring_lock for
297 * io_uring instances that don't use IORING_SETUP_SQPOLL.
298 * For SQPOLL, only the single threaded io_sq_thread() will
299 * manipulate the list, hence no extra locking is needed there.
301 struct list_head poll_list;
302 struct hlist_head *cancel_hash;
303 unsigned cancel_hash_bits;
304 bool poll_multi_file;
306 spinlock_t inflight_lock;
307 struct list_head inflight_list;
308 } ____cacheline_aligned_in_smp;
312 * First field must be the file pointer in all the
313 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
315 struct io_poll_iocb {
318 struct wait_queue_head *head;
324 struct wait_queue_entry wait;
329 struct file *put_file;
333 struct io_timeout_data {
334 struct io_kiocb *req;
335 struct hrtimer timer;
336 struct timespec64 ts;
337 enum hrtimer_mode mode;
343 struct sockaddr __user *addr;
344 int __user *addr_len;
369 /* NOTE: kiocb has the file as the first member, so don't do it here */
377 struct sockaddr __user *addr;
384 struct user_msghdr __user *msg;
397 struct filename *filename;
398 struct statx __user *buffer;
402 struct io_files_update {
423 struct io_async_connect {
424 struct sockaddr_storage address;
427 struct io_async_msghdr {
428 struct iovec fast_iov[UIO_FASTIOV];
430 struct sockaddr __user *uaddr;
435 struct iovec fast_iov[UIO_FASTIOV];
441 struct io_async_open {
442 struct filename *filename;
445 struct io_async_ctx {
447 struct io_async_rw rw;
448 struct io_async_msghdr msg;
449 struct io_async_connect connect;
450 struct io_timeout_data timeout;
451 struct io_async_open open;
456 * NOTE! Each of the iocb union members has the file pointer
457 * as the first entry in their struct definition. So you can
458 * access the file pointer through any of the sub-structs,
459 * or directly as just 'ki_filp' in this struct.
465 struct io_poll_iocb poll;
466 struct io_accept accept;
468 struct io_cancel cancel;
469 struct io_timeout timeout;
470 struct io_connect connect;
471 struct io_sr_msg sr_msg;
473 struct io_close close;
474 struct io_files_update files_update;
475 struct io_fadvise fadvise;
476 struct io_madvise madvise;
479 struct io_async_ctx *io;
481 * llist_node is only used for poll deferred completions
483 struct llist_node llist_node;
486 bool needs_fixed_file;
489 struct io_ring_ctx *ctx;
491 struct list_head list;
492 struct hlist_node hash_node;
494 struct list_head link_list;
497 #define REQ_F_NOWAIT 1 /* must not punt to workers */
498 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
499 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
500 #define REQ_F_LINK_NEXT 8 /* already grabbed next link */
501 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
502 #define REQ_F_LINK 64 /* linked sqes */
503 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
504 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
505 #define REQ_F_TIMEOUT 1024 /* timeout request */
506 #define REQ_F_ISREG 2048 /* regular file */
507 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
508 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
509 #define REQ_F_INFLIGHT 16384 /* on inflight list */
510 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
511 #define REQ_F_HARDLINK 65536 /* doesn't sever on completion < 0 */
512 #define REQ_F_FORCE_ASYNC 131072 /* IOSQE_ASYNC */
513 #define REQ_F_CUR_POS 262144 /* read/write uses file position */
518 struct list_head inflight_entry;
520 struct io_wq_work work;
523 #define IO_PLUG_THRESHOLD 2
524 #define IO_IOPOLL_BATCH 8
526 struct io_submit_state {
527 struct blk_plug plug;
530 * io_kiocb alloc cache
532 void *reqs[IO_IOPOLL_BATCH];
533 unsigned int free_reqs;
534 unsigned int cur_req;
537 * File reference cache
541 unsigned int has_refs;
542 unsigned int used_refs;
543 unsigned int ios_left;
547 /* needs req->io allocated for deferral/async */
548 unsigned async_ctx : 1;
549 /* needs current->mm setup, does mm access */
550 unsigned needs_mm : 1;
551 /* needs req->file assigned */
552 unsigned needs_file : 1;
553 /* needs req->file assigned IFF fd is >= 0 */
554 unsigned fd_non_neg : 1;
555 /* hash wq insertion if file is a regular file */
556 unsigned hash_reg_file : 1;
557 /* unbound wq insertion if file is a non-regular file */
558 unsigned unbound_nonreg_file : 1;
559 /* opcode is not supported by this kernel */
560 unsigned not_supported : 1;
563 static const struct io_op_def io_op_defs[] = {
568 /* IORING_OP_READV */
572 .unbound_nonreg_file = 1,
575 /* IORING_OP_WRITEV */
580 .unbound_nonreg_file = 1,
583 /* IORING_OP_FSYNC */
587 /* IORING_OP_READ_FIXED */
589 .unbound_nonreg_file = 1,
592 /* IORING_OP_WRITE_FIXED */
595 .unbound_nonreg_file = 1,
598 /* IORING_OP_POLL_ADD */
600 .unbound_nonreg_file = 1,
603 /* IORING_OP_POLL_REMOVE */
606 /* IORING_OP_SYNC_FILE_RANGE */
610 /* IORING_OP_SENDMSG */
614 .unbound_nonreg_file = 1,
617 /* IORING_OP_RECVMSG */
621 .unbound_nonreg_file = 1,
624 /* IORING_OP_TIMEOUT */
629 /* IORING_OP_TIMEOUT_REMOVE */
632 /* IORING_OP_ACCEPT */
635 .unbound_nonreg_file = 1,
638 /* IORING_OP_ASYNC_CANCEL */
641 /* IORING_OP_LINK_TIMEOUT */
646 /* IORING_OP_CONNECT */
650 .unbound_nonreg_file = 1,
653 /* IORING_OP_FALLOCATE */
657 /* IORING_OP_OPENAT */
662 /* IORING_OP_CLOSE */
666 /* IORING_OP_FILES_UPDATE */
670 /* IORING_OP_STATX */
679 .unbound_nonreg_file = 1,
682 /* IORING_OP_WRITE */
685 .unbound_nonreg_file = 1,
688 /* IORING_OP_FADVISE */
692 /* IORING_OP_MADVISE */
699 .unbound_nonreg_file = 1,
705 .unbound_nonreg_file = 1,
708 /* IORING_OP_OPENAT2 */
714 static void io_wq_submit_work(struct io_wq_work **workptr);
715 static void io_cqring_fill_event(struct io_kiocb *req, long res);
716 static void io_put_req(struct io_kiocb *req);
717 static void __io_double_put_req(struct io_kiocb *req);
718 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
719 static void io_queue_linked_timeout(struct io_kiocb *req);
720 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
721 struct io_uring_files_update *ip,
724 static struct kmem_cache *req_cachep;
726 static const struct file_operations io_uring_fops;
728 struct sock *io_uring_get_socket(struct file *file)
730 #if defined(CONFIG_UNIX)
731 if (file->f_op == &io_uring_fops) {
732 struct io_ring_ctx *ctx = file->private_data;
734 return ctx->ring_sock->sk;
739 EXPORT_SYMBOL(io_uring_get_socket);
741 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
743 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
745 complete(&ctx->completions[0]);
748 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
750 struct io_ring_ctx *ctx;
753 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
757 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
758 if (!ctx->fallback_req)
761 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
762 if (!ctx->completions)
766 * Use 5 bits less than the max cq entries, that should give us around
767 * 32 entries per hash list if totally full and uniformly spread.
769 hash_bits = ilog2(p->cq_entries);
773 ctx->cancel_hash_bits = hash_bits;
774 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
776 if (!ctx->cancel_hash)
778 __hash_init(ctx->cancel_hash, 1U << hash_bits);
780 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
781 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
784 ctx->flags = p->flags;
785 init_waitqueue_head(&ctx->cq_wait);
786 INIT_LIST_HEAD(&ctx->cq_overflow_list);
787 init_completion(&ctx->completions[0]);
788 init_completion(&ctx->completions[1]);
789 mutex_init(&ctx->uring_lock);
790 init_waitqueue_head(&ctx->wait);
791 spin_lock_init(&ctx->completion_lock);
792 init_llist_head(&ctx->poll_llist);
793 INIT_LIST_HEAD(&ctx->poll_list);
794 INIT_LIST_HEAD(&ctx->defer_list);
795 INIT_LIST_HEAD(&ctx->timeout_list);
796 init_waitqueue_head(&ctx->inflight_wait);
797 spin_lock_init(&ctx->inflight_lock);
798 INIT_LIST_HEAD(&ctx->inflight_list);
801 if (ctx->fallback_req)
802 kmem_cache_free(req_cachep, ctx->fallback_req);
803 kfree(ctx->completions);
804 kfree(ctx->cancel_hash);
809 static inline bool __req_need_defer(struct io_kiocb *req)
811 struct io_ring_ctx *ctx = req->ctx;
813 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
814 + atomic_read(&ctx->cached_cq_overflow);
817 static inline bool req_need_defer(struct io_kiocb *req)
819 if (unlikely(req->flags & REQ_F_IO_DRAIN))
820 return __req_need_defer(req);
825 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
827 struct io_kiocb *req;
829 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
830 if (req && !req_need_defer(req)) {
831 list_del_init(&req->list);
838 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
840 struct io_kiocb *req;
842 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
844 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
846 if (!__req_need_defer(req)) {
847 list_del_init(&req->list);
855 static void __io_commit_cqring(struct io_ring_ctx *ctx)
857 struct io_rings *rings = ctx->rings;
859 /* order cqe stores with ring update */
860 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
862 if (wq_has_sleeper(&ctx->cq_wait)) {
863 wake_up_interruptible(&ctx->cq_wait);
864 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
868 static inline bool io_prep_async_work(struct io_kiocb *req,
869 struct io_kiocb **link)
871 const struct io_op_def *def = &io_op_defs[req->opcode];
872 bool do_hashed = false;
874 if (req->flags & REQ_F_ISREG) {
875 if (def->hash_reg_file)
878 if (def->unbound_nonreg_file)
879 req->work.flags |= IO_WQ_WORK_UNBOUND;
882 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
884 *link = io_prep_linked_timeout(req);
888 static inline void io_queue_async_work(struct io_kiocb *req)
890 struct io_ring_ctx *ctx = req->ctx;
891 struct io_kiocb *link;
894 do_hashed = io_prep_async_work(req, &link);
896 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
899 io_wq_enqueue(ctx->io_wq, &req->work);
901 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
902 file_inode(req->file));
906 io_queue_linked_timeout(link);
909 static void io_kill_timeout(struct io_kiocb *req)
913 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
915 atomic_inc(&req->ctx->cq_timeouts);
916 list_del_init(&req->list);
917 io_cqring_fill_event(req, 0);
922 static void io_kill_timeouts(struct io_ring_ctx *ctx)
924 struct io_kiocb *req, *tmp;
926 spin_lock_irq(&ctx->completion_lock);
927 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
928 io_kill_timeout(req);
929 spin_unlock_irq(&ctx->completion_lock);
932 static void io_commit_cqring(struct io_ring_ctx *ctx)
934 struct io_kiocb *req;
936 while ((req = io_get_timeout_req(ctx)) != NULL)
937 io_kill_timeout(req);
939 __io_commit_cqring(ctx);
941 while ((req = io_get_deferred_req(ctx)) != NULL)
942 io_queue_async_work(req);
945 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
947 struct io_rings *rings = ctx->rings;
950 tail = ctx->cached_cq_tail;
952 * writes to the cq entry need to come after reading head; the
953 * control dependency is enough as we're using WRITE_ONCE to
956 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
959 ctx->cached_cq_tail++;
960 return &rings->cqes[tail & ctx->cq_mask];
963 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
965 if (!ctx->eventfd_async)
967 return io_wq_current_is_worker() || in_interrupt();
970 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
972 if (waitqueue_active(&ctx->wait))
974 if (waitqueue_active(&ctx->sqo_wait))
975 wake_up(&ctx->sqo_wait);
976 if (ctx->cq_ev_fd && io_should_trigger_evfd(ctx))
977 eventfd_signal(ctx->cq_ev_fd, 1);
980 /* Returns true if there are no backlogged entries after the flush */
981 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
983 struct io_rings *rings = ctx->rings;
984 struct io_uring_cqe *cqe;
985 struct io_kiocb *req;
990 if (list_empty_careful(&ctx->cq_overflow_list))
992 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
993 rings->cq_ring_entries))
997 spin_lock_irqsave(&ctx->completion_lock, flags);
999 /* if force is set, the ring is going away. always drop after that */
1001 ctx->cq_overflow_flushed = 1;
1004 while (!list_empty(&ctx->cq_overflow_list)) {
1005 cqe = io_get_cqring(ctx);
1009 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1011 list_move(&req->list, &list);
1013 WRITE_ONCE(cqe->user_data, req->user_data);
1014 WRITE_ONCE(cqe->res, req->result);
1015 WRITE_ONCE(cqe->flags, 0);
1017 WRITE_ONCE(ctx->rings->cq_overflow,
1018 atomic_inc_return(&ctx->cached_cq_overflow));
1022 io_commit_cqring(ctx);
1024 clear_bit(0, &ctx->sq_check_overflow);
1025 clear_bit(0, &ctx->cq_check_overflow);
1027 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1028 io_cqring_ev_posted(ctx);
1030 while (!list_empty(&list)) {
1031 req = list_first_entry(&list, struct io_kiocb, list);
1032 list_del(&req->list);
1039 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1041 struct io_ring_ctx *ctx = req->ctx;
1042 struct io_uring_cqe *cqe;
1044 trace_io_uring_complete(ctx, req->user_data, res);
1047 * If we can't get a cq entry, userspace overflowed the
1048 * submission (by quite a lot). Increment the overflow count in
1051 cqe = io_get_cqring(ctx);
1053 WRITE_ONCE(cqe->user_data, req->user_data);
1054 WRITE_ONCE(cqe->res, res);
1055 WRITE_ONCE(cqe->flags, 0);
1056 } else if (ctx->cq_overflow_flushed) {
1057 WRITE_ONCE(ctx->rings->cq_overflow,
1058 atomic_inc_return(&ctx->cached_cq_overflow));
1060 if (list_empty(&ctx->cq_overflow_list)) {
1061 set_bit(0, &ctx->sq_check_overflow);
1062 set_bit(0, &ctx->cq_check_overflow);
1064 refcount_inc(&req->refs);
1066 list_add_tail(&req->list, &ctx->cq_overflow_list);
1070 static void io_cqring_add_event(struct io_kiocb *req, long res)
1072 struct io_ring_ctx *ctx = req->ctx;
1073 unsigned long flags;
1075 spin_lock_irqsave(&ctx->completion_lock, flags);
1076 io_cqring_fill_event(req, res);
1077 io_commit_cqring(ctx);
1078 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1080 io_cqring_ev_posted(ctx);
1083 static inline bool io_is_fallback_req(struct io_kiocb *req)
1085 return req == (struct io_kiocb *)
1086 ((unsigned long) req->ctx->fallback_req & ~1UL);
1089 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1091 struct io_kiocb *req;
1093 req = ctx->fallback_req;
1094 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1100 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1101 struct io_submit_state *state)
1103 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1104 struct io_kiocb *req;
1107 req = kmem_cache_alloc(req_cachep, gfp);
1110 } else if (!state->free_reqs) {
1114 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1115 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1118 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1119 * retry single alloc to be on the safe side.
1121 if (unlikely(ret <= 0)) {
1122 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1123 if (!state->reqs[0])
1127 state->free_reqs = ret - 1;
1129 req = state->reqs[0];
1131 req = state->reqs[state->cur_req];
1141 /* one is dropped after submission, the other at completion */
1142 refcount_set(&req->refs, 2);
1144 INIT_IO_WORK(&req->work, io_wq_submit_work);
1147 req = io_get_fallback_req(ctx);
1150 percpu_ref_put(&ctx->refs);
1154 static void __io_req_do_free(struct io_kiocb *req)
1156 if (likely(!io_is_fallback_req(req)))
1157 kmem_cache_free(req_cachep, req);
1159 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1162 static void __io_req_aux_free(struct io_kiocb *req)
1164 struct io_ring_ctx *ctx = req->ctx;
1168 if (req->flags & REQ_F_FIXED_FILE)
1169 percpu_ref_put(&ctx->file_data->refs);
1175 static void __io_free_req(struct io_kiocb *req)
1177 __io_req_aux_free(req);
1179 if (req->flags & REQ_F_INFLIGHT) {
1180 struct io_ring_ctx *ctx = req->ctx;
1181 unsigned long flags;
1183 spin_lock_irqsave(&ctx->inflight_lock, flags);
1184 list_del(&req->inflight_entry);
1185 if (waitqueue_active(&ctx->inflight_wait))
1186 wake_up(&ctx->inflight_wait);
1187 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1190 percpu_ref_put(&req->ctx->refs);
1191 __io_req_do_free(req);
1195 void *reqs[IO_IOPOLL_BATCH];
1200 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1202 int fixed_refs = rb->to_free;
1206 if (rb->need_iter) {
1207 int i, inflight = 0;
1208 unsigned long flags;
1211 for (i = 0; i < rb->to_free; i++) {
1212 struct io_kiocb *req = rb->reqs[i];
1214 if (req->flags & REQ_F_FIXED_FILE) {
1218 if (req->flags & REQ_F_INFLIGHT)
1220 __io_req_aux_free(req);
1225 spin_lock_irqsave(&ctx->inflight_lock, flags);
1226 for (i = 0; i < rb->to_free; i++) {
1227 struct io_kiocb *req = rb->reqs[i];
1229 if (req->flags & REQ_F_INFLIGHT) {
1230 list_del(&req->inflight_entry);
1235 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1237 if (waitqueue_active(&ctx->inflight_wait))
1238 wake_up(&ctx->inflight_wait);
1241 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1243 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1244 percpu_ref_put_many(&ctx->refs, rb->to_free);
1245 rb->to_free = rb->need_iter = 0;
1248 static bool io_link_cancel_timeout(struct io_kiocb *req)
1250 struct io_ring_ctx *ctx = req->ctx;
1253 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1255 io_cqring_fill_event(req, -ECANCELED);
1256 io_commit_cqring(ctx);
1257 req->flags &= ~REQ_F_LINK;
1265 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1267 struct io_ring_ctx *ctx = req->ctx;
1268 bool wake_ev = false;
1270 /* Already got next link */
1271 if (req->flags & REQ_F_LINK_NEXT)
1275 * The list should never be empty when we are called here. But could
1276 * potentially happen if the chain is messed up, check to be on the
1279 while (!list_empty(&req->link_list)) {
1280 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1281 struct io_kiocb, link_list);
1283 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1284 (nxt->flags & REQ_F_TIMEOUT))) {
1285 list_del_init(&nxt->link_list);
1286 wake_ev |= io_link_cancel_timeout(nxt);
1287 req->flags &= ~REQ_F_LINK_TIMEOUT;
1291 list_del_init(&req->link_list);
1292 if (!list_empty(&nxt->link_list))
1293 nxt->flags |= REQ_F_LINK;
1298 req->flags |= REQ_F_LINK_NEXT;
1300 io_cqring_ev_posted(ctx);
1304 * Called if REQ_F_LINK is set, and we fail the head request
1306 static void io_fail_links(struct io_kiocb *req)
1308 struct io_ring_ctx *ctx = req->ctx;
1309 unsigned long flags;
1311 spin_lock_irqsave(&ctx->completion_lock, flags);
1313 while (!list_empty(&req->link_list)) {
1314 struct io_kiocb *link = list_first_entry(&req->link_list,
1315 struct io_kiocb, link_list);
1317 list_del_init(&link->link_list);
1318 trace_io_uring_fail_link(req, link);
1320 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1321 link->opcode == IORING_OP_LINK_TIMEOUT) {
1322 io_link_cancel_timeout(link);
1324 io_cqring_fill_event(link, -ECANCELED);
1325 __io_double_put_req(link);
1327 req->flags &= ~REQ_F_LINK_TIMEOUT;
1330 io_commit_cqring(ctx);
1331 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1332 io_cqring_ev_posted(ctx);
1335 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1337 if (likely(!(req->flags & REQ_F_LINK)))
1341 * If LINK is set, we have dependent requests in this chain. If we
1342 * didn't fail this request, queue the first one up, moving any other
1343 * dependencies to the next request. In case of failure, fail the rest
1346 if (req->flags & REQ_F_FAIL_LINK) {
1348 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1349 REQ_F_LINK_TIMEOUT) {
1350 struct io_ring_ctx *ctx = req->ctx;
1351 unsigned long flags;
1354 * If this is a timeout link, we could be racing with the
1355 * timeout timer. Grab the completion lock for this case to
1356 * protect against that.
1358 spin_lock_irqsave(&ctx->completion_lock, flags);
1359 io_req_link_next(req, nxt);
1360 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1362 io_req_link_next(req, nxt);
1366 static void io_free_req(struct io_kiocb *req)
1368 struct io_kiocb *nxt = NULL;
1370 io_req_find_next(req, &nxt);
1374 io_queue_async_work(nxt);
1378 * Drop reference to request, return next in chain (if there is one) if this
1379 * was the last reference to this request.
1381 __attribute__((nonnull))
1382 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1384 io_req_find_next(req, nxtptr);
1386 if (refcount_dec_and_test(&req->refs))
1390 static void io_put_req(struct io_kiocb *req)
1392 if (refcount_dec_and_test(&req->refs))
1397 * Must only be used if we don't need to care about links, usually from
1398 * within the completion handling itself.
1400 static void __io_double_put_req(struct io_kiocb *req)
1402 /* drop both submit and complete references */
1403 if (refcount_sub_and_test(2, &req->refs))
1407 static void io_double_put_req(struct io_kiocb *req)
1409 /* drop both submit and complete references */
1410 if (refcount_sub_and_test(2, &req->refs))
1414 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1416 struct io_rings *rings = ctx->rings;
1418 if (test_bit(0, &ctx->cq_check_overflow)) {
1420 * noflush == true is from the waitqueue handler, just ensure
1421 * we wake up the task, and the next invocation will flush the
1422 * entries. We cannot safely to it from here.
1424 if (noflush && !list_empty(&ctx->cq_overflow_list))
1427 io_cqring_overflow_flush(ctx, false);
1430 /* See comment at the top of this file */
1432 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1435 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1437 struct io_rings *rings = ctx->rings;
1439 /* make sure SQ entry isn't read before tail */
1440 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1443 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1445 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1448 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1451 rb->reqs[rb->to_free++] = req;
1452 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1453 io_free_req_many(req->ctx, rb);
1458 * Find and free completed poll iocbs
1460 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1461 struct list_head *done)
1463 struct req_batch rb;
1464 struct io_kiocb *req;
1466 rb.to_free = rb.need_iter = 0;
1467 while (!list_empty(done)) {
1468 req = list_first_entry(done, struct io_kiocb, list);
1469 list_del(&req->list);
1471 io_cqring_fill_event(req, req->result);
1474 if (refcount_dec_and_test(&req->refs) &&
1475 !io_req_multi_free(&rb, req))
1479 io_commit_cqring(ctx);
1480 io_free_req_many(ctx, &rb);
1483 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1486 struct io_kiocb *req, *tmp;
1492 * Only spin for completions if we don't have multiple devices hanging
1493 * off our complete list, and we're under the requested amount.
1495 spin = !ctx->poll_multi_file && *nr_events < min;
1498 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1499 struct kiocb *kiocb = &req->rw.kiocb;
1502 * Move completed entries to our local list. If we find a
1503 * request that requires polling, break out and complete
1504 * the done list first, if we have entries there.
1506 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1507 list_move_tail(&req->list, &done);
1510 if (!list_empty(&done))
1513 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1522 if (!list_empty(&done))
1523 io_iopoll_complete(ctx, nr_events, &done);
1529 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1530 * non-spinning poll check - we'll still enter the driver poll loop, but only
1531 * as a non-spinning completion check.
1533 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1536 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1539 ret = io_do_iopoll(ctx, nr_events, min);
1542 if (!min || *nr_events >= min)
1550 * We can't just wait for polled events to come to us, we have to actively
1551 * find and complete them.
1553 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1555 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1558 mutex_lock(&ctx->uring_lock);
1559 while (!list_empty(&ctx->poll_list)) {
1560 unsigned int nr_events = 0;
1562 io_iopoll_getevents(ctx, &nr_events, 1);
1565 * Ensure we allow local-to-the-cpu processing to take place,
1566 * in this case we need to ensure that we reap all events.
1570 mutex_unlock(&ctx->uring_lock);
1573 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1576 int iters = 0, ret = 0;
1582 * Don't enter poll loop if we already have events pending.
1583 * If we do, we can potentially be spinning for commands that
1584 * already triggered a CQE (eg in error).
1586 if (io_cqring_events(ctx, false))
1590 * If a submit got punted to a workqueue, we can have the
1591 * application entering polling for a command before it gets
1592 * issued. That app will hold the uring_lock for the duration
1593 * of the poll right here, so we need to take a breather every
1594 * now and then to ensure that the issue has a chance to add
1595 * the poll to the issued list. Otherwise we can spin here
1596 * forever, while the workqueue is stuck trying to acquire the
1599 if (!(++iters & 7)) {
1600 mutex_unlock(&ctx->uring_lock);
1601 mutex_lock(&ctx->uring_lock);
1604 if (*nr_events < min)
1605 tmin = min - *nr_events;
1607 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1611 } while (min && !*nr_events && !need_resched());
1616 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1622 * We disallow the app entering submit/complete with polling, but we
1623 * still need to lock the ring to prevent racing with polled issue
1624 * that got punted to a workqueue.
1626 mutex_lock(&ctx->uring_lock);
1627 ret = __io_iopoll_check(ctx, nr_events, min);
1628 mutex_unlock(&ctx->uring_lock);
1632 static void kiocb_end_write(struct io_kiocb *req)
1635 * Tell lockdep we inherited freeze protection from submission
1638 if (req->flags & REQ_F_ISREG) {
1639 struct inode *inode = file_inode(req->file);
1641 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1643 file_end_write(req->file);
1646 static inline void req_set_fail_links(struct io_kiocb *req)
1648 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1649 req->flags |= REQ_F_FAIL_LINK;
1652 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1654 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1656 if (kiocb->ki_flags & IOCB_WRITE)
1657 kiocb_end_write(req);
1659 if (res != req->result)
1660 req_set_fail_links(req);
1661 io_cqring_add_event(req, res);
1664 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1666 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1668 io_complete_rw_common(kiocb, res);
1672 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1674 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1675 struct io_kiocb *nxt = NULL;
1677 io_complete_rw_common(kiocb, res);
1678 io_put_req_find_next(req, &nxt);
1683 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1685 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1687 if (kiocb->ki_flags & IOCB_WRITE)
1688 kiocb_end_write(req);
1690 if (res != req->result)
1691 req_set_fail_links(req);
1694 req->flags |= REQ_F_IOPOLL_COMPLETED;
1698 * After the iocb has been issued, it's safe to be found on the poll list.
1699 * Adding the kiocb to the list AFTER submission ensures that we don't
1700 * find it from a io_iopoll_getevents() thread before the issuer is done
1701 * accessing the kiocb cookie.
1703 static void io_iopoll_req_issued(struct io_kiocb *req)
1705 struct io_ring_ctx *ctx = req->ctx;
1708 * Track whether we have multiple files in our lists. This will impact
1709 * how we do polling eventually, not spinning if we're on potentially
1710 * different devices.
1712 if (list_empty(&ctx->poll_list)) {
1713 ctx->poll_multi_file = false;
1714 } else if (!ctx->poll_multi_file) {
1715 struct io_kiocb *list_req;
1717 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1719 if (list_req->file != req->file)
1720 ctx->poll_multi_file = true;
1724 * For fast devices, IO may have already completed. If it has, add
1725 * it to the front so we find it first.
1727 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1728 list_add(&req->list, &ctx->poll_list);
1730 list_add_tail(&req->list, &ctx->poll_list);
1733 static void io_file_put(struct io_submit_state *state)
1736 int diff = state->has_refs - state->used_refs;
1739 fput_many(state->file, diff);
1745 * Get as many references to a file as we have IOs left in this submission,
1746 * assuming most submissions are for one file, or at least that each file
1747 * has more than one submission.
1749 static struct file *io_file_get(struct io_submit_state *state, int fd)
1755 if (state->fd == fd) {
1762 state->file = fget_many(fd, state->ios_left);
1767 state->has_refs = state->ios_left;
1768 state->used_refs = 1;
1774 * If we tracked the file through the SCM inflight mechanism, we could support
1775 * any file. For now, just ensure that anything potentially problematic is done
1778 static bool io_file_supports_async(struct file *file)
1780 umode_t mode = file_inode(file)->i_mode;
1782 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1784 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1790 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1791 bool force_nonblock)
1793 struct io_ring_ctx *ctx = req->ctx;
1794 struct kiocb *kiocb = &req->rw.kiocb;
1801 if (S_ISREG(file_inode(req->file)->i_mode))
1802 req->flags |= REQ_F_ISREG;
1804 kiocb->ki_pos = READ_ONCE(sqe->off);
1805 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1806 req->flags |= REQ_F_CUR_POS;
1807 kiocb->ki_pos = req->file->f_pos;
1809 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1810 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1812 ioprio = READ_ONCE(sqe->ioprio);
1814 ret = ioprio_check_cap(ioprio);
1818 kiocb->ki_ioprio = ioprio;
1820 kiocb->ki_ioprio = get_current_ioprio();
1822 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1826 /* don't allow async punt if RWF_NOWAIT was requested */
1827 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1828 (req->file->f_flags & O_NONBLOCK))
1829 req->flags |= REQ_F_NOWAIT;
1832 kiocb->ki_flags |= IOCB_NOWAIT;
1834 if (ctx->flags & IORING_SETUP_IOPOLL) {
1835 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1836 !kiocb->ki_filp->f_op->iopoll)
1839 kiocb->ki_flags |= IOCB_HIPRI;
1840 kiocb->ki_complete = io_complete_rw_iopoll;
1843 if (kiocb->ki_flags & IOCB_HIPRI)
1845 kiocb->ki_complete = io_complete_rw;
1848 req->rw.addr = READ_ONCE(sqe->addr);
1849 req->rw.len = READ_ONCE(sqe->len);
1850 /* we own ->private, reuse it for the buffer index */
1851 req->rw.kiocb.private = (void *) (unsigned long)
1852 READ_ONCE(sqe->buf_index);
1856 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1862 case -ERESTARTNOINTR:
1863 case -ERESTARTNOHAND:
1864 case -ERESTART_RESTARTBLOCK:
1866 * We can't just restart the syscall, since previously
1867 * submitted sqes may already be in progress. Just fail this
1873 kiocb->ki_complete(kiocb, ret, 0);
1877 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1880 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1882 if (req->flags & REQ_F_CUR_POS)
1883 req->file->f_pos = kiocb->ki_pos;
1884 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1885 *nxt = __io_complete_rw(kiocb, ret);
1887 io_rw_done(kiocb, ret);
1890 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1891 struct iov_iter *iter)
1893 struct io_ring_ctx *ctx = req->ctx;
1894 size_t len = req->rw.len;
1895 struct io_mapped_ubuf *imu;
1896 unsigned index, buf_index;
1900 /* attempt to use fixed buffers without having provided iovecs */
1901 if (unlikely(!ctx->user_bufs))
1904 buf_index = (unsigned long) req->rw.kiocb.private;
1905 if (unlikely(buf_index >= ctx->nr_user_bufs))
1908 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1909 imu = &ctx->user_bufs[index];
1910 buf_addr = req->rw.addr;
1913 if (buf_addr + len < buf_addr)
1915 /* not inside the mapped region */
1916 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1920 * May not be a start of buffer, set size appropriately
1921 * and advance us to the beginning.
1923 offset = buf_addr - imu->ubuf;
1924 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1928 * Don't use iov_iter_advance() here, as it's really slow for
1929 * using the latter parts of a big fixed buffer - it iterates
1930 * over each segment manually. We can cheat a bit here, because
1933 * 1) it's a BVEC iter, we set it up
1934 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1935 * first and last bvec
1937 * So just find our index, and adjust the iterator afterwards.
1938 * If the offset is within the first bvec (or the whole first
1939 * bvec, just use iov_iter_advance(). This makes it easier
1940 * since we can just skip the first segment, which may not
1941 * be PAGE_SIZE aligned.
1943 const struct bio_vec *bvec = imu->bvec;
1945 if (offset <= bvec->bv_len) {
1946 iov_iter_advance(iter, offset);
1948 unsigned long seg_skip;
1950 /* skip first vec */
1951 offset -= bvec->bv_len;
1952 seg_skip = 1 + (offset >> PAGE_SHIFT);
1954 iter->bvec = bvec + seg_skip;
1955 iter->nr_segs -= seg_skip;
1956 iter->count -= bvec->bv_len + offset;
1957 iter->iov_offset = offset & ~PAGE_MASK;
1964 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1965 struct iovec **iovec, struct iov_iter *iter)
1967 void __user *buf = u64_to_user_ptr(req->rw.addr);
1968 size_t sqe_len = req->rw.len;
1971 opcode = req->opcode;
1972 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1974 return io_import_fixed(req, rw, iter);
1977 /* buffer index only valid with fixed read/write */
1978 if (req->rw.kiocb.private)
1981 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
1983 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
1989 struct io_async_rw *iorw = &req->io->rw;
1992 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
1993 if (iorw->iov == iorw->fast_iov)
2001 #ifdef CONFIG_COMPAT
2002 if (req->ctx->compat)
2003 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2007 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2011 * For files that don't have ->read_iter() and ->write_iter(), handle them
2012 * by looping over ->read() or ->write() manually.
2014 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2015 struct iov_iter *iter)
2020 * Don't support polled IO through this interface, and we can't
2021 * support non-blocking either. For the latter, this just causes
2022 * the kiocb to be handled from an async context.
2024 if (kiocb->ki_flags & IOCB_HIPRI)
2026 if (kiocb->ki_flags & IOCB_NOWAIT)
2029 while (iov_iter_count(iter)) {
2033 if (!iov_iter_is_bvec(iter)) {
2034 iovec = iov_iter_iovec(iter);
2036 /* fixed buffers import bvec */
2037 iovec.iov_base = kmap(iter->bvec->bv_page)
2039 iovec.iov_len = min(iter->count,
2040 iter->bvec->bv_len - iter->iov_offset);
2044 nr = file->f_op->read(file, iovec.iov_base,
2045 iovec.iov_len, &kiocb->ki_pos);
2047 nr = file->f_op->write(file, iovec.iov_base,
2048 iovec.iov_len, &kiocb->ki_pos);
2051 if (iov_iter_is_bvec(iter))
2052 kunmap(iter->bvec->bv_page);
2060 if (nr != iovec.iov_len)
2062 iov_iter_advance(iter, nr);
2068 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2069 struct iovec *iovec, struct iovec *fast_iov,
2070 struct iov_iter *iter)
2072 req->io->rw.nr_segs = iter->nr_segs;
2073 req->io->rw.size = io_size;
2074 req->io->rw.iov = iovec;
2075 if (!req->io->rw.iov) {
2076 req->io->rw.iov = req->io->rw.fast_iov;
2077 memcpy(req->io->rw.iov, fast_iov,
2078 sizeof(struct iovec) * iter->nr_segs);
2082 static int io_alloc_async_ctx(struct io_kiocb *req)
2084 if (!io_op_defs[req->opcode].async_ctx)
2086 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2087 return req->io == NULL;
2090 static void io_rw_async(struct io_wq_work **workptr)
2092 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2093 struct iovec *iov = NULL;
2095 if (req->io->rw.iov != req->io->rw.fast_iov)
2096 iov = req->io->rw.iov;
2097 io_wq_submit_work(workptr);
2101 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2102 struct iovec *iovec, struct iovec *fast_iov,
2103 struct iov_iter *iter)
2105 if (req->opcode == IORING_OP_READ_FIXED ||
2106 req->opcode == IORING_OP_WRITE_FIXED)
2108 if (!req->io && io_alloc_async_ctx(req))
2111 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2112 req->work.func = io_rw_async;
2116 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2117 bool force_nonblock)
2119 struct io_async_ctx *io;
2120 struct iov_iter iter;
2123 ret = io_prep_rw(req, sqe, force_nonblock);
2127 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2134 io->rw.iov = io->rw.fast_iov;
2136 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2141 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2145 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2146 bool force_nonblock)
2148 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2149 struct kiocb *kiocb = &req->rw.kiocb;
2150 struct iov_iter iter;
2152 ssize_t io_size, ret;
2154 ret = io_import_iovec(READ, req, &iovec, &iter);
2158 /* Ensure we clear previously set non-block flag */
2159 if (!force_nonblock)
2160 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2164 if (req->flags & REQ_F_LINK)
2165 req->result = io_size;
2168 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2169 * we know to async punt it even if it was opened O_NONBLOCK
2171 if (force_nonblock && !io_file_supports_async(req->file)) {
2172 req->flags |= REQ_F_MUST_PUNT;
2176 iov_count = iov_iter_count(&iter);
2177 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2181 if (req->file->f_op->read_iter)
2182 ret2 = call_read_iter(req->file, kiocb, &iter);
2184 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2186 /* Catch -EAGAIN return for forced non-blocking submission */
2187 if (!force_nonblock || ret2 != -EAGAIN) {
2188 kiocb_done(kiocb, ret2, nxt, req->in_async);
2191 ret = io_setup_async_rw(req, io_size, iovec,
2192 inline_vecs, &iter);
2199 if (!io_wq_current_is_worker())
2204 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2205 bool force_nonblock)
2207 struct io_async_ctx *io;
2208 struct iov_iter iter;
2211 ret = io_prep_rw(req, sqe, force_nonblock);
2215 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2222 io->rw.iov = io->rw.fast_iov;
2224 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2229 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2233 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2234 bool force_nonblock)
2236 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2237 struct kiocb *kiocb = &req->rw.kiocb;
2238 struct iov_iter iter;
2240 ssize_t ret, io_size;
2242 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2246 /* Ensure we clear previously set non-block flag */
2247 if (!force_nonblock)
2248 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2252 if (req->flags & REQ_F_LINK)
2253 req->result = io_size;
2256 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2257 * we know to async punt it even if it was opened O_NONBLOCK
2259 if (force_nonblock && !io_file_supports_async(req->file)) {
2260 req->flags |= REQ_F_MUST_PUNT;
2264 /* file path doesn't support NOWAIT for non-direct_IO */
2265 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2266 (req->flags & REQ_F_ISREG))
2269 iov_count = iov_iter_count(&iter);
2270 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2275 * Open-code file_start_write here to grab freeze protection,
2276 * which will be released by another thread in
2277 * io_complete_rw(). Fool lockdep by telling it the lock got
2278 * released so that it doesn't complain about the held lock when
2279 * we return to userspace.
2281 if (req->flags & REQ_F_ISREG) {
2282 __sb_start_write(file_inode(req->file)->i_sb,
2283 SB_FREEZE_WRITE, true);
2284 __sb_writers_release(file_inode(req->file)->i_sb,
2287 kiocb->ki_flags |= IOCB_WRITE;
2289 if (req->file->f_op->write_iter)
2290 ret2 = call_write_iter(req->file, kiocb, &iter);
2292 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2293 if (!force_nonblock || ret2 != -EAGAIN) {
2294 kiocb_done(kiocb, ret2, nxt, req->in_async);
2297 ret = io_setup_async_rw(req, io_size, iovec,
2298 inline_vecs, &iter);
2305 if (!io_wq_current_is_worker())
2311 * IORING_OP_NOP just posts a completion event, nothing else.
2313 static int io_nop(struct io_kiocb *req)
2315 struct io_ring_ctx *ctx = req->ctx;
2317 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2320 io_cqring_add_event(req, 0);
2325 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2327 struct io_ring_ctx *ctx = req->ctx;
2332 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2334 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2337 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2338 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2341 req->sync.off = READ_ONCE(sqe->off);
2342 req->sync.len = READ_ONCE(sqe->len);
2346 static bool io_req_cancelled(struct io_kiocb *req)
2348 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2349 req_set_fail_links(req);
2350 io_cqring_add_event(req, -ECANCELED);
2358 static void io_link_work_cb(struct io_wq_work **workptr)
2360 struct io_wq_work *work = *workptr;
2361 struct io_kiocb *link = work->data;
2363 io_queue_linked_timeout(link);
2364 work->func = io_wq_submit_work;
2367 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2369 struct io_kiocb *link;
2371 io_prep_async_work(nxt, &link);
2372 *workptr = &nxt->work;
2374 nxt->work.flags |= IO_WQ_WORK_CB;
2375 nxt->work.func = io_link_work_cb;
2376 nxt->work.data = link;
2380 static void io_fsync_finish(struct io_wq_work **workptr)
2382 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2383 loff_t end = req->sync.off + req->sync.len;
2384 struct io_kiocb *nxt = NULL;
2387 if (io_req_cancelled(req))
2390 ret = vfs_fsync_range(req->file, req->sync.off,
2391 end > 0 ? end : LLONG_MAX,
2392 req->sync.flags & IORING_FSYNC_DATASYNC);
2394 req_set_fail_links(req);
2395 io_cqring_add_event(req, ret);
2396 io_put_req_find_next(req, &nxt);
2398 io_wq_assign_next(workptr, nxt);
2401 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2402 bool force_nonblock)
2404 struct io_wq_work *work, *old_work;
2406 /* fsync always requires a blocking context */
2407 if (force_nonblock) {
2409 req->work.func = io_fsync_finish;
2413 work = old_work = &req->work;
2414 io_fsync_finish(&work);
2415 if (work && work != old_work)
2416 *nxt = container_of(work, struct io_kiocb, work);
2420 static void io_fallocate_finish(struct io_wq_work **workptr)
2422 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2423 struct io_kiocb *nxt = NULL;
2426 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2429 req_set_fail_links(req);
2430 io_cqring_add_event(req, ret);
2431 io_put_req_find_next(req, &nxt);
2433 io_wq_assign_next(workptr, nxt);
2436 static int io_fallocate_prep(struct io_kiocb *req,
2437 const struct io_uring_sqe *sqe)
2439 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2442 req->sync.off = READ_ONCE(sqe->off);
2443 req->sync.len = READ_ONCE(sqe->addr);
2444 req->sync.mode = READ_ONCE(sqe->len);
2448 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2449 bool force_nonblock)
2451 struct io_wq_work *work, *old_work;
2453 /* fallocate always requiring blocking context */
2454 if (force_nonblock) {
2456 req->work.func = io_fallocate_finish;
2460 work = old_work = &req->work;
2461 io_fallocate_finish(&work);
2462 if (work && work != old_work)
2463 *nxt = container_of(work, struct io_kiocb, work);
2468 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2470 const char __user *fname;
2473 if (sqe->ioprio || sqe->buf_index)
2476 req->open.dfd = READ_ONCE(sqe->fd);
2477 req->open.how.mode = READ_ONCE(sqe->len);
2478 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2479 req->open.how.flags = READ_ONCE(sqe->open_flags);
2481 req->open.filename = getname(fname);
2482 if (IS_ERR(req->open.filename)) {
2483 ret = PTR_ERR(req->open.filename);
2484 req->open.filename = NULL;
2491 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2493 struct open_how __user *how;
2494 const char __user *fname;
2498 if (sqe->ioprio || sqe->buf_index)
2501 req->open.dfd = READ_ONCE(sqe->fd);
2502 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2503 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2504 len = READ_ONCE(sqe->len);
2506 if (len < OPEN_HOW_SIZE_VER0)
2509 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2514 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2515 req->open.how.flags |= O_LARGEFILE;
2517 req->open.filename = getname(fname);
2518 if (IS_ERR(req->open.filename)) {
2519 ret = PTR_ERR(req->open.filename);
2520 req->open.filename = NULL;
2527 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2528 bool force_nonblock)
2530 struct open_flags op;
2534 if (force_nonblock) {
2535 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2539 ret = build_open_flags(&req->open.how, &op);
2543 ret = get_unused_fd_flags(req->open.how.flags);
2547 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2550 ret = PTR_ERR(file);
2552 fsnotify_open(file);
2553 fd_install(ret, file);
2556 putname(req->open.filename);
2558 req_set_fail_links(req);
2559 io_cqring_add_event(req, ret);
2560 io_put_req_find_next(req, nxt);
2564 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2565 bool force_nonblock)
2567 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2568 return io_openat2(req, nxt, force_nonblock);
2571 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2573 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2574 if (sqe->ioprio || sqe->buf_index || sqe->off)
2577 req->madvise.addr = READ_ONCE(sqe->addr);
2578 req->madvise.len = READ_ONCE(sqe->len);
2579 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2586 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2587 bool force_nonblock)
2589 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2590 struct io_madvise *ma = &req->madvise;
2596 ret = do_madvise(ma->addr, ma->len, ma->advice);
2598 req_set_fail_links(req);
2599 io_cqring_add_event(req, ret);
2600 io_put_req_find_next(req, nxt);
2607 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2609 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2612 req->fadvise.offset = READ_ONCE(sqe->off);
2613 req->fadvise.len = READ_ONCE(sqe->len);
2614 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2618 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2619 bool force_nonblock)
2621 struct io_fadvise *fa = &req->fadvise;
2624 /* DONTNEED may block, others _should_ not */
2625 if (fa->advice == POSIX_FADV_DONTNEED && force_nonblock)
2628 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2630 req_set_fail_links(req);
2631 io_cqring_add_event(req, ret);
2632 io_put_req_find_next(req, nxt);
2636 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2638 const char __user *fname;
2639 unsigned lookup_flags;
2642 if (sqe->ioprio || sqe->buf_index)
2645 req->open.dfd = READ_ONCE(sqe->fd);
2646 req->open.mask = READ_ONCE(sqe->len);
2647 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2648 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2649 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2651 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2654 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2655 if (IS_ERR(req->open.filename)) {
2656 ret = PTR_ERR(req->open.filename);
2657 req->open.filename = NULL;
2664 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2665 bool force_nonblock)
2667 struct io_open *ctx = &req->open;
2668 unsigned lookup_flags;
2676 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2680 /* filename_lookup() drops it, keep a reference */
2681 ctx->filename->refcnt++;
2683 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2688 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2690 if (retry_estale(ret, lookup_flags)) {
2691 lookup_flags |= LOOKUP_REVAL;
2695 ret = cp_statx(&stat, ctx->buffer);
2697 putname(ctx->filename);
2699 req_set_fail_links(req);
2700 io_cqring_add_event(req, ret);
2701 io_put_req_find_next(req, nxt);
2705 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2708 * If we queue this for async, it must not be cancellable. That would
2709 * leave the 'file' in an undeterminate state.
2711 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2713 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2714 sqe->rw_flags || sqe->buf_index)
2716 if (sqe->flags & IOSQE_FIXED_FILE)
2719 req->close.fd = READ_ONCE(sqe->fd);
2720 if (req->file->f_op == &io_uring_fops ||
2721 req->close.fd == req->ctx->ring_fd)
2727 static void io_close_finish(struct io_wq_work **workptr)
2729 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2730 struct io_kiocb *nxt = NULL;
2732 /* Invoked with files, we need to do the close */
2733 if (req->work.files) {
2736 ret = filp_close(req->close.put_file, req->work.files);
2738 req_set_fail_links(req);
2740 io_cqring_add_event(req, ret);
2743 fput(req->close.put_file);
2745 /* we bypassed the re-issue, drop the submission reference */
2747 io_put_req_find_next(req, &nxt);
2749 io_wq_assign_next(workptr, nxt);
2752 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2753 bool force_nonblock)
2757 req->close.put_file = NULL;
2758 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2762 /* if the file has a flush method, be safe and punt to async */
2763 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker()) {
2764 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2769 * No ->flush(), safely close from here and just punt the
2770 * fput() to async context.
2772 ret = filp_close(req->close.put_file, current->files);
2775 req_set_fail_links(req);
2776 io_cqring_add_event(req, ret);
2778 if (io_wq_current_is_worker()) {
2779 struct io_wq_work *old_work, *work;
2781 old_work = work = &req->work;
2782 io_close_finish(&work);
2783 if (work && work != old_work)
2784 *nxt = container_of(work, struct io_kiocb, work);
2789 req->work.func = io_close_finish;
2793 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2795 struct io_ring_ctx *ctx = req->ctx;
2800 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2802 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2805 req->sync.off = READ_ONCE(sqe->off);
2806 req->sync.len = READ_ONCE(sqe->len);
2807 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2811 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2813 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2814 struct io_kiocb *nxt = NULL;
2817 if (io_req_cancelled(req))
2820 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2823 req_set_fail_links(req);
2824 io_cqring_add_event(req, ret);
2825 io_put_req_find_next(req, &nxt);
2827 io_wq_assign_next(workptr, nxt);
2830 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2831 bool force_nonblock)
2833 struct io_wq_work *work, *old_work;
2835 /* sync_file_range always requires a blocking context */
2836 if (force_nonblock) {
2838 req->work.func = io_sync_file_range_finish;
2842 work = old_work = &req->work;
2843 io_sync_file_range_finish(&work);
2844 if (work && work != old_work)
2845 *nxt = container_of(work, struct io_kiocb, work);
2849 #if defined(CONFIG_NET)
2850 static void io_sendrecv_async(struct io_wq_work **workptr)
2852 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2853 struct iovec *iov = NULL;
2855 if (req->io->rw.iov != req->io->rw.fast_iov)
2856 iov = req->io->msg.iov;
2857 io_wq_submit_work(workptr);
2862 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2864 #if defined(CONFIG_NET)
2865 struct io_sr_msg *sr = &req->sr_msg;
2866 struct io_async_ctx *io = req->io;
2868 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2869 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2870 sr->len = READ_ONCE(sqe->len);
2872 if (!io || req->opcode == IORING_OP_SEND)
2875 io->msg.iov = io->msg.fast_iov;
2876 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2883 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2884 bool force_nonblock)
2886 #if defined(CONFIG_NET)
2887 struct io_async_msghdr *kmsg = NULL;
2888 struct socket *sock;
2891 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2894 sock = sock_from_file(req->file, &ret);
2896 struct io_async_ctx io;
2897 struct sockaddr_storage addr;
2901 kmsg = &req->io->msg;
2902 kmsg->msg.msg_name = &addr;
2903 /* if iov is set, it's allocated already */
2905 kmsg->iov = kmsg->fast_iov;
2906 kmsg->msg.msg_iter.iov = kmsg->iov;
2908 struct io_sr_msg *sr = &req->sr_msg;
2911 kmsg->msg.msg_name = &addr;
2913 io.msg.iov = io.msg.fast_iov;
2914 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2915 sr->msg_flags, &io.msg.iov);
2920 flags = req->sr_msg.msg_flags;
2921 if (flags & MSG_DONTWAIT)
2922 req->flags |= REQ_F_NOWAIT;
2923 else if (force_nonblock)
2924 flags |= MSG_DONTWAIT;
2926 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2927 if (force_nonblock && ret == -EAGAIN) {
2930 if (io_alloc_async_ctx(req))
2932 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2933 req->work.func = io_sendrecv_async;
2936 if (ret == -ERESTARTSYS)
2940 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2942 io_cqring_add_event(req, ret);
2944 req_set_fail_links(req);
2945 io_put_req_find_next(req, nxt);
2952 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
2953 bool force_nonblock)
2955 #if defined(CONFIG_NET)
2956 struct socket *sock;
2959 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2962 sock = sock_from_file(req->file, &ret);
2964 struct io_sr_msg *sr = &req->sr_msg;
2969 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
2974 msg.msg_name = NULL;
2975 msg.msg_control = NULL;
2976 msg.msg_controllen = 0;
2977 msg.msg_namelen = 0;
2979 flags = req->sr_msg.msg_flags;
2980 if (flags & MSG_DONTWAIT)
2981 req->flags |= REQ_F_NOWAIT;
2982 else if (force_nonblock)
2983 flags |= MSG_DONTWAIT;
2985 ret = __sys_sendmsg_sock(sock, &msg, flags);
2986 if (force_nonblock && ret == -EAGAIN)
2988 if (ret == -ERESTARTSYS)
2992 io_cqring_add_event(req, ret);
2994 req_set_fail_links(req);
2995 io_put_req_find_next(req, nxt);
3002 static int io_recvmsg_prep(struct io_kiocb *req,
3003 const struct io_uring_sqe *sqe)
3005 #if defined(CONFIG_NET)
3006 struct io_sr_msg *sr = &req->sr_msg;
3007 struct io_async_ctx *io = req->io;
3009 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3010 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3012 if (!io || req->opcode == IORING_OP_RECV)
3015 io->msg.iov = io->msg.fast_iov;
3016 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3017 &io->msg.uaddr, &io->msg.iov);
3023 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3024 bool force_nonblock)
3026 #if defined(CONFIG_NET)
3027 struct io_async_msghdr *kmsg = NULL;
3028 struct socket *sock;
3031 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3034 sock = sock_from_file(req->file, &ret);
3036 struct io_async_ctx io;
3037 struct sockaddr_storage addr;
3041 kmsg = &req->io->msg;
3042 kmsg->msg.msg_name = &addr;
3043 /* if iov is set, it's allocated already */
3045 kmsg->iov = kmsg->fast_iov;
3046 kmsg->msg.msg_iter.iov = kmsg->iov;
3048 struct io_sr_msg *sr = &req->sr_msg;
3051 kmsg->msg.msg_name = &addr;
3053 io.msg.iov = io.msg.fast_iov;
3054 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3055 sr->msg_flags, &io.msg.uaddr,
3061 flags = req->sr_msg.msg_flags;
3062 if (flags & MSG_DONTWAIT)
3063 req->flags |= REQ_F_NOWAIT;
3064 else if (force_nonblock)
3065 flags |= MSG_DONTWAIT;
3067 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3068 kmsg->uaddr, flags);
3069 if (force_nonblock && ret == -EAGAIN) {
3072 if (io_alloc_async_ctx(req))
3074 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3075 req->work.func = io_sendrecv_async;
3078 if (ret == -ERESTARTSYS)
3082 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
3084 io_cqring_add_event(req, ret);
3086 req_set_fail_links(req);
3087 io_put_req_find_next(req, nxt);
3094 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3095 bool force_nonblock)
3097 #if defined(CONFIG_NET)
3098 struct socket *sock;
3101 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3104 sock = sock_from_file(req->file, &ret);
3106 struct io_sr_msg *sr = &req->sr_msg;
3111 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3116 msg.msg_name = NULL;
3117 msg.msg_control = NULL;
3118 msg.msg_controllen = 0;
3119 msg.msg_namelen = 0;
3120 msg.msg_iocb = NULL;
3123 flags = req->sr_msg.msg_flags;
3124 if (flags & MSG_DONTWAIT)
3125 req->flags |= REQ_F_NOWAIT;
3126 else if (force_nonblock)
3127 flags |= MSG_DONTWAIT;
3129 ret = __sys_recvmsg_sock(sock, &msg, NULL, NULL, flags);
3130 if (force_nonblock && ret == -EAGAIN)
3132 if (ret == -ERESTARTSYS)
3136 io_cqring_add_event(req, ret);
3138 req_set_fail_links(req);
3139 io_put_req_find_next(req, nxt);
3147 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3149 #if defined(CONFIG_NET)
3150 struct io_accept *accept = &req->accept;
3152 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3154 if (sqe->ioprio || sqe->len || sqe->buf_index)
3157 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3158 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3159 accept->flags = READ_ONCE(sqe->accept_flags);
3166 #if defined(CONFIG_NET)
3167 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3168 bool force_nonblock)
3170 struct io_accept *accept = &req->accept;
3171 unsigned file_flags;
3174 file_flags = force_nonblock ? O_NONBLOCK : 0;
3175 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3176 accept->addr_len, accept->flags);
3177 if (ret == -EAGAIN && force_nonblock)
3179 if (ret == -ERESTARTSYS)
3182 req_set_fail_links(req);
3183 io_cqring_add_event(req, ret);
3184 io_put_req_find_next(req, nxt);
3188 static void io_accept_finish(struct io_wq_work **workptr)
3190 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3191 struct io_kiocb *nxt = NULL;
3193 if (io_req_cancelled(req))
3195 __io_accept(req, &nxt, false);
3197 io_wq_assign_next(workptr, nxt);
3201 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3202 bool force_nonblock)
3204 #if defined(CONFIG_NET)
3207 ret = __io_accept(req, nxt, force_nonblock);
3208 if (ret == -EAGAIN && force_nonblock) {
3209 req->work.func = io_accept_finish;
3210 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3220 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3222 #if defined(CONFIG_NET)
3223 struct io_connect *conn = &req->connect;
3224 struct io_async_ctx *io = req->io;
3226 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3228 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3231 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3232 conn->addr_len = READ_ONCE(sqe->addr2);
3237 return move_addr_to_kernel(conn->addr, conn->addr_len,
3238 &io->connect.address);
3244 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3245 bool force_nonblock)
3247 #if defined(CONFIG_NET)
3248 struct io_async_ctx __io, *io;
3249 unsigned file_flags;
3255 ret = move_addr_to_kernel(req->connect.addr,
3256 req->connect.addr_len,
3257 &__io.connect.address);
3263 file_flags = force_nonblock ? O_NONBLOCK : 0;
3265 ret = __sys_connect_file(req->file, &io->connect.address,
3266 req->connect.addr_len, file_flags);
3267 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3270 if (io_alloc_async_ctx(req)) {
3274 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3277 if (ret == -ERESTARTSYS)
3281 req_set_fail_links(req);
3282 io_cqring_add_event(req, ret);
3283 io_put_req_find_next(req, nxt);
3290 static void io_poll_remove_one(struct io_kiocb *req)
3292 struct io_poll_iocb *poll = &req->poll;
3294 spin_lock(&poll->head->lock);
3295 WRITE_ONCE(poll->canceled, true);
3296 if (!list_empty(&poll->wait.entry)) {
3297 list_del_init(&poll->wait.entry);
3298 io_queue_async_work(req);
3300 spin_unlock(&poll->head->lock);
3301 hash_del(&req->hash_node);
3304 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3306 struct hlist_node *tmp;
3307 struct io_kiocb *req;
3310 spin_lock_irq(&ctx->completion_lock);
3311 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3312 struct hlist_head *list;
3314 list = &ctx->cancel_hash[i];
3315 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3316 io_poll_remove_one(req);
3318 spin_unlock_irq(&ctx->completion_lock);
3321 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3323 struct hlist_head *list;
3324 struct io_kiocb *req;
3326 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3327 hlist_for_each_entry(req, list, hash_node) {
3328 if (sqe_addr == req->user_data) {
3329 io_poll_remove_one(req);
3337 static int io_poll_remove_prep(struct io_kiocb *req,
3338 const struct io_uring_sqe *sqe)
3340 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3342 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3346 req->poll.addr = READ_ONCE(sqe->addr);
3351 * Find a running poll command that matches one specified in sqe->addr,
3352 * and remove it if found.
3354 static int io_poll_remove(struct io_kiocb *req)
3356 struct io_ring_ctx *ctx = req->ctx;
3360 addr = req->poll.addr;
3361 spin_lock_irq(&ctx->completion_lock);
3362 ret = io_poll_cancel(ctx, addr);
3363 spin_unlock_irq(&ctx->completion_lock);
3365 io_cqring_add_event(req, ret);
3367 req_set_fail_links(req);
3372 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3374 struct io_ring_ctx *ctx = req->ctx;
3376 req->poll.done = true;
3378 io_cqring_fill_event(req, error);
3380 io_cqring_fill_event(req, mangle_poll(mask));
3381 io_commit_cqring(ctx);
3384 static void io_poll_complete_work(struct io_wq_work **workptr)
3386 struct io_wq_work *work = *workptr;
3387 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3388 struct io_poll_iocb *poll = &req->poll;
3389 struct poll_table_struct pt = { ._key = poll->events };
3390 struct io_ring_ctx *ctx = req->ctx;
3391 struct io_kiocb *nxt = NULL;
3395 if (work->flags & IO_WQ_WORK_CANCEL) {
3396 WRITE_ONCE(poll->canceled, true);
3398 } else if (READ_ONCE(poll->canceled)) {
3402 if (ret != -ECANCELED)
3403 mask = vfs_poll(poll->file, &pt) & poll->events;
3406 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3407 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3408 * synchronize with them. In the cancellation case the list_del_init
3409 * itself is not actually needed, but harmless so we keep it in to
3410 * avoid further branches in the fast path.
3412 spin_lock_irq(&ctx->completion_lock);
3413 if (!mask && ret != -ECANCELED) {
3414 add_wait_queue(poll->head, &poll->wait);
3415 spin_unlock_irq(&ctx->completion_lock);
3418 hash_del(&req->hash_node);
3419 io_poll_complete(req, mask, ret);
3420 spin_unlock_irq(&ctx->completion_lock);
3422 io_cqring_ev_posted(ctx);
3425 req_set_fail_links(req);
3426 io_put_req_find_next(req, &nxt);
3428 io_wq_assign_next(workptr, nxt);
3431 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3433 struct io_kiocb *req, *tmp;
3434 struct req_batch rb;
3436 rb.to_free = rb.need_iter = 0;
3437 spin_lock_irq(&ctx->completion_lock);
3438 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3439 hash_del(&req->hash_node);
3440 io_poll_complete(req, req->result, 0);
3442 if (refcount_dec_and_test(&req->refs) &&
3443 !io_req_multi_free(&rb, req)) {
3444 req->flags |= REQ_F_COMP_LOCKED;
3448 spin_unlock_irq(&ctx->completion_lock);
3450 io_cqring_ev_posted(ctx);
3451 io_free_req_many(ctx, &rb);
3454 static void io_poll_flush(struct io_wq_work **workptr)
3456 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3457 struct llist_node *nodes;
3459 nodes = llist_del_all(&req->ctx->poll_llist);
3461 __io_poll_flush(req->ctx, nodes);
3464 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3467 struct io_poll_iocb *poll = wait->private;
3468 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3469 struct io_ring_ctx *ctx = req->ctx;
3470 __poll_t mask = key_to_poll(key);
3472 /* for instances that support it check for an event match first: */
3473 if (mask && !(mask & poll->events))
3476 list_del_init(&poll->wait.entry);
3479 * Run completion inline if we can. We're using trylock here because
3480 * we are violating the completion_lock -> poll wq lock ordering.
3481 * If we have a link timeout we're going to need the completion_lock
3482 * for finalizing the request, mark us as having grabbed that already.
3485 unsigned long flags;
3487 if (llist_empty(&ctx->poll_llist) &&
3488 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3489 hash_del(&req->hash_node);
3490 io_poll_complete(req, mask, 0);
3491 req->flags |= REQ_F_COMP_LOCKED;
3493 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3495 io_cqring_ev_posted(ctx);
3499 req->llist_node.next = NULL;
3500 /* if the list wasn't empty, we're done */
3501 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3504 req->work.func = io_poll_flush;
3508 io_queue_async_work(req);
3513 struct io_poll_table {
3514 struct poll_table_struct pt;
3515 struct io_kiocb *req;
3519 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3520 struct poll_table_struct *p)
3522 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3524 if (unlikely(pt->req->poll.head)) {
3525 pt->error = -EINVAL;
3530 pt->req->poll.head = head;
3531 add_wait_queue(head, &pt->req->poll.wait);
3534 static void io_poll_req_insert(struct io_kiocb *req)
3536 struct io_ring_ctx *ctx = req->ctx;
3537 struct hlist_head *list;
3539 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3540 hlist_add_head(&req->hash_node, list);
3543 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3545 struct io_poll_iocb *poll = &req->poll;
3548 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3550 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3555 events = READ_ONCE(sqe->poll_events);
3556 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3560 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3562 struct io_poll_iocb *poll = &req->poll;
3563 struct io_ring_ctx *ctx = req->ctx;
3564 struct io_poll_table ipt;
3565 bool cancel = false;
3568 INIT_IO_WORK(&req->work, io_poll_complete_work);
3569 INIT_HLIST_NODE(&req->hash_node);
3573 poll->canceled = false;
3575 ipt.pt._qproc = io_poll_queue_proc;
3576 ipt.pt._key = poll->events;
3578 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3580 /* initialized the list so that we can do list_empty checks */
3581 INIT_LIST_HEAD(&poll->wait.entry);
3582 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3583 poll->wait.private = poll;
3585 INIT_LIST_HEAD(&req->list);
3587 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3589 spin_lock_irq(&ctx->completion_lock);
3590 if (likely(poll->head)) {
3591 spin_lock(&poll->head->lock);
3592 if (unlikely(list_empty(&poll->wait.entry))) {
3598 if (mask || ipt.error)
3599 list_del_init(&poll->wait.entry);
3601 WRITE_ONCE(poll->canceled, true);
3602 else if (!poll->done) /* actually waiting for an event */
3603 io_poll_req_insert(req);
3604 spin_unlock(&poll->head->lock);
3606 if (mask) { /* no async, we'd stolen it */
3608 io_poll_complete(req, mask, 0);
3610 spin_unlock_irq(&ctx->completion_lock);
3613 io_cqring_ev_posted(ctx);
3614 io_put_req_find_next(req, nxt);
3619 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3621 struct io_timeout_data *data = container_of(timer,
3622 struct io_timeout_data, timer);
3623 struct io_kiocb *req = data->req;
3624 struct io_ring_ctx *ctx = req->ctx;
3625 unsigned long flags;
3627 atomic_inc(&ctx->cq_timeouts);
3629 spin_lock_irqsave(&ctx->completion_lock, flags);
3631 * We could be racing with timeout deletion. If the list is empty,
3632 * then timeout lookup already found it and will be handling it.
3634 if (!list_empty(&req->list)) {
3635 struct io_kiocb *prev;
3638 * Adjust the reqs sequence before the current one because it
3639 * will consume a slot in the cq_ring and the cq_tail
3640 * pointer will be increased, otherwise other timeout reqs may
3641 * return in advance without waiting for enough wait_nr.
3644 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3646 list_del_init(&req->list);
3649 io_cqring_fill_event(req, -ETIME);
3650 io_commit_cqring(ctx);
3651 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3653 io_cqring_ev_posted(ctx);
3654 req_set_fail_links(req);
3656 return HRTIMER_NORESTART;
3659 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3661 struct io_kiocb *req;
3664 list_for_each_entry(req, &ctx->timeout_list, list) {
3665 if (user_data == req->user_data) {
3666 list_del_init(&req->list);
3675 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3679 req_set_fail_links(req);
3680 io_cqring_fill_event(req, -ECANCELED);
3685 static int io_timeout_remove_prep(struct io_kiocb *req,
3686 const struct io_uring_sqe *sqe)
3688 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3690 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3693 req->timeout.addr = READ_ONCE(sqe->addr);
3694 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3695 if (req->timeout.flags)
3702 * Remove or update an existing timeout command
3704 static int io_timeout_remove(struct io_kiocb *req)
3706 struct io_ring_ctx *ctx = req->ctx;
3709 spin_lock_irq(&ctx->completion_lock);
3710 ret = io_timeout_cancel(ctx, req->timeout.addr);
3712 io_cqring_fill_event(req, ret);
3713 io_commit_cqring(ctx);
3714 spin_unlock_irq(&ctx->completion_lock);
3715 io_cqring_ev_posted(ctx);
3717 req_set_fail_links(req);
3722 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3723 bool is_timeout_link)
3725 struct io_timeout_data *data;
3728 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3730 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3732 if (sqe->off && is_timeout_link)
3734 flags = READ_ONCE(sqe->timeout_flags);
3735 if (flags & ~IORING_TIMEOUT_ABS)
3738 req->timeout.count = READ_ONCE(sqe->off);
3740 if (!req->io && io_alloc_async_ctx(req))
3743 data = &req->io->timeout;
3745 req->flags |= REQ_F_TIMEOUT;
3747 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3750 if (flags & IORING_TIMEOUT_ABS)
3751 data->mode = HRTIMER_MODE_ABS;
3753 data->mode = HRTIMER_MODE_REL;
3755 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3759 static int io_timeout(struct io_kiocb *req)
3762 struct io_ring_ctx *ctx = req->ctx;
3763 struct io_timeout_data *data;
3764 struct list_head *entry;
3767 data = &req->io->timeout;
3770 * sqe->off holds how many events that need to occur for this
3771 * timeout event to be satisfied. If it isn't set, then this is
3772 * a pure timeout request, sequence isn't used.
3774 count = req->timeout.count;
3776 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3777 spin_lock_irq(&ctx->completion_lock);
3778 entry = ctx->timeout_list.prev;
3782 req->sequence = ctx->cached_sq_head + count - 1;
3783 data->seq_offset = count;
3786 * Insertion sort, ensuring the first entry in the list is always
3787 * the one we need first.
3789 spin_lock_irq(&ctx->completion_lock);
3790 list_for_each_prev(entry, &ctx->timeout_list) {
3791 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3792 unsigned nxt_sq_head;
3793 long long tmp, tmp_nxt;
3794 u32 nxt_offset = nxt->io->timeout.seq_offset;
3796 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3800 * Since cached_sq_head + count - 1 can overflow, use type long
3803 tmp = (long long)ctx->cached_sq_head + count - 1;
3804 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3805 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3808 * cached_sq_head may overflow, and it will never overflow twice
3809 * once there is some timeout req still be valid.
3811 if (ctx->cached_sq_head < nxt_sq_head)
3818 * Sequence of reqs after the insert one and itself should
3819 * be adjusted because each timeout req consumes a slot.
3824 req->sequence -= span;
3826 list_add(&req->list, entry);
3827 data->timer.function = io_timeout_fn;
3828 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3829 spin_unlock_irq(&ctx->completion_lock);
3833 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3835 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3837 return req->user_data == (unsigned long) data;
3840 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3842 enum io_wq_cancel cancel_ret;
3845 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3846 switch (cancel_ret) {
3847 case IO_WQ_CANCEL_OK:
3850 case IO_WQ_CANCEL_RUNNING:
3853 case IO_WQ_CANCEL_NOTFOUND:
3861 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3862 struct io_kiocb *req, __u64 sqe_addr,
3863 struct io_kiocb **nxt, int success_ret)
3865 unsigned long flags;
3868 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3869 if (ret != -ENOENT) {
3870 spin_lock_irqsave(&ctx->completion_lock, flags);
3874 spin_lock_irqsave(&ctx->completion_lock, flags);
3875 ret = io_timeout_cancel(ctx, sqe_addr);
3878 ret = io_poll_cancel(ctx, sqe_addr);
3882 io_cqring_fill_event(req, ret);
3883 io_commit_cqring(ctx);
3884 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3885 io_cqring_ev_posted(ctx);
3888 req_set_fail_links(req);
3889 io_put_req_find_next(req, nxt);
3892 static int io_async_cancel_prep(struct io_kiocb *req,
3893 const struct io_uring_sqe *sqe)
3895 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3897 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3901 req->cancel.addr = READ_ONCE(sqe->addr);
3905 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3907 struct io_ring_ctx *ctx = req->ctx;
3909 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3913 static int io_files_update_prep(struct io_kiocb *req,
3914 const struct io_uring_sqe *sqe)
3916 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
3919 req->files_update.offset = READ_ONCE(sqe->off);
3920 req->files_update.nr_args = READ_ONCE(sqe->len);
3921 if (!req->files_update.nr_args)
3923 req->files_update.arg = READ_ONCE(sqe->addr);
3927 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
3929 struct io_ring_ctx *ctx = req->ctx;
3930 struct io_uring_files_update up;
3933 if (force_nonblock) {
3934 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3938 up.offset = req->files_update.offset;
3939 up.fds = req->files_update.arg;
3941 mutex_lock(&ctx->uring_lock);
3942 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
3943 mutex_unlock(&ctx->uring_lock);
3946 req_set_fail_links(req);
3947 io_cqring_add_event(req, ret);
3952 static int io_req_defer_prep(struct io_kiocb *req,
3953 const struct io_uring_sqe *sqe)
3957 switch (req->opcode) {
3960 case IORING_OP_READV:
3961 case IORING_OP_READ_FIXED:
3962 case IORING_OP_READ:
3963 ret = io_read_prep(req, sqe, true);
3965 case IORING_OP_WRITEV:
3966 case IORING_OP_WRITE_FIXED:
3967 case IORING_OP_WRITE:
3968 ret = io_write_prep(req, sqe, true);
3970 case IORING_OP_POLL_ADD:
3971 ret = io_poll_add_prep(req, sqe);
3973 case IORING_OP_POLL_REMOVE:
3974 ret = io_poll_remove_prep(req, sqe);
3976 case IORING_OP_FSYNC:
3977 ret = io_prep_fsync(req, sqe);
3979 case IORING_OP_SYNC_FILE_RANGE:
3980 ret = io_prep_sfr(req, sqe);
3982 case IORING_OP_SENDMSG:
3983 case IORING_OP_SEND:
3984 ret = io_sendmsg_prep(req, sqe);
3986 case IORING_OP_RECVMSG:
3987 case IORING_OP_RECV:
3988 ret = io_recvmsg_prep(req, sqe);
3990 case IORING_OP_CONNECT:
3991 ret = io_connect_prep(req, sqe);
3993 case IORING_OP_TIMEOUT:
3994 ret = io_timeout_prep(req, sqe, false);
3996 case IORING_OP_TIMEOUT_REMOVE:
3997 ret = io_timeout_remove_prep(req, sqe);
3999 case IORING_OP_ASYNC_CANCEL:
4000 ret = io_async_cancel_prep(req, sqe);
4002 case IORING_OP_LINK_TIMEOUT:
4003 ret = io_timeout_prep(req, sqe, true);
4005 case IORING_OP_ACCEPT:
4006 ret = io_accept_prep(req, sqe);
4008 case IORING_OP_FALLOCATE:
4009 ret = io_fallocate_prep(req, sqe);
4011 case IORING_OP_OPENAT:
4012 ret = io_openat_prep(req, sqe);
4014 case IORING_OP_CLOSE:
4015 ret = io_close_prep(req, sqe);
4017 case IORING_OP_FILES_UPDATE:
4018 ret = io_files_update_prep(req, sqe);
4020 case IORING_OP_STATX:
4021 ret = io_statx_prep(req, sqe);
4023 case IORING_OP_FADVISE:
4024 ret = io_fadvise_prep(req, sqe);
4026 case IORING_OP_MADVISE:
4027 ret = io_madvise_prep(req, sqe);
4029 case IORING_OP_OPENAT2:
4030 ret = io_openat2_prep(req, sqe);
4033 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4042 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4044 struct io_ring_ctx *ctx = req->ctx;
4047 /* Still need defer if there is pending req in defer list. */
4048 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4051 if (!req->io && io_alloc_async_ctx(req))
4054 ret = io_req_defer_prep(req, sqe);
4058 spin_lock_irq(&ctx->completion_lock);
4059 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4060 spin_unlock_irq(&ctx->completion_lock);
4064 trace_io_uring_defer(ctx, req, req->user_data);
4065 list_add_tail(&req->list, &ctx->defer_list);
4066 spin_unlock_irq(&ctx->completion_lock);
4067 return -EIOCBQUEUED;
4070 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4071 struct io_kiocb **nxt, bool force_nonblock)
4073 struct io_ring_ctx *ctx = req->ctx;
4076 switch (req->opcode) {
4080 case IORING_OP_READV:
4081 case IORING_OP_READ_FIXED:
4082 case IORING_OP_READ:
4084 ret = io_read_prep(req, sqe, force_nonblock);
4088 ret = io_read(req, nxt, force_nonblock);
4090 case IORING_OP_WRITEV:
4091 case IORING_OP_WRITE_FIXED:
4092 case IORING_OP_WRITE:
4094 ret = io_write_prep(req, sqe, force_nonblock);
4098 ret = io_write(req, nxt, force_nonblock);
4100 case IORING_OP_FSYNC:
4102 ret = io_prep_fsync(req, sqe);
4106 ret = io_fsync(req, nxt, force_nonblock);
4108 case IORING_OP_POLL_ADD:
4110 ret = io_poll_add_prep(req, sqe);
4114 ret = io_poll_add(req, nxt);
4116 case IORING_OP_POLL_REMOVE:
4118 ret = io_poll_remove_prep(req, sqe);
4122 ret = io_poll_remove(req);
4124 case IORING_OP_SYNC_FILE_RANGE:
4126 ret = io_prep_sfr(req, sqe);
4130 ret = io_sync_file_range(req, nxt, force_nonblock);
4132 case IORING_OP_SENDMSG:
4133 case IORING_OP_SEND:
4135 ret = io_sendmsg_prep(req, sqe);
4139 if (req->opcode == IORING_OP_SENDMSG)
4140 ret = io_sendmsg(req, nxt, force_nonblock);
4142 ret = io_send(req, nxt, force_nonblock);
4144 case IORING_OP_RECVMSG:
4145 case IORING_OP_RECV:
4147 ret = io_recvmsg_prep(req, sqe);
4151 if (req->opcode == IORING_OP_RECVMSG)
4152 ret = io_recvmsg(req, nxt, force_nonblock);
4154 ret = io_recv(req, nxt, force_nonblock);
4156 case IORING_OP_TIMEOUT:
4158 ret = io_timeout_prep(req, sqe, false);
4162 ret = io_timeout(req);
4164 case IORING_OP_TIMEOUT_REMOVE:
4166 ret = io_timeout_remove_prep(req, sqe);
4170 ret = io_timeout_remove(req);
4172 case IORING_OP_ACCEPT:
4174 ret = io_accept_prep(req, sqe);
4178 ret = io_accept(req, nxt, force_nonblock);
4180 case IORING_OP_CONNECT:
4182 ret = io_connect_prep(req, sqe);
4186 ret = io_connect(req, nxt, force_nonblock);
4188 case IORING_OP_ASYNC_CANCEL:
4190 ret = io_async_cancel_prep(req, sqe);
4194 ret = io_async_cancel(req, nxt);
4196 case IORING_OP_FALLOCATE:
4198 ret = io_fallocate_prep(req, sqe);
4202 ret = io_fallocate(req, nxt, force_nonblock);
4204 case IORING_OP_OPENAT:
4206 ret = io_openat_prep(req, sqe);
4210 ret = io_openat(req, nxt, force_nonblock);
4212 case IORING_OP_CLOSE:
4214 ret = io_close_prep(req, sqe);
4218 ret = io_close(req, nxt, force_nonblock);
4220 case IORING_OP_FILES_UPDATE:
4222 ret = io_files_update_prep(req, sqe);
4226 ret = io_files_update(req, force_nonblock);
4228 case IORING_OP_STATX:
4230 ret = io_statx_prep(req, sqe);
4234 ret = io_statx(req, nxt, force_nonblock);
4236 case IORING_OP_FADVISE:
4238 ret = io_fadvise_prep(req, sqe);
4242 ret = io_fadvise(req, nxt, force_nonblock);
4244 case IORING_OP_MADVISE:
4246 ret = io_madvise_prep(req, sqe);
4250 ret = io_madvise(req, nxt, force_nonblock);
4252 case IORING_OP_OPENAT2:
4254 ret = io_openat2_prep(req, sqe);
4258 ret = io_openat2(req, nxt, force_nonblock);
4268 if (ctx->flags & IORING_SETUP_IOPOLL) {
4269 const bool in_async = io_wq_current_is_worker();
4271 if (req->result == -EAGAIN)
4274 /* workqueue context doesn't hold uring_lock, grab it now */
4276 mutex_lock(&ctx->uring_lock);
4278 io_iopoll_req_issued(req);
4281 mutex_unlock(&ctx->uring_lock);
4287 static void io_wq_submit_work(struct io_wq_work **workptr)
4289 struct io_wq_work *work = *workptr;
4290 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4291 struct io_kiocb *nxt = NULL;
4294 /* if NO_CANCEL is set, we must still run the work */
4295 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4296 IO_WQ_WORK_CANCEL) {
4301 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
4302 req->in_async = true;
4304 ret = io_issue_sqe(req, NULL, &nxt, false);
4306 * We can get EAGAIN for polled IO even though we're
4307 * forcing a sync submission from here, since we can't
4308 * wait for request slots on the block side.
4316 /* drop submission reference */
4320 req_set_fail_links(req);
4321 io_cqring_add_event(req, ret);
4325 /* if a dependent link is ready, pass it back */
4327 io_wq_assign_next(workptr, nxt);
4330 static int io_req_needs_file(struct io_kiocb *req, int fd)
4332 if (!io_op_defs[req->opcode].needs_file)
4334 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4339 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4342 struct fixed_file_table *table;
4344 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4345 return table->files[index & IORING_FILE_TABLE_MASK];;
4348 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4349 const struct io_uring_sqe *sqe)
4351 struct io_ring_ctx *ctx = req->ctx;
4355 flags = READ_ONCE(sqe->flags);
4356 fd = READ_ONCE(sqe->fd);
4358 if (flags & IOSQE_IO_DRAIN)
4359 req->flags |= REQ_F_IO_DRAIN;
4361 if (!io_req_needs_file(req, fd))
4364 if (flags & IOSQE_FIXED_FILE) {
4365 if (unlikely(!ctx->file_data ||
4366 (unsigned) fd >= ctx->nr_user_files))
4368 fd = array_index_nospec(fd, ctx->nr_user_files);
4369 req->file = io_file_from_index(ctx, fd);
4372 req->flags |= REQ_F_FIXED_FILE;
4373 percpu_ref_get(&ctx->file_data->refs);
4375 if (req->needs_fixed_file)
4377 trace_io_uring_file_get(ctx, fd);
4378 req->file = io_file_get(state, fd);
4379 if (unlikely(!req->file))
4386 static int io_grab_files(struct io_kiocb *req)
4389 struct io_ring_ctx *ctx = req->ctx;
4391 if (!ctx->ring_file)
4395 spin_lock_irq(&ctx->inflight_lock);
4397 * We use the f_ops->flush() handler to ensure that we can flush
4398 * out work accessing these files if the fd is closed. Check if
4399 * the fd has changed since we started down this path, and disallow
4400 * this operation if it has.
4402 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4403 list_add(&req->inflight_entry, &ctx->inflight_list);
4404 req->flags |= REQ_F_INFLIGHT;
4405 req->work.files = current->files;
4408 spin_unlock_irq(&ctx->inflight_lock);
4414 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4416 struct io_timeout_data *data = container_of(timer,
4417 struct io_timeout_data, timer);
4418 struct io_kiocb *req = data->req;
4419 struct io_ring_ctx *ctx = req->ctx;
4420 struct io_kiocb *prev = NULL;
4421 unsigned long flags;
4423 spin_lock_irqsave(&ctx->completion_lock, flags);
4426 * We don't expect the list to be empty, that will only happen if we
4427 * race with the completion of the linked work.
4429 if (!list_empty(&req->link_list)) {
4430 prev = list_entry(req->link_list.prev, struct io_kiocb,
4432 if (refcount_inc_not_zero(&prev->refs)) {
4433 list_del_init(&req->link_list);
4434 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4439 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4442 req_set_fail_links(prev);
4443 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4447 io_cqring_add_event(req, -ETIME);
4450 return HRTIMER_NORESTART;
4453 static void io_queue_linked_timeout(struct io_kiocb *req)
4455 struct io_ring_ctx *ctx = req->ctx;
4458 * If the list is now empty, then our linked request finished before
4459 * we got a chance to setup the timer
4461 spin_lock_irq(&ctx->completion_lock);
4462 if (!list_empty(&req->link_list)) {
4463 struct io_timeout_data *data = &req->io->timeout;
4465 data->timer.function = io_link_timeout_fn;
4466 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4469 spin_unlock_irq(&ctx->completion_lock);
4471 /* drop submission reference */
4475 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4477 struct io_kiocb *nxt;
4479 if (!(req->flags & REQ_F_LINK))
4482 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4484 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4487 req->flags |= REQ_F_LINK_TIMEOUT;
4491 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4493 struct io_kiocb *linked_timeout;
4494 struct io_kiocb *nxt = NULL;
4498 linked_timeout = io_prep_linked_timeout(req);
4500 ret = io_issue_sqe(req, sqe, &nxt, true);
4503 * We async punt it if the file wasn't marked NOWAIT, or if the file
4504 * doesn't support non-blocking read/write attempts
4506 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4507 (req->flags & REQ_F_MUST_PUNT))) {
4508 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
4509 ret = io_grab_files(req);
4515 * Queued up for async execution, worker will release
4516 * submit reference when the iocb is actually submitted.
4518 io_queue_async_work(req);
4523 /* drop submission reference */
4526 if (linked_timeout) {
4528 io_queue_linked_timeout(linked_timeout);
4530 io_put_req(linked_timeout);
4533 /* and drop final reference, if we failed */
4535 io_cqring_add_event(req, ret);
4536 req_set_fail_links(req);
4547 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4551 ret = io_req_defer(req, sqe);
4553 if (ret != -EIOCBQUEUED) {
4554 io_cqring_add_event(req, ret);
4555 req_set_fail_links(req);
4556 io_double_put_req(req);
4558 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4560 * Never try inline submit of IOSQE_ASYNC is set, go straight
4561 * to async execution.
4563 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4564 io_queue_async_work(req);
4566 __io_queue_sqe(req, sqe);
4570 static inline void io_queue_link_head(struct io_kiocb *req)
4572 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4573 io_cqring_add_event(req, -ECANCELED);
4574 io_double_put_req(req);
4576 io_queue_sqe(req, NULL);
4579 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4580 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4582 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4583 struct io_submit_state *state, struct io_kiocb **link)
4585 struct io_ring_ctx *ctx = req->ctx;
4586 unsigned int sqe_flags;
4589 sqe_flags = READ_ONCE(sqe->flags);
4591 /* enforce forwards compatibility on users */
4592 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4596 if (sqe_flags & IOSQE_ASYNC)
4597 req->flags |= REQ_F_FORCE_ASYNC;
4599 ret = io_req_set_file(state, req, sqe);
4600 if (unlikely(ret)) {
4602 io_cqring_add_event(req, ret);
4603 io_double_put_req(req);
4608 * If we already have a head request, queue this one for async
4609 * submittal once the head completes. If we don't have a head but
4610 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4611 * submitted sync once the chain is complete. If none of those
4612 * conditions are true (normal request), then just queue it.
4615 struct io_kiocb *head = *link;
4617 if (sqe_flags & IOSQE_IO_DRAIN) {
4618 head->flags |= REQ_F_IO_DRAIN;
4619 ctx->drain_next = 1;
4622 if (sqe_flags & IOSQE_IO_HARDLINK)
4623 req->flags |= REQ_F_HARDLINK;
4625 if (io_alloc_async_ctx(req)) {
4630 ret = io_req_defer_prep(req, sqe);
4632 /* fail even hard links since we don't submit */
4633 head->flags |= REQ_F_FAIL_LINK;
4636 trace_io_uring_link(ctx, req, head);
4637 list_add_tail(&req->link_list, &head->link_list);
4639 /* last request of a link, enqueue the link */
4640 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4641 io_queue_link_head(head);
4645 if (unlikely(ctx->drain_next)) {
4646 req->flags |= REQ_F_IO_DRAIN;
4647 req->ctx->drain_next = 0;
4649 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4650 req->flags |= REQ_F_LINK;
4651 if (sqe_flags & IOSQE_IO_HARDLINK)
4652 req->flags |= REQ_F_HARDLINK;
4654 INIT_LIST_HEAD(&req->link_list);
4655 ret = io_req_defer_prep(req, sqe);
4657 req->flags |= REQ_F_FAIL_LINK;
4660 io_queue_sqe(req, sqe);
4668 * Batched submission is done, ensure local IO is flushed out.
4670 static void io_submit_state_end(struct io_submit_state *state)
4672 blk_finish_plug(&state->plug);
4674 if (state->free_reqs)
4675 kmem_cache_free_bulk(req_cachep, state->free_reqs,
4676 &state->reqs[state->cur_req]);
4680 * Start submission side cache.
4682 static void io_submit_state_start(struct io_submit_state *state,
4683 unsigned int max_ios)
4685 blk_start_plug(&state->plug);
4686 state->free_reqs = 0;
4688 state->ios_left = max_ios;
4691 static void io_commit_sqring(struct io_ring_ctx *ctx)
4693 struct io_rings *rings = ctx->rings;
4696 * Ensure any loads from the SQEs are done at this point,
4697 * since once we write the new head, the application could
4698 * write new data to them.
4700 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4704 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4705 * that is mapped by userspace. This means that care needs to be taken to
4706 * ensure that reads are stable, as we cannot rely on userspace always
4707 * being a good citizen. If members of the sqe are validated and then later
4708 * used, it's important that those reads are done through READ_ONCE() to
4709 * prevent a re-load down the line.
4711 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4712 const struct io_uring_sqe **sqe_ptr)
4714 u32 *sq_array = ctx->sq_array;
4718 * The cached sq head (or cq tail) serves two purposes:
4720 * 1) allows us to batch the cost of updating the user visible
4722 * 2) allows the kernel side to track the head on its own, even
4723 * though the application is the one updating it.
4725 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4726 if (likely(head < ctx->sq_entries)) {
4728 * All io need record the previous position, if LINK vs DARIN,
4729 * it can be used to mark the position of the first IO in the
4732 req->sequence = ctx->cached_sq_head;
4733 *sqe_ptr = &ctx->sq_sqes[head];
4734 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4735 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4736 ctx->cached_sq_head++;
4740 /* drop invalid entries */
4741 ctx->cached_sq_head++;
4742 ctx->cached_sq_dropped++;
4743 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4747 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4748 struct file *ring_file, int ring_fd,
4749 struct mm_struct **mm, bool async)
4751 struct io_submit_state state, *statep = NULL;
4752 struct io_kiocb *link = NULL;
4753 int i, submitted = 0;
4754 bool mm_fault = false;
4756 /* if we have a backlog and couldn't flush it all, return BUSY */
4757 if (test_bit(0, &ctx->sq_check_overflow)) {
4758 if (!list_empty(&ctx->cq_overflow_list) &&
4759 !io_cqring_overflow_flush(ctx, false))
4763 /* make sure SQ entry isn't read before tail */
4764 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
4766 if (!percpu_ref_tryget_many(&ctx->refs, nr))
4769 if (nr > IO_PLUG_THRESHOLD) {
4770 io_submit_state_start(&state, nr);
4774 ctx->ring_fd = ring_fd;
4775 ctx->ring_file = ring_file;
4777 for (i = 0; i < nr; i++) {
4778 const struct io_uring_sqe *sqe;
4779 struct io_kiocb *req;
4781 req = io_get_req(ctx, statep);
4782 if (unlikely(!req)) {
4784 submitted = -EAGAIN;
4787 if (!io_get_sqring(ctx, req, &sqe)) {
4788 __io_req_do_free(req);
4792 /* will complete beyond this point, count as submitted */
4795 if (unlikely(req->opcode >= IORING_OP_LAST)) {
4796 io_cqring_add_event(req, -EINVAL);
4797 io_double_put_req(req);
4801 if (io_op_defs[req->opcode].needs_mm && !*mm) {
4802 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
4804 use_mm(ctx->sqo_mm);
4809 req->has_user = *mm != NULL;
4810 req->in_async = async;
4811 req->needs_fixed_file = async;
4812 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
4814 if (!io_submit_sqe(req, sqe, statep, &link))
4818 if (submitted != nr)
4819 percpu_ref_put_many(&ctx->refs, nr - submitted);
4821 io_queue_link_head(link);
4823 io_submit_state_end(&state);
4825 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4826 io_commit_sqring(ctx);
4831 static int io_sq_thread(void *data)
4833 struct io_ring_ctx *ctx = data;
4834 struct mm_struct *cur_mm = NULL;
4835 const struct cred *old_cred;
4836 mm_segment_t old_fs;
4839 unsigned long timeout;
4842 complete(&ctx->completions[1]);
4846 old_cred = override_creds(ctx->creds);
4848 ret = timeout = inflight = 0;
4849 while (!kthread_should_park()) {
4850 unsigned int to_submit;
4853 unsigned nr_events = 0;
4855 if (ctx->flags & IORING_SETUP_IOPOLL) {
4857 * inflight is the count of the maximum possible
4858 * entries we submitted, but it can be smaller
4859 * if we dropped some of them. If we don't have
4860 * poll entries available, then we know that we
4861 * have nothing left to poll for. Reset the
4862 * inflight count to zero in that case.
4864 mutex_lock(&ctx->uring_lock);
4865 if (!list_empty(&ctx->poll_list))
4866 __io_iopoll_check(ctx, &nr_events, 0);
4869 mutex_unlock(&ctx->uring_lock);
4872 * Normal IO, just pretend everything completed.
4873 * We don't have to poll completions for that.
4875 nr_events = inflight;
4878 inflight -= nr_events;
4880 timeout = jiffies + ctx->sq_thread_idle;
4883 to_submit = io_sqring_entries(ctx);
4886 * If submit got -EBUSY, flag us as needing the application
4887 * to enter the kernel to reap and flush events.
4889 if (!to_submit || ret == -EBUSY) {
4891 * We're polling. If we're within the defined idle
4892 * period, then let us spin without work before going
4893 * to sleep. The exception is if we got EBUSY doing
4894 * more IO, we should wait for the application to
4895 * reap events and wake us up.
4898 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
4904 * Drop cur_mm before scheduling, we can't hold it for
4905 * long periods (or over schedule()). Do this before
4906 * adding ourselves to the waitqueue, as the unuse/drop
4915 prepare_to_wait(&ctx->sqo_wait, &wait,
4916 TASK_INTERRUPTIBLE);
4918 /* Tell userspace we may need a wakeup call */
4919 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
4920 /* make sure to read SQ tail after writing flags */
4923 to_submit = io_sqring_entries(ctx);
4924 if (!to_submit || ret == -EBUSY) {
4925 if (kthread_should_park()) {
4926 finish_wait(&ctx->sqo_wait, &wait);
4929 if (signal_pending(current))
4930 flush_signals(current);
4932 finish_wait(&ctx->sqo_wait, &wait);
4934 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4937 finish_wait(&ctx->sqo_wait, &wait);
4939 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4942 mutex_lock(&ctx->uring_lock);
4943 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
4944 mutex_unlock(&ctx->uring_lock);
4954 revert_creds(old_cred);
4961 struct io_wait_queue {
4962 struct wait_queue_entry wq;
4963 struct io_ring_ctx *ctx;
4965 unsigned nr_timeouts;
4968 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
4970 struct io_ring_ctx *ctx = iowq->ctx;
4973 * Wake up if we have enough events, or if a timeout occurred since we
4974 * started waiting. For timeouts, we always want to return to userspace,
4975 * regardless of event count.
4977 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
4978 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4981 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
4982 int wake_flags, void *key)
4984 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
4987 /* use noflush == true, as we can't safely rely on locking context */
4988 if (!io_should_wake(iowq, true))
4991 return autoremove_wake_function(curr, mode, wake_flags, key);
4995 * Wait until events become available, if we don't already have some. The
4996 * application must reap them itself, as they reside on the shared cq ring.
4998 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
4999 const sigset_t __user *sig, size_t sigsz)
5001 struct io_wait_queue iowq = {
5004 .func = io_wake_function,
5005 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5008 .to_wait = min_events,
5010 struct io_rings *rings = ctx->rings;
5013 if (io_cqring_events(ctx, false) >= min_events)
5017 #ifdef CONFIG_COMPAT
5018 if (in_compat_syscall())
5019 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5023 ret = set_user_sigmask(sig, sigsz);
5029 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5030 trace_io_uring_cqring_wait(ctx, min_events);
5032 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5033 TASK_INTERRUPTIBLE);
5034 if (io_should_wake(&iowq, false))
5037 if (signal_pending(current)) {
5042 finish_wait(&ctx->wait, &iowq.wq);
5044 restore_saved_sigmask_unless(ret == -EINTR);
5046 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5049 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5051 #if defined(CONFIG_UNIX)
5052 if (ctx->ring_sock) {
5053 struct sock *sock = ctx->ring_sock->sk;
5054 struct sk_buff *skb;
5056 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5062 for (i = 0; i < ctx->nr_user_files; i++) {
5065 file = io_file_from_index(ctx, i);
5072 static void io_file_ref_kill(struct percpu_ref *ref)
5074 struct fixed_file_data *data;
5076 data = container_of(ref, struct fixed_file_data, refs);
5077 complete(&data->done);
5080 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5082 struct fixed_file_data *data = ctx->file_data;
5083 unsigned nr_tables, i;
5088 /* protect against inflight atomic switch, which drops the ref */
5089 percpu_ref_get(&data->refs);
5090 /* wait for existing switches */
5091 flush_work(&data->ref_work);
5092 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5093 wait_for_completion(&data->done);
5094 percpu_ref_put(&data->refs);
5095 /* flush potential new switch */
5096 flush_work(&data->ref_work);
5097 percpu_ref_exit(&data->refs);
5099 __io_sqe_files_unregister(ctx);
5100 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5101 for (i = 0; i < nr_tables; i++)
5102 kfree(data->table[i].files);
5105 ctx->file_data = NULL;
5106 ctx->nr_user_files = 0;
5110 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5112 if (ctx->sqo_thread) {
5113 wait_for_completion(&ctx->completions[1]);
5115 * The park is a bit of a work-around, without it we get
5116 * warning spews on shutdown with SQPOLL set and affinity
5117 * set to a single CPU.
5119 kthread_park(ctx->sqo_thread);
5120 kthread_stop(ctx->sqo_thread);
5121 ctx->sqo_thread = NULL;
5125 static void io_finish_async(struct io_ring_ctx *ctx)
5127 io_sq_thread_stop(ctx);
5130 io_wq_destroy(ctx->io_wq);
5135 #if defined(CONFIG_UNIX)
5137 * Ensure the UNIX gc is aware of our file set, so we are certain that
5138 * the io_uring can be safely unregistered on process exit, even if we have
5139 * loops in the file referencing.
5141 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5143 struct sock *sk = ctx->ring_sock->sk;
5144 struct scm_fp_list *fpl;
5145 struct sk_buff *skb;
5148 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5149 unsigned long inflight = ctx->user->unix_inflight + nr;
5151 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5155 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5159 skb = alloc_skb(0, GFP_KERNEL);
5168 fpl->user = get_uid(ctx->user);
5169 for (i = 0; i < nr; i++) {
5170 struct file *file = io_file_from_index(ctx, i + offset);
5174 fpl->fp[nr_files] = get_file(file);
5175 unix_inflight(fpl->user, fpl->fp[nr_files]);
5180 fpl->max = SCM_MAX_FD;
5181 fpl->count = nr_files;
5182 UNIXCB(skb).fp = fpl;
5183 skb->destructor = unix_destruct_scm;
5184 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5185 skb_queue_head(&sk->sk_receive_queue, skb);
5187 for (i = 0; i < nr_files; i++)
5198 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5199 * causes regular reference counting to break down. We rely on the UNIX
5200 * garbage collection to take care of this problem for us.
5202 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5204 unsigned left, total;
5208 left = ctx->nr_user_files;
5210 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
5212 ret = __io_sqe_files_scm(ctx, this_files, total);
5216 total += this_files;
5222 while (total < ctx->nr_user_files) {
5223 struct file *file = io_file_from_index(ctx, total);
5233 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5239 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5244 for (i = 0; i < nr_tables; i++) {
5245 struct fixed_file_table *table = &ctx->file_data->table[i];
5246 unsigned this_files;
5248 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5249 table->files = kcalloc(this_files, sizeof(struct file *),
5253 nr_files -= this_files;
5259 for (i = 0; i < nr_tables; i++) {
5260 struct fixed_file_table *table = &ctx->file_data->table[i];
5261 kfree(table->files);
5266 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5268 #if defined(CONFIG_UNIX)
5269 struct sock *sock = ctx->ring_sock->sk;
5270 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5271 struct sk_buff *skb;
5274 __skb_queue_head_init(&list);
5277 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5278 * remove this entry and rearrange the file array.
5280 skb = skb_dequeue(head);
5282 struct scm_fp_list *fp;
5284 fp = UNIXCB(skb).fp;
5285 for (i = 0; i < fp->count; i++) {
5288 if (fp->fp[i] != file)
5291 unix_notinflight(fp->user, fp->fp[i]);
5292 left = fp->count - 1 - i;
5294 memmove(&fp->fp[i], &fp->fp[i + 1],
5295 left * sizeof(struct file *));
5302 __skb_queue_tail(&list, skb);
5312 __skb_queue_tail(&list, skb);
5314 skb = skb_dequeue(head);
5317 if (skb_peek(&list)) {
5318 spin_lock_irq(&head->lock);
5319 while ((skb = __skb_dequeue(&list)) != NULL)
5320 __skb_queue_tail(head, skb);
5321 spin_unlock_irq(&head->lock);
5328 struct io_file_put {
5329 struct llist_node llist;
5331 struct completion *done;
5334 static void io_ring_file_ref_switch(struct work_struct *work)
5336 struct io_file_put *pfile, *tmp;
5337 struct fixed_file_data *data;
5338 struct llist_node *node;
5340 data = container_of(work, struct fixed_file_data, ref_work);
5342 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5343 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5344 io_ring_file_put(data->ctx, pfile->file);
5346 complete(pfile->done);
5352 percpu_ref_get(&data->refs);
5353 percpu_ref_switch_to_percpu(&data->refs);
5356 static void io_file_data_ref_zero(struct percpu_ref *ref)
5358 struct fixed_file_data *data;
5360 data = container_of(ref, struct fixed_file_data, refs);
5362 /* we can't safely switch from inside this context, punt to wq */
5363 queue_work(system_wq, &data->ref_work);
5366 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5369 __s32 __user *fds = (__s32 __user *) arg;
5379 if (nr_args > IORING_MAX_FIXED_FILES)
5382 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5383 if (!ctx->file_data)
5385 ctx->file_data->ctx = ctx;
5386 init_completion(&ctx->file_data->done);
5388 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5389 ctx->file_data->table = kcalloc(nr_tables,
5390 sizeof(struct fixed_file_table),
5392 if (!ctx->file_data->table) {
5393 kfree(ctx->file_data);
5394 ctx->file_data = NULL;
5398 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5399 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5400 kfree(ctx->file_data->table);
5401 kfree(ctx->file_data);
5402 ctx->file_data = NULL;
5405 ctx->file_data->put_llist.first = NULL;
5406 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5408 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5409 percpu_ref_exit(&ctx->file_data->refs);
5410 kfree(ctx->file_data->table);
5411 kfree(ctx->file_data);
5412 ctx->file_data = NULL;
5416 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5417 struct fixed_file_table *table;
5421 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5423 /* allow sparse sets */
5429 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5430 index = i & IORING_FILE_TABLE_MASK;
5438 * Don't allow io_uring instances to be registered. If UNIX
5439 * isn't enabled, then this causes a reference cycle and this
5440 * instance can never get freed. If UNIX is enabled we'll
5441 * handle it just fine, but there's still no point in allowing
5442 * a ring fd as it doesn't support regular read/write anyway.
5444 if (file->f_op == &io_uring_fops) {
5449 table->files[index] = file;
5453 for (i = 0; i < ctx->nr_user_files; i++) {
5454 file = io_file_from_index(ctx, i);
5458 for (i = 0; i < nr_tables; i++)
5459 kfree(ctx->file_data->table[i].files);
5461 kfree(ctx->file_data->table);
5462 kfree(ctx->file_data);
5463 ctx->file_data = NULL;
5464 ctx->nr_user_files = 0;
5468 ret = io_sqe_files_scm(ctx);
5470 io_sqe_files_unregister(ctx);
5475 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5478 #if defined(CONFIG_UNIX)
5479 struct sock *sock = ctx->ring_sock->sk;
5480 struct sk_buff_head *head = &sock->sk_receive_queue;
5481 struct sk_buff *skb;
5484 * See if we can merge this file into an existing skb SCM_RIGHTS
5485 * file set. If there's no room, fall back to allocating a new skb
5486 * and filling it in.
5488 spin_lock_irq(&head->lock);
5489 skb = skb_peek(head);
5491 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5493 if (fpl->count < SCM_MAX_FD) {
5494 __skb_unlink(skb, head);
5495 spin_unlock_irq(&head->lock);
5496 fpl->fp[fpl->count] = get_file(file);
5497 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5499 spin_lock_irq(&head->lock);
5500 __skb_queue_head(head, skb);
5505 spin_unlock_irq(&head->lock);
5512 return __io_sqe_files_scm(ctx, 1, index);
5518 static void io_atomic_switch(struct percpu_ref *ref)
5520 struct fixed_file_data *data;
5522 data = container_of(ref, struct fixed_file_data, refs);
5523 clear_bit(FFD_F_ATOMIC, &data->state);
5526 static bool io_queue_file_removal(struct fixed_file_data *data,
5529 struct io_file_put *pfile, pfile_stack;
5530 DECLARE_COMPLETION_ONSTACK(done);
5533 * If we fail allocating the struct we need for doing async reomval
5534 * of this file, just punt to sync and wait for it.
5536 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5538 pfile = &pfile_stack;
5539 pfile->done = &done;
5543 llist_add(&pfile->llist, &data->put_llist);
5545 if (pfile == &pfile_stack) {
5546 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5547 percpu_ref_put(&data->refs);
5548 percpu_ref_switch_to_atomic(&data->refs,
5551 wait_for_completion(&done);
5552 flush_work(&data->ref_work);
5559 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5560 struct io_uring_files_update *up,
5563 struct fixed_file_data *data = ctx->file_data;
5564 bool ref_switch = false;
5570 if (check_add_overflow(up->offset, nr_args, &done))
5572 if (done > ctx->nr_user_files)
5576 fds = u64_to_user_ptr(up->fds);
5578 struct fixed_file_table *table;
5582 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5586 i = array_index_nospec(up->offset, ctx->nr_user_files);
5587 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5588 index = i & IORING_FILE_TABLE_MASK;
5589 if (table->files[index]) {
5590 file = io_file_from_index(ctx, index);
5591 table->files[index] = NULL;
5592 if (io_queue_file_removal(data, file))
5602 * Don't allow io_uring instances to be registered. If
5603 * UNIX isn't enabled, then this causes a reference
5604 * cycle and this instance can never get freed. If UNIX
5605 * is enabled we'll handle it just fine, but there's
5606 * still no point in allowing a ring fd as it doesn't
5607 * support regular read/write anyway.
5609 if (file->f_op == &io_uring_fops) {
5614 table->files[index] = file;
5615 err = io_sqe_file_register(ctx, file, i);
5624 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5625 percpu_ref_put(&data->refs);
5626 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5629 return done ? done : err;
5631 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5634 struct io_uring_files_update up;
5636 if (!ctx->file_data)
5640 if (copy_from_user(&up, arg, sizeof(up)))
5645 return __io_sqe_files_update(ctx, &up, nr_args);
5648 static void io_put_work(struct io_wq_work *work)
5650 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5655 static void io_get_work(struct io_wq_work *work)
5657 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5659 refcount_inc(&req->refs);
5662 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5663 struct io_uring_params *p)
5665 struct io_wq_data data;
5666 unsigned concurrency;
5669 init_waitqueue_head(&ctx->sqo_wait);
5670 mmgrab(current->mm);
5671 ctx->sqo_mm = current->mm;
5673 if (ctx->flags & IORING_SETUP_SQPOLL) {
5675 if (!capable(CAP_SYS_ADMIN))
5678 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5679 if (!ctx->sq_thread_idle)
5680 ctx->sq_thread_idle = HZ;
5682 if (p->flags & IORING_SETUP_SQ_AFF) {
5683 int cpu = p->sq_thread_cpu;
5686 if (cpu >= nr_cpu_ids)
5688 if (!cpu_online(cpu))
5691 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5695 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5698 if (IS_ERR(ctx->sqo_thread)) {
5699 ret = PTR_ERR(ctx->sqo_thread);
5700 ctx->sqo_thread = NULL;
5703 wake_up_process(ctx->sqo_thread);
5704 } else if (p->flags & IORING_SETUP_SQ_AFF) {
5705 /* Can't have SQ_AFF without SQPOLL */
5710 data.mm = ctx->sqo_mm;
5711 data.user = ctx->user;
5712 data.creds = ctx->creds;
5713 data.get_work = io_get_work;
5714 data.put_work = io_put_work;
5716 /* Do QD, or 4 * CPUS, whatever is smallest */
5717 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5718 ctx->io_wq = io_wq_create(concurrency, &data);
5719 if (IS_ERR(ctx->io_wq)) {
5720 ret = PTR_ERR(ctx->io_wq);
5727 io_finish_async(ctx);
5728 mmdrop(ctx->sqo_mm);
5733 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
5735 atomic_long_sub(nr_pages, &user->locked_vm);
5738 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
5740 unsigned long page_limit, cur_pages, new_pages;
5742 /* Don't allow more pages than we can safely lock */
5743 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5746 cur_pages = atomic_long_read(&user->locked_vm);
5747 new_pages = cur_pages + nr_pages;
5748 if (new_pages > page_limit)
5750 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5751 new_pages) != cur_pages);
5756 static void io_mem_free(void *ptr)
5763 page = virt_to_head_page(ptr);
5764 if (put_page_testzero(page))
5765 free_compound_page(page);
5768 static void *io_mem_alloc(size_t size)
5770 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
5773 return (void *) __get_free_pages(gfp_flags, get_order(size));
5776 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
5779 struct io_rings *rings;
5780 size_t off, sq_array_size;
5782 off = struct_size(rings, cqes, cq_entries);
5783 if (off == SIZE_MAX)
5787 off = ALIGN(off, SMP_CACHE_BYTES);
5792 sq_array_size = array_size(sizeof(u32), sq_entries);
5793 if (sq_array_size == SIZE_MAX)
5796 if (check_add_overflow(off, sq_array_size, &off))
5805 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
5809 pages = (size_t)1 << get_order(
5810 rings_size(sq_entries, cq_entries, NULL));
5811 pages += (size_t)1 << get_order(
5812 array_size(sizeof(struct io_uring_sqe), sq_entries));
5817 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
5821 if (!ctx->user_bufs)
5824 for (i = 0; i < ctx->nr_user_bufs; i++) {
5825 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5827 for (j = 0; j < imu->nr_bvecs; j++)
5828 put_user_page(imu->bvec[j].bv_page);
5830 if (ctx->account_mem)
5831 io_unaccount_mem(ctx->user, imu->nr_bvecs);
5836 kfree(ctx->user_bufs);
5837 ctx->user_bufs = NULL;
5838 ctx->nr_user_bufs = 0;
5842 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
5843 void __user *arg, unsigned index)
5845 struct iovec __user *src;
5847 #ifdef CONFIG_COMPAT
5849 struct compat_iovec __user *ciovs;
5850 struct compat_iovec ciov;
5852 ciovs = (struct compat_iovec __user *) arg;
5853 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
5856 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
5857 dst->iov_len = ciov.iov_len;
5861 src = (struct iovec __user *) arg;
5862 if (copy_from_user(dst, &src[index], sizeof(*dst)))
5867 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
5870 struct vm_area_struct **vmas = NULL;
5871 struct page **pages = NULL;
5872 int i, j, got_pages = 0;
5877 if (!nr_args || nr_args > UIO_MAXIOV)
5880 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
5882 if (!ctx->user_bufs)
5885 for (i = 0; i < nr_args; i++) {
5886 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5887 unsigned long off, start, end, ubuf;
5892 ret = io_copy_iov(ctx, &iov, arg, i);
5897 * Don't impose further limits on the size and buffer
5898 * constraints here, we'll -EINVAL later when IO is
5899 * submitted if they are wrong.
5902 if (!iov.iov_base || !iov.iov_len)
5905 /* arbitrary limit, but we need something */
5906 if (iov.iov_len > SZ_1G)
5909 ubuf = (unsigned long) iov.iov_base;
5910 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
5911 start = ubuf >> PAGE_SHIFT;
5912 nr_pages = end - start;
5914 if (ctx->account_mem) {
5915 ret = io_account_mem(ctx->user, nr_pages);
5921 if (!pages || nr_pages > got_pages) {
5924 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
5926 vmas = kvmalloc_array(nr_pages,
5927 sizeof(struct vm_area_struct *),
5929 if (!pages || !vmas) {
5931 if (ctx->account_mem)
5932 io_unaccount_mem(ctx->user, nr_pages);
5935 got_pages = nr_pages;
5938 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
5942 if (ctx->account_mem)
5943 io_unaccount_mem(ctx->user, nr_pages);
5948 down_read(¤t->mm->mmap_sem);
5949 pret = get_user_pages(ubuf, nr_pages,
5950 FOLL_WRITE | FOLL_LONGTERM,
5952 if (pret == nr_pages) {
5953 /* don't support file backed memory */
5954 for (j = 0; j < nr_pages; j++) {
5955 struct vm_area_struct *vma = vmas[j];
5958 !is_file_hugepages(vma->vm_file)) {
5964 ret = pret < 0 ? pret : -EFAULT;
5966 up_read(¤t->mm->mmap_sem);
5969 * if we did partial map, or found file backed vmas,
5970 * release any pages we did get
5973 put_user_pages(pages, pret);
5974 if (ctx->account_mem)
5975 io_unaccount_mem(ctx->user, nr_pages);
5980 off = ubuf & ~PAGE_MASK;
5982 for (j = 0; j < nr_pages; j++) {
5985 vec_len = min_t(size_t, size, PAGE_SIZE - off);
5986 imu->bvec[j].bv_page = pages[j];
5987 imu->bvec[j].bv_len = vec_len;
5988 imu->bvec[j].bv_offset = off;
5992 /* store original address for later verification */
5994 imu->len = iov.iov_len;
5995 imu->nr_bvecs = nr_pages;
5997 ctx->nr_user_bufs++;
6005 io_sqe_buffer_unregister(ctx);
6009 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6011 __s32 __user *fds = arg;
6017 if (copy_from_user(&fd, fds, sizeof(*fds)))
6020 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6021 if (IS_ERR(ctx->cq_ev_fd)) {
6022 int ret = PTR_ERR(ctx->cq_ev_fd);
6023 ctx->cq_ev_fd = NULL;
6030 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6032 if (ctx->cq_ev_fd) {
6033 eventfd_ctx_put(ctx->cq_ev_fd);
6034 ctx->cq_ev_fd = NULL;
6041 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6043 io_finish_async(ctx);
6045 mmdrop(ctx->sqo_mm);
6047 io_iopoll_reap_events(ctx);
6048 io_sqe_buffer_unregister(ctx);
6049 io_sqe_files_unregister(ctx);
6050 io_eventfd_unregister(ctx);
6052 #if defined(CONFIG_UNIX)
6053 if (ctx->ring_sock) {
6054 ctx->ring_sock->file = NULL; /* so that iput() is called */
6055 sock_release(ctx->ring_sock);
6059 io_mem_free(ctx->rings);
6060 io_mem_free(ctx->sq_sqes);
6062 percpu_ref_exit(&ctx->refs);
6063 if (ctx->account_mem)
6064 io_unaccount_mem(ctx->user,
6065 ring_pages(ctx->sq_entries, ctx->cq_entries));
6066 free_uid(ctx->user);
6067 put_cred(ctx->creds);
6068 kfree(ctx->completions);
6069 kfree(ctx->cancel_hash);
6070 kmem_cache_free(req_cachep, ctx->fallback_req);
6074 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6076 struct io_ring_ctx *ctx = file->private_data;
6079 poll_wait(file, &ctx->cq_wait, wait);
6081 * synchronizes with barrier from wq_has_sleeper call in
6085 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6086 ctx->rings->sq_ring_entries)
6087 mask |= EPOLLOUT | EPOLLWRNORM;
6088 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
6089 mask |= EPOLLIN | EPOLLRDNORM;
6094 static int io_uring_fasync(int fd, struct file *file, int on)
6096 struct io_ring_ctx *ctx = file->private_data;
6098 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6101 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6103 mutex_lock(&ctx->uring_lock);
6104 percpu_ref_kill(&ctx->refs);
6105 mutex_unlock(&ctx->uring_lock);
6107 io_kill_timeouts(ctx);
6108 io_poll_remove_all(ctx);
6111 io_wq_cancel_all(ctx->io_wq);
6113 io_iopoll_reap_events(ctx);
6114 /* if we failed setting up the ctx, we might not have any rings */
6116 io_cqring_overflow_flush(ctx, true);
6117 wait_for_completion(&ctx->completions[0]);
6118 io_ring_ctx_free(ctx);
6121 static int io_uring_release(struct inode *inode, struct file *file)
6123 struct io_ring_ctx *ctx = file->private_data;
6125 file->private_data = NULL;
6126 io_ring_ctx_wait_and_kill(ctx);
6130 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6131 struct files_struct *files)
6133 struct io_kiocb *req;
6136 while (!list_empty_careful(&ctx->inflight_list)) {
6137 struct io_kiocb *cancel_req = NULL;
6139 spin_lock_irq(&ctx->inflight_lock);
6140 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
6141 if (req->work.files != files)
6143 /* req is being completed, ignore */
6144 if (!refcount_inc_not_zero(&req->refs))
6150 prepare_to_wait(&ctx->inflight_wait, &wait,
6151 TASK_UNINTERRUPTIBLE);
6152 spin_unlock_irq(&ctx->inflight_lock);
6154 /* We need to keep going until we don't find a matching req */
6158 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6159 io_put_req(cancel_req);
6162 finish_wait(&ctx->inflight_wait, &wait);
6165 static int io_uring_flush(struct file *file, void *data)
6167 struct io_ring_ctx *ctx = file->private_data;
6169 io_uring_cancel_files(ctx, data);
6170 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
6171 io_cqring_overflow_flush(ctx, true);
6172 io_wq_cancel_all(ctx->io_wq);
6177 static void *io_uring_validate_mmap_request(struct file *file,
6178 loff_t pgoff, size_t sz)
6180 struct io_ring_ctx *ctx = file->private_data;
6181 loff_t offset = pgoff << PAGE_SHIFT;
6186 case IORING_OFF_SQ_RING:
6187 case IORING_OFF_CQ_RING:
6190 case IORING_OFF_SQES:
6194 return ERR_PTR(-EINVAL);
6197 page = virt_to_head_page(ptr);
6198 if (sz > page_size(page))
6199 return ERR_PTR(-EINVAL);
6206 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6208 size_t sz = vma->vm_end - vma->vm_start;
6212 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6214 return PTR_ERR(ptr);
6216 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6217 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6220 #else /* !CONFIG_MMU */
6222 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6224 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6227 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6229 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6232 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6233 unsigned long addr, unsigned long len,
6234 unsigned long pgoff, unsigned long flags)
6238 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6240 return PTR_ERR(ptr);
6242 return (unsigned long) ptr;
6245 #endif /* !CONFIG_MMU */
6247 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6248 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6251 struct io_ring_ctx *ctx;
6256 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
6264 if (f.file->f_op != &io_uring_fops)
6268 ctx = f.file->private_data;
6269 if (!percpu_ref_tryget(&ctx->refs))
6273 * For SQ polling, the thread will do all submissions and completions.
6274 * Just return the requested submit count, and wake the thread if
6278 if (ctx->flags & IORING_SETUP_SQPOLL) {
6279 if (!list_empty_careful(&ctx->cq_overflow_list))
6280 io_cqring_overflow_flush(ctx, false);
6281 if (flags & IORING_ENTER_SQ_WAKEUP)
6282 wake_up(&ctx->sqo_wait);
6283 submitted = to_submit;
6284 } else if (to_submit) {
6285 struct mm_struct *cur_mm;
6287 if (current->mm != ctx->sqo_mm ||
6288 current_cred() != ctx->creds) {
6293 mutex_lock(&ctx->uring_lock);
6294 /* already have mm, so io_submit_sqes() won't try to grab it */
6295 cur_mm = ctx->sqo_mm;
6296 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6298 mutex_unlock(&ctx->uring_lock);
6300 if (submitted != to_submit)
6303 if (flags & IORING_ENTER_GETEVENTS) {
6304 unsigned nr_events = 0;
6306 min_complete = min(min_complete, ctx->cq_entries);
6308 if (ctx->flags & IORING_SETUP_IOPOLL) {
6309 ret = io_iopoll_check(ctx, &nr_events, min_complete);
6311 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6316 percpu_ref_put(&ctx->refs);
6319 return submitted ? submitted : ret;
6322 static const struct file_operations io_uring_fops = {
6323 .release = io_uring_release,
6324 .flush = io_uring_flush,
6325 .mmap = io_uring_mmap,
6327 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6328 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6330 .poll = io_uring_poll,
6331 .fasync = io_uring_fasync,
6334 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6335 struct io_uring_params *p)
6337 struct io_rings *rings;
6338 size_t size, sq_array_offset;
6340 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6341 if (size == SIZE_MAX)
6344 rings = io_mem_alloc(size);
6349 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6350 rings->sq_ring_mask = p->sq_entries - 1;
6351 rings->cq_ring_mask = p->cq_entries - 1;
6352 rings->sq_ring_entries = p->sq_entries;
6353 rings->cq_ring_entries = p->cq_entries;
6354 ctx->sq_mask = rings->sq_ring_mask;
6355 ctx->cq_mask = rings->cq_ring_mask;
6356 ctx->sq_entries = rings->sq_ring_entries;
6357 ctx->cq_entries = rings->cq_ring_entries;
6359 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6360 if (size == SIZE_MAX) {
6361 io_mem_free(ctx->rings);
6366 ctx->sq_sqes = io_mem_alloc(size);
6367 if (!ctx->sq_sqes) {
6368 io_mem_free(ctx->rings);
6377 * Allocate an anonymous fd, this is what constitutes the application
6378 * visible backing of an io_uring instance. The application mmaps this
6379 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6380 * we have to tie this fd to a socket for file garbage collection purposes.
6382 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6387 #if defined(CONFIG_UNIX)
6388 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6394 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6398 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6399 O_RDWR | O_CLOEXEC);
6402 ret = PTR_ERR(file);
6406 #if defined(CONFIG_UNIX)
6407 ctx->ring_sock->file = file;
6409 fd_install(ret, file);
6412 #if defined(CONFIG_UNIX)
6413 sock_release(ctx->ring_sock);
6414 ctx->ring_sock = NULL;
6419 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6421 struct user_struct *user = NULL;
6422 struct io_ring_ctx *ctx;
6428 if (entries > IORING_MAX_ENTRIES) {
6429 if (!(p->flags & IORING_SETUP_CLAMP))
6431 entries = IORING_MAX_ENTRIES;
6435 * Use twice as many entries for the CQ ring. It's possible for the
6436 * application to drive a higher depth than the size of the SQ ring,
6437 * since the sqes are only used at submission time. This allows for
6438 * some flexibility in overcommitting a bit. If the application has
6439 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6440 * of CQ ring entries manually.
6442 p->sq_entries = roundup_pow_of_two(entries);
6443 if (p->flags & IORING_SETUP_CQSIZE) {
6445 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6446 * to a power-of-two, if it isn't already. We do NOT impose
6447 * any cq vs sq ring sizing.
6449 if (p->cq_entries < p->sq_entries)
6451 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6452 if (!(p->flags & IORING_SETUP_CLAMP))
6454 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6456 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6458 p->cq_entries = 2 * p->sq_entries;
6461 user = get_uid(current_user());
6462 account_mem = !capable(CAP_IPC_LOCK);
6465 ret = io_account_mem(user,
6466 ring_pages(p->sq_entries, p->cq_entries));
6473 ctx = io_ring_ctx_alloc(p);
6476 io_unaccount_mem(user, ring_pages(p->sq_entries,
6481 ctx->compat = in_compat_syscall();
6482 ctx->account_mem = account_mem;
6484 ctx->creds = get_current_cred();
6486 ret = io_allocate_scq_urings(ctx, p);
6490 ret = io_sq_offload_start(ctx, p);
6494 memset(&p->sq_off, 0, sizeof(p->sq_off));
6495 p->sq_off.head = offsetof(struct io_rings, sq.head);
6496 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6497 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6498 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6499 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6500 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6501 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6503 memset(&p->cq_off, 0, sizeof(p->cq_off));
6504 p->cq_off.head = offsetof(struct io_rings, cq.head);
6505 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6506 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6507 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6508 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6509 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6512 * Install ring fd as the very last thing, so we don't risk someone
6513 * having closed it before we finish setup
6515 ret = io_uring_get_fd(ctx);
6519 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6520 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS;
6521 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6524 io_ring_ctx_wait_and_kill(ctx);
6529 * Sets up an aio uring context, and returns the fd. Applications asks for a
6530 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6531 * params structure passed in.
6533 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6535 struct io_uring_params p;
6539 if (copy_from_user(&p, params, sizeof(p)))
6541 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6546 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6547 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6548 IORING_SETUP_CLAMP))
6551 ret = io_uring_create(entries, &p);
6555 if (copy_to_user(params, &p, sizeof(p)))
6561 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6562 struct io_uring_params __user *, params)
6564 return io_uring_setup(entries, params);
6567 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6569 struct io_uring_probe *p;
6573 size = struct_size(p, ops, nr_args);
6574 if (size == SIZE_MAX)
6576 p = kzalloc(size, GFP_KERNEL);
6581 if (copy_from_user(p, arg, size))
6584 if (memchr_inv(p, 0, size))
6587 p->last_op = IORING_OP_LAST - 1;
6588 if (nr_args > IORING_OP_LAST)
6589 nr_args = IORING_OP_LAST;
6591 for (i = 0; i < nr_args; i++) {
6593 if (!io_op_defs[i].not_supported)
6594 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6599 if (copy_to_user(arg, p, size))
6606 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6607 void __user *arg, unsigned nr_args)
6608 __releases(ctx->uring_lock)
6609 __acquires(ctx->uring_lock)
6614 * We're inside the ring mutex, if the ref is already dying, then
6615 * someone else killed the ctx or is already going through
6616 * io_uring_register().
6618 if (percpu_ref_is_dying(&ctx->refs))
6621 if (opcode != IORING_UNREGISTER_FILES &&
6622 opcode != IORING_REGISTER_FILES_UPDATE &&
6623 opcode != IORING_REGISTER_PROBE) {
6624 percpu_ref_kill(&ctx->refs);
6627 * Drop uring mutex before waiting for references to exit. If
6628 * another thread is currently inside io_uring_enter() it might
6629 * need to grab the uring_lock to make progress. If we hold it
6630 * here across the drain wait, then we can deadlock. It's safe
6631 * to drop the mutex here, since no new references will come in
6632 * after we've killed the percpu ref.
6634 mutex_unlock(&ctx->uring_lock);
6635 ret = wait_for_completion_interruptible(&ctx->completions[0]);
6636 mutex_lock(&ctx->uring_lock);
6638 percpu_ref_resurrect(&ctx->refs);
6645 case IORING_REGISTER_BUFFERS:
6646 ret = io_sqe_buffer_register(ctx, arg, nr_args);
6648 case IORING_UNREGISTER_BUFFERS:
6652 ret = io_sqe_buffer_unregister(ctx);
6654 case IORING_REGISTER_FILES:
6655 ret = io_sqe_files_register(ctx, arg, nr_args);
6657 case IORING_UNREGISTER_FILES:
6661 ret = io_sqe_files_unregister(ctx);
6663 case IORING_REGISTER_FILES_UPDATE:
6664 ret = io_sqe_files_update(ctx, arg, nr_args);
6666 case IORING_REGISTER_EVENTFD:
6667 case IORING_REGISTER_EVENTFD_ASYNC:
6671 ret = io_eventfd_register(ctx, arg);
6674 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
6675 ctx->eventfd_async = 1;
6677 ctx->eventfd_async = 0;
6679 case IORING_UNREGISTER_EVENTFD:
6683 ret = io_eventfd_unregister(ctx);
6685 case IORING_REGISTER_PROBE:
6687 if (!arg || nr_args > 256)
6689 ret = io_probe(ctx, arg, nr_args);
6697 if (opcode != IORING_UNREGISTER_FILES &&
6698 opcode != IORING_REGISTER_FILES_UPDATE &&
6699 opcode != IORING_REGISTER_PROBE) {
6700 /* bring the ctx back to life */
6701 percpu_ref_reinit(&ctx->refs);
6703 reinit_completion(&ctx->completions[0]);
6708 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
6709 void __user *, arg, unsigned int, nr_args)
6711 struct io_ring_ctx *ctx;
6720 if (f.file->f_op != &io_uring_fops)
6723 ctx = f.file->private_data;
6725 mutex_lock(&ctx->uring_lock);
6726 ret = __io_uring_register(ctx, opcode, arg, nr_args);
6727 mutex_unlock(&ctx->uring_lock);
6728 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
6729 ctx->cq_ev_fd != NULL, ret);
6735 static int __init io_uring_init(void)
6737 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
6738 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
6741 __initcall(io_uring_init);