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"
104 #include "openclose.h"
105 #include "uring_cmd.h"
109 #include "msg_ring.h"
114 #define IORING_MAX_ENTRIES 32768
115 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
117 /* only define max */
118 #define IORING_MAX_FIXED_FILES (1U << 20)
119 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
120 IORING_REGISTER_LAST + IORING_OP_LAST)
122 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
123 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
124 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
126 #define IORING_MAX_REG_BUFFERS (1U << 14)
128 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
129 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
131 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
132 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
134 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
135 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
138 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
141 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
144 struct list_head list;
149 struct io_mapped_ubuf *buf;
153 struct io_rsrc_node {
154 struct percpu_ref refs;
155 struct list_head node;
156 struct list_head rsrc_list;
157 struct io_rsrc_data *rsrc_data;
158 struct llist_node llist;
162 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
164 struct io_rsrc_data {
165 struct io_ring_ctx *ctx;
171 struct completion done;
175 #define IO_COMPL_BATCH 32
176 #define IO_REQ_CACHE_SIZE 32
177 #define IO_REQ_ALLOC_BATCH 8
180 * First field must be the file pointer in all the
181 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
184 /* NOTE: kiocb has the file as the first member, so don't do it here */
191 struct io_rsrc_update {
199 struct iov_iter iter;
200 struct iov_iter_state iter_state;
201 struct iovec fast_iov[UIO_FASTIOV];
205 struct io_rw_state s;
206 const struct iovec *free_iovec;
208 struct wait_page_queue wpq;
212 IORING_RSRC_FILE = 0,
213 IORING_RSRC_BUFFER = 1,
217 IO_CHECK_CQ_OVERFLOW_BIT,
218 IO_CHECK_CQ_DROPPED_BIT,
221 struct io_defer_entry {
222 struct list_head list;
223 struct io_kiocb *req;
227 /* requests with any of those set should undergo io_disarm_next() */
228 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
229 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
231 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
232 struct task_struct *task,
235 static void io_dismantle_req(struct io_kiocb *req);
236 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
237 struct io_uring_rsrc_update2 *up,
239 static void io_clean_op(struct io_kiocb *req);
240 static void io_queue_sqe(struct io_kiocb *req);
241 static void io_rsrc_put_work(struct work_struct *work);
243 static void io_req_task_queue(struct io_kiocb *req);
244 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
245 static int io_req_prep_async(struct io_kiocb *req);
247 static void io_eventfd_signal(struct io_ring_ctx *ctx);
249 static struct kmem_cache *req_cachep;
251 const char *io_uring_get_opcode(u8 opcode)
253 if (opcode < IORING_OP_LAST)
254 return io_op_defs[opcode].name;
258 struct sock *io_uring_get_socket(struct file *file)
260 #if defined(CONFIG_UNIX)
261 if (io_is_uring_fops(file)) {
262 struct io_ring_ctx *ctx = file->private_data;
264 return ctx->ring_sock->sk;
269 EXPORT_SYMBOL(io_uring_get_socket);
271 #if defined(CONFIG_UNIX)
272 static inline bool io_file_need_scm(struct file *filp)
274 #if defined(IO_URING_SCM_ALL)
277 return !!unix_get_socket(filp);
281 static inline bool io_file_need_scm(struct file *filp)
287 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
290 mutex_lock(&ctx->uring_lock);
295 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
297 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
298 __io_submit_flush_completions(ctx);
301 #define IO_RSRC_REF_BATCH 100
303 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
305 percpu_ref_put_many(&node->refs, nr);
308 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
309 struct io_ring_ctx *ctx)
310 __must_hold(&ctx->uring_lock)
312 struct io_rsrc_node *node = req->rsrc_node;
315 if (node == ctx->rsrc_node)
316 ctx->rsrc_cached_refs++;
318 io_rsrc_put_node(node, 1);
322 static inline void io_req_put_rsrc(struct io_kiocb *req)
325 io_rsrc_put_node(req->rsrc_node, 1);
328 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
329 __must_hold(&ctx->uring_lock)
331 if (ctx->rsrc_cached_refs) {
332 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
333 ctx->rsrc_cached_refs = 0;
337 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
338 __must_hold(&ctx->uring_lock)
340 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
341 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
344 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
345 struct io_ring_ctx *ctx,
346 unsigned int issue_flags)
348 if (!req->rsrc_node) {
349 req->rsrc_node = ctx->rsrc_node;
351 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
352 lockdep_assert_held(&ctx->uring_lock);
353 ctx->rsrc_cached_refs--;
354 if (unlikely(ctx->rsrc_cached_refs < 0))
355 io_rsrc_refs_refill(ctx);
357 percpu_ref_get(&req->rsrc_node->refs);
362 static bool io_match_linked(struct io_kiocb *head)
364 struct io_kiocb *req;
366 io_for_each_link(req, head) {
367 if (req->flags & REQ_F_INFLIGHT)
374 * As io_match_task() but protected against racing with linked timeouts.
375 * User must not hold timeout_lock.
377 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
382 if (task && head->task != task)
387 if (head->flags & REQ_F_LINK_TIMEOUT) {
388 struct io_ring_ctx *ctx = head->ctx;
390 /* protect against races with linked timeouts */
391 spin_lock_irq(&ctx->timeout_lock);
392 matched = io_match_linked(head);
393 spin_unlock_irq(&ctx->timeout_lock);
395 matched = io_match_linked(head);
400 static inline void req_fail_link_node(struct io_kiocb *req, int res)
403 io_req_set_res(req, res, 0);
406 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
408 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
411 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
413 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
415 complete(&ctx->ref_comp);
418 static __cold void io_fallback_req_func(struct work_struct *work)
420 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
422 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
423 struct io_kiocb *req, *tmp;
426 percpu_ref_get(&ctx->refs);
427 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
428 req->io_task_work.func(req, &locked);
431 io_submit_flush_completions(ctx);
432 mutex_unlock(&ctx->uring_lock);
434 percpu_ref_put(&ctx->refs);
437 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
439 struct io_ring_ctx *ctx;
442 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
446 xa_init(&ctx->io_bl_xa);
449 * Use 5 bits less than the max cq entries, that should give us around
450 * 32 entries per hash list if totally full and uniformly spread.
452 hash_bits = ilog2(p->cq_entries);
456 ctx->cancel_hash_bits = hash_bits;
457 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
459 if (!ctx->cancel_hash)
461 __hash_init(ctx->cancel_hash, 1U << hash_bits);
463 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
464 if (!ctx->dummy_ubuf)
466 /* set invalid range, so io_import_fixed() fails meeting it */
467 ctx->dummy_ubuf->ubuf = -1UL;
469 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
470 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
473 ctx->flags = p->flags;
474 init_waitqueue_head(&ctx->sqo_sq_wait);
475 INIT_LIST_HEAD(&ctx->sqd_list);
476 INIT_LIST_HEAD(&ctx->cq_overflow_list);
477 INIT_LIST_HEAD(&ctx->io_buffers_cache);
478 INIT_LIST_HEAD(&ctx->apoll_cache);
479 init_completion(&ctx->ref_comp);
480 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
481 mutex_init(&ctx->uring_lock);
482 init_waitqueue_head(&ctx->cq_wait);
483 spin_lock_init(&ctx->completion_lock);
484 spin_lock_init(&ctx->timeout_lock);
485 INIT_WQ_LIST(&ctx->iopoll_list);
486 INIT_LIST_HEAD(&ctx->io_buffers_pages);
487 INIT_LIST_HEAD(&ctx->io_buffers_comp);
488 INIT_LIST_HEAD(&ctx->defer_list);
489 INIT_LIST_HEAD(&ctx->timeout_list);
490 INIT_LIST_HEAD(&ctx->ltimeout_list);
491 spin_lock_init(&ctx->rsrc_ref_lock);
492 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
493 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
494 init_llist_head(&ctx->rsrc_put_llist);
495 INIT_LIST_HEAD(&ctx->tctx_list);
496 ctx->submit_state.free_list.next = NULL;
497 INIT_WQ_LIST(&ctx->locked_free_list);
498 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
499 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
502 kfree(ctx->dummy_ubuf);
503 kfree(ctx->cancel_hash);
505 xa_destroy(&ctx->io_bl_xa);
510 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
512 struct io_rings *r = ctx->rings;
514 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
518 static bool req_need_defer(struct io_kiocb *req, u32 seq)
520 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
521 struct io_ring_ctx *ctx = req->ctx;
523 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
529 static inline bool io_req_ffs_set(struct io_kiocb *req)
531 return req->flags & REQ_F_FIXED_FILE;
534 static inline void io_req_track_inflight(struct io_kiocb *req)
536 if (!(req->flags & REQ_F_INFLIGHT)) {
537 req->flags |= REQ_F_INFLIGHT;
538 atomic_inc(&req->task->io_uring->inflight_tracked);
542 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
544 if (WARN_ON_ONCE(!req->link))
547 req->flags &= ~REQ_F_ARM_LTIMEOUT;
548 req->flags |= REQ_F_LINK_TIMEOUT;
550 /* linked timeouts should have two refs once prep'ed */
551 io_req_set_refcount(req);
552 __io_req_set_refcount(req->link, 2);
556 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
558 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
560 return __io_prep_linked_timeout(req);
563 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
565 io_queue_linked_timeout(__io_prep_linked_timeout(req));
568 static inline void io_arm_ltimeout(struct io_kiocb *req)
570 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
571 __io_arm_ltimeout(req);
574 static void io_prep_async_work(struct io_kiocb *req)
576 const struct io_op_def *def = &io_op_defs[req->opcode];
577 struct io_ring_ctx *ctx = req->ctx;
579 if (!(req->flags & REQ_F_CREDS)) {
580 req->flags |= REQ_F_CREDS;
581 req->creds = get_current_cred();
584 req->work.list.next = NULL;
586 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
587 if (req->flags & REQ_F_FORCE_ASYNC)
588 req->work.flags |= IO_WQ_WORK_CONCURRENT;
590 if (req->flags & REQ_F_ISREG) {
591 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
592 io_wq_hash_work(&req->work, file_inode(req->file));
593 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
594 if (def->unbound_nonreg_file)
595 req->work.flags |= IO_WQ_WORK_UNBOUND;
599 static void io_prep_async_link(struct io_kiocb *req)
601 struct io_kiocb *cur;
603 if (req->flags & REQ_F_LINK_TIMEOUT) {
604 struct io_ring_ctx *ctx = req->ctx;
606 spin_lock_irq(&ctx->timeout_lock);
607 io_for_each_link(cur, req)
608 io_prep_async_work(cur);
609 spin_unlock_irq(&ctx->timeout_lock);
611 io_for_each_link(cur, req)
612 io_prep_async_work(cur);
616 static inline void io_req_add_compl_list(struct io_kiocb *req)
618 struct io_submit_state *state = &req->ctx->submit_state;
620 if (!(req->flags & REQ_F_CQE_SKIP))
621 state->flush_cqes = true;
622 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
625 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
627 struct io_kiocb *link = io_prep_linked_timeout(req);
628 struct io_uring_task *tctx = req->task->io_uring;
631 BUG_ON(!tctx->io_wq);
633 /* init ->work of the whole link before punting */
634 io_prep_async_link(req);
637 * Not expected to happen, but if we do have a bug where this _can_
638 * happen, catch it here and ensure the request is marked as
639 * canceled. That will make io-wq go through the usual work cancel
640 * procedure rather than attempt to run this request (or create a new
643 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
644 req->work.flags |= IO_WQ_WORK_CANCEL;
646 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
647 req->opcode, req->flags, &req->work,
648 io_wq_is_hashed(&req->work));
649 io_wq_enqueue(tctx->io_wq, &req->work);
651 io_queue_linked_timeout(link);
654 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
656 while (!list_empty(&ctx->defer_list)) {
657 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
658 struct io_defer_entry, list);
660 if (req_need_defer(de->req, de->seq))
662 list_del_init(&de->list);
663 io_req_task_queue(de->req);
668 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
670 if (ctx->off_timeout_used || ctx->drain_active) {
671 spin_lock(&ctx->completion_lock);
672 if (ctx->off_timeout_used)
673 io_flush_timeouts(ctx);
674 if (ctx->drain_active)
675 io_queue_deferred(ctx);
676 io_commit_cqring(ctx);
677 spin_unlock(&ctx->completion_lock);
680 io_eventfd_signal(ctx);
683 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
685 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
689 * writes to the cq entry need to come after reading head; the
690 * control dependency is enough as we're using WRITE_ONCE to
693 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
695 struct io_rings *rings = ctx->rings;
696 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
697 unsigned int shift = 0;
698 unsigned int free, queued, len;
700 if (ctx->flags & IORING_SETUP_CQE32)
703 /* userspace may cheat modifying the tail, be safe and do min */
704 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
705 free = ctx->cq_entries - queued;
706 /* we need a contiguous range, limit based on the current array offset */
707 len = min(free, ctx->cq_entries - off);
711 ctx->cached_cq_tail++;
712 ctx->cqe_cached = &rings->cqes[off];
713 ctx->cqe_sentinel = ctx->cqe_cached + len;
715 return &rings->cqes[off << shift];
718 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
720 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
721 struct io_uring_cqe *cqe = ctx->cqe_cached;
723 if (ctx->flags & IORING_SETUP_CQE32) {
724 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
729 ctx->cached_cq_tail++;
734 return __io_get_cqe(ctx);
737 static void io_eventfd_signal(struct io_ring_ctx *ctx)
739 struct io_ev_fd *ev_fd;
743 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
746 ev_fd = rcu_dereference(ctx->io_ev_fd);
749 * Check again if ev_fd exists incase an io_eventfd_unregister call
750 * completed between the NULL check of ctx->io_ev_fd at the start of
751 * the function and rcu_read_lock.
753 if (unlikely(!ev_fd))
755 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
758 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
759 eventfd_signal(ev_fd->cq_ev_fd, 1);
764 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
767 * wake_up_all() may seem excessive, but io_wake_function() and
768 * io_should_wake() handle the termination of the loop and only
769 * wake as many waiters as we need to.
771 if (wq_has_sleeper(&ctx->cq_wait))
772 wake_up_all(&ctx->cq_wait);
776 * This should only get called when at least one event has been posted.
777 * Some applications rely on the eventfd notification count only changing
778 * IFF a new CQE has been added to the CQ ring. There's no depedency on
779 * 1:1 relationship between how many times this function is called (and
780 * hence the eventfd count) and number of CQEs posted to the CQ ring.
782 void io_cqring_ev_posted(struct io_ring_ctx *ctx)
784 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
786 __io_commit_cqring_flush(ctx);
791 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
793 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
795 __io_commit_cqring_flush(ctx);
797 if (ctx->flags & IORING_SETUP_SQPOLL)
801 /* Returns true if there are no backlogged entries after the flush */
802 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
804 bool all_flushed, posted;
805 size_t cqe_size = sizeof(struct io_uring_cqe);
807 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
810 if (ctx->flags & IORING_SETUP_CQE32)
814 spin_lock(&ctx->completion_lock);
815 while (!list_empty(&ctx->cq_overflow_list)) {
816 struct io_uring_cqe *cqe = io_get_cqe(ctx);
817 struct io_overflow_cqe *ocqe;
821 ocqe = list_first_entry(&ctx->cq_overflow_list,
822 struct io_overflow_cqe, list);
824 memcpy(cqe, &ocqe->cqe, cqe_size);
826 io_account_cq_overflow(ctx);
829 list_del(&ocqe->list);
833 all_flushed = list_empty(&ctx->cq_overflow_list);
835 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
836 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
839 io_commit_cqring(ctx);
840 spin_unlock(&ctx->completion_lock);
842 io_cqring_ev_posted(ctx);
846 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
850 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
851 /* iopoll syncs against uring_lock, not completion_lock */
852 if (ctx->flags & IORING_SETUP_IOPOLL)
853 mutex_lock(&ctx->uring_lock);
854 ret = __io_cqring_overflow_flush(ctx, false);
855 if (ctx->flags & IORING_SETUP_IOPOLL)
856 mutex_unlock(&ctx->uring_lock);
862 static void __io_put_task(struct task_struct *task, int nr)
864 struct io_uring_task *tctx = task->io_uring;
866 percpu_counter_sub(&tctx->inflight, nr);
867 if (unlikely(atomic_read(&tctx->in_idle)))
868 wake_up(&tctx->wait);
869 put_task_struct_many(task, nr);
872 /* must to be called somewhat shortly after putting a request */
873 static inline void io_put_task(struct task_struct *task, int nr)
875 if (likely(task == current))
876 task->io_uring->cached_refs += nr;
878 __io_put_task(task, nr);
881 static void io_task_refs_refill(struct io_uring_task *tctx)
883 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
885 percpu_counter_add(&tctx->inflight, refill);
886 refcount_add(refill, ¤t->usage);
887 tctx->cached_refs += refill;
890 static inline void io_get_task_refs(int nr)
892 struct io_uring_task *tctx = current->io_uring;
894 tctx->cached_refs -= nr;
895 if (unlikely(tctx->cached_refs < 0))
896 io_task_refs_refill(tctx);
899 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
901 struct io_uring_task *tctx = task->io_uring;
902 unsigned int refs = tctx->cached_refs;
905 tctx->cached_refs = 0;
906 percpu_counter_sub(&tctx->inflight, refs);
907 put_task_struct_many(task, refs);
911 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
912 s32 res, u32 cflags, u64 extra1,
915 struct io_overflow_cqe *ocqe;
916 size_t ocq_size = sizeof(struct io_overflow_cqe);
917 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
920 ocq_size += sizeof(struct io_uring_cqe);
922 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
923 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
926 * If we're in ring overflow flush mode, or in task cancel mode,
927 * or cannot allocate an overflow entry, then we need to drop it
930 io_account_cq_overflow(ctx);
931 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
934 if (list_empty(&ctx->cq_overflow_list)) {
935 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
936 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
939 ocqe->cqe.user_data = user_data;
941 ocqe->cqe.flags = cflags;
943 ocqe->cqe.big_cqe[0] = extra1;
944 ocqe->cqe.big_cqe[1] = extra2;
946 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
950 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
951 struct io_kiocb *req)
953 struct io_uring_cqe *cqe;
955 if (!(ctx->flags & IORING_SETUP_CQE32)) {
956 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
957 req->cqe.res, req->cqe.flags, 0, 0);
960 * If we can't get a cq entry, userspace overflowed the
961 * submission (by quite a lot). Increment the overflow count in
964 cqe = io_get_cqe(ctx);
966 memcpy(cqe, &req->cqe, sizeof(*cqe));
970 return io_cqring_event_overflow(ctx, req->cqe.user_data,
971 req->cqe.res, req->cqe.flags,
974 u64 extra1 = 0, extra2 = 0;
976 if (req->flags & REQ_F_CQE32_INIT) {
977 extra1 = req->extra1;
978 extra2 = req->extra2;
981 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
982 req->cqe.res, req->cqe.flags, extra1, extra2);
985 * If we can't get a cq entry, userspace overflowed the
986 * submission (by quite a lot). Increment the overflow count in
989 cqe = io_get_cqe(ctx);
991 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
992 WRITE_ONCE(cqe->big_cqe[0], extra1);
993 WRITE_ONCE(cqe->big_cqe[1], extra2);
997 return io_cqring_event_overflow(ctx, req->cqe.user_data,
998 req->cqe.res, req->cqe.flags,
1003 bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
1006 struct io_uring_cqe *cqe;
1009 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
1012 * If we can't get a cq entry, userspace overflowed the
1013 * submission (by quite a lot). Increment the overflow count in
1016 cqe = io_get_cqe(ctx);
1018 WRITE_ONCE(cqe->user_data, user_data);
1019 WRITE_ONCE(cqe->res, res);
1020 WRITE_ONCE(cqe->flags, cflags);
1022 if (ctx->flags & IORING_SETUP_CQE32) {
1023 WRITE_ONCE(cqe->big_cqe[0], 0);
1024 WRITE_ONCE(cqe->big_cqe[1], 0);
1028 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
1031 static void __io_req_complete_put(struct io_kiocb *req)
1034 * If we're the last reference to this request, add to our locked
1037 if (req_ref_put_and_test(req)) {
1038 struct io_ring_ctx *ctx = req->ctx;
1040 if (req->flags & IO_REQ_LINK_FLAGS) {
1041 if (req->flags & IO_DISARM_MASK)
1042 io_disarm_next(req);
1044 io_req_task_queue(req->link);
1048 io_req_put_rsrc(req);
1050 * Selected buffer deallocation in io_clean_op() assumes that
1051 * we don't hold ->completion_lock. Clean them here to avoid
1054 io_put_kbuf_comp(req);
1055 io_dismantle_req(req);
1056 io_put_task(req->task, 1);
1057 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1058 ctx->locked_free_nr++;
1062 void __io_req_complete_post(struct io_kiocb *req)
1064 if (!(req->flags & REQ_F_CQE_SKIP))
1065 __io_fill_cqe_req(req->ctx, req);
1066 __io_req_complete_put(req);
1069 void io_req_complete_post(struct io_kiocb *req)
1071 struct io_ring_ctx *ctx = req->ctx;
1073 spin_lock(&ctx->completion_lock);
1074 __io_req_complete_post(req);
1075 io_commit_cqring(ctx);
1076 spin_unlock(&ctx->completion_lock);
1077 io_cqring_ev_posted(ctx);
1080 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
1082 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1083 req->flags |= REQ_F_COMPLETE_INLINE;
1085 io_req_complete_post(req);
1088 void io_req_complete_failed(struct io_kiocb *req, s32 res)
1091 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1092 io_req_complete_post(req);
1096 * Don't initialise the fields below on every allocation, but do that in
1097 * advance and keep them valid across allocations.
1099 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1103 req->async_data = NULL;
1104 /* not necessary, but safer to zero */
1108 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1109 struct io_submit_state *state)
1111 spin_lock(&ctx->completion_lock);
1112 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1113 ctx->locked_free_nr = 0;
1114 spin_unlock(&ctx->completion_lock);
1117 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
1119 return !ctx->submit_state.free_list.next;
1123 * A request might get retired back into the request caches even before opcode
1124 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1125 * Because of that, io_alloc_req() should be called only under ->uring_lock
1126 * and with extra caution to not get a request that is still worked on.
1128 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1129 __must_hold(&ctx->uring_lock)
1131 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1132 void *reqs[IO_REQ_ALLOC_BATCH];
1136 * If we have more than a batch's worth of requests in our IRQ side
1137 * locked cache, grab the lock and move them over to our submission
1140 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1141 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1142 if (!io_req_cache_empty(ctx))
1146 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1149 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1150 * retry single alloc to be on the safe side.
1152 if (unlikely(ret <= 0)) {
1153 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1159 percpu_ref_get_many(&ctx->refs, ret);
1160 for (i = 0; i < ret; i++) {
1161 struct io_kiocb *req = reqs[i];
1163 io_preinit_req(req, ctx);
1164 io_req_add_to_cache(req, ctx);
1169 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
1171 if (unlikely(io_req_cache_empty(ctx)))
1172 return __io_alloc_req_refill(ctx);
1176 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1178 struct io_wq_work_node *node;
1180 node = wq_stack_extract(&ctx->submit_state.free_list);
1181 return container_of(node, struct io_kiocb, comp_list);
1184 static inline void io_dismantle_req(struct io_kiocb *req)
1186 unsigned int flags = req->flags;
1188 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
1190 if (!(flags & REQ_F_FIXED_FILE))
1191 io_put_file(req->file);
1194 __cold void io_free_req(struct io_kiocb *req)
1196 struct io_ring_ctx *ctx = req->ctx;
1198 io_req_put_rsrc(req);
1199 io_dismantle_req(req);
1200 io_put_task(req->task, 1);
1202 spin_lock(&ctx->completion_lock);
1203 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1204 ctx->locked_free_nr++;
1205 spin_unlock(&ctx->completion_lock);
1208 static void __io_req_find_next_prep(struct io_kiocb *req)
1210 struct io_ring_ctx *ctx = req->ctx;
1213 spin_lock(&ctx->completion_lock);
1214 posted = io_disarm_next(req);
1215 io_commit_cqring(ctx);
1216 spin_unlock(&ctx->completion_lock);
1218 io_cqring_ev_posted(ctx);
1221 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1223 struct io_kiocb *nxt;
1226 * If LINK is set, we have dependent requests in this chain. If we
1227 * didn't fail this request, queue the first one up, moving any other
1228 * dependencies to the next request. In case of failure, fail the rest
1231 if (unlikely(req->flags & IO_DISARM_MASK))
1232 __io_req_find_next_prep(req);
1238 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
1242 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1243 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1245 io_submit_flush_completions(ctx);
1246 mutex_unlock(&ctx->uring_lock);
1249 percpu_ref_put(&ctx->refs);
1252 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
1254 io_commit_cqring(ctx);
1255 spin_unlock(&ctx->completion_lock);
1256 io_cqring_ev_posted(ctx);
1259 static void handle_prev_tw_list(struct io_wq_work_node *node,
1260 struct io_ring_ctx **ctx, bool *uring_locked)
1262 if (*ctx && !*uring_locked)
1263 spin_lock(&(*ctx)->completion_lock);
1266 struct io_wq_work_node *next = node->next;
1267 struct io_kiocb *req = container_of(node, struct io_kiocb,
1270 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1272 if (req->ctx != *ctx) {
1273 if (unlikely(!*uring_locked && *ctx))
1274 ctx_commit_and_unlock(*ctx);
1276 ctx_flush_and_put(*ctx, uring_locked);
1278 /* if not contended, grab and improve batching */
1279 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
1280 percpu_ref_get(&(*ctx)->refs);
1281 if (unlikely(!*uring_locked))
1282 spin_lock(&(*ctx)->completion_lock);
1284 if (likely(*uring_locked)) {
1285 req->io_task_work.func(req, uring_locked);
1287 req->cqe.flags = io_put_kbuf_comp(req);
1288 __io_req_complete_post(req);
1293 if (unlikely(!*uring_locked))
1294 ctx_commit_and_unlock(*ctx);
1297 static void handle_tw_list(struct io_wq_work_node *node,
1298 struct io_ring_ctx **ctx, bool *locked)
1301 struct io_wq_work_node *next = node->next;
1302 struct io_kiocb *req = container_of(node, struct io_kiocb,
1305 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1307 if (req->ctx != *ctx) {
1308 ctx_flush_and_put(*ctx, locked);
1310 /* if not contended, grab and improve batching */
1311 *locked = mutex_trylock(&(*ctx)->uring_lock);
1312 percpu_ref_get(&(*ctx)->refs);
1314 req->io_task_work.func(req, locked);
1319 void tctx_task_work(struct callback_head *cb)
1321 bool uring_locked = false;
1322 struct io_ring_ctx *ctx = NULL;
1323 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1327 struct io_wq_work_node *node1, *node2;
1329 spin_lock_irq(&tctx->task_lock);
1330 node1 = tctx->prio_task_list.first;
1331 node2 = tctx->task_list.first;
1332 INIT_WQ_LIST(&tctx->task_list);
1333 INIT_WQ_LIST(&tctx->prio_task_list);
1334 if (!node2 && !node1)
1335 tctx->task_running = false;
1336 spin_unlock_irq(&tctx->task_lock);
1337 if (!node2 && !node1)
1341 handle_prev_tw_list(node1, &ctx, &uring_locked);
1343 handle_tw_list(node2, &ctx, &uring_locked);
1346 if (data_race(!tctx->task_list.first) &&
1347 data_race(!tctx->prio_task_list.first) && uring_locked)
1348 io_submit_flush_completions(ctx);
1351 ctx_flush_and_put(ctx, &uring_locked);
1353 /* relaxed read is enough as only the task itself sets ->in_idle */
1354 if (unlikely(atomic_read(&tctx->in_idle)))
1355 io_uring_drop_tctx_refs(current);
1358 static void __io_req_task_work_add(struct io_kiocb *req,
1359 struct io_uring_task *tctx,
1360 struct io_wq_work_list *list)
1362 struct io_ring_ctx *ctx = req->ctx;
1363 struct io_wq_work_node *node;
1364 unsigned long flags;
1367 spin_lock_irqsave(&tctx->task_lock, flags);
1368 wq_list_add_tail(&req->io_task_work.node, list);
1369 running = tctx->task_running;
1371 tctx->task_running = true;
1372 spin_unlock_irqrestore(&tctx->task_lock, flags);
1374 /* task_work already pending, we're done */
1378 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1379 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1381 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1384 spin_lock_irqsave(&tctx->task_lock, flags);
1385 tctx->task_running = false;
1386 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
1387 spin_unlock_irqrestore(&tctx->task_lock, flags);
1390 req = container_of(node, struct io_kiocb, io_task_work.node);
1392 if (llist_add(&req->io_task_work.fallback_node,
1393 &req->ctx->fallback_llist))
1394 schedule_delayed_work(&req->ctx->fallback_work, 1);
1398 void io_req_task_work_add(struct io_kiocb *req)
1400 struct io_uring_task *tctx = req->task->io_uring;
1402 __io_req_task_work_add(req, tctx, &tctx->task_list);
1405 static void io_req_task_prio_work_add(struct io_kiocb *req)
1407 struct io_uring_task *tctx = req->task->io_uring;
1409 if (req->ctx->flags & IORING_SETUP_SQPOLL)
1410 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
1412 __io_req_task_work_add(req, tctx, &tctx->task_list);
1415 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
1417 io_req_complete_post(req);
1420 void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
1422 io_req_set_res(req, res, cflags);
1423 req->io_task_work.func = io_req_tw_post;
1424 io_req_task_work_add(req);
1427 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
1429 /* not needed for normal modes, but SQPOLL depends on it */
1430 io_tw_lock(req->ctx, locked);
1431 io_req_complete_failed(req, req->cqe.res);
1434 void io_req_task_submit(struct io_kiocb *req, bool *locked)
1436 io_tw_lock(req->ctx, locked);
1437 /* req->task == current here, checking PF_EXITING is safe */
1438 if (likely(!(req->task->flags & PF_EXITING)))
1441 io_req_complete_failed(req, -EFAULT);
1444 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1446 io_req_set_res(req, ret, 0);
1447 req->io_task_work.func = io_req_task_cancel;
1448 io_req_task_work_add(req);
1451 static void io_req_task_queue(struct io_kiocb *req)
1453 req->io_task_work.func = io_req_task_submit;
1454 io_req_task_work_add(req);
1457 static void io_req_task_queue_reissue(struct io_kiocb *req)
1459 req->io_task_work.func = io_queue_iowq;
1460 io_req_task_work_add(req);
1463 void io_queue_next(struct io_kiocb *req)
1465 struct io_kiocb *nxt = io_req_find_next(req);
1468 io_req_task_queue(nxt);
1471 static void io_free_batch_list(struct io_ring_ctx *ctx,
1472 struct io_wq_work_node *node)
1473 __must_hold(&ctx->uring_lock)
1475 struct task_struct *task = NULL;
1479 struct io_kiocb *req = container_of(node, struct io_kiocb,
1482 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1483 if (req->flags & REQ_F_REFCOUNT) {
1484 node = req->comp_list.next;
1485 if (!req_ref_put_and_test(req))
1488 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1489 struct async_poll *apoll = req->apoll;
1491 if (apoll->double_poll)
1492 kfree(apoll->double_poll);
1493 list_add(&apoll->poll.wait.entry,
1495 req->flags &= ~REQ_F_POLLED;
1497 if (req->flags & IO_REQ_LINK_FLAGS)
1499 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1502 if (!(req->flags & REQ_F_FIXED_FILE))
1503 io_put_file(req->file);
1505 io_req_put_rsrc_locked(req, ctx);
1507 if (req->task != task) {
1509 io_put_task(task, task_refs);
1514 node = req->comp_list.next;
1515 io_req_add_to_cache(req, ctx);
1519 io_put_task(task, task_refs);
1522 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1523 __must_hold(&ctx->uring_lock)
1525 struct io_wq_work_node *node, *prev;
1526 struct io_submit_state *state = &ctx->submit_state;
1528 if (state->flush_cqes) {
1529 spin_lock(&ctx->completion_lock);
1530 wq_list_for_each(node, prev, &state->compl_reqs) {
1531 struct io_kiocb *req = container_of(node, struct io_kiocb,
1534 if (!(req->flags & REQ_F_CQE_SKIP))
1535 __io_fill_cqe_req(ctx, req);
1538 io_commit_cqring(ctx);
1539 spin_unlock(&ctx->completion_lock);
1540 io_cqring_ev_posted(ctx);
1541 state->flush_cqes = false;
1544 io_free_batch_list(ctx, state->compl_reqs.first);
1545 INIT_WQ_LIST(&state->compl_reqs);
1549 * Drop reference to request, return next in chain (if there is one) if this
1550 * was the last reference to this request.
1552 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
1554 struct io_kiocb *nxt = NULL;
1556 if (req_ref_put_and_test(req)) {
1557 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
1558 nxt = io_req_find_next(req);
1564 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1566 /* See comment at the top of this file */
1568 return __io_cqring_events(ctx);
1571 int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
1573 struct io_wq_work_node *pos, *start, *prev;
1574 unsigned int poll_flags = BLK_POLL_NOSLEEP;
1575 DEFINE_IO_COMP_BATCH(iob);
1579 * Only spin for completions if we don't have multiple devices hanging
1580 * off our complete list.
1582 if (ctx->poll_multi_queue || force_nonspin)
1583 poll_flags |= BLK_POLL_ONESHOT;
1585 wq_list_for_each(pos, start, &ctx->iopoll_list) {
1586 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1587 struct io_rw *rw = io_kiocb_to_cmd(req);
1591 * Move completed and retryable entries to our local lists.
1592 * If we find a request that requires polling, break out
1593 * and complete those lists first, if we have entries there.
1595 if (READ_ONCE(req->iopoll_completed))
1598 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
1599 if (unlikely(ret < 0))
1602 poll_flags |= BLK_POLL_ONESHOT;
1604 /* iopoll may have completed current req */
1605 if (!rq_list_empty(iob.req_list) ||
1606 READ_ONCE(req->iopoll_completed))
1610 if (!rq_list_empty(iob.req_list))
1616 wq_list_for_each_resume(pos, prev) {
1617 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1619 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
1620 if (!smp_load_acquire(&req->iopoll_completed))
1623 if (unlikely(req->flags & REQ_F_CQE_SKIP))
1626 req->cqe.flags = io_put_kbuf(req, 0);
1627 __io_fill_cqe_req(req->ctx, req);
1630 if (unlikely(!nr_events))
1633 io_commit_cqring(ctx);
1634 io_cqring_ev_posted_iopoll(ctx);
1635 pos = start ? start->next : ctx->iopoll_list.first;
1636 wq_list_cut(&ctx->iopoll_list, prev, start);
1637 io_free_batch_list(ctx, pos);
1642 * We can't just wait for polled events to come to us, we have to actively
1643 * find and complete them.
1645 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1647 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1650 mutex_lock(&ctx->uring_lock);
1651 while (!wq_list_empty(&ctx->iopoll_list)) {
1652 /* let it sleep and repeat later if can't complete a request */
1653 if (io_do_iopoll(ctx, true) == 0)
1656 * Ensure we allow local-to-the-cpu processing to take place,
1657 * in this case we need to ensure that we reap all events.
1658 * Also let task_work, etc. to progress by releasing the mutex
1660 if (need_resched()) {
1661 mutex_unlock(&ctx->uring_lock);
1663 mutex_lock(&ctx->uring_lock);
1666 mutex_unlock(&ctx->uring_lock);
1669 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1671 unsigned int nr_events = 0;
1673 unsigned long check_cq;
1676 * Don't enter poll loop if we already have events pending.
1677 * If we do, we can potentially be spinning for commands that
1678 * already triggered a CQE (eg in error).
1680 check_cq = READ_ONCE(ctx->check_cq);
1681 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1682 __io_cqring_overflow_flush(ctx, false);
1683 if (io_cqring_events(ctx))
1687 * Similarly do not spin if we have not informed the user of any
1690 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
1695 * If a submit got punted to a workqueue, we can have the
1696 * application entering polling for a command before it gets
1697 * issued. That app will hold the uring_lock for the duration
1698 * of the poll right here, so we need to take a breather every
1699 * now and then to ensure that the issue has a chance to add
1700 * the poll to the issued list. Otherwise we can spin here
1701 * forever, while the workqueue is stuck trying to acquire the
1704 if (wq_list_empty(&ctx->iopoll_list)) {
1705 u32 tail = ctx->cached_cq_tail;
1707 mutex_unlock(&ctx->uring_lock);
1709 mutex_lock(&ctx->uring_lock);
1711 /* some requests don't go through iopoll_list */
1712 if (tail != ctx->cached_cq_tail ||
1713 wq_list_empty(&ctx->iopoll_list))
1716 ret = io_do_iopoll(ctx, !min);
1721 } while (nr_events < min && !need_resched());
1726 static void kiocb_end_write(struct io_kiocb *req)
1729 * Tell lockdep we inherited freeze protection from submission
1732 if (req->flags & REQ_F_ISREG) {
1733 struct super_block *sb = file_inode(req->file)->i_sb;
1735 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
1741 static bool io_resubmit_prep(struct io_kiocb *req)
1743 struct io_async_rw *io = req->async_data;
1745 if (!req_has_async_data(req))
1746 return !io_req_prep_async(req);
1747 iov_iter_restore(&io->s.iter, &io->s.iter_state);
1751 static bool io_rw_should_reissue(struct io_kiocb *req)
1753 umode_t mode = file_inode(req->file)->i_mode;
1754 struct io_ring_ctx *ctx = req->ctx;
1756 if (!S_ISBLK(mode) && !S_ISREG(mode))
1758 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
1759 !(ctx->flags & IORING_SETUP_IOPOLL)))
1762 * If ref is dying, we might be running poll reap from the exit work.
1763 * Don't attempt to reissue from that path, just let it fail with
1766 if (percpu_ref_is_dying(&ctx->refs))
1769 * Play it safe and assume not safe to re-import and reissue if we're
1770 * not in the original thread group (or in task context).
1772 if (!same_thread_group(req->task, current) || !in_task())
1777 static bool io_resubmit_prep(struct io_kiocb *req)
1781 static bool io_rw_should_reissue(struct io_kiocb *req)
1787 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
1789 struct io_rw *rw = io_kiocb_to_cmd(req);
1791 if (rw->kiocb.ki_flags & IOCB_WRITE) {
1792 kiocb_end_write(req);
1793 fsnotify_modify(req->file);
1795 fsnotify_access(req->file);
1797 if (unlikely(res != req->cqe.res)) {
1798 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
1799 io_rw_should_reissue(req)) {
1800 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
1809 inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
1812 req->cqe.flags |= io_put_kbuf(req, 0);
1813 req->flags |= REQ_F_COMPLETE_INLINE;
1814 io_req_add_compl_list(req);
1816 req->cqe.flags |= io_put_kbuf(req, IO_URING_F_UNLOCKED);
1817 io_req_complete_post(req);
1821 static void __io_complete_rw(struct io_kiocb *req, long res,
1822 unsigned int issue_flags)
1824 if (__io_complete_rw_common(req, res))
1826 io_req_set_res(req, req->cqe.res, io_put_kbuf(req, issue_flags));
1827 __io_req_complete(req, issue_flags);
1830 static void io_complete_rw(struct kiocb *kiocb, long res)
1832 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1833 struct io_kiocb *req = cmd_to_io_kiocb(rw);
1835 if (__io_complete_rw_common(req, res))
1837 io_req_set_res(req, res, 0);
1838 req->io_task_work.func = io_req_task_complete;
1839 io_req_task_prio_work_add(req);
1842 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
1844 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1845 struct io_kiocb *req = cmd_to_io_kiocb(rw);
1847 if (kiocb->ki_flags & IOCB_WRITE)
1848 kiocb_end_write(req);
1849 if (unlikely(res != req->cqe.res)) {
1850 if (res == -EAGAIN && io_rw_should_reissue(req)) {
1851 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
1857 /* order with io_iopoll_complete() checking ->iopoll_completed */
1858 smp_store_release(&req->iopoll_completed, 1);
1862 * After the iocb has been issued, it's safe to be found on the poll list.
1863 * Adding the kiocb to the list AFTER submission ensures that we don't
1864 * find it from a io_do_iopoll() thread before the issuer is done
1865 * accessing the kiocb cookie.
1867 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1869 struct io_ring_ctx *ctx = req->ctx;
1870 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1872 /* workqueue context doesn't hold uring_lock, grab it now */
1873 if (unlikely(needs_lock))
1874 mutex_lock(&ctx->uring_lock);
1877 * Track whether we have multiple files in our lists. This will impact
1878 * how we do polling eventually, not spinning if we're on potentially
1879 * different devices.
1881 if (wq_list_empty(&ctx->iopoll_list)) {
1882 ctx->poll_multi_queue = false;
1883 } else if (!ctx->poll_multi_queue) {
1884 struct io_kiocb *list_req;
1886 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1888 if (list_req->file != req->file)
1889 ctx->poll_multi_queue = true;
1893 * For fast devices, IO may have already completed. If it has, add
1894 * it to the front so we find it first.
1896 if (READ_ONCE(req->iopoll_completed))
1897 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1899 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1901 if (unlikely(needs_lock)) {
1903 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1904 * in sq thread task context or in io worker task context. If
1905 * current task context is sq thread, we don't need to check
1906 * whether should wake up sq thread.
1908 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1909 wq_has_sleeper(&ctx->sq_data->wait))
1910 wake_up(&ctx->sq_data->wait);
1912 mutex_unlock(&ctx->uring_lock);
1916 static bool io_bdev_nowait(struct block_device *bdev)
1918 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
1922 * If we tracked the file through the SCM inflight mechanism, we could support
1923 * any file. For now, just ensure that anything potentially problematic is done
1926 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
1928 if (S_ISBLK(mode)) {
1929 if (IS_ENABLED(CONFIG_BLOCK) &&
1930 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
1936 if (S_ISREG(mode)) {
1937 if (IS_ENABLED(CONFIG_BLOCK) &&
1938 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
1939 !io_is_uring_fops(file))
1944 /* any ->read/write should understand O_NONBLOCK */
1945 if (file->f_flags & O_NONBLOCK)
1947 return file->f_mode & FMODE_NOWAIT;
1951 * If we tracked the file through the SCM inflight mechanism, we could support
1952 * any file. For now, just ensure that anything potentially problematic is done
1955 unsigned int io_file_get_flags(struct file *file)
1957 umode_t mode = file_inode(file)->i_mode;
1958 unsigned int res = 0;
1962 if (__io_file_supports_nowait(file, mode))
1964 if (io_file_need_scm(file))
1969 static inline bool io_file_supports_nowait(struct io_kiocb *req)
1971 return req->flags & REQ_F_SUPPORT_NOWAIT;
1974 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1976 struct io_rw *rw = io_kiocb_to_cmd(req);
1980 rw->kiocb.ki_pos = READ_ONCE(sqe->off);
1981 /* used for fixed read/write too - just read unconditionally */
1982 req->buf_index = READ_ONCE(sqe->buf_index);
1984 if (req->opcode == IORING_OP_READ_FIXED ||
1985 req->opcode == IORING_OP_WRITE_FIXED) {
1986 struct io_ring_ctx *ctx = req->ctx;
1989 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
1991 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
1992 req->imu = ctx->user_bufs[index];
1993 io_req_set_rsrc_node(req, ctx, 0);
1996 ioprio = READ_ONCE(sqe->ioprio);
1998 ret = ioprio_check_cap(ioprio);
2002 rw->kiocb.ki_ioprio = ioprio;
2004 rw->kiocb.ki_ioprio = get_current_ioprio();
2007 rw->addr = READ_ONCE(sqe->addr);
2008 rw->len = READ_ONCE(sqe->len);
2009 rw->flags = READ_ONCE(sqe->rw_flags);
2013 static void io_readv_writev_cleanup(struct io_kiocb *req)
2015 struct io_async_rw *io = req->async_data;
2017 kfree(io->free_iovec);
2020 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2026 case -ERESTARTNOINTR:
2027 case -ERESTARTNOHAND:
2028 case -ERESTART_RESTARTBLOCK:
2030 * We can't just restart the syscall, since previously
2031 * submitted sqes may already be in progress. Just fail this
2037 kiocb->ki_complete(kiocb, ret);
2041 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
2043 struct io_rw *rw = io_kiocb_to_cmd(req);
2045 if (rw->kiocb.ki_pos != -1)
2046 return &rw->kiocb.ki_pos;
2048 if (!(req->file->f_mode & FMODE_STREAM)) {
2049 req->flags |= REQ_F_CUR_POS;
2050 rw->kiocb.ki_pos = req->file->f_pos;
2051 return &rw->kiocb.ki_pos;
2054 rw->kiocb.ki_pos = 0;
2058 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
2059 unsigned int issue_flags)
2061 struct io_async_rw *io = req->async_data;
2062 struct io_rw *rw = io_kiocb_to_cmd(req);
2064 /* add previously done IO, if any */
2065 if (req_has_async_data(req) && io->bytes_done > 0) {
2067 ret = io->bytes_done;
2069 ret += io->bytes_done;
2072 if (req->flags & REQ_F_CUR_POS)
2073 req->file->f_pos = rw->kiocb.ki_pos;
2074 if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
2075 __io_complete_rw(req, ret, issue_flags);
2077 io_rw_done(&rw->kiocb, ret);
2079 if (req->flags & REQ_F_REISSUE) {
2080 req->flags &= ~REQ_F_REISSUE;
2081 if (io_resubmit_prep(req))
2082 io_req_task_queue_reissue(req);
2084 io_req_task_queue_fail(req, ret);
2088 static int __io_import_fixed(struct io_kiocb *req, int ddir,
2089 struct iov_iter *iter, struct io_mapped_ubuf *imu)
2091 struct io_rw *rw = io_kiocb_to_cmd(req);
2092 size_t len = rw->len;
2093 u64 buf_end, buf_addr = rw->addr;
2096 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2098 /* not inside the mapped region */
2099 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2103 * May not be a start of buffer, set size appropriately
2104 * and advance us to the beginning.
2106 offset = buf_addr - imu->ubuf;
2107 iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
2111 * Don't use iov_iter_advance() here, as it's really slow for
2112 * using the latter parts of a big fixed buffer - it iterates
2113 * over each segment manually. We can cheat a bit here, because
2116 * 1) it's a BVEC iter, we set it up
2117 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2118 * first and last bvec
2120 * So just find our index, and adjust the iterator afterwards.
2121 * If the offset is within the first bvec (or the whole first
2122 * bvec, just use iov_iter_advance(). This makes it easier
2123 * since we can just skip the first segment, which may not
2124 * be PAGE_SIZE aligned.
2126 const struct bio_vec *bvec = imu->bvec;
2128 if (offset <= bvec->bv_len) {
2129 iov_iter_advance(iter, offset);
2131 unsigned long seg_skip;
2133 /* skip first vec */
2134 offset -= bvec->bv_len;
2135 seg_skip = 1 + (offset >> PAGE_SHIFT);
2137 iter->bvec = bvec + seg_skip;
2138 iter->nr_segs -= seg_skip;
2139 iter->count -= bvec->bv_len + offset;
2140 iter->iov_offset = offset & ~PAGE_MASK;
2147 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2148 unsigned int issue_flags)
2150 if (WARN_ON_ONCE(!req->imu))
2152 return __io_import_fixed(req, rw, iter, req->imu);
2155 #ifdef CONFIG_COMPAT
2156 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2157 unsigned int issue_flags)
2159 struct io_rw *rw = io_kiocb_to_cmd(req);
2160 struct compat_iovec __user *uiov;
2161 compat_ssize_t clen;
2165 uiov = u64_to_user_ptr(rw->addr);
2166 if (!access_ok(uiov, sizeof(*uiov)))
2168 if (__get_user(clen, &uiov->iov_len))
2174 buf = io_buffer_select(req, &len, issue_flags);
2177 rw->addr = (unsigned long) buf;
2178 iov[0].iov_base = buf;
2179 rw->len = iov[0].iov_len = (compat_size_t) len;
2184 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2185 unsigned int issue_flags)
2187 struct io_rw *rw = io_kiocb_to_cmd(req);
2188 struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
2192 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2195 len = iov[0].iov_len;
2198 buf = io_buffer_select(req, &len, issue_flags);
2201 rw->addr = (unsigned long) buf;
2202 iov[0].iov_base = buf;
2203 rw->len = iov[0].iov_len = len;
2207 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2208 unsigned int issue_flags)
2210 struct io_rw *rw = io_kiocb_to_cmd(req);
2212 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
2213 iov[0].iov_base = u64_to_user_ptr(rw->addr);
2214 iov[0].iov_len = rw->len;
2220 #ifdef CONFIG_COMPAT
2221 if (req->ctx->compat)
2222 return io_compat_import(req, iov, issue_flags);
2225 return __io_iov_buffer_select(req, iov, issue_flags);
2228 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
2229 struct io_rw_state *s,
2230 unsigned int issue_flags)
2232 struct io_rw *rw = io_kiocb_to_cmd(req);
2233 struct iov_iter *iter = &s->iter;
2234 u8 opcode = req->opcode;
2235 struct iovec *iovec;
2240 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2241 ret = io_import_fixed(req, ddir, iter, issue_flags);
2243 return ERR_PTR(ret);
2247 buf = u64_to_user_ptr(rw->addr);
2250 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2251 if (io_do_buffer_select(req)) {
2252 buf = io_buffer_select(req, &sqe_len, issue_flags);
2254 return ERR_PTR(-ENOBUFS);
2255 rw->addr = (unsigned long) buf;
2259 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
2261 return ERR_PTR(ret);
2265 iovec = s->fast_iov;
2266 if (req->flags & REQ_F_BUFFER_SELECT) {
2267 ret = io_iov_buffer_select(req, iovec, issue_flags);
2269 return ERR_PTR(ret);
2270 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
2274 ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
2276 if (unlikely(ret < 0))
2277 return ERR_PTR(ret);
2281 static inline int io_import_iovec(int rw, struct io_kiocb *req,
2282 struct iovec **iovec, struct io_rw_state *s,
2283 unsigned int issue_flags)
2285 *iovec = __io_import_iovec(rw, req, s, issue_flags);
2286 if (unlikely(IS_ERR(*iovec)))
2287 return PTR_ERR(*iovec);
2289 iov_iter_save_state(&s->iter, &s->iter_state);
2293 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2295 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2299 * For files that don't have ->read_iter() and ->write_iter(), handle them
2300 * by looping over ->read() or ->write() manually.
2302 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
2304 struct kiocb *kiocb = &rw->kiocb;
2305 struct file *file = kiocb->ki_filp;
2310 * Don't support polled IO through this interface, and we can't
2311 * support non-blocking either. For the latter, this just causes
2312 * the kiocb to be handled from an async context.
2314 if (kiocb->ki_flags & IOCB_HIPRI)
2316 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
2317 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
2320 ppos = io_kiocb_ppos(kiocb);
2322 while (iov_iter_count(iter)) {
2326 if (!iov_iter_is_bvec(iter)) {
2327 iovec = iov_iter_iovec(iter);
2329 iovec.iov_base = u64_to_user_ptr(rw->addr);
2330 iovec.iov_len = rw->len;
2334 nr = file->f_op->read(file, iovec.iov_base,
2335 iovec.iov_len, ppos);
2337 nr = file->f_op->write(file, iovec.iov_base,
2338 iovec.iov_len, ppos);
2347 if (!iov_iter_is_bvec(iter)) {
2348 iov_iter_advance(iter, nr);
2355 if (nr != iovec.iov_len)
2362 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
2363 const struct iovec *fast_iov, struct iov_iter *iter)
2365 struct io_async_rw *io = req->async_data;
2367 memcpy(&io->s.iter, iter, sizeof(*iter));
2368 io->free_iovec = iovec;
2370 /* can only be fixed buffers, no need to do anything */
2371 if (iov_iter_is_bvec(iter))
2374 unsigned iov_off = 0;
2376 io->s.iter.iov = io->s.fast_iov;
2377 if (iter->iov != fast_iov) {
2378 iov_off = iter->iov - fast_iov;
2379 io->s.iter.iov += iov_off;
2381 if (io->s.fast_iov != fast_iov)
2382 memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
2383 sizeof(struct iovec) * iter->nr_segs);
2385 req->flags |= REQ_F_NEED_CLEANUP;
2389 bool io_alloc_async_data(struct io_kiocb *req)
2391 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
2392 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
2393 if (req->async_data) {
2394 req->flags |= REQ_F_ASYNC_DATA;
2400 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
2401 struct io_rw_state *s, bool force)
2403 if (!force && !io_op_defs[req->opcode].prep_async)
2405 if (!req_has_async_data(req)) {
2406 struct io_async_rw *iorw;
2408 if (io_alloc_async_data(req)) {
2413 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
2414 iorw = req->async_data;
2415 /* we've copied and mapped the iter, ensure state is saved */
2416 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
2421 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
2423 struct io_async_rw *iorw = req->async_data;
2427 /* submission path, ->uring_lock should already be taken */
2428 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
2429 if (unlikely(ret < 0))
2432 iorw->bytes_done = 0;
2433 iorw->free_iovec = iov;
2435 req->flags |= REQ_F_NEED_CLEANUP;
2439 static int io_readv_prep_async(struct io_kiocb *req)
2441 return io_rw_prep_async(req, READ);
2444 static int io_writev_prep_async(struct io_kiocb *req)
2446 return io_rw_prep_async(req, WRITE);
2450 * This is our waitqueue callback handler, registered through __folio_lock_async()
2451 * when we initially tried to do the IO with the iocb armed our waitqueue.
2452 * This gets called when the page is unlocked, and we generally expect that to
2453 * happen when the page IO is completed and the page is now uptodate. This will
2454 * queue a task_work based retry of the operation, attempting to copy the data
2455 * again. If the latter fails because the page was NOT uptodate, then we will
2456 * do a thread based blocking retry of the operation. That's the unexpected
2459 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2460 int sync, void *arg)
2462 struct wait_page_queue *wpq;
2463 struct io_kiocb *req = wait->private;
2464 struct io_rw *rw = io_kiocb_to_cmd(req);
2465 struct wait_page_key *key = arg;
2467 wpq = container_of(wait, struct wait_page_queue, wait);
2469 if (!wake_page_match(wpq, key))
2472 rw->kiocb.ki_flags &= ~IOCB_WAITQ;
2473 list_del_init(&wait->entry);
2474 io_req_task_queue(req);
2479 * This controls whether a given IO request should be armed for async page
2480 * based retry. If we return false here, the request is handed to the async
2481 * worker threads for retry. If we're doing buffered reads on a regular file,
2482 * we prepare a private wait_page_queue entry and retry the operation. This
2483 * will either succeed because the page is now uptodate and unlocked, or it
2484 * will register a callback when the page is unlocked at IO completion. Through
2485 * that callback, io_uring uses task_work to setup a retry of the operation.
2486 * That retry will attempt the buffered read again. The retry will generally
2487 * succeed, or in rare cases where it fails, we then fall back to using the
2488 * async worker threads for a blocking retry.
2490 static bool io_rw_should_retry(struct io_kiocb *req)
2492 struct io_async_rw *io = req->async_data;
2493 struct wait_page_queue *wait = &io->wpq;
2494 struct io_rw *rw = io_kiocb_to_cmd(req);
2495 struct kiocb *kiocb = &rw->kiocb;
2497 /* never retry for NOWAIT, we just complete with -EAGAIN */
2498 if (req->flags & REQ_F_NOWAIT)
2501 /* Only for buffered IO */
2502 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
2506 * just use poll if we can, and don't attempt if the fs doesn't
2507 * support callback based unlocks
2509 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2512 wait->wait.func = io_async_buf_func;
2513 wait->wait.private = req;
2514 wait->wait.flags = 0;
2515 INIT_LIST_HEAD(&wait->wait.entry);
2516 kiocb->ki_flags |= IOCB_WAITQ;
2517 kiocb->ki_flags &= ~IOCB_NOWAIT;
2518 kiocb->ki_waitq = wait;
2522 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
2524 struct file *file = rw->kiocb.ki_filp;
2526 if (likely(file->f_op->read_iter))
2527 return call_read_iter(file, &rw->kiocb, iter);
2528 else if (file->f_op->read)
2529 return loop_rw_iter(READ, rw, iter);
2534 static bool need_read_all(struct io_kiocb *req)
2536 return req->flags & REQ_F_ISREG ||
2537 S_ISBLK(file_inode(req->file)->i_mode);
2540 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
2542 struct io_rw *rw = io_kiocb_to_cmd(req);
2543 struct kiocb *kiocb = &rw->kiocb;
2544 struct io_ring_ctx *ctx = req->ctx;
2545 struct file *file = req->file;
2548 if (unlikely(!file || !(file->f_mode & mode)))
2551 if (!io_req_ffs_set(req))
2552 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
2554 kiocb->ki_flags = iocb_flags(file);
2555 ret = kiocb_set_rw_flags(kiocb, rw->flags);
2560 * If the file is marked O_NONBLOCK, still allow retry for it if it
2561 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2562 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2564 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2565 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
2566 req->flags |= REQ_F_NOWAIT;
2568 if (ctx->flags & IORING_SETUP_IOPOLL) {
2569 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
2572 kiocb->private = NULL;
2573 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2574 kiocb->ki_complete = io_complete_rw_iopoll;
2575 req->iopoll_completed = 0;
2577 if (kiocb->ki_flags & IOCB_HIPRI)
2579 kiocb->ki_complete = io_complete_rw;
2585 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
2587 struct io_rw *rw = io_kiocb_to_cmd(req);
2588 struct io_rw_state __s, *s = &__s;
2589 struct iovec *iovec;
2590 struct kiocb *kiocb = &rw->kiocb;
2591 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2592 struct io_async_rw *io;
2596 if (!req_has_async_data(req)) {
2597 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2598 if (unlikely(ret < 0))
2601 io = req->async_data;
2605 * Safe and required to re-import if we're using provided
2606 * buffers, as we dropped the selected one before retry.
2608 if (io_do_buffer_select(req)) {
2609 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2610 if (unlikely(ret < 0))
2615 * We come here from an earlier attempt, restore our state to
2616 * match in case it doesn't. It's cheap enough that we don't
2617 * need to make this conditional.
2619 iov_iter_restore(&s->iter, &s->iter_state);
2622 ret = io_rw_init_file(req, FMODE_READ);
2623 if (unlikely(ret)) {
2627 req->cqe.res = iov_iter_count(&s->iter);
2629 if (force_nonblock) {
2630 /* If the file doesn't support async, just async punt */
2631 if (unlikely(!io_file_supports_nowait(req))) {
2632 ret = io_setup_async_rw(req, iovec, s, true);
2633 return ret ?: -EAGAIN;
2635 kiocb->ki_flags |= IOCB_NOWAIT;
2637 /* Ensure we clear previously set non-block flag */
2638 kiocb->ki_flags &= ~IOCB_NOWAIT;
2641 ppos = io_kiocb_update_pos(req);
2643 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
2644 if (unlikely(ret)) {
2649 ret = io_iter_do_read(rw, &s->iter);
2651 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
2652 req->flags &= ~REQ_F_REISSUE;
2653 /* if we can poll, just do that */
2654 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
2656 /* IOPOLL retry should happen for io-wq threads */
2657 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
2659 /* no retry on NONBLOCK nor RWF_NOWAIT */
2660 if (req->flags & REQ_F_NOWAIT)
2663 } else if (ret == -EIOCBQUEUED) {
2665 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
2666 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
2667 /* read all, failed, already did sync or don't want to retry */
2672 * Don't depend on the iter state matching what was consumed, or being
2673 * untouched in case of error. Restore it and we'll advance it
2674 * manually if we need to.
2676 iov_iter_restore(&s->iter, &s->iter_state);
2678 ret2 = io_setup_async_rw(req, iovec, s, true);
2683 io = req->async_data;
2686 * Now use our persistent iterator and state, if we aren't already.
2687 * We've restored and mapped the iter to match.
2692 * We end up here because of a partial read, either from
2693 * above or inside this loop. Advance the iter by the bytes
2694 * that were consumed.
2696 iov_iter_advance(&s->iter, ret);
2697 if (!iov_iter_count(&s->iter))
2699 io->bytes_done += ret;
2700 iov_iter_save_state(&s->iter, &s->iter_state);
2702 /* if we can retry, do so with the callbacks armed */
2703 if (!io_rw_should_retry(req)) {
2704 kiocb->ki_flags &= ~IOCB_WAITQ;
2709 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
2710 * we get -EIOCBQUEUED, then we'll get a notification when the
2711 * desired page gets unlocked. We can also get a partial read
2712 * here, and if we do, then just retry at the new offset.
2714 ret = io_iter_do_read(rw, &s->iter);
2715 if (ret == -EIOCBQUEUED)
2716 return IOU_ISSUE_SKIP_COMPLETE;
2717 /* we got some bytes, but not all. retry. */
2718 kiocb->ki_flags &= ~IOCB_WAITQ;
2719 iov_iter_restore(&s->iter, &s->iter_state);
2722 kiocb_done(req, ret, issue_flags);
2724 /* it's faster to check here then delegate to kfree */
2727 return IOU_ISSUE_SKIP_COMPLETE;
2730 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
2732 struct io_rw *rw = io_kiocb_to_cmd(req);
2733 struct io_rw_state __s, *s = &__s;
2734 struct iovec *iovec;
2735 struct kiocb *kiocb = &rw->kiocb;
2736 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2740 if (!req_has_async_data(req)) {
2741 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
2742 if (unlikely(ret < 0))
2745 struct io_async_rw *io = req->async_data;
2748 iov_iter_restore(&s->iter, &s->iter_state);
2751 ret = io_rw_init_file(req, FMODE_WRITE);
2752 if (unlikely(ret)) {
2756 req->cqe.res = iov_iter_count(&s->iter);
2758 if (force_nonblock) {
2759 /* If the file doesn't support async, just async punt */
2760 if (unlikely(!io_file_supports_nowait(req)))
2763 /* file path doesn't support NOWAIT for non-direct_IO */
2764 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2765 (req->flags & REQ_F_ISREG))
2768 kiocb->ki_flags |= IOCB_NOWAIT;
2770 /* Ensure we clear previously set non-block flag */
2771 kiocb->ki_flags &= ~IOCB_NOWAIT;
2774 ppos = io_kiocb_update_pos(req);
2776 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
2781 * Open-code file_start_write here to grab freeze protection,
2782 * which will be released by another thread in
2783 * io_complete_rw(). Fool lockdep by telling it the lock got
2784 * released so that it doesn't complain about the held lock when
2785 * we return to userspace.
2787 if (req->flags & REQ_F_ISREG) {
2788 sb_start_write(file_inode(req->file)->i_sb);
2789 __sb_writers_release(file_inode(req->file)->i_sb,
2792 kiocb->ki_flags |= IOCB_WRITE;
2794 if (likely(req->file->f_op->write_iter))
2795 ret2 = call_write_iter(req->file, kiocb, &s->iter);
2796 else if (req->file->f_op->write)
2797 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
2801 if (req->flags & REQ_F_REISSUE) {
2802 req->flags &= ~REQ_F_REISSUE;
2807 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
2808 * retry them without IOCB_NOWAIT.
2810 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2812 /* no retry on NONBLOCK nor RWF_NOWAIT */
2813 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
2815 if (!force_nonblock || ret2 != -EAGAIN) {
2816 /* IOPOLL retry should happen for io-wq threads */
2817 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
2820 kiocb_done(req, ret2, issue_flags);
2821 ret = IOU_ISSUE_SKIP_COMPLETE;
2824 iov_iter_restore(&s->iter, &s->iter_state);
2825 ret = io_setup_async_rw(req, iovec, s, false);
2826 return ret ?: -EAGAIN;
2829 /* it's reportedly faster than delegating the null check to kfree() */
2836 * Note when io_fixed_fd_install() returns error value, it will ensure
2837 * fput() is called correspondingly.
2839 int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
2840 struct file *file, unsigned int file_slot)
2842 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
2843 struct io_ring_ctx *ctx = req->ctx;
2846 io_ring_submit_lock(ctx, issue_flags);
2849 ret = io_file_bitmap_get(ctx);
2850 if (unlikely(ret < 0))
2857 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
2858 if (!ret && alloc_slot)
2861 io_ring_submit_unlock(ctx, issue_flags);
2862 if (unlikely(ret < 0))
2867 static __maybe_unused int io_eopnotsupp_prep(struct io_kiocb *kiocb,
2868 const struct io_uring_sqe *sqe)
2873 static int io_files_update_prep(struct io_kiocb *req,
2874 const struct io_uring_sqe *sqe)
2876 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
2878 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
2880 if (sqe->rw_flags || sqe->splice_fd_in)
2883 up->offset = READ_ONCE(sqe->off);
2884 up->nr_args = READ_ONCE(sqe->len);
2887 up->arg = READ_ONCE(sqe->addr);
2891 static int io_files_update_with_index_alloc(struct io_kiocb *req,
2892 unsigned int issue_flags)
2894 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
2895 __s32 __user *fds = u64_to_user_ptr(up->arg);
2900 if (!req->ctx->file_data)
2903 for (done = 0; done < up->nr_args; done++) {
2904 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
2914 ret = io_fixed_fd_install(req, issue_flags, file,
2915 IORING_FILE_INDEX_ALLOC);
2918 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
2919 __io_close_fixed(req, issue_flags, ret);
2930 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
2932 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
2933 struct io_ring_ctx *ctx = req->ctx;
2934 struct io_uring_rsrc_update2 up2;
2937 up2.offset = up->offset;
2944 if (up->offset == IORING_FILE_INDEX_ALLOC) {
2945 ret = io_files_update_with_index_alloc(req, issue_flags);
2947 io_ring_submit_lock(ctx, issue_flags);
2948 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
2950 io_ring_submit_unlock(ctx, issue_flags);
2955 io_req_set_res(req, ret, 0);
2959 static int io_req_prep_async(struct io_kiocb *req)
2961 const struct io_op_def *def = &io_op_defs[req->opcode];
2963 /* assign early for deferred execution for non-fixed file */
2964 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
2965 req->file = io_file_get_normal(req, req->cqe.fd);
2966 if (!def->prep_async)
2968 if (WARN_ON_ONCE(req_has_async_data(req)))
2970 if (io_alloc_async_data(req))
2973 return def->prep_async(req);
2976 static u32 io_get_sequence(struct io_kiocb *req)
2978 u32 seq = req->ctx->cached_sq_head;
2979 struct io_kiocb *cur;
2981 /* need original cached_sq_head, but it was increased for each req */
2982 io_for_each_link(cur, req)
2987 static __cold void io_drain_req(struct io_kiocb *req)
2989 struct io_ring_ctx *ctx = req->ctx;
2990 struct io_defer_entry *de;
2992 u32 seq = io_get_sequence(req);
2994 /* Still need defer if there is pending req in defer list. */
2995 spin_lock(&ctx->completion_lock);
2996 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
2997 spin_unlock(&ctx->completion_lock);
2999 ctx->drain_active = false;
3000 io_req_task_queue(req);
3003 spin_unlock(&ctx->completion_lock);
3005 ret = io_req_prep_async(req);
3008 io_req_complete_failed(req, ret);
3011 io_prep_async_link(req);
3012 de = kmalloc(sizeof(*de), GFP_KERNEL);
3018 spin_lock(&ctx->completion_lock);
3019 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
3020 spin_unlock(&ctx->completion_lock);
3025 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
3028 list_add_tail(&de->list, &ctx->defer_list);
3029 spin_unlock(&ctx->completion_lock);
3032 static void io_clean_op(struct io_kiocb *req)
3034 if (req->flags & REQ_F_BUFFER_SELECTED) {
3035 spin_lock(&req->ctx->completion_lock);
3036 io_put_kbuf_comp(req);
3037 spin_unlock(&req->ctx->completion_lock);
3040 if (req->flags & REQ_F_NEED_CLEANUP) {
3041 const struct io_op_def *def = &io_op_defs[req->opcode];
3046 if ((req->flags & REQ_F_POLLED) && req->apoll) {
3047 kfree(req->apoll->double_poll);
3051 if (req->flags & REQ_F_INFLIGHT) {
3052 struct io_uring_task *tctx = req->task->io_uring;
3054 atomic_dec(&tctx->inflight_tracked);
3056 if (req->flags & REQ_F_CREDS)
3057 put_cred(req->creds);
3058 if (req->flags & REQ_F_ASYNC_DATA) {
3059 kfree(req->async_data);
3060 req->async_data = NULL;
3062 req->flags &= ~IO_REQ_CLEAN_FLAGS;
3065 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
3067 if (req->file || !io_op_defs[req->opcode].needs_file)
3070 if (req->flags & REQ_F_FIXED_FILE)
3071 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
3073 req->file = io_file_get_normal(req, req->cqe.fd);
3078 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
3080 const struct io_op_def *def = &io_op_defs[req->opcode];
3081 const struct cred *creds = NULL;
3084 if (unlikely(!io_assign_file(req, issue_flags)))
3087 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
3088 creds = override_creds(req->creds);
3090 if (!def->audit_skip)
3091 audit_uring_entry(req->opcode);
3093 ret = def->issue(req, issue_flags);
3095 if (!def->audit_skip)
3096 audit_uring_exit(!ret, ret);
3099 revert_creds(creds);
3102 __io_req_complete(req, issue_flags);
3103 else if (ret != IOU_ISSUE_SKIP_COMPLETE)
3106 /* If the op doesn't have a file, we're not polling for it */
3107 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
3108 io_iopoll_req_issued(req, issue_flags);
3113 int io_poll_issue(struct io_kiocb *req, bool *locked)
3115 io_tw_lock(req->ctx, locked);
3116 if (unlikely(req->task->flags & PF_EXITING))
3118 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3121 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
3123 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3125 req = io_put_req_find_next(req);
3126 return req ? &req->work : NULL;
3129 void io_wq_submit_work(struct io_wq_work *work)
3131 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3132 const struct io_op_def *def = &io_op_defs[req->opcode];
3133 unsigned int issue_flags = IO_URING_F_UNLOCKED;
3134 bool needs_poll = false;
3135 int ret = 0, err = -ECANCELED;
3137 /* one will be dropped by ->io_free_work() after returning to io-wq */
3138 if (!(req->flags & REQ_F_REFCOUNT))
3139 __io_req_set_refcount(req, 2);
3143 io_arm_ltimeout(req);
3145 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
3146 if (work->flags & IO_WQ_WORK_CANCEL) {
3148 io_req_task_queue_fail(req, err);
3151 if (!io_assign_file(req, issue_flags)) {
3153 work->flags |= IO_WQ_WORK_CANCEL;
3157 if (req->flags & REQ_F_FORCE_ASYNC) {
3158 bool opcode_poll = def->pollin || def->pollout;
3160 if (opcode_poll && file_can_poll(req->file)) {
3162 issue_flags |= IO_URING_F_NONBLOCK;
3167 ret = io_issue_sqe(req, issue_flags);
3171 * We can get EAGAIN for iopolled IO even though we're
3172 * forcing a sync submission from here, since we can't
3173 * wait for request slots on the block side.
3176 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
3182 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
3184 /* aborted or ready, in either case retry blocking */
3186 issue_flags &= ~IO_URING_F_NONBLOCK;
3189 /* avoid locking problems by failing it from a clean context */
3191 io_req_task_queue_fail(req, ret);
3194 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
3195 unsigned int issue_flags)
3197 struct io_ring_ctx *ctx = req->ctx;
3198 struct file *file = NULL;
3199 unsigned long file_ptr;
3201 io_ring_submit_lock(ctx, issue_flags);
3203 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
3205 fd = array_index_nospec(fd, ctx->nr_user_files);
3206 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
3207 file = (struct file *) (file_ptr & FFS_MASK);
3208 file_ptr &= ~FFS_MASK;
3209 /* mask in overlapping REQ_F and FFS bits */
3210 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
3211 io_req_set_rsrc_node(req, ctx, 0);
3212 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
3214 io_ring_submit_unlock(ctx, issue_flags);
3218 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
3220 struct file *file = fget(fd);
3222 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
3224 /* we don't allow fixed io_uring files */
3225 if (file && io_is_uring_fops(file))
3226 io_req_track_inflight(req);
3230 static void io_queue_async(struct io_kiocb *req, int ret)
3231 __must_hold(&req->ctx->uring_lock)
3233 struct io_kiocb *linked_timeout;
3235 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
3236 io_req_complete_failed(req, ret);
3240 linked_timeout = io_prep_linked_timeout(req);
3242 switch (io_arm_poll_handler(req, 0)) {
3243 case IO_APOLL_READY:
3244 io_req_task_queue(req);
3246 case IO_APOLL_ABORTED:
3248 * Queued up for async execution, worker will release
3249 * submit reference when the iocb is actually submitted.
3251 io_kbuf_recycle(req, 0);
3252 io_queue_iowq(req, NULL);
3259 io_queue_linked_timeout(linked_timeout);
3262 static inline void io_queue_sqe(struct io_kiocb *req)
3263 __must_hold(&req->ctx->uring_lock)
3267 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3269 if (req->flags & REQ_F_COMPLETE_INLINE) {
3270 io_req_add_compl_list(req);
3274 * We async punt it if the file wasn't marked NOWAIT, or if the file
3275 * doesn't support non-blocking read/write attempts
3278 io_arm_ltimeout(req);
3280 io_queue_async(req, ret);
3283 static void io_queue_sqe_fallback(struct io_kiocb *req)
3284 __must_hold(&req->ctx->uring_lock)
3286 if (unlikely(req->flags & REQ_F_FAIL)) {
3288 * We don't submit, fail them all, for that replace hardlinks
3289 * with normal links. Extra REQ_F_LINK is tolerated.
3291 req->flags &= ~REQ_F_HARDLINK;
3292 req->flags |= REQ_F_LINK;
3293 io_req_complete_failed(req, req->cqe.res);
3294 } else if (unlikely(req->ctx->drain_active)) {
3297 int ret = io_req_prep_async(req);
3300 io_req_complete_failed(req, ret);
3302 io_queue_iowq(req, NULL);
3307 * Check SQE restrictions (opcode and flags).
3309 * Returns 'true' if SQE is allowed, 'false' otherwise.
3311 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
3312 struct io_kiocb *req,
3313 unsigned int sqe_flags)
3315 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
3318 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
3319 ctx->restrictions.sqe_flags_required)
3322 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
3323 ctx->restrictions.sqe_flags_required))
3329 static void io_init_req_drain(struct io_kiocb *req)
3331 struct io_ring_ctx *ctx = req->ctx;
3332 struct io_kiocb *head = ctx->submit_state.link.head;
3334 ctx->drain_active = true;
3337 * If we need to drain a request in the middle of a link, drain
3338 * the head request and the next request/link after the current
3339 * link. Considering sequential execution of links,
3340 * REQ_F_IO_DRAIN will be maintained for every request of our
3343 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
3344 ctx->drain_next = true;
3348 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
3349 const struct io_uring_sqe *sqe)
3350 __must_hold(&ctx->uring_lock)
3352 const struct io_op_def *def;
3353 unsigned int sqe_flags;
3357 /* req is partially pre-initialised, see io_preinit_req() */
3358 req->opcode = opcode = READ_ONCE(sqe->opcode);
3359 /* same numerical values with corresponding REQ_F_*, safe to copy */
3360 req->flags = sqe_flags = READ_ONCE(sqe->flags);
3361 req->cqe.user_data = READ_ONCE(sqe->user_data);
3363 req->rsrc_node = NULL;
3364 req->task = current;
3366 if (unlikely(opcode >= IORING_OP_LAST)) {
3370 def = &io_op_defs[opcode];
3371 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
3372 /* enforce forwards compatibility on users */
3373 if (sqe_flags & ~SQE_VALID_FLAGS)
3375 if (sqe_flags & IOSQE_BUFFER_SELECT) {
3376 if (!def->buffer_select)
3378 req->buf_index = READ_ONCE(sqe->buf_group);
3380 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
3381 ctx->drain_disabled = true;
3382 if (sqe_flags & IOSQE_IO_DRAIN) {
3383 if (ctx->drain_disabled)
3385 io_init_req_drain(req);
3388 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
3389 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
3391 /* knock it to the slow queue path, will be drained there */
3392 if (ctx->drain_active)
3393 req->flags |= REQ_F_FORCE_ASYNC;
3394 /* if there is no link, we're at "next" request and need to drain */
3395 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
3396 ctx->drain_next = false;
3397 ctx->drain_active = true;
3398 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
3402 if (!def->ioprio && sqe->ioprio)
3404 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
3407 if (def->needs_file) {
3408 struct io_submit_state *state = &ctx->submit_state;
3410 req->cqe.fd = READ_ONCE(sqe->fd);
3413 * Plug now if we have more than 2 IO left after this, and the
3414 * target is potentially a read/write to block based storage.
3416 if (state->need_plug && def->plug) {
3417 state->plug_started = true;
3418 state->need_plug = false;
3419 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
3423 personality = READ_ONCE(sqe->personality);
3427 req->creds = xa_load(&ctx->personalities, personality);
3430 get_cred(req->creds);
3431 ret = security_uring_override_creds(req->creds);
3433 put_cred(req->creds);
3436 req->flags |= REQ_F_CREDS;
3439 return def->prep(req, sqe);
3442 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
3443 struct io_kiocb *req, int ret)
3445 struct io_ring_ctx *ctx = req->ctx;
3446 struct io_submit_link *link = &ctx->submit_state.link;
3447 struct io_kiocb *head = link->head;
3449 trace_io_uring_req_failed(sqe, ctx, req, ret);
3452 * Avoid breaking links in the middle as it renders links with SQPOLL
3453 * unusable. Instead of failing eagerly, continue assembling the link if
3454 * applicable and mark the head with REQ_F_FAIL. The link flushing code
3455 * should find the flag and handle the rest.
3457 req_fail_link_node(req, ret);
3458 if (head && !(head->flags & REQ_F_FAIL))
3459 req_fail_link_node(head, -ECANCELED);
3461 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
3463 link->last->link = req;
3467 io_queue_sqe_fallback(req);
3472 link->last->link = req;
3479 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
3480 const struct io_uring_sqe *sqe)
3481 __must_hold(&ctx->uring_lock)
3483 struct io_submit_link *link = &ctx->submit_state.link;
3486 ret = io_init_req(ctx, req, sqe);
3488 return io_submit_fail_init(sqe, req, ret);
3490 /* don't need @sqe from now on */
3491 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
3493 ctx->flags & IORING_SETUP_SQPOLL);
3496 * If we already have a head request, queue this one for async
3497 * submittal once the head completes. If we don't have a head but
3498 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3499 * submitted sync once the chain is complete. If none of those
3500 * conditions are true (normal request), then just queue it.
3502 if (unlikely(link->head)) {
3503 ret = io_req_prep_async(req);
3505 return io_submit_fail_init(sqe, req, ret);
3507 trace_io_uring_link(ctx, req, link->head);
3508 link->last->link = req;
3511 if (req->flags & IO_REQ_LINK_FLAGS)
3513 /* last request of the link, flush it */
3516 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
3519 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
3520 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
3521 if (req->flags & IO_REQ_LINK_FLAGS) {
3526 io_queue_sqe_fallback(req);
3536 * Batched submission is done, ensure local IO is flushed out.
3538 static void io_submit_state_end(struct io_ring_ctx *ctx)
3540 struct io_submit_state *state = &ctx->submit_state;
3542 if (unlikely(state->link.head))
3543 io_queue_sqe_fallback(state->link.head);
3544 /* flush only after queuing links as they can generate completions */
3545 io_submit_flush_completions(ctx);
3546 if (state->plug_started)
3547 blk_finish_plug(&state->plug);
3551 * Start submission side cache.
3553 static void io_submit_state_start(struct io_submit_state *state,
3554 unsigned int max_ios)
3556 state->plug_started = false;
3557 state->need_plug = max_ios > 2;
3558 state->submit_nr = max_ios;
3559 /* set only head, no need to init link_last in advance */
3560 state->link.head = NULL;
3563 static void io_commit_sqring(struct io_ring_ctx *ctx)
3565 struct io_rings *rings = ctx->rings;
3568 * Ensure any loads from the SQEs are done at this point,
3569 * since once we write the new head, the application could
3570 * write new data to them.
3572 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3576 * Fetch an sqe, if one is available. Note this returns a pointer to memory
3577 * that is mapped by userspace. This means that care needs to be taken to
3578 * ensure that reads are stable, as we cannot rely on userspace always
3579 * being a good citizen. If members of the sqe are validated and then later
3580 * used, it's important that those reads are done through READ_ONCE() to
3581 * prevent a re-load down the line.
3583 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
3585 unsigned head, mask = ctx->sq_entries - 1;
3586 unsigned sq_idx = ctx->cached_sq_head++ & mask;
3589 * The cached sq head (or cq tail) serves two purposes:
3591 * 1) allows us to batch the cost of updating the user visible
3593 * 2) allows the kernel side to track the head on its own, even
3594 * though the application is the one updating it.
3596 head = READ_ONCE(ctx->sq_array[sq_idx]);
3597 if (likely(head < ctx->sq_entries)) {
3598 /* double index for 128-byte SQEs, twice as long */
3599 if (ctx->flags & IORING_SETUP_SQE128)
3601 return &ctx->sq_sqes[head];
3604 /* drop invalid entries */
3606 WRITE_ONCE(ctx->rings->sq_dropped,
3607 READ_ONCE(ctx->rings->sq_dropped) + 1);
3611 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
3612 __must_hold(&ctx->uring_lock)
3614 unsigned int entries = io_sqring_entries(ctx);
3618 if (unlikely(!entries))
3620 /* make sure SQ entry isn't read before tail */
3621 ret = left = min3(nr, ctx->sq_entries, entries);
3622 io_get_task_refs(left);
3623 io_submit_state_start(&ctx->submit_state, left);
3626 const struct io_uring_sqe *sqe;
3627 struct io_kiocb *req;
3629 if (unlikely(!io_alloc_req_refill(ctx)))
3631 req = io_alloc_req(ctx);
3632 sqe = io_get_sqe(ctx);
3633 if (unlikely(!sqe)) {
3634 io_req_add_to_cache(req, ctx);
3639 * Continue submitting even for sqe failure if the
3640 * ring was setup with IORING_SETUP_SUBMIT_ALL
3642 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
3643 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
3649 if (unlikely(left)) {
3651 /* try again if it submitted nothing and can't allocate a req */
3652 if (!ret && io_req_cache_empty(ctx))
3654 current->io_uring->cached_refs += left;
3657 io_submit_state_end(ctx);
3658 /* Commit SQ ring head once we've consumed and submitted all SQEs */
3659 io_commit_sqring(ctx);
3663 struct io_wait_queue {
3664 struct wait_queue_entry wq;
3665 struct io_ring_ctx *ctx;
3667 unsigned nr_timeouts;
3670 static inline bool io_should_wake(struct io_wait_queue *iowq)
3672 struct io_ring_ctx *ctx = iowq->ctx;
3673 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
3676 * Wake up if we have enough events, or if a timeout occurred since we
3677 * started waiting. For timeouts, we always want to return to userspace,
3678 * regardless of event count.
3680 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3683 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3684 int wake_flags, void *key)
3686 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3690 * Cannot safely flush overflowed CQEs from here, ensure we wake up
3691 * the task, and the next invocation will do it.
3693 if (io_should_wake(iowq) ||
3694 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
3695 return autoremove_wake_function(curr, mode, wake_flags, key);
3699 static int io_run_task_work_sig(void)
3701 if (io_run_task_work())
3703 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
3704 return -ERESTARTSYS;
3705 if (task_sigpending(current))
3710 /* when returns >0, the caller should retry */
3711 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
3712 struct io_wait_queue *iowq,
3716 unsigned long check_cq;
3718 /* make sure we run task_work before checking for signals */
3719 ret = io_run_task_work_sig();
3720 if (ret || io_should_wake(iowq))
3722 check_cq = READ_ONCE(ctx->check_cq);
3723 /* let the caller flush overflows, retry */
3724 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3726 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3728 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
3734 * Wait until events become available, if we don't already have some. The
3735 * application must reap them itself, as they reside on the shared cq ring.
3737 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3738 const sigset_t __user *sig, size_t sigsz,
3739 struct __kernel_timespec __user *uts)
3741 struct io_wait_queue iowq;
3742 struct io_rings *rings = ctx->rings;
3743 ktime_t timeout = KTIME_MAX;
3747 io_cqring_overflow_flush(ctx);
3748 if (io_cqring_events(ctx) >= min_events)
3750 if (!io_run_task_work())
3755 #ifdef CONFIG_COMPAT
3756 if (in_compat_syscall())
3757 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3761 ret = set_user_sigmask(sig, sigsz);
3768 struct timespec64 ts;
3770 if (get_timespec64(&ts, uts))
3772 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
3775 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
3776 iowq.wq.private = current;
3777 INIT_LIST_HEAD(&iowq.wq.entry);
3779 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3780 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
3782 trace_io_uring_cqring_wait(ctx, min_events);
3784 /* if we can't even flush overflow, don't wait for more */
3785 if (!io_cqring_overflow_flush(ctx)) {
3789 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
3790 TASK_INTERRUPTIBLE);
3791 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
3795 finish_wait(&ctx->cq_wait, &iowq.wq);
3796 restore_saved_sigmask_unless(ret == -EINTR);
3798 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3801 static void io_free_page_table(void **table, size_t size)
3803 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
3805 for (i = 0; i < nr_tables; i++)
3810 static __cold void **io_alloc_page_table(size_t size)
3812 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
3813 size_t init_size = size;
3816 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
3820 for (i = 0; i < nr_tables; i++) {
3821 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
3823 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
3825 io_free_page_table(table, init_size);
3833 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
3835 percpu_ref_exit(&ref_node->refs);
3839 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
3841 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
3842 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
3843 unsigned long flags;
3844 bool first_add = false;
3845 unsigned long delay = HZ;
3847 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
3850 /* if we are mid-quiesce then do not delay */
3851 if (node->rsrc_data->quiesce)
3854 while (!list_empty(&ctx->rsrc_ref_list)) {
3855 node = list_first_entry(&ctx->rsrc_ref_list,
3856 struct io_rsrc_node, node);
3857 /* recycle ref nodes in order */
3860 list_del(&node->node);
3861 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
3863 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
3866 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
3869 static struct io_rsrc_node *io_rsrc_node_alloc(void)
3871 struct io_rsrc_node *ref_node;
3873 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
3877 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
3882 INIT_LIST_HEAD(&ref_node->node);
3883 INIT_LIST_HEAD(&ref_node->rsrc_list);
3884 ref_node->done = false;
3888 void io_rsrc_node_switch(struct io_ring_ctx *ctx,
3889 struct io_rsrc_data *data_to_kill)
3890 __must_hold(&ctx->uring_lock)
3892 WARN_ON_ONCE(!ctx->rsrc_backup_node);
3893 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
3895 io_rsrc_refs_drop(ctx);
3898 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
3900 rsrc_node->rsrc_data = data_to_kill;
3901 spin_lock_irq(&ctx->rsrc_ref_lock);
3902 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
3903 spin_unlock_irq(&ctx->rsrc_ref_lock);
3905 atomic_inc(&data_to_kill->refs);
3906 percpu_ref_kill(&rsrc_node->refs);
3907 ctx->rsrc_node = NULL;
3910 if (!ctx->rsrc_node) {
3911 ctx->rsrc_node = ctx->rsrc_backup_node;
3912 ctx->rsrc_backup_node = NULL;
3916 int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
3918 if (ctx->rsrc_backup_node)
3920 ctx->rsrc_backup_node = io_rsrc_node_alloc();
3921 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
3924 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
3925 struct io_ring_ctx *ctx)
3929 /* As we may drop ->uring_lock, other task may have started quiesce */
3933 data->quiesce = true;
3935 ret = io_rsrc_node_switch_start(ctx);
3938 io_rsrc_node_switch(ctx, data);
3940 /* kill initial ref, already quiesced if zero */
3941 if (atomic_dec_and_test(&data->refs))
3943 mutex_unlock(&ctx->uring_lock);
3944 flush_delayed_work(&ctx->rsrc_put_work);
3945 ret = wait_for_completion_interruptible(&data->done);
3947 mutex_lock(&ctx->uring_lock);
3948 if (atomic_read(&data->refs) > 0) {
3950 * it has been revived by another thread while
3953 mutex_unlock(&ctx->uring_lock);
3959 atomic_inc(&data->refs);
3960 /* wait for all works potentially completing data->done */
3961 flush_delayed_work(&ctx->rsrc_put_work);
3962 reinit_completion(&data->done);
3964 ret = io_run_task_work_sig();
3965 mutex_lock(&ctx->uring_lock);
3967 data->quiesce = false;
3972 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
3974 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
3975 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
3977 return &data->tags[table_idx][off];
3980 static void io_rsrc_data_free(struct io_rsrc_data *data)
3982 size_t size = data->nr * sizeof(data->tags[0][0]);
3985 io_free_page_table((void **)data->tags, size);
3989 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
3990 u64 __user *utags, unsigned nr,
3991 struct io_rsrc_data **pdata)
3993 struct io_rsrc_data *data;
3997 data = kzalloc(sizeof(*data), GFP_KERNEL);
4000 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
4008 data->do_put = do_put;
4011 for (i = 0; i < nr; i++) {
4012 u64 *tag_slot = io_get_tag_slot(data, i);
4014 if (copy_from_user(tag_slot, &utags[i],
4020 atomic_set(&data->refs, 1);
4021 init_completion(&data->done);
4025 io_rsrc_data_free(data);
4029 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4031 #if !defined(IO_URING_SCM_ALL)
4034 for (i = 0; i < ctx->nr_user_files; i++) {
4035 struct file *file = io_file_from_index(&ctx->file_table, i);
4039 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
4041 io_file_bitmap_clear(&ctx->file_table, i);
4046 #if defined(CONFIG_UNIX)
4047 if (ctx->ring_sock) {
4048 struct sock *sock = ctx->ring_sock->sk;
4049 struct sk_buff *skb;
4051 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4055 io_free_file_tables(&ctx->file_table);
4056 io_rsrc_data_free(ctx->file_data);
4057 ctx->file_data = NULL;
4058 ctx->nr_user_files = 0;
4061 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4063 unsigned nr = ctx->nr_user_files;
4066 if (!ctx->file_data)
4070 * Quiesce may unlock ->uring_lock, and while it's not held
4071 * prevent new requests using the table.
4073 ctx->nr_user_files = 0;
4074 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
4075 ctx->nr_user_files = nr;
4077 __io_sqe_files_unregister(ctx);
4082 * Ensure the UNIX gc is aware of our file set, so we are certain that
4083 * the io_uring can be safely unregistered on process exit, even if we have
4084 * loops in the file referencing. We account only files that can hold other
4085 * files because otherwise they can't form a loop and so are not interesting
4088 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
4090 #if defined(CONFIG_UNIX)
4091 struct sock *sk = ctx->ring_sock->sk;
4092 struct sk_buff_head *head = &sk->sk_receive_queue;
4093 struct scm_fp_list *fpl;
4094 struct sk_buff *skb;
4096 if (likely(!io_file_need_scm(file)))
4100 * See if we can merge this file into an existing skb SCM_RIGHTS
4101 * file set. If there's no room, fall back to allocating a new skb
4102 * and filling it in.
4104 spin_lock_irq(&head->lock);
4105 skb = skb_peek(head);
4106 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
4107 __skb_unlink(skb, head);
4110 spin_unlock_irq(&head->lock);
4113 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4117 skb = alloc_skb(0, GFP_KERNEL);
4123 fpl->user = get_uid(current_user());
4124 fpl->max = SCM_MAX_FD;
4127 UNIXCB(skb).fp = fpl;
4129 skb->destructor = unix_destruct_scm;
4130 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4133 fpl = UNIXCB(skb).fp;
4134 fpl->fp[fpl->count++] = get_file(file);
4135 unix_inflight(fpl->user, file);
4136 skb_queue_head(head, skb);
4142 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
4144 struct file *file = prsrc->file;
4145 #if defined(CONFIG_UNIX)
4146 struct sock *sock = ctx->ring_sock->sk;
4147 struct sk_buff_head list, *head = &sock->sk_receive_queue;
4148 struct sk_buff *skb;
4151 if (!io_file_need_scm(file)) {
4156 __skb_queue_head_init(&list);
4159 * Find the skb that holds this file in its SCM_RIGHTS. When found,
4160 * remove this entry and rearrange the file array.
4162 skb = skb_dequeue(head);
4164 struct scm_fp_list *fp;
4166 fp = UNIXCB(skb).fp;
4167 for (i = 0; i < fp->count; i++) {
4170 if (fp->fp[i] != file)
4173 unix_notinflight(fp->user, fp->fp[i]);
4174 left = fp->count - 1 - i;
4176 memmove(&fp->fp[i], &fp->fp[i + 1],
4177 left * sizeof(struct file *));
4184 __skb_queue_tail(&list, skb);
4194 __skb_queue_tail(&list, skb);
4196 skb = skb_dequeue(head);
4199 if (skb_peek(&list)) {
4200 spin_lock_irq(&head->lock);
4201 while ((skb = __skb_dequeue(&list)) != NULL)
4202 __skb_queue_tail(head, skb);
4203 spin_unlock_irq(&head->lock);
4210 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
4212 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
4213 struct io_ring_ctx *ctx = rsrc_data->ctx;
4214 struct io_rsrc_put *prsrc, *tmp;
4216 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
4217 list_del(&prsrc->list);
4220 if (ctx->flags & IORING_SETUP_IOPOLL)
4221 mutex_lock(&ctx->uring_lock);
4223 spin_lock(&ctx->completion_lock);
4224 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
4225 io_commit_cqring(ctx);
4226 spin_unlock(&ctx->completion_lock);
4227 io_cqring_ev_posted(ctx);
4229 if (ctx->flags & IORING_SETUP_IOPOLL)
4230 mutex_unlock(&ctx->uring_lock);
4233 rsrc_data->do_put(ctx, prsrc);
4237 io_rsrc_node_destroy(ref_node);
4238 if (atomic_dec_and_test(&rsrc_data->refs))
4239 complete(&rsrc_data->done);
4242 static void io_rsrc_put_work(struct work_struct *work)
4244 struct io_ring_ctx *ctx;
4245 struct llist_node *node;
4247 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
4248 node = llist_del_all(&ctx->rsrc_put_llist);
4251 struct io_rsrc_node *ref_node;
4252 struct llist_node *next = node->next;
4254 ref_node = llist_entry(node, struct io_rsrc_node, llist);
4255 __io_rsrc_put_work(ref_node);
4260 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4261 unsigned nr_args, u64 __user *tags)
4263 __s32 __user *fds = (__s32 __user *) arg;
4272 if (nr_args > IORING_MAX_FIXED_FILES)
4274 if (nr_args > rlimit(RLIMIT_NOFILE))
4276 ret = io_rsrc_node_switch_start(ctx);
4279 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
4284 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
4285 io_rsrc_data_free(ctx->file_data);
4286 ctx->file_data = NULL;
4290 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4291 struct io_fixed_file *file_slot;
4293 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
4297 /* allow sparse sets */
4298 if (!fds || fd == -1) {
4300 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
4307 if (unlikely(!file))
4311 * Don't allow io_uring instances to be registered. If UNIX
4312 * isn't enabled, then this causes a reference cycle and this
4313 * instance can never get freed. If UNIX is enabled we'll
4314 * handle it just fine, but there's still no point in allowing
4315 * a ring fd as it doesn't support regular read/write anyway.
4317 if (io_is_uring_fops(file)) {
4321 ret = io_scm_file_account(ctx, file);
4326 file_slot = io_fixed_file_slot(&ctx->file_table, i);
4327 io_fixed_file_set(file_slot, file);
4328 io_file_bitmap_set(&ctx->file_table, i);
4331 io_rsrc_node_switch(ctx, NULL);
4334 __io_sqe_files_unregister(ctx);
4338 int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
4339 struct io_rsrc_node *node, void *rsrc)
4341 u64 *tag_slot = io_get_tag_slot(data, idx);
4342 struct io_rsrc_put *prsrc;
4344 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
4348 prsrc->tag = *tag_slot;
4351 list_add(&prsrc->list, &node->rsrc_list);
4355 int io_install_fixed_file(struct io_kiocb *req, struct file *file,
4356 unsigned int issue_flags, u32 slot_index)
4357 __must_hold(&req->ctx->uring_lock)
4359 struct io_ring_ctx *ctx = req->ctx;
4360 bool needs_switch = false;
4361 struct io_fixed_file *file_slot;
4364 if (io_is_uring_fops(file))
4366 if (!ctx->file_data)
4368 if (slot_index >= ctx->nr_user_files)
4371 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
4372 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
4374 if (file_slot->file_ptr) {
4375 struct file *old_file;
4377 ret = io_rsrc_node_switch_start(ctx);
4381 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
4382 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
4383 ctx->rsrc_node, old_file);
4386 file_slot->file_ptr = 0;
4387 io_file_bitmap_clear(&ctx->file_table, slot_index);
4388 needs_switch = true;
4391 ret = io_scm_file_account(ctx, file);
4393 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
4394 io_fixed_file_set(file_slot, file);
4395 io_file_bitmap_set(&ctx->file_table, slot_index);
4399 io_rsrc_node_switch(ctx, ctx->file_data);
4405 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
4406 struct io_uring_rsrc_update2 *up,
4409 u64 __user *tags = u64_to_user_ptr(up->tags);
4410 __s32 __user *fds = u64_to_user_ptr(up->data);
4411 struct io_rsrc_data *data = ctx->file_data;
4412 struct io_fixed_file *file_slot;
4416 bool needs_switch = false;
4418 if (!ctx->file_data)
4420 if (up->offset + nr_args > ctx->nr_user_files)
4423 for (done = 0; done < nr_args; done++) {
4426 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
4427 copy_from_user(&fd, &fds[done], sizeof(fd))) {
4431 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
4435 if (fd == IORING_REGISTER_FILES_SKIP)
4438 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
4439 file_slot = io_fixed_file_slot(&ctx->file_table, i);
4441 if (file_slot->file_ptr) {
4442 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
4443 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
4446 file_slot->file_ptr = 0;
4447 io_file_bitmap_clear(&ctx->file_table, i);
4448 needs_switch = true;
4457 * Don't allow io_uring instances to be registered. If
4458 * UNIX isn't enabled, then this causes a reference
4459 * cycle and this instance can never get freed. If UNIX
4460 * is enabled we'll handle it just fine, but there's
4461 * still no point in allowing a ring fd as it doesn't
4462 * support regular read/write anyway.
4464 if (io_is_uring_fops(file)) {
4469 err = io_scm_file_account(ctx, file);
4474 *io_get_tag_slot(data, i) = tag;
4475 io_fixed_file_set(file_slot, file);
4476 io_file_bitmap_set(&ctx->file_table, i);
4481 io_rsrc_node_switch(ctx, data);
4482 return done ? done : err;
4485 static inline void __io_unaccount_mem(struct user_struct *user,
4486 unsigned long nr_pages)
4488 atomic_long_sub(nr_pages, &user->locked_vm);
4491 static inline int __io_account_mem(struct user_struct *user,
4492 unsigned long nr_pages)
4494 unsigned long page_limit, cur_pages, new_pages;
4496 /* Don't allow more pages than we can safely lock */
4497 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4500 cur_pages = atomic_long_read(&user->locked_vm);
4501 new_pages = cur_pages + nr_pages;
4502 if (new_pages > page_limit)
4504 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4505 new_pages) != cur_pages);
4510 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
4513 __io_unaccount_mem(ctx->user, nr_pages);
4515 if (ctx->mm_account)
4516 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
4519 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
4524 ret = __io_account_mem(ctx->user, nr_pages);
4529 if (ctx->mm_account)
4530 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
4535 static void io_mem_free(void *ptr)
4542 page = virt_to_head_page(ptr);
4543 if (put_page_testzero(page))
4544 free_compound_page(page);
4547 static void *io_mem_alloc(size_t size)
4549 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
4551 return (void *) __get_free_pages(gfp, get_order(size));
4554 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
4555 unsigned int cq_entries, size_t *sq_offset)
4557 struct io_rings *rings;
4558 size_t off, sq_array_size;
4560 off = struct_size(rings, cqes, cq_entries);
4561 if (off == SIZE_MAX)
4563 if (ctx->flags & IORING_SETUP_CQE32) {
4564 if (check_shl_overflow(off, 1, &off))
4569 off = ALIGN(off, SMP_CACHE_BYTES);
4577 sq_array_size = array_size(sizeof(u32), sq_entries);
4578 if (sq_array_size == SIZE_MAX)
4581 if (check_add_overflow(off, sq_array_size, &off))
4587 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
4589 struct io_mapped_ubuf *imu = *slot;
4592 if (imu != ctx->dummy_ubuf) {
4593 for (i = 0; i < imu->nr_bvecs; i++)
4594 unpin_user_page(imu->bvec[i].bv_page);
4595 if (imu->acct_pages)
4596 io_unaccount_mem(ctx, imu->acct_pages);
4602 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
4604 io_buffer_unmap(ctx, &prsrc->buf);
4608 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
4612 for (i = 0; i < ctx->nr_user_bufs; i++)
4613 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
4614 kfree(ctx->user_bufs);
4615 io_rsrc_data_free(ctx->buf_data);
4616 ctx->user_bufs = NULL;
4617 ctx->buf_data = NULL;
4618 ctx->nr_user_bufs = 0;
4621 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
4623 unsigned nr = ctx->nr_user_bufs;
4630 * Quiesce may unlock ->uring_lock, and while it's not held
4631 * prevent new requests using the table.
4633 ctx->nr_user_bufs = 0;
4634 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
4635 ctx->nr_user_bufs = nr;
4637 __io_sqe_buffers_unregister(ctx);
4641 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4642 void __user *arg, unsigned index)
4644 struct iovec __user *src;
4646 #ifdef CONFIG_COMPAT
4648 struct compat_iovec __user *ciovs;
4649 struct compat_iovec ciov;
4651 ciovs = (struct compat_iovec __user *) arg;
4652 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4655 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
4656 dst->iov_len = ciov.iov_len;
4660 src = (struct iovec __user *) arg;
4661 if (copy_from_user(dst, &src[index], sizeof(*dst)))
4667 * Not super efficient, but this is just a registration time. And we do cache
4668 * the last compound head, so generally we'll only do a full search if we don't
4671 * We check if the given compound head page has already been accounted, to
4672 * avoid double accounting it. This allows us to account the full size of the
4673 * page, not just the constituent pages of a huge page.
4675 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
4676 int nr_pages, struct page *hpage)
4680 /* check current page array */
4681 for (i = 0; i < nr_pages; i++) {
4682 if (!PageCompound(pages[i]))
4684 if (compound_head(pages[i]) == hpage)
4688 /* check previously registered pages */
4689 for (i = 0; i < ctx->nr_user_bufs; i++) {
4690 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
4692 for (j = 0; j < imu->nr_bvecs; j++) {
4693 if (!PageCompound(imu->bvec[j].bv_page))
4695 if (compound_head(imu->bvec[j].bv_page) == hpage)
4703 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
4704 int nr_pages, struct io_mapped_ubuf *imu,
4705 struct page **last_hpage)
4709 imu->acct_pages = 0;
4710 for (i = 0; i < nr_pages; i++) {
4711 if (!PageCompound(pages[i])) {
4716 hpage = compound_head(pages[i]);
4717 if (hpage == *last_hpage)
4719 *last_hpage = hpage;
4720 if (headpage_already_acct(ctx, pages, i, hpage))
4722 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
4726 if (!imu->acct_pages)
4729 ret = io_account_mem(ctx, imu->acct_pages);
4731 imu->acct_pages = 0;
4735 struct page **io_pin_pages(unsigned long ubuf, unsigned long len, int *npages)
4737 unsigned long start, end, nr_pages;
4738 struct vm_area_struct **vmas = NULL;
4739 struct page **pages = NULL;
4740 int i, pret, ret = -ENOMEM;
4742 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4743 start = ubuf >> PAGE_SHIFT;
4744 nr_pages = end - start;
4746 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
4750 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
4756 mmap_read_lock(current->mm);
4757 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
4759 if (pret == nr_pages) {
4760 /* don't support file backed memory */
4761 for (i = 0; i < nr_pages; i++) {
4762 struct vm_area_struct *vma = vmas[i];
4764 if (vma_is_shmem(vma))
4767 !is_file_hugepages(vma->vm_file)) {
4774 ret = pret < 0 ? pret : -EFAULT;
4776 mmap_read_unlock(current->mm);
4779 * if we did partial map, or found file backed vmas,
4780 * release any pages we did get
4783 unpin_user_pages(pages, pret);
4791 pages = ERR_PTR(ret);
4796 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
4797 struct io_mapped_ubuf **pimu,
4798 struct page **last_hpage)
4800 struct io_mapped_ubuf *imu = NULL;
4801 struct page **pages = NULL;
4804 int ret, nr_pages, i;
4806 if (!iov->iov_base) {
4807 *pimu = ctx->dummy_ubuf;
4814 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
4816 if (IS_ERR(pages)) {
4817 ret = PTR_ERR(pages);
4822 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
4826 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
4828 unpin_user_pages(pages, nr_pages);
4832 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
4833 size = iov->iov_len;
4834 for (i = 0; i < nr_pages; i++) {
4837 vec_len = min_t(size_t, size, PAGE_SIZE - off);
4838 imu->bvec[i].bv_page = pages[i];
4839 imu->bvec[i].bv_len = vec_len;
4840 imu->bvec[i].bv_offset = off;
4844 /* store original address for later verification */
4845 imu->ubuf = (unsigned long) iov->iov_base;
4846 imu->ubuf_end = imu->ubuf + iov->iov_len;
4847 imu->nr_bvecs = nr_pages;
4857 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
4859 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
4860 return ctx->user_bufs ? 0 : -ENOMEM;
4863 static int io_buffer_validate(struct iovec *iov)
4865 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
4868 * Don't impose further limits on the size and buffer
4869 * constraints here, we'll -EINVAL later when IO is
4870 * submitted if they are wrong.
4873 return iov->iov_len ? -EFAULT : 0;
4877 /* arbitrary limit, but we need something */
4878 if (iov->iov_len > SZ_1G)
4881 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
4887 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
4888 unsigned int nr_args, u64 __user *tags)
4890 struct page *last_hpage = NULL;
4891 struct io_rsrc_data *data;
4897 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
4899 ret = io_rsrc_node_switch_start(ctx);
4902 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
4905 ret = io_buffers_map_alloc(ctx, nr_args);
4907 io_rsrc_data_free(data);
4911 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
4913 ret = io_copy_iov(ctx, &iov, arg, i);
4916 ret = io_buffer_validate(&iov);
4920 memset(&iov, 0, sizeof(iov));
4923 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
4928 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
4934 WARN_ON_ONCE(ctx->buf_data);
4936 ctx->buf_data = data;
4938 __io_sqe_buffers_unregister(ctx);
4940 io_rsrc_node_switch(ctx, NULL);
4944 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
4945 struct io_uring_rsrc_update2 *up,
4946 unsigned int nr_args)
4948 u64 __user *tags = u64_to_user_ptr(up->tags);
4949 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
4950 struct page *last_hpage = NULL;
4951 bool needs_switch = false;
4957 if (up->offset + nr_args > ctx->nr_user_bufs)
4960 for (done = 0; done < nr_args; done++) {
4961 struct io_mapped_ubuf *imu;
4962 int offset = up->offset + done;
4965 err = io_copy_iov(ctx, &iov, iovs, done);
4968 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
4972 err = io_buffer_validate(&iov);
4975 if (!iov.iov_base && tag) {
4979 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
4983 i = array_index_nospec(offset, ctx->nr_user_bufs);
4984 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
4985 err = io_queue_rsrc_removal(ctx->buf_data, i,
4986 ctx->rsrc_node, ctx->user_bufs[i]);
4987 if (unlikely(err)) {
4988 io_buffer_unmap(ctx, &imu);
4991 ctx->user_bufs[i] = NULL;
4992 needs_switch = true;
4995 ctx->user_bufs[i] = imu;
4996 *io_get_tag_slot(ctx->buf_data, offset) = tag;
5000 io_rsrc_node_switch(ctx, ctx->buf_data);
5001 return done ? done : err;
5004 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
5005 unsigned int eventfd_async)
5007 struct io_ev_fd *ev_fd;
5008 __s32 __user *fds = arg;
5011 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5012 lockdep_is_held(&ctx->uring_lock));
5016 if (copy_from_user(&fd, fds, sizeof(*fds)))
5019 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
5023 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
5024 if (IS_ERR(ev_fd->cq_ev_fd)) {
5025 int ret = PTR_ERR(ev_fd->cq_ev_fd);
5029 ev_fd->eventfd_async = eventfd_async;
5030 ctx->has_evfd = true;
5031 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
5035 static void io_eventfd_put(struct rcu_head *rcu)
5037 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
5039 eventfd_ctx_put(ev_fd->cq_ev_fd);
5043 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
5045 struct io_ev_fd *ev_fd;
5047 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5048 lockdep_is_held(&ctx->uring_lock));
5050 ctx->has_evfd = false;
5051 rcu_assign_pointer(ctx->io_ev_fd, NULL);
5052 call_rcu(&ev_fd->rcu, io_eventfd_put);
5059 static void io_req_caches_free(struct io_ring_ctx *ctx)
5061 struct io_submit_state *state = &ctx->submit_state;
5064 mutex_lock(&ctx->uring_lock);
5065 io_flush_cached_locked_reqs(ctx, state);
5067 while (!io_req_cache_empty(ctx)) {
5068 struct io_wq_work_node *node;
5069 struct io_kiocb *req;
5071 node = wq_stack_extract(&state->free_list);
5072 req = container_of(node, struct io_kiocb, comp_list);
5073 kmem_cache_free(req_cachep, req);
5077 percpu_ref_put_many(&ctx->refs, nr);
5078 mutex_unlock(&ctx->uring_lock);
5081 static void io_wait_rsrc_data(struct io_rsrc_data *data)
5083 if (data && !atomic_dec_and_test(&data->refs))
5084 wait_for_completion(&data->done);
5087 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
5089 struct async_poll *apoll;
5091 while (!list_empty(&ctx->apoll_cache)) {
5092 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
5094 list_del(&apoll->poll.wait.entry);
5099 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
5101 io_sq_thread_finish(ctx);
5103 if (ctx->mm_account) {
5104 mmdrop(ctx->mm_account);
5105 ctx->mm_account = NULL;
5108 io_rsrc_refs_drop(ctx);
5109 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
5110 io_wait_rsrc_data(ctx->buf_data);
5111 io_wait_rsrc_data(ctx->file_data);
5113 mutex_lock(&ctx->uring_lock);
5115 __io_sqe_buffers_unregister(ctx);
5117 __io_sqe_files_unregister(ctx);
5119 __io_cqring_overflow_flush(ctx, true);
5120 io_eventfd_unregister(ctx);
5121 io_flush_apoll_cache(ctx);
5122 mutex_unlock(&ctx->uring_lock);
5123 io_destroy_buffers(ctx);
5125 put_cred(ctx->sq_creds);
5127 /* there are no registered resources left, nobody uses it */
5129 io_rsrc_node_destroy(ctx->rsrc_node);
5130 if (ctx->rsrc_backup_node)
5131 io_rsrc_node_destroy(ctx->rsrc_backup_node);
5132 flush_delayed_work(&ctx->rsrc_put_work);
5133 flush_delayed_work(&ctx->fallback_work);
5135 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
5136 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
5138 #if defined(CONFIG_UNIX)
5139 if (ctx->ring_sock) {
5140 ctx->ring_sock->file = NULL; /* so that iput() is called */
5141 sock_release(ctx->ring_sock);
5144 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
5146 io_mem_free(ctx->rings);
5147 io_mem_free(ctx->sq_sqes);
5149 percpu_ref_exit(&ctx->refs);
5150 free_uid(ctx->user);
5151 io_req_caches_free(ctx);
5153 io_wq_put_hash(ctx->hash_map);
5154 kfree(ctx->cancel_hash);
5155 kfree(ctx->dummy_ubuf);
5157 xa_destroy(&ctx->io_bl_xa);
5161 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
5163 struct io_ring_ctx *ctx = file->private_data;
5166 poll_wait(file, &ctx->cq_wait, wait);
5168 * synchronizes with barrier from wq_has_sleeper call in
5172 if (!io_sqring_full(ctx))
5173 mask |= EPOLLOUT | EPOLLWRNORM;
5176 * Don't flush cqring overflow list here, just do a simple check.
5177 * Otherwise there could possible be ABBA deadlock:
5180 * lock(&ctx->uring_lock);
5182 * lock(&ctx->uring_lock);
5185 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
5186 * pushs them to do the flush.
5188 if (io_cqring_events(ctx) ||
5189 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
5190 mask |= EPOLLIN | EPOLLRDNORM;
5195 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
5197 const struct cred *creds;
5199 creds = xa_erase(&ctx->personalities, id);
5208 struct io_tctx_exit {
5209 struct callback_head task_work;
5210 struct completion completion;
5211 struct io_ring_ctx *ctx;
5214 static __cold void io_tctx_exit_cb(struct callback_head *cb)
5216 struct io_uring_task *tctx = current->io_uring;
5217 struct io_tctx_exit *work;
5219 work = container_of(cb, struct io_tctx_exit, task_work);
5221 * When @in_idle, we're in cancellation and it's racy to remove the
5222 * node. It'll be removed by the end of cancellation, just ignore it.
5224 if (!atomic_read(&tctx->in_idle))
5225 io_uring_del_tctx_node((unsigned long)work->ctx);
5226 complete(&work->completion);
5229 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
5231 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5233 return req->ctx == data;
5236 static __cold void io_ring_exit_work(struct work_struct *work)
5238 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
5239 unsigned long timeout = jiffies + HZ * 60 * 5;
5240 unsigned long interval = HZ / 20;
5241 struct io_tctx_exit exit;
5242 struct io_tctx_node *node;
5246 * If we're doing polled IO and end up having requests being
5247 * submitted async (out-of-line), then completions can come in while
5248 * we're waiting for refs to drop. We need to reap these manually,
5249 * as nobody else will be looking for them.
5252 io_uring_try_cancel_requests(ctx, NULL, true);
5254 struct io_sq_data *sqd = ctx->sq_data;
5255 struct task_struct *tsk;
5257 io_sq_thread_park(sqd);
5259 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
5260 io_wq_cancel_cb(tsk->io_uring->io_wq,
5261 io_cancel_ctx_cb, ctx, true);
5262 io_sq_thread_unpark(sqd);
5265 io_req_caches_free(ctx);
5267 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
5268 /* there is little hope left, don't run it too often */
5271 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
5273 init_completion(&exit.completion);
5274 init_task_work(&exit.task_work, io_tctx_exit_cb);
5277 * Some may use context even when all refs and requests have been put,
5278 * and they are free to do so while still holding uring_lock or
5279 * completion_lock, see io_req_task_submit(). Apart from other work,
5280 * this lock/unlock section also waits them to finish.
5282 mutex_lock(&ctx->uring_lock);
5283 while (!list_empty(&ctx->tctx_list)) {
5284 WARN_ON_ONCE(time_after(jiffies, timeout));
5286 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
5288 /* don't spin on a single task if cancellation failed */
5289 list_rotate_left(&ctx->tctx_list);
5290 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
5291 if (WARN_ON_ONCE(ret))
5294 mutex_unlock(&ctx->uring_lock);
5295 wait_for_completion(&exit.completion);
5296 mutex_lock(&ctx->uring_lock);
5298 mutex_unlock(&ctx->uring_lock);
5299 spin_lock(&ctx->completion_lock);
5300 spin_unlock(&ctx->completion_lock);
5302 io_ring_ctx_free(ctx);
5305 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
5307 unsigned long index;
5308 struct creds *creds;
5310 mutex_lock(&ctx->uring_lock);
5311 percpu_ref_kill(&ctx->refs);
5313 __io_cqring_overflow_flush(ctx, true);
5314 xa_for_each(&ctx->personalities, index, creds)
5315 io_unregister_personality(ctx, index);
5316 mutex_unlock(&ctx->uring_lock);
5318 /* failed during ring init, it couldn't have issued any requests */
5320 io_kill_timeouts(ctx, NULL, true);
5321 io_poll_remove_all(ctx, NULL, true);
5322 /* if we failed setting up the ctx, we might not have any rings */
5323 io_iopoll_try_reap_events(ctx);
5326 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
5328 * Use system_unbound_wq to avoid spawning tons of event kworkers
5329 * if we're exiting a ton of rings at the same time. It just adds
5330 * noise and overhead, there's no discernable change in runtime
5331 * over using system_wq.
5333 queue_work(system_unbound_wq, &ctx->exit_work);
5336 static int io_uring_release(struct inode *inode, struct file *file)
5338 struct io_ring_ctx *ctx = file->private_data;
5340 file->private_data = NULL;
5341 io_ring_ctx_wait_and_kill(ctx);
5345 struct io_task_cancel {
5346 struct task_struct *task;
5350 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
5352 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5353 struct io_task_cancel *cancel = data;
5355 return io_match_task_safe(req, cancel->task, cancel->all);
5358 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
5359 struct task_struct *task,
5362 struct io_defer_entry *de;
5365 spin_lock(&ctx->completion_lock);
5366 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
5367 if (io_match_task_safe(de->req, task, cancel_all)) {
5368 list_cut_position(&list, &ctx->defer_list, &de->list);
5372 spin_unlock(&ctx->completion_lock);
5373 if (list_empty(&list))
5376 while (!list_empty(&list)) {
5377 de = list_first_entry(&list, struct io_defer_entry, list);
5378 list_del_init(&de->list);
5379 io_req_complete_failed(de->req, -ECANCELED);
5385 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
5387 struct io_tctx_node *node;
5388 enum io_wq_cancel cret;
5391 mutex_lock(&ctx->uring_lock);
5392 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5393 struct io_uring_task *tctx = node->task->io_uring;
5396 * io_wq will stay alive while we hold uring_lock, because it's
5397 * killed after ctx nodes, which requires to take the lock.
5399 if (!tctx || !tctx->io_wq)
5401 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
5402 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
5404 mutex_unlock(&ctx->uring_lock);
5409 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
5410 struct task_struct *task,
5413 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
5414 struct io_uring_task *tctx = task ? task->io_uring : NULL;
5416 /* failed during ring init, it couldn't have issued any requests */
5421 enum io_wq_cancel cret;
5425 ret |= io_uring_try_cancel_iowq(ctx);
5426 } else if (tctx && tctx->io_wq) {
5428 * Cancels requests of all rings, not only @ctx, but
5429 * it's fine as the task is in exit/exec.
5431 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
5433 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
5436 /* SQPOLL thread does its own polling */
5437 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
5438 (ctx->sq_data && ctx->sq_data->thread == current)) {
5439 while (!wq_list_empty(&ctx->iopoll_list)) {
5440 io_iopoll_try_reap_events(ctx);
5445 ret |= io_cancel_defer_files(ctx, task, cancel_all);
5446 ret |= io_poll_remove_all(ctx, task, cancel_all);
5447 ret |= io_kill_timeouts(ctx, task, cancel_all);
5449 ret |= io_run_task_work();
5456 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
5459 return atomic_read(&tctx->inflight_tracked);
5460 return percpu_counter_sum(&tctx->inflight);
5464 * Find any io_uring ctx that this task has registered or done IO on, and cancel
5465 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
5467 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
5469 struct io_uring_task *tctx = current->io_uring;
5470 struct io_ring_ctx *ctx;
5474 WARN_ON_ONCE(sqd && sqd->thread != current);
5476 if (!current->io_uring)
5479 io_wq_exit_start(tctx->io_wq);
5481 atomic_inc(&tctx->in_idle);
5483 io_uring_drop_tctx_refs(current);
5484 /* read completions before cancelations */
5485 inflight = tctx_inflight(tctx, !cancel_all);
5490 struct io_tctx_node *node;
5491 unsigned long index;
5493 xa_for_each(&tctx->xa, index, node) {
5494 /* sqpoll task will cancel all its requests */
5495 if (node->ctx->sq_data)
5497 io_uring_try_cancel_requests(node->ctx, current,
5501 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
5502 io_uring_try_cancel_requests(ctx, current,
5506 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
5508 io_uring_drop_tctx_refs(current);
5511 * If we've seen completions, retry without waiting. This
5512 * avoids a race where a completion comes in before we did
5513 * prepare_to_wait().
5515 if (inflight == tctx_inflight(tctx, !cancel_all))
5517 finish_wait(&tctx->wait, &wait);
5520 io_uring_clean_tctx(tctx);
5523 * We shouldn't run task_works after cancel, so just leave
5524 * ->in_idle set for normal exit.
5526 atomic_dec(&tctx->in_idle);
5527 /* for exec all current's requests should be gone, kill tctx */
5528 __io_uring_free(current);
5532 void __io_uring_cancel(bool cancel_all)
5534 io_uring_cancel_generic(cancel_all, NULL);
5537 static void *io_uring_validate_mmap_request(struct file *file,
5538 loff_t pgoff, size_t sz)
5540 struct io_ring_ctx *ctx = file->private_data;
5541 loff_t offset = pgoff << PAGE_SHIFT;
5546 case IORING_OFF_SQ_RING:
5547 case IORING_OFF_CQ_RING:
5550 case IORING_OFF_SQES:
5554 return ERR_PTR(-EINVAL);
5557 page = virt_to_head_page(ptr);
5558 if (sz > page_size(page))
5559 return ERR_PTR(-EINVAL);
5566 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5568 size_t sz = vma->vm_end - vma->vm_start;
5572 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
5574 return PTR_ERR(ptr);
5576 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
5577 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
5580 #else /* !CONFIG_MMU */
5582 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5584 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
5587 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
5589 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
5592 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
5593 unsigned long addr, unsigned long len,
5594 unsigned long pgoff, unsigned long flags)
5598 ptr = io_uring_validate_mmap_request(file, pgoff, len);
5600 return PTR_ERR(ptr);
5602 return (unsigned long) ptr;
5605 #endif /* !CONFIG_MMU */
5607 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
5609 if (flags & IORING_ENTER_EXT_ARG) {
5610 struct io_uring_getevents_arg arg;
5612 if (argsz != sizeof(arg))
5614 if (copy_from_user(&arg, argp, sizeof(arg)))
5620 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
5621 struct __kernel_timespec __user **ts,
5622 const sigset_t __user **sig)
5624 struct io_uring_getevents_arg arg;
5627 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
5628 * is just a pointer to the sigset_t.
5630 if (!(flags & IORING_ENTER_EXT_ARG)) {
5631 *sig = (const sigset_t __user *) argp;
5637 * EXT_ARG is set - ensure we agree on the size of it and copy in our
5638 * timespec and sigset_t pointers if good.
5640 if (*argsz != sizeof(arg))
5642 if (copy_from_user(&arg, argp, sizeof(arg)))
5646 *sig = u64_to_user_ptr(arg.sigmask);
5647 *argsz = arg.sigmask_sz;
5648 *ts = u64_to_user_ptr(arg.ts);
5652 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
5653 u32, min_complete, u32, flags, const void __user *, argp,
5656 struct io_ring_ctx *ctx;
5662 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
5663 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
5664 IORING_ENTER_REGISTERED_RING)))
5668 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
5669 * need only dereference our task private array to find it.
5671 if (flags & IORING_ENTER_REGISTERED_RING) {
5672 struct io_uring_task *tctx = current->io_uring;
5674 if (!tctx || fd >= IO_RINGFD_REG_MAX)
5676 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
5677 f.file = tctx->registered_rings[fd];
5683 if (unlikely(!f.file))
5687 if (unlikely(!io_is_uring_fops(f.file)))
5691 ctx = f.file->private_data;
5692 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
5696 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
5700 * For SQ polling, the thread will do all submissions and completions.
5701 * Just return the requested submit count, and wake the thread if
5705 if (ctx->flags & IORING_SETUP_SQPOLL) {
5706 io_cqring_overflow_flush(ctx);
5708 if (unlikely(ctx->sq_data->thread == NULL)) {
5712 if (flags & IORING_ENTER_SQ_WAKEUP)
5713 wake_up(&ctx->sq_data->wait);
5714 if (flags & IORING_ENTER_SQ_WAIT) {
5715 ret = io_sqpoll_wait_sq(ctx);
5720 } else if (to_submit) {
5721 ret = io_uring_add_tctx_node(ctx);
5725 mutex_lock(&ctx->uring_lock);
5726 ret = io_submit_sqes(ctx, to_submit);
5727 if (ret != to_submit) {
5728 mutex_unlock(&ctx->uring_lock);
5731 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
5733 mutex_unlock(&ctx->uring_lock);
5735 if (flags & IORING_ENTER_GETEVENTS) {
5737 if (ctx->syscall_iopoll) {
5739 * We disallow the app entering submit/complete with
5740 * polling, but we still need to lock the ring to
5741 * prevent racing with polled issue that got punted to
5744 mutex_lock(&ctx->uring_lock);
5746 ret2 = io_validate_ext_arg(flags, argp, argsz);
5747 if (likely(!ret2)) {
5748 min_complete = min(min_complete,
5750 ret2 = io_iopoll_check(ctx, min_complete);
5752 mutex_unlock(&ctx->uring_lock);
5754 const sigset_t __user *sig;
5755 struct __kernel_timespec __user *ts;
5757 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
5758 if (likely(!ret2)) {
5759 min_complete = min(min_complete,
5761 ret2 = io_cqring_wait(ctx, min_complete, sig,
5770 * EBADR indicates that one or more CQE were dropped.
5771 * Once the user has been informed we can clear the bit
5772 * as they are obviously ok with those drops.
5774 if (unlikely(ret2 == -EBADR))
5775 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
5781 percpu_ref_put(&ctx->refs);
5787 static const struct file_operations io_uring_fops = {
5788 .release = io_uring_release,
5789 .mmap = io_uring_mmap,
5791 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
5792 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
5794 .poll = io_uring_poll,
5795 #ifdef CONFIG_PROC_FS
5796 .show_fdinfo = io_uring_show_fdinfo,
5800 bool io_is_uring_fops(struct file *file)
5802 return file->f_op == &io_uring_fops;
5805 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
5806 struct io_uring_params *p)
5808 struct io_rings *rings;
5809 size_t size, sq_array_offset;
5811 /* make sure these are sane, as we already accounted them */
5812 ctx->sq_entries = p->sq_entries;
5813 ctx->cq_entries = p->cq_entries;
5815 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
5816 if (size == SIZE_MAX)
5819 rings = io_mem_alloc(size);
5824 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
5825 rings->sq_ring_mask = p->sq_entries - 1;
5826 rings->cq_ring_mask = p->cq_entries - 1;
5827 rings->sq_ring_entries = p->sq_entries;
5828 rings->cq_ring_entries = p->cq_entries;
5830 if (p->flags & IORING_SETUP_SQE128)
5831 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
5833 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
5834 if (size == SIZE_MAX) {
5835 io_mem_free(ctx->rings);
5840 ctx->sq_sqes = io_mem_alloc(size);
5841 if (!ctx->sq_sqes) {
5842 io_mem_free(ctx->rings);
5850 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
5854 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
5858 ret = io_uring_add_tctx_node(ctx);
5863 fd_install(fd, file);
5868 * Allocate an anonymous fd, this is what constitutes the application
5869 * visible backing of an io_uring instance. The application mmaps this
5870 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
5871 * we have to tie this fd to a socket for file garbage collection purposes.
5873 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
5876 #if defined(CONFIG_UNIX)
5879 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
5882 return ERR_PTR(ret);
5885 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
5886 O_RDWR | O_CLOEXEC, NULL);
5887 #if defined(CONFIG_UNIX)
5889 sock_release(ctx->ring_sock);
5890 ctx->ring_sock = NULL;
5892 ctx->ring_sock->file = file;
5898 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
5899 struct io_uring_params __user *params)
5901 struct io_ring_ctx *ctx;
5907 if (entries > IORING_MAX_ENTRIES) {
5908 if (!(p->flags & IORING_SETUP_CLAMP))
5910 entries = IORING_MAX_ENTRIES;
5914 * Use twice as many entries for the CQ ring. It's possible for the
5915 * application to drive a higher depth than the size of the SQ ring,
5916 * since the sqes are only used at submission time. This allows for
5917 * some flexibility in overcommitting a bit. If the application has
5918 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
5919 * of CQ ring entries manually.
5921 p->sq_entries = roundup_pow_of_two(entries);
5922 if (p->flags & IORING_SETUP_CQSIZE) {
5924 * If IORING_SETUP_CQSIZE is set, we do the same roundup
5925 * to a power-of-two, if it isn't already. We do NOT impose
5926 * any cq vs sq ring sizing.
5930 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
5931 if (!(p->flags & IORING_SETUP_CLAMP))
5933 p->cq_entries = IORING_MAX_CQ_ENTRIES;
5935 p->cq_entries = roundup_pow_of_two(p->cq_entries);
5936 if (p->cq_entries < p->sq_entries)
5939 p->cq_entries = 2 * p->sq_entries;
5942 ctx = io_ring_ctx_alloc(p);
5947 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
5948 * space applications don't need to do io completion events
5949 * polling again, they can rely on io_sq_thread to do polling
5950 * work, which can reduce cpu usage and uring_lock contention.
5952 if (ctx->flags & IORING_SETUP_IOPOLL &&
5953 !(ctx->flags & IORING_SETUP_SQPOLL))
5954 ctx->syscall_iopoll = 1;
5956 ctx->compat = in_compat_syscall();
5957 if (!capable(CAP_IPC_LOCK))
5958 ctx->user = get_uid(current_user());
5961 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
5962 * COOP_TASKRUN is set, then IPIs are never needed by the app.
5965 if (ctx->flags & IORING_SETUP_SQPOLL) {
5966 /* IPI related flags don't make sense with SQPOLL */
5967 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
5968 IORING_SETUP_TASKRUN_FLAG))
5970 ctx->notify_method = TWA_SIGNAL_NO_IPI;
5971 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
5972 ctx->notify_method = TWA_SIGNAL_NO_IPI;
5974 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
5976 ctx->notify_method = TWA_SIGNAL;
5980 * This is just grabbed for accounting purposes. When a process exits,
5981 * the mm is exited and dropped before the files, hence we need to hang
5982 * on to this mm purely for the purposes of being able to unaccount
5983 * memory (locked/pinned vm). It's not used for anything else.
5985 mmgrab(current->mm);
5986 ctx->mm_account = current->mm;
5988 ret = io_allocate_scq_urings(ctx, p);
5992 ret = io_sq_offload_create(ctx, p);
5995 /* always set a rsrc node */
5996 ret = io_rsrc_node_switch_start(ctx);
5999 io_rsrc_node_switch(ctx, NULL);
6001 memset(&p->sq_off, 0, sizeof(p->sq_off));
6002 p->sq_off.head = offsetof(struct io_rings, sq.head);
6003 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6004 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6005 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6006 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6007 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6008 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6010 memset(&p->cq_off, 0, sizeof(p->cq_off));
6011 p->cq_off.head = offsetof(struct io_rings, cq.head);
6012 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6013 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6014 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6015 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6016 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6017 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
6019 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6020 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6021 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
6022 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
6023 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
6024 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
6025 IORING_FEAT_LINKED_FILE;
6027 if (copy_to_user(params, p, sizeof(*p))) {
6032 file = io_uring_get_file(ctx);
6034 ret = PTR_ERR(file);
6039 * Install ring fd as the very last thing, so we don't risk someone
6040 * having closed it before we finish setup
6042 ret = io_uring_install_fd(ctx, file);
6044 /* fput will clean it up */
6049 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6052 io_ring_ctx_wait_and_kill(ctx);
6057 * Sets up an aio uring context, and returns the fd. Applications asks for a
6058 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6059 * params structure passed in.
6061 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6063 struct io_uring_params p;
6066 if (copy_from_user(&p, params, sizeof(p)))
6068 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6073 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6074 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6075 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
6076 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
6077 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
6078 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
6081 return io_uring_create(entries, &p, params);
6084 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6085 struct io_uring_params __user *, params)
6087 return io_uring_setup(entries, params);
6090 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
6093 struct io_uring_probe *p;
6097 size = struct_size(p, ops, nr_args);
6098 if (size == SIZE_MAX)
6100 p = kzalloc(size, GFP_KERNEL);
6105 if (copy_from_user(p, arg, size))
6108 if (memchr_inv(p, 0, size))
6111 p->last_op = IORING_OP_LAST - 1;
6112 if (nr_args > IORING_OP_LAST)
6113 nr_args = IORING_OP_LAST;
6115 for (i = 0; i < nr_args; i++) {
6117 if (!io_op_defs[i].not_supported)
6118 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6123 if (copy_to_user(arg, p, size))
6130 static int io_register_personality(struct io_ring_ctx *ctx)
6132 const struct cred *creds;
6136 creds = get_current_cred();
6138 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
6139 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
6147 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
6148 void __user *arg, unsigned int nr_args)
6150 struct io_uring_restriction *res;
6154 /* Restrictions allowed only if rings started disabled */
6155 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6158 /* We allow only a single restrictions registration */
6159 if (ctx->restrictions.registered)
6162 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
6165 size = array_size(nr_args, sizeof(*res));
6166 if (size == SIZE_MAX)
6169 res = memdup_user(arg, size);
6171 return PTR_ERR(res);
6175 for (i = 0; i < nr_args; i++) {
6176 switch (res[i].opcode) {
6177 case IORING_RESTRICTION_REGISTER_OP:
6178 if (res[i].register_op >= IORING_REGISTER_LAST) {
6183 __set_bit(res[i].register_op,
6184 ctx->restrictions.register_op);
6186 case IORING_RESTRICTION_SQE_OP:
6187 if (res[i].sqe_op >= IORING_OP_LAST) {
6192 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
6194 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
6195 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
6197 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
6198 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
6207 /* Reset all restrictions if an error happened */
6209 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
6211 ctx->restrictions.registered = true;
6217 static int io_register_enable_rings(struct io_ring_ctx *ctx)
6219 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6222 if (ctx->restrictions.registered)
6223 ctx->restricted = 1;
6225 ctx->flags &= ~IORING_SETUP_R_DISABLED;
6226 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
6227 wake_up(&ctx->sq_data->wait);
6231 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
6232 struct io_uring_rsrc_update2 *up,
6238 if (check_add_overflow(up->offset, nr_args, &tmp))
6240 err = io_rsrc_node_switch_start(ctx);
6245 case IORING_RSRC_FILE:
6246 return __io_sqe_files_update(ctx, up, nr_args);
6247 case IORING_RSRC_BUFFER:
6248 return __io_sqe_buffers_update(ctx, up, nr_args);
6253 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
6256 struct io_uring_rsrc_update2 up;
6260 memset(&up, 0, sizeof(up));
6261 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
6263 if (up.resv || up.resv2)
6265 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
6268 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
6269 unsigned size, unsigned type)
6271 struct io_uring_rsrc_update2 up;
6273 if (size != sizeof(up))
6275 if (copy_from_user(&up, arg, sizeof(up)))
6277 if (!up.nr || up.resv || up.resv2)
6279 return __io_register_rsrc_update(ctx, type, &up, up.nr);
6282 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
6283 unsigned int size, unsigned int type)
6285 struct io_uring_rsrc_register rr;
6287 /* keep it extendible */
6288 if (size != sizeof(rr))
6291 memset(&rr, 0, sizeof(rr));
6292 if (copy_from_user(&rr, arg, size))
6294 if (!rr.nr || rr.resv2)
6296 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
6300 case IORING_RSRC_FILE:
6301 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6303 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
6304 rr.nr, u64_to_user_ptr(rr.tags));
6305 case IORING_RSRC_BUFFER:
6306 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6308 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
6309 rr.nr, u64_to_user_ptr(rr.tags));
6314 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
6315 void __user *arg, unsigned len)
6317 struct io_uring_task *tctx = current->io_uring;
6318 cpumask_var_t new_mask;
6321 if (!tctx || !tctx->io_wq)
6324 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6327 cpumask_clear(new_mask);
6328 if (len > cpumask_size())
6329 len = cpumask_size();
6331 if (in_compat_syscall()) {
6332 ret = compat_get_bitmap(cpumask_bits(new_mask),
6333 (const compat_ulong_t __user *)arg,
6334 len * 8 /* CHAR_BIT */);
6336 ret = copy_from_user(new_mask, arg, len);
6340 free_cpumask_var(new_mask);
6344 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
6345 free_cpumask_var(new_mask);
6349 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
6351 struct io_uring_task *tctx = current->io_uring;
6353 if (!tctx || !tctx->io_wq)
6356 return io_wq_cpu_affinity(tctx->io_wq, NULL);
6359 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
6361 __must_hold(&ctx->uring_lock)
6363 struct io_tctx_node *node;
6364 struct io_uring_task *tctx = NULL;
6365 struct io_sq_data *sqd = NULL;
6369 if (copy_from_user(new_count, arg, sizeof(new_count)))
6371 for (i = 0; i < ARRAY_SIZE(new_count); i++)
6372 if (new_count[i] > INT_MAX)
6375 if (ctx->flags & IORING_SETUP_SQPOLL) {
6379 * Observe the correct sqd->lock -> ctx->uring_lock
6380 * ordering. Fine to drop uring_lock here, we hold
6383 refcount_inc(&sqd->refs);
6384 mutex_unlock(&ctx->uring_lock);
6385 mutex_lock(&sqd->lock);
6386 mutex_lock(&ctx->uring_lock);
6388 tctx = sqd->thread->io_uring;
6391 tctx = current->io_uring;
6394 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
6396 for (i = 0; i < ARRAY_SIZE(new_count); i++)
6398 ctx->iowq_limits[i] = new_count[i];
6399 ctx->iowq_limits_set = true;
6401 if (tctx && tctx->io_wq) {
6402 ret = io_wq_max_workers(tctx->io_wq, new_count);
6406 memset(new_count, 0, sizeof(new_count));
6410 mutex_unlock(&sqd->lock);
6411 io_put_sq_data(sqd);
6414 if (copy_to_user(arg, new_count, sizeof(new_count)))
6417 /* that's it for SQPOLL, only the SQPOLL task creates requests */
6421 /* now propagate the restriction to all registered users */
6422 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6423 struct io_uring_task *tctx = node->task->io_uring;
6425 if (WARN_ON_ONCE(!tctx->io_wq))
6428 for (i = 0; i < ARRAY_SIZE(new_count); i++)
6429 new_count[i] = ctx->iowq_limits[i];
6430 /* ignore errors, it always returns zero anyway */
6431 (void)io_wq_max_workers(tctx->io_wq, new_count);
6436 mutex_unlock(&sqd->lock);
6437 io_put_sq_data(sqd);
6442 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6443 void __user *arg, unsigned nr_args)
6444 __releases(ctx->uring_lock)
6445 __acquires(ctx->uring_lock)
6450 * We're inside the ring mutex, if the ref is already dying, then
6451 * someone else killed the ctx or is already going through
6452 * io_uring_register().
6454 if (percpu_ref_is_dying(&ctx->refs))
6457 if (ctx->restricted) {
6458 if (opcode >= IORING_REGISTER_LAST)
6460 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
6461 if (!test_bit(opcode, ctx->restrictions.register_op))
6466 case IORING_REGISTER_BUFFERS:
6470 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
6472 case IORING_UNREGISTER_BUFFERS:
6476 ret = io_sqe_buffers_unregister(ctx);
6478 case IORING_REGISTER_FILES:
6482 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
6484 case IORING_UNREGISTER_FILES:
6488 ret = io_sqe_files_unregister(ctx);
6490 case IORING_REGISTER_FILES_UPDATE:
6491 ret = io_register_files_update(ctx, arg, nr_args);
6493 case IORING_REGISTER_EVENTFD:
6497 ret = io_eventfd_register(ctx, arg, 0);
6499 case IORING_REGISTER_EVENTFD_ASYNC:
6503 ret = io_eventfd_register(ctx, arg, 1);
6505 case IORING_UNREGISTER_EVENTFD:
6509 ret = io_eventfd_unregister(ctx);
6511 case IORING_REGISTER_PROBE:
6513 if (!arg || nr_args > 256)
6515 ret = io_probe(ctx, arg, nr_args);
6517 case IORING_REGISTER_PERSONALITY:
6521 ret = io_register_personality(ctx);
6523 case IORING_UNREGISTER_PERSONALITY:
6527 ret = io_unregister_personality(ctx, nr_args);
6529 case IORING_REGISTER_ENABLE_RINGS:
6533 ret = io_register_enable_rings(ctx);
6535 case IORING_REGISTER_RESTRICTIONS:
6536 ret = io_register_restrictions(ctx, arg, nr_args);
6538 case IORING_REGISTER_FILES2:
6539 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
6541 case IORING_REGISTER_FILES_UPDATE2:
6542 ret = io_register_rsrc_update(ctx, arg, nr_args,
6545 case IORING_REGISTER_BUFFERS2:
6546 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
6548 case IORING_REGISTER_BUFFERS_UPDATE:
6549 ret = io_register_rsrc_update(ctx, arg, nr_args,
6550 IORING_RSRC_BUFFER);
6552 case IORING_REGISTER_IOWQ_AFF:
6554 if (!arg || !nr_args)
6556 ret = io_register_iowq_aff(ctx, arg, nr_args);
6558 case IORING_UNREGISTER_IOWQ_AFF:
6562 ret = io_unregister_iowq_aff(ctx);
6564 case IORING_REGISTER_IOWQ_MAX_WORKERS:
6566 if (!arg || nr_args != 2)
6568 ret = io_register_iowq_max_workers(ctx, arg);
6570 case IORING_REGISTER_RING_FDS:
6571 ret = io_ringfd_register(ctx, arg, nr_args);
6573 case IORING_UNREGISTER_RING_FDS:
6574 ret = io_ringfd_unregister(ctx, arg, nr_args);
6576 case IORING_REGISTER_PBUF_RING:
6578 if (!arg || nr_args != 1)
6580 ret = io_register_pbuf_ring(ctx, arg);
6582 case IORING_UNREGISTER_PBUF_RING:
6584 if (!arg || nr_args != 1)
6586 ret = io_unregister_pbuf_ring(ctx, arg);
6596 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
6597 void __user *, arg, unsigned int, nr_args)
6599 struct io_ring_ctx *ctx;
6608 if (!io_is_uring_fops(f.file))
6611 ctx = f.file->private_data;
6615 mutex_lock(&ctx->uring_lock);
6616 ret = __io_uring_register(ctx, opcode, arg, nr_args);
6617 mutex_unlock(&ctx->uring_lock);
6618 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
6624 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
6630 const struct io_op_def io_op_defs[] = {
6635 .prep = io_nop_prep,
6638 [IORING_OP_READV] = {
6640 .unbound_nonreg_file = 1,
6647 .async_size = sizeof(struct io_async_rw),
6651 .prep_async = io_readv_prep_async,
6652 .cleanup = io_readv_writev_cleanup,
6654 [IORING_OP_WRITEV] = {
6657 .unbound_nonreg_file = 1,
6663 .async_size = sizeof(struct io_async_rw),
6667 .prep_async = io_writev_prep_async,
6668 .cleanup = io_readv_writev_cleanup,
6670 [IORING_OP_FSYNC] = {
6674 .prep = io_fsync_prep,
6677 [IORING_OP_READ_FIXED] = {
6679 .unbound_nonreg_file = 1,
6685 .async_size = sizeof(struct io_async_rw),
6686 .name = "READ_FIXED",
6690 [IORING_OP_WRITE_FIXED] = {
6693 .unbound_nonreg_file = 1,
6699 .async_size = sizeof(struct io_async_rw),
6700 .name = "WRITE_FIXED",
6704 [IORING_OP_POLL_ADD] = {
6706 .unbound_nonreg_file = 1,
6709 .prep = io_poll_add_prep,
6710 .issue = io_poll_add,
6712 [IORING_OP_POLL_REMOVE] = {
6714 .name = "POLL_REMOVE",
6715 .prep = io_poll_remove_prep,
6716 .issue = io_poll_remove,
6718 [IORING_OP_SYNC_FILE_RANGE] = {
6721 .name = "SYNC_FILE_RANGE",
6722 .prep = io_sfr_prep,
6723 .issue = io_sync_file_range,
6725 [IORING_OP_SENDMSG] = {
6727 .unbound_nonreg_file = 1,
6731 #if defined(CONFIG_NET)
6732 .async_size = sizeof(struct io_async_msghdr),
6733 .prep = io_sendmsg_prep,
6734 .issue = io_sendmsg,
6735 .prep_async = io_sendmsg_prep_async,
6736 .cleanup = io_sendmsg_recvmsg_cleanup,
6738 .prep = io_eopnotsupp_prep,
6741 [IORING_OP_RECVMSG] = {
6743 .unbound_nonreg_file = 1,
6748 #if defined(CONFIG_NET)
6749 .async_size = sizeof(struct io_async_msghdr),
6750 .prep = io_recvmsg_prep,
6751 .issue = io_recvmsg,
6752 .prep_async = io_recvmsg_prep_async,
6753 .cleanup = io_sendmsg_recvmsg_cleanup,
6755 .prep = io_eopnotsupp_prep,
6758 [IORING_OP_TIMEOUT] = {
6760 .async_size = sizeof(struct io_timeout_data),
6762 .prep = io_timeout_prep,
6763 .issue = io_timeout,
6765 [IORING_OP_TIMEOUT_REMOVE] = {
6766 /* used by timeout updates' prep() */
6768 .name = "TIMEOUT_REMOVE",
6769 .prep = io_timeout_remove_prep,
6770 .issue = io_timeout_remove,
6772 [IORING_OP_ACCEPT] = {
6774 .unbound_nonreg_file = 1,
6776 .poll_exclusive = 1,
6777 .ioprio = 1, /* used for flags */
6779 #if defined(CONFIG_NET)
6780 .prep = io_accept_prep,
6783 .prep = io_eopnotsupp_prep,
6786 [IORING_OP_ASYNC_CANCEL] = {
6788 .name = "ASYNC_CANCEL",
6789 .prep = io_async_cancel_prep,
6790 .issue = io_async_cancel,
6792 [IORING_OP_LINK_TIMEOUT] = {
6794 .async_size = sizeof(struct io_timeout_data),
6795 .name = "LINK_TIMEOUT",
6796 .prep = io_link_timeout_prep,
6797 .issue = io_no_issue,
6799 [IORING_OP_CONNECT] = {
6801 .unbound_nonreg_file = 1,
6804 #if defined(CONFIG_NET)
6805 .async_size = sizeof(struct io_async_connect),
6806 .prep = io_connect_prep,
6807 .issue = io_connect,
6808 .prep_async = io_connect_prep_async,
6810 .prep = io_eopnotsupp_prep,
6813 [IORING_OP_FALLOCATE] = {
6815 .name = "FALLOCATE",
6816 .prep = io_fallocate_prep,
6817 .issue = io_fallocate,
6819 [IORING_OP_OPENAT] = {
6821 .prep = io_openat_prep,
6823 .cleanup = io_open_cleanup,
6825 [IORING_OP_CLOSE] = {
6827 .prep = io_close_prep,
6830 [IORING_OP_FILES_UPDATE] = {
6833 .name = "FILES_UPDATE",
6834 .prep = io_files_update_prep,
6835 .issue = io_files_update,
6837 [IORING_OP_STATX] = {
6840 .prep = io_statx_prep,
6842 .cleanup = io_statx_cleanup,
6844 [IORING_OP_READ] = {
6846 .unbound_nonreg_file = 1,
6853 .async_size = sizeof(struct io_async_rw),
6858 [IORING_OP_WRITE] = {
6861 .unbound_nonreg_file = 1,
6867 .async_size = sizeof(struct io_async_rw),
6872 [IORING_OP_FADVISE] = {
6876 .prep = io_fadvise_prep,
6877 .issue = io_fadvise,
6879 [IORING_OP_MADVISE] = {
6881 .prep = io_madvise_prep,
6882 .issue = io_madvise,
6884 [IORING_OP_SEND] = {
6886 .unbound_nonreg_file = 1,
6891 #if defined(CONFIG_NET)
6892 .prep = io_sendmsg_prep,
6895 .prep = io_eopnotsupp_prep,
6898 [IORING_OP_RECV] = {
6900 .unbound_nonreg_file = 1,
6906 #if defined(CONFIG_NET)
6907 .prep = io_recvmsg_prep,
6910 .prep = io_eopnotsupp_prep,
6913 [IORING_OP_OPENAT2] = {
6915 .prep = io_openat2_prep,
6916 .issue = io_openat2,
6917 .cleanup = io_open_cleanup,
6919 [IORING_OP_EPOLL_CTL] = {
6920 .unbound_nonreg_file = 1,
6923 #if defined(CONFIG_EPOLL)
6924 .prep = io_epoll_ctl_prep,
6925 .issue = io_epoll_ctl,
6927 .prep = io_eopnotsupp_prep,
6930 [IORING_OP_SPLICE] = {
6933 .unbound_nonreg_file = 1,
6936 .prep = io_splice_prep,
6939 [IORING_OP_PROVIDE_BUFFERS] = {
6942 .name = "PROVIDE_BUFFERS",
6943 .prep = io_provide_buffers_prep,
6944 .issue = io_provide_buffers,
6946 [IORING_OP_REMOVE_BUFFERS] = {
6949 .name = "REMOVE_BUFFERS",
6950 .prep = io_remove_buffers_prep,
6951 .issue = io_remove_buffers,
6956 .unbound_nonreg_file = 1,
6959 .prep = io_tee_prep,
6962 [IORING_OP_SHUTDOWN] = {
6965 #if defined(CONFIG_NET)
6966 .prep = io_shutdown_prep,
6967 .issue = io_shutdown,
6969 .prep = io_eopnotsupp_prep,
6972 [IORING_OP_RENAMEAT] = {
6974 .prep = io_renameat_prep,
6975 .issue = io_renameat,
6976 .cleanup = io_renameat_cleanup,
6978 [IORING_OP_UNLINKAT] = {
6980 .prep = io_unlinkat_prep,
6981 .issue = io_unlinkat,
6982 .cleanup = io_unlinkat_cleanup,
6984 [IORING_OP_MKDIRAT] = {
6986 .prep = io_mkdirat_prep,
6987 .issue = io_mkdirat,
6988 .cleanup = io_mkdirat_cleanup,
6990 [IORING_OP_SYMLINKAT] = {
6991 .name = "SYMLINKAT",
6992 .prep = io_symlinkat_prep,
6993 .issue = io_symlinkat,
6994 .cleanup = io_link_cleanup,
6996 [IORING_OP_LINKAT] = {
6998 .prep = io_linkat_prep,
7000 .cleanup = io_link_cleanup,
7002 [IORING_OP_MSG_RING] = {
7006 .prep = io_msg_ring_prep,
7007 .issue = io_msg_ring,
7009 [IORING_OP_FSETXATTR] = {
7011 .name = "FSETXATTR",
7012 .prep = io_fsetxattr_prep,
7013 .issue = io_fsetxattr,
7014 .cleanup = io_xattr_cleanup,
7016 [IORING_OP_SETXATTR] = {
7018 .prep = io_setxattr_prep,
7019 .issue = io_setxattr,
7020 .cleanup = io_xattr_cleanup,
7022 [IORING_OP_FGETXATTR] = {
7024 .name = "FGETXATTR",
7025 .prep = io_fgetxattr_prep,
7026 .issue = io_fgetxattr,
7027 .cleanup = io_xattr_cleanup,
7029 [IORING_OP_GETXATTR] = {
7031 .prep = io_getxattr_prep,
7032 .issue = io_getxattr,
7033 .cleanup = io_xattr_cleanup,
7035 [IORING_OP_SOCKET] = {
7038 #if defined(CONFIG_NET)
7039 .prep = io_socket_prep,
7042 .prep = io_eopnotsupp_prep,
7045 [IORING_OP_URING_CMD] = {
7048 .name = "URING_CMD",
7049 .async_size = uring_cmd_pdu_size(1),
7050 .prep = io_uring_cmd_prep,
7051 .issue = io_uring_cmd,
7052 .prep_async = io_uring_cmd_prep_async,
7056 static int __init io_uring_init(void)
7060 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7061 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7062 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7065 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7066 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7067 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7068 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7069 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7070 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7071 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7072 BUILD_BUG_SQE_ELEM(8, __u64, off);
7073 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7074 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7075 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
7076 BUILD_BUG_SQE_ELEM(24, __u32, len);
7077 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7078 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7079 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7080 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7081 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
7082 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
7083 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7084 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7085 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7086 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7087 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7088 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7089 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7090 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7091 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
7092 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7093 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7094 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
7095 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7096 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
7097 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
7098 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
7100 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
7101 sizeof(struct io_uring_rsrc_update));
7102 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
7103 sizeof(struct io_uring_rsrc_update2));
7105 /* ->buf_index is u16 */
7106 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
7107 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
7108 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
7109 offsetof(struct io_uring_buf_ring, tail));
7111 /* should fit into one byte */
7112 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
7113 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
7114 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
7116 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7117 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
7119 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
7121 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
7122 BUG_ON(!io_op_defs[i].prep);
7123 if (io_op_defs[i].prep != io_eopnotsupp_prep)
7124 BUG_ON(!io_op_defs[i].issue);
7125 WARN_ON_ONCE(!io_op_defs[i].name);
7128 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
7132 __initcall(io_uring_init);