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>
74 #define CREATE_TRACE_POINTS
75 #include <trace/events/io_uring.h>
77 #include <uapi/linux/io_uring.h>
82 #define IORING_MAX_ENTRIES 32768
83 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
86 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
88 #define IORING_FILE_TABLE_SHIFT 9
89 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
90 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
91 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
94 u32 head ____cacheline_aligned_in_smp;
95 u32 tail ____cacheline_aligned_in_smp;
99 * This data is shared with the application through the mmap at offsets
100 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
102 * The offsets to the member fields are published through struct
103 * io_sqring_offsets when calling io_uring_setup.
107 * Head and tail offsets into the ring; the offsets need to be
108 * masked to get valid indices.
110 * The kernel controls head of the sq ring and the tail of the cq ring,
111 * and the application controls tail of the sq ring and the head of the
114 struct io_uring sq, cq;
116 * Bitmasks to apply to head and tail offsets (constant, equals
119 u32 sq_ring_mask, cq_ring_mask;
120 /* Ring sizes (constant, power of 2) */
121 u32 sq_ring_entries, cq_ring_entries;
123 * Number of invalid entries dropped by the kernel due to
124 * invalid index stored in array
126 * Written by the kernel, shouldn't be modified by the
127 * application (i.e. get number of "new events" by comparing to
130 * After a new SQ head value was read by the application this
131 * counter includes all submissions that were dropped reaching
132 * the new SQ head (and possibly more).
138 * Written by the kernel, shouldn't be modified by the
141 * The application needs a full memory barrier before checking
142 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
146 * Number of completion events lost because the queue was full;
147 * this should be avoided by the application by making sure
148 * there are not more requests pending than there is space in
149 * the completion queue.
151 * Written by the kernel, shouldn't be modified by the
152 * application (i.e. get number of "new events" by comparing to
155 * As completion events come in out of order this counter is not
156 * ordered with any other data.
160 * Ring buffer of completion events.
162 * The kernel writes completion events fresh every time they are
163 * produced, so the application is allowed to modify pending
166 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
169 struct io_mapped_ubuf {
172 struct bio_vec *bvec;
173 unsigned int nr_bvecs;
176 struct fixed_file_table {
182 struct percpu_ref refs;
183 } ____cacheline_aligned_in_smp;
189 bool cq_overflow_flushed;
193 * Ring buffer of indices into array of io_uring_sqe, which is
194 * mmapped by the application using the IORING_OFF_SQES offset.
196 * This indirection could e.g. be used to assign fixed
197 * io_uring_sqe entries to operations and only submit them to
198 * the queue when needed.
200 * The kernel modifies neither the indices array nor the entries
204 unsigned cached_sq_head;
207 unsigned sq_thread_idle;
208 unsigned cached_sq_dropped;
209 atomic_t cached_cq_overflow;
210 struct io_uring_sqe *sq_sqes;
212 struct list_head defer_list;
213 struct list_head timeout_list;
214 struct list_head cq_overflow_list;
216 wait_queue_head_t inflight_wait;
217 } ____cacheline_aligned_in_smp;
219 struct io_rings *rings;
223 struct task_struct *sqo_thread; /* if using sq thread polling */
224 struct mm_struct *sqo_mm;
225 wait_queue_head_t sqo_wait;
228 * If used, fixed file set. Writers must ensure that ->refs is dead,
229 * readers must ensure that ->refs is alive as long as the file* is
230 * used. Only updated through io_uring_register(2).
232 struct fixed_file_table *file_table;
233 unsigned nr_user_files;
235 /* if used, fixed mapped user buffers */
236 unsigned nr_user_bufs;
237 struct io_mapped_ubuf *user_bufs;
239 struct user_struct *user;
241 const struct cred *creds;
243 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
244 struct completion *completions;
246 /* if all else fails... */
247 struct io_kiocb *fallback_req;
249 #if defined(CONFIG_UNIX)
250 struct socket *ring_sock;
254 unsigned cached_cq_tail;
257 atomic_t cq_timeouts;
258 struct wait_queue_head cq_wait;
259 struct fasync_struct *cq_fasync;
260 struct eventfd_ctx *cq_ev_fd;
261 } ____cacheline_aligned_in_smp;
264 struct mutex uring_lock;
265 wait_queue_head_t wait;
266 } ____cacheline_aligned_in_smp;
269 spinlock_t completion_lock;
270 bool poll_multi_file;
272 * ->poll_list is protected by the ctx->uring_lock for
273 * io_uring instances that don't use IORING_SETUP_SQPOLL.
274 * For SQPOLL, only the single threaded io_sq_thread() will
275 * manipulate the list, hence no extra locking is needed there.
277 struct list_head poll_list;
278 struct hlist_head *cancel_hash;
279 unsigned cancel_hash_bits;
281 spinlock_t inflight_lock;
282 struct list_head inflight_list;
283 } ____cacheline_aligned_in_smp;
287 * First field must be the file pointer in all the
288 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
290 struct io_poll_iocb {
293 struct wait_queue_head *head;
299 struct wait_queue_entry wait;
302 struct io_timeout_data {
303 struct io_kiocb *req;
304 struct hrtimer timer;
305 struct timespec64 ts;
306 enum hrtimer_mode mode;
312 struct sockaddr __user *addr;
313 int __user *addr_len;
335 struct io_async_connect {
336 struct sockaddr_storage address;
339 struct io_async_msghdr {
340 struct iovec fast_iov[UIO_FASTIOV];
342 struct sockaddr __user *uaddr;
347 struct iovec fast_iov[UIO_FASTIOV];
353 struct io_async_ctx {
354 struct io_uring_sqe sqe;
356 struct io_async_rw rw;
357 struct io_async_msghdr msg;
358 struct io_async_connect connect;
359 struct io_timeout_data timeout;
364 * NOTE! Each of the iocb union members has the file pointer
365 * as the first entry in their struct definition. So you can
366 * access the file pointer through any of the sub-structs,
367 * or directly as just 'ki_filp' in this struct.
373 struct io_poll_iocb poll;
374 struct io_accept accept;
376 struct io_cancel cancel;
377 struct io_timeout timeout;
380 const struct io_uring_sqe *sqe;
381 struct io_async_ctx *io;
382 struct file *ring_file;
386 bool needs_fixed_file;
388 struct io_ring_ctx *ctx;
390 struct list_head list;
391 struct hlist_node hash_node;
393 struct list_head link_list;
396 #define REQ_F_NOWAIT 1 /* must not punt to workers */
397 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
398 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
399 #define REQ_F_LINK_NEXT 8 /* already grabbed next link */
400 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
401 #define REQ_F_IO_DRAINED 32 /* drain done */
402 #define REQ_F_LINK 64 /* linked sqes */
403 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
404 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
405 #define REQ_F_DRAIN_LINK 512 /* link should be fully drained */
406 #define REQ_F_TIMEOUT 1024 /* timeout request */
407 #define REQ_F_ISREG 2048 /* regular file */
408 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
409 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
410 #define REQ_F_INFLIGHT 16384 /* on inflight list */
411 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
412 #define REQ_F_HARDLINK 65536 /* doesn't sever on completion < 0 */
413 #define REQ_F_PREPPED 131072 /* request already opcode prepared */
418 struct list_head inflight_entry;
420 struct io_wq_work work;
423 #define IO_PLUG_THRESHOLD 2
424 #define IO_IOPOLL_BATCH 8
426 struct io_submit_state {
427 struct blk_plug plug;
430 * io_kiocb alloc cache
432 void *reqs[IO_IOPOLL_BATCH];
433 unsigned int free_reqs;
434 unsigned int cur_req;
437 * File reference cache
441 unsigned int has_refs;
442 unsigned int used_refs;
443 unsigned int ios_left;
446 static void io_wq_submit_work(struct io_wq_work **workptr);
447 static void io_cqring_fill_event(struct io_kiocb *req, long res);
448 static void __io_free_req(struct io_kiocb *req);
449 static void io_put_req(struct io_kiocb *req);
450 static void io_double_put_req(struct io_kiocb *req);
451 static void __io_double_put_req(struct io_kiocb *req);
452 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
453 static void io_queue_linked_timeout(struct io_kiocb *req);
455 static struct kmem_cache *req_cachep;
457 static const struct file_operations io_uring_fops;
459 struct sock *io_uring_get_socket(struct file *file)
461 #if defined(CONFIG_UNIX)
462 if (file->f_op == &io_uring_fops) {
463 struct io_ring_ctx *ctx = file->private_data;
465 return ctx->ring_sock->sk;
470 EXPORT_SYMBOL(io_uring_get_socket);
472 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
474 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
476 complete(&ctx->completions[0]);
479 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
481 struct io_ring_ctx *ctx;
484 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
488 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
489 if (!ctx->fallback_req)
492 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
493 if (!ctx->completions)
497 * Use 5 bits less than the max cq entries, that should give us around
498 * 32 entries per hash list if totally full and uniformly spread.
500 hash_bits = ilog2(p->cq_entries);
504 ctx->cancel_hash_bits = hash_bits;
505 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
507 if (!ctx->cancel_hash)
509 __hash_init(ctx->cancel_hash, 1U << hash_bits);
511 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
512 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
515 ctx->flags = p->flags;
516 init_waitqueue_head(&ctx->cq_wait);
517 INIT_LIST_HEAD(&ctx->cq_overflow_list);
518 init_completion(&ctx->completions[0]);
519 init_completion(&ctx->completions[1]);
520 mutex_init(&ctx->uring_lock);
521 init_waitqueue_head(&ctx->wait);
522 spin_lock_init(&ctx->completion_lock);
523 INIT_LIST_HEAD(&ctx->poll_list);
524 INIT_LIST_HEAD(&ctx->defer_list);
525 INIT_LIST_HEAD(&ctx->timeout_list);
526 init_waitqueue_head(&ctx->inflight_wait);
527 spin_lock_init(&ctx->inflight_lock);
528 INIT_LIST_HEAD(&ctx->inflight_list);
531 if (ctx->fallback_req)
532 kmem_cache_free(req_cachep, ctx->fallback_req);
533 kfree(ctx->completions);
534 kfree(ctx->cancel_hash);
539 static inline bool __req_need_defer(struct io_kiocb *req)
541 struct io_ring_ctx *ctx = req->ctx;
543 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
544 + atomic_read(&ctx->cached_cq_overflow);
547 static inline bool req_need_defer(struct io_kiocb *req)
549 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
550 return __req_need_defer(req);
555 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
557 struct io_kiocb *req;
559 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
560 if (req && !req_need_defer(req)) {
561 list_del_init(&req->list);
568 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
570 struct io_kiocb *req;
572 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
574 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
576 if (!__req_need_defer(req)) {
577 list_del_init(&req->list);
585 static void __io_commit_cqring(struct io_ring_ctx *ctx)
587 struct io_rings *rings = ctx->rings;
589 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
590 /* order cqe stores with ring update */
591 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
593 if (wq_has_sleeper(&ctx->cq_wait)) {
594 wake_up_interruptible(&ctx->cq_wait);
595 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
600 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
602 u8 opcode = READ_ONCE(sqe->opcode);
604 return !(opcode == IORING_OP_READ_FIXED ||
605 opcode == IORING_OP_WRITE_FIXED);
608 static inline bool io_prep_async_work(struct io_kiocb *req,
609 struct io_kiocb **link)
611 bool do_hashed = false;
614 switch (req->sqe->opcode) {
615 case IORING_OP_WRITEV:
616 case IORING_OP_WRITE_FIXED:
617 /* only regular files should be hashed for writes */
618 if (req->flags & REQ_F_ISREG)
621 case IORING_OP_READV:
622 case IORING_OP_READ_FIXED:
623 case IORING_OP_SENDMSG:
624 case IORING_OP_RECVMSG:
625 case IORING_OP_ACCEPT:
626 case IORING_OP_POLL_ADD:
627 case IORING_OP_CONNECT:
629 * We know REQ_F_ISREG is not set on some of these
630 * opcodes, but this enables us to keep the check in
633 if (!(req->flags & REQ_F_ISREG))
634 req->work.flags |= IO_WQ_WORK_UNBOUND;
637 if (io_sqe_needs_user(req->sqe))
638 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
641 *link = io_prep_linked_timeout(req);
645 static inline void io_queue_async_work(struct io_kiocb *req)
647 struct io_ring_ctx *ctx = req->ctx;
648 struct io_kiocb *link;
651 do_hashed = io_prep_async_work(req, &link);
653 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
656 io_wq_enqueue(ctx->io_wq, &req->work);
658 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
659 file_inode(req->file));
663 io_queue_linked_timeout(link);
666 static void io_kill_timeout(struct io_kiocb *req)
670 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
672 atomic_inc(&req->ctx->cq_timeouts);
673 list_del_init(&req->list);
674 io_cqring_fill_event(req, 0);
679 static void io_kill_timeouts(struct io_ring_ctx *ctx)
681 struct io_kiocb *req, *tmp;
683 spin_lock_irq(&ctx->completion_lock);
684 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
685 io_kill_timeout(req);
686 spin_unlock_irq(&ctx->completion_lock);
689 static void io_commit_cqring(struct io_ring_ctx *ctx)
691 struct io_kiocb *req;
693 while ((req = io_get_timeout_req(ctx)) != NULL)
694 io_kill_timeout(req);
696 __io_commit_cqring(ctx);
698 while ((req = io_get_deferred_req(ctx)) != NULL) {
699 req->flags |= REQ_F_IO_DRAINED;
700 io_queue_async_work(req);
704 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
706 struct io_rings *rings = ctx->rings;
709 tail = ctx->cached_cq_tail;
711 * writes to the cq entry need to come after reading head; the
712 * control dependency is enough as we're using WRITE_ONCE to
715 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
718 ctx->cached_cq_tail++;
719 return &rings->cqes[tail & ctx->cq_mask];
722 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
724 if (waitqueue_active(&ctx->wait))
726 if (waitqueue_active(&ctx->sqo_wait))
727 wake_up(&ctx->sqo_wait);
729 eventfd_signal(ctx->cq_ev_fd, 1);
732 /* Returns true if there are no backlogged entries after the flush */
733 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
735 struct io_rings *rings = ctx->rings;
736 struct io_uring_cqe *cqe;
737 struct io_kiocb *req;
742 if (list_empty_careful(&ctx->cq_overflow_list))
744 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
745 rings->cq_ring_entries))
749 spin_lock_irqsave(&ctx->completion_lock, flags);
751 /* if force is set, the ring is going away. always drop after that */
753 ctx->cq_overflow_flushed = true;
756 while (!list_empty(&ctx->cq_overflow_list)) {
757 cqe = io_get_cqring(ctx);
761 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
763 list_move(&req->list, &list);
765 WRITE_ONCE(cqe->user_data, req->user_data);
766 WRITE_ONCE(cqe->res, req->result);
767 WRITE_ONCE(cqe->flags, 0);
769 WRITE_ONCE(ctx->rings->cq_overflow,
770 atomic_inc_return(&ctx->cached_cq_overflow));
774 io_commit_cqring(ctx);
775 spin_unlock_irqrestore(&ctx->completion_lock, flags);
776 io_cqring_ev_posted(ctx);
778 while (!list_empty(&list)) {
779 req = list_first_entry(&list, struct io_kiocb, list);
780 list_del(&req->list);
787 static void io_cqring_fill_event(struct io_kiocb *req, long res)
789 struct io_ring_ctx *ctx = req->ctx;
790 struct io_uring_cqe *cqe;
792 trace_io_uring_complete(ctx, req->user_data, res);
795 * If we can't get a cq entry, userspace overflowed the
796 * submission (by quite a lot). Increment the overflow count in
799 cqe = io_get_cqring(ctx);
801 WRITE_ONCE(cqe->user_data, req->user_data);
802 WRITE_ONCE(cqe->res, res);
803 WRITE_ONCE(cqe->flags, 0);
804 } else if (ctx->cq_overflow_flushed) {
805 WRITE_ONCE(ctx->rings->cq_overflow,
806 atomic_inc_return(&ctx->cached_cq_overflow));
808 refcount_inc(&req->refs);
810 list_add_tail(&req->list, &ctx->cq_overflow_list);
814 static void io_cqring_add_event(struct io_kiocb *req, long res)
816 struct io_ring_ctx *ctx = req->ctx;
819 spin_lock_irqsave(&ctx->completion_lock, flags);
820 io_cqring_fill_event(req, res);
821 io_commit_cqring(ctx);
822 spin_unlock_irqrestore(&ctx->completion_lock, flags);
824 io_cqring_ev_posted(ctx);
827 static inline bool io_is_fallback_req(struct io_kiocb *req)
829 return req == (struct io_kiocb *)
830 ((unsigned long) req->ctx->fallback_req & ~1UL);
833 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
835 struct io_kiocb *req;
837 req = ctx->fallback_req;
838 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
844 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
845 struct io_submit_state *state)
847 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
848 struct io_kiocb *req;
850 if (!percpu_ref_tryget(&ctx->refs))
854 req = kmem_cache_alloc(req_cachep, gfp);
857 } else if (!state->free_reqs) {
861 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
862 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
865 * Bulk alloc is all-or-nothing. If we fail to get a batch,
866 * retry single alloc to be on the safe side.
868 if (unlikely(ret <= 0)) {
869 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
874 state->free_reqs = ret - 1;
876 req = state->reqs[0];
878 req = state->reqs[state->cur_req];
885 req->ring_file = NULL;
889 /* one is dropped after submission, the other at completion */
890 refcount_set(&req->refs, 2);
892 INIT_IO_WORK(&req->work, io_wq_submit_work);
895 req = io_get_fallback_req(ctx);
898 percpu_ref_put(&ctx->refs);
902 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
905 kmem_cache_free_bulk(req_cachep, *nr, reqs);
906 percpu_ref_put_many(&ctx->refs, *nr);
911 static void __io_free_req(struct io_kiocb *req)
913 struct io_ring_ctx *ctx = req->ctx;
917 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
919 if (req->flags & REQ_F_INFLIGHT) {
922 spin_lock_irqsave(&ctx->inflight_lock, flags);
923 list_del(&req->inflight_entry);
924 if (waitqueue_active(&ctx->inflight_wait))
925 wake_up(&ctx->inflight_wait);
926 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
928 percpu_ref_put(&ctx->refs);
929 if (likely(!io_is_fallback_req(req)))
930 kmem_cache_free(req_cachep, req);
932 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
935 static bool io_link_cancel_timeout(struct io_kiocb *req)
937 struct io_ring_ctx *ctx = req->ctx;
940 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
942 io_cqring_fill_event(req, -ECANCELED);
943 io_commit_cqring(ctx);
944 req->flags &= ~REQ_F_LINK;
952 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
954 struct io_ring_ctx *ctx = req->ctx;
955 bool wake_ev = false;
957 /* Already got next link */
958 if (req->flags & REQ_F_LINK_NEXT)
962 * The list should never be empty when we are called here. But could
963 * potentially happen if the chain is messed up, check to be on the
966 while (!list_empty(&req->link_list)) {
967 struct io_kiocb *nxt = list_first_entry(&req->link_list,
968 struct io_kiocb, link_list);
970 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
971 (nxt->flags & REQ_F_TIMEOUT))) {
972 list_del_init(&nxt->link_list);
973 wake_ev |= io_link_cancel_timeout(nxt);
974 req->flags &= ~REQ_F_LINK_TIMEOUT;
978 list_del_init(&req->link_list);
979 if (!list_empty(&nxt->link_list))
980 nxt->flags |= REQ_F_LINK;
985 req->flags |= REQ_F_LINK_NEXT;
987 io_cqring_ev_posted(ctx);
991 * Called if REQ_F_LINK is set, and we fail the head request
993 static void io_fail_links(struct io_kiocb *req)
995 struct io_ring_ctx *ctx = req->ctx;
998 spin_lock_irqsave(&ctx->completion_lock, flags);
1000 while (!list_empty(&req->link_list)) {
1001 struct io_kiocb *link = list_first_entry(&req->link_list,
1002 struct io_kiocb, link_list);
1004 list_del_init(&link->link_list);
1005 trace_io_uring_fail_link(req, link);
1007 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1008 link->sqe->opcode == IORING_OP_LINK_TIMEOUT) {
1009 io_link_cancel_timeout(link);
1011 io_cqring_fill_event(link, -ECANCELED);
1012 __io_double_put_req(link);
1014 req->flags &= ~REQ_F_LINK_TIMEOUT;
1017 io_commit_cqring(ctx);
1018 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1019 io_cqring_ev_posted(ctx);
1022 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1024 if (likely(!(req->flags & REQ_F_LINK)))
1028 * If LINK is set, we have dependent requests in this chain. If we
1029 * didn't fail this request, queue the first one up, moving any other
1030 * dependencies to the next request. In case of failure, fail the rest
1033 if (req->flags & REQ_F_FAIL_LINK) {
1035 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1036 REQ_F_LINK_TIMEOUT) {
1037 struct io_ring_ctx *ctx = req->ctx;
1038 unsigned long flags;
1041 * If this is a timeout link, we could be racing with the
1042 * timeout timer. Grab the completion lock for this case to
1043 * protect against that.
1045 spin_lock_irqsave(&ctx->completion_lock, flags);
1046 io_req_link_next(req, nxt);
1047 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1049 io_req_link_next(req, nxt);
1053 static void io_free_req(struct io_kiocb *req)
1055 struct io_kiocb *nxt = NULL;
1057 io_req_find_next(req, &nxt);
1061 io_queue_async_work(nxt);
1065 * Drop reference to request, return next in chain (if there is one) if this
1066 * was the last reference to this request.
1068 __attribute__((nonnull))
1069 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1071 io_req_find_next(req, nxtptr);
1073 if (refcount_dec_and_test(&req->refs))
1077 static void io_put_req(struct io_kiocb *req)
1079 if (refcount_dec_and_test(&req->refs))
1084 * Must only be used if we don't need to care about links, usually from
1085 * within the completion handling itself.
1087 static void __io_double_put_req(struct io_kiocb *req)
1089 /* drop both submit and complete references */
1090 if (refcount_sub_and_test(2, &req->refs))
1094 static void io_double_put_req(struct io_kiocb *req)
1096 /* drop both submit and complete references */
1097 if (refcount_sub_and_test(2, &req->refs))
1101 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1103 struct io_rings *rings = ctx->rings;
1106 * noflush == true is from the waitqueue handler, just ensure we wake
1107 * up the task, and the next invocation will flush the entries. We
1108 * cannot safely to it from here.
1110 if (noflush && !list_empty(&ctx->cq_overflow_list))
1113 io_cqring_overflow_flush(ctx, false);
1115 /* See comment at the top of this file */
1117 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
1120 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1122 struct io_rings *rings = ctx->rings;
1124 /* make sure SQ entry isn't read before tail */
1125 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1129 * Find and free completed poll iocbs
1131 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1132 struct list_head *done)
1134 void *reqs[IO_IOPOLL_BATCH];
1135 struct io_kiocb *req;
1139 while (!list_empty(done)) {
1140 req = list_first_entry(done, struct io_kiocb, list);
1141 list_del(&req->list);
1143 io_cqring_fill_event(req, req->result);
1146 if (refcount_dec_and_test(&req->refs)) {
1147 /* If we're not using fixed files, we have to pair the
1148 * completion part with the file put. Use regular
1149 * completions for those, only batch free for fixed
1150 * file and non-linked commands.
1152 if (((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
1153 REQ_F_FIXED_FILE) && !io_is_fallback_req(req) &&
1155 reqs[to_free++] = req;
1156 if (to_free == ARRAY_SIZE(reqs))
1157 io_free_req_many(ctx, reqs, &to_free);
1164 io_commit_cqring(ctx);
1165 io_free_req_many(ctx, reqs, &to_free);
1168 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1171 struct io_kiocb *req, *tmp;
1177 * Only spin for completions if we don't have multiple devices hanging
1178 * off our complete list, and we're under the requested amount.
1180 spin = !ctx->poll_multi_file && *nr_events < min;
1183 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1184 struct kiocb *kiocb = &req->rw;
1187 * Move completed entries to our local list. If we find a
1188 * request that requires polling, break out and complete
1189 * the done list first, if we have entries there.
1191 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1192 list_move_tail(&req->list, &done);
1195 if (!list_empty(&done))
1198 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1207 if (!list_empty(&done))
1208 io_iopoll_complete(ctx, nr_events, &done);
1214 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1215 * non-spinning poll check - we'll still enter the driver poll loop, but only
1216 * as a non-spinning completion check.
1218 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1221 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1224 ret = io_do_iopoll(ctx, nr_events, min);
1227 if (!min || *nr_events >= min)
1235 * We can't just wait for polled events to come to us, we have to actively
1236 * find and complete them.
1238 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1240 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1243 mutex_lock(&ctx->uring_lock);
1244 while (!list_empty(&ctx->poll_list)) {
1245 unsigned int nr_events = 0;
1247 io_iopoll_getevents(ctx, &nr_events, 1);
1250 * Ensure we allow local-to-the-cpu processing to take place,
1251 * in this case we need to ensure that we reap all events.
1255 mutex_unlock(&ctx->uring_lock);
1258 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1261 int iters = 0, ret = 0;
1267 * Don't enter poll loop if we already have events pending.
1268 * If we do, we can potentially be spinning for commands that
1269 * already triggered a CQE (eg in error).
1271 if (io_cqring_events(ctx, false))
1275 * If a submit got punted to a workqueue, we can have the
1276 * application entering polling for a command before it gets
1277 * issued. That app will hold the uring_lock for the duration
1278 * of the poll right here, so we need to take a breather every
1279 * now and then to ensure that the issue has a chance to add
1280 * the poll to the issued list. Otherwise we can spin here
1281 * forever, while the workqueue is stuck trying to acquire the
1284 if (!(++iters & 7)) {
1285 mutex_unlock(&ctx->uring_lock);
1286 mutex_lock(&ctx->uring_lock);
1289 if (*nr_events < min)
1290 tmin = min - *nr_events;
1292 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1296 } while (min && !*nr_events && !need_resched());
1301 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1307 * We disallow the app entering submit/complete with polling, but we
1308 * still need to lock the ring to prevent racing with polled issue
1309 * that got punted to a workqueue.
1311 mutex_lock(&ctx->uring_lock);
1312 ret = __io_iopoll_check(ctx, nr_events, min);
1313 mutex_unlock(&ctx->uring_lock);
1317 static void kiocb_end_write(struct io_kiocb *req)
1320 * Tell lockdep we inherited freeze protection from submission
1323 if (req->flags & REQ_F_ISREG) {
1324 struct inode *inode = file_inode(req->file);
1326 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1328 file_end_write(req->file);
1331 static inline void req_set_fail_links(struct io_kiocb *req)
1333 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1334 req->flags |= REQ_F_FAIL_LINK;
1337 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1339 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1341 if (kiocb->ki_flags & IOCB_WRITE)
1342 kiocb_end_write(req);
1344 if (res != req->result)
1345 req_set_fail_links(req);
1346 io_cqring_add_event(req, res);
1349 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1351 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1353 io_complete_rw_common(kiocb, res);
1357 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1359 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1360 struct io_kiocb *nxt = NULL;
1362 io_complete_rw_common(kiocb, res);
1363 io_put_req_find_next(req, &nxt);
1368 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1370 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1372 if (kiocb->ki_flags & IOCB_WRITE)
1373 kiocb_end_write(req);
1375 if (res != req->result)
1376 req_set_fail_links(req);
1379 req->flags |= REQ_F_IOPOLL_COMPLETED;
1383 * After the iocb has been issued, it's safe to be found on the poll list.
1384 * Adding the kiocb to the list AFTER submission ensures that we don't
1385 * find it from a io_iopoll_getevents() thread before the issuer is done
1386 * accessing the kiocb cookie.
1388 static void io_iopoll_req_issued(struct io_kiocb *req)
1390 struct io_ring_ctx *ctx = req->ctx;
1393 * Track whether we have multiple files in our lists. This will impact
1394 * how we do polling eventually, not spinning if we're on potentially
1395 * different devices.
1397 if (list_empty(&ctx->poll_list)) {
1398 ctx->poll_multi_file = false;
1399 } else if (!ctx->poll_multi_file) {
1400 struct io_kiocb *list_req;
1402 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1404 if (list_req->rw.ki_filp != req->rw.ki_filp)
1405 ctx->poll_multi_file = true;
1409 * For fast devices, IO may have already completed. If it has, add
1410 * it to the front so we find it first.
1412 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1413 list_add(&req->list, &ctx->poll_list);
1415 list_add_tail(&req->list, &ctx->poll_list);
1418 static void io_file_put(struct io_submit_state *state)
1421 int diff = state->has_refs - state->used_refs;
1424 fput_many(state->file, diff);
1430 * Get as many references to a file as we have IOs left in this submission,
1431 * assuming most submissions are for one file, or at least that each file
1432 * has more than one submission.
1434 static struct file *io_file_get(struct io_submit_state *state, int fd)
1440 if (state->fd == fd) {
1447 state->file = fget_many(fd, state->ios_left);
1452 state->has_refs = state->ios_left;
1453 state->used_refs = 1;
1459 * If we tracked the file through the SCM inflight mechanism, we could support
1460 * any file. For now, just ensure that anything potentially problematic is done
1463 static bool io_file_supports_async(struct file *file)
1465 umode_t mode = file_inode(file)->i_mode;
1467 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1469 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1475 static int io_prep_rw(struct io_kiocb *req, bool force_nonblock)
1477 const struct io_uring_sqe *sqe = req->sqe;
1478 struct io_ring_ctx *ctx = req->ctx;
1479 struct kiocb *kiocb = &req->rw;
1486 if (S_ISREG(file_inode(req->file)->i_mode))
1487 req->flags |= REQ_F_ISREG;
1489 kiocb->ki_pos = READ_ONCE(sqe->off);
1490 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1491 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1493 ioprio = READ_ONCE(sqe->ioprio);
1495 ret = ioprio_check_cap(ioprio);
1499 kiocb->ki_ioprio = ioprio;
1501 kiocb->ki_ioprio = get_current_ioprio();
1503 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1507 /* don't allow async punt if RWF_NOWAIT was requested */
1508 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1509 (req->file->f_flags & O_NONBLOCK))
1510 req->flags |= REQ_F_NOWAIT;
1513 kiocb->ki_flags |= IOCB_NOWAIT;
1515 if (ctx->flags & IORING_SETUP_IOPOLL) {
1516 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1517 !kiocb->ki_filp->f_op->iopoll)
1520 kiocb->ki_flags |= IOCB_HIPRI;
1521 kiocb->ki_complete = io_complete_rw_iopoll;
1524 if (kiocb->ki_flags & IOCB_HIPRI)
1526 kiocb->ki_complete = io_complete_rw;
1531 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1537 case -ERESTARTNOINTR:
1538 case -ERESTARTNOHAND:
1539 case -ERESTART_RESTARTBLOCK:
1541 * We can't just restart the syscall, since previously
1542 * submitted sqes may already be in progress. Just fail this
1548 kiocb->ki_complete(kiocb, ret, 0);
1552 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1555 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1556 *nxt = __io_complete_rw(kiocb, ret);
1558 io_rw_done(kiocb, ret);
1561 static ssize_t io_import_fixed(struct io_ring_ctx *ctx, int rw,
1562 const struct io_uring_sqe *sqe,
1563 struct iov_iter *iter)
1565 size_t len = READ_ONCE(sqe->len);
1566 struct io_mapped_ubuf *imu;
1567 unsigned index, buf_index;
1571 /* attempt to use fixed buffers without having provided iovecs */
1572 if (unlikely(!ctx->user_bufs))
1575 buf_index = READ_ONCE(sqe->buf_index);
1576 if (unlikely(buf_index >= ctx->nr_user_bufs))
1579 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1580 imu = &ctx->user_bufs[index];
1581 buf_addr = READ_ONCE(sqe->addr);
1584 if (buf_addr + len < buf_addr)
1586 /* not inside the mapped region */
1587 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1591 * May not be a start of buffer, set size appropriately
1592 * and advance us to the beginning.
1594 offset = buf_addr - imu->ubuf;
1595 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1599 * Don't use iov_iter_advance() here, as it's really slow for
1600 * using the latter parts of a big fixed buffer - it iterates
1601 * over each segment manually. We can cheat a bit here, because
1604 * 1) it's a BVEC iter, we set it up
1605 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1606 * first and last bvec
1608 * So just find our index, and adjust the iterator afterwards.
1609 * If the offset is within the first bvec (or the whole first
1610 * bvec, just use iov_iter_advance(). This makes it easier
1611 * since we can just skip the first segment, which may not
1612 * be PAGE_SIZE aligned.
1614 const struct bio_vec *bvec = imu->bvec;
1616 if (offset <= bvec->bv_len) {
1617 iov_iter_advance(iter, offset);
1619 unsigned long seg_skip;
1621 /* skip first vec */
1622 offset -= bvec->bv_len;
1623 seg_skip = 1 + (offset >> PAGE_SHIFT);
1625 iter->bvec = bvec + seg_skip;
1626 iter->nr_segs -= seg_skip;
1627 iter->count -= bvec->bv_len + offset;
1628 iter->iov_offset = offset & ~PAGE_MASK;
1635 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1636 struct iovec **iovec, struct iov_iter *iter)
1638 const struct io_uring_sqe *sqe = req->sqe;
1639 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1640 size_t sqe_len = READ_ONCE(sqe->len);
1644 * We're reading ->opcode for the second time, but the first read
1645 * doesn't care whether it's _FIXED or not, so it doesn't matter
1646 * whether ->opcode changes concurrently. The first read does care
1647 * about whether it is a READ or a WRITE, so we don't trust this read
1648 * for that purpose and instead let the caller pass in the read/write
1651 opcode = READ_ONCE(sqe->opcode);
1652 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1654 return io_import_fixed(req->ctx, rw, sqe, iter);
1658 struct io_async_rw *iorw = &req->io->rw;
1661 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
1662 if (iorw->iov == iorw->fast_iov)
1670 #ifdef CONFIG_COMPAT
1671 if (req->ctx->compat)
1672 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1676 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1680 * For files that don't have ->read_iter() and ->write_iter(), handle them
1681 * by looping over ->read() or ->write() manually.
1683 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1684 struct iov_iter *iter)
1689 * Don't support polled IO through this interface, and we can't
1690 * support non-blocking either. For the latter, this just causes
1691 * the kiocb to be handled from an async context.
1693 if (kiocb->ki_flags & IOCB_HIPRI)
1695 if (kiocb->ki_flags & IOCB_NOWAIT)
1698 while (iov_iter_count(iter)) {
1702 if (!iov_iter_is_bvec(iter)) {
1703 iovec = iov_iter_iovec(iter);
1705 /* fixed buffers import bvec */
1706 iovec.iov_base = kmap(iter->bvec->bv_page)
1708 iovec.iov_len = min(iter->count,
1709 iter->bvec->bv_len - iter->iov_offset);
1713 nr = file->f_op->read(file, iovec.iov_base,
1714 iovec.iov_len, &kiocb->ki_pos);
1716 nr = file->f_op->write(file, iovec.iov_base,
1717 iovec.iov_len, &kiocb->ki_pos);
1720 if (iov_iter_is_bvec(iter))
1721 kunmap(iter->bvec->bv_page);
1729 if (nr != iovec.iov_len)
1731 iov_iter_advance(iter, nr);
1737 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
1738 struct iovec *iovec, struct iovec *fast_iov,
1739 struct iov_iter *iter)
1741 req->io->rw.nr_segs = iter->nr_segs;
1742 req->io->rw.size = io_size;
1743 req->io->rw.iov = iovec;
1744 if (!req->io->rw.iov) {
1745 req->io->rw.iov = req->io->rw.fast_iov;
1746 memcpy(req->io->rw.iov, fast_iov,
1747 sizeof(struct iovec) * iter->nr_segs);
1751 static int io_alloc_async_ctx(struct io_kiocb *req)
1753 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
1755 memcpy(&req->io->sqe, req->sqe, sizeof(req->io->sqe));
1756 req->sqe = &req->io->sqe;
1763 static void io_rw_async(struct io_wq_work **workptr)
1765 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
1766 struct iovec *iov = NULL;
1768 if (req->io->rw.iov != req->io->rw.fast_iov)
1769 iov = req->io->rw.iov;
1770 io_wq_submit_work(workptr);
1774 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
1775 struct iovec *iovec, struct iovec *fast_iov,
1776 struct iov_iter *iter)
1778 if (!req->io && io_alloc_async_ctx(req))
1781 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
1782 req->work.func = io_rw_async;
1786 static int io_read_prep(struct io_kiocb *req, struct iovec **iovec,
1787 struct iov_iter *iter, bool force_nonblock)
1791 ret = io_prep_rw(req, force_nonblock);
1795 if (unlikely(!(req->file->f_mode & FMODE_READ)))
1798 return io_import_iovec(READ, req, iovec, iter);
1801 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1802 bool force_nonblock)
1804 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1805 struct kiocb *kiocb = &req->rw;
1806 struct iov_iter iter;
1809 ssize_t io_size, ret;
1812 ret = io_read_prep(req, &iovec, &iter, force_nonblock);
1816 ret = io_import_iovec(READ, req, &iovec, &iter);
1823 if (req->flags & REQ_F_LINK)
1824 req->result = io_size;
1827 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1828 * we know to async punt it even if it was opened O_NONBLOCK
1830 if (force_nonblock && !io_file_supports_async(file)) {
1831 req->flags |= REQ_F_MUST_PUNT;
1835 iov_count = iov_iter_count(&iter);
1836 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1840 if (file->f_op->read_iter)
1841 ret2 = call_read_iter(file, kiocb, &iter);
1843 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1846 * In case of a short read, punt to async. This can happen
1847 * if we have data partially cached. Alternatively we can
1848 * return the short read, in which case the application will
1849 * need to issue another SQE and wait for it. That SQE will
1850 * need async punt anyway, so it's more efficient to do it
1853 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1854 (req->flags & REQ_F_ISREG) &&
1855 ret2 > 0 && ret2 < io_size)
1857 /* Catch -EAGAIN return for forced non-blocking submission */
1858 if (!force_nonblock || ret2 != -EAGAIN) {
1859 kiocb_done(kiocb, ret2, nxt, req->in_async);
1862 ret = io_setup_async_rw(req, io_size, iovec,
1863 inline_vecs, &iter);
1870 if (!io_wq_current_is_worker())
1875 static int io_write_prep(struct io_kiocb *req, struct iovec **iovec,
1876 struct iov_iter *iter, bool force_nonblock)
1880 ret = io_prep_rw(req, force_nonblock);
1884 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
1887 return io_import_iovec(WRITE, req, iovec, iter);
1890 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1891 bool force_nonblock)
1893 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1894 struct kiocb *kiocb = &req->rw;
1895 struct iov_iter iter;
1898 ssize_t ret, io_size;
1901 ret = io_write_prep(req, &iovec, &iter, force_nonblock);
1905 ret = io_import_iovec(WRITE, req, &iovec, &iter);
1910 file = kiocb->ki_filp;
1912 if (req->flags & REQ_F_LINK)
1913 req->result = io_size;
1916 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1917 * we know to async punt it even if it was opened O_NONBLOCK
1919 if (force_nonblock && !io_file_supports_async(req->file)) {
1920 req->flags |= REQ_F_MUST_PUNT;
1924 /* file path doesn't support NOWAIT for non-direct_IO */
1925 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
1926 (req->flags & REQ_F_ISREG))
1929 iov_count = iov_iter_count(&iter);
1930 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1935 * Open-code file_start_write here to grab freeze protection,
1936 * which will be released by another thread in
1937 * io_complete_rw(). Fool lockdep by telling it the lock got
1938 * released so that it doesn't complain about the held lock when
1939 * we return to userspace.
1941 if (req->flags & REQ_F_ISREG) {
1942 __sb_start_write(file_inode(file)->i_sb,
1943 SB_FREEZE_WRITE, true);
1944 __sb_writers_release(file_inode(file)->i_sb,
1947 kiocb->ki_flags |= IOCB_WRITE;
1949 if (file->f_op->write_iter)
1950 ret2 = call_write_iter(file, kiocb, &iter);
1952 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1953 if (!force_nonblock || ret2 != -EAGAIN) {
1954 kiocb_done(kiocb, ret2, nxt, req->in_async);
1957 ret = io_setup_async_rw(req, io_size, iovec,
1958 inline_vecs, &iter);
1965 if (!io_wq_current_is_worker())
1971 * IORING_OP_NOP just posts a completion event, nothing else.
1973 static int io_nop(struct io_kiocb *req)
1975 struct io_ring_ctx *ctx = req->ctx;
1977 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1980 io_cqring_add_event(req, 0);
1985 static int io_prep_fsync(struct io_kiocb *req)
1987 const struct io_uring_sqe *sqe = req->sqe;
1988 struct io_ring_ctx *ctx = req->ctx;
1990 if (req->flags & REQ_F_PREPPED)
1995 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1997 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2000 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2001 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2004 req->sync.off = READ_ONCE(sqe->off);
2005 req->sync.len = READ_ONCE(sqe->len);
2006 req->flags |= REQ_F_PREPPED;
2010 static bool io_req_cancelled(struct io_kiocb *req)
2012 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2013 req_set_fail_links(req);
2014 io_cqring_add_event(req, -ECANCELED);
2022 static void io_fsync_finish(struct io_wq_work **workptr)
2024 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2025 loff_t end = req->sync.off + req->sync.len;
2026 struct io_kiocb *nxt = NULL;
2029 if (io_req_cancelled(req))
2032 ret = vfs_fsync_range(req->rw.ki_filp, req->sync.off,
2033 end > 0 ? end : LLONG_MAX,
2034 req->sync.flags & IORING_FSYNC_DATASYNC);
2036 req_set_fail_links(req);
2037 io_cqring_add_event(req, ret);
2038 io_put_req_find_next(req, &nxt);
2040 *workptr = &nxt->work;
2043 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2044 bool force_nonblock)
2046 struct io_wq_work *work, *old_work;
2049 ret = io_prep_fsync(req);
2053 /* fsync always requires a blocking context */
2054 if (force_nonblock) {
2056 req->work.func = io_fsync_finish;
2060 work = old_work = &req->work;
2061 io_fsync_finish(&work);
2062 if (work && work != old_work)
2063 *nxt = container_of(work, struct io_kiocb, work);
2067 static int io_prep_sfr(struct io_kiocb *req)
2069 const struct io_uring_sqe *sqe = req->sqe;
2070 struct io_ring_ctx *ctx = req->ctx;
2072 if (req->flags & REQ_F_PREPPED)
2077 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2079 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2082 req->sync.off = READ_ONCE(sqe->off);
2083 req->sync.len = READ_ONCE(sqe->len);
2084 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2085 req->flags |= REQ_F_PREPPED;
2089 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2091 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2092 struct io_kiocb *nxt = NULL;
2095 if (io_req_cancelled(req))
2098 ret = sync_file_range(req->rw.ki_filp, req->sync.off, req->sync.len,
2101 req_set_fail_links(req);
2102 io_cqring_add_event(req, ret);
2103 io_put_req_find_next(req, &nxt);
2105 *workptr = &nxt->work;
2108 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2109 bool force_nonblock)
2111 struct io_wq_work *work, *old_work;
2114 ret = io_prep_sfr(req);
2118 /* sync_file_range always requires a blocking context */
2119 if (force_nonblock) {
2121 req->work.func = io_sync_file_range_finish;
2125 work = old_work = &req->work;
2126 io_sync_file_range_finish(&work);
2127 if (work && work != old_work)
2128 *nxt = container_of(work, struct io_kiocb, work);
2132 #if defined(CONFIG_NET)
2133 static void io_sendrecv_async(struct io_wq_work **workptr)
2135 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2136 struct iovec *iov = NULL;
2138 if (req->io->rw.iov != req->io->rw.fast_iov)
2139 iov = req->io->msg.iov;
2140 io_wq_submit_work(workptr);
2145 static int io_sendmsg_prep(struct io_kiocb *req, struct io_async_ctx *io)
2147 #if defined(CONFIG_NET)
2148 const struct io_uring_sqe *sqe = req->sqe;
2149 struct user_msghdr __user *msg;
2152 flags = READ_ONCE(sqe->msg_flags);
2153 msg = (struct user_msghdr __user *)(unsigned long) READ_ONCE(sqe->addr);
2154 io->msg.iov = io->msg.fast_iov;
2155 return sendmsg_copy_msghdr(&io->msg.msg, msg, flags, &io->msg.iov);
2161 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2162 bool force_nonblock)
2164 #if defined(CONFIG_NET)
2165 const struct io_uring_sqe *sqe = req->sqe;
2166 struct io_async_msghdr *kmsg = NULL;
2167 struct socket *sock;
2170 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2173 sock = sock_from_file(req->file, &ret);
2175 struct io_async_ctx io;
2176 struct sockaddr_storage addr;
2179 flags = READ_ONCE(sqe->msg_flags);
2180 if (flags & MSG_DONTWAIT)
2181 req->flags |= REQ_F_NOWAIT;
2182 else if (force_nonblock)
2183 flags |= MSG_DONTWAIT;
2186 kmsg = &req->io->msg;
2187 kmsg->msg.msg_name = &addr;
2188 /* if iov is set, it's allocated already */
2190 kmsg->iov = kmsg->fast_iov;
2191 kmsg->msg.msg_iter.iov = kmsg->iov;
2194 kmsg->msg.msg_name = &addr;
2195 ret = io_sendmsg_prep(req, &io);
2200 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2201 if (force_nonblock && ret == -EAGAIN) {
2204 if (io_alloc_async_ctx(req))
2206 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2207 req->work.func = io_sendrecv_async;
2210 if (ret == -ERESTARTSYS)
2215 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2217 io_cqring_add_event(req, ret);
2219 req_set_fail_links(req);
2220 io_put_req_find_next(req, nxt);
2227 static int io_recvmsg_prep(struct io_kiocb *req, struct io_async_ctx *io)
2229 #if defined(CONFIG_NET)
2230 const struct io_uring_sqe *sqe = req->sqe;
2231 struct user_msghdr __user *msg;
2234 flags = READ_ONCE(sqe->msg_flags);
2235 msg = (struct user_msghdr __user *)(unsigned long) READ_ONCE(sqe->addr);
2236 io->msg.iov = io->msg.fast_iov;
2237 return recvmsg_copy_msghdr(&io->msg.msg, msg, flags, &io->msg.uaddr,
2244 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2245 bool force_nonblock)
2247 #if defined(CONFIG_NET)
2248 const struct io_uring_sqe *sqe = req->sqe;
2249 struct io_async_msghdr *kmsg = NULL;
2250 struct socket *sock;
2253 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2256 sock = sock_from_file(req->file, &ret);
2258 struct user_msghdr __user *msg;
2259 struct io_async_ctx io;
2260 struct sockaddr_storage addr;
2263 flags = READ_ONCE(sqe->msg_flags);
2264 if (flags & MSG_DONTWAIT)
2265 req->flags |= REQ_F_NOWAIT;
2266 else if (force_nonblock)
2267 flags |= MSG_DONTWAIT;
2269 msg = (struct user_msghdr __user *) (unsigned long)
2270 READ_ONCE(sqe->addr);
2272 kmsg = &req->io->msg;
2273 kmsg->msg.msg_name = &addr;
2274 /* if iov is set, it's allocated already */
2276 kmsg->iov = kmsg->fast_iov;
2277 kmsg->msg.msg_iter.iov = kmsg->iov;
2280 kmsg->msg.msg_name = &addr;
2281 ret = io_recvmsg_prep(req, &io);
2286 ret = __sys_recvmsg_sock(sock, &kmsg->msg, msg, kmsg->uaddr, flags);
2287 if (force_nonblock && ret == -EAGAIN) {
2290 if (io_alloc_async_ctx(req))
2292 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2293 req->work.func = io_sendrecv_async;
2296 if (ret == -ERESTARTSYS)
2301 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2303 io_cqring_add_event(req, ret);
2305 req_set_fail_links(req);
2306 io_put_req_find_next(req, nxt);
2313 static int io_accept_prep(struct io_kiocb *req)
2315 #if defined(CONFIG_NET)
2316 const struct io_uring_sqe *sqe = req->sqe;
2317 struct io_accept *accept = &req->accept;
2319 if (req->flags & REQ_F_PREPPED)
2322 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2324 if (sqe->ioprio || sqe->len || sqe->buf_index)
2327 accept->addr = (struct sockaddr __user *)
2328 (unsigned long) READ_ONCE(sqe->addr);
2329 accept->addr_len = (int __user *) (unsigned long) READ_ONCE(sqe->addr2);
2330 accept->flags = READ_ONCE(sqe->accept_flags);
2331 req->flags |= REQ_F_PREPPED;
2338 #if defined(CONFIG_NET)
2339 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2340 bool force_nonblock)
2342 struct io_accept *accept = &req->accept;
2343 unsigned file_flags;
2346 file_flags = force_nonblock ? O_NONBLOCK : 0;
2347 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
2348 accept->addr_len, accept->flags);
2349 if (ret == -EAGAIN && force_nonblock)
2351 if (ret == -ERESTARTSYS)
2354 req_set_fail_links(req);
2355 io_cqring_add_event(req, ret);
2356 io_put_req_find_next(req, nxt);
2360 static void io_accept_finish(struct io_wq_work **workptr)
2362 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2363 struct io_kiocb *nxt = NULL;
2365 if (io_req_cancelled(req))
2367 __io_accept(req, &nxt, false);
2369 *workptr = &nxt->work;
2373 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2374 bool force_nonblock)
2376 #if defined(CONFIG_NET)
2379 ret = io_accept_prep(req);
2383 ret = __io_accept(req, nxt, force_nonblock);
2384 if (ret == -EAGAIN && force_nonblock) {
2385 req->work.func = io_accept_finish;
2386 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2396 static int io_connect_prep(struct io_kiocb *req, struct io_async_ctx *io)
2398 #if defined(CONFIG_NET)
2399 const struct io_uring_sqe *sqe = req->sqe;
2400 struct sockaddr __user *addr;
2403 addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
2404 addr_len = READ_ONCE(sqe->addr2);
2405 return move_addr_to_kernel(addr, addr_len, &io->connect.address);
2411 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
2412 bool force_nonblock)
2414 #if defined(CONFIG_NET)
2415 const struct io_uring_sqe *sqe = req->sqe;
2416 struct io_async_ctx __io, *io;
2417 unsigned file_flags;
2420 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2422 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
2425 addr_len = READ_ONCE(sqe->addr2);
2426 file_flags = force_nonblock ? O_NONBLOCK : 0;
2431 ret = io_connect_prep(req, &__io);
2437 ret = __sys_connect_file(req->file, &io->connect.address, addr_len,
2439 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
2442 if (io_alloc_async_ctx(req)) {
2446 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
2449 if (ret == -ERESTARTSYS)
2453 req_set_fail_links(req);
2454 io_cqring_add_event(req, ret);
2455 io_put_req_find_next(req, nxt);
2462 static void io_poll_remove_one(struct io_kiocb *req)
2464 struct io_poll_iocb *poll = &req->poll;
2466 spin_lock(&poll->head->lock);
2467 WRITE_ONCE(poll->canceled, true);
2468 if (!list_empty(&poll->wait.entry)) {
2469 list_del_init(&poll->wait.entry);
2470 io_queue_async_work(req);
2472 spin_unlock(&poll->head->lock);
2473 hash_del(&req->hash_node);
2476 static void io_poll_remove_all(struct io_ring_ctx *ctx)
2478 struct hlist_node *tmp;
2479 struct io_kiocb *req;
2482 spin_lock_irq(&ctx->completion_lock);
2483 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
2484 struct hlist_head *list;
2486 list = &ctx->cancel_hash[i];
2487 hlist_for_each_entry_safe(req, tmp, list, hash_node)
2488 io_poll_remove_one(req);
2490 spin_unlock_irq(&ctx->completion_lock);
2493 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
2495 struct hlist_head *list;
2496 struct io_kiocb *req;
2498 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
2499 hlist_for_each_entry(req, list, hash_node) {
2500 if (sqe_addr == req->user_data) {
2501 io_poll_remove_one(req);
2509 static int io_poll_remove_prep(struct io_kiocb *req)
2511 const struct io_uring_sqe *sqe = req->sqe;
2513 if (req->flags & REQ_F_PREPPED)
2515 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2517 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
2521 req->poll.addr = READ_ONCE(sqe->addr);
2522 req->flags |= REQ_F_PREPPED;
2527 * Find a running poll command that matches one specified in sqe->addr,
2528 * and remove it if found.
2530 static int io_poll_remove(struct io_kiocb *req)
2532 struct io_ring_ctx *ctx = req->ctx;
2536 ret = io_poll_remove_prep(req);
2540 addr = req->poll.addr;
2541 spin_lock_irq(&ctx->completion_lock);
2542 ret = io_poll_cancel(ctx, addr);
2543 spin_unlock_irq(&ctx->completion_lock);
2545 io_cqring_add_event(req, ret);
2547 req_set_fail_links(req);
2552 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
2554 struct io_ring_ctx *ctx = req->ctx;
2556 req->poll.done = true;
2558 io_cqring_fill_event(req, error);
2560 io_cqring_fill_event(req, mangle_poll(mask));
2561 io_commit_cqring(ctx);
2564 static void io_poll_complete_work(struct io_wq_work **workptr)
2566 struct io_wq_work *work = *workptr;
2567 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2568 struct io_poll_iocb *poll = &req->poll;
2569 struct poll_table_struct pt = { ._key = poll->events };
2570 struct io_ring_ctx *ctx = req->ctx;
2571 struct io_kiocb *nxt = NULL;
2575 if (work->flags & IO_WQ_WORK_CANCEL) {
2576 WRITE_ONCE(poll->canceled, true);
2578 } else if (READ_ONCE(poll->canceled)) {
2582 if (ret != -ECANCELED)
2583 mask = vfs_poll(poll->file, &pt) & poll->events;
2586 * Note that ->ki_cancel callers also delete iocb from active_reqs after
2587 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
2588 * synchronize with them. In the cancellation case the list_del_init
2589 * itself is not actually needed, but harmless so we keep it in to
2590 * avoid further branches in the fast path.
2592 spin_lock_irq(&ctx->completion_lock);
2593 if (!mask && ret != -ECANCELED) {
2594 add_wait_queue(poll->head, &poll->wait);
2595 spin_unlock_irq(&ctx->completion_lock);
2598 hash_del(&req->hash_node);
2599 io_poll_complete(req, mask, ret);
2600 spin_unlock_irq(&ctx->completion_lock);
2602 io_cqring_ev_posted(ctx);
2605 req_set_fail_links(req);
2606 io_put_req_find_next(req, &nxt);
2608 *workptr = &nxt->work;
2611 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2614 struct io_poll_iocb *poll = wait->private;
2615 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2616 struct io_ring_ctx *ctx = req->ctx;
2617 __poll_t mask = key_to_poll(key);
2618 unsigned long flags;
2620 /* for instances that support it check for an event match first: */
2621 if (mask && !(mask & poll->events))
2624 list_del_init(&poll->wait.entry);
2627 * Run completion inline if we can. We're using trylock here because
2628 * we are violating the completion_lock -> poll wq lock ordering.
2629 * If we have a link timeout we're going to need the completion_lock
2630 * for finalizing the request, mark us as having grabbed that already.
2632 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2633 hash_del(&req->hash_node);
2634 io_poll_complete(req, mask, 0);
2635 req->flags |= REQ_F_COMP_LOCKED;
2637 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2639 io_cqring_ev_posted(ctx);
2641 io_queue_async_work(req);
2647 struct io_poll_table {
2648 struct poll_table_struct pt;
2649 struct io_kiocb *req;
2653 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2654 struct poll_table_struct *p)
2656 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2658 if (unlikely(pt->req->poll.head)) {
2659 pt->error = -EINVAL;
2664 pt->req->poll.head = head;
2665 add_wait_queue(head, &pt->req->poll.wait);
2668 static void io_poll_req_insert(struct io_kiocb *req)
2670 struct io_ring_ctx *ctx = req->ctx;
2671 struct hlist_head *list;
2673 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
2674 hlist_add_head(&req->hash_node, list);
2677 static int io_poll_add_prep(struct io_kiocb *req)
2679 const struct io_uring_sqe *sqe = req->sqe;
2680 struct io_poll_iocb *poll = &req->poll;
2683 if (req->flags & REQ_F_PREPPED)
2685 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2687 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2692 req->flags |= REQ_F_PREPPED;
2693 events = READ_ONCE(sqe->poll_events);
2694 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2698 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
2700 struct io_poll_iocb *poll = &req->poll;
2701 struct io_ring_ctx *ctx = req->ctx;
2702 struct io_poll_table ipt;
2703 bool cancel = false;
2707 ret = io_poll_add_prep(req);
2711 INIT_IO_WORK(&req->work, io_poll_complete_work);
2712 INIT_HLIST_NODE(&req->hash_node);
2716 poll->canceled = false;
2718 ipt.pt._qproc = io_poll_queue_proc;
2719 ipt.pt._key = poll->events;
2721 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2723 /* initialized the list so that we can do list_empty checks */
2724 INIT_LIST_HEAD(&poll->wait.entry);
2725 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
2726 poll->wait.private = poll;
2728 INIT_LIST_HEAD(&req->list);
2730 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
2732 spin_lock_irq(&ctx->completion_lock);
2733 if (likely(poll->head)) {
2734 spin_lock(&poll->head->lock);
2735 if (unlikely(list_empty(&poll->wait.entry))) {
2741 if (mask || ipt.error)
2742 list_del_init(&poll->wait.entry);
2744 WRITE_ONCE(poll->canceled, true);
2745 else if (!poll->done) /* actually waiting for an event */
2746 io_poll_req_insert(req);
2747 spin_unlock(&poll->head->lock);
2749 if (mask) { /* no async, we'd stolen it */
2751 io_poll_complete(req, mask, 0);
2753 spin_unlock_irq(&ctx->completion_lock);
2756 io_cqring_ev_posted(ctx);
2757 io_put_req_find_next(req, nxt);
2762 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
2764 struct io_timeout_data *data = container_of(timer,
2765 struct io_timeout_data, timer);
2766 struct io_kiocb *req = data->req;
2767 struct io_ring_ctx *ctx = req->ctx;
2768 unsigned long flags;
2770 atomic_inc(&ctx->cq_timeouts);
2772 spin_lock_irqsave(&ctx->completion_lock, flags);
2774 * We could be racing with timeout deletion. If the list is empty,
2775 * then timeout lookup already found it and will be handling it.
2777 if (!list_empty(&req->list)) {
2778 struct io_kiocb *prev;
2781 * Adjust the reqs sequence before the current one because it
2782 * will consume a slot in the cq_ring and the cq_tail
2783 * pointer will be increased, otherwise other timeout reqs may
2784 * return in advance without waiting for enough wait_nr.
2787 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
2789 list_del_init(&req->list);
2792 io_cqring_fill_event(req, -ETIME);
2793 io_commit_cqring(ctx);
2794 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2796 io_cqring_ev_posted(ctx);
2797 req_set_fail_links(req);
2799 return HRTIMER_NORESTART;
2802 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
2804 struct io_kiocb *req;
2807 list_for_each_entry(req, &ctx->timeout_list, list) {
2808 if (user_data == req->user_data) {
2809 list_del_init(&req->list);
2818 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
2822 req_set_fail_links(req);
2823 io_cqring_fill_event(req, -ECANCELED);
2828 static int io_timeout_remove_prep(struct io_kiocb *req)
2830 const struct io_uring_sqe *sqe = req->sqe;
2832 if (req->flags & REQ_F_PREPPED)
2834 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2836 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2839 req->timeout.addr = READ_ONCE(sqe->addr);
2840 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
2841 if (req->timeout.flags)
2844 req->flags |= REQ_F_PREPPED;
2849 * Remove or update an existing timeout command
2851 static int io_timeout_remove(struct io_kiocb *req)
2853 struct io_ring_ctx *ctx = req->ctx;
2856 ret = io_timeout_remove_prep(req);
2860 spin_lock_irq(&ctx->completion_lock);
2861 ret = io_timeout_cancel(ctx, req->timeout.addr);
2863 io_cqring_fill_event(req, ret);
2864 io_commit_cqring(ctx);
2865 spin_unlock_irq(&ctx->completion_lock);
2866 io_cqring_ev_posted(ctx);
2868 req_set_fail_links(req);
2873 static int io_timeout_prep(struct io_kiocb *req, struct io_async_ctx *io,
2874 bool is_timeout_link)
2876 const struct io_uring_sqe *sqe = req->sqe;
2877 struct io_timeout_data *data;
2880 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2882 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
2884 if (sqe->off && is_timeout_link)
2886 flags = READ_ONCE(sqe->timeout_flags);
2887 if (flags & ~IORING_TIMEOUT_ABS)
2890 data = &io->timeout;
2892 req->flags |= REQ_F_TIMEOUT;
2894 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
2897 if (flags & IORING_TIMEOUT_ABS)
2898 data->mode = HRTIMER_MODE_ABS;
2900 data->mode = HRTIMER_MODE_REL;
2902 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
2906 static int io_timeout(struct io_kiocb *req)
2908 const struct io_uring_sqe *sqe = req->sqe;
2910 struct io_ring_ctx *ctx = req->ctx;
2911 struct io_timeout_data *data;
2912 struct list_head *entry;
2917 if (io_alloc_async_ctx(req))
2919 ret = io_timeout_prep(req, req->io, false);
2923 data = &req->io->timeout;
2926 * sqe->off holds how many events that need to occur for this
2927 * timeout event to be satisfied. If it isn't set, then this is
2928 * a pure timeout request, sequence isn't used.
2930 count = READ_ONCE(sqe->off);
2932 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2933 spin_lock_irq(&ctx->completion_lock);
2934 entry = ctx->timeout_list.prev;
2938 req->sequence = ctx->cached_sq_head + count - 1;
2939 data->seq_offset = count;
2942 * Insertion sort, ensuring the first entry in the list is always
2943 * the one we need first.
2945 spin_lock_irq(&ctx->completion_lock);
2946 list_for_each_prev(entry, &ctx->timeout_list) {
2947 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2948 unsigned nxt_sq_head;
2949 long long tmp, tmp_nxt;
2950 u32 nxt_offset = nxt->io->timeout.seq_offset;
2952 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2956 * Since cached_sq_head + count - 1 can overflow, use type long
2959 tmp = (long long)ctx->cached_sq_head + count - 1;
2960 nxt_sq_head = nxt->sequence - nxt_offset + 1;
2961 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
2964 * cached_sq_head may overflow, and it will never overflow twice
2965 * once there is some timeout req still be valid.
2967 if (ctx->cached_sq_head < nxt_sq_head)
2974 * Sequence of reqs after the insert one and itself should
2975 * be adjusted because each timeout req consumes a slot.
2980 req->sequence -= span;
2982 list_add(&req->list, entry);
2983 data->timer.function = io_timeout_fn;
2984 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
2985 spin_unlock_irq(&ctx->completion_lock);
2989 static bool io_cancel_cb(struct io_wq_work *work, void *data)
2991 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2993 return req->user_data == (unsigned long) data;
2996 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
2998 enum io_wq_cancel cancel_ret;
3001 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3002 switch (cancel_ret) {
3003 case IO_WQ_CANCEL_OK:
3006 case IO_WQ_CANCEL_RUNNING:
3009 case IO_WQ_CANCEL_NOTFOUND:
3017 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3018 struct io_kiocb *req, __u64 sqe_addr,
3019 struct io_kiocb **nxt, int success_ret)
3021 unsigned long flags;
3024 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3025 if (ret != -ENOENT) {
3026 spin_lock_irqsave(&ctx->completion_lock, flags);
3030 spin_lock_irqsave(&ctx->completion_lock, flags);
3031 ret = io_timeout_cancel(ctx, sqe_addr);
3034 ret = io_poll_cancel(ctx, sqe_addr);
3038 io_cqring_fill_event(req, ret);
3039 io_commit_cqring(ctx);
3040 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3041 io_cqring_ev_posted(ctx);
3044 req_set_fail_links(req);
3045 io_put_req_find_next(req, nxt);
3048 static int io_async_cancel_prep(struct io_kiocb *req)
3050 const struct io_uring_sqe *sqe = req->sqe;
3052 if (req->flags & REQ_F_PREPPED)
3054 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3056 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3060 req->flags |= REQ_F_PREPPED;
3061 req->cancel.addr = READ_ONCE(sqe->addr);
3065 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3067 struct io_ring_ctx *ctx = req->ctx;
3070 ret = io_async_cancel_prep(req);
3074 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3078 static int io_req_defer_prep(struct io_kiocb *req)
3080 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3081 struct io_async_ctx *io = req->io;
3082 struct iov_iter iter;
3085 switch (io->sqe.opcode) {
3086 case IORING_OP_READV:
3087 case IORING_OP_READ_FIXED:
3088 /* ensure prep does right import */
3090 ret = io_read_prep(req, &iovec, &iter, true);
3094 io_req_map_rw(req, ret, iovec, inline_vecs, &iter);
3097 case IORING_OP_WRITEV:
3098 case IORING_OP_WRITE_FIXED:
3099 /* ensure prep does right import */
3101 ret = io_write_prep(req, &iovec, &iter, true);
3105 io_req_map_rw(req, ret, iovec, inline_vecs, &iter);
3108 case IORING_OP_POLL_ADD:
3109 ret = io_poll_add_prep(req);
3111 case IORING_OP_POLL_REMOVE:
3112 ret = io_poll_remove_prep(req);
3114 case IORING_OP_FSYNC:
3115 ret = io_prep_fsync(req);
3117 case IORING_OP_SYNC_FILE_RANGE:
3118 ret = io_prep_sfr(req);
3120 case IORING_OP_SENDMSG:
3121 ret = io_sendmsg_prep(req, io);
3123 case IORING_OP_RECVMSG:
3124 ret = io_recvmsg_prep(req, io);
3126 case IORING_OP_CONNECT:
3127 ret = io_connect_prep(req, io);
3129 case IORING_OP_TIMEOUT:
3130 ret = io_timeout_prep(req, io, false);
3132 case IORING_OP_TIMEOUT_REMOVE:
3133 ret = io_timeout_remove_prep(req);
3135 case IORING_OP_ASYNC_CANCEL:
3136 ret = io_async_cancel_prep(req);
3138 case IORING_OP_LINK_TIMEOUT:
3139 ret = io_timeout_prep(req, io, true);
3141 case IORING_OP_ACCEPT:
3142 ret = io_accept_prep(req);
3152 static int io_req_defer(struct io_kiocb *req)
3154 struct io_ring_ctx *ctx = req->ctx;
3157 /* Still need defer if there is pending req in defer list. */
3158 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
3161 if (io_alloc_async_ctx(req))
3164 ret = io_req_defer_prep(req);
3168 spin_lock_irq(&ctx->completion_lock);
3169 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
3170 spin_unlock_irq(&ctx->completion_lock);
3174 trace_io_uring_defer(ctx, req, req->user_data);
3175 list_add_tail(&req->list, &ctx->defer_list);
3176 spin_unlock_irq(&ctx->completion_lock);
3177 return -EIOCBQUEUED;
3180 __attribute__((nonnull))
3181 static int io_issue_sqe(struct io_kiocb *req, struct io_kiocb **nxt,
3182 bool force_nonblock)
3185 struct io_ring_ctx *ctx = req->ctx;
3187 opcode = READ_ONCE(req->sqe->opcode);
3192 case IORING_OP_READV:
3193 if (unlikely(req->sqe->buf_index))
3195 ret = io_read(req, nxt, force_nonblock);
3197 case IORING_OP_WRITEV:
3198 if (unlikely(req->sqe->buf_index))
3200 ret = io_write(req, nxt, force_nonblock);
3202 case IORING_OP_READ_FIXED:
3203 ret = io_read(req, nxt, force_nonblock);
3205 case IORING_OP_WRITE_FIXED:
3206 ret = io_write(req, nxt, force_nonblock);
3208 case IORING_OP_FSYNC:
3209 ret = io_fsync(req, nxt, force_nonblock);
3211 case IORING_OP_POLL_ADD:
3212 ret = io_poll_add(req, nxt);
3214 case IORING_OP_POLL_REMOVE:
3215 ret = io_poll_remove(req);
3217 case IORING_OP_SYNC_FILE_RANGE:
3218 ret = io_sync_file_range(req, nxt, force_nonblock);
3220 case IORING_OP_SENDMSG:
3221 ret = io_sendmsg(req, nxt, force_nonblock);
3223 case IORING_OP_RECVMSG:
3224 ret = io_recvmsg(req, nxt, force_nonblock);
3226 case IORING_OP_TIMEOUT:
3227 ret = io_timeout(req);
3229 case IORING_OP_TIMEOUT_REMOVE:
3230 ret = io_timeout_remove(req);
3232 case IORING_OP_ACCEPT:
3233 ret = io_accept(req, nxt, force_nonblock);
3235 case IORING_OP_CONNECT:
3236 ret = io_connect(req, nxt, force_nonblock);
3238 case IORING_OP_ASYNC_CANCEL:
3239 ret = io_async_cancel(req, nxt);
3249 if (ctx->flags & IORING_SETUP_IOPOLL) {
3250 if (req->result == -EAGAIN)
3253 io_iopoll_req_issued(req);
3259 static void io_link_work_cb(struct io_wq_work **workptr)
3261 struct io_wq_work *work = *workptr;
3262 struct io_kiocb *link = work->data;
3264 io_queue_linked_timeout(link);
3265 work->func = io_wq_submit_work;
3268 static void io_wq_submit_work(struct io_wq_work **workptr)
3270 struct io_wq_work *work = *workptr;
3271 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3272 struct io_kiocb *nxt = NULL;
3275 /* Ensure we clear previously set non-block flag */
3276 req->rw.ki_flags &= ~IOCB_NOWAIT;
3278 if (work->flags & IO_WQ_WORK_CANCEL)
3282 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
3283 req->in_async = true;
3285 ret = io_issue_sqe(req, &nxt, false);
3287 * We can get EAGAIN for polled IO even though we're
3288 * forcing a sync submission from here, since we can't
3289 * wait for request slots on the block side.
3297 /* drop submission reference */
3301 req_set_fail_links(req);
3302 io_cqring_add_event(req, ret);
3306 /* if a dependent link is ready, pass it back */
3308 struct io_kiocb *link;
3310 io_prep_async_work(nxt, &link);
3311 *workptr = &nxt->work;
3313 nxt->work.flags |= IO_WQ_WORK_CB;
3314 nxt->work.func = io_link_work_cb;
3315 nxt->work.data = link;
3320 static bool io_req_op_valid(int op)
3322 return op >= IORING_OP_NOP && op < IORING_OP_LAST;
3325 static int io_op_needs_file(const struct io_uring_sqe *sqe)
3327 int op = READ_ONCE(sqe->opcode);
3331 case IORING_OP_POLL_REMOVE:
3332 case IORING_OP_TIMEOUT:
3333 case IORING_OP_TIMEOUT_REMOVE:
3334 case IORING_OP_ASYNC_CANCEL:
3335 case IORING_OP_LINK_TIMEOUT:
3338 if (io_req_op_valid(op))
3344 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
3347 struct fixed_file_table *table;
3349 table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
3350 return table->files[index & IORING_FILE_TABLE_MASK];
3353 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req)
3355 struct io_ring_ctx *ctx = req->ctx;
3359 flags = READ_ONCE(req->sqe->flags);
3360 fd = READ_ONCE(req->sqe->fd);
3362 if (flags & IOSQE_IO_DRAIN)
3363 req->flags |= REQ_F_IO_DRAIN;
3365 ret = io_op_needs_file(req->sqe);
3369 if (flags & IOSQE_FIXED_FILE) {
3370 if (unlikely(!ctx->file_table ||
3371 (unsigned) fd >= ctx->nr_user_files))
3373 fd = array_index_nospec(fd, ctx->nr_user_files);
3374 req->file = io_file_from_index(ctx, fd);
3377 req->flags |= REQ_F_FIXED_FILE;
3379 if (req->needs_fixed_file)
3381 trace_io_uring_file_get(ctx, fd);
3382 req->file = io_file_get(state, fd);
3383 if (unlikely(!req->file))
3390 static int io_grab_files(struct io_kiocb *req)
3393 struct io_ring_ctx *ctx = req->ctx;
3396 spin_lock_irq(&ctx->inflight_lock);
3398 * We use the f_ops->flush() handler to ensure that we can flush
3399 * out work accessing these files if the fd is closed. Check if
3400 * the fd has changed since we started down this path, and disallow
3401 * this operation if it has.
3403 if (fcheck(req->ring_fd) == req->ring_file) {
3404 list_add(&req->inflight_entry, &ctx->inflight_list);
3405 req->flags |= REQ_F_INFLIGHT;
3406 req->work.files = current->files;
3409 spin_unlock_irq(&ctx->inflight_lock);
3415 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
3417 struct io_timeout_data *data = container_of(timer,
3418 struct io_timeout_data, timer);
3419 struct io_kiocb *req = data->req;
3420 struct io_ring_ctx *ctx = req->ctx;
3421 struct io_kiocb *prev = NULL;
3422 unsigned long flags;
3424 spin_lock_irqsave(&ctx->completion_lock, flags);
3427 * We don't expect the list to be empty, that will only happen if we
3428 * race with the completion of the linked work.
3430 if (!list_empty(&req->link_list)) {
3431 prev = list_entry(req->link_list.prev, struct io_kiocb,
3433 if (refcount_inc_not_zero(&prev->refs)) {
3434 list_del_init(&req->link_list);
3435 prev->flags &= ~REQ_F_LINK_TIMEOUT;
3440 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3443 req_set_fail_links(prev);
3444 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
3448 io_cqring_add_event(req, -ETIME);
3451 return HRTIMER_NORESTART;
3454 static void io_queue_linked_timeout(struct io_kiocb *req)
3456 struct io_ring_ctx *ctx = req->ctx;
3459 * If the list is now empty, then our linked request finished before
3460 * we got a chance to setup the timer
3462 spin_lock_irq(&ctx->completion_lock);
3463 if (!list_empty(&req->link_list)) {
3464 struct io_timeout_data *data = &req->io->timeout;
3466 data->timer.function = io_link_timeout_fn;
3467 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
3470 spin_unlock_irq(&ctx->completion_lock);
3472 /* drop submission reference */
3476 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
3478 struct io_kiocb *nxt;
3480 if (!(req->flags & REQ_F_LINK))
3483 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
3485 if (!nxt || nxt->sqe->opcode != IORING_OP_LINK_TIMEOUT)
3488 req->flags |= REQ_F_LINK_TIMEOUT;
3492 static void __io_queue_sqe(struct io_kiocb *req)
3494 struct io_kiocb *linked_timeout;
3495 struct io_kiocb *nxt = NULL;
3499 linked_timeout = io_prep_linked_timeout(req);
3501 ret = io_issue_sqe(req, &nxt, true);
3504 * We async punt it if the file wasn't marked NOWAIT, or if the file
3505 * doesn't support non-blocking read/write attempts
3507 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
3508 (req->flags & REQ_F_MUST_PUNT))) {
3509 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
3510 ret = io_grab_files(req);
3516 * Queued up for async execution, worker will release
3517 * submit reference when the iocb is actually submitted.
3519 io_queue_async_work(req);
3524 /* drop submission reference */
3527 if (linked_timeout) {
3529 io_queue_linked_timeout(linked_timeout);
3531 io_put_req(linked_timeout);
3534 /* and drop final reference, if we failed */
3536 io_cqring_add_event(req, ret);
3537 req_set_fail_links(req);
3548 static void io_queue_sqe(struct io_kiocb *req)
3552 if (unlikely(req->ctx->drain_next)) {
3553 req->flags |= REQ_F_IO_DRAIN;
3554 req->ctx->drain_next = false;
3556 req->ctx->drain_next = (req->flags & REQ_F_DRAIN_LINK);
3558 ret = io_req_defer(req);
3560 if (ret != -EIOCBQUEUED) {
3561 io_cqring_add_event(req, ret);
3562 req_set_fail_links(req);
3563 io_double_put_req(req);
3566 __io_queue_sqe(req);
3569 static inline void io_queue_link_head(struct io_kiocb *req)
3571 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
3572 io_cqring_add_event(req, -ECANCELED);
3573 io_double_put_req(req);
3578 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
3581 static bool io_submit_sqe(struct io_kiocb *req, struct io_submit_state *state,
3582 struct io_kiocb **link)
3584 struct io_ring_ctx *ctx = req->ctx;
3587 req->user_data = req->sqe->user_data;
3589 /* enforce forwards compatibility on users */
3590 if (unlikely(req->sqe->flags & ~SQE_VALID_FLAGS)) {
3595 ret = io_req_set_file(state, req);
3596 if (unlikely(ret)) {
3598 io_cqring_add_event(req, ret);
3599 io_double_put_req(req);
3604 * If we already have a head request, queue this one for async
3605 * submittal once the head completes. If we don't have a head but
3606 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3607 * submitted sync once the chain is complete. If none of those
3608 * conditions are true (normal request), then just queue it.
3611 struct io_kiocb *prev = *link;
3613 if (req->sqe->flags & IOSQE_IO_DRAIN)
3614 (*link)->flags |= REQ_F_DRAIN_LINK | REQ_F_IO_DRAIN;
3616 if (req->sqe->flags & IOSQE_IO_HARDLINK)
3617 req->flags |= REQ_F_HARDLINK;
3619 if (io_alloc_async_ctx(req)) {
3624 ret = io_req_defer_prep(req);
3626 /* fail even hard links since we don't submit */
3627 prev->flags |= REQ_F_FAIL_LINK;
3630 trace_io_uring_link(ctx, req, prev);
3631 list_add_tail(&req->link_list, &prev->link_list);
3632 } else if (req->sqe->flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
3633 req->flags |= REQ_F_LINK;
3634 if (req->sqe->flags & IOSQE_IO_HARDLINK)
3635 req->flags |= REQ_F_HARDLINK;
3637 INIT_LIST_HEAD(&req->link_list);
3647 * Batched submission is done, ensure local IO is flushed out.
3649 static void io_submit_state_end(struct io_submit_state *state)
3651 blk_finish_plug(&state->plug);
3653 if (state->free_reqs)
3654 kmem_cache_free_bulk(req_cachep, state->free_reqs,
3655 &state->reqs[state->cur_req]);
3659 * Start submission side cache.
3661 static void io_submit_state_start(struct io_submit_state *state,
3662 unsigned int max_ios)
3664 blk_start_plug(&state->plug);
3665 state->free_reqs = 0;
3667 state->ios_left = max_ios;
3670 static void io_commit_sqring(struct io_ring_ctx *ctx)
3672 struct io_rings *rings = ctx->rings;
3674 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
3676 * Ensure any loads from the SQEs are done at this point,
3677 * since once we write the new head, the application could
3678 * write new data to them.
3680 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3685 * Fetch an sqe, if one is available. Note that req->sqe will point to memory
3686 * that is mapped by userspace. This means that care needs to be taken to
3687 * ensure that reads are stable, as we cannot rely on userspace always
3688 * being a good citizen. If members of the sqe are validated and then later
3689 * used, it's important that those reads are done through READ_ONCE() to
3690 * prevent a re-load down the line.
3692 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req)
3694 struct io_rings *rings = ctx->rings;
3695 u32 *sq_array = ctx->sq_array;
3699 * The cached sq head (or cq tail) serves two purposes:
3701 * 1) allows us to batch the cost of updating the user visible
3703 * 2) allows the kernel side to track the head on its own, even
3704 * though the application is the one updating it.
3706 head = ctx->cached_sq_head;
3707 /* make sure SQ entry isn't read before tail */
3708 if (unlikely(head == smp_load_acquire(&rings->sq.tail)))
3711 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
3712 if (likely(head < ctx->sq_entries)) {
3714 * All io need record the previous position, if LINK vs DARIN,
3715 * it can be used to mark the position of the first IO in the
3718 req->sequence = ctx->cached_sq_head;
3719 req->sqe = &ctx->sq_sqes[head];
3720 ctx->cached_sq_head++;
3724 /* drop invalid entries */
3725 ctx->cached_sq_head++;
3726 ctx->cached_sq_dropped++;
3727 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
3731 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
3732 struct file *ring_file, int ring_fd,
3733 struct mm_struct **mm, bool async)
3735 struct io_submit_state state, *statep = NULL;
3736 struct io_kiocb *link = NULL;
3737 int i, submitted = 0;
3738 bool mm_fault = false;
3740 /* if we have a backlog and couldn't flush it all, return BUSY */
3741 if (!list_empty(&ctx->cq_overflow_list) &&
3742 !io_cqring_overflow_flush(ctx, false))
3745 if (nr > IO_PLUG_THRESHOLD) {
3746 io_submit_state_start(&state, nr);
3750 for (i = 0; i < nr; i++) {
3751 struct io_kiocb *req;
3752 unsigned int sqe_flags;
3754 req = io_get_req(ctx, statep);
3755 if (unlikely(!req)) {
3757 submitted = -EAGAIN;
3760 if (!io_get_sqring(ctx, req)) {
3765 if (io_sqe_needs_user(req->sqe) && !*mm) {
3766 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
3768 use_mm(ctx->sqo_mm);
3774 sqe_flags = req->sqe->flags;
3776 req->ring_file = ring_file;
3777 req->ring_fd = ring_fd;
3778 req->has_user = *mm != NULL;
3779 req->in_async = async;
3780 req->needs_fixed_file = async;
3781 trace_io_uring_submit_sqe(ctx, req->sqe->user_data,
3783 if (!io_submit_sqe(req, statep, &link))
3786 * If previous wasn't linked and we have a linked command,
3787 * that's the end of the chain. Submit the previous link.
3789 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) && link) {
3790 io_queue_link_head(link);
3796 io_queue_link_head(link);
3798 io_submit_state_end(&state);
3800 /* Commit SQ ring head once we've consumed and submitted all SQEs */
3801 io_commit_sqring(ctx);
3806 static int io_sq_thread(void *data)
3808 struct io_ring_ctx *ctx = data;
3809 struct mm_struct *cur_mm = NULL;
3810 const struct cred *old_cred;
3811 mm_segment_t old_fs;
3814 unsigned long timeout;
3817 complete(&ctx->completions[1]);
3821 old_cred = override_creds(ctx->creds);
3823 ret = timeout = inflight = 0;
3824 while (!kthread_should_park()) {
3825 unsigned int to_submit;
3828 unsigned nr_events = 0;
3830 if (ctx->flags & IORING_SETUP_IOPOLL) {
3832 * inflight is the count of the maximum possible
3833 * entries we submitted, but it can be smaller
3834 * if we dropped some of them. If we don't have
3835 * poll entries available, then we know that we
3836 * have nothing left to poll for. Reset the
3837 * inflight count to zero in that case.
3839 mutex_lock(&ctx->uring_lock);
3840 if (!list_empty(&ctx->poll_list))
3841 __io_iopoll_check(ctx, &nr_events, 0);
3844 mutex_unlock(&ctx->uring_lock);
3847 * Normal IO, just pretend everything completed.
3848 * We don't have to poll completions for that.
3850 nr_events = inflight;
3853 inflight -= nr_events;
3855 timeout = jiffies + ctx->sq_thread_idle;
3858 to_submit = io_sqring_entries(ctx);
3861 * If submit got -EBUSY, flag us as needing the application
3862 * to enter the kernel to reap and flush events.
3864 if (!to_submit || ret == -EBUSY) {
3866 * We're polling. If we're within the defined idle
3867 * period, then let us spin without work before going
3868 * to sleep. The exception is if we got EBUSY doing
3869 * more IO, we should wait for the application to
3870 * reap events and wake us up.
3873 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
3879 * Drop cur_mm before scheduling, we can't hold it for
3880 * long periods (or over schedule()). Do this before
3881 * adding ourselves to the waitqueue, as the unuse/drop
3890 prepare_to_wait(&ctx->sqo_wait, &wait,
3891 TASK_INTERRUPTIBLE);
3893 /* Tell userspace we may need a wakeup call */
3894 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
3895 /* make sure to read SQ tail after writing flags */
3898 to_submit = io_sqring_entries(ctx);
3899 if (!to_submit || ret == -EBUSY) {
3900 if (kthread_should_park()) {
3901 finish_wait(&ctx->sqo_wait, &wait);
3904 if (signal_pending(current))
3905 flush_signals(current);
3907 finish_wait(&ctx->sqo_wait, &wait);
3909 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3912 finish_wait(&ctx->sqo_wait, &wait);
3914 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3917 to_submit = min(to_submit, ctx->sq_entries);
3918 mutex_lock(&ctx->uring_lock);
3919 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
3920 mutex_unlock(&ctx->uring_lock);
3930 revert_creds(old_cred);
3937 struct io_wait_queue {
3938 struct wait_queue_entry wq;
3939 struct io_ring_ctx *ctx;
3941 unsigned nr_timeouts;
3944 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
3946 struct io_ring_ctx *ctx = iowq->ctx;
3949 * Wake up if we have enough events, or if a timeout occurred since we
3950 * started waiting. For timeouts, we always want to return to userspace,
3951 * regardless of event count.
3953 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
3954 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3957 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3958 int wake_flags, void *key)
3960 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3963 /* use noflush == true, as we can't safely rely on locking context */
3964 if (!io_should_wake(iowq, true))
3967 return autoremove_wake_function(curr, mode, wake_flags, key);
3971 * Wait until events become available, if we don't already have some. The
3972 * application must reap them itself, as they reside on the shared cq ring.
3974 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3975 const sigset_t __user *sig, size_t sigsz)
3977 struct io_wait_queue iowq = {
3980 .func = io_wake_function,
3981 .entry = LIST_HEAD_INIT(iowq.wq.entry),
3984 .to_wait = min_events,
3986 struct io_rings *rings = ctx->rings;
3989 if (io_cqring_events(ctx, false) >= min_events)
3993 #ifdef CONFIG_COMPAT
3994 if (in_compat_syscall())
3995 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3999 ret = set_user_sigmask(sig, sigsz);
4005 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
4006 trace_io_uring_cqring_wait(ctx, min_events);
4008 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
4009 TASK_INTERRUPTIBLE);
4010 if (io_should_wake(&iowq, false))
4013 if (signal_pending(current)) {
4018 finish_wait(&ctx->wait, &iowq.wq);
4020 restore_saved_sigmask_unless(ret == -EINTR);
4022 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
4025 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4027 #if defined(CONFIG_UNIX)
4028 if (ctx->ring_sock) {
4029 struct sock *sock = ctx->ring_sock->sk;
4030 struct sk_buff *skb;
4032 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4038 for (i = 0; i < ctx->nr_user_files; i++) {
4041 file = io_file_from_index(ctx, i);
4048 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4050 unsigned nr_tables, i;
4052 if (!ctx->file_table)
4055 __io_sqe_files_unregister(ctx);
4056 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
4057 for (i = 0; i < nr_tables; i++)
4058 kfree(ctx->file_table[i].files);
4059 kfree(ctx->file_table);
4060 ctx->file_table = NULL;
4061 ctx->nr_user_files = 0;
4065 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
4067 if (ctx->sqo_thread) {
4068 wait_for_completion(&ctx->completions[1]);
4070 * The park is a bit of a work-around, without it we get
4071 * warning spews on shutdown with SQPOLL set and affinity
4072 * set to a single CPU.
4074 kthread_park(ctx->sqo_thread);
4075 kthread_stop(ctx->sqo_thread);
4076 ctx->sqo_thread = NULL;
4080 static void io_finish_async(struct io_ring_ctx *ctx)
4082 io_sq_thread_stop(ctx);
4085 io_wq_destroy(ctx->io_wq);
4090 #if defined(CONFIG_UNIX)
4091 static void io_destruct_skb(struct sk_buff *skb)
4093 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
4096 io_wq_flush(ctx->io_wq);
4098 unix_destruct_scm(skb);
4102 * Ensure the UNIX gc is aware of our file set, so we are certain that
4103 * the io_uring can be safely unregistered on process exit, even if we have
4104 * loops in the file referencing.
4106 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
4108 struct sock *sk = ctx->ring_sock->sk;
4109 struct scm_fp_list *fpl;
4110 struct sk_buff *skb;
4113 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
4114 unsigned long inflight = ctx->user->unix_inflight + nr;
4116 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
4120 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4124 skb = alloc_skb(0, GFP_KERNEL);
4133 fpl->user = get_uid(ctx->user);
4134 for (i = 0; i < nr; i++) {
4135 struct file *file = io_file_from_index(ctx, i + offset);
4139 fpl->fp[nr_files] = get_file(file);
4140 unix_inflight(fpl->user, fpl->fp[nr_files]);
4145 fpl->max = SCM_MAX_FD;
4146 fpl->count = nr_files;
4147 UNIXCB(skb).fp = fpl;
4148 skb->destructor = io_destruct_skb;
4149 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4150 skb_queue_head(&sk->sk_receive_queue, skb);
4152 for (i = 0; i < nr_files; i++)
4163 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
4164 * causes regular reference counting to break down. We rely on the UNIX
4165 * garbage collection to take care of this problem for us.
4167 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4169 unsigned left, total;
4173 left = ctx->nr_user_files;
4175 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
4177 ret = __io_sqe_files_scm(ctx, this_files, total);
4181 total += this_files;
4187 while (total < ctx->nr_user_files) {
4188 struct file *file = io_file_from_index(ctx, total);
4198 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4204 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
4209 for (i = 0; i < nr_tables; i++) {
4210 struct fixed_file_table *table = &ctx->file_table[i];
4211 unsigned this_files;
4213 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
4214 table->files = kcalloc(this_files, sizeof(struct file *),
4218 nr_files -= this_files;
4224 for (i = 0; i < nr_tables; i++) {
4225 struct fixed_file_table *table = &ctx->file_table[i];
4226 kfree(table->files);
4231 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4234 __s32 __user *fds = (__s32 __user *) arg;
4239 if (ctx->file_table)
4243 if (nr_args > IORING_MAX_FIXED_FILES)
4246 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
4247 ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
4249 if (!ctx->file_table)
4252 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
4253 kfree(ctx->file_table);
4254 ctx->file_table = NULL;
4258 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4259 struct fixed_file_table *table;
4263 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
4265 /* allow sparse sets */
4271 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4272 index = i & IORING_FILE_TABLE_MASK;
4273 table->files[index] = fget(fd);
4276 if (!table->files[index])
4279 * Don't allow io_uring instances to be registered. If UNIX
4280 * isn't enabled, then this causes a reference cycle and this
4281 * instance can never get freed. If UNIX is enabled we'll
4282 * handle it just fine, but there's still no point in allowing
4283 * a ring fd as it doesn't support regular read/write anyway.
4285 if (table->files[index]->f_op == &io_uring_fops) {
4286 fput(table->files[index]);
4293 for (i = 0; i < ctx->nr_user_files; i++) {
4296 file = io_file_from_index(ctx, i);
4300 for (i = 0; i < nr_tables; i++)
4301 kfree(ctx->file_table[i].files);
4303 kfree(ctx->file_table);
4304 ctx->file_table = NULL;
4305 ctx->nr_user_files = 0;
4309 ret = io_sqe_files_scm(ctx);
4311 io_sqe_files_unregister(ctx);
4316 static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
4318 #if defined(CONFIG_UNIX)
4319 struct file *file = io_file_from_index(ctx, index);
4320 struct sock *sock = ctx->ring_sock->sk;
4321 struct sk_buff_head list, *head = &sock->sk_receive_queue;
4322 struct sk_buff *skb;
4325 __skb_queue_head_init(&list);
4328 * Find the skb that holds this file in its SCM_RIGHTS. When found,
4329 * remove this entry and rearrange the file array.
4331 skb = skb_dequeue(head);
4333 struct scm_fp_list *fp;
4335 fp = UNIXCB(skb).fp;
4336 for (i = 0; i < fp->count; i++) {
4339 if (fp->fp[i] != file)
4342 unix_notinflight(fp->user, fp->fp[i]);
4343 left = fp->count - 1 - i;
4345 memmove(&fp->fp[i], &fp->fp[i + 1],
4346 left * sizeof(struct file *));
4353 __skb_queue_tail(&list, skb);
4363 __skb_queue_tail(&list, skb);
4365 skb = skb_dequeue(head);
4368 if (skb_peek(&list)) {
4369 spin_lock_irq(&head->lock);
4370 while ((skb = __skb_dequeue(&list)) != NULL)
4371 __skb_queue_tail(head, skb);
4372 spin_unlock_irq(&head->lock);
4375 fput(io_file_from_index(ctx, index));
4379 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
4382 #if defined(CONFIG_UNIX)
4383 struct sock *sock = ctx->ring_sock->sk;
4384 struct sk_buff_head *head = &sock->sk_receive_queue;
4385 struct sk_buff *skb;
4388 * See if we can merge this file into an existing skb SCM_RIGHTS
4389 * file set. If there's no room, fall back to allocating a new skb
4390 * and filling it in.
4392 spin_lock_irq(&head->lock);
4393 skb = skb_peek(head);
4395 struct scm_fp_list *fpl = UNIXCB(skb).fp;
4397 if (fpl->count < SCM_MAX_FD) {
4398 __skb_unlink(skb, head);
4399 spin_unlock_irq(&head->lock);
4400 fpl->fp[fpl->count] = get_file(file);
4401 unix_inflight(fpl->user, fpl->fp[fpl->count]);
4403 spin_lock_irq(&head->lock);
4404 __skb_queue_head(head, skb);
4409 spin_unlock_irq(&head->lock);
4416 return __io_sqe_files_scm(ctx, 1, index);
4422 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
4425 struct io_uring_files_update up;
4430 if (!ctx->file_table)
4434 if (copy_from_user(&up, arg, sizeof(up)))
4436 if (check_add_overflow(up.offset, nr_args, &done))
4438 if (done > ctx->nr_user_files)
4442 fds = (__s32 __user *) up.fds;
4444 struct fixed_file_table *table;
4448 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
4452 i = array_index_nospec(up.offset, ctx->nr_user_files);
4453 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4454 index = i & IORING_FILE_TABLE_MASK;
4455 if (table->files[index]) {
4456 io_sqe_file_unregister(ctx, i);
4457 table->files[index] = NULL;
4468 * Don't allow io_uring instances to be registered. If
4469 * UNIX isn't enabled, then this causes a reference
4470 * cycle and this instance can never get freed. If UNIX
4471 * is enabled we'll handle it just fine, but there's
4472 * still no point in allowing a ring fd as it doesn't
4473 * support regular read/write anyway.
4475 if (file->f_op == &io_uring_fops) {
4480 table->files[index] = file;
4481 err = io_sqe_file_register(ctx, file, i);
4490 return done ? done : err;
4493 static void io_put_work(struct io_wq_work *work)
4495 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4500 static void io_get_work(struct io_wq_work *work)
4502 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4504 refcount_inc(&req->refs);
4507 static int io_sq_offload_start(struct io_ring_ctx *ctx,
4508 struct io_uring_params *p)
4510 struct io_wq_data data;
4511 unsigned concurrency;
4514 init_waitqueue_head(&ctx->sqo_wait);
4515 mmgrab(current->mm);
4516 ctx->sqo_mm = current->mm;
4518 if (ctx->flags & IORING_SETUP_SQPOLL) {
4520 if (!capable(CAP_SYS_ADMIN))
4523 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
4524 if (!ctx->sq_thread_idle)
4525 ctx->sq_thread_idle = HZ;
4527 if (p->flags & IORING_SETUP_SQ_AFF) {
4528 int cpu = p->sq_thread_cpu;
4531 if (cpu >= nr_cpu_ids)
4533 if (!cpu_online(cpu))
4536 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
4540 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
4543 if (IS_ERR(ctx->sqo_thread)) {
4544 ret = PTR_ERR(ctx->sqo_thread);
4545 ctx->sqo_thread = NULL;
4548 wake_up_process(ctx->sqo_thread);
4549 } else if (p->flags & IORING_SETUP_SQ_AFF) {
4550 /* Can't have SQ_AFF without SQPOLL */
4555 data.mm = ctx->sqo_mm;
4556 data.user = ctx->user;
4557 data.creds = ctx->creds;
4558 data.get_work = io_get_work;
4559 data.put_work = io_put_work;
4561 /* Do QD, or 4 * CPUS, whatever is smallest */
4562 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
4563 ctx->io_wq = io_wq_create(concurrency, &data);
4564 if (IS_ERR(ctx->io_wq)) {
4565 ret = PTR_ERR(ctx->io_wq);
4572 io_finish_async(ctx);
4573 mmdrop(ctx->sqo_mm);
4578 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
4580 atomic_long_sub(nr_pages, &user->locked_vm);
4583 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
4585 unsigned long page_limit, cur_pages, new_pages;
4587 /* Don't allow more pages than we can safely lock */
4588 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4591 cur_pages = atomic_long_read(&user->locked_vm);
4592 new_pages = cur_pages + nr_pages;
4593 if (new_pages > page_limit)
4595 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4596 new_pages) != cur_pages);
4601 static void io_mem_free(void *ptr)
4608 page = virt_to_head_page(ptr);
4609 if (put_page_testzero(page))
4610 free_compound_page(page);
4613 static void *io_mem_alloc(size_t size)
4615 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
4618 return (void *) __get_free_pages(gfp_flags, get_order(size));
4621 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
4624 struct io_rings *rings;
4625 size_t off, sq_array_size;
4627 off = struct_size(rings, cqes, cq_entries);
4628 if (off == SIZE_MAX)
4632 off = ALIGN(off, SMP_CACHE_BYTES);
4637 sq_array_size = array_size(sizeof(u32), sq_entries);
4638 if (sq_array_size == SIZE_MAX)
4641 if (check_add_overflow(off, sq_array_size, &off))
4650 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
4654 pages = (size_t)1 << get_order(
4655 rings_size(sq_entries, cq_entries, NULL));
4656 pages += (size_t)1 << get_order(
4657 array_size(sizeof(struct io_uring_sqe), sq_entries));
4662 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
4666 if (!ctx->user_bufs)
4669 for (i = 0; i < ctx->nr_user_bufs; i++) {
4670 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4672 for (j = 0; j < imu->nr_bvecs; j++)
4673 put_user_page(imu->bvec[j].bv_page);
4675 if (ctx->account_mem)
4676 io_unaccount_mem(ctx->user, imu->nr_bvecs);
4681 kfree(ctx->user_bufs);
4682 ctx->user_bufs = NULL;
4683 ctx->nr_user_bufs = 0;
4687 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4688 void __user *arg, unsigned index)
4690 struct iovec __user *src;
4692 #ifdef CONFIG_COMPAT
4694 struct compat_iovec __user *ciovs;
4695 struct compat_iovec ciov;
4697 ciovs = (struct compat_iovec __user *) arg;
4698 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4701 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
4702 dst->iov_len = ciov.iov_len;
4706 src = (struct iovec __user *) arg;
4707 if (copy_from_user(dst, &src[index], sizeof(*dst)))
4712 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
4715 struct vm_area_struct **vmas = NULL;
4716 struct page **pages = NULL;
4717 int i, j, got_pages = 0;
4722 if (!nr_args || nr_args > UIO_MAXIOV)
4725 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
4727 if (!ctx->user_bufs)
4730 for (i = 0; i < nr_args; i++) {
4731 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4732 unsigned long off, start, end, ubuf;
4737 ret = io_copy_iov(ctx, &iov, arg, i);
4742 * Don't impose further limits on the size and buffer
4743 * constraints here, we'll -EINVAL later when IO is
4744 * submitted if they are wrong.
4747 if (!iov.iov_base || !iov.iov_len)
4750 /* arbitrary limit, but we need something */
4751 if (iov.iov_len > SZ_1G)
4754 ubuf = (unsigned long) iov.iov_base;
4755 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4756 start = ubuf >> PAGE_SHIFT;
4757 nr_pages = end - start;
4759 if (ctx->account_mem) {
4760 ret = io_account_mem(ctx->user, nr_pages);
4766 if (!pages || nr_pages > got_pages) {
4769 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
4771 vmas = kvmalloc_array(nr_pages,
4772 sizeof(struct vm_area_struct *),
4774 if (!pages || !vmas) {
4776 if (ctx->account_mem)
4777 io_unaccount_mem(ctx->user, nr_pages);
4780 got_pages = nr_pages;
4783 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
4787 if (ctx->account_mem)
4788 io_unaccount_mem(ctx->user, nr_pages);
4793 down_read(¤t->mm->mmap_sem);
4794 pret = get_user_pages(ubuf, nr_pages,
4795 FOLL_WRITE | FOLL_LONGTERM,
4797 if (pret == nr_pages) {
4798 /* don't support file backed memory */
4799 for (j = 0; j < nr_pages; j++) {
4800 struct vm_area_struct *vma = vmas[j];
4803 !is_file_hugepages(vma->vm_file)) {
4809 ret = pret < 0 ? pret : -EFAULT;
4811 up_read(¤t->mm->mmap_sem);
4814 * if we did partial map, or found file backed vmas,
4815 * release any pages we did get
4818 put_user_pages(pages, pret);
4819 if (ctx->account_mem)
4820 io_unaccount_mem(ctx->user, nr_pages);
4825 off = ubuf & ~PAGE_MASK;
4827 for (j = 0; j < nr_pages; j++) {
4830 vec_len = min_t(size_t, size, PAGE_SIZE - off);
4831 imu->bvec[j].bv_page = pages[j];
4832 imu->bvec[j].bv_len = vec_len;
4833 imu->bvec[j].bv_offset = off;
4837 /* store original address for later verification */
4839 imu->len = iov.iov_len;
4840 imu->nr_bvecs = nr_pages;
4842 ctx->nr_user_bufs++;
4850 io_sqe_buffer_unregister(ctx);
4854 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
4856 __s32 __user *fds = arg;
4862 if (copy_from_user(&fd, fds, sizeof(*fds)))
4865 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
4866 if (IS_ERR(ctx->cq_ev_fd)) {
4867 int ret = PTR_ERR(ctx->cq_ev_fd);
4868 ctx->cq_ev_fd = NULL;
4875 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
4877 if (ctx->cq_ev_fd) {
4878 eventfd_ctx_put(ctx->cq_ev_fd);
4879 ctx->cq_ev_fd = NULL;
4886 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
4888 io_finish_async(ctx);
4890 mmdrop(ctx->sqo_mm);
4892 io_iopoll_reap_events(ctx);
4893 io_sqe_buffer_unregister(ctx);
4894 io_sqe_files_unregister(ctx);
4895 io_eventfd_unregister(ctx);
4897 #if defined(CONFIG_UNIX)
4898 if (ctx->ring_sock) {
4899 ctx->ring_sock->file = NULL; /* so that iput() is called */
4900 sock_release(ctx->ring_sock);
4904 io_mem_free(ctx->rings);
4905 io_mem_free(ctx->sq_sqes);
4907 percpu_ref_exit(&ctx->refs);
4908 if (ctx->account_mem)
4909 io_unaccount_mem(ctx->user,
4910 ring_pages(ctx->sq_entries, ctx->cq_entries));
4911 free_uid(ctx->user);
4912 put_cred(ctx->creds);
4913 kfree(ctx->completions);
4914 kfree(ctx->cancel_hash);
4915 kmem_cache_free(req_cachep, ctx->fallback_req);
4919 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
4921 struct io_ring_ctx *ctx = file->private_data;
4924 poll_wait(file, &ctx->cq_wait, wait);
4926 * synchronizes with barrier from wq_has_sleeper call in
4930 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
4931 ctx->rings->sq_ring_entries)
4932 mask |= EPOLLOUT | EPOLLWRNORM;
4933 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
4934 mask |= EPOLLIN | EPOLLRDNORM;
4939 static int io_uring_fasync(int fd, struct file *file, int on)
4941 struct io_ring_ctx *ctx = file->private_data;
4943 return fasync_helper(fd, file, on, &ctx->cq_fasync);
4946 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
4948 mutex_lock(&ctx->uring_lock);
4949 percpu_ref_kill(&ctx->refs);
4950 mutex_unlock(&ctx->uring_lock);
4952 io_kill_timeouts(ctx);
4953 io_poll_remove_all(ctx);
4956 io_wq_cancel_all(ctx->io_wq);
4958 io_iopoll_reap_events(ctx);
4959 /* if we failed setting up the ctx, we might not have any rings */
4961 io_cqring_overflow_flush(ctx, true);
4962 wait_for_completion(&ctx->completions[0]);
4963 io_ring_ctx_free(ctx);
4966 static int io_uring_release(struct inode *inode, struct file *file)
4968 struct io_ring_ctx *ctx = file->private_data;
4970 file->private_data = NULL;
4971 io_ring_ctx_wait_and_kill(ctx);
4975 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
4976 struct files_struct *files)
4978 struct io_kiocb *req;
4981 while (!list_empty_careful(&ctx->inflight_list)) {
4982 struct io_kiocb *cancel_req = NULL;
4984 spin_lock_irq(&ctx->inflight_lock);
4985 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
4986 if (req->work.files != files)
4988 /* req is being completed, ignore */
4989 if (!refcount_inc_not_zero(&req->refs))
4995 prepare_to_wait(&ctx->inflight_wait, &wait,
4996 TASK_UNINTERRUPTIBLE);
4997 spin_unlock_irq(&ctx->inflight_lock);
4999 /* We need to keep going until we don't find a matching req */
5003 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
5004 io_put_req(cancel_req);
5007 finish_wait(&ctx->inflight_wait, &wait);
5010 static int io_uring_flush(struct file *file, void *data)
5012 struct io_ring_ctx *ctx = file->private_data;
5014 io_uring_cancel_files(ctx, data);
5015 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
5016 io_cqring_overflow_flush(ctx, true);
5017 io_wq_cancel_all(ctx->io_wq);
5022 static void *io_uring_validate_mmap_request(struct file *file,
5023 loff_t pgoff, size_t sz)
5025 struct io_ring_ctx *ctx = file->private_data;
5026 loff_t offset = pgoff << PAGE_SHIFT;
5031 case IORING_OFF_SQ_RING:
5032 case IORING_OFF_CQ_RING:
5035 case IORING_OFF_SQES:
5039 return ERR_PTR(-EINVAL);
5042 page = virt_to_head_page(ptr);
5043 if (sz > page_size(page))
5044 return ERR_PTR(-EINVAL);
5051 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5053 size_t sz = vma->vm_end - vma->vm_start;
5057 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
5059 return PTR_ERR(ptr);
5061 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
5062 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
5065 #else /* !CONFIG_MMU */
5067 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5069 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
5072 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
5074 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
5077 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
5078 unsigned long addr, unsigned long len,
5079 unsigned long pgoff, unsigned long flags)
5083 ptr = io_uring_validate_mmap_request(file, pgoff, len);
5085 return PTR_ERR(ptr);
5087 return (unsigned long) ptr;
5090 #endif /* !CONFIG_MMU */
5092 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
5093 u32, min_complete, u32, flags, const sigset_t __user *, sig,
5096 struct io_ring_ctx *ctx;
5101 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
5109 if (f.file->f_op != &io_uring_fops)
5113 ctx = f.file->private_data;
5114 if (!percpu_ref_tryget(&ctx->refs))
5118 * For SQ polling, the thread will do all submissions and completions.
5119 * Just return the requested submit count, and wake the thread if
5123 if (ctx->flags & IORING_SETUP_SQPOLL) {
5124 if (!list_empty_careful(&ctx->cq_overflow_list))
5125 io_cqring_overflow_flush(ctx, false);
5126 if (flags & IORING_ENTER_SQ_WAKEUP)
5127 wake_up(&ctx->sqo_wait);
5128 submitted = to_submit;
5129 } else if (to_submit) {
5130 struct mm_struct *cur_mm;
5132 to_submit = min(to_submit, ctx->sq_entries);
5133 mutex_lock(&ctx->uring_lock);
5134 /* already have mm, so io_submit_sqes() won't try to grab it */
5135 cur_mm = ctx->sqo_mm;
5136 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
5138 mutex_unlock(&ctx->uring_lock);
5140 if (flags & IORING_ENTER_GETEVENTS) {
5141 unsigned nr_events = 0;
5143 min_complete = min(min_complete, ctx->cq_entries);
5145 if (ctx->flags & IORING_SETUP_IOPOLL) {
5146 ret = io_iopoll_check(ctx, &nr_events, min_complete);
5148 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
5152 percpu_ref_put(&ctx->refs);
5155 return submitted ? submitted : ret;
5158 static const struct file_operations io_uring_fops = {
5159 .release = io_uring_release,
5160 .flush = io_uring_flush,
5161 .mmap = io_uring_mmap,
5163 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
5164 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
5166 .poll = io_uring_poll,
5167 .fasync = io_uring_fasync,
5170 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
5171 struct io_uring_params *p)
5173 struct io_rings *rings;
5174 size_t size, sq_array_offset;
5176 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
5177 if (size == SIZE_MAX)
5180 rings = io_mem_alloc(size);
5185 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
5186 rings->sq_ring_mask = p->sq_entries - 1;
5187 rings->cq_ring_mask = p->cq_entries - 1;
5188 rings->sq_ring_entries = p->sq_entries;
5189 rings->cq_ring_entries = p->cq_entries;
5190 ctx->sq_mask = rings->sq_ring_mask;
5191 ctx->cq_mask = rings->cq_ring_mask;
5192 ctx->sq_entries = rings->sq_ring_entries;
5193 ctx->cq_entries = rings->cq_ring_entries;
5195 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
5196 if (size == SIZE_MAX) {
5197 io_mem_free(ctx->rings);
5202 ctx->sq_sqes = io_mem_alloc(size);
5203 if (!ctx->sq_sqes) {
5204 io_mem_free(ctx->rings);
5213 * Allocate an anonymous fd, this is what constitutes the application
5214 * visible backing of an io_uring instance. The application mmaps this
5215 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
5216 * we have to tie this fd to a socket for file garbage collection purposes.
5218 static int io_uring_get_fd(struct io_ring_ctx *ctx)
5223 #if defined(CONFIG_UNIX)
5224 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
5230 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
5234 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
5235 O_RDWR | O_CLOEXEC);
5238 ret = PTR_ERR(file);
5242 #if defined(CONFIG_UNIX)
5243 ctx->ring_sock->file = file;
5244 ctx->ring_sock->sk->sk_user_data = ctx;
5246 fd_install(ret, file);
5249 #if defined(CONFIG_UNIX)
5250 sock_release(ctx->ring_sock);
5251 ctx->ring_sock = NULL;
5256 static int io_uring_create(unsigned entries, struct io_uring_params *p)
5258 struct user_struct *user = NULL;
5259 struct io_ring_ctx *ctx;
5263 if (!entries || entries > IORING_MAX_ENTRIES)
5267 * Use twice as many entries for the CQ ring. It's possible for the
5268 * application to drive a higher depth than the size of the SQ ring,
5269 * since the sqes are only used at submission time. This allows for
5270 * some flexibility in overcommitting a bit. If the application has
5271 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
5272 * of CQ ring entries manually.
5274 p->sq_entries = roundup_pow_of_two(entries);
5275 if (p->flags & IORING_SETUP_CQSIZE) {
5277 * If IORING_SETUP_CQSIZE is set, we do the same roundup
5278 * to a power-of-two, if it isn't already. We do NOT impose
5279 * any cq vs sq ring sizing.
5281 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
5283 p->cq_entries = roundup_pow_of_two(p->cq_entries);
5285 p->cq_entries = 2 * p->sq_entries;
5288 user = get_uid(current_user());
5289 account_mem = !capable(CAP_IPC_LOCK);
5292 ret = io_account_mem(user,
5293 ring_pages(p->sq_entries, p->cq_entries));
5300 ctx = io_ring_ctx_alloc(p);
5303 io_unaccount_mem(user, ring_pages(p->sq_entries,
5308 ctx->compat = in_compat_syscall();
5309 ctx->account_mem = account_mem;
5311 ctx->creds = get_current_cred();
5313 ret = io_allocate_scq_urings(ctx, p);
5317 ret = io_sq_offload_start(ctx, p);
5321 memset(&p->sq_off, 0, sizeof(p->sq_off));
5322 p->sq_off.head = offsetof(struct io_rings, sq.head);
5323 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
5324 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
5325 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
5326 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
5327 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
5328 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
5330 memset(&p->cq_off, 0, sizeof(p->cq_off));
5331 p->cq_off.head = offsetof(struct io_rings, cq.head);
5332 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
5333 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
5334 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
5335 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
5336 p->cq_off.cqes = offsetof(struct io_rings, cqes);
5339 * Install ring fd as the very last thing, so we don't risk someone
5340 * having closed it before we finish setup
5342 ret = io_uring_get_fd(ctx);
5346 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
5347 IORING_FEAT_SUBMIT_STABLE;
5348 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
5351 io_ring_ctx_wait_and_kill(ctx);
5356 * Sets up an aio uring context, and returns the fd. Applications asks for a
5357 * ring size, we return the actual sq/cq ring sizes (among other things) in the
5358 * params structure passed in.
5360 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
5362 struct io_uring_params p;
5366 if (copy_from_user(&p, params, sizeof(p)))
5368 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
5373 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
5374 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
5377 ret = io_uring_create(entries, &p);
5381 if (copy_to_user(params, &p, sizeof(p)))
5387 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
5388 struct io_uring_params __user *, params)
5390 return io_uring_setup(entries, params);
5393 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
5394 void __user *arg, unsigned nr_args)
5395 __releases(ctx->uring_lock)
5396 __acquires(ctx->uring_lock)
5401 * We're inside the ring mutex, if the ref is already dying, then
5402 * someone else killed the ctx or is already going through
5403 * io_uring_register().
5405 if (percpu_ref_is_dying(&ctx->refs))
5408 percpu_ref_kill(&ctx->refs);
5411 * Drop uring mutex before waiting for references to exit. If another
5412 * thread is currently inside io_uring_enter() it might need to grab
5413 * the uring_lock to make progress. If we hold it here across the drain
5414 * wait, then we can deadlock. It's safe to drop the mutex here, since
5415 * no new references will come in after we've killed the percpu ref.
5417 mutex_unlock(&ctx->uring_lock);
5418 wait_for_completion(&ctx->completions[0]);
5419 mutex_lock(&ctx->uring_lock);
5422 case IORING_REGISTER_BUFFERS:
5423 ret = io_sqe_buffer_register(ctx, arg, nr_args);
5425 case IORING_UNREGISTER_BUFFERS:
5429 ret = io_sqe_buffer_unregister(ctx);
5431 case IORING_REGISTER_FILES:
5432 ret = io_sqe_files_register(ctx, arg, nr_args);
5434 case IORING_UNREGISTER_FILES:
5438 ret = io_sqe_files_unregister(ctx);
5440 case IORING_REGISTER_FILES_UPDATE:
5441 ret = io_sqe_files_update(ctx, arg, nr_args);
5443 case IORING_REGISTER_EVENTFD:
5447 ret = io_eventfd_register(ctx, arg);
5449 case IORING_UNREGISTER_EVENTFD:
5453 ret = io_eventfd_unregister(ctx);
5460 /* bring the ctx back to life */
5461 reinit_completion(&ctx->completions[0]);
5462 percpu_ref_reinit(&ctx->refs);
5466 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
5467 void __user *, arg, unsigned int, nr_args)
5469 struct io_ring_ctx *ctx;
5478 if (f.file->f_op != &io_uring_fops)
5481 ctx = f.file->private_data;
5483 mutex_lock(&ctx->uring_lock);
5484 ret = __io_uring_register(ctx, opcode, arg, nr_args);
5485 mutex_unlock(&ctx->uring_lock);
5486 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
5487 ctx->cq_ev_fd != NULL, ret);
5493 static int __init io_uring_init(void)
5495 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
5498 __initcall(io_uring_init);