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_cqe (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 <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/fsnotify.h>
74 #include <linux/fadvise.h>
75 #include <linux/eventpoll.h>
76 #include <linux/task_work.h>
77 #include <linux/pagemap.h>
78 #include <linux/io_uring.h>
79 #include <linux/audit.h>
80 #include <linux/security.h>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
89 #include "io_uring_types.h"
103 #include "openclose.h"
104 #include "uring_cmd.h"
108 #include "msg_ring.h"
112 #define IORING_MAX_ENTRIES 32768
113 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
115 /* only define max */
116 #define IORING_MAX_FIXED_FILES (1U << 20)
117 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
118 IORING_REGISTER_LAST + IORING_OP_LAST)
120 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
121 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
122 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
124 #define IORING_MAX_REG_BUFFERS (1U << 14)
126 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
127 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
129 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
130 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
132 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
133 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
136 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
139 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
142 struct list_head list;
147 struct io_mapped_ubuf *buf;
151 struct io_rsrc_node {
152 struct percpu_ref refs;
153 struct list_head node;
154 struct list_head rsrc_list;
155 struct io_rsrc_data *rsrc_data;
156 struct llist_node llist;
160 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
162 struct io_rsrc_data {
163 struct io_ring_ctx *ctx;
169 struct completion done;
173 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
174 struct io_buffer_list {
176 * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
177 * then these are classic provided buffers and ->buf_list is used.
180 struct list_head buf_list;
182 struct page **buf_pages;
183 struct io_uring_buf_ring *buf_ring;
188 /* below is for ring provided buffers */
196 struct list_head list;
203 #define IO_COMPL_BATCH 32
204 #define IO_REQ_CACHE_SIZE 32
205 #define IO_REQ_ALLOC_BATCH 8
207 #define BGID_ARRAY 64
210 * First field must be the file pointer in all the
211 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
221 /* NOTE: kiocb has the file as the first member, so don't do it here */
228 struct io_rsrc_update {
235 struct io_provide_buf {
245 struct iov_iter iter;
246 struct iov_iter_state iter_state;
247 struct iovec fast_iov[UIO_FASTIOV];
251 struct io_rw_state s;
252 const struct iovec *free_iovec;
254 struct wait_page_queue wpq;
258 IORING_RSRC_FILE = 0,
259 IORING_RSRC_BUFFER = 1,
263 IO_CHECK_CQ_OVERFLOW_BIT,
264 IO_CHECK_CQ_DROPPED_BIT,
267 struct io_defer_entry {
268 struct list_head list;
269 struct io_kiocb *req;
273 /* requests with any of those set should undergo io_disarm_next() */
274 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
275 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
277 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
278 struct task_struct *task,
281 static void io_dismantle_req(struct io_kiocb *req);
282 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
283 struct io_uring_rsrc_update2 *up,
285 static void io_clean_op(struct io_kiocb *req);
286 static void io_queue_sqe(struct io_kiocb *req);
287 static void io_rsrc_put_work(struct work_struct *work);
289 static void io_req_task_queue(struct io_kiocb *req);
290 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
291 static int io_req_prep_async(struct io_kiocb *req);
293 static void io_eventfd_signal(struct io_ring_ctx *ctx);
295 static struct kmem_cache *req_cachep;
297 const char *io_uring_get_opcode(u8 opcode)
299 if (opcode < IORING_OP_LAST)
300 return io_op_defs[opcode].name;
304 struct sock *io_uring_get_socket(struct file *file)
306 #if defined(CONFIG_UNIX)
307 if (io_is_uring_fops(file)) {
308 struct io_ring_ctx *ctx = file->private_data;
310 return ctx->ring_sock->sk;
315 EXPORT_SYMBOL(io_uring_get_socket);
317 #if defined(CONFIG_UNIX)
318 static inline bool io_file_need_scm(struct file *filp)
320 #if defined(IO_URING_SCM_ALL)
323 return !!unix_get_socket(filp);
327 static inline bool io_file_need_scm(struct file *filp)
333 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
336 mutex_lock(&ctx->uring_lock);
341 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
343 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
344 __io_submit_flush_completions(ctx);
347 #define IO_RSRC_REF_BATCH 100
349 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
351 percpu_ref_put_many(&node->refs, nr);
354 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
355 struct io_ring_ctx *ctx)
356 __must_hold(&ctx->uring_lock)
358 struct io_rsrc_node *node = req->rsrc_node;
361 if (node == ctx->rsrc_node)
362 ctx->rsrc_cached_refs++;
364 io_rsrc_put_node(node, 1);
368 static inline void io_req_put_rsrc(struct io_kiocb *req)
371 io_rsrc_put_node(req->rsrc_node, 1);
374 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
375 __must_hold(&ctx->uring_lock)
377 if (ctx->rsrc_cached_refs) {
378 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
379 ctx->rsrc_cached_refs = 0;
383 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
384 __must_hold(&ctx->uring_lock)
386 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
387 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
390 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
391 struct io_ring_ctx *ctx,
392 unsigned int issue_flags)
394 if (!req->rsrc_node) {
395 req->rsrc_node = ctx->rsrc_node;
397 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
398 lockdep_assert_held(&ctx->uring_lock);
399 ctx->rsrc_cached_refs--;
400 if (unlikely(ctx->rsrc_cached_refs < 0))
401 io_rsrc_refs_refill(ctx);
403 percpu_ref_get(&req->rsrc_node->refs);
408 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
410 if (req->flags & REQ_F_BUFFER_RING) {
412 req->buf_list->head++;
413 req->flags &= ~REQ_F_BUFFER_RING;
415 list_add(&req->kbuf->list, list);
416 req->flags &= ~REQ_F_BUFFER_SELECTED;
419 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
422 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
424 lockdep_assert_held(&req->ctx->completion_lock);
426 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
428 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
431 inline unsigned int io_put_kbuf(struct io_kiocb *req, unsigned issue_flags)
435 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
439 * We can add this buffer back to two lists:
441 * 1) The io_buffers_cache list. This one is protected by the
442 * ctx->uring_lock. If we already hold this lock, add back to this
443 * list as we can grab it from issue as well.
444 * 2) The io_buffers_comp list. This one is protected by the
445 * ctx->completion_lock.
447 * We migrate buffers from the comp_list to the issue cache list
450 if (req->flags & REQ_F_BUFFER_RING) {
451 /* no buffers to recycle for this case */
452 cflags = __io_put_kbuf(req, NULL);
453 } else if (issue_flags & IO_URING_F_UNLOCKED) {
454 struct io_ring_ctx *ctx = req->ctx;
456 spin_lock(&ctx->completion_lock);
457 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
458 spin_unlock(&ctx->completion_lock);
460 lockdep_assert_held(&req->ctx->uring_lock);
462 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
468 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
471 if (ctx->io_bl && bgid < BGID_ARRAY)
472 return &ctx->io_bl[bgid];
474 return xa_load(&ctx->io_bl_xa, bgid);
477 void __io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
479 struct io_ring_ctx *ctx = req->ctx;
480 struct io_buffer_list *bl;
481 struct io_buffer *buf;
484 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
485 * the flag and hence ensure that bl->head doesn't get incremented.
486 * If the tail has already been incremented, hang on to it.
488 if (req->flags & REQ_F_BUFFER_RING) {
490 if (req->flags & REQ_F_PARTIAL_IO) {
491 req->buf_list->head++;
492 req->buf_list = NULL;
494 req->buf_index = req->buf_list->bgid;
495 req->flags &= ~REQ_F_BUFFER_RING;
501 io_ring_submit_lock(ctx, issue_flags);
504 bl = io_buffer_get_list(ctx, buf->bgid);
505 list_add(&buf->list, &bl->buf_list);
506 req->flags &= ~REQ_F_BUFFER_SELECTED;
507 req->buf_index = buf->bgid;
509 io_ring_submit_unlock(ctx, issue_flags);
512 static bool io_match_linked(struct io_kiocb *head)
514 struct io_kiocb *req;
516 io_for_each_link(req, head) {
517 if (req->flags & REQ_F_INFLIGHT)
524 * As io_match_task() but protected against racing with linked timeouts.
525 * User must not hold timeout_lock.
527 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
532 if (task && head->task != task)
537 if (head->flags & REQ_F_LINK_TIMEOUT) {
538 struct io_ring_ctx *ctx = head->ctx;
540 /* protect against races with linked timeouts */
541 spin_lock_irq(&ctx->timeout_lock);
542 matched = io_match_linked(head);
543 spin_unlock_irq(&ctx->timeout_lock);
545 matched = io_match_linked(head);
550 static inline void req_fail_link_node(struct io_kiocb *req, int res)
553 io_req_set_res(req, res, 0);
556 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
558 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
561 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
563 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
565 complete(&ctx->ref_comp);
568 static __cold void io_fallback_req_func(struct work_struct *work)
570 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
572 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
573 struct io_kiocb *req, *tmp;
576 percpu_ref_get(&ctx->refs);
577 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
578 req->io_task_work.func(req, &locked);
581 io_submit_flush_completions(ctx);
582 mutex_unlock(&ctx->uring_lock);
584 percpu_ref_put(&ctx->refs);
587 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
589 struct io_ring_ctx *ctx;
592 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
596 xa_init(&ctx->io_bl_xa);
599 * Use 5 bits less than the max cq entries, that should give us around
600 * 32 entries per hash list if totally full and uniformly spread.
602 hash_bits = ilog2(p->cq_entries);
606 ctx->cancel_hash_bits = hash_bits;
607 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
609 if (!ctx->cancel_hash)
611 __hash_init(ctx->cancel_hash, 1U << hash_bits);
613 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
614 if (!ctx->dummy_ubuf)
616 /* set invalid range, so io_import_fixed() fails meeting it */
617 ctx->dummy_ubuf->ubuf = -1UL;
619 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
620 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
623 ctx->flags = p->flags;
624 init_waitqueue_head(&ctx->sqo_sq_wait);
625 INIT_LIST_HEAD(&ctx->sqd_list);
626 INIT_LIST_HEAD(&ctx->cq_overflow_list);
627 INIT_LIST_HEAD(&ctx->io_buffers_cache);
628 INIT_LIST_HEAD(&ctx->apoll_cache);
629 init_completion(&ctx->ref_comp);
630 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
631 mutex_init(&ctx->uring_lock);
632 init_waitqueue_head(&ctx->cq_wait);
633 spin_lock_init(&ctx->completion_lock);
634 spin_lock_init(&ctx->timeout_lock);
635 INIT_WQ_LIST(&ctx->iopoll_list);
636 INIT_LIST_HEAD(&ctx->io_buffers_pages);
637 INIT_LIST_HEAD(&ctx->io_buffers_comp);
638 INIT_LIST_HEAD(&ctx->defer_list);
639 INIT_LIST_HEAD(&ctx->timeout_list);
640 INIT_LIST_HEAD(&ctx->ltimeout_list);
641 spin_lock_init(&ctx->rsrc_ref_lock);
642 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
643 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
644 init_llist_head(&ctx->rsrc_put_llist);
645 INIT_LIST_HEAD(&ctx->tctx_list);
646 ctx->submit_state.free_list.next = NULL;
647 INIT_WQ_LIST(&ctx->locked_free_list);
648 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
649 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
652 kfree(ctx->dummy_ubuf);
653 kfree(ctx->cancel_hash);
655 xa_destroy(&ctx->io_bl_xa);
660 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
662 struct io_rings *r = ctx->rings;
664 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
668 static bool req_need_defer(struct io_kiocb *req, u32 seq)
670 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
671 struct io_ring_ctx *ctx = req->ctx;
673 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
679 static inline bool io_req_ffs_set(struct io_kiocb *req)
681 return req->flags & REQ_F_FIXED_FILE;
684 static inline void io_req_track_inflight(struct io_kiocb *req)
686 if (!(req->flags & REQ_F_INFLIGHT)) {
687 req->flags |= REQ_F_INFLIGHT;
688 atomic_inc(&req->task->io_uring->inflight_tracked);
692 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
694 if (WARN_ON_ONCE(!req->link))
697 req->flags &= ~REQ_F_ARM_LTIMEOUT;
698 req->flags |= REQ_F_LINK_TIMEOUT;
700 /* linked timeouts should have two refs once prep'ed */
701 io_req_set_refcount(req);
702 __io_req_set_refcount(req->link, 2);
706 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
708 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
710 return __io_prep_linked_timeout(req);
713 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
715 io_queue_linked_timeout(__io_prep_linked_timeout(req));
718 static inline void io_arm_ltimeout(struct io_kiocb *req)
720 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
721 __io_arm_ltimeout(req);
724 static void io_prep_async_work(struct io_kiocb *req)
726 const struct io_op_def *def = &io_op_defs[req->opcode];
727 struct io_ring_ctx *ctx = req->ctx;
729 if (!(req->flags & REQ_F_CREDS)) {
730 req->flags |= REQ_F_CREDS;
731 req->creds = get_current_cred();
734 req->work.list.next = NULL;
736 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
737 if (req->flags & REQ_F_FORCE_ASYNC)
738 req->work.flags |= IO_WQ_WORK_CONCURRENT;
740 if (req->flags & REQ_F_ISREG) {
741 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
742 io_wq_hash_work(&req->work, file_inode(req->file));
743 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
744 if (def->unbound_nonreg_file)
745 req->work.flags |= IO_WQ_WORK_UNBOUND;
749 static void io_prep_async_link(struct io_kiocb *req)
751 struct io_kiocb *cur;
753 if (req->flags & REQ_F_LINK_TIMEOUT) {
754 struct io_ring_ctx *ctx = req->ctx;
756 spin_lock_irq(&ctx->timeout_lock);
757 io_for_each_link(cur, req)
758 io_prep_async_work(cur);
759 spin_unlock_irq(&ctx->timeout_lock);
761 io_for_each_link(cur, req)
762 io_prep_async_work(cur);
766 static inline void io_req_add_compl_list(struct io_kiocb *req)
768 struct io_submit_state *state = &req->ctx->submit_state;
770 if (!(req->flags & REQ_F_CQE_SKIP))
771 state->flush_cqes = true;
772 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
775 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
777 struct io_kiocb *link = io_prep_linked_timeout(req);
778 struct io_uring_task *tctx = req->task->io_uring;
781 BUG_ON(!tctx->io_wq);
783 /* init ->work of the whole link before punting */
784 io_prep_async_link(req);
787 * Not expected to happen, but if we do have a bug where this _can_
788 * happen, catch it here and ensure the request is marked as
789 * canceled. That will make io-wq go through the usual work cancel
790 * procedure rather than attempt to run this request (or create a new
793 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
794 req->work.flags |= IO_WQ_WORK_CANCEL;
796 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
797 req->opcode, req->flags, &req->work,
798 io_wq_is_hashed(&req->work));
799 io_wq_enqueue(tctx->io_wq, &req->work);
801 io_queue_linked_timeout(link);
804 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
806 while (!list_empty(&ctx->defer_list)) {
807 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
808 struct io_defer_entry, list);
810 if (req_need_defer(de->req, de->seq))
812 list_del_init(&de->list);
813 io_req_task_queue(de->req);
818 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
820 if (ctx->off_timeout_used || ctx->drain_active) {
821 spin_lock(&ctx->completion_lock);
822 if (ctx->off_timeout_used)
823 io_flush_timeouts(ctx);
824 if (ctx->drain_active)
825 io_queue_deferred(ctx);
826 io_commit_cqring(ctx);
827 spin_unlock(&ctx->completion_lock);
830 io_eventfd_signal(ctx);
833 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
835 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
839 * writes to the cq entry need to come after reading head; the
840 * control dependency is enough as we're using WRITE_ONCE to
843 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
845 struct io_rings *rings = ctx->rings;
846 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
847 unsigned int shift = 0;
848 unsigned int free, queued, len;
850 if (ctx->flags & IORING_SETUP_CQE32)
853 /* userspace may cheat modifying the tail, be safe and do min */
854 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
855 free = ctx->cq_entries - queued;
856 /* we need a contiguous range, limit based on the current array offset */
857 len = min(free, ctx->cq_entries - off);
861 ctx->cached_cq_tail++;
862 ctx->cqe_cached = &rings->cqes[off];
863 ctx->cqe_sentinel = ctx->cqe_cached + len;
865 return &rings->cqes[off << shift];
868 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
870 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
871 struct io_uring_cqe *cqe = ctx->cqe_cached;
873 if (ctx->flags & IORING_SETUP_CQE32) {
874 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
879 ctx->cached_cq_tail++;
884 return __io_get_cqe(ctx);
887 static void io_eventfd_signal(struct io_ring_ctx *ctx)
889 struct io_ev_fd *ev_fd;
893 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
896 ev_fd = rcu_dereference(ctx->io_ev_fd);
899 * Check again if ev_fd exists incase an io_eventfd_unregister call
900 * completed between the NULL check of ctx->io_ev_fd at the start of
901 * the function and rcu_read_lock.
903 if (unlikely(!ev_fd))
905 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
908 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
909 eventfd_signal(ev_fd->cq_ev_fd, 1);
914 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
917 * wake_up_all() may seem excessive, but io_wake_function() and
918 * io_should_wake() handle the termination of the loop and only
919 * wake as many waiters as we need to.
921 if (wq_has_sleeper(&ctx->cq_wait))
922 wake_up_all(&ctx->cq_wait);
926 * This should only get called when at least one event has been posted.
927 * Some applications rely on the eventfd notification count only changing
928 * IFF a new CQE has been added to the CQ ring. There's no depedency on
929 * 1:1 relationship between how many times this function is called (and
930 * hence the eventfd count) and number of CQEs posted to the CQ ring.
932 void io_cqring_ev_posted(struct io_ring_ctx *ctx)
934 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
936 __io_commit_cqring_flush(ctx);
941 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
943 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
945 __io_commit_cqring_flush(ctx);
947 if (ctx->flags & IORING_SETUP_SQPOLL)
951 /* Returns true if there are no backlogged entries after the flush */
952 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
954 bool all_flushed, posted;
955 size_t cqe_size = sizeof(struct io_uring_cqe);
957 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
960 if (ctx->flags & IORING_SETUP_CQE32)
964 spin_lock(&ctx->completion_lock);
965 while (!list_empty(&ctx->cq_overflow_list)) {
966 struct io_uring_cqe *cqe = io_get_cqe(ctx);
967 struct io_overflow_cqe *ocqe;
971 ocqe = list_first_entry(&ctx->cq_overflow_list,
972 struct io_overflow_cqe, list);
974 memcpy(cqe, &ocqe->cqe, cqe_size);
976 io_account_cq_overflow(ctx);
979 list_del(&ocqe->list);
983 all_flushed = list_empty(&ctx->cq_overflow_list);
985 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
986 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
989 io_commit_cqring(ctx);
990 spin_unlock(&ctx->completion_lock);
992 io_cqring_ev_posted(ctx);
996 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1000 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
1001 /* iopoll syncs against uring_lock, not completion_lock */
1002 if (ctx->flags & IORING_SETUP_IOPOLL)
1003 mutex_lock(&ctx->uring_lock);
1004 ret = __io_cqring_overflow_flush(ctx, false);
1005 if (ctx->flags & IORING_SETUP_IOPOLL)
1006 mutex_unlock(&ctx->uring_lock);
1012 static void __io_put_task(struct task_struct *task, int nr)
1014 struct io_uring_task *tctx = task->io_uring;
1016 percpu_counter_sub(&tctx->inflight, nr);
1017 if (unlikely(atomic_read(&tctx->in_idle)))
1018 wake_up(&tctx->wait);
1019 put_task_struct_many(task, nr);
1022 /* must to be called somewhat shortly after putting a request */
1023 static inline void io_put_task(struct task_struct *task, int nr)
1025 if (likely(task == current))
1026 task->io_uring->cached_refs += nr;
1028 __io_put_task(task, nr);
1031 static void io_task_refs_refill(struct io_uring_task *tctx)
1033 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1035 percpu_counter_add(&tctx->inflight, refill);
1036 refcount_add(refill, ¤t->usage);
1037 tctx->cached_refs += refill;
1040 static inline void io_get_task_refs(int nr)
1042 struct io_uring_task *tctx = current->io_uring;
1044 tctx->cached_refs -= nr;
1045 if (unlikely(tctx->cached_refs < 0))
1046 io_task_refs_refill(tctx);
1049 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1051 struct io_uring_task *tctx = task->io_uring;
1052 unsigned int refs = tctx->cached_refs;
1055 tctx->cached_refs = 0;
1056 percpu_counter_sub(&tctx->inflight, refs);
1057 put_task_struct_many(task, refs);
1061 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1062 s32 res, u32 cflags, u64 extra1,
1065 struct io_overflow_cqe *ocqe;
1066 size_t ocq_size = sizeof(struct io_overflow_cqe);
1067 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
1070 ocq_size += sizeof(struct io_uring_cqe);
1072 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
1073 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
1076 * If we're in ring overflow flush mode, or in task cancel mode,
1077 * or cannot allocate an overflow entry, then we need to drop it
1080 io_account_cq_overflow(ctx);
1081 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
1084 if (list_empty(&ctx->cq_overflow_list)) {
1085 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1086 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1089 ocqe->cqe.user_data = user_data;
1090 ocqe->cqe.res = res;
1091 ocqe->cqe.flags = cflags;
1093 ocqe->cqe.big_cqe[0] = extra1;
1094 ocqe->cqe.big_cqe[1] = extra2;
1096 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1100 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
1101 struct io_kiocb *req)
1103 struct io_uring_cqe *cqe;
1105 if (!(ctx->flags & IORING_SETUP_CQE32)) {
1106 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1107 req->cqe.res, req->cqe.flags, 0, 0);
1110 * If we can't get a cq entry, userspace overflowed the
1111 * submission (by quite a lot). Increment the overflow count in
1114 cqe = io_get_cqe(ctx);
1116 memcpy(cqe, &req->cqe, sizeof(*cqe));
1120 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1121 req->cqe.res, req->cqe.flags,
1124 u64 extra1 = 0, extra2 = 0;
1126 if (req->flags & REQ_F_CQE32_INIT) {
1127 extra1 = req->extra1;
1128 extra2 = req->extra2;
1131 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1132 req->cqe.res, req->cqe.flags, extra1, extra2);
1135 * If we can't get a cq entry, userspace overflowed the
1136 * submission (by quite a lot). Increment the overflow count in
1139 cqe = io_get_cqe(ctx);
1141 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
1142 WRITE_ONCE(cqe->big_cqe[0], extra1);
1143 WRITE_ONCE(cqe->big_cqe[1], extra2);
1147 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1148 req->cqe.res, req->cqe.flags,
1153 bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
1156 struct io_uring_cqe *cqe;
1159 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
1162 * If we can't get a cq entry, userspace overflowed the
1163 * submission (by quite a lot). Increment the overflow count in
1166 cqe = io_get_cqe(ctx);
1168 WRITE_ONCE(cqe->user_data, user_data);
1169 WRITE_ONCE(cqe->res, res);
1170 WRITE_ONCE(cqe->flags, cflags);
1172 if (ctx->flags & IORING_SETUP_CQE32) {
1173 WRITE_ONCE(cqe->big_cqe[0], 0);
1174 WRITE_ONCE(cqe->big_cqe[1], 0);
1178 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
1181 static void __io_req_complete_put(struct io_kiocb *req)
1184 * If we're the last reference to this request, add to our locked
1187 if (req_ref_put_and_test(req)) {
1188 struct io_ring_ctx *ctx = req->ctx;
1190 if (req->flags & IO_REQ_LINK_FLAGS) {
1191 if (req->flags & IO_DISARM_MASK)
1192 io_disarm_next(req);
1194 io_req_task_queue(req->link);
1198 io_req_put_rsrc(req);
1200 * Selected buffer deallocation in io_clean_op() assumes that
1201 * we don't hold ->completion_lock. Clean them here to avoid
1204 io_put_kbuf_comp(req);
1205 io_dismantle_req(req);
1206 io_put_task(req->task, 1);
1207 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1208 ctx->locked_free_nr++;
1212 void __io_req_complete_post(struct io_kiocb *req)
1214 if (!(req->flags & REQ_F_CQE_SKIP))
1215 __io_fill_cqe_req(req->ctx, req);
1216 __io_req_complete_put(req);
1219 void io_req_complete_post(struct io_kiocb *req)
1221 struct io_ring_ctx *ctx = req->ctx;
1223 spin_lock(&ctx->completion_lock);
1224 __io_req_complete_post(req);
1225 io_commit_cqring(ctx);
1226 spin_unlock(&ctx->completion_lock);
1227 io_cqring_ev_posted(ctx);
1230 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
1232 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1233 req->flags |= REQ_F_COMPLETE_INLINE;
1235 io_req_complete_post(req);
1238 void io_req_complete_failed(struct io_kiocb *req, s32 res)
1241 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1242 io_req_complete_post(req);
1246 * Don't initialise the fields below on every allocation, but do that in
1247 * advance and keep them valid across allocations.
1249 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1253 req->async_data = NULL;
1254 /* not necessary, but safer to zero */
1258 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1259 struct io_submit_state *state)
1261 spin_lock(&ctx->completion_lock);
1262 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1263 ctx->locked_free_nr = 0;
1264 spin_unlock(&ctx->completion_lock);
1267 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
1269 return !ctx->submit_state.free_list.next;
1273 * A request might get retired back into the request caches even before opcode
1274 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1275 * Because of that, io_alloc_req() should be called only under ->uring_lock
1276 * and with extra caution to not get a request that is still worked on.
1278 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1279 __must_hold(&ctx->uring_lock)
1281 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1282 void *reqs[IO_REQ_ALLOC_BATCH];
1286 * If we have more than a batch's worth of requests in our IRQ side
1287 * locked cache, grab the lock and move them over to our submission
1290 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1291 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1292 if (!io_req_cache_empty(ctx))
1296 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1299 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1300 * retry single alloc to be on the safe side.
1302 if (unlikely(ret <= 0)) {
1303 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1309 percpu_ref_get_many(&ctx->refs, ret);
1310 for (i = 0; i < ret; i++) {
1311 struct io_kiocb *req = reqs[i];
1313 io_preinit_req(req, ctx);
1314 io_req_add_to_cache(req, ctx);
1319 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
1321 if (unlikely(io_req_cache_empty(ctx)))
1322 return __io_alloc_req_refill(ctx);
1326 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1328 struct io_wq_work_node *node;
1330 node = wq_stack_extract(&ctx->submit_state.free_list);
1331 return container_of(node, struct io_kiocb, comp_list);
1334 static inline void io_dismantle_req(struct io_kiocb *req)
1336 unsigned int flags = req->flags;
1338 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
1340 if (!(flags & REQ_F_FIXED_FILE))
1341 io_put_file(req->file);
1344 __cold void io_free_req(struct io_kiocb *req)
1346 struct io_ring_ctx *ctx = req->ctx;
1348 io_req_put_rsrc(req);
1349 io_dismantle_req(req);
1350 io_put_task(req->task, 1);
1352 spin_lock(&ctx->completion_lock);
1353 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1354 ctx->locked_free_nr++;
1355 spin_unlock(&ctx->completion_lock);
1358 static void __io_req_find_next_prep(struct io_kiocb *req)
1360 struct io_ring_ctx *ctx = req->ctx;
1363 spin_lock(&ctx->completion_lock);
1364 posted = io_disarm_next(req);
1365 io_commit_cqring(ctx);
1366 spin_unlock(&ctx->completion_lock);
1368 io_cqring_ev_posted(ctx);
1371 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1373 struct io_kiocb *nxt;
1376 * If LINK is set, we have dependent requests in this chain. If we
1377 * didn't fail this request, queue the first one up, moving any other
1378 * dependencies to the next request. In case of failure, fail the rest
1381 if (unlikely(req->flags & IO_DISARM_MASK))
1382 __io_req_find_next_prep(req);
1388 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
1392 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1393 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1395 io_submit_flush_completions(ctx);
1396 mutex_unlock(&ctx->uring_lock);
1399 percpu_ref_put(&ctx->refs);
1402 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
1404 io_commit_cqring(ctx);
1405 spin_unlock(&ctx->completion_lock);
1406 io_cqring_ev_posted(ctx);
1409 static void handle_prev_tw_list(struct io_wq_work_node *node,
1410 struct io_ring_ctx **ctx, bool *uring_locked)
1412 if (*ctx && !*uring_locked)
1413 spin_lock(&(*ctx)->completion_lock);
1416 struct io_wq_work_node *next = node->next;
1417 struct io_kiocb *req = container_of(node, struct io_kiocb,
1420 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1422 if (req->ctx != *ctx) {
1423 if (unlikely(!*uring_locked && *ctx))
1424 ctx_commit_and_unlock(*ctx);
1426 ctx_flush_and_put(*ctx, uring_locked);
1428 /* if not contended, grab and improve batching */
1429 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
1430 percpu_ref_get(&(*ctx)->refs);
1431 if (unlikely(!*uring_locked))
1432 spin_lock(&(*ctx)->completion_lock);
1434 if (likely(*uring_locked)) {
1435 req->io_task_work.func(req, uring_locked);
1437 req->cqe.flags = io_put_kbuf_comp(req);
1438 __io_req_complete_post(req);
1443 if (unlikely(!*uring_locked))
1444 ctx_commit_and_unlock(*ctx);
1447 static void handle_tw_list(struct io_wq_work_node *node,
1448 struct io_ring_ctx **ctx, bool *locked)
1451 struct io_wq_work_node *next = node->next;
1452 struct io_kiocb *req = container_of(node, struct io_kiocb,
1455 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1457 if (req->ctx != *ctx) {
1458 ctx_flush_and_put(*ctx, locked);
1460 /* if not contended, grab and improve batching */
1461 *locked = mutex_trylock(&(*ctx)->uring_lock);
1462 percpu_ref_get(&(*ctx)->refs);
1464 req->io_task_work.func(req, locked);
1469 void tctx_task_work(struct callback_head *cb)
1471 bool uring_locked = false;
1472 struct io_ring_ctx *ctx = NULL;
1473 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1477 struct io_wq_work_node *node1, *node2;
1479 spin_lock_irq(&tctx->task_lock);
1480 node1 = tctx->prio_task_list.first;
1481 node2 = tctx->task_list.first;
1482 INIT_WQ_LIST(&tctx->task_list);
1483 INIT_WQ_LIST(&tctx->prio_task_list);
1484 if (!node2 && !node1)
1485 tctx->task_running = false;
1486 spin_unlock_irq(&tctx->task_lock);
1487 if (!node2 && !node1)
1491 handle_prev_tw_list(node1, &ctx, &uring_locked);
1493 handle_tw_list(node2, &ctx, &uring_locked);
1496 if (data_race(!tctx->task_list.first) &&
1497 data_race(!tctx->prio_task_list.first) && uring_locked)
1498 io_submit_flush_completions(ctx);
1501 ctx_flush_and_put(ctx, &uring_locked);
1503 /* relaxed read is enough as only the task itself sets ->in_idle */
1504 if (unlikely(atomic_read(&tctx->in_idle)))
1505 io_uring_drop_tctx_refs(current);
1508 static void __io_req_task_work_add(struct io_kiocb *req,
1509 struct io_uring_task *tctx,
1510 struct io_wq_work_list *list)
1512 struct io_ring_ctx *ctx = req->ctx;
1513 struct io_wq_work_node *node;
1514 unsigned long flags;
1517 spin_lock_irqsave(&tctx->task_lock, flags);
1518 wq_list_add_tail(&req->io_task_work.node, list);
1519 running = tctx->task_running;
1521 tctx->task_running = true;
1522 spin_unlock_irqrestore(&tctx->task_lock, flags);
1524 /* task_work already pending, we're done */
1528 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1529 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1531 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1534 spin_lock_irqsave(&tctx->task_lock, flags);
1535 tctx->task_running = false;
1536 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
1537 spin_unlock_irqrestore(&tctx->task_lock, flags);
1540 req = container_of(node, struct io_kiocb, io_task_work.node);
1542 if (llist_add(&req->io_task_work.fallback_node,
1543 &req->ctx->fallback_llist))
1544 schedule_delayed_work(&req->ctx->fallback_work, 1);
1548 void io_req_task_work_add(struct io_kiocb *req)
1550 struct io_uring_task *tctx = req->task->io_uring;
1552 __io_req_task_work_add(req, tctx, &tctx->task_list);
1555 static void io_req_task_prio_work_add(struct io_kiocb *req)
1557 struct io_uring_task *tctx = req->task->io_uring;
1559 if (req->ctx->flags & IORING_SETUP_SQPOLL)
1560 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
1562 __io_req_task_work_add(req, tctx, &tctx->task_list);
1565 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
1567 io_req_complete_post(req);
1570 void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
1572 io_req_set_res(req, res, cflags);
1573 req->io_task_work.func = io_req_tw_post;
1574 io_req_task_work_add(req);
1577 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
1579 /* not needed for normal modes, but SQPOLL depends on it */
1580 io_tw_lock(req->ctx, locked);
1581 io_req_complete_failed(req, req->cqe.res);
1584 void io_req_task_submit(struct io_kiocb *req, bool *locked)
1586 io_tw_lock(req->ctx, locked);
1587 /* req->task == current here, checking PF_EXITING is safe */
1588 if (likely(!(req->task->flags & PF_EXITING)))
1591 io_req_complete_failed(req, -EFAULT);
1594 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1596 io_req_set_res(req, ret, 0);
1597 req->io_task_work.func = io_req_task_cancel;
1598 io_req_task_work_add(req);
1601 static void io_req_task_queue(struct io_kiocb *req)
1603 req->io_task_work.func = io_req_task_submit;
1604 io_req_task_work_add(req);
1607 static void io_req_task_queue_reissue(struct io_kiocb *req)
1609 req->io_task_work.func = io_queue_iowq;
1610 io_req_task_work_add(req);
1613 void io_queue_next(struct io_kiocb *req)
1615 struct io_kiocb *nxt = io_req_find_next(req);
1618 io_req_task_queue(nxt);
1621 static void io_free_batch_list(struct io_ring_ctx *ctx,
1622 struct io_wq_work_node *node)
1623 __must_hold(&ctx->uring_lock)
1625 struct task_struct *task = NULL;
1629 struct io_kiocb *req = container_of(node, struct io_kiocb,
1632 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1633 if (req->flags & REQ_F_REFCOUNT) {
1634 node = req->comp_list.next;
1635 if (!req_ref_put_and_test(req))
1638 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1639 struct async_poll *apoll = req->apoll;
1641 if (apoll->double_poll)
1642 kfree(apoll->double_poll);
1643 list_add(&apoll->poll.wait.entry,
1645 req->flags &= ~REQ_F_POLLED;
1647 if (req->flags & IO_REQ_LINK_FLAGS)
1649 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1652 if (!(req->flags & REQ_F_FIXED_FILE))
1653 io_put_file(req->file);
1655 io_req_put_rsrc_locked(req, ctx);
1657 if (req->task != task) {
1659 io_put_task(task, task_refs);
1664 node = req->comp_list.next;
1665 io_req_add_to_cache(req, ctx);
1669 io_put_task(task, task_refs);
1672 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1673 __must_hold(&ctx->uring_lock)
1675 struct io_wq_work_node *node, *prev;
1676 struct io_submit_state *state = &ctx->submit_state;
1678 if (state->flush_cqes) {
1679 spin_lock(&ctx->completion_lock);
1680 wq_list_for_each(node, prev, &state->compl_reqs) {
1681 struct io_kiocb *req = container_of(node, struct io_kiocb,
1684 if (!(req->flags & REQ_F_CQE_SKIP))
1685 __io_fill_cqe_req(ctx, req);
1688 io_commit_cqring(ctx);
1689 spin_unlock(&ctx->completion_lock);
1690 io_cqring_ev_posted(ctx);
1691 state->flush_cqes = false;
1694 io_free_batch_list(ctx, state->compl_reqs.first);
1695 INIT_WQ_LIST(&state->compl_reqs);
1699 * Drop reference to request, return next in chain (if there is one) if this
1700 * was the last reference to this request.
1702 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
1704 struct io_kiocb *nxt = NULL;
1706 if (req_ref_put_and_test(req)) {
1707 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
1708 nxt = io_req_find_next(req);
1714 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1716 /* See comment at the top of this file */
1718 return __io_cqring_events(ctx);
1721 int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
1723 struct io_wq_work_node *pos, *start, *prev;
1724 unsigned int poll_flags = BLK_POLL_NOSLEEP;
1725 DEFINE_IO_COMP_BATCH(iob);
1729 * Only spin for completions if we don't have multiple devices hanging
1730 * off our complete list.
1732 if (ctx->poll_multi_queue || force_nonspin)
1733 poll_flags |= BLK_POLL_ONESHOT;
1735 wq_list_for_each(pos, start, &ctx->iopoll_list) {
1736 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1737 struct io_rw *rw = io_kiocb_to_cmd(req);
1741 * Move completed and retryable entries to our local lists.
1742 * If we find a request that requires polling, break out
1743 * and complete those lists first, if we have entries there.
1745 if (READ_ONCE(req->iopoll_completed))
1748 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
1749 if (unlikely(ret < 0))
1752 poll_flags |= BLK_POLL_ONESHOT;
1754 /* iopoll may have completed current req */
1755 if (!rq_list_empty(iob.req_list) ||
1756 READ_ONCE(req->iopoll_completed))
1760 if (!rq_list_empty(iob.req_list))
1766 wq_list_for_each_resume(pos, prev) {
1767 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1769 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
1770 if (!smp_load_acquire(&req->iopoll_completed))
1773 if (unlikely(req->flags & REQ_F_CQE_SKIP))
1776 req->cqe.flags = io_put_kbuf(req, 0);
1777 __io_fill_cqe_req(req->ctx, req);
1780 if (unlikely(!nr_events))
1783 io_commit_cqring(ctx);
1784 io_cqring_ev_posted_iopoll(ctx);
1785 pos = start ? start->next : ctx->iopoll_list.first;
1786 wq_list_cut(&ctx->iopoll_list, prev, start);
1787 io_free_batch_list(ctx, pos);
1792 * We can't just wait for polled events to come to us, we have to actively
1793 * find and complete them.
1795 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1797 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1800 mutex_lock(&ctx->uring_lock);
1801 while (!wq_list_empty(&ctx->iopoll_list)) {
1802 /* let it sleep and repeat later if can't complete a request */
1803 if (io_do_iopoll(ctx, true) == 0)
1806 * Ensure we allow local-to-the-cpu processing to take place,
1807 * in this case we need to ensure that we reap all events.
1808 * Also let task_work, etc. to progress by releasing the mutex
1810 if (need_resched()) {
1811 mutex_unlock(&ctx->uring_lock);
1813 mutex_lock(&ctx->uring_lock);
1816 mutex_unlock(&ctx->uring_lock);
1819 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1821 unsigned int nr_events = 0;
1823 unsigned long check_cq;
1826 * Don't enter poll loop if we already have events pending.
1827 * If we do, we can potentially be spinning for commands that
1828 * already triggered a CQE (eg in error).
1830 check_cq = READ_ONCE(ctx->check_cq);
1831 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1832 __io_cqring_overflow_flush(ctx, false);
1833 if (io_cqring_events(ctx))
1837 * Similarly do not spin if we have not informed the user of any
1840 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
1845 * If a submit got punted to a workqueue, we can have the
1846 * application entering polling for a command before it gets
1847 * issued. That app will hold the uring_lock for the duration
1848 * of the poll right here, so we need to take a breather every
1849 * now and then to ensure that the issue has a chance to add
1850 * the poll to the issued list. Otherwise we can spin here
1851 * forever, while the workqueue is stuck trying to acquire the
1854 if (wq_list_empty(&ctx->iopoll_list)) {
1855 u32 tail = ctx->cached_cq_tail;
1857 mutex_unlock(&ctx->uring_lock);
1859 mutex_lock(&ctx->uring_lock);
1861 /* some requests don't go through iopoll_list */
1862 if (tail != ctx->cached_cq_tail ||
1863 wq_list_empty(&ctx->iopoll_list))
1866 ret = io_do_iopoll(ctx, !min);
1871 } while (nr_events < min && !need_resched());
1876 static void kiocb_end_write(struct io_kiocb *req)
1879 * Tell lockdep we inherited freeze protection from submission
1882 if (req->flags & REQ_F_ISREG) {
1883 struct super_block *sb = file_inode(req->file)->i_sb;
1885 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
1891 static bool io_resubmit_prep(struct io_kiocb *req)
1893 struct io_async_rw *io = req->async_data;
1895 if (!req_has_async_data(req))
1896 return !io_req_prep_async(req);
1897 iov_iter_restore(&io->s.iter, &io->s.iter_state);
1901 static bool io_rw_should_reissue(struct io_kiocb *req)
1903 umode_t mode = file_inode(req->file)->i_mode;
1904 struct io_ring_ctx *ctx = req->ctx;
1906 if (!S_ISBLK(mode) && !S_ISREG(mode))
1908 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
1909 !(ctx->flags & IORING_SETUP_IOPOLL)))
1912 * If ref is dying, we might be running poll reap from the exit work.
1913 * Don't attempt to reissue from that path, just let it fail with
1916 if (percpu_ref_is_dying(&ctx->refs))
1919 * Play it safe and assume not safe to re-import and reissue if we're
1920 * not in the original thread group (or in task context).
1922 if (!same_thread_group(req->task, current) || !in_task())
1927 static bool io_resubmit_prep(struct io_kiocb *req)
1931 static bool io_rw_should_reissue(struct io_kiocb *req)
1937 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
1939 struct io_rw *rw = io_kiocb_to_cmd(req);
1941 if (rw->kiocb.ki_flags & IOCB_WRITE) {
1942 kiocb_end_write(req);
1943 fsnotify_modify(req->file);
1945 fsnotify_access(req->file);
1947 if (unlikely(res != req->cqe.res)) {
1948 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
1949 io_rw_should_reissue(req)) {
1950 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
1959 inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
1962 req->cqe.flags |= io_put_kbuf(req, 0);
1963 req->flags |= REQ_F_COMPLETE_INLINE;
1964 io_req_add_compl_list(req);
1966 req->cqe.flags |= io_put_kbuf(req, IO_URING_F_UNLOCKED);
1967 io_req_complete_post(req);
1971 static void __io_complete_rw(struct io_kiocb *req, long res,
1972 unsigned int issue_flags)
1974 if (__io_complete_rw_common(req, res))
1976 io_req_set_res(req, req->cqe.res, io_put_kbuf(req, issue_flags));
1977 __io_req_complete(req, issue_flags);
1980 static void io_complete_rw(struct kiocb *kiocb, long res)
1982 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1983 struct io_kiocb *req = cmd_to_io_kiocb(rw);
1985 if (__io_complete_rw_common(req, res))
1987 io_req_set_res(req, res, 0);
1988 req->io_task_work.func = io_req_task_complete;
1989 io_req_task_prio_work_add(req);
1992 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
1994 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1995 struct io_kiocb *req = cmd_to_io_kiocb(rw);
1997 if (kiocb->ki_flags & IOCB_WRITE)
1998 kiocb_end_write(req);
1999 if (unlikely(res != req->cqe.res)) {
2000 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2001 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2007 /* order with io_iopoll_complete() checking ->iopoll_completed */
2008 smp_store_release(&req->iopoll_completed, 1);
2012 * After the iocb has been issued, it's safe to be found on the poll list.
2013 * Adding the kiocb to the list AFTER submission ensures that we don't
2014 * find it from a io_do_iopoll() thread before the issuer is done
2015 * accessing the kiocb cookie.
2017 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2019 struct io_ring_ctx *ctx = req->ctx;
2020 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2022 /* workqueue context doesn't hold uring_lock, grab it now */
2023 if (unlikely(needs_lock))
2024 mutex_lock(&ctx->uring_lock);
2027 * Track whether we have multiple files in our lists. This will impact
2028 * how we do polling eventually, not spinning if we're on potentially
2029 * different devices.
2031 if (wq_list_empty(&ctx->iopoll_list)) {
2032 ctx->poll_multi_queue = false;
2033 } else if (!ctx->poll_multi_queue) {
2034 struct io_kiocb *list_req;
2036 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2038 if (list_req->file != req->file)
2039 ctx->poll_multi_queue = true;
2043 * For fast devices, IO may have already completed. If it has, add
2044 * it to the front so we find it first.
2046 if (READ_ONCE(req->iopoll_completed))
2047 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2049 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2051 if (unlikely(needs_lock)) {
2053 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2054 * in sq thread task context or in io worker task context. If
2055 * current task context is sq thread, we don't need to check
2056 * whether should wake up sq thread.
2058 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2059 wq_has_sleeper(&ctx->sq_data->wait))
2060 wake_up(&ctx->sq_data->wait);
2062 mutex_unlock(&ctx->uring_lock);
2066 static bool io_bdev_nowait(struct block_device *bdev)
2068 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2072 * If we tracked the file through the SCM inflight mechanism, we could support
2073 * any file. For now, just ensure that anything potentially problematic is done
2076 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2078 if (S_ISBLK(mode)) {
2079 if (IS_ENABLED(CONFIG_BLOCK) &&
2080 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2086 if (S_ISREG(mode)) {
2087 if (IS_ENABLED(CONFIG_BLOCK) &&
2088 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2089 !io_is_uring_fops(file))
2094 /* any ->read/write should understand O_NONBLOCK */
2095 if (file->f_flags & O_NONBLOCK)
2097 return file->f_mode & FMODE_NOWAIT;
2101 * If we tracked the file through the SCM inflight mechanism, we could support
2102 * any file. For now, just ensure that anything potentially problematic is done
2105 unsigned int io_file_get_flags(struct file *file)
2107 umode_t mode = file_inode(file)->i_mode;
2108 unsigned int res = 0;
2112 if (__io_file_supports_nowait(file, mode))
2114 if (io_file_need_scm(file))
2119 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2121 return req->flags & REQ_F_SUPPORT_NOWAIT;
2124 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2126 struct io_rw *rw = io_kiocb_to_cmd(req);
2130 rw->kiocb.ki_pos = READ_ONCE(sqe->off);
2131 /* used for fixed read/write too - just read unconditionally */
2132 req->buf_index = READ_ONCE(sqe->buf_index);
2134 if (req->opcode == IORING_OP_READ_FIXED ||
2135 req->opcode == IORING_OP_WRITE_FIXED) {
2136 struct io_ring_ctx *ctx = req->ctx;
2139 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
2141 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
2142 req->imu = ctx->user_bufs[index];
2143 io_req_set_rsrc_node(req, ctx, 0);
2146 ioprio = READ_ONCE(sqe->ioprio);
2148 ret = ioprio_check_cap(ioprio);
2152 rw->kiocb.ki_ioprio = ioprio;
2154 rw->kiocb.ki_ioprio = get_current_ioprio();
2157 rw->addr = READ_ONCE(sqe->addr);
2158 rw->len = READ_ONCE(sqe->len);
2159 rw->flags = READ_ONCE(sqe->rw_flags);
2163 static void io_readv_writev_cleanup(struct io_kiocb *req)
2165 struct io_async_rw *io = req->async_data;
2167 kfree(io->free_iovec);
2170 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2176 case -ERESTARTNOINTR:
2177 case -ERESTARTNOHAND:
2178 case -ERESTART_RESTARTBLOCK:
2180 * We can't just restart the syscall, since previously
2181 * submitted sqes may already be in progress. Just fail this
2187 kiocb->ki_complete(kiocb, ret);
2191 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
2193 struct io_rw *rw = io_kiocb_to_cmd(req);
2195 if (rw->kiocb.ki_pos != -1)
2196 return &rw->kiocb.ki_pos;
2198 if (!(req->file->f_mode & FMODE_STREAM)) {
2199 req->flags |= REQ_F_CUR_POS;
2200 rw->kiocb.ki_pos = req->file->f_pos;
2201 return &rw->kiocb.ki_pos;
2204 rw->kiocb.ki_pos = 0;
2208 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
2209 unsigned int issue_flags)
2211 struct io_async_rw *io = req->async_data;
2212 struct io_rw *rw = io_kiocb_to_cmd(req);
2214 /* add previously done IO, if any */
2215 if (req_has_async_data(req) && io->bytes_done > 0) {
2217 ret = io->bytes_done;
2219 ret += io->bytes_done;
2222 if (req->flags & REQ_F_CUR_POS)
2223 req->file->f_pos = rw->kiocb.ki_pos;
2224 if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
2225 __io_complete_rw(req, ret, issue_flags);
2227 io_rw_done(&rw->kiocb, ret);
2229 if (req->flags & REQ_F_REISSUE) {
2230 req->flags &= ~REQ_F_REISSUE;
2231 if (io_resubmit_prep(req))
2232 io_req_task_queue_reissue(req);
2234 io_req_task_queue_fail(req, ret);
2238 static int __io_import_fixed(struct io_kiocb *req, int ddir,
2239 struct iov_iter *iter, struct io_mapped_ubuf *imu)
2241 struct io_rw *rw = io_kiocb_to_cmd(req);
2242 size_t len = rw->len;
2243 u64 buf_end, buf_addr = rw->addr;
2246 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2248 /* not inside the mapped region */
2249 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2253 * May not be a start of buffer, set size appropriately
2254 * and advance us to the beginning.
2256 offset = buf_addr - imu->ubuf;
2257 iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
2261 * Don't use iov_iter_advance() here, as it's really slow for
2262 * using the latter parts of a big fixed buffer - it iterates
2263 * over each segment manually. We can cheat a bit here, because
2266 * 1) it's a BVEC iter, we set it up
2267 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2268 * first and last bvec
2270 * So just find our index, and adjust the iterator afterwards.
2271 * If the offset is within the first bvec (or the whole first
2272 * bvec, just use iov_iter_advance(). This makes it easier
2273 * since we can just skip the first segment, which may not
2274 * be PAGE_SIZE aligned.
2276 const struct bio_vec *bvec = imu->bvec;
2278 if (offset <= bvec->bv_len) {
2279 iov_iter_advance(iter, offset);
2281 unsigned long seg_skip;
2283 /* skip first vec */
2284 offset -= bvec->bv_len;
2285 seg_skip = 1 + (offset >> PAGE_SHIFT);
2287 iter->bvec = bvec + seg_skip;
2288 iter->nr_segs -= seg_skip;
2289 iter->count -= bvec->bv_len + offset;
2290 iter->iov_offset = offset & ~PAGE_MASK;
2297 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2298 unsigned int issue_flags)
2300 if (WARN_ON_ONCE(!req->imu))
2302 return __io_import_fixed(req, rw, iter, req->imu);
2305 static int io_buffer_add_list(struct io_ring_ctx *ctx,
2306 struct io_buffer_list *bl, unsigned int bgid)
2309 if (bgid < BGID_ARRAY)
2312 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
2315 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
2316 struct io_buffer_list *bl)
2318 if (!list_empty(&bl->buf_list)) {
2319 struct io_buffer *kbuf;
2321 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
2322 list_del(&kbuf->list);
2323 if (*len > kbuf->len)
2325 req->flags |= REQ_F_BUFFER_SELECTED;
2327 req->buf_index = kbuf->bid;
2328 return u64_to_user_ptr(kbuf->addr);
2333 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
2334 struct io_buffer_list *bl,
2335 unsigned int issue_flags)
2337 struct io_uring_buf_ring *br = bl->buf_ring;
2338 struct io_uring_buf *buf;
2339 __u16 head = bl->head;
2341 if (unlikely(smp_load_acquire(&br->tail) == head))
2345 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
2346 buf = &br->bufs[head];
2348 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
2349 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
2350 buf = page_address(bl->buf_pages[index]);
2353 if (*len > buf->len)
2355 req->flags |= REQ_F_BUFFER_RING;
2357 req->buf_index = buf->bid;
2359 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
2361 * If we came in unlocked, we have no choice but to consume the
2362 * buffer here. This does mean it'll be pinned until the IO
2363 * completes. But coming in unlocked means we're in io-wq
2364 * context, hence there should be no further retry. For the
2365 * locked case, the caller must ensure to call the commit when
2366 * the transfer completes (or if we get -EAGAIN and must poll
2369 req->buf_list = NULL;
2372 return u64_to_user_ptr(buf->addr);
2375 void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
2376 unsigned int issue_flags)
2378 struct io_ring_ctx *ctx = req->ctx;
2379 struct io_buffer_list *bl;
2380 void __user *ret = NULL;
2382 io_ring_submit_lock(req->ctx, issue_flags);
2384 bl = io_buffer_get_list(ctx, req->buf_index);
2386 if (bl->buf_nr_pages)
2387 ret = io_ring_buffer_select(req, len, bl, issue_flags);
2389 ret = io_provided_buffer_select(req, len, bl);
2391 io_ring_submit_unlock(req->ctx, issue_flags);
2395 #ifdef CONFIG_COMPAT
2396 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2397 unsigned int issue_flags)
2399 struct io_rw *rw = io_kiocb_to_cmd(req);
2400 struct compat_iovec __user *uiov;
2401 compat_ssize_t clen;
2405 uiov = u64_to_user_ptr(rw->addr);
2406 if (!access_ok(uiov, sizeof(*uiov)))
2408 if (__get_user(clen, &uiov->iov_len))
2414 buf = io_buffer_select(req, &len, issue_flags);
2417 rw->addr = (unsigned long) buf;
2418 iov[0].iov_base = buf;
2419 rw->len = iov[0].iov_len = (compat_size_t) len;
2424 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2425 unsigned int issue_flags)
2427 struct io_rw *rw = io_kiocb_to_cmd(req);
2428 struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
2432 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2435 len = iov[0].iov_len;
2438 buf = io_buffer_select(req, &len, issue_flags);
2441 rw->addr = (unsigned long) buf;
2442 iov[0].iov_base = buf;
2443 rw->len = iov[0].iov_len = len;
2447 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2448 unsigned int issue_flags)
2450 struct io_rw *rw = io_kiocb_to_cmd(req);
2452 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
2453 iov[0].iov_base = u64_to_user_ptr(rw->addr);
2454 iov[0].iov_len = rw->len;
2460 #ifdef CONFIG_COMPAT
2461 if (req->ctx->compat)
2462 return io_compat_import(req, iov, issue_flags);
2465 return __io_iov_buffer_select(req, iov, issue_flags);
2468 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
2469 struct io_rw_state *s,
2470 unsigned int issue_flags)
2472 struct io_rw *rw = io_kiocb_to_cmd(req);
2473 struct iov_iter *iter = &s->iter;
2474 u8 opcode = req->opcode;
2475 struct iovec *iovec;
2480 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2481 ret = io_import_fixed(req, ddir, iter, issue_flags);
2483 return ERR_PTR(ret);
2487 buf = u64_to_user_ptr(rw->addr);
2490 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2491 if (io_do_buffer_select(req)) {
2492 buf = io_buffer_select(req, &sqe_len, issue_flags);
2494 return ERR_PTR(-ENOBUFS);
2495 rw->addr = (unsigned long) buf;
2499 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
2501 return ERR_PTR(ret);
2505 iovec = s->fast_iov;
2506 if (req->flags & REQ_F_BUFFER_SELECT) {
2507 ret = io_iov_buffer_select(req, iovec, issue_flags);
2509 return ERR_PTR(ret);
2510 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
2514 ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
2516 if (unlikely(ret < 0))
2517 return ERR_PTR(ret);
2521 static inline int io_import_iovec(int rw, struct io_kiocb *req,
2522 struct iovec **iovec, struct io_rw_state *s,
2523 unsigned int issue_flags)
2525 *iovec = __io_import_iovec(rw, req, s, issue_flags);
2526 if (unlikely(IS_ERR(*iovec)))
2527 return PTR_ERR(*iovec);
2529 iov_iter_save_state(&s->iter, &s->iter_state);
2533 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2535 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2539 * For files that don't have ->read_iter() and ->write_iter(), handle them
2540 * by looping over ->read() or ->write() manually.
2542 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
2544 struct kiocb *kiocb = &rw->kiocb;
2545 struct file *file = kiocb->ki_filp;
2550 * Don't support polled IO through this interface, and we can't
2551 * support non-blocking either. For the latter, this just causes
2552 * the kiocb to be handled from an async context.
2554 if (kiocb->ki_flags & IOCB_HIPRI)
2556 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
2557 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
2560 ppos = io_kiocb_ppos(kiocb);
2562 while (iov_iter_count(iter)) {
2566 if (!iov_iter_is_bvec(iter)) {
2567 iovec = iov_iter_iovec(iter);
2569 iovec.iov_base = u64_to_user_ptr(rw->addr);
2570 iovec.iov_len = rw->len;
2574 nr = file->f_op->read(file, iovec.iov_base,
2575 iovec.iov_len, ppos);
2577 nr = file->f_op->write(file, iovec.iov_base,
2578 iovec.iov_len, ppos);
2587 if (!iov_iter_is_bvec(iter)) {
2588 iov_iter_advance(iter, nr);
2595 if (nr != iovec.iov_len)
2602 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
2603 const struct iovec *fast_iov, struct iov_iter *iter)
2605 struct io_async_rw *io = req->async_data;
2607 memcpy(&io->s.iter, iter, sizeof(*iter));
2608 io->free_iovec = iovec;
2610 /* can only be fixed buffers, no need to do anything */
2611 if (iov_iter_is_bvec(iter))
2614 unsigned iov_off = 0;
2616 io->s.iter.iov = io->s.fast_iov;
2617 if (iter->iov != fast_iov) {
2618 iov_off = iter->iov - fast_iov;
2619 io->s.iter.iov += iov_off;
2621 if (io->s.fast_iov != fast_iov)
2622 memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
2623 sizeof(struct iovec) * iter->nr_segs);
2625 req->flags |= REQ_F_NEED_CLEANUP;
2629 bool io_alloc_async_data(struct io_kiocb *req)
2631 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
2632 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
2633 if (req->async_data) {
2634 req->flags |= REQ_F_ASYNC_DATA;
2640 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
2641 struct io_rw_state *s, bool force)
2643 if (!force && !io_op_defs[req->opcode].prep_async)
2645 if (!req_has_async_data(req)) {
2646 struct io_async_rw *iorw;
2648 if (io_alloc_async_data(req)) {
2653 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
2654 iorw = req->async_data;
2655 /* we've copied and mapped the iter, ensure state is saved */
2656 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
2661 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
2663 struct io_async_rw *iorw = req->async_data;
2667 /* submission path, ->uring_lock should already be taken */
2668 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
2669 if (unlikely(ret < 0))
2672 iorw->bytes_done = 0;
2673 iorw->free_iovec = iov;
2675 req->flags |= REQ_F_NEED_CLEANUP;
2679 static int io_readv_prep_async(struct io_kiocb *req)
2681 return io_rw_prep_async(req, READ);
2684 static int io_writev_prep_async(struct io_kiocb *req)
2686 return io_rw_prep_async(req, WRITE);
2690 * This is our waitqueue callback handler, registered through __folio_lock_async()
2691 * when we initially tried to do the IO with the iocb armed our waitqueue.
2692 * This gets called when the page is unlocked, and we generally expect that to
2693 * happen when the page IO is completed and the page is now uptodate. This will
2694 * queue a task_work based retry of the operation, attempting to copy the data
2695 * again. If the latter fails because the page was NOT uptodate, then we will
2696 * do a thread based blocking retry of the operation. That's the unexpected
2699 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2700 int sync, void *arg)
2702 struct wait_page_queue *wpq;
2703 struct io_kiocb *req = wait->private;
2704 struct io_rw *rw = io_kiocb_to_cmd(req);
2705 struct wait_page_key *key = arg;
2707 wpq = container_of(wait, struct wait_page_queue, wait);
2709 if (!wake_page_match(wpq, key))
2712 rw->kiocb.ki_flags &= ~IOCB_WAITQ;
2713 list_del_init(&wait->entry);
2714 io_req_task_queue(req);
2719 * This controls whether a given IO request should be armed for async page
2720 * based retry. If we return false here, the request is handed to the async
2721 * worker threads for retry. If we're doing buffered reads on a regular file,
2722 * we prepare a private wait_page_queue entry and retry the operation. This
2723 * will either succeed because the page is now uptodate and unlocked, or it
2724 * will register a callback when the page is unlocked at IO completion. Through
2725 * that callback, io_uring uses task_work to setup a retry of the operation.
2726 * That retry will attempt the buffered read again. The retry will generally
2727 * succeed, or in rare cases where it fails, we then fall back to using the
2728 * async worker threads for a blocking retry.
2730 static bool io_rw_should_retry(struct io_kiocb *req)
2732 struct io_async_rw *io = req->async_data;
2733 struct wait_page_queue *wait = &io->wpq;
2734 struct io_rw *rw = io_kiocb_to_cmd(req);
2735 struct kiocb *kiocb = &rw->kiocb;
2737 /* never retry for NOWAIT, we just complete with -EAGAIN */
2738 if (req->flags & REQ_F_NOWAIT)
2741 /* Only for buffered IO */
2742 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
2746 * just use poll if we can, and don't attempt if the fs doesn't
2747 * support callback based unlocks
2749 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2752 wait->wait.func = io_async_buf_func;
2753 wait->wait.private = req;
2754 wait->wait.flags = 0;
2755 INIT_LIST_HEAD(&wait->wait.entry);
2756 kiocb->ki_flags |= IOCB_WAITQ;
2757 kiocb->ki_flags &= ~IOCB_NOWAIT;
2758 kiocb->ki_waitq = wait;
2762 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
2764 struct file *file = rw->kiocb.ki_filp;
2766 if (likely(file->f_op->read_iter))
2767 return call_read_iter(file, &rw->kiocb, iter);
2768 else if (file->f_op->read)
2769 return loop_rw_iter(READ, rw, iter);
2774 static bool need_read_all(struct io_kiocb *req)
2776 return req->flags & REQ_F_ISREG ||
2777 S_ISBLK(file_inode(req->file)->i_mode);
2780 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
2782 struct io_rw *rw = io_kiocb_to_cmd(req);
2783 struct kiocb *kiocb = &rw->kiocb;
2784 struct io_ring_ctx *ctx = req->ctx;
2785 struct file *file = req->file;
2788 if (unlikely(!file || !(file->f_mode & mode)))
2791 if (!io_req_ffs_set(req))
2792 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
2794 kiocb->ki_flags = iocb_flags(file);
2795 ret = kiocb_set_rw_flags(kiocb, rw->flags);
2800 * If the file is marked O_NONBLOCK, still allow retry for it if it
2801 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2802 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2804 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2805 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
2806 req->flags |= REQ_F_NOWAIT;
2808 if (ctx->flags & IORING_SETUP_IOPOLL) {
2809 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
2812 kiocb->private = NULL;
2813 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2814 kiocb->ki_complete = io_complete_rw_iopoll;
2815 req->iopoll_completed = 0;
2817 if (kiocb->ki_flags & IOCB_HIPRI)
2819 kiocb->ki_complete = io_complete_rw;
2825 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
2827 struct io_rw *rw = io_kiocb_to_cmd(req);
2828 struct io_rw_state __s, *s = &__s;
2829 struct iovec *iovec;
2830 struct kiocb *kiocb = &rw->kiocb;
2831 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2832 struct io_async_rw *io;
2836 if (!req_has_async_data(req)) {
2837 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2838 if (unlikely(ret < 0))
2841 io = req->async_data;
2845 * Safe and required to re-import if we're using provided
2846 * buffers, as we dropped the selected one before retry.
2848 if (io_do_buffer_select(req)) {
2849 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2850 if (unlikely(ret < 0))
2855 * We come here from an earlier attempt, restore our state to
2856 * match in case it doesn't. It's cheap enough that we don't
2857 * need to make this conditional.
2859 iov_iter_restore(&s->iter, &s->iter_state);
2862 ret = io_rw_init_file(req, FMODE_READ);
2863 if (unlikely(ret)) {
2867 req->cqe.res = iov_iter_count(&s->iter);
2869 if (force_nonblock) {
2870 /* If the file doesn't support async, just async punt */
2871 if (unlikely(!io_file_supports_nowait(req))) {
2872 ret = io_setup_async_rw(req, iovec, s, true);
2873 return ret ?: -EAGAIN;
2875 kiocb->ki_flags |= IOCB_NOWAIT;
2877 /* Ensure we clear previously set non-block flag */
2878 kiocb->ki_flags &= ~IOCB_NOWAIT;
2881 ppos = io_kiocb_update_pos(req);
2883 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
2884 if (unlikely(ret)) {
2889 ret = io_iter_do_read(rw, &s->iter);
2891 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
2892 req->flags &= ~REQ_F_REISSUE;
2893 /* if we can poll, just do that */
2894 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
2896 /* IOPOLL retry should happen for io-wq threads */
2897 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
2899 /* no retry on NONBLOCK nor RWF_NOWAIT */
2900 if (req->flags & REQ_F_NOWAIT)
2903 } else if (ret == -EIOCBQUEUED) {
2905 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
2906 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
2907 /* read all, failed, already did sync or don't want to retry */
2912 * Don't depend on the iter state matching what was consumed, or being
2913 * untouched in case of error. Restore it and we'll advance it
2914 * manually if we need to.
2916 iov_iter_restore(&s->iter, &s->iter_state);
2918 ret2 = io_setup_async_rw(req, iovec, s, true);
2923 io = req->async_data;
2926 * Now use our persistent iterator and state, if we aren't already.
2927 * We've restored and mapped the iter to match.
2932 * We end up here because of a partial read, either from
2933 * above or inside this loop. Advance the iter by the bytes
2934 * that were consumed.
2936 iov_iter_advance(&s->iter, ret);
2937 if (!iov_iter_count(&s->iter))
2939 io->bytes_done += ret;
2940 iov_iter_save_state(&s->iter, &s->iter_state);
2942 /* if we can retry, do so with the callbacks armed */
2943 if (!io_rw_should_retry(req)) {
2944 kiocb->ki_flags &= ~IOCB_WAITQ;
2949 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
2950 * we get -EIOCBQUEUED, then we'll get a notification when the
2951 * desired page gets unlocked. We can also get a partial read
2952 * here, and if we do, then just retry at the new offset.
2954 ret = io_iter_do_read(rw, &s->iter);
2955 if (ret == -EIOCBQUEUED)
2956 return IOU_ISSUE_SKIP_COMPLETE;
2957 /* we got some bytes, but not all. retry. */
2958 kiocb->ki_flags &= ~IOCB_WAITQ;
2959 iov_iter_restore(&s->iter, &s->iter_state);
2962 kiocb_done(req, ret, issue_flags);
2964 /* it's faster to check here then delegate to kfree */
2967 return IOU_ISSUE_SKIP_COMPLETE;
2970 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
2972 struct io_rw *rw = io_kiocb_to_cmd(req);
2973 struct io_rw_state __s, *s = &__s;
2974 struct iovec *iovec;
2975 struct kiocb *kiocb = &rw->kiocb;
2976 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2980 if (!req_has_async_data(req)) {
2981 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
2982 if (unlikely(ret < 0))
2985 struct io_async_rw *io = req->async_data;
2988 iov_iter_restore(&s->iter, &s->iter_state);
2991 ret = io_rw_init_file(req, FMODE_WRITE);
2992 if (unlikely(ret)) {
2996 req->cqe.res = iov_iter_count(&s->iter);
2998 if (force_nonblock) {
2999 /* If the file doesn't support async, just async punt */
3000 if (unlikely(!io_file_supports_nowait(req)))
3003 /* file path doesn't support NOWAIT for non-direct_IO */
3004 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3005 (req->flags & REQ_F_ISREG))
3008 kiocb->ki_flags |= IOCB_NOWAIT;
3010 /* Ensure we clear previously set non-block flag */
3011 kiocb->ki_flags &= ~IOCB_NOWAIT;
3014 ppos = io_kiocb_update_pos(req);
3016 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
3021 * Open-code file_start_write here to grab freeze protection,
3022 * which will be released by another thread in
3023 * io_complete_rw(). Fool lockdep by telling it the lock got
3024 * released so that it doesn't complain about the held lock when
3025 * we return to userspace.
3027 if (req->flags & REQ_F_ISREG) {
3028 sb_start_write(file_inode(req->file)->i_sb);
3029 __sb_writers_release(file_inode(req->file)->i_sb,
3032 kiocb->ki_flags |= IOCB_WRITE;
3034 if (likely(req->file->f_op->write_iter))
3035 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3036 else if (req->file->f_op->write)
3037 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
3041 if (req->flags & REQ_F_REISSUE) {
3042 req->flags &= ~REQ_F_REISSUE;
3047 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3048 * retry them without IOCB_NOWAIT.
3050 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3052 /* no retry on NONBLOCK nor RWF_NOWAIT */
3053 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3055 if (!force_nonblock || ret2 != -EAGAIN) {
3056 /* IOPOLL retry should happen for io-wq threads */
3057 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3060 kiocb_done(req, ret2, issue_flags);
3061 ret = IOU_ISSUE_SKIP_COMPLETE;
3064 iov_iter_restore(&s->iter, &s->iter_state);
3065 ret = io_setup_async_rw(req, iovec, s, false);
3066 return ret ?: -EAGAIN;
3069 /* it's reportedly faster than delegating the null check to kfree() */
3076 * Note when io_fixed_fd_install() returns error value, it will ensure
3077 * fput() is called correspondingly.
3079 int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
3080 struct file *file, unsigned int file_slot)
3082 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
3083 struct io_ring_ctx *ctx = req->ctx;
3086 io_ring_submit_lock(ctx, issue_flags);
3089 ret = io_file_bitmap_get(ctx);
3090 if (unlikely(ret < 0))
3097 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
3098 if (!ret && alloc_slot)
3101 io_ring_submit_unlock(ctx, issue_flags);
3102 if (unlikely(ret < 0))
3107 static int io_remove_buffers_prep(struct io_kiocb *req,
3108 const struct io_uring_sqe *sqe)
3110 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3113 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
3117 tmp = READ_ONCE(sqe->fd);
3118 if (!tmp || tmp > USHRT_MAX)
3121 memset(p, 0, sizeof(*p));
3123 p->bgid = READ_ONCE(sqe->buf_group);
3127 static int __io_remove_buffers(struct io_ring_ctx *ctx,
3128 struct io_buffer_list *bl, unsigned nbufs)
3132 /* shouldn't happen */
3136 if (bl->buf_nr_pages) {
3139 i = bl->buf_ring->tail - bl->head;
3140 for (j = 0; j < bl->buf_nr_pages; j++)
3141 unpin_user_page(bl->buf_pages[j]);
3142 kvfree(bl->buf_pages);
3143 bl->buf_pages = NULL;
3144 bl->buf_nr_pages = 0;
3145 /* make sure it's seen as empty */
3146 INIT_LIST_HEAD(&bl->buf_list);
3150 /* the head kbuf is the list itself */
3151 while (!list_empty(&bl->buf_list)) {
3152 struct io_buffer *nxt;
3154 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
3155 list_del(&nxt->list);
3165 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3167 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3168 struct io_ring_ctx *ctx = req->ctx;
3169 struct io_buffer_list *bl;
3172 io_ring_submit_lock(ctx, issue_flags);
3175 bl = io_buffer_get_list(ctx, p->bgid);
3178 /* can't use provide/remove buffers command on mapped buffers */
3179 if (!bl->buf_nr_pages)
3180 ret = __io_remove_buffers(ctx, bl, p->nbufs);
3185 /* complete before unlock, IOPOLL may need the lock */
3186 io_req_set_res(req, ret, 0);
3187 __io_req_complete(req, issue_flags);
3188 io_ring_submit_unlock(ctx, issue_flags);
3189 return IOU_ISSUE_SKIP_COMPLETE;
3192 static int io_provide_buffers_prep(struct io_kiocb *req,
3193 const struct io_uring_sqe *sqe)
3195 unsigned long size, tmp_check;
3196 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3199 if (sqe->rw_flags || sqe->splice_fd_in)
3202 tmp = READ_ONCE(sqe->fd);
3203 if (!tmp || tmp > USHRT_MAX)
3206 p->addr = READ_ONCE(sqe->addr);
3207 p->len = READ_ONCE(sqe->len);
3209 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3212 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3215 size = (unsigned long)p->len * p->nbufs;
3216 if (!access_ok(u64_to_user_ptr(p->addr), size))
3219 p->bgid = READ_ONCE(sqe->buf_group);
3220 tmp = READ_ONCE(sqe->off);
3221 if (tmp > USHRT_MAX)
3227 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
3229 struct io_buffer *buf;
3234 * Completions that don't happen inline (eg not under uring_lock) will
3235 * add to ->io_buffers_comp. If we don't have any free buffers, check
3236 * the completion list and splice those entries first.
3238 if (!list_empty_careful(&ctx->io_buffers_comp)) {
3239 spin_lock(&ctx->completion_lock);
3240 if (!list_empty(&ctx->io_buffers_comp)) {
3241 list_splice_init(&ctx->io_buffers_comp,
3242 &ctx->io_buffers_cache);
3243 spin_unlock(&ctx->completion_lock);
3246 spin_unlock(&ctx->completion_lock);
3250 * No free buffers and no completion entries either. Allocate a new
3251 * page worth of buffer entries and add those to our freelist.
3253 page = alloc_page(GFP_KERNEL_ACCOUNT);
3257 list_add(&page->lru, &ctx->io_buffers_pages);
3259 buf = page_address(page);
3260 bufs_in_page = PAGE_SIZE / sizeof(*buf);
3261 while (bufs_in_page) {
3262 list_add_tail(&buf->list, &ctx->io_buffers_cache);
3270 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
3271 struct io_buffer_list *bl)
3273 struct io_buffer *buf;
3274 u64 addr = pbuf->addr;
3275 int i, bid = pbuf->bid;
3277 for (i = 0; i < pbuf->nbufs; i++) {
3278 if (list_empty(&ctx->io_buffers_cache) &&
3279 io_refill_buffer_cache(ctx))
3281 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
3283 list_move_tail(&buf->list, &bl->buf_list);
3285 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
3287 buf->bgid = pbuf->bgid;
3293 return i ? 0 : -ENOMEM;
3296 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
3300 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
3305 for (i = 0; i < BGID_ARRAY; i++) {
3306 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
3307 ctx->io_bl[i].bgid = i;
3313 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3315 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3316 struct io_ring_ctx *ctx = req->ctx;
3317 struct io_buffer_list *bl;
3320 io_ring_submit_lock(ctx, issue_flags);
3322 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
3323 ret = io_init_bl_list(ctx);
3328 bl = io_buffer_get_list(ctx, p->bgid);
3329 if (unlikely(!bl)) {
3330 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
3335 INIT_LIST_HEAD(&bl->buf_list);
3336 ret = io_buffer_add_list(ctx, bl, p->bgid);
3342 /* can't add buffers via this command for a mapped buffer ring */
3343 if (bl->buf_nr_pages) {
3348 ret = io_add_buffers(ctx, p, bl);
3352 /* complete before unlock, IOPOLL may need the lock */
3353 io_req_set_res(req, ret, 0);
3354 __io_req_complete(req, issue_flags);
3355 io_ring_submit_unlock(ctx, issue_flags);
3356 return IOU_ISSUE_SKIP_COMPLETE;
3359 static __maybe_unused int io_eopnotsupp_prep(struct io_kiocb *kiocb,
3360 const struct io_uring_sqe *sqe)
3365 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3367 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3368 struct io_cancel_data *cd = data;
3370 if (req->ctx != cd->ctx)
3372 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
3374 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
3375 if (req->file != cd->file)
3378 if (req->cqe.user_data != cd->data)
3381 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
3382 if (cd->seq == req->work.cancel_seq)
3384 req->work.cancel_seq = cd->seq;
3389 static int io_async_cancel_one(struct io_uring_task *tctx,
3390 struct io_cancel_data *cd)
3392 enum io_wq_cancel cancel_ret;
3396 if (!tctx || !tctx->io_wq)
3399 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
3400 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
3401 switch (cancel_ret) {
3402 case IO_WQ_CANCEL_OK:
3405 case IO_WQ_CANCEL_RUNNING:
3408 case IO_WQ_CANCEL_NOTFOUND:
3416 int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
3418 struct io_ring_ctx *ctx = req->ctx;
3421 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
3423 ret = io_async_cancel_one(req->task->io_uring, cd);
3425 * Fall-through even for -EALREADY, as we may have poll armed
3426 * that need unarming.
3431 spin_lock(&ctx->completion_lock);
3432 ret = io_poll_cancel(ctx, cd);
3435 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
3436 ret = io_timeout_cancel(ctx, cd);
3438 spin_unlock(&ctx->completion_lock);
3442 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
3443 IORING_ASYNC_CANCEL_ANY)
3445 static int io_async_cancel_prep(struct io_kiocb *req,
3446 const struct io_uring_sqe *sqe)
3448 struct io_cancel *cancel = io_kiocb_to_cmd(req);
3450 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
3452 if (sqe->off || sqe->len || sqe->splice_fd_in)
3455 cancel->addr = READ_ONCE(sqe->addr);
3456 cancel->flags = READ_ONCE(sqe->cancel_flags);
3457 if (cancel->flags & ~CANCEL_FLAGS)
3459 if (cancel->flags & IORING_ASYNC_CANCEL_FD) {
3460 if (cancel->flags & IORING_ASYNC_CANCEL_ANY)
3462 cancel->fd = READ_ONCE(sqe->fd);
3468 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
3469 unsigned int issue_flags)
3471 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
3472 struct io_ring_ctx *ctx = cd->ctx;
3473 struct io_tctx_node *node;
3477 ret = io_try_cancel(req, cd);
3485 /* slow path, try all io-wq's */
3486 io_ring_submit_lock(ctx, issue_flags);
3488 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3489 struct io_uring_task *tctx = node->task->io_uring;
3491 ret = io_async_cancel_one(tctx, cd);
3492 if (ret != -ENOENT) {
3498 io_ring_submit_unlock(ctx, issue_flags);
3499 return all ? nr : ret;
3502 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
3504 struct io_cancel *cancel = io_kiocb_to_cmd(req);
3505 struct io_cancel_data cd = {
3507 .data = cancel->addr,
3508 .flags = cancel->flags,
3509 .seq = atomic_inc_return(&req->ctx->cancel_seq),
3513 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
3514 if (req->flags & REQ_F_FIXED_FILE)
3515 req->file = io_file_get_fixed(req, cancel->fd,
3518 req->file = io_file_get_normal(req, cancel->fd);
3523 cd.file = req->file;
3526 ret = __io_async_cancel(&cd, req, issue_flags);
3530 io_req_set_res(req, ret, 0);
3534 static int io_files_update_prep(struct io_kiocb *req,
3535 const struct io_uring_sqe *sqe)
3537 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
3539 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
3541 if (sqe->rw_flags || sqe->splice_fd_in)
3544 up->offset = READ_ONCE(sqe->off);
3545 up->nr_args = READ_ONCE(sqe->len);
3548 up->arg = READ_ONCE(sqe->addr);
3552 static int io_files_update_with_index_alloc(struct io_kiocb *req,
3553 unsigned int issue_flags)
3555 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
3556 __s32 __user *fds = u64_to_user_ptr(up->arg);
3561 if (!req->ctx->file_data)
3564 for (done = 0; done < up->nr_args; done++) {
3565 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
3575 ret = io_fixed_fd_install(req, issue_flags, file,
3576 IORING_FILE_INDEX_ALLOC);
3579 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
3580 __io_close_fixed(req, issue_flags, ret);
3591 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
3593 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
3594 struct io_ring_ctx *ctx = req->ctx;
3595 struct io_uring_rsrc_update2 up2;
3598 up2.offset = up->offset;
3605 if (up->offset == IORING_FILE_INDEX_ALLOC) {
3606 ret = io_files_update_with_index_alloc(req, issue_flags);
3608 io_ring_submit_lock(ctx, issue_flags);
3609 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
3611 io_ring_submit_unlock(ctx, issue_flags);
3616 io_req_set_res(req, ret, 0);
3620 static int io_req_prep_async(struct io_kiocb *req)
3622 const struct io_op_def *def = &io_op_defs[req->opcode];
3624 /* assign early for deferred execution for non-fixed file */
3625 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
3626 req->file = io_file_get_normal(req, req->cqe.fd);
3627 if (!def->prep_async)
3629 if (WARN_ON_ONCE(req_has_async_data(req)))
3631 if (io_alloc_async_data(req))
3634 return def->prep_async(req);
3637 static u32 io_get_sequence(struct io_kiocb *req)
3639 u32 seq = req->ctx->cached_sq_head;
3640 struct io_kiocb *cur;
3642 /* need original cached_sq_head, but it was increased for each req */
3643 io_for_each_link(cur, req)
3648 static __cold void io_drain_req(struct io_kiocb *req)
3650 struct io_ring_ctx *ctx = req->ctx;
3651 struct io_defer_entry *de;
3653 u32 seq = io_get_sequence(req);
3655 /* Still need defer if there is pending req in defer list. */
3656 spin_lock(&ctx->completion_lock);
3657 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
3658 spin_unlock(&ctx->completion_lock);
3660 ctx->drain_active = false;
3661 io_req_task_queue(req);
3664 spin_unlock(&ctx->completion_lock);
3666 ret = io_req_prep_async(req);
3669 io_req_complete_failed(req, ret);
3672 io_prep_async_link(req);
3673 de = kmalloc(sizeof(*de), GFP_KERNEL);
3679 spin_lock(&ctx->completion_lock);
3680 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
3681 spin_unlock(&ctx->completion_lock);
3686 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
3689 list_add_tail(&de->list, &ctx->defer_list);
3690 spin_unlock(&ctx->completion_lock);
3693 static void io_clean_op(struct io_kiocb *req)
3695 if (req->flags & REQ_F_BUFFER_SELECTED) {
3696 spin_lock(&req->ctx->completion_lock);
3697 io_put_kbuf_comp(req);
3698 spin_unlock(&req->ctx->completion_lock);
3701 if (req->flags & REQ_F_NEED_CLEANUP) {
3702 const struct io_op_def *def = &io_op_defs[req->opcode];
3707 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3708 kfree(req->apoll->double_poll);
3712 if (req->flags & REQ_F_INFLIGHT) {
3713 struct io_uring_task *tctx = req->task->io_uring;
3715 atomic_dec(&tctx->inflight_tracked);
3717 if (req->flags & REQ_F_CREDS)
3718 put_cred(req->creds);
3719 if (req->flags & REQ_F_ASYNC_DATA) {
3720 kfree(req->async_data);
3721 req->async_data = NULL;
3723 req->flags &= ~IO_REQ_CLEAN_FLAGS;
3726 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
3728 if (req->file || !io_op_defs[req->opcode].needs_file)
3731 if (req->flags & REQ_F_FIXED_FILE)
3732 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
3734 req->file = io_file_get_normal(req, req->cqe.fd);
3739 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
3741 const struct io_op_def *def = &io_op_defs[req->opcode];
3742 const struct cred *creds = NULL;
3745 if (unlikely(!io_assign_file(req, issue_flags)))
3748 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
3749 creds = override_creds(req->creds);
3751 if (!def->audit_skip)
3752 audit_uring_entry(req->opcode);
3754 ret = def->issue(req, issue_flags);
3756 if (!def->audit_skip)
3757 audit_uring_exit(!ret, ret);
3760 revert_creds(creds);
3763 __io_req_complete(req, issue_flags);
3764 else if (ret != IOU_ISSUE_SKIP_COMPLETE)
3767 /* If the op doesn't have a file, we're not polling for it */
3768 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
3769 io_iopoll_req_issued(req, issue_flags);
3774 int io_poll_issue(struct io_kiocb *req, bool *locked)
3776 io_tw_lock(req->ctx, locked);
3777 if (unlikely(req->task->flags & PF_EXITING))
3779 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3782 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
3784 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3786 req = io_put_req_find_next(req);
3787 return req ? &req->work : NULL;
3790 void io_wq_submit_work(struct io_wq_work *work)
3792 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3793 const struct io_op_def *def = &io_op_defs[req->opcode];
3794 unsigned int issue_flags = IO_URING_F_UNLOCKED;
3795 bool needs_poll = false;
3796 int ret = 0, err = -ECANCELED;
3798 /* one will be dropped by ->io_free_work() after returning to io-wq */
3799 if (!(req->flags & REQ_F_REFCOUNT))
3800 __io_req_set_refcount(req, 2);
3804 io_arm_ltimeout(req);
3806 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
3807 if (work->flags & IO_WQ_WORK_CANCEL) {
3809 io_req_task_queue_fail(req, err);
3812 if (!io_assign_file(req, issue_flags)) {
3814 work->flags |= IO_WQ_WORK_CANCEL;
3818 if (req->flags & REQ_F_FORCE_ASYNC) {
3819 bool opcode_poll = def->pollin || def->pollout;
3821 if (opcode_poll && file_can_poll(req->file)) {
3823 issue_flags |= IO_URING_F_NONBLOCK;
3828 ret = io_issue_sqe(req, issue_flags);
3832 * We can get EAGAIN for iopolled IO even though we're
3833 * forcing a sync submission from here, since we can't
3834 * wait for request slots on the block side.
3837 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
3843 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
3845 /* aborted or ready, in either case retry blocking */
3847 issue_flags &= ~IO_URING_F_NONBLOCK;
3850 /* avoid locking problems by failing it from a clean context */
3852 io_req_task_queue_fail(req, ret);
3855 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
3856 unsigned int issue_flags)
3858 struct io_ring_ctx *ctx = req->ctx;
3859 struct file *file = NULL;
3860 unsigned long file_ptr;
3862 io_ring_submit_lock(ctx, issue_flags);
3864 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
3866 fd = array_index_nospec(fd, ctx->nr_user_files);
3867 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
3868 file = (struct file *) (file_ptr & FFS_MASK);
3869 file_ptr &= ~FFS_MASK;
3870 /* mask in overlapping REQ_F and FFS bits */
3871 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
3872 io_req_set_rsrc_node(req, ctx, 0);
3873 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
3875 io_ring_submit_unlock(ctx, issue_flags);
3879 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
3881 struct file *file = fget(fd);
3883 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
3885 /* we don't allow fixed io_uring files */
3886 if (file && io_is_uring_fops(file))
3887 io_req_track_inflight(req);
3891 static void io_queue_async(struct io_kiocb *req, int ret)
3892 __must_hold(&req->ctx->uring_lock)
3894 struct io_kiocb *linked_timeout;
3896 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
3897 io_req_complete_failed(req, ret);
3901 linked_timeout = io_prep_linked_timeout(req);
3903 switch (io_arm_poll_handler(req, 0)) {
3904 case IO_APOLL_READY:
3905 io_req_task_queue(req);
3907 case IO_APOLL_ABORTED:
3909 * Queued up for async execution, worker will release
3910 * submit reference when the iocb is actually submitted.
3912 io_kbuf_recycle(req, 0);
3913 io_queue_iowq(req, NULL);
3920 io_queue_linked_timeout(linked_timeout);
3923 static inline void io_queue_sqe(struct io_kiocb *req)
3924 __must_hold(&req->ctx->uring_lock)
3928 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3930 if (req->flags & REQ_F_COMPLETE_INLINE) {
3931 io_req_add_compl_list(req);
3935 * We async punt it if the file wasn't marked NOWAIT, or if the file
3936 * doesn't support non-blocking read/write attempts
3939 io_arm_ltimeout(req);
3941 io_queue_async(req, ret);
3944 static void io_queue_sqe_fallback(struct io_kiocb *req)
3945 __must_hold(&req->ctx->uring_lock)
3947 if (unlikely(req->flags & REQ_F_FAIL)) {
3949 * We don't submit, fail them all, for that replace hardlinks
3950 * with normal links. Extra REQ_F_LINK is tolerated.
3952 req->flags &= ~REQ_F_HARDLINK;
3953 req->flags |= REQ_F_LINK;
3954 io_req_complete_failed(req, req->cqe.res);
3955 } else if (unlikely(req->ctx->drain_active)) {
3958 int ret = io_req_prep_async(req);
3961 io_req_complete_failed(req, ret);
3963 io_queue_iowq(req, NULL);
3968 * Check SQE restrictions (opcode and flags).
3970 * Returns 'true' if SQE is allowed, 'false' otherwise.
3972 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
3973 struct io_kiocb *req,
3974 unsigned int sqe_flags)
3976 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
3979 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
3980 ctx->restrictions.sqe_flags_required)
3983 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
3984 ctx->restrictions.sqe_flags_required))
3990 static void io_init_req_drain(struct io_kiocb *req)
3992 struct io_ring_ctx *ctx = req->ctx;
3993 struct io_kiocb *head = ctx->submit_state.link.head;
3995 ctx->drain_active = true;
3998 * If we need to drain a request in the middle of a link, drain
3999 * the head request and the next request/link after the current
4000 * link. Considering sequential execution of links,
4001 * REQ_F_IO_DRAIN will be maintained for every request of our
4004 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
4005 ctx->drain_next = true;
4009 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
4010 const struct io_uring_sqe *sqe)
4011 __must_hold(&ctx->uring_lock)
4013 const struct io_op_def *def;
4014 unsigned int sqe_flags;
4018 /* req is partially pre-initialised, see io_preinit_req() */
4019 req->opcode = opcode = READ_ONCE(sqe->opcode);
4020 /* same numerical values with corresponding REQ_F_*, safe to copy */
4021 req->flags = sqe_flags = READ_ONCE(sqe->flags);
4022 req->cqe.user_data = READ_ONCE(sqe->user_data);
4024 req->rsrc_node = NULL;
4025 req->task = current;
4027 if (unlikely(opcode >= IORING_OP_LAST)) {
4031 def = &io_op_defs[opcode];
4032 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
4033 /* enforce forwards compatibility on users */
4034 if (sqe_flags & ~SQE_VALID_FLAGS)
4036 if (sqe_flags & IOSQE_BUFFER_SELECT) {
4037 if (!def->buffer_select)
4039 req->buf_index = READ_ONCE(sqe->buf_group);
4041 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
4042 ctx->drain_disabled = true;
4043 if (sqe_flags & IOSQE_IO_DRAIN) {
4044 if (ctx->drain_disabled)
4046 io_init_req_drain(req);
4049 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
4050 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
4052 /* knock it to the slow queue path, will be drained there */
4053 if (ctx->drain_active)
4054 req->flags |= REQ_F_FORCE_ASYNC;
4055 /* if there is no link, we're at "next" request and need to drain */
4056 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
4057 ctx->drain_next = false;
4058 ctx->drain_active = true;
4059 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
4063 if (!def->ioprio && sqe->ioprio)
4065 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
4068 if (def->needs_file) {
4069 struct io_submit_state *state = &ctx->submit_state;
4071 req->cqe.fd = READ_ONCE(sqe->fd);
4074 * Plug now if we have more than 2 IO left after this, and the
4075 * target is potentially a read/write to block based storage.
4077 if (state->need_plug && def->plug) {
4078 state->plug_started = true;
4079 state->need_plug = false;
4080 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
4084 personality = READ_ONCE(sqe->personality);
4088 req->creds = xa_load(&ctx->personalities, personality);
4091 get_cred(req->creds);
4092 ret = security_uring_override_creds(req->creds);
4094 put_cred(req->creds);
4097 req->flags |= REQ_F_CREDS;
4100 return def->prep(req, sqe);
4103 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
4104 struct io_kiocb *req, int ret)
4106 struct io_ring_ctx *ctx = req->ctx;
4107 struct io_submit_link *link = &ctx->submit_state.link;
4108 struct io_kiocb *head = link->head;
4110 trace_io_uring_req_failed(sqe, ctx, req, ret);
4113 * Avoid breaking links in the middle as it renders links with SQPOLL
4114 * unusable. Instead of failing eagerly, continue assembling the link if
4115 * applicable and mark the head with REQ_F_FAIL. The link flushing code
4116 * should find the flag and handle the rest.
4118 req_fail_link_node(req, ret);
4119 if (head && !(head->flags & REQ_F_FAIL))
4120 req_fail_link_node(head, -ECANCELED);
4122 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
4124 link->last->link = req;
4128 io_queue_sqe_fallback(req);
4133 link->last->link = req;
4140 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
4141 const struct io_uring_sqe *sqe)
4142 __must_hold(&ctx->uring_lock)
4144 struct io_submit_link *link = &ctx->submit_state.link;
4147 ret = io_init_req(ctx, req, sqe);
4149 return io_submit_fail_init(sqe, req, ret);
4151 /* don't need @sqe from now on */
4152 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
4154 ctx->flags & IORING_SETUP_SQPOLL);
4157 * If we already have a head request, queue this one for async
4158 * submittal once the head completes. If we don't have a head but
4159 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4160 * submitted sync once the chain is complete. If none of those
4161 * conditions are true (normal request), then just queue it.
4163 if (unlikely(link->head)) {
4164 ret = io_req_prep_async(req);
4166 return io_submit_fail_init(sqe, req, ret);
4168 trace_io_uring_link(ctx, req, link->head);
4169 link->last->link = req;
4172 if (req->flags & IO_REQ_LINK_FLAGS)
4174 /* last request of the link, flush it */
4177 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
4180 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
4181 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
4182 if (req->flags & IO_REQ_LINK_FLAGS) {
4187 io_queue_sqe_fallback(req);
4197 * Batched submission is done, ensure local IO is flushed out.
4199 static void io_submit_state_end(struct io_ring_ctx *ctx)
4201 struct io_submit_state *state = &ctx->submit_state;
4203 if (unlikely(state->link.head))
4204 io_queue_sqe_fallback(state->link.head);
4205 /* flush only after queuing links as they can generate completions */
4206 io_submit_flush_completions(ctx);
4207 if (state->plug_started)
4208 blk_finish_plug(&state->plug);
4212 * Start submission side cache.
4214 static void io_submit_state_start(struct io_submit_state *state,
4215 unsigned int max_ios)
4217 state->plug_started = false;
4218 state->need_plug = max_ios > 2;
4219 state->submit_nr = max_ios;
4220 /* set only head, no need to init link_last in advance */
4221 state->link.head = NULL;
4224 static void io_commit_sqring(struct io_ring_ctx *ctx)
4226 struct io_rings *rings = ctx->rings;
4229 * Ensure any loads from the SQEs are done at this point,
4230 * since once we write the new head, the application could
4231 * write new data to them.
4233 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4237 * Fetch an sqe, if one is available. Note this returns a pointer to memory
4238 * that is mapped by userspace. This means that care needs to be taken to
4239 * ensure that reads are stable, as we cannot rely on userspace always
4240 * being a good citizen. If members of the sqe are validated and then later
4241 * used, it's important that those reads are done through READ_ONCE() to
4242 * prevent a re-load down the line.
4244 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
4246 unsigned head, mask = ctx->sq_entries - 1;
4247 unsigned sq_idx = ctx->cached_sq_head++ & mask;
4250 * The cached sq head (or cq tail) serves two purposes:
4252 * 1) allows us to batch the cost of updating the user visible
4254 * 2) allows the kernel side to track the head on its own, even
4255 * though the application is the one updating it.
4257 head = READ_ONCE(ctx->sq_array[sq_idx]);
4258 if (likely(head < ctx->sq_entries)) {
4259 /* double index for 128-byte SQEs, twice as long */
4260 if (ctx->flags & IORING_SETUP_SQE128)
4262 return &ctx->sq_sqes[head];
4265 /* drop invalid entries */
4267 WRITE_ONCE(ctx->rings->sq_dropped,
4268 READ_ONCE(ctx->rings->sq_dropped) + 1);
4272 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
4273 __must_hold(&ctx->uring_lock)
4275 unsigned int entries = io_sqring_entries(ctx);
4279 if (unlikely(!entries))
4281 /* make sure SQ entry isn't read before tail */
4282 ret = left = min3(nr, ctx->sq_entries, entries);
4283 io_get_task_refs(left);
4284 io_submit_state_start(&ctx->submit_state, left);
4287 const struct io_uring_sqe *sqe;
4288 struct io_kiocb *req;
4290 if (unlikely(!io_alloc_req_refill(ctx)))
4292 req = io_alloc_req(ctx);
4293 sqe = io_get_sqe(ctx);
4294 if (unlikely(!sqe)) {
4295 io_req_add_to_cache(req, ctx);
4300 * Continue submitting even for sqe failure if the
4301 * ring was setup with IORING_SETUP_SUBMIT_ALL
4303 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
4304 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
4310 if (unlikely(left)) {
4312 /* try again if it submitted nothing and can't allocate a req */
4313 if (!ret && io_req_cache_empty(ctx))
4315 current->io_uring->cached_refs += left;
4318 io_submit_state_end(ctx);
4319 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4320 io_commit_sqring(ctx);
4324 struct io_wait_queue {
4325 struct wait_queue_entry wq;
4326 struct io_ring_ctx *ctx;
4328 unsigned nr_timeouts;
4331 static inline bool io_should_wake(struct io_wait_queue *iowq)
4333 struct io_ring_ctx *ctx = iowq->ctx;
4334 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
4337 * Wake up if we have enough events, or if a timeout occurred since we
4338 * started waiting. For timeouts, we always want to return to userspace,
4339 * regardless of event count.
4341 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4344 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
4345 int wake_flags, void *key)
4347 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
4351 * Cannot safely flush overflowed CQEs from here, ensure we wake up
4352 * the task, and the next invocation will do it.
4354 if (io_should_wake(iowq) ||
4355 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
4356 return autoremove_wake_function(curr, mode, wake_flags, key);
4360 static int io_run_task_work_sig(void)
4362 if (io_run_task_work())
4364 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
4365 return -ERESTARTSYS;
4366 if (task_sigpending(current))
4371 /* when returns >0, the caller should retry */
4372 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
4373 struct io_wait_queue *iowq,
4377 unsigned long check_cq;
4379 /* make sure we run task_work before checking for signals */
4380 ret = io_run_task_work_sig();
4381 if (ret || io_should_wake(iowq))
4383 check_cq = READ_ONCE(ctx->check_cq);
4384 /* let the caller flush overflows, retry */
4385 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
4387 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
4389 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
4395 * Wait until events become available, if we don't already have some. The
4396 * application must reap them itself, as they reside on the shared cq ring.
4398 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
4399 const sigset_t __user *sig, size_t sigsz,
4400 struct __kernel_timespec __user *uts)
4402 struct io_wait_queue iowq;
4403 struct io_rings *rings = ctx->rings;
4404 ktime_t timeout = KTIME_MAX;
4408 io_cqring_overflow_flush(ctx);
4409 if (io_cqring_events(ctx) >= min_events)
4411 if (!io_run_task_work())
4416 #ifdef CONFIG_COMPAT
4417 if (in_compat_syscall())
4418 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
4422 ret = set_user_sigmask(sig, sigsz);
4429 struct timespec64 ts;
4431 if (get_timespec64(&ts, uts))
4433 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
4436 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
4437 iowq.wq.private = current;
4438 INIT_LIST_HEAD(&iowq.wq.entry);
4440 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
4441 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
4443 trace_io_uring_cqring_wait(ctx, min_events);
4445 /* if we can't even flush overflow, don't wait for more */
4446 if (!io_cqring_overflow_flush(ctx)) {
4450 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
4451 TASK_INTERRUPTIBLE);
4452 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
4456 finish_wait(&ctx->cq_wait, &iowq.wq);
4457 restore_saved_sigmask_unless(ret == -EINTR);
4459 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
4462 static void io_free_page_table(void **table, size_t size)
4464 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
4466 for (i = 0; i < nr_tables; i++)
4471 static __cold void **io_alloc_page_table(size_t size)
4473 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
4474 size_t init_size = size;
4477 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
4481 for (i = 0; i < nr_tables; i++) {
4482 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
4484 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
4486 io_free_page_table(table, init_size);
4494 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
4496 percpu_ref_exit(&ref_node->refs);
4500 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
4502 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
4503 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
4504 unsigned long flags;
4505 bool first_add = false;
4506 unsigned long delay = HZ;
4508 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
4511 /* if we are mid-quiesce then do not delay */
4512 if (node->rsrc_data->quiesce)
4515 while (!list_empty(&ctx->rsrc_ref_list)) {
4516 node = list_first_entry(&ctx->rsrc_ref_list,
4517 struct io_rsrc_node, node);
4518 /* recycle ref nodes in order */
4521 list_del(&node->node);
4522 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
4524 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
4527 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
4530 static struct io_rsrc_node *io_rsrc_node_alloc(void)
4532 struct io_rsrc_node *ref_node;
4534 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
4538 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
4543 INIT_LIST_HEAD(&ref_node->node);
4544 INIT_LIST_HEAD(&ref_node->rsrc_list);
4545 ref_node->done = false;
4549 void io_rsrc_node_switch(struct io_ring_ctx *ctx,
4550 struct io_rsrc_data *data_to_kill)
4551 __must_hold(&ctx->uring_lock)
4553 WARN_ON_ONCE(!ctx->rsrc_backup_node);
4554 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
4556 io_rsrc_refs_drop(ctx);
4559 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
4561 rsrc_node->rsrc_data = data_to_kill;
4562 spin_lock_irq(&ctx->rsrc_ref_lock);
4563 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
4564 spin_unlock_irq(&ctx->rsrc_ref_lock);
4566 atomic_inc(&data_to_kill->refs);
4567 percpu_ref_kill(&rsrc_node->refs);
4568 ctx->rsrc_node = NULL;
4571 if (!ctx->rsrc_node) {
4572 ctx->rsrc_node = ctx->rsrc_backup_node;
4573 ctx->rsrc_backup_node = NULL;
4577 int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
4579 if (ctx->rsrc_backup_node)
4581 ctx->rsrc_backup_node = io_rsrc_node_alloc();
4582 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
4585 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
4586 struct io_ring_ctx *ctx)
4590 /* As we may drop ->uring_lock, other task may have started quiesce */
4594 data->quiesce = true;
4596 ret = io_rsrc_node_switch_start(ctx);
4599 io_rsrc_node_switch(ctx, data);
4601 /* kill initial ref, already quiesced if zero */
4602 if (atomic_dec_and_test(&data->refs))
4604 mutex_unlock(&ctx->uring_lock);
4605 flush_delayed_work(&ctx->rsrc_put_work);
4606 ret = wait_for_completion_interruptible(&data->done);
4608 mutex_lock(&ctx->uring_lock);
4609 if (atomic_read(&data->refs) > 0) {
4611 * it has been revived by another thread while
4614 mutex_unlock(&ctx->uring_lock);
4620 atomic_inc(&data->refs);
4621 /* wait for all works potentially completing data->done */
4622 flush_delayed_work(&ctx->rsrc_put_work);
4623 reinit_completion(&data->done);
4625 ret = io_run_task_work_sig();
4626 mutex_lock(&ctx->uring_lock);
4628 data->quiesce = false;
4633 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
4635 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
4636 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
4638 return &data->tags[table_idx][off];
4641 static void io_rsrc_data_free(struct io_rsrc_data *data)
4643 size_t size = data->nr * sizeof(data->tags[0][0]);
4646 io_free_page_table((void **)data->tags, size);
4650 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
4651 u64 __user *utags, unsigned nr,
4652 struct io_rsrc_data **pdata)
4654 struct io_rsrc_data *data;
4658 data = kzalloc(sizeof(*data), GFP_KERNEL);
4661 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
4669 data->do_put = do_put;
4672 for (i = 0; i < nr; i++) {
4673 u64 *tag_slot = io_get_tag_slot(data, i);
4675 if (copy_from_user(tag_slot, &utags[i],
4681 atomic_set(&data->refs, 1);
4682 init_completion(&data->done);
4686 io_rsrc_data_free(data);
4690 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4692 #if !defined(IO_URING_SCM_ALL)
4695 for (i = 0; i < ctx->nr_user_files; i++) {
4696 struct file *file = io_file_from_index(&ctx->file_table, i);
4700 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
4702 io_file_bitmap_clear(&ctx->file_table, i);
4707 #if defined(CONFIG_UNIX)
4708 if (ctx->ring_sock) {
4709 struct sock *sock = ctx->ring_sock->sk;
4710 struct sk_buff *skb;
4712 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4716 io_free_file_tables(&ctx->file_table);
4717 io_rsrc_data_free(ctx->file_data);
4718 ctx->file_data = NULL;
4719 ctx->nr_user_files = 0;
4722 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4724 unsigned nr = ctx->nr_user_files;
4727 if (!ctx->file_data)
4731 * Quiesce may unlock ->uring_lock, and while it's not held
4732 * prevent new requests using the table.
4734 ctx->nr_user_files = 0;
4735 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
4736 ctx->nr_user_files = nr;
4738 __io_sqe_files_unregister(ctx);
4743 * Ensure the UNIX gc is aware of our file set, so we are certain that
4744 * the io_uring can be safely unregistered on process exit, even if we have
4745 * loops in the file referencing. We account only files that can hold other
4746 * files because otherwise they can't form a loop and so are not interesting
4749 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
4751 #if defined(CONFIG_UNIX)
4752 struct sock *sk = ctx->ring_sock->sk;
4753 struct sk_buff_head *head = &sk->sk_receive_queue;
4754 struct scm_fp_list *fpl;
4755 struct sk_buff *skb;
4757 if (likely(!io_file_need_scm(file)))
4761 * See if we can merge this file into an existing skb SCM_RIGHTS
4762 * file set. If there's no room, fall back to allocating a new skb
4763 * and filling it in.
4765 spin_lock_irq(&head->lock);
4766 skb = skb_peek(head);
4767 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
4768 __skb_unlink(skb, head);
4771 spin_unlock_irq(&head->lock);
4774 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4778 skb = alloc_skb(0, GFP_KERNEL);
4784 fpl->user = get_uid(current_user());
4785 fpl->max = SCM_MAX_FD;
4788 UNIXCB(skb).fp = fpl;
4790 skb->destructor = unix_destruct_scm;
4791 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4794 fpl = UNIXCB(skb).fp;
4795 fpl->fp[fpl->count++] = get_file(file);
4796 unix_inflight(fpl->user, file);
4797 skb_queue_head(head, skb);
4803 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
4805 struct file *file = prsrc->file;
4806 #if defined(CONFIG_UNIX)
4807 struct sock *sock = ctx->ring_sock->sk;
4808 struct sk_buff_head list, *head = &sock->sk_receive_queue;
4809 struct sk_buff *skb;
4812 if (!io_file_need_scm(file)) {
4817 __skb_queue_head_init(&list);
4820 * Find the skb that holds this file in its SCM_RIGHTS. When found,
4821 * remove this entry and rearrange the file array.
4823 skb = skb_dequeue(head);
4825 struct scm_fp_list *fp;
4827 fp = UNIXCB(skb).fp;
4828 for (i = 0; i < fp->count; i++) {
4831 if (fp->fp[i] != file)
4834 unix_notinflight(fp->user, fp->fp[i]);
4835 left = fp->count - 1 - i;
4837 memmove(&fp->fp[i], &fp->fp[i + 1],
4838 left * sizeof(struct file *));
4845 __skb_queue_tail(&list, skb);
4855 __skb_queue_tail(&list, skb);
4857 skb = skb_dequeue(head);
4860 if (skb_peek(&list)) {
4861 spin_lock_irq(&head->lock);
4862 while ((skb = __skb_dequeue(&list)) != NULL)
4863 __skb_queue_tail(head, skb);
4864 spin_unlock_irq(&head->lock);
4871 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
4873 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
4874 struct io_ring_ctx *ctx = rsrc_data->ctx;
4875 struct io_rsrc_put *prsrc, *tmp;
4877 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
4878 list_del(&prsrc->list);
4881 if (ctx->flags & IORING_SETUP_IOPOLL)
4882 mutex_lock(&ctx->uring_lock);
4884 spin_lock(&ctx->completion_lock);
4885 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
4886 io_commit_cqring(ctx);
4887 spin_unlock(&ctx->completion_lock);
4888 io_cqring_ev_posted(ctx);
4890 if (ctx->flags & IORING_SETUP_IOPOLL)
4891 mutex_unlock(&ctx->uring_lock);
4894 rsrc_data->do_put(ctx, prsrc);
4898 io_rsrc_node_destroy(ref_node);
4899 if (atomic_dec_and_test(&rsrc_data->refs))
4900 complete(&rsrc_data->done);
4903 static void io_rsrc_put_work(struct work_struct *work)
4905 struct io_ring_ctx *ctx;
4906 struct llist_node *node;
4908 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
4909 node = llist_del_all(&ctx->rsrc_put_llist);
4912 struct io_rsrc_node *ref_node;
4913 struct llist_node *next = node->next;
4915 ref_node = llist_entry(node, struct io_rsrc_node, llist);
4916 __io_rsrc_put_work(ref_node);
4921 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4922 unsigned nr_args, u64 __user *tags)
4924 __s32 __user *fds = (__s32 __user *) arg;
4933 if (nr_args > IORING_MAX_FIXED_FILES)
4935 if (nr_args > rlimit(RLIMIT_NOFILE))
4937 ret = io_rsrc_node_switch_start(ctx);
4940 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
4945 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
4946 io_rsrc_data_free(ctx->file_data);
4947 ctx->file_data = NULL;
4951 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4952 struct io_fixed_file *file_slot;
4954 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
4958 /* allow sparse sets */
4959 if (!fds || fd == -1) {
4961 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
4968 if (unlikely(!file))
4972 * Don't allow io_uring instances to be registered. If UNIX
4973 * isn't enabled, then this causes a reference cycle and this
4974 * instance can never get freed. If UNIX is enabled we'll
4975 * handle it just fine, but there's still no point in allowing
4976 * a ring fd as it doesn't support regular read/write anyway.
4978 if (io_is_uring_fops(file)) {
4982 ret = io_scm_file_account(ctx, file);
4987 file_slot = io_fixed_file_slot(&ctx->file_table, i);
4988 io_fixed_file_set(file_slot, file);
4989 io_file_bitmap_set(&ctx->file_table, i);
4992 io_rsrc_node_switch(ctx, NULL);
4995 __io_sqe_files_unregister(ctx);
4999 int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
5000 struct io_rsrc_node *node, void *rsrc)
5002 u64 *tag_slot = io_get_tag_slot(data, idx);
5003 struct io_rsrc_put *prsrc;
5005 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
5009 prsrc->tag = *tag_slot;
5012 list_add(&prsrc->list, &node->rsrc_list);
5016 int io_install_fixed_file(struct io_kiocb *req, struct file *file,
5017 unsigned int issue_flags, u32 slot_index)
5018 __must_hold(&req->ctx->uring_lock)
5020 struct io_ring_ctx *ctx = req->ctx;
5021 bool needs_switch = false;
5022 struct io_fixed_file *file_slot;
5025 if (io_is_uring_fops(file))
5027 if (!ctx->file_data)
5029 if (slot_index >= ctx->nr_user_files)
5032 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
5033 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
5035 if (file_slot->file_ptr) {
5036 struct file *old_file;
5038 ret = io_rsrc_node_switch_start(ctx);
5042 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
5043 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
5044 ctx->rsrc_node, old_file);
5047 file_slot->file_ptr = 0;
5048 io_file_bitmap_clear(&ctx->file_table, slot_index);
5049 needs_switch = true;
5052 ret = io_scm_file_account(ctx, file);
5054 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
5055 io_fixed_file_set(file_slot, file);
5056 io_file_bitmap_set(&ctx->file_table, slot_index);
5060 io_rsrc_node_switch(ctx, ctx->file_data);
5066 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5067 struct io_uring_rsrc_update2 *up,
5070 u64 __user *tags = u64_to_user_ptr(up->tags);
5071 __s32 __user *fds = u64_to_user_ptr(up->data);
5072 struct io_rsrc_data *data = ctx->file_data;
5073 struct io_fixed_file *file_slot;
5077 bool needs_switch = false;
5079 if (!ctx->file_data)
5081 if (up->offset + nr_args > ctx->nr_user_files)
5084 for (done = 0; done < nr_args; done++) {
5087 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
5088 copy_from_user(&fd, &fds[done], sizeof(fd))) {
5092 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
5096 if (fd == IORING_REGISTER_FILES_SKIP)
5099 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
5100 file_slot = io_fixed_file_slot(&ctx->file_table, i);
5102 if (file_slot->file_ptr) {
5103 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
5104 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
5107 file_slot->file_ptr = 0;
5108 io_file_bitmap_clear(&ctx->file_table, i);
5109 needs_switch = true;
5118 * Don't allow io_uring instances to be registered. If
5119 * UNIX isn't enabled, then this causes a reference
5120 * cycle and this instance can never get freed. If UNIX
5121 * is enabled we'll handle it just fine, but there's
5122 * still no point in allowing a ring fd as it doesn't
5123 * support regular read/write anyway.
5125 if (io_is_uring_fops(file)) {
5130 err = io_scm_file_account(ctx, file);
5135 *io_get_tag_slot(data, i) = tag;
5136 io_fixed_file_set(file_slot, file);
5137 io_file_bitmap_set(&ctx->file_table, i);
5142 io_rsrc_node_switch(ctx, data);
5143 return done ? done : err;
5146 static inline void __io_unaccount_mem(struct user_struct *user,
5147 unsigned long nr_pages)
5149 atomic_long_sub(nr_pages, &user->locked_vm);
5152 static inline int __io_account_mem(struct user_struct *user,
5153 unsigned long nr_pages)
5155 unsigned long page_limit, cur_pages, new_pages;
5157 /* Don't allow more pages than we can safely lock */
5158 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5161 cur_pages = atomic_long_read(&user->locked_vm);
5162 new_pages = cur_pages + nr_pages;
5163 if (new_pages > page_limit)
5165 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5166 new_pages) != cur_pages);
5171 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
5174 __io_unaccount_mem(ctx->user, nr_pages);
5176 if (ctx->mm_account)
5177 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
5180 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
5185 ret = __io_account_mem(ctx->user, nr_pages);
5190 if (ctx->mm_account)
5191 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
5196 static void io_mem_free(void *ptr)
5203 page = virt_to_head_page(ptr);
5204 if (put_page_testzero(page))
5205 free_compound_page(page);
5208 static void *io_mem_alloc(size_t size)
5210 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
5212 return (void *) __get_free_pages(gfp, get_order(size));
5215 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
5216 unsigned int cq_entries, size_t *sq_offset)
5218 struct io_rings *rings;
5219 size_t off, sq_array_size;
5221 off = struct_size(rings, cqes, cq_entries);
5222 if (off == SIZE_MAX)
5224 if (ctx->flags & IORING_SETUP_CQE32) {
5225 if (check_shl_overflow(off, 1, &off))
5230 off = ALIGN(off, SMP_CACHE_BYTES);
5238 sq_array_size = array_size(sizeof(u32), sq_entries);
5239 if (sq_array_size == SIZE_MAX)
5242 if (check_add_overflow(off, sq_array_size, &off))
5248 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
5250 struct io_mapped_ubuf *imu = *slot;
5253 if (imu != ctx->dummy_ubuf) {
5254 for (i = 0; i < imu->nr_bvecs; i++)
5255 unpin_user_page(imu->bvec[i].bv_page);
5256 if (imu->acct_pages)
5257 io_unaccount_mem(ctx, imu->acct_pages);
5263 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
5265 io_buffer_unmap(ctx, &prsrc->buf);
5269 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
5273 for (i = 0; i < ctx->nr_user_bufs; i++)
5274 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
5275 kfree(ctx->user_bufs);
5276 io_rsrc_data_free(ctx->buf_data);
5277 ctx->user_bufs = NULL;
5278 ctx->buf_data = NULL;
5279 ctx->nr_user_bufs = 0;
5282 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
5284 unsigned nr = ctx->nr_user_bufs;
5291 * Quiesce may unlock ->uring_lock, and while it's not held
5292 * prevent new requests using the table.
5294 ctx->nr_user_bufs = 0;
5295 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
5296 ctx->nr_user_bufs = nr;
5298 __io_sqe_buffers_unregister(ctx);
5302 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
5303 void __user *arg, unsigned index)
5305 struct iovec __user *src;
5307 #ifdef CONFIG_COMPAT
5309 struct compat_iovec __user *ciovs;
5310 struct compat_iovec ciov;
5312 ciovs = (struct compat_iovec __user *) arg;
5313 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
5316 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
5317 dst->iov_len = ciov.iov_len;
5321 src = (struct iovec __user *) arg;
5322 if (copy_from_user(dst, &src[index], sizeof(*dst)))
5328 * Not super efficient, but this is just a registration time. And we do cache
5329 * the last compound head, so generally we'll only do a full search if we don't
5332 * We check if the given compound head page has already been accounted, to
5333 * avoid double accounting it. This allows us to account the full size of the
5334 * page, not just the constituent pages of a huge page.
5336 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
5337 int nr_pages, struct page *hpage)
5341 /* check current page array */
5342 for (i = 0; i < nr_pages; i++) {
5343 if (!PageCompound(pages[i]))
5345 if (compound_head(pages[i]) == hpage)
5349 /* check previously registered pages */
5350 for (i = 0; i < ctx->nr_user_bufs; i++) {
5351 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
5353 for (j = 0; j < imu->nr_bvecs; j++) {
5354 if (!PageCompound(imu->bvec[j].bv_page))
5356 if (compound_head(imu->bvec[j].bv_page) == hpage)
5364 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
5365 int nr_pages, struct io_mapped_ubuf *imu,
5366 struct page **last_hpage)
5370 imu->acct_pages = 0;
5371 for (i = 0; i < nr_pages; i++) {
5372 if (!PageCompound(pages[i])) {
5377 hpage = compound_head(pages[i]);
5378 if (hpage == *last_hpage)
5380 *last_hpage = hpage;
5381 if (headpage_already_acct(ctx, pages, i, hpage))
5383 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
5387 if (!imu->acct_pages)
5390 ret = io_account_mem(ctx, imu->acct_pages);
5392 imu->acct_pages = 0;
5396 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
5399 unsigned long start, end, nr_pages;
5400 struct vm_area_struct **vmas = NULL;
5401 struct page **pages = NULL;
5402 int i, pret, ret = -ENOMEM;
5404 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
5405 start = ubuf >> PAGE_SHIFT;
5406 nr_pages = end - start;
5408 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
5412 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
5418 mmap_read_lock(current->mm);
5419 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
5421 if (pret == nr_pages) {
5422 /* don't support file backed memory */
5423 for (i = 0; i < nr_pages; i++) {
5424 struct vm_area_struct *vma = vmas[i];
5426 if (vma_is_shmem(vma))
5429 !is_file_hugepages(vma->vm_file)) {
5436 ret = pret < 0 ? pret : -EFAULT;
5438 mmap_read_unlock(current->mm);
5441 * if we did partial map, or found file backed vmas,
5442 * release any pages we did get
5445 unpin_user_pages(pages, pret);
5453 pages = ERR_PTR(ret);
5458 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
5459 struct io_mapped_ubuf **pimu,
5460 struct page **last_hpage)
5462 struct io_mapped_ubuf *imu = NULL;
5463 struct page **pages = NULL;
5466 int ret, nr_pages, i;
5468 if (!iov->iov_base) {
5469 *pimu = ctx->dummy_ubuf;
5476 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
5478 if (IS_ERR(pages)) {
5479 ret = PTR_ERR(pages);
5484 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
5488 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
5490 unpin_user_pages(pages, nr_pages);
5494 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
5495 size = iov->iov_len;
5496 for (i = 0; i < nr_pages; i++) {
5499 vec_len = min_t(size_t, size, PAGE_SIZE - off);
5500 imu->bvec[i].bv_page = pages[i];
5501 imu->bvec[i].bv_len = vec_len;
5502 imu->bvec[i].bv_offset = off;
5506 /* store original address for later verification */
5507 imu->ubuf = (unsigned long) iov->iov_base;
5508 imu->ubuf_end = imu->ubuf + iov->iov_len;
5509 imu->nr_bvecs = nr_pages;
5519 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
5521 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
5522 return ctx->user_bufs ? 0 : -ENOMEM;
5525 static int io_buffer_validate(struct iovec *iov)
5527 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
5530 * Don't impose further limits on the size and buffer
5531 * constraints here, we'll -EINVAL later when IO is
5532 * submitted if they are wrong.
5535 return iov->iov_len ? -EFAULT : 0;
5539 /* arbitrary limit, but we need something */
5540 if (iov->iov_len > SZ_1G)
5543 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
5549 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
5550 unsigned int nr_args, u64 __user *tags)
5552 struct page *last_hpage = NULL;
5553 struct io_rsrc_data *data;
5559 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
5561 ret = io_rsrc_node_switch_start(ctx);
5564 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
5567 ret = io_buffers_map_alloc(ctx, nr_args);
5569 io_rsrc_data_free(data);
5573 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
5575 ret = io_copy_iov(ctx, &iov, arg, i);
5578 ret = io_buffer_validate(&iov);
5582 memset(&iov, 0, sizeof(iov));
5585 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
5590 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
5596 WARN_ON_ONCE(ctx->buf_data);
5598 ctx->buf_data = data;
5600 __io_sqe_buffers_unregister(ctx);
5602 io_rsrc_node_switch(ctx, NULL);
5606 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
5607 struct io_uring_rsrc_update2 *up,
5608 unsigned int nr_args)
5610 u64 __user *tags = u64_to_user_ptr(up->tags);
5611 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
5612 struct page *last_hpage = NULL;
5613 bool needs_switch = false;
5619 if (up->offset + nr_args > ctx->nr_user_bufs)
5622 for (done = 0; done < nr_args; done++) {
5623 struct io_mapped_ubuf *imu;
5624 int offset = up->offset + done;
5627 err = io_copy_iov(ctx, &iov, iovs, done);
5630 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
5634 err = io_buffer_validate(&iov);
5637 if (!iov.iov_base && tag) {
5641 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
5645 i = array_index_nospec(offset, ctx->nr_user_bufs);
5646 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
5647 err = io_queue_rsrc_removal(ctx->buf_data, i,
5648 ctx->rsrc_node, ctx->user_bufs[i]);
5649 if (unlikely(err)) {
5650 io_buffer_unmap(ctx, &imu);
5653 ctx->user_bufs[i] = NULL;
5654 needs_switch = true;
5657 ctx->user_bufs[i] = imu;
5658 *io_get_tag_slot(ctx->buf_data, offset) = tag;
5662 io_rsrc_node_switch(ctx, ctx->buf_data);
5663 return done ? done : err;
5666 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
5667 unsigned int eventfd_async)
5669 struct io_ev_fd *ev_fd;
5670 __s32 __user *fds = arg;
5673 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5674 lockdep_is_held(&ctx->uring_lock));
5678 if (copy_from_user(&fd, fds, sizeof(*fds)))
5681 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
5685 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
5686 if (IS_ERR(ev_fd->cq_ev_fd)) {
5687 int ret = PTR_ERR(ev_fd->cq_ev_fd);
5691 ev_fd->eventfd_async = eventfd_async;
5692 ctx->has_evfd = true;
5693 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
5697 static void io_eventfd_put(struct rcu_head *rcu)
5699 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
5701 eventfd_ctx_put(ev_fd->cq_ev_fd);
5705 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
5707 struct io_ev_fd *ev_fd;
5709 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5710 lockdep_is_held(&ctx->uring_lock));
5712 ctx->has_evfd = false;
5713 rcu_assign_pointer(ctx->io_ev_fd, NULL);
5714 call_rcu(&ev_fd->rcu, io_eventfd_put);
5721 static void io_destroy_buffers(struct io_ring_ctx *ctx)
5723 struct io_buffer_list *bl;
5724 unsigned long index;
5727 for (i = 0; i < BGID_ARRAY; i++) {
5730 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
5733 xa_for_each(&ctx->io_bl_xa, index, bl) {
5734 xa_erase(&ctx->io_bl_xa, bl->bgid);
5735 __io_remove_buffers(ctx, bl, -1U);
5739 while (!list_empty(&ctx->io_buffers_pages)) {
5742 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
5743 list_del_init(&page->lru);
5748 static void io_req_caches_free(struct io_ring_ctx *ctx)
5750 struct io_submit_state *state = &ctx->submit_state;
5753 mutex_lock(&ctx->uring_lock);
5754 io_flush_cached_locked_reqs(ctx, state);
5756 while (!io_req_cache_empty(ctx)) {
5757 struct io_wq_work_node *node;
5758 struct io_kiocb *req;
5760 node = wq_stack_extract(&state->free_list);
5761 req = container_of(node, struct io_kiocb, comp_list);
5762 kmem_cache_free(req_cachep, req);
5766 percpu_ref_put_many(&ctx->refs, nr);
5767 mutex_unlock(&ctx->uring_lock);
5770 static void io_wait_rsrc_data(struct io_rsrc_data *data)
5772 if (data && !atomic_dec_and_test(&data->refs))
5773 wait_for_completion(&data->done);
5776 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
5778 struct async_poll *apoll;
5780 while (!list_empty(&ctx->apoll_cache)) {
5781 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
5783 list_del(&apoll->poll.wait.entry);
5788 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
5790 io_sq_thread_finish(ctx);
5792 if (ctx->mm_account) {
5793 mmdrop(ctx->mm_account);
5794 ctx->mm_account = NULL;
5797 io_rsrc_refs_drop(ctx);
5798 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
5799 io_wait_rsrc_data(ctx->buf_data);
5800 io_wait_rsrc_data(ctx->file_data);
5802 mutex_lock(&ctx->uring_lock);
5804 __io_sqe_buffers_unregister(ctx);
5806 __io_sqe_files_unregister(ctx);
5808 __io_cqring_overflow_flush(ctx, true);
5809 io_eventfd_unregister(ctx);
5810 io_flush_apoll_cache(ctx);
5811 mutex_unlock(&ctx->uring_lock);
5812 io_destroy_buffers(ctx);
5814 put_cred(ctx->sq_creds);
5816 /* there are no registered resources left, nobody uses it */
5818 io_rsrc_node_destroy(ctx->rsrc_node);
5819 if (ctx->rsrc_backup_node)
5820 io_rsrc_node_destroy(ctx->rsrc_backup_node);
5821 flush_delayed_work(&ctx->rsrc_put_work);
5822 flush_delayed_work(&ctx->fallback_work);
5824 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
5825 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
5827 #if defined(CONFIG_UNIX)
5828 if (ctx->ring_sock) {
5829 ctx->ring_sock->file = NULL; /* so that iput() is called */
5830 sock_release(ctx->ring_sock);
5833 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
5835 io_mem_free(ctx->rings);
5836 io_mem_free(ctx->sq_sqes);
5838 percpu_ref_exit(&ctx->refs);
5839 free_uid(ctx->user);
5840 io_req_caches_free(ctx);
5842 io_wq_put_hash(ctx->hash_map);
5843 kfree(ctx->cancel_hash);
5844 kfree(ctx->dummy_ubuf);
5846 xa_destroy(&ctx->io_bl_xa);
5850 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
5852 struct io_ring_ctx *ctx = file->private_data;
5855 poll_wait(file, &ctx->cq_wait, wait);
5857 * synchronizes with barrier from wq_has_sleeper call in
5861 if (!io_sqring_full(ctx))
5862 mask |= EPOLLOUT | EPOLLWRNORM;
5865 * Don't flush cqring overflow list here, just do a simple check.
5866 * Otherwise there could possible be ABBA deadlock:
5869 * lock(&ctx->uring_lock);
5871 * lock(&ctx->uring_lock);
5874 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
5875 * pushs them to do the flush.
5877 if (io_cqring_events(ctx) ||
5878 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
5879 mask |= EPOLLIN | EPOLLRDNORM;
5884 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
5886 const struct cred *creds;
5888 creds = xa_erase(&ctx->personalities, id);
5897 struct io_tctx_exit {
5898 struct callback_head task_work;
5899 struct completion completion;
5900 struct io_ring_ctx *ctx;
5903 static __cold void io_tctx_exit_cb(struct callback_head *cb)
5905 struct io_uring_task *tctx = current->io_uring;
5906 struct io_tctx_exit *work;
5908 work = container_of(cb, struct io_tctx_exit, task_work);
5910 * When @in_idle, we're in cancellation and it's racy to remove the
5911 * node. It'll be removed by the end of cancellation, just ignore it.
5913 if (!atomic_read(&tctx->in_idle))
5914 io_uring_del_tctx_node((unsigned long)work->ctx);
5915 complete(&work->completion);
5918 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
5920 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5922 return req->ctx == data;
5925 static __cold void io_ring_exit_work(struct work_struct *work)
5927 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
5928 unsigned long timeout = jiffies + HZ * 60 * 5;
5929 unsigned long interval = HZ / 20;
5930 struct io_tctx_exit exit;
5931 struct io_tctx_node *node;
5935 * If we're doing polled IO and end up having requests being
5936 * submitted async (out-of-line), then completions can come in while
5937 * we're waiting for refs to drop. We need to reap these manually,
5938 * as nobody else will be looking for them.
5941 io_uring_try_cancel_requests(ctx, NULL, true);
5943 struct io_sq_data *sqd = ctx->sq_data;
5944 struct task_struct *tsk;
5946 io_sq_thread_park(sqd);
5948 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
5949 io_wq_cancel_cb(tsk->io_uring->io_wq,
5950 io_cancel_ctx_cb, ctx, true);
5951 io_sq_thread_unpark(sqd);
5954 io_req_caches_free(ctx);
5956 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
5957 /* there is little hope left, don't run it too often */
5960 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
5962 init_completion(&exit.completion);
5963 init_task_work(&exit.task_work, io_tctx_exit_cb);
5966 * Some may use context even when all refs and requests have been put,
5967 * and they are free to do so while still holding uring_lock or
5968 * completion_lock, see io_req_task_submit(). Apart from other work,
5969 * this lock/unlock section also waits them to finish.
5971 mutex_lock(&ctx->uring_lock);
5972 while (!list_empty(&ctx->tctx_list)) {
5973 WARN_ON_ONCE(time_after(jiffies, timeout));
5975 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
5977 /* don't spin on a single task if cancellation failed */
5978 list_rotate_left(&ctx->tctx_list);
5979 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
5980 if (WARN_ON_ONCE(ret))
5983 mutex_unlock(&ctx->uring_lock);
5984 wait_for_completion(&exit.completion);
5985 mutex_lock(&ctx->uring_lock);
5987 mutex_unlock(&ctx->uring_lock);
5988 spin_lock(&ctx->completion_lock);
5989 spin_unlock(&ctx->completion_lock);
5991 io_ring_ctx_free(ctx);
5994 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
5996 unsigned long index;
5997 struct creds *creds;
5999 mutex_lock(&ctx->uring_lock);
6000 percpu_ref_kill(&ctx->refs);
6002 __io_cqring_overflow_flush(ctx, true);
6003 xa_for_each(&ctx->personalities, index, creds)
6004 io_unregister_personality(ctx, index);
6005 mutex_unlock(&ctx->uring_lock);
6007 /* failed during ring init, it couldn't have issued any requests */
6009 io_kill_timeouts(ctx, NULL, true);
6010 io_poll_remove_all(ctx, NULL, true);
6011 /* if we failed setting up the ctx, we might not have any rings */
6012 io_iopoll_try_reap_events(ctx);
6015 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
6017 * Use system_unbound_wq to avoid spawning tons of event kworkers
6018 * if we're exiting a ton of rings at the same time. It just adds
6019 * noise and overhead, there's no discernable change in runtime
6020 * over using system_wq.
6022 queue_work(system_unbound_wq, &ctx->exit_work);
6025 static int io_uring_release(struct inode *inode, struct file *file)
6027 struct io_ring_ctx *ctx = file->private_data;
6029 file->private_data = NULL;
6030 io_ring_ctx_wait_and_kill(ctx);
6034 struct io_task_cancel {
6035 struct task_struct *task;
6039 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
6041 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6042 struct io_task_cancel *cancel = data;
6044 return io_match_task_safe(req, cancel->task, cancel->all);
6047 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
6048 struct task_struct *task,
6051 struct io_defer_entry *de;
6054 spin_lock(&ctx->completion_lock);
6055 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
6056 if (io_match_task_safe(de->req, task, cancel_all)) {
6057 list_cut_position(&list, &ctx->defer_list, &de->list);
6061 spin_unlock(&ctx->completion_lock);
6062 if (list_empty(&list))
6065 while (!list_empty(&list)) {
6066 de = list_first_entry(&list, struct io_defer_entry, list);
6067 list_del_init(&de->list);
6068 io_req_complete_failed(de->req, -ECANCELED);
6074 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
6076 struct io_tctx_node *node;
6077 enum io_wq_cancel cret;
6080 mutex_lock(&ctx->uring_lock);
6081 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6082 struct io_uring_task *tctx = node->task->io_uring;
6085 * io_wq will stay alive while we hold uring_lock, because it's
6086 * killed after ctx nodes, which requires to take the lock.
6088 if (!tctx || !tctx->io_wq)
6090 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
6091 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
6093 mutex_unlock(&ctx->uring_lock);
6098 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
6099 struct task_struct *task,
6102 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
6103 struct io_uring_task *tctx = task ? task->io_uring : NULL;
6105 /* failed during ring init, it couldn't have issued any requests */
6110 enum io_wq_cancel cret;
6114 ret |= io_uring_try_cancel_iowq(ctx);
6115 } else if (tctx && tctx->io_wq) {
6117 * Cancels requests of all rings, not only @ctx, but
6118 * it's fine as the task is in exit/exec.
6120 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
6122 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
6125 /* SQPOLL thread does its own polling */
6126 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
6127 (ctx->sq_data && ctx->sq_data->thread == current)) {
6128 while (!wq_list_empty(&ctx->iopoll_list)) {
6129 io_iopoll_try_reap_events(ctx);
6134 ret |= io_cancel_defer_files(ctx, task, cancel_all);
6135 ret |= io_poll_remove_all(ctx, task, cancel_all);
6136 ret |= io_kill_timeouts(ctx, task, cancel_all);
6138 ret |= io_run_task_work();
6145 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
6148 return atomic_read(&tctx->inflight_tracked);
6149 return percpu_counter_sum(&tctx->inflight);
6153 * Find any io_uring ctx that this task has registered or done IO on, and cancel
6154 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
6156 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
6158 struct io_uring_task *tctx = current->io_uring;
6159 struct io_ring_ctx *ctx;
6163 WARN_ON_ONCE(sqd && sqd->thread != current);
6165 if (!current->io_uring)
6168 io_wq_exit_start(tctx->io_wq);
6170 atomic_inc(&tctx->in_idle);
6172 io_uring_drop_tctx_refs(current);
6173 /* read completions before cancelations */
6174 inflight = tctx_inflight(tctx, !cancel_all);
6179 struct io_tctx_node *node;
6180 unsigned long index;
6182 xa_for_each(&tctx->xa, index, node) {
6183 /* sqpoll task will cancel all its requests */
6184 if (node->ctx->sq_data)
6186 io_uring_try_cancel_requests(node->ctx, current,
6190 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6191 io_uring_try_cancel_requests(ctx, current,
6195 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
6197 io_uring_drop_tctx_refs(current);
6200 * If we've seen completions, retry without waiting. This
6201 * avoids a race where a completion comes in before we did
6202 * prepare_to_wait().
6204 if (inflight == tctx_inflight(tctx, !cancel_all))
6206 finish_wait(&tctx->wait, &wait);
6209 io_uring_clean_tctx(tctx);
6212 * We shouldn't run task_works after cancel, so just leave
6213 * ->in_idle set for normal exit.
6215 atomic_dec(&tctx->in_idle);
6216 /* for exec all current's requests should be gone, kill tctx */
6217 __io_uring_free(current);
6221 void __io_uring_cancel(bool cancel_all)
6223 io_uring_cancel_generic(cancel_all, NULL);
6226 static void *io_uring_validate_mmap_request(struct file *file,
6227 loff_t pgoff, size_t sz)
6229 struct io_ring_ctx *ctx = file->private_data;
6230 loff_t offset = pgoff << PAGE_SHIFT;
6235 case IORING_OFF_SQ_RING:
6236 case IORING_OFF_CQ_RING:
6239 case IORING_OFF_SQES:
6243 return ERR_PTR(-EINVAL);
6246 page = virt_to_head_page(ptr);
6247 if (sz > page_size(page))
6248 return ERR_PTR(-EINVAL);
6255 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6257 size_t sz = vma->vm_end - vma->vm_start;
6261 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6263 return PTR_ERR(ptr);
6265 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6266 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6269 #else /* !CONFIG_MMU */
6271 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6273 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6276 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6278 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6281 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6282 unsigned long addr, unsigned long len,
6283 unsigned long pgoff, unsigned long flags)
6287 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6289 return PTR_ERR(ptr);
6291 return (unsigned long) ptr;
6294 #endif /* !CONFIG_MMU */
6296 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
6298 if (flags & IORING_ENTER_EXT_ARG) {
6299 struct io_uring_getevents_arg arg;
6301 if (argsz != sizeof(arg))
6303 if (copy_from_user(&arg, argp, sizeof(arg)))
6309 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
6310 struct __kernel_timespec __user **ts,
6311 const sigset_t __user **sig)
6313 struct io_uring_getevents_arg arg;
6316 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
6317 * is just a pointer to the sigset_t.
6319 if (!(flags & IORING_ENTER_EXT_ARG)) {
6320 *sig = (const sigset_t __user *) argp;
6326 * EXT_ARG is set - ensure we agree on the size of it and copy in our
6327 * timespec and sigset_t pointers if good.
6329 if (*argsz != sizeof(arg))
6331 if (copy_from_user(&arg, argp, sizeof(arg)))
6335 *sig = u64_to_user_ptr(arg.sigmask);
6336 *argsz = arg.sigmask_sz;
6337 *ts = u64_to_user_ptr(arg.ts);
6341 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6342 u32, min_complete, u32, flags, const void __user *, argp,
6345 struct io_ring_ctx *ctx;
6351 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
6352 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
6353 IORING_ENTER_REGISTERED_RING)))
6357 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
6358 * need only dereference our task private array to find it.
6360 if (flags & IORING_ENTER_REGISTERED_RING) {
6361 struct io_uring_task *tctx = current->io_uring;
6363 if (!tctx || fd >= IO_RINGFD_REG_MAX)
6365 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
6366 f.file = tctx->registered_rings[fd];
6372 if (unlikely(!f.file))
6376 if (unlikely(!io_is_uring_fops(f.file)))
6380 ctx = f.file->private_data;
6381 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
6385 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
6389 * For SQ polling, the thread will do all submissions and completions.
6390 * Just return the requested submit count, and wake the thread if
6394 if (ctx->flags & IORING_SETUP_SQPOLL) {
6395 io_cqring_overflow_flush(ctx);
6397 if (unlikely(ctx->sq_data->thread == NULL)) {
6401 if (flags & IORING_ENTER_SQ_WAKEUP)
6402 wake_up(&ctx->sq_data->wait);
6403 if (flags & IORING_ENTER_SQ_WAIT) {
6404 ret = io_sqpoll_wait_sq(ctx);
6409 } else if (to_submit) {
6410 ret = io_uring_add_tctx_node(ctx);
6414 mutex_lock(&ctx->uring_lock);
6415 ret = io_submit_sqes(ctx, to_submit);
6416 if (ret != to_submit) {
6417 mutex_unlock(&ctx->uring_lock);
6420 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
6422 mutex_unlock(&ctx->uring_lock);
6424 if (flags & IORING_ENTER_GETEVENTS) {
6426 if (ctx->syscall_iopoll) {
6428 * We disallow the app entering submit/complete with
6429 * polling, but we still need to lock the ring to
6430 * prevent racing with polled issue that got punted to
6433 mutex_lock(&ctx->uring_lock);
6435 ret2 = io_validate_ext_arg(flags, argp, argsz);
6436 if (likely(!ret2)) {
6437 min_complete = min(min_complete,
6439 ret2 = io_iopoll_check(ctx, min_complete);
6441 mutex_unlock(&ctx->uring_lock);
6443 const sigset_t __user *sig;
6444 struct __kernel_timespec __user *ts;
6446 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
6447 if (likely(!ret2)) {
6448 min_complete = min(min_complete,
6450 ret2 = io_cqring_wait(ctx, min_complete, sig,
6459 * EBADR indicates that one or more CQE were dropped.
6460 * Once the user has been informed we can clear the bit
6461 * as they are obviously ok with those drops.
6463 if (unlikely(ret2 == -EBADR))
6464 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
6470 percpu_ref_put(&ctx->refs);
6476 static const struct file_operations io_uring_fops = {
6477 .release = io_uring_release,
6478 .mmap = io_uring_mmap,
6480 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6481 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6483 .poll = io_uring_poll,
6484 #ifdef CONFIG_PROC_FS
6485 .show_fdinfo = io_uring_show_fdinfo,
6489 bool io_is_uring_fops(struct file *file)
6491 return file->f_op == &io_uring_fops;
6494 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6495 struct io_uring_params *p)
6497 struct io_rings *rings;
6498 size_t size, sq_array_offset;
6500 /* make sure these are sane, as we already accounted them */
6501 ctx->sq_entries = p->sq_entries;
6502 ctx->cq_entries = p->cq_entries;
6504 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
6505 if (size == SIZE_MAX)
6508 rings = io_mem_alloc(size);
6513 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6514 rings->sq_ring_mask = p->sq_entries - 1;
6515 rings->cq_ring_mask = p->cq_entries - 1;
6516 rings->sq_ring_entries = p->sq_entries;
6517 rings->cq_ring_entries = p->cq_entries;
6519 if (p->flags & IORING_SETUP_SQE128)
6520 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
6522 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6523 if (size == SIZE_MAX) {
6524 io_mem_free(ctx->rings);
6529 ctx->sq_sqes = io_mem_alloc(size);
6530 if (!ctx->sq_sqes) {
6531 io_mem_free(ctx->rings);
6539 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
6543 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6547 ret = io_uring_add_tctx_node(ctx);
6552 fd_install(fd, file);
6557 * Allocate an anonymous fd, this is what constitutes the application
6558 * visible backing of an io_uring instance. The application mmaps this
6559 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6560 * we have to tie this fd to a socket for file garbage collection purposes.
6562 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
6565 #if defined(CONFIG_UNIX)
6568 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6571 return ERR_PTR(ret);
6574 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
6575 O_RDWR | O_CLOEXEC, NULL);
6576 #if defined(CONFIG_UNIX)
6578 sock_release(ctx->ring_sock);
6579 ctx->ring_sock = NULL;
6581 ctx->ring_sock->file = file;
6587 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
6588 struct io_uring_params __user *params)
6590 struct io_ring_ctx *ctx;
6596 if (entries > IORING_MAX_ENTRIES) {
6597 if (!(p->flags & IORING_SETUP_CLAMP))
6599 entries = IORING_MAX_ENTRIES;
6603 * Use twice as many entries for the CQ ring. It's possible for the
6604 * application to drive a higher depth than the size of the SQ ring,
6605 * since the sqes are only used at submission time. This allows for
6606 * some flexibility in overcommitting a bit. If the application has
6607 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6608 * of CQ ring entries manually.
6610 p->sq_entries = roundup_pow_of_two(entries);
6611 if (p->flags & IORING_SETUP_CQSIZE) {
6613 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6614 * to a power-of-two, if it isn't already. We do NOT impose
6615 * any cq vs sq ring sizing.
6619 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6620 if (!(p->flags & IORING_SETUP_CLAMP))
6622 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6624 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6625 if (p->cq_entries < p->sq_entries)
6628 p->cq_entries = 2 * p->sq_entries;
6631 ctx = io_ring_ctx_alloc(p);
6636 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
6637 * space applications don't need to do io completion events
6638 * polling again, they can rely on io_sq_thread to do polling
6639 * work, which can reduce cpu usage and uring_lock contention.
6641 if (ctx->flags & IORING_SETUP_IOPOLL &&
6642 !(ctx->flags & IORING_SETUP_SQPOLL))
6643 ctx->syscall_iopoll = 1;
6645 ctx->compat = in_compat_syscall();
6646 if (!capable(CAP_IPC_LOCK))
6647 ctx->user = get_uid(current_user());
6650 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
6651 * COOP_TASKRUN is set, then IPIs are never needed by the app.
6654 if (ctx->flags & IORING_SETUP_SQPOLL) {
6655 /* IPI related flags don't make sense with SQPOLL */
6656 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
6657 IORING_SETUP_TASKRUN_FLAG))
6659 ctx->notify_method = TWA_SIGNAL_NO_IPI;
6660 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
6661 ctx->notify_method = TWA_SIGNAL_NO_IPI;
6663 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
6665 ctx->notify_method = TWA_SIGNAL;
6669 * This is just grabbed for accounting purposes. When a process exits,
6670 * the mm is exited and dropped before the files, hence we need to hang
6671 * on to this mm purely for the purposes of being able to unaccount
6672 * memory (locked/pinned vm). It's not used for anything else.
6674 mmgrab(current->mm);
6675 ctx->mm_account = current->mm;
6677 ret = io_allocate_scq_urings(ctx, p);
6681 ret = io_sq_offload_create(ctx, p);
6684 /* always set a rsrc node */
6685 ret = io_rsrc_node_switch_start(ctx);
6688 io_rsrc_node_switch(ctx, NULL);
6690 memset(&p->sq_off, 0, sizeof(p->sq_off));
6691 p->sq_off.head = offsetof(struct io_rings, sq.head);
6692 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6693 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6694 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6695 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6696 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6697 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6699 memset(&p->cq_off, 0, sizeof(p->cq_off));
6700 p->cq_off.head = offsetof(struct io_rings, cq.head);
6701 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6702 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6703 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6704 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6705 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6706 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
6708 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6709 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6710 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
6711 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
6712 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
6713 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
6714 IORING_FEAT_LINKED_FILE;
6716 if (copy_to_user(params, p, sizeof(*p))) {
6721 file = io_uring_get_file(ctx);
6723 ret = PTR_ERR(file);
6728 * Install ring fd as the very last thing, so we don't risk someone
6729 * having closed it before we finish setup
6731 ret = io_uring_install_fd(ctx, file);
6733 /* fput will clean it up */
6738 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6741 io_ring_ctx_wait_and_kill(ctx);
6746 * Sets up an aio uring context, and returns the fd. Applications asks for a
6747 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6748 * params structure passed in.
6750 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6752 struct io_uring_params p;
6755 if (copy_from_user(&p, params, sizeof(p)))
6757 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6762 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6763 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6764 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
6765 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
6766 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
6767 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
6770 return io_uring_create(entries, &p, params);
6773 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6774 struct io_uring_params __user *, params)
6776 return io_uring_setup(entries, params);
6779 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
6782 struct io_uring_probe *p;
6786 size = struct_size(p, ops, nr_args);
6787 if (size == SIZE_MAX)
6789 p = kzalloc(size, GFP_KERNEL);
6794 if (copy_from_user(p, arg, size))
6797 if (memchr_inv(p, 0, size))
6800 p->last_op = IORING_OP_LAST - 1;
6801 if (nr_args > IORING_OP_LAST)
6802 nr_args = IORING_OP_LAST;
6804 for (i = 0; i < nr_args; i++) {
6806 if (!io_op_defs[i].not_supported)
6807 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6812 if (copy_to_user(arg, p, size))
6819 static int io_register_personality(struct io_ring_ctx *ctx)
6821 const struct cred *creds;
6825 creds = get_current_cred();
6827 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
6828 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
6836 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
6837 void __user *arg, unsigned int nr_args)
6839 struct io_uring_restriction *res;
6843 /* Restrictions allowed only if rings started disabled */
6844 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6847 /* We allow only a single restrictions registration */
6848 if (ctx->restrictions.registered)
6851 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
6854 size = array_size(nr_args, sizeof(*res));
6855 if (size == SIZE_MAX)
6858 res = memdup_user(arg, size);
6860 return PTR_ERR(res);
6864 for (i = 0; i < nr_args; i++) {
6865 switch (res[i].opcode) {
6866 case IORING_RESTRICTION_REGISTER_OP:
6867 if (res[i].register_op >= IORING_REGISTER_LAST) {
6872 __set_bit(res[i].register_op,
6873 ctx->restrictions.register_op);
6875 case IORING_RESTRICTION_SQE_OP:
6876 if (res[i].sqe_op >= IORING_OP_LAST) {
6881 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
6883 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
6884 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
6886 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
6887 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
6896 /* Reset all restrictions if an error happened */
6898 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
6900 ctx->restrictions.registered = true;
6906 static int io_register_enable_rings(struct io_ring_ctx *ctx)
6908 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6911 if (ctx->restrictions.registered)
6912 ctx->restricted = 1;
6914 ctx->flags &= ~IORING_SETUP_R_DISABLED;
6915 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
6916 wake_up(&ctx->sq_data->wait);
6920 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
6921 struct io_uring_rsrc_update2 *up,
6927 if (check_add_overflow(up->offset, nr_args, &tmp))
6929 err = io_rsrc_node_switch_start(ctx);
6934 case IORING_RSRC_FILE:
6935 return __io_sqe_files_update(ctx, up, nr_args);
6936 case IORING_RSRC_BUFFER:
6937 return __io_sqe_buffers_update(ctx, up, nr_args);
6942 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
6945 struct io_uring_rsrc_update2 up;
6949 memset(&up, 0, sizeof(up));
6950 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
6952 if (up.resv || up.resv2)
6954 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
6957 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
6958 unsigned size, unsigned type)
6960 struct io_uring_rsrc_update2 up;
6962 if (size != sizeof(up))
6964 if (copy_from_user(&up, arg, sizeof(up)))
6966 if (!up.nr || up.resv || up.resv2)
6968 return __io_register_rsrc_update(ctx, type, &up, up.nr);
6971 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
6972 unsigned int size, unsigned int type)
6974 struct io_uring_rsrc_register rr;
6976 /* keep it extendible */
6977 if (size != sizeof(rr))
6980 memset(&rr, 0, sizeof(rr));
6981 if (copy_from_user(&rr, arg, size))
6983 if (!rr.nr || rr.resv2)
6985 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
6989 case IORING_RSRC_FILE:
6990 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6992 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
6993 rr.nr, u64_to_user_ptr(rr.tags));
6994 case IORING_RSRC_BUFFER:
6995 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6997 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
6998 rr.nr, u64_to_user_ptr(rr.tags));
7003 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
7004 void __user *arg, unsigned len)
7006 struct io_uring_task *tctx = current->io_uring;
7007 cpumask_var_t new_mask;
7010 if (!tctx || !tctx->io_wq)
7013 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
7016 cpumask_clear(new_mask);
7017 if (len > cpumask_size())
7018 len = cpumask_size();
7020 if (in_compat_syscall()) {
7021 ret = compat_get_bitmap(cpumask_bits(new_mask),
7022 (const compat_ulong_t __user *)arg,
7023 len * 8 /* CHAR_BIT */);
7025 ret = copy_from_user(new_mask, arg, len);
7029 free_cpumask_var(new_mask);
7033 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
7034 free_cpumask_var(new_mask);
7038 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
7040 struct io_uring_task *tctx = current->io_uring;
7042 if (!tctx || !tctx->io_wq)
7045 return io_wq_cpu_affinity(tctx->io_wq, NULL);
7048 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
7050 __must_hold(&ctx->uring_lock)
7052 struct io_tctx_node *node;
7053 struct io_uring_task *tctx = NULL;
7054 struct io_sq_data *sqd = NULL;
7058 if (copy_from_user(new_count, arg, sizeof(new_count)))
7060 for (i = 0; i < ARRAY_SIZE(new_count); i++)
7061 if (new_count[i] > INT_MAX)
7064 if (ctx->flags & IORING_SETUP_SQPOLL) {
7068 * Observe the correct sqd->lock -> ctx->uring_lock
7069 * ordering. Fine to drop uring_lock here, we hold
7072 refcount_inc(&sqd->refs);
7073 mutex_unlock(&ctx->uring_lock);
7074 mutex_lock(&sqd->lock);
7075 mutex_lock(&ctx->uring_lock);
7077 tctx = sqd->thread->io_uring;
7080 tctx = current->io_uring;
7083 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
7085 for (i = 0; i < ARRAY_SIZE(new_count); i++)
7087 ctx->iowq_limits[i] = new_count[i];
7088 ctx->iowq_limits_set = true;
7090 if (tctx && tctx->io_wq) {
7091 ret = io_wq_max_workers(tctx->io_wq, new_count);
7095 memset(new_count, 0, sizeof(new_count));
7099 mutex_unlock(&sqd->lock);
7100 io_put_sq_data(sqd);
7103 if (copy_to_user(arg, new_count, sizeof(new_count)))
7106 /* that's it for SQPOLL, only the SQPOLL task creates requests */
7110 /* now propagate the restriction to all registered users */
7111 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7112 struct io_uring_task *tctx = node->task->io_uring;
7114 if (WARN_ON_ONCE(!tctx->io_wq))
7117 for (i = 0; i < ARRAY_SIZE(new_count); i++)
7118 new_count[i] = ctx->iowq_limits[i];
7119 /* ignore errors, it always returns zero anyway */
7120 (void)io_wq_max_workers(tctx->io_wq, new_count);
7125 mutex_unlock(&sqd->lock);
7126 io_put_sq_data(sqd);
7131 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
7133 struct io_uring_buf_ring *br;
7134 struct io_uring_buf_reg reg;
7135 struct io_buffer_list *bl, *free_bl = NULL;
7136 struct page **pages;
7139 if (copy_from_user(®, arg, sizeof(reg)))
7142 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
7146 if (reg.ring_addr & ~PAGE_MASK)
7148 if (!is_power_of_2(reg.ring_entries))
7151 /* cannot disambiguate full vs empty due to head/tail size */
7152 if (reg.ring_entries >= 65536)
7155 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
7156 int ret = io_init_bl_list(ctx);
7161 bl = io_buffer_get_list(ctx, reg.bgid);
7163 /* if mapped buffer ring OR classic exists, don't allow */
7164 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
7167 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
7172 pages = io_pin_pages(reg.ring_addr,
7173 struct_size(br, bufs, reg.ring_entries),
7175 if (IS_ERR(pages)) {
7177 return PTR_ERR(pages);
7180 br = page_address(pages[0]);
7181 bl->buf_pages = pages;
7182 bl->buf_nr_pages = nr_pages;
7183 bl->nr_entries = reg.ring_entries;
7185 bl->mask = reg.ring_entries - 1;
7186 io_buffer_add_list(ctx, bl, reg.bgid);
7190 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
7192 struct io_uring_buf_reg reg;
7193 struct io_buffer_list *bl;
7195 if (copy_from_user(®, arg, sizeof(reg)))
7197 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
7200 bl = io_buffer_get_list(ctx, reg.bgid);
7203 if (!bl->buf_nr_pages)
7206 __io_remove_buffers(ctx, bl, -1U);
7207 if (bl->bgid >= BGID_ARRAY) {
7208 xa_erase(&ctx->io_bl_xa, bl->bgid);
7214 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
7215 void __user *arg, unsigned nr_args)
7216 __releases(ctx->uring_lock)
7217 __acquires(ctx->uring_lock)
7222 * We're inside the ring mutex, if the ref is already dying, then
7223 * someone else killed the ctx or is already going through
7224 * io_uring_register().
7226 if (percpu_ref_is_dying(&ctx->refs))
7229 if (ctx->restricted) {
7230 if (opcode >= IORING_REGISTER_LAST)
7232 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
7233 if (!test_bit(opcode, ctx->restrictions.register_op))
7238 case IORING_REGISTER_BUFFERS:
7242 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
7244 case IORING_UNREGISTER_BUFFERS:
7248 ret = io_sqe_buffers_unregister(ctx);
7250 case IORING_REGISTER_FILES:
7254 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
7256 case IORING_UNREGISTER_FILES:
7260 ret = io_sqe_files_unregister(ctx);
7262 case IORING_REGISTER_FILES_UPDATE:
7263 ret = io_register_files_update(ctx, arg, nr_args);
7265 case IORING_REGISTER_EVENTFD:
7269 ret = io_eventfd_register(ctx, arg, 0);
7271 case IORING_REGISTER_EVENTFD_ASYNC:
7275 ret = io_eventfd_register(ctx, arg, 1);
7277 case IORING_UNREGISTER_EVENTFD:
7281 ret = io_eventfd_unregister(ctx);
7283 case IORING_REGISTER_PROBE:
7285 if (!arg || nr_args > 256)
7287 ret = io_probe(ctx, arg, nr_args);
7289 case IORING_REGISTER_PERSONALITY:
7293 ret = io_register_personality(ctx);
7295 case IORING_UNREGISTER_PERSONALITY:
7299 ret = io_unregister_personality(ctx, nr_args);
7301 case IORING_REGISTER_ENABLE_RINGS:
7305 ret = io_register_enable_rings(ctx);
7307 case IORING_REGISTER_RESTRICTIONS:
7308 ret = io_register_restrictions(ctx, arg, nr_args);
7310 case IORING_REGISTER_FILES2:
7311 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
7313 case IORING_REGISTER_FILES_UPDATE2:
7314 ret = io_register_rsrc_update(ctx, arg, nr_args,
7317 case IORING_REGISTER_BUFFERS2:
7318 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
7320 case IORING_REGISTER_BUFFERS_UPDATE:
7321 ret = io_register_rsrc_update(ctx, arg, nr_args,
7322 IORING_RSRC_BUFFER);
7324 case IORING_REGISTER_IOWQ_AFF:
7326 if (!arg || !nr_args)
7328 ret = io_register_iowq_aff(ctx, arg, nr_args);
7330 case IORING_UNREGISTER_IOWQ_AFF:
7334 ret = io_unregister_iowq_aff(ctx);
7336 case IORING_REGISTER_IOWQ_MAX_WORKERS:
7338 if (!arg || nr_args != 2)
7340 ret = io_register_iowq_max_workers(ctx, arg);
7342 case IORING_REGISTER_RING_FDS:
7343 ret = io_ringfd_register(ctx, arg, nr_args);
7345 case IORING_UNREGISTER_RING_FDS:
7346 ret = io_ringfd_unregister(ctx, arg, nr_args);
7348 case IORING_REGISTER_PBUF_RING:
7350 if (!arg || nr_args != 1)
7352 ret = io_register_pbuf_ring(ctx, arg);
7354 case IORING_UNREGISTER_PBUF_RING:
7356 if (!arg || nr_args != 1)
7358 ret = io_unregister_pbuf_ring(ctx, arg);
7368 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7369 void __user *, arg, unsigned int, nr_args)
7371 struct io_ring_ctx *ctx;
7380 if (!io_is_uring_fops(f.file))
7383 ctx = f.file->private_data;
7387 mutex_lock(&ctx->uring_lock);
7388 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7389 mutex_unlock(&ctx->uring_lock);
7390 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
7396 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
7402 const struct io_op_def io_op_defs[] = {
7407 .prep = io_nop_prep,
7410 [IORING_OP_READV] = {
7412 .unbound_nonreg_file = 1,
7419 .async_size = sizeof(struct io_async_rw),
7423 .prep_async = io_readv_prep_async,
7424 .cleanup = io_readv_writev_cleanup,
7426 [IORING_OP_WRITEV] = {
7429 .unbound_nonreg_file = 1,
7435 .async_size = sizeof(struct io_async_rw),
7439 .prep_async = io_writev_prep_async,
7440 .cleanup = io_readv_writev_cleanup,
7442 [IORING_OP_FSYNC] = {
7446 .prep = io_fsync_prep,
7449 [IORING_OP_READ_FIXED] = {
7451 .unbound_nonreg_file = 1,
7457 .async_size = sizeof(struct io_async_rw),
7458 .name = "READ_FIXED",
7462 [IORING_OP_WRITE_FIXED] = {
7465 .unbound_nonreg_file = 1,
7471 .async_size = sizeof(struct io_async_rw),
7472 .name = "WRITE_FIXED",
7476 [IORING_OP_POLL_ADD] = {
7478 .unbound_nonreg_file = 1,
7481 .prep = io_poll_add_prep,
7482 .issue = io_poll_add,
7484 [IORING_OP_POLL_REMOVE] = {
7486 .name = "POLL_REMOVE",
7487 .prep = io_poll_remove_prep,
7488 .issue = io_poll_remove,
7490 [IORING_OP_SYNC_FILE_RANGE] = {
7493 .name = "SYNC_FILE_RANGE",
7494 .prep = io_sfr_prep,
7495 .issue = io_sync_file_range,
7497 [IORING_OP_SENDMSG] = {
7499 .unbound_nonreg_file = 1,
7503 #if defined(CONFIG_NET)
7504 .async_size = sizeof(struct io_async_msghdr),
7505 .prep = io_sendmsg_prep,
7506 .issue = io_sendmsg,
7507 .prep_async = io_sendmsg_prep_async,
7508 .cleanup = io_sendmsg_recvmsg_cleanup,
7510 .prep = io_eopnotsupp_prep,
7513 [IORING_OP_RECVMSG] = {
7515 .unbound_nonreg_file = 1,
7520 #if defined(CONFIG_NET)
7521 .async_size = sizeof(struct io_async_msghdr),
7522 .prep = io_recvmsg_prep,
7523 .issue = io_recvmsg,
7524 .prep_async = io_recvmsg_prep_async,
7525 .cleanup = io_sendmsg_recvmsg_cleanup,
7527 .prep = io_eopnotsupp_prep,
7530 [IORING_OP_TIMEOUT] = {
7532 .async_size = sizeof(struct io_timeout_data),
7534 .prep = io_timeout_prep,
7535 .issue = io_timeout,
7537 [IORING_OP_TIMEOUT_REMOVE] = {
7538 /* used by timeout updates' prep() */
7540 .name = "TIMEOUT_REMOVE",
7541 .prep = io_timeout_remove_prep,
7542 .issue = io_timeout_remove,
7544 [IORING_OP_ACCEPT] = {
7546 .unbound_nonreg_file = 1,
7548 .poll_exclusive = 1,
7549 .ioprio = 1, /* used for flags */
7551 #if defined(CONFIG_NET)
7552 .prep = io_accept_prep,
7555 .prep = io_eopnotsupp_prep,
7558 [IORING_OP_ASYNC_CANCEL] = {
7560 .name = "ASYNC_CANCEL",
7561 .prep = io_async_cancel_prep,
7562 .issue = io_async_cancel,
7564 [IORING_OP_LINK_TIMEOUT] = {
7566 .async_size = sizeof(struct io_timeout_data),
7567 .name = "LINK_TIMEOUT",
7568 .prep = io_link_timeout_prep,
7569 .issue = io_no_issue,
7571 [IORING_OP_CONNECT] = {
7573 .unbound_nonreg_file = 1,
7576 #if defined(CONFIG_NET)
7577 .async_size = sizeof(struct io_async_connect),
7578 .prep = io_connect_prep,
7579 .issue = io_connect,
7580 .prep_async = io_connect_prep_async,
7582 .prep = io_eopnotsupp_prep,
7585 [IORING_OP_FALLOCATE] = {
7587 .name = "FALLOCATE",
7588 .prep = io_fallocate_prep,
7589 .issue = io_fallocate,
7591 [IORING_OP_OPENAT] = {
7593 .prep = io_openat_prep,
7595 .cleanup = io_open_cleanup,
7597 [IORING_OP_CLOSE] = {
7599 .prep = io_close_prep,
7602 [IORING_OP_FILES_UPDATE] = {
7605 .name = "FILES_UPDATE",
7606 .prep = io_files_update_prep,
7607 .issue = io_files_update,
7609 [IORING_OP_STATX] = {
7612 .prep = io_statx_prep,
7614 .cleanup = io_statx_cleanup,
7616 [IORING_OP_READ] = {
7618 .unbound_nonreg_file = 1,
7625 .async_size = sizeof(struct io_async_rw),
7630 [IORING_OP_WRITE] = {
7633 .unbound_nonreg_file = 1,
7639 .async_size = sizeof(struct io_async_rw),
7644 [IORING_OP_FADVISE] = {
7648 .prep = io_fadvise_prep,
7649 .issue = io_fadvise,
7651 [IORING_OP_MADVISE] = {
7653 .prep = io_madvise_prep,
7654 .issue = io_madvise,
7656 [IORING_OP_SEND] = {
7658 .unbound_nonreg_file = 1,
7663 #if defined(CONFIG_NET)
7664 .prep = io_sendmsg_prep,
7667 .prep = io_eopnotsupp_prep,
7670 [IORING_OP_RECV] = {
7672 .unbound_nonreg_file = 1,
7678 #if defined(CONFIG_NET)
7679 .prep = io_recvmsg_prep,
7682 .prep = io_eopnotsupp_prep,
7685 [IORING_OP_OPENAT2] = {
7687 .prep = io_openat2_prep,
7688 .issue = io_openat2,
7689 .cleanup = io_open_cleanup,
7691 [IORING_OP_EPOLL_CTL] = {
7692 .unbound_nonreg_file = 1,
7695 #if defined(CONFIG_EPOLL)
7696 .prep = io_epoll_ctl_prep,
7697 .issue = io_epoll_ctl,
7699 .prep = io_eopnotsupp_prep,
7702 [IORING_OP_SPLICE] = {
7705 .unbound_nonreg_file = 1,
7708 .prep = io_splice_prep,
7711 [IORING_OP_PROVIDE_BUFFERS] = {
7714 .name = "PROVIDE_BUFFERS",
7715 .prep = io_provide_buffers_prep,
7716 .issue = io_provide_buffers,
7718 [IORING_OP_REMOVE_BUFFERS] = {
7721 .name = "REMOVE_BUFFERS",
7722 .prep = io_remove_buffers_prep,
7723 .issue = io_remove_buffers,
7728 .unbound_nonreg_file = 1,
7731 .prep = io_tee_prep,
7734 [IORING_OP_SHUTDOWN] = {
7737 #if defined(CONFIG_NET)
7738 .prep = io_shutdown_prep,
7739 .issue = io_shutdown,
7741 .prep = io_eopnotsupp_prep,
7744 [IORING_OP_RENAMEAT] = {
7746 .prep = io_renameat_prep,
7747 .issue = io_renameat,
7748 .cleanup = io_renameat_cleanup,
7750 [IORING_OP_UNLINKAT] = {
7752 .prep = io_unlinkat_prep,
7753 .issue = io_unlinkat,
7754 .cleanup = io_unlinkat_cleanup,
7756 [IORING_OP_MKDIRAT] = {
7758 .prep = io_mkdirat_prep,
7759 .issue = io_mkdirat,
7760 .cleanup = io_mkdirat_cleanup,
7762 [IORING_OP_SYMLINKAT] = {
7763 .name = "SYMLINKAT",
7764 .prep = io_symlinkat_prep,
7765 .issue = io_symlinkat,
7766 .cleanup = io_link_cleanup,
7768 [IORING_OP_LINKAT] = {
7770 .prep = io_linkat_prep,
7772 .cleanup = io_link_cleanup,
7774 [IORING_OP_MSG_RING] = {
7778 .prep = io_msg_ring_prep,
7779 .issue = io_msg_ring,
7781 [IORING_OP_FSETXATTR] = {
7783 .name = "FSETXATTR",
7784 .prep = io_fsetxattr_prep,
7785 .issue = io_fsetxattr,
7786 .cleanup = io_xattr_cleanup,
7788 [IORING_OP_SETXATTR] = {
7790 .prep = io_setxattr_prep,
7791 .issue = io_setxattr,
7792 .cleanup = io_xattr_cleanup,
7794 [IORING_OP_FGETXATTR] = {
7796 .name = "FGETXATTR",
7797 .prep = io_fgetxattr_prep,
7798 .issue = io_fgetxattr,
7799 .cleanup = io_xattr_cleanup,
7801 [IORING_OP_GETXATTR] = {
7803 .prep = io_getxattr_prep,
7804 .issue = io_getxattr,
7805 .cleanup = io_xattr_cleanup,
7807 [IORING_OP_SOCKET] = {
7810 #if defined(CONFIG_NET)
7811 .prep = io_socket_prep,
7814 .prep = io_eopnotsupp_prep,
7817 [IORING_OP_URING_CMD] = {
7820 .name = "URING_CMD",
7821 .async_size = uring_cmd_pdu_size(1),
7822 .prep = io_uring_cmd_prep,
7823 .issue = io_uring_cmd,
7824 .prep_async = io_uring_cmd_prep_async,
7828 static int __init io_uring_init(void)
7832 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7833 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7834 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7837 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7838 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7839 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7840 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7841 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7842 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7843 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7844 BUILD_BUG_SQE_ELEM(8, __u64, off);
7845 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7846 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7847 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
7848 BUILD_BUG_SQE_ELEM(24, __u32, len);
7849 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7850 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7851 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7852 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7853 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
7854 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
7855 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7856 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7857 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7858 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7859 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7860 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7861 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7862 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7863 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
7864 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7865 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7866 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
7867 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7868 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
7869 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
7870 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
7872 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
7873 sizeof(struct io_uring_rsrc_update));
7874 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
7875 sizeof(struct io_uring_rsrc_update2));
7877 /* ->buf_index is u16 */
7878 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
7879 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
7880 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
7881 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
7882 offsetof(struct io_uring_buf_ring, tail));
7884 /* should fit into one byte */
7885 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
7886 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
7887 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
7889 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7890 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
7892 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
7894 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
7895 BUG_ON(!io_op_defs[i].prep);
7896 if (io_op_defs[i].prep != io_eopnotsupp_prep)
7897 BUG_ON(!io_op_defs[i].issue);
7898 WARN_ON_ONCE(!io_op_defs[i].name);
7901 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
7905 __initcall(io_uring_init);