1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
50 #include <linux/sched/signal.h>
52 #include <linux/file.h>
53 #include <linux/fdtable.h>
55 #include <linux/mman.h>
56 #include <linux/mmu_context.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/kthread.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
79 #include <uapi/linux/io_uring.h>
84 #define IORING_MAX_ENTRIES 32768
85 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
88 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
90 #define IORING_FILE_TABLE_SHIFT 9
91 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
92 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
93 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
96 u32 head ____cacheline_aligned_in_smp;
97 u32 tail ____cacheline_aligned_in_smp;
101 * This data is shared with the application through the mmap at offsets
102 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
104 * The offsets to the member fields are published through struct
105 * io_sqring_offsets when calling io_uring_setup.
109 * Head and tail offsets into the ring; the offsets need to be
110 * masked to get valid indices.
112 * The kernel controls head of the sq ring and the tail of the cq ring,
113 * and the application controls tail of the sq ring and the head of the
116 struct io_uring sq, cq;
118 * Bitmasks to apply to head and tail offsets (constant, equals
121 u32 sq_ring_mask, cq_ring_mask;
122 /* Ring sizes (constant, power of 2) */
123 u32 sq_ring_entries, cq_ring_entries;
125 * Number of invalid entries dropped by the kernel due to
126 * invalid index stored in array
128 * Written by the kernel, shouldn't be modified by the
129 * application (i.e. get number of "new events" by comparing to
132 * After a new SQ head value was read by the application this
133 * counter includes all submissions that were dropped reaching
134 * the new SQ head (and possibly more).
140 * Written by the kernel, shouldn't be modified by the
143 * The application needs a full memory barrier before checking
144 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
148 * Number of completion events lost because the queue was full;
149 * this should be avoided by the application by making sure
150 * there are not more requests pending than there is space in
151 * the completion queue.
153 * Written by the kernel, shouldn't be modified by the
154 * application (i.e. get number of "new events" by comparing to
157 * As completion events come in out of order this counter is not
158 * ordered with any other data.
162 * Ring buffer of completion events.
164 * The kernel writes completion events fresh every time they are
165 * produced, so the application is allowed to modify pending
168 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
171 struct io_mapped_ubuf {
174 struct bio_vec *bvec;
175 unsigned int nr_bvecs;
178 struct fixed_file_table {
186 struct fixed_file_data {
187 struct fixed_file_table *table;
188 struct io_ring_ctx *ctx;
190 struct percpu_ref refs;
191 struct llist_head put_llist;
193 struct work_struct ref_work;
194 struct completion done;
199 struct percpu_ref refs;
200 } ____cacheline_aligned_in_smp;
206 bool cq_overflow_flushed;
210 * Ring buffer of indices into array of io_uring_sqe, which is
211 * mmapped by the application using the IORING_OFF_SQES offset.
213 * This indirection could e.g. be used to assign fixed
214 * io_uring_sqe entries to operations and only submit them to
215 * the queue when needed.
217 * The kernel modifies neither the indices array nor the entries
221 unsigned cached_sq_head;
224 unsigned sq_thread_idle;
225 unsigned cached_sq_dropped;
226 atomic_t cached_cq_overflow;
227 unsigned long sq_check_overflow;
229 struct list_head defer_list;
230 struct list_head timeout_list;
231 struct list_head cq_overflow_list;
233 wait_queue_head_t inflight_wait;
234 struct io_uring_sqe *sq_sqes;
235 } ____cacheline_aligned_in_smp;
237 struct io_rings *rings;
241 struct task_struct *sqo_thread; /* if using sq thread polling */
242 struct mm_struct *sqo_mm;
243 wait_queue_head_t sqo_wait;
246 * If used, fixed file set. Writers must ensure that ->refs is dead,
247 * readers must ensure that ->refs is alive as long as the file* is
248 * used. Only updated through io_uring_register(2).
250 struct fixed_file_data *file_data;
251 unsigned nr_user_files;
253 /* if used, fixed mapped user buffers */
254 unsigned nr_user_bufs;
255 struct io_mapped_ubuf *user_bufs;
257 struct user_struct *user;
259 const struct cred *creds;
261 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
262 struct completion *completions;
264 /* if all else fails... */
265 struct io_kiocb *fallback_req;
267 #if defined(CONFIG_UNIX)
268 struct socket *ring_sock;
272 unsigned cached_cq_tail;
275 atomic_t cq_timeouts;
276 unsigned long cq_check_overflow;
277 struct wait_queue_head cq_wait;
278 struct fasync_struct *cq_fasync;
279 struct eventfd_ctx *cq_ev_fd;
280 } ____cacheline_aligned_in_smp;
283 struct mutex uring_lock;
284 wait_queue_head_t wait;
285 } ____cacheline_aligned_in_smp;
288 spinlock_t completion_lock;
289 struct llist_head poll_llist;
292 * ->poll_list is protected by the ctx->uring_lock for
293 * io_uring instances that don't use IORING_SETUP_SQPOLL.
294 * For SQPOLL, only the single threaded io_sq_thread() will
295 * manipulate the list, hence no extra locking is needed there.
297 struct list_head poll_list;
298 struct hlist_head *cancel_hash;
299 unsigned cancel_hash_bits;
300 bool poll_multi_file;
302 spinlock_t inflight_lock;
303 struct list_head inflight_list;
304 } ____cacheline_aligned_in_smp;
308 * First field must be the file pointer in all the
309 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
311 struct io_poll_iocb {
314 struct wait_queue_head *head;
320 struct wait_queue_entry wait;
325 struct file *put_file;
329 struct io_timeout_data {
330 struct io_kiocb *req;
331 struct hrtimer timer;
332 struct timespec64 ts;
333 enum hrtimer_mode mode;
339 struct sockaddr __user *addr;
340 int __user *addr_len;
365 /* NOTE: kiocb has the file as the first member, so don't do it here */
373 struct sockaddr __user *addr;
379 struct user_msghdr __user *msg;
390 const char __user *fname;
391 struct filename *filename;
392 struct statx __user *buffer;
396 struct io_files_update {
403 struct io_async_connect {
404 struct sockaddr_storage address;
407 struct io_async_msghdr {
408 struct iovec fast_iov[UIO_FASTIOV];
410 struct sockaddr __user *uaddr;
415 struct iovec fast_iov[UIO_FASTIOV];
421 struct io_async_open {
422 struct filename *filename;
425 struct io_async_ctx {
427 struct io_async_rw rw;
428 struct io_async_msghdr msg;
429 struct io_async_connect connect;
430 struct io_timeout_data timeout;
431 struct io_async_open open;
436 * NOTE! Each of the iocb union members has the file pointer
437 * as the first entry in their struct definition. So you can
438 * access the file pointer through any of the sub-structs,
439 * or directly as just 'ki_filp' in this struct.
445 struct io_poll_iocb poll;
446 struct io_accept accept;
448 struct io_cancel cancel;
449 struct io_timeout timeout;
450 struct io_connect connect;
451 struct io_sr_msg sr_msg;
453 struct io_close close;
454 struct io_files_update files_update;
457 struct io_async_ctx *io;
460 * ring_file is only used in the submission path, and
461 * llist_node is only used for poll deferred completions
463 struct file *ring_file;
464 struct llist_node llist_node;
469 bool needs_fixed_file;
472 struct io_ring_ctx *ctx;
474 struct list_head list;
475 struct hlist_node hash_node;
477 struct list_head link_list;
480 #define REQ_F_NOWAIT 1 /* must not punt to workers */
481 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
482 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
483 #define REQ_F_LINK_NEXT 8 /* already grabbed next link */
484 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
485 #define REQ_F_IO_DRAINED 32 /* drain done */
486 #define REQ_F_LINK 64 /* linked sqes */
487 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
488 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
489 #define REQ_F_DRAIN_LINK 512 /* link should be fully drained */
490 #define REQ_F_TIMEOUT 1024 /* timeout request */
491 #define REQ_F_ISREG 2048 /* regular file */
492 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
493 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
494 #define REQ_F_INFLIGHT 16384 /* on inflight list */
495 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
496 #define REQ_F_HARDLINK 65536 /* doesn't sever on completion < 0 */
497 #define REQ_F_FORCE_ASYNC 131072 /* IOSQE_ASYNC */
502 struct list_head inflight_entry;
504 struct io_wq_work work;
507 #define IO_PLUG_THRESHOLD 2
508 #define IO_IOPOLL_BATCH 8
510 struct io_submit_state {
511 struct blk_plug plug;
514 * io_kiocb alloc cache
516 void *reqs[IO_IOPOLL_BATCH];
517 unsigned int free_reqs;
518 unsigned int cur_req;
521 * File reference cache
525 unsigned int has_refs;
526 unsigned int used_refs;
527 unsigned int ios_left;
531 /* needs req->io allocated for deferral/async */
532 unsigned async_ctx : 1;
533 /* needs current->mm setup, does mm access */
534 unsigned needs_mm : 1;
535 /* needs req->file assigned */
536 unsigned needs_file : 1;
537 /* needs req->file assigned IFF fd is >= 0 */
538 unsigned fd_non_neg : 1;
539 /* hash wq insertion if file is a regular file */
540 unsigned hash_reg_file : 1;
541 /* unbound wq insertion if file is a non-regular file */
542 unsigned unbound_nonreg_file : 1;
545 static const struct io_op_def io_op_defs[] = {
550 /* IORING_OP_READV */
554 .unbound_nonreg_file = 1,
557 /* IORING_OP_WRITEV */
562 .unbound_nonreg_file = 1,
565 /* IORING_OP_FSYNC */
569 /* IORING_OP_READ_FIXED */
571 .unbound_nonreg_file = 1,
574 /* IORING_OP_WRITE_FIXED */
577 .unbound_nonreg_file = 1,
580 /* IORING_OP_POLL_ADD */
582 .unbound_nonreg_file = 1,
585 /* IORING_OP_POLL_REMOVE */
588 /* IORING_OP_SYNC_FILE_RANGE */
592 /* IORING_OP_SENDMSG */
596 .unbound_nonreg_file = 1,
599 /* IORING_OP_RECVMSG */
603 .unbound_nonreg_file = 1,
606 /* IORING_OP_TIMEOUT */
611 /* IORING_OP_TIMEOUT_REMOVE */
614 /* IORING_OP_ACCEPT */
617 .unbound_nonreg_file = 1,
620 /* IORING_OP_ASYNC_CANCEL */
623 /* IORING_OP_LINK_TIMEOUT */
628 /* IORING_OP_CONNECT */
632 .unbound_nonreg_file = 1,
635 /* IORING_OP_FALLOCATE */
639 /* IORING_OP_OPENAT */
644 /* IORING_OP_CLOSE */
648 /* IORING_OP_FILES_UPDATE */
652 /* IORING_OP_STATX */
659 static void io_wq_submit_work(struct io_wq_work **workptr);
660 static void io_cqring_fill_event(struct io_kiocb *req, long res);
661 static void io_put_req(struct io_kiocb *req);
662 static void __io_double_put_req(struct io_kiocb *req);
663 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
664 static void io_queue_linked_timeout(struct io_kiocb *req);
665 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
666 struct io_uring_files_update *ip,
669 static struct kmem_cache *req_cachep;
671 static const struct file_operations io_uring_fops;
673 struct sock *io_uring_get_socket(struct file *file)
675 #if defined(CONFIG_UNIX)
676 if (file->f_op == &io_uring_fops) {
677 struct io_ring_ctx *ctx = file->private_data;
679 return ctx->ring_sock->sk;
684 EXPORT_SYMBOL(io_uring_get_socket);
686 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
688 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
690 complete(&ctx->completions[0]);
693 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
695 struct io_ring_ctx *ctx;
698 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
702 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
703 if (!ctx->fallback_req)
706 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
707 if (!ctx->completions)
711 * Use 5 bits less than the max cq entries, that should give us around
712 * 32 entries per hash list if totally full and uniformly spread.
714 hash_bits = ilog2(p->cq_entries);
718 ctx->cancel_hash_bits = hash_bits;
719 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
721 if (!ctx->cancel_hash)
723 __hash_init(ctx->cancel_hash, 1U << hash_bits);
725 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
726 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
729 ctx->flags = p->flags;
730 init_waitqueue_head(&ctx->cq_wait);
731 INIT_LIST_HEAD(&ctx->cq_overflow_list);
732 init_completion(&ctx->completions[0]);
733 init_completion(&ctx->completions[1]);
734 mutex_init(&ctx->uring_lock);
735 init_waitqueue_head(&ctx->wait);
736 spin_lock_init(&ctx->completion_lock);
737 init_llist_head(&ctx->poll_llist);
738 INIT_LIST_HEAD(&ctx->poll_list);
739 INIT_LIST_HEAD(&ctx->defer_list);
740 INIT_LIST_HEAD(&ctx->timeout_list);
741 init_waitqueue_head(&ctx->inflight_wait);
742 spin_lock_init(&ctx->inflight_lock);
743 INIT_LIST_HEAD(&ctx->inflight_list);
746 if (ctx->fallback_req)
747 kmem_cache_free(req_cachep, ctx->fallback_req);
748 kfree(ctx->completions);
749 kfree(ctx->cancel_hash);
754 static inline bool __req_need_defer(struct io_kiocb *req)
756 struct io_ring_ctx *ctx = req->ctx;
758 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
759 + atomic_read(&ctx->cached_cq_overflow);
762 static inline bool req_need_defer(struct io_kiocb *req)
764 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
765 return __req_need_defer(req);
770 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
772 struct io_kiocb *req;
774 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
775 if (req && !req_need_defer(req)) {
776 list_del_init(&req->list);
783 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
785 struct io_kiocb *req;
787 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
789 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
791 if (!__req_need_defer(req)) {
792 list_del_init(&req->list);
800 static void __io_commit_cqring(struct io_ring_ctx *ctx)
802 struct io_rings *rings = ctx->rings;
804 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
805 /* order cqe stores with ring update */
806 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
808 if (wq_has_sleeper(&ctx->cq_wait)) {
809 wake_up_interruptible(&ctx->cq_wait);
810 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
815 static inline bool io_prep_async_work(struct io_kiocb *req,
816 struct io_kiocb **link)
818 const struct io_op_def *def = &io_op_defs[req->opcode];
819 bool do_hashed = false;
821 if (req->flags & REQ_F_ISREG) {
822 if (def->hash_reg_file)
825 if (def->unbound_nonreg_file)
826 req->work.flags |= IO_WQ_WORK_UNBOUND;
829 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
831 *link = io_prep_linked_timeout(req);
835 static inline void io_queue_async_work(struct io_kiocb *req)
837 struct io_ring_ctx *ctx = req->ctx;
838 struct io_kiocb *link;
841 do_hashed = io_prep_async_work(req, &link);
843 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
846 io_wq_enqueue(ctx->io_wq, &req->work);
848 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
849 file_inode(req->file));
853 io_queue_linked_timeout(link);
856 static void io_kill_timeout(struct io_kiocb *req)
860 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
862 atomic_inc(&req->ctx->cq_timeouts);
863 list_del_init(&req->list);
864 io_cqring_fill_event(req, 0);
869 static void io_kill_timeouts(struct io_ring_ctx *ctx)
871 struct io_kiocb *req, *tmp;
873 spin_lock_irq(&ctx->completion_lock);
874 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
875 io_kill_timeout(req);
876 spin_unlock_irq(&ctx->completion_lock);
879 static void io_commit_cqring(struct io_ring_ctx *ctx)
881 struct io_kiocb *req;
883 while ((req = io_get_timeout_req(ctx)) != NULL)
884 io_kill_timeout(req);
886 __io_commit_cqring(ctx);
888 while ((req = io_get_deferred_req(ctx)) != NULL) {
889 req->flags |= REQ_F_IO_DRAINED;
890 io_queue_async_work(req);
894 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
896 struct io_rings *rings = ctx->rings;
899 tail = ctx->cached_cq_tail;
901 * writes to the cq entry need to come after reading head; the
902 * control dependency is enough as we're using WRITE_ONCE to
905 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
908 ctx->cached_cq_tail++;
909 return &rings->cqes[tail & ctx->cq_mask];
912 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
914 if (waitqueue_active(&ctx->wait))
916 if (waitqueue_active(&ctx->sqo_wait))
917 wake_up(&ctx->sqo_wait);
919 eventfd_signal(ctx->cq_ev_fd, 1);
922 /* Returns true if there are no backlogged entries after the flush */
923 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
925 struct io_rings *rings = ctx->rings;
926 struct io_uring_cqe *cqe;
927 struct io_kiocb *req;
932 if (list_empty_careful(&ctx->cq_overflow_list))
934 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
935 rings->cq_ring_entries))
939 spin_lock_irqsave(&ctx->completion_lock, flags);
941 /* if force is set, the ring is going away. always drop after that */
943 ctx->cq_overflow_flushed = true;
946 while (!list_empty(&ctx->cq_overflow_list)) {
947 cqe = io_get_cqring(ctx);
951 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
953 list_move(&req->list, &list);
955 WRITE_ONCE(cqe->user_data, req->user_data);
956 WRITE_ONCE(cqe->res, req->result);
957 WRITE_ONCE(cqe->flags, 0);
959 WRITE_ONCE(ctx->rings->cq_overflow,
960 atomic_inc_return(&ctx->cached_cq_overflow));
964 io_commit_cqring(ctx);
966 clear_bit(0, &ctx->sq_check_overflow);
967 clear_bit(0, &ctx->cq_check_overflow);
969 spin_unlock_irqrestore(&ctx->completion_lock, flags);
970 io_cqring_ev_posted(ctx);
972 while (!list_empty(&list)) {
973 req = list_first_entry(&list, struct io_kiocb, list);
974 list_del(&req->list);
981 static void io_cqring_fill_event(struct io_kiocb *req, long res)
983 struct io_ring_ctx *ctx = req->ctx;
984 struct io_uring_cqe *cqe;
986 trace_io_uring_complete(ctx, req->user_data, res);
989 * If we can't get a cq entry, userspace overflowed the
990 * submission (by quite a lot). Increment the overflow count in
993 cqe = io_get_cqring(ctx);
995 WRITE_ONCE(cqe->user_data, req->user_data);
996 WRITE_ONCE(cqe->res, res);
997 WRITE_ONCE(cqe->flags, 0);
998 } else if (ctx->cq_overflow_flushed) {
999 WRITE_ONCE(ctx->rings->cq_overflow,
1000 atomic_inc_return(&ctx->cached_cq_overflow));
1002 if (list_empty(&ctx->cq_overflow_list)) {
1003 set_bit(0, &ctx->sq_check_overflow);
1004 set_bit(0, &ctx->cq_check_overflow);
1006 refcount_inc(&req->refs);
1008 list_add_tail(&req->list, &ctx->cq_overflow_list);
1012 static void io_cqring_add_event(struct io_kiocb *req, long res)
1014 struct io_ring_ctx *ctx = req->ctx;
1015 unsigned long flags;
1017 spin_lock_irqsave(&ctx->completion_lock, flags);
1018 io_cqring_fill_event(req, res);
1019 io_commit_cqring(ctx);
1020 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1022 io_cqring_ev_posted(ctx);
1025 static inline bool io_is_fallback_req(struct io_kiocb *req)
1027 return req == (struct io_kiocb *)
1028 ((unsigned long) req->ctx->fallback_req & ~1UL);
1031 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1033 struct io_kiocb *req;
1035 req = ctx->fallback_req;
1036 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1042 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1043 struct io_submit_state *state)
1045 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1046 struct io_kiocb *req;
1048 if (!percpu_ref_tryget(&ctx->refs))
1052 req = kmem_cache_alloc(req_cachep, gfp);
1055 } else if (!state->free_reqs) {
1059 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1060 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1063 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1064 * retry single alloc to be on the safe side.
1066 if (unlikely(ret <= 0)) {
1067 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1068 if (!state->reqs[0])
1072 state->free_reqs = ret - 1;
1074 req = state->reqs[0];
1076 req = state->reqs[state->cur_req];
1083 req->ring_file = NULL;
1087 /* one is dropped after submission, the other at completion */
1088 refcount_set(&req->refs, 2);
1090 INIT_IO_WORK(&req->work, io_wq_submit_work);
1093 req = io_get_fallback_req(ctx);
1096 percpu_ref_put(&ctx->refs);
1100 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
1103 kmem_cache_free_bulk(req_cachep, *nr, reqs);
1104 percpu_ref_put_many(&ctx->refs, *nr);
1105 percpu_ref_put_many(&ctx->file_data->refs, *nr);
1110 static void __io_free_req(struct io_kiocb *req)
1112 struct io_ring_ctx *ctx = req->ctx;
1117 if (req->flags & REQ_F_FIXED_FILE)
1118 percpu_ref_put(&ctx->file_data->refs);
1122 if (req->flags & REQ_F_INFLIGHT) {
1123 unsigned long flags;
1125 spin_lock_irqsave(&ctx->inflight_lock, flags);
1126 list_del(&req->inflight_entry);
1127 if (waitqueue_active(&ctx->inflight_wait))
1128 wake_up(&ctx->inflight_wait);
1129 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1131 percpu_ref_put(&ctx->refs);
1132 if (likely(!io_is_fallback_req(req)))
1133 kmem_cache_free(req_cachep, req);
1135 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
1138 static bool io_link_cancel_timeout(struct io_kiocb *req)
1140 struct io_ring_ctx *ctx = req->ctx;
1143 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1145 io_cqring_fill_event(req, -ECANCELED);
1146 io_commit_cqring(ctx);
1147 req->flags &= ~REQ_F_LINK;
1155 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1157 struct io_ring_ctx *ctx = req->ctx;
1158 bool wake_ev = false;
1160 /* Already got next link */
1161 if (req->flags & REQ_F_LINK_NEXT)
1165 * The list should never be empty when we are called here. But could
1166 * potentially happen if the chain is messed up, check to be on the
1169 while (!list_empty(&req->link_list)) {
1170 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1171 struct io_kiocb, link_list);
1173 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1174 (nxt->flags & REQ_F_TIMEOUT))) {
1175 list_del_init(&nxt->link_list);
1176 wake_ev |= io_link_cancel_timeout(nxt);
1177 req->flags &= ~REQ_F_LINK_TIMEOUT;
1181 list_del_init(&req->link_list);
1182 if (!list_empty(&nxt->link_list))
1183 nxt->flags |= REQ_F_LINK;
1188 req->flags |= REQ_F_LINK_NEXT;
1190 io_cqring_ev_posted(ctx);
1194 * Called if REQ_F_LINK is set, and we fail the head request
1196 static void io_fail_links(struct io_kiocb *req)
1198 struct io_ring_ctx *ctx = req->ctx;
1199 unsigned long flags;
1201 spin_lock_irqsave(&ctx->completion_lock, flags);
1203 while (!list_empty(&req->link_list)) {
1204 struct io_kiocb *link = list_first_entry(&req->link_list,
1205 struct io_kiocb, link_list);
1207 list_del_init(&link->link_list);
1208 trace_io_uring_fail_link(req, link);
1210 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1211 link->opcode == IORING_OP_LINK_TIMEOUT) {
1212 io_link_cancel_timeout(link);
1214 io_cqring_fill_event(link, -ECANCELED);
1215 __io_double_put_req(link);
1217 req->flags &= ~REQ_F_LINK_TIMEOUT;
1220 io_commit_cqring(ctx);
1221 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1222 io_cqring_ev_posted(ctx);
1225 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1227 if (likely(!(req->flags & REQ_F_LINK)))
1231 * If LINK is set, we have dependent requests in this chain. If we
1232 * didn't fail this request, queue the first one up, moving any other
1233 * dependencies to the next request. In case of failure, fail the rest
1236 if (req->flags & REQ_F_FAIL_LINK) {
1238 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1239 REQ_F_LINK_TIMEOUT) {
1240 struct io_ring_ctx *ctx = req->ctx;
1241 unsigned long flags;
1244 * If this is a timeout link, we could be racing with the
1245 * timeout timer. Grab the completion lock for this case to
1246 * protect against that.
1248 spin_lock_irqsave(&ctx->completion_lock, flags);
1249 io_req_link_next(req, nxt);
1250 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1252 io_req_link_next(req, nxt);
1256 static void io_free_req(struct io_kiocb *req)
1258 struct io_kiocb *nxt = NULL;
1260 io_req_find_next(req, &nxt);
1264 io_queue_async_work(nxt);
1268 * Drop reference to request, return next in chain (if there is one) if this
1269 * was the last reference to this request.
1271 __attribute__((nonnull))
1272 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1274 io_req_find_next(req, nxtptr);
1276 if (refcount_dec_and_test(&req->refs))
1280 static void io_put_req(struct io_kiocb *req)
1282 if (refcount_dec_and_test(&req->refs))
1287 * Must only be used if we don't need to care about links, usually from
1288 * within the completion handling itself.
1290 static void __io_double_put_req(struct io_kiocb *req)
1292 /* drop both submit and complete references */
1293 if (refcount_sub_and_test(2, &req->refs))
1297 static void io_double_put_req(struct io_kiocb *req)
1299 /* drop both submit and complete references */
1300 if (refcount_sub_and_test(2, &req->refs))
1304 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1306 struct io_rings *rings = ctx->rings;
1308 if (test_bit(0, &ctx->cq_check_overflow)) {
1310 * noflush == true is from the waitqueue handler, just ensure
1311 * we wake up the task, and the next invocation will flush the
1312 * entries. We cannot safely to it from here.
1314 if (noflush && !list_empty(&ctx->cq_overflow_list))
1317 io_cqring_overflow_flush(ctx, false);
1320 /* See comment at the top of this file */
1322 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1325 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1327 struct io_rings *rings = ctx->rings;
1329 /* make sure SQ entry isn't read before tail */
1330 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1333 static inline bool io_req_multi_free(struct io_kiocb *req)
1336 * If we're not using fixed files, we have to pair the completion part
1337 * with the file put. Use regular completions for those, only batch
1338 * free for fixed file and non-linked commands.
1340 if (((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) == REQ_F_FIXED_FILE)
1341 && !io_is_fallback_req(req) && !req->io)
1348 * Find and free completed poll iocbs
1350 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1351 struct list_head *done)
1353 void *reqs[IO_IOPOLL_BATCH];
1354 struct io_kiocb *req;
1358 while (!list_empty(done)) {
1359 req = list_first_entry(done, struct io_kiocb, list);
1360 list_del(&req->list);
1362 io_cqring_fill_event(req, req->result);
1365 if (refcount_dec_and_test(&req->refs)) {
1366 if (io_req_multi_free(req)) {
1367 reqs[to_free++] = req;
1368 if (to_free == ARRAY_SIZE(reqs))
1369 io_free_req_many(ctx, reqs, &to_free);
1376 io_commit_cqring(ctx);
1377 io_free_req_many(ctx, reqs, &to_free);
1380 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1383 struct io_kiocb *req, *tmp;
1389 * Only spin for completions if we don't have multiple devices hanging
1390 * off our complete list, and we're under the requested amount.
1392 spin = !ctx->poll_multi_file && *nr_events < min;
1395 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1396 struct kiocb *kiocb = &req->rw.kiocb;
1399 * Move completed entries to our local list. If we find a
1400 * request that requires polling, break out and complete
1401 * the done list first, if we have entries there.
1403 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1404 list_move_tail(&req->list, &done);
1407 if (!list_empty(&done))
1410 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1419 if (!list_empty(&done))
1420 io_iopoll_complete(ctx, nr_events, &done);
1426 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1427 * non-spinning poll check - we'll still enter the driver poll loop, but only
1428 * as a non-spinning completion check.
1430 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1433 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1436 ret = io_do_iopoll(ctx, nr_events, min);
1439 if (!min || *nr_events >= min)
1447 * We can't just wait for polled events to come to us, we have to actively
1448 * find and complete them.
1450 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1452 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1455 mutex_lock(&ctx->uring_lock);
1456 while (!list_empty(&ctx->poll_list)) {
1457 unsigned int nr_events = 0;
1459 io_iopoll_getevents(ctx, &nr_events, 1);
1462 * Ensure we allow local-to-the-cpu processing to take place,
1463 * in this case we need to ensure that we reap all events.
1467 mutex_unlock(&ctx->uring_lock);
1470 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1473 int iters = 0, ret = 0;
1479 * Don't enter poll loop if we already have events pending.
1480 * If we do, we can potentially be spinning for commands that
1481 * already triggered a CQE (eg in error).
1483 if (io_cqring_events(ctx, false))
1487 * If a submit got punted to a workqueue, we can have the
1488 * application entering polling for a command before it gets
1489 * issued. That app will hold the uring_lock for the duration
1490 * of the poll right here, so we need to take a breather every
1491 * now and then to ensure that the issue has a chance to add
1492 * the poll to the issued list. Otherwise we can spin here
1493 * forever, while the workqueue is stuck trying to acquire the
1496 if (!(++iters & 7)) {
1497 mutex_unlock(&ctx->uring_lock);
1498 mutex_lock(&ctx->uring_lock);
1501 if (*nr_events < min)
1502 tmin = min - *nr_events;
1504 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1508 } while (min && !*nr_events && !need_resched());
1513 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1519 * We disallow the app entering submit/complete with polling, but we
1520 * still need to lock the ring to prevent racing with polled issue
1521 * that got punted to a workqueue.
1523 mutex_lock(&ctx->uring_lock);
1524 ret = __io_iopoll_check(ctx, nr_events, min);
1525 mutex_unlock(&ctx->uring_lock);
1529 static void kiocb_end_write(struct io_kiocb *req)
1532 * Tell lockdep we inherited freeze protection from submission
1535 if (req->flags & REQ_F_ISREG) {
1536 struct inode *inode = file_inode(req->file);
1538 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1540 file_end_write(req->file);
1543 static inline void req_set_fail_links(struct io_kiocb *req)
1545 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1546 req->flags |= REQ_F_FAIL_LINK;
1549 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1551 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1553 if (kiocb->ki_flags & IOCB_WRITE)
1554 kiocb_end_write(req);
1556 if (res != req->result)
1557 req_set_fail_links(req);
1558 io_cqring_add_event(req, res);
1561 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1563 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1565 io_complete_rw_common(kiocb, res);
1569 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1571 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1572 struct io_kiocb *nxt = NULL;
1574 io_complete_rw_common(kiocb, res);
1575 io_put_req_find_next(req, &nxt);
1580 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1582 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1584 if (kiocb->ki_flags & IOCB_WRITE)
1585 kiocb_end_write(req);
1587 if (res != req->result)
1588 req_set_fail_links(req);
1591 req->flags |= REQ_F_IOPOLL_COMPLETED;
1595 * After the iocb has been issued, it's safe to be found on the poll list.
1596 * Adding the kiocb to the list AFTER submission ensures that we don't
1597 * find it from a io_iopoll_getevents() thread before the issuer is done
1598 * accessing the kiocb cookie.
1600 static void io_iopoll_req_issued(struct io_kiocb *req)
1602 struct io_ring_ctx *ctx = req->ctx;
1605 * Track whether we have multiple files in our lists. This will impact
1606 * how we do polling eventually, not spinning if we're on potentially
1607 * different devices.
1609 if (list_empty(&ctx->poll_list)) {
1610 ctx->poll_multi_file = false;
1611 } else if (!ctx->poll_multi_file) {
1612 struct io_kiocb *list_req;
1614 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1616 if (list_req->file != req->file)
1617 ctx->poll_multi_file = true;
1621 * For fast devices, IO may have already completed. If it has, add
1622 * it to the front so we find it first.
1624 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1625 list_add(&req->list, &ctx->poll_list);
1627 list_add_tail(&req->list, &ctx->poll_list);
1630 static void io_file_put(struct io_submit_state *state)
1633 int diff = state->has_refs - state->used_refs;
1636 fput_many(state->file, diff);
1642 * Get as many references to a file as we have IOs left in this submission,
1643 * assuming most submissions are for one file, or at least that each file
1644 * has more than one submission.
1646 static struct file *io_file_get(struct io_submit_state *state, int fd)
1652 if (state->fd == fd) {
1659 state->file = fget_many(fd, state->ios_left);
1664 state->has_refs = state->ios_left;
1665 state->used_refs = 1;
1671 * If we tracked the file through the SCM inflight mechanism, we could support
1672 * any file. For now, just ensure that anything potentially problematic is done
1675 static bool io_file_supports_async(struct file *file)
1677 umode_t mode = file_inode(file)->i_mode;
1679 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1681 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1687 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1688 bool force_nonblock)
1690 struct io_ring_ctx *ctx = req->ctx;
1691 struct kiocb *kiocb = &req->rw.kiocb;
1698 if (S_ISREG(file_inode(req->file)->i_mode))
1699 req->flags |= REQ_F_ISREG;
1701 kiocb->ki_pos = READ_ONCE(sqe->off);
1702 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1703 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1705 ioprio = READ_ONCE(sqe->ioprio);
1707 ret = ioprio_check_cap(ioprio);
1711 kiocb->ki_ioprio = ioprio;
1713 kiocb->ki_ioprio = get_current_ioprio();
1715 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1719 /* don't allow async punt if RWF_NOWAIT was requested */
1720 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1721 (req->file->f_flags & O_NONBLOCK))
1722 req->flags |= REQ_F_NOWAIT;
1725 kiocb->ki_flags |= IOCB_NOWAIT;
1727 if (ctx->flags & IORING_SETUP_IOPOLL) {
1728 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1729 !kiocb->ki_filp->f_op->iopoll)
1732 kiocb->ki_flags |= IOCB_HIPRI;
1733 kiocb->ki_complete = io_complete_rw_iopoll;
1736 if (kiocb->ki_flags & IOCB_HIPRI)
1738 kiocb->ki_complete = io_complete_rw;
1741 req->rw.addr = READ_ONCE(sqe->addr);
1742 req->rw.len = READ_ONCE(sqe->len);
1743 /* we own ->private, reuse it for the buffer index */
1744 req->rw.kiocb.private = (void *) (unsigned long)
1745 READ_ONCE(sqe->buf_index);
1749 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1755 case -ERESTARTNOINTR:
1756 case -ERESTARTNOHAND:
1757 case -ERESTART_RESTARTBLOCK:
1759 * We can't just restart the syscall, since previously
1760 * submitted sqes may already be in progress. Just fail this
1766 kiocb->ki_complete(kiocb, ret, 0);
1770 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1773 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1774 *nxt = __io_complete_rw(kiocb, ret);
1776 io_rw_done(kiocb, ret);
1779 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1780 struct iov_iter *iter)
1782 struct io_ring_ctx *ctx = req->ctx;
1783 size_t len = req->rw.len;
1784 struct io_mapped_ubuf *imu;
1785 unsigned index, buf_index;
1789 /* attempt to use fixed buffers without having provided iovecs */
1790 if (unlikely(!ctx->user_bufs))
1793 buf_index = (unsigned long) req->rw.kiocb.private;
1794 if (unlikely(buf_index >= ctx->nr_user_bufs))
1797 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1798 imu = &ctx->user_bufs[index];
1799 buf_addr = req->rw.addr;
1802 if (buf_addr + len < buf_addr)
1804 /* not inside the mapped region */
1805 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1809 * May not be a start of buffer, set size appropriately
1810 * and advance us to the beginning.
1812 offset = buf_addr - imu->ubuf;
1813 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1817 * Don't use iov_iter_advance() here, as it's really slow for
1818 * using the latter parts of a big fixed buffer - it iterates
1819 * over each segment manually. We can cheat a bit here, because
1822 * 1) it's a BVEC iter, we set it up
1823 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1824 * first and last bvec
1826 * So just find our index, and adjust the iterator afterwards.
1827 * If the offset is within the first bvec (or the whole first
1828 * bvec, just use iov_iter_advance(). This makes it easier
1829 * since we can just skip the first segment, which may not
1830 * be PAGE_SIZE aligned.
1832 const struct bio_vec *bvec = imu->bvec;
1834 if (offset <= bvec->bv_len) {
1835 iov_iter_advance(iter, offset);
1837 unsigned long seg_skip;
1839 /* skip first vec */
1840 offset -= bvec->bv_len;
1841 seg_skip = 1 + (offset >> PAGE_SHIFT);
1843 iter->bvec = bvec + seg_skip;
1844 iter->nr_segs -= seg_skip;
1845 iter->count -= bvec->bv_len + offset;
1846 iter->iov_offset = offset & ~PAGE_MASK;
1853 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1854 struct iovec **iovec, struct iov_iter *iter)
1856 void __user *buf = u64_to_user_ptr(req->rw.addr);
1857 size_t sqe_len = req->rw.len;
1860 opcode = req->opcode;
1861 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1863 return io_import_fixed(req, rw, iter);
1866 /* buffer index only valid with fixed read/write */
1867 if (req->rw.kiocb.private)
1871 struct io_async_rw *iorw = &req->io->rw;
1874 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
1875 if (iorw->iov == iorw->fast_iov)
1883 #ifdef CONFIG_COMPAT
1884 if (req->ctx->compat)
1885 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1889 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1893 * For files that don't have ->read_iter() and ->write_iter(), handle them
1894 * by looping over ->read() or ->write() manually.
1896 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1897 struct iov_iter *iter)
1902 * Don't support polled IO through this interface, and we can't
1903 * support non-blocking either. For the latter, this just causes
1904 * the kiocb to be handled from an async context.
1906 if (kiocb->ki_flags & IOCB_HIPRI)
1908 if (kiocb->ki_flags & IOCB_NOWAIT)
1911 while (iov_iter_count(iter)) {
1915 if (!iov_iter_is_bvec(iter)) {
1916 iovec = iov_iter_iovec(iter);
1918 /* fixed buffers import bvec */
1919 iovec.iov_base = kmap(iter->bvec->bv_page)
1921 iovec.iov_len = min(iter->count,
1922 iter->bvec->bv_len - iter->iov_offset);
1926 nr = file->f_op->read(file, iovec.iov_base,
1927 iovec.iov_len, &kiocb->ki_pos);
1929 nr = file->f_op->write(file, iovec.iov_base,
1930 iovec.iov_len, &kiocb->ki_pos);
1933 if (iov_iter_is_bvec(iter))
1934 kunmap(iter->bvec->bv_page);
1942 if (nr != iovec.iov_len)
1944 iov_iter_advance(iter, nr);
1950 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
1951 struct iovec *iovec, struct iovec *fast_iov,
1952 struct iov_iter *iter)
1954 req->io->rw.nr_segs = iter->nr_segs;
1955 req->io->rw.size = io_size;
1956 req->io->rw.iov = iovec;
1957 if (!req->io->rw.iov) {
1958 req->io->rw.iov = req->io->rw.fast_iov;
1959 memcpy(req->io->rw.iov, fast_iov,
1960 sizeof(struct iovec) * iter->nr_segs);
1964 static int io_alloc_async_ctx(struct io_kiocb *req)
1966 if (!io_op_defs[req->opcode].async_ctx)
1968 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
1969 return req->io == NULL;
1972 static void io_rw_async(struct io_wq_work **workptr)
1974 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
1975 struct iovec *iov = NULL;
1977 if (req->io->rw.iov != req->io->rw.fast_iov)
1978 iov = req->io->rw.iov;
1979 io_wq_submit_work(workptr);
1983 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
1984 struct iovec *iovec, struct iovec *fast_iov,
1985 struct iov_iter *iter)
1987 if (req->opcode == IORING_OP_READ_FIXED ||
1988 req->opcode == IORING_OP_WRITE_FIXED)
1990 if (!req->io && io_alloc_async_ctx(req))
1993 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
1994 req->work.func = io_rw_async;
1998 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1999 bool force_nonblock)
2001 struct io_async_ctx *io;
2002 struct iov_iter iter;
2005 ret = io_prep_rw(req, sqe, force_nonblock);
2009 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2016 io->rw.iov = io->rw.fast_iov;
2018 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2023 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2027 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2028 bool force_nonblock)
2030 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2031 struct kiocb *kiocb = &req->rw.kiocb;
2032 struct iov_iter iter;
2034 ssize_t io_size, ret;
2036 ret = io_import_iovec(READ, req, &iovec, &iter);
2040 /* Ensure we clear previously set non-block flag */
2041 if (!force_nonblock)
2042 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2046 if (req->flags & REQ_F_LINK)
2047 req->result = io_size;
2050 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2051 * we know to async punt it even if it was opened O_NONBLOCK
2053 if (force_nonblock && !io_file_supports_async(req->file)) {
2054 req->flags |= REQ_F_MUST_PUNT;
2058 iov_count = iov_iter_count(&iter);
2059 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2063 if (req->file->f_op->read_iter)
2064 ret2 = call_read_iter(req->file, kiocb, &iter);
2066 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2068 /* Catch -EAGAIN return for forced non-blocking submission */
2069 if (!force_nonblock || ret2 != -EAGAIN) {
2070 kiocb_done(kiocb, ret2, nxt, req->in_async);
2073 ret = io_setup_async_rw(req, io_size, iovec,
2074 inline_vecs, &iter);
2081 if (!io_wq_current_is_worker())
2086 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2087 bool force_nonblock)
2089 struct io_async_ctx *io;
2090 struct iov_iter iter;
2093 ret = io_prep_rw(req, sqe, force_nonblock);
2097 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2104 io->rw.iov = io->rw.fast_iov;
2106 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2111 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2115 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2116 bool force_nonblock)
2118 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2119 struct kiocb *kiocb = &req->rw.kiocb;
2120 struct iov_iter iter;
2122 ssize_t ret, io_size;
2124 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2128 /* Ensure we clear previously set non-block flag */
2129 if (!force_nonblock)
2130 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2134 if (req->flags & REQ_F_LINK)
2135 req->result = io_size;
2138 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2139 * we know to async punt it even if it was opened O_NONBLOCK
2141 if (force_nonblock && !io_file_supports_async(req->file)) {
2142 req->flags |= REQ_F_MUST_PUNT;
2146 /* file path doesn't support NOWAIT for non-direct_IO */
2147 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2148 (req->flags & REQ_F_ISREG))
2151 iov_count = iov_iter_count(&iter);
2152 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2157 * Open-code file_start_write here to grab freeze protection,
2158 * which will be released by another thread in
2159 * io_complete_rw(). Fool lockdep by telling it the lock got
2160 * released so that it doesn't complain about the held lock when
2161 * we return to userspace.
2163 if (req->flags & REQ_F_ISREG) {
2164 __sb_start_write(file_inode(req->file)->i_sb,
2165 SB_FREEZE_WRITE, true);
2166 __sb_writers_release(file_inode(req->file)->i_sb,
2169 kiocb->ki_flags |= IOCB_WRITE;
2171 if (req->file->f_op->write_iter)
2172 ret2 = call_write_iter(req->file, kiocb, &iter);
2174 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2175 if (!force_nonblock || ret2 != -EAGAIN) {
2176 kiocb_done(kiocb, ret2, nxt, req->in_async);
2179 ret = io_setup_async_rw(req, io_size, iovec,
2180 inline_vecs, &iter);
2187 if (!io_wq_current_is_worker())
2193 * IORING_OP_NOP just posts a completion event, nothing else.
2195 static int io_nop(struct io_kiocb *req)
2197 struct io_ring_ctx *ctx = req->ctx;
2199 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2202 io_cqring_add_event(req, 0);
2207 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2209 struct io_ring_ctx *ctx = req->ctx;
2214 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2216 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2219 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2220 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2223 req->sync.off = READ_ONCE(sqe->off);
2224 req->sync.len = READ_ONCE(sqe->len);
2228 static bool io_req_cancelled(struct io_kiocb *req)
2230 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2231 req_set_fail_links(req);
2232 io_cqring_add_event(req, -ECANCELED);
2240 static void io_link_work_cb(struct io_wq_work **workptr)
2242 struct io_wq_work *work = *workptr;
2243 struct io_kiocb *link = work->data;
2245 io_queue_linked_timeout(link);
2246 work->func = io_wq_submit_work;
2249 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2251 struct io_kiocb *link;
2253 io_prep_async_work(nxt, &link);
2254 *workptr = &nxt->work;
2256 nxt->work.flags |= IO_WQ_WORK_CB;
2257 nxt->work.func = io_link_work_cb;
2258 nxt->work.data = link;
2262 static void io_fsync_finish(struct io_wq_work **workptr)
2264 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2265 loff_t end = req->sync.off + req->sync.len;
2266 struct io_kiocb *nxt = NULL;
2269 if (io_req_cancelled(req))
2272 ret = vfs_fsync_range(req->file, req->sync.off,
2273 end > 0 ? end : LLONG_MAX,
2274 req->sync.flags & IORING_FSYNC_DATASYNC);
2276 req_set_fail_links(req);
2277 io_cqring_add_event(req, ret);
2278 io_put_req_find_next(req, &nxt);
2280 io_wq_assign_next(workptr, nxt);
2283 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2284 bool force_nonblock)
2286 struct io_wq_work *work, *old_work;
2288 /* fsync always requires a blocking context */
2289 if (force_nonblock) {
2291 req->work.func = io_fsync_finish;
2295 work = old_work = &req->work;
2296 io_fsync_finish(&work);
2297 if (work && work != old_work)
2298 *nxt = container_of(work, struct io_kiocb, work);
2302 static void io_fallocate_finish(struct io_wq_work **workptr)
2304 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2305 struct io_kiocb *nxt = NULL;
2308 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2311 req_set_fail_links(req);
2312 io_cqring_add_event(req, ret);
2313 io_put_req_find_next(req, &nxt);
2315 io_wq_assign_next(workptr, nxt);
2318 static int io_fallocate_prep(struct io_kiocb *req,
2319 const struct io_uring_sqe *sqe)
2321 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2324 req->sync.off = READ_ONCE(sqe->off);
2325 req->sync.len = READ_ONCE(sqe->addr);
2326 req->sync.mode = READ_ONCE(sqe->len);
2330 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2331 bool force_nonblock)
2333 struct io_wq_work *work, *old_work;
2335 /* fallocate always requiring blocking context */
2336 if (force_nonblock) {
2338 req->work.func = io_fallocate_finish;
2342 work = old_work = &req->work;
2343 io_fallocate_finish(&work);
2344 if (work && work != old_work)
2345 *nxt = container_of(work, struct io_kiocb, work);
2350 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2354 if (sqe->ioprio || sqe->buf_index)
2357 req->open.dfd = READ_ONCE(sqe->fd);
2358 req->open.mode = READ_ONCE(sqe->len);
2359 req->open.fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2360 req->open.flags = READ_ONCE(sqe->open_flags);
2362 req->open.filename = getname(req->open.fname);
2363 if (IS_ERR(req->open.filename)) {
2364 ret = PTR_ERR(req->open.filename);
2365 req->open.filename = NULL;
2372 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2373 bool force_nonblock)
2375 struct open_flags op;
2376 struct open_how how;
2380 if (force_nonblock) {
2381 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2385 how = build_open_how(req->open.flags, req->open.mode);
2386 ret = build_open_flags(&how, &op);
2390 ret = get_unused_fd_flags(how.flags);
2394 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2397 ret = PTR_ERR(file);
2399 fsnotify_open(file);
2400 fd_install(ret, file);
2403 putname(req->open.filename);
2405 req_set_fail_links(req);
2406 io_cqring_add_event(req, ret);
2407 io_put_req_find_next(req, nxt);
2411 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2413 unsigned lookup_flags;
2416 if (sqe->ioprio || sqe->buf_index)
2419 req->open.dfd = READ_ONCE(sqe->fd);
2420 req->open.mask = READ_ONCE(sqe->len);
2421 req->open.fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2422 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2423 req->open.flags = READ_ONCE(sqe->statx_flags);
2425 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.flags))
2428 req->open.filename = getname_flags(req->open.fname, lookup_flags, NULL);
2429 if (IS_ERR(req->open.filename)) {
2430 ret = PTR_ERR(req->open.filename);
2431 req->open.filename = NULL;
2438 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2439 bool force_nonblock)
2441 struct io_open *ctx = &req->open;
2442 unsigned lookup_flags;
2450 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->flags))
2454 /* filename_lookup() drops it, keep a reference */
2455 ctx->filename->refcnt++;
2457 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2462 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->flags);
2464 if (retry_estale(ret, lookup_flags)) {
2465 lookup_flags |= LOOKUP_REVAL;
2469 ret = cp_statx(&stat, ctx->buffer);
2471 putname(ctx->filename);
2473 req_set_fail_links(req);
2474 io_cqring_add_event(req, ret);
2475 io_put_req_find_next(req, nxt);
2479 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2482 * If we queue this for async, it must not be cancellable. That would
2483 * leave the 'file' in an undeterminate state.
2485 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2487 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2488 sqe->rw_flags || sqe->buf_index)
2490 if (sqe->flags & IOSQE_FIXED_FILE)
2493 req->close.fd = READ_ONCE(sqe->fd);
2494 if (req->file->f_op == &io_uring_fops ||
2495 req->close.fd == req->ring_fd)
2501 static void io_close_finish(struct io_wq_work **workptr)
2503 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2504 struct io_kiocb *nxt = NULL;
2506 /* Invoked with files, we need to do the close */
2507 if (req->work.files) {
2510 ret = filp_close(req->close.put_file, req->work.files);
2512 req_set_fail_links(req);
2514 io_cqring_add_event(req, ret);
2517 fput(req->close.put_file);
2519 /* we bypassed the re-issue, drop the submission reference */
2521 io_put_req_find_next(req, &nxt);
2523 io_wq_assign_next(workptr, nxt);
2526 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2527 bool force_nonblock)
2531 req->close.put_file = NULL;
2532 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2536 /* if the file has a flush method, be safe and punt to async */
2537 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker()) {
2538 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2543 * No ->flush(), safely close from here and just punt the
2544 * fput() to async context.
2546 ret = filp_close(req->close.put_file, current->files);
2549 req_set_fail_links(req);
2550 io_cqring_add_event(req, ret);
2552 if (io_wq_current_is_worker()) {
2553 struct io_wq_work *old_work, *work;
2555 old_work = work = &req->work;
2556 io_close_finish(&work);
2557 if (work && work != old_work)
2558 *nxt = container_of(work, struct io_kiocb, work);
2563 req->work.func = io_close_finish;
2567 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2569 struct io_ring_ctx *ctx = req->ctx;
2574 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2576 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2579 req->sync.off = READ_ONCE(sqe->off);
2580 req->sync.len = READ_ONCE(sqe->len);
2581 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2585 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2587 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2588 struct io_kiocb *nxt = NULL;
2591 if (io_req_cancelled(req))
2594 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2597 req_set_fail_links(req);
2598 io_cqring_add_event(req, ret);
2599 io_put_req_find_next(req, &nxt);
2601 io_wq_assign_next(workptr, nxt);
2604 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2605 bool force_nonblock)
2607 struct io_wq_work *work, *old_work;
2609 /* sync_file_range always requires a blocking context */
2610 if (force_nonblock) {
2612 req->work.func = io_sync_file_range_finish;
2616 work = old_work = &req->work;
2617 io_sync_file_range_finish(&work);
2618 if (work && work != old_work)
2619 *nxt = container_of(work, struct io_kiocb, work);
2623 #if defined(CONFIG_NET)
2624 static void io_sendrecv_async(struct io_wq_work **workptr)
2626 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2627 struct iovec *iov = NULL;
2629 if (req->io->rw.iov != req->io->rw.fast_iov)
2630 iov = req->io->msg.iov;
2631 io_wq_submit_work(workptr);
2636 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2638 #if defined(CONFIG_NET)
2639 struct io_sr_msg *sr = &req->sr_msg;
2640 struct io_async_ctx *io = req->io;
2642 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2643 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2648 io->msg.iov = io->msg.fast_iov;
2649 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2656 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2657 bool force_nonblock)
2659 #if defined(CONFIG_NET)
2660 struct io_async_msghdr *kmsg = NULL;
2661 struct socket *sock;
2664 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2667 sock = sock_from_file(req->file, &ret);
2669 struct io_async_ctx io;
2670 struct sockaddr_storage addr;
2674 kmsg = &req->io->msg;
2675 kmsg->msg.msg_name = &addr;
2676 /* if iov is set, it's allocated already */
2678 kmsg->iov = kmsg->fast_iov;
2679 kmsg->msg.msg_iter.iov = kmsg->iov;
2681 struct io_sr_msg *sr = &req->sr_msg;
2684 kmsg->msg.msg_name = &addr;
2686 io.msg.iov = io.msg.fast_iov;
2687 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2688 sr->msg_flags, &io.msg.iov);
2693 flags = req->sr_msg.msg_flags;
2694 if (flags & MSG_DONTWAIT)
2695 req->flags |= REQ_F_NOWAIT;
2696 else if (force_nonblock)
2697 flags |= MSG_DONTWAIT;
2699 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2700 if (force_nonblock && ret == -EAGAIN) {
2703 if (io_alloc_async_ctx(req))
2705 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2706 req->work.func = io_sendrecv_async;
2709 if (ret == -ERESTARTSYS)
2713 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2715 io_cqring_add_event(req, ret);
2717 req_set_fail_links(req);
2718 io_put_req_find_next(req, nxt);
2725 static int io_recvmsg_prep(struct io_kiocb *req,
2726 const struct io_uring_sqe *sqe)
2728 #if defined(CONFIG_NET)
2729 struct io_sr_msg *sr = &req->sr_msg;
2730 struct io_async_ctx *io = req->io;
2732 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2733 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2738 io->msg.iov = io->msg.fast_iov;
2739 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2740 &io->msg.uaddr, &io->msg.iov);
2746 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2747 bool force_nonblock)
2749 #if defined(CONFIG_NET)
2750 struct io_async_msghdr *kmsg = NULL;
2751 struct socket *sock;
2754 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2757 sock = sock_from_file(req->file, &ret);
2759 struct io_async_ctx io;
2760 struct sockaddr_storage addr;
2764 kmsg = &req->io->msg;
2765 kmsg->msg.msg_name = &addr;
2766 /* if iov is set, it's allocated already */
2768 kmsg->iov = kmsg->fast_iov;
2769 kmsg->msg.msg_iter.iov = kmsg->iov;
2771 struct io_sr_msg *sr = &req->sr_msg;
2774 kmsg->msg.msg_name = &addr;
2776 io.msg.iov = io.msg.fast_iov;
2777 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
2778 sr->msg_flags, &io.msg.uaddr,
2784 flags = req->sr_msg.msg_flags;
2785 if (flags & MSG_DONTWAIT)
2786 req->flags |= REQ_F_NOWAIT;
2787 else if (force_nonblock)
2788 flags |= MSG_DONTWAIT;
2790 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
2791 kmsg->uaddr, flags);
2792 if (force_nonblock && ret == -EAGAIN) {
2795 if (io_alloc_async_ctx(req))
2797 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2798 req->work.func = io_sendrecv_async;
2801 if (ret == -ERESTARTSYS)
2805 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2807 io_cqring_add_event(req, ret);
2809 req_set_fail_links(req);
2810 io_put_req_find_next(req, nxt);
2817 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2819 #if defined(CONFIG_NET)
2820 struct io_accept *accept = &req->accept;
2822 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2824 if (sqe->ioprio || sqe->len || sqe->buf_index)
2827 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
2828 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2829 accept->flags = READ_ONCE(sqe->accept_flags);
2836 #if defined(CONFIG_NET)
2837 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2838 bool force_nonblock)
2840 struct io_accept *accept = &req->accept;
2841 unsigned file_flags;
2844 file_flags = force_nonblock ? O_NONBLOCK : 0;
2845 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
2846 accept->addr_len, accept->flags);
2847 if (ret == -EAGAIN && force_nonblock)
2849 if (ret == -ERESTARTSYS)
2852 req_set_fail_links(req);
2853 io_cqring_add_event(req, ret);
2854 io_put_req_find_next(req, nxt);
2858 static void io_accept_finish(struct io_wq_work **workptr)
2860 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2861 struct io_kiocb *nxt = NULL;
2863 if (io_req_cancelled(req))
2865 __io_accept(req, &nxt, false);
2867 io_wq_assign_next(workptr, nxt);
2871 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2872 bool force_nonblock)
2874 #if defined(CONFIG_NET)
2877 ret = __io_accept(req, nxt, force_nonblock);
2878 if (ret == -EAGAIN && force_nonblock) {
2879 req->work.func = io_accept_finish;
2880 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2890 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2892 #if defined(CONFIG_NET)
2893 struct io_connect *conn = &req->connect;
2894 struct io_async_ctx *io = req->io;
2896 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2898 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
2901 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
2902 conn->addr_len = READ_ONCE(sqe->addr2);
2907 return move_addr_to_kernel(conn->addr, conn->addr_len,
2908 &io->connect.address);
2914 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
2915 bool force_nonblock)
2917 #if defined(CONFIG_NET)
2918 struct io_async_ctx __io, *io;
2919 unsigned file_flags;
2925 ret = move_addr_to_kernel(req->connect.addr,
2926 req->connect.addr_len,
2927 &__io.connect.address);
2933 file_flags = force_nonblock ? O_NONBLOCK : 0;
2935 ret = __sys_connect_file(req->file, &io->connect.address,
2936 req->connect.addr_len, file_flags);
2937 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
2940 if (io_alloc_async_ctx(req)) {
2944 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
2947 if (ret == -ERESTARTSYS)
2951 req_set_fail_links(req);
2952 io_cqring_add_event(req, ret);
2953 io_put_req_find_next(req, nxt);
2960 static void io_poll_remove_one(struct io_kiocb *req)
2962 struct io_poll_iocb *poll = &req->poll;
2964 spin_lock(&poll->head->lock);
2965 WRITE_ONCE(poll->canceled, true);
2966 if (!list_empty(&poll->wait.entry)) {
2967 list_del_init(&poll->wait.entry);
2968 io_queue_async_work(req);
2970 spin_unlock(&poll->head->lock);
2971 hash_del(&req->hash_node);
2974 static void io_poll_remove_all(struct io_ring_ctx *ctx)
2976 struct hlist_node *tmp;
2977 struct io_kiocb *req;
2980 spin_lock_irq(&ctx->completion_lock);
2981 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
2982 struct hlist_head *list;
2984 list = &ctx->cancel_hash[i];
2985 hlist_for_each_entry_safe(req, tmp, list, hash_node)
2986 io_poll_remove_one(req);
2988 spin_unlock_irq(&ctx->completion_lock);
2991 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
2993 struct hlist_head *list;
2994 struct io_kiocb *req;
2996 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
2997 hlist_for_each_entry(req, list, hash_node) {
2998 if (sqe_addr == req->user_data) {
2999 io_poll_remove_one(req);
3007 static int io_poll_remove_prep(struct io_kiocb *req,
3008 const struct io_uring_sqe *sqe)
3010 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3012 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3016 req->poll.addr = READ_ONCE(sqe->addr);
3021 * Find a running poll command that matches one specified in sqe->addr,
3022 * and remove it if found.
3024 static int io_poll_remove(struct io_kiocb *req)
3026 struct io_ring_ctx *ctx = req->ctx;
3030 addr = req->poll.addr;
3031 spin_lock_irq(&ctx->completion_lock);
3032 ret = io_poll_cancel(ctx, addr);
3033 spin_unlock_irq(&ctx->completion_lock);
3035 io_cqring_add_event(req, ret);
3037 req_set_fail_links(req);
3042 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3044 struct io_ring_ctx *ctx = req->ctx;
3046 req->poll.done = true;
3048 io_cqring_fill_event(req, error);
3050 io_cqring_fill_event(req, mangle_poll(mask));
3051 io_commit_cqring(ctx);
3054 static void io_poll_complete_work(struct io_wq_work **workptr)
3056 struct io_wq_work *work = *workptr;
3057 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3058 struct io_poll_iocb *poll = &req->poll;
3059 struct poll_table_struct pt = { ._key = poll->events };
3060 struct io_ring_ctx *ctx = req->ctx;
3061 struct io_kiocb *nxt = NULL;
3065 if (work->flags & IO_WQ_WORK_CANCEL) {
3066 WRITE_ONCE(poll->canceled, true);
3068 } else if (READ_ONCE(poll->canceled)) {
3072 if (ret != -ECANCELED)
3073 mask = vfs_poll(poll->file, &pt) & poll->events;
3076 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3077 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3078 * synchronize with them. In the cancellation case the list_del_init
3079 * itself is not actually needed, but harmless so we keep it in to
3080 * avoid further branches in the fast path.
3082 spin_lock_irq(&ctx->completion_lock);
3083 if (!mask && ret != -ECANCELED) {
3084 add_wait_queue(poll->head, &poll->wait);
3085 spin_unlock_irq(&ctx->completion_lock);
3088 hash_del(&req->hash_node);
3089 io_poll_complete(req, mask, ret);
3090 spin_unlock_irq(&ctx->completion_lock);
3092 io_cqring_ev_posted(ctx);
3095 req_set_fail_links(req);
3096 io_put_req_find_next(req, &nxt);
3098 io_wq_assign_next(workptr, nxt);
3101 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3103 void *reqs[IO_IOPOLL_BATCH];
3104 struct io_kiocb *req, *tmp;
3107 spin_lock_irq(&ctx->completion_lock);
3108 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3109 hash_del(&req->hash_node);
3110 io_poll_complete(req, req->result, 0);
3112 if (refcount_dec_and_test(&req->refs)) {
3113 if (io_req_multi_free(req)) {
3114 reqs[to_free++] = req;
3115 if (to_free == ARRAY_SIZE(reqs))
3116 io_free_req_many(ctx, reqs, &to_free);
3118 req->flags |= REQ_F_COMP_LOCKED;
3123 spin_unlock_irq(&ctx->completion_lock);
3125 io_cqring_ev_posted(ctx);
3126 io_free_req_many(ctx, reqs, &to_free);
3129 static void io_poll_flush(struct io_wq_work **workptr)
3131 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3132 struct llist_node *nodes;
3134 nodes = llist_del_all(&req->ctx->poll_llist);
3136 __io_poll_flush(req->ctx, nodes);
3139 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3142 struct io_poll_iocb *poll = wait->private;
3143 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3144 struct io_ring_ctx *ctx = req->ctx;
3145 __poll_t mask = key_to_poll(key);
3147 /* for instances that support it check for an event match first: */
3148 if (mask && !(mask & poll->events))
3151 list_del_init(&poll->wait.entry);
3154 * Run completion inline if we can. We're using trylock here because
3155 * we are violating the completion_lock -> poll wq lock ordering.
3156 * If we have a link timeout we're going to need the completion_lock
3157 * for finalizing the request, mark us as having grabbed that already.
3160 unsigned long flags;
3162 if (llist_empty(&ctx->poll_llist) &&
3163 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3164 hash_del(&req->hash_node);
3165 io_poll_complete(req, mask, 0);
3166 req->flags |= REQ_F_COMP_LOCKED;
3168 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3170 io_cqring_ev_posted(ctx);
3174 req->llist_node.next = NULL;
3175 /* if the list wasn't empty, we're done */
3176 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3179 req->work.func = io_poll_flush;
3183 io_queue_async_work(req);
3188 struct io_poll_table {
3189 struct poll_table_struct pt;
3190 struct io_kiocb *req;
3194 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3195 struct poll_table_struct *p)
3197 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3199 if (unlikely(pt->req->poll.head)) {
3200 pt->error = -EINVAL;
3205 pt->req->poll.head = head;
3206 add_wait_queue(head, &pt->req->poll.wait);
3209 static void io_poll_req_insert(struct io_kiocb *req)
3211 struct io_ring_ctx *ctx = req->ctx;
3212 struct hlist_head *list;
3214 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3215 hlist_add_head(&req->hash_node, list);
3218 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3220 struct io_poll_iocb *poll = &req->poll;
3223 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3225 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3230 events = READ_ONCE(sqe->poll_events);
3231 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3235 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3237 struct io_poll_iocb *poll = &req->poll;
3238 struct io_ring_ctx *ctx = req->ctx;
3239 struct io_poll_table ipt;
3240 bool cancel = false;
3243 INIT_IO_WORK(&req->work, io_poll_complete_work);
3244 INIT_HLIST_NODE(&req->hash_node);
3248 poll->canceled = false;
3250 ipt.pt._qproc = io_poll_queue_proc;
3251 ipt.pt._key = poll->events;
3253 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3255 /* initialized the list so that we can do list_empty checks */
3256 INIT_LIST_HEAD(&poll->wait.entry);
3257 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3258 poll->wait.private = poll;
3260 INIT_LIST_HEAD(&req->list);
3262 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3264 spin_lock_irq(&ctx->completion_lock);
3265 if (likely(poll->head)) {
3266 spin_lock(&poll->head->lock);
3267 if (unlikely(list_empty(&poll->wait.entry))) {
3273 if (mask || ipt.error)
3274 list_del_init(&poll->wait.entry);
3276 WRITE_ONCE(poll->canceled, true);
3277 else if (!poll->done) /* actually waiting for an event */
3278 io_poll_req_insert(req);
3279 spin_unlock(&poll->head->lock);
3281 if (mask) { /* no async, we'd stolen it */
3283 io_poll_complete(req, mask, 0);
3285 spin_unlock_irq(&ctx->completion_lock);
3288 io_cqring_ev_posted(ctx);
3289 io_put_req_find_next(req, nxt);
3294 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3296 struct io_timeout_data *data = container_of(timer,
3297 struct io_timeout_data, timer);
3298 struct io_kiocb *req = data->req;
3299 struct io_ring_ctx *ctx = req->ctx;
3300 unsigned long flags;
3302 atomic_inc(&ctx->cq_timeouts);
3304 spin_lock_irqsave(&ctx->completion_lock, flags);
3306 * We could be racing with timeout deletion. If the list is empty,
3307 * then timeout lookup already found it and will be handling it.
3309 if (!list_empty(&req->list)) {
3310 struct io_kiocb *prev;
3313 * Adjust the reqs sequence before the current one because it
3314 * will consume a slot in the cq_ring and the cq_tail
3315 * pointer will be increased, otherwise other timeout reqs may
3316 * return in advance without waiting for enough wait_nr.
3319 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3321 list_del_init(&req->list);
3324 io_cqring_fill_event(req, -ETIME);
3325 io_commit_cqring(ctx);
3326 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3328 io_cqring_ev_posted(ctx);
3329 req_set_fail_links(req);
3331 return HRTIMER_NORESTART;
3334 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3336 struct io_kiocb *req;
3339 list_for_each_entry(req, &ctx->timeout_list, list) {
3340 if (user_data == req->user_data) {
3341 list_del_init(&req->list);
3350 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3354 req_set_fail_links(req);
3355 io_cqring_fill_event(req, -ECANCELED);
3360 static int io_timeout_remove_prep(struct io_kiocb *req,
3361 const struct io_uring_sqe *sqe)
3363 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3365 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3368 req->timeout.addr = READ_ONCE(sqe->addr);
3369 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3370 if (req->timeout.flags)
3377 * Remove or update an existing timeout command
3379 static int io_timeout_remove(struct io_kiocb *req)
3381 struct io_ring_ctx *ctx = req->ctx;
3384 spin_lock_irq(&ctx->completion_lock);
3385 ret = io_timeout_cancel(ctx, req->timeout.addr);
3387 io_cqring_fill_event(req, ret);
3388 io_commit_cqring(ctx);
3389 spin_unlock_irq(&ctx->completion_lock);
3390 io_cqring_ev_posted(ctx);
3392 req_set_fail_links(req);
3397 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3398 bool is_timeout_link)
3400 struct io_timeout_data *data;
3403 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3405 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3407 if (sqe->off && is_timeout_link)
3409 flags = READ_ONCE(sqe->timeout_flags);
3410 if (flags & ~IORING_TIMEOUT_ABS)
3413 req->timeout.count = READ_ONCE(sqe->off);
3415 if (!req->io && io_alloc_async_ctx(req))
3418 data = &req->io->timeout;
3420 req->flags |= REQ_F_TIMEOUT;
3422 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3425 if (flags & IORING_TIMEOUT_ABS)
3426 data->mode = HRTIMER_MODE_ABS;
3428 data->mode = HRTIMER_MODE_REL;
3430 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3434 static int io_timeout(struct io_kiocb *req)
3437 struct io_ring_ctx *ctx = req->ctx;
3438 struct io_timeout_data *data;
3439 struct list_head *entry;
3442 data = &req->io->timeout;
3445 * sqe->off holds how many events that need to occur for this
3446 * timeout event to be satisfied. If it isn't set, then this is
3447 * a pure timeout request, sequence isn't used.
3449 count = req->timeout.count;
3451 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3452 spin_lock_irq(&ctx->completion_lock);
3453 entry = ctx->timeout_list.prev;
3457 req->sequence = ctx->cached_sq_head + count - 1;
3458 data->seq_offset = count;
3461 * Insertion sort, ensuring the first entry in the list is always
3462 * the one we need first.
3464 spin_lock_irq(&ctx->completion_lock);
3465 list_for_each_prev(entry, &ctx->timeout_list) {
3466 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3467 unsigned nxt_sq_head;
3468 long long tmp, tmp_nxt;
3469 u32 nxt_offset = nxt->io->timeout.seq_offset;
3471 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3475 * Since cached_sq_head + count - 1 can overflow, use type long
3478 tmp = (long long)ctx->cached_sq_head + count - 1;
3479 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3480 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3483 * cached_sq_head may overflow, and it will never overflow twice
3484 * once there is some timeout req still be valid.
3486 if (ctx->cached_sq_head < nxt_sq_head)
3493 * Sequence of reqs after the insert one and itself should
3494 * be adjusted because each timeout req consumes a slot.
3499 req->sequence -= span;
3501 list_add(&req->list, entry);
3502 data->timer.function = io_timeout_fn;
3503 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3504 spin_unlock_irq(&ctx->completion_lock);
3508 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3510 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3512 return req->user_data == (unsigned long) data;
3515 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3517 enum io_wq_cancel cancel_ret;
3520 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3521 switch (cancel_ret) {
3522 case IO_WQ_CANCEL_OK:
3525 case IO_WQ_CANCEL_RUNNING:
3528 case IO_WQ_CANCEL_NOTFOUND:
3536 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3537 struct io_kiocb *req, __u64 sqe_addr,
3538 struct io_kiocb **nxt, int success_ret)
3540 unsigned long flags;
3543 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3544 if (ret != -ENOENT) {
3545 spin_lock_irqsave(&ctx->completion_lock, flags);
3549 spin_lock_irqsave(&ctx->completion_lock, flags);
3550 ret = io_timeout_cancel(ctx, sqe_addr);
3553 ret = io_poll_cancel(ctx, sqe_addr);
3557 io_cqring_fill_event(req, ret);
3558 io_commit_cqring(ctx);
3559 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3560 io_cqring_ev_posted(ctx);
3563 req_set_fail_links(req);
3564 io_put_req_find_next(req, nxt);
3567 static int io_async_cancel_prep(struct io_kiocb *req,
3568 const struct io_uring_sqe *sqe)
3570 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3572 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3576 req->cancel.addr = READ_ONCE(sqe->addr);
3580 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3582 struct io_ring_ctx *ctx = req->ctx;
3584 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3588 static int io_files_update_prep(struct io_kiocb *req,
3589 const struct io_uring_sqe *sqe)
3591 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
3594 req->files_update.offset = READ_ONCE(sqe->off);
3595 req->files_update.nr_args = READ_ONCE(sqe->len);
3596 if (!req->files_update.nr_args)
3598 req->files_update.arg = READ_ONCE(sqe->addr);
3602 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
3604 struct io_ring_ctx *ctx = req->ctx;
3605 struct io_uring_files_update up;
3608 if (force_nonblock) {
3609 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
3613 up.offset = req->files_update.offset;
3614 up.fds = req->files_update.arg;
3616 mutex_lock(&ctx->uring_lock);
3617 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
3618 mutex_unlock(&ctx->uring_lock);
3621 req_set_fail_links(req);
3622 io_cqring_add_event(req, ret);
3627 static int io_req_defer_prep(struct io_kiocb *req,
3628 const struct io_uring_sqe *sqe)
3632 switch (req->opcode) {
3635 case IORING_OP_READV:
3636 case IORING_OP_READ_FIXED:
3637 ret = io_read_prep(req, sqe, true);
3639 case IORING_OP_WRITEV:
3640 case IORING_OP_WRITE_FIXED:
3641 ret = io_write_prep(req, sqe, true);
3643 case IORING_OP_POLL_ADD:
3644 ret = io_poll_add_prep(req, sqe);
3646 case IORING_OP_POLL_REMOVE:
3647 ret = io_poll_remove_prep(req, sqe);
3649 case IORING_OP_FSYNC:
3650 ret = io_prep_fsync(req, sqe);
3652 case IORING_OP_SYNC_FILE_RANGE:
3653 ret = io_prep_sfr(req, sqe);
3655 case IORING_OP_SENDMSG:
3656 ret = io_sendmsg_prep(req, sqe);
3658 case IORING_OP_RECVMSG:
3659 ret = io_recvmsg_prep(req, sqe);
3661 case IORING_OP_CONNECT:
3662 ret = io_connect_prep(req, sqe);
3664 case IORING_OP_TIMEOUT:
3665 ret = io_timeout_prep(req, sqe, false);
3667 case IORING_OP_TIMEOUT_REMOVE:
3668 ret = io_timeout_remove_prep(req, sqe);
3670 case IORING_OP_ASYNC_CANCEL:
3671 ret = io_async_cancel_prep(req, sqe);
3673 case IORING_OP_LINK_TIMEOUT:
3674 ret = io_timeout_prep(req, sqe, true);
3676 case IORING_OP_ACCEPT:
3677 ret = io_accept_prep(req, sqe);
3679 case IORING_OP_FALLOCATE:
3680 ret = io_fallocate_prep(req, sqe);
3682 case IORING_OP_OPENAT:
3683 ret = io_openat_prep(req, sqe);
3685 case IORING_OP_CLOSE:
3686 ret = io_close_prep(req, sqe);
3688 case IORING_OP_FILES_UPDATE:
3689 ret = io_files_update_prep(req, sqe);
3691 case IORING_OP_STATX:
3692 ret = io_statx_prep(req, sqe);
3695 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
3704 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3706 struct io_ring_ctx *ctx = req->ctx;
3709 /* Still need defer if there is pending req in defer list. */
3710 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
3713 if (!req->io && io_alloc_async_ctx(req))
3716 ret = io_req_defer_prep(req, sqe);
3720 spin_lock_irq(&ctx->completion_lock);
3721 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
3722 spin_unlock_irq(&ctx->completion_lock);
3726 trace_io_uring_defer(ctx, req, req->user_data);
3727 list_add_tail(&req->list, &ctx->defer_list);
3728 spin_unlock_irq(&ctx->completion_lock);
3729 return -EIOCBQUEUED;
3732 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3733 struct io_kiocb **nxt, bool force_nonblock)
3735 struct io_ring_ctx *ctx = req->ctx;
3738 switch (req->opcode) {
3742 case IORING_OP_READV:
3743 case IORING_OP_READ_FIXED:
3745 ret = io_read_prep(req, sqe, force_nonblock);
3749 ret = io_read(req, nxt, force_nonblock);
3751 case IORING_OP_WRITEV:
3752 case IORING_OP_WRITE_FIXED:
3754 ret = io_write_prep(req, sqe, force_nonblock);
3758 ret = io_write(req, nxt, force_nonblock);
3760 case IORING_OP_FSYNC:
3762 ret = io_prep_fsync(req, sqe);
3766 ret = io_fsync(req, nxt, force_nonblock);
3768 case IORING_OP_POLL_ADD:
3770 ret = io_poll_add_prep(req, sqe);
3774 ret = io_poll_add(req, nxt);
3776 case IORING_OP_POLL_REMOVE:
3778 ret = io_poll_remove_prep(req, sqe);
3782 ret = io_poll_remove(req);
3784 case IORING_OP_SYNC_FILE_RANGE:
3786 ret = io_prep_sfr(req, sqe);
3790 ret = io_sync_file_range(req, nxt, force_nonblock);
3792 case IORING_OP_SENDMSG:
3794 ret = io_sendmsg_prep(req, sqe);
3798 ret = io_sendmsg(req, nxt, force_nonblock);
3800 case IORING_OP_RECVMSG:
3802 ret = io_recvmsg_prep(req, sqe);
3806 ret = io_recvmsg(req, nxt, force_nonblock);
3808 case IORING_OP_TIMEOUT:
3810 ret = io_timeout_prep(req, sqe, false);
3814 ret = io_timeout(req);
3816 case IORING_OP_TIMEOUT_REMOVE:
3818 ret = io_timeout_remove_prep(req, sqe);
3822 ret = io_timeout_remove(req);
3824 case IORING_OP_ACCEPT:
3826 ret = io_accept_prep(req, sqe);
3830 ret = io_accept(req, nxt, force_nonblock);
3832 case IORING_OP_CONNECT:
3834 ret = io_connect_prep(req, sqe);
3838 ret = io_connect(req, nxt, force_nonblock);
3840 case IORING_OP_ASYNC_CANCEL:
3842 ret = io_async_cancel_prep(req, sqe);
3846 ret = io_async_cancel(req, nxt);
3848 case IORING_OP_FALLOCATE:
3850 ret = io_fallocate_prep(req, sqe);
3854 ret = io_fallocate(req, nxt, force_nonblock);
3856 case IORING_OP_OPENAT:
3858 ret = io_openat_prep(req, sqe);
3862 ret = io_openat(req, nxt, force_nonblock);
3864 case IORING_OP_CLOSE:
3866 ret = io_close_prep(req, sqe);
3870 ret = io_close(req, nxt, force_nonblock);
3872 case IORING_OP_FILES_UPDATE:
3874 ret = io_files_update_prep(req, sqe);
3878 ret = io_files_update(req, force_nonblock);
3880 case IORING_OP_STATX:
3882 ret = io_statx_prep(req, sqe);
3886 ret = io_statx(req, nxt, force_nonblock);
3896 if (ctx->flags & IORING_SETUP_IOPOLL) {
3897 const bool in_async = io_wq_current_is_worker();
3899 if (req->result == -EAGAIN)
3902 /* workqueue context doesn't hold uring_lock, grab it now */
3904 mutex_lock(&ctx->uring_lock);
3906 io_iopoll_req_issued(req);
3909 mutex_unlock(&ctx->uring_lock);
3915 static void io_wq_submit_work(struct io_wq_work **workptr)
3917 struct io_wq_work *work = *workptr;
3918 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3919 struct io_kiocb *nxt = NULL;
3922 /* if NO_CANCEL is set, we must still run the work */
3923 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
3924 IO_WQ_WORK_CANCEL) {
3929 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
3930 req->in_async = true;
3932 ret = io_issue_sqe(req, NULL, &nxt, false);
3934 * We can get EAGAIN for polled IO even though we're
3935 * forcing a sync submission from here, since we can't
3936 * wait for request slots on the block side.
3944 /* drop submission reference */
3948 req_set_fail_links(req);
3949 io_cqring_add_event(req, ret);
3953 /* if a dependent link is ready, pass it back */
3955 io_wq_assign_next(workptr, nxt);
3958 static int io_req_needs_file(struct io_kiocb *req, int fd)
3960 if (!io_op_defs[req->opcode].needs_file)
3962 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
3967 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
3970 struct fixed_file_table *table;
3972 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
3973 return table->files[index & IORING_FILE_TABLE_MASK];;
3976 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
3977 const struct io_uring_sqe *sqe)
3979 struct io_ring_ctx *ctx = req->ctx;
3983 flags = READ_ONCE(sqe->flags);
3984 fd = READ_ONCE(sqe->fd);
3986 if (flags & IOSQE_IO_DRAIN)
3987 req->flags |= REQ_F_IO_DRAIN;
3989 if (!io_req_needs_file(req, fd))
3992 if (flags & IOSQE_FIXED_FILE) {
3993 if (unlikely(!ctx->file_data ||
3994 (unsigned) fd >= ctx->nr_user_files))
3996 fd = array_index_nospec(fd, ctx->nr_user_files);
3997 req->file = io_file_from_index(ctx, fd);
4000 req->flags |= REQ_F_FIXED_FILE;
4001 percpu_ref_get(&ctx->file_data->refs);
4003 if (req->needs_fixed_file)
4005 trace_io_uring_file_get(ctx, fd);
4006 req->file = io_file_get(state, fd);
4007 if (unlikely(!req->file))
4014 static int io_grab_files(struct io_kiocb *req)
4017 struct io_ring_ctx *ctx = req->ctx;
4019 if (!req->ring_file)
4023 spin_lock_irq(&ctx->inflight_lock);
4025 * We use the f_ops->flush() handler to ensure that we can flush
4026 * out work accessing these files if the fd is closed. Check if
4027 * the fd has changed since we started down this path, and disallow
4028 * this operation if it has.
4030 if (fcheck(req->ring_fd) == req->ring_file) {
4031 list_add(&req->inflight_entry, &ctx->inflight_list);
4032 req->flags |= REQ_F_INFLIGHT;
4033 req->work.files = current->files;
4036 spin_unlock_irq(&ctx->inflight_lock);
4042 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4044 struct io_timeout_data *data = container_of(timer,
4045 struct io_timeout_data, timer);
4046 struct io_kiocb *req = data->req;
4047 struct io_ring_ctx *ctx = req->ctx;
4048 struct io_kiocb *prev = NULL;
4049 unsigned long flags;
4051 spin_lock_irqsave(&ctx->completion_lock, flags);
4054 * We don't expect the list to be empty, that will only happen if we
4055 * race with the completion of the linked work.
4057 if (!list_empty(&req->link_list)) {
4058 prev = list_entry(req->link_list.prev, struct io_kiocb,
4060 if (refcount_inc_not_zero(&prev->refs)) {
4061 list_del_init(&req->link_list);
4062 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4067 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4070 req_set_fail_links(prev);
4071 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4075 io_cqring_add_event(req, -ETIME);
4078 return HRTIMER_NORESTART;
4081 static void io_queue_linked_timeout(struct io_kiocb *req)
4083 struct io_ring_ctx *ctx = req->ctx;
4086 * If the list is now empty, then our linked request finished before
4087 * we got a chance to setup the timer
4089 spin_lock_irq(&ctx->completion_lock);
4090 if (!list_empty(&req->link_list)) {
4091 struct io_timeout_data *data = &req->io->timeout;
4093 data->timer.function = io_link_timeout_fn;
4094 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4097 spin_unlock_irq(&ctx->completion_lock);
4099 /* drop submission reference */
4103 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4105 struct io_kiocb *nxt;
4107 if (!(req->flags & REQ_F_LINK))
4110 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4112 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4115 req->flags |= REQ_F_LINK_TIMEOUT;
4119 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4121 struct io_kiocb *linked_timeout;
4122 struct io_kiocb *nxt = NULL;
4126 linked_timeout = io_prep_linked_timeout(req);
4128 ret = io_issue_sqe(req, sqe, &nxt, true);
4131 * We async punt it if the file wasn't marked NOWAIT, or if the file
4132 * doesn't support non-blocking read/write attempts
4134 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4135 (req->flags & REQ_F_MUST_PUNT))) {
4136 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
4137 ret = io_grab_files(req);
4143 * Queued up for async execution, worker will release
4144 * submit reference when the iocb is actually submitted.
4146 io_queue_async_work(req);
4151 /* drop submission reference */
4154 if (linked_timeout) {
4156 io_queue_linked_timeout(linked_timeout);
4158 io_put_req(linked_timeout);
4161 /* and drop final reference, if we failed */
4163 io_cqring_add_event(req, ret);
4164 req_set_fail_links(req);
4175 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4179 if (unlikely(req->ctx->drain_next)) {
4180 req->flags |= REQ_F_IO_DRAIN;
4181 req->ctx->drain_next = false;
4183 req->ctx->drain_next = (req->flags & REQ_F_DRAIN_LINK);
4185 ret = io_req_defer(req, sqe);
4187 if (ret != -EIOCBQUEUED) {
4188 io_cqring_add_event(req, ret);
4189 req_set_fail_links(req);
4190 io_double_put_req(req);
4192 } else if ((req->flags & REQ_F_FORCE_ASYNC) &&
4193 !io_wq_current_is_worker()) {
4195 * Never try inline submit of IOSQE_ASYNC is set, go straight
4196 * to async execution.
4198 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4199 io_queue_async_work(req);
4201 __io_queue_sqe(req, sqe);
4205 static inline void io_queue_link_head(struct io_kiocb *req)
4207 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4208 io_cqring_add_event(req, -ECANCELED);
4209 io_double_put_req(req);
4211 io_queue_sqe(req, NULL);
4214 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4215 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4217 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4218 struct io_submit_state *state, struct io_kiocb **link)
4220 struct io_ring_ctx *ctx = req->ctx;
4221 unsigned int sqe_flags;
4224 sqe_flags = READ_ONCE(sqe->flags);
4226 /* enforce forwards compatibility on users */
4227 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4231 if (sqe_flags & IOSQE_ASYNC)
4232 req->flags |= REQ_F_FORCE_ASYNC;
4234 ret = io_req_set_file(state, req, sqe);
4235 if (unlikely(ret)) {
4237 io_cqring_add_event(req, ret);
4238 io_double_put_req(req);
4243 * If we already have a head request, queue this one for async
4244 * submittal once the head completes. If we don't have a head but
4245 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4246 * submitted sync once the chain is complete. If none of those
4247 * conditions are true (normal request), then just queue it.
4250 struct io_kiocb *head = *link;
4252 if (sqe_flags & IOSQE_IO_DRAIN)
4253 head->flags |= REQ_F_DRAIN_LINK | REQ_F_IO_DRAIN;
4255 if (sqe_flags & IOSQE_IO_HARDLINK)
4256 req->flags |= REQ_F_HARDLINK;
4258 if (io_alloc_async_ctx(req)) {
4263 ret = io_req_defer_prep(req, sqe);
4265 /* fail even hard links since we don't submit */
4266 head->flags |= REQ_F_FAIL_LINK;
4269 trace_io_uring_link(ctx, req, head);
4270 list_add_tail(&req->link_list, &head->link_list);
4272 /* last request of a link, enqueue the link */
4273 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4274 io_queue_link_head(head);
4277 } else if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4278 req->flags |= REQ_F_LINK;
4279 if (sqe_flags & IOSQE_IO_HARDLINK)
4280 req->flags |= REQ_F_HARDLINK;
4282 INIT_LIST_HEAD(&req->link_list);
4283 ret = io_req_defer_prep(req, sqe);
4285 req->flags |= REQ_F_FAIL_LINK;
4288 io_queue_sqe(req, sqe);
4295 * Batched submission is done, ensure local IO is flushed out.
4297 static void io_submit_state_end(struct io_submit_state *state)
4299 blk_finish_plug(&state->plug);
4301 if (state->free_reqs)
4302 kmem_cache_free_bulk(req_cachep, state->free_reqs,
4303 &state->reqs[state->cur_req]);
4307 * Start submission side cache.
4309 static void io_submit_state_start(struct io_submit_state *state,
4310 unsigned int max_ios)
4312 blk_start_plug(&state->plug);
4313 state->free_reqs = 0;
4315 state->ios_left = max_ios;
4318 static void io_commit_sqring(struct io_ring_ctx *ctx)
4320 struct io_rings *rings = ctx->rings;
4322 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
4324 * Ensure any loads from the SQEs are done at this point,
4325 * since once we write the new head, the application could
4326 * write new data to them.
4328 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4333 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4334 * that is mapped by userspace. This means that care needs to be taken to
4335 * ensure that reads are stable, as we cannot rely on userspace always
4336 * being a good citizen. If members of the sqe are validated and then later
4337 * used, it's important that those reads are done through READ_ONCE() to
4338 * prevent a re-load down the line.
4340 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4341 const struct io_uring_sqe **sqe_ptr)
4343 struct io_rings *rings = ctx->rings;
4344 u32 *sq_array = ctx->sq_array;
4348 * The cached sq head (or cq tail) serves two purposes:
4350 * 1) allows us to batch the cost of updating the user visible
4352 * 2) allows the kernel side to track the head on its own, even
4353 * though the application is the one updating it.
4355 head = ctx->cached_sq_head;
4356 /* make sure SQ entry isn't read before tail */
4357 if (unlikely(head == smp_load_acquire(&rings->sq.tail)))
4360 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
4361 if (likely(head < ctx->sq_entries)) {
4363 * All io need record the previous position, if LINK vs DARIN,
4364 * it can be used to mark the position of the first IO in the
4367 req->sequence = ctx->cached_sq_head;
4368 *sqe_ptr = &ctx->sq_sqes[head];
4369 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4370 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4371 ctx->cached_sq_head++;
4375 /* drop invalid entries */
4376 ctx->cached_sq_head++;
4377 ctx->cached_sq_dropped++;
4378 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
4382 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4383 struct file *ring_file, int ring_fd,
4384 struct mm_struct **mm, bool async)
4386 struct io_submit_state state, *statep = NULL;
4387 struct io_kiocb *link = NULL;
4388 int i, submitted = 0;
4389 bool mm_fault = false;
4391 /* if we have a backlog and couldn't flush it all, return BUSY */
4392 if (test_bit(0, &ctx->sq_check_overflow)) {
4393 if (!list_empty(&ctx->cq_overflow_list) &&
4394 !io_cqring_overflow_flush(ctx, false))
4398 if (nr > IO_PLUG_THRESHOLD) {
4399 io_submit_state_start(&state, nr);
4403 for (i = 0; i < nr; i++) {
4404 const struct io_uring_sqe *sqe;
4405 struct io_kiocb *req;
4407 req = io_get_req(ctx, statep);
4408 if (unlikely(!req)) {
4410 submitted = -EAGAIN;
4413 if (!io_get_sqring(ctx, req, &sqe)) {
4418 /* will complete beyond this point, count as submitted */
4421 if (unlikely(req->opcode >= IORING_OP_LAST)) {
4422 io_cqring_add_event(req, -EINVAL);
4423 io_double_put_req(req);
4427 if (io_op_defs[req->opcode].needs_mm && !*mm) {
4428 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
4430 use_mm(ctx->sqo_mm);
4435 req->ring_file = ring_file;
4436 req->ring_fd = ring_fd;
4437 req->has_user = *mm != NULL;
4438 req->in_async = async;
4439 req->needs_fixed_file = async;
4440 trace_io_uring_submit_sqe(ctx, req->user_data, true, async);
4441 if (!io_submit_sqe(req, sqe, statep, &link))
4446 io_queue_link_head(link);
4448 io_submit_state_end(&state);
4450 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4451 io_commit_sqring(ctx);
4456 static int io_sq_thread(void *data)
4458 struct io_ring_ctx *ctx = data;
4459 struct mm_struct *cur_mm = NULL;
4460 const struct cred *old_cred;
4461 mm_segment_t old_fs;
4464 unsigned long timeout;
4467 complete(&ctx->completions[1]);
4471 old_cred = override_creds(ctx->creds);
4473 ret = timeout = inflight = 0;
4474 while (!kthread_should_park()) {
4475 unsigned int to_submit;
4478 unsigned nr_events = 0;
4480 if (ctx->flags & IORING_SETUP_IOPOLL) {
4482 * inflight is the count of the maximum possible
4483 * entries we submitted, but it can be smaller
4484 * if we dropped some of them. If we don't have
4485 * poll entries available, then we know that we
4486 * have nothing left to poll for. Reset the
4487 * inflight count to zero in that case.
4489 mutex_lock(&ctx->uring_lock);
4490 if (!list_empty(&ctx->poll_list))
4491 __io_iopoll_check(ctx, &nr_events, 0);
4494 mutex_unlock(&ctx->uring_lock);
4497 * Normal IO, just pretend everything completed.
4498 * We don't have to poll completions for that.
4500 nr_events = inflight;
4503 inflight -= nr_events;
4505 timeout = jiffies + ctx->sq_thread_idle;
4508 to_submit = io_sqring_entries(ctx);
4511 * If submit got -EBUSY, flag us as needing the application
4512 * to enter the kernel to reap and flush events.
4514 if (!to_submit || ret == -EBUSY) {
4516 * We're polling. If we're within the defined idle
4517 * period, then let us spin without work before going
4518 * to sleep. The exception is if we got EBUSY doing
4519 * more IO, we should wait for the application to
4520 * reap events and wake us up.
4523 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
4529 * Drop cur_mm before scheduling, we can't hold it for
4530 * long periods (or over schedule()). Do this before
4531 * adding ourselves to the waitqueue, as the unuse/drop
4540 prepare_to_wait(&ctx->sqo_wait, &wait,
4541 TASK_INTERRUPTIBLE);
4543 /* Tell userspace we may need a wakeup call */
4544 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
4545 /* make sure to read SQ tail after writing flags */
4548 to_submit = io_sqring_entries(ctx);
4549 if (!to_submit || ret == -EBUSY) {
4550 if (kthread_should_park()) {
4551 finish_wait(&ctx->sqo_wait, &wait);
4554 if (signal_pending(current))
4555 flush_signals(current);
4557 finish_wait(&ctx->sqo_wait, &wait);
4559 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4562 finish_wait(&ctx->sqo_wait, &wait);
4564 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4567 to_submit = min(to_submit, ctx->sq_entries);
4568 mutex_lock(&ctx->uring_lock);
4569 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
4570 mutex_unlock(&ctx->uring_lock);
4580 revert_creds(old_cred);
4587 struct io_wait_queue {
4588 struct wait_queue_entry wq;
4589 struct io_ring_ctx *ctx;
4591 unsigned nr_timeouts;
4594 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
4596 struct io_ring_ctx *ctx = iowq->ctx;
4599 * Wake up if we have enough events, or if a timeout occurred since we
4600 * started waiting. For timeouts, we always want to return to userspace,
4601 * regardless of event count.
4603 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
4604 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4607 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
4608 int wake_flags, void *key)
4610 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
4613 /* use noflush == true, as we can't safely rely on locking context */
4614 if (!io_should_wake(iowq, true))
4617 return autoremove_wake_function(curr, mode, wake_flags, key);
4621 * Wait until events become available, if we don't already have some. The
4622 * application must reap them itself, as they reside on the shared cq ring.
4624 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
4625 const sigset_t __user *sig, size_t sigsz)
4627 struct io_wait_queue iowq = {
4630 .func = io_wake_function,
4631 .entry = LIST_HEAD_INIT(iowq.wq.entry),
4634 .to_wait = min_events,
4636 struct io_rings *rings = ctx->rings;
4639 if (io_cqring_events(ctx, false) >= min_events)
4643 #ifdef CONFIG_COMPAT
4644 if (in_compat_syscall())
4645 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
4649 ret = set_user_sigmask(sig, sigsz);
4655 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
4656 trace_io_uring_cqring_wait(ctx, min_events);
4658 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
4659 TASK_INTERRUPTIBLE);
4660 if (io_should_wake(&iowq, false))
4663 if (signal_pending(current)) {
4668 finish_wait(&ctx->wait, &iowq.wq);
4670 restore_saved_sigmask_unless(ret == -EINTR);
4672 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
4675 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4677 #if defined(CONFIG_UNIX)
4678 if (ctx->ring_sock) {
4679 struct sock *sock = ctx->ring_sock->sk;
4680 struct sk_buff *skb;
4682 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4688 for (i = 0; i < ctx->nr_user_files; i++) {
4691 file = io_file_from_index(ctx, i);
4698 static void io_file_ref_kill(struct percpu_ref *ref)
4700 struct fixed_file_data *data;
4702 data = container_of(ref, struct fixed_file_data, refs);
4703 complete(&data->done);
4706 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4708 struct fixed_file_data *data = ctx->file_data;
4709 unsigned nr_tables, i;
4714 /* protect against inflight atomic switch, which drops the ref */
4715 flush_work(&data->ref_work);
4716 percpu_ref_get(&data->refs);
4717 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
4718 wait_for_completion(&data->done);
4719 percpu_ref_put(&data->refs);
4720 percpu_ref_exit(&data->refs);
4722 __io_sqe_files_unregister(ctx);
4723 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
4724 for (i = 0; i < nr_tables; i++)
4725 kfree(data->table[i].files);
4728 ctx->file_data = NULL;
4729 ctx->nr_user_files = 0;
4733 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
4735 if (ctx->sqo_thread) {
4736 wait_for_completion(&ctx->completions[1]);
4738 * The park is a bit of a work-around, without it we get
4739 * warning spews on shutdown with SQPOLL set and affinity
4740 * set to a single CPU.
4742 kthread_park(ctx->sqo_thread);
4743 kthread_stop(ctx->sqo_thread);
4744 ctx->sqo_thread = NULL;
4748 static void io_finish_async(struct io_ring_ctx *ctx)
4750 io_sq_thread_stop(ctx);
4753 io_wq_destroy(ctx->io_wq);
4758 #if defined(CONFIG_UNIX)
4760 * Ensure the UNIX gc is aware of our file set, so we are certain that
4761 * the io_uring can be safely unregistered on process exit, even if we have
4762 * loops in the file referencing.
4764 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
4766 struct sock *sk = ctx->ring_sock->sk;
4767 struct scm_fp_list *fpl;
4768 struct sk_buff *skb;
4771 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
4772 unsigned long inflight = ctx->user->unix_inflight + nr;
4774 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
4778 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4782 skb = alloc_skb(0, GFP_KERNEL);
4791 fpl->user = get_uid(ctx->user);
4792 for (i = 0; i < nr; i++) {
4793 struct file *file = io_file_from_index(ctx, i + offset);
4797 fpl->fp[nr_files] = get_file(file);
4798 unix_inflight(fpl->user, fpl->fp[nr_files]);
4803 fpl->max = SCM_MAX_FD;
4804 fpl->count = nr_files;
4805 UNIXCB(skb).fp = fpl;
4806 skb->destructor = unix_destruct_scm;
4807 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4808 skb_queue_head(&sk->sk_receive_queue, skb);
4810 for (i = 0; i < nr_files; i++)
4821 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
4822 * causes regular reference counting to break down. We rely on the UNIX
4823 * garbage collection to take care of this problem for us.
4825 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4827 unsigned left, total;
4831 left = ctx->nr_user_files;
4833 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
4835 ret = __io_sqe_files_scm(ctx, this_files, total);
4839 total += this_files;
4845 while (total < ctx->nr_user_files) {
4846 struct file *file = io_file_from_index(ctx, total);
4856 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4862 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
4867 for (i = 0; i < nr_tables; i++) {
4868 struct fixed_file_table *table = &ctx->file_data->table[i];
4869 unsigned this_files;
4871 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
4872 table->files = kcalloc(this_files, sizeof(struct file *),
4876 nr_files -= this_files;
4882 for (i = 0; i < nr_tables; i++) {
4883 struct fixed_file_table *table = &ctx->file_data->table[i];
4884 kfree(table->files);
4889 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
4891 #if defined(CONFIG_UNIX)
4892 struct sock *sock = ctx->ring_sock->sk;
4893 struct sk_buff_head list, *head = &sock->sk_receive_queue;
4894 struct sk_buff *skb;
4897 __skb_queue_head_init(&list);
4900 * Find the skb that holds this file in its SCM_RIGHTS. When found,
4901 * remove this entry and rearrange the file array.
4903 skb = skb_dequeue(head);
4905 struct scm_fp_list *fp;
4907 fp = UNIXCB(skb).fp;
4908 for (i = 0; i < fp->count; i++) {
4911 if (fp->fp[i] != file)
4914 unix_notinflight(fp->user, fp->fp[i]);
4915 left = fp->count - 1 - i;
4917 memmove(&fp->fp[i], &fp->fp[i + 1],
4918 left * sizeof(struct file *));
4925 __skb_queue_tail(&list, skb);
4935 __skb_queue_tail(&list, skb);
4937 skb = skb_dequeue(head);
4940 if (skb_peek(&list)) {
4941 spin_lock_irq(&head->lock);
4942 while ((skb = __skb_dequeue(&list)) != NULL)
4943 __skb_queue_tail(head, skb);
4944 spin_unlock_irq(&head->lock);
4951 struct io_file_put {
4952 struct llist_node llist;
4954 struct completion *done;
4957 static void io_ring_file_ref_switch(struct work_struct *work)
4959 struct io_file_put *pfile, *tmp;
4960 struct fixed_file_data *data;
4961 struct llist_node *node;
4963 data = container_of(work, struct fixed_file_data, ref_work);
4965 while ((node = llist_del_all(&data->put_llist)) != NULL) {
4966 llist_for_each_entry_safe(pfile, tmp, node, llist) {
4967 io_ring_file_put(data->ctx, pfile->file);
4969 complete(pfile->done);
4975 percpu_ref_get(&data->refs);
4976 percpu_ref_switch_to_percpu(&data->refs);
4979 static void io_file_data_ref_zero(struct percpu_ref *ref)
4981 struct fixed_file_data *data;
4983 data = container_of(ref, struct fixed_file_data, refs);
4985 /* we can't safely switch from inside this context, punt to wq */
4986 queue_work(system_wq, &data->ref_work);
4989 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4992 __s32 __user *fds = (__s32 __user *) arg;
5002 if (nr_args > IORING_MAX_FIXED_FILES)
5005 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5006 if (!ctx->file_data)
5008 ctx->file_data->ctx = ctx;
5009 init_completion(&ctx->file_data->done);
5011 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5012 ctx->file_data->table = kcalloc(nr_tables,
5013 sizeof(struct fixed_file_table),
5015 if (!ctx->file_data->table) {
5016 kfree(ctx->file_data);
5017 ctx->file_data = NULL;
5021 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5022 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5023 kfree(ctx->file_data->table);
5024 kfree(ctx->file_data);
5025 ctx->file_data = NULL;
5028 ctx->file_data->put_llist.first = NULL;
5029 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5031 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5032 percpu_ref_exit(&ctx->file_data->refs);
5033 kfree(ctx->file_data->table);
5034 kfree(ctx->file_data);
5035 ctx->file_data = NULL;
5039 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5040 struct fixed_file_table *table;
5044 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5046 /* allow sparse sets */
5052 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5053 index = i & IORING_FILE_TABLE_MASK;
5061 * Don't allow io_uring instances to be registered. If UNIX
5062 * isn't enabled, then this causes a reference cycle and this
5063 * instance can never get freed. If UNIX is enabled we'll
5064 * handle it just fine, but there's still no point in allowing
5065 * a ring fd as it doesn't support regular read/write anyway.
5067 if (file->f_op == &io_uring_fops) {
5072 table->files[index] = file;
5076 for (i = 0; i < ctx->nr_user_files; i++) {
5077 file = io_file_from_index(ctx, i);
5081 for (i = 0; i < nr_tables; i++)
5082 kfree(ctx->file_data->table[i].files);
5084 kfree(ctx->file_data->table);
5085 kfree(ctx->file_data);
5086 ctx->file_data = NULL;
5087 ctx->nr_user_files = 0;
5091 ret = io_sqe_files_scm(ctx);
5093 io_sqe_files_unregister(ctx);
5098 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5101 #if defined(CONFIG_UNIX)
5102 struct sock *sock = ctx->ring_sock->sk;
5103 struct sk_buff_head *head = &sock->sk_receive_queue;
5104 struct sk_buff *skb;
5107 * See if we can merge this file into an existing skb SCM_RIGHTS
5108 * file set. If there's no room, fall back to allocating a new skb
5109 * and filling it in.
5111 spin_lock_irq(&head->lock);
5112 skb = skb_peek(head);
5114 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5116 if (fpl->count < SCM_MAX_FD) {
5117 __skb_unlink(skb, head);
5118 spin_unlock_irq(&head->lock);
5119 fpl->fp[fpl->count] = get_file(file);
5120 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5122 spin_lock_irq(&head->lock);
5123 __skb_queue_head(head, skb);
5128 spin_unlock_irq(&head->lock);
5135 return __io_sqe_files_scm(ctx, 1, index);
5141 static void io_atomic_switch(struct percpu_ref *ref)
5143 struct fixed_file_data *data;
5145 data = container_of(ref, struct fixed_file_data, refs);
5146 clear_bit(FFD_F_ATOMIC, &data->state);
5149 static bool io_queue_file_removal(struct fixed_file_data *data,
5152 struct io_file_put *pfile, pfile_stack;
5153 DECLARE_COMPLETION_ONSTACK(done);
5156 * If we fail allocating the struct we need for doing async reomval
5157 * of this file, just punt to sync and wait for it.
5159 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5161 pfile = &pfile_stack;
5162 pfile->done = &done;
5166 llist_add(&pfile->llist, &data->put_llist);
5168 if (pfile == &pfile_stack) {
5169 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5170 percpu_ref_put(&data->refs);
5171 percpu_ref_switch_to_atomic(&data->refs,
5174 wait_for_completion(&done);
5175 flush_work(&data->ref_work);
5182 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5183 struct io_uring_files_update *up,
5186 struct fixed_file_data *data = ctx->file_data;
5187 bool ref_switch = false;
5193 if (check_add_overflow(up->offset, nr_args, &done))
5195 if (done > ctx->nr_user_files)
5199 fds = u64_to_user_ptr(up->fds);
5201 struct fixed_file_table *table;
5205 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5209 i = array_index_nospec(up->offset, ctx->nr_user_files);
5210 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5211 index = i & IORING_FILE_TABLE_MASK;
5212 if (table->files[index]) {
5213 file = io_file_from_index(ctx, index);
5214 table->files[index] = NULL;
5215 if (io_queue_file_removal(data, file))
5225 * Don't allow io_uring instances to be registered. If
5226 * UNIX isn't enabled, then this causes a reference
5227 * cycle and this instance can never get freed. If UNIX
5228 * is enabled we'll handle it just fine, but there's
5229 * still no point in allowing a ring fd as it doesn't
5230 * support regular read/write anyway.
5232 if (file->f_op == &io_uring_fops) {
5237 table->files[index] = file;
5238 err = io_sqe_file_register(ctx, file, i);
5247 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5248 percpu_ref_put(&data->refs);
5249 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5252 return done ? done : err;
5254 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5257 struct io_uring_files_update up;
5259 if (!ctx->file_data)
5263 if (copy_from_user(&up, arg, sizeof(up)))
5268 return __io_sqe_files_update(ctx, &up, nr_args);
5271 static void io_put_work(struct io_wq_work *work)
5273 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5278 static void io_get_work(struct io_wq_work *work)
5280 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5282 refcount_inc(&req->refs);
5285 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5286 struct io_uring_params *p)
5288 struct io_wq_data data;
5289 unsigned concurrency;
5292 init_waitqueue_head(&ctx->sqo_wait);
5293 mmgrab(current->mm);
5294 ctx->sqo_mm = current->mm;
5296 if (ctx->flags & IORING_SETUP_SQPOLL) {
5298 if (!capable(CAP_SYS_ADMIN))
5301 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5302 if (!ctx->sq_thread_idle)
5303 ctx->sq_thread_idle = HZ;
5305 if (p->flags & IORING_SETUP_SQ_AFF) {
5306 int cpu = p->sq_thread_cpu;
5309 if (cpu >= nr_cpu_ids)
5311 if (!cpu_online(cpu))
5314 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5318 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5321 if (IS_ERR(ctx->sqo_thread)) {
5322 ret = PTR_ERR(ctx->sqo_thread);
5323 ctx->sqo_thread = NULL;
5326 wake_up_process(ctx->sqo_thread);
5327 } else if (p->flags & IORING_SETUP_SQ_AFF) {
5328 /* Can't have SQ_AFF without SQPOLL */
5333 data.mm = ctx->sqo_mm;
5334 data.user = ctx->user;
5335 data.creds = ctx->creds;
5336 data.get_work = io_get_work;
5337 data.put_work = io_put_work;
5339 /* Do QD, or 4 * CPUS, whatever is smallest */
5340 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5341 ctx->io_wq = io_wq_create(concurrency, &data);
5342 if (IS_ERR(ctx->io_wq)) {
5343 ret = PTR_ERR(ctx->io_wq);
5350 io_finish_async(ctx);
5351 mmdrop(ctx->sqo_mm);
5356 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
5358 atomic_long_sub(nr_pages, &user->locked_vm);
5361 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
5363 unsigned long page_limit, cur_pages, new_pages;
5365 /* Don't allow more pages than we can safely lock */
5366 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5369 cur_pages = atomic_long_read(&user->locked_vm);
5370 new_pages = cur_pages + nr_pages;
5371 if (new_pages > page_limit)
5373 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5374 new_pages) != cur_pages);
5379 static void io_mem_free(void *ptr)
5386 page = virt_to_head_page(ptr);
5387 if (put_page_testzero(page))
5388 free_compound_page(page);
5391 static void *io_mem_alloc(size_t size)
5393 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
5396 return (void *) __get_free_pages(gfp_flags, get_order(size));
5399 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
5402 struct io_rings *rings;
5403 size_t off, sq_array_size;
5405 off = struct_size(rings, cqes, cq_entries);
5406 if (off == SIZE_MAX)
5410 off = ALIGN(off, SMP_CACHE_BYTES);
5415 sq_array_size = array_size(sizeof(u32), sq_entries);
5416 if (sq_array_size == SIZE_MAX)
5419 if (check_add_overflow(off, sq_array_size, &off))
5428 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
5432 pages = (size_t)1 << get_order(
5433 rings_size(sq_entries, cq_entries, NULL));
5434 pages += (size_t)1 << get_order(
5435 array_size(sizeof(struct io_uring_sqe), sq_entries));
5440 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
5444 if (!ctx->user_bufs)
5447 for (i = 0; i < ctx->nr_user_bufs; i++) {
5448 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5450 for (j = 0; j < imu->nr_bvecs; j++)
5451 put_user_page(imu->bvec[j].bv_page);
5453 if (ctx->account_mem)
5454 io_unaccount_mem(ctx->user, imu->nr_bvecs);
5459 kfree(ctx->user_bufs);
5460 ctx->user_bufs = NULL;
5461 ctx->nr_user_bufs = 0;
5465 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
5466 void __user *arg, unsigned index)
5468 struct iovec __user *src;
5470 #ifdef CONFIG_COMPAT
5472 struct compat_iovec __user *ciovs;
5473 struct compat_iovec ciov;
5475 ciovs = (struct compat_iovec __user *) arg;
5476 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
5479 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
5480 dst->iov_len = ciov.iov_len;
5484 src = (struct iovec __user *) arg;
5485 if (copy_from_user(dst, &src[index], sizeof(*dst)))
5490 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
5493 struct vm_area_struct **vmas = NULL;
5494 struct page **pages = NULL;
5495 int i, j, got_pages = 0;
5500 if (!nr_args || nr_args > UIO_MAXIOV)
5503 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
5505 if (!ctx->user_bufs)
5508 for (i = 0; i < nr_args; i++) {
5509 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5510 unsigned long off, start, end, ubuf;
5515 ret = io_copy_iov(ctx, &iov, arg, i);
5520 * Don't impose further limits on the size and buffer
5521 * constraints here, we'll -EINVAL later when IO is
5522 * submitted if they are wrong.
5525 if (!iov.iov_base || !iov.iov_len)
5528 /* arbitrary limit, but we need something */
5529 if (iov.iov_len > SZ_1G)
5532 ubuf = (unsigned long) iov.iov_base;
5533 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
5534 start = ubuf >> PAGE_SHIFT;
5535 nr_pages = end - start;
5537 if (ctx->account_mem) {
5538 ret = io_account_mem(ctx->user, nr_pages);
5544 if (!pages || nr_pages > got_pages) {
5547 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
5549 vmas = kvmalloc_array(nr_pages,
5550 sizeof(struct vm_area_struct *),
5552 if (!pages || !vmas) {
5554 if (ctx->account_mem)
5555 io_unaccount_mem(ctx->user, nr_pages);
5558 got_pages = nr_pages;
5561 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
5565 if (ctx->account_mem)
5566 io_unaccount_mem(ctx->user, nr_pages);
5571 down_read(¤t->mm->mmap_sem);
5572 pret = get_user_pages(ubuf, nr_pages,
5573 FOLL_WRITE | FOLL_LONGTERM,
5575 if (pret == nr_pages) {
5576 /* don't support file backed memory */
5577 for (j = 0; j < nr_pages; j++) {
5578 struct vm_area_struct *vma = vmas[j];
5581 !is_file_hugepages(vma->vm_file)) {
5587 ret = pret < 0 ? pret : -EFAULT;
5589 up_read(¤t->mm->mmap_sem);
5592 * if we did partial map, or found file backed vmas,
5593 * release any pages we did get
5596 put_user_pages(pages, pret);
5597 if (ctx->account_mem)
5598 io_unaccount_mem(ctx->user, nr_pages);
5603 off = ubuf & ~PAGE_MASK;
5605 for (j = 0; j < nr_pages; j++) {
5608 vec_len = min_t(size_t, size, PAGE_SIZE - off);
5609 imu->bvec[j].bv_page = pages[j];
5610 imu->bvec[j].bv_len = vec_len;
5611 imu->bvec[j].bv_offset = off;
5615 /* store original address for later verification */
5617 imu->len = iov.iov_len;
5618 imu->nr_bvecs = nr_pages;
5620 ctx->nr_user_bufs++;
5628 io_sqe_buffer_unregister(ctx);
5632 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
5634 __s32 __user *fds = arg;
5640 if (copy_from_user(&fd, fds, sizeof(*fds)))
5643 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
5644 if (IS_ERR(ctx->cq_ev_fd)) {
5645 int ret = PTR_ERR(ctx->cq_ev_fd);
5646 ctx->cq_ev_fd = NULL;
5653 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
5655 if (ctx->cq_ev_fd) {
5656 eventfd_ctx_put(ctx->cq_ev_fd);
5657 ctx->cq_ev_fd = NULL;
5664 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
5666 io_finish_async(ctx);
5668 mmdrop(ctx->sqo_mm);
5670 io_iopoll_reap_events(ctx);
5671 io_sqe_buffer_unregister(ctx);
5672 io_sqe_files_unregister(ctx);
5673 io_eventfd_unregister(ctx);
5675 #if defined(CONFIG_UNIX)
5676 if (ctx->ring_sock) {
5677 ctx->ring_sock->file = NULL; /* so that iput() is called */
5678 sock_release(ctx->ring_sock);
5682 io_mem_free(ctx->rings);
5683 io_mem_free(ctx->sq_sqes);
5685 percpu_ref_exit(&ctx->refs);
5686 if (ctx->account_mem)
5687 io_unaccount_mem(ctx->user,
5688 ring_pages(ctx->sq_entries, ctx->cq_entries));
5689 free_uid(ctx->user);
5690 put_cred(ctx->creds);
5691 kfree(ctx->completions);
5692 kfree(ctx->cancel_hash);
5693 kmem_cache_free(req_cachep, ctx->fallback_req);
5697 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
5699 struct io_ring_ctx *ctx = file->private_data;
5702 poll_wait(file, &ctx->cq_wait, wait);
5704 * synchronizes with barrier from wq_has_sleeper call in
5708 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
5709 ctx->rings->sq_ring_entries)
5710 mask |= EPOLLOUT | EPOLLWRNORM;
5711 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
5712 mask |= EPOLLIN | EPOLLRDNORM;
5717 static int io_uring_fasync(int fd, struct file *file, int on)
5719 struct io_ring_ctx *ctx = file->private_data;
5721 return fasync_helper(fd, file, on, &ctx->cq_fasync);
5724 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
5726 mutex_lock(&ctx->uring_lock);
5727 percpu_ref_kill(&ctx->refs);
5728 mutex_unlock(&ctx->uring_lock);
5730 io_kill_timeouts(ctx);
5731 io_poll_remove_all(ctx);
5734 io_wq_cancel_all(ctx->io_wq);
5736 io_iopoll_reap_events(ctx);
5737 /* if we failed setting up the ctx, we might not have any rings */
5739 io_cqring_overflow_flush(ctx, true);
5740 wait_for_completion(&ctx->completions[0]);
5741 io_ring_ctx_free(ctx);
5744 static int io_uring_release(struct inode *inode, struct file *file)
5746 struct io_ring_ctx *ctx = file->private_data;
5748 file->private_data = NULL;
5749 io_ring_ctx_wait_and_kill(ctx);
5753 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
5754 struct files_struct *files)
5756 struct io_kiocb *req;
5759 while (!list_empty_careful(&ctx->inflight_list)) {
5760 struct io_kiocb *cancel_req = NULL;
5762 spin_lock_irq(&ctx->inflight_lock);
5763 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
5764 if (req->work.files != files)
5766 /* req is being completed, ignore */
5767 if (!refcount_inc_not_zero(&req->refs))
5773 prepare_to_wait(&ctx->inflight_wait, &wait,
5774 TASK_UNINTERRUPTIBLE);
5775 spin_unlock_irq(&ctx->inflight_lock);
5777 /* We need to keep going until we don't find a matching req */
5781 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
5782 io_put_req(cancel_req);
5785 finish_wait(&ctx->inflight_wait, &wait);
5788 static int io_uring_flush(struct file *file, void *data)
5790 struct io_ring_ctx *ctx = file->private_data;
5792 io_uring_cancel_files(ctx, data);
5793 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
5794 io_cqring_overflow_flush(ctx, true);
5795 io_wq_cancel_all(ctx->io_wq);
5800 static void *io_uring_validate_mmap_request(struct file *file,
5801 loff_t pgoff, size_t sz)
5803 struct io_ring_ctx *ctx = file->private_data;
5804 loff_t offset = pgoff << PAGE_SHIFT;
5809 case IORING_OFF_SQ_RING:
5810 case IORING_OFF_CQ_RING:
5813 case IORING_OFF_SQES:
5817 return ERR_PTR(-EINVAL);
5820 page = virt_to_head_page(ptr);
5821 if (sz > page_size(page))
5822 return ERR_PTR(-EINVAL);
5829 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5831 size_t sz = vma->vm_end - vma->vm_start;
5835 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
5837 return PTR_ERR(ptr);
5839 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
5840 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
5843 #else /* !CONFIG_MMU */
5845 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5847 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
5850 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
5852 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
5855 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
5856 unsigned long addr, unsigned long len,
5857 unsigned long pgoff, unsigned long flags)
5861 ptr = io_uring_validate_mmap_request(file, pgoff, len);
5863 return PTR_ERR(ptr);
5865 return (unsigned long) ptr;
5868 #endif /* !CONFIG_MMU */
5870 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
5871 u32, min_complete, u32, flags, const sigset_t __user *, sig,
5874 struct io_ring_ctx *ctx;
5879 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
5887 if (f.file->f_op != &io_uring_fops)
5891 ctx = f.file->private_data;
5892 if (!percpu_ref_tryget(&ctx->refs))
5896 * For SQ polling, the thread will do all submissions and completions.
5897 * Just return the requested submit count, and wake the thread if
5901 if (ctx->flags & IORING_SETUP_SQPOLL) {
5902 if (!list_empty_careful(&ctx->cq_overflow_list))
5903 io_cqring_overflow_flush(ctx, false);
5904 if (flags & IORING_ENTER_SQ_WAKEUP)
5905 wake_up(&ctx->sqo_wait);
5906 submitted = to_submit;
5907 } else if (to_submit) {
5908 struct mm_struct *cur_mm;
5910 if (current->mm != ctx->sqo_mm ||
5911 current_cred() != ctx->creds) {
5916 to_submit = min(to_submit, ctx->sq_entries);
5917 mutex_lock(&ctx->uring_lock);
5918 /* already have mm, so io_submit_sqes() won't try to grab it */
5919 cur_mm = ctx->sqo_mm;
5920 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
5922 mutex_unlock(&ctx->uring_lock);
5924 if (submitted != to_submit)
5927 if (flags & IORING_ENTER_GETEVENTS) {
5928 unsigned nr_events = 0;
5930 min_complete = min(min_complete, ctx->cq_entries);
5932 if (ctx->flags & IORING_SETUP_IOPOLL) {
5933 ret = io_iopoll_check(ctx, &nr_events, min_complete);
5935 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
5940 percpu_ref_put(&ctx->refs);
5943 return submitted ? submitted : ret;
5946 static const struct file_operations io_uring_fops = {
5947 .release = io_uring_release,
5948 .flush = io_uring_flush,
5949 .mmap = io_uring_mmap,
5951 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
5952 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
5954 .poll = io_uring_poll,
5955 .fasync = io_uring_fasync,
5958 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
5959 struct io_uring_params *p)
5961 struct io_rings *rings;
5962 size_t size, sq_array_offset;
5964 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
5965 if (size == SIZE_MAX)
5968 rings = io_mem_alloc(size);
5973 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
5974 rings->sq_ring_mask = p->sq_entries - 1;
5975 rings->cq_ring_mask = p->cq_entries - 1;
5976 rings->sq_ring_entries = p->sq_entries;
5977 rings->cq_ring_entries = p->cq_entries;
5978 ctx->sq_mask = rings->sq_ring_mask;
5979 ctx->cq_mask = rings->cq_ring_mask;
5980 ctx->sq_entries = rings->sq_ring_entries;
5981 ctx->cq_entries = rings->cq_ring_entries;
5983 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
5984 if (size == SIZE_MAX) {
5985 io_mem_free(ctx->rings);
5990 ctx->sq_sqes = io_mem_alloc(size);
5991 if (!ctx->sq_sqes) {
5992 io_mem_free(ctx->rings);
6001 * Allocate an anonymous fd, this is what constitutes the application
6002 * visible backing of an io_uring instance. The application mmaps this
6003 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6004 * we have to tie this fd to a socket for file garbage collection purposes.
6006 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6011 #if defined(CONFIG_UNIX)
6012 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6018 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6022 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6023 O_RDWR | O_CLOEXEC);
6026 ret = PTR_ERR(file);
6030 #if defined(CONFIG_UNIX)
6031 ctx->ring_sock->file = file;
6033 fd_install(ret, file);
6036 #if defined(CONFIG_UNIX)
6037 sock_release(ctx->ring_sock);
6038 ctx->ring_sock = NULL;
6043 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6045 struct user_struct *user = NULL;
6046 struct io_ring_ctx *ctx;
6050 if (!entries || entries > IORING_MAX_ENTRIES)
6054 * Use twice as many entries for the CQ ring. It's possible for the
6055 * application to drive a higher depth than the size of the SQ ring,
6056 * since the sqes are only used at submission time. This allows for
6057 * some flexibility in overcommitting a bit. If the application has
6058 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6059 * of CQ ring entries manually.
6061 p->sq_entries = roundup_pow_of_two(entries);
6062 if (p->flags & IORING_SETUP_CQSIZE) {
6064 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6065 * to a power-of-two, if it isn't already. We do NOT impose
6066 * any cq vs sq ring sizing.
6068 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
6070 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6072 p->cq_entries = 2 * p->sq_entries;
6075 user = get_uid(current_user());
6076 account_mem = !capable(CAP_IPC_LOCK);
6079 ret = io_account_mem(user,
6080 ring_pages(p->sq_entries, p->cq_entries));
6087 ctx = io_ring_ctx_alloc(p);
6090 io_unaccount_mem(user, ring_pages(p->sq_entries,
6095 ctx->compat = in_compat_syscall();
6096 ctx->account_mem = account_mem;
6098 ctx->creds = get_current_cred();
6100 ret = io_allocate_scq_urings(ctx, p);
6104 ret = io_sq_offload_start(ctx, p);
6108 memset(&p->sq_off, 0, sizeof(p->sq_off));
6109 p->sq_off.head = offsetof(struct io_rings, sq.head);
6110 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6111 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6112 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6113 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6114 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6115 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6117 memset(&p->cq_off, 0, sizeof(p->cq_off));
6118 p->cq_off.head = offsetof(struct io_rings, cq.head);
6119 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6120 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6121 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6122 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6123 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6126 * Install ring fd as the very last thing, so we don't risk someone
6127 * having closed it before we finish setup
6129 ret = io_uring_get_fd(ctx);
6133 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6134 IORING_FEAT_SUBMIT_STABLE;
6135 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6138 io_ring_ctx_wait_and_kill(ctx);
6143 * Sets up an aio uring context, and returns the fd. Applications asks for a
6144 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6145 * params structure passed in.
6147 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6149 struct io_uring_params p;
6153 if (copy_from_user(&p, params, sizeof(p)))
6155 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6160 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6161 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
6164 ret = io_uring_create(entries, &p);
6168 if (copy_to_user(params, &p, sizeof(p)))
6174 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6175 struct io_uring_params __user *, params)
6177 return io_uring_setup(entries, params);
6180 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6181 void __user *arg, unsigned nr_args)
6182 __releases(ctx->uring_lock)
6183 __acquires(ctx->uring_lock)
6188 * We're inside the ring mutex, if the ref is already dying, then
6189 * someone else killed the ctx or is already going through
6190 * io_uring_register().
6192 if (percpu_ref_is_dying(&ctx->refs))
6195 if (opcode != IORING_UNREGISTER_FILES &&
6196 opcode != IORING_REGISTER_FILES_UPDATE) {
6197 percpu_ref_kill(&ctx->refs);
6200 * Drop uring mutex before waiting for references to exit. If
6201 * another thread is currently inside io_uring_enter() it might
6202 * need to grab the uring_lock to make progress. If we hold it
6203 * here across the drain wait, then we can deadlock. It's safe
6204 * to drop the mutex here, since no new references will come in
6205 * after we've killed the percpu ref.
6207 mutex_unlock(&ctx->uring_lock);
6208 wait_for_completion(&ctx->completions[0]);
6209 mutex_lock(&ctx->uring_lock);
6213 case IORING_REGISTER_BUFFERS:
6214 ret = io_sqe_buffer_register(ctx, arg, nr_args);
6216 case IORING_UNREGISTER_BUFFERS:
6220 ret = io_sqe_buffer_unregister(ctx);
6222 case IORING_REGISTER_FILES:
6223 ret = io_sqe_files_register(ctx, arg, nr_args);
6225 case IORING_UNREGISTER_FILES:
6229 ret = io_sqe_files_unregister(ctx);
6231 case IORING_REGISTER_FILES_UPDATE:
6232 ret = io_sqe_files_update(ctx, arg, nr_args);
6234 case IORING_REGISTER_EVENTFD:
6238 ret = io_eventfd_register(ctx, arg);
6240 case IORING_UNREGISTER_EVENTFD:
6244 ret = io_eventfd_unregister(ctx);
6252 if (opcode != IORING_UNREGISTER_FILES &&
6253 opcode != IORING_REGISTER_FILES_UPDATE) {
6254 /* bring the ctx back to life */
6255 reinit_completion(&ctx->completions[0]);
6256 percpu_ref_reinit(&ctx->refs);
6261 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
6262 void __user *, arg, unsigned int, nr_args)
6264 struct io_ring_ctx *ctx;
6273 if (f.file->f_op != &io_uring_fops)
6276 ctx = f.file->private_data;
6278 mutex_lock(&ctx->uring_lock);
6279 ret = __io_uring_register(ctx, opcode, arg, nr_args);
6280 mutex_unlock(&ctx->uring_lock);
6281 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
6282 ctx->cq_ev_fd != NULL, ret);
6288 static int __init io_uring_init(void)
6290 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
6291 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
6294 __initcall(io_uring_init);