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 void io_req_work_grab_env(struct io_kiocb *req,
879 const struct io_op_def *def)
881 if (!req->work.mm && def->needs_mm) {
883 req->work.mm = current->mm;
885 if (!req->work.creds)
886 req->work.creds = get_current_cred();
889 static inline void io_req_work_drop_env(struct io_kiocb *req)
892 mmdrop(req->work.mm);
895 if (req->work.creds) {
896 put_cred(req->work.creds);
897 req->work.creds = NULL;
901 static inline bool io_prep_async_work(struct io_kiocb *req,
902 struct io_kiocb **link)
904 const struct io_op_def *def = &io_op_defs[req->opcode];
905 bool do_hashed = false;
907 if (req->flags & REQ_F_ISREG) {
908 if (def->hash_reg_file)
911 if (def->unbound_nonreg_file)
912 req->work.flags |= IO_WQ_WORK_UNBOUND;
915 io_req_work_grab_env(req, def);
917 *link = io_prep_linked_timeout(req);
921 static inline void io_queue_async_work(struct io_kiocb *req)
923 struct io_ring_ctx *ctx = req->ctx;
924 struct io_kiocb *link;
927 do_hashed = io_prep_async_work(req, &link);
929 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
932 io_wq_enqueue(ctx->io_wq, &req->work);
934 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
935 file_inode(req->file));
939 io_queue_linked_timeout(link);
942 static void io_kill_timeout(struct io_kiocb *req)
946 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
948 atomic_inc(&req->ctx->cq_timeouts);
949 list_del_init(&req->list);
950 io_cqring_fill_event(req, 0);
955 static void io_kill_timeouts(struct io_ring_ctx *ctx)
957 struct io_kiocb *req, *tmp;
959 spin_lock_irq(&ctx->completion_lock);
960 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
961 io_kill_timeout(req);
962 spin_unlock_irq(&ctx->completion_lock);
965 static void io_commit_cqring(struct io_ring_ctx *ctx)
967 struct io_kiocb *req;
969 while ((req = io_get_timeout_req(ctx)) != NULL)
970 io_kill_timeout(req);
972 __io_commit_cqring(ctx);
974 while ((req = io_get_deferred_req(ctx)) != NULL)
975 io_queue_async_work(req);
978 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
980 struct io_rings *rings = ctx->rings;
983 tail = ctx->cached_cq_tail;
985 * writes to the cq entry need to come after reading head; the
986 * control dependency is enough as we're using WRITE_ONCE to
989 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
992 ctx->cached_cq_tail++;
993 return &rings->cqes[tail & ctx->cq_mask];
996 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
998 if (!ctx->eventfd_async)
1000 return io_wq_current_is_worker() || in_interrupt();
1003 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1005 if (waitqueue_active(&ctx->wait))
1006 wake_up(&ctx->wait);
1007 if (waitqueue_active(&ctx->sqo_wait))
1008 wake_up(&ctx->sqo_wait);
1009 if (ctx->cq_ev_fd && io_should_trigger_evfd(ctx))
1010 eventfd_signal(ctx->cq_ev_fd, 1);
1013 /* Returns true if there are no backlogged entries after the flush */
1014 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1016 struct io_rings *rings = ctx->rings;
1017 struct io_uring_cqe *cqe;
1018 struct io_kiocb *req;
1019 unsigned long flags;
1023 if (list_empty_careful(&ctx->cq_overflow_list))
1025 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1026 rings->cq_ring_entries))
1030 spin_lock_irqsave(&ctx->completion_lock, flags);
1032 /* if force is set, the ring is going away. always drop after that */
1034 ctx->cq_overflow_flushed = 1;
1037 while (!list_empty(&ctx->cq_overflow_list)) {
1038 cqe = io_get_cqring(ctx);
1042 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1044 list_move(&req->list, &list);
1046 WRITE_ONCE(cqe->user_data, req->user_data);
1047 WRITE_ONCE(cqe->res, req->result);
1048 WRITE_ONCE(cqe->flags, 0);
1050 WRITE_ONCE(ctx->rings->cq_overflow,
1051 atomic_inc_return(&ctx->cached_cq_overflow));
1055 io_commit_cqring(ctx);
1057 clear_bit(0, &ctx->sq_check_overflow);
1058 clear_bit(0, &ctx->cq_check_overflow);
1060 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1061 io_cqring_ev_posted(ctx);
1063 while (!list_empty(&list)) {
1064 req = list_first_entry(&list, struct io_kiocb, list);
1065 list_del(&req->list);
1072 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1074 struct io_ring_ctx *ctx = req->ctx;
1075 struct io_uring_cqe *cqe;
1077 trace_io_uring_complete(ctx, req->user_data, res);
1080 * If we can't get a cq entry, userspace overflowed the
1081 * submission (by quite a lot). Increment the overflow count in
1084 cqe = io_get_cqring(ctx);
1086 WRITE_ONCE(cqe->user_data, req->user_data);
1087 WRITE_ONCE(cqe->res, res);
1088 WRITE_ONCE(cqe->flags, 0);
1089 } else if (ctx->cq_overflow_flushed) {
1090 WRITE_ONCE(ctx->rings->cq_overflow,
1091 atomic_inc_return(&ctx->cached_cq_overflow));
1093 if (list_empty(&ctx->cq_overflow_list)) {
1094 set_bit(0, &ctx->sq_check_overflow);
1095 set_bit(0, &ctx->cq_check_overflow);
1097 refcount_inc(&req->refs);
1099 list_add_tail(&req->list, &ctx->cq_overflow_list);
1103 static void io_cqring_add_event(struct io_kiocb *req, long res)
1105 struct io_ring_ctx *ctx = req->ctx;
1106 unsigned long flags;
1108 spin_lock_irqsave(&ctx->completion_lock, flags);
1109 io_cqring_fill_event(req, res);
1110 io_commit_cqring(ctx);
1111 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1113 io_cqring_ev_posted(ctx);
1116 static inline bool io_is_fallback_req(struct io_kiocb *req)
1118 return req == (struct io_kiocb *)
1119 ((unsigned long) req->ctx->fallback_req & ~1UL);
1122 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1124 struct io_kiocb *req;
1126 req = ctx->fallback_req;
1127 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1133 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1134 struct io_submit_state *state)
1136 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1137 struct io_kiocb *req;
1140 req = kmem_cache_alloc(req_cachep, gfp);
1143 } else if (!state->free_reqs) {
1147 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1148 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1151 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1152 * retry single alloc to be on the safe side.
1154 if (unlikely(ret <= 0)) {
1155 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1156 if (!state->reqs[0])
1160 state->free_reqs = ret - 1;
1162 req = state->reqs[0];
1164 req = state->reqs[state->cur_req];
1174 /* one is dropped after submission, the other at completion */
1175 refcount_set(&req->refs, 2);
1177 INIT_IO_WORK(&req->work, io_wq_submit_work);
1180 req = io_get_fallback_req(ctx);
1183 percpu_ref_put(&ctx->refs);
1187 static void __io_req_do_free(struct io_kiocb *req)
1189 if (likely(!io_is_fallback_req(req)))
1190 kmem_cache_free(req_cachep, req);
1192 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1195 static void __io_req_aux_free(struct io_kiocb *req)
1197 struct io_ring_ctx *ctx = req->ctx;
1201 if (req->flags & REQ_F_FIXED_FILE)
1202 percpu_ref_put(&ctx->file_data->refs);
1207 io_req_work_drop_env(req);
1210 static void __io_free_req(struct io_kiocb *req)
1212 __io_req_aux_free(req);
1214 if (req->flags & REQ_F_INFLIGHT) {
1215 struct io_ring_ctx *ctx = req->ctx;
1216 unsigned long flags;
1218 spin_lock_irqsave(&ctx->inflight_lock, flags);
1219 list_del(&req->inflight_entry);
1220 if (waitqueue_active(&ctx->inflight_wait))
1221 wake_up(&ctx->inflight_wait);
1222 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1225 percpu_ref_put(&req->ctx->refs);
1226 __io_req_do_free(req);
1230 void *reqs[IO_IOPOLL_BATCH];
1235 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1237 int fixed_refs = rb->to_free;
1241 if (rb->need_iter) {
1242 int i, inflight = 0;
1243 unsigned long flags;
1246 for (i = 0; i < rb->to_free; i++) {
1247 struct io_kiocb *req = rb->reqs[i];
1249 if (req->flags & REQ_F_FIXED_FILE) {
1253 if (req->flags & REQ_F_INFLIGHT)
1255 __io_req_aux_free(req);
1260 spin_lock_irqsave(&ctx->inflight_lock, flags);
1261 for (i = 0; i < rb->to_free; i++) {
1262 struct io_kiocb *req = rb->reqs[i];
1264 if (req->flags & REQ_F_INFLIGHT) {
1265 list_del(&req->inflight_entry);
1270 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1272 if (waitqueue_active(&ctx->inflight_wait))
1273 wake_up(&ctx->inflight_wait);
1276 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1278 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1279 percpu_ref_put_many(&ctx->refs, rb->to_free);
1280 rb->to_free = rb->need_iter = 0;
1283 static bool io_link_cancel_timeout(struct io_kiocb *req)
1285 struct io_ring_ctx *ctx = req->ctx;
1288 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1290 io_cqring_fill_event(req, -ECANCELED);
1291 io_commit_cqring(ctx);
1292 req->flags &= ~REQ_F_LINK;
1300 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1302 struct io_ring_ctx *ctx = req->ctx;
1303 bool wake_ev = false;
1305 /* Already got next link */
1306 if (req->flags & REQ_F_LINK_NEXT)
1310 * The list should never be empty when we are called here. But could
1311 * potentially happen if the chain is messed up, check to be on the
1314 while (!list_empty(&req->link_list)) {
1315 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1316 struct io_kiocb, link_list);
1318 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1319 (nxt->flags & REQ_F_TIMEOUT))) {
1320 list_del_init(&nxt->link_list);
1321 wake_ev |= io_link_cancel_timeout(nxt);
1322 req->flags &= ~REQ_F_LINK_TIMEOUT;
1326 list_del_init(&req->link_list);
1327 if (!list_empty(&nxt->link_list))
1328 nxt->flags |= REQ_F_LINK;
1333 req->flags |= REQ_F_LINK_NEXT;
1335 io_cqring_ev_posted(ctx);
1339 * Called if REQ_F_LINK is set, and we fail the head request
1341 static void io_fail_links(struct io_kiocb *req)
1343 struct io_ring_ctx *ctx = req->ctx;
1344 unsigned long flags;
1346 spin_lock_irqsave(&ctx->completion_lock, flags);
1348 while (!list_empty(&req->link_list)) {
1349 struct io_kiocb *link = list_first_entry(&req->link_list,
1350 struct io_kiocb, link_list);
1352 list_del_init(&link->link_list);
1353 trace_io_uring_fail_link(req, link);
1355 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1356 link->opcode == IORING_OP_LINK_TIMEOUT) {
1357 io_link_cancel_timeout(link);
1359 io_cqring_fill_event(link, -ECANCELED);
1360 __io_double_put_req(link);
1362 req->flags &= ~REQ_F_LINK_TIMEOUT;
1365 io_commit_cqring(ctx);
1366 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1367 io_cqring_ev_posted(ctx);
1370 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1372 if (likely(!(req->flags & REQ_F_LINK)))
1376 * If LINK is set, we have dependent requests in this chain. If we
1377 * didn't fail this request, queue the first one up, moving any other
1378 * dependencies to the next request. In case of failure, fail the rest
1381 if (req->flags & REQ_F_FAIL_LINK) {
1383 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1384 REQ_F_LINK_TIMEOUT) {
1385 struct io_ring_ctx *ctx = req->ctx;
1386 unsigned long flags;
1389 * If this is a timeout link, we could be racing with the
1390 * timeout timer. Grab the completion lock for this case to
1391 * protect against that.
1393 spin_lock_irqsave(&ctx->completion_lock, flags);
1394 io_req_link_next(req, nxt);
1395 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1397 io_req_link_next(req, nxt);
1401 static void io_free_req(struct io_kiocb *req)
1403 struct io_kiocb *nxt = NULL;
1405 io_req_find_next(req, &nxt);
1409 io_queue_async_work(nxt);
1413 * Drop reference to request, return next in chain (if there is one) if this
1414 * was the last reference to this request.
1416 __attribute__((nonnull))
1417 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1419 io_req_find_next(req, nxtptr);
1421 if (refcount_dec_and_test(&req->refs))
1425 static void io_put_req(struct io_kiocb *req)
1427 if (refcount_dec_and_test(&req->refs))
1432 * Must only be used if we don't need to care about links, usually from
1433 * within the completion handling itself.
1435 static void __io_double_put_req(struct io_kiocb *req)
1437 /* drop both submit and complete references */
1438 if (refcount_sub_and_test(2, &req->refs))
1442 static void io_double_put_req(struct io_kiocb *req)
1444 /* drop both submit and complete references */
1445 if (refcount_sub_and_test(2, &req->refs))
1449 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1451 struct io_rings *rings = ctx->rings;
1453 if (test_bit(0, &ctx->cq_check_overflow)) {
1455 * noflush == true is from the waitqueue handler, just ensure
1456 * we wake up the task, and the next invocation will flush the
1457 * entries. We cannot safely to it from here.
1459 if (noflush && !list_empty(&ctx->cq_overflow_list))
1462 io_cqring_overflow_flush(ctx, false);
1465 /* See comment at the top of this file */
1467 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1470 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1472 struct io_rings *rings = ctx->rings;
1474 /* make sure SQ entry isn't read before tail */
1475 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1478 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1480 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1483 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1486 rb->reqs[rb->to_free++] = req;
1487 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1488 io_free_req_many(req->ctx, rb);
1493 * Find and free completed poll iocbs
1495 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1496 struct list_head *done)
1498 struct req_batch rb;
1499 struct io_kiocb *req;
1501 rb.to_free = rb.need_iter = 0;
1502 while (!list_empty(done)) {
1503 req = list_first_entry(done, struct io_kiocb, list);
1504 list_del(&req->list);
1506 io_cqring_fill_event(req, req->result);
1509 if (refcount_dec_and_test(&req->refs) &&
1510 !io_req_multi_free(&rb, req))
1514 io_commit_cqring(ctx);
1515 io_free_req_many(ctx, &rb);
1518 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1521 struct io_kiocb *req, *tmp;
1527 * Only spin for completions if we don't have multiple devices hanging
1528 * off our complete list, and we're under the requested amount.
1530 spin = !ctx->poll_multi_file && *nr_events < min;
1533 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1534 struct kiocb *kiocb = &req->rw.kiocb;
1537 * Move completed entries to our local list. If we find a
1538 * request that requires polling, break out and complete
1539 * the done list first, if we have entries there.
1541 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1542 list_move_tail(&req->list, &done);
1545 if (!list_empty(&done))
1548 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1557 if (!list_empty(&done))
1558 io_iopoll_complete(ctx, nr_events, &done);
1564 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1565 * non-spinning poll check - we'll still enter the driver poll loop, but only
1566 * as a non-spinning completion check.
1568 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1571 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1574 ret = io_do_iopoll(ctx, nr_events, min);
1577 if (!min || *nr_events >= min)
1585 * We can't just wait for polled events to come to us, we have to actively
1586 * find and complete them.
1588 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1590 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1593 mutex_lock(&ctx->uring_lock);
1594 while (!list_empty(&ctx->poll_list)) {
1595 unsigned int nr_events = 0;
1597 io_iopoll_getevents(ctx, &nr_events, 1);
1600 * Ensure we allow local-to-the-cpu processing to take place,
1601 * in this case we need to ensure that we reap all events.
1605 mutex_unlock(&ctx->uring_lock);
1608 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1611 int iters = 0, ret = 0;
1617 * Don't enter poll loop if we already have events pending.
1618 * If we do, we can potentially be spinning for commands that
1619 * already triggered a CQE (eg in error).
1621 if (io_cqring_events(ctx, false))
1625 * If a submit got punted to a workqueue, we can have the
1626 * application entering polling for a command before it gets
1627 * issued. That app will hold the uring_lock for the duration
1628 * of the poll right here, so we need to take a breather every
1629 * now and then to ensure that the issue has a chance to add
1630 * the poll to the issued list. Otherwise we can spin here
1631 * forever, while the workqueue is stuck trying to acquire the
1634 if (!(++iters & 7)) {
1635 mutex_unlock(&ctx->uring_lock);
1636 mutex_lock(&ctx->uring_lock);
1639 if (*nr_events < min)
1640 tmin = min - *nr_events;
1642 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1646 } while (min && !*nr_events && !need_resched());
1651 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1657 * We disallow the app entering submit/complete with polling, but we
1658 * still need to lock the ring to prevent racing with polled issue
1659 * that got punted to a workqueue.
1661 mutex_lock(&ctx->uring_lock);
1662 ret = __io_iopoll_check(ctx, nr_events, min);
1663 mutex_unlock(&ctx->uring_lock);
1667 static void kiocb_end_write(struct io_kiocb *req)
1670 * Tell lockdep we inherited freeze protection from submission
1673 if (req->flags & REQ_F_ISREG) {
1674 struct inode *inode = file_inode(req->file);
1676 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1678 file_end_write(req->file);
1681 static inline void req_set_fail_links(struct io_kiocb *req)
1683 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1684 req->flags |= REQ_F_FAIL_LINK;
1687 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1689 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1691 if (kiocb->ki_flags & IOCB_WRITE)
1692 kiocb_end_write(req);
1694 if (res != req->result)
1695 req_set_fail_links(req);
1696 io_cqring_add_event(req, res);
1699 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1701 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1703 io_complete_rw_common(kiocb, res);
1707 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1709 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1710 struct io_kiocb *nxt = NULL;
1712 io_complete_rw_common(kiocb, res);
1713 io_put_req_find_next(req, &nxt);
1718 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1720 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1722 if (kiocb->ki_flags & IOCB_WRITE)
1723 kiocb_end_write(req);
1725 if (res != req->result)
1726 req_set_fail_links(req);
1729 req->flags |= REQ_F_IOPOLL_COMPLETED;
1733 * After the iocb has been issued, it's safe to be found on the poll list.
1734 * Adding the kiocb to the list AFTER submission ensures that we don't
1735 * find it from a io_iopoll_getevents() thread before the issuer is done
1736 * accessing the kiocb cookie.
1738 static void io_iopoll_req_issued(struct io_kiocb *req)
1740 struct io_ring_ctx *ctx = req->ctx;
1743 * Track whether we have multiple files in our lists. This will impact
1744 * how we do polling eventually, not spinning if we're on potentially
1745 * different devices.
1747 if (list_empty(&ctx->poll_list)) {
1748 ctx->poll_multi_file = false;
1749 } else if (!ctx->poll_multi_file) {
1750 struct io_kiocb *list_req;
1752 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1754 if (list_req->file != req->file)
1755 ctx->poll_multi_file = true;
1759 * For fast devices, IO may have already completed. If it has, add
1760 * it to the front so we find it first.
1762 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1763 list_add(&req->list, &ctx->poll_list);
1765 list_add_tail(&req->list, &ctx->poll_list);
1768 static void io_file_put(struct io_submit_state *state)
1771 int diff = state->has_refs - state->used_refs;
1774 fput_many(state->file, diff);
1780 * Get as many references to a file as we have IOs left in this submission,
1781 * assuming most submissions are for one file, or at least that each file
1782 * has more than one submission.
1784 static struct file *io_file_get(struct io_submit_state *state, int fd)
1790 if (state->fd == fd) {
1797 state->file = fget_many(fd, state->ios_left);
1802 state->has_refs = state->ios_left;
1803 state->used_refs = 1;
1809 * If we tracked the file through the SCM inflight mechanism, we could support
1810 * any file. For now, just ensure that anything potentially problematic is done
1813 static bool io_file_supports_async(struct file *file)
1815 umode_t mode = file_inode(file)->i_mode;
1817 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1819 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1825 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1826 bool force_nonblock)
1828 struct io_ring_ctx *ctx = req->ctx;
1829 struct kiocb *kiocb = &req->rw.kiocb;
1836 if (S_ISREG(file_inode(req->file)->i_mode))
1837 req->flags |= REQ_F_ISREG;
1839 kiocb->ki_pos = READ_ONCE(sqe->off);
1840 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1841 req->flags |= REQ_F_CUR_POS;
1842 kiocb->ki_pos = req->file->f_pos;
1844 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1845 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1847 ioprio = READ_ONCE(sqe->ioprio);
1849 ret = ioprio_check_cap(ioprio);
1853 kiocb->ki_ioprio = ioprio;
1855 kiocb->ki_ioprio = get_current_ioprio();
1857 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1861 /* don't allow async punt if RWF_NOWAIT was requested */
1862 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1863 (req->file->f_flags & O_NONBLOCK))
1864 req->flags |= REQ_F_NOWAIT;
1867 kiocb->ki_flags |= IOCB_NOWAIT;
1869 if (ctx->flags & IORING_SETUP_IOPOLL) {
1870 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1871 !kiocb->ki_filp->f_op->iopoll)
1874 kiocb->ki_flags |= IOCB_HIPRI;
1875 kiocb->ki_complete = io_complete_rw_iopoll;
1878 if (kiocb->ki_flags & IOCB_HIPRI)
1880 kiocb->ki_complete = io_complete_rw;
1883 req->rw.addr = READ_ONCE(sqe->addr);
1884 req->rw.len = READ_ONCE(sqe->len);
1885 /* we own ->private, reuse it for the buffer index */
1886 req->rw.kiocb.private = (void *) (unsigned long)
1887 READ_ONCE(sqe->buf_index);
1891 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1897 case -ERESTARTNOINTR:
1898 case -ERESTARTNOHAND:
1899 case -ERESTART_RESTARTBLOCK:
1901 * We can't just restart the syscall, since previously
1902 * submitted sqes may already be in progress. Just fail this
1908 kiocb->ki_complete(kiocb, ret, 0);
1912 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1915 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1917 if (req->flags & REQ_F_CUR_POS)
1918 req->file->f_pos = kiocb->ki_pos;
1919 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1920 *nxt = __io_complete_rw(kiocb, ret);
1922 io_rw_done(kiocb, ret);
1925 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1926 struct iov_iter *iter)
1928 struct io_ring_ctx *ctx = req->ctx;
1929 size_t len = req->rw.len;
1930 struct io_mapped_ubuf *imu;
1931 unsigned index, buf_index;
1935 /* attempt to use fixed buffers without having provided iovecs */
1936 if (unlikely(!ctx->user_bufs))
1939 buf_index = (unsigned long) req->rw.kiocb.private;
1940 if (unlikely(buf_index >= ctx->nr_user_bufs))
1943 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1944 imu = &ctx->user_bufs[index];
1945 buf_addr = req->rw.addr;
1948 if (buf_addr + len < buf_addr)
1950 /* not inside the mapped region */
1951 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1955 * May not be a start of buffer, set size appropriately
1956 * and advance us to the beginning.
1958 offset = buf_addr - imu->ubuf;
1959 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1963 * Don't use iov_iter_advance() here, as it's really slow for
1964 * using the latter parts of a big fixed buffer - it iterates
1965 * over each segment manually. We can cheat a bit here, because
1968 * 1) it's a BVEC iter, we set it up
1969 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1970 * first and last bvec
1972 * So just find our index, and adjust the iterator afterwards.
1973 * If the offset is within the first bvec (or the whole first
1974 * bvec, just use iov_iter_advance(). This makes it easier
1975 * since we can just skip the first segment, which may not
1976 * be PAGE_SIZE aligned.
1978 const struct bio_vec *bvec = imu->bvec;
1980 if (offset <= bvec->bv_len) {
1981 iov_iter_advance(iter, offset);
1983 unsigned long seg_skip;
1985 /* skip first vec */
1986 offset -= bvec->bv_len;
1987 seg_skip = 1 + (offset >> PAGE_SHIFT);
1989 iter->bvec = bvec + seg_skip;
1990 iter->nr_segs -= seg_skip;
1991 iter->count -= bvec->bv_len + offset;
1992 iter->iov_offset = offset & ~PAGE_MASK;
1999 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2000 struct iovec **iovec, struct iov_iter *iter)
2002 void __user *buf = u64_to_user_ptr(req->rw.addr);
2003 size_t sqe_len = req->rw.len;
2006 opcode = req->opcode;
2007 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2009 return io_import_fixed(req, rw, iter);
2012 /* buffer index only valid with fixed read/write */
2013 if (req->rw.kiocb.private)
2016 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2018 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2024 struct io_async_rw *iorw = &req->io->rw;
2027 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2028 if (iorw->iov == iorw->fast_iov)
2036 #ifdef CONFIG_COMPAT
2037 if (req->ctx->compat)
2038 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2042 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2046 * For files that don't have ->read_iter() and ->write_iter(), handle them
2047 * by looping over ->read() or ->write() manually.
2049 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2050 struct iov_iter *iter)
2055 * Don't support polled IO through this interface, and we can't
2056 * support non-blocking either. For the latter, this just causes
2057 * the kiocb to be handled from an async context.
2059 if (kiocb->ki_flags & IOCB_HIPRI)
2061 if (kiocb->ki_flags & IOCB_NOWAIT)
2064 while (iov_iter_count(iter)) {
2068 if (!iov_iter_is_bvec(iter)) {
2069 iovec = iov_iter_iovec(iter);
2071 /* fixed buffers import bvec */
2072 iovec.iov_base = kmap(iter->bvec->bv_page)
2074 iovec.iov_len = min(iter->count,
2075 iter->bvec->bv_len - iter->iov_offset);
2079 nr = file->f_op->read(file, iovec.iov_base,
2080 iovec.iov_len, &kiocb->ki_pos);
2082 nr = file->f_op->write(file, iovec.iov_base,
2083 iovec.iov_len, &kiocb->ki_pos);
2086 if (iov_iter_is_bvec(iter))
2087 kunmap(iter->bvec->bv_page);
2095 if (nr != iovec.iov_len)
2097 iov_iter_advance(iter, nr);
2103 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2104 struct iovec *iovec, struct iovec *fast_iov,
2105 struct iov_iter *iter)
2107 req->io->rw.nr_segs = iter->nr_segs;
2108 req->io->rw.size = io_size;
2109 req->io->rw.iov = iovec;
2110 if (!req->io->rw.iov) {
2111 req->io->rw.iov = req->io->rw.fast_iov;
2112 memcpy(req->io->rw.iov, fast_iov,
2113 sizeof(struct iovec) * iter->nr_segs);
2117 static int io_alloc_async_ctx(struct io_kiocb *req)
2119 if (!io_op_defs[req->opcode].async_ctx)
2121 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2122 return req->io == NULL;
2125 static void io_rw_async(struct io_wq_work **workptr)
2127 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2128 struct iovec *iov = NULL;
2130 if (req->io->rw.iov != req->io->rw.fast_iov)
2131 iov = req->io->rw.iov;
2132 io_wq_submit_work(workptr);
2136 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2137 struct iovec *iovec, struct iovec *fast_iov,
2138 struct iov_iter *iter)
2140 if (!io_op_defs[req->opcode].async_ctx)
2142 if (!req->io && io_alloc_async_ctx(req))
2145 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2146 req->work.func = io_rw_async;
2150 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2151 bool force_nonblock)
2153 struct io_async_ctx *io;
2154 struct iov_iter iter;
2157 ret = io_prep_rw(req, sqe, force_nonblock);
2161 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2168 io->rw.iov = io->rw.fast_iov;
2170 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2175 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2179 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2180 bool force_nonblock)
2182 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2183 struct kiocb *kiocb = &req->rw.kiocb;
2184 struct iov_iter iter;
2186 ssize_t io_size, ret;
2188 ret = io_import_iovec(READ, req, &iovec, &iter);
2192 /* Ensure we clear previously set non-block flag */
2193 if (!force_nonblock)
2194 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2198 if (req->flags & REQ_F_LINK)
2199 req->result = io_size;
2202 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2203 * we know to async punt it even if it was opened O_NONBLOCK
2205 if (force_nonblock && !io_file_supports_async(req->file)) {
2206 req->flags |= REQ_F_MUST_PUNT;
2210 iov_count = iov_iter_count(&iter);
2211 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2215 if (req->file->f_op->read_iter)
2216 ret2 = call_read_iter(req->file, kiocb, &iter);
2218 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2220 /* Catch -EAGAIN return for forced non-blocking submission */
2221 if (!force_nonblock || ret2 != -EAGAIN) {
2222 kiocb_done(kiocb, ret2, nxt, req->in_async);
2225 ret = io_setup_async_rw(req, io_size, iovec,
2226 inline_vecs, &iter);
2233 if (!io_wq_current_is_worker())
2238 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2239 bool force_nonblock)
2241 struct io_async_ctx *io;
2242 struct iov_iter iter;
2245 ret = io_prep_rw(req, sqe, force_nonblock);
2249 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2256 io->rw.iov = io->rw.fast_iov;
2258 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2263 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2267 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2268 bool force_nonblock)
2270 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2271 struct kiocb *kiocb = &req->rw.kiocb;
2272 struct iov_iter iter;
2274 ssize_t ret, io_size;
2276 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2280 /* Ensure we clear previously set non-block flag */
2281 if (!force_nonblock)
2282 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2286 if (req->flags & REQ_F_LINK)
2287 req->result = io_size;
2290 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2291 * we know to async punt it even if it was opened O_NONBLOCK
2293 if (force_nonblock && !io_file_supports_async(req->file)) {
2294 req->flags |= REQ_F_MUST_PUNT;
2298 /* file path doesn't support NOWAIT for non-direct_IO */
2299 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2300 (req->flags & REQ_F_ISREG))
2303 iov_count = iov_iter_count(&iter);
2304 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2309 * Open-code file_start_write here to grab freeze protection,
2310 * which will be released by another thread in
2311 * io_complete_rw(). Fool lockdep by telling it the lock got
2312 * released so that it doesn't complain about the held lock when
2313 * we return to userspace.
2315 if (req->flags & REQ_F_ISREG) {
2316 __sb_start_write(file_inode(req->file)->i_sb,
2317 SB_FREEZE_WRITE, true);
2318 __sb_writers_release(file_inode(req->file)->i_sb,
2321 kiocb->ki_flags |= IOCB_WRITE;
2323 if (req->file->f_op->write_iter)
2324 ret2 = call_write_iter(req->file, kiocb, &iter);
2326 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2327 if (!force_nonblock || ret2 != -EAGAIN) {
2328 kiocb_done(kiocb, ret2, nxt, req->in_async);
2331 ret = io_setup_async_rw(req, io_size, iovec,
2332 inline_vecs, &iter);
2339 if (!io_wq_current_is_worker())
2345 * IORING_OP_NOP just posts a completion event, nothing else.
2347 static int io_nop(struct io_kiocb *req)
2349 struct io_ring_ctx *ctx = req->ctx;
2351 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2354 io_cqring_add_event(req, 0);
2359 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2361 struct io_ring_ctx *ctx = req->ctx;
2366 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2368 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2371 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2372 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2375 req->sync.off = READ_ONCE(sqe->off);
2376 req->sync.len = READ_ONCE(sqe->len);
2380 static bool io_req_cancelled(struct io_kiocb *req)
2382 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2383 req_set_fail_links(req);
2384 io_cqring_add_event(req, -ECANCELED);
2392 static void io_link_work_cb(struct io_wq_work **workptr)
2394 struct io_wq_work *work = *workptr;
2395 struct io_kiocb *link = work->data;
2397 io_queue_linked_timeout(link);
2398 work->func = io_wq_submit_work;
2401 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2403 struct io_kiocb *link;
2405 io_prep_async_work(nxt, &link);
2406 *workptr = &nxt->work;
2408 nxt->work.flags |= IO_WQ_WORK_CB;
2409 nxt->work.func = io_link_work_cb;
2410 nxt->work.data = link;
2414 static void io_fsync_finish(struct io_wq_work **workptr)
2416 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2417 loff_t end = req->sync.off + req->sync.len;
2418 struct io_kiocb *nxt = NULL;
2421 if (io_req_cancelled(req))
2424 ret = vfs_fsync_range(req->file, req->sync.off,
2425 end > 0 ? end : LLONG_MAX,
2426 req->sync.flags & IORING_FSYNC_DATASYNC);
2428 req_set_fail_links(req);
2429 io_cqring_add_event(req, ret);
2430 io_put_req_find_next(req, &nxt);
2432 io_wq_assign_next(workptr, nxt);
2435 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2436 bool force_nonblock)
2438 struct io_wq_work *work, *old_work;
2440 /* fsync always requires a blocking context */
2441 if (force_nonblock) {
2443 req->work.func = io_fsync_finish;
2447 work = old_work = &req->work;
2448 io_fsync_finish(&work);
2449 if (work && work != old_work)
2450 *nxt = container_of(work, struct io_kiocb, work);
2454 static void io_fallocate_finish(struct io_wq_work **workptr)
2456 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2457 struct io_kiocb *nxt = NULL;
2460 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2463 req_set_fail_links(req);
2464 io_cqring_add_event(req, ret);
2465 io_put_req_find_next(req, &nxt);
2467 io_wq_assign_next(workptr, nxt);
2470 static int io_fallocate_prep(struct io_kiocb *req,
2471 const struct io_uring_sqe *sqe)
2473 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2476 req->sync.off = READ_ONCE(sqe->off);
2477 req->sync.len = READ_ONCE(sqe->addr);
2478 req->sync.mode = READ_ONCE(sqe->len);
2482 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2483 bool force_nonblock)
2485 struct io_wq_work *work, *old_work;
2487 /* fallocate always requiring blocking context */
2488 if (force_nonblock) {
2490 req->work.func = io_fallocate_finish;
2494 work = old_work = &req->work;
2495 io_fallocate_finish(&work);
2496 if (work && work != old_work)
2497 *nxt = container_of(work, struct io_kiocb, work);
2502 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2504 const char __user *fname;
2507 if (sqe->ioprio || sqe->buf_index)
2510 req->open.dfd = READ_ONCE(sqe->fd);
2511 req->open.how.mode = READ_ONCE(sqe->len);
2512 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2513 req->open.how.flags = READ_ONCE(sqe->open_flags);
2515 req->open.filename = getname(fname);
2516 if (IS_ERR(req->open.filename)) {
2517 ret = PTR_ERR(req->open.filename);
2518 req->open.filename = NULL;
2525 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2527 struct open_how __user *how;
2528 const char __user *fname;
2532 if (sqe->ioprio || sqe->buf_index)
2535 req->open.dfd = READ_ONCE(sqe->fd);
2536 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2537 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2538 len = READ_ONCE(sqe->len);
2540 if (len < OPEN_HOW_SIZE_VER0)
2543 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2548 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2549 req->open.how.flags |= O_LARGEFILE;
2551 req->open.filename = getname(fname);
2552 if (IS_ERR(req->open.filename)) {
2553 ret = PTR_ERR(req->open.filename);
2554 req->open.filename = NULL;
2561 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2562 bool force_nonblock)
2564 struct open_flags op;
2568 if (force_nonblock) {
2569 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2573 ret = build_open_flags(&req->open.how, &op);
2577 ret = get_unused_fd_flags(req->open.how.flags);
2581 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2584 ret = PTR_ERR(file);
2586 fsnotify_open(file);
2587 fd_install(ret, file);
2590 putname(req->open.filename);
2592 req_set_fail_links(req);
2593 io_cqring_add_event(req, ret);
2594 io_put_req_find_next(req, nxt);
2598 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2599 bool force_nonblock)
2601 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2602 return io_openat2(req, nxt, force_nonblock);
2605 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2607 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2608 if (sqe->ioprio || sqe->buf_index || sqe->off)
2611 req->madvise.addr = READ_ONCE(sqe->addr);
2612 req->madvise.len = READ_ONCE(sqe->len);
2613 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2620 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2621 bool force_nonblock)
2623 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2624 struct io_madvise *ma = &req->madvise;
2630 ret = do_madvise(ma->addr, ma->len, ma->advice);
2632 req_set_fail_links(req);
2633 io_cqring_add_event(req, ret);
2634 io_put_req_find_next(req, nxt);
2641 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2643 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2646 req->fadvise.offset = READ_ONCE(sqe->off);
2647 req->fadvise.len = READ_ONCE(sqe->len);
2648 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2652 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2653 bool force_nonblock)
2655 struct io_fadvise *fa = &req->fadvise;
2658 /* DONTNEED may block, others _should_ not */
2659 if (fa->advice == POSIX_FADV_DONTNEED && force_nonblock)
2662 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2664 req_set_fail_links(req);
2665 io_cqring_add_event(req, ret);
2666 io_put_req_find_next(req, nxt);
2670 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2672 const char __user *fname;
2673 unsigned lookup_flags;
2676 if (sqe->ioprio || sqe->buf_index)
2679 req->open.dfd = READ_ONCE(sqe->fd);
2680 req->open.mask = READ_ONCE(sqe->len);
2681 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2682 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2683 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2685 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2688 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2689 if (IS_ERR(req->open.filename)) {
2690 ret = PTR_ERR(req->open.filename);
2691 req->open.filename = NULL;
2698 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2699 bool force_nonblock)
2701 struct io_open *ctx = &req->open;
2702 unsigned lookup_flags;
2710 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2714 /* filename_lookup() drops it, keep a reference */
2715 ctx->filename->refcnt++;
2717 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2722 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2724 if (retry_estale(ret, lookup_flags)) {
2725 lookup_flags |= LOOKUP_REVAL;
2729 ret = cp_statx(&stat, ctx->buffer);
2731 putname(ctx->filename);
2733 req_set_fail_links(req);
2734 io_cqring_add_event(req, ret);
2735 io_put_req_find_next(req, nxt);
2739 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2742 * If we queue this for async, it must not be cancellable. That would
2743 * leave the 'file' in an undeterminate state.
2745 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2747 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2748 sqe->rw_flags || sqe->buf_index)
2750 if (sqe->flags & IOSQE_FIXED_FILE)
2753 req->close.fd = READ_ONCE(sqe->fd);
2754 if (req->file->f_op == &io_uring_fops ||
2755 req->close.fd == req->ctx->ring_fd)
2761 static void io_close_finish(struct io_wq_work **workptr)
2763 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2764 struct io_kiocb *nxt = NULL;
2766 /* Invoked with files, we need to do the close */
2767 if (req->work.files) {
2770 ret = filp_close(req->close.put_file, req->work.files);
2772 req_set_fail_links(req);
2774 io_cqring_add_event(req, ret);
2777 fput(req->close.put_file);
2779 /* we bypassed the re-issue, drop the submission reference */
2781 io_put_req_find_next(req, &nxt);
2783 io_wq_assign_next(workptr, nxt);
2786 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2787 bool force_nonblock)
2791 req->close.put_file = NULL;
2792 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2796 /* if the file has a flush method, be safe and punt to async */
2797 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker()) {
2798 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2803 * No ->flush(), safely close from here and just punt the
2804 * fput() to async context.
2806 ret = filp_close(req->close.put_file, current->files);
2809 req_set_fail_links(req);
2810 io_cqring_add_event(req, ret);
2812 if (io_wq_current_is_worker()) {
2813 struct io_wq_work *old_work, *work;
2815 old_work = work = &req->work;
2816 io_close_finish(&work);
2817 if (work && work != old_work)
2818 *nxt = container_of(work, struct io_kiocb, work);
2823 req->work.func = io_close_finish;
2827 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2829 struct io_ring_ctx *ctx = req->ctx;
2834 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2836 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2839 req->sync.off = READ_ONCE(sqe->off);
2840 req->sync.len = READ_ONCE(sqe->len);
2841 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2845 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2847 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2848 struct io_kiocb *nxt = NULL;
2851 if (io_req_cancelled(req))
2854 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2857 req_set_fail_links(req);
2858 io_cqring_add_event(req, ret);
2859 io_put_req_find_next(req, &nxt);
2861 io_wq_assign_next(workptr, nxt);
2864 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2865 bool force_nonblock)
2867 struct io_wq_work *work, *old_work;
2869 /* sync_file_range always requires a blocking context */
2870 if (force_nonblock) {
2872 req->work.func = io_sync_file_range_finish;
2876 work = old_work = &req->work;
2877 io_sync_file_range_finish(&work);
2878 if (work && work != old_work)
2879 *nxt = container_of(work, struct io_kiocb, work);
2883 #if defined(CONFIG_NET)
2884 static void io_sendrecv_async(struct io_wq_work **workptr)
2886 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2887 struct iovec *iov = NULL;
2889 if (req->io->rw.iov != req->io->rw.fast_iov)
2890 iov = req->io->msg.iov;
2891 io_wq_submit_work(workptr);
2896 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2898 #if defined(CONFIG_NET)
2899 struct io_sr_msg *sr = &req->sr_msg;
2900 struct io_async_ctx *io = req->io;
2902 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2903 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2904 sr->len = READ_ONCE(sqe->len);
2906 if (!io || req->opcode == IORING_OP_SEND)
2909 io->msg.iov = io->msg.fast_iov;
2910 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2917 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2918 bool force_nonblock)
2920 #if defined(CONFIG_NET)
2921 struct io_async_msghdr *kmsg = NULL;
2922 struct socket *sock;
2925 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2928 sock = sock_from_file(req->file, &ret);
2930 struct io_async_ctx io;
2931 struct sockaddr_storage addr;
2935 kmsg = &req->io->msg;
2936 kmsg->msg.msg_name = &addr;
2937 /* if iov is set, it's allocated already */
2939 kmsg->iov = kmsg->fast_iov;
2940 kmsg->msg.msg_iter.iov = kmsg->iov;
2942 struct io_sr_msg *sr = &req->sr_msg;
2945 kmsg->msg.msg_name = &addr;
2947 io.msg.iov = io.msg.fast_iov;
2948 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2949 sr->msg_flags, &io.msg.iov);
2954 flags = req->sr_msg.msg_flags;
2955 if (flags & MSG_DONTWAIT)
2956 req->flags |= REQ_F_NOWAIT;
2957 else if (force_nonblock)
2958 flags |= MSG_DONTWAIT;
2960 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2961 if (force_nonblock && ret == -EAGAIN) {
2964 if (io_alloc_async_ctx(req))
2966 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2967 req->work.func = io_sendrecv_async;
2970 if (ret == -ERESTARTSYS)
2974 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2976 io_cqring_add_event(req, ret);
2978 req_set_fail_links(req);
2979 io_put_req_find_next(req, nxt);
2986 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
2987 bool force_nonblock)
2989 #if defined(CONFIG_NET)
2990 struct socket *sock;
2993 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2996 sock = sock_from_file(req->file, &ret);
2998 struct io_sr_msg *sr = &req->sr_msg;
3003 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3008 msg.msg_name = NULL;
3009 msg.msg_control = NULL;
3010 msg.msg_controllen = 0;
3011 msg.msg_namelen = 0;
3013 flags = req->sr_msg.msg_flags;
3014 if (flags & MSG_DONTWAIT)
3015 req->flags |= REQ_F_NOWAIT;
3016 else if (force_nonblock)
3017 flags |= MSG_DONTWAIT;
3019 ret = __sys_sendmsg_sock(sock, &msg, flags);
3020 if (force_nonblock && ret == -EAGAIN)
3022 if (ret == -ERESTARTSYS)
3026 io_cqring_add_event(req, ret);
3028 req_set_fail_links(req);
3029 io_put_req_find_next(req, nxt);
3036 static int io_recvmsg_prep(struct io_kiocb *req,
3037 const struct io_uring_sqe *sqe)
3039 #if defined(CONFIG_NET)
3040 struct io_sr_msg *sr = &req->sr_msg;
3041 struct io_async_ctx *io = req->io;
3043 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3044 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3046 if (!io || req->opcode == IORING_OP_RECV)
3049 io->msg.iov = io->msg.fast_iov;
3050 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3051 &io->msg.uaddr, &io->msg.iov);
3057 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3058 bool force_nonblock)
3060 #if defined(CONFIG_NET)
3061 struct io_async_msghdr *kmsg = NULL;
3062 struct socket *sock;
3065 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3068 sock = sock_from_file(req->file, &ret);
3070 struct io_async_ctx io;
3071 struct sockaddr_storage addr;
3075 kmsg = &req->io->msg;
3076 kmsg->msg.msg_name = &addr;
3077 /* if iov is set, it's allocated already */
3079 kmsg->iov = kmsg->fast_iov;
3080 kmsg->msg.msg_iter.iov = kmsg->iov;
3082 struct io_sr_msg *sr = &req->sr_msg;
3085 kmsg->msg.msg_name = &addr;
3087 io.msg.iov = io.msg.fast_iov;
3088 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3089 sr->msg_flags, &io.msg.uaddr,
3095 flags = req->sr_msg.msg_flags;
3096 if (flags & MSG_DONTWAIT)
3097 req->flags |= REQ_F_NOWAIT;
3098 else if (force_nonblock)
3099 flags |= MSG_DONTWAIT;
3101 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3102 kmsg->uaddr, flags);
3103 if (force_nonblock && ret == -EAGAIN) {
3106 if (io_alloc_async_ctx(req))
3108 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3109 req->work.func = io_sendrecv_async;
3112 if (ret == -ERESTARTSYS)
3116 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
3118 io_cqring_add_event(req, ret);
3120 req_set_fail_links(req);
3121 io_put_req_find_next(req, nxt);
3128 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3129 bool force_nonblock)
3131 #if defined(CONFIG_NET)
3132 struct socket *sock;
3135 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3138 sock = sock_from_file(req->file, &ret);
3140 struct io_sr_msg *sr = &req->sr_msg;
3145 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3150 msg.msg_name = NULL;
3151 msg.msg_control = NULL;
3152 msg.msg_controllen = 0;
3153 msg.msg_namelen = 0;
3154 msg.msg_iocb = NULL;
3157 flags = req->sr_msg.msg_flags;
3158 if (flags & MSG_DONTWAIT)
3159 req->flags |= REQ_F_NOWAIT;
3160 else if (force_nonblock)
3161 flags |= MSG_DONTWAIT;
3163 ret = __sys_recvmsg_sock(sock, &msg, NULL, NULL, flags);
3164 if (force_nonblock && ret == -EAGAIN)
3166 if (ret == -ERESTARTSYS)
3170 io_cqring_add_event(req, ret);
3172 req_set_fail_links(req);
3173 io_put_req_find_next(req, nxt);
3181 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3183 #if defined(CONFIG_NET)
3184 struct io_accept *accept = &req->accept;
3186 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3188 if (sqe->ioprio || sqe->len || sqe->buf_index)
3191 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3192 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3193 accept->flags = READ_ONCE(sqe->accept_flags);
3200 #if defined(CONFIG_NET)
3201 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3202 bool force_nonblock)
3204 struct io_accept *accept = &req->accept;
3205 unsigned file_flags;
3208 file_flags = force_nonblock ? O_NONBLOCK : 0;
3209 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3210 accept->addr_len, accept->flags);
3211 if (ret == -EAGAIN && force_nonblock)
3213 if (ret == -ERESTARTSYS)
3216 req_set_fail_links(req);
3217 io_cqring_add_event(req, ret);
3218 io_put_req_find_next(req, nxt);
3222 static void io_accept_finish(struct io_wq_work **workptr)
3224 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3225 struct io_kiocb *nxt = NULL;
3227 if (io_req_cancelled(req))
3229 __io_accept(req, &nxt, false);
3231 io_wq_assign_next(workptr, nxt);
3235 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3236 bool force_nonblock)
3238 #if defined(CONFIG_NET)
3241 ret = __io_accept(req, nxt, force_nonblock);
3242 if (ret == -EAGAIN && force_nonblock) {
3243 req->work.func = io_accept_finish;
3244 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3254 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3256 #if defined(CONFIG_NET)
3257 struct io_connect *conn = &req->connect;
3258 struct io_async_ctx *io = req->io;
3260 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3262 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3265 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3266 conn->addr_len = READ_ONCE(sqe->addr2);
3271 return move_addr_to_kernel(conn->addr, conn->addr_len,
3272 &io->connect.address);
3278 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3279 bool force_nonblock)
3281 #if defined(CONFIG_NET)
3282 struct io_async_ctx __io, *io;
3283 unsigned file_flags;
3289 ret = move_addr_to_kernel(req->connect.addr,
3290 req->connect.addr_len,
3291 &__io.connect.address);
3297 file_flags = force_nonblock ? O_NONBLOCK : 0;
3299 ret = __sys_connect_file(req->file, &io->connect.address,
3300 req->connect.addr_len, file_flags);
3301 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3304 if (io_alloc_async_ctx(req)) {
3308 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3311 if (ret == -ERESTARTSYS)
3315 req_set_fail_links(req);
3316 io_cqring_add_event(req, ret);
3317 io_put_req_find_next(req, nxt);
3324 static void io_poll_remove_one(struct io_kiocb *req)
3326 struct io_poll_iocb *poll = &req->poll;
3328 spin_lock(&poll->head->lock);
3329 WRITE_ONCE(poll->canceled, true);
3330 if (!list_empty(&poll->wait.entry)) {
3331 list_del_init(&poll->wait.entry);
3332 io_queue_async_work(req);
3334 spin_unlock(&poll->head->lock);
3335 hash_del(&req->hash_node);
3338 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3340 struct hlist_node *tmp;
3341 struct io_kiocb *req;
3344 spin_lock_irq(&ctx->completion_lock);
3345 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3346 struct hlist_head *list;
3348 list = &ctx->cancel_hash[i];
3349 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3350 io_poll_remove_one(req);
3352 spin_unlock_irq(&ctx->completion_lock);
3355 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3357 struct hlist_head *list;
3358 struct io_kiocb *req;
3360 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3361 hlist_for_each_entry(req, list, hash_node) {
3362 if (sqe_addr == req->user_data) {
3363 io_poll_remove_one(req);
3371 static int io_poll_remove_prep(struct io_kiocb *req,
3372 const struct io_uring_sqe *sqe)
3374 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3376 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3380 req->poll.addr = READ_ONCE(sqe->addr);
3385 * Find a running poll command that matches one specified in sqe->addr,
3386 * and remove it if found.
3388 static int io_poll_remove(struct io_kiocb *req)
3390 struct io_ring_ctx *ctx = req->ctx;
3394 addr = req->poll.addr;
3395 spin_lock_irq(&ctx->completion_lock);
3396 ret = io_poll_cancel(ctx, addr);
3397 spin_unlock_irq(&ctx->completion_lock);
3399 io_cqring_add_event(req, ret);
3401 req_set_fail_links(req);
3406 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3408 struct io_ring_ctx *ctx = req->ctx;
3410 req->poll.done = true;
3412 io_cqring_fill_event(req, error);
3414 io_cqring_fill_event(req, mangle_poll(mask));
3415 io_commit_cqring(ctx);
3418 static void io_poll_complete_work(struct io_wq_work **workptr)
3420 struct io_wq_work *work = *workptr;
3421 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3422 struct io_poll_iocb *poll = &req->poll;
3423 struct poll_table_struct pt = { ._key = poll->events };
3424 struct io_ring_ctx *ctx = req->ctx;
3425 struct io_kiocb *nxt = NULL;
3429 if (work->flags & IO_WQ_WORK_CANCEL) {
3430 WRITE_ONCE(poll->canceled, true);
3432 } else if (READ_ONCE(poll->canceled)) {
3436 if (ret != -ECANCELED)
3437 mask = vfs_poll(poll->file, &pt) & poll->events;
3440 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3441 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3442 * synchronize with them. In the cancellation case the list_del_init
3443 * itself is not actually needed, but harmless so we keep it in to
3444 * avoid further branches in the fast path.
3446 spin_lock_irq(&ctx->completion_lock);
3447 if (!mask && ret != -ECANCELED) {
3448 add_wait_queue(poll->head, &poll->wait);
3449 spin_unlock_irq(&ctx->completion_lock);
3452 hash_del(&req->hash_node);
3453 io_poll_complete(req, mask, ret);
3454 spin_unlock_irq(&ctx->completion_lock);
3456 io_cqring_ev_posted(ctx);
3459 req_set_fail_links(req);
3460 io_put_req_find_next(req, &nxt);
3462 io_wq_assign_next(workptr, nxt);
3465 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3467 struct io_kiocb *req, *tmp;
3468 struct req_batch rb;
3470 rb.to_free = rb.need_iter = 0;
3471 spin_lock_irq(&ctx->completion_lock);
3472 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3473 hash_del(&req->hash_node);
3474 io_poll_complete(req, req->result, 0);
3476 if (refcount_dec_and_test(&req->refs) &&
3477 !io_req_multi_free(&rb, req)) {
3478 req->flags |= REQ_F_COMP_LOCKED;
3482 spin_unlock_irq(&ctx->completion_lock);
3484 io_cqring_ev_posted(ctx);
3485 io_free_req_many(ctx, &rb);
3488 static void io_poll_flush(struct io_wq_work **workptr)
3490 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3491 struct llist_node *nodes;
3493 nodes = llist_del_all(&req->ctx->poll_llist);
3495 __io_poll_flush(req->ctx, nodes);
3498 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3501 struct io_poll_iocb *poll = wait->private;
3502 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3503 struct io_ring_ctx *ctx = req->ctx;
3504 __poll_t mask = key_to_poll(key);
3506 /* for instances that support it check for an event match first: */
3507 if (mask && !(mask & poll->events))
3510 list_del_init(&poll->wait.entry);
3513 * Run completion inline if we can. We're using trylock here because
3514 * we are violating the completion_lock -> poll wq lock ordering.
3515 * If we have a link timeout we're going to need the completion_lock
3516 * for finalizing the request, mark us as having grabbed that already.
3519 unsigned long flags;
3521 if (llist_empty(&ctx->poll_llist) &&
3522 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3523 hash_del(&req->hash_node);
3524 io_poll_complete(req, mask, 0);
3525 req->flags |= REQ_F_COMP_LOCKED;
3527 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3529 io_cqring_ev_posted(ctx);
3533 req->llist_node.next = NULL;
3534 /* if the list wasn't empty, we're done */
3535 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3538 req->work.func = io_poll_flush;
3542 io_queue_async_work(req);
3547 struct io_poll_table {
3548 struct poll_table_struct pt;
3549 struct io_kiocb *req;
3553 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3554 struct poll_table_struct *p)
3556 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3558 if (unlikely(pt->req->poll.head)) {
3559 pt->error = -EINVAL;
3564 pt->req->poll.head = head;
3565 add_wait_queue(head, &pt->req->poll.wait);
3568 static void io_poll_req_insert(struct io_kiocb *req)
3570 struct io_ring_ctx *ctx = req->ctx;
3571 struct hlist_head *list;
3573 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3574 hlist_add_head(&req->hash_node, list);
3577 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3579 struct io_poll_iocb *poll = &req->poll;
3582 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3584 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3589 events = READ_ONCE(sqe->poll_events);
3590 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3594 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3596 struct io_poll_iocb *poll = &req->poll;
3597 struct io_ring_ctx *ctx = req->ctx;
3598 struct io_poll_table ipt;
3599 bool cancel = false;
3602 INIT_IO_WORK(&req->work, io_poll_complete_work);
3603 INIT_HLIST_NODE(&req->hash_node);
3607 poll->canceled = false;
3609 ipt.pt._qproc = io_poll_queue_proc;
3610 ipt.pt._key = poll->events;
3612 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3614 /* initialized the list so that we can do list_empty checks */
3615 INIT_LIST_HEAD(&poll->wait.entry);
3616 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3617 poll->wait.private = poll;
3619 INIT_LIST_HEAD(&req->list);
3621 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3623 spin_lock_irq(&ctx->completion_lock);
3624 if (likely(poll->head)) {
3625 spin_lock(&poll->head->lock);
3626 if (unlikely(list_empty(&poll->wait.entry))) {
3632 if (mask || ipt.error)
3633 list_del_init(&poll->wait.entry);
3635 WRITE_ONCE(poll->canceled, true);
3636 else if (!poll->done) /* actually waiting for an event */
3637 io_poll_req_insert(req);
3638 spin_unlock(&poll->head->lock);
3640 if (mask) { /* no async, we'd stolen it */
3642 io_poll_complete(req, mask, 0);
3644 spin_unlock_irq(&ctx->completion_lock);
3647 io_cqring_ev_posted(ctx);
3648 io_put_req_find_next(req, nxt);
3653 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3655 struct io_timeout_data *data = container_of(timer,
3656 struct io_timeout_data, timer);
3657 struct io_kiocb *req = data->req;
3658 struct io_ring_ctx *ctx = req->ctx;
3659 unsigned long flags;
3661 atomic_inc(&ctx->cq_timeouts);
3663 spin_lock_irqsave(&ctx->completion_lock, flags);
3665 * We could be racing with timeout deletion. If the list is empty,
3666 * then timeout lookup already found it and will be handling it.
3668 if (!list_empty(&req->list)) {
3669 struct io_kiocb *prev;
3672 * Adjust the reqs sequence before the current one because it
3673 * will consume a slot in the cq_ring and the cq_tail
3674 * pointer will be increased, otherwise other timeout reqs may
3675 * return in advance without waiting for enough wait_nr.
3678 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3680 list_del_init(&req->list);
3683 io_cqring_fill_event(req, -ETIME);
3684 io_commit_cqring(ctx);
3685 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3687 io_cqring_ev_posted(ctx);
3688 req_set_fail_links(req);
3690 return HRTIMER_NORESTART;
3693 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3695 struct io_kiocb *req;
3698 list_for_each_entry(req, &ctx->timeout_list, list) {
3699 if (user_data == req->user_data) {
3700 list_del_init(&req->list);
3709 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3713 req_set_fail_links(req);
3714 io_cqring_fill_event(req, -ECANCELED);
3719 static int io_timeout_remove_prep(struct io_kiocb *req,
3720 const struct io_uring_sqe *sqe)
3722 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3724 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3727 req->timeout.addr = READ_ONCE(sqe->addr);
3728 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3729 if (req->timeout.flags)
3736 * Remove or update an existing timeout command
3738 static int io_timeout_remove(struct io_kiocb *req)
3740 struct io_ring_ctx *ctx = req->ctx;
3743 spin_lock_irq(&ctx->completion_lock);
3744 ret = io_timeout_cancel(ctx, req->timeout.addr);
3746 io_cqring_fill_event(req, ret);
3747 io_commit_cqring(ctx);
3748 spin_unlock_irq(&ctx->completion_lock);
3749 io_cqring_ev_posted(ctx);
3751 req_set_fail_links(req);
3756 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3757 bool is_timeout_link)
3759 struct io_timeout_data *data;
3762 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3764 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3766 if (sqe->off && is_timeout_link)
3768 flags = READ_ONCE(sqe->timeout_flags);
3769 if (flags & ~IORING_TIMEOUT_ABS)
3772 req->timeout.count = READ_ONCE(sqe->off);
3774 if (!req->io && io_alloc_async_ctx(req))
3777 data = &req->io->timeout;
3779 req->flags |= REQ_F_TIMEOUT;
3781 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3784 if (flags & IORING_TIMEOUT_ABS)
3785 data->mode = HRTIMER_MODE_ABS;
3787 data->mode = HRTIMER_MODE_REL;
3789 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3793 static int io_timeout(struct io_kiocb *req)
3796 struct io_ring_ctx *ctx = req->ctx;
3797 struct io_timeout_data *data;
3798 struct list_head *entry;
3801 data = &req->io->timeout;
3804 * sqe->off holds how many events that need to occur for this
3805 * timeout event to be satisfied. If it isn't set, then this is
3806 * a pure timeout request, sequence isn't used.
3808 count = req->timeout.count;
3810 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3811 spin_lock_irq(&ctx->completion_lock);
3812 entry = ctx->timeout_list.prev;
3816 req->sequence = ctx->cached_sq_head + count - 1;
3817 data->seq_offset = count;
3820 * Insertion sort, ensuring the first entry in the list is always
3821 * the one we need first.
3823 spin_lock_irq(&ctx->completion_lock);
3824 list_for_each_prev(entry, &ctx->timeout_list) {
3825 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3826 unsigned nxt_sq_head;
3827 long long tmp, tmp_nxt;
3828 u32 nxt_offset = nxt->io->timeout.seq_offset;
3830 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3834 * Since cached_sq_head + count - 1 can overflow, use type long
3837 tmp = (long long)ctx->cached_sq_head + count - 1;
3838 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3839 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3842 * cached_sq_head may overflow, and it will never overflow twice
3843 * once there is some timeout req still be valid.
3845 if (ctx->cached_sq_head < nxt_sq_head)
3852 * Sequence of reqs after the insert one and itself should
3853 * be adjusted because each timeout req consumes a slot.
3858 req->sequence -= span;
3860 list_add(&req->list, entry);
3861 data->timer.function = io_timeout_fn;
3862 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3863 spin_unlock_irq(&ctx->completion_lock);
3867 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3869 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3871 return req->user_data == (unsigned long) data;
3874 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3876 enum io_wq_cancel cancel_ret;
3879 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3880 switch (cancel_ret) {
3881 case IO_WQ_CANCEL_OK:
3884 case IO_WQ_CANCEL_RUNNING:
3887 case IO_WQ_CANCEL_NOTFOUND:
3895 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3896 struct io_kiocb *req, __u64 sqe_addr,
3897 struct io_kiocb **nxt, int success_ret)
3899 unsigned long flags;
3902 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3903 if (ret != -ENOENT) {
3904 spin_lock_irqsave(&ctx->completion_lock, flags);
3908 spin_lock_irqsave(&ctx->completion_lock, flags);
3909 ret = io_timeout_cancel(ctx, sqe_addr);
3912 ret = io_poll_cancel(ctx, sqe_addr);
3916 io_cqring_fill_event(req, ret);
3917 io_commit_cqring(ctx);
3918 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3919 io_cqring_ev_posted(ctx);
3922 req_set_fail_links(req);
3923 io_put_req_find_next(req, nxt);
3926 static int io_async_cancel_prep(struct io_kiocb *req,
3927 const struct io_uring_sqe *sqe)
3929 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3931 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3935 req->cancel.addr = READ_ONCE(sqe->addr);
3939 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3941 struct io_ring_ctx *ctx = req->ctx;
3943 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3947 static int io_files_update_prep(struct io_kiocb *req,
3948 const struct io_uring_sqe *sqe)
3950 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
3953 req->files_update.offset = READ_ONCE(sqe->off);
3954 req->files_update.nr_args = READ_ONCE(sqe->len);
3955 if (!req->files_update.nr_args)
3957 req->files_update.arg = READ_ONCE(sqe->addr);
3961 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
3963 struct io_ring_ctx *ctx = req->ctx;
3964 struct io_uring_files_update up;
3967 if (force_nonblock) {
3968 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3972 up.offset = req->files_update.offset;
3973 up.fds = req->files_update.arg;
3975 mutex_lock(&ctx->uring_lock);
3976 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
3977 mutex_unlock(&ctx->uring_lock);
3980 req_set_fail_links(req);
3981 io_cqring_add_event(req, ret);
3986 static int io_req_defer_prep(struct io_kiocb *req,
3987 const struct io_uring_sqe *sqe)
3991 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
3993 switch (req->opcode) {
3996 case IORING_OP_READV:
3997 case IORING_OP_READ_FIXED:
3998 case IORING_OP_READ:
3999 ret = io_read_prep(req, sqe, true);
4001 case IORING_OP_WRITEV:
4002 case IORING_OP_WRITE_FIXED:
4003 case IORING_OP_WRITE:
4004 ret = io_write_prep(req, sqe, true);
4006 case IORING_OP_POLL_ADD:
4007 ret = io_poll_add_prep(req, sqe);
4009 case IORING_OP_POLL_REMOVE:
4010 ret = io_poll_remove_prep(req, sqe);
4012 case IORING_OP_FSYNC:
4013 ret = io_prep_fsync(req, sqe);
4015 case IORING_OP_SYNC_FILE_RANGE:
4016 ret = io_prep_sfr(req, sqe);
4018 case IORING_OP_SENDMSG:
4019 case IORING_OP_SEND:
4020 ret = io_sendmsg_prep(req, sqe);
4022 case IORING_OP_RECVMSG:
4023 case IORING_OP_RECV:
4024 ret = io_recvmsg_prep(req, sqe);
4026 case IORING_OP_CONNECT:
4027 ret = io_connect_prep(req, sqe);
4029 case IORING_OP_TIMEOUT:
4030 ret = io_timeout_prep(req, sqe, false);
4032 case IORING_OP_TIMEOUT_REMOVE:
4033 ret = io_timeout_remove_prep(req, sqe);
4035 case IORING_OP_ASYNC_CANCEL:
4036 ret = io_async_cancel_prep(req, sqe);
4038 case IORING_OP_LINK_TIMEOUT:
4039 ret = io_timeout_prep(req, sqe, true);
4041 case IORING_OP_ACCEPT:
4042 ret = io_accept_prep(req, sqe);
4044 case IORING_OP_FALLOCATE:
4045 ret = io_fallocate_prep(req, sqe);
4047 case IORING_OP_OPENAT:
4048 ret = io_openat_prep(req, sqe);
4050 case IORING_OP_CLOSE:
4051 ret = io_close_prep(req, sqe);
4053 case IORING_OP_FILES_UPDATE:
4054 ret = io_files_update_prep(req, sqe);
4056 case IORING_OP_STATX:
4057 ret = io_statx_prep(req, sqe);
4059 case IORING_OP_FADVISE:
4060 ret = io_fadvise_prep(req, sqe);
4062 case IORING_OP_MADVISE:
4063 ret = io_madvise_prep(req, sqe);
4065 case IORING_OP_OPENAT2:
4066 ret = io_openat2_prep(req, sqe);
4069 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4078 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4080 struct io_ring_ctx *ctx = req->ctx;
4083 /* Still need defer if there is pending req in defer list. */
4084 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4087 if (!req->io && io_alloc_async_ctx(req))
4090 ret = io_req_defer_prep(req, sqe);
4094 spin_lock_irq(&ctx->completion_lock);
4095 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4096 spin_unlock_irq(&ctx->completion_lock);
4100 trace_io_uring_defer(ctx, req, req->user_data);
4101 list_add_tail(&req->list, &ctx->defer_list);
4102 spin_unlock_irq(&ctx->completion_lock);
4103 return -EIOCBQUEUED;
4106 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4107 struct io_kiocb **nxt, bool force_nonblock)
4109 struct io_ring_ctx *ctx = req->ctx;
4112 switch (req->opcode) {
4116 case IORING_OP_READV:
4117 case IORING_OP_READ_FIXED:
4118 case IORING_OP_READ:
4120 ret = io_read_prep(req, sqe, force_nonblock);
4124 ret = io_read(req, nxt, force_nonblock);
4126 case IORING_OP_WRITEV:
4127 case IORING_OP_WRITE_FIXED:
4128 case IORING_OP_WRITE:
4130 ret = io_write_prep(req, sqe, force_nonblock);
4134 ret = io_write(req, nxt, force_nonblock);
4136 case IORING_OP_FSYNC:
4138 ret = io_prep_fsync(req, sqe);
4142 ret = io_fsync(req, nxt, force_nonblock);
4144 case IORING_OP_POLL_ADD:
4146 ret = io_poll_add_prep(req, sqe);
4150 ret = io_poll_add(req, nxt);
4152 case IORING_OP_POLL_REMOVE:
4154 ret = io_poll_remove_prep(req, sqe);
4158 ret = io_poll_remove(req);
4160 case IORING_OP_SYNC_FILE_RANGE:
4162 ret = io_prep_sfr(req, sqe);
4166 ret = io_sync_file_range(req, nxt, force_nonblock);
4168 case IORING_OP_SENDMSG:
4169 case IORING_OP_SEND:
4171 ret = io_sendmsg_prep(req, sqe);
4175 if (req->opcode == IORING_OP_SENDMSG)
4176 ret = io_sendmsg(req, nxt, force_nonblock);
4178 ret = io_send(req, nxt, force_nonblock);
4180 case IORING_OP_RECVMSG:
4181 case IORING_OP_RECV:
4183 ret = io_recvmsg_prep(req, sqe);
4187 if (req->opcode == IORING_OP_RECVMSG)
4188 ret = io_recvmsg(req, nxt, force_nonblock);
4190 ret = io_recv(req, nxt, force_nonblock);
4192 case IORING_OP_TIMEOUT:
4194 ret = io_timeout_prep(req, sqe, false);
4198 ret = io_timeout(req);
4200 case IORING_OP_TIMEOUT_REMOVE:
4202 ret = io_timeout_remove_prep(req, sqe);
4206 ret = io_timeout_remove(req);
4208 case IORING_OP_ACCEPT:
4210 ret = io_accept_prep(req, sqe);
4214 ret = io_accept(req, nxt, force_nonblock);
4216 case IORING_OP_CONNECT:
4218 ret = io_connect_prep(req, sqe);
4222 ret = io_connect(req, nxt, force_nonblock);
4224 case IORING_OP_ASYNC_CANCEL:
4226 ret = io_async_cancel_prep(req, sqe);
4230 ret = io_async_cancel(req, nxt);
4232 case IORING_OP_FALLOCATE:
4234 ret = io_fallocate_prep(req, sqe);
4238 ret = io_fallocate(req, nxt, force_nonblock);
4240 case IORING_OP_OPENAT:
4242 ret = io_openat_prep(req, sqe);
4246 ret = io_openat(req, nxt, force_nonblock);
4248 case IORING_OP_CLOSE:
4250 ret = io_close_prep(req, sqe);
4254 ret = io_close(req, nxt, force_nonblock);
4256 case IORING_OP_FILES_UPDATE:
4258 ret = io_files_update_prep(req, sqe);
4262 ret = io_files_update(req, force_nonblock);
4264 case IORING_OP_STATX:
4266 ret = io_statx_prep(req, sqe);
4270 ret = io_statx(req, nxt, force_nonblock);
4272 case IORING_OP_FADVISE:
4274 ret = io_fadvise_prep(req, sqe);
4278 ret = io_fadvise(req, nxt, force_nonblock);
4280 case IORING_OP_MADVISE:
4282 ret = io_madvise_prep(req, sqe);
4286 ret = io_madvise(req, nxt, force_nonblock);
4288 case IORING_OP_OPENAT2:
4290 ret = io_openat2_prep(req, sqe);
4294 ret = io_openat2(req, nxt, force_nonblock);
4304 if (ctx->flags & IORING_SETUP_IOPOLL) {
4305 const bool in_async = io_wq_current_is_worker();
4307 if (req->result == -EAGAIN)
4310 /* workqueue context doesn't hold uring_lock, grab it now */
4312 mutex_lock(&ctx->uring_lock);
4314 io_iopoll_req_issued(req);
4317 mutex_unlock(&ctx->uring_lock);
4323 static void io_wq_submit_work(struct io_wq_work **workptr)
4325 struct io_wq_work *work = *workptr;
4326 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4327 struct io_kiocb *nxt = NULL;
4330 /* if NO_CANCEL is set, we must still run the work */
4331 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4332 IO_WQ_WORK_CANCEL) {
4337 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
4338 req->in_async = true;
4340 ret = io_issue_sqe(req, NULL, &nxt, false);
4342 * We can get EAGAIN for polled IO even though we're
4343 * forcing a sync submission from here, since we can't
4344 * wait for request slots on the block side.
4352 /* drop submission reference */
4356 req_set_fail_links(req);
4357 io_cqring_add_event(req, ret);
4361 /* if a dependent link is ready, pass it back */
4363 io_wq_assign_next(workptr, nxt);
4366 static int io_req_needs_file(struct io_kiocb *req, int fd)
4368 if (!io_op_defs[req->opcode].needs_file)
4370 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4375 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4378 struct fixed_file_table *table;
4380 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4381 return table->files[index & IORING_FILE_TABLE_MASK];;
4384 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4385 const struct io_uring_sqe *sqe)
4387 struct io_ring_ctx *ctx = req->ctx;
4391 flags = READ_ONCE(sqe->flags);
4392 fd = READ_ONCE(sqe->fd);
4394 if (!io_req_needs_file(req, fd))
4397 if (flags & IOSQE_FIXED_FILE) {
4398 if (unlikely(!ctx->file_data ||
4399 (unsigned) fd >= ctx->nr_user_files))
4401 fd = array_index_nospec(fd, ctx->nr_user_files);
4402 req->file = io_file_from_index(ctx, fd);
4405 req->flags |= REQ_F_FIXED_FILE;
4406 percpu_ref_get(&ctx->file_data->refs);
4408 if (req->needs_fixed_file)
4410 trace_io_uring_file_get(ctx, fd);
4411 req->file = io_file_get(state, fd);
4412 if (unlikely(!req->file))
4419 static int io_grab_files(struct io_kiocb *req)
4422 struct io_ring_ctx *ctx = req->ctx;
4424 if (!ctx->ring_file)
4428 spin_lock_irq(&ctx->inflight_lock);
4430 * We use the f_ops->flush() handler to ensure that we can flush
4431 * out work accessing these files if the fd is closed. Check if
4432 * the fd has changed since we started down this path, and disallow
4433 * this operation if it has.
4435 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4436 list_add(&req->inflight_entry, &ctx->inflight_list);
4437 req->flags |= REQ_F_INFLIGHT;
4438 req->work.files = current->files;
4441 spin_unlock_irq(&ctx->inflight_lock);
4447 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4449 struct io_timeout_data *data = container_of(timer,
4450 struct io_timeout_data, timer);
4451 struct io_kiocb *req = data->req;
4452 struct io_ring_ctx *ctx = req->ctx;
4453 struct io_kiocb *prev = NULL;
4454 unsigned long flags;
4456 spin_lock_irqsave(&ctx->completion_lock, flags);
4459 * We don't expect the list to be empty, that will only happen if we
4460 * race with the completion of the linked work.
4462 if (!list_empty(&req->link_list)) {
4463 prev = list_entry(req->link_list.prev, struct io_kiocb,
4465 if (refcount_inc_not_zero(&prev->refs)) {
4466 list_del_init(&req->link_list);
4467 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4472 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4475 req_set_fail_links(prev);
4476 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4480 io_cqring_add_event(req, -ETIME);
4483 return HRTIMER_NORESTART;
4486 static void io_queue_linked_timeout(struct io_kiocb *req)
4488 struct io_ring_ctx *ctx = req->ctx;
4491 * If the list is now empty, then our linked request finished before
4492 * we got a chance to setup the timer
4494 spin_lock_irq(&ctx->completion_lock);
4495 if (!list_empty(&req->link_list)) {
4496 struct io_timeout_data *data = &req->io->timeout;
4498 data->timer.function = io_link_timeout_fn;
4499 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4502 spin_unlock_irq(&ctx->completion_lock);
4504 /* drop submission reference */
4508 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4510 struct io_kiocb *nxt;
4512 if (!(req->flags & REQ_F_LINK))
4515 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4517 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4520 req->flags |= REQ_F_LINK_TIMEOUT;
4524 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4526 struct io_kiocb *linked_timeout;
4527 struct io_kiocb *nxt = NULL;
4531 linked_timeout = io_prep_linked_timeout(req);
4533 ret = io_issue_sqe(req, sqe, &nxt, true);
4536 * We async punt it if the file wasn't marked NOWAIT, or if the file
4537 * doesn't support non-blocking read/write attempts
4539 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4540 (req->flags & REQ_F_MUST_PUNT))) {
4542 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
4543 ret = io_grab_files(req);
4549 * Queued up for async execution, worker will release
4550 * submit reference when the iocb is actually submitted.
4552 io_queue_async_work(req);
4557 /* drop submission reference */
4560 if (linked_timeout) {
4562 io_queue_linked_timeout(linked_timeout);
4564 io_put_req(linked_timeout);
4567 /* and drop final reference, if we failed */
4569 io_cqring_add_event(req, ret);
4570 req_set_fail_links(req);
4578 if (req->flags & REQ_F_FORCE_ASYNC)
4584 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4588 ret = io_req_defer(req, sqe);
4590 if (ret != -EIOCBQUEUED) {
4592 io_cqring_add_event(req, ret);
4593 req_set_fail_links(req);
4594 io_double_put_req(req);
4596 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4597 ret = io_req_defer_prep(req, sqe);
4598 if (unlikely(ret < 0))
4601 * Never try inline submit of IOSQE_ASYNC is set, go straight
4602 * to async execution.
4604 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4605 io_queue_async_work(req);
4607 __io_queue_sqe(req, sqe);
4611 static inline void io_queue_link_head(struct io_kiocb *req)
4613 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4614 io_cqring_add_event(req, -ECANCELED);
4615 io_double_put_req(req);
4617 io_queue_sqe(req, NULL);
4620 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4621 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4623 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4624 struct io_submit_state *state, struct io_kiocb **link)
4626 struct io_ring_ctx *ctx = req->ctx;
4627 unsigned int sqe_flags;
4630 sqe_flags = READ_ONCE(sqe->flags);
4632 /* enforce forwards compatibility on users */
4633 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4637 /* same numerical values with corresponding REQ_F_*, safe to copy */
4638 req->flags |= sqe_flags & (IOSQE_IO_DRAIN|IOSQE_IO_HARDLINK|
4641 ret = io_req_set_file(state, req, sqe);
4642 if (unlikely(ret)) {
4644 io_cqring_add_event(req, ret);
4645 io_double_put_req(req);
4650 * If we already have a head request, queue this one for async
4651 * submittal once the head completes. If we don't have a head but
4652 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4653 * submitted sync once the chain is complete. If none of those
4654 * conditions are true (normal request), then just queue it.
4657 struct io_kiocb *head = *link;
4660 * Taking sequential execution of a link, draining both sides
4661 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
4662 * requests in the link. So, it drains the head and the
4663 * next after the link request. The last one is done via
4664 * drain_next flag to persist the effect across calls.
4666 if (sqe_flags & IOSQE_IO_DRAIN) {
4667 head->flags |= REQ_F_IO_DRAIN;
4668 ctx->drain_next = 1;
4670 if (io_alloc_async_ctx(req)) {
4675 ret = io_req_defer_prep(req, sqe);
4677 /* fail even hard links since we don't submit */
4678 head->flags |= REQ_F_FAIL_LINK;
4681 trace_io_uring_link(ctx, req, head);
4682 list_add_tail(&req->link_list, &head->link_list);
4684 /* last request of a link, enqueue the link */
4685 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4686 io_queue_link_head(head);
4690 if (unlikely(ctx->drain_next)) {
4691 req->flags |= REQ_F_IO_DRAIN;
4692 req->ctx->drain_next = 0;
4694 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4695 req->flags |= REQ_F_LINK;
4696 INIT_LIST_HEAD(&req->link_list);
4697 ret = io_req_defer_prep(req, sqe);
4699 req->flags |= REQ_F_FAIL_LINK;
4702 io_queue_sqe(req, sqe);
4710 * Batched submission is done, ensure local IO is flushed out.
4712 static void io_submit_state_end(struct io_submit_state *state)
4714 blk_finish_plug(&state->plug);
4716 if (state->free_reqs)
4717 kmem_cache_free_bulk(req_cachep, state->free_reqs,
4718 &state->reqs[state->cur_req]);
4722 * Start submission side cache.
4724 static void io_submit_state_start(struct io_submit_state *state,
4725 unsigned int max_ios)
4727 blk_start_plug(&state->plug);
4728 state->free_reqs = 0;
4730 state->ios_left = max_ios;
4733 static void io_commit_sqring(struct io_ring_ctx *ctx)
4735 struct io_rings *rings = ctx->rings;
4738 * Ensure any loads from the SQEs are done at this point,
4739 * since once we write the new head, the application could
4740 * write new data to them.
4742 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4746 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4747 * that is mapped by userspace. This means that care needs to be taken to
4748 * ensure that reads are stable, as we cannot rely on userspace always
4749 * being a good citizen. If members of the sqe are validated and then later
4750 * used, it's important that those reads are done through READ_ONCE() to
4751 * prevent a re-load down the line.
4753 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4754 const struct io_uring_sqe **sqe_ptr)
4756 u32 *sq_array = ctx->sq_array;
4760 * The cached sq head (or cq tail) serves two purposes:
4762 * 1) allows us to batch the cost of updating the user visible
4764 * 2) allows the kernel side to track the head on its own, even
4765 * though the application is the one updating it.
4767 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4768 if (likely(head < ctx->sq_entries)) {
4770 * All io need record the previous position, if LINK vs DARIN,
4771 * it can be used to mark the position of the first IO in the
4774 req->sequence = ctx->cached_sq_head;
4775 *sqe_ptr = &ctx->sq_sqes[head];
4776 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4777 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4778 ctx->cached_sq_head++;
4782 /* drop invalid entries */
4783 ctx->cached_sq_head++;
4784 ctx->cached_sq_dropped++;
4785 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4789 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4790 struct file *ring_file, int ring_fd,
4791 struct mm_struct **mm, bool async)
4793 struct io_submit_state state, *statep = NULL;
4794 struct io_kiocb *link = NULL;
4795 int i, submitted = 0;
4796 bool mm_fault = false;
4798 /* if we have a backlog and couldn't flush it all, return BUSY */
4799 if (test_bit(0, &ctx->sq_check_overflow)) {
4800 if (!list_empty(&ctx->cq_overflow_list) &&
4801 !io_cqring_overflow_flush(ctx, false))
4805 /* make sure SQ entry isn't read before tail */
4806 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
4808 if (!percpu_ref_tryget_many(&ctx->refs, nr))
4811 if (nr > IO_PLUG_THRESHOLD) {
4812 io_submit_state_start(&state, nr);
4816 ctx->ring_fd = ring_fd;
4817 ctx->ring_file = ring_file;
4819 for (i = 0; i < nr; i++) {
4820 const struct io_uring_sqe *sqe;
4821 struct io_kiocb *req;
4823 req = io_get_req(ctx, statep);
4824 if (unlikely(!req)) {
4826 submitted = -EAGAIN;
4829 if (!io_get_sqring(ctx, req, &sqe)) {
4830 __io_req_do_free(req);
4834 /* will complete beyond this point, count as submitted */
4837 if (unlikely(req->opcode >= IORING_OP_LAST)) {
4838 io_cqring_add_event(req, -EINVAL);
4839 io_double_put_req(req);
4843 if (io_op_defs[req->opcode].needs_mm && !*mm) {
4844 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
4846 use_mm(ctx->sqo_mm);
4851 req->has_user = *mm != NULL;
4852 req->in_async = async;
4853 req->needs_fixed_file = async;
4854 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
4856 if (!io_submit_sqe(req, sqe, statep, &link))
4860 if (unlikely(submitted != nr)) {
4861 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
4863 percpu_ref_put_many(&ctx->refs, nr - ref_used);
4866 io_queue_link_head(link);
4868 io_submit_state_end(&state);
4870 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4871 io_commit_sqring(ctx);
4876 static int io_sq_thread(void *data)
4878 struct io_ring_ctx *ctx = data;
4879 struct mm_struct *cur_mm = NULL;
4880 const struct cred *old_cred;
4881 mm_segment_t old_fs;
4884 unsigned long timeout;
4887 complete(&ctx->completions[1]);
4891 old_cred = override_creds(ctx->creds);
4893 ret = timeout = inflight = 0;
4894 while (!kthread_should_park()) {
4895 unsigned int to_submit;
4898 unsigned nr_events = 0;
4900 if (ctx->flags & IORING_SETUP_IOPOLL) {
4902 * inflight is the count of the maximum possible
4903 * entries we submitted, but it can be smaller
4904 * if we dropped some of them. If we don't have
4905 * poll entries available, then we know that we
4906 * have nothing left to poll for. Reset the
4907 * inflight count to zero in that case.
4909 mutex_lock(&ctx->uring_lock);
4910 if (!list_empty(&ctx->poll_list))
4911 __io_iopoll_check(ctx, &nr_events, 0);
4914 mutex_unlock(&ctx->uring_lock);
4917 * Normal IO, just pretend everything completed.
4918 * We don't have to poll completions for that.
4920 nr_events = inflight;
4923 inflight -= nr_events;
4925 timeout = jiffies + ctx->sq_thread_idle;
4928 to_submit = io_sqring_entries(ctx);
4931 * If submit got -EBUSY, flag us as needing the application
4932 * to enter the kernel to reap and flush events.
4934 if (!to_submit || ret == -EBUSY) {
4936 * We're polling. If we're within the defined idle
4937 * period, then let us spin without work before going
4938 * to sleep. The exception is if we got EBUSY doing
4939 * more IO, we should wait for the application to
4940 * reap events and wake us up.
4943 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
4949 * Drop cur_mm before scheduling, we can't hold it for
4950 * long periods (or over schedule()). Do this before
4951 * adding ourselves to the waitqueue, as the unuse/drop
4960 prepare_to_wait(&ctx->sqo_wait, &wait,
4961 TASK_INTERRUPTIBLE);
4963 /* Tell userspace we may need a wakeup call */
4964 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
4965 /* make sure to read SQ tail after writing flags */
4968 to_submit = io_sqring_entries(ctx);
4969 if (!to_submit || ret == -EBUSY) {
4970 if (kthread_should_park()) {
4971 finish_wait(&ctx->sqo_wait, &wait);
4974 if (signal_pending(current))
4975 flush_signals(current);
4977 finish_wait(&ctx->sqo_wait, &wait);
4979 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4982 finish_wait(&ctx->sqo_wait, &wait);
4984 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4987 mutex_lock(&ctx->uring_lock);
4988 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
4989 mutex_unlock(&ctx->uring_lock);
4999 revert_creds(old_cred);
5006 struct io_wait_queue {
5007 struct wait_queue_entry wq;
5008 struct io_ring_ctx *ctx;
5010 unsigned nr_timeouts;
5013 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
5015 struct io_ring_ctx *ctx = iowq->ctx;
5018 * Wake up if we have enough events, or if a timeout occurred since we
5019 * started waiting. For timeouts, we always want to return to userspace,
5020 * regardless of event count.
5022 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
5023 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5026 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5027 int wake_flags, void *key)
5029 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5032 /* use noflush == true, as we can't safely rely on locking context */
5033 if (!io_should_wake(iowq, true))
5036 return autoremove_wake_function(curr, mode, wake_flags, key);
5040 * Wait until events become available, if we don't already have some. The
5041 * application must reap them itself, as they reside on the shared cq ring.
5043 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5044 const sigset_t __user *sig, size_t sigsz)
5046 struct io_wait_queue iowq = {
5049 .func = io_wake_function,
5050 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5053 .to_wait = min_events,
5055 struct io_rings *rings = ctx->rings;
5058 if (io_cqring_events(ctx, false) >= min_events)
5062 #ifdef CONFIG_COMPAT
5063 if (in_compat_syscall())
5064 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5068 ret = set_user_sigmask(sig, sigsz);
5074 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5075 trace_io_uring_cqring_wait(ctx, min_events);
5077 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5078 TASK_INTERRUPTIBLE);
5079 if (io_should_wake(&iowq, false))
5082 if (signal_pending(current)) {
5087 finish_wait(&ctx->wait, &iowq.wq);
5089 restore_saved_sigmask_unless(ret == -EINTR);
5091 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5094 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5096 #if defined(CONFIG_UNIX)
5097 if (ctx->ring_sock) {
5098 struct sock *sock = ctx->ring_sock->sk;
5099 struct sk_buff *skb;
5101 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5107 for (i = 0; i < ctx->nr_user_files; i++) {
5110 file = io_file_from_index(ctx, i);
5117 static void io_file_ref_kill(struct percpu_ref *ref)
5119 struct fixed_file_data *data;
5121 data = container_of(ref, struct fixed_file_data, refs);
5122 complete(&data->done);
5125 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5127 struct fixed_file_data *data = ctx->file_data;
5128 unsigned nr_tables, i;
5133 /* protect against inflight atomic switch, which drops the ref */
5134 percpu_ref_get(&data->refs);
5135 /* wait for existing switches */
5136 flush_work(&data->ref_work);
5137 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5138 wait_for_completion(&data->done);
5139 percpu_ref_put(&data->refs);
5140 /* flush potential new switch */
5141 flush_work(&data->ref_work);
5142 percpu_ref_exit(&data->refs);
5144 __io_sqe_files_unregister(ctx);
5145 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5146 for (i = 0; i < nr_tables; i++)
5147 kfree(data->table[i].files);
5150 ctx->file_data = NULL;
5151 ctx->nr_user_files = 0;
5155 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5157 if (ctx->sqo_thread) {
5158 wait_for_completion(&ctx->completions[1]);
5160 * The park is a bit of a work-around, without it we get
5161 * warning spews on shutdown with SQPOLL set and affinity
5162 * set to a single CPU.
5164 kthread_park(ctx->sqo_thread);
5165 kthread_stop(ctx->sqo_thread);
5166 ctx->sqo_thread = NULL;
5170 static void io_finish_async(struct io_ring_ctx *ctx)
5172 io_sq_thread_stop(ctx);
5175 io_wq_destroy(ctx->io_wq);
5180 #if defined(CONFIG_UNIX)
5182 * Ensure the UNIX gc is aware of our file set, so we are certain that
5183 * the io_uring can be safely unregistered on process exit, even if we have
5184 * loops in the file referencing.
5186 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5188 struct sock *sk = ctx->ring_sock->sk;
5189 struct scm_fp_list *fpl;
5190 struct sk_buff *skb;
5193 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5194 unsigned long inflight = ctx->user->unix_inflight + nr;
5196 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5200 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5204 skb = alloc_skb(0, GFP_KERNEL);
5213 fpl->user = get_uid(ctx->user);
5214 for (i = 0; i < nr; i++) {
5215 struct file *file = io_file_from_index(ctx, i + offset);
5219 fpl->fp[nr_files] = get_file(file);
5220 unix_inflight(fpl->user, fpl->fp[nr_files]);
5225 fpl->max = SCM_MAX_FD;
5226 fpl->count = nr_files;
5227 UNIXCB(skb).fp = fpl;
5228 skb->destructor = unix_destruct_scm;
5229 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5230 skb_queue_head(&sk->sk_receive_queue, skb);
5232 for (i = 0; i < nr_files; i++)
5243 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5244 * causes regular reference counting to break down. We rely on the UNIX
5245 * garbage collection to take care of this problem for us.
5247 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5249 unsigned left, total;
5253 left = ctx->nr_user_files;
5255 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
5257 ret = __io_sqe_files_scm(ctx, this_files, total);
5261 total += this_files;
5267 while (total < ctx->nr_user_files) {
5268 struct file *file = io_file_from_index(ctx, total);
5278 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5284 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5289 for (i = 0; i < nr_tables; i++) {
5290 struct fixed_file_table *table = &ctx->file_data->table[i];
5291 unsigned this_files;
5293 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5294 table->files = kcalloc(this_files, sizeof(struct file *),
5298 nr_files -= this_files;
5304 for (i = 0; i < nr_tables; i++) {
5305 struct fixed_file_table *table = &ctx->file_data->table[i];
5306 kfree(table->files);
5311 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5313 #if defined(CONFIG_UNIX)
5314 struct sock *sock = ctx->ring_sock->sk;
5315 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5316 struct sk_buff *skb;
5319 __skb_queue_head_init(&list);
5322 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5323 * remove this entry and rearrange the file array.
5325 skb = skb_dequeue(head);
5327 struct scm_fp_list *fp;
5329 fp = UNIXCB(skb).fp;
5330 for (i = 0; i < fp->count; i++) {
5333 if (fp->fp[i] != file)
5336 unix_notinflight(fp->user, fp->fp[i]);
5337 left = fp->count - 1 - i;
5339 memmove(&fp->fp[i], &fp->fp[i + 1],
5340 left * sizeof(struct file *));
5347 __skb_queue_tail(&list, skb);
5357 __skb_queue_tail(&list, skb);
5359 skb = skb_dequeue(head);
5362 if (skb_peek(&list)) {
5363 spin_lock_irq(&head->lock);
5364 while ((skb = __skb_dequeue(&list)) != NULL)
5365 __skb_queue_tail(head, skb);
5366 spin_unlock_irq(&head->lock);
5373 struct io_file_put {
5374 struct llist_node llist;
5376 struct completion *done;
5379 static void io_ring_file_ref_switch(struct work_struct *work)
5381 struct io_file_put *pfile, *tmp;
5382 struct fixed_file_data *data;
5383 struct llist_node *node;
5385 data = container_of(work, struct fixed_file_data, ref_work);
5387 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5388 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5389 io_ring_file_put(data->ctx, pfile->file);
5391 complete(pfile->done);
5397 percpu_ref_get(&data->refs);
5398 percpu_ref_switch_to_percpu(&data->refs);
5401 static void io_file_data_ref_zero(struct percpu_ref *ref)
5403 struct fixed_file_data *data;
5405 data = container_of(ref, struct fixed_file_data, refs);
5407 /* we can't safely switch from inside this context, punt to wq */
5408 queue_work(system_wq, &data->ref_work);
5411 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5414 __s32 __user *fds = (__s32 __user *) arg;
5424 if (nr_args > IORING_MAX_FIXED_FILES)
5427 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5428 if (!ctx->file_data)
5430 ctx->file_data->ctx = ctx;
5431 init_completion(&ctx->file_data->done);
5433 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5434 ctx->file_data->table = kcalloc(nr_tables,
5435 sizeof(struct fixed_file_table),
5437 if (!ctx->file_data->table) {
5438 kfree(ctx->file_data);
5439 ctx->file_data = NULL;
5443 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5444 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5445 kfree(ctx->file_data->table);
5446 kfree(ctx->file_data);
5447 ctx->file_data = NULL;
5450 ctx->file_data->put_llist.first = NULL;
5451 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5453 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5454 percpu_ref_exit(&ctx->file_data->refs);
5455 kfree(ctx->file_data->table);
5456 kfree(ctx->file_data);
5457 ctx->file_data = NULL;
5461 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5462 struct fixed_file_table *table;
5466 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5468 /* allow sparse sets */
5474 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5475 index = i & IORING_FILE_TABLE_MASK;
5483 * Don't allow io_uring instances to be registered. If UNIX
5484 * isn't enabled, then this causes a reference cycle and this
5485 * instance can never get freed. If UNIX is enabled we'll
5486 * handle it just fine, but there's still no point in allowing
5487 * a ring fd as it doesn't support regular read/write anyway.
5489 if (file->f_op == &io_uring_fops) {
5494 table->files[index] = file;
5498 for (i = 0; i < ctx->nr_user_files; i++) {
5499 file = io_file_from_index(ctx, i);
5503 for (i = 0; i < nr_tables; i++)
5504 kfree(ctx->file_data->table[i].files);
5506 kfree(ctx->file_data->table);
5507 kfree(ctx->file_data);
5508 ctx->file_data = NULL;
5509 ctx->nr_user_files = 0;
5513 ret = io_sqe_files_scm(ctx);
5515 io_sqe_files_unregister(ctx);
5520 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5523 #if defined(CONFIG_UNIX)
5524 struct sock *sock = ctx->ring_sock->sk;
5525 struct sk_buff_head *head = &sock->sk_receive_queue;
5526 struct sk_buff *skb;
5529 * See if we can merge this file into an existing skb SCM_RIGHTS
5530 * file set. If there's no room, fall back to allocating a new skb
5531 * and filling it in.
5533 spin_lock_irq(&head->lock);
5534 skb = skb_peek(head);
5536 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5538 if (fpl->count < SCM_MAX_FD) {
5539 __skb_unlink(skb, head);
5540 spin_unlock_irq(&head->lock);
5541 fpl->fp[fpl->count] = get_file(file);
5542 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5544 spin_lock_irq(&head->lock);
5545 __skb_queue_head(head, skb);
5550 spin_unlock_irq(&head->lock);
5557 return __io_sqe_files_scm(ctx, 1, index);
5563 static void io_atomic_switch(struct percpu_ref *ref)
5565 struct fixed_file_data *data;
5567 data = container_of(ref, struct fixed_file_data, refs);
5568 clear_bit(FFD_F_ATOMIC, &data->state);
5571 static bool io_queue_file_removal(struct fixed_file_data *data,
5574 struct io_file_put *pfile, pfile_stack;
5575 DECLARE_COMPLETION_ONSTACK(done);
5578 * If we fail allocating the struct we need for doing async reomval
5579 * of this file, just punt to sync and wait for it.
5581 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5583 pfile = &pfile_stack;
5584 pfile->done = &done;
5588 llist_add(&pfile->llist, &data->put_llist);
5590 if (pfile == &pfile_stack) {
5591 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5592 percpu_ref_put(&data->refs);
5593 percpu_ref_switch_to_atomic(&data->refs,
5596 wait_for_completion(&done);
5597 flush_work(&data->ref_work);
5604 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5605 struct io_uring_files_update *up,
5608 struct fixed_file_data *data = ctx->file_data;
5609 bool ref_switch = false;
5615 if (check_add_overflow(up->offset, nr_args, &done))
5617 if (done > ctx->nr_user_files)
5621 fds = u64_to_user_ptr(up->fds);
5623 struct fixed_file_table *table;
5627 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5631 i = array_index_nospec(up->offset, ctx->nr_user_files);
5632 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5633 index = i & IORING_FILE_TABLE_MASK;
5634 if (table->files[index]) {
5635 file = io_file_from_index(ctx, index);
5636 table->files[index] = NULL;
5637 if (io_queue_file_removal(data, file))
5647 * Don't allow io_uring instances to be registered. If
5648 * UNIX isn't enabled, then this causes a reference
5649 * cycle and this instance can never get freed. If UNIX
5650 * is enabled we'll handle it just fine, but there's
5651 * still no point in allowing a ring fd as it doesn't
5652 * support regular read/write anyway.
5654 if (file->f_op == &io_uring_fops) {
5659 table->files[index] = file;
5660 err = io_sqe_file_register(ctx, file, i);
5669 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5670 percpu_ref_put(&data->refs);
5671 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5674 return done ? done : err;
5676 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5679 struct io_uring_files_update up;
5681 if (!ctx->file_data)
5685 if (copy_from_user(&up, arg, sizeof(up)))
5690 return __io_sqe_files_update(ctx, &up, nr_args);
5693 static void io_put_work(struct io_wq_work *work)
5695 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5700 static void io_get_work(struct io_wq_work *work)
5702 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5704 refcount_inc(&req->refs);
5707 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5708 struct io_uring_params *p)
5710 struct io_wq_data data;
5711 unsigned concurrency;
5714 init_waitqueue_head(&ctx->sqo_wait);
5715 mmgrab(current->mm);
5716 ctx->sqo_mm = current->mm;
5718 if (ctx->flags & IORING_SETUP_SQPOLL) {
5720 if (!capable(CAP_SYS_ADMIN))
5723 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5724 if (!ctx->sq_thread_idle)
5725 ctx->sq_thread_idle = HZ;
5727 if (p->flags & IORING_SETUP_SQ_AFF) {
5728 int cpu = p->sq_thread_cpu;
5731 if (cpu >= nr_cpu_ids)
5733 if (!cpu_online(cpu))
5736 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5740 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5743 if (IS_ERR(ctx->sqo_thread)) {
5744 ret = PTR_ERR(ctx->sqo_thread);
5745 ctx->sqo_thread = NULL;
5748 wake_up_process(ctx->sqo_thread);
5749 } else if (p->flags & IORING_SETUP_SQ_AFF) {
5750 /* Can't have SQ_AFF without SQPOLL */
5755 data.user = ctx->user;
5756 data.get_work = io_get_work;
5757 data.put_work = io_put_work;
5759 /* Do QD, or 4 * CPUS, whatever is smallest */
5760 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5761 ctx->io_wq = io_wq_create(concurrency, &data);
5762 if (IS_ERR(ctx->io_wq)) {
5763 ret = PTR_ERR(ctx->io_wq);
5770 io_finish_async(ctx);
5771 mmdrop(ctx->sqo_mm);
5776 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
5778 atomic_long_sub(nr_pages, &user->locked_vm);
5781 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
5783 unsigned long page_limit, cur_pages, new_pages;
5785 /* Don't allow more pages than we can safely lock */
5786 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5789 cur_pages = atomic_long_read(&user->locked_vm);
5790 new_pages = cur_pages + nr_pages;
5791 if (new_pages > page_limit)
5793 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5794 new_pages) != cur_pages);
5799 static void io_mem_free(void *ptr)
5806 page = virt_to_head_page(ptr);
5807 if (put_page_testzero(page))
5808 free_compound_page(page);
5811 static void *io_mem_alloc(size_t size)
5813 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
5816 return (void *) __get_free_pages(gfp_flags, get_order(size));
5819 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
5822 struct io_rings *rings;
5823 size_t off, sq_array_size;
5825 off = struct_size(rings, cqes, cq_entries);
5826 if (off == SIZE_MAX)
5830 off = ALIGN(off, SMP_CACHE_BYTES);
5835 sq_array_size = array_size(sizeof(u32), sq_entries);
5836 if (sq_array_size == SIZE_MAX)
5839 if (check_add_overflow(off, sq_array_size, &off))
5848 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
5852 pages = (size_t)1 << get_order(
5853 rings_size(sq_entries, cq_entries, NULL));
5854 pages += (size_t)1 << get_order(
5855 array_size(sizeof(struct io_uring_sqe), sq_entries));
5860 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
5864 if (!ctx->user_bufs)
5867 for (i = 0; i < ctx->nr_user_bufs; i++) {
5868 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5870 for (j = 0; j < imu->nr_bvecs; j++)
5871 put_user_page(imu->bvec[j].bv_page);
5873 if (ctx->account_mem)
5874 io_unaccount_mem(ctx->user, imu->nr_bvecs);
5879 kfree(ctx->user_bufs);
5880 ctx->user_bufs = NULL;
5881 ctx->nr_user_bufs = 0;
5885 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
5886 void __user *arg, unsigned index)
5888 struct iovec __user *src;
5890 #ifdef CONFIG_COMPAT
5892 struct compat_iovec __user *ciovs;
5893 struct compat_iovec ciov;
5895 ciovs = (struct compat_iovec __user *) arg;
5896 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
5899 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
5900 dst->iov_len = ciov.iov_len;
5904 src = (struct iovec __user *) arg;
5905 if (copy_from_user(dst, &src[index], sizeof(*dst)))
5910 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
5913 struct vm_area_struct **vmas = NULL;
5914 struct page **pages = NULL;
5915 int i, j, got_pages = 0;
5920 if (!nr_args || nr_args > UIO_MAXIOV)
5923 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
5925 if (!ctx->user_bufs)
5928 for (i = 0; i < nr_args; i++) {
5929 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5930 unsigned long off, start, end, ubuf;
5935 ret = io_copy_iov(ctx, &iov, arg, i);
5940 * Don't impose further limits on the size and buffer
5941 * constraints here, we'll -EINVAL later when IO is
5942 * submitted if they are wrong.
5945 if (!iov.iov_base || !iov.iov_len)
5948 /* arbitrary limit, but we need something */
5949 if (iov.iov_len > SZ_1G)
5952 ubuf = (unsigned long) iov.iov_base;
5953 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
5954 start = ubuf >> PAGE_SHIFT;
5955 nr_pages = end - start;
5957 if (ctx->account_mem) {
5958 ret = io_account_mem(ctx->user, nr_pages);
5964 if (!pages || nr_pages > got_pages) {
5967 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
5969 vmas = kvmalloc_array(nr_pages,
5970 sizeof(struct vm_area_struct *),
5972 if (!pages || !vmas) {
5974 if (ctx->account_mem)
5975 io_unaccount_mem(ctx->user, nr_pages);
5978 got_pages = nr_pages;
5981 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
5985 if (ctx->account_mem)
5986 io_unaccount_mem(ctx->user, nr_pages);
5991 down_read(¤t->mm->mmap_sem);
5992 pret = get_user_pages(ubuf, nr_pages,
5993 FOLL_WRITE | FOLL_LONGTERM,
5995 if (pret == nr_pages) {
5996 /* don't support file backed memory */
5997 for (j = 0; j < nr_pages; j++) {
5998 struct vm_area_struct *vma = vmas[j];
6001 !is_file_hugepages(vma->vm_file)) {
6007 ret = pret < 0 ? pret : -EFAULT;
6009 up_read(¤t->mm->mmap_sem);
6012 * if we did partial map, or found file backed vmas,
6013 * release any pages we did get
6016 put_user_pages(pages, pret);
6017 if (ctx->account_mem)
6018 io_unaccount_mem(ctx->user, nr_pages);
6023 off = ubuf & ~PAGE_MASK;
6025 for (j = 0; j < nr_pages; j++) {
6028 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6029 imu->bvec[j].bv_page = pages[j];
6030 imu->bvec[j].bv_len = vec_len;
6031 imu->bvec[j].bv_offset = off;
6035 /* store original address for later verification */
6037 imu->len = iov.iov_len;
6038 imu->nr_bvecs = nr_pages;
6040 ctx->nr_user_bufs++;
6048 io_sqe_buffer_unregister(ctx);
6052 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6054 __s32 __user *fds = arg;
6060 if (copy_from_user(&fd, fds, sizeof(*fds)))
6063 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6064 if (IS_ERR(ctx->cq_ev_fd)) {
6065 int ret = PTR_ERR(ctx->cq_ev_fd);
6066 ctx->cq_ev_fd = NULL;
6073 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6075 if (ctx->cq_ev_fd) {
6076 eventfd_ctx_put(ctx->cq_ev_fd);
6077 ctx->cq_ev_fd = NULL;
6084 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6086 io_finish_async(ctx);
6088 mmdrop(ctx->sqo_mm);
6090 io_iopoll_reap_events(ctx);
6091 io_sqe_buffer_unregister(ctx);
6092 io_sqe_files_unregister(ctx);
6093 io_eventfd_unregister(ctx);
6095 #if defined(CONFIG_UNIX)
6096 if (ctx->ring_sock) {
6097 ctx->ring_sock->file = NULL; /* so that iput() is called */
6098 sock_release(ctx->ring_sock);
6102 io_mem_free(ctx->rings);
6103 io_mem_free(ctx->sq_sqes);
6105 percpu_ref_exit(&ctx->refs);
6106 if (ctx->account_mem)
6107 io_unaccount_mem(ctx->user,
6108 ring_pages(ctx->sq_entries, ctx->cq_entries));
6109 free_uid(ctx->user);
6110 put_cred(ctx->creds);
6111 kfree(ctx->completions);
6112 kfree(ctx->cancel_hash);
6113 kmem_cache_free(req_cachep, ctx->fallback_req);
6117 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6119 struct io_ring_ctx *ctx = file->private_data;
6122 poll_wait(file, &ctx->cq_wait, wait);
6124 * synchronizes with barrier from wq_has_sleeper call in
6128 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6129 ctx->rings->sq_ring_entries)
6130 mask |= EPOLLOUT | EPOLLWRNORM;
6131 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
6132 mask |= EPOLLIN | EPOLLRDNORM;
6137 static int io_uring_fasync(int fd, struct file *file, int on)
6139 struct io_ring_ctx *ctx = file->private_data;
6141 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6144 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6146 mutex_lock(&ctx->uring_lock);
6147 percpu_ref_kill(&ctx->refs);
6148 mutex_unlock(&ctx->uring_lock);
6150 io_kill_timeouts(ctx);
6151 io_poll_remove_all(ctx);
6154 io_wq_cancel_all(ctx->io_wq);
6156 io_iopoll_reap_events(ctx);
6157 /* if we failed setting up the ctx, we might not have any rings */
6159 io_cqring_overflow_flush(ctx, true);
6160 wait_for_completion(&ctx->completions[0]);
6161 io_ring_ctx_free(ctx);
6164 static int io_uring_release(struct inode *inode, struct file *file)
6166 struct io_ring_ctx *ctx = file->private_data;
6168 file->private_data = NULL;
6169 io_ring_ctx_wait_and_kill(ctx);
6173 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6174 struct files_struct *files)
6176 struct io_kiocb *req;
6179 while (!list_empty_careful(&ctx->inflight_list)) {
6180 struct io_kiocb *cancel_req = NULL;
6182 spin_lock_irq(&ctx->inflight_lock);
6183 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
6184 if (req->work.files != files)
6186 /* req is being completed, ignore */
6187 if (!refcount_inc_not_zero(&req->refs))
6193 prepare_to_wait(&ctx->inflight_wait, &wait,
6194 TASK_UNINTERRUPTIBLE);
6195 spin_unlock_irq(&ctx->inflight_lock);
6197 /* We need to keep going until we don't find a matching req */
6201 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6202 io_put_req(cancel_req);
6205 finish_wait(&ctx->inflight_wait, &wait);
6208 static int io_uring_flush(struct file *file, void *data)
6210 struct io_ring_ctx *ctx = file->private_data;
6212 io_uring_cancel_files(ctx, data);
6213 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
6214 io_cqring_overflow_flush(ctx, true);
6215 io_wq_cancel_all(ctx->io_wq);
6220 static void *io_uring_validate_mmap_request(struct file *file,
6221 loff_t pgoff, size_t sz)
6223 struct io_ring_ctx *ctx = file->private_data;
6224 loff_t offset = pgoff << PAGE_SHIFT;
6229 case IORING_OFF_SQ_RING:
6230 case IORING_OFF_CQ_RING:
6233 case IORING_OFF_SQES:
6237 return ERR_PTR(-EINVAL);
6240 page = virt_to_head_page(ptr);
6241 if (sz > page_size(page))
6242 return ERR_PTR(-EINVAL);
6249 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6251 size_t sz = vma->vm_end - vma->vm_start;
6255 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6257 return PTR_ERR(ptr);
6259 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6260 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6263 #else /* !CONFIG_MMU */
6265 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6267 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6270 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6272 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6275 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6276 unsigned long addr, unsigned long len,
6277 unsigned long pgoff, unsigned long flags)
6281 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6283 return PTR_ERR(ptr);
6285 return (unsigned long) ptr;
6288 #endif /* !CONFIG_MMU */
6290 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6291 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6294 struct io_ring_ctx *ctx;
6299 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
6307 if (f.file->f_op != &io_uring_fops)
6311 ctx = f.file->private_data;
6312 if (!percpu_ref_tryget(&ctx->refs))
6316 * For SQ polling, the thread will do all submissions and completions.
6317 * Just return the requested submit count, and wake the thread if
6321 if (ctx->flags & IORING_SETUP_SQPOLL) {
6322 if (!list_empty_careful(&ctx->cq_overflow_list))
6323 io_cqring_overflow_flush(ctx, false);
6324 if (flags & IORING_ENTER_SQ_WAKEUP)
6325 wake_up(&ctx->sqo_wait);
6326 submitted = to_submit;
6327 } else if (to_submit) {
6328 struct mm_struct *cur_mm;
6330 if (current->mm != ctx->sqo_mm ||
6331 current_cred() != ctx->creds) {
6336 mutex_lock(&ctx->uring_lock);
6337 /* already have mm, so io_submit_sqes() won't try to grab it */
6338 cur_mm = ctx->sqo_mm;
6339 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6341 mutex_unlock(&ctx->uring_lock);
6343 if (submitted != to_submit)
6346 if (flags & IORING_ENTER_GETEVENTS) {
6347 unsigned nr_events = 0;
6349 min_complete = min(min_complete, ctx->cq_entries);
6351 if (ctx->flags & IORING_SETUP_IOPOLL) {
6352 ret = io_iopoll_check(ctx, &nr_events, min_complete);
6354 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6359 percpu_ref_put(&ctx->refs);
6362 return submitted ? submitted : ret;
6365 static const struct file_operations io_uring_fops = {
6366 .release = io_uring_release,
6367 .flush = io_uring_flush,
6368 .mmap = io_uring_mmap,
6370 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6371 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6373 .poll = io_uring_poll,
6374 .fasync = io_uring_fasync,
6377 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6378 struct io_uring_params *p)
6380 struct io_rings *rings;
6381 size_t size, sq_array_offset;
6383 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6384 if (size == SIZE_MAX)
6387 rings = io_mem_alloc(size);
6392 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6393 rings->sq_ring_mask = p->sq_entries - 1;
6394 rings->cq_ring_mask = p->cq_entries - 1;
6395 rings->sq_ring_entries = p->sq_entries;
6396 rings->cq_ring_entries = p->cq_entries;
6397 ctx->sq_mask = rings->sq_ring_mask;
6398 ctx->cq_mask = rings->cq_ring_mask;
6399 ctx->sq_entries = rings->sq_ring_entries;
6400 ctx->cq_entries = rings->cq_ring_entries;
6402 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6403 if (size == SIZE_MAX) {
6404 io_mem_free(ctx->rings);
6409 ctx->sq_sqes = io_mem_alloc(size);
6410 if (!ctx->sq_sqes) {
6411 io_mem_free(ctx->rings);
6420 * Allocate an anonymous fd, this is what constitutes the application
6421 * visible backing of an io_uring instance. The application mmaps this
6422 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6423 * we have to tie this fd to a socket for file garbage collection purposes.
6425 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6430 #if defined(CONFIG_UNIX)
6431 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6437 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6441 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6442 O_RDWR | O_CLOEXEC);
6445 ret = PTR_ERR(file);
6449 #if defined(CONFIG_UNIX)
6450 ctx->ring_sock->file = file;
6452 fd_install(ret, file);
6455 #if defined(CONFIG_UNIX)
6456 sock_release(ctx->ring_sock);
6457 ctx->ring_sock = NULL;
6462 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6464 struct user_struct *user = NULL;
6465 struct io_ring_ctx *ctx;
6471 if (entries > IORING_MAX_ENTRIES) {
6472 if (!(p->flags & IORING_SETUP_CLAMP))
6474 entries = IORING_MAX_ENTRIES;
6478 * Use twice as many entries for the CQ ring. It's possible for the
6479 * application to drive a higher depth than the size of the SQ ring,
6480 * since the sqes are only used at submission time. This allows for
6481 * some flexibility in overcommitting a bit. If the application has
6482 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6483 * of CQ ring entries manually.
6485 p->sq_entries = roundup_pow_of_two(entries);
6486 if (p->flags & IORING_SETUP_CQSIZE) {
6488 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6489 * to a power-of-two, if it isn't already. We do NOT impose
6490 * any cq vs sq ring sizing.
6492 if (p->cq_entries < p->sq_entries)
6494 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6495 if (!(p->flags & IORING_SETUP_CLAMP))
6497 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6499 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6501 p->cq_entries = 2 * p->sq_entries;
6504 user = get_uid(current_user());
6505 account_mem = !capable(CAP_IPC_LOCK);
6508 ret = io_account_mem(user,
6509 ring_pages(p->sq_entries, p->cq_entries));
6516 ctx = io_ring_ctx_alloc(p);
6519 io_unaccount_mem(user, ring_pages(p->sq_entries,
6524 ctx->compat = in_compat_syscall();
6525 ctx->account_mem = account_mem;
6527 ctx->creds = get_current_cred();
6529 ret = io_allocate_scq_urings(ctx, p);
6533 ret = io_sq_offload_start(ctx, p);
6537 memset(&p->sq_off, 0, sizeof(p->sq_off));
6538 p->sq_off.head = offsetof(struct io_rings, sq.head);
6539 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6540 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6541 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6542 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6543 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6544 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6546 memset(&p->cq_off, 0, sizeof(p->cq_off));
6547 p->cq_off.head = offsetof(struct io_rings, cq.head);
6548 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6549 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6550 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6551 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6552 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6555 * Install ring fd as the very last thing, so we don't risk someone
6556 * having closed it before we finish setup
6558 ret = io_uring_get_fd(ctx);
6562 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6563 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6564 IORING_FEAT_CUR_PERSONALITY;
6565 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6568 io_ring_ctx_wait_and_kill(ctx);
6573 * Sets up an aio uring context, and returns the fd. Applications asks for a
6574 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6575 * params structure passed in.
6577 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6579 struct io_uring_params p;
6583 if (copy_from_user(&p, params, sizeof(p)))
6585 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6590 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6591 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6592 IORING_SETUP_CLAMP))
6595 ret = io_uring_create(entries, &p);
6599 if (copy_to_user(params, &p, sizeof(p)))
6605 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6606 struct io_uring_params __user *, params)
6608 return io_uring_setup(entries, params);
6611 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6613 struct io_uring_probe *p;
6617 size = struct_size(p, ops, nr_args);
6618 if (size == SIZE_MAX)
6620 p = kzalloc(size, GFP_KERNEL);
6625 if (copy_from_user(p, arg, size))
6628 if (memchr_inv(p, 0, size))
6631 p->last_op = IORING_OP_LAST - 1;
6632 if (nr_args > IORING_OP_LAST)
6633 nr_args = IORING_OP_LAST;
6635 for (i = 0; i < nr_args; i++) {
6637 if (!io_op_defs[i].not_supported)
6638 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6643 if (copy_to_user(arg, p, size))
6650 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6651 void __user *arg, unsigned nr_args)
6652 __releases(ctx->uring_lock)
6653 __acquires(ctx->uring_lock)
6658 * We're inside the ring mutex, if the ref is already dying, then
6659 * someone else killed the ctx or is already going through
6660 * io_uring_register().
6662 if (percpu_ref_is_dying(&ctx->refs))
6665 if (opcode != IORING_UNREGISTER_FILES &&
6666 opcode != IORING_REGISTER_FILES_UPDATE &&
6667 opcode != IORING_REGISTER_PROBE) {
6668 percpu_ref_kill(&ctx->refs);
6671 * Drop uring mutex before waiting for references to exit. If
6672 * another thread is currently inside io_uring_enter() it might
6673 * need to grab the uring_lock to make progress. If we hold it
6674 * here across the drain wait, then we can deadlock. It's safe
6675 * to drop the mutex here, since no new references will come in
6676 * after we've killed the percpu ref.
6678 mutex_unlock(&ctx->uring_lock);
6679 ret = wait_for_completion_interruptible(&ctx->completions[0]);
6680 mutex_lock(&ctx->uring_lock);
6682 percpu_ref_resurrect(&ctx->refs);
6689 case IORING_REGISTER_BUFFERS:
6690 ret = io_sqe_buffer_register(ctx, arg, nr_args);
6692 case IORING_UNREGISTER_BUFFERS:
6696 ret = io_sqe_buffer_unregister(ctx);
6698 case IORING_REGISTER_FILES:
6699 ret = io_sqe_files_register(ctx, arg, nr_args);
6701 case IORING_UNREGISTER_FILES:
6705 ret = io_sqe_files_unregister(ctx);
6707 case IORING_REGISTER_FILES_UPDATE:
6708 ret = io_sqe_files_update(ctx, arg, nr_args);
6710 case IORING_REGISTER_EVENTFD:
6711 case IORING_REGISTER_EVENTFD_ASYNC:
6715 ret = io_eventfd_register(ctx, arg);
6718 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
6719 ctx->eventfd_async = 1;
6721 ctx->eventfd_async = 0;
6723 case IORING_UNREGISTER_EVENTFD:
6727 ret = io_eventfd_unregister(ctx);
6729 case IORING_REGISTER_PROBE:
6731 if (!arg || nr_args > 256)
6733 ret = io_probe(ctx, arg, nr_args);
6741 if (opcode != IORING_UNREGISTER_FILES &&
6742 opcode != IORING_REGISTER_FILES_UPDATE &&
6743 opcode != IORING_REGISTER_PROBE) {
6744 /* bring the ctx back to life */
6745 percpu_ref_reinit(&ctx->refs);
6747 reinit_completion(&ctx->completions[0]);
6752 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
6753 void __user *, arg, unsigned int, nr_args)
6755 struct io_ring_ctx *ctx;
6764 if (f.file->f_op != &io_uring_fops)
6767 ctx = f.file->private_data;
6769 mutex_lock(&ctx->uring_lock);
6770 ret = __io_uring_register(ctx, opcode, arg, nr_args);
6771 mutex_unlock(&ctx->uring_lock);
6772 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
6773 ctx->cq_ev_fd != NULL, ret);
6779 static int __init io_uring_init(void)
6781 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
6782 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
6785 __initcall(io_uring_init);