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>
49 #include <linux/bits.h>
51 #include <linux/sched/signal.h>
53 #include <linux/file.h>
54 #include <linux/fdtable.h>
56 #include <linux/mman.h>
57 #include <linux/mmu_context.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
78 #define CREATE_TRACE_POINTS
79 #include <trace/events/io_uring.h>
81 #include <uapi/linux/io_uring.h>
86 #define IORING_MAX_ENTRIES 32768
87 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
90 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
92 #define IORING_FILE_TABLE_SHIFT 9
93 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
94 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
95 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
98 u32 head ____cacheline_aligned_in_smp;
99 u32 tail ____cacheline_aligned_in_smp;
103 * This data is shared with the application through the mmap at offsets
104 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
106 * The offsets to the member fields are published through struct
107 * io_sqring_offsets when calling io_uring_setup.
111 * Head and tail offsets into the ring; the offsets need to be
112 * masked to get valid indices.
114 * The kernel controls head of the sq ring and the tail of the cq ring,
115 * and the application controls tail of the sq ring and the head of the
118 struct io_uring sq, cq;
120 * Bitmasks to apply to head and tail offsets (constant, equals
123 u32 sq_ring_mask, cq_ring_mask;
124 /* Ring sizes (constant, power of 2) */
125 u32 sq_ring_entries, cq_ring_entries;
127 * Number of invalid entries dropped by the kernel due to
128 * invalid index stored in array
130 * Written by the kernel, shouldn't be modified by the
131 * application (i.e. get number of "new events" by comparing to
134 * After a new SQ head value was read by the application this
135 * counter includes all submissions that were dropped reaching
136 * the new SQ head (and possibly more).
142 * Written by the kernel, shouldn't be modified by the
145 * The application needs a full memory barrier before checking
146 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
150 * Number of completion events lost because the queue was full;
151 * this should be avoided by the application by making sure
152 * there are not more requests pending than there is space in
153 * the completion queue.
155 * Written by the kernel, shouldn't be modified by the
156 * application (i.e. get number of "new events" by comparing to
159 * As completion events come in out of order this counter is not
160 * ordered with any other data.
164 * Ring buffer of completion events.
166 * The kernel writes completion events fresh every time they are
167 * produced, so the application is allowed to modify pending
170 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
173 struct io_mapped_ubuf {
176 struct bio_vec *bvec;
177 unsigned int nr_bvecs;
180 struct fixed_file_table {
188 struct fixed_file_data {
189 struct fixed_file_table *table;
190 struct io_ring_ctx *ctx;
192 struct percpu_ref refs;
193 struct llist_head put_llist;
195 struct work_struct ref_work;
196 struct completion done;
201 struct percpu_ref refs;
202 } ____cacheline_aligned_in_smp;
208 int cq_overflow_flushed: 1;
210 int eventfd_async: 1;
213 * Ring buffer of indices into array of io_uring_sqe, which is
214 * mmapped by the application using the IORING_OFF_SQES offset.
216 * This indirection could e.g. be used to assign fixed
217 * io_uring_sqe entries to operations and only submit them to
218 * the queue when needed.
220 * The kernel modifies neither the indices array nor the entries
224 unsigned cached_sq_head;
227 unsigned sq_thread_idle;
228 unsigned cached_sq_dropped;
229 atomic_t cached_cq_overflow;
230 unsigned long sq_check_overflow;
232 struct list_head defer_list;
233 struct list_head timeout_list;
234 struct list_head cq_overflow_list;
236 wait_queue_head_t inflight_wait;
237 struct io_uring_sqe *sq_sqes;
238 } ____cacheline_aligned_in_smp;
240 struct io_rings *rings;
244 struct task_struct *sqo_thread; /* if using sq thread polling */
245 struct mm_struct *sqo_mm;
246 wait_queue_head_t sqo_wait;
249 * If used, fixed file set. Writers must ensure that ->refs is dead,
250 * readers must ensure that ->refs is alive as long as the file* is
251 * used. Only updated through io_uring_register(2).
253 struct fixed_file_data *file_data;
254 unsigned nr_user_files;
256 struct file *ring_file;
258 /* if used, fixed mapped user buffers */
259 unsigned nr_user_bufs;
260 struct io_mapped_ubuf *user_bufs;
262 struct user_struct *user;
264 const struct cred *creds;
266 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
267 struct completion *completions;
269 /* if all else fails... */
270 struct io_kiocb *fallback_req;
272 #if defined(CONFIG_UNIX)
273 struct socket *ring_sock;
277 unsigned cached_cq_tail;
280 atomic_t cq_timeouts;
281 unsigned long cq_check_overflow;
282 struct wait_queue_head cq_wait;
283 struct fasync_struct *cq_fasync;
284 struct eventfd_ctx *cq_ev_fd;
285 } ____cacheline_aligned_in_smp;
288 struct mutex uring_lock;
289 wait_queue_head_t wait;
290 } ____cacheline_aligned_in_smp;
293 spinlock_t completion_lock;
294 struct llist_head poll_llist;
297 * ->poll_list is protected by the ctx->uring_lock for
298 * io_uring instances that don't use IORING_SETUP_SQPOLL.
299 * For SQPOLL, only the single threaded io_sq_thread() will
300 * manipulate the list, hence no extra locking is needed there.
302 struct list_head poll_list;
303 struct hlist_head *cancel_hash;
304 unsigned cancel_hash_bits;
305 bool poll_multi_file;
307 spinlock_t inflight_lock;
308 struct list_head inflight_list;
309 } ____cacheline_aligned_in_smp;
313 * First field must be the file pointer in all the
314 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
316 struct io_poll_iocb {
319 struct wait_queue_head *head;
325 struct wait_queue_entry wait;
330 struct file *put_file;
334 struct io_timeout_data {
335 struct io_kiocb *req;
336 struct hrtimer timer;
337 struct timespec64 ts;
338 enum hrtimer_mode mode;
344 struct sockaddr __user *addr;
345 int __user *addr_len;
370 /* NOTE: kiocb has the file as the first member, so don't do it here */
378 struct sockaddr __user *addr;
385 struct user_msghdr __user *msg;
398 struct filename *filename;
399 struct statx __user *buffer;
403 struct io_files_update {
424 struct io_async_connect {
425 struct sockaddr_storage address;
428 struct io_async_msghdr {
429 struct iovec fast_iov[UIO_FASTIOV];
431 struct sockaddr __user *uaddr;
436 struct iovec fast_iov[UIO_FASTIOV];
442 struct io_async_open {
443 struct filename *filename;
446 struct io_async_ctx {
448 struct io_async_rw rw;
449 struct io_async_msghdr msg;
450 struct io_async_connect connect;
451 struct io_timeout_data timeout;
452 struct io_async_open open;
457 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
458 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
459 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
460 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
461 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
468 REQ_F_IOPOLL_COMPLETED_BIT,
469 REQ_F_LINK_TIMEOUT_BIT,
473 REQ_F_TIMEOUT_NOSEQ_BIT,
474 REQ_F_COMP_LOCKED_BIT,
479 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
480 /* drain existing IO first */
481 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
483 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
484 /* doesn't sever on completion < 0 */
485 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
487 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
489 /* already grabbed next link */
490 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
491 /* fail rest of links */
492 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
493 /* on inflight list */
494 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
495 /* read/write uses file position */
496 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
497 /* must not punt to workers */
498 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
499 /* polled IO has completed */
500 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
501 /* has linked timeout */
502 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
503 /* timeout request */
504 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
506 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
507 /* must be punted even for NONBLOCK */
508 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
509 /* no timeout sequence */
510 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
511 /* completion under lock */
512 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
516 * NOTE! Each of the iocb union members has the file pointer
517 * as the first entry in their struct definition. So you can
518 * access the file pointer through any of the sub-structs,
519 * or directly as just 'ki_filp' in this struct.
525 struct io_poll_iocb poll;
526 struct io_accept accept;
528 struct io_cancel cancel;
529 struct io_timeout timeout;
530 struct io_connect connect;
531 struct io_sr_msg sr_msg;
533 struct io_close close;
534 struct io_files_update files_update;
535 struct io_fadvise fadvise;
536 struct io_madvise madvise;
539 struct io_async_ctx *io;
541 * llist_node is only used for poll deferred completions
543 struct llist_node llist_node;
546 bool needs_fixed_file;
549 struct io_ring_ctx *ctx;
551 struct list_head list;
552 struct hlist_node hash_node;
554 struct list_head link_list;
561 struct list_head inflight_entry;
563 struct io_wq_work work;
566 #define IO_PLUG_THRESHOLD 2
567 #define IO_IOPOLL_BATCH 8
569 struct io_submit_state {
570 struct blk_plug plug;
573 * io_kiocb alloc cache
575 void *reqs[IO_IOPOLL_BATCH];
576 unsigned int free_reqs;
577 unsigned int cur_req;
580 * File reference cache
584 unsigned int has_refs;
585 unsigned int used_refs;
586 unsigned int ios_left;
590 /* needs req->io allocated for deferral/async */
591 unsigned async_ctx : 1;
592 /* needs current->mm setup, does mm access */
593 unsigned needs_mm : 1;
594 /* needs req->file assigned */
595 unsigned needs_file : 1;
596 /* needs req->file assigned IFF fd is >= 0 */
597 unsigned fd_non_neg : 1;
598 /* hash wq insertion if file is a regular file */
599 unsigned hash_reg_file : 1;
600 /* unbound wq insertion if file is a non-regular file */
601 unsigned unbound_nonreg_file : 1;
602 /* opcode is not supported by this kernel */
603 unsigned not_supported : 1;
606 static const struct io_op_def io_op_defs[] = {
607 [IORING_OP_NOP] = {},
608 [IORING_OP_READV] = {
612 .unbound_nonreg_file = 1,
614 [IORING_OP_WRITEV] = {
619 .unbound_nonreg_file = 1,
621 [IORING_OP_FSYNC] = {
624 [IORING_OP_READ_FIXED] = {
626 .unbound_nonreg_file = 1,
628 [IORING_OP_WRITE_FIXED] = {
631 .unbound_nonreg_file = 1,
633 [IORING_OP_POLL_ADD] = {
635 .unbound_nonreg_file = 1,
637 [IORING_OP_POLL_REMOVE] = {},
638 [IORING_OP_SYNC_FILE_RANGE] = {
641 [IORING_OP_SENDMSG] = {
645 .unbound_nonreg_file = 1,
647 [IORING_OP_RECVMSG] = {
651 .unbound_nonreg_file = 1,
653 [IORING_OP_TIMEOUT] = {
657 [IORING_OP_TIMEOUT_REMOVE] = {},
658 [IORING_OP_ACCEPT] = {
661 .unbound_nonreg_file = 1,
663 [IORING_OP_ASYNC_CANCEL] = {},
664 [IORING_OP_LINK_TIMEOUT] = {
668 [IORING_OP_CONNECT] = {
672 .unbound_nonreg_file = 1,
674 [IORING_OP_FALLOCATE] = {
677 [IORING_OP_OPENAT] = {
681 [IORING_OP_CLOSE] = {
684 [IORING_OP_FILES_UPDATE] = {
687 [IORING_OP_STATX] = {
695 .unbound_nonreg_file = 1,
697 [IORING_OP_WRITE] = {
700 .unbound_nonreg_file = 1,
702 [IORING_OP_FADVISE] = {
705 [IORING_OP_MADVISE] = {
711 .unbound_nonreg_file = 1,
716 .unbound_nonreg_file = 1,
718 [IORING_OP_OPENAT2] = {
724 static void io_wq_submit_work(struct io_wq_work **workptr);
725 static void io_cqring_fill_event(struct io_kiocb *req, long res);
726 static void io_put_req(struct io_kiocb *req);
727 static void __io_double_put_req(struct io_kiocb *req);
728 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
729 static void io_queue_linked_timeout(struct io_kiocb *req);
730 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
731 struct io_uring_files_update *ip,
734 static struct kmem_cache *req_cachep;
736 static const struct file_operations io_uring_fops;
738 struct sock *io_uring_get_socket(struct file *file)
740 #if defined(CONFIG_UNIX)
741 if (file->f_op == &io_uring_fops) {
742 struct io_ring_ctx *ctx = file->private_data;
744 return ctx->ring_sock->sk;
749 EXPORT_SYMBOL(io_uring_get_socket);
751 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
753 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
755 complete(&ctx->completions[0]);
758 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
760 struct io_ring_ctx *ctx;
763 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
767 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
768 if (!ctx->fallback_req)
771 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
772 if (!ctx->completions)
776 * Use 5 bits less than the max cq entries, that should give us around
777 * 32 entries per hash list if totally full and uniformly spread.
779 hash_bits = ilog2(p->cq_entries);
783 ctx->cancel_hash_bits = hash_bits;
784 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
786 if (!ctx->cancel_hash)
788 __hash_init(ctx->cancel_hash, 1U << hash_bits);
790 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
791 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
794 ctx->flags = p->flags;
795 init_waitqueue_head(&ctx->cq_wait);
796 INIT_LIST_HEAD(&ctx->cq_overflow_list);
797 init_completion(&ctx->completions[0]);
798 init_completion(&ctx->completions[1]);
799 mutex_init(&ctx->uring_lock);
800 init_waitqueue_head(&ctx->wait);
801 spin_lock_init(&ctx->completion_lock);
802 init_llist_head(&ctx->poll_llist);
803 INIT_LIST_HEAD(&ctx->poll_list);
804 INIT_LIST_HEAD(&ctx->defer_list);
805 INIT_LIST_HEAD(&ctx->timeout_list);
806 init_waitqueue_head(&ctx->inflight_wait);
807 spin_lock_init(&ctx->inflight_lock);
808 INIT_LIST_HEAD(&ctx->inflight_list);
811 if (ctx->fallback_req)
812 kmem_cache_free(req_cachep, ctx->fallback_req);
813 kfree(ctx->completions);
814 kfree(ctx->cancel_hash);
819 static inline bool __req_need_defer(struct io_kiocb *req)
821 struct io_ring_ctx *ctx = req->ctx;
823 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
824 + atomic_read(&ctx->cached_cq_overflow);
827 static inline bool req_need_defer(struct io_kiocb *req)
829 if (unlikely(req->flags & REQ_F_IO_DRAIN))
830 return __req_need_defer(req);
835 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
837 struct io_kiocb *req;
839 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
840 if (req && !req_need_defer(req)) {
841 list_del_init(&req->list);
848 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
850 struct io_kiocb *req;
852 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
854 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
856 if (!__req_need_defer(req)) {
857 list_del_init(&req->list);
865 static void __io_commit_cqring(struct io_ring_ctx *ctx)
867 struct io_rings *rings = ctx->rings;
869 /* order cqe stores with ring update */
870 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
872 if (wq_has_sleeper(&ctx->cq_wait)) {
873 wake_up_interruptible(&ctx->cq_wait);
874 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
878 static inline bool io_prep_async_work(struct io_kiocb *req,
879 struct io_kiocb **link)
881 const struct io_op_def *def = &io_op_defs[req->opcode];
882 bool do_hashed = false;
884 if (req->flags & REQ_F_ISREG) {
885 if (def->hash_reg_file)
888 if (def->unbound_nonreg_file)
889 req->work.flags |= IO_WQ_WORK_UNBOUND;
892 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
894 *link = io_prep_linked_timeout(req);
898 static inline void io_queue_async_work(struct io_kiocb *req)
900 struct io_ring_ctx *ctx = req->ctx;
901 struct io_kiocb *link;
904 do_hashed = io_prep_async_work(req, &link);
906 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
909 io_wq_enqueue(ctx->io_wq, &req->work);
911 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
912 file_inode(req->file));
916 io_queue_linked_timeout(link);
919 static void io_kill_timeout(struct io_kiocb *req)
923 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
925 atomic_inc(&req->ctx->cq_timeouts);
926 list_del_init(&req->list);
927 io_cqring_fill_event(req, 0);
932 static void io_kill_timeouts(struct io_ring_ctx *ctx)
934 struct io_kiocb *req, *tmp;
936 spin_lock_irq(&ctx->completion_lock);
937 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
938 io_kill_timeout(req);
939 spin_unlock_irq(&ctx->completion_lock);
942 static void io_commit_cqring(struct io_ring_ctx *ctx)
944 struct io_kiocb *req;
946 while ((req = io_get_timeout_req(ctx)) != NULL)
947 io_kill_timeout(req);
949 __io_commit_cqring(ctx);
951 while ((req = io_get_deferred_req(ctx)) != NULL)
952 io_queue_async_work(req);
955 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
957 struct io_rings *rings = ctx->rings;
960 tail = ctx->cached_cq_tail;
962 * writes to the cq entry need to come after reading head; the
963 * control dependency is enough as we're using WRITE_ONCE to
966 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
969 ctx->cached_cq_tail++;
970 return &rings->cqes[tail & ctx->cq_mask];
973 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
975 if (!ctx->eventfd_async)
977 return io_wq_current_is_worker() || in_interrupt();
980 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
982 if (waitqueue_active(&ctx->wait))
984 if (waitqueue_active(&ctx->sqo_wait))
985 wake_up(&ctx->sqo_wait);
986 if (ctx->cq_ev_fd && io_should_trigger_evfd(ctx))
987 eventfd_signal(ctx->cq_ev_fd, 1);
990 /* Returns true if there are no backlogged entries after the flush */
991 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
993 struct io_rings *rings = ctx->rings;
994 struct io_uring_cqe *cqe;
995 struct io_kiocb *req;
1000 if (list_empty_careful(&ctx->cq_overflow_list))
1002 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1003 rings->cq_ring_entries))
1007 spin_lock_irqsave(&ctx->completion_lock, flags);
1009 /* if force is set, the ring is going away. always drop after that */
1011 ctx->cq_overflow_flushed = 1;
1014 while (!list_empty(&ctx->cq_overflow_list)) {
1015 cqe = io_get_cqring(ctx);
1019 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1021 list_move(&req->list, &list);
1023 WRITE_ONCE(cqe->user_data, req->user_data);
1024 WRITE_ONCE(cqe->res, req->result);
1025 WRITE_ONCE(cqe->flags, 0);
1027 WRITE_ONCE(ctx->rings->cq_overflow,
1028 atomic_inc_return(&ctx->cached_cq_overflow));
1032 io_commit_cqring(ctx);
1034 clear_bit(0, &ctx->sq_check_overflow);
1035 clear_bit(0, &ctx->cq_check_overflow);
1037 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1038 io_cqring_ev_posted(ctx);
1040 while (!list_empty(&list)) {
1041 req = list_first_entry(&list, struct io_kiocb, list);
1042 list_del(&req->list);
1049 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1051 struct io_ring_ctx *ctx = req->ctx;
1052 struct io_uring_cqe *cqe;
1054 trace_io_uring_complete(ctx, req->user_data, res);
1057 * If we can't get a cq entry, userspace overflowed the
1058 * submission (by quite a lot). Increment the overflow count in
1061 cqe = io_get_cqring(ctx);
1063 WRITE_ONCE(cqe->user_data, req->user_data);
1064 WRITE_ONCE(cqe->res, res);
1065 WRITE_ONCE(cqe->flags, 0);
1066 } else if (ctx->cq_overflow_flushed) {
1067 WRITE_ONCE(ctx->rings->cq_overflow,
1068 atomic_inc_return(&ctx->cached_cq_overflow));
1070 if (list_empty(&ctx->cq_overflow_list)) {
1071 set_bit(0, &ctx->sq_check_overflow);
1072 set_bit(0, &ctx->cq_check_overflow);
1074 refcount_inc(&req->refs);
1076 list_add_tail(&req->list, &ctx->cq_overflow_list);
1080 static void io_cqring_add_event(struct io_kiocb *req, long res)
1082 struct io_ring_ctx *ctx = req->ctx;
1083 unsigned long flags;
1085 spin_lock_irqsave(&ctx->completion_lock, flags);
1086 io_cqring_fill_event(req, res);
1087 io_commit_cqring(ctx);
1088 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1090 io_cqring_ev_posted(ctx);
1093 static inline bool io_is_fallback_req(struct io_kiocb *req)
1095 return req == (struct io_kiocb *)
1096 ((unsigned long) req->ctx->fallback_req & ~1UL);
1099 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1101 struct io_kiocb *req;
1103 req = ctx->fallback_req;
1104 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1110 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1111 struct io_submit_state *state)
1113 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1114 struct io_kiocb *req;
1117 req = kmem_cache_alloc(req_cachep, gfp);
1120 } else if (!state->free_reqs) {
1124 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1125 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1128 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1129 * retry single alloc to be on the safe side.
1131 if (unlikely(ret <= 0)) {
1132 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1133 if (!state->reqs[0])
1137 state->free_reqs = ret - 1;
1139 req = state->reqs[0];
1141 req = state->reqs[state->cur_req];
1151 /* one is dropped after submission, the other at completion */
1152 refcount_set(&req->refs, 2);
1154 INIT_IO_WORK(&req->work, io_wq_submit_work);
1157 req = io_get_fallback_req(ctx);
1160 percpu_ref_put(&ctx->refs);
1164 static void __io_req_do_free(struct io_kiocb *req)
1166 if (likely(!io_is_fallback_req(req)))
1167 kmem_cache_free(req_cachep, req);
1169 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1172 static void __io_req_aux_free(struct io_kiocb *req)
1174 struct io_ring_ctx *ctx = req->ctx;
1178 if (req->flags & REQ_F_FIXED_FILE)
1179 percpu_ref_put(&ctx->file_data->refs);
1185 static void __io_free_req(struct io_kiocb *req)
1187 __io_req_aux_free(req);
1189 if (req->flags & REQ_F_INFLIGHT) {
1190 struct io_ring_ctx *ctx = req->ctx;
1191 unsigned long flags;
1193 spin_lock_irqsave(&ctx->inflight_lock, flags);
1194 list_del(&req->inflight_entry);
1195 if (waitqueue_active(&ctx->inflight_wait))
1196 wake_up(&ctx->inflight_wait);
1197 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1200 percpu_ref_put(&req->ctx->refs);
1201 __io_req_do_free(req);
1205 void *reqs[IO_IOPOLL_BATCH];
1210 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1212 int fixed_refs = rb->to_free;
1216 if (rb->need_iter) {
1217 int i, inflight = 0;
1218 unsigned long flags;
1221 for (i = 0; i < rb->to_free; i++) {
1222 struct io_kiocb *req = rb->reqs[i];
1224 if (req->flags & REQ_F_FIXED_FILE) {
1228 if (req->flags & REQ_F_INFLIGHT)
1230 __io_req_aux_free(req);
1235 spin_lock_irqsave(&ctx->inflight_lock, flags);
1236 for (i = 0; i < rb->to_free; i++) {
1237 struct io_kiocb *req = rb->reqs[i];
1239 if (req->flags & REQ_F_INFLIGHT) {
1240 list_del(&req->inflight_entry);
1245 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1247 if (waitqueue_active(&ctx->inflight_wait))
1248 wake_up(&ctx->inflight_wait);
1251 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1253 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1254 percpu_ref_put_many(&ctx->refs, rb->to_free);
1255 rb->to_free = rb->need_iter = 0;
1258 static bool io_link_cancel_timeout(struct io_kiocb *req)
1260 struct io_ring_ctx *ctx = req->ctx;
1263 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1265 io_cqring_fill_event(req, -ECANCELED);
1266 io_commit_cqring(ctx);
1267 req->flags &= ~REQ_F_LINK;
1275 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1277 struct io_ring_ctx *ctx = req->ctx;
1278 bool wake_ev = false;
1280 /* Already got next link */
1281 if (req->flags & REQ_F_LINK_NEXT)
1285 * The list should never be empty when we are called here. But could
1286 * potentially happen if the chain is messed up, check to be on the
1289 while (!list_empty(&req->link_list)) {
1290 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1291 struct io_kiocb, link_list);
1293 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1294 (nxt->flags & REQ_F_TIMEOUT))) {
1295 list_del_init(&nxt->link_list);
1296 wake_ev |= io_link_cancel_timeout(nxt);
1297 req->flags &= ~REQ_F_LINK_TIMEOUT;
1301 list_del_init(&req->link_list);
1302 if (!list_empty(&nxt->link_list))
1303 nxt->flags |= REQ_F_LINK;
1308 req->flags |= REQ_F_LINK_NEXT;
1310 io_cqring_ev_posted(ctx);
1314 * Called if REQ_F_LINK is set, and we fail the head request
1316 static void io_fail_links(struct io_kiocb *req)
1318 struct io_ring_ctx *ctx = req->ctx;
1319 unsigned long flags;
1321 spin_lock_irqsave(&ctx->completion_lock, flags);
1323 while (!list_empty(&req->link_list)) {
1324 struct io_kiocb *link = list_first_entry(&req->link_list,
1325 struct io_kiocb, link_list);
1327 list_del_init(&link->link_list);
1328 trace_io_uring_fail_link(req, link);
1330 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1331 link->opcode == IORING_OP_LINK_TIMEOUT) {
1332 io_link_cancel_timeout(link);
1334 io_cqring_fill_event(link, -ECANCELED);
1335 __io_double_put_req(link);
1337 req->flags &= ~REQ_F_LINK_TIMEOUT;
1340 io_commit_cqring(ctx);
1341 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1342 io_cqring_ev_posted(ctx);
1345 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1347 if (likely(!(req->flags & REQ_F_LINK)))
1351 * If LINK is set, we have dependent requests in this chain. If we
1352 * didn't fail this request, queue the first one up, moving any other
1353 * dependencies to the next request. In case of failure, fail the rest
1356 if (req->flags & REQ_F_FAIL_LINK) {
1358 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1359 REQ_F_LINK_TIMEOUT) {
1360 struct io_ring_ctx *ctx = req->ctx;
1361 unsigned long flags;
1364 * If this is a timeout link, we could be racing with the
1365 * timeout timer. Grab the completion lock for this case to
1366 * protect against that.
1368 spin_lock_irqsave(&ctx->completion_lock, flags);
1369 io_req_link_next(req, nxt);
1370 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1372 io_req_link_next(req, nxt);
1376 static void io_free_req(struct io_kiocb *req)
1378 struct io_kiocb *nxt = NULL;
1380 io_req_find_next(req, &nxt);
1384 io_queue_async_work(nxt);
1388 * Drop reference to request, return next in chain (if there is one) if this
1389 * was the last reference to this request.
1391 __attribute__((nonnull))
1392 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1394 io_req_find_next(req, nxtptr);
1396 if (refcount_dec_and_test(&req->refs))
1400 static void io_put_req(struct io_kiocb *req)
1402 if (refcount_dec_and_test(&req->refs))
1407 * Must only be used if we don't need to care about links, usually from
1408 * within the completion handling itself.
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 void io_double_put_req(struct io_kiocb *req)
1419 /* drop both submit and complete references */
1420 if (refcount_sub_and_test(2, &req->refs))
1424 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1426 struct io_rings *rings = ctx->rings;
1428 if (test_bit(0, &ctx->cq_check_overflow)) {
1430 * noflush == true is from the waitqueue handler, just ensure
1431 * we wake up the task, and the next invocation will flush the
1432 * entries. We cannot safely to it from here.
1434 if (noflush && !list_empty(&ctx->cq_overflow_list))
1437 io_cqring_overflow_flush(ctx, false);
1440 /* See comment at the top of this file */
1442 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1445 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1447 struct io_rings *rings = ctx->rings;
1449 /* make sure SQ entry isn't read before tail */
1450 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1453 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1455 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1458 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1461 rb->reqs[rb->to_free++] = req;
1462 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1463 io_free_req_many(req->ctx, rb);
1468 * Find and free completed poll iocbs
1470 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1471 struct list_head *done)
1473 struct req_batch rb;
1474 struct io_kiocb *req;
1476 rb.to_free = rb.need_iter = 0;
1477 while (!list_empty(done)) {
1478 req = list_first_entry(done, struct io_kiocb, list);
1479 list_del(&req->list);
1481 io_cqring_fill_event(req, req->result);
1484 if (refcount_dec_and_test(&req->refs) &&
1485 !io_req_multi_free(&rb, req))
1489 io_commit_cqring(ctx);
1490 io_free_req_many(ctx, &rb);
1493 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1496 struct io_kiocb *req, *tmp;
1502 * Only spin for completions if we don't have multiple devices hanging
1503 * off our complete list, and we're under the requested amount.
1505 spin = !ctx->poll_multi_file && *nr_events < min;
1508 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1509 struct kiocb *kiocb = &req->rw.kiocb;
1512 * Move completed entries to our local list. If we find a
1513 * request that requires polling, break out and complete
1514 * the done list first, if we have entries there.
1516 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1517 list_move_tail(&req->list, &done);
1520 if (!list_empty(&done))
1523 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1532 if (!list_empty(&done))
1533 io_iopoll_complete(ctx, nr_events, &done);
1539 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1540 * non-spinning poll check - we'll still enter the driver poll loop, but only
1541 * as a non-spinning completion check.
1543 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1546 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1549 ret = io_do_iopoll(ctx, nr_events, min);
1552 if (!min || *nr_events >= min)
1560 * We can't just wait for polled events to come to us, we have to actively
1561 * find and complete them.
1563 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1565 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1568 mutex_lock(&ctx->uring_lock);
1569 while (!list_empty(&ctx->poll_list)) {
1570 unsigned int nr_events = 0;
1572 io_iopoll_getevents(ctx, &nr_events, 1);
1575 * Ensure we allow local-to-the-cpu processing to take place,
1576 * in this case we need to ensure that we reap all events.
1580 mutex_unlock(&ctx->uring_lock);
1583 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1586 int iters = 0, ret = 0;
1592 * Don't enter poll loop if we already have events pending.
1593 * If we do, we can potentially be spinning for commands that
1594 * already triggered a CQE (eg in error).
1596 if (io_cqring_events(ctx, false))
1600 * If a submit got punted to a workqueue, we can have the
1601 * application entering polling for a command before it gets
1602 * issued. That app will hold the uring_lock for the duration
1603 * of the poll right here, so we need to take a breather every
1604 * now and then to ensure that the issue has a chance to add
1605 * the poll to the issued list. Otherwise we can spin here
1606 * forever, while the workqueue is stuck trying to acquire the
1609 if (!(++iters & 7)) {
1610 mutex_unlock(&ctx->uring_lock);
1611 mutex_lock(&ctx->uring_lock);
1614 if (*nr_events < min)
1615 tmin = min - *nr_events;
1617 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1621 } while (min && !*nr_events && !need_resched());
1626 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1632 * We disallow the app entering submit/complete with polling, but we
1633 * still need to lock the ring to prevent racing with polled issue
1634 * that got punted to a workqueue.
1636 mutex_lock(&ctx->uring_lock);
1637 ret = __io_iopoll_check(ctx, nr_events, min);
1638 mutex_unlock(&ctx->uring_lock);
1642 static void kiocb_end_write(struct io_kiocb *req)
1645 * Tell lockdep we inherited freeze protection from submission
1648 if (req->flags & REQ_F_ISREG) {
1649 struct inode *inode = file_inode(req->file);
1651 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1653 file_end_write(req->file);
1656 static inline void req_set_fail_links(struct io_kiocb *req)
1658 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1659 req->flags |= REQ_F_FAIL_LINK;
1662 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1664 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1666 if (kiocb->ki_flags & IOCB_WRITE)
1667 kiocb_end_write(req);
1669 if (res != req->result)
1670 req_set_fail_links(req);
1671 io_cqring_add_event(req, res);
1674 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1676 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1678 io_complete_rw_common(kiocb, res);
1682 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1684 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1685 struct io_kiocb *nxt = NULL;
1687 io_complete_rw_common(kiocb, res);
1688 io_put_req_find_next(req, &nxt);
1693 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1695 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1697 if (kiocb->ki_flags & IOCB_WRITE)
1698 kiocb_end_write(req);
1700 if (res != req->result)
1701 req_set_fail_links(req);
1704 req->flags |= REQ_F_IOPOLL_COMPLETED;
1708 * After the iocb has been issued, it's safe to be found on the poll list.
1709 * Adding the kiocb to the list AFTER submission ensures that we don't
1710 * find it from a io_iopoll_getevents() thread before the issuer is done
1711 * accessing the kiocb cookie.
1713 static void io_iopoll_req_issued(struct io_kiocb *req)
1715 struct io_ring_ctx *ctx = req->ctx;
1718 * Track whether we have multiple files in our lists. This will impact
1719 * how we do polling eventually, not spinning if we're on potentially
1720 * different devices.
1722 if (list_empty(&ctx->poll_list)) {
1723 ctx->poll_multi_file = false;
1724 } else if (!ctx->poll_multi_file) {
1725 struct io_kiocb *list_req;
1727 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1729 if (list_req->file != req->file)
1730 ctx->poll_multi_file = true;
1734 * For fast devices, IO may have already completed. If it has, add
1735 * it to the front so we find it first.
1737 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1738 list_add(&req->list, &ctx->poll_list);
1740 list_add_tail(&req->list, &ctx->poll_list);
1743 static void io_file_put(struct io_submit_state *state)
1746 int diff = state->has_refs - state->used_refs;
1749 fput_many(state->file, diff);
1755 * Get as many references to a file as we have IOs left in this submission,
1756 * assuming most submissions are for one file, or at least that each file
1757 * has more than one submission.
1759 static struct file *io_file_get(struct io_submit_state *state, int fd)
1765 if (state->fd == fd) {
1772 state->file = fget_many(fd, state->ios_left);
1777 state->has_refs = state->ios_left;
1778 state->used_refs = 1;
1784 * If we tracked the file through the SCM inflight mechanism, we could support
1785 * any file. For now, just ensure that anything potentially problematic is done
1788 static bool io_file_supports_async(struct file *file)
1790 umode_t mode = file_inode(file)->i_mode;
1792 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1794 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1800 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1801 bool force_nonblock)
1803 struct io_ring_ctx *ctx = req->ctx;
1804 struct kiocb *kiocb = &req->rw.kiocb;
1811 if (S_ISREG(file_inode(req->file)->i_mode))
1812 req->flags |= REQ_F_ISREG;
1814 kiocb->ki_pos = READ_ONCE(sqe->off);
1815 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1816 req->flags |= REQ_F_CUR_POS;
1817 kiocb->ki_pos = req->file->f_pos;
1819 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1820 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1822 ioprio = READ_ONCE(sqe->ioprio);
1824 ret = ioprio_check_cap(ioprio);
1828 kiocb->ki_ioprio = ioprio;
1830 kiocb->ki_ioprio = get_current_ioprio();
1832 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1836 /* don't allow async punt if RWF_NOWAIT was requested */
1837 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1838 (req->file->f_flags & O_NONBLOCK))
1839 req->flags |= REQ_F_NOWAIT;
1842 kiocb->ki_flags |= IOCB_NOWAIT;
1844 if (ctx->flags & IORING_SETUP_IOPOLL) {
1845 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1846 !kiocb->ki_filp->f_op->iopoll)
1849 kiocb->ki_flags |= IOCB_HIPRI;
1850 kiocb->ki_complete = io_complete_rw_iopoll;
1853 if (kiocb->ki_flags & IOCB_HIPRI)
1855 kiocb->ki_complete = io_complete_rw;
1858 req->rw.addr = READ_ONCE(sqe->addr);
1859 req->rw.len = READ_ONCE(sqe->len);
1860 /* we own ->private, reuse it for the buffer index */
1861 req->rw.kiocb.private = (void *) (unsigned long)
1862 READ_ONCE(sqe->buf_index);
1866 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1872 case -ERESTARTNOINTR:
1873 case -ERESTARTNOHAND:
1874 case -ERESTART_RESTARTBLOCK:
1876 * We can't just restart the syscall, since previously
1877 * submitted sqes may already be in progress. Just fail this
1883 kiocb->ki_complete(kiocb, ret, 0);
1887 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1890 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1892 if (req->flags & REQ_F_CUR_POS)
1893 req->file->f_pos = kiocb->ki_pos;
1894 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1895 *nxt = __io_complete_rw(kiocb, ret);
1897 io_rw_done(kiocb, ret);
1900 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1901 struct iov_iter *iter)
1903 struct io_ring_ctx *ctx = req->ctx;
1904 size_t len = req->rw.len;
1905 struct io_mapped_ubuf *imu;
1906 unsigned index, buf_index;
1910 /* attempt to use fixed buffers without having provided iovecs */
1911 if (unlikely(!ctx->user_bufs))
1914 buf_index = (unsigned long) req->rw.kiocb.private;
1915 if (unlikely(buf_index >= ctx->nr_user_bufs))
1918 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1919 imu = &ctx->user_bufs[index];
1920 buf_addr = req->rw.addr;
1923 if (buf_addr + len < buf_addr)
1925 /* not inside the mapped region */
1926 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1930 * May not be a start of buffer, set size appropriately
1931 * and advance us to the beginning.
1933 offset = buf_addr - imu->ubuf;
1934 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1938 * Don't use iov_iter_advance() here, as it's really slow for
1939 * using the latter parts of a big fixed buffer - it iterates
1940 * over each segment manually. We can cheat a bit here, because
1943 * 1) it's a BVEC iter, we set it up
1944 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1945 * first and last bvec
1947 * So just find our index, and adjust the iterator afterwards.
1948 * If the offset is within the first bvec (or the whole first
1949 * bvec, just use iov_iter_advance(). This makes it easier
1950 * since we can just skip the first segment, which may not
1951 * be PAGE_SIZE aligned.
1953 const struct bio_vec *bvec = imu->bvec;
1955 if (offset <= bvec->bv_len) {
1956 iov_iter_advance(iter, offset);
1958 unsigned long seg_skip;
1960 /* skip first vec */
1961 offset -= bvec->bv_len;
1962 seg_skip = 1 + (offset >> PAGE_SHIFT);
1964 iter->bvec = bvec + seg_skip;
1965 iter->nr_segs -= seg_skip;
1966 iter->count -= bvec->bv_len + offset;
1967 iter->iov_offset = offset & ~PAGE_MASK;
1974 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1975 struct iovec **iovec, struct iov_iter *iter)
1977 void __user *buf = u64_to_user_ptr(req->rw.addr);
1978 size_t sqe_len = req->rw.len;
1981 opcode = req->opcode;
1982 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1984 return io_import_fixed(req, rw, iter);
1987 /* buffer index only valid with fixed read/write */
1988 if (req->rw.kiocb.private)
1991 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
1993 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
1999 struct io_async_rw *iorw = &req->io->rw;
2002 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2003 if (iorw->iov == iorw->fast_iov)
2011 #ifdef CONFIG_COMPAT
2012 if (req->ctx->compat)
2013 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2017 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2021 * For files that don't have ->read_iter() and ->write_iter(), handle them
2022 * by looping over ->read() or ->write() manually.
2024 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2025 struct iov_iter *iter)
2030 * Don't support polled IO through this interface, and we can't
2031 * support non-blocking either. For the latter, this just causes
2032 * the kiocb to be handled from an async context.
2034 if (kiocb->ki_flags & IOCB_HIPRI)
2036 if (kiocb->ki_flags & IOCB_NOWAIT)
2039 while (iov_iter_count(iter)) {
2043 if (!iov_iter_is_bvec(iter)) {
2044 iovec = iov_iter_iovec(iter);
2046 /* fixed buffers import bvec */
2047 iovec.iov_base = kmap(iter->bvec->bv_page)
2049 iovec.iov_len = min(iter->count,
2050 iter->bvec->bv_len - iter->iov_offset);
2054 nr = file->f_op->read(file, iovec.iov_base,
2055 iovec.iov_len, &kiocb->ki_pos);
2057 nr = file->f_op->write(file, iovec.iov_base,
2058 iovec.iov_len, &kiocb->ki_pos);
2061 if (iov_iter_is_bvec(iter))
2062 kunmap(iter->bvec->bv_page);
2070 if (nr != iovec.iov_len)
2072 iov_iter_advance(iter, nr);
2078 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2079 struct iovec *iovec, struct iovec *fast_iov,
2080 struct iov_iter *iter)
2082 req->io->rw.nr_segs = iter->nr_segs;
2083 req->io->rw.size = io_size;
2084 req->io->rw.iov = iovec;
2085 if (!req->io->rw.iov) {
2086 req->io->rw.iov = req->io->rw.fast_iov;
2087 memcpy(req->io->rw.iov, fast_iov,
2088 sizeof(struct iovec) * iter->nr_segs);
2092 static int io_alloc_async_ctx(struct io_kiocb *req)
2094 if (!io_op_defs[req->opcode].async_ctx)
2096 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2097 return req->io == NULL;
2100 static void io_rw_async(struct io_wq_work **workptr)
2102 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2103 struct iovec *iov = NULL;
2105 if (req->io->rw.iov != req->io->rw.fast_iov)
2106 iov = req->io->rw.iov;
2107 io_wq_submit_work(workptr);
2111 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2112 struct iovec *iovec, struct iovec *fast_iov,
2113 struct iov_iter *iter)
2115 if (!io_op_defs[req->opcode].async_ctx)
2117 if (!req->io && io_alloc_async_ctx(req))
2120 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2121 req->work.func = io_rw_async;
2125 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2126 bool force_nonblock)
2128 struct io_async_ctx *io;
2129 struct iov_iter iter;
2132 ret = io_prep_rw(req, sqe, force_nonblock);
2136 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2143 io->rw.iov = io->rw.fast_iov;
2145 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2150 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2154 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2155 bool force_nonblock)
2157 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2158 struct kiocb *kiocb = &req->rw.kiocb;
2159 struct iov_iter iter;
2161 ssize_t io_size, ret;
2163 ret = io_import_iovec(READ, req, &iovec, &iter);
2167 /* Ensure we clear previously set non-block flag */
2168 if (!force_nonblock)
2169 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2173 if (req->flags & REQ_F_LINK)
2174 req->result = io_size;
2177 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2178 * we know to async punt it even if it was opened O_NONBLOCK
2180 if (force_nonblock && !io_file_supports_async(req->file)) {
2181 req->flags |= REQ_F_MUST_PUNT;
2185 iov_count = iov_iter_count(&iter);
2186 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2190 if (req->file->f_op->read_iter)
2191 ret2 = call_read_iter(req->file, kiocb, &iter);
2193 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2195 /* Catch -EAGAIN return for forced non-blocking submission */
2196 if (!force_nonblock || ret2 != -EAGAIN) {
2197 kiocb_done(kiocb, ret2, nxt, req->in_async);
2200 ret = io_setup_async_rw(req, io_size, iovec,
2201 inline_vecs, &iter);
2208 if (!io_wq_current_is_worker())
2213 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2214 bool force_nonblock)
2216 struct io_async_ctx *io;
2217 struct iov_iter iter;
2220 ret = io_prep_rw(req, sqe, force_nonblock);
2224 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2231 io->rw.iov = io->rw.fast_iov;
2233 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2238 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2242 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2243 bool force_nonblock)
2245 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2246 struct kiocb *kiocb = &req->rw.kiocb;
2247 struct iov_iter iter;
2249 ssize_t ret, io_size;
2251 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2255 /* Ensure we clear previously set non-block flag */
2256 if (!force_nonblock)
2257 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2261 if (req->flags & REQ_F_LINK)
2262 req->result = io_size;
2265 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2266 * we know to async punt it even if it was opened O_NONBLOCK
2268 if (force_nonblock && !io_file_supports_async(req->file)) {
2269 req->flags |= REQ_F_MUST_PUNT;
2273 /* file path doesn't support NOWAIT for non-direct_IO */
2274 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2275 (req->flags & REQ_F_ISREG))
2278 iov_count = iov_iter_count(&iter);
2279 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2284 * Open-code file_start_write here to grab freeze protection,
2285 * which will be released by another thread in
2286 * io_complete_rw(). Fool lockdep by telling it the lock got
2287 * released so that it doesn't complain about the held lock when
2288 * we return to userspace.
2290 if (req->flags & REQ_F_ISREG) {
2291 __sb_start_write(file_inode(req->file)->i_sb,
2292 SB_FREEZE_WRITE, true);
2293 __sb_writers_release(file_inode(req->file)->i_sb,
2296 kiocb->ki_flags |= IOCB_WRITE;
2298 if (req->file->f_op->write_iter)
2299 ret2 = call_write_iter(req->file, kiocb, &iter);
2301 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2302 if (!force_nonblock || ret2 != -EAGAIN) {
2303 kiocb_done(kiocb, ret2, nxt, req->in_async);
2306 ret = io_setup_async_rw(req, io_size, iovec,
2307 inline_vecs, &iter);
2314 if (!io_wq_current_is_worker())
2320 * IORING_OP_NOP just posts a completion event, nothing else.
2322 static int io_nop(struct io_kiocb *req)
2324 struct io_ring_ctx *ctx = req->ctx;
2326 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2329 io_cqring_add_event(req, 0);
2334 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2336 struct io_ring_ctx *ctx = req->ctx;
2341 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2343 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2346 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2347 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2350 req->sync.off = READ_ONCE(sqe->off);
2351 req->sync.len = READ_ONCE(sqe->len);
2355 static bool io_req_cancelled(struct io_kiocb *req)
2357 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2358 req_set_fail_links(req);
2359 io_cqring_add_event(req, -ECANCELED);
2367 static void io_link_work_cb(struct io_wq_work **workptr)
2369 struct io_wq_work *work = *workptr;
2370 struct io_kiocb *link = work->data;
2372 io_queue_linked_timeout(link);
2373 work->func = io_wq_submit_work;
2376 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2378 struct io_kiocb *link;
2380 io_prep_async_work(nxt, &link);
2381 *workptr = &nxt->work;
2383 nxt->work.flags |= IO_WQ_WORK_CB;
2384 nxt->work.func = io_link_work_cb;
2385 nxt->work.data = link;
2389 static void io_fsync_finish(struct io_wq_work **workptr)
2391 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2392 loff_t end = req->sync.off + req->sync.len;
2393 struct io_kiocb *nxt = NULL;
2396 if (io_req_cancelled(req))
2399 ret = vfs_fsync_range(req->file, req->sync.off,
2400 end > 0 ? end : LLONG_MAX,
2401 req->sync.flags & IORING_FSYNC_DATASYNC);
2403 req_set_fail_links(req);
2404 io_cqring_add_event(req, ret);
2405 io_put_req_find_next(req, &nxt);
2407 io_wq_assign_next(workptr, nxt);
2410 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2411 bool force_nonblock)
2413 struct io_wq_work *work, *old_work;
2415 /* fsync always requires a blocking context */
2416 if (force_nonblock) {
2418 req->work.func = io_fsync_finish;
2422 work = old_work = &req->work;
2423 io_fsync_finish(&work);
2424 if (work && work != old_work)
2425 *nxt = container_of(work, struct io_kiocb, work);
2429 static void io_fallocate_finish(struct io_wq_work **workptr)
2431 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2432 struct io_kiocb *nxt = NULL;
2435 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2438 req_set_fail_links(req);
2439 io_cqring_add_event(req, ret);
2440 io_put_req_find_next(req, &nxt);
2442 io_wq_assign_next(workptr, nxt);
2445 static int io_fallocate_prep(struct io_kiocb *req,
2446 const struct io_uring_sqe *sqe)
2448 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2451 req->sync.off = READ_ONCE(sqe->off);
2452 req->sync.len = READ_ONCE(sqe->addr);
2453 req->sync.mode = READ_ONCE(sqe->len);
2457 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2458 bool force_nonblock)
2460 struct io_wq_work *work, *old_work;
2462 /* fallocate always requiring blocking context */
2463 if (force_nonblock) {
2465 req->work.func = io_fallocate_finish;
2469 work = old_work = &req->work;
2470 io_fallocate_finish(&work);
2471 if (work && work != old_work)
2472 *nxt = container_of(work, struct io_kiocb, work);
2477 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2479 const char __user *fname;
2482 if (sqe->ioprio || sqe->buf_index)
2485 req->open.dfd = READ_ONCE(sqe->fd);
2486 req->open.how.mode = READ_ONCE(sqe->len);
2487 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2488 req->open.how.flags = READ_ONCE(sqe->open_flags);
2490 req->open.filename = getname(fname);
2491 if (IS_ERR(req->open.filename)) {
2492 ret = PTR_ERR(req->open.filename);
2493 req->open.filename = NULL;
2500 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2502 struct open_how __user *how;
2503 const char __user *fname;
2507 if (sqe->ioprio || sqe->buf_index)
2510 req->open.dfd = READ_ONCE(sqe->fd);
2511 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2512 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2513 len = READ_ONCE(sqe->len);
2515 if (len < OPEN_HOW_SIZE_VER0)
2518 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2523 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2524 req->open.how.flags |= O_LARGEFILE;
2526 req->open.filename = getname(fname);
2527 if (IS_ERR(req->open.filename)) {
2528 ret = PTR_ERR(req->open.filename);
2529 req->open.filename = NULL;
2536 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2537 bool force_nonblock)
2539 struct open_flags op;
2543 if (force_nonblock) {
2544 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2548 ret = build_open_flags(&req->open.how, &op);
2552 ret = get_unused_fd_flags(req->open.how.flags);
2556 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2559 ret = PTR_ERR(file);
2561 fsnotify_open(file);
2562 fd_install(ret, file);
2565 putname(req->open.filename);
2567 req_set_fail_links(req);
2568 io_cqring_add_event(req, ret);
2569 io_put_req_find_next(req, nxt);
2573 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2574 bool force_nonblock)
2576 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2577 return io_openat2(req, nxt, force_nonblock);
2580 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2582 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2583 if (sqe->ioprio || sqe->buf_index || sqe->off)
2586 req->madvise.addr = READ_ONCE(sqe->addr);
2587 req->madvise.len = READ_ONCE(sqe->len);
2588 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2595 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2596 bool force_nonblock)
2598 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2599 struct io_madvise *ma = &req->madvise;
2605 ret = do_madvise(ma->addr, ma->len, ma->advice);
2607 req_set_fail_links(req);
2608 io_cqring_add_event(req, ret);
2609 io_put_req_find_next(req, nxt);
2616 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2618 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2621 req->fadvise.offset = READ_ONCE(sqe->off);
2622 req->fadvise.len = READ_ONCE(sqe->len);
2623 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2627 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2628 bool force_nonblock)
2630 struct io_fadvise *fa = &req->fadvise;
2633 /* DONTNEED may block, others _should_ not */
2634 if (fa->advice == POSIX_FADV_DONTNEED && force_nonblock)
2637 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2639 req_set_fail_links(req);
2640 io_cqring_add_event(req, ret);
2641 io_put_req_find_next(req, nxt);
2645 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2647 const char __user *fname;
2648 unsigned lookup_flags;
2651 if (sqe->ioprio || sqe->buf_index)
2654 req->open.dfd = READ_ONCE(sqe->fd);
2655 req->open.mask = READ_ONCE(sqe->len);
2656 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2657 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2658 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2660 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2663 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2664 if (IS_ERR(req->open.filename)) {
2665 ret = PTR_ERR(req->open.filename);
2666 req->open.filename = NULL;
2673 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2674 bool force_nonblock)
2676 struct io_open *ctx = &req->open;
2677 unsigned lookup_flags;
2685 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2689 /* filename_lookup() drops it, keep a reference */
2690 ctx->filename->refcnt++;
2692 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2697 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2699 if (retry_estale(ret, lookup_flags)) {
2700 lookup_flags |= LOOKUP_REVAL;
2704 ret = cp_statx(&stat, ctx->buffer);
2706 putname(ctx->filename);
2708 req_set_fail_links(req);
2709 io_cqring_add_event(req, ret);
2710 io_put_req_find_next(req, nxt);
2714 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2717 * If we queue this for async, it must not be cancellable. That would
2718 * leave the 'file' in an undeterminate state.
2720 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2722 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2723 sqe->rw_flags || sqe->buf_index)
2725 if (sqe->flags & IOSQE_FIXED_FILE)
2728 req->close.fd = READ_ONCE(sqe->fd);
2729 if (req->file->f_op == &io_uring_fops ||
2730 req->close.fd == req->ctx->ring_fd)
2736 static void io_close_finish(struct io_wq_work **workptr)
2738 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2739 struct io_kiocb *nxt = NULL;
2741 /* Invoked with files, we need to do the close */
2742 if (req->work.files) {
2745 ret = filp_close(req->close.put_file, req->work.files);
2747 req_set_fail_links(req);
2749 io_cqring_add_event(req, ret);
2752 fput(req->close.put_file);
2754 /* we bypassed the re-issue, drop the submission reference */
2756 io_put_req_find_next(req, &nxt);
2758 io_wq_assign_next(workptr, nxt);
2761 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2762 bool force_nonblock)
2766 req->close.put_file = NULL;
2767 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2771 /* if the file has a flush method, be safe and punt to async */
2772 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker()) {
2773 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2778 * No ->flush(), safely close from here and just punt the
2779 * fput() to async context.
2781 ret = filp_close(req->close.put_file, current->files);
2784 req_set_fail_links(req);
2785 io_cqring_add_event(req, ret);
2787 if (io_wq_current_is_worker()) {
2788 struct io_wq_work *old_work, *work;
2790 old_work = work = &req->work;
2791 io_close_finish(&work);
2792 if (work && work != old_work)
2793 *nxt = container_of(work, struct io_kiocb, work);
2798 req->work.func = io_close_finish;
2802 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2804 struct io_ring_ctx *ctx = req->ctx;
2809 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2811 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2814 req->sync.off = READ_ONCE(sqe->off);
2815 req->sync.len = READ_ONCE(sqe->len);
2816 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2820 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2822 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2823 struct io_kiocb *nxt = NULL;
2826 if (io_req_cancelled(req))
2829 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2832 req_set_fail_links(req);
2833 io_cqring_add_event(req, ret);
2834 io_put_req_find_next(req, &nxt);
2836 io_wq_assign_next(workptr, nxt);
2839 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2840 bool force_nonblock)
2842 struct io_wq_work *work, *old_work;
2844 /* sync_file_range always requires a blocking context */
2845 if (force_nonblock) {
2847 req->work.func = io_sync_file_range_finish;
2851 work = old_work = &req->work;
2852 io_sync_file_range_finish(&work);
2853 if (work && work != old_work)
2854 *nxt = container_of(work, struct io_kiocb, work);
2858 #if defined(CONFIG_NET)
2859 static void io_sendrecv_async(struct io_wq_work **workptr)
2861 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2862 struct iovec *iov = NULL;
2864 if (req->io->rw.iov != req->io->rw.fast_iov)
2865 iov = req->io->msg.iov;
2866 io_wq_submit_work(workptr);
2871 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2873 #if defined(CONFIG_NET)
2874 struct io_sr_msg *sr = &req->sr_msg;
2875 struct io_async_ctx *io = req->io;
2877 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2878 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2879 sr->len = READ_ONCE(sqe->len);
2881 if (!io || req->opcode == IORING_OP_SEND)
2884 io->msg.iov = io->msg.fast_iov;
2885 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2892 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2893 bool force_nonblock)
2895 #if defined(CONFIG_NET)
2896 struct io_async_msghdr *kmsg = NULL;
2897 struct socket *sock;
2900 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2903 sock = sock_from_file(req->file, &ret);
2905 struct io_async_ctx io;
2906 struct sockaddr_storage addr;
2910 kmsg = &req->io->msg;
2911 kmsg->msg.msg_name = &addr;
2912 /* if iov is set, it's allocated already */
2914 kmsg->iov = kmsg->fast_iov;
2915 kmsg->msg.msg_iter.iov = kmsg->iov;
2917 struct io_sr_msg *sr = &req->sr_msg;
2920 kmsg->msg.msg_name = &addr;
2922 io.msg.iov = io.msg.fast_iov;
2923 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2924 sr->msg_flags, &io.msg.iov);
2929 flags = req->sr_msg.msg_flags;
2930 if (flags & MSG_DONTWAIT)
2931 req->flags |= REQ_F_NOWAIT;
2932 else if (force_nonblock)
2933 flags |= MSG_DONTWAIT;
2935 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2936 if (force_nonblock && ret == -EAGAIN) {
2939 if (io_alloc_async_ctx(req))
2941 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2942 req->work.func = io_sendrecv_async;
2945 if (ret == -ERESTARTSYS)
2949 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2951 io_cqring_add_event(req, ret);
2953 req_set_fail_links(req);
2954 io_put_req_find_next(req, nxt);
2961 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
2962 bool force_nonblock)
2964 #if defined(CONFIG_NET)
2965 struct socket *sock;
2968 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2971 sock = sock_from_file(req->file, &ret);
2973 struct io_sr_msg *sr = &req->sr_msg;
2978 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
2983 msg.msg_name = NULL;
2984 msg.msg_control = NULL;
2985 msg.msg_controllen = 0;
2986 msg.msg_namelen = 0;
2988 flags = req->sr_msg.msg_flags;
2989 if (flags & MSG_DONTWAIT)
2990 req->flags |= REQ_F_NOWAIT;
2991 else if (force_nonblock)
2992 flags |= MSG_DONTWAIT;
2994 ret = __sys_sendmsg_sock(sock, &msg, flags);
2995 if (force_nonblock && ret == -EAGAIN)
2997 if (ret == -ERESTARTSYS)
3001 io_cqring_add_event(req, ret);
3003 req_set_fail_links(req);
3004 io_put_req_find_next(req, nxt);
3011 static int io_recvmsg_prep(struct io_kiocb *req,
3012 const struct io_uring_sqe *sqe)
3014 #if defined(CONFIG_NET)
3015 struct io_sr_msg *sr = &req->sr_msg;
3016 struct io_async_ctx *io = req->io;
3018 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3019 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3021 if (!io || req->opcode == IORING_OP_RECV)
3024 io->msg.iov = io->msg.fast_iov;
3025 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3026 &io->msg.uaddr, &io->msg.iov);
3032 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3033 bool force_nonblock)
3035 #if defined(CONFIG_NET)
3036 struct io_async_msghdr *kmsg = NULL;
3037 struct socket *sock;
3040 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3043 sock = sock_from_file(req->file, &ret);
3045 struct io_async_ctx io;
3046 struct sockaddr_storage addr;
3050 kmsg = &req->io->msg;
3051 kmsg->msg.msg_name = &addr;
3052 /* if iov is set, it's allocated already */
3054 kmsg->iov = kmsg->fast_iov;
3055 kmsg->msg.msg_iter.iov = kmsg->iov;
3057 struct io_sr_msg *sr = &req->sr_msg;
3060 kmsg->msg.msg_name = &addr;
3062 io.msg.iov = io.msg.fast_iov;
3063 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3064 sr->msg_flags, &io.msg.uaddr,
3070 flags = req->sr_msg.msg_flags;
3071 if (flags & MSG_DONTWAIT)
3072 req->flags |= REQ_F_NOWAIT;
3073 else if (force_nonblock)
3074 flags |= MSG_DONTWAIT;
3076 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3077 kmsg->uaddr, flags);
3078 if (force_nonblock && ret == -EAGAIN) {
3081 if (io_alloc_async_ctx(req))
3083 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3084 req->work.func = io_sendrecv_async;
3087 if (ret == -ERESTARTSYS)
3091 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
3093 io_cqring_add_event(req, ret);
3095 req_set_fail_links(req);
3096 io_put_req_find_next(req, nxt);
3103 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3104 bool force_nonblock)
3106 #if defined(CONFIG_NET)
3107 struct socket *sock;
3110 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3113 sock = sock_from_file(req->file, &ret);
3115 struct io_sr_msg *sr = &req->sr_msg;
3120 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3125 msg.msg_name = NULL;
3126 msg.msg_control = NULL;
3127 msg.msg_controllen = 0;
3128 msg.msg_namelen = 0;
3129 msg.msg_iocb = NULL;
3132 flags = req->sr_msg.msg_flags;
3133 if (flags & MSG_DONTWAIT)
3134 req->flags |= REQ_F_NOWAIT;
3135 else if (force_nonblock)
3136 flags |= MSG_DONTWAIT;
3138 ret = __sys_recvmsg_sock(sock, &msg, NULL, NULL, flags);
3139 if (force_nonblock && ret == -EAGAIN)
3141 if (ret == -ERESTARTSYS)
3145 io_cqring_add_event(req, ret);
3147 req_set_fail_links(req);
3148 io_put_req_find_next(req, nxt);
3156 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3158 #if defined(CONFIG_NET)
3159 struct io_accept *accept = &req->accept;
3161 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3163 if (sqe->ioprio || sqe->len || sqe->buf_index)
3166 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3167 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3168 accept->flags = READ_ONCE(sqe->accept_flags);
3175 #if defined(CONFIG_NET)
3176 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3177 bool force_nonblock)
3179 struct io_accept *accept = &req->accept;
3180 unsigned file_flags;
3183 file_flags = force_nonblock ? O_NONBLOCK : 0;
3184 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3185 accept->addr_len, accept->flags);
3186 if (ret == -EAGAIN && force_nonblock)
3188 if (ret == -ERESTARTSYS)
3191 req_set_fail_links(req);
3192 io_cqring_add_event(req, ret);
3193 io_put_req_find_next(req, nxt);
3197 static void io_accept_finish(struct io_wq_work **workptr)
3199 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3200 struct io_kiocb *nxt = NULL;
3202 if (io_req_cancelled(req))
3204 __io_accept(req, &nxt, false);
3206 io_wq_assign_next(workptr, nxt);
3210 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3211 bool force_nonblock)
3213 #if defined(CONFIG_NET)
3216 ret = __io_accept(req, nxt, force_nonblock);
3217 if (ret == -EAGAIN && force_nonblock) {
3218 req->work.func = io_accept_finish;
3219 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3229 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3231 #if defined(CONFIG_NET)
3232 struct io_connect *conn = &req->connect;
3233 struct io_async_ctx *io = req->io;
3235 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3237 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3240 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3241 conn->addr_len = READ_ONCE(sqe->addr2);
3246 return move_addr_to_kernel(conn->addr, conn->addr_len,
3247 &io->connect.address);
3253 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3254 bool force_nonblock)
3256 #if defined(CONFIG_NET)
3257 struct io_async_ctx __io, *io;
3258 unsigned file_flags;
3264 ret = move_addr_to_kernel(req->connect.addr,
3265 req->connect.addr_len,
3266 &__io.connect.address);
3272 file_flags = force_nonblock ? O_NONBLOCK : 0;
3274 ret = __sys_connect_file(req->file, &io->connect.address,
3275 req->connect.addr_len, file_flags);
3276 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3279 if (io_alloc_async_ctx(req)) {
3283 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3286 if (ret == -ERESTARTSYS)
3290 req_set_fail_links(req);
3291 io_cqring_add_event(req, ret);
3292 io_put_req_find_next(req, nxt);
3299 static void io_poll_remove_one(struct io_kiocb *req)
3301 struct io_poll_iocb *poll = &req->poll;
3303 spin_lock(&poll->head->lock);
3304 WRITE_ONCE(poll->canceled, true);
3305 if (!list_empty(&poll->wait.entry)) {
3306 list_del_init(&poll->wait.entry);
3307 io_queue_async_work(req);
3309 spin_unlock(&poll->head->lock);
3310 hash_del(&req->hash_node);
3313 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3315 struct hlist_node *tmp;
3316 struct io_kiocb *req;
3319 spin_lock_irq(&ctx->completion_lock);
3320 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3321 struct hlist_head *list;
3323 list = &ctx->cancel_hash[i];
3324 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3325 io_poll_remove_one(req);
3327 spin_unlock_irq(&ctx->completion_lock);
3330 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3332 struct hlist_head *list;
3333 struct io_kiocb *req;
3335 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3336 hlist_for_each_entry(req, list, hash_node) {
3337 if (sqe_addr == req->user_data) {
3338 io_poll_remove_one(req);
3346 static int io_poll_remove_prep(struct io_kiocb *req,
3347 const struct io_uring_sqe *sqe)
3349 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3351 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3355 req->poll.addr = READ_ONCE(sqe->addr);
3360 * Find a running poll command that matches one specified in sqe->addr,
3361 * and remove it if found.
3363 static int io_poll_remove(struct io_kiocb *req)
3365 struct io_ring_ctx *ctx = req->ctx;
3369 addr = req->poll.addr;
3370 spin_lock_irq(&ctx->completion_lock);
3371 ret = io_poll_cancel(ctx, addr);
3372 spin_unlock_irq(&ctx->completion_lock);
3374 io_cqring_add_event(req, ret);
3376 req_set_fail_links(req);
3381 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3383 struct io_ring_ctx *ctx = req->ctx;
3385 req->poll.done = true;
3387 io_cqring_fill_event(req, error);
3389 io_cqring_fill_event(req, mangle_poll(mask));
3390 io_commit_cqring(ctx);
3393 static void io_poll_complete_work(struct io_wq_work **workptr)
3395 struct io_wq_work *work = *workptr;
3396 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3397 struct io_poll_iocb *poll = &req->poll;
3398 struct poll_table_struct pt = { ._key = poll->events };
3399 struct io_ring_ctx *ctx = req->ctx;
3400 struct io_kiocb *nxt = NULL;
3404 if (work->flags & IO_WQ_WORK_CANCEL) {
3405 WRITE_ONCE(poll->canceled, true);
3407 } else if (READ_ONCE(poll->canceled)) {
3411 if (ret != -ECANCELED)
3412 mask = vfs_poll(poll->file, &pt) & poll->events;
3415 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3416 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3417 * synchronize with them. In the cancellation case the list_del_init
3418 * itself is not actually needed, but harmless so we keep it in to
3419 * avoid further branches in the fast path.
3421 spin_lock_irq(&ctx->completion_lock);
3422 if (!mask && ret != -ECANCELED) {
3423 add_wait_queue(poll->head, &poll->wait);
3424 spin_unlock_irq(&ctx->completion_lock);
3427 hash_del(&req->hash_node);
3428 io_poll_complete(req, mask, ret);
3429 spin_unlock_irq(&ctx->completion_lock);
3431 io_cqring_ev_posted(ctx);
3434 req_set_fail_links(req);
3435 io_put_req_find_next(req, &nxt);
3437 io_wq_assign_next(workptr, nxt);
3440 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3442 struct io_kiocb *req, *tmp;
3443 struct req_batch rb;
3445 rb.to_free = rb.need_iter = 0;
3446 spin_lock_irq(&ctx->completion_lock);
3447 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3448 hash_del(&req->hash_node);
3449 io_poll_complete(req, req->result, 0);
3451 if (refcount_dec_and_test(&req->refs) &&
3452 !io_req_multi_free(&rb, req)) {
3453 req->flags |= REQ_F_COMP_LOCKED;
3457 spin_unlock_irq(&ctx->completion_lock);
3459 io_cqring_ev_posted(ctx);
3460 io_free_req_many(ctx, &rb);
3463 static void io_poll_flush(struct io_wq_work **workptr)
3465 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3466 struct llist_node *nodes;
3468 nodes = llist_del_all(&req->ctx->poll_llist);
3470 __io_poll_flush(req->ctx, nodes);
3473 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3476 struct io_poll_iocb *poll = wait->private;
3477 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3478 struct io_ring_ctx *ctx = req->ctx;
3479 __poll_t mask = key_to_poll(key);
3481 /* for instances that support it check for an event match first: */
3482 if (mask && !(mask & poll->events))
3485 list_del_init(&poll->wait.entry);
3488 * Run completion inline if we can. We're using trylock here because
3489 * we are violating the completion_lock -> poll wq lock ordering.
3490 * If we have a link timeout we're going to need the completion_lock
3491 * for finalizing the request, mark us as having grabbed that already.
3494 unsigned long flags;
3496 if (llist_empty(&ctx->poll_llist) &&
3497 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3498 hash_del(&req->hash_node);
3499 io_poll_complete(req, mask, 0);
3500 req->flags |= REQ_F_COMP_LOCKED;
3502 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3504 io_cqring_ev_posted(ctx);
3508 req->llist_node.next = NULL;
3509 /* if the list wasn't empty, we're done */
3510 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3513 req->work.func = io_poll_flush;
3517 io_queue_async_work(req);
3522 struct io_poll_table {
3523 struct poll_table_struct pt;
3524 struct io_kiocb *req;
3528 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3529 struct poll_table_struct *p)
3531 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3533 if (unlikely(pt->req->poll.head)) {
3534 pt->error = -EINVAL;
3539 pt->req->poll.head = head;
3540 add_wait_queue(head, &pt->req->poll.wait);
3543 static void io_poll_req_insert(struct io_kiocb *req)
3545 struct io_ring_ctx *ctx = req->ctx;
3546 struct hlist_head *list;
3548 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3549 hlist_add_head(&req->hash_node, list);
3552 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3554 struct io_poll_iocb *poll = &req->poll;
3557 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3559 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3564 events = READ_ONCE(sqe->poll_events);
3565 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3569 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3571 struct io_poll_iocb *poll = &req->poll;
3572 struct io_ring_ctx *ctx = req->ctx;
3573 struct io_poll_table ipt;
3574 bool cancel = false;
3577 INIT_IO_WORK(&req->work, io_poll_complete_work);
3578 INIT_HLIST_NODE(&req->hash_node);
3582 poll->canceled = false;
3584 ipt.pt._qproc = io_poll_queue_proc;
3585 ipt.pt._key = poll->events;
3587 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3589 /* initialized the list so that we can do list_empty checks */
3590 INIT_LIST_HEAD(&poll->wait.entry);
3591 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3592 poll->wait.private = poll;
3594 INIT_LIST_HEAD(&req->list);
3596 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3598 spin_lock_irq(&ctx->completion_lock);
3599 if (likely(poll->head)) {
3600 spin_lock(&poll->head->lock);
3601 if (unlikely(list_empty(&poll->wait.entry))) {
3607 if (mask || ipt.error)
3608 list_del_init(&poll->wait.entry);
3610 WRITE_ONCE(poll->canceled, true);
3611 else if (!poll->done) /* actually waiting for an event */
3612 io_poll_req_insert(req);
3613 spin_unlock(&poll->head->lock);
3615 if (mask) { /* no async, we'd stolen it */
3617 io_poll_complete(req, mask, 0);
3619 spin_unlock_irq(&ctx->completion_lock);
3622 io_cqring_ev_posted(ctx);
3623 io_put_req_find_next(req, nxt);
3628 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3630 struct io_timeout_data *data = container_of(timer,
3631 struct io_timeout_data, timer);
3632 struct io_kiocb *req = data->req;
3633 struct io_ring_ctx *ctx = req->ctx;
3634 unsigned long flags;
3636 atomic_inc(&ctx->cq_timeouts);
3638 spin_lock_irqsave(&ctx->completion_lock, flags);
3640 * We could be racing with timeout deletion. If the list is empty,
3641 * then timeout lookup already found it and will be handling it.
3643 if (!list_empty(&req->list)) {
3644 struct io_kiocb *prev;
3647 * Adjust the reqs sequence before the current one because it
3648 * will consume a slot in the cq_ring and the cq_tail
3649 * pointer will be increased, otherwise other timeout reqs may
3650 * return in advance without waiting for enough wait_nr.
3653 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3655 list_del_init(&req->list);
3658 io_cqring_fill_event(req, -ETIME);
3659 io_commit_cqring(ctx);
3660 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3662 io_cqring_ev_posted(ctx);
3663 req_set_fail_links(req);
3665 return HRTIMER_NORESTART;
3668 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3670 struct io_kiocb *req;
3673 list_for_each_entry(req, &ctx->timeout_list, list) {
3674 if (user_data == req->user_data) {
3675 list_del_init(&req->list);
3684 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3688 req_set_fail_links(req);
3689 io_cqring_fill_event(req, -ECANCELED);
3694 static int io_timeout_remove_prep(struct io_kiocb *req,
3695 const struct io_uring_sqe *sqe)
3697 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3699 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3702 req->timeout.addr = READ_ONCE(sqe->addr);
3703 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3704 if (req->timeout.flags)
3711 * Remove or update an existing timeout command
3713 static int io_timeout_remove(struct io_kiocb *req)
3715 struct io_ring_ctx *ctx = req->ctx;
3718 spin_lock_irq(&ctx->completion_lock);
3719 ret = io_timeout_cancel(ctx, req->timeout.addr);
3721 io_cqring_fill_event(req, ret);
3722 io_commit_cqring(ctx);
3723 spin_unlock_irq(&ctx->completion_lock);
3724 io_cqring_ev_posted(ctx);
3726 req_set_fail_links(req);
3731 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3732 bool is_timeout_link)
3734 struct io_timeout_data *data;
3737 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3739 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3741 if (sqe->off && is_timeout_link)
3743 flags = READ_ONCE(sqe->timeout_flags);
3744 if (flags & ~IORING_TIMEOUT_ABS)
3747 req->timeout.count = READ_ONCE(sqe->off);
3749 if (!req->io && io_alloc_async_ctx(req))
3752 data = &req->io->timeout;
3754 req->flags |= REQ_F_TIMEOUT;
3756 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3759 if (flags & IORING_TIMEOUT_ABS)
3760 data->mode = HRTIMER_MODE_ABS;
3762 data->mode = HRTIMER_MODE_REL;
3764 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3768 static int io_timeout(struct io_kiocb *req)
3771 struct io_ring_ctx *ctx = req->ctx;
3772 struct io_timeout_data *data;
3773 struct list_head *entry;
3776 data = &req->io->timeout;
3779 * sqe->off holds how many events that need to occur for this
3780 * timeout event to be satisfied. If it isn't set, then this is
3781 * a pure timeout request, sequence isn't used.
3783 count = req->timeout.count;
3785 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3786 spin_lock_irq(&ctx->completion_lock);
3787 entry = ctx->timeout_list.prev;
3791 req->sequence = ctx->cached_sq_head + count - 1;
3792 data->seq_offset = count;
3795 * Insertion sort, ensuring the first entry in the list is always
3796 * the one we need first.
3798 spin_lock_irq(&ctx->completion_lock);
3799 list_for_each_prev(entry, &ctx->timeout_list) {
3800 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3801 unsigned nxt_sq_head;
3802 long long tmp, tmp_nxt;
3803 u32 nxt_offset = nxt->io->timeout.seq_offset;
3805 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3809 * Since cached_sq_head + count - 1 can overflow, use type long
3812 tmp = (long long)ctx->cached_sq_head + count - 1;
3813 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3814 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3817 * cached_sq_head may overflow, and it will never overflow twice
3818 * once there is some timeout req still be valid.
3820 if (ctx->cached_sq_head < nxt_sq_head)
3827 * Sequence of reqs after the insert one and itself should
3828 * be adjusted because each timeout req consumes a slot.
3833 req->sequence -= span;
3835 list_add(&req->list, entry);
3836 data->timer.function = io_timeout_fn;
3837 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3838 spin_unlock_irq(&ctx->completion_lock);
3842 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3844 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3846 return req->user_data == (unsigned long) data;
3849 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3851 enum io_wq_cancel cancel_ret;
3854 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3855 switch (cancel_ret) {
3856 case IO_WQ_CANCEL_OK:
3859 case IO_WQ_CANCEL_RUNNING:
3862 case IO_WQ_CANCEL_NOTFOUND:
3870 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3871 struct io_kiocb *req, __u64 sqe_addr,
3872 struct io_kiocb **nxt, int success_ret)
3874 unsigned long flags;
3877 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3878 if (ret != -ENOENT) {
3879 spin_lock_irqsave(&ctx->completion_lock, flags);
3883 spin_lock_irqsave(&ctx->completion_lock, flags);
3884 ret = io_timeout_cancel(ctx, sqe_addr);
3887 ret = io_poll_cancel(ctx, sqe_addr);
3891 io_cqring_fill_event(req, ret);
3892 io_commit_cqring(ctx);
3893 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3894 io_cqring_ev_posted(ctx);
3897 req_set_fail_links(req);
3898 io_put_req_find_next(req, nxt);
3901 static int io_async_cancel_prep(struct io_kiocb *req,
3902 const struct io_uring_sqe *sqe)
3904 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3906 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3910 req->cancel.addr = READ_ONCE(sqe->addr);
3914 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3916 struct io_ring_ctx *ctx = req->ctx;
3918 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3922 static int io_files_update_prep(struct io_kiocb *req,
3923 const struct io_uring_sqe *sqe)
3925 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
3928 req->files_update.offset = READ_ONCE(sqe->off);
3929 req->files_update.nr_args = READ_ONCE(sqe->len);
3930 if (!req->files_update.nr_args)
3932 req->files_update.arg = READ_ONCE(sqe->addr);
3936 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
3938 struct io_ring_ctx *ctx = req->ctx;
3939 struct io_uring_files_update up;
3942 if (force_nonblock) {
3943 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3947 up.offset = req->files_update.offset;
3948 up.fds = req->files_update.arg;
3950 mutex_lock(&ctx->uring_lock);
3951 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
3952 mutex_unlock(&ctx->uring_lock);
3955 req_set_fail_links(req);
3956 io_cqring_add_event(req, ret);
3961 static int io_req_defer_prep(struct io_kiocb *req,
3962 const struct io_uring_sqe *sqe)
3966 switch (req->opcode) {
3969 case IORING_OP_READV:
3970 case IORING_OP_READ_FIXED:
3971 case IORING_OP_READ:
3972 ret = io_read_prep(req, sqe, true);
3974 case IORING_OP_WRITEV:
3975 case IORING_OP_WRITE_FIXED:
3976 case IORING_OP_WRITE:
3977 ret = io_write_prep(req, sqe, true);
3979 case IORING_OP_POLL_ADD:
3980 ret = io_poll_add_prep(req, sqe);
3982 case IORING_OP_POLL_REMOVE:
3983 ret = io_poll_remove_prep(req, sqe);
3985 case IORING_OP_FSYNC:
3986 ret = io_prep_fsync(req, sqe);
3988 case IORING_OP_SYNC_FILE_RANGE:
3989 ret = io_prep_sfr(req, sqe);
3991 case IORING_OP_SENDMSG:
3992 case IORING_OP_SEND:
3993 ret = io_sendmsg_prep(req, sqe);
3995 case IORING_OP_RECVMSG:
3996 case IORING_OP_RECV:
3997 ret = io_recvmsg_prep(req, sqe);
3999 case IORING_OP_CONNECT:
4000 ret = io_connect_prep(req, sqe);
4002 case IORING_OP_TIMEOUT:
4003 ret = io_timeout_prep(req, sqe, false);
4005 case IORING_OP_TIMEOUT_REMOVE:
4006 ret = io_timeout_remove_prep(req, sqe);
4008 case IORING_OP_ASYNC_CANCEL:
4009 ret = io_async_cancel_prep(req, sqe);
4011 case IORING_OP_LINK_TIMEOUT:
4012 ret = io_timeout_prep(req, sqe, true);
4014 case IORING_OP_ACCEPT:
4015 ret = io_accept_prep(req, sqe);
4017 case IORING_OP_FALLOCATE:
4018 ret = io_fallocate_prep(req, sqe);
4020 case IORING_OP_OPENAT:
4021 ret = io_openat_prep(req, sqe);
4023 case IORING_OP_CLOSE:
4024 ret = io_close_prep(req, sqe);
4026 case IORING_OP_FILES_UPDATE:
4027 ret = io_files_update_prep(req, sqe);
4029 case IORING_OP_STATX:
4030 ret = io_statx_prep(req, sqe);
4032 case IORING_OP_FADVISE:
4033 ret = io_fadvise_prep(req, sqe);
4035 case IORING_OP_MADVISE:
4036 ret = io_madvise_prep(req, sqe);
4038 case IORING_OP_OPENAT2:
4039 ret = io_openat2_prep(req, sqe);
4042 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4051 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4053 struct io_ring_ctx *ctx = req->ctx;
4056 /* Still need defer if there is pending req in defer list. */
4057 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4060 if (!req->io && io_alloc_async_ctx(req))
4063 ret = io_req_defer_prep(req, sqe);
4067 spin_lock_irq(&ctx->completion_lock);
4068 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4069 spin_unlock_irq(&ctx->completion_lock);
4073 trace_io_uring_defer(ctx, req, req->user_data);
4074 list_add_tail(&req->list, &ctx->defer_list);
4075 spin_unlock_irq(&ctx->completion_lock);
4076 return -EIOCBQUEUED;
4079 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4080 struct io_kiocb **nxt, bool force_nonblock)
4082 struct io_ring_ctx *ctx = req->ctx;
4085 switch (req->opcode) {
4089 case IORING_OP_READV:
4090 case IORING_OP_READ_FIXED:
4091 case IORING_OP_READ:
4093 ret = io_read_prep(req, sqe, force_nonblock);
4097 ret = io_read(req, nxt, force_nonblock);
4099 case IORING_OP_WRITEV:
4100 case IORING_OP_WRITE_FIXED:
4101 case IORING_OP_WRITE:
4103 ret = io_write_prep(req, sqe, force_nonblock);
4107 ret = io_write(req, nxt, force_nonblock);
4109 case IORING_OP_FSYNC:
4111 ret = io_prep_fsync(req, sqe);
4115 ret = io_fsync(req, nxt, force_nonblock);
4117 case IORING_OP_POLL_ADD:
4119 ret = io_poll_add_prep(req, sqe);
4123 ret = io_poll_add(req, nxt);
4125 case IORING_OP_POLL_REMOVE:
4127 ret = io_poll_remove_prep(req, sqe);
4131 ret = io_poll_remove(req);
4133 case IORING_OP_SYNC_FILE_RANGE:
4135 ret = io_prep_sfr(req, sqe);
4139 ret = io_sync_file_range(req, nxt, force_nonblock);
4141 case IORING_OP_SENDMSG:
4142 case IORING_OP_SEND:
4144 ret = io_sendmsg_prep(req, sqe);
4148 if (req->opcode == IORING_OP_SENDMSG)
4149 ret = io_sendmsg(req, nxt, force_nonblock);
4151 ret = io_send(req, nxt, force_nonblock);
4153 case IORING_OP_RECVMSG:
4154 case IORING_OP_RECV:
4156 ret = io_recvmsg_prep(req, sqe);
4160 if (req->opcode == IORING_OP_RECVMSG)
4161 ret = io_recvmsg(req, nxt, force_nonblock);
4163 ret = io_recv(req, nxt, force_nonblock);
4165 case IORING_OP_TIMEOUT:
4167 ret = io_timeout_prep(req, sqe, false);
4171 ret = io_timeout(req);
4173 case IORING_OP_TIMEOUT_REMOVE:
4175 ret = io_timeout_remove_prep(req, sqe);
4179 ret = io_timeout_remove(req);
4181 case IORING_OP_ACCEPT:
4183 ret = io_accept_prep(req, sqe);
4187 ret = io_accept(req, nxt, force_nonblock);
4189 case IORING_OP_CONNECT:
4191 ret = io_connect_prep(req, sqe);
4195 ret = io_connect(req, nxt, force_nonblock);
4197 case IORING_OP_ASYNC_CANCEL:
4199 ret = io_async_cancel_prep(req, sqe);
4203 ret = io_async_cancel(req, nxt);
4205 case IORING_OP_FALLOCATE:
4207 ret = io_fallocate_prep(req, sqe);
4211 ret = io_fallocate(req, nxt, force_nonblock);
4213 case IORING_OP_OPENAT:
4215 ret = io_openat_prep(req, sqe);
4219 ret = io_openat(req, nxt, force_nonblock);
4221 case IORING_OP_CLOSE:
4223 ret = io_close_prep(req, sqe);
4227 ret = io_close(req, nxt, force_nonblock);
4229 case IORING_OP_FILES_UPDATE:
4231 ret = io_files_update_prep(req, sqe);
4235 ret = io_files_update(req, force_nonblock);
4237 case IORING_OP_STATX:
4239 ret = io_statx_prep(req, sqe);
4243 ret = io_statx(req, nxt, force_nonblock);
4245 case IORING_OP_FADVISE:
4247 ret = io_fadvise_prep(req, sqe);
4251 ret = io_fadvise(req, nxt, force_nonblock);
4253 case IORING_OP_MADVISE:
4255 ret = io_madvise_prep(req, sqe);
4259 ret = io_madvise(req, nxt, force_nonblock);
4261 case IORING_OP_OPENAT2:
4263 ret = io_openat2_prep(req, sqe);
4267 ret = io_openat2(req, nxt, force_nonblock);
4277 if (ctx->flags & IORING_SETUP_IOPOLL) {
4278 const bool in_async = io_wq_current_is_worker();
4280 if (req->result == -EAGAIN)
4283 /* workqueue context doesn't hold uring_lock, grab it now */
4285 mutex_lock(&ctx->uring_lock);
4287 io_iopoll_req_issued(req);
4290 mutex_unlock(&ctx->uring_lock);
4296 static void io_wq_submit_work(struct io_wq_work **workptr)
4298 struct io_wq_work *work = *workptr;
4299 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4300 struct io_kiocb *nxt = NULL;
4303 /* if NO_CANCEL is set, we must still run the work */
4304 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4305 IO_WQ_WORK_CANCEL) {
4310 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
4311 req->in_async = true;
4313 ret = io_issue_sqe(req, NULL, &nxt, false);
4315 * We can get EAGAIN for polled IO even though we're
4316 * forcing a sync submission from here, since we can't
4317 * wait for request slots on the block side.
4325 /* drop submission reference */
4329 req_set_fail_links(req);
4330 io_cqring_add_event(req, ret);
4334 /* if a dependent link is ready, pass it back */
4336 io_wq_assign_next(workptr, nxt);
4339 static int io_req_needs_file(struct io_kiocb *req, int fd)
4341 if (!io_op_defs[req->opcode].needs_file)
4343 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4348 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4351 struct fixed_file_table *table;
4353 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4354 return table->files[index & IORING_FILE_TABLE_MASK];;
4357 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4358 const struct io_uring_sqe *sqe)
4360 struct io_ring_ctx *ctx = req->ctx;
4364 flags = READ_ONCE(sqe->flags);
4365 fd = READ_ONCE(sqe->fd);
4367 if (!io_req_needs_file(req, fd))
4370 if (flags & IOSQE_FIXED_FILE) {
4371 if (unlikely(!ctx->file_data ||
4372 (unsigned) fd >= ctx->nr_user_files))
4374 fd = array_index_nospec(fd, ctx->nr_user_files);
4375 req->file = io_file_from_index(ctx, fd);
4378 req->flags |= REQ_F_FIXED_FILE;
4379 percpu_ref_get(&ctx->file_data->refs);
4381 if (req->needs_fixed_file)
4383 trace_io_uring_file_get(ctx, fd);
4384 req->file = io_file_get(state, fd);
4385 if (unlikely(!req->file))
4392 static int io_grab_files(struct io_kiocb *req)
4395 struct io_ring_ctx *ctx = req->ctx;
4397 if (!ctx->ring_file)
4401 spin_lock_irq(&ctx->inflight_lock);
4403 * We use the f_ops->flush() handler to ensure that we can flush
4404 * out work accessing these files if the fd is closed. Check if
4405 * the fd has changed since we started down this path, and disallow
4406 * this operation if it has.
4408 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4409 list_add(&req->inflight_entry, &ctx->inflight_list);
4410 req->flags |= REQ_F_INFLIGHT;
4411 req->work.files = current->files;
4414 spin_unlock_irq(&ctx->inflight_lock);
4420 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4422 struct io_timeout_data *data = container_of(timer,
4423 struct io_timeout_data, timer);
4424 struct io_kiocb *req = data->req;
4425 struct io_ring_ctx *ctx = req->ctx;
4426 struct io_kiocb *prev = NULL;
4427 unsigned long flags;
4429 spin_lock_irqsave(&ctx->completion_lock, flags);
4432 * We don't expect the list to be empty, that will only happen if we
4433 * race with the completion of the linked work.
4435 if (!list_empty(&req->link_list)) {
4436 prev = list_entry(req->link_list.prev, struct io_kiocb,
4438 if (refcount_inc_not_zero(&prev->refs)) {
4439 list_del_init(&req->link_list);
4440 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4445 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4448 req_set_fail_links(prev);
4449 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4453 io_cqring_add_event(req, -ETIME);
4456 return HRTIMER_NORESTART;
4459 static void io_queue_linked_timeout(struct io_kiocb *req)
4461 struct io_ring_ctx *ctx = req->ctx;
4464 * If the list is now empty, then our linked request finished before
4465 * we got a chance to setup the timer
4467 spin_lock_irq(&ctx->completion_lock);
4468 if (!list_empty(&req->link_list)) {
4469 struct io_timeout_data *data = &req->io->timeout;
4471 data->timer.function = io_link_timeout_fn;
4472 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4475 spin_unlock_irq(&ctx->completion_lock);
4477 /* drop submission reference */
4481 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4483 struct io_kiocb *nxt;
4485 if (!(req->flags & REQ_F_LINK))
4488 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4490 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4493 req->flags |= REQ_F_LINK_TIMEOUT;
4497 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4499 struct io_kiocb *linked_timeout;
4500 struct io_kiocb *nxt = NULL;
4504 linked_timeout = io_prep_linked_timeout(req);
4506 ret = io_issue_sqe(req, sqe, &nxt, true);
4509 * We async punt it if the file wasn't marked NOWAIT, or if the file
4510 * doesn't support non-blocking read/write attempts
4512 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4513 (req->flags & REQ_F_MUST_PUNT))) {
4515 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
4516 ret = io_grab_files(req);
4522 * Queued up for async execution, worker will release
4523 * submit reference when the iocb is actually submitted.
4525 io_queue_async_work(req);
4530 /* drop submission reference */
4533 if (linked_timeout) {
4535 io_queue_linked_timeout(linked_timeout);
4537 io_put_req(linked_timeout);
4540 /* and drop final reference, if we failed */
4542 io_cqring_add_event(req, ret);
4543 req_set_fail_links(req);
4551 if (req->flags & REQ_F_FORCE_ASYNC)
4557 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4561 ret = io_req_defer(req, sqe);
4563 if (ret != -EIOCBQUEUED) {
4565 io_cqring_add_event(req, ret);
4566 req_set_fail_links(req);
4567 io_double_put_req(req);
4569 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4570 ret = io_req_defer_prep(req, sqe);
4571 if (unlikely(ret < 0))
4574 * Never try inline submit of IOSQE_ASYNC is set, go straight
4575 * to async execution.
4577 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4578 io_queue_async_work(req);
4580 __io_queue_sqe(req, sqe);
4584 static inline void io_queue_link_head(struct io_kiocb *req)
4586 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4587 io_cqring_add_event(req, -ECANCELED);
4588 io_double_put_req(req);
4590 io_queue_sqe(req, NULL);
4593 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4594 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4596 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4597 struct io_submit_state *state, struct io_kiocb **link)
4599 struct io_ring_ctx *ctx = req->ctx;
4600 unsigned int sqe_flags;
4603 sqe_flags = READ_ONCE(sqe->flags);
4605 /* enforce forwards compatibility on users */
4606 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4610 /* same numerical values with corresponding REQ_F_*, safe to copy */
4611 req->flags |= sqe_flags & (IOSQE_IO_DRAIN|IOSQE_IO_HARDLINK|
4614 ret = io_req_set_file(state, req, sqe);
4615 if (unlikely(ret)) {
4617 io_cqring_add_event(req, ret);
4618 io_double_put_req(req);
4623 * If we already have a head request, queue this one for async
4624 * submittal once the head completes. If we don't have a head but
4625 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4626 * submitted sync once the chain is complete. If none of those
4627 * conditions are true (normal request), then just queue it.
4630 struct io_kiocb *head = *link;
4633 * Taking sequential execution of a link, draining both sides
4634 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
4635 * requests in the link. So, it drains the head and the
4636 * next after the link request. The last one is done via
4637 * drain_next flag to persist the effect across calls.
4639 if (sqe_flags & IOSQE_IO_DRAIN) {
4640 head->flags |= REQ_F_IO_DRAIN;
4641 ctx->drain_next = 1;
4643 if (io_alloc_async_ctx(req)) {
4648 ret = io_req_defer_prep(req, sqe);
4650 /* fail even hard links since we don't submit */
4651 head->flags |= REQ_F_FAIL_LINK;
4654 trace_io_uring_link(ctx, req, head);
4655 list_add_tail(&req->link_list, &head->link_list);
4657 /* last request of a link, enqueue the link */
4658 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4659 io_queue_link_head(head);
4663 if (unlikely(ctx->drain_next)) {
4664 req->flags |= REQ_F_IO_DRAIN;
4665 req->ctx->drain_next = 0;
4667 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4668 req->flags |= REQ_F_LINK;
4669 INIT_LIST_HEAD(&req->link_list);
4670 ret = io_req_defer_prep(req, sqe);
4672 req->flags |= REQ_F_FAIL_LINK;
4675 io_queue_sqe(req, sqe);
4683 * Batched submission is done, ensure local IO is flushed out.
4685 static void io_submit_state_end(struct io_submit_state *state)
4687 blk_finish_plug(&state->plug);
4689 if (state->free_reqs)
4690 kmem_cache_free_bulk(req_cachep, state->free_reqs,
4691 &state->reqs[state->cur_req]);
4695 * Start submission side cache.
4697 static void io_submit_state_start(struct io_submit_state *state,
4698 unsigned int max_ios)
4700 blk_start_plug(&state->plug);
4701 state->free_reqs = 0;
4703 state->ios_left = max_ios;
4706 static void io_commit_sqring(struct io_ring_ctx *ctx)
4708 struct io_rings *rings = ctx->rings;
4711 * Ensure any loads from the SQEs are done at this point,
4712 * since once we write the new head, the application could
4713 * write new data to them.
4715 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4719 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4720 * that is mapped by userspace. This means that care needs to be taken to
4721 * ensure that reads are stable, as we cannot rely on userspace always
4722 * being a good citizen. If members of the sqe are validated and then later
4723 * used, it's important that those reads are done through READ_ONCE() to
4724 * prevent a re-load down the line.
4726 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4727 const struct io_uring_sqe **sqe_ptr)
4729 u32 *sq_array = ctx->sq_array;
4733 * The cached sq head (or cq tail) serves two purposes:
4735 * 1) allows us to batch the cost of updating the user visible
4737 * 2) allows the kernel side to track the head on its own, even
4738 * though the application is the one updating it.
4740 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4741 if (likely(head < ctx->sq_entries)) {
4743 * All io need record the previous position, if LINK vs DARIN,
4744 * it can be used to mark the position of the first IO in the
4747 req->sequence = ctx->cached_sq_head;
4748 *sqe_ptr = &ctx->sq_sqes[head];
4749 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4750 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4751 ctx->cached_sq_head++;
4755 /* drop invalid entries */
4756 ctx->cached_sq_head++;
4757 ctx->cached_sq_dropped++;
4758 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4762 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4763 struct file *ring_file, int ring_fd,
4764 struct mm_struct **mm, bool async)
4766 struct io_submit_state state, *statep = NULL;
4767 struct io_kiocb *link = NULL;
4768 int i, submitted = 0;
4769 bool mm_fault = false;
4771 /* if we have a backlog and couldn't flush it all, return BUSY */
4772 if (test_bit(0, &ctx->sq_check_overflow)) {
4773 if (!list_empty(&ctx->cq_overflow_list) &&
4774 !io_cqring_overflow_flush(ctx, false))
4778 /* make sure SQ entry isn't read before tail */
4779 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
4781 if (!percpu_ref_tryget_many(&ctx->refs, nr))
4784 if (nr > IO_PLUG_THRESHOLD) {
4785 io_submit_state_start(&state, nr);
4789 ctx->ring_fd = ring_fd;
4790 ctx->ring_file = ring_file;
4792 for (i = 0; i < nr; i++) {
4793 const struct io_uring_sqe *sqe;
4794 struct io_kiocb *req;
4796 req = io_get_req(ctx, statep);
4797 if (unlikely(!req)) {
4799 submitted = -EAGAIN;
4802 if (!io_get_sqring(ctx, req, &sqe)) {
4803 __io_req_do_free(req);
4807 /* will complete beyond this point, count as submitted */
4810 if (unlikely(req->opcode >= IORING_OP_LAST)) {
4811 io_cqring_add_event(req, -EINVAL);
4812 io_double_put_req(req);
4816 if (io_op_defs[req->opcode].needs_mm && !*mm) {
4817 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
4819 use_mm(ctx->sqo_mm);
4824 req->has_user = *mm != NULL;
4825 req->in_async = async;
4826 req->needs_fixed_file = async;
4827 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
4829 if (!io_submit_sqe(req, sqe, statep, &link))
4833 if (unlikely(submitted != nr)) {
4834 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
4836 percpu_ref_put_many(&ctx->refs, nr - ref_used);
4839 io_queue_link_head(link);
4841 io_submit_state_end(&state);
4843 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4844 io_commit_sqring(ctx);
4849 static int io_sq_thread(void *data)
4851 struct io_ring_ctx *ctx = data;
4852 struct mm_struct *cur_mm = NULL;
4853 const struct cred *old_cred;
4854 mm_segment_t old_fs;
4857 unsigned long timeout;
4860 complete(&ctx->completions[1]);
4864 old_cred = override_creds(ctx->creds);
4866 ret = timeout = inflight = 0;
4867 while (!kthread_should_park()) {
4868 unsigned int to_submit;
4871 unsigned nr_events = 0;
4873 if (ctx->flags & IORING_SETUP_IOPOLL) {
4875 * inflight is the count of the maximum possible
4876 * entries we submitted, but it can be smaller
4877 * if we dropped some of them. If we don't have
4878 * poll entries available, then we know that we
4879 * have nothing left to poll for. Reset the
4880 * inflight count to zero in that case.
4882 mutex_lock(&ctx->uring_lock);
4883 if (!list_empty(&ctx->poll_list))
4884 __io_iopoll_check(ctx, &nr_events, 0);
4887 mutex_unlock(&ctx->uring_lock);
4890 * Normal IO, just pretend everything completed.
4891 * We don't have to poll completions for that.
4893 nr_events = inflight;
4896 inflight -= nr_events;
4898 timeout = jiffies + ctx->sq_thread_idle;
4901 to_submit = io_sqring_entries(ctx);
4904 * If submit got -EBUSY, flag us as needing the application
4905 * to enter the kernel to reap and flush events.
4907 if (!to_submit || ret == -EBUSY) {
4909 * We're polling. If we're within the defined idle
4910 * period, then let us spin without work before going
4911 * to sleep. The exception is if we got EBUSY doing
4912 * more IO, we should wait for the application to
4913 * reap events and wake us up.
4916 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
4922 * Drop cur_mm before scheduling, we can't hold it for
4923 * long periods (or over schedule()). Do this before
4924 * adding ourselves to the waitqueue, as the unuse/drop
4933 prepare_to_wait(&ctx->sqo_wait, &wait,
4934 TASK_INTERRUPTIBLE);
4936 /* Tell userspace we may need a wakeup call */
4937 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
4938 /* make sure to read SQ tail after writing flags */
4941 to_submit = io_sqring_entries(ctx);
4942 if (!to_submit || ret == -EBUSY) {
4943 if (kthread_should_park()) {
4944 finish_wait(&ctx->sqo_wait, &wait);
4947 if (signal_pending(current))
4948 flush_signals(current);
4950 finish_wait(&ctx->sqo_wait, &wait);
4952 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4955 finish_wait(&ctx->sqo_wait, &wait);
4957 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4960 mutex_lock(&ctx->uring_lock);
4961 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
4962 mutex_unlock(&ctx->uring_lock);
4972 revert_creds(old_cred);
4979 struct io_wait_queue {
4980 struct wait_queue_entry wq;
4981 struct io_ring_ctx *ctx;
4983 unsigned nr_timeouts;
4986 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
4988 struct io_ring_ctx *ctx = iowq->ctx;
4991 * Wake up if we have enough events, or if a timeout occurred since we
4992 * started waiting. For timeouts, we always want to return to userspace,
4993 * regardless of event count.
4995 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
4996 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4999 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5000 int wake_flags, void *key)
5002 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5005 /* use noflush == true, as we can't safely rely on locking context */
5006 if (!io_should_wake(iowq, true))
5009 return autoremove_wake_function(curr, mode, wake_flags, key);
5013 * Wait until events become available, if we don't already have some. The
5014 * application must reap them itself, as they reside on the shared cq ring.
5016 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5017 const sigset_t __user *sig, size_t sigsz)
5019 struct io_wait_queue iowq = {
5022 .func = io_wake_function,
5023 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5026 .to_wait = min_events,
5028 struct io_rings *rings = ctx->rings;
5031 if (io_cqring_events(ctx, false) >= min_events)
5035 #ifdef CONFIG_COMPAT
5036 if (in_compat_syscall())
5037 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5041 ret = set_user_sigmask(sig, sigsz);
5047 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5048 trace_io_uring_cqring_wait(ctx, min_events);
5050 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5051 TASK_INTERRUPTIBLE);
5052 if (io_should_wake(&iowq, false))
5055 if (signal_pending(current)) {
5060 finish_wait(&ctx->wait, &iowq.wq);
5062 restore_saved_sigmask_unless(ret == -EINTR);
5064 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5067 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5069 #if defined(CONFIG_UNIX)
5070 if (ctx->ring_sock) {
5071 struct sock *sock = ctx->ring_sock->sk;
5072 struct sk_buff *skb;
5074 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5080 for (i = 0; i < ctx->nr_user_files; i++) {
5083 file = io_file_from_index(ctx, i);
5090 static void io_file_ref_kill(struct percpu_ref *ref)
5092 struct fixed_file_data *data;
5094 data = container_of(ref, struct fixed_file_data, refs);
5095 complete(&data->done);
5098 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5100 struct fixed_file_data *data = ctx->file_data;
5101 unsigned nr_tables, i;
5106 /* protect against inflight atomic switch, which drops the ref */
5107 percpu_ref_get(&data->refs);
5108 /* wait for existing switches */
5109 flush_work(&data->ref_work);
5110 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5111 wait_for_completion(&data->done);
5112 percpu_ref_put(&data->refs);
5113 /* flush potential new switch */
5114 flush_work(&data->ref_work);
5115 percpu_ref_exit(&data->refs);
5117 __io_sqe_files_unregister(ctx);
5118 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5119 for (i = 0; i < nr_tables; i++)
5120 kfree(data->table[i].files);
5123 ctx->file_data = NULL;
5124 ctx->nr_user_files = 0;
5128 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5130 if (ctx->sqo_thread) {
5131 wait_for_completion(&ctx->completions[1]);
5133 * The park is a bit of a work-around, without it we get
5134 * warning spews on shutdown with SQPOLL set and affinity
5135 * set to a single CPU.
5137 kthread_park(ctx->sqo_thread);
5138 kthread_stop(ctx->sqo_thread);
5139 ctx->sqo_thread = NULL;
5143 static void io_finish_async(struct io_ring_ctx *ctx)
5145 io_sq_thread_stop(ctx);
5148 io_wq_destroy(ctx->io_wq);
5153 #if defined(CONFIG_UNIX)
5155 * Ensure the UNIX gc is aware of our file set, so we are certain that
5156 * the io_uring can be safely unregistered on process exit, even if we have
5157 * loops in the file referencing.
5159 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5161 struct sock *sk = ctx->ring_sock->sk;
5162 struct scm_fp_list *fpl;
5163 struct sk_buff *skb;
5166 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5167 unsigned long inflight = ctx->user->unix_inflight + nr;
5169 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5173 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5177 skb = alloc_skb(0, GFP_KERNEL);
5186 fpl->user = get_uid(ctx->user);
5187 for (i = 0; i < nr; i++) {
5188 struct file *file = io_file_from_index(ctx, i + offset);
5192 fpl->fp[nr_files] = get_file(file);
5193 unix_inflight(fpl->user, fpl->fp[nr_files]);
5198 fpl->max = SCM_MAX_FD;
5199 fpl->count = nr_files;
5200 UNIXCB(skb).fp = fpl;
5201 skb->destructor = unix_destruct_scm;
5202 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5203 skb_queue_head(&sk->sk_receive_queue, skb);
5205 for (i = 0; i < nr_files; i++)
5216 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5217 * causes regular reference counting to break down. We rely on the UNIX
5218 * garbage collection to take care of this problem for us.
5220 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5222 unsigned left, total;
5226 left = ctx->nr_user_files;
5228 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
5230 ret = __io_sqe_files_scm(ctx, this_files, total);
5234 total += this_files;
5240 while (total < ctx->nr_user_files) {
5241 struct file *file = io_file_from_index(ctx, total);
5251 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5257 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5262 for (i = 0; i < nr_tables; i++) {
5263 struct fixed_file_table *table = &ctx->file_data->table[i];
5264 unsigned this_files;
5266 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5267 table->files = kcalloc(this_files, sizeof(struct file *),
5271 nr_files -= this_files;
5277 for (i = 0; i < nr_tables; i++) {
5278 struct fixed_file_table *table = &ctx->file_data->table[i];
5279 kfree(table->files);
5284 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5286 #if defined(CONFIG_UNIX)
5287 struct sock *sock = ctx->ring_sock->sk;
5288 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5289 struct sk_buff *skb;
5292 __skb_queue_head_init(&list);
5295 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5296 * remove this entry and rearrange the file array.
5298 skb = skb_dequeue(head);
5300 struct scm_fp_list *fp;
5302 fp = UNIXCB(skb).fp;
5303 for (i = 0; i < fp->count; i++) {
5306 if (fp->fp[i] != file)
5309 unix_notinflight(fp->user, fp->fp[i]);
5310 left = fp->count - 1 - i;
5312 memmove(&fp->fp[i], &fp->fp[i + 1],
5313 left * sizeof(struct file *));
5320 __skb_queue_tail(&list, skb);
5330 __skb_queue_tail(&list, skb);
5332 skb = skb_dequeue(head);
5335 if (skb_peek(&list)) {
5336 spin_lock_irq(&head->lock);
5337 while ((skb = __skb_dequeue(&list)) != NULL)
5338 __skb_queue_tail(head, skb);
5339 spin_unlock_irq(&head->lock);
5346 struct io_file_put {
5347 struct llist_node llist;
5349 struct completion *done;
5352 static void io_ring_file_ref_switch(struct work_struct *work)
5354 struct io_file_put *pfile, *tmp;
5355 struct fixed_file_data *data;
5356 struct llist_node *node;
5358 data = container_of(work, struct fixed_file_data, ref_work);
5360 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5361 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5362 io_ring_file_put(data->ctx, pfile->file);
5364 complete(pfile->done);
5370 percpu_ref_get(&data->refs);
5371 percpu_ref_switch_to_percpu(&data->refs);
5374 static void io_file_data_ref_zero(struct percpu_ref *ref)
5376 struct fixed_file_data *data;
5378 data = container_of(ref, struct fixed_file_data, refs);
5380 /* we can't safely switch from inside this context, punt to wq */
5381 queue_work(system_wq, &data->ref_work);
5384 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5387 __s32 __user *fds = (__s32 __user *) arg;
5397 if (nr_args > IORING_MAX_FIXED_FILES)
5400 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5401 if (!ctx->file_data)
5403 ctx->file_data->ctx = ctx;
5404 init_completion(&ctx->file_data->done);
5406 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5407 ctx->file_data->table = kcalloc(nr_tables,
5408 sizeof(struct fixed_file_table),
5410 if (!ctx->file_data->table) {
5411 kfree(ctx->file_data);
5412 ctx->file_data = NULL;
5416 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5417 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5418 kfree(ctx->file_data->table);
5419 kfree(ctx->file_data);
5420 ctx->file_data = NULL;
5423 ctx->file_data->put_llist.first = NULL;
5424 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5426 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5427 percpu_ref_exit(&ctx->file_data->refs);
5428 kfree(ctx->file_data->table);
5429 kfree(ctx->file_data);
5430 ctx->file_data = NULL;
5434 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5435 struct fixed_file_table *table;
5439 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5441 /* allow sparse sets */
5447 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5448 index = i & IORING_FILE_TABLE_MASK;
5456 * Don't allow io_uring instances to be registered. If UNIX
5457 * isn't enabled, then this causes a reference cycle and this
5458 * instance can never get freed. If UNIX is enabled we'll
5459 * handle it just fine, but there's still no point in allowing
5460 * a ring fd as it doesn't support regular read/write anyway.
5462 if (file->f_op == &io_uring_fops) {
5467 table->files[index] = file;
5471 for (i = 0; i < ctx->nr_user_files; i++) {
5472 file = io_file_from_index(ctx, i);
5476 for (i = 0; i < nr_tables; i++)
5477 kfree(ctx->file_data->table[i].files);
5479 kfree(ctx->file_data->table);
5480 kfree(ctx->file_data);
5481 ctx->file_data = NULL;
5482 ctx->nr_user_files = 0;
5486 ret = io_sqe_files_scm(ctx);
5488 io_sqe_files_unregister(ctx);
5493 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5496 #if defined(CONFIG_UNIX)
5497 struct sock *sock = ctx->ring_sock->sk;
5498 struct sk_buff_head *head = &sock->sk_receive_queue;
5499 struct sk_buff *skb;
5502 * See if we can merge this file into an existing skb SCM_RIGHTS
5503 * file set. If there's no room, fall back to allocating a new skb
5504 * and filling it in.
5506 spin_lock_irq(&head->lock);
5507 skb = skb_peek(head);
5509 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5511 if (fpl->count < SCM_MAX_FD) {
5512 __skb_unlink(skb, head);
5513 spin_unlock_irq(&head->lock);
5514 fpl->fp[fpl->count] = get_file(file);
5515 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5517 spin_lock_irq(&head->lock);
5518 __skb_queue_head(head, skb);
5523 spin_unlock_irq(&head->lock);
5530 return __io_sqe_files_scm(ctx, 1, index);
5536 static void io_atomic_switch(struct percpu_ref *ref)
5538 struct fixed_file_data *data;
5540 data = container_of(ref, struct fixed_file_data, refs);
5541 clear_bit(FFD_F_ATOMIC, &data->state);
5544 static bool io_queue_file_removal(struct fixed_file_data *data,
5547 struct io_file_put *pfile, pfile_stack;
5548 DECLARE_COMPLETION_ONSTACK(done);
5551 * If we fail allocating the struct we need for doing async reomval
5552 * of this file, just punt to sync and wait for it.
5554 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5556 pfile = &pfile_stack;
5557 pfile->done = &done;
5561 llist_add(&pfile->llist, &data->put_llist);
5563 if (pfile == &pfile_stack) {
5564 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5565 percpu_ref_put(&data->refs);
5566 percpu_ref_switch_to_atomic(&data->refs,
5569 wait_for_completion(&done);
5570 flush_work(&data->ref_work);
5577 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5578 struct io_uring_files_update *up,
5581 struct fixed_file_data *data = ctx->file_data;
5582 bool ref_switch = false;
5588 if (check_add_overflow(up->offset, nr_args, &done))
5590 if (done > ctx->nr_user_files)
5594 fds = u64_to_user_ptr(up->fds);
5596 struct fixed_file_table *table;
5600 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5604 i = array_index_nospec(up->offset, ctx->nr_user_files);
5605 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5606 index = i & IORING_FILE_TABLE_MASK;
5607 if (table->files[index]) {
5608 file = io_file_from_index(ctx, index);
5609 table->files[index] = NULL;
5610 if (io_queue_file_removal(data, file))
5620 * Don't allow io_uring instances to be registered. If
5621 * UNIX isn't enabled, then this causes a reference
5622 * cycle and this instance can never get freed. If UNIX
5623 * is enabled we'll handle it just fine, but there's
5624 * still no point in allowing a ring fd as it doesn't
5625 * support regular read/write anyway.
5627 if (file->f_op == &io_uring_fops) {
5632 table->files[index] = file;
5633 err = io_sqe_file_register(ctx, file, i);
5642 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5643 percpu_ref_put(&data->refs);
5644 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5647 return done ? done : err;
5649 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5652 struct io_uring_files_update up;
5654 if (!ctx->file_data)
5658 if (copy_from_user(&up, arg, sizeof(up)))
5663 return __io_sqe_files_update(ctx, &up, nr_args);
5666 static void io_put_work(struct io_wq_work *work)
5668 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5673 static void io_get_work(struct io_wq_work *work)
5675 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5677 refcount_inc(&req->refs);
5680 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5681 struct io_uring_params *p)
5683 struct io_wq_data data;
5684 unsigned concurrency;
5687 init_waitqueue_head(&ctx->sqo_wait);
5688 mmgrab(current->mm);
5689 ctx->sqo_mm = current->mm;
5691 if (ctx->flags & IORING_SETUP_SQPOLL) {
5693 if (!capable(CAP_SYS_ADMIN))
5696 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5697 if (!ctx->sq_thread_idle)
5698 ctx->sq_thread_idle = HZ;
5700 if (p->flags & IORING_SETUP_SQ_AFF) {
5701 int cpu = p->sq_thread_cpu;
5704 if (cpu >= nr_cpu_ids)
5706 if (!cpu_online(cpu))
5709 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5713 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5716 if (IS_ERR(ctx->sqo_thread)) {
5717 ret = PTR_ERR(ctx->sqo_thread);
5718 ctx->sqo_thread = NULL;
5721 wake_up_process(ctx->sqo_thread);
5722 } else if (p->flags & IORING_SETUP_SQ_AFF) {
5723 /* Can't have SQ_AFF without SQPOLL */
5728 data.mm = ctx->sqo_mm;
5729 data.user = ctx->user;
5730 data.creds = ctx->creds;
5731 data.get_work = io_get_work;
5732 data.put_work = io_put_work;
5734 /* Do QD, or 4 * CPUS, whatever is smallest */
5735 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5736 ctx->io_wq = io_wq_create(concurrency, &data);
5737 if (IS_ERR(ctx->io_wq)) {
5738 ret = PTR_ERR(ctx->io_wq);
5745 io_finish_async(ctx);
5746 mmdrop(ctx->sqo_mm);
5751 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
5753 atomic_long_sub(nr_pages, &user->locked_vm);
5756 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
5758 unsigned long page_limit, cur_pages, new_pages;
5760 /* Don't allow more pages than we can safely lock */
5761 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5764 cur_pages = atomic_long_read(&user->locked_vm);
5765 new_pages = cur_pages + nr_pages;
5766 if (new_pages > page_limit)
5768 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5769 new_pages) != cur_pages);
5774 static void io_mem_free(void *ptr)
5781 page = virt_to_head_page(ptr);
5782 if (put_page_testzero(page))
5783 free_compound_page(page);
5786 static void *io_mem_alloc(size_t size)
5788 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
5791 return (void *) __get_free_pages(gfp_flags, get_order(size));
5794 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
5797 struct io_rings *rings;
5798 size_t off, sq_array_size;
5800 off = struct_size(rings, cqes, cq_entries);
5801 if (off == SIZE_MAX)
5805 off = ALIGN(off, SMP_CACHE_BYTES);
5810 sq_array_size = array_size(sizeof(u32), sq_entries);
5811 if (sq_array_size == SIZE_MAX)
5814 if (check_add_overflow(off, sq_array_size, &off))
5823 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
5827 pages = (size_t)1 << get_order(
5828 rings_size(sq_entries, cq_entries, NULL));
5829 pages += (size_t)1 << get_order(
5830 array_size(sizeof(struct io_uring_sqe), sq_entries));
5835 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
5839 if (!ctx->user_bufs)
5842 for (i = 0; i < ctx->nr_user_bufs; i++) {
5843 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5845 for (j = 0; j < imu->nr_bvecs; j++)
5846 put_user_page(imu->bvec[j].bv_page);
5848 if (ctx->account_mem)
5849 io_unaccount_mem(ctx->user, imu->nr_bvecs);
5854 kfree(ctx->user_bufs);
5855 ctx->user_bufs = NULL;
5856 ctx->nr_user_bufs = 0;
5860 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
5861 void __user *arg, unsigned index)
5863 struct iovec __user *src;
5865 #ifdef CONFIG_COMPAT
5867 struct compat_iovec __user *ciovs;
5868 struct compat_iovec ciov;
5870 ciovs = (struct compat_iovec __user *) arg;
5871 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
5874 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
5875 dst->iov_len = ciov.iov_len;
5879 src = (struct iovec __user *) arg;
5880 if (copy_from_user(dst, &src[index], sizeof(*dst)))
5885 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
5888 struct vm_area_struct **vmas = NULL;
5889 struct page **pages = NULL;
5890 int i, j, got_pages = 0;
5895 if (!nr_args || nr_args > UIO_MAXIOV)
5898 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
5900 if (!ctx->user_bufs)
5903 for (i = 0; i < nr_args; i++) {
5904 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5905 unsigned long off, start, end, ubuf;
5910 ret = io_copy_iov(ctx, &iov, arg, i);
5915 * Don't impose further limits on the size and buffer
5916 * constraints here, we'll -EINVAL later when IO is
5917 * submitted if they are wrong.
5920 if (!iov.iov_base || !iov.iov_len)
5923 /* arbitrary limit, but we need something */
5924 if (iov.iov_len > SZ_1G)
5927 ubuf = (unsigned long) iov.iov_base;
5928 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
5929 start = ubuf >> PAGE_SHIFT;
5930 nr_pages = end - start;
5932 if (ctx->account_mem) {
5933 ret = io_account_mem(ctx->user, nr_pages);
5939 if (!pages || nr_pages > got_pages) {
5942 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
5944 vmas = kvmalloc_array(nr_pages,
5945 sizeof(struct vm_area_struct *),
5947 if (!pages || !vmas) {
5949 if (ctx->account_mem)
5950 io_unaccount_mem(ctx->user, nr_pages);
5953 got_pages = nr_pages;
5956 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
5960 if (ctx->account_mem)
5961 io_unaccount_mem(ctx->user, nr_pages);
5966 down_read(¤t->mm->mmap_sem);
5967 pret = get_user_pages(ubuf, nr_pages,
5968 FOLL_WRITE | FOLL_LONGTERM,
5970 if (pret == nr_pages) {
5971 /* don't support file backed memory */
5972 for (j = 0; j < nr_pages; j++) {
5973 struct vm_area_struct *vma = vmas[j];
5976 !is_file_hugepages(vma->vm_file)) {
5982 ret = pret < 0 ? pret : -EFAULT;
5984 up_read(¤t->mm->mmap_sem);
5987 * if we did partial map, or found file backed vmas,
5988 * release any pages we did get
5991 put_user_pages(pages, pret);
5992 if (ctx->account_mem)
5993 io_unaccount_mem(ctx->user, nr_pages);
5998 off = ubuf & ~PAGE_MASK;
6000 for (j = 0; j < nr_pages; j++) {
6003 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6004 imu->bvec[j].bv_page = pages[j];
6005 imu->bvec[j].bv_len = vec_len;
6006 imu->bvec[j].bv_offset = off;
6010 /* store original address for later verification */
6012 imu->len = iov.iov_len;
6013 imu->nr_bvecs = nr_pages;
6015 ctx->nr_user_bufs++;
6023 io_sqe_buffer_unregister(ctx);
6027 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6029 __s32 __user *fds = arg;
6035 if (copy_from_user(&fd, fds, sizeof(*fds)))
6038 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6039 if (IS_ERR(ctx->cq_ev_fd)) {
6040 int ret = PTR_ERR(ctx->cq_ev_fd);
6041 ctx->cq_ev_fd = NULL;
6048 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6050 if (ctx->cq_ev_fd) {
6051 eventfd_ctx_put(ctx->cq_ev_fd);
6052 ctx->cq_ev_fd = NULL;
6059 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6061 io_finish_async(ctx);
6063 mmdrop(ctx->sqo_mm);
6065 io_iopoll_reap_events(ctx);
6066 io_sqe_buffer_unregister(ctx);
6067 io_sqe_files_unregister(ctx);
6068 io_eventfd_unregister(ctx);
6070 #if defined(CONFIG_UNIX)
6071 if (ctx->ring_sock) {
6072 ctx->ring_sock->file = NULL; /* so that iput() is called */
6073 sock_release(ctx->ring_sock);
6077 io_mem_free(ctx->rings);
6078 io_mem_free(ctx->sq_sqes);
6080 percpu_ref_exit(&ctx->refs);
6081 if (ctx->account_mem)
6082 io_unaccount_mem(ctx->user,
6083 ring_pages(ctx->sq_entries, ctx->cq_entries));
6084 free_uid(ctx->user);
6085 put_cred(ctx->creds);
6086 kfree(ctx->completions);
6087 kfree(ctx->cancel_hash);
6088 kmem_cache_free(req_cachep, ctx->fallback_req);
6092 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6094 struct io_ring_ctx *ctx = file->private_data;
6097 poll_wait(file, &ctx->cq_wait, wait);
6099 * synchronizes with barrier from wq_has_sleeper call in
6103 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6104 ctx->rings->sq_ring_entries)
6105 mask |= EPOLLOUT | EPOLLWRNORM;
6106 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
6107 mask |= EPOLLIN | EPOLLRDNORM;
6112 static int io_uring_fasync(int fd, struct file *file, int on)
6114 struct io_ring_ctx *ctx = file->private_data;
6116 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6119 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6121 mutex_lock(&ctx->uring_lock);
6122 percpu_ref_kill(&ctx->refs);
6123 mutex_unlock(&ctx->uring_lock);
6125 io_kill_timeouts(ctx);
6126 io_poll_remove_all(ctx);
6129 io_wq_cancel_all(ctx->io_wq);
6131 io_iopoll_reap_events(ctx);
6132 /* if we failed setting up the ctx, we might not have any rings */
6134 io_cqring_overflow_flush(ctx, true);
6135 wait_for_completion(&ctx->completions[0]);
6136 io_ring_ctx_free(ctx);
6139 static int io_uring_release(struct inode *inode, struct file *file)
6141 struct io_ring_ctx *ctx = file->private_data;
6143 file->private_data = NULL;
6144 io_ring_ctx_wait_and_kill(ctx);
6148 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6149 struct files_struct *files)
6151 struct io_kiocb *req;
6154 while (!list_empty_careful(&ctx->inflight_list)) {
6155 struct io_kiocb *cancel_req = NULL;
6157 spin_lock_irq(&ctx->inflight_lock);
6158 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
6159 if (req->work.files != files)
6161 /* req is being completed, ignore */
6162 if (!refcount_inc_not_zero(&req->refs))
6168 prepare_to_wait(&ctx->inflight_wait, &wait,
6169 TASK_UNINTERRUPTIBLE);
6170 spin_unlock_irq(&ctx->inflight_lock);
6172 /* We need to keep going until we don't find a matching req */
6176 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6177 io_put_req(cancel_req);
6180 finish_wait(&ctx->inflight_wait, &wait);
6183 static int io_uring_flush(struct file *file, void *data)
6185 struct io_ring_ctx *ctx = file->private_data;
6187 io_uring_cancel_files(ctx, data);
6188 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
6189 io_cqring_overflow_flush(ctx, true);
6190 io_wq_cancel_all(ctx->io_wq);
6195 static void *io_uring_validate_mmap_request(struct file *file,
6196 loff_t pgoff, size_t sz)
6198 struct io_ring_ctx *ctx = file->private_data;
6199 loff_t offset = pgoff << PAGE_SHIFT;
6204 case IORING_OFF_SQ_RING:
6205 case IORING_OFF_CQ_RING:
6208 case IORING_OFF_SQES:
6212 return ERR_PTR(-EINVAL);
6215 page = virt_to_head_page(ptr);
6216 if (sz > page_size(page))
6217 return ERR_PTR(-EINVAL);
6224 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6226 size_t sz = vma->vm_end - vma->vm_start;
6230 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6232 return PTR_ERR(ptr);
6234 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6235 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6238 #else /* !CONFIG_MMU */
6240 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6242 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6245 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6247 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6250 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6251 unsigned long addr, unsigned long len,
6252 unsigned long pgoff, unsigned long flags)
6256 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6258 return PTR_ERR(ptr);
6260 return (unsigned long) ptr;
6263 #endif /* !CONFIG_MMU */
6265 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6266 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6269 struct io_ring_ctx *ctx;
6274 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
6282 if (f.file->f_op != &io_uring_fops)
6286 ctx = f.file->private_data;
6287 if (!percpu_ref_tryget(&ctx->refs))
6291 * For SQ polling, the thread will do all submissions and completions.
6292 * Just return the requested submit count, and wake the thread if
6296 if (ctx->flags & IORING_SETUP_SQPOLL) {
6297 if (!list_empty_careful(&ctx->cq_overflow_list))
6298 io_cqring_overflow_flush(ctx, false);
6299 if (flags & IORING_ENTER_SQ_WAKEUP)
6300 wake_up(&ctx->sqo_wait);
6301 submitted = to_submit;
6302 } else if (to_submit) {
6303 struct mm_struct *cur_mm;
6305 if (current->mm != ctx->sqo_mm ||
6306 current_cred() != ctx->creds) {
6311 mutex_lock(&ctx->uring_lock);
6312 /* already have mm, so io_submit_sqes() won't try to grab it */
6313 cur_mm = ctx->sqo_mm;
6314 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6316 mutex_unlock(&ctx->uring_lock);
6318 if (submitted != to_submit)
6321 if (flags & IORING_ENTER_GETEVENTS) {
6322 unsigned nr_events = 0;
6324 min_complete = min(min_complete, ctx->cq_entries);
6326 if (ctx->flags & IORING_SETUP_IOPOLL) {
6327 ret = io_iopoll_check(ctx, &nr_events, min_complete);
6329 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6334 percpu_ref_put(&ctx->refs);
6337 return submitted ? submitted : ret;
6340 static const struct file_operations io_uring_fops = {
6341 .release = io_uring_release,
6342 .flush = io_uring_flush,
6343 .mmap = io_uring_mmap,
6345 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6346 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6348 .poll = io_uring_poll,
6349 .fasync = io_uring_fasync,
6352 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6353 struct io_uring_params *p)
6355 struct io_rings *rings;
6356 size_t size, sq_array_offset;
6358 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6359 if (size == SIZE_MAX)
6362 rings = io_mem_alloc(size);
6367 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6368 rings->sq_ring_mask = p->sq_entries - 1;
6369 rings->cq_ring_mask = p->cq_entries - 1;
6370 rings->sq_ring_entries = p->sq_entries;
6371 rings->cq_ring_entries = p->cq_entries;
6372 ctx->sq_mask = rings->sq_ring_mask;
6373 ctx->cq_mask = rings->cq_ring_mask;
6374 ctx->sq_entries = rings->sq_ring_entries;
6375 ctx->cq_entries = rings->cq_ring_entries;
6377 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6378 if (size == SIZE_MAX) {
6379 io_mem_free(ctx->rings);
6384 ctx->sq_sqes = io_mem_alloc(size);
6385 if (!ctx->sq_sqes) {
6386 io_mem_free(ctx->rings);
6395 * Allocate an anonymous fd, this is what constitutes the application
6396 * visible backing of an io_uring instance. The application mmaps this
6397 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6398 * we have to tie this fd to a socket for file garbage collection purposes.
6400 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6405 #if defined(CONFIG_UNIX)
6406 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6412 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6416 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6417 O_RDWR | O_CLOEXEC);
6420 ret = PTR_ERR(file);
6424 #if defined(CONFIG_UNIX)
6425 ctx->ring_sock->file = file;
6427 fd_install(ret, file);
6430 #if defined(CONFIG_UNIX)
6431 sock_release(ctx->ring_sock);
6432 ctx->ring_sock = NULL;
6437 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6439 struct user_struct *user = NULL;
6440 struct io_ring_ctx *ctx;
6446 if (entries > IORING_MAX_ENTRIES) {
6447 if (!(p->flags & IORING_SETUP_CLAMP))
6449 entries = IORING_MAX_ENTRIES;
6453 * Use twice as many entries for the CQ ring. It's possible for the
6454 * application to drive a higher depth than the size of the SQ ring,
6455 * since the sqes are only used at submission time. This allows for
6456 * some flexibility in overcommitting a bit. If the application has
6457 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6458 * of CQ ring entries manually.
6460 p->sq_entries = roundup_pow_of_two(entries);
6461 if (p->flags & IORING_SETUP_CQSIZE) {
6463 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6464 * to a power-of-two, if it isn't already. We do NOT impose
6465 * any cq vs sq ring sizing.
6467 if (p->cq_entries < p->sq_entries)
6469 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6470 if (!(p->flags & IORING_SETUP_CLAMP))
6472 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6474 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6476 p->cq_entries = 2 * p->sq_entries;
6479 user = get_uid(current_user());
6480 account_mem = !capable(CAP_IPC_LOCK);
6483 ret = io_account_mem(user,
6484 ring_pages(p->sq_entries, p->cq_entries));
6491 ctx = io_ring_ctx_alloc(p);
6494 io_unaccount_mem(user, ring_pages(p->sq_entries,
6499 ctx->compat = in_compat_syscall();
6500 ctx->account_mem = account_mem;
6502 ctx->creds = get_current_cred();
6504 ret = io_allocate_scq_urings(ctx, p);
6508 ret = io_sq_offload_start(ctx, p);
6512 memset(&p->sq_off, 0, sizeof(p->sq_off));
6513 p->sq_off.head = offsetof(struct io_rings, sq.head);
6514 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6515 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6516 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6517 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6518 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6519 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6521 memset(&p->cq_off, 0, sizeof(p->cq_off));
6522 p->cq_off.head = offsetof(struct io_rings, cq.head);
6523 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6524 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6525 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6526 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6527 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6530 * Install ring fd as the very last thing, so we don't risk someone
6531 * having closed it before we finish setup
6533 ret = io_uring_get_fd(ctx);
6537 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6538 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS;
6539 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6542 io_ring_ctx_wait_and_kill(ctx);
6547 * Sets up an aio uring context, and returns the fd. Applications asks for a
6548 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6549 * params structure passed in.
6551 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6553 struct io_uring_params p;
6557 if (copy_from_user(&p, params, sizeof(p)))
6559 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6564 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6565 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6566 IORING_SETUP_CLAMP))
6569 ret = io_uring_create(entries, &p);
6573 if (copy_to_user(params, &p, sizeof(p)))
6579 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6580 struct io_uring_params __user *, params)
6582 return io_uring_setup(entries, params);
6585 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6587 struct io_uring_probe *p;
6591 size = struct_size(p, ops, nr_args);
6592 if (size == SIZE_MAX)
6594 p = kzalloc(size, GFP_KERNEL);
6599 if (copy_from_user(p, arg, size))
6602 if (memchr_inv(p, 0, size))
6605 p->last_op = IORING_OP_LAST - 1;
6606 if (nr_args > IORING_OP_LAST)
6607 nr_args = IORING_OP_LAST;
6609 for (i = 0; i < nr_args; i++) {
6611 if (!io_op_defs[i].not_supported)
6612 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6617 if (copy_to_user(arg, p, size))
6624 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6625 void __user *arg, unsigned nr_args)
6626 __releases(ctx->uring_lock)
6627 __acquires(ctx->uring_lock)
6632 * We're inside the ring mutex, if the ref is already dying, then
6633 * someone else killed the ctx or is already going through
6634 * io_uring_register().
6636 if (percpu_ref_is_dying(&ctx->refs))
6639 if (opcode != IORING_UNREGISTER_FILES &&
6640 opcode != IORING_REGISTER_FILES_UPDATE &&
6641 opcode != IORING_REGISTER_PROBE) {
6642 percpu_ref_kill(&ctx->refs);
6645 * Drop uring mutex before waiting for references to exit. If
6646 * another thread is currently inside io_uring_enter() it might
6647 * need to grab the uring_lock to make progress. If we hold it
6648 * here across the drain wait, then we can deadlock. It's safe
6649 * to drop the mutex here, since no new references will come in
6650 * after we've killed the percpu ref.
6652 mutex_unlock(&ctx->uring_lock);
6653 ret = wait_for_completion_interruptible(&ctx->completions[0]);
6654 mutex_lock(&ctx->uring_lock);
6656 percpu_ref_resurrect(&ctx->refs);
6663 case IORING_REGISTER_BUFFERS:
6664 ret = io_sqe_buffer_register(ctx, arg, nr_args);
6666 case IORING_UNREGISTER_BUFFERS:
6670 ret = io_sqe_buffer_unregister(ctx);
6672 case IORING_REGISTER_FILES:
6673 ret = io_sqe_files_register(ctx, arg, nr_args);
6675 case IORING_UNREGISTER_FILES:
6679 ret = io_sqe_files_unregister(ctx);
6681 case IORING_REGISTER_FILES_UPDATE:
6682 ret = io_sqe_files_update(ctx, arg, nr_args);
6684 case IORING_REGISTER_EVENTFD:
6685 case IORING_REGISTER_EVENTFD_ASYNC:
6689 ret = io_eventfd_register(ctx, arg);
6692 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
6693 ctx->eventfd_async = 1;
6695 ctx->eventfd_async = 0;
6697 case IORING_UNREGISTER_EVENTFD:
6701 ret = io_eventfd_unregister(ctx);
6703 case IORING_REGISTER_PROBE:
6705 if (!arg || nr_args > 256)
6707 ret = io_probe(ctx, arg, nr_args);
6715 if (opcode != IORING_UNREGISTER_FILES &&
6716 opcode != IORING_REGISTER_FILES_UPDATE &&
6717 opcode != IORING_REGISTER_PROBE) {
6718 /* bring the ctx back to life */
6719 percpu_ref_reinit(&ctx->refs);
6721 reinit_completion(&ctx->completions[0]);
6726 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
6727 void __user *, arg, unsigned int, nr_args)
6729 struct io_ring_ctx *ctx;
6738 if (f.file->f_op != &io_uring_fops)
6741 ctx = f.file->private_data;
6743 mutex_lock(&ctx->uring_lock);
6744 ret = __io_uring_register(ctx, opcode, arg, nr_args);
6745 mutex_unlock(&ctx->uring_lock);
6746 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
6747 ctx->cq_ev_fd != NULL, ret);
6753 static int __init io_uring_init(void)
6755 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
6756 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
6759 __initcall(io_uring_init);