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;
192 * Ring buffer of indices into array of io_uring_sqe, which is
193 * mmapped by the application using the IORING_OFF_SQES offset.
195 * This indirection could e.g. be used to assign fixed
196 * io_uring_sqe entries to operations and only submit them to
197 * the queue when needed.
199 * The kernel modifies neither the indices array nor the entries
203 unsigned cached_sq_head;
206 unsigned sq_thread_idle;
207 unsigned cached_sq_dropped;
208 atomic_t cached_cq_overflow;
209 struct io_uring_sqe *sq_sqes;
211 struct list_head defer_list;
212 struct list_head timeout_list;
213 struct list_head cq_overflow_list;
215 wait_queue_head_t inflight_wait;
216 } ____cacheline_aligned_in_smp;
218 struct io_rings *rings;
222 struct task_struct *sqo_thread; /* if using sq thread polling */
223 struct mm_struct *sqo_mm;
224 wait_queue_head_t sqo_wait;
227 * If used, fixed file set. Writers must ensure that ->refs is dead,
228 * readers must ensure that ->refs is alive as long as the file* is
229 * used. Only updated through io_uring_register(2).
231 struct fixed_file_table *file_table;
232 unsigned nr_user_files;
234 /* if used, fixed mapped user buffers */
235 unsigned nr_user_bufs;
236 struct io_mapped_ubuf *user_bufs;
238 struct user_struct *user;
242 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
243 struct completion *completions;
245 /* if all else fails... */
246 struct io_kiocb *fallback_req;
248 #if defined(CONFIG_UNIX)
249 struct socket *ring_sock;
253 unsigned cached_cq_tail;
256 atomic_t cq_timeouts;
257 struct wait_queue_head cq_wait;
258 struct fasync_struct *cq_fasync;
259 struct eventfd_ctx *cq_ev_fd;
260 } ____cacheline_aligned_in_smp;
263 struct mutex uring_lock;
264 wait_queue_head_t wait;
265 } ____cacheline_aligned_in_smp;
268 spinlock_t completion_lock;
269 bool poll_multi_file;
271 * ->poll_list is protected by the ctx->uring_lock for
272 * io_uring instances that don't use IORING_SETUP_SQPOLL.
273 * For SQPOLL, only the single threaded io_sq_thread() will
274 * manipulate the list, hence no extra locking is needed there.
276 struct list_head poll_list;
277 struct rb_root cancel_tree;
279 spinlock_t inflight_lock;
280 struct list_head inflight_list;
281 } ____cacheline_aligned_in_smp;
285 * First field must be the file pointer in all the
286 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
288 struct io_poll_iocb {
290 struct wait_queue_head *head;
294 struct wait_queue_entry *wait;
297 struct io_timeout_data {
298 struct io_kiocb *req;
299 struct hrtimer timer;
300 struct timespec64 ts;
301 enum hrtimer_mode mode;
307 struct io_timeout_data *data;
311 * NOTE! Each of the iocb union members has the file pointer
312 * as the first entry in their struct definition. So you can
313 * access the file pointer through any of the sub-structs,
314 * or directly as just 'ki_filp' in this struct.
320 struct io_poll_iocb poll;
321 struct io_timeout timeout;
324 const struct io_uring_sqe *sqe;
325 struct file *ring_file;
329 bool needs_fixed_file;
331 struct io_ring_ctx *ctx;
333 struct list_head list;
334 struct rb_node rb_node;
336 struct list_head link_list;
339 #define REQ_F_NOWAIT 1 /* must not punt to workers */
340 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
341 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
342 #define REQ_F_LINK_NEXT 8 /* already grabbed next link */
343 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
344 #define REQ_F_IO_DRAINED 32 /* drain done */
345 #define REQ_F_LINK 64 /* linked sqes */
346 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
347 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
348 #define REQ_F_DRAIN_LINK 512 /* link should be fully drained */
349 #define REQ_F_TIMEOUT 1024 /* timeout request */
350 #define REQ_F_ISREG 2048 /* regular file */
351 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
352 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
353 #define REQ_F_INFLIGHT 16384 /* on inflight list */
354 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
355 #define REQ_F_FREE_SQE 65536 /* free sqe if not async queued */
360 struct list_head inflight_entry;
362 struct io_wq_work work;
365 #define IO_PLUG_THRESHOLD 2
366 #define IO_IOPOLL_BATCH 8
368 struct io_submit_state {
369 struct blk_plug plug;
372 * io_kiocb alloc cache
374 void *reqs[IO_IOPOLL_BATCH];
375 unsigned int free_reqs;
376 unsigned int cur_req;
379 * File reference cache
383 unsigned int has_refs;
384 unsigned int used_refs;
385 unsigned int ios_left;
388 static void io_wq_submit_work(struct io_wq_work **workptr);
389 static void io_cqring_fill_event(struct io_kiocb *req, long res);
390 static void __io_free_req(struct io_kiocb *req);
391 static void io_put_req(struct io_kiocb *req);
392 static void io_double_put_req(struct io_kiocb *req);
393 static void __io_double_put_req(struct io_kiocb *req);
394 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
395 static void io_queue_linked_timeout(struct io_kiocb *req);
397 static struct kmem_cache *req_cachep;
399 static const struct file_operations io_uring_fops;
401 struct sock *io_uring_get_socket(struct file *file)
403 #if defined(CONFIG_UNIX)
404 if (file->f_op == &io_uring_fops) {
405 struct io_ring_ctx *ctx = file->private_data;
407 return ctx->ring_sock->sk;
412 EXPORT_SYMBOL(io_uring_get_socket);
414 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
416 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
418 complete(&ctx->completions[0]);
421 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
423 struct io_ring_ctx *ctx;
425 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
429 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
430 if (!ctx->fallback_req)
433 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
434 if (!ctx->completions)
437 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
438 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
441 ctx->flags = p->flags;
442 init_waitqueue_head(&ctx->cq_wait);
443 INIT_LIST_HEAD(&ctx->cq_overflow_list);
444 init_completion(&ctx->completions[0]);
445 init_completion(&ctx->completions[1]);
446 mutex_init(&ctx->uring_lock);
447 init_waitqueue_head(&ctx->wait);
448 spin_lock_init(&ctx->completion_lock);
449 INIT_LIST_HEAD(&ctx->poll_list);
450 ctx->cancel_tree = RB_ROOT;
451 INIT_LIST_HEAD(&ctx->defer_list);
452 INIT_LIST_HEAD(&ctx->timeout_list);
453 init_waitqueue_head(&ctx->inflight_wait);
454 spin_lock_init(&ctx->inflight_lock);
455 INIT_LIST_HEAD(&ctx->inflight_list);
458 if (ctx->fallback_req)
459 kmem_cache_free(req_cachep, ctx->fallback_req);
460 kfree(ctx->completions);
465 static inline bool __req_need_defer(struct io_kiocb *req)
467 struct io_ring_ctx *ctx = req->ctx;
469 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
470 + atomic_read(&ctx->cached_cq_overflow);
473 static inline bool req_need_defer(struct io_kiocb *req)
475 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
476 return __req_need_defer(req);
481 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
483 struct io_kiocb *req;
485 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
486 if (req && !req_need_defer(req)) {
487 list_del_init(&req->list);
494 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
496 struct io_kiocb *req;
498 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
500 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
502 if (!__req_need_defer(req)) {
503 list_del_init(&req->list);
511 static void __io_commit_cqring(struct io_ring_ctx *ctx)
513 struct io_rings *rings = ctx->rings;
515 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
516 /* order cqe stores with ring update */
517 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
519 if (wq_has_sleeper(&ctx->cq_wait)) {
520 wake_up_interruptible(&ctx->cq_wait);
521 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
526 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
528 u8 opcode = READ_ONCE(sqe->opcode);
530 return !(opcode == IORING_OP_READ_FIXED ||
531 opcode == IORING_OP_WRITE_FIXED);
534 static inline bool io_prep_async_work(struct io_kiocb *req,
535 struct io_kiocb **link)
537 bool do_hashed = false;
540 switch (req->sqe->opcode) {
541 case IORING_OP_WRITEV:
542 case IORING_OP_WRITE_FIXED:
545 case IORING_OP_READV:
546 case IORING_OP_READ_FIXED:
547 case IORING_OP_SENDMSG:
548 case IORING_OP_RECVMSG:
549 case IORING_OP_ACCEPT:
550 case IORING_OP_POLL_ADD:
551 case IORING_OP_CONNECT:
553 * We know REQ_F_ISREG is not set on some of these
554 * opcodes, but this enables us to keep the check in
557 if (!(req->flags & REQ_F_ISREG))
558 req->work.flags |= IO_WQ_WORK_UNBOUND;
561 if (io_sqe_needs_user(req->sqe))
562 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
565 *link = io_prep_linked_timeout(req);
569 static inline void io_queue_async_work(struct io_kiocb *req)
571 struct io_ring_ctx *ctx = req->ctx;
572 struct io_kiocb *link;
575 do_hashed = io_prep_async_work(req, &link);
577 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
580 io_wq_enqueue(ctx->io_wq, &req->work);
582 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
583 file_inode(req->file));
587 io_queue_linked_timeout(link);
590 static void io_kill_timeout(struct io_kiocb *req)
594 ret = hrtimer_try_to_cancel(&req->timeout.data->timer);
596 atomic_inc(&req->ctx->cq_timeouts);
597 list_del_init(&req->list);
598 io_cqring_fill_event(req, 0);
603 static void io_kill_timeouts(struct io_ring_ctx *ctx)
605 struct io_kiocb *req, *tmp;
607 spin_lock_irq(&ctx->completion_lock);
608 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
609 io_kill_timeout(req);
610 spin_unlock_irq(&ctx->completion_lock);
613 static void io_commit_cqring(struct io_ring_ctx *ctx)
615 struct io_kiocb *req;
617 while ((req = io_get_timeout_req(ctx)) != NULL)
618 io_kill_timeout(req);
620 __io_commit_cqring(ctx);
622 while ((req = io_get_deferred_req(ctx)) != NULL) {
623 req->flags |= REQ_F_IO_DRAINED;
624 io_queue_async_work(req);
628 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
630 struct io_rings *rings = ctx->rings;
633 tail = ctx->cached_cq_tail;
635 * writes to the cq entry need to come after reading head; the
636 * control dependency is enough as we're using WRITE_ONCE to
639 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
642 ctx->cached_cq_tail++;
643 return &rings->cqes[tail & ctx->cq_mask];
646 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
648 if (waitqueue_active(&ctx->wait))
650 if (waitqueue_active(&ctx->sqo_wait))
651 wake_up(&ctx->sqo_wait);
653 eventfd_signal(ctx->cq_ev_fd, 1);
656 /* Returns true if there are no backlogged entries after the flush */
657 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
659 struct io_rings *rings = ctx->rings;
660 struct io_uring_cqe *cqe;
661 struct io_kiocb *req;
666 if (list_empty_careful(&ctx->cq_overflow_list))
668 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
669 rings->cq_ring_entries))
673 spin_lock_irqsave(&ctx->completion_lock, flags);
675 /* if force is set, the ring is going away. always drop after that */
677 ctx->cq_overflow_flushed = true;
680 while (!list_empty(&ctx->cq_overflow_list)) {
681 cqe = io_get_cqring(ctx);
685 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
687 list_move(&req->list, &list);
689 WRITE_ONCE(cqe->user_data, req->user_data);
690 WRITE_ONCE(cqe->res, req->result);
691 WRITE_ONCE(cqe->flags, 0);
693 WRITE_ONCE(ctx->rings->cq_overflow,
694 atomic_inc_return(&ctx->cached_cq_overflow));
698 io_commit_cqring(ctx);
699 spin_unlock_irqrestore(&ctx->completion_lock, flags);
700 io_cqring_ev_posted(ctx);
702 while (!list_empty(&list)) {
703 req = list_first_entry(&list, struct io_kiocb, list);
704 list_del(&req->list);
711 static void io_cqring_fill_event(struct io_kiocb *req, long res)
713 struct io_ring_ctx *ctx = req->ctx;
714 struct io_uring_cqe *cqe;
716 trace_io_uring_complete(ctx, req->user_data, res);
719 * If we can't get a cq entry, userspace overflowed the
720 * submission (by quite a lot). Increment the overflow count in
723 cqe = io_get_cqring(ctx);
725 WRITE_ONCE(cqe->user_data, req->user_data);
726 WRITE_ONCE(cqe->res, res);
727 WRITE_ONCE(cqe->flags, 0);
728 } else if (ctx->cq_overflow_flushed) {
729 WRITE_ONCE(ctx->rings->cq_overflow,
730 atomic_inc_return(&ctx->cached_cq_overflow));
732 refcount_inc(&req->refs);
734 list_add_tail(&req->list, &ctx->cq_overflow_list);
738 static void io_cqring_add_event(struct io_kiocb *req, long res)
740 struct io_ring_ctx *ctx = req->ctx;
743 spin_lock_irqsave(&ctx->completion_lock, flags);
744 io_cqring_fill_event(req, res);
745 io_commit_cqring(ctx);
746 spin_unlock_irqrestore(&ctx->completion_lock, flags);
748 io_cqring_ev_posted(ctx);
751 static inline bool io_is_fallback_req(struct io_kiocb *req)
753 return req == (struct io_kiocb *)
754 ((unsigned long) req->ctx->fallback_req & ~1UL);
757 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
759 struct io_kiocb *req;
761 req = ctx->fallback_req;
762 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
768 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
769 struct io_submit_state *state)
771 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
772 struct io_kiocb *req;
774 if (!percpu_ref_tryget(&ctx->refs))
778 req = kmem_cache_alloc(req_cachep, gfp);
781 } else if (!state->free_reqs) {
785 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
786 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
789 * Bulk alloc is all-or-nothing. If we fail to get a batch,
790 * retry single alloc to be on the safe side.
792 if (unlikely(ret <= 0)) {
793 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
798 state->free_reqs = ret - 1;
800 req = state->reqs[0];
802 req = state->reqs[state->cur_req];
808 req->ring_file = NULL;
812 /* one is dropped after submission, the other at completion */
813 refcount_set(&req->refs, 2);
815 INIT_IO_WORK(&req->work, io_wq_submit_work);
818 req = io_get_fallback_req(ctx);
821 percpu_ref_put(&ctx->refs);
825 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
828 kmem_cache_free_bulk(req_cachep, *nr, reqs);
829 percpu_ref_put_many(&ctx->refs, *nr);
834 static void __io_free_req(struct io_kiocb *req)
836 struct io_ring_ctx *ctx = req->ctx;
838 if (req->flags & REQ_F_FREE_SQE)
840 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
842 if (req->flags & REQ_F_INFLIGHT) {
845 spin_lock_irqsave(&ctx->inflight_lock, flags);
846 list_del(&req->inflight_entry);
847 if (waitqueue_active(&ctx->inflight_wait))
848 wake_up(&ctx->inflight_wait);
849 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
851 if (req->flags & REQ_F_TIMEOUT)
852 kfree(req->timeout.data);
853 percpu_ref_put(&ctx->refs);
854 if (likely(!io_is_fallback_req(req)))
855 kmem_cache_free(req_cachep, req);
857 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
860 static bool io_link_cancel_timeout(struct io_kiocb *req)
862 struct io_ring_ctx *ctx = req->ctx;
865 ret = hrtimer_try_to_cancel(&req->timeout.data->timer);
867 io_cqring_fill_event(req, -ECANCELED);
868 io_commit_cqring(ctx);
869 req->flags &= ~REQ_F_LINK;
877 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
879 struct io_ring_ctx *ctx = req->ctx;
880 struct io_kiocb *nxt;
881 bool wake_ev = false;
883 /* Already got next link */
884 if (req->flags & REQ_F_LINK_NEXT)
888 * The list should never be empty when we are called here. But could
889 * potentially happen if the chain is messed up, check to be on the
892 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
894 list_del_init(&nxt->list);
896 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
897 (nxt->flags & REQ_F_TIMEOUT)) {
898 wake_ev |= io_link_cancel_timeout(nxt);
899 nxt = list_first_entry_or_null(&req->link_list,
900 struct io_kiocb, list);
901 req->flags &= ~REQ_F_LINK_TIMEOUT;
904 if (!list_empty(&req->link_list)) {
905 INIT_LIST_HEAD(&nxt->link_list);
906 list_splice(&req->link_list, &nxt->link_list);
907 nxt->flags |= REQ_F_LINK;
914 req->flags |= REQ_F_LINK_NEXT;
916 io_cqring_ev_posted(ctx);
920 * Called if REQ_F_LINK is set, and we fail the head request
922 static void io_fail_links(struct io_kiocb *req)
924 struct io_ring_ctx *ctx = req->ctx;
925 struct io_kiocb *link;
928 spin_lock_irqsave(&ctx->completion_lock, flags);
930 while (!list_empty(&req->link_list)) {
931 link = list_first_entry(&req->link_list, struct io_kiocb, list);
932 list_del_init(&link->list);
934 trace_io_uring_fail_link(req, link);
936 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
937 link->sqe->opcode == IORING_OP_LINK_TIMEOUT) {
938 io_link_cancel_timeout(link);
940 io_cqring_fill_event(link, -ECANCELED);
941 __io_double_put_req(link);
943 req->flags &= ~REQ_F_LINK_TIMEOUT;
946 io_commit_cqring(ctx);
947 spin_unlock_irqrestore(&ctx->completion_lock, flags);
948 io_cqring_ev_posted(ctx);
951 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
953 if (likely(!(req->flags & REQ_F_LINK)))
957 * If LINK is set, we have dependent requests in this chain. If we
958 * didn't fail this request, queue the first one up, moving any other
959 * dependencies to the next request. In case of failure, fail the rest
962 if (req->flags & REQ_F_FAIL_LINK) {
964 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
965 REQ_F_LINK_TIMEOUT) {
966 struct io_ring_ctx *ctx = req->ctx;
970 * If this is a timeout link, we could be racing with the
971 * timeout timer. Grab the completion lock for this case to
972 * protect against that.
974 spin_lock_irqsave(&ctx->completion_lock, flags);
975 io_req_link_next(req, nxt);
976 spin_unlock_irqrestore(&ctx->completion_lock, flags);
978 io_req_link_next(req, nxt);
982 static void io_free_req(struct io_kiocb *req)
984 struct io_kiocb *nxt = NULL;
986 io_req_find_next(req, &nxt);
990 io_queue_async_work(nxt);
994 * Drop reference to request, return next in chain (if there is one) if this
995 * was the last reference to this request.
997 __attribute__((nonnull))
998 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1000 io_req_find_next(req, nxtptr);
1002 if (refcount_dec_and_test(&req->refs))
1006 static void io_put_req(struct io_kiocb *req)
1008 if (refcount_dec_and_test(&req->refs))
1013 * Must only be used if we don't need to care about links, usually from
1014 * within the completion handling itself.
1016 static void __io_double_put_req(struct io_kiocb *req)
1018 /* drop both submit and complete references */
1019 if (refcount_sub_and_test(2, &req->refs))
1023 static void io_double_put_req(struct io_kiocb *req)
1025 /* drop both submit and complete references */
1026 if (refcount_sub_and_test(2, &req->refs))
1030 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1032 struct io_rings *rings = ctx->rings;
1035 * noflush == true is from the waitqueue handler, just ensure we wake
1036 * up the task, and the next invocation will flush the entries. We
1037 * cannot safely to it from here.
1039 if (noflush && !list_empty(&ctx->cq_overflow_list))
1042 io_cqring_overflow_flush(ctx, false);
1044 /* See comment at the top of this file */
1046 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
1049 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1051 struct io_rings *rings = ctx->rings;
1053 /* make sure SQ entry isn't read before tail */
1054 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1058 * Find and free completed poll iocbs
1060 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1061 struct list_head *done)
1063 void *reqs[IO_IOPOLL_BATCH];
1064 struct io_kiocb *req;
1068 while (!list_empty(done)) {
1069 req = list_first_entry(done, struct io_kiocb, list);
1070 list_del(&req->list);
1072 io_cqring_fill_event(req, req->result);
1075 if (refcount_dec_and_test(&req->refs)) {
1076 /* If we're not using fixed files, we have to pair the
1077 * completion part with the file put. Use regular
1078 * completions for those, only batch free for fixed
1079 * file and non-linked commands.
1082 (REQ_F_FIXED_FILE|REQ_F_LINK|REQ_F_FREE_SQE)) ==
1083 REQ_F_FIXED_FILE) && !io_is_fallback_req(req)) {
1084 reqs[to_free++] = req;
1085 if (to_free == ARRAY_SIZE(reqs))
1086 io_free_req_many(ctx, reqs, &to_free);
1093 io_commit_cqring(ctx);
1094 io_free_req_many(ctx, reqs, &to_free);
1097 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1100 struct io_kiocb *req, *tmp;
1106 * Only spin for completions if we don't have multiple devices hanging
1107 * off our complete list, and we're under the requested amount.
1109 spin = !ctx->poll_multi_file && *nr_events < min;
1112 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1113 struct kiocb *kiocb = &req->rw;
1116 * Move completed entries to our local list. If we find a
1117 * request that requires polling, break out and complete
1118 * the done list first, if we have entries there.
1120 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1121 list_move_tail(&req->list, &done);
1124 if (!list_empty(&done))
1127 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1136 if (!list_empty(&done))
1137 io_iopoll_complete(ctx, nr_events, &done);
1143 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
1144 * non-spinning poll check - we'll still enter the driver poll loop, but only
1145 * as a non-spinning completion check.
1147 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1150 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1153 ret = io_do_iopoll(ctx, nr_events, min);
1156 if (!min || *nr_events >= min)
1164 * We can't just wait for polled events to come to us, we have to actively
1165 * find and complete them.
1167 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1169 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1172 mutex_lock(&ctx->uring_lock);
1173 while (!list_empty(&ctx->poll_list)) {
1174 unsigned int nr_events = 0;
1176 io_iopoll_getevents(ctx, &nr_events, 1);
1179 * Ensure we allow local-to-the-cpu processing to take place,
1180 * in this case we need to ensure that we reap all events.
1184 mutex_unlock(&ctx->uring_lock);
1187 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1190 int iters = 0, ret = 0;
1196 * Don't enter poll loop if we already have events pending.
1197 * If we do, we can potentially be spinning for commands that
1198 * already triggered a CQE (eg in error).
1200 if (io_cqring_events(ctx, false))
1204 * If a submit got punted to a workqueue, we can have the
1205 * application entering polling for a command before it gets
1206 * issued. That app will hold the uring_lock for the duration
1207 * of the poll right here, so we need to take a breather every
1208 * now and then to ensure that the issue has a chance to add
1209 * the poll to the issued list. Otherwise we can spin here
1210 * forever, while the workqueue is stuck trying to acquire the
1213 if (!(++iters & 7)) {
1214 mutex_unlock(&ctx->uring_lock);
1215 mutex_lock(&ctx->uring_lock);
1218 if (*nr_events < min)
1219 tmin = min - *nr_events;
1221 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1225 } while (min && !*nr_events && !need_resched());
1230 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1236 * We disallow the app entering submit/complete with polling, but we
1237 * still need to lock the ring to prevent racing with polled issue
1238 * that got punted to a workqueue.
1240 mutex_lock(&ctx->uring_lock);
1241 ret = __io_iopoll_check(ctx, nr_events, min);
1242 mutex_unlock(&ctx->uring_lock);
1246 static void kiocb_end_write(struct io_kiocb *req)
1249 * Tell lockdep we inherited freeze protection from submission
1252 if (req->flags & REQ_F_ISREG) {
1253 struct inode *inode = file_inode(req->file);
1255 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1257 file_end_write(req->file);
1260 static void io_complete_rw_common(struct kiocb *kiocb, long res)
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;
1269 io_cqring_add_event(req, res);
1272 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1274 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1276 io_complete_rw_common(kiocb, res);
1280 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1282 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1283 struct io_kiocb *nxt = NULL;
1285 io_complete_rw_common(kiocb, res);
1286 io_put_req_find_next(req, &nxt);
1291 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1293 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1295 if (kiocb->ki_flags & IOCB_WRITE)
1296 kiocb_end_write(req);
1298 if ((req->flags & REQ_F_LINK) && res != req->result)
1299 req->flags |= REQ_F_FAIL_LINK;
1302 req->flags |= REQ_F_IOPOLL_COMPLETED;
1306 * After the iocb has been issued, it's safe to be found on the poll list.
1307 * Adding the kiocb to the list AFTER submission ensures that we don't
1308 * find it from a io_iopoll_getevents() thread before the issuer is done
1309 * accessing the kiocb cookie.
1311 static void io_iopoll_req_issued(struct io_kiocb *req)
1313 struct io_ring_ctx *ctx = req->ctx;
1316 * Track whether we have multiple files in our lists. This will impact
1317 * how we do polling eventually, not spinning if we're on potentially
1318 * different devices.
1320 if (list_empty(&ctx->poll_list)) {
1321 ctx->poll_multi_file = false;
1322 } else if (!ctx->poll_multi_file) {
1323 struct io_kiocb *list_req;
1325 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1327 if (list_req->rw.ki_filp != req->rw.ki_filp)
1328 ctx->poll_multi_file = true;
1332 * For fast devices, IO may have already completed. If it has, add
1333 * it to the front so we find it first.
1335 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1336 list_add(&req->list, &ctx->poll_list);
1338 list_add_tail(&req->list, &ctx->poll_list);
1341 static void io_file_put(struct io_submit_state *state)
1344 int diff = state->has_refs - state->used_refs;
1347 fput_many(state->file, diff);
1353 * Get as many references to a file as we have IOs left in this submission,
1354 * assuming most submissions are for one file, or at least that each file
1355 * has more than one submission.
1357 static struct file *io_file_get(struct io_submit_state *state, int fd)
1363 if (state->fd == fd) {
1370 state->file = fget_many(fd, state->ios_left);
1375 state->has_refs = state->ios_left;
1376 state->used_refs = 1;
1382 * If we tracked the file through the SCM inflight mechanism, we could support
1383 * any file. For now, just ensure that anything potentially problematic is done
1386 static bool io_file_supports_async(struct file *file)
1388 umode_t mode = file_inode(file)->i_mode;
1390 if (S_ISBLK(mode) || S_ISCHR(mode))
1392 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1398 static int io_prep_rw(struct io_kiocb *req, bool force_nonblock)
1400 const struct io_uring_sqe *sqe = req->sqe;
1401 struct io_ring_ctx *ctx = req->ctx;
1402 struct kiocb *kiocb = &req->rw;
1409 if (S_ISREG(file_inode(req->file)->i_mode))
1410 req->flags |= REQ_F_ISREG;
1413 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1414 * we know to async punt it even if it was opened O_NONBLOCK
1416 if (force_nonblock && !io_file_supports_async(req->file)) {
1417 req->flags |= REQ_F_MUST_PUNT;
1421 kiocb->ki_pos = READ_ONCE(sqe->off);
1422 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1423 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1425 ioprio = READ_ONCE(sqe->ioprio);
1427 ret = ioprio_check_cap(ioprio);
1431 kiocb->ki_ioprio = ioprio;
1433 kiocb->ki_ioprio = get_current_ioprio();
1435 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1439 /* don't allow async punt if RWF_NOWAIT was requested */
1440 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1441 (req->file->f_flags & O_NONBLOCK))
1442 req->flags |= REQ_F_NOWAIT;
1445 kiocb->ki_flags |= IOCB_NOWAIT;
1447 if (ctx->flags & IORING_SETUP_IOPOLL) {
1448 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1449 !kiocb->ki_filp->f_op->iopoll)
1452 kiocb->ki_flags |= IOCB_HIPRI;
1453 kiocb->ki_complete = io_complete_rw_iopoll;
1456 if (kiocb->ki_flags & IOCB_HIPRI)
1458 kiocb->ki_complete = io_complete_rw;
1463 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1469 case -ERESTARTNOINTR:
1470 case -ERESTARTNOHAND:
1471 case -ERESTART_RESTARTBLOCK:
1473 * We can't just restart the syscall, since previously
1474 * submitted sqes may already be in progress. Just fail this
1480 kiocb->ki_complete(kiocb, ret, 0);
1484 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1487 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1488 *nxt = __io_complete_rw(kiocb, ret);
1490 io_rw_done(kiocb, ret);
1493 static ssize_t io_import_fixed(struct io_ring_ctx *ctx, int rw,
1494 const struct io_uring_sqe *sqe,
1495 struct iov_iter *iter)
1497 size_t len = READ_ONCE(sqe->len);
1498 struct io_mapped_ubuf *imu;
1499 unsigned index, buf_index;
1503 /* attempt to use fixed buffers without having provided iovecs */
1504 if (unlikely(!ctx->user_bufs))
1507 buf_index = READ_ONCE(sqe->buf_index);
1508 if (unlikely(buf_index >= ctx->nr_user_bufs))
1511 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1512 imu = &ctx->user_bufs[index];
1513 buf_addr = READ_ONCE(sqe->addr);
1516 if (buf_addr + len < buf_addr)
1518 /* not inside the mapped region */
1519 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1523 * May not be a start of buffer, set size appropriately
1524 * and advance us to the beginning.
1526 offset = buf_addr - imu->ubuf;
1527 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1531 * Don't use iov_iter_advance() here, as it's really slow for
1532 * using the latter parts of a big fixed buffer - it iterates
1533 * over each segment manually. We can cheat a bit here, because
1536 * 1) it's a BVEC iter, we set it up
1537 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1538 * first and last bvec
1540 * So just find our index, and adjust the iterator afterwards.
1541 * If the offset is within the first bvec (or the whole first
1542 * bvec, just use iov_iter_advance(). This makes it easier
1543 * since we can just skip the first segment, which may not
1544 * be PAGE_SIZE aligned.
1546 const struct bio_vec *bvec = imu->bvec;
1548 if (offset <= bvec->bv_len) {
1549 iov_iter_advance(iter, offset);
1551 unsigned long seg_skip;
1553 /* skip first vec */
1554 offset -= bvec->bv_len;
1555 seg_skip = 1 + (offset >> PAGE_SHIFT);
1557 iter->bvec = bvec + seg_skip;
1558 iter->nr_segs -= seg_skip;
1559 iter->count -= bvec->bv_len + offset;
1560 iter->iov_offset = offset & ~PAGE_MASK;
1567 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1568 struct iovec **iovec, struct iov_iter *iter)
1570 const struct io_uring_sqe *sqe = req->sqe;
1571 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1572 size_t sqe_len = READ_ONCE(sqe->len);
1576 * We're reading ->opcode for the second time, but the first read
1577 * doesn't care whether it's _FIXED or not, so it doesn't matter
1578 * whether ->opcode changes concurrently. The first read does care
1579 * about whether it is a READ or a WRITE, so we don't trust this read
1580 * for that purpose and instead let the caller pass in the read/write
1583 opcode = READ_ONCE(sqe->opcode);
1584 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1586 return io_import_fixed(req->ctx, rw, sqe, iter);
1592 #ifdef CONFIG_COMPAT
1593 if (req->ctx->compat)
1594 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1598 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1602 * For files that don't have ->read_iter() and ->write_iter(), handle them
1603 * by looping over ->read() or ->write() manually.
1605 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1606 struct iov_iter *iter)
1611 * Don't support polled IO through this interface, and we can't
1612 * support non-blocking either. For the latter, this just causes
1613 * the kiocb to be handled from an async context.
1615 if (kiocb->ki_flags & IOCB_HIPRI)
1617 if (kiocb->ki_flags & IOCB_NOWAIT)
1620 while (iov_iter_count(iter)) {
1624 if (!iov_iter_is_bvec(iter)) {
1625 iovec = iov_iter_iovec(iter);
1627 /* fixed buffers import bvec */
1628 iovec.iov_base = kmap(iter->bvec->bv_page)
1630 iovec.iov_len = min(iter->count,
1631 iter->bvec->bv_len - iter->iov_offset);
1635 nr = file->f_op->read(file, iovec.iov_base,
1636 iovec.iov_len, &kiocb->ki_pos);
1638 nr = file->f_op->write(file, iovec.iov_base,
1639 iovec.iov_len, &kiocb->ki_pos);
1642 if (iov_iter_is_bvec(iter))
1643 kunmap(iter->bvec->bv_page);
1651 if (nr != iovec.iov_len)
1653 iov_iter_advance(iter, nr);
1659 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1660 bool force_nonblock)
1662 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1663 struct kiocb *kiocb = &req->rw;
1664 struct iov_iter iter;
1667 ssize_t read_size, ret;
1669 ret = io_prep_rw(req, force_nonblock);
1672 file = kiocb->ki_filp;
1674 if (unlikely(!(file->f_mode & FMODE_READ)))
1677 ret = io_import_iovec(READ, req, &iovec, &iter);
1682 if (req->flags & REQ_F_LINK)
1683 req->result = read_size;
1685 iov_count = iov_iter_count(&iter);
1686 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1690 if (file->f_op->read_iter)
1691 ret2 = call_read_iter(file, kiocb, &iter);
1693 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1696 * In case of a short read, punt to async. This can happen
1697 * if we have data partially cached. Alternatively we can
1698 * return the short read, in which case the application will
1699 * need to issue another SQE and wait for it. That SQE will
1700 * need async punt anyway, so it's more efficient to do it
1703 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1704 (req->flags & REQ_F_ISREG) &&
1705 ret2 > 0 && ret2 < read_size)
1707 /* Catch -EAGAIN return for forced non-blocking submission */
1708 if (!force_nonblock || ret2 != -EAGAIN)
1709 kiocb_done(kiocb, ret2, nxt, req->in_async);
1717 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1718 bool force_nonblock)
1720 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1721 struct kiocb *kiocb = &req->rw;
1722 struct iov_iter iter;
1727 ret = io_prep_rw(req, force_nonblock);
1731 file = kiocb->ki_filp;
1732 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1735 ret = io_import_iovec(WRITE, req, &iovec, &iter);
1739 if (req->flags & REQ_F_LINK)
1742 iov_count = iov_iter_count(&iter);
1745 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
1748 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1753 * Open-code file_start_write here to grab freeze protection,
1754 * which will be released by another thread in
1755 * io_complete_rw(). Fool lockdep by telling it the lock got
1756 * released so that it doesn't complain about the held lock when
1757 * we return to userspace.
1759 if (req->flags & REQ_F_ISREG) {
1760 __sb_start_write(file_inode(file)->i_sb,
1761 SB_FREEZE_WRITE, true);
1762 __sb_writers_release(file_inode(file)->i_sb,
1765 kiocb->ki_flags |= IOCB_WRITE;
1767 if (file->f_op->write_iter)
1768 ret2 = call_write_iter(file, kiocb, &iter);
1770 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1771 if (!force_nonblock || ret2 != -EAGAIN)
1772 kiocb_done(kiocb, ret2, nxt, req->in_async);
1782 * IORING_OP_NOP just posts a completion event, nothing else.
1784 static int io_nop(struct io_kiocb *req)
1786 struct io_ring_ctx *ctx = req->ctx;
1788 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1791 io_cqring_add_event(req, 0);
1796 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1798 struct io_ring_ctx *ctx = req->ctx;
1803 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1805 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1811 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1812 struct io_kiocb **nxt, bool force_nonblock)
1814 loff_t sqe_off = READ_ONCE(sqe->off);
1815 loff_t sqe_len = READ_ONCE(sqe->len);
1816 loff_t end = sqe_off + sqe_len;
1817 unsigned fsync_flags;
1820 fsync_flags = READ_ONCE(sqe->fsync_flags);
1821 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1824 ret = io_prep_fsync(req, sqe);
1828 /* fsync always requires a blocking context */
1832 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1833 end > 0 ? end : LLONG_MAX,
1834 fsync_flags & IORING_FSYNC_DATASYNC);
1836 if (ret < 0 && (req->flags & REQ_F_LINK))
1837 req->flags |= REQ_F_FAIL_LINK;
1838 io_cqring_add_event(req, ret);
1839 io_put_req_find_next(req, nxt);
1843 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1845 struct io_ring_ctx *ctx = req->ctx;
1851 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1853 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1859 static int io_sync_file_range(struct io_kiocb *req,
1860 const struct io_uring_sqe *sqe,
1861 struct io_kiocb **nxt,
1862 bool force_nonblock)
1869 ret = io_prep_sfr(req, sqe);
1873 /* sync_file_range always requires a blocking context */
1877 sqe_off = READ_ONCE(sqe->off);
1878 sqe_len = READ_ONCE(sqe->len);
1879 flags = READ_ONCE(sqe->sync_range_flags);
1881 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1883 if (ret < 0 && (req->flags & REQ_F_LINK))
1884 req->flags |= REQ_F_FAIL_LINK;
1885 io_cqring_add_event(req, ret);
1886 io_put_req_find_next(req, nxt);
1890 #if defined(CONFIG_NET)
1891 static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1892 struct io_kiocb **nxt, bool force_nonblock,
1893 long (*fn)(struct socket *, struct user_msghdr __user *,
1896 struct socket *sock;
1899 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1902 sock = sock_from_file(req->file, &ret);
1904 struct user_msghdr __user *msg;
1907 flags = READ_ONCE(sqe->msg_flags);
1908 if (flags & MSG_DONTWAIT)
1909 req->flags |= REQ_F_NOWAIT;
1910 else if (force_nonblock)
1911 flags |= MSG_DONTWAIT;
1913 msg = (struct user_msghdr __user *) (unsigned long)
1914 READ_ONCE(sqe->addr);
1916 ret = fn(sock, msg, flags);
1917 if (force_nonblock && ret == -EAGAIN)
1921 io_cqring_add_event(req, ret);
1922 if (ret < 0 && (req->flags & REQ_F_LINK))
1923 req->flags |= REQ_F_FAIL_LINK;
1924 io_put_req_find_next(req, nxt);
1929 static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1930 struct io_kiocb **nxt, bool force_nonblock)
1932 #if defined(CONFIG_NET)
1933 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1934 __sys_sendmsg_sock);
1940 static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1941 struct io_kiocb **nxt, bool force_nonblock)
1943 #if defined(CONFIG_NET)
1944 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1945 __sys_recvmsg_sock);
1951 static int io_accept(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1952 struct io_kiocb **nxt, bool force_nonblock)
1954 #if defined(CONFIG_NET)
1955 struct sockaddr __user *addr;
1956 int __user *addr_len;
1957 unsigned file_flags;
1960 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
1962 if (sqe->ioprio || sqe->len || sqe->buf_index)
1965 addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
1966 addr_len = (int __user *) (unsigned long) READ_ONCE(sqe->addr2);
1967 flags = READ_ONCE(sqe->accept_flags);
1968 file_flags = force_nonblock ? O_NONBLOCK : 0;
1970 ret = __sys_accept4_file(req->file, file_flags, addr, addr_len, flags);
1971 if (ret == -EAGAIN && force_nonblock) {
1972 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
1975 if (ret == -ERESTARTSYS)
1977 if (ret < 0 && (req->flags & REQ_F_LINK))
1978 req->flags |= REQ_F_FAIL_LINK;
1979 io_cqring_add_event(req, ret);
1980 io_put_req_find_next(req, nxt);
1987 static int io_connect(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1988 struct io_kiocb **nxt, bool force_nonblock)
1990 #if defined(CONFIG_NET)
1991 struct sockaddr __user *addr;
1992 unsigned file_flags;
1995 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
1997 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
2000 addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
2001 addr_len = READ_ONCE(sqe->addr2);
2002 file_flags = force_nonblock ? O_NONBLOCK : 0;
2004 ret = __sys_connect_file(req->file, addr, addr_len, file_flags);
2005 if (ret == -EAGAIN && force_nonblock)
2007 if (ret == -ERESTARTSYS)
2009 if (ret < 0 && (req->flags & REQ_F_LINK))
2010 req->flags |= REQ_F_FAIL_LINK;
2011 io_cqring_add_event(req, ret);
2012 io_put_req_find_next(req, nxt);
2019 static inline void io_poll_remove_req(struct io_kiocb *req)
2021 if (!RB_EMPTY_NODE(&req->rb_node)) {
2022 rb_erase(&req->rb_node, &req->ctx->cancel_tree);
2023 RB_CLEAR_NODE(&req->rb_node);
2027 static void io_poll_remove_one(struct io_kiocb *req)
2029 struct io_poll_iocb *poll = &req->poll;
2031 spin_lock(&poll->head->lock);
2032 WRITE_ONCE(poll->canceled, true);
2033 if (!list_empty(&poll->wait->entry)) {
2034 list_del_init(&poll->wait->entry);
2035 io_queue_async_work(req);
2037 spin_unlock(&poll->head->lock);
2038 io_poll_remove_req(req);
2041 static void io_poll_remove_all(struct io_ring_ctx *ctx)
2043 struct rb_node *node;
2044 struct io_kiocb *req;
2046 spin_lock_irq(&ctx->completion_lock);
2047 while ((node = rb_first(&ctx->cancel_tree)) != NULL) {
2048 req = rb_entry(node, struct io_kiocb, rb_node);
2049 io_poll_remove_one(req);
2051 spin_unlock_irq(&ctx->completion_lock);
2054 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
2056 struct rb_node *p, *parent = NULL;
2057 struct io_kiocb *req;
2059 p = ctx->cancel_tree.rb_node;
2062 req = rb_entry(parent, struct io_kiocb, rb_node);
2063 if (sqe_addr < req->user_data) {
2065 } else if (sqe_addr > req->user_data) {
2068 io_poll_remove_one(req);
2077 * Find a running poll command that matches one specified in sqe->addr,
2078 * and remove it if found.
2080 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2082 struct io_ring_ctx *ctx = req->ctx;
2085 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2087 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
2091 spin_lock_irq(&ctx->completion_lock);
2092 ret = io_poll_cancel(ctx, READ_ONCE(sqe->addr));
2093 spin_unlock_irq(&ctx->completion_lock);
2095 io_cqring_add_event(req, ret);
2096 if (ret < 0 && (req->flags & REQ_F_LINK))
2097 req->flags |= REQ_F_FAIL_LINK;
2102 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
2104 struct io_ring_ctx *ctx = req->ctx;
2106 req->poll.done = true;
2107 kfree(req->poll.wait);
2109 io_cqring_fill_event(req, error);
2111 io_cqring_fill_event(req, mangle_poll(mask));
2112 io_commit_cqring(ctx);
2115 static void io_poll_complete_work(struct io_wq_work **workptr)
2117 struct io_wq_work *work = *workptr;
2118 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2119 struct io_poll_iocb *poll = &req->poll;
2120 struct poll_table_struct pt = { ._key = poll->events };
2121 struct io_ring_ctx *ctx = req->ctx;
2122 struct io_kiocb *nxt = NULL;
2126 if (work->flags & IO_WQ_WORK_CANCEL) {
2127 WRITE_ONCE(poll->canceled, true);
2129 } else if (READ_ONCE(poll->canceled)) {
2133 if (ret != -ECANCELED)
2134 mask = vfs_poll(poll->file, &pt) & poll->events;
2137 * Note that ->ki_cancel callers also delete iocb from active_reqs after
2138 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
2139 * synchronize with them. In the cancellation case the list_del_init
2140 * itself is not actually needed, but harmless so we keep it in to
2141 * avoid further branches in the fast path.
2143 spin_lock_irq(&ctx->completion_lock);
2144 if (!mask && ret != -ECANCELED) {
2145 add_wait_queue(poll->head, poll->wait);
2146 spin_unlock_irq(&ctx->completion_lock);
2149 io_poll_remove_req(req);
2150 io_poll_complete(req, mask, ret);
2151 spin_unlock_irq(&ctx->completion_lock);
2153 io_cqring_ev_posted(ctx);
2155 if (ret < 0 && req->flags & REQ_F_LINK)
2156 req->flags |= REQ_F_FAIL_LINK;
2157 io_put_req_find_next(req, &nxt);
2159 *workptr = &nxt->work;
2162 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2165 struct io_poll_iocb *poll = wait->private;
2166 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2167 struct io_ring_ctx *ctx = req->ctx;
2168 __poll_t mask = key_to_poll(key);
2169 unsigned long flags;
2171 /* for instances that support it check for an event match first: */
2172 if (mask && !(mask & poll->events))
2175 list_del_init(&poll->wait->entry);
2178 * Run completion inline if we can. We're using trylock here because
2179 * we are violating the completion_lock -> poll wq lock ordering.
2180 * If we have a link timeout we're going to need the completion_lock
2181 * for finalizing the request, mark us as having grabbed that already.
2183 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2184 io_poll_remove_req(req);
2185 io_poll_complete(req, mask, 0);
2186 req->flags |= REQ_F_COMP_LOCKED;
2188 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2190 io_cqring_ev_posted(ctx);
2192 io_queue_async_work(req);
2198 struct io_poll_table {
2199 struct poll_table_struct pt;
2200 struct io_kiocb *req;
2204 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2205 struct poll_table_struct *p)
2207 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2209 if (unlikely(pt->req->poll.head)) {
2210 pt->error = -EINVAL;
2215 pt->req->poll.head = head;
2216 add_wait_queue(head, pt->req->poll.wait);
2219 static void io_poll_req_insert(struct io_kiocb *req)
2221 struct io_ring_ctx *ctx = req->ctx;
2222 struct rb_node **p = &ctx->cancel_tree.rb_node;
2223 struct rb_node *parent = NULL;
2224 struct io_kiocb *tmp;
2228 tmp = rb_entry(parent, struct io_kiocb, rb_node);
2229 if (req->user_data < tmp->user_data)
2232 p = &(*p)->rb_right;
2234 rb_link_node(&req->rb_node, parent, p);
2235 rb_insert_color(&req->rb_node, &ctx->cancel_tree);
2238 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2239 struct io_kiocb **nxt)
2241 struct io_poll_iocb *poll = &req->poll;
2242 struct io_ring_ctx *ctx = req->ctx;
2243 struct io_poll_table ipt;
2244 bool cancel = false;
2248 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2250 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2255 poll->wait = kmalloc(sizeof(*poll->wait), GFP_KERNEL);
2260 INIT_IO_WORK(&req->work, io_poll_complete_work);
2261 events = READ_ONCE(sqe->poll_events);
2262 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2263 RB_CLEAR_NODE(&req->rb_node);
2267 poll->canceled = false;
2269 ipt.pt._qproc = io_poll_queue_proc;
2270 ipt.pt._key = poll->events;
2272 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2274 /* initialized the list so that we can do list_empty checks */
2275 INIT_LIST_HEAD(&poll->wait->entry);
2276 init_waitqueue_func_entry(poll->wait, io_poll_wake);
2277 poll->wait->private = poll;
2279 INIT_LIST_HEAD(&req->list);
2281 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
2283 spin_lock_irq(&ctx->completion_lock);
2284 if (likely(poll->head)) {
2285 spin_lock(&poll->head->lock);
2286 if (unlikely(list_empty(&poll->wait->entry))) {
2292 if (mask || ipt.error)
2293 list_del_init(&poll->wait->entry);
2295 WRITE_ONCE(poll->canceled, true);
2296 else if (!poll->done) /* actually waiting for an event */
2297 io_poll_req_insert(req);
2298 spin_unlock(&poll->head->lock);
2300 if (mask) { /* no async, we'd stolen it */
2302 io_poll_complete(req, mask, 0);
2304 spin_unlock_irq(&ctx->completion_lock);
2307 io_cqring_ev_posted(ctx);
2308 io_put_req_find_next(req, nxt);
2313 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
2315 struct io_timeout_data *data = container_of(timer,
2316 struct io_timeout_data, timer);
2317 struct io_kiocb *req = data->req;
2318 struct io_ring_ctx *ctx = req->ctx;
2319 unsigned long flags;
2321 atomic_inc(&ctx->cq_timeouts);
2323 spin_lock_irqsave(&ctx->completion_lock, flags);
2325 * We could be racing with timeout deletion. If the list is empty,
2326 * then timeout lookup already found it and will be handling it.
2328 if (!list_empty(&req->list)) {
2329 struct io_kiocb *prev;
2332 * Adjust the reqs sequence before the current one because it
2333 * will consume a slot in the cq_ring and the the cq_tail
2334 * pointer will be increased, otherwise other timeout reqs may
2335 * return in advance without waiting for enough wait_nr.
2338 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
2340 list_del_init(&req->list);
2343 io_cqring_fill_event(req, -ETIME);
2344 io_commit_cqring(ctx);
2345 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2347 io_cqring_ev_posted(ctx);
2348 if (req->flags & REQ_F_LINK)
2349 req->flags |= REQ_F_FAIL_LINK;
2351 return HRTIMER_NORESTART;
2354 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
2356 struct io_kiocb *req;
2359 list_for_each_entry(req, &ctx->timeout_list, list) {
2360 if (user_data == req->user_data) {
2361 list_del_init(&req->list);
2370 ret = hrtimer_try_to_cancel(&req->timeout.data->timer);
2374 if (req->flags & REQ_F_LINK)
2375 req->flags |= REQ_F_FAIL_LINK;
2376 io_cqring_fill_event(req, -ECANCELED);
2382 * Remove or update an existing timeout command
2384 static int io_timeout_remove(struct io_kiocb *req,
2385 const struct io_uring_sqe *sqe)
2387 struct io_ring_ctx *ctx = req->ctx;
2391 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2393 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2395 flags = READ_ONCE(sqe->timeout_flags);
2399 spin_lock_irq(&ctx->completion_lock);
2400 ret = io_timeout_cancel(ctx, READ_ONCE(sqe->addr));
2402 io_cqring_fill_event(req, ret);
2403 io_commit_cqring(ctx);
2404 spin_unlock_irq(&ctx->completion_lock);
2405 io_cqring_ev_posted(ctx);
2406 if (ret < 0 && req->flags & REQ_F_LINK)
2407 req->flags |= REQ_F_FAIL_LINK;
2412 static int io_timeout_setup(struct io_kiocb *req)
2414 const struct io_uring_sqe *sqe = req->sqe;
2415 struct io_timeout_data *data;
2418 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2420 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
2422 flags = READ_ONCE(sqe->timeout_flags);
2423 if (flags & ~IORING_TIMEOUT_ABS)
2426 data = kzalloc(sizeof(struct io_timeout_data), GFP_KERNEL);
2430 req->timeout.data = data;
2431 req->flags |= REQ_F_TIMEOUT;
2433 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
2436 if (flags & IORING_TIMEOUT_ABS)
2437 data->mode = HRTIMER_MODE_ABS;
2439 data->mode = HRTIMER_MODE_REL;
2441 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
2445 static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2448 struct io_ring_ctx *ctx = req->ctx;
2449 struct io_timeout_data *data;
2450 struct list_head *entry;
2454 ret = io_timeout_setup(req);
2455 /* common setup allows flags (like links) set, we don't */
2456 if (!ret && sqe->flags)
2462 * sqe->off holds how many events that need to occur for this
2463 * timeout event to be satisfied. If it isn't set, then this is
2464 * a pure timeout request, sequence isn't used.
2466 count = READ_ONCE(sqe->off);
2468 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2469 spin_lock_irq(&ctx->completion_lock);
2470 entry = ctx->timeout_list.prev;
2474 req->sequence = ctx->cached_sq_head + count - 1;
2475 req->timeout.data->seq_offset = count;
2478 * Insertion sort, ensuring the first entry in the list is always
2479 * the one we need first.
2481 spin_lock_irq(&ctx->completion_lock);
2482 list_for_each_prev(entry, &ctx->timeout_list) {
2483 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2484 unsigned nxt_sq_head;
2485 long long tmp, tmp_nxt;
2486 u32 nxt_offset = nxt->timeout.data->seq_offset;
2488 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2492 * Since cached_sq_head + count - 1 can overflow, use type long
2495 tmp = (long long)ctx->cached_sq_head + count - 1;
2496 nxt_sq_head = nxt->sequence - nxt_offset + 1;
2497 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
2500 * cached_sq_head may overflow, and it will never overflow twice
2501 * once there is some timeout req still be valid.
2503 if (ctx->cached_sq_head < nxt_sq_head)
2510 * Sequence of reqs after the insert one and itself should
2511 * be adjusted because each timeout req consumes a slot.
2516 req->sequence -= span;
2518 list_add(&req->list, entry);
2519 data = req->timeout.data;
2520 data->timer.function = io_timeout_fn;
2521 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
2522 spin_unlock_irq(&ctx->completion_lock);
2526 static bool io_cancel_cb(struct io_wq_work *work, void *data)
2528 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2530 return req->user_data == (unsigned long) data;
2533 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
2535 enum io_wq_cancel cancel_ret;
2538 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
2539 switch (cancel_ret) {
2540 case IO_WQ_CANCEL_OK:
2543 case IO_WQ_CANCEL_RUNNING:
2546 case IO_WQ_CANCEL_NOTFOUND:
2554 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
2555 struct io_kiocb *req, __u64 sqe_addr,
2556 struct io_kiocb **nxt, int success_ret)
2558 unsigned long flags;
2561 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
2562 if (ret != -ENOENT) {
2563 spin_lock_irqsave(&ctx->completion_lock, flags);
2567 spin_lock_irqsave(&ctx->completion_lock, flags);
2568 ret = io_timeout_cancel(ctx, sqe_addr);
2571 ret = io_poll_cancel(ctx, sqe_addr);
2575 io_cqring_fill_event(req, ret);
2576 io_commit_cqring(ctx);
2577 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2578 io_cqring_ev_posted(ctx);
2580 if (ret < 0 && (req->flags & REQ_F_LINK))
2581 req->flags |= REQ_F_FAIL_LINK;
2582 io_put_req_find_next(req, nxt);
2585 static int io_async_cancel(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2586 struct io_kiocb **nxt)
2588 struct io_ring_ctx *ctx = req->ctx;
2590 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2592 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
2596 io_async_find_and_cancel(ctx, req, READ_ONCE(sqe->addr), nxt, 0);
2600 static int io_req_defer(struct io_kiocb *req)
2602 struct io_uring_sqe *sqe_copy;
2603 struct io_ring_ctx *ctx = req->ctx;
2605 /* Still need defer if there is pending req in defer list. */
2606 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
2609 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2613 spin_lock_irq(&ctx->completion_lock);
2614 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
2615 spin_unlock_irq(&ctx->completion_lock);
2620 memcpy(sqe_copy, req->sqe, sizeof(*sqe_copy));
2621 req->flags |= REQ_F_FREE_SQE;
2622 req->sqe = sqe_copy;
2624 trace_io_uring_defer(ctx, req, req->user_data);
2625 list_add_tail(&req->list, &ctx->defer_list);
2626 spin_unlock_irq(&ctx->completion_lock);
2627 return -EIOCBQUEUED;
2630 __attribute__((nonnull))
2631 static int io_issue_sqe(struct io_kiocb *req, struct io_kiocb **nxt,
2632 bool force_nonblock)
2635 struct io_ring_ctx *ctx = req->ctx;
2637 opcode = READ_ONCE(req->sqe->opcode);
2642 case IORING_OP_READV:
2643 if (unlikely(req->sqe->buf_index))
2645 ret = io_read(req, nxt, force_nonblock);
2647 case IORING_OP_WRITEV:
2648 if (unlikely(req->sqe->buf_index))
2650 ret = io_write(req, nxt, force_nonblock);
2652 case IORING_OP_READ_FIXED:
2653 ret = io_read(req, nxt, force_nonblock);
2655 case IORING_OP_WRITE_FIXED:
2656 ret = io_write(req, nxt, force_nonblock);
2658 case IORING_OP_FSYNC:
2659 ret = io_fsync(req, req->sqe, nxt, force_nonblock);
2661 case IORING_OP_POLL_ADD:
2662 ret = io_poll_add(req, req->sqe, nxt);
2664 case IORING_OP_POLL_REMOVE:
2665 ret = io_poll_remove(req, req->sqe);
2667 case IORING_OP_SYNC_FILE_RANGE:
2668 ret = io_sync_file_range(req, req->sqe, nxt, force_nonblock);
2670 case IORING_OP_SENDMSG:
2671 ret = io_sendmsg(req, req->sqe, nxt, force_nonblock);
2673 case IORING_OP_RECVMSG:
2674 ret = io_recvmsg(req, req->sqe, nxt, force_nonblock);
2676 case IORING_OP_TIMEOUT:
2677 ret = io_timeout(req, req->sqe);
2679 case IORING_OP_TIMEOUT_REMOVE:
2680 ret = io_timeout_remove(req, req->sqe);
2682 case IORING_OP_ACCEPT:
2683 ret = io_accept(req, req->sqe, nxt, force_nonblock);
2685 case IORING_OP_CONNECT:
2686 ret = io_connect(req, req->sqe, nxt, force_nonblock);
2688 case IORING_OP_ASYNC_CANCEL:
2689 ret = io_async_cancel(req, req->sqe, nxt);
2699 if (ctx->flags & IORING_SETUP_IOPOLL) {
2700 if (req->result == -EAGAIN)
2703 /* workqueue context doesn't hold uring_lock, grab it now */
2705 mutex_lock(&ctx->uring_lock);
2706 io_iopoll_req_issued(req);
2708 mutex_unlock(&ctx->uring_lock);
2714 static void io_link_work_cb(struct io_wq_work **workptr)
2716 struct io_wq_work *work = *workptr;
2717 struct io_kiocb *link = work->data;
2719 io_queue_linked_timeout(link);
2720 work->func = io_wq_submit_work;
2723 static void io_wq_submit_work(struct io_wq_work **workptr)
2725 struct io_wq_work *work = *workptr;
2726 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2727 struct io_kiocb *nxt = NULL;
2730 /* Ensure we clear previously set non-block flag */
2731 req->rw.ki_flags &= ~IOCB_NOWAIT;
2733 if (work->flags & IO_WQ_WORK_CANCEL)
2737 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
2738 req->in_async = true;
2740 ret = io_issue_sqe(req, &nxt, false);
2742 * We can get EAGAIN for polled IO even though we're
2743 * forcing a sync submission from here, since we can't
2744 * wait for request slots on the block side.
2752 /* drop submission reference */
2756 if (req->flags & REQ_F_LINK)
2757 req->flags |= REQ_F_FAIL_LINK;
2758 io_cqring_add_event(req, ret);
2762 /* if a dependent link is ready, pass it back */
2764 struct io_kiocb *link;
2766 io_prep_async_work(nxt, &link);
2767 *workptr = &nxt->work;
2769 nxt->work.flags |= IO_WQ_WORK_CB;
2770 nxt->work.func = io_link_work_cb;
2771 nxt->work.data = link;
2776 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2778 int op = READ_ONCE(sqe->opcode);
2782 case IORING_OP_POLL_REMOVE:
2783 case IORING_OP_TIMEOUT:
2784 case IORING_OP_TIMEOUT_REMOVE:
2785 case IORING_OP_ASYNC_CANCEL:
2786 case IORING_OP_LINK_TIMEOUT:
2793 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
2796 struct fixed_file_table *table;
2798 table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
2799 return table->files[index & IORING_FILE_TABLE_MASK];
2802 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req)
2804 struct io_ring_ctx *ctx = req->ctx;
2808 flags = READ_ONCE(req->sqe->flags);
2809 fd = READ_ONCE(req->sqe->fd);
2811 if (flags & IOSQE_IO_DRAIN)
2812 req->flags |= REQ_F_IO_DRAIN;
2814 if (!io_op_needs_file(req->sqe))
2817 if (flags & IOSQE_FIXED_FILE) {
2818 if (unlikely(!ctx->file_table ||
2819 (unsigned) fd >= ctx->nr_user_files))
2821 fd = array_index_nospec(fd, ctx->nr_user_files);
2822 req->file = io_file_from_index(ctx, fd);
2825 req->flags |= REQ_F_FIXED_FILE;
2827 if (req->needs_fixed_file)
2829 trace_io_uring_file_get(ctx, fd);
2830 req->file = io_file_get(state, fd);
2831 if (unlikely(!req->file))
2838 static int io_grab_files(struct io_kiocb *req)
2841 struct io_ring_ctx *ctx = req->ctx;
2844 spin_lock_irq(&ctx->inflight_lock);
2846 * We use the f_ops->flush() handler to ensure that we can flush
2847 * out work accessing these files if the fd is closed. Check if
2848 * the fd has changed since we started down this path, and disallow
2849 * this operation if it has.
2851 if (fcheck(req->ring_fd) == req->ring_file) {
2852 list_add(&req->inflight_entry, &ctx->inflight_list);
2853 req->flags |= REQ_F_INFLIGHT;
2854 req->work.files = current->files;
2857 spin_unlock_irq(&ctx->inflight_lock);
2863 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2865 struct io_timeout_data *data = container_of(timer,
2866 struct io_timeout_data, timer);
2867 struct io_kiocb *req = data->req;
2868 struct io_ring_ctx *ctx = req->ctx;
2869 struct io_kiocb *prev = NULL;
2870 unsigned long flags;
2872 spin_lock_irqsave(&ctx->completion_lock, flags);
2875 * We don't expect the list to be empty, that will only happen if we
2876 * race with the completion of the linked work.
2878 if (!list_empty(&req->list)) {
2879 prev = list_entry(req->list.prev, struct io_kiocb, link_list);
2880 if (refcount_inc_not_zero(&prev->refs)) {
2881 list_del_init(&req->list);
2882 prev->flags &= ~REQ_F_LINK_TIMEOUT;
2887 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2890 if (prev->flags & REQ_F_LINK)
2891 prev->flags |= REQ_F_FAIL_LINK;
2892 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
2896 io_cqring_add_event(req, -ETIME);
2899 return HRTIMER_NORESTART;
2902 static void io_queue_linked_timeout(struct io_kiocb *req)
2904 struct io_ring_ctx *ctx = req->ctx;
2907 * If the list is now empty, then our linked request finished before
2908 * we got a chance to setup the timer
2910 spin_lock_irq(&ctx->completion_lock);
2911 if (!list_empty(&req->list)) {
2912 struct io_timeout_data *data = req->timeout.data;
2914 data->timer.function = io_link_timeout_fn;
2915 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
2918 spin_unlock_irq(&ctx->completion_lock);
2920 /* drop submission reference */
2924 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2926 struct io_kiocb *nxt;
2928 if (!(req->flags & REQ_F_LINK))
2931 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
2932 if (!nxt || nxt->sqe->opcode != IORING_OP_LINK_TIMEOUT)
2935 req->flags |= REQ_F_LINK_TIMEOUT;
2939 static void __io_queue_sqe(struct io_kiocb *req)
2941 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
2942 struct io_kiocb *nxt = NULL;
2945 ret = io_issue_sqe(req, &nxt, true);
2947 io_queue_async_work(nxt);
2950 * We async punt it if the file wasn't marked NOWAIT, or if the file
2951 * doesn't support non-blocking read/write attempts
2953 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2954 (req->flags & REQ_F_MUST_PUNT))) {
2955 struct io_uring_sqe *sqe_copy;
2957 sqe_copy = kmemdup(req->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2961 req->sqe = sqe_copy;
2962 req->flags |= REQ_F_FREE_SQE;
2964 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
2965 ret = io_grab_files(req);
2971 * Queued up for async execution, worker will release
2972 * submit reference when the iocb is actually submitted.
2974 io_queue_async_work(req);
2979 /* drop submission reference */
2982 if (linked_timeout) {
2984 io_queue_linked_timeout(linked_timeout);
2986 io_put_req(linked_timeout);
2989 /* and drop final reference, if we failed */
2991 io_cqring_add_event(req, ret);
2992 if (req->flags & REQ_F_LINK)
2993 req->flags |= REQ_F_FAIL_LINK;
2998 static void io_queue_sqe(struct io_kiocb *req)
3002 if (unlikely(req->ctx->drain_next)) {
3003 req->flags |= REQ_F_IO_DRAIN;
3004 req->ctx->drain_next = false;
3006 req->ctx->drain_next = (req->flags & REQ_F_DRAIN_LINK);
3008 ret = io_req_defer(req);
3010 if (ret != -EIOCBQUEUED) {
3011 io_cqring_add_event(req, ret);
3012 if (req->flags & REQ_F_LINK)
3013 req->flags |= REQ_F_FAIL_LINK;
3014 io_double_put_req(req);
3017 __io_queue_sqe(req);
3020 static inline void io_queue_link_head(struct io_kiocb *req)
3022 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
3023 io_cqring_add_event(req, -ECANCELED);
3024 io_double_put_req(req);
3030 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
3032 static void io_submit_sqe(struct io_kiocb *req, struct io_submit_state *state,
3033 struct io_kiocb **link)
3035 struct io_ring_ctx *ctx = req->ctx;
3038 req->user_data = req->sqe->user_data;
3040 /* enforce forwards compatibility on users */
3041 if (unlikely(req->sqe->flags & ~SQE_VALID_FLAGS)) {
3046 ret = io_req_set_file(state, req);
3047 if (unlikely(ret)) {
3049 io_cqring_add_event(req, ret);
3050 io_double_put_req(req);
3055 * If we already have a head request, queue this one for async
3056 * submittal once the head completes. If we don't have a head but
3057 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3058 * submitted sync once the chain is complete. If none of those
3059 * conditions are true (normal request), then just queue it.
3062 struct io_kiocb *prev = *link;
3063 struct io_uring_sqe *sqe_copy;
3065 if (req->sqe->flags & IOSQE_IO_DRAIN)
3066 (*link)->flags |= REQ_F_DRAIN_LINK | REQ_F_IO_DRAIN;
3068 if (READ_ONCE(req->sqe->opcode) == IORING_OP_LINK_TIMEOUT) {
3069 ret = io_timeout_setup(req);
3070 /* common setup allows offset being set, we don't */
3071 if (!ret && req->sqe->off)
3074 prev->flags |= REQ_F_FAIL_LINK;
3079 sqe_copy = kmemdup(req->sqe, sizeof(*sqe_copy), GFP_KERNEL);
3085 req->sqe = sqe_copy;
3086 req->flags |= REQ_F_FREE_SQE;
3087 trace_io_uring_link(ctx, req, prev);
3088 list_add_tail(&req->list, &prev->link_list);
3089 } else if (req->sqe->flags & IOSQE_IO_LINK) {
3090 req->flags |= REQ_F_LINK;
3092 INIT_LIST_HEAD(&req->link_list);
3100 * Batched submission is done, ensure local IO is flushed out.
3102 static void io_submit_state_end(struct io_submit_state *state)
3104 blk_finish_plug(&state->plug);
3106 if (state->free_reqs)
3107 kmem_cache_free_bulk(req_cachep, state->free_reqs,
3108 &state->reqs[state->cur_req]);
3112 * Start submission side cache.
3114 static void io_submit_state_start(struct io_submit_state *state,
3115 struct io_ring_ctx *ctx, unsigned max_ios)
3117 blk_start_plug(&state->plug);
3118 state->free_reqs = 0;
3120 state->ios_left = max_ios;
3123 static void io_commit_sqring(struct io_ring_ctx *ctx)
3125 struct io_rings *rings = ctx->rings;
3127 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
3129 * Ensure any loads from the SQEs are done at this point,
3130 * since once we write the new head, the application could
3131 * write new data to them.
3133 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3138 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
3139 * that is mapped by userspace. This means that care needs to be taken to
3140 * ensure that reads are stable, as we cannot rely on userspace always
3141 * being a good citizen. If members of the sqe are validated and then later
3142 * used, it's important that those reads are done through READ_ONCE() to
3143 * prevent a re-load down the line.
3145 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req)
3147 struct io_rings *rings = ctx->rings;
3148 u32 *sq_array = ctx->sq_array;
3152 * The cached sq head (or cq tail) serves two purposes:
3154 * 1) allows us to batch the cost of updating the user visible
3156 * 2) allows the kernel side to track the head on its own, even
3157 * though the application is the one updating it.
3159 head = ctx->cached_sq_head;
3160 /* make sure SQ entry isn't read before tail */
3161 if (unlikely(head == smp_load_acquire(&rings->sq.tail)))
3164 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
3165 if (likely(head < ctx->sq_entries)) {
3167 * All io need record the previous position, if LINK vs DARIN,
3168 * it can be used to mark the position of the first IO in the
3171 req->sequence = ctx->cached_sq_head;
3172 req->sqe = &ctx->sq_sqes[head];
3173 ctx->cached_sq_head++;
3177 /* drop invalid entries */
3178 ctx->cached_sq_head++;
3179 ctx->cached_sq_dropped++;
3180 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
3184 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
3185 struct file *ring_file, int ring_fd,
3186 struct mm_struct **mm, bool async)
3188 struct io_submit_state state, *statep = NULL;
3189 struct io_kiocb *link = NULL;
3190 int i, submitted = 0;
3191 bool mm_fault = false;
3193 /* if we have a backlog and couldn't flush it all, return BUSY */
3194 if (!list_empty(&ctx->cq_overflow_list) &&
3195 !io_cqring_overflow_flush(ctx, false))
3198 if (nr > IO_PLUG_THRESHOLD) {
3199 io_submit_state_start(&state, ctx, nr);
3203 for (i = 0; i < nr; i++) {
3204 struct io_kiocb *req;
3205 unsigned int sqe_flags;
3207 req = io_get_req(ctx, statep);
3208 if (unlikely(!req)) {
3210 submitted = -EAGAIN;
3213 if (!io_get_sqring(ctx, req)) {
3218 if (io_sqe_needs_user(req->sqe) && !*mm) {
3219 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
3221 use_mm(ctx->sqo_mm);
3226 sqe_flags = req->sqe->flags;
3228 req->ring_file = ring_file;
3229 req->ring_fd = ring_fd;
3230 req->has_user = *mm != NULL;
3231 req->in_async = async;
3232 req->needs_fixed_file = async;
3233 trace_io_uring_submit_sqe(ctx, req->sqe->user_data,
3235 io_submit_sqe(req, statep, &link);
3239 * If previous wasn't linked and we have a linked command,
3240 * that's the end of the chain. Submit the previous link.
3242 if (!(sqe_flags & IOSQE_IO_LINK) && link) {
3243 io_queue_link_head(link);
3249 io_queue_link_head(link);
3251 io_submit_state_end(&state);
3253 /* Commit SQ ring head once we've consumed and submitted all SQEs */
3254 io_commit_sqring(ctx);
3259 static int io_sq_thread(void *data)
3261 struct io_ring_ctx *ctx = data;
3262 struct mm_struct *cur_mm = NULL;
3263 const struct cred *old_cred;
3264 mm_segment_t old_fs;
3267 unsigned long timeout;
3270 complete(&ctx->completions[1]);
3274 old_cred = override_creds(ctx->creds);
3276 ret = timeout = inflight = 0;
3277 while (!kthread_should_park()) {
3278 unsigned int to_submit;
3281 unsigned nr_events = 0;
3283 if (ctx->flags & IORING_SETUP_IOPOLL) {
3285 * inflight is the count of the maximum possible
3286 * entries we submitted, but it can be smaller
3287 * if we dropped some of them. If we don't have
3288 * poll entries available, then we know that we
3289 * have nothing left to poll for. Reset the
3290 * inflight count to zero in that case.
3292 mutex_lock(&ctx->uring_lock);
3293 if (!list_empty(&ctx->poll_list))
3294 __io_iopoll_check(ctx, &nr_events, 0);
3297 mutex_unlock(&ctx->uring_lock);
3300 * Normal IO, just pretend everything completed.
3301 * We don't have to poll completions for that.
3303 nr_events = inflight;
3306 inflight -= nr_events;
3308 timeout = jiffies + ctx->sq_thread_idle;
3311 to_submit = io_sqring_entries(ctx);
3314 * If submit got -EBUSY, flag us as needing the application
3315 * to enter the kernel to reap and flush events.
3317 if (!to_submit || ret == -EBUSY) {
3319 * We're polling. If we're within the defined idle
3320 * period, then let us spin without work before going
3321 * to sleep. The exception is if we got EBUSY doing
3322 * more IO, we should wait for the application to
3323 * reap events and wake us up.
3326 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
3332 * Drop cur_mm before scheduling, we can't hold it for
3333 * long periods (or over schedule()). Do this before
3334 * adding ourselves to the waitqueue, as the unuse/drop
3343 prepare_to_wait(&ctx->sqo_wait, &wait,
3344 TASK_INTERRUPTIBLE);
3346 /* Tell userspace we may need a wakeup call */
3347 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
3348 /* make sure to read SQ tail after writing flags */
3351 to_submit = io_sqring_entries(ctx);
3352 if (!to_submit || ret == -EBUSY) {
3353 if (kthread_should_park()) {
3354 finish_wait(&ctx->sqo_wait, &wait);
3357 if (signal_pending(current))
3358 flush_signals(current);
3360 finish_wait(&ctx->sqo_wait, &wait);
3362 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3365 finish_wait(&ctx->sqo_wait, &wait);
3367 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
3370 to_submit = min(to_submit, ctx->sq_entries);
3371 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
3381 revert_creds(old_cred);
3388 struct io_wait_queue {
3389 struct wait_queue_entry wq;
3390 struct io_ring_ctx *ctx;
3392 unsigned nr_timeouts;
3395 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
3397 struct io_ring_ctx *ctx = iowq->ctx;
3400 * Wake up if we have enough events, or if a timeout occured since we
3401 * started waiting. For timeouts, we always want to return to userspace,
3402 * regardless of event count.
3404 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
3405 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3408 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3409 int wake_flags, void *key)
3411 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3414 /* use noflush == true, as we can't safely rely on locking context */
3415 if (!io_should_wake(iowq, true))
3418 return autoremove_wake_function(curr, mode, wake_flags, key);
3422 * Wait until events become available, if we don't already have some. The
3423 * application must reap them itself, as they reside on the shared cq ring.
3425 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3426 const sigset_t __user *sig, size_t sigsz)
3428 struct io_wait_queue iowq = {
3431 .func = io_wake_function,
3432 .entry = LIST_HEAD_INIT(iowq.wq.entry),
3435 .to_wait = min_events,
3437 struct io_rings *rings = ctx->rings;
3440 if (io_cqring_events(ctx, false) >= min_events)
3444 #ifdef CONFIG_COMPAT
3445 if (in_compat_syscall())
3446 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3450 ret = set_user_sigmask(sig, sigsz);
3456 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3457 trace_io_uring_cqring_wait(ctx, min_events);
3459 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3460 TASK_INTERRUPTIBLE);
3461 if (io_should_wake(&iowq, false))
3464 if (signal_pending(current)) {
3469 finish_wait(&ctx->wait, &iowq.wq);
3471 restore_saved_sigmask_unless(ret == -EINTR);
3473 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3476 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3478 #if defined(CONFIG_UNIX)
3479 if (ctx->ring_sock) {
3480 struct sock *sock = ctx->ring_sock->sk;
3481 struct sk_buff *skb;
3483 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
3489 for (i = 0; i < ctx->nr_user_files; i++) {
3492 file = io_file_from_index(ctx, i);
3499 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3501 unsigned nr_tables, i;
3503 if (!ctx->file_table)
3506 __io_sqe_files_unregister(ctx);
3507 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
3508 for (i = 0; i < nr_tables; i++)
3509 kfree(ctx->file_table[i].files);
3510 kfree(ctx->file_table);
3511 ctx->file_table = NULL;
3512 ctx->nr_user_files = 0;
3516 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3518 if (ctx->sqo_thread) {
3519 wait_for_completion(&ctx->completions[1]);
3521 * The park is a bit of a work-around, without it we get
3522 * warning spews on shutdown with SQPOLL set and affinity
3523 * set to a single CPU.
3525 kthread_park(ctx->sqo_thread);
3526 kthread_stop(ctx->sqo_thread);
3527 ctx->sqo_thread = NULL;
3531 static void io_finish_async(struct io_ring_ctx *ctx)
3533 io_sq_thread_stop(ctx);
3536 io_wq_destroy(ctx->io_wq);
3541 #if defined(CONFIG_UNIX)
3542 static void io_destruct_skb(struct sk_buff *skb)
3544 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
3547 io_wq_flush(ctx->io_wq);
3549 unix_destruct_scm(skb);
3553 * Ensure the UNIX gc is aware of our file set, so we are certain that
3554 * the io_uring can be safely unregistered on process exit, even if we have
3555 * loops in the file referencing.
3557 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
3559 struct sock *sk = ctx->ring_sock->sk;
3560 struct scm_fp_list *fpl;
3561 struct sk_buff *skb;
3564 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
3565 unsigned long inflight = ctx->user->unix_inflight + nr;
3567 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
3571 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
3575 skb = alloc_skb(0, GFP_KERNEL);
3584 fpl->user = get_uid(ctx->user);
3585 for (i = 0; i < nr; i++) {
3586 struct file *file = io_file_from_index(ctx, i + offset);
3590 fpl->fp[nr_files] = get_file(file);
3591 unix_inflight(fpl->user, fpl->fp[nr_files]);
3596 fpl->max = SCM_MAX_FD;
3597 fpl->count = nr_files;
3598 UNIXCB(skb).fp = fpl;
3599 skb->destructor = io_destruct_skb;
3600 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
3601 skb_queue_head(&sk->sk_receive_queue, skb);
3603 for (i = 0; i < nr_files; i++)
3614 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3615 * causes regular reference counting to break down. We rely on the UNIX
3616 * garbage collection to take care of this problem for us.
3618 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3620 unsigned left, total;
3624 left = ctx->nr_user_files;
3626 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
3628 ret = __io_sqe_files_scm(ctx, this_files, total);
3632 total += this_files;
3638 while (total < ctx->nr_user_files) {
3639 struct file *file = io_file_from_index(ctx, total);
3649 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3655 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
3660 for (i = 0; i < nr_tables; i++) {
3661 struct fixed_file_table *table = &ctx->file_table[i];
3662 unsigned this_files;
3664 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
3665 table->files = kcalloc(this_files, sizeof(struct file *),
3669 nr_files -= this_files;
3675 for (i = 0; i < nr_tables; i++) {
3676 struct fixed_file_table *table = &ctx->file_table[i];
3677 kfree(table->files);
3682 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3685 __s32 __user *fds = (__s32 __user *) arg;
3690 if (ctx->file_table)
3694 if (nr_args > IORING_MAX_FIXED_FILES)
3697 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
3698 ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
3700 if (!ctx->file_table)
3703 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
3704 kfree(ctx->file_table);
3705 ctx->file_table = NULL;
3709 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
3710 struct fixed_file_table *table;
3714 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3716 /* allow sparse sets */
3722 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3723 index = i & IORING_FILE_TABLE_MASK;
3724 table->files[index] = fget(fd);
3727 if (!table->files[index])
3730 * Don't allow io_uring instances to be registered. If UNIX
3731 * isn't enabled, then this causes a reference cycle and this
3732 * instance can never get freed. If UNIX is enabled we'll
3733 * handle it just fine, but there's still no point in allowing
3734 * a ring fd as it doesn't support regular read/write anyway.
3736 if (table->files[index]->f_op == &io_uring_fops) {
3737 fput(table->files[index]);
3744 for (i = 0; i < ctx->nr_user_files; i++) {
3747 file = io_file_from_index(ctx, i);
3751 for (i = 0; i < nr_tables; i++)
3752 kfree(ctx->file_table[i].files);
3754 kfree(ctx->file_table);
3755 ctx->file_table = NULL;
3756 ctx->nr_user_files = 0;
3760 ret = io_sqe_files_scm(ctx);
3762 io_sqe_files_unregister(ctx);
3767 static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
3769 #if defined(CONFIG_UNIX)
3770 struct file *file = io_file_from_index(ctx, index);
3771 struct sock *sock = ctx->ring_sock->sk;
3772 struct sk_buff_head list, *head = &sock->sk_receive_queue;
3773 struct sk_buff *skb;
3776 __skb_queue_head_init(&list);
3779 * Find the skb that holds this file in its SCM_RIGHTS. When found,
3780 * remove this entry and rearrange the file array.
3782 skb = skb_dequeue(head);
3784 struct scm_fp_list *fp;
3786 fp = UNIXCB(skb).fp;
3787 for (i = 0; i < fp->count; i++) {
3790 if (fp->fp[i] != file)
3793 unix_notinflight(fp->user, fp->fp[i]);
3794 left = fp->count - 1 - i;
3796 memmove(&fp->fp[i], &fp->fp[i + 1],
3797 left * sizeof(struct file *));
3804 __skb_queue_tail(&list, skb);
3814 __skb_queue_tail(&list, skb);
3816 skb = skb_dequeue(head);
3819 if (skb_peek(&list)) {
3820 spin_lock_irq(&head->lock);
3821 while ((skb = __skb_dequeue(&list)) != NULL)
3822 __skb_queue_tail(head, skb);
3823 spin_unlock_irq(&head->lock);
3826 fput(io_file_from_index(ctx, index));
3830 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
3833 #if defined(CONFIG_UNIX)
3834 struct sock *sock = ctx->ring_sock->sk;
3835 struct sk_buff_head *head = &sock->sk_receive_queue;
3836 struct sk_buff *skb;
3839 * See if we can merge this file into an existing skb SCM_RIGHTS
3840 * file set. If there's no room, fall back to allocating a new skb
3841 * and filling it in.
3843 spin_lock_irq(&head->lock);
3844 skb = skb_peek(head);
3846 struct scm_fp_list *fpl = UNIXCB(skb).fp;
3848 if (fpl->count < SCM_MAX_FD) {
3849 __skb_unlink(skb, head);
3850 spin_unlock_irq(&head->lock);
3851 fpl->fp[fpl->count] = get_file(file);
3852 unix_inflight(fpl->user, fpl->fp[fpl->count]);
3854 spin_lock_irq(&head->lock);
3855 __skb_queue_head(head, skb);
3860 spin_unlock_irq(&head->lock);
3867 return __io_sqe_files_scm(ctx, 1, index);
3873 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
3876 struct io_uring_files_update up;
3881 if (!ctx->file_table)
3885 if (copy_from_user(&up, arg, sizeof(up)))
3887 if (check_add_overflow(up.offset, nr_args, &done))
3889 if (done > ctx->nr_user_files)
3893 fds = (__s32 __user *) up.fds;
3895 struct fixed_file_table *table;
3899 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
3903 i = array_index_nospec(up.offset, ctx->nr_user_files);
3904 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3905 index = i & IORING_FILE_TABLE_MASK;
3906 if (table->files[index]) {
3907 io_sqe_file_unregister(ctx, i);
3908 table->files[index] = NULL;
3919 * Don't allow io_uring instances to be registered. If
3920 * UNIX isn't enabled, then this causes a reference
3921 * cycle and this instance can never get freed. If UNIX
3922 * is enabled we'll handle it just fine, but there's
3923 * still no point in allowing a ring fd as it doesn't
3924 * support regular read/write anyway.
3926 if (file->f_op == &io_uring_fops) {
3931 table->files[index] = file;
3932 err = io_sqe_file_register(ctx, file, i);
3941 return done ? done : err;
3944 static void io_put_work(struct io_wq_work *work)
3946 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3951 static void io_get_work(struct io_wq_work *work)
3953 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3955 refcount_inc(&req->refs);
3958 static int io_sq_offload_start(struct io_ring_ctx *ctx,
3959 struct io_uring_params *p)
3961 struct io_wq_data data;
3962 unsigned concurrency;
3965 init_waitqueue_head(&ctx->sqo_wait);
3966 mmgrab(current->mm);
3967 ctx->sqo_mm = current->mm;
3969 if (ctx->flags & IORING_SETUP_SQPOLL) {
3971 if (!capable(CAP_SYS_ADMIN))
3974 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3975 if (!ctx->sq_thread_idle)
3976 ctx->sq_thread_idle = HZ;
3978 if (p->flags & IORING_SETUP_SQ_AFF) {
3979 int cpu = p->sq_thread_cpu;
3982 if (cpu >= nr_cpu_ids)
3984 if (!cpu_online(cpu))
3987 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3991 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3994 if (IS_ERR(ctx->sqo_thread)) {
3995 ret = PTR_ERR(ctx->sqo_thread);
3996 ctx->sqo_thread = NULL;
3999 wake_up_process(ctx->sqo_thread);
4000 } else if (p->flags & IORING_SETUP_SQ_AFF) {
4001 /* Can't have SQ_AFF without SQPOLL */
4006 data.mm = ctx->sqo_mm;
4007 data.user = ctx->user;
4008 data.creds = ctx->creds;
4009 data.get_work = io_get_work;
4010 data.put_work = io_put_work;
4012 /* Do QD, or 4 * CPUS, whatever is smallest */
4013 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
4014 ctx->io_wq = io_wq_create(concurrency, &data);
4015 if (IS_ERR(ctx->io_wq)) {
4016 ret = PTR_ERR(ctx->io_wq);
4023 io_finish_async(ctx);
4024 mmdrop(ctx->sqo_mm);
4029 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
4031 atomic_long_sub(nr_pages, &user->locked_vm);
4034 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
4036 unsigned long page_limit, cur_pages, new_pages;
4038 /* Don't allow more pages than we can safely lock */
4039 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4042 cur_pages = atomic_long_read(&user->locked_vm);
4043 new_pages = cur_pages + nr_pages;
4044 if (new_pages > page_limit)
4046 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4047 new_pages) != cur_pages);
4052 static void io_mem_free(void *ptr)
4059 page = virt_to_head_page(ptr);
4060 if (put_page_testzero(page))
4061 free_compound_page(page);
4064 static void *io_mem_alloc(size_t size)
4066 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
4069 return (void *) __get_free_pages(gfp_flags, get_order(size));
4072 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
4075 struct io_rings *rings;
4076 size_t off, sq_array_size;
4078 off = struct_size(rings, cqes, cq_entries);
4079 if (off == SIZE_MAX)
4083 off = ALIGN(off, SMP_CACHE_BYTES);
4088 sq_array_size = array_size(sizeof(u32), sq_entries);
4089 if (sq_array_size == SIZE_MAX)
4092 if (check_add_overflow(off, sq_array_size, &off))
4101 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
4105 pages = (size_t)1 << get_order(
4106 rings_size(sq_entries, cq_entries, NULL));
4107 pages += (size_t)1 << get_order(
4108 array_size(sizeof(struct io_uring_sqe), sq_entries));
4113 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
4117 if (!ctx->user_bufs)
4120 for (i = 0; i < ctx->nr_user_bufs; i++) {
4121 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4123 for (j = 0; j < imu->nr_bvecs; j++)
4124 put_user_page(imu->bvec[j].bv_page);
4126 if (ctx->account_mem)
4127 io_unaccount_mem(ctx->user, imu->nr_bvecs);
4132 kfree(ctx->user_bufs);
4133 ctx->user_bufs = NULL;
4134 ctx->nr_user_bufs = 0;
4138 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4139 void __user *arg, unsigned index)
4141 struct iovec __user *src;
4143 #ifdef CONFIG_COMPAT
4145 struct compat_iovec __user *ciovs;
4146 struct compat_iovec ciov;
4148 ciovs = (struct compat_iovec __user *) arg;
4149 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4152 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
4153 dst->iov_len = ciov.iov_len;
4157 src = (struct iovec __user *) arg;
4158 if (copy_from_user(dst, &src[index], sizeof(*dst)))
4163 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
4166 struct vm_area_struct **vmas = NULL;
4167 struct page **pages = NULL;
4168 int i, j, got_pages = 0;
4173 if (!nr_args || nr_args > UIO_MAXIOV)
4176 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
4178 if (!ctx->user_bufs)
4181 for (i = 0; i < nr_args; i++) {
4182 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4183 unsigned long off, start, end, ubuf;
4188 ret = io_copy_iov(ctx, &iov, arg, i);
4193 * Don't impose further limits on the size and buffer
4194 * constraints here, we'll -EINVAL later when IO is
4195 * submitted if they are wrong.
4198 if (!iov.iov_base || !iov.iov_len)
4201 /* arbitrary limit, but we need something */
4202 if (iov.iov_len > SZ_1G)
4205 ubuf = (unsigned long) iov.iov_base;
4206 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4207 start = ubuf >> PAGE_SHIFT;
4208 nr_pages = end - start;
4210 if (ctx->account_mem) {
4211 ret = io_account_mem(ctx->user, nr_pages);
4217 if (!pages || nr_pages > got_pages) {
4220 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
4222 vmas = kvmalloc_array(nr_pages,
4223 sizeof(struct vm_area_struct *),
4225 if (!pages || !vmas) {
4227 if (ctx->account_mem)
4228 io_unaccount_mem(ctx->user, nr_pages);
4231 got_pages = nr_pages;
4234 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
4238 if (ctx->account_mem)
4239 io_unaccount_mem(ctx->user, nr_pages);
4244 down_read(¤t->mm->mmap_sem);
4245 pret = get_user_pages(ubuf, nr_pages,
4246 FOLL_WRITE | FOLL_LONGTERM,
4248 if (pret == nr_pages) {
4249 /* don't support file backed memory */
4250 for (j = 0; j < nr_pages; j++) {
4251 struct vm_area_struct *vma = vmas[j];
4254 !is_file_hugepages(vma->vm_file)) {
4260 ret = pret < 0 ? pret : -EFAULT;
4262 up_read(¤t->mm->mmap_sem);
4265 * if we did partial map, or found file backed vmas,
4266 * release any pages we did get
4269 put_user_pages(pages, pret);
4270 if (ctx->account_mem)
4271 io_unaccount_mem(ctx->user, nr_pages);
4276 off = ubuf & ~PAGE_MASK;
4278 for (j = 0; j < nr_pages; j++) {
4281 vec_len = min_t(size_t, size, PAGE_SIZE - off);
4282 imu->bvec[j].bv_page = pages[j];
4283 imu->bvec[j].bv_len = vec_len;
4284 imu->bvec[j].bv_offset = off;
4288 /* store original address for later verification */
4290 imu->len = iov.iov_len;
4291 imu->nr_bvecs = nr_pages;
4293 ctx->nr_user_bufs++;
4301 io_sqe_buffer_unregister(ctx);
4305 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
4307 __s32 __user *fds = arg;
4313 if (copy_from_user(&fd, fds, sizeof(*fds)))
4316 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
4317 if (IS_ERR(ctx->cq_ev_fd)) {
4318 int ret = PTR_ERR(ctx->cq_ev_fd);
4319 ctx->cq_ev_fd = NULL;
4326 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
4328 if (ctx->cq_ev_fd) {
4329 eventfd_ctx_put(ctx->cq_ev_fd);
4330 ctx->cq_ev_fd = NULL;
4337 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
4339 io_finish_async(ctx);
4341 mmdrop(ctx->sqo_mm);
4343 io_iopoll_reap_events(ctx);
4344 io_sqe_buffer_unregister(ctx);
4345 io_sqe_files_unregister(ctx);
4346 io_eventfd_unregister(ctx);
4348 #if defined(CONFIG_UNIX)
4349 if (ctx->ring_sock) {
4350 ctx->ring_sock->file = NULL; /* so that iput() is called */
4351 sock_release(ctx->ring_sock);
4355 io_mem_free(ctx->rings);
4356 io_mem_free(ctx->sq_sqes);
4358 percpu_ref_exit(&ctx->refs);
4359 if (ctx->account_mem)
4360 io_unaccount_mem(ctx->user,
4361 ring_pages(ctx->sq_entries, ctx->cq_entries));
4362 free_uid(ctx->user);
4363 put_cred(ctx->creds);
4364 kfree(ctx->completions);
4365 kmem_cache_free(req_cachep, ctx->fallback_req);
4369 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
4371 struct io_ring_ctx *ctx = file->private_data;
4374 poll_wait(file, &ctx->cq_wait, wait);
4376 * synchronizes with barrier from wq_has_sleeper call in
4380 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
4381 ctx->rings->sq_ring_entries)
4382 mask |= EPOLLOUT | EPOLLWRNORM;
4383 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
4384 mask |= EPOLLIN | EPOLLRDNORM;
4389 static int io_uring_fasync(int fd, struct file *file, int on)
4391 struct io_ring_ctx *ctx = file->private_data;
4393 return fasync_helper(fd, file, on, &ctx->cq_fasync);
4396 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
4398 mutex_lock(&ctx->uring_lock);
4399 percpu_ref_kill(&ctx->refs);
4400 mutex_unlock(&ctx->uring_lock);
4402 io_kill_timeouts(ctx);
4403 io_poll_remove_all(ctx);
4406 io_wq_cancel_all(ctx->io_wq);
4408 io_iopoll_reap_events(ctx);
4409 /* if we failed setting up the ctx, we might not have any rings */
4411 io_cqring_overflow_flush(ctx, true);
4412 wait_for_completion(&ctx->completions[0]);
4413 io_ring_ctx_free(ctx);
4416 static int io_uring_release(struct inode *inode, struct file *file)
4418 struct io_ring_ctx *ctx = file->private_data;
4420 file->private_data = NULL;
4421 io_ring_ctx_wait_and_kill(ctx);
4425 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
4426 struct files_struct *files)
4428 struct io_kiocb *req;
4431 while (!list_empty_careful(&ctx->inflight_list)) {
4432 struct io_kiocb *cancel_req = NULL;
4434 spin_lock_irq(&ctx->inflight_lock);
4435 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
4436 if (req->work.files != files)
4438 /* req is being completed, ignore */
4439 if (!refcount_inc_not_zero(&req->refs))
4445 prepare_to_wait(&ctx->inflight_wait, &wait,
4446 TASK_UNINTERRUPTIBLE);
4447 spin_unlock_irq(&ctx->inflight_lock);
4449 /* We need to keep going until we don't find a matching req */
4453 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
4454 io_put_req(cancel_req);
4457 finish_wait(&ctx->inflight_wait, &wait);
4460 static int io_uring_flush(struct file *file, void *data)
4462 struct io_ring_ctx *ctx = file->private_data;
4464 io_uring_cancel_files(ctx, data);
4465 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
4466 io_cqring_overflow_flush(ctx, true);
4467 io_wq_cancel_all(ctx->io_wq);
4472 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
4474 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
4475 unsigned long sz = vma->vm_end - vma->vm_start;
4476 struct io_ring_ctx *ctx = file->private_data;
4482 case IORING_OFF_SQ_RING:
4483 case IORING_OFF_CQ_RING:
4486 case IORING_OFF_SQES:
4493 page = virt_to_head_page(ptr);
4494 if (sz > page_size(page))
4497 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
4498 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
4501 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
4502 u32, min_complete, u32, flags, const sigset_t __user *, sig,
4505 struct io_ring_ctx *ctx;
4510 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
4518 if (f.file->f_op != &io_uring_fops)
4522 ctx = f.file->private_data;
4523 if (!percpu_ref_tryget(&ctx->refs))
4527 * For SQ polling, the thread will do all submissions and completions.
4528 * Just return the requested submit count, and wake the thread if
4532 if (ctx->flags & IORING_SETUP_SQPOLL) {
4533 if (!list_empty_careful(&ctx->cq_overflow_list))
4534 io_cqring_overflow_flush(ctx, false);
4535 if (flags & IORING_ENTER_SQ_WAKEUP)
4536 wake_up(&ctx->sqo_wait);
4537 submitted = to_submit;
4538 } else if (to_submit) {
4539 struct mm_struct *cur_mm;
4541 to_submit = min(to_submit, ctx->sq_entries);
4542 mutex_lock(&ctx->uring_lock);
4543 /* already have mm, so io_submit_sqes() won't try to grab it */
4544 cur_mm = ctx->sqo_mm;
4545 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
4547 mutex_unlock(&ctx->uring_lock);
4549 if (flags & IORING_ENTER_GETEVENTS) {
4550 unsigned nr_events = 0;
4552 min_complete = min(min_complete, ctx->cq_entries);
4554 if (ctx->flags & IORING_SETUP_IOPOLL) {
4555 ret = io_iopoll_check(ctx, &nr_events, min_complete);
4557 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
4561 percpu_ref_put(&ctx->refs);
4564 return submitted ? submitted : ret;
4567 static const struct file_operations io_uring_fops = {
4568 .release = io_uring_release,
4569 .flush = io_uring_flush,
4570 .mmap = io_uring_mmap,
4571 .poll = io_uring_poll,
4572 .fasync = io_uring_fasync,
4575 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
4576 struct io_uring_params *p)
4578 struct io_rings *rings;
4579 size_t size, sq_array_offset;
4581 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
4582 if (size == SIZE_MAX)
4585 rings = io_mem_alloc(size);
4590 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
4591 rings->sq_ring_mask = p->sq_entries - 1;
4592 rings->cq_ring_mask = p->cq_entries - 1;
4593 rings->sq_ring_entries = p->sq_entries;
4594 rings->cq_ring_entries = p->cq_entries;
4595 ctx->sq_mask = rings->sq_ring_mask;
4596 ctx->cq_mask = rings->cq_ring_mask;
4597 ctx->sq_entries = rings->sq_ring_entries;
4598 ctx->cq_entries = rings->cq_ring_entries;
4600 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
4601 if (size == SIZE_MAX) {
4602 io_mem_free(ctx->rings);
4607 ctx->sq_sqes = io_mem_alloc(size);
4608 if (!ctx->sq_sqes) {
4609 io_mem_free(ctx->rings);
4618 * Allocate an anonymous fd, this is what constitutes the application
4619 * visible backing of an io_uring instance. The application mmaps this
4620 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
4621 * we have to tie this fd to a socket for file garbage collection purposes.
4623 static int io_uring_get_fd(struct io_ring_ctx *ctx)
4628 #if defined(CONFIG_UNIX)
4629 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
4635 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
4639 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
4640 O_RDWR | O_CLOEXEC);
4643 ret = PTR_ERR(file);
4647 #if defined(CONFIG_UNIX)
4648 ctx->ring_sock->file = file;
4649 ctx->ring_sock->sk->sk_user_data = ctx;
4651 fd_install(ret, file);
4654 #if defined(CONFIG_UNIX)
4655 sock_release(ctx->ring_sock);
4656 ctx->ring_sock = NULL;
4661 static int io_uring_create(unsigned entries, struct io_uring_params *p)
4663 struct user_struct *user = NULL;
4664 struct io_ring_ctx *ctx;
4668 if (!entries || entries > IORING_MAX_ENTRIES)
4672 * Use twice as many entries for the CQ ring. It's possible for the
4673 * application to drive a higher depth than the size of the SQ ring,
4674 * since the sqes are only used at submission time. This allows for
4675 * some flexibility in overcommitting a bit. If the application has
4676 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
4677 * of CQ ring entries manually.
4679 p->sq_entries = roundup_pow_of_two(entries);
4680 if (p->flags & IORING_SETUP_CQSIZE) {
4682 * If IORING_SETUP_CQSIZE is set, we do the same roundup
4683 * to a power-of-two, if it isn't already. We do NOT impose
4684 * any cq vs sq ring sizing.
4686 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
4688 p->cq_entries = roundup_pow_of_two(p->cq_entries);
4690 p->cq_entries = 2 * p->sq_entries;
4693 user = get_uid(current_user());
4694 account_mem = !capable(CAP_IPC_LOCK);
4697 ret = io_account_mem(user,
4698 ring_pages(p->sq_entries, p->cq_entries));
4705 ctx = io_ring_ctx_alloc(p);
4708 io_unaccount_mem(user, ring_pages(p->sq_entries,
4713 ctx->compat = in_compat_syscall();
4714 ctx->account_mem = account_mem;
4716 ctx->creds = prepare_creds();
4718 ret = io_allocate_scq_urings(ctx, p);
4722 ret = io_sq_offload_start(ctx, p);
4726 memset(&p->sq_off, 0, sizeof(p->sq_off));
4727 p->sq_off.head = offsetof(struct io_rings, sq.head);
4728 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
4729 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
4730 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
4731 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
4732 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
4733 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
4735 memset(&p->cq_off, 0, sizeof(p->cq_off));
4736 p->cq_off.head = offsetof(struct io_rings, cq.head);
4737 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
4738 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
4739 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
4740 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
4741 p->cq_off.cqes = offsetof(struct io_rings, cqes);
4744 * Install ring fd as the very last thing, so we don't risk someone
4745 * having closed it before we finish setup
4747 ret = io_uring_get_fd(ctx);
4751 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP;
4752 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
4755 io_ring_ctx_wait_and_kill(ctx);
4760 * Sets up an aio uring context, and returns the fd. Applications asks for a
4761 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4762 * params structure passed in.
4764 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4766 struct io_uring_params p;
4770 if (copy_from_user(&p, params, sizeof(p)))
4772 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4777 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4778 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
4781 ret = io_uring_create(entries, &p);
4785 if (copy_to_user(params, &p, sizeof(p)))
4791 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4792 struct io_uring_params __user *, params)
4794 return io_uring_setup(entries, params);
4797 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4798 void __user *arg, unsigned nr_args)
4799 __releases(ctx->uring_lock)
4800 __acquires(ctx->uring_lock)
4805 * We're inside the ring mutex, if the ref is already dying, then
4806 * someone else killed the ctx or is already going through
4807 * io_uring_register().
4809 if (percpu_ref_is_dying(&ctx->refs))
4812 percpu_ref_kill(&ctx->refs);
4815 * Drop uring mutex before waiting for references to exit. If another
4816 * thread is currently inside io_uring_enter() it might need to grab
4817 * the uring_lock to make progress. If we hold it here across the drain
4818 * wait, then we can deadlock. It's safe to drop the mutex here, since
4819 * no new references will come in after we've killed the percpu ref.
4821 mutex_unlock(&ctx->uring_lock);
4822 wait_for_completion(&ctx->completions[0]);
4823 mutex_lock(&ctx->uring_lock);
4826 case IORING_REGISTER_BUFFERS:
4827 ret = io_sqe_buffer_register(ctx, arg, nr_args);
4829 case IORING_UNREGISTER_BUFFERS:
4833 ret = io_sqe_buffer_unregister(ctx);
4835 case IORING_REGISTER_FILES:
4836 ret = io_sqe_files_register(ctx, arg, nr_args);
4838 case IORING_UNREGISTER_FILES:
4842 ret = io_sqe_files_unregister(ctx);
4844 case IORING_REGISTER_FILES_UPDATE:
4845 ret = io_sqe_files_update(ctx, arg, nr_args);
4847 case IORING_REGISTER_EVENTFD:
4851 ret = io_eventfd_register(ctx, arg);
4853 case IORING_UNREGISTER_EVENTFD:
4857 ret = io_eventfd_unregister(ctx);
4864 /* bring the ctx back to life */
4865 reinit_completion(&ctx->completions[0]);
4866 percpu_ref_reinit(&ctx->refs);
4870 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4871 void __user *, arg, unsigned int, nr_args)
4873 struct io_ring_ctx *ctx;
4882 if (f.file->f_op != &io_uring_fops)
4885 ctx = f.file->private_data;
4887 mutex_lock(&ctx->uring_lock);
4888 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4889 mutex_unlock(&ctx->uring_lock);
4890 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
4891 ctx->cq_ev_fd != NULL, ret);
4897 static int __init io_uring_init(void)
4899 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4902 __initcall(io_uring_init);