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>
73 #define CREATE_TRACE_POINTS
74 #include <trace/events/io_uring.h>
76 #include <uapi/linux/io_uring.h>
81 #define IORING_MAX_ENTRIES 32768
82 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
85 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
87 #define IORING_FILE_TABLE_SHIFT 9
88 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
89 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
90 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
93 u32 head ____cacheline_aligned_in_smp;
94 u32 tail ____cacheline_aligned_in_smp;
98 * This data is shared with the application through the mmap at offsets
99 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
101 * The offsets to the member fields are published through struct
102 * io_sqring_offsets when calling io_uring_setup.
106 * Head and tail offsets into the ring; the offsets need to be
107 * masked to get valid indices.
109 * The kernel controls head of the sq ring and the tail of the cq ring,
110 * and the application controls tail of the sq ring and the head of the
113 struct io_uring sq, cq;
115 * Bitmasks to apply to head and tail offsets (constant, equals
118 u32 sq_ring_mask, cq_ring_mask;
119 /* Ring sizes (constant, power of 2) */
120 u32 sq_ring_entries, cq_ring_entries;
122 * Number of invalid entries dropped by the kernel due to
123 * invalid index stored in array
125 * Written by the kernel, shouldn't be modified by the
126 * application (i.e. get number of "new events" by comparing to
129 * After a new SQ head value was read by the application this
130 * counter includes all submissions that were dropped reaching
131 * the new SQ head (and possibly more).
137 * Written by the kernel, shouldn't be modified by the
140 * The application needs a full memory barrier before checking
141 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
145 * Number of completion events lost because the queue was full;
146 * this should be avoided by the application by making sure
147 * there are not more requests pending thatn there is space in
148 * the completion queue.
150 * Written by the kernel, shouldn't be modified by the
151 * application (i.e. get number of "new events" by comparing to
154 * As completion events come in out of order this counter is not
155 * ordered with any other data.
159 * Ring buffer of completion events.
161 * The kernel writes completion events fresh every time they are
162 * produced, so the application is allowed to modify pending
165 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
168 struct io_mapped_ubuf {
171 struct bio_vec *bvec;
172 unsigned int nr_bvecs;
175 struct fixed_file_table {
181 struct percpu_ref refs;
182 } ____cacheline_aligned_in_smp;
188 bool cq_overflow_flushed;
191 * Ring buffer of indices into array of io_uring_sqe, which is
192 * mmapped by the application using the IORING_OFF_SQES offset.
194 * This indirection could e.g. be used to assign fixed
195 * io_uring_sqe entries to operations and only submit them to
196 * the queue when needed.
198 * The kernel modifies neither the indices array nor the entries
202 unsigned cached_sq_head;
205 unsigned sq_thread_idle;
206 unsigned cached_sq_dropped;
207 atomic_t cached_cq_overflow;
208 struct io_uring_sqe *sq_sqes;
210 struct list_head defer_list;
211 struct list_head timeout_list;
212 struct list_head cq_overflow_list;
214 wait_queue_head_t inflight_wait;
215 } ____cacheline_aligned_in_smp;
217 struct io_rings *rings;
221 struct task_struct *sqo_thread; /* if using sq thread polling */
222 struct mm_struct *sqo_mm;
223 wait_queue_head_t sqo_wait;
226 * If used, fixed file set. Writers must ensure that ->refs is dead,
227 * readers must ensure that ->refs is alive as long as the file* is
228 * used. Only updated through io_uring_register(2).
230 struct fixed_file_table *file_table;
231 unsigned nr_user_files;
233 /* if used, fixed mapped user buffers */
234 unsigned nr_user_bufs;
235 struct io_mapped_ubuf *user_bufs;
237 struct user_struct *user;
239 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
240 struct completion *completions;
242 /* if all else fails... */
243 struct io_kiocb *fallback_req;
245 #if defined(CONFIG_UNIX)
246 struct socket *ring_sock;
250 unsigned cached_cq_tail;
253 atomic_t cq_timeouts;
254 struct wait_queue_head cq_wait;
255 struct fasync_struct *cq_fasync;
256 struct eventfd_ctx *cq_ev_fd;
257 } ____cacheline_aligned_in_smp;
260 struct mutex uring_lock;
261 wait_queue_head_t wait;
262 } ____cacheline_aligned_in_smp;
265 spinlock_t completion_lock;
266 bool poll_multi_file;
268 * ->poll_list is protected by the ctx->uring_lock for
269 * io_uring instances that don't use IORING_SETUP_SQPOLL.
270 * For SQPOLL, only the single threaded io_sq_thread() will
271 * manipulate the list, hence no extra locking is needed there.
273 struct list_head poll_list;
274 struct rb_root cancel_tree;
276 spinlock_t inflight_lock;
277 struct list_head inflight_list;
278 } ____cacheline_aligned_in_smp;
282 const struct io_uring_sqe *sqe;
283 struct file *ring_file;
288 bool needs_fixed_file;
292 * First field must be the file pointer in all the
293 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
295 struct io_poll_iocb {
297 struct wait_queue_head *head;
301 struct wait_queue_entry wait;
306 struct hrtimer timer;
310 * NOTE! Each of the iocb union members has the file pointer
311 * as the first entry in their struct definition. So you can
312 * access the file pointer through any of the sub-structs,
313 * or directly as just 'ki_filp' in this struct.
319 struct io_poll_iocb poll;
320 struct io_timeout timeout;
323 struct sqe_submit submit;
325 struct io_ring_ctx *ctx;
327 struct list_head list;
328 struct rb_node rb_node;
330 struct list_head link_list;
333 #define REQ_F_NOWAIT 1 /* must not punt to workers */
334 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
335 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
336 #define REQ_F_SEQ_PREV 8 /* sequential with previous */
337 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
338 #define REQ_F_IO_DRAINED 32 /* drain done */
339 #define REQ_F_LINK 64 /* linked sqes */
340 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
341 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
342 #define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
343 #define REQ_F_TIMEOUT 1024 /* timeout request */
344 #define REQ_F_ISREG 2048 /* regular file */
345 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
346 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
347 #define REQ_F_INFLIGHT 16384 /* on inflight list */
348 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
353 struct list_head inflight_entry;
355 struct io_wq_work work;
358 #define IO_PLUG_THRESHOLD 2
359 #define IO_IOPOLL_BATCH 8
361 struct io_submit_state {
362 struct blk_plug plug;
365 * io_kiocb alloc cache
367 void *reqs[IO_IOPOLL_BATCH];
368 unsigned int free_reqs;
369 unsigned int cur_req;
372 * File reference cache
376 unsigned int has_refs;
377 unsigned int used_refs;
378 unsigned int ios_left;
381 static void io_wq_submit_work(struct io_wq_work **workptr);
382 static void io_cqring_fill_event(struct io_kiocb *req, long res);
383 static void __io_free_req(struct io_kiocb *req);
384 static void io_put_req(struct io_kiocb *req);
385 static void io_double_put_req(struct io_kiocb *req);
387 static struct kmem_cache *req_cachep;
389 static const struct file_operations io_uring_fops;
391 struct sock *io_uring_get_socket(struct file *file)
393 #if defined(CONFIG_UNIX)
394 if (file->f_op == &io_uring_fops) {
395 struct io_ring_ctx *ctx = file->private_data;
397 return ctx->ring_sock->sk;
402 EXPORT_SYMBOL(io_uring_get_socket);
404 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
406 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
408 complete(&ctx->completions[0]);
411 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
413 struct io_ring_ctx *ctx;
415 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
419 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
420 if (!ctx->fallback_req)
423 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
424 if (!ctx->completions)
427 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
428 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
431 ctx->flags = p->flags;
432 init_waitqueue_head(&ctx->cq_wait);
433 INIT_LIST_HEAD(&ctx->cq_overflow_list);
434 init_completion(&ctx->completions[0]);
435 init_completion(&ctx->completions[1]);
436 mutex_init(&ctx->uring_lock);
437 init_waitqueue_head(&ctx->wait);
438 spin_lock_init(&ctx->completion_lock);
439 INIT_LIST_HEAD(&ctx->poll_list);
440 ctx->cancel_tree = RB_ROOT;
441 INIT_LIST_HEAD(&ctx->defer_list);
442 INIT_LIST_HEAD(&ctx->timeout_list);
443 init_waitqueue_head(&ctx->inflight_wait);
444 spin_lock_init(&ctx->inflight_lock);
445 INIT_LIST_HEAD(&ctx->inflight_list);
448 if (ctx->fallback_req)
449 kmem_cache_free(req_cachep, ctx->fallback_req);
450 kfree(ctx->completions);
455 static inline bool __req_need_defer(struct io_kiocb *req)
457 struct io_ring_ctx *ctx = req->ctx;
459 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
460 + atomic_read(&ctx->cached_cq_overflow);
463 static inline bool req_need_defer(struct io_kiocb *req)
465 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
466 return __req_need_defer(req);
471 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
473 struct io_kiocb *req;
475 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
476 if (req && !req_need_defer(req)) {
477 list_del_init(&req->list);
484 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
486 struct io_kiocb *req;
488 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
490 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
492 if (!__req_need_defer(req)) {
493 list_del_init(&req->list);
501 static void __io_commit_cqring(struct io_ring_ctx *ctx)
503 struct io_rings *rings = ctx->rings;
505 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
506 /* order cqe stores with ring update */
507 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
509 if (wq_has_sleeper(&ctx->cq_wait)) {
510 wake_up_interruptible(&ctx->cq_wait);
511 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
516 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
518 u8 opcode = READ_ONCE(sqe->opcode);
520 return !(opcode == IORING_OP_READ_FIXED ||
521 opcode == IORING_OP_WRITE_FIXED);
524 static inline bool io_prep_async_work(struct io_kiocb *req)
526 bool do_hashed = false;
528 if (req->submit.sqe) {
529 switch (req->submit.sqe->opcode) {
530 case IORING_OP_WRITEV:
531 case IORING_OP_WRITE_FIXED:
534 case IORING_OP_READV:
535 case IORING_OP_READ_FIXED:
536 case IORING_OP_SENDMSG:
537 case IORING_OP_RECVMSG:
538 case IORING_OP_ACCEPT:
539 case IORING_OP_POLL_ADD:
541 * We know REQ_F_ISREG is not set on some of these
542 * opcodes, but this enables us to keep the check in
545 if (!(req->flags & REQ_F_ISREG))
546 req->work.flags |= IO_WQ_WORK_UNBOUND;
549 if (io_sqe_needs_user(req->submit.sqe))
550 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
556 static inline void io_queue_async_work(struct io_kiocb *req)
558 bool do_hashed = io_prep_async_work(req);
559 struct io_ring_ctx *ctx = req->ctx;
561 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
564 io_wq_enqueue(ctx->io_wq, &req->work);
566 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
567 file_inode(req->file));
571 static void io_kill_timeout(struct io_kiocb *req)
575 ret = hrtimer_try_to_cancel(&req->timeout.timer);
577 atomic_inc(&req->ctx->cq_timeouts);
578 list_del_init(&req->list);
579 io_cqring_fill_event(req, 0);
584 static void io_kill_timeouts(struct io_ring_ctx *ctx)
586 struct io_kiocb *req, *tmp;
588 spin_lock_irq(&ctx->completion_lock);
589 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
590 io_kill_timeout(req);
591 spin_unlock_irq(&ctx->completion_lock);
594 static void io_commit_cqring(struct io_ring_ctx *ctx)
596 struct io_kiocb *req;
598 while ((req = io_get_timeout_req(ctx)) != NULL)
599 io_kill_timeout(req);
601 __io_commit_cqring(ctx);
603 while ((req = io_get_deferred_req(ctx)) != NULL) {
604 if (req->flags & REQ_F_SHADOW_DRAIN) {
605 /* Just for drain, free it. */
609 req->flags |= REQ_F_IO_DRAINED;
610 io_queue_async_work(req);
614 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
616 struct io_rings *rings = ctx->rings;
619 tail = ctx->cached_cq_tail;
621 * writes to the cq entry need to come after reading head; the
622 * control dependency is enough as we're using WRITE_ONCE to
625 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
628 ctx->cached_cq_tail++;
629 return &rings->cqes[tail & ctx->cq_mask];
632 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
634 if (waitqueue_active(&ctx->wait))
636 if (waitqueue_active(&ctx->sqo_wait))
637 wake_up(&ctx->sqo_wait);
639 eventfd_signal(ctx->cq_ev_fd, 1);
642 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
644 struct io_rings *rings = ctx->rings;
645 struct io_uring_cqe *cqe;
646 struct io_kiocb *req;
651 if (list_empty_careful(&ctx->cq_overflow_list))
653 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
654 rings->cq_ring_entries))
658 spin_lock_irqsave(&ctx->completion_lock, flags);
660 /* if force is set, the ring is going away. always drop after that */
662 ctx->cq_overflow_flushed = true;
664 while (!list_empty(&ctx->cq_overflow_list)) {
665 cqe = io_get_cqring(ctx);
669 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
671 list_move(&req->list, &list);
673 WRITE_ONCE(cqe->user_data, req->user_data);
674 WRITE_ONCE(cqe->res, req->result);
675 WRITE_ONCE(cqe->flags, 0);
677 WRITE_ONCE(ctx->rings->cq_overflow,
678 atomic_inc_return(&ctx->cached_cq_overflow));
682 io_commit_cqring(ctx);
683 spin_unlock_irqrestore(&ctx->completion_lock, flags);
684 io_cqring_ev_posted(ctx);
686 while (!list_empty(&list)) {
687 req = list_first_entry(&list, struct io_kiocb, list);
688 list_del(&req->list);
693 static void io_cqring_fill_event(struct io_kiocb *req, long res)
695 struct io_ring_ctx *ctx = req->ctx;
696 struct io_uring_cqe *cqe;
698 trace_io_uring_complete(ctx, req->user_data, res);
701 * If we can't get a cq entry, userspace overflowed the
702 * submission (by quite a lot). Increment the overflow count in
705 cqe = io_get_cqring(ctx);
707 WRITE_ONCE(cqe->user_data, req->user_data);
708 WRITE_ONCE(cqe->res, res);
709 WRITE_ONCE(cqe->flags, 0);
710 } else if (ctx->cq_overflow_flushed) {
711 WRITE_ONCE(ctx->rings->cq_overflow,
712 atomic_inc_return(&ctx->cached_cq_overflow));
714 refcount_inc(&req->refs);
716 list_add_tail(&req->list, &ctx->cq_overflow_list);
720 static void io_cqring_add_event(struct io_kiocb *req, long res)
722 struct io_ring_ctx *ctx = req->ctx;
725 spin_lock_irqsave(&ctx->completion_lock, flags);
726 io_cqring_fill_event(req, res);
727 io_commit_cqring(ctx);
728 spin_unlock_irqrestore(&ctx->completion_lock, flags);
730 io_cqring_ev_posted(ctx);
733 static inline bool io_is_fallback_req(struct io_kiocb *req)
735 return req == (struct io_kiocb *)
736 ((unsigned long) req->ctx->fallback_req & ~1UL);
739 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
741 struct io_kiocb *req;
743 req = ctx->fallback_req;
744 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
750 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
751 struct io_submit_state *state)
753 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
754 struct io_kiocb *req;
756 if (!percpu_ref_tryget(&ctx->refs))
760 req = kmem_cache_alloc(req_cachep, gfp);
763 } else if (!state->free_reqs) {
767 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
768 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
771 * Bulk alloc is all-or-nothing. If we fail to get a batch,
772 * retry single alloc to be on the safe side.
774 if (unlikely(ret <= 0)) {
775 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
780 state->free_reqs = ret - 1;
782 req = state->reqs[0];
784 req = state->reqs[state->cur_req];
793 /* one is dropped after submission, the other at completion */
794 refcount_set(&req->refs, 2);
796 INIT_IO_WORK(&req->work, io_wq_submit_work);
799 req = io_get_fallback_req(ctx);
802 percpu_ref_put(&ctx->refs);
806 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
809 kmem_cache_free_bulk(req_cachep, *nr, reqs);
810 percpu_ref_put_many(&ctx->refs, *nr);
815 static void __io_free_req(struct io_kiocb *req)
817 struct io_ring_ctx *ctx = req->ctx;
819 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
821 if (req->flags & REQ_F_INFLIGHT) {
824 spin_lock_irqsave(&ctx->inflight_lock, flags);
825 list_del(&req->inflight_entry);
826 if (waitqueue_active(&ctx->inflight_wait))
827 wake_up(&ctx->inflight_wait);
828 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
830 percpu_ref_put(&ctx->refs);
831 if (likely(!io_is_fallback_req(req)))
832 kmem_cache_free(req_cachep, req);
834 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
837 static bool io_link_cancel_timeout(struct io_kiocb *req)
839 struct io_ring_ctx *ctx = req->ctx;
842 ret = hrtimer_try_to_cancel(&req->timeout.timer);
844 io_cqring_fill_event(req, -ECANCELED);
845 io_commit_cqring(ctx);
846 req->flags &= ~REQ_F_LINK;
854 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
856 struct io_ring_ctx *ctx = req->ctx;
857 struct io_kiocb *nxt;
858 bool wake_ev = false;
861 * The list should never be empty when we are called here. But could
862 * potentially happen if the chain is messed up, check to be on the
865 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
867 list_del_init(&nxt->list);
868 if (!list_empty(&req->link_list)) {
869 INIT_LIST_HEAD(&nxt->link_list);
870 list_splice(&req->link_list, &nxt->link_list);
871 nxt->flags |= REQ_F_LINK;
875 * If we're in async work, we can continue processing the chain
876 * in this context instead of having to queue up new async work.
878 if (req->flags & REQ_F_LINK_TIMEOUT) {
879 wake_ev = io_link_cancel_timeout(nxt);
881 /* we dropped this link, get next */
882 nxt = list_first_entry_or_null(&req->link_list,
883 struct io_kiocb, list);
884 } else if (nxtptr && io_wq_current_is_worker()) {
888 io_queue_async_work(nxt);
894 io_cqring_ev_posted(ctx);
898 * Called if REQ_F_LINK is set, and we fail the head request
900 static void io_fail_links(struct io_kiocb *req)
902 struct io_ring_ctx *ctx = req->ctx;
903 struct io_kiocb *link;
906 spin_lock_irqsave(&ctx->completion_lock, flags);
908 while (!list_empty(&req->link_list)) {
909 link = list_first_entry(&req->link_list, struct io_kiocb, list);
910 list_del_init(&link->list);
912 trace_io_uring_fail_link(req, link);
914 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
915 link->submit.sqe->opcode == IORING_OP_LINK_TIMEOUT) {
916 io_link_cancel_timeout(link);
918 io_cqring_fill_event(link, -ECANCELED);
919 io_double_put_req(link);
923 io_commit_cqring(ctx);
924 spin_unlock_irqrestore(&ctx->completion_lock, flags);
925 io_cqring_ev_posted(ctx);
928 static void io_free_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
930 if (likely(!(req->flags & REQ_F_LINK))) {
936 * If LINK is set, we have dependent requests in this chain. If we
937 * didn't fail this request, queue the first one up, moving any other
938 * dependencies to the next request. In case of failure, fail the rest
941 if (req->flags & REQ_F_FAIL_LINK) {
943 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
944 REQ_F_LINK_TIMEOUT) {
945 struct io_ring_ctx *ctx = req->ctx;
949 * If this is a timeout link, we could be racing with the
950 * timeout timer. Grab the completion lock for this case to
951 * protect against that.
953 spin_lock_irqsave(&ctx->completion_lock, flags);
954 io_req_link_next(req, nxt);
955 spin_unlock_irqrestore(&ctx->completion_lock, flags);
957 io_req_link_next(req, nxt);
963 static void io_free_req(struct io_kiocb *req)
965 io_free_req_find_next(req, NULL);
969 * Drop reference to request, return next in chain (if there is one) if this
970 * was the last reference to this request.
972 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
974 struct io_kiocb *nxt = NULL;
976 if (refcount_dec_and_test(&req->refs))
977 io_free_req_find_next(req, &nxt);
983 io_queue_async_work(nxt);
987 static void io_put_req(struct io_kiocb *req)
989 if (refcount_dec_and_test(&req->refs))
993 static void io_double_put_req(struct io_kiocb *req)
995 /* drop both submit and complete references */
996 if (refcount_sub_and_test(2, &req->refs))
1000 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1002 struct io_rings *rings = ctx->rings;
1005 * noflush == true is from the waitqueue handler, just ensure we wake
1006 * up the task, and the next invocation will flush the entries. We
1007 * cannot safely to it from here.
1009 if (noflush && !list_empty(&ctx->cq_overflow_list))
1012 io_cqring_overflow_flush(ctx, false);
1014 /* See comment at the top of this file */
1016 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
1019 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1021 struct io_rings *rings = ctx->rings;
1023 /* make sure SQ entry isn't read before tail */
1024 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1028 * Find and free completed poll iocbs
1030 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1031 struct list_head *done)
1033 void *reqs[IO_IOPOLL_BATCH];
1034 struct io_kiocb *req;
1038 while (!list_empty(done)) {
1039 req = list_first_entry(done, struct io_kiocb, list);
1040 list_del(&req->list);
1042 io_cqring_fill_event(req, req->result);
1045 if (refcount_dec_and_test(&req->refs)) {
1046 /* If we're not using fixed files, we have to pair the
1047 * completion part with the file put. Use regular
1048 * completions for those, only batch free for fixed
1049 * file and non-linked commands.
1051 if (((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
1052 REQ_F_FIXED_FILE) && !io_is_fallback_req(req)) {
1053 reqs[to_free++] = req;
1054 if (to_free == ARRAY_SIZE(reqs))
1055 io_free_req_many(ctx, reqs, &to_free);
1062 io_commit_cqring(ctx);
1063 io_free_req_many(ctx, reqs, &to_free);
1066 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1069 struct io_kiocb *req, *tmp;
1075 * Only spin for completions if we don't have multiple devices hanging
1076 * off our complete list, and we're under the requested amount.
1078 spin = !ctx->poll_multi_file && *nr_events < min;
1081 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1082 struct kiocb *kiocb = &req->rw;
1085 * Move completed entries to our local list. If we find a
1086 * request that requires polling, break out and complete
1087 * the done list first, if we have entries there.
1089 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1090 list_move_tail(&req->list, &done);
1093 if (!list_empty(&done))
1096 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1105 if (!list_empty(&done))
1106 io_iopoll_complete(ctx, nr_events, &done);
1112 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
1113 * non-spinning poll check - we'll still enter the driver poll loop, but only
1114 * as a non-spinning completion check.
1116 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1119 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1122 ret = io_do_iopoll(ctx, nr_events, min);
1125 if (!min || *nr_events >= min)
1133 * We can't just wait for polled events to come to us, we have to actively
1134 * find and complete them.
1136 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1138 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1141 mutex_lock(&ctx->uring_lock);
1142 while (!list_empty(&ctx->poll_list)) {
1143 unsigned int nr_events = 0;
1145 io_iopoll_getevents(ctx, &nr_events, 1);
1148 * Ensure we allow local-to-the-cpu processing to take place,
1149 * in this case we need to ensure that we reap all events.
1153 mutex_unlock(&ctx->uring_lock);
1156 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1159 int iters = 0, ret = 0;
1165 * Don't enter poll loop if we already have events pending.
1166 * If we do, we can potentially be spinning for commands that
1167 * already triggered a CQE (eg in error).
1169 if (io_cqring_events(ctx, false))
1173 * If a submit got punted to a workqueue, we can have the
1174 * application entering polling for a command before it gets
1175 * issued. That app will hold the uring_lock for the duration
1176 * of the poll right here, so we need to take a breather every
1177 * now and then to ensure that the issue has a chance to add
1178 * the poll to the issued list. Otherwise we can spin here
1179 * forever, while the workqueue is stuck trying to acquire the
1182 if (!(++iters & 7)) {
1183 mutex_unlock(&ctx->uring_lock);
1184 mutex_lock(&ctx->uring_lock);
1187 if (*nr_events < min)
1188 tmin = min - *nr_events;
1190 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1194 } while (min && !*nr_events && !need_resched());
1199 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1205 * We disallow the app entering submit/complete with polling, but we
1206 * still need to lock the ring to prevent racing with polled issue
1207 * that got punted to a workqueue.
1209 mutex_lock(&ctx->uring_lock);
1210 ret = __io_iopoll_check(ctx, nr_events, min);
1211 mutex_unlock(&ctx->uring_lock);
1215 static void kiocb_end_write(struct io_kiocb *req)
1218 * Tell lockdep we inherited freeze protection from submission
1221 if (req->flags & REQ_F_ISREG) {
1222 struct inode *inode = file_inode(req->file);
1224 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1226 file_end_write(req->file);
1229 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1231 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1233 if (kiocb->ki_flags & IOCB_WRITE)
1234 kiocb_end_write(req);
1236 if ((req->flags & REQ_F_LINK) && res != req->result)
1237 req->flags |= REQ_F_FAIL_LINK;
1238 io_cqring_add_event(req, res);
1241 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1243 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1245 io_complete_rw_common(kiocb, res);
1249 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1251 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1252 struct io_kiocb *nxt = NULL;
1254 io_complete_rw_common(kiocb, res);
1255 io_put_req_find_next(req, &nxt);
1260 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1262 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1264 if (kiocb->ki_flags & IOCB_WRITE)
1265 kiocb_end_write(req);
1267 if ((req->flags & REQ_F_LINK) && res != req->result)
1268 req->flags |= REQ_F_FAIL_LINK;
1271 req->flags |= REQ_F_IOPOLL_COMPLETED;
1275 * After the iocb has been issued, it's safe to be found on the poll list.
1276 * Adding the kiocb to the list AFTER submission ensures that we don't
1277 * find it from a io_iopoll_getevents() thread before the issuer is done
1278 * accessing the kiocb cookie.
1280 static void io_iopoll_req_issued(struct io_kiocb *req)
1282 struct io_ring_ctx *ctx = req->ctx;
1285 * Track whether we have multiple files in our lists. This will impact
1286 * how we do polling eventually, not spinning if we're on potentially
1287 * different devices.
1289 if (list_empty(&ctx->poll_list)) {
1290 ctx->poll_multi_file = false;
1291 } else if (!ctx->poll_multi_file) {
1292 struct io_kiocb *list_req;
1294 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1296 if (list_req->rw.ki_filp != req->rw.ki_filp)
1297 ctx->poll_multi_file = true;
1301 * For fast devices, IO may have already completed. If it has, add
1302 * it to the front so we find it first.
1304 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1305 list_add(&req->list, &ctx->poll_list);
1307 list_add_tail(&req->list, &ctx->poll_list);
1310 static void io_file_put(struct io_submit_state *state)
1313 int diff = state->has_refs - state->used_refs;
1316 fput_many(state->file, diff);
1322 * Get as many references to a file as we have IOs left in this submission,
1323 * assuming most submissions are for one file, or at least that each file
1324 * has more than one submission.
1326 static struct file *io_file_get(struct io_submit_state *state, int fd)
1332 if (state->fd == fd) {
1339 state->file = fget_many(fd, state->ios_left);
1344 state->has_refs = state->ios_left;
1345 state->used_refs = 1;
1351 * If we tracked the file through the SCM inflight mechanism, we could support
1352 * any file. For now, just ensure that anything potentially problematic is done
1355 static bool io_file_supports_async(struct file *file)
1357 umode_t mode = file_inode(file)->i_mode;
1359 if (S_ISBLK(mode) || S_ISCHR(mode))
1361 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1367 static int io_prep_rw(struct io_kiocb *req, bool force_nonblock)
1369 const struct io_uring_sqe *sqe = req->submit.sqe;
1370 struct io_ring_ctx *ctx = req->ctx;
1371 struct kiocb *kiocb = &req->rw;
1378 if (S_ISREG(file_inode(req->file)->i_mode))
1379 req->flags |= REQ_F_ISREG;
1382 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1383 * we know to async punt it even if it was opened O_NONBLOCK
1385 if (force_nonblock && !io_file_supports_async(req->file)) {
1386 req->flags |= REQ_F_MUST_PUNT;
1390 kiocb->ki_pos = READ_ONCE(sqe->off);
1391 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1392 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1394 ioprio = READ_ONCE(sqe->ioprio);
1396 ret = ioprio_check_cap(ioprio);
1400 kiocb->ki_ioprio = ioprio;
1402 kiocb->ki_ioprio = get_current_ioprio();
1404 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1408 /* don't allow async punt if RWF_NOWAIT was requested */
1409 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1410 (req->file->f_flags & O_NONBLOCK))
1411 req->flags |= REQ_F_NOWAIT;
1414 kiocb->ki_flags |= IOCB_NOWAIT;
1416 if (ctx->flags & IORING_SETUP_IOPOLL) {
1417 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1418 !kiocb->ki_filp->f_op->iopoll)
1421 kiocb->ki_flags |= IOCB_HIPRI;
1422 kiocb->ki_complete = io_complete_rw_iopoll;
1425 if (kiocb->ki_flags & IOCB_HIPRI)
1427 kiocb->ki_complete = io_complete_rw;
1432 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1438 case -ERESTARTNOINTR:
1439 case -ERESTARTNOHAND:
1440 case -ERESTART_RESTARTBLOCK:
1442 * We can't just restart the syscall, since previously
1443 * submitted sqes may already be in progress. Just fail this
1449 kiocb->ki_complete(kiocb, ret, 0);
1453 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1456 if (in_async && ret >= 0 && nxt && kiocb->ki_complete == io_complete_rw)
1457 *nxt = __io_complete_rw(kiocb, ret);
1459 io_rw_done(kiocb, ret);
1462 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1463 const struct io_uring_sqe *sqe,
1464 struct iov_iter *iter)
1466 size_t len = READ_ONCE(sqe->len);
1467 struct io_mapped_ubuf *imu;
1468 unsigned index, buf_index;
1472 /* attempt to use fixed buffers without having provided iovecs */
1473 if (unlikely(!ctx->user_bufs))
1476 buf_index = READ_ONCE(sqe->buf_index);
1477 if (unlikely(buf_index >= ctx->nr_user_bufs))
1480 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1481 imu = &ctx->user_bufs[index];
1482 buf_addr = READ_ONCE(sqe->addr);
1485 if (buf_addr + len < buf_addr)
1487 /* not inside the mapped region */
1488 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1492 * May not be a start of buffer, set size appropriately
1493 * and advance us to the beginning.
1495 offset = buf_addr - imu->ubuf;
1496 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1500 * Don't use iov_iter_advance() here, as it's really slow for
1501 * using the latter parts of a big fixed buffer - it iterates
1502 * over each segment manually. We can cheat a bit here, because
1505 * 1) it's a BVEC iter, we set it up
1506 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1507 * first and last bvec
1509 * So just find our index, and adjust the iterator afterwards.
1510 * If the offset is within the first bvec (or the whole first
1511 * bvec, just use iov_iter_advance(). This makes it easier
1512 * since we can just skip the first segment, which may not
1513 * be PAGE_SIZE aligned.
1515 const struct bio_vec *bvec = imu->bvec;
1517 if (offset <= bvec->bv_len) {
1518 iov_iter_advance(iter, offset);
1520 unsigned long seg_skip;
1522 /* skip first vec */
1523 offset -= bvec->bv_len;
1524 seg_skip = 1 + (offset >> PAGE_SHIFT);
1526 iter->bvec = bvec + seg_skip;
1527 iter->nr_segs -= seg_skip;
1528 iter->count -= bvec->bv_len + offset;
1529 iter->iov_offset = offset & ~PAGE_MASK;
1536 static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1537 const struct sqe_submit *s, struct iovec **iovec,
1538 struct iov_iter *iter)
1540 const struct io_uring_sqe *sqe = s->sqe;
1541 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1542 size_t sqe_len = READ_ONCE(sqe->len);
1546 * We're reading ->opcode for the second time, but the first read
1547 * doesn't care whether it's _FIXED or not, so it doesn't matter
1548 * whether ->opcode changes concurrently. The first read does care
1549 * about whether it is a READ or a WRITE, so we don't trust this read
1550 * for that purpose and instead let the caller pass in the read/write
1553 opcode = READ_ONCE(sqe->opcode);
1554 if (opcode == IORING_OP_READ_FIXED ||
1555 opcode == IORING_OP_WRITE_FIXED) {
1556 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
1564 #ifdef CONFIG_COMPAT
1566 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1570 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1574 * For files that don't have ->read_iter() and ->write_iter(), handle them
1575 * by looping over ->read() or ->write() manually.
1577 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1578 struct iov_iter *iter)
1583 * Don't support polled IO through this interface, and we can't
1584 * support non-blocking either. For the latter, this just causes
1585 * the kiocb to be handled from an async context.
1587 if (kiocb->ki_flags & IOCB_HIPRI)
1589 if (kiocb->ki_flags & IOCB_NOWAIT)
1592 while (iov_iter_count(iter)) {
1593 struct iovec iovec = iov_iter_iovec(iter);
1597 nr = file->f_op->read(file, iovec.iov_base,
1598 iovec.iov_len, &kiocb->ki_pos);
1600 nr = file->f_op->write(file, iovec.iov_base,
1601 iovec.iov_len, &kiocb->ki_pos);
1610 if (nr != iovec.iov_len)
1612 iov_iter_advance(iter, nr);
1618 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1619 bool force_nonblock)
1621 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1622 struct kiocb *kiocb = &req->rw;
1623 struct iov_iter iter;
1626 ssize_t read_size, ret;
1628 ret = io_prep_rw(req, force_nonblock);
1631 file = kiocb->ki_filp;
1633 if (unlikely(!(file->f_mode & FMODE_READ)))
1636 ret = io_import_iovec(req->ctx, READ, &req->submit, &iovec, &iter);
1641 if (req->flags & REQ_F_LINK)
1642 req->result = read_size;
1644 iov_count = iov_iter_count(&iter);
1645 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1649 if (file->f_op->read_iter)
1650 ret2 = call_read_iter(file, kiocb, &iter);
1652 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1655 * In case of a short read, punt to async. This can happen
1656 * if we have data partially cached. Alternatively we can
1657 * return the short read, in which case the application will
1658 * need to issue another SQE and wait for it. That SQE will
1659 * need async punt anyway, so it's more efficient to do it
1662 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1663 (req->flags & REQ_F_ISREG) &&
1664 ret2 > 0 && ret2 < read_size)
1666 /* Catch -EAGAIN return for forced non-blocking submission */
1667 if (!force_nonblock || ret2 != -EAGAIN)
1668 kiocb_done(kiocb, ret2, nxt, req->submit.in_async);
1676 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1677 bool force_nonblock)
1679 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1680 struct kiocb *kiocb = &req->rw;
1681 struct iov_iter iter;
1686 ret = io_prep_rw(req, force_nonblock);
1690 file = kiocb->ki_filp;
1691 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1694 ret = io_import_iovec(req->ctx, WRITE, &req->submit, &iovec, &iter);
1698 if (req->flags & REQ_F_LINK)
1701 iov_count = iov_iter_count(&iter);
1704 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
1707 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1712 * Open-code file_start_write here to grab freeze protection,
1713 * which will be released by another thread in
1714 * io_complete_rw(). Fool lockdep by telling it the lock got
1715 * released so that it doesn't complain about the held lock when
1716 * we return to userspace.
1718 if (req->flags & REQ_F_ISREG) {
1719 __sb_start_write(file_inode(file)->i_sb,
1720 SB_FREEZE_WRITE, true);
1721 __sb_writers_release(file_inode(file)->i_sb,
1724 kiocb->ki_flags |= IOCB_WRITE;
1726 if (file->f_op->write_iter)
1727 ret2 = call_write_iter(file, kiocb, &iter);
1729 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1730 if (!force_nonblock || ret2 != -EAGAIN)
1731 kiocb_done(kiocb, ret2, nxt, req->submit.in_async);
1741 * IORING_OP_NOP just posts a completion event, nothing else.
1743 static int io_nop(struct io_kiocb *req)
1745 struct io_ring_ctx *ctx = req->ctx;
1747 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1750 io_cqring_add_event(req, 0);
1755 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1757 struct io_ring_ctx *ctx = req->ctx;
1762 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1764 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1770 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1771 struct io_kiocb **nxt, bool force_nonblock)
1773 loff_t sqe_off = READ_ONCE(sqe->off);
1774 loff_t sqe_len = READ_ONCE(sqe->len);
1775 loff_t end = sqe_off + sqe_len;
1776 unsigned fsync_flags;
1779 fsync_flags = READ_ONCE(sqe->fsync_flags);
1780 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1783 ret = io_prep_fsync(req, sqe);
1787 /* fsync always requires a blocking context */
1791 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1792 end > 0 ? end : LLONG_MAX,
1793 fsync_flags & IORING_FSYNC_DATASYNC);
1795 if (ret < 0 && (req->flags & REQ_F_LINK))
1796 req->flags |= REQ_F_FAIL_LINK;
1797 io_cqring_add_event(req, ret);
1798 io_put_req_find_next(req, nxt);
1802 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1804 struct io_ring_ctx *ctx = req->ctx;
1810 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1812 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1818 static int io_sync_file_range(struct io_kiocb *req,
1819 const struct io_uring_sqe *sqe,
1820 struct io_kiocb **nxt,
1821 bool force_nonblock)
1828 ret = io_prep_sfr(req, sqe);
1832 /* sync_file_range always requires a blocking context */
1836 sqe_off = READ_ONCE(sqe->off);
1837 sqe_len = READ_ONCE(sqe->len);
1838 flags = READ_ONCE(sqe->sync_range_flags);
1840 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1842 if (ret < 0 && (req->flags & REQ_F_LINK))
1843 req->flags |= REQ_F_FAIL_LINK;
1844 io_cqring_add_event(req, ret);
1845 io_put_req_find_next(req, nxt);
1849 #if defined(CONFIG_NET)
1850 static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1851 struct io_kiocb **nxt, bool force_nonblock,
1852 long (*fn)(struct socket *, struct user_msghdr __user *,
1855 struct socket *sock;
1858 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1861 sock = sock_from_file(req->file, &ret);
1863 struct user_msghdr __user *msg;
1866 flags = READ_ONCE(sqe->msg_flags);
1867 if (flags & MSG_DONTWAIT)
1868 req->flags |= REQ_F_NOWAIT;
1869 else if (force_nonblock)
1870 flags |= MSG_DONTWAIT;
1872 msg = (struct user_msghdr __user *) (unsigned long)
1873 READ_ONCE(sqe->addr);
1875 ret = fn(sock, msg, flags);
1876 if (force_nonblock && ret == -EAGAIN)
1880 io_cqring_add_event(req, ret);
1881 if (ret < 0 && (req->flags & REQ_F_LINK))
1882 req->flags |= REQ_F_FAIL_LINK;
1883 io_put_req_find_next(req, nxt);
1888 static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1889 struct io_kiocb **nxt, bool force_nonblock)
1891 #if defined(CONFIG_NET)
1892 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1893 __sys_sendmsg_sock);
1899 static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1900 struct io_kiocb **nxt, bool force_nonblock)
1902 #if defined(CONFIG_NET)
1903 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1904 __sys_recvmsg_sock);
1910 static int io_accept(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1911 struct io_kiocb **nxt, bool force_nonblock)
1913 #if defined(CONFIG_NET)
1914 struct sockaddr __user *addr;
1915 int __user *addr_len;
1916 unsigned file_flags;
1919 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
1921 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1924 addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
1925 addr_len = (int __user *) (unsigned long) READ_ONCE(sqe->addr2);
1926 flags = READ_ONCE(sqe->accept_flags);
1927 file_flags = force_nonblock ? O_NONBLOCK : 0;
1929 ret = __sys_accept4_file(req->file, file_flags, addr, addr_len, flags);
1930 if (ret == -EAGAIN && force_nonblock) {
1931 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
1934 if (ret == -ERESTARTSYS)
1936 if (ret < 0 && (req->flags & REQ_F_LINK))
1937 req->flags |= REQ_F_FAIL_LINK;
1938 io_cqring_add_event(req, ret);
1939 io_put_req_find_next(req, nxt);
1946 static inline void io_poll_remove_req(struct io_kiocb *req)
1948 if (!RB_EMPTY_NODE(&req->rb_node)) {
1949 rb_erase(&req->rb_node, &req->ctx->cancel_tree);
1950 RB_CLEAR_NODE(&req->rb_node);
1954 static void io_poll_remove_one(struct io_kiocb *req)
1956 struct io_poll_iocb *poll = &req->poll;
1958 spin_lock(&poll->head->lock);
1959 WRITE_ONCE(poll->canceled, true);
1960 if (!list_empty(&poll->wait.entry)) {
1961 list_del_init(&poll->wait.entry);
1962 io_queue_async_work(req);
1964 spin_unlock(&poll->head->lock);
1965 io_poll_remove_req(req);
1968 static void io_poll_remove_all(struct io_ring_ctx *ctx)
1970 struct rb_node *node;
1971 struct io_kiocb *req;
1973 spin_lock_irq(&ctx->completion_lock);
1974 while ((node = rb_first(&ctx->cancel_tree)) != NULL) {
1975 req = rb_entry(node, struct io_kiocb, rb_node);
1976 io_poll_remove_one(req);
1978 spin_unlock_irq(&ctx->completion_lock);
1981 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
1983 struct rb_node *p, *parent = NULL;
1984 struct io_kiocb *req;
1986 p = ctx->cancel_tree.rb_node;
1989 req = rb_entry(parent, struct io_kiocb, rb_node);
1990 if (sqe_addr < req->user_data) {
1992 } else if (sqe_addr > req->user_data) {
1995 io_poll_remove_one(req);
2004 * Find a running poll command that matches one specified in sqe->addr,
2005 * and remove it if found.
2007 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2009 struct io_ring_ctx *ctx = req->ctx;
2012 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2014 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
2018 spin_lock_irq(&ctx->completion_lock);
2019 ret = io_poll_cancel(ctx, READ_ONCE(sqe->addr));
2020 spin_unlock_irq(&ctx->completion_lock);
2022 io_cqring_add_event(req, ret);
2023 if (ret < 0 && (req->flags & REQ_F_LINK))
2024 req->flags |= REQ_F_FAIL_LINK;
2029 static void io_poll_complete(struct io_kiocb *req, __poll_t mask)
2031 struct io_ring_ctx *ctx = req->ctx;
2033 req->poll.done = true;
2034 io_cqring_fill_event(req, mangle_poll(mask));
2035 io_commit_cqring(ctx);
2038 static void io_poll_complete_work(struct io_wq_work **workptr)
2040 struct io_wq_work *work = *workptr;
2041 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2042 struct io_poll_iocb *poll = &req->poll;
2043 struct poll_table_struct pt = { ._key = poll->events };
2044 struct io_ring_ctx *ctx = req->ctx;
2045 struct io_kiocb *nxt = NULL;
2048 if (work->flags & IO_WQ_WORK_CANCEL)
2049 WRITE_ONCE(poll->canceled, true);
2051 if (!READ_ONCE(poll->canceled))
2052 mask = vfs_poll(poll->file, &pt) & poll->events;
2055 * Note that ->ki_cancel callers also delete iocb from active_reqs after
2056 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
2057 * synchronize with them. In the cancellation case the list_del_init
2058 * itself is not actually needed, but harmless so we keep it in to
2059 * avoid further branches in the fast path.
2061 spin_lock_irq(&ctx->completion_lock);
2062 if (!mask && !READ_ONCE(poll->canceled)) {
2063 add_wait_queue(poll->head, &poll->wait);
2064 spin_unlock_irq(&ctx->completion_lock);
2067 io_poll_remove_req(req);
2068 io_poll_complete(req, mask);
2069 spin_unlock_irq(&ctx->completion_lock);
2071 io_cqring_ev_posted(ctx);
2073 io_put_req_find_next(req, &nxt);
2075 *workptr = &nxt->work;
2078 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2081 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
2083 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2084 struct io_ring_ctx *ctx = req->ctx;
2085 __poll_t mask = key_to_poll(key);
2086 unsigned long flags;
2088 /* for instances that support it check for an event match first: */
2089 if (mask && !(mask & poll->events))
2092 list_del_init(&poll->wait.entry);
2095 * Run completion inline if we can. We're using trylock here because
2096 * we are violating the completion_lock -> poll wq lock ordering.
2097 * If we have a link timeout we're going to need the completion_lock
2098 * for finalizing the request, mark us as having grabbed that already.
2100 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2101 io_poll_remove_req(req);
2102 io_poll_complete(req, mask);
2103 req->flags |= REQ_F_COMP_LOCKED;
2105 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2107 io_cqring_ev_posted(ctx);
2109 io_queue_async_work(req);
2115 struct io_poll_table {
2116 struct poll_table_struct pt;
2117 struct io_kiocb *req;
2121 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2122 struct poll_table_struct *p)
2124 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2126 if (unlikely(pt->req->poll.head)) {
2127 pt->error = -EINVAL;
2132 pt->req->poll.head = head;
2133 add_wait_queue(head, &pt->req->poll.wait);
2136 static void io_poll_req_insert(struct io_kiocb *req)
2138 struct io_ring_ctx *ctx = req->ctx;
2139 struct rb_node **p = &ctx->cancel_tree.rb_node;
2140 struct rb_node *parent = NULL;
2141 struct io_kiocb *tmp;
2145 tmp = rb_entry(parent, struct io_kiocb, rb_node);
2146 if (req->user_data < tmp->user_data)
2149 p = &(*p)->rb_right;
2151 rb_link_node(&req->rb_node, parent, p);
2152 rb_insert_color(&req->rb_node, &ctx->cancel_tree);
2155 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2156 struct io_kiocb **nxt)
2158 struct io_poll_iocb *poll = &req->poll;
2159 struct io_ring_ctx *ctx = req->ctx;
2160 struct io_poll_table ipt;
2161 bool cancel = false;
2165 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2167 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2172 req->submit.sqe = NULL;
2173 INIT_IO_WORK(&req->work, io_poll_complete_work);
2174 events = READ_ONCE(sqe->poll_events);
2175 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2176 RB_CLEAR_NODE(&req->rb_node);
2180 poll->canceled = false;
2182 ipt.pt._qproc = io_poll_queue_proc;
2183 ipt.pt._key = poll->events;
2185 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2187 /* initialized the list so that we can do list_empty checks */
2188 INIT_LIST_HEAD(&poll->wait.entry);
2189 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
2191 INIT_LIST_HEAD(&req->list);
2193 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
2195 spin_lock_irq(&ctx->completion_lock);
2196 if (likely(poll->head)) {
2197 spin_lock(&poll->head->lock);
2198 if (unlikely(list_empty(&poll->wait.entry))) {
2204 if (mask || ipt.error)
2205 list_del_init(&poll->wait.entry);
2207 WRITE_ONCE(poll->canceled, true);
2208 else if (!poll->done) /* actually waiting for an event */
2209 io_poll_req_insert(req);
2210 spin_unlock(&poll->head->lock);
2212 if (mask) { /* no async, we'd stolen it */
2214 io_poll_complete(req, mask);
2216 spin_unlock_irq(&ctx->completion_lock);
2219 io_cqring_ev_posted(ctx);
2220 io_put_req_find_next(req, nxt);
2225 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
2227 struct io_ring_ctx *ctx;
2228 struct io_kiocb *req;
2229 unsigned long flags;
2231 req = container_of(timer, struct io_kiocb, timeout.timer);
2233 atomic_inc(&ctx->cq_timeouts);
2235 spin_lock_irqsave(&ctx->completion_lock, flags);
2237 * We could be racing with timeout deletion. If the list is empty,
2238 * then timeout lookup already found it and will be handling it.
2240 if (!list_empty(&req->list)) {
2241 struct io_kiocb *prev;
2244 * Adjust the reqs sequence before the current one because it
2245 * will consume a slot in the cq_ring and the the cq_tail
2246 * pointer will be increased, otherwise other timeout reqs may
2247 * return in advance without waiting for enough wait_nr.
2250 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
2252 list_del_init(&req->list);
2255 io_cqring_fill_event(req, -ETIME);
2256 io_commit_cqring(ctx);
2257 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2259 io_cqring_ev_posted(ctx);
2260 if (req->flags & REQ_F_LINK)
2261 req->flags |= REQ_F_FAIL_LINK;
2263 return HRTIMER_NORESTART;
2266 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
2268 struct io_kiocb *req;
2271 list_for_each_entry(req, &ctx->timeout_list, list) {
2272 if (user_data == req->user_data) {
2273 list_del_init(&req->list);
2282 ret = hrtimer_try_to_cancel(&req->timeout.timer);
2286 io_cqring_fill_event(req, -ECANCELED);
2292 * Remove or update an existing timeout command
2294 static int io_timeout_remove(struct io_kiocb *req,
2295 const struct io_uring_sqe *sqe)
2297 struct io_ring_ctx *ctx = req->ctx;
2301 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2303 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2305 flags = READ_ONCE(sqe->timeout_flags);
2309 spin_lock_irq(&ctx->completion_lock);
2310 ret = io_timeout_cancel(ctx, READ_ONCE(sqe->addr));
2312 io_cqring_fill_event(req, ret);
2313 io_commit_cqring(ctx);
2314 spin_unlock_irq(&ctx->completion_lock);
2315 io_cqring_ev_posted(ctx);
2316 if (ret < 0 && req->flags & REQ_F_LINK)
2317 req->flags |= REQ_F_FAIL_LINK;
2322 static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2325 struct io_ring_ctx *ctx = req->ctx;
2326 struct list_head *entry;
2327 enum hrtimer_mode mode;
2328 struct timespec64 ts;
2332 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2334 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len != 1)
2336 flags = READ_ONCE(sqe->timeout_flags);
2337 if (flags & ~IORING_TIMEOUT_ABS)
2340 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
2343 if (flags & IORING_TIMEOUT_ABS)
2344 mode = HRTIMER_MODE_ABS;
2346 mode = HRTIMER_MODE_REL;
2348 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, mode);
2349 req->flags |= REQ_F_TIMEOUT;
2352 * sqe->off holds how many events that need to occur for this
2353 * timeout event to be satisfied. If it isn't set, then this is
2354 * a pure timeout request, sequence isn't used.
2356 count = READ_ONCE(sqe->off);
2358 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2359 spin_lock_irq(&ctx->completion_lock);
2360 entry = ctx->timeout_list.prev;
2364 req->sequence = ctx->cached_sq_head + count - 1;
2365 /* reuse it to store the count */
2366 req->submit.sequence = count;
2369 * Insertion sort, ensuring the first entry in the list is always
2370 * the one we need first.
2372 spin_lock_irq(&ctx->completion_lock);
2373 list_for_each_prev(entry, &ctx->timeout_list) {
2374 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2375 unsigned nxt_sq_head;
2376 long long tmp, tmp_nxt;
2378 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2382 * Since cached_sq_head + count - 1 can overflow, use type long
2385 tmp = (long long)ctx->cached_sq_head + count - 1;
2386 nxt_sq_head = nxt->sequence - nxt->submit.sequence + 1;
2387 tmp_nxt = (long long)nxt_sq_head + nxt->submit.sequence - 1;
2390 * cached_sq_head may overflow, and it will never overflow twice
2391 * once there is some timeout req still be valid.
2393 if (ctx->cached_sq_head < nxt_sq_head)
2400 * Sequence of reqs after the insert one and itself should
2401 * be adjusted because each timeout req consumes a slot.
2406 req->sequence -= span;
2408 list_add(&req->list, entry);
2409 req->timeout.timer.function = io_timeout_fn;
2410 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts), mode);
2411 spin_unlock_irq(&ctx->completion_lock);
2415 static bool io_cancel_cb(struct io_wq_work *work, void *data)
2417 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2419 return req->user_data == (unsigned long) data;
2422 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
2424 enum io_wq_cancel cancel_ret;
2427 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
2428 switch (cancel_ret) {
2429 case IO_WQ_CANCEL_OK:
2432 case IO_WQ_CANCEL_RUNNING:
2435 case IO_WQ_CANCEL_NOTFOUND:
2443 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
2444 struct io_kiocb *req, __u64 sqe_addr,
2445 struct io_kiocb **nxt)
2447 unsigned long flags;
2450 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
2451 if (ret != -ENOENT) {
2452 spin_lock_irqsave(&ctx->completion_lock, flags);
2456 spin_lock_irqsave(&ctx->completion_lock, flags);
2457 ret = io_timeout_cancel(ctx, sqe_addr);
2460 ret = io_poll_cancel(ctx, sqe_addr);
2462 io_cqring_fill_event(req, ret);
2463 io_commit_cqring(ctx);
2464 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2465 io_cqring_ev_posted(ctx);
2467 if (ret < 0 && (req->flags & REQ_F_LINK))
2468 req->flags |= REQ_F_FAIL_LINK;
2469 io_put_req_find_next(req, nxt);
2472 static int io_async_cancel(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2473 struct io_kiocb **nxt)
2475 struct io_ring_ctx *ctx = req->ctx;
2477 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2479 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
2483 io_async_find_and_cancel(ctx, req, READ_ONCE(sqe->addr), NULL);
2487 static int io_req_defer(struct io_kiocb *req)
2489 const struct io_uring_sqe *sqe = req->submit.sqe;
2490 struct io_uring_sqe *sqe_copy;
2491 struct io_ring_ctx *ctx = req->ctx;
2493 /* Still need defer if there is pending req in defer list. */
2494 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
2497 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2501 spin_lock_irq(&ctx->completion_lock);
2502 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
2503 spin_unlock_irq(&ctx->completion_lock);
2508 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
2509 req->submit.sqe = sqe_copy;
2511 trace_io_uring_defer(ctx, req, false);
2512 list_add_tail(&req->list, &ctx->defer_list);
2513 spin_unlock_irq(&ctx->completion_lock);
2514 return -EIOCBQUEUED;
2517 static int __io_submit_sqe(struct io_kiocb *req, struct io_kiocb **nxt,
2518 bool force_nonblock)
2521 struct sqe_submit *s = &req->submit;
2522 struct io_ring_ctx *ctx = req->ctx;
2524 opcode = READ_ONCE(s->sqe->opcode);
2529 case IORING_OP_READV:
2530 if (unlikely(s->sqe->buf_index))
2532 ret = io_read(req, nxt, force_nonblock);
2534 case IORING_OP_WRITEV:
2535 if (unlikely(s->sqe->buf_index))
2537 ret = io_write(req, nxt, force_nonblock);
2539 case IORING_OP_READ_FIXED:
2540 ret = io_read(req, nxt, force_nonblock);
2542 case IORING_OP_WRITE_FIXED:
2543 ret = io_write(req, nxt, force_nonblock);
2545 case IORING_OP_FSYNC:
2546 ret = io_fsync(req, s->sqe, nxt, force_nonblock);
2548 case IORING_OP_POLL_ADD:
2549 ret = io_poll_add(req, s->sqe, nxt);
2551 case IORING_OP_POLL_REMOVE:
2552 ret = io_poll_remove(req, s->sqe);
2554 case IORING_OP_SYNC_FILE_RANGE:
2555 ret = io_sync_file_range(req, s->sqe, nxt, force_nonblock);
2557 case IORING_OP_SENDMSG:
2558 ret = io_sendmsg(req, s->sqe, nxt, force_nonblock);
2560 case IORING_OP_RECVMSG:
2561 ret = io_recvmsg(req, s->sqe, nxt, force_nonblock);
2563 case IORING_OP_TIMEOUT:
2564 ret = io_timeout(req, s->sqe);
2566 case IORING_OP_TIMEOUT_REMOVE:
2567 ret = io_timeout_remove(req, s->sqe);
2569 case IORING_OP_ACCEPT:
2570 ret = io_accept(req, s->sqe, nxt, force_nonblock);
2572 case IORING_OP_ASYNC_CANCEL:
2573 ret = io_async_cancel(req, s->sqe, nxt);
2583 if (ctx->flags & IORING_SETUP_IOPOLL) {
2584 if (req->result == -EAGAIN)
2587 /* workqueue context doesn't hold uring_lock, grab it now */
2589 mutex_lock(&ctx->uring_lock);
2590 io_iopoll_req_issued(req);
2592 mutex_unlock(&ctx->uring_lock);
2598 static void io_wq_submit_work(struct io_wq_work **workptr)
2600 struct io_wq_work *work = *workptr;
2601 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2602 struct sqe_submit *s = &req->submit;
2603 const struct io_uring_sqe *sqe = s->sqe;
2604 struct io_kiocb *nxt = NULL;
2607 /* Ensure we clear previously set non-block flag */
2608 req->rw.ki_flags &= ~IOCB_NOWAIT;
2610 if (work->flags & IO_WQ_WORK_CANCEL)
2614 s->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
2617 ret = __io_submit_sqe(req, &nxt, false);
2619 * We can get EAGAIN for polled IO even though we're
2620 * forcing a sync submission from here, since we can't
2621 * wait for request slots on the block side.
2629 /* drop submission reference */
2633 if (req->flags & REQ_F_LINK)
2634 req->flags |= REQ_F_FAIL_LINK;
2635 io_cqring_add_event(req, ret);
2639 /* async context always use a copy of the sqe */
2642 /* if a dependent link is ready, pass it back */
2644 io_prep_async_work(nxt);
2645 *workptr = &nxt->work;
2649 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2651 int op = READ_ONCE(sqe->opcode);
2655 case IORING_OP_POLL_REMOVE:
2656 case IORING_OP_TIMEOUT:
2657 case IORING_OP_TIMEOUT_REMOVE:
2658 case IORING_OP_ASYNC_CANCEL:
2659 case IORING_OP_LINK_TIMEOUT:
2666 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
2669 struct fixed_file_table *table;
2671 table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
2672 return table->files[index & IORING_FILE_TABLE_MASK];
2675 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req)
2677 struct sqe_submit *s = &req->submit;
2678 struct io_ring_ctx *ctx = req->ctx;
2682 flags = READ_ONCE(s->sqe->flags);
2683 fd = READ_ONCE(s->sqe->fd);
2685 if (flags & IOSQE_IO_DRAIN)
2686 req->flags |= REQ_F_IO_DRAIN;
2688 * All io need record the previous position, if LINK vs DARIN,
2689 * it can be used to mark the position of the first IO in the
2692 req->sequence = s->sequence;
2694 if (!io_op_needs_file(s->sqe))
2697 if (flags & IOSQE_FIXED_FILE) {
2698 if (unlikely(!ctx->file_table ||
2699 (unsigned) fd >= ctx->nr_user_files))
2701 fd = array_index_nospec(fd, ctx->nr_user_files);
2702 req->file = io_file_from_index(ctx, fd);
2705 req->flags |= REQ_F_FIXED_FILE;
2707 if (s->needs_fixed_file)
2709 trace_io_uring_file_get(ctx, fd);
2710 req->file = io_file_get(state, fd);
2711 if (unlikely(!req->file))
2718 static int io_grab_files(struct io_kiocb *req)
2721 struct io_ring_ctx *ctx = req->ctx;
2724 spin_lock_irq(&ctx->inflight_lock);
2726 * We use the f_ops->flush() handler to ensure that we can flush
2727 * out work accessing these files if the fd is closed. Check if
2728 * the fd has changed since we started down this path, and disallow
2729 * this operation if it has.
2731 if (fcheck(req->submit.ring_fd) == req->submit.ring_file) {
2732 list_add(&req->inflight_entry, &ctx->inflight_list);
2733 req->flags |= REQ_F_INFLIGHT;
2734 req->work.files = current->files;
2737 spin_unlock_irq(&ctx->inflight_lock);
2743 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2745 struct io_kiocb *req = container_of(timer, struct io_kiocb,
2747 struct io_ring_ctx *ctx = req->ctx;
2748 struct io_kiocb *prev = NULL;
2749 unsigned long flags;
2751 spin_lock_irqsave(&ctx->completion_lock, flags);
2754 * We don't expect the list to be empty, that will only happen if we
2755 * race with the completion of the linked work.
2757 if (!list_empty(&req->list)) {
2758 prev = list_entry(req->list.prev, struct io_kiocb, link_list);
2759 if (refcount_inc_not_zero(&prev->refs))
2760 list_del_init(&req->list);
2765 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2768 io_async_find_and_cancel(ctx, req, prev->user_data, NULL);
2771 io_cqring_add_event(req, -ETIME);
2774 return HRTIMER_NORESTART;
2777 static void io_queue_linked_timeout(struct io_kiocb *req, struct timespec64 *ts,
2778 enum hrtimer_mode *mode)
2780 struct io_ring_ctx *ctx = req->ctx;
2783 * If the list is now empty, then our linked request finished before
2784 * we got a chance to setup the timer
2786 spin_lock_irq(&ctx->completion_lock);
2787 if (!list_empty(&req->list)) {
2788 req->timeout.timer.function = io_link_timeout_fn;
2789 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(*ts),
2792 spin_unlock_irq(&ctx->completion_lock);
2794 /* drop submission reference */
2798 static int io_validate_link_timeout(const struct io_uring_sqe *sqe,
2799 struct timespec64 *ts)
2801 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 || sqe->off)
2803 if (sqe->timeout_flags & ~IORING_TIMEOUT_ABS)
2805 if (get_timespec64(ts, u64_to_user_ptr(sqe->addr)))
2811 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req,
2812 struct timespec64 *ts,
2813 enum hrtimer_mode *mode)
2815 struct io_kiocb *nxt;
2818 if (!(req->flags & REQ_F_LINK))
2821 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
2822 if (!nxt || nxt->submit.sqe->opcode != IORING_OP_LINK_TIMEOUT)
2825 ret = io_validate_link_timeout(nxt->submit.sqe, ts);
2827 list_del_init(&nxt->list);
2828 io_cqring_add_event(nxt, ret);
2829 io_double_put_req(nxt);
2830 return ERR_PTR(-ECANCELED);
2833 if (nxt->submit.sqe->timeout_flags & IORING_TIMEOUT_ABS)
2834 *mode = HRTIMER_MODE_ABS;
2836 *mode = HRTIMER_MODE_REL;
2838 req->flags |= REQ_F_LINK_TIMEOUT;
2839 hrtimer_init(&nxt->timeout.timer, CLOCK_MONOTONIC, *mode);
2843 static int __io_queue_sqe(struct io_kiocb *req)
2845 enum hrtimer_mode mode;
2846 struct io_kiocb *nxt;
2847 struct timespec64 ts;
2850 nxt = io_prep_linked_timeout(req, &ts, &mode);
2857 ret = __io_submit_sqe(req, NULL, true);
2860 * We async punt it if the file wasn't marked NOWAIT, or if the file
2861 * doesn't support non-blocking read/write attempts
2863 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2864 (req->flags & REQ_F_MUST_PUNT))) {
2865 struct sqe_submit *s = &req->submit;
2866 struct io_uring_sqe *sqe_copy;
2868 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2871 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
2872 ret = io_grab_files(req);
2880 * Queued up for async execution, worker will release
2881 * submit reference when the iocb is actually submitted.
2883 io_queue_async_work(req);
2886 io_queue_linked_timeout(nxt, &ts, &mode);
2893 /* drop submission reference */
2898 io_queue_linked_timeout(nxt, &ts, &mode);
2903 /* and drop final reference, if we failed */
2905 io_cqring_add_event(req, ret);
2906 if (req->flags & REQ_F_LINK)
2907 req->flags |= REQ_F_FAIL_LINK;
2914 static int io_queue_sqe(struct io_kiocb *req)
2918 ret = io_req_defer(req);
2920 if (ret != -EIOCBQUEUED) {
2921 io_cqring_add_event(req, ret);
2922 io_double_put_req(req);
2927 return __io_queue_sqe(req);
2930 static int io_queue_link_head(struct io_kiocb *req, struct io_kiocb *shadow)
2933 int need_submit = false;
2934 struct io_ring_ctx *ctx = req->ctx;
2937 return io_queue_sqe(req);
2940 * Mark the first IO in link list as DRAIN, let all the following
2941 * IOs enter the defer list. all IO needs to be completed before link
2944 req->flags |= REQ_F_IO_DRAIN;
2945 ret = io_req_defer(req);
2947 if (ret != -EIOCBQUEUED) {
2948 io_cqring_add_event(req, ret);
2949 io_double_put_req(req);
2950 __io_free_req(shadow);
2955 * If ret == 0 means that all IOs in front of link io are
2956 * running done. let's queue link head.
2961 /* Insert shadow req to defer_list, blocking next IOs */
2962 spin_lock_irq(&ctx->completion_lock);
2963 trace_io_uring_defer(ctx, shadow, true);
2964 list_add_tail(&shadow->list, &ctx->defer_list);
2965 spin_unlock_irq(&ctx->completion_lock);
2968 return __io_queue_sqe(req);
2973 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2975 static void io_submit_sqe(struct io_kiocb *req, struct io_submit_state *state,
2976 struct io_kiocb **link)
2978 struct io_uring_sqe *sqe_copy;
2979 struct sqe_submit *s = &req->submit;
2980 struct io_ring_ctx *ctx = req->ctx;
2983 req->user_data = s->sqe->user_data;
2985 /* enforce forwards compatibility on users */
2986 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2991 ret = io_req_set_file(state, req);
2992 if (unlikely(ret)) {
2994 io_cqring_add_event(req, ret);
2995 io_double_put_req(req);
3000 * If we already have a head request, queue this one for async
3001 * submittal once the head completes. If we don't have a head but
3002 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3003 * submitted sync once the chain is complete. If none of those
3004 * conditions are true (normal request), then just queue it.
3007 struct io_kiocb *prev = *link;
3009 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
3016 trace_io_uring_link(ctx, req, prev);
3017 list_add_tail(&req->list, &prev->link_list);
3018 } else if (s->sqe->flags & IOSQE_IO_LINK) {
3019 req->flags |= REQ_F_LINK;
3021 INIT_LIST_HEAD(&req->link_list);
3023 } else if (READ_ONCE(s->sqe->opcode) == IORING_OP_LINK_TIMEOUT) {
3024 /* Only valid as a linked SQE */
3033 * Batched submission is done, ensure local IO is flushed out.
3035 static void io_submit_state_end(struct io_submit_state *state)
3037 blk_finish_plug(&state->plug);
3039 if (state->free_reqs)
3040 kmem_cache_free_bulk(req_cachep, state->free_reqs,
3041 &state->reqs[state->cur_req]);
3045 * Start submission side cache.
3047 static void io_submit_state_start(struct io_submit_state *state,
3048 struct io_ring_ctx *ctx, unsigned max_ios)
3050 blk_start_plug(&state->plug);
3051 state->free_reqs = 0;
3053 state->ios_left = max_ios;
3056 static void io_commit_sqring(struct io_ring_ctx *ctx)
3058 struct io_rings *rings = ctx->rings;
3060 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
3062 * Ensure any loads from the SQEs are done at this point,
3063 * since once we write the new head, the application could
3064 * write new data to them.
3066 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3071 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
3072 * that is mapped by userspace. This means that care needs to be taken to
3073 * ensure that reads are stable, as we cannot rely on userspace always
3074 * being a good citizen. If members of the sqe are validated and then later
3075 * used, it's important that those reads are done through READ_ONCE() to
3076 * prevent a re-load down the line.
3078 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
3080 struct io_rings *rings = ctx->rings;
3081 u32 *sq_array = ctx->sq_array;
3085 * The cached sq head (or cq tail) serves two purposes:
3087 * 1) allows us to batch the cost of updating the user visible
3089 * 2) allows the kernel side to track the head on its own, even
3090 * though the application is the one updating it.
3092 head = ctx->cached_sq_head;
3093 /* make sure SQ entry isn't read before tail */
3094 if (head == smp_load_acquire(&rings->sq.tail))
3097 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
3098 if (head < ctx->sq_entries) {
3099 s->ring_file = NULL;
3100 s->sqe = &ctx->sq_sqes[head];
3101 s->sequence = ctx->cached_sq_head;
3102 ctx->cached_sq_head++;
3106 /* drop invalid entries */
3107 ctx->cached_sq_head++;
3108 ctx->cached_sq_dropped++;
3109 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
3113 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
3114 struct file *ring_file, int ring_fd,
3115 struct mm_struct **mm, bool async)
3117 struct io_submit_state state, *statep = NULL;
3118 struct io_kiocb *link = NULL;
3119 struct io_kiocb *shadow_req = NULL;
3120 int i, submitted = 0;
3121 bool mm_fault = false;
3123 if (!list_empty(&ctx->cq_overflow_list)) {
3124 io_cqring_overflow_flush(ctx, false);
3128 if (nr > IO_PLUG_THRESHOLD) {
3129 io_submit_state_start(&state, ctx, nr);
3133 for (i = 0; i < nr; i++) {
3134 struct io_kiocb *req;
3135 unsigned int sqe_flags;
3137 req = io_get_req(ctx, statep);
3138 if (unlikely(!req)) {
3140 submitted = -EAGAIN;
3143 if (!io_get_sqring(ctx, &req->submit)) {
3148 if (io_sqe_needs_user(req->submit.sqe) && !*mm) {
3149 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
3151 use_mm(ctx->sqo_mm);
3156 sqe_flags = req->submit.sqe->flags;
3158 if (link && (sqe_flags & IOSQE_IO_DRAIN)) {
3160 shadow_req = io_get_req(ctx, NULL);
3161 if (unlikely(!shadow_req))
3163 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
3164 refcount_dec(&shadow_req->refs);
3166 shadow_req->sequence = req->submit.sequence;
3170 req->submit.ring_file = ring_file;
3171 req->submit.ring_fd = ring_fd;
3172 req->submit.has_user = *mm != NULL;
3173 req->submit.in_async = async;
3174 req->submit.needs_fixed_file = async;
3175 trace_io_uring_submit_sqe(ctx, req->submit.sqe->user_data,
3177 io_submit_sqe(req, statep, &link);
3181 * If previous wasn't linked and we have a linked command,
3182 * that's the end of the chain. Submit the previous link.
3184 if (!(sqe_flags & IOSQE_IO_LINK) && link) {
3185 io_queue_link_head(link, shadow_req);
3192 io_queue_link_head(link, shadow_req);
3194 io_submit_state_end(&state);
3196 /* Commit SQ ring head once we've consumed and submitted all SQEs */
3197 io_commit_sqring(ctx);
3202 static int io_sq_thread(void *data)
3204 struct io_ring_ctx *ctx = data;
3205 struct mm_struct *cur_mm = NULL;
3206 mm_segment_t old_fs;
3209 unsigned long timeout;
3212 complete(&ctx->completions[1]);
3217 ret = timeout = inflight = 0;
3218 while (!kthread_should_park()) {
3219 unsigned int to_submit;
3222 unsigned nr_events = 0;
3224 if (ctx->flags & IORING_SETUP_IOPOLL) {
3226 * inflight is the count of the maximum possible
3227 * entries we submitted, but it can be smaller
3228 * if we dropped some of them. If we don't have
3229 * poll entries available, then we know that we
3230 * have nothing left to poll for. Reset the
3231 * inflight count to zero in that case.
3233 mutex_lock(&ctx->uring_lock);
3234 if (!list_empty(&ctx->poll_list))
3235 __io_iopoll_check(ctx, &nr_events, 0);
3238 mutex_unlock(&ctx->uring_lock);
3241 * Normal IO, just pretend everything completed.
3242 * We don't have to poll completions for that.
3244 nr_events = inflight;
3247 inflight -= nr_events;
3249 timeout = jiffies + ctx->sq_thread_idle;
3252 to_submit = io_sqring_entries(ctx);
3255 * If submit got -EBUSY, flag us as needing the application
3256 * to enter the kernel to reap and flush events.
3258 if (!to_submit || ret == -EBUSY) {
3260 * We're polling. If we're within the defined idle
3261 * period, then let us spin without work before going
3262 * to sleep. The exception is if we got EBUSY doing
3263 * more IO, we should wait for the application to
3264 * reap events and wake us up.
3267 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
3273 * Drop cur_mm before scheduling, we can't hold it for
3274 * long periods (or over schedule()). Do this before
3275 * adding ourselves to the waitqueue, as the unuse/drop
3284 prepare_to_wait(&ctx->sqo_wait, &wait,
3285 TASK_INTERRUPTIBLE);
3287 /* Tell userspace we may need a wakeup call */
3288 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
3289 /* make sure to read SQ tail after writing flags */
3292 to_submit = io_sqring_entries(ctx);
3293 if (!to_submit || ret == -EBUSY) {
3294 if (kthread_should_park()) {
3295 finish_wait(&ctx->sqo_wait, &wait);
3298 if (signal_pending(current))
3299 flush_signals(current);
3301 finish_wait(&ctx->sqo_wait, &wait);
3303 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3306 finish_wait(&ctx->sqo_wait, &wait);
3308 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3311 to_submit = min(to_submit, ctx->sq_entries);
3312 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
3328 struct io_wait_queue {
3329 struct wait_queue_entry wq;
3330 struct io_ring_ctx *ctx;
3332 unsigned nr_timeouts;
3335 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
3337 struct io_ring_ctx *ctx = iowq->ctx;
3340 * Wake up if we have enough events, or if a timeout occured since we
3341 * started waiting. For timeouts, we always want to return to userspace,
3342 * regardless of event count.
3344 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
3345 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3348 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3349 int wake_flags, void *key)
3351 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3354 /* use noflush == true, as we can't safely rely on locking context */
3355 if (!io_should_wake(iowq, true))
3358 return autoremove_wake_function(curr, mode, wake_flags, key);
3362 * Wait until events become available, if we don't already have some. The
3363 * application must reap them itself, as they reside on the shared cq ring.
3365 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3366 const sigset_t __user *sig, size_t sigsz)
3368 struct io_wait_queue iowq = {
3371 .func = io_wake_function,
3372 .entry = LIST_HEAD_INIT(iowq.wq.entry),
3375 .to_wait = min_events,
3377 struct io_rings *rings = ctx->rings;
3380 if (io_cqring_events(ctx, false) >= min_events)
3384 #ifdef CONFIG_COMPAT
3385 if (in_compat_syscall())
3386 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3390 ret = set_user_sigmask(sig, sigsz);
3396 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3397 trace_io_uring_cqring_wait(ctx, min_events);
3399 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3400 TASK_INTERRUPTIBLE);
3401 if (io_should_wake(&iowq, false))
3404 if (signal_pending(current)) {
3409 finish_wait(&ctx->wait, &iowq.wq);
3411 restore_saved_sigmask_unless(ret == -EINTR);
3413 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3416 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3418 #if defined(CONFIG_UNIX)
3419 if (ctx->ring_sock) {
3420 struct sock *sock = ctx->ring_sock->sk;
3421 struct sk_buff *skb;
3423 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
3429 for (i = 0; i < ctx->nr_user_files; i++) {
3432 file = io_file_from_index(ctx, i);
3439 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3441 unsigned nr_tables, i;
3443 if (!ctx->file_table)
3446 __io_sqe_files_unregister(ctx);
3447 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
3448 for (i = 0; i < nr_tables; i++)
3449 kfree(ctx->file_table[i].files);
3450 kfree(ctx->file_table);
3451 ctx->file_table = NULL;
3452 ctx->nr_user_files = 0;
3456 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3458 if (ctx->sqo_thread) {
3459 wait_for_completion(&ctx->completions[1]);
3461 * The park is a bit of a work-around, without it we get
3462 * warning spews on shutdown with SQPOLL set and affinity
3463 * set to a single CPU.
3465 kthread_park(ctx->sqo_thread);
3466 kthread_stop(ctx->sqo_thread);
3467 ctx->sqo_thread = NULL;
3471 static void io_finish_async(struct io_ring_ctx *ctx)
3473 io_sq_thread_stop(ctx);
3476 io_wq_destroy(ctx->io_wq);
3481 #if defined(CONFIG_UNIX)
3482 static void io_destruct_skb(struct sk_buff *skb)
3484 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
3487 io_wq_flush(ctx->io_wq);
3489 unix_destruct_scm(skb);
3493 * Ensure the UNIX gc is aware of our file set, so we are certain that
3494 * the io_uring can be safely unregistered on process exit, even if we have
3495 * loops in the file referencing.
3497 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
3499 struct sock *sk = ctx->ring_sock->sk;
3500 struct scm_fp_list *fpl;
3501 struct sk_buff *skb;
3504 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
3505 unsigned long inflight = ctx->user->unix_inflight + nr;
3507 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
3511 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
3515 skb = alloc_skb(0, GFP_KERNEL);
3524 fpl->user = get_uid(ctx->user);
3525 for (i = 0; i < nr; i++) {
3526 struct file *file = io_file_from_index(ctx, i + offset);
3530 fpl->fp[nr_files] = get_file(file);
3531 unix_inflight(fpl->user, fpl->fp[nr_files]);
3536 fpl->max = SCM_MAX_FD;
3537 fpl->count = nr_files;
3538 UNIXCB(skb).fp = fpl;
3539 skb->destructor = io_destruct_skb;
3540 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
3541 skb_queue_head(&sk->sk_receive_queue, skb);
3543 for (i = 0; i < nr_files; i++)
3554 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3555 * causes regular reference counting to break down. We rely on the UNIX
3556 * garbage collection to take care of this problem for us.
3558 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3560 unsigned left, total;
3564 left = ctx->nr_user_files;
3566 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
3568 ret = __io_sqe_files_scm(ctx, this_files, total);
3572 total += this_files;
3578 while (total < ctx->nr_user_files) {
3579 struct file *file = io_file_from_index(ctx, total);
3589 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3595 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
3600 for (i = 0; i < nr_tables; i++) {
3601 struct fixed_file_table *table = &ctx->file_table[i];
3602 unsigned this_files;
3604 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
3605 table->files = kcalloc(this_files, sizeof(struct file *),
3609 nr_files -= this_files;
3615 for (i = 0; i < nr_tables; i++) {
3616 struct fixed_file_table *table = &ctx->file_table[i];
3617 kfree(table->files);
3622 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3625 __s32 __user *fds = (__s32 __user *) arg;
3630 if (ctx->file_table)
3634 if (nr_args > IORING_MAX_FIXED_FILES)
3637 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
3638 ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
3640 if (!ctx->file_table)
3643 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
3644 kfree(ctx->file_table);
3645 ctx->file_table = NULL;
3649 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
3650 struct fixed_file_table *table;
3654 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3656 /* allow sparse sets */
3662 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3663 index = i & IORING_FILE_TABLE_MASK;
3664 table->files[index] = fget(fd);
3667 if (!table->files[index])
3670 * Don't allow io_uring instances to be registered. If UNIX
3671 * isn't enabled, then this causes a reference cycle and this
3672 * instance can never get freed. If UNIX is enabled we'll
3673 * handle it just fine, but there's still no point in allowing
3674 * a ring fd as it doesn't support regular read/write anyway.
3676 if (table->files[index]->f_op == &io_uring_fops) {
3677 fput(table->files[index]);
3684 for (i = 0; i < ctx->nr_user_files; i++) {
3687 file = io_file_from_index(ctx, i);
3691 for (i = 0; i < nr_tables; i++)
3692 kfree(ctx->file_table[i].files);
3694 kfree(ctx->file_table);
3695 ctx->file_table = NULL;
3696 ctx->nr_user_files = 0;
3700 ret = io_sqe_files_scm(ctx);
3702 io_sqe_files_unregister(ctx);
3707 static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
3709 #if defined(CONFIG_UNIX)
3710 struct file *file = io_file_from_index(ctx, index);
3711 struct sock *sock = ctx->ring_sock->sk;
3712 struct sk_buff_head list, *head = &sock->sk_receive_queue;
3713 struct sk_buff *skb;
3716 __skb_queue_head_init(&list);
3719 * Find the skb that holds this file in its SCM_RIGHTS. When found,
3720 * remove this entry and rearrange the file array.
3722 skb = skb_dequeue(head);
3724 struct scm_fp_list *fp;
3726 fp = UNIXCB(skb).fp;
3727 for (i = 0; i < fp->count; i++) {
3730 if (fp->fp[i] != file)
3733 unix_notinflight(fp->user, fp->fp[i]);
3734 left = fp->count - 1 - i;
3736 memmove(&fp->fp[i], &fp->fp[i + 1],
3737 left * sizeof(struct file *));
3744 __skb_queue_tail(&list, skb);
3754 __skb_queue_tail(&list, skb);
3756 skb = skb_dequeue(head);
3759 if (skb_peek(&list)) {
3760 spin_lock_irq(&head->lock);
3761 while ((skb = __skb_dequeue(&list)) != NULL)
3762 __skb_queue_tail(head, skb);
3763 spin_unlock_irq(&head->lock);
3766 fput(io_file_from_index(ctx, index));
3770 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
3773 #if defined(CONFIG_UNIX)
3774 struct sock *sock = ctx->ring_sock->sk;
3775 struct sk_buff_head *head = &sock->sk_receive_queue;
3776 struct sk_buff *skb;
3779 * See if we can merge this file into an existing skb SCM_RIGHTS
3780 * file set. If there's no room, fall back to allocating a new skb
3781 * and filling it in.
3783 spin_lock_irq(&head->lock);
3784 skb = skb_peek(head);
3786 struct scm_fp_list *fpl = UNIXCB(skb).fp;
3788 if (fpl->count < SCM_MAX_FD) {
3789 __skb_unlink(skb, head);
3790 spin_unlock_irq(&head->lock);
3791 fpl->fp[fpl->count] = get_file(file);
3792 unix_inflight(fpl->user, fpl->fp[fpl->count]);
3794 spin_lock_irq(&head->lock);
3795 __skb_queue_head(head, skb);
3800 spin_unlock_irq(&head->lock);
3807 return __io_sqe_files_scm(ctx, 1, index);
3813 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
3816 struct io_uring_files_update up;
3821 if (!ctx->file_table)
3825 if (copy_from_user(&up, arg, sizeof(up)))
3827 if (check_add_overflow(up.offset, nr_args, &done))
3829 if (done > ctx->nr_user_files)
3833 fds = (__s32 __user *) up.fds;
3835 struct fixed_file_table *table;
3839 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
3843 i = array_index_nospec(up.offset, ctx->nr_user_files);
3844 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3845 index = i & IORING_FILE_TABLE_MASK;
3846 if (table->files[index]) {
3847 io_sqe_file_unregister(ctx, i);
3848 table->files[index] = NULL;
3859 * Don't allow io_uring instances to be registered. If
3860 * UNIX isn't enabled, then this causes a reference
3861 * cycle and this instance can never get freed. If UNIX
3862 * is enabled we'll handle it just fine, but there's
3863 * still no point in allowing a ring fd as it doesn't
3864 * support regular read/write anyway.
3866 if (file->f_op == &io_uring_fops) {
3871 table->files[index] = file;
3872 err = io_sqe_file_register(ctx, file, i);
3881 return done ? done : err;
3884 static void io_put_work(struct io_wq_work *work)
3886 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3891 static void io_get_work(struct io_wq_work *work)
3893 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3895 refcount_inc(&req->refs);
3898 static int io_sq_offload_start(struct io_ring_ctx *ctx,
3899 struct io_uring_params *p)
3901 unsigned concurrency;
3904 init_waitqueue_head(&ctx->sqo_wait);
3905 mmgrab(current->mm);
3906 ctx->sqo_mm = current->mm;
3908 if (ctx->flags & IORING_SETUP_SQPOLL) {
3910 if (!capable(CAP_SYS_ADMIN))
3913 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3914 if (!ctx->sq_thread_idle)
3915 ctx->sq_thread_idle = HZ;
3917 if (p->flags & IORING_SETUP_SQ_AFF) {
3918 int cpu = p->sq_thread_cpu;
3921 if (cpu >= nr_cpu_ids)
3923 if (!cpu_online(cpu))
3926 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3930 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3933 if (IS_ERR(ctx->sqo_thread)) {
3934 ret = PTR_ERR(ctx->sqo_thread);
3935 ctx->sqo_thread = NULL;
3938 wake_up_process(ctx->sqo_thread);
3939 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3940 /* Can't have SQ_AFF without SQPOLL */
3945 /* Do QD, or 4 * CPUS, whatever is smallest */
3946 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
3947 ctx->io_wq = io_wq_create(concurrency, ctx->sqo_mm, ctx->user,
3948 io_get_work, io_put_work);
3949 if (IS_ERR(ctx->io_wq)) {
3950 ret = PTR_ERR(ctx->io_wq);
3957 io_finish_async(ctx);
3958 mmdrop(ctx->sqo_mm);
3963 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3965 atomic_long_sub(nr_pages, &user->locked_vm);
3968 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3970 unsigned long page_limit, cur_pages, new_pages;
3972 /* Don't allow more pages than we can safely lock */
3973 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3976 cur_pages = atomic_long_read(&user->locked_vm);
3977 new_pages = cur_pages + nr_pages;
3978 if (new_pages > page_limit)
3980 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3981 new_pages) != cur_pages);
3986 static void io_mem_free(void *ptr)
3993 page = virt_to_head_page(ptr);
3994 if (put_page_testzero(page))
3995 free_compound_page(page);
3998 static void *io_mem_alloc(size_t size)
4000 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
4003 return (void *) __get_free_pages(gfp_flags, get_order(size));
4006 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
4009 struct io_rings *rings;
4010 size_t off, sq_array_size;
4012 off = struct_size(rings, cqes, cq_entries);
4013 if (off == SIZE_MAX)
4017 off = ALIGN(off, SMP_CACHE_BYTES);
4022 sq_array_size = array_size(sizeof(u32), sq_entries);
4023 if (sq_array_size == SIZE_MAX)
4026 if (check_add_overflow(off, sq_array_size, &off))
4035 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
4039 pages = (size_t)1 << get_order(
4040 rings_size(sq_entries, cq_entries, NULL));
4041 pages += (size_t)1 << get_order(
4042 array_size(sizeof(struct io_uring_sqe), sq_entries));
4047 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
4051 if (!ctx->user_bufs)
4054 for (i = 0; i < ctx->nr_user_bufs; i++) {
4055 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4057 for (j = 0; j < imu->nr_bvecs; j++)
4058 put_user_page(imu->bvec[j].bv_page);
4060 if (ctx->account_mem)
4061 io_unaccount_mem(ctx->user, imu->nr_bvecs);
4066 kfree(ctx->user_bufs);
4067 ctx->user_bufs = NULL;
4068 ctx->nr_user_bufs = 0;
4072 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4073 void __user *arg, unsigned index)
4075 struct iovec __user *src;
4077 #ifdef CONFIG_COMPAT
4079 struct compat_iovec __user *ciovs;
4080 struct compat_iovec ciov;
4082 ciovs = (struct compat_iovec __user *) arg;
4083 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4086 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
4087 dst->iov_len = ciov.iov_len;
4091 src = (struct iovec __user *) arg;
4092 if (copy_from_user(dst, &src[index], sizeof(*dst)))
4097 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
4100 struct vm_area_struct **vmas = NULL;
4101 struct page **pages = NULL;
4102 int i, j, got_pages = 0;
4107 if (!nr_args || nr_args > UIO_MAXIOV)
4110 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
4112 if (!ctx->user_bufs)
4115 for (i = 0; i < nr_args; i++) {
4116 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4117 unsigned long off, start, end, ubuf;
4122 ret = io_copy_iov(ctx, &iov, arg, i);
4127 * Don't impose further limits on the size and buffer
4128 * constraints here, we'll -EINVAL later when IO is
4129 * submitted if they are wrong.
4132 if (!iov.iov_base || !iov.iov_len)
4135 /* arbitrary limit, but we need something */
4136 if (iov.iov_len > SZ_1G)
4139 ubuf = (unsigned long) iov.iov_base;
4140 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4141 start = ubuf >> PAGE_SHIFT;
4142 nr_pages = end - start;
4144 if (ctx->account_mem) {
4145 ret = io_account_mem(ctx->user, nr_pages);
4151 if (!pages || nr_pages > got_pages) {
4154 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
4156 vmas = kvmalloc_array(nr_pages,
4157 sizeof(struct vm_area_struct *),
4159 if (!pages || !vmas) {
4161 if (ctx->account_mem)
4162 io_unaccount_mem(ctx->user, nr_pages);
4165 got_pages = nr_pages;
4168 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
4172 if (ctx->account_mem)
4173 io_unaccount_mem(ctx->user, nr_pages);
4178 down_read(¤t->mm->mmap_sem);
4179 pret = get_user_pages(ubuf, nr_pages,
4180 FOLL_WRITE | FOLL_LONGTERM,
4182 if (pret == nr_pages) {
4183 /* don't support file backed memory */
4184 for (j = 0; j < nr_pages; j++) {
4185 struct vm_area_struct *vma = vmas[j];
4188 !is_file_hugepages(vma->vm_file)) {
4194 ret = pret < 0 ? pret : -EFAULT;
4196 up_read(¤t->mm->mmap_sem);
4199 * if we did partial map, or found file backed vmas,
4200 * release any pages we did get
4203 put_user_pages(pages, pret);
4204 if (ctx->account_mem)
4205 io_unaccount_mem(ctx->user, nr_pages);
4210 off = ubuf & ~PAGE_MASK;
4212 for (j = 0; j < nr_pages; j++) {
4215 vec_len = min_t(size_t, size, PAGE_SIZE - off);
4216 imu->bvec[j].bv_page = pages[j];
4217 imu->bvec[j].bv_len = vec_len;
4218 imu->bvec[j].bv_offset = off;
4222 /* store original address for later verification */
4224 imu->len = iov.iov_len;
4225 imu->nr_bvecs = nr_pages;
4227 ctx->nr_user_bufs++;
4235 io_sqe_buffer_unregister(ctx);
4239 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
4241 __s32 __user *fds = arg;
4247 if (copy_from_user(&fd, fds, sizeof(*fds)))
4250 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
4251 if (IS_ERR(ctx->cq_ev_fd)) {
4252 int ret = PTR_ERR(ctx->cq_ev_fd);
4253 ctx->cq_ev_fd = NULL;
4260 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
4262 if (ctx->cq_ev_fd) {
4263 eventfd_ctx_put(ctx->cq_ev_fd);
4264 ctx->cq_ev_fd = NULL;
4271 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
4273 io_finish_async(ctx);
4275 mmdrop(ctx->sqo_mm);
4277 io_iopoll_reap_events(ctx);
4278 io_sqe_buffer_unregister(ctx);
4279 io_sqe_files_unregister(ctx);
4280 io_eventfd_unregister(ctx);
4282 #if defined(CONFIG_UNIX)
4283 if (ctx->ring_sock) {
4284 ctx->ring_sock->file = NULL; /* so that iput() is called */
4285 sock_release(ctx->ring_sock);
4289 io_mem_free(ctx->rings);
4290 io_mem_free(ctx->sq_sqes);
4292 percpu_ref_exit(&ctx->refs);
4293 if (ctx->account_mem)
4294 io_unaccount_mem(ctx->user,
4295 ring_pages(ctx->sq_entries, ctx->cq_entries));
4296 free_uid(ctx->user);
4297 kfree(ctx->completions);
4298 kmem_cache_free(req_cachep, ctx->fallback_req);
4302 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
4304 struct io_ring_ctx *ctx = file->private_data;
4307 poll_wait(file, &ctx->cq_wait, wait);
4309 * synchronizes with barrier from wq_has_sleeper call in
4313 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
4314 ctx->rings->sq_ring_entries)
4315 mask |= EPOLLOUT | EPOLLWRNORM;
4316 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
4317 mask |= EPOLLIN | EPOLLRDNORM;
4322 static int io_uring_fasync(int fd, struct file *file, int on)
4324 struct io_ring_ctx *ctx = file->private_data;
4326 return fasync_helper(fd, file, on, &ctx->cq_fasync);
4329 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
4331 mutex_lock(&ctx->uring_lock);
4332 percpu_ref_kill(&ctx->refs);
4333 mutex_unlock(&ctx->uring_lock);
4335 io_kill_timeouts(ctx);
4336 io_poll_remove_all(ctx);
4339 io_wq_cancel_all(ctx->io_wq);
4341 io_iopoll_reap_events(ctx);
4342 /* if we failed setting up the ctx, we might not have any rings */
4344 io_cqring_overflow_flush(ctx, true);
4345 wait_for_completion(&ctx->completions[0]);
4346 io_ring_ctx_free(ctx);
4349 static int io_uring_release(struct inode *inode, struct file *file)
4351 struct io_ring_ctx *ctx = file->private_data;
4353 file->private_data = NULL;
4354 io_ring_ctx_wait_and_kill(ctx);
4358 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
4359 struct files_struct *files)
4361 struct io_kiocb *req;
4364 while (!list_empty_careful(&ctx->inflight_list)) {
4365 struct io_kiocb *cancel_req = NULL;
4367 spin_lock_irq(&ctx->inflight_lock);
4368 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
4369 if (req->work.files != files)
4371 /* req is being completed, ignore */
4372 if (!refcount_inc_not_zero(&req->refs))
4378 prepare_to_wait(&ctx->inflight_wait, &wait,
4379 TASK_UNINTERRUPTIBLE);
4380 spin_unlock_irq(&ctx->inflight_lock);
4382 /* We need to keep going until we don't find a matching req */
4386 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
4387 io_put_req(cancel_req);
4390 finish_wait(&ctx->inflight_wait, &wait);
4393 static int io_uring_flush(struct file *file, void *data)
4395 struct io_ring_ctx *ctx = file->private_data;
4397 io_uring_cancel_files(ctx, data);
4398 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
4399 io_cqring_overflow_flush(ctx, true);
4400 io_wq_cancel_all(ctx->io_wq);
4405 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
4407 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
4408 unsigned long sz = vma->vm_end - vma->vm_start;
4409 struct io_ring_ctx *ctx = file->private_data;
4415 case IORING_OFF_SQ_RING:
4416 case IORING_OFF_CQ_RING:
4419 case IORING_OFF_SQES:
4426 page = virt_to_head_page(ptr);
4427 if (sz > page_size(page))
4430 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
4431 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
4434 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
4435 u32, min_complete, u32, flags, const sigset_t __user *, sig,
4438 struct io_ring_ctx *ctx;
4443 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
4451 if (f.file->f_op != &io_uring_fops)
4455 ctx = f.file->private_data;
4456 if (!percpu_ref_tryget(&ctx->refs))
4460 * For SQ polling, the thread will do all submissions and completions.
4461 * Just return the requested submit count, and wake the thread if
4465 if (ctx->flags & IORING_SETUP_SQPOLL) {
4466 if (!list_empty_careful(&ctx->cq_overflow_list))
4467 io_cqring_overflow_flush(ctx, false);
4468 if (flags & IORING_ENTER_SQ_WAKEUP)
4469 wake_up(&ctx->sqo_wait);
4470 submitted = to_submit;
4471 } else if (to_submit) {
4472 struct mm_struct *cur_mm;
4474 to_submit = min(to_submit, ctx->sq_entries);
4475 mutex_lock(&ctx->uring_lock);
4476 /* already have mm, so io_submit_sqes() won't try to grab it */
4477 cur_mm = ctx->sqo_mm;
4478 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
4480 mutex_unlock(&ctx->uring_lock);
4482 if (flags & IORING_ENTER_GETEVENTS) {
4483 unsigned nr_events = 0;
4485 min_complete = min(min_complete, ctx->cq_entries);
4487 if (ctx->flags & IORING_SETUP_IOPOLL) {
4488 ret = io_iopoll_check(ctx, &nr_events, min_complete);
4490 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
4494 percpu_ref_put(&ctx->refs);
4497 return submitted ? submitted : ret;
4500 static const struct file_operations io_uring_fops = {
4501 .release = io_uring_release,
4502 .flush = io_uring_flush,
4503 .mmap = io_uring_mmap,
4504 .poll = io_uring_poll,
4505 .fasync = io_uring_fasync,
4508 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
4509 struct io_uring_params *p)
4511 struct io_rings *rings;
4512 size_t size, sq_array_offset;
4514 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
4515 if (size == SIZE_MAX)
4518 rings = io_mem_alloc(size);
4523 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
4524 rings->sq_ring_mask = p->sq_entries - 1;
4525 rings->cq_ring_mask = p->cq_entries - 1;
4526 rings->sq_ring_entries = p->sq_entries;
4527 rings->cq_ring_entries = p->cq_entries;
4528 ctx->sq_mask = rings->sq_ring_mask;
4529 ctx->cq_mask = rings->cq_ring_mask;
4530 ctx->sq_entries = rings->sq_ring_entries;
4531 ctx->cq_entries = rings->cq_ring_entries;
4533 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
4534 if (size == SIZE_MAX)
4537 ctx->sq_sqes = io_mem_alloc(size);
4545 * Allocate an anonymous fd, this is what constitutes the application
4546 * visible backing of an io_uring instance. The application mmaps this
4547 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
4548 * we have to tie this fd to a socket for file garbage collection purposes.
4550 static int io_uring_get_fd(struct io_ring_ctx *ctx)
4555 #if defined(CONFIG_UNIX)
4556 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
4562 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
4566 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
4567 O_RDWR | O_CLOEXEC);
4570 ret = PTR_ERR(file);
4574 #if defined(CONFIG_UNIX)
4575 ctx->ring_sock->file = file;
4576 ctx->ring_sock->sk->sk_user_data = ctx;
4578 fd_install(ret, file);
4581 #if defined(CONFIG_UNIX)
4582 sock_release(ctx->ring_sock);
4583 ctx->ring_sock = NULL;
4588 static int io_uring_create(unsigned entries, struct io_uring_params *p)
4590 struct user_struct *user = NULL;
4591 struct io_ring_ctx *ctx;
4595 if (!entries || entries > IORING_MAX_ENTRIES)
4599 * Use twice as many entries for the CQ ring. It's possible for the
4600 * application to drive a higher depth than the size of the SQ ring,
4601 * since the sqes are only used at submission time. This allows for
4602 * some flexibility in overcommitting a bit. If the application has
4603 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
4604 * of CQ ring entries manually.
4606 p->sq_entries = roundup_pow_of_two(entries);
4607 if (p->flags & IORING_SETUP_CQSIZE) {
4609 * If IORING_SETUP_CQSIZE is set, we do the same roundup
4610 * to a power-of-two, if it isn't already. We do NOT impose
4611 * any cq vs sq ring sizing.
4613 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
4615 p->cq_entries = roundup_pow_of_two(p->cq_entries);
4617 p->cq_entries = 2 * p->sq_entries;
4620 user = get_uid(current_user());
4621 account_mem = !capable(CAP_IPC_LOCK);
4624 ret = io_account_mem(user,
4625 ring_pages(p->sq_entries, p->cq_entries));
4632 ctx = io_ring_ctx_alloc(p);
4635 io_unaccount_mem(user, ring_pages(p->sq_entries,
4640 ctx->compat = in_compat_syscall();
4641 ctx->account_mem = account_mem;
4644 ret = io_allocate_scq_urings(ctx, p);
4648 ret = io_sq_offload_start(ctx, p);
4652 memset(&p->sq_off, 0, sizeof(p->sq_off));
4653 p->sq_off.head = offsetof(struct io_rings, sq.head);
4654 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
4655 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
4656 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
4657 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
4658 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
4659 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
4661 memset(&p->cq_off, 0, sizeof(p->cq_off));
4662 p->cq_off.head = offsetof(struct io_rings, cq.head);
4663 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
4664 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
4665 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
4666 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
4667 p->cq_off.cqes = offsetof(struct io_rings, cqes);
4670 * Install ring fd as the very last thing, so we don't risk someone
4671 * having closed it before we finish setup
4673 ret = io_uring_get_fd(ctx);
4677 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP;
4678 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
4681 io_ring_ctx_wait_and_kill(ctx);
4686 * Sets up an aio uring context, and returns the fd. Applications asks for a
4687 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4688 * params structure passed in.
4690 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4692 struct io_uring_params p;
4696 if (copy_from_user(&p, params, sizeof(p)))
4698 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4703 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4704 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
4707 ret = io_uring_create(entries, &p);
4711 if (copy_to_user(params, &p, sizeof(p)))
4717 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4718 struct io_uring_params __user *, params)
4720 return io_uring_setup(entries, params);
4723 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4724 void __user *arg, unsigned nr_args)
4725 __releases(ctx->uring_lock)
4726 __acquires(ctx->uring_lock)
4731 * We're inside the ring mutex, if the ref is already dying, then
4732 * someone else killed the ctx or is already going through
4733 * io_uring_register().
4735 if (percpu_ref_is_dying(&ctx->refs))
4738 percpu_ref_kill(&ctx->refs);
4741 * Drop uring mutex before waiting for references to exit. If another
4742 * thread is currently inside io_uring_enter() it might need to grab
4743 * the uring_lock to make progress. If we hold it here across the drain
4744 * wait, then we can deadlock. It's safe to drop the mutex here, since
4745 * no new references will come in after we've killed the percpu ref.
4747 mutex_unlock(&ctx->uring_lock);
4748 wait_for_completion(&ctx->completions[0]);
4749 mutex_lock(&ctx->uring_lock);
4752 case IORING_REGISTER_BUFFERS:
4753 ret = io_sqe_buffer_register(ctx, arg, nr_args);
4755 case IORING_UNREGISTER_BUFFERS:
4759 ret = io_sqe_buffer_unregister(ctx);
4761 case IORING_REGISTER_FILES:
4762 ret = io_sqe_files_register(ctx, arg, nr_args);
4764 case IORING_UNREGISTER_FILES:
4768 ret = io_sqe_files_unregister(ctx);
4770 case IORING_REGISTER_FILES_UPDATE:
4771 ret = io_sqe_files_update(ctx, arg, nr_args);
4773 case IORING_REGISTER_EVENTFD:
4777 ret = io_eventfd_register(ctx, arg);
4779 case IORING_UNREGISTER_EVENTFD:
4783 ret = io_eventfd_unregister(ctx);
4790 /* bring the ctx back to life */
4791 reinit_completion(&ctx->completions[0]);
4792 percpu_ref_reinit(&ctx->refs);
4796 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4797 void __user *, arg, unsigned int, nr_args)
4799 struct io_ring_ctx *ctx;
4808 if (f.file->f_op != &io_uring_fops)
4811 ctx = f.file->private_data;
4813 mutex_lock(&ctx->uring_lock);
4814 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4815 mutex_unlock(&ctx->uring_lock);
4816 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
4817 ctx->cq_ev_fd != NULL, ret);
4823 static int __init io_uring_init(void)
4825 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4828 __initcall(io_uring_init);