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_IO_DRAINED 32 /* drain done */
503 #define REQ_F_LINK 64 /* linked sqes */
504 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
505 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
506 #define REQ_F_TIMEOUT 1024 /* timeout request */
507 #define REQ_F_ISREG 2048 /* regular file */
508 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
509 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
510 #define REQ_F_INFLIGHT 16384 /* on inflight list */
511 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
512 #define REQ_F_HARDLINK 65536 /* doesn't sever on completion < 0 */
513 #define REQ_F_FORCE_ASYNC 131072 /* IOSQE_ASYNC */
514 #define REQ_F_CUR_POS 262144 /* read/write uses file position */
519 struct list_head inflight_entry;
521 struct io_wq_work work;
524 #define IO_PLUG_THRESHOLD 2
525 #define IO_IOPOLL_BATCH 8
527 struct io_submit_state {
528 struct blk_plug plug;
531 * io_kiocb alloc cache
533 void *reqs[IO_IOPOLL_BATCH];
534 unsigned int free_reqs;
535 unsigned int cur_req;
538 * File reference cache
542 unsigned int has_refs;
543 unsigned int used_refs;
544 unsigned int ios_left;
548 /* needs req->io allocated for deferral/async */
549 unsigned async_ctx : 1;
550 /* needs current->mm setup, does mm access */
551 unsigned needs_mm : 1;
552 /* needs req->file assigned */
553 unsigned needs_file : 1;
554 /* needs req->file assigned IFF fd is >= 0 */
555 unsigned fd_non_neg : 1;
556 /* hash wq insertion if file is a regular file */
557 unsigned hash_reg_file : 1;
558 /* unbound wq insertion if file is a non-regular file */
559 unsigned unbound_nonreg_file : 1;
560 /* opcode is not supported by this kernel */
561 unsigned not_supported : 1;
564 static const struct io_op_def io_op_defs[] = {
569 /* IORING_OP_READV */
573 .unbound_nonreg_file = 1,
576 /* IORING_OP_WRITEV */
581 .unbound_nonreg_file = 1,
584 /* IORING_OP_FSYNC */
588 /* IORING_OP_READ_FIXED */
590 .unbound_nonreg_file = 1,
593 /* IORING_OP_WRITE_FIXED */
596 .unbound_nonreg_file = 1,
599 /* IORING_OP_POLL_ADD */
601 .unbound_nonreg_file = 1,
604 /* IORING_OP_POLL_REMOVE */
607 /* IORING_OP_SYNC_FILE_RANGE */
611 /* IORING_OP_SENDMSG */
615 .unbound_nonreg_file = 1,
618 /* IORING_OP_RECVMSG */
622 .unbound_nonreg_file = 1,
625 /* IORING_OP_TIMEOUT */
630 /* IORING_OP_TIMEOUT_REMOVE */
633 /* IORING_OP_ACCEPT */
636 .unbound_nonreg_file = 1,
639 /* IORING_OP_ASYNC_CANCEL */
642 /* IORING_OP_LINK_TIMEOUT */
647 /* IORING_OP_CONNECT */
651 .unbound_nonreg_file = 1,
654 /* IORING_OP_FALLOCATE */
658 /* IORING_OP_OPENAT */
663 /* IORING_OP_CLOSE */
667 /* IORING_OP_FILES_UPDATE */
671 /* IORING_OP_STATX */
680 .unbound_nonreg_file = 1,
683 /* IORING_OP_WRITE */
686 .unbound_nonreg_file = 1,
689 /* IORING_OP_FADVISE */
693 /* IORING_OP_MADVISE */
700 .unbound_nonreg_file = 1,
706 .unbound_nonreg_file = 1,
709 /* IORING_OP_OPENAT2 */
715 static void io_wq_submit_work(struct io_wq_work **workptr);
716 static void io_cqring_fill_event(struct io_kiocb *req, long res);
717 static void io_put_req(struct io_kiocb *req);
718 static void __io_double_put_req(struct io_kiocb *req);
719 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
720 static void io_queue_linked_timeout(struct io_kiocb *req);
721 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
722 struct io_uring_files_update *ip,
725 static struct kmem_cache *req_cachep;
727 static const struct file_operations io_uring_fops;
729 struct sock *io_uring_get_socket(struct file *file)
731 #if defined(CONFIG_UNIX)
732 if (file->f_op == &io_uring_fops) {
733 struct io_ring_ctx *ctx = file->private_data;
735 return ctx->ring_sock->sk;
740 EXPORT_SYMBOL(io_uring_get_socket);
742 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
744 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
746 complete(&ctx->completions[0]);
749 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
751 struct io_ring_ctx *ctx;
754 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
758 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
759 if (!ctx->fallback_req)
762 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
763 if (!ctx->completions)
767 * Use 5 bits less than the max cq entries, that should give us around
768 * 32 entries per hash list if totally full and uniformly spread.
770 hash_bits = ilog2(p->cq_entries);
774 ctx->cancel_hash_bits = hash_bits;
775 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
777 if (!ctx->cancel_hash)
779 __hash_init(ctx->cancel_hash, 1U << hash_bits);
781 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
782 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
785 ctx->flags = p->flags;
786 init_waitqueue_head(&ctx->cq_wait);
787 INIT_LIST_HEAD(&ctx->cq_overflow_list);
788 init_completion(&ctx->completions[0]);
789 init_completion(&ctx->completions[1]);
790 mutex_init(&ctx->uring_lock);
791 init_waitqueue_head(&ctx->wait);
792 spin_lock_init(&ctx->completion_lock);
793 init_llist_head(&ctx->poll_llist);
794 INIT_LIST_HEAD(&ctx->poll_list);
795 INIT_LIST_HEAD(&ctx->defer_list);
796 INIT_LIST_HEAD(&ctx->timeout_list);
797 init_waitqueue_head(&ctx->inflight_wait);
798 spin_lock_init(&ctx->inflight_lock);
799 INIT_LIST_HEAD(&ctx->inflight_list);
802 if (ctx->fallback_req)
803 kmem_cache_free(req_cachep, ctx->fallback_req);
804 kfree(ctx->completions);
805 kfree(ctx->cancel_hash);
810 static inline bool __req_need_defer(struct io_kiocb *req)
812 struct io_ring_ctx *ctx = req->ctx;
814 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
815 + atomic_read(&ctx->cached_cq_overflow);
818 static inline bool req_need_defer(struct io_kiocb *req)
820 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
821 return __req_need_defer(req);
826 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
828 struct io_kiocb *req;
830 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
831 if (req && !req_need_defer(req)) {
832 list_del_init(&req->list);
839 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
841 struct io_kiocb *req;
843 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
845 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
847 if (!__req_need_defer(req)) {
848 list_del_init(&req->list);
856 static void __io_commit_cqring(struct io_ring_ctx *ctx)
858 struct io_rings *rings = ctx->rings;
860 /* order cqe stores with ring update */
861 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
863 if (wq_has_sleeper(&ctx->cq_wait)) {
864 wake_up_interruptible(&ctx->cq_wait);
865 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
869 static inline bool io_prep_async_work(struct io_kiocb *req,
870 struct io_kiocb **link)
872 const struct io_op_def *def = &io_op_defs[req->opcode];
873 bool do_hashed = false;
875 if (req->flags & REQ_F_ISREG) {
876 if (def->hash_reg_file)
879 if (def->unbound_nonreg_file)
880 req->work.flags |= IO_WQ_WORK_UNBOUND;
883 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
885 *link = io_prep_linked_timeout(req);
889 static inline void io_queue_async_work(struct io_kiocb *req)
891 struct io_ring_ctx *ctx = req->ctx;
892 struct io_kiocb *link;
895 do_hashed = io_prep_async_work(req, &link);
897 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
900 io_wq_enqueue(ctx->io_wq, &req->work);
902 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
903 file_inode(req->file));
907 io_queue_linked_timeout(link);
910 static void io_kill_timeout(struct io_kiocb *req)
914 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
916 atomic_inc(&req->ctx->cq_timeouts);
917 list_del_init(&req->list);
918 io_cqring_fill_event(req, 0);
923 static void io_kill_timeouts(struct io_ring_ctx *ctx)
925 struct io_kiocb *req, *tmp;
927 spin_lock_irq(&ctx->completion_lock);
928 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
929 io_kill_timeout(req);
930 spin_unlock_irq(&ctx->completion_lock);
933 static void io_commit_cqring(struct io_ring_ctx *ctx)
935 struct io_kiocb *req;
937 while ((req = io_get_timeout_req(ctx)) != NULL)
938 io_kill_timeout(req);
940 __io_commit_cqring(ctx);
942 while ((req = io_get_deferred_req(ctx)) != NULL) {
943 req->flags |= REQ_F_IO_DRAINED;
944 io_queue_async_work(req);
948 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
950 struct io_rings *rings = ctx->rings;
953 tail = ctx->cached_cq_tail;
955 * writes to the cq entry need to come after reading head; the
956 * control dependency is enough as we're using WRITE_ONCE to
959 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
962 ctx->cached_cq_tail++;
963 return &rings->cqes[tail & ctx->cq_mask];
966 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
968 if (!ctx->eventfd_async)
970 return io_wq_current_is_worker() || in_interrupt();
973 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
975 if (waitqueue_active(&ctx->wait))
977 if (waitqueue_active(&ctx->sqo_wait))
978 wake_up(&ctx->sqo_wait);
979 if (ctx->cq_ev_fd && io_should_trigger_evfd(ctx))
980 eventfd_signal(ctx->cq_ev_fd, 1);
983 /* Returns true if there are no backlogged entries after the flush */
984 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
986 struct io_rings *rings = ctx->rings;
987 struct io_uring_cqe *cqe;
988 struct io_kiocb *req;
993 if (list_empty_careful(&ctx->cq_overflow_list))
995 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
996 rings->cq_ring_entries))
1000 spin_lock_irqsave(&ctx->completion_lock, flags);
1002 /* if force is set, the ring is going away. always drop after that */
1004 ctx->cq_overflow_flushed = 1;
1007 while (!list_empty(&ctx->cq_overflow_list)) {
1008 cqe = io_get_cqring(ctx);
1012 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1014 list_move(&req->list, &list);
1016 WRITE_ONCE(cqe->user_data, req->user_data);
1017 WRITE_ONCE(cqe->res, req->result);
1018 WRITE_ONCE(cqe->flags, 0);
1020 WRITE_ONCE(ctx->rings->cq_overflow,
1021 atomic_inc_return(&ctx->cached_cq_overflow));
1025 io_commit_cqring(ctx);
1027 clear_bit(0, &ctx->sq_check_overflow);
1028 clear_bit(0, &ctx->cq_check_overflow);
1030 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1031 io_cqring_ev_posted(ctx);
1033 while (!list_empty(&list)) {
1034 req = list_first_entry(&list, struct io_kiocb, list);
1035 list_del(&req->list);
1042 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1044 struct io_ring_ctx *ctx = req->ctx;
1045 struct io_uring_cqe *cqe;
1047 trace_io_uring_complete(ctx, req->user_data, res);
1050 * If we can't get a cq entry, userspace overflowed the
1051 * submission (by quite a lot). Increment the overflow count in
1054 cqe = io_get_cqring(ctx);
1056 WRITE_ONCE(cqe->user_data, req->user_data);
1057 WRITE_ONCE(cqe->res, res);
1058 WRITE_ONCE(cqe->flags, 0);
1059 } else if (ctx->cq_overflow_flushed) {
1060 WRITE_ONCE(ctx->rings->cq_overflow,
1061 atomic_inc_return(&ctx->cached_cq_overflow));
1063 if (list_empty(&ctx->cq_overflow_list)) {
1064 set_bit(0, &ctx->sq_check_overflow);
1065 set_bit(0, &ctx->cq_check_overflow);
1067 refcount_inc(&req->refs);
1069 list_add_tail(&req->list, &ctx->cq_overflow_list);
1073 static void io_cqring_add_event(struct io_kiocb *req, long res)
1075 struct io_ring_ctx *ctx = req->ctx;
1076 unsigned long flags;
1078 spin_lock_irqsave(&ctx->completion_lock, flags);
1079 io_cqring_fill_event(req, res);
1080 io_commit_cqring(ctx);
1081 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1083 io_cqring_ev_posted(ctx);
1086 static inline bool io_is_fallback_req(struct io_kiocb *req)
1088 return req == (struct io_kiocb *)
1089 ((unsigned long) req->ctx->fallback_req & ~1UL);
1092 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1094 struct io_kiocb *req;
1096 req = ctx->fallback_req;
1097 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1103 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1104 struct io_submit_state *state)
1106 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1107 struct io_kiocb *req;
1110 req = kmem_cache_alloc(req_cachep, gfp);
1113 } else if (!state->free_reqs) {
1117 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1118 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1121 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1122 * retry single alloc to be on the safe side.
1124 if (unlikely(ret <= 0)) {
1125 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1126 if (!state->reqs[0])
1130 state->free_reqs = ret - 1;
1132 req = state->reqs[0];
1134 req = state->reqs[state->cur_req];
1144 /* one is dropped after submission, the other at completion */
1145 refcount_set(&req->refs, 2);
1147 INIT_IO_WORK(&req->work, io_wq_submit_work);
1150 req = io_get_fallback_req(ctx);
1153 percpu_ref_put(&ctx->refs);
1157 static void __io_req_do_free(struct io_kiocb *req)
1159 if (likely(!io_is_fallback_req(req)))
1160 kmem_cache_free(req_cachep, req);
1162 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1165 static void __io_req_aux_free(struct io_kiocb *req)
1167 struct io_ring_ctx *ctx = req->ctx;
1171 if (req->flags & REQ_F_FIXED_FILE)
1172 percpu_ref_put(&ctx->file_data->refs);
1178 static void __io_free_req(struct io_kiocb *req)
1180 __io_req_aux_free(req);
1182 if (req->flags & REQ_F_INFLIGHT) {
1183 struct io_ring_ctx *ctx = req->ctx;
1184 unsigned long flags;
1186 spin_lock_irqsave(&ctx->inflight_lock, flags);
1187 list_del(&req->inflight_entry);
1188 if (waitqueue_active(&ctx->inflight_wait))
1189 wake_up(&ctx->inflight_wait);
1190 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1193 percpu_ref_put(&req->ctx->refs);
1194 __io_req_do_free(req);
1198 void *reqs[IO_IOPOLL_BATCH];
1203 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1205 int fixed_refs = rb->to_free;
1209 if (rb->need_iter) {
1210 int i, inflight = 0;
1211 unsigned long flags;
1214 for (i = 0; i < rb->to_free; i++) {
1215 struct io_kiocb *req = rb->reqs[i];
1217 if (req->flags & REQ_F_FIXED_FILE) {
1221 if (req->flags & REQ_F_INFLIGHT)
1223 __io_req_aux_free(req);
1228 spin_lock_irqsave(&ctx->inflight_lock, flags);
1229 for (i = 0; i < rb->to_free; i++) {
1230 struct io_kiocb *req = rb->reqs[i];
1232 if (req->flags & REQ_F_INFLIGHT) {
1233 list_del(&req->inflight_entry);
1238 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1240 if (waitqueue_active(&ctx->inflight_wait))
1241 wake_up(&ctx->inflight_wait);
1244 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1246 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1247 percpu_ref_put_many(&ctx->refs, rb->to_free);
1248 rb->to_free = rb->need_iter = 0;
1251 static bool io_link_cancel_timeout(struct io_kiocb *req)
1253 struct io_ring_ctx *ctx = req->ctx;
1256 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1258 io_cqring_fill_event(req, -ECANCELED);
1259 io_commit_cqring(ctx);
1260 req->flags &= ~REQ_F_LINK;
1268 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1270 struct io_ring_ctx *ctx = req->ctx;
1271 bool wake_ev = false;
1273 /* Already got next link */
1274 if (req->flags & REQ_F_LINK_NEXT)
1278 * The list should never be empty when we are called here. But could
1279 * potentially happen if the chain is messed up, check to be on the
1282 while (!list_empty(&req->link_list)) {
1283 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1284 struct io_kiocb, link_list);
1286 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1287 (nxt->flags & REQ_F_TIMEOUT))) {
1288 list_del_init(&nxt->link_list);
1289 wake_ev |= io_link_cancel_timeout(nxt);
1290 req->flags &= ~REQ_F_LINK_TIMEOUT;
1294 list_del_init(&req->link_list);
1295 if (!list_empty(&nxt->link_list))
1296 nxt->flags |= REQ_F_LINK;
1301 req->flags |= REQ_F_LINK_NEXT;
1303 io_cqring_ev_posted(ctx);
1307 * Called if REQ_F_LINK is set, and we fail the head request
1309 static void io_fail_links(struct io_kiocb *req)
1311 struct io_ring_ctx *ctx = req->ctx;
1312 unsigned long flags;
1314 spin_lock_irqsave(&ctx->completion_lock, flags);
1316 while (!list_empty(&req->link_list)) {
1317 struct io_kiocb *link = list_first_entry(&req->link_list,
1318 struct io_kiocb, link_list);
1320 list_del_init(&link->link_list);
1321 trace_io_uring_fail_link(req, link);
1323 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1324 link->opcode == IORING_OP_LINK_TIMEOUT) {
1325 io_link_cancel_timeout(link);
1327 io_cqring_fill_event(link, -ECANCELED);
1328 __io_double_put_req(link);
1330 req->flags &= ~REQ_F_LINK_TIMEOUT;
1333 io_commit_cqring(ctx);
1334 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1335 io_cqring_ev_posted(ctx);
1338 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1340 if (likely(!(req->flags & REQ_F_LINK)))
1344 * If LINK is set, we have dependent requests in this chain. If we
1345 * didn't fail this request, queue the first one up, moving any other
1346 * dependencies to the next request. In case of failure, fail the rest
1349 if (req->flags & REQ_F_FAIL_LINK) {
1351 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1352 REQ_F_LINK_TIMEOUT) {
1353 struct io_ring_ctx *ctx = req->ctx;
1354 unsigned long flags;
1357 * If this is a timeout link, we could be racing with the
1358 * timeout timer. Grab the completion lock for this case to
1359 * protect against that.
1361 spin_lock_irqsave(&ctx->completion_lock, flags);
1362 io_req_link_next(req, nxt);
1363 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1365 io_req_link_next(req, nxt);
1369 static void io_free_req(struct io_kiocb *req)
1371 struct io_kiocb *nxt = NULL;
1373 io_req_find_next(req, &nxt);
1377 io_queue_async_work(nxt);
1381 * Drop reference to request, return next in chain (if there is one) if this
1382 * was the last reference to this request.
1384 __attribute__((nonnull))
1385 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1387 io_req_find_next(req, nxtptr);
1389 if (refcount_dec_and_test(&req->refs))
1393 static void io_put_req(struct io_kiocb *req)
1395 if (refcount_dec_and_test(&req->refs))
1400 * Must only be used if we don't need to care about links, usually from
1401 * within the completion handling itself.
1403 static void __io_double_put_req(struct io_kiocb *req)
1405 /* drop both submit and complete references */
1406 if (refcount_sub_and_test(2, &req->refs))
1410 static void io_double_put_req(struct io_kiocb *req)
1412 /* drop both submit and complete references */
1413 if (refcount_sub_and_test(2, &req->refs))
1417 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1419 struct io_rings *rings = ctx->rings;
1421 if (test_bit(0, &ctx->cq_check_overflow)) {
1423 * noflush == true is from the waitqueue handler, just ensure
1424 * we wake up the task, and the next invocation will flush the
1425 * entries. We cannot safely to it from here.
1427 if (noflush && !list_empty(&ctx->cq_overflow_list))
1430 io_cqring_overflow_flush(ctx, false);
1433 /* See comment at the top of this file */
1435 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1438 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1440 struct io_rings *rings = ctx->rings;
1442 /* make sure SQ entry isn't read before tail */
1443 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1446 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1448 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1451 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1454 rb->reqs[rb->to_free++] = req;
1455 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1456 io_free_req_many(req->ctx, rb);
1461 * Find and free completed poll iocbs
1463 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1464 struct list_head *done)
1466 struct req_batch rb;
1467 struct io_kiocb *req;
1469 rb.to_free = rb.need_iter = 0;
1470 while (!list_empty(done)) {
1471 req = list_first_entry(done, struct io_kiocb, list);
1472 list_del(&req->list);
1474 io_cqring_fill_event(req, req->result);
1477 if (refcount_dec_and_test(&req->refs) &&
1478 !io_req_multi_free(&rb, req))
1482 io_commit_cqring(ctx);
1483 io_free_req_many(ctx, &rb);
1486 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1489 struct io_kiocb *req, *tmp;
1495 * Only spin for completions if we don't have multiple devices hanging
1496 * off our complete list, and we're under the requested amount.
1498 spin = !ctx->poll_multi_file && *nr_events < min;
1501 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1502 struct kiocb *kiocb = &req->rw.kiocb;
1505 * Move completed entries to our local list. If we find a
1506 * request that requires polling, break out and complete
1507 * the done list first, if we have entries there.
1509 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1510 list_move_tail(&req->list, &done);
1513 if (!list_empty(&done))
1516 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1525 if (!list_empty(&done))
1526 io_iopoll_complete(ctx, nr_events, &done);
1532 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1533 * non-spinning poll check - we'll still enter the driver poll loop, but only
1534 * as a non-spinning completion check.
1536 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1539 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1542 ret = io_do_iopoll(ctx, nr_events, min);
1545 if (!min || *nr_events >= min)
1553 * We can't just wait for polled events to come to us, we have to actively
1554 * find and complete them.
1556 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1558 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1561 mutex_lock(&ctx->uring_lock);
1562 while (!list_empty(&ctx->poll_list)) {
1563 unsigned int nr_events = 0;
1565 io_iopoll_getevents(ctx, &nr_events, 1);
1568 * Ensure we allow local-to-the-cpu processing to take place,
1569 * in this case we need to ensure that we reap all events.
1573 mutex_unlock(&ctx->uring_lock);
1576 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1579 int iters = 0, ret = 0;
1585 * Don't enter poll loop if we already have events pending.
1586 * If we do, we can potentially be spinning for commands that
1587 * already triggered a CQE (eg in error).
1589 if (io_cqring_events(ctx, false))
1593 * If a submit got punted to a workqueue, we can have the
1594 * application entering polling for a command before it gets
1595 * issued. That app will hold the uring_lock for the duration
1596 * of the poll right here, so we need to take a breather every
1597 * now and then to ensure that the issue has a chance to add
1598 * the poll to the issued list. Otherwise we can spin here
1599 * forever, while the workqueue is stuck trying to acquire the
1602 if (!(++iters & 7)) {
1603 mutex_unlock(&ctx->uring_lock);
1604 mutex_lock(&ctx->uring_lock);
1607 if (*nr_events < min)
1608 tmin = min - *nr_events;
1610 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1614 } while (min && !*nr_events && !need_resched());
1619 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1625 * We disallow the app entering submit/complete with polling, but we
1626 * still need to lock the ring to prevent racing with polled issue
1627 * that got punted to a workqueue.
1629 mutex_lock(&ctx->uring_lock);
1630 ret = __io_iopoll_check(ctx, nr_events, min);
1631 mutex_unlock(&ctx->uring_lock);
1635 static void kiocb_end_write(struct io_kiocb *req)
1638 * Tell lockdep we inherited freeze protection from submission
1641 if (req->flags & REQ_F_ISREG) {
1642 struct inode *inode = file_inode(req->file);
1644 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1646 file_end_write(req->file);
1649 static inline void req_set_fail_links(struct io_kiocb *req)
1651 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1652 req->flags |= REQ_F_FAIL_LINK;
1655 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1657 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1659 if (kiocb->ki_flags & IOCB_WRITE)
1660 kiocb_end_write(req);
1662 if (res != req->result)
1663 req_set_fail_links(req);
1664 io_cqring_add_event(req, res);
1667 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1669 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1671 io_complete_rw_common(kiocb, res);
1675 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1677 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1678 struct io_kiocb *nxt = NULL;
1680 io_complete_rw_common(kiocb, res);
1681 io_put_req_find_next(req, &nxt);
1686 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1688 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1690 if (kiocb->ki_flags & IOCB_WRITE)
1691 kiocb_end_write(req);
1693 if (res != req->result)
1694 req_set_fail_links(req);
1697 req->flags |= REQ_F_IOPOLL_COMPLETED;
1701 * After the iocb has been issued, it's safe to be found on the poll list.
1702 * Adding the kiocb to the list AFTER submission ensures that we don't
1703 * find it from a io_iopoll_getevents() thread before the issuer is done
1704 * accessing the kiocb cookie.
1706 static void io_iopoll_req_issued(struct io_kiocb *req)
1708 struct io_ring_ctx *ctx = req->ctx;
1711 * Track whether we have multiple files in our lists. This will impact
1712 * how we do polling eventually, not spinning if we're on potentially
1713 * different devices.
1715 if (list_empty(&ctx->poll_list)) {
1716 ctx->poll_multi_file = false;
1717 } else if (!ctx->poll_multi_file) {
1718 struct io_kiocb *list_req;
1720 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1722 if (list_req->file != req->file)
1723 ctx->poll_multi_file = true;
1727 * For fast devices, IO may have already completed. If it has, add
1728 * it to the front so we find it first.
1730 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1731 list_add(&req->list, &ctx->poll_list);
1733 list_add_tail(&req->list, &ctx->poll_list);
1736 static void io_file_put(struct io_submit_state *state)
1739 int diff = state->has_refs - state->used_refs;
1742 fput_many(state->file, diff);
1748 * Get as many references to a file as we have IOs left in this submission,
1749 * assuming most submissions are for one file, or at least that each file
1750 * has more than one submission.
1752 static struct file *io_file_get(struct io_submit_state *state, int fd)
1758 if (state->fd == fd) {
1765 state->file = fget_many(fd, state->ios_left);
1770 state->has_refs = state->ios_left;
1771 state->used_refs = 1;
1777 * If we tracked the file through the SCM inflight mechanism, we could support
1778 * any file. For now, just ensure that anything potentially problematic is done
1781 static bool io_file_supports_async(struct file *file)
1783 umode_t mode = file_inode(file)->i_mode;
1785 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1787 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1793 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1794 bool force_nonblock)
1796 struct io_ring_ctx *ctx = req->ctx;
1797 struct kiocb *kiocb = &req->rw.kiocb;
1804 if (S_ISREG(file_inode(req->file)->i_mode))
1805 req->flags |= REQ_F_ISREG;
1807 kiocb->ki_pos = READ_ONCE(sqe->off);
1808 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1809 req->flags |= REQ_F_CUR_POS;
1810 kiocb->ki_pos = req->file->f_pos;
1812 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1813 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1815 ioprio = READ_ONCE(sqe->ioprio);
1817 ret = ioprio_check_cap(ioprio);
1821 kiocb->ki_ioprio = ioprio;
1823 kiocb->ki_ioprio = get_current_ioprio();
1825 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1829 /* don't allow async punt if RWF_NOWAIT was requested */
1830 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1831 (req->file->f_flags & O_NONBLOCK))
1832 req->flags |= REQ_F_NOWAIT;
1835 kiocb->ki_flags |= IOCB_NOWAIT;
1837 if (ctx->flags & IORING_SETUP_IOPOLL) {
1838 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1839 !kiocb->ki_filp->f_op->iopoll)
1842 kiocb->ki_flags |= IOCB_HIPRI;
1843 kiocb->ki_complete = io_complete_rw_iopoll;
1846 if (kiocb->ki_flags & IOCB_HIPRI)
1848 kiocb->ki_complete = io_complete_rw;
1851 req->rw.addr = READ_ONCE(sqe->addr);
1852 req->rw.len = READ_ONCE(sqe->len);
1853 /* we own ->private, reuse it for the buffer index */
1854 req->rw.kiocb.private = (void *) (unsigned long)
1855 READ_ONCE(sqe->buf_index);
1859 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1865 case -ERESTARTNOINTR:
1866 case -ERESTARTNOHAND:
1867 case -ERESTART_RESTARTBLOCK:
1869 * We can't just restart the syscall, since previously
1870 * submitted sqes may already be in progress. Just fail this
1876 kiocb->ki_complete(kiocb, ret, 0);
1880 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1883 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1885 if (req->flags & REQ_F_CUR_POS)
1886 req->file->f_pos = kiocb->ki_pos;
1887 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1888 *nxt = __io_complete_rw(kiocb, ret);
1890 io_rw_done(kiocb, ret);
1893 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1894 struct iov_iter *iter)
1896 struct io_ring_ctx *ctx = req->ctx;
1897 size_t len = req->rw.len;
1898 struct io_mapped_ubuf *imu;
1899 unsigned index, buf_index;
1903 /* attempt to use fixed buffers without having provided iovecs */
1904 if (unlikely(!ctx->user_bufs))
1907 buf_index = (unsigned long) req->rw.kiocb.private;
1908 if (unlikely(buf_index >= ctx->nr_user_bufs))
1911 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1912 imu = &ctx->user_bufs[index];
1913 buf_addr = req->rw.addr;
1916 if (buf_addr + len < buf_addr)
1918 /* not inside the mapped region */
1919 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1923 * May not be a start of buffer, set size appropriately
1924 * and advance us to the beginning.
1926 offset = buf_addr - imu->ubuf;
1927 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1931 * Don't use iov_iter_advance() here, as it's really slow for
1932 * using the latter parts of a big fixed buffer - it iterates
1933 * over each segment manually. We can cheat a bit here, because
1936 * 1) it's a BVEC iter, we set it up
1937 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1938 * first and last bvec
1940 * So just find our index, and adjust the iterator afterwards.
1941 * If the offset is within the first bvec (or the whole first
1942 * bvec, just use iov_iter_advance(). This makes it easier
1943 * since we can just skip the first segment, which may not
1944 * be PAGE_SIZE aligned.
1946 const struct bio_vec *bvec = imu->bvec;
1948 if (offset <= bvec->bv_len) {
1949 iov_iter_advance(iter, offset);
1951 unsigned long seg_skip;
1953 /* skip first vec */
1954 offset -= bvec->bv_len;
1955 seg_skip = 1 + (offset >> PAGE_SHIFT);
1957 iter->bvec = bvec + seg_skip;
1958 iter->nr_segs -= seg_skip;
1959 iter->count -= bvec->bv_len + offset;
1960 iter->iov_offset = offset & ~PAGE_MASK;
1967 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1968 struct iovec **iovec, struct iov_iter *iter)
1970 void __user *buf = u64_to_user_ptr(req->rw.addr);
1971 size_t sqe_len = req->rw.len;
1974 opcode = req->opcode;
1975 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1977 return io_import_fixed(req, rw, iter);
1980 /* buffer index only valid with fixed read/write */
1981 if (req->rw.kiocb.private)
1984 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
1986 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
1992 struct io_async_rw *iorw = &req->io->rw;
1995 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
1996 if (iorw->iov == iorw->fast_iov)
2004 #ifdef CONFIG_COMPAT
2005 if (req->ctx->compat)
2006 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2010 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2014 * For files that don't have ->read_iter() and ->write_iter(), handle them
2015 * by looping over ->read() or ->write() manually.
2017 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2018 struct iov_iter *iter)
2023 * Don't support polled IO through this interface, and we can't
2024 * support non-blocking either. For the latter, this just causes
2025 * the kiocb to be handled from an async context.
2027 if (kiocb->ki_flags & IOCB_HIPRI)
2029 if (kiocb->ki_flags & IOCB_NOWAIT)
2032 while (iov_iter_count(iter)) {
2036 if (!iov_iter_is_bvec(iter)) {
2037 iovec = iov_iter_iovec(iter);
2039 /* fixed buffers import bvec */
2040 iovec.iov_base = kmap(iter->bvec->bv_page)
2042 iovec.iov_len = min(iter->count,
2043 iter->bvec->bv_len - iter->iov_offset);
2047 nr = file->f_op->read(file, iovec.iov_base,
2048 iovec.iov_len, &kiocb->ki_pos);
2050 nr = file->f_op->write(file, iovec.iov_base,
2051 iovec.iov_len, &kiocb->ki_pos);
2054 if (iov_iter_is_bvec(iter))
2055 kunmap(iter->bvec->bv_page);
2063 if (nr != iovec.iov_len)
2065 iov_iter_advance(iter, nr);
2071 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2072 struct iovec *iovec, struct iovec *fast_iov,
2073 struct iov_iter *iter)
2075 req->io->rw.nr_segs = iter->nr_segs;
2076 req->io->rw.size = io_size;
2077 req->io->rw.iov = iovec;
2078 if (!req->io->rw.iov) {
2079 req->io->rw.iov = req->io->rw.fast_iov;
2080 memcpy(req->io->rw.iov, fast_iov,
2081 sizeof(struct iovec) * iter->nr_segs);
2085 static int io_alloc_async_ctx(struct io_kiocb *req)
2087 if (!io_op_defs[req->opcode].async_ctx)
2089 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2090 return req->io == NULL;
2093 static void io_rw_async(struct io_wq_work **workptr)
2095 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2096 struct iovec *iov = NULL;
2098 if (req->io->rw.iov != req->io->rw.fast_iov)
2099 iov = req->io->rw.iov;
2100 io_wq_submit_work(workptr);
2104 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2105 struct iovec *iovec, struct iovec *fast_iov,
2106 struct iov_iter *iter)
2108 if (req->opcode == IORING_OP_READ_FIXED ||
2109 req->opcode == IORING_OP_WRITE_FIXED)
2111 if (!req->io && io_alloc_async_ctx(req))
2114 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2115 req->work.func = io_rw_async;
2119 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2120 bool force_nonblock)
2122 struct io_async_ctx *io;
2123 struct iov_iter iter;
2126 ret = io_prep_rw(req, sqe, force_nonblock);
2130 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2137 io->rw.iov = io->rw.fast_iov;
2139 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2144 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2148 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2149 bool force_nonblock)
2151 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2152 struct kiocb *kiocb = &req->rw.kiocb;
2153 struct iov_iter iter;
2155 ssize_t io_size, ret;
2157 ret = io_import_iovec(READ, req, &iovec, &iter);
2161 /* Ensure we clear previously set non-block flag */
2162 if (!force_nonblock)
2163 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2167 if (req->flags & REQ_F_LINK)
2168 req->result = io_size;
2171 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2172 * we know to async punt it even if it was opened O_NONBLOCK
2174 if (force_nonblock && !io_file_supports_async(req->file)) {
2175 req->flags |= REQ_F_MUST_PUNT;
2179 iov_count = iov_iter_count(&iter);
2180 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2184 if (req->file->f_op->read_iter)
2185 ret2 = call_read_iter(req->file, kiocb, &iter);
2187 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2189 /* Catch -EAGAIN return for forced non-blocking submission */
2190 if (!force_nonblock || ret2 != -EAGAIN) {
2191 kiocb_done(kiocb, ret2, nxt, req->in_async);
2194 ret = io_setup_async_rw(req, io_size, iovec,
2195 inline_vecs, &iter);
2202 if (!io_wq_current_is_worker())
2207 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2208 bool force_nonblock)
2210 struct io_async_ctx *io;
2211 struct iov_iter iter;
2214 ret = io_prep_rw(req, sqe, force_nonblock);
2218 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2225 io->rw.iov = io->rw.fast_iov;
2227 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2232 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2236 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2237 bool force_nonblock)
2239 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2240 struct kiocb *kiocb = &req->rw.kiocb;
2241 struct iov_iter iter;
2243 ssize_t ret, io_size;
2245 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2249 /* Ensure we clear previously set non-block flag */
2250 if (!force_nonblock)
2251 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2255 if (req->flags & REQ_F_LINK)
2256 req->result = io_size;
2259 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2260 * we know to async punt it even if it was opened O_NONBLOCK
2262 if (force_nonblock && !io_file_supports_async(req->file)) {
2263 req->flags |= REQ_F_MUST_PUNT;
2267 /* file path doesn't support NOWAIT for non-direct_IO */
2268 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2269 (req->flags & REQ_F_ISREG))
2272 iov_count = iov_iter_count(&iter);
2273 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2278 * Open-code file_start_write here to grab freeze protection,
2279 * which will be released by another thread in
2280 * io_complete_rw(). Fool lockdep by telling it the lock got
2281 * released so that it doesn't complain about the held lock when
2282 * we return to userspace.
2284 if (req->flags & REQ_F_ISREG) {
2285 __sb_start_write(file_inode(req->file)->i_sb,
2286 SB_FREEZE_WRITE, true);
2287 __sb_writers_release(file_inode(req->file)->i_sb,
2290 kiocb->ki_flags |= IOCB_WRITE;
2292 if (req->file->f_op->write_iter)
2293 ret2 = call_write_iter(req->file, kiocb, &iter);
2295 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2296 if (!force_nonblock || ret2 != -EAGAIN) {
2297 kiocb_done(kiocb, ret2, nxt, req->in_async);
2300 ret = io_setup_async_rw(req, io_size, iovec,
2301 inline_vecs, &iter);
2308 if (!io_wq_current_is_worker())
2314 * IORING_OP_NOP just posts a completion event, nothing else.
2316 static int io_nop(struct io_kiocb *req)
2318 struct io_ring_ctx *ctx = req->ctx;
2320 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2323 io_cqring_add_event(req, 0);
2328 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2330 struct io_ring_ctx *ctx = req->ctx;
2335 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2337 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2340 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2341 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2344 req->sync.off = READ_ONCE(sqe->off);
2345 req->sync.len = READ_ONCE(sqe->len);
2349 static bool io_req_cancelled(struct io_kiocb *req)
2351 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2352 req_set_fail_links(req);
2353 io_cqring_add_event(req, -ECANCELED);
2361 static void io_link_work_cb(struct io_wq_work **workptr)
2363 struct io_wq_work *work = *workptr;
2364 struct io_kiocb *link = work->data;
2366 io_queue_linked_timeout(link);
2367 work->func = io_wq_submit_work;
2370 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2372 struct io_kiocb *link;
2374 io_prep_async_work(nxt, &link);
2375 *workptr = &nxt->work;
2377 nxt->work.flags |= IO_WQ_WORK_CB;
2378 nxt->work.func = io_link_work_cb;
2379 nxt->work.data = link;
2383 static void io_fsync_finish(struct io_wq_work **workptr)
2385 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2386 loff_t end = req->sync.off + req->sync.len;
2387 struct io_kiocb *nxt = NULL;
2390 if (io_req_cancelled(req))
2393 ret = vfs_fsync_range(req->file, req->sync.off,
2394 end > 0 ? end : LLONG_MAX,
2395 req->sync.flags & IORING_FSYNC_DATASYNC);
2397 req_set_fail_links(req);
2398 io_cqring_add_event(req, ret);
2399 io_put_req_find_next(req, &nxt);
2401 io_wq_assign_next(workptr, nxt);
2404 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2405 bool force_nonblock)
2407 struct io_wq_work *work, *old_work;
2409 /* fsync always requires a blocking context */
2410 if (force_nonblock) {
2412 req->work.func = io_fsync_finish;
2416 work = old_work = &req->work;
2417 io_fsync_finish(&work);
2418 if (work && work != old_work)
2419 *nxt = container_of(work, struct io_kiocb, work);
2423 static void io_fallocate_finish(struct io_wq_work **workptr)
2425 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2426 struct io_kiocb *nxt = NULL;
2429 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2432 req_set_fail_links(req);
2433 io_cqring_add_event(req, ret);
2434 io_put_req_find_next(req, &nxt);
2436 io_wq_assign_next(workptr, nxt);
2439 static int io_fallocate_prep(struct io_kiocb *req,
2440 const struct io_uring_sqe *sqe)
2442 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2445 req->sync.off = READ_ONCE(sqe->off);
2446 req->sync.len = READ_ONCE(sqe->addr);
2447 req->sync.mode = READ_ONCE(sqe->len);
2451 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2452 bool force_nonblock)
2454 struct io_wq_work *work, *old_work;
2456 /* fallocate always requiring blocking context */
2457 if (force_nonblock) {
2459 req->work.func = io_fallocate_finish;
2463 work = old_work = &req->work;
2464 io_fallocate_finish(&work);
2465 if (work && work != old_work)
2466 *nxt = container_of(work, struct io_kiocb, work);
2471 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2473 const char __user *fname;
2476 if (sqe->ioprio || sqe->buf_index)
2479 req->open.dfd = READ_ONCE(sqe->fd);
2480 req->open.how.mode = READ_ONCE(sqe->len);
2481 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2482 req->open.how.flags = READ_ONCE(sqe->open_flags);
2484 req->open.filename = getname(fname);
2485 if (IS_ERR(req->open.filename)) {
2486 ret = PTR_ERR(req->open.filename);
2487 req->open.filename = NULL;
2494 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2496 struct open_how __user *how;
2497 const char __user *fname;
2501 if (sqe->ioprio || sqe->buf_index)
2504 req->open.dfd = READ_ONCE(sqe->fd);
2505 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2506 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2507 len = READ_ONCE(sqe->len);
2509 if (len < OPEN_HOW_SIZE_VER0)
2512 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2517 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2518 req->open.how.flags |= O_LARGEFILE;
2520 req->open.filename = getname(fname);
2521 if (IS_ERR(req->open.filename)) {
2522 ret = PTR_ERR(req->open.filename);
2523 req->open.filename = NULL;
2530 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2531 bool force_nonblock)
2533 struct open_flags op;
2537 if (force_nonblock) {
2538 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2542 ret = build_open_flags(&req->open.how, &op);
2546 ret = get_unused_fd_flags(req->open.how.flags);
2550 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2553 ret = PTR_ERR(file);
2555 fsnotify_open(file);
2556 fd_install(ret, file);
2559 putname(req->open.filename);
2561 req_set_fail_links(req);
2562 io_cqring_add_event(req, ret);
2563 io_put_req_find_next(req, nxt);
2567 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2568 bool force_nonblock)
2570 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2571 return io_openat2(req, nxt, force_nonblock);
2574 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2576 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2577 if (sqe->ioprio || sqe->buf_index || sqe->off)
2580 req->madvise.addr = READ_ONCE(sqe->addr);
2581 req->madvise.len = READ_ONCE(sqe->len);
2582 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2589 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2590 bool force_nonblock)
2592 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2593 struct io_madvise *ma = &req->madvise;
2599 ret = do_madvise(ma->addr, ma->len, ma->advice);
2601 req_set_fail_links(req);
2602 io_cqring_add_event(req, ret);
2603 io_put_req_find_next(req, nxt);
2610 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2612 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2615 req->fadvise.offset = READ_ONCE(sqe->off);
2616 req->fadvise.len = READ_ONCE(sqe->len);
2617 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2621 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2622 bool force_nonblock)
2624 struct io_fadvise *fa = &req->fadvise;
2627 /* DONTNEED may block, others _should_ not */
2628 if (fa->advice == POSIX_FADV_DONTNEED && force_nonblock)
2631 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2633 req_set_fail_links(req);
2634 io_cqring_add_event(req, ret);
2635 io_put_req_find_next(req, nxt);
2639 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2641 const char __user *fname;
2642 unsigned lookup_flags;
2645 if (sqe->ioprio || sqe->buf_index)
2648 req->open.dfd = READ_ONCE(sqe->fd);
2649 req->open.mask = READ_ONCE(sqe->len);
2650 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2651 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2652 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2654 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2657 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2658 if (IS_ERR(req->open.filename)) {
2659 ret = PTR_ERR(req->open.filename);
2660 req->open.filename = NULL;
2667 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2668 bool force_nonblock)
2670 struct io_open *ctx = &req->open;
2671 unsigned lookup_flags;
2679 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2683 /* filename_lookup() drops it, keep a reference */
2684 ctx->filename->refcnt++;
2686 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2691 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2693 if (retry_estale(ret, lookup_flags)) {
2694 lookup_flags |= LOOKUP_REVAL;
2698 ret = cp_statx(&stat, ctx->buffer);
2700 putname(ctx->filename);
2702 req_set_fail_links(req);
2703 io_cqring_add_event(req, ret);
2704 io_put_req_find_next(req, nxt);
2708 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2711 * If we queue this for async, it must not be cancellable. That would
2712 * leave the 'file' in an undeterminate state.
2714 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2716 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2717 sqe->rw_flags || sqe->buf_index)
2719 if (sqe->flags & IOSQE_FIXED_FILE)
2722 req->close.fd = READ_ONCE(sqe->fd);
2723 if (req->file->f_op == &io_uring_fops ||
2724 req->close.fd == req->ctx->ring_fd)
2730 static void io_close_finish(struct io_wq_work **workptr)
2732 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2733 struct io_kiocb *nxt = NULL;
2735 /* Invoked with files, we need to do the close */
2736 if (req->work.files) {
2739 ret = filp_close(req->close.put_file, req->work.files);
2741 req_set_fail_links(req);
2743 io_cqring_add_event(req, ret);
2746 fput(req->close.put_file);
2748 /* we bypassed the re-issue, drop the submission reference */
2750 io_put_req_find_next(req, &nxt);
2752 io_wq_assign_next(workptr, nxt);
2755 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2756 bool force_nonblock)
2760 req->close.put_file = NULL;
2761 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2765 /* if the file has a flush method, be safe and punt to async */
2766 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker()) {
2767 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2772 * No ->flush(), safely close from here and just punt the
2773 * fput() to async context.
2775 ret = filp_close(req->close.put_file, current->files);
2778 req_set_fail_links(req);
2779 io_cqring_add_event(req, ret);
2781 if (io_wq_current_is_worker()) {
2782 struct io_wq_work *old_work, *work;
2784 old_work = work = &req->work;
2785 io_close_finish(&work);
2786 if (work && work != old_work)
2787 *nxt = container_of(work, struct io_kiocb, work);
2792 req->work.func = io_close_finish;
2796 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2798 struct io_ring_ctx *ctx = req->ctx;
2803 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2805 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2808 req->sync.off = READ_ONCE(sqe->off);
2809 req->sync.len = READ_ONCE(sqe->len);
2810 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2814 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2816 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2817 struct io_kiocb *nxt = NULL;
2820 if (io_req_cancelled(req))
2823 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2826 req_set_fail_links(req);
2827 io_cqring_add_event(req, ret);
2828 io_put_req_find_next(req, &nxt);
2830 io_wq_assign_next(workptr, nxt);
2833 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2834 bool force_nonblock)
2836 struct io_wq_work *work, *old_work;
2838 /* sync_file_range always requires a blocking context */
2839 if (force_nonblock) {
2841 req->work.func = io_sync_file_range_finish;
2845 work = old_work = &req->work;
2846 io_sync_file_range_finish(&work);
2847 if (work && work != old_work)
2848 *nxt = container_of(work, struct io_kiocb, work);
2852 #if defined(CONFIG_NET)
2853 static void io_sendrecv_async(struct io_wq_work **workptr)
2855 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2856 struct iovec *iov = NULL;
2858 if (req->io->rw.iov != req->io->rw.fast_iov)
2859 iov = req->io->msg.iov;
2860 io_wq_submit_work(workptr);
2865 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2867 #if defined(CONFIG_NET)
2868 struct io_sr_msg *sr = &req->sr_msg;
2869 struct io_async_ctx *io = req->io;
2871 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2872 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2873 sr->len = READ_ONCE(sqe->len);
2875 if (!io || req->opcode == IORING_OP_SEND)
2878 io->msg.iov = io->msg.fast_iov;
2879 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2886 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2887 bool force_nonblock)
2889 #if defined(CONFIG_NET)
2890 struct io_async_msghdr *kmsg = NULL;
2891 struct socket *sock;
2894 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2897 sock = sock_from_file(req->file, &ret);
2899 struct io_async_ctx io;
2900 struct sockaddr_storage addr;
2904 kmsg = &req->io->msg;
2905 kmsg->msg.msg_name = &addr;
2906 /* if iov is set, it's allocated already */
2908 kmsg->iov = kmsg->fast_iov;
2909 kmsg->msg.msg_iter.iov = kmsg->iov;
2911 struct io_sr_msg *sr = &req->sr_msg;
2914 kmsg->msg.msg_name = &addr;
2916 io.msg.iov = io.msg.fast_iov;
2917 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2918 sr->msg_flags, &io.msg.iov);
2923 flags = req->sr_msg.msg_flags;
2924 if (flags & MSG_DONTWAIT)
2925 req->flags |= REQ_F_NOWAIT;
2926 else if (force_nonblock)
2927 flags |= MSG_DONTWAIT;
2929 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2930 if (force_nonblock && ret == -EAGAIN) {
2933 if (io_alloc_async_ctx(req))
2935 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2936 req->work.func = io_sendrecv_async;
2939 if (ret == -ERESTARTSYS)
2943 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2945 io_cqring_add_event(req, ret);
2947 req_set_fail_links(req);
2948 io_put_req_find_next(req, nxt);
2955 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
2956 bool force_nonblock)
2958 #if defined(CONFIG_NET)
2959 struct socket *sock;
2962 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2965 sock = sock_from_file(req->file, &ret);
2967 struct io_sr_msg *sr = &req->sr_msg;
2972 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
2977 msg.msg_name = NULL;
2978 msg.msg_control = NULL;
2979 msg.msg_controllen = 0;
2980 msg.msg_namelen = 0;
2982 flags = req->sr_msg.msg_flags;
2983 if (flags & MSG_DONTWAIT)
2984 req->flags |= REQ_F_NOWAIT;
2985 else if (force_nonblock)
2986 flags |= MSG_DONTWAIT;
2988 ret = __sys_sendmsg_sock(sock, &msg, flags);
2989 if (force_nonblock && ret == -EAGAIN)
2991 if (ret == -ERESTARTSYS)
2995 io_cqring_add_event(req, ret);
2997 req_set_fail_links(req);
2998 io_put_req_find_next(req, nxt);
3005 static int io_recvmsg_prep(struct io_kiocb *req,
3006 const struct io_uring_sqe *sqe)
3008 #if defined(CONFIG_NET)
3009 struct io_sr_msg *sr = &req->sr_msg;
3010 struct io_async_ctx *io = req->io;
3012 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3013 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3015 if (!io || req->opcode == IORING_OP_RECV)
3018 io->msg.iov = io->msg.fast_iov;
3019 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3020 &io->msg.uaddr, &io->msg.iov);
3026 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3027 bool force_nonblock)
3029 #if defined(CONFIG_NET)
3030 struct io_async_msghdr *kmsg = NULL;
3031 struct socket *sock;
3034 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3037 sock = sock_from_file(req->file, &ret);
3039 struct io_async_ctx io;
3040 struct sockaddr_storage addr;
3044 kmsg = &req->io->msg;
3045 kmsg->msg.msg_name = &addr;
3046 /* if iov is set, it's allocated already */
3048 kmsg->iov = kmsg->fast_iov;
3049 kmsg->msg.msg_iter.iov = kmsg->iov;
3051 struct io_sr_msg *sr = &req->sr_msg;
3054 kmsg->msg.msg_name = &addr;
3056 io.msg.iov = io.msg.fast_iov;
3057 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3058 sr->msg_flags, &io.msg.uaddr,
3064 flags = req->sr_msg.msg_flags;
3065 if (flags & MSG_DONTWAIT)
3066 req->flags |= REQ_F_NOWAIT;
3067 else if (force_nonblock)
3068 flags |= MSG_DONTWAIT;
3070 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3071 kmsg->uaddr, flags);
3072 if (force_nonblock && ret == -EAGAIN) {
3075 if (io_alloc_async_ctx(req))
3077 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3078 req->work.func = io_sendrecv_async;
3081 if (ret == -ERESTARTSYS)
3085 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
3087 io_cqring_add_event(req, ret);
3089 req_set_fail_links(req);
3090 io_put_req_find_next(req, nxt);
3097 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3098 bool force_nonblock)
3100 #if defined(CONFIG_NET)
3101 struct socket *sock;
3104 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3107 sock = sock_from_file(req->file, &ret);
3109 struct io_sr_msg *sr = &req->sr_msg;
3114 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3119 msg.msg_name = NULL;
3120 msg.msg_control = NULL;
3121 msg.msg_controllen = 0;
3122 msg.msg_namelen = 0;
3123 msg.msg_iocb = NULL;
3126 flags = req->sr_msg.msg_flags;
3127 if (flags & MSG_DONTWAIT)
3128 req->flags |= REQ_F_NOWAIT;
3129 else if (force_nonblock)
3130 flags |= MSG_DONTWAIT;
3132 ret = __sys_recvmsg_sock(sock, &msg, NULL, NULL, flags);
3133 if (force_nonblock && ret == -EAGAIN)
3135 if (ret == -ERESTARTSYS)
3139 io_cqring_add_event(req, ret);
3141 req_set_fail_links(req);
3142 io_put_req_find_next(req, nxt);
3150 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3152 #if defined(CONFIG_NET)
3153 struct io_accept *accept = &req->accept;
3155 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3157 if (sqe->ioprio || sqe->len || sqe->buf_index)
3160 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3161 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3162 accept->flags = READ_ONCE(sqe->accept_flags);
3169 #if defined(CONFIG_NET)
3170 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3171 bool force_nonblock)
3173 struct io_accept *accept = &req->accept;
3174 unsigned file_flags;
3177 file_flags = force_nonblock ? O_NONBLOCK : 0;
3178 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3179 accept->addr_len, accept->flags);
3180 if (ret == -EAGAIN && force_nonblock)
3182 if (ret == -ERESTARTSYS)
3185 req_set_fail_links(req);
3186 io_cqring_add_event(req, ret);
3187 io_put_req_find_next(req, nxt);
3191 static void io_accept_finish(struct io_wq_work **workptr)
3193 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3194 struct io_kiocb *nxt = NULL;
3196 if (io_req_cancelled(req))
3198 __io_accept(req, &nxt, false);
3200 io_wq_assign_next(workptr, nxt);
3204 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3205 bool force_nonblock)
3207 #if defined(CONFIG_NET)
3210 ret = __io_accept(req, nxt, force_nonblock);
3211 if (ret == -EAGAIN && force_nonblock) {
3212 req->work.func = io_accept_finish;
3213 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3223 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3225 #if defined(CONFIG_NET)
3226 struct io_connect *conn = &req->connect;
3227 struct io_async_ctx *io = req->io;
3229 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3231 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3234 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3235 conn->addr_len = READ_ONCE(sqe->addr2);
3240 return move_addr_to_kernel(conn->addr, conn->addr_len,
3241 &io->connect.address);
3247 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3248 bool force_nonblock)
3250 #if defined(CONFIG_NET)
3251 struct io_async_ctx __io, *io;
3252 unsigned file_flags;
3258 ret = move_addr_to_kernel(req->connect.addr,
3259 req->connect.addr_len,
3260 &__io.connect.address);
3266 file_flags = force_nonblock ? O_NONBLOCK : 0;
3268 ret = __sys_connect_file(req->file, &io->connect.address,
3269 req->connect.addr_len, file_flags);
3270 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3273 if (io_alloc_async_ctx(req)) {
3277 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3280 if (ret == -ERESTARTSYS)
3284 req_set_fail_links(req);
3285 io_cqring_add_event(req, ret);
3286 io_put_req_find_next(req, nxt);
3293 static void io_poll_remove_one(struct io_kiocb *req)
3295 struct io_poll_iocb *poll = &req->poll;
3297 spin_lock(&poll->head->lock);
3298 WRITE_ONCE(poll->canceled, true);
3299 if (!list_empty(&poll->wait.entry)) {
3300 list_del_init(&poll->wait.entry);
3301 io_queue_async_work(req);
3303 spin_unlock(&poll->head->lock);
3304 hash_del(&req->hash_node);
3307 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3309 struct hlist_node *tmp;
3310 struct io_kiocb *req;
3313 spin_lock_irq(&ctx->completion_lock);
3314 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3315 struct hlist_head *list;
3317 list = &ctx->cancel_hash[i];
3318 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3319 io_poll_remove_one(req);
3321 spin_unlock_irq(&ctx->completion_lock);
3324 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3326 struct hlist_head *list;
3327 struct io_kiocb *req;
3329 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3330 hlist_for_each_entry(req, list, hash_node) {
3331 if (sqe_addr == req->user_data) {
3332 io_poll_remove_one(req);
3340 static int io_poll_remove_prep(struct io_kiocb *req,
3341 const struct io_uring_sqe *sqe)
3343 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3345 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3349 req->poll.addr = READ_ONCE(sqe->addr);
3354 * Find a running poll command that matches one specified in sqe->addr,
3355 * and remove it if found.
3357 static int io_poll_remove(struct io_kiocb *req)
3359 struct io_ring_ctx *ctx = req->ctx;
3363 addr = req->poll.addr;
3364 spin_lock_irq(&ctx->completion_lock);
3365 ret = io_poll_cancel(ctx, addr);
3366 spin_unlock_irq(&ctx->completion_lock);
3368 io_cqring_add_event(req, ret);
3370 req_set_fail_links(req);
3375 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3377 struct io_ring_ctx *ctx = req->ctx;
3379 req->poll.done = true;
3381 io_cqring_fill_event(req, error);
3383 io_cqring_fill_event(req, mangle_poll(mask));
3384 io_commit_cqring(ctx);
3387 static void io_poll_complete_work(struct io_wq_work **workptr)
3389 struct io_wq_work *work = *workptr;
3390 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3391 struct io_poll_iocb *poll = &req->poll;
3392 struct poll_table_struct pt = { ._key = poll->events };
3393 struct io_ring_ctx *ctx = req->ctx;
3394 struct io_kiocb *nxt = NULL;
3398 if (work->flags & IO_WQ_WORK_CANCEL) {
3399 WRITE_ONCE(poll->canceled, true);
3401 } else if (READ_ONCE(poll->canceled)) {
3405 if (ret != -ECANCELED)
3406 mask = vfs_poll(poll->file, &pt) & poll->events;
3409 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3410 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3411 * synchronize with them. In the cancellation case the list_del_init
3412 * itself is not actually needed, but harmless so we keep it in to
3413 * avoid further branches in the fast path.
3415 spin_lock_irq(&ctx->completion_lock);
3416 if (!mask && ret != -ECANCELED) {
3417 add_wait_queue(poll->head, &poll->wait);
3418 spin_unlock_irq(&ctx->completion_lock);
3421 hash_del(&req->hash_node);
3422 io_poll_complete(req, mask, ret);
3423 spin_unlock_irq(&ctx->completion_lock);
3425 io_cqring_ev_posted(ctx);
3428 req_set_fail_links(req);
3429 io_put_req_find_next(req, &nxt);
3431 io_wq_assign_next(workptr, nxt);
3434 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3436 struct io_kiocb *req, *tmp;
3437 struct req_batch rb;
3439 rb.to_free = rb.need_iter = 0;
3440 spin_lock_irq(&ctx->completion_lock);
3441 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3442 hash_del(&req->hash_node);
3443 io_poll_complete(req, req->result, 0);
3445 if (refcount_dec_and_test(&req->refs) &&
3446 !io_req_multi_free(&rb, req)) {
3447 req->flags |= REQ_F_COMP_LOCKED;
3451 spin_unlock_irq(&ctx->completion_lock);
3453 io_cqring_ev_posted(ctx);
3454 io_free_req_many(ctx, &rb);
3457 static void io_poll_flush(struct io_wq_work **workptr)
3459 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3460 struct llist_node *nodes;
3462 nodes = llist_del_all(&req->ctx->poll_llist);
3464 __io_poll_flush(req->ctx, nodes);
3467 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3470 struct io_poll_iocb *poll = wait->private;
3471 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3472 struct io_ring_ctx *ctx = req->ctx;
3473 __poll_t mask = key_to_poll(key);
3475 /* for instances that support it check for an event match first: */
3476 if (mask && !(mask & poll->events))
3479 list_del_init(&poll->wait.entry);
3482 * Run completion inline if we can. We're using trylock here because
3483 * we are violating the completion_lock -> poll wq lock ordering.
3484 * If we have a link timeout we're going to need the completion_lock
3485 * for finalizing the request, mark us as having grabbed that already.
3488 unsigned long flags;
3490 if (llist_empty(&ctx->poll_llist) &&
3491 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3492 hash_del(&req->hash_node);
3493 io_poll_complete(req, mask, 0);
3494 req->flags |= REQ_F_COMP_LOCKED;
3496 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3498 io_cqring_ev_posted(ctx);
3502 req->llist_node.next = NULL;
3503 /* if the list wasn't empty, we're done */
3504 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3507 req->work.func = io_poll_flush;
3511 io_queue_async_work(req);
3516 struct io_poll_table {
3517 struct poll_table_struct pt;
3518 struct io_kiocb *req;
3522 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3523 struct poll_table_struct *p)
3525 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3527 if (unlikely(pt->req->poll.head)) {
3528 pt->error = -EINVAL;
3533 pt->req->poll.head = head;
3534 add_wait_queue(head, &pt->req->poll.wait);
3537 static void io_poll_req_insert(struct io_kiocb *req)
3539 struct io_ring_ctx *ctx = req->ctx;
3540 struct hlist_head *list;
3542 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3543 hlist_add_head(&req->hash_node, list);
3546 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3548 struct io_poll_iocb *poll = &req->poll;
3551 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3553 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3558 events = READ_ONCE(sqe->poll_events);
3559 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3563 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3565 struct io_poll_iocb *poll = &req->poll;
3566 struct io_ring_ctx *ctx = req->ctx;
3567 struct io_poll_table ipt;
3568 bool cancel = false;
3571 INIT_IO_WORK(&req->work, io_poll_complete_work);
3572 INIT_HLIST_NODE(&req->hash_node);
3576 poll->canceled = false;
3578 ipt.pt._qproc = io_poll_queue_proc;
3579 ipt.pt._key = poll->events;
3581 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3583 /* initialized the list so that we can do list_empty checks */
3584 INIT_LIST_HEAD(&poll->wait.entry);
3585 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3586 poll->wait.private = poll;
3588 INIT_LIST_HEAD(&req->list);
3590 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3592 spin_lock_irq(&ctx->completion_lock);
3593 if (likely(poll->head)) {
3594 spin_lock(&poll->head->lock);
3595 if (unlikely(list_empty(&poll->wait.entry))) {
3601 if (mask || ipt.error)
3602 list_del_init(&poll->wait.entry);
3604 WRITE_ONCE(poll->canceled, true);
3605 else if (!poll->done) /* actually waiting for an event */
3606 io_poll_req_insert(req);
3607 spin_unlock(&poll->head->lock);
3609 if (mask) { /* no async, we'd stolen it */
3611 io_poll_complete(req, mask, 0);
3613 spin_unlock_irq(&ctx->completion_lock);
3616 io_cqring_ev_posted(ctx);
3617 io_put_req_find_next(req, nxt);
3622 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3624 struct io_timeout_data *data = container_of(timer,
3625 struct io_timeout_data, timer);
3626 struct io_kiocb *req = data->req;
3627 struct io_ring_ctx *ctx = req->ctx;
3628 unsigned long flags;
3630 atomic_inc(&ctx->cq_timeouts);
3632 spin_lock_irqsave(&ctx->completion_lock, flags);
3634 * We could be racing with timeout deletion. If the list is empty,
3635 * then timeout lookup already found it and will be handling it.
3637 if (!list_empty(&req->list)) {
3638 struct io_kiocb *prev;
3641 * Adjust the reqs sequence before the current one because it
3642 * will consume a slot in the cq_ring and the cq_tail
3643 * pointer will be increased, otherwise other timeout reqs may
3644 * return in advance without waiting for enough wait_nr.
3647 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3649 list_del_init(&req->list);
3652 io_cqring_fill_event(req, -ETIME);
3653 io_commit_cqring(ctx);
3654 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3656 io_cqring_ev_posted(ctx);
3657 req_set_fail_links(req);
3659 return HRTIMER_NORESTART;
3662 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3664 struct io_kiocb *req;
3667 list_for_each_entry(req, &ctx->timeout_list, list) {
3668 if (user_data == req->user_data) {
3669 list_del_init(&req->list);
3678 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3682 req_set_fail_links(req);
3683 io_cqring_fill_event(req, -ECANCELED);
3688 static int io_timeout_remove_prep(struct io_kiocb *req,
3689 const struct io_uring_sqe *sqe)
3691 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3693 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3696 req->timeout.addr = READ_ONCE(sqe->addr);
3697 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3698 if (req->timeout.flags)
3705 * Remove or update an existing timeout command
3707 static int io_timeout_remove(struct io_kiocb *req)
3709 struct io_ring_ctx *ctx = req->ctx;
3712 spin_lock_irq(&ctx->completion_lock);
3713 ret = io_timeout_cancel(ctx, req->timeout.addr);
3715 io_cqring_fill_event(req, ret);
3716 io_commit_cqring(ctx);
3717 spin_unlock_irq(&ctx->completion_lock);
3718 io_cqring_ev_posted(ctx);
3720 req_set_fail_links(req);
3725 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3726 bool is_timeout_link)
3728 struct io_timeout_data *data;
3731 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3733 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3735 if (sqe->off && is_timeout_link)
3737 flags = READ_ONCE(sqe->timeout_flags);
3738 if (flags & ~IORING_TIMEOUT_ABS)
3741 req->timeout.count = READ_ONCE(sqe->off);
3743 if (!req->io && io_alloc_async_ctx(req))
3746 data = &req->io->timeout;
3748 req->flags |= REQ_F_TIMEOUT;
3750 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3753 if (flags & IORING_TIMEOUT_ABS)
3754 data->mode = HRTIMER_MODE_ABS;
3756 data->mode = HRTIMER_MODE_REL;
3758 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3762 static int io_timeout(struct io_kiocb *req)
3765 struct io_ring_ctx *ctx = req->ctx;
3766 struct io_timeout_data *data;
3767 struct list_head *entry;
3770 data = &req->io->timeout;
3773 * sqe->off holds how many events that need to occur for this
3774 * timeout event to be satisfied. If it isn't set, then this is
3775 * a pure timeout request, sequence isn't used.
3777 count = req->timeout.count;
3779 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3780 spin_lock_irq(&ctx->completion_lock);
3781 entry = ctx->timeout_list.prev;
3785 req->sequence = ctx->cached_sq_head + count - 1;
3786 data->seq_offset = count;
3789 * Insertion sort, ensuring the first entry in the list is always
3790 * the one we need first.
3792 spin_lock_irq(&ctx->completion_lock);
3793 list_for_each_prev(entry, &ctx->timeout_list) {
3794 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3795 unsigned nxt_sq_head;
3796 long long tmp, tmp_nxt;
3797 u32 nxt_offset = nxt->io->timeout.seq_offset;
3799 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3803 * Since cached_sq_head + count - 1 can overflow, use type long
3806 tmp = (long long)ctx->cached_sq_head + count - 1;
3807 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3808 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3811 * cached_sq_head may overflow, and it will never overflow twice
3812 * once there is some timeout req still be valid.
3814 if (ctx->cached_sq_head < nxt_sq_head)
3821 * Sequence of reqs after the insert one and itself should
3822 * be adjusted because each timeout req consumes a slot.
3827 req->sequence -= span;
3829 list_add(&req->list, entry);
3830 data->timer.function = io_timeout_fn;
3831 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3832 spin_unlock_irq(&ctx->completion_lock);
3836 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3838 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3840 return req->user_data == (unsigned long) data;
3843 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3845 enum io_wq_cancel cancel_ret;
3848 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3849 switch (cancel_ret) {
3850 case IO_WQ_CANCEL_OK:
3853 case IO_WQ_CANCEL_RUNNING:
3856 case IO_WQ_CANCEL_NOTFOUND:
3864 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3865 struct io_kiocb *req, __u64 sqe_addr,
3866 struct io_kiocb **nxt, int success_ret)
3868 unsigned long flags;
3871 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3872 if (ret != -ENOENT) {
3873 spin_lock_irqsave(&ctx->completion_lock, flags);
3877 spin_lock_irqsave(&ctx->completion_lock, flags);
3878 ret = io_timeout_cancel(ctx, sqe_addr);
3881 ret = io_poll_cancel(ctx, sqe_addr);
3885 io_cqring_fill_event(req, ret);
3886 io_commit_cqring(ctx);
3887 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3888 io_cqring_ev_posted(ctx);
3891 req_set_fail_links(req);
3892 io_put_req_find_next(req, nxt);
3895 static int io_async_cancel_prep(struct io_kiocb *req,
3896 const struct io_uring_sqe *sqe)
3898 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3900 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3904 req->cancel.addr = READ_ONCE(sqe->addr);
3908 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3910 struct io_ring_ctx *ctx = req->ctx;
3912 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3916 static int io_files_update_prep(struct io_kiocb *req,
3917 const struct io_uring_sqe *sqe)
3919 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
3922 req->files_update.offset = READ_ONCE(sqe->off);
3923 req->files_update.nr_args = READ_ONCE(sqe->len);
3924 if (!req->files_update.nr_args)
3926 req->files_update.arg = READ_ONCE(sqe->addr);
3930 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
3932 struct io_ring_ctx *ctx = req->ctx;
3933 struct io_uring_files_update up;
3936 if (force_nonblock) {
3937 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3941 up.offset = req->files_update.offset;
3942 up.fds = req->files_update.arg;
3944 mutex_lock(&ctx->uring_lock);
3945 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
3946 mutex_unlock(&ctx->uring_lock);
3949 req_set_fail_links(req);
3950 io_cqring_add_event(req, ret);
3955 static int io_req_defer_prep(struct io_kiocb *req,
3956 const struct io_uring_sqe *sqe)
3960 switch (req->opcode) {
3963 case IORING_OP_READV:
3964 case IORING_OP_READ_FIXED:
3965 case IORING_OP_READ:
3966 ret = io_read_prep(req, sqe, true);
3968 case IORING_OP_WRITEV:
3969 case IORING_OP_WRITE_FIXED:
3970 case IORING_OP_WRITE:
3971 ret = io_write_prep(req, sqe, true);
3973 case IORING_OP_POLL_ADD:
3974 ret = io_poll_add_prep(req, sqe);
3976 case IORING_OP_POLL_REMOVE:
3977 ret = io_poll_remove_prep(req, sqe);
3979 case IORING_OP_FSYNC:
3980 ret = io_prep_fsync(req, sqe);
3982 case IORING_OP_SYNC_FILE_RANGE:
3983 ret = io_prep_sfr(req, sqe);
3985 case IORING_OP_SENDMSG:
3986 case IORING_OP_SEND:
3987 ret = io_sendmsg_prep(req, sqe);
3989 case IORING_OP_RECVMSG:
3990 case IORING_OP_RECV:
3991 ret = io_recvmsg_prep(req, sqe);
3993 case IORING_OP_CONNECT:
3994 ret = io_connect_prep(req, sqe);
3996 case IORING_OP_TIMEOUT:
3997 ret = io_timeout_prep(req, sqe, false);
3999 case IORING_OP_TIMEOUT_REMOVE:
4000 ret = io_timeout_remove_prep(req, sqe);
4002 case IORING_OP_ASYNC_CANCEL:
4003 ret = io_async_cancel_prep(req, sqe);
4005 case IORING_OP_LINK_TIMEOUT:
4006 ret = io_timeout_prep(req, sqe, true);
4008 case IORING_OP_ACCEPT:
4009 ret = io_accept_prep(req, sqe);
4011 case IORING_OP_FALLOCATE:
4012 ret = io_fallocate_prep(req, sqe);
4014 case IORING_OP_OPENAT:
4015 ret = io_openat_prep(req, sqe);
4017 case IORING_OP_CLOSE:
4018 ret = io_close_prep(req, sqe);
4020 case IORING_OP_FILES_UPDATE:
4021 ret = io_files_update_prep(req, sqe);
4023 case IORING_OP_STATX:
4024 ret = io_statx_prep(req, sqe);
4026 case IORING_OP_FADVISE:
4027 ret = io_fadvise_prep(req, sqe);
4029 case IORING_OP_MADVISE:
4030 ret = io_madvise_prep(req, sqe);
4032 case IORING_OP_OPENAT2:
4033 ret = io_openat2_prep(req, sqe);
4036 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4045 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4047 struct io_ring_ctx *ctx = req->ctx;
4050 /* Still need defer if there is pending req in defer list. */
4051 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4054 if (!req->io && io_alloc_async_ctx(req))
4057 ret = io_req_defer_prep(req, sqe);
4061 spin_lock_irq(&ctx->completion_lock);
4062 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4063 spin_unlock_irq(&ctx->completion_lock);
4067 trace_io_uring_defer(ctx, req, req->user_data);
4068 list_add_tail(&req->list, &ctx->defer_list);
4069 spin_unlock_irq(&ctx->completion_lock);
4070 return -EIOCBQUEUED;
4073 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4074 struct io_kiocb **nxt, bool force_nonblock)
4076 struct io_ring_ctx *ctx = req->ctx;
4079 switch (req->opcode) {
4083 case IORING_OP_READV:
4084 case IORING_OP_READ_FIXED:
4085 case IORING_OP_READ:
4087 ret = io_read_prep(req, sqe, force_nonblock);
4091 ret = io_read(req, nxt, force_nonblock);
4093 case IORING_OP_WRITEV:
4094 case IORING_OP_WRITE_FIXED:
4095 case IORING_OP_WRITE:
4097 ret = io_write_prep(req, sqe, force_nonblock);
4101 ret = io_write(req, nxt, force_nonblock);
4103 case IORING_OP_FSYNC:
4105 ret = io_prep_fsync(req, sqe);
4109 ret = io_fsync(req, nxt, force_nonblock);
4111 case IORING_OP_POLL_ADD:
4113 ret = io_poll_add_prep(req, sqe);
4117 ret = io_poll_add(req, nxt);
4119 case IORING_OP_POLL_REMOVE:
4121 ret = io_poll_remove_prep(req, sqe);
4125 ret = io_poll_remove(req);
4127 case IORING_OP_SYNC_FILE_RANGE:
4129 ret = io_prep_sfr(req, sqe);
4133 ret = io_sync_file_range(req, nxt, force_nonblock);
4135 case IORING_OP_SENDMSG:
4136 case IORING_OP_SEND:
4138 ret = io_sendmsg_prep(req, sqe);
4142 if (req->opcode == IORING_OP_SENDMSG)
4143 ret = io_sendmsg(req, nxt, force_nonblock);
4145 ret = io_send(req, nxt, force_nonblock);
4147 case IORING_OP_RECVMSG:
4148 case IORING_OP_RECV:
4150 ret = io_recvmsg_prep(req, sqe);
4154 if (req->opcode == IORING_OP_RECVMSG)
4155 ret = io_recvmsg(req, nxt, force_nonblock);
4157 ret = io_recv(req, nxt, force_nonblock);
4159 case IORING_OP_TIMEOUT:
4161 ret = io_timeout_prep(req, sqe, false);
4165 ret = io_timeout(req);
4167 case IORING_OP_TIMEOUT_REMOVE:
4169 ret = io_timeout_remove_prep(req, sqe);
4173 ret = io_timeout_remove(req);
4175 case IORING_OP_ACCEPT:
4177 ret = io_accept_prep(req, sqe);
4181 ret = io_accept(req, nxt, force_nonblock);
4183 case IORING_OP_CONNECT:
4185 ret = io_connect_prep(req, sqe);
4189 ret = io_connect(req, nxt, force_nonblock);
4191 case IORING_OP_ASYNC_CANCEL:
4193 ret = io_async_cancel_prep(req, sqe);
4197 ret = io_async_cancel(req, nxt);
4199 case IORING_OP_FALLOCATE:
4201 ret = io_fallocate_prep(req, sqe);
4205 ret = io_fallocate(req, nxt, force_nonblock);
4207 case IORING_OP_OPENAT:
4209 ret = io_openat_prep(req, sqe);
4213 ret = io_openat(req, nxt, force_nonblock);
4215 case IORING_OP_CLOSE:
4217 ret = io_close_prep(req, sqe);
4221 ret = io_close(req, nxt, force_nonblock);
4223 case IORING_OP_FILES_UPDATE:
4225 ret = io_files_update_prep(req, sqe);
4229 ret = io_files_update(req, force_nonblock);
4231 case IORING_OP_STATX:
4233 ret = io_statx_prep(req, sqe);
4237 ret = io_statx(req, nxt, force_nonblock);
4239 case IORING_OP_FADVISE:
4241 ret = io_fadvise_prep(req, sqe);
4245 ret = io_fadvise(req, nxt, force_nonblock);
4247 case IORING_OP_MADVISE:
4249 ret = io_madvise_prep(req, sqe);
4253 ret = io_madvise(req, nxt, force_nonblock);
4255 case IORING_OP_OPENAT2:
4257 ret = io_openat2_prep(req, sqe);
4261 ret = io_openat2(req, nxt, force_nonblock);
4271 if (ctx->flags & IORING_SETUP_IOPOLL) {
4272 const bool in_async = io_wq_current_is_worker();
4274 if (req->result == -EAGAIN)
4277 /* workqueue context doesn't hold uring_lock, grab it now */
4279 mutex_lock(&ctx->uring_lock);
4281 io_iopoll_req_issued(req);
4284 mutex_unlock(&ctx->uring_lock);
4290 static void io_wq_submit_work(struct io_wq_work **workptr)
4292 struct io_wq_work *work = *workptr;
4293 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4294 struct io_kiocb *nxt = NULL;
4297 /* if NO_CANCEL is set, we must still run the work */
4298 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4299 IO_WQ_WORK_CANCEL) {
4304 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
4305 req->in_async = true;
4307 ret = io_issue_sqe(req, NULL, &nxt, false);
4309 * We can get EAGAIN for polled IO even though we're
4310 * forcing a sync submission from here, since we can't
4311 * wait for request slots on the block side.
4319 /* drop submission reference */
4323 req_set_fail_links(req);
4324 io_cqring_add_event(req, ret);
4328 /* if a dependent link is ready, pass it back */
4330 io_wq_assign_next(workptr, nxt);
4333 static int io_req_needs_file(struct io_kiocb *req, int fd)
4335 if (!io_op_defs[req->opcode].needs_file)
4337 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4342 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4345 struct fixed_file_table *table;
4347 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4348 return table->files[index & IORING_FILE_TABLE_MASK];;
4351 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4352 const struct io_uring_sqe *sqe)
4354 struct io_ring_ctx *ctx = req->ctx;
4358 flags = READ_ONCE(sqe->flags);
4359 fd = READ_ONCE(sqe->fd);
4361 if (flags & IOSQE_IO_DRAIN)
4362 req->flags |= REQ_F_IO_DRAIN;
4364 if (!io_req_needs_file(req, fd))
4367 if (flags & IOSQE_FIXED_FILE) {
4368 if (unlikely(!ctx->file_data ||
4369 (unsigned) fd >= ctx->nr_user_files))
4371 fd = array_index_nospec(fd, ctx->nr_user_files);
4372 req->file = io_file_from_index(ctx, fd);
4375 req->flags |= REQ_F_FIXED_FILE;
4376 percpu_ref_get(&ctx->file_data->refs);
4378 if (req->needs_fixed_file)
4380 trace_io_uring_file_get(ctx, fd);
4381 req->file = io_file_get(state, fd);
4382 if (unlikely(!req->file))
4389 static int io_grab_files(struct io_kiocb *req)
4392 struct io_ring_ctx *ctx = req->ctx;
4394 if (!ctx->ring_file)
4398 spin_lock_irq(&ctx->inflight_lock);
4400 * We use the f_ops->flush() handler to ensure that we can flush
4401 * out work accessing these files if the fd is closed. Check if
4402 * the fd has changed since we started down this path, and disallow
4403 * this operation if it has.
4405 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4406 list_add(&req->inflight_entry, &ctx->inflight_list);
4407 req->flags |= REQ_F_INFLIGHT;
4408 req->work.files = current->files;
4411 spin_unlock_irq(&ctx->inflight_lock);
4417 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4419 struct io_timeout_data *data = container_of(timer,
4420 struct io_timeout_data, timer);
4421 struct io_kiocb *req = data->req;
4422 struct io_ring_ctx *ctx = req->ctx;
4423 struct io_kiocb *prev = NULL;
4424 unsigned long flags;
4426 spin_lock_irqsave(&ctx->completion_lock, flags);
4429 * We don't expect the list to be empty, that will only happen if we
4430 * race with the completion of the linked work.
4432 if (!list_empty(&req->link_list)) {
4433 prev = list_entry(req->link_list.prev, struct io_kiocb,
4435 if (refcount_inc_not_zero(&prev->refs)) {
4436 list_del_init(&req->link_list);
4437 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4442 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4445 req_set_fail_links(prev);
4446 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4450 io_cqring_add_event(req, -ETIME);
4453 return HRTIMER_NORESTART;
4456 static void io_queue_linked_timeout(struct io_kiocb *req)
4458 struct io_ring_ctx *ctx = req->ctx;
4461 * If the list is now empty, then our linked request finished before
4462 * we got a chance to setup the timer
4464 spin_lock_irq(&ctx->completion_lock);
4465 if (!list_empty(&req->link_list)) {
4466 struct io_timeout_data *data = &req->io->timeout;
4468 data->timer.function = io_link_timeout_fn;
4469 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4472 spin_unlock_irq(&ctx->completion_lock);
4474 /* drop submission reference */
4478 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4480 struct io_kiocb *nxt;
4482 if (!(req->flags & REQ_F_LINK))
4485 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4487 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4490 req->flags |= REQ_F_LINK_TIMEOUT;
4494 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4496 struct io_kiocb *linked_timeout;
4497 struct io_kiocb *nxt = NULL;
4501 linked_timeout = io_prep_linked_timeout(req);
4503 ret = io_issue_sqe(req, sqe, &nxt, true);
4506 * We async punt it if the file wasn't marked NOWAIT, or if the file
4507 * doesn't support non-blocking read/write attempts
4509 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4510 (req->flags & REQ_F_MUST_PUNT))) {
4511 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
4512 ret = io_grab_files(req);
4518 * Queued up for async execution, worker will release
4519 * submit reference when the iocb is actually submitted.
4521 io_queue_async_work(req);
4526 /* drop submission reference */
4529 if (linked_timeout) {
4531 io_queue_linked_timeout(linked_timeout);
4533 io_put_req(linked_timeout);
4536 /* and drop final reference, if we failed */
4538 io_cqring_add_event(req, ret);
4539 req_set_fail_links(req);
4550 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4554 ret = io_req_defer(req, sqe);
4556 if (ret != -EIOCBQUEUED) {
4557 io_cqring_add_event(req, ret);
4558 req_set_fail_links(req);
4559 io_double_put_req(req);
4561 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4563 * Never try inline submit of IOSQE_ASYNC is set, go straight
4564 * to async execution.
4566 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4567 io_queue_async_work(req);
4569 __io_queue_sqe(req, sqe);
4573 static inline void io_queue_link_head(struct io_kiocb *req)
4575 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4576 io_cqring_add_event(req, -ECANCELED);
4577 io_double_put_req(req);
4579 io_queue_sqe(req, NULL);
4582 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4583 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4585 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4586 struct io_submit_state *state, struct io_kiocb **link)
4588 struct io_ring_ctx *ctx = req->ctx;
4589 unsigned int sqe_flags;
4592 sqe_flags = READ_ONCE(sqe->flags);
4594 /* enforce forwards compatibility on users */
4595 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4599 if (sqe_flags & IOSQE_ASYNC)
4600 req->flags |= REQ_F_FORCE_ASYNC;
4602 ret = io_req_set_file(state, req, sqe);
4603 if (unlikely(ret)) {
4605 io_cqring_add_event(req, ret);
4606 io_double_put_req(req);
4611 * If we already have a head request, queue this one for async
4612 * submittal once the head completes. If we don't have a head but
4613 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4614 * submitted sync once the chain is complete. If none of those
4615 * conditions are true (normal request), then just queue it.
4618 struct io_kiocb *head = *link;
4620 if (sqe_flags & IOSQE_IO_DRAIN) {
4621 head->flags |= REQ_F_IO_DRAIN;
4622 ctx->drain_next = 1;
4625 if (sqe_flags & IOSQE_IO_HARDLINK)
4626 req->flags |= REQ_F_HARDLINK;
4628 if (io_alloc_async_ctx(req)) {
4633 ret = io_req_defer_prep(req, sqe);
4635 /* fail even hard links since we don't submit */
4636 head->flags |= REQ_F_FAIL_LINK;
4639 trace_io_uring_link(ctx, req, head);
4640 list_add_tail(&req->link_list, &head->link_list);
4642 /* last request of a link, enqueue the link */
4643 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4644 io_queue_link_head(head);
4648 if (unlikely(ctx->drain_next)) {
4649 req->flags |= REQ_F_IO_DRAIN;
4650 req->ctx->drain_next = 0;
4652 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4653 req->flags |= REQ_F_LINK;
4654 if (sqe_flags & IOSQE_IO_HARDLINK)
4655 req->flags |= REQ_F_HARDLINK;
4657 INIT_LIST_HEAD(&req->link_list);
4658 ret = io_req_defer_prep(req, sqe);
4660 req->flags |= REQ_F_FAIL_LINK;
4663 io_queue_sqe(req, sqe);
4671 * Batched submission is done, ensure local IO is flushed out.
4673 static void io_submit_state_end(struct io_submit_state *state)
4675 blk_finish_plug(&state->plug);
4677 if (state->free_reqs)
4678 kmem_cache_free_bulk(req_cachep, state->free_reqs,
4679 &state->reqs[state->cur_req]);
4683 * Start submission side cache.
4685 static void io_submit_state_start(struct io_submit_state *state,
4686 unsigned int max_ios)
4688 blk_start_plug(&state->plug);
4689 state->free_reqs = 0;
4691 state->ios_left = max_ios;
4694 static void io_commit_sqring(struct io_ring_ctx *ctx)
4696 struct io_rings *rings = ctx->rings;
4699 * Ensure any loads from the SQEs are done at this point,
4700 * since once we write the new head, the application could
4701 * write new data to them.
4703 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4707 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4708 * that is mapped by userspace. This means that care needs to be taken to
4709 * ensure that reads are stable, as we cannot rely on userspace always
4710 * being a good citizen. If members of the sqe are validated and then later
4711 * used, it's important that those reads are done through READ_ONCE() to
4712 * prevent a re-load down the line.
4714 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4715 const struct io_uring_sqe **sqe_ptr)
4717 u32 *sq_array = ctx->sq_array;
4721 * The cached sq head (or cq tail) serves two purposes:
4723 * 1) allows us to batch the cost of updating the user visible
4725 * 2) allows the kernel side to track the head on its own, even
4726 * though the application is the one updating it.
4728 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4729 if (likely(head < ctx->sq_entries)) {
4731 * All io need record the previous position, if LINK vs DARIN,
4732 * it can be used to mark the position of the first IO in the
4735 req->sequence = ctx->cached_sq_head;
4736 *sqe_ptr = &ctx->sq_sqes[head];
4737 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4738 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4739 ctx->cached_sq_head++;
4743 /* drop invalid entries */
4744 ctx->cached_sq_head++;
4745 ctx->cached_sq_dropped++;
4746 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4750 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4751 struct file *ring_file, int ring_fd,
4752 struct mm_struct **mm, bool async)
4754 struct io_submit_state state, *statep = NULL;
4755 struct io_kiocb *link = NULL;
4756 int i, submitted = 0;
4757 bool mm_fault = false;
4759 /* if we have a backlog and couldn't flush it all, return BUSY */
4760 if (test_bit(0, &ctx->sq_check_overflow)) {
4761 if (!list_empty(&ctx->cq_overflow_list) &&
4762 !io_cqring_overflow_flush(ctx, false))
4766 /* make sure SQ entry isn't read before tail */
4767 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
4769 if (!percpu_ref_tryget_many(&ctx->refs, nr))
4772 if (nr > IO_PLUG_THRESHOLD) {
4773 io_submit_state_start(&state, nr);
4777 ctx->ring_fd = ring_fd;
4778 ctx->ring_file = ring_file;
4780 for (i = 0; i < nr; i++) {
4781 const struct io_uring_sqe *sqe;
4782 struct io_kiocb *req;
4784 req = io_get_req(ctx, statep);
4785 if (unlikely(!req)) {
4787 submitted = -EAGAIN;
4790 if (!io_get_sqring(ctx, req, &sqe)) {
4791 __io_req_do_free(req);
4795 /* will complete beyond this point, count as submitted */
4798 if (unlikely(req->opcode >= IORING_OP_LAST)) {
4799 io_cqring_add_event(req, -EINVAL);
4800 io_double_put_req(req);
4804 if (io_op_defs[req->opcode].needs_mm && !*mm) {
4805 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
4807 use_mm(ctx->sqo_mm);
4812 req->has_user = *mm != NULL;
4813 req->in_async = async;
4814 req->needs_fixed_file = async;
4815 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
4817 if (!io_submit_sqe(req, sqe, statep, &link))
4821 if (submitted != nr)
4822 percpu_ref_put_many(&ctx->refs, nr - submitted);
4824 io_queue_link_head(link);
4826 io_submit_state_end(&state);
4828 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4829 io_commit_sqring(ctx);
4834 static int io_sq_thread(void *data)
4836 struct io_ring_ctx *ctx = data;
4837 struct mm_struct *cur_mm = NULL;
4838 const struct cred *old_cred;
4839 mm_segment_t old_fs;
4842 unsigned long timeout;
4845 complete(&ctx->completions[1]);
4849 old_cred = override_creds(ctx->creds);
4851 ret = timeout = inflight = 0;
4852 while (!kthread_should_park()) {
4853 unsigned int to_submit;
4856 unsigned nr_events = 0;
4858 if (ctx->flags & IORING_SETUP_IOPOLL) {
4860 * inflight is the count of the maximum possible
4861 * entries we submitted, but it can be smaller
4862 * if we dropped some of them. If we don't have
4863 * poll entries available, then we know that we
4864 * have nothing left to poll for. Reset the
4865 * inflight count to zero in that case.
4867 mutex_lock(&ctx->uring_lock);
4868 if (!list_empty(&ctx->poll_list))
4869 __io_iopoll_check(ctx, &nr_events, 0);
4872 mutex_unlock(&ctx->uring_lock);
4875 * Normal IO, just pretend everything completed.
4876 * We don't have to poll completions for that.
4878 nr_events = inflight;
4881 inflight -= nr_events;
4883 timeout = jiffies + ctx->sq_thread_idle;
4886 to_submit = io_sqring_entries(ctx);
4889 * If submit got -EBUSY, flag us as needing the application
4890 * to enter the kernel to reap and flush events.
4892 if (!to_submit || ret == -EBUSY) {
4894 * We're polling. If we're within the defined idle
4895 * period, then let us spin without work before going
4896 * to sleep. The exception is if we got EBUSY doing
4897 * more IO, we should wait for the application to
4898 * reap events and wake us up.
4901 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
4907 * Drop cur_mm before scheduling, we can't hold it for
4908 * long periods (or over schedule()). Do this before
4909 * adding ourselves to the waitqueue, as the unuse/drop
4918 prepare_to_wait(&ctx->sqo_wait, &wait,
4919 TASK_INTERRUPTIBLE);
4921 /* Tell userspace we may need a wakeup call */
4922 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
4923 /* make sure to read SQ tail after writing flags */
4926 to_submit = io_sqring_entries(ctx);
4927 if (!to_submit || ret == -EBUSY) {
4928 if (kthread_should_park()) {
4929 finish_wait(&ctx->sqo_wait, &wait);
4932 if (signal_pending(current))
4933 flush_signals(current);
4935 finish_wait(&ctx->sqo_wait, &wait);
4937 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4940 finish_wait(&ctx->sqo_wait, &wait);
4942 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4945 mutex_lock(&ctx->uring_lock);
4946 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
4947 mutex_unlock(&ctx->uring_lock);
4957 revert_creds(old_cred);
4964 struct io_wait_queue {
4965 struct wait_queue_entry wq;
4966 struct io_ring_ctx *ctx;
4968 unsigned nr_timeouts;
4971 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
4973 struct io_ring_ctx *ctx = iowq->ctx;
4976 * Wake up if we have enough events, or if a timeout occurred since we
4977 * started waiting. For timeouts, we always want to return to userspace,
4978 * regardless of event count.
4980 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
4981 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4984 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
4985 int wake_flags, void *key)
4987 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
4990 /* use noflush == true, as we can't safely rely on locking context */
4991 if (!io_should_wake(iowq, true))
4994 return autoremove_wake_function(curr, mode, wake_flags, key);
4998 * Wait until events become available, if we don't already have some. The
4999 * application must reap them itself, as they reside on the shared cq ring.
5001 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5002 const sigset_t __user *sig, size_t sigsz)
5004 struct io_wait_queue iowq = {
5007 .func = io_wake_function,
5008 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5011 .to_wait = min_events,
5013 struct io_rings *rings = ctx->rings;
5016 if (io_cqring_events(ctx, false) >= min_events)
5020 #ifdef CONFIG_COMPAT
5021 if (in_compat_syscall())
5022 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5026 ret = set_user_sigmask(sig, sigsz);
5032 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5033 trace_io_uring_cqring_wait(ctx, min_events);
5035 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5036 TASK_INTERRUPTIBLE);
5037 if (io_should_wake(&iowq, false))
5040 if (signal_pending(current)) {
5045 finish_wait(&ctx->wait, &iowq.wq);
5047 restore_saved_sigmask_unless(ret == -EINTR);
5049 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5052 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5054 #if defined(CONFIG_UNIX)
5055 if (ctx->ring_sock) {
5056 struct sock *sock = ctx->ring_sock->sk;
5057 struct sk_buff *skb;
5059 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5065 for (i = 0; i < ctx->nr_user_files; i++) {
5068 file = io_file_from_index(ctx, i);
5075 static void io_file_ref_kill(struct percpu_ref *ref)
5077 struct fixed_file_data *data;
5079 data = container_of(ref, struct fixed_file_data, refs);
5080 complete(&data->done);
5083 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5085 struct fixed_file_data *data = ctx->file_data;
5086 unsigned nr_tables, i;
5091 /* protect against inflight atomic switch, which drops the ref */
5092 flush_work(&data->ref_work);
5093 percpu_ref_get(&data->refs);
5094 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5095 wait_for_completion(&data->done);
5096 percpu_ref_put(&data->refs);
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);