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/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/audit.h>
82 #include <linux/security.h>
84 #define CREATE_TRACE_POINTS
85 #include <trace/events/io_uring.h>
87 #include <uapi/linux/io_uring.h>
89 #include "../fs/internal.h"
92 #include "io_uring_types.h"
101 #include "openclose.h"
102 #include "uring_cmd.h"
106 #define IORING_MAX_ENTRIES 32768
107 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
108 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
110 /* only define max */
111 #define IORING_MAX_FIXED_FILES (1U << 20)
112 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
113 IORING_REGISTER_LAST + IORING_OP_LAST)
115 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
116 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
117 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
119 #define IORING_MAX_REG_BUFFERS (1U << 14)
121 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
122 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
124 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
125 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
127 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
128 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
131 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
134 #define IO_APOLL_MULTI_POLLED (REQ_F_APOLL_MULTISHOT | REQ_F_POLLED)
136 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
138 struct io_mapped_ubuf {
141 unsigned int nr_bvecs;
142 unsigned long acct_pages;
143 struct bio_vec bvec[];
148 struct io_overflow_cqe {
149 struct list_head list;
150 struct io_uring_cqe cqe;
154 struct list_head list;
159 struct io_mapped_ubuf *buf;
163 struct io_rsrc_node {
164 struct percpu_ref refs;
165 struct list_head node;
166 struct list_head rsrc_list;
167 struct io_rsrc_data *rsrc_data;
168 struct llist_node llist;
172 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
174 struct io_rsrc_data {
175 struct io_ring_ctx *ctx;
181 struct completion done;
185 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
186 struct io_buffer_list {
188 * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
189 * then these are classic provided buffers and ->buf_list is used.
192 struct list_head buf_list;
194 struct page **buf_pages;
195 struct io_uring_buf_ring *buf_ring;
200 /* below is for ring provided buffers */
208 struct list_head list;
216 IO_SQ_THREAD_SHOULD_STOP = 0,
217 IO_SQ_THREAD_SHOULD_PARK,
222 atomic_t park_pending;
225 /* ctx's that are using this sqd */
226 struct list_head ctx_list;
228 struct task_struct *thread;
229 struct wait_queue_head wait;
231 unsigned sq_thread_idle;
237 struct completion exited;
240 #define IO_COMPL_BATCH 32
241 #define IO_REQ_CACHE_SIZE 32
242 #define IO_REQ_ALLOC_BATCH 8
244 #define BGID_ARRAY 64
247 * Arbitrary limit, can be raised if need be
249 #define IO_RINGFD_REG_MAX 16
251 struct io_uring_task {
252 /* submission side */
255 struct wait_queue_head wait;
256 const struct io_ring_ctx *last;
258 struct percpu_counter inflight;
259 atomic_t inflight_tracked;
262 spinlock_t task_lock;
263 struct io_wq_work_list task_list;
264 struct io_wq_work_list prio_task_list;
265 struct callback_head task_work;
266 struct file **registered_rings;
271 * First field must be the file pointer in all the
272 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
276 struct wait_queue_head *head;
278 struct wait_queue_entry wait;
281 struct io_poll_update {
287 bool update_user_data;
290 struct io_timeout_data {
291 struct io_kiocb *req;
292 struct hrtimer timer;
293 struct timespec64 ts;
294 enum hrtimer_mode mode;
300 struct sockaddr __user *addr;
301 int __user *addr_len;
304 unsigned long nofile;
314 unsigned long nofile;
328 struct list_head list;
329 /* head of the link, used by linked timeouts only */
330 struct io_kiocb *head;
331 /* for linked completions */
332 struct io_kiocb *prev;
335 struct io_timeout_rem {
340 struct timespec64 ts;
346 /* NOTE: kiocb has the file as the first member, so don't do it here */
355 struct sockaddr __user *addr;
362 struct compat_msghdr __user *umsg_compat;
363 struct user_msghdr __user *umsg;
372 struct io_rsrc_update {
379 struct io_provide_buf {
399 struct io_async_connect {
400 struct sockaddr_storage address;
403 struct io_async_msghdr {
404 struct iovec fast_iov[UIO_FASTIOV];
405 /* points to an allocated iov, if NULL we use fast_iov instead */
406 struct iovec *free_iov;
407 struct sockaddr __user *uaddr;
409 struct sockaddr_storage addr;
413 struct iov_iter iter;
414 struct iov_iter_state iter_state;
415 struct iovec fast_iov[UIO_FASTIOV];
419 struct io_rw_state s;
420 const struct iovec *free_iovec;
422 struct wait_page_queue wpq;
427 struct io_poll *double_poll;
431 IORING_RSRC_FILE = 0,
432 IORING_RSRC_BUFFER = 1,
436 IO_CHECK_CQ_OVERFLOW_BIT,
437 IO_CHECK_CQ_DROPPED_BIT,
440 struct io_tctx_node {
441 struct list_head ctx_node;
442 struct task_struct *task;
443 struct io_ring_ctx *ctx;
446 struct io_defer_entry {
447 struct list_head list;
448 struct io_kiocb *req;
452 struct io_cancel_data {
453 struct io_ring_ctx *ctx;
463 /* needs req->file assigned */
464 unsigned needs_file : 1;
465 /* should block plug */
467 /* hash wq insertion if file is a regular file */
468 unsigned hash_reg_file : 1;
469 /* unbound wq insertion if file is a non-regular file */
470 unsigned unbound_nonreg_file : 1;
471 /* set if opcode supports polled "wait" */
473 unsigned pollout : 1;
474 unsigned poll_exclusive : 1;
475 /* op supports buffer selection */
476 unsigned buffer_select : 1;
477 /* opcode is not supported by this kernel */
478 unsigned not_supported : 1;
480 unsigned audit_skip : 1;
481 /* supports ioprio */
483 /* supports iopoll */
485 /* size of async data needed, if any */
486 unsigned short async_size;
488 int (*prep)(struct io_kiocb *, const struct io_uring_sqe *);
489 int (*issue)(struct io_kiocb *, unsigned int);
490 int (*prep_async)(struct io_kiocb *);
491 void (*cleanup)(struct io_kiocb *);
494 static const struct io_op_def io_op_defs[];
496 /* requests with any of those set should undergo io_disarm_next() */
497 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
498 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
500 static bool io_disarm_next(struct io_kiocb *req);
501 static void io_uring_del_tctx_node(unsigned long index);
502 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
503 struct task_struct *task,
505 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
507 static void io_dismantle_req(struct io_kiocb *req);
508 static void io_queue_linked_timeout(struct io_kiocb *req);
509 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
510 struct io_uring_rsrc_update2 *up,
512 static void io_clean_op(struct io_kiocb *req);
513 static void io_queue_sqe(struct io_kiocb *req);
514 static void io_rsrc_put_work(struct work_struct *work);
516 static void io_req_task_queue(struct io_kiocb *req);
517 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
518 static int io_req_prep_async(struct io_kiocb *req);
520 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
521 unsigned int issue_flags, u32 slot_index);
523 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
524 static void io_eventfd_signal(struct io_ring_ctx *ctx);
525 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
527 static struct kmem_cache *req_cachep;
529 static const struct file_operations io_uring_fops;
531 const char *io_uring_get_opcode(u8 opcode)
533 switch ((enum io_uring_op)opcode) {
536 case IORING_OP_READV:
538 case IORING_OP_WRITEV:
540 case IORING_OP_FSYNC:
542 case IORING_OP_READ_FIXED:
544 case IORING_OP_WRITE_FIXED:
545 return "WRITE_FIXED";
546 case IORING_OP_POLL_ADD:
548 case IORING_OP_POLL_REMOVE:
549 return "POLL_REMOVE";
550 case IORING_OP_SYNC_FILE_RANGE:
551 return "SYNC_FILE_RANGE";
552 case IORING_OP_SENDMSG:
554 case IORING_OP_RECVMSG:
556 case IORING_OP_TIMEOUT:
558 case IORING_OP_TIMEOUT_REMOVE:
559 return "TIMEOUT_REMOVE";
560 case IORING_OP_ACCEPT:
562 case IORING_OP_ASYNC_CANCEL:
563 return "ASYNC_CANCEL";
564 case IORING_OP_LINK_TIMEOUT:
565 return "LINK_TIMEOUT";
566 case IORING_OP_CONNECT:
568 case IORING_OP_FALLOCATE:
570 case IORING_OP_OPENAT:
572 case IORING_OP_CLOSE:
574 case IORING_OP_FILES_UPDATE:
575 return "FILES_UPDATE";
576 case IORING_OP_STATX:
580 case IORING_OP_WRITE:
582 case IORING_OP_FADVISE:
584 case IORING_OP_MADVISE:
590 case IORING_OP_OPENAT2:
592 case IORING_OP_EPOLL_CTL:
594 case IORING_OP_SPLICE:
596 case IORING_OP_PROVIDE_BUFFERS:
597 return "PROVIDE_BUFFERS";
598 case IORING_OP_REMOVE_BUFFERS:
599 return "REMOVE_BUFFERS";
602 case IORING_OP_SHUTDOWN:
604 case IORING_OP_RENAMEAT:
606 case IORING_OP_UNLINKAT:
608 case IORING_OP_MKDIRAT:
610 case IORING_OP_SYMLINKAT:
612 case IORING_OP_LINKAT:
614 case IORING_OP_MSG_RING:
616 case IORING_OP_FSETXATTR:
618 case IORING_OP_SETXATTR:
620 case IORING_OP_FGETXATTR:
622 case IORING_OP_GETXATTR:
624 case IORING_OP_SOCKET:
626 case IORING_OP_URING_CMD:
634 bool io_is_uring_fops(struct file *file)
636 return file->f_op == &io_uring_fops;
639 struct sock *io_uring_get_socket(struct file *file)
641 #if defined(CONFIG_UNIX)
642 if (io_is_uring_fops(file)) {
643 struct io_ring_ctx *ctx = file->private_data;
645 return ctx->ring_sock->sk;
650 EXPORT_SYMBOL(io_uring_get_socket);
652 #if defined(CONFIG_UNIX)
653 static inline bool io_file_need_scm(struct file *filp)
655 #if defined(IO_URING_SCM_ALL)
658 return !!unix_get_socket(filp);
662 static inline bool io_file_need_scm(struct file *filp)
668 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
671 mutex_lock(&ctx->uring_lock);
676 #define io_for_each_link(pos, head) \
677 for (pos = (head); pos; pos = pos->link)
680 * Shamelessly stolen from the mm implementation of page reference checking,
681 * see commit f958d7b528b1 for details.
683 #define req_ref_zero_or_close_to_overflow(req) \
684 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
686 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
688 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
689 return atomic_inc_not_zero(&req->refs);
692 static inline bool req_ref_put_and_test(struct io_kiocb *req)
694 if (likely(!(req->flags & REQ_F_REFCOUNT)))
697 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
698 return atomic_dec_and_test(&req->refs);
701 static inline void req_ref_get(struct io_kiocb *req)
703 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
704 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
705 atomic_inc(&req->refs);
708 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
710 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
711 __io_submit_flush_completions(ctx);
714 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
716 if (!(req->flags & REQ_F_REFCOUNT)) {
717 req->flags |= REQ_F_REFCOUNT;
718 atomic_set(&req->refs, nr);
722 static inline void io_req_set_refcount(struct io_kiocb *req)
724 __io_req_set_refcount(req, 1);
727 #define IO_RSRC_REF_BATCH 100
729 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
731 percpu_ref_put_many(&node->refs, nr);
734 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
735 struct io_ring_ctx *ctx)
736 __must_hold(&ctx->uring_lock)
738 struct io_rsrc_node *node = req->rsrc_node;
741 if (node == ctx->rsrc_node)
742 ctx->rsrc_cached_refs++;
744 io_rsrc_put_node(node, 1);
748 static inline void io_req_put_rsrc(struct io_kiocb *req)
751 io_rsrc_put_node(req->rsrc_node, 1);
754 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
755 __must_hold(&ctx->uring_lock)
757 if (ctx->rsrc_cached_refs) {
758 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
759 ctx->rsrc_cached_refs = 0;
763 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
764 __must_hold(&ctx->uring_lock)
766 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
767 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
770 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
771 struct io_ring_ctx *ctx,
772 unsigned int issue_flags)
774 if (!req->rsrc_node) {
775 req->rsrc_node = ctx->rsrc_node;
777 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
778 lockdep_assert_held(&ctx->uring_lock);
779 ctx->rsrc_cached_refs--;
780 if (unlikely(ctx->rsrc_cached_refs < 0))
781 io_rsrc_refs_refill(ctx);
783 percpu_ref_get(&req->rsrc_node->refs);
788 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
790 if (req->flags & REQ_F_BUFFER_RING) {
792 req->buf_list->head++;
793 req->flags &= ~REQ_F_BUFFER_RING;
795 list_add(&req->kbuf->list, list);
796 req->flags &= ~REQ_F_BUFFER_SELECTED;
799 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
802 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
804 lockdep_assert_held(&req->ctx->completion_lock);
806 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
808 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
811 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
812 unsigned issue_flags)
816 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
820 * We can add this buffer back to two lists:
822 * 1) The io_buffers_cache list. This one is protected by the
823 * ctx->uring_lock. If we already hold this lock, add back to this
824 * list as we can grab it from issue as well.
825 * 2) The io_buffers_comp list. This one is protected by the
826 * ctx->completion_lock.
828 * We migrate buffers from the comp_list to the issue cache list
831 if (req->flags & REQ_F_BUFFER_RING) {
832 /* no buffers to recycle for this case */
833 cflags = __io_put_kbuf(req, NULL);
834 } else if (issue_flags & IO_URING_F_UNLOCKED) {
835 struct io_ring_ctx *ctx = req->ctx;
837 spin_lock(&ctx->completion_lock);
838 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
839 spin_unlock(&ctx->completion_lock);
841 lockdep_assert_held(&req->ctx->uring_lock);
843 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
849 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
852 if (ctx->io_bl && bgid < BGID_ARRAY)
853 return &ctx->io_bl[bgid];
855 return xa_load(&ctx->io_bl_xa, bgid);
858 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
860 struct io_ring_ctx *ctx = req->ctx;
861 struct io_buffer_list *bl;
862 struct io_buffer *buf;
864 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
867 * For legacy provided buffer mode, don't recycle if we already did
868 * IO to this buffer. For ring-mapped provided buffer mode, we should
869 * increment ring->head to explicitly monopolize the buffer to avoid
872 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
873 (req->flags & REQ_F_PARTIAL_IO))
877 * READV uses fields in `struct io_rw` (len/addr) to stash the selected
878 * buffer data. However if that buffer is recycled the original request
879 * data stored in addr is lost. Therefore forbid recycling for now.
881 if (req->opcode == IORING_OP_READV)
885 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
886 * the flag and hence ensure that bl->head doesn't get incremented.
887 * If the tail has already been incremented, hang on to it.
889 if (req->flags & REQ_F_BUFFER_RING) {
891 if (req->flags & REQ_F_PARTIAL_IO) {
892 req->buf_list->head++;
893 req->buf_list = NULL;
895 req->buf_index = req->buf_list->bgid;
896 req->flags &= ~REQ_F_BUFFER_RING;
902 io_ring_submit_lock(ctx, issue_flags);
905 bl = io_buffer_get_list(ctx, buf->bgid);
906 list_add(&buf->list, &bl->buf_list);
907 req->flags &= ~REQ_F_BUFFER_SELECTED;
908 req->buf_index = buf->bgid;
910 io_ring_submit_unlock(ctx, issue_flags);
913 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
915 __must_hold(&req->ctx->timeout_lock)
917 struct io_kiocb *req;
919 if (task && head->task != task)
924 io_for_each_link(req, head) {
925 if (req->flags & REQ_F_INFLIGHT)
931 static bool io_match_linked(struct io_kiocb *head)
933 struct io_kiocb *req;
935 io_for_each_link(req, head) {
936 if (req->flags & REQ_F_INFLIGHT)
943 * As io_match_task() but protected against racing with linked timeouts.
944 * User must not hold timeout_lock.
946 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
951 if (task && head->task != task)
956 if (head->flags & REQ_F_LINK_TIMEOUT) {
957 struct io_ring_ctx *ctx = head->ctx;
959 /* protect against races with linked timeouts */
960 spin_lock_irq(&ctx->timeout_lock);
961 matched = io_match_linked(head);
962 spin_unlock_irq(&ctx->timeout_lock);
964 matched = io_match_linked(head);
969 static inline void req_fail_link_node(struct io_kiocb *req, int res)
972 io_req_set_res(req, res, 0);
975 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
977 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
980 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
982 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
984 complete(&ctx->ref_comp);
987 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
989 struct io_timeout *timeout = io_kiocb_to_cmd(req);
991 return !timeout->off;
994 static __cold void io_fallback_req_func(struct work_struct *work)
996 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
998 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
999 struct io_kiocb *req, *tmp;
1000 bool locked = false;
1002 percpu_ref_get(&ctx->refs);
1003 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1004 req->io_task_work.func(req, &locked);
1007 io_submit_flush_completions(ctx);
1008 mutex_unlock(&ctx->uring_lock);
1010 percpu_ref_put(&ctx->refs);
1013 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1015 struct io_ring_ctx *ctx;
1018 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1022 xa_init(&ctx->io_bl_xa);
1025 * Use 5 bits less than the max cq entries, that should give us around
1026 * 32 entries per hash list if totally full and uniformly spread.
1028 hash_bits = ilog2(p->cq_entries);
1032 ctx->cancel_hash_bits = hash_bits;
1033 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1035 if (!ctx->cancel_hash)
1037 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1039 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1040 if (!ctx->dummy_ubuf)
1042 /* set invalid range, so io_import_fixed() fails meeting it */
1043 ctx->dummy_ubuf->ubuf = -1UL;
1045 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1046 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1049 ctx->flags = p->flags;
1050 init_waitqueue_head(&ctx->sqo_sq_wait);
1051 INIT_LIST_HEAD(&ctx->sqd_list);
1052 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1053 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1054 INIT_LIST_HEAD(&ctx->apoll_cache);
1055 init_completion(&ctx->ref_comp);
1056 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1057 mutex_init(&ctx->uring_lock);
1058 init_waitqueue_head(&ctx->cq_wait);
1059 spin_lock_init(&ctx->completion_lock);
1060 spin_lock_init(&ctx->timeout_lock);
1061 INIT_WQ_LIST(&ctx->iopoll_list);
1062 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1063 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1064 INIT_LIST_HEAD(&ctx->defer_list);
1065 INIT_LIST_HEAD(&ctx->timeout_list);
1066 INIT_LIST_HEAD(&ctx->ltimeout_list);
1067 spin_lock_init(&ctx->rsrc_ref_lock);
1068 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1069 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1070 init_llist_head(&ctx->rsrc_put_llist);
1071 INIT_LIST_HEAD(&ctx->tctx_list);
1072 ctx->submit_state.free_list.next = NULL;
1073 INIT_WQ_LIST(&ctx->locked_free_list);
1074 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1075 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1078 kfree(ctx->dummy_ubuf);
1079 kfree(ctx->cancel_hash);
1081 xa_destroy(&ctx->io_bl_xa);
1086 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1088 struct io_rings *r = ctx->rings;
1090 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1094 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1096 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1097 struct io_ring_ctx *ctx = req->ctx;
1099 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1105 static inline bool io_req_ffs_set(struct io_kiocb *req)
1107 return req->flags & REQ_F_FIXED_FILE;
1110 static inline void io_req_track_inflight(struct io_kiocb *req)
1112 if (!(req->flags & REQ_F_INFLIGHT)) {
1113 req->flags |= REQ_F_INFLIGHT;
1114 atomic_inc(&req->task->io_uring->inflight_tracked);
1118 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1120 if (WARN_ON_ONCE(!req->link))
1123 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1124 req->flags |= REQ_F_LINK_TIMEOUT;
1126 /* linked timeouts should have two refs once prep'ed */
1127 io_req_set_refcount(req);
1128 __io_req_set_refcount(req->link, 2);
1132 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1134 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1136 return __io_prep_linked_timeout(req);
1139 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1141 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1144 static inline void io_arm_ltimeout(struct io_kiocb *req)
1146 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1147 __io_arm_ltimeout(req);
1150 static void io_prep_async_work(struct io_kiocb *req)
1152 const struct io_op_def *def = &io_op_defs[req->opcode];
1153 struct io_ring_ctx *ctx = req->ctx;
1155 if (!(req->flags & REQ_F_CREDS)) {
1156 req->flags |= REQ_F_CREDS;
1157 req->creds = get_current_cred();
1160 req->work.list.next = NULL;
1161 req->work.flags = 0;
1162 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1163 if (req->flags & REQ_F_FORCE_ASYNC)
1164 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1166 if (req->flags & REQ_F_ISREG) {
1167 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1168 io_wq_hash_work(&req->work, file_inode(req->file));
1169 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1170 if (def->unbound_nonreg_file)
1171 req->work.flags |= IO_WQ_WORK_UNBOUND;
1175 static void io_prep_async_link(struct io_kiocb *req)
1177 struct io_kiocb *cur;
1179 if (req->flags & REQ_F_LINK_TIMEOUT) {
1180 struct io_ring_ctx *ctx = req->ctx;
1182 spin_lock_irq(&ctx->timeout_lock);
1183 io_for_each_link(cur, req)
1184 io_prep_async_work(cur);
1185 spin_unlock_irq(&ctx->timeout_lock);
1187 io_for_each_link(cur, req)
1188 io_prep_async_work(cur);
1192 static inline void io_req_add_compl_list(struct io_kiocb *req)
1194 struct io_submit_state *state = &req->ctx->submit_state;
1196 if (!(req->flags & REQ_F_CQE_SKIP))
1197 state->flush_cqes = true;
1198 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1201 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1203 struct io_kiocb *link = io_prep_linked_timeout(req);
1204 struct io_uring_task *tctx = req->task->io_uring;
1207 BUG_ON(!tctx->io_wq);
1209 /* init ->work of the whole link before punting */
1210 io_prep_async_link(req);
1213 * Not expected to happen, but if we do have a bug where this _can_
1214 * happen, catch it here and ensure the request is marked as
1215 * canceled. That will make io-wq go through the usual work cancel
1216 * procedure rather than attempt to run this request (or create a new
1219 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1220 req->work.flags |= IO_WQ_WORK_CANCEL;
1222 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1223 req->opcode, req->flags, &req->work,
1224 io_wq_is_hashed(&req->work));
1225 io_wq_enqueue(tctx->io_wq, &req->work);
1227 io_queue_linked_timeout(link);
1230 static void io_kill_timeout(struct io_kiocb *req, int status)
1231 __must_hold(&req->ctx->completion_lock)
1232 __must_hold(&req->ctx->timeout_lock)
1234 struct io_timeout_data *io = req->async_data;
1236 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1237 struct io_timeout *timeout = io_kiocb_to_cmd(req);
1241 atomic_set(&req->ctx->cq_timeouts,
1242 atomic_read(&req->ctx->cq_timeouts) + 1);
1243 list_del_init(&timeout->list);
1244 io_req_tw_post_queue(req, status, 0);
1248 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1250 while (!list_empty(&ctx->defer_list)) {
1251 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1252 struct io_defer_entry, list);
1254 if (req_need_defer(de->req, de->seq))
1256 list_del_init(&de->list);
1257 io_req_task_queue(de->req);
1262 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1263 __must_hold(&ctx->completion_lock)
1265 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1266 struct io_timeout *timeout, *tmp;
1268 spin_lock_irq(&ctx->timeout_lock);
1269 list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
1270 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
1271 u32 events_needed, events_got;
1273 if (io_is_timeout_noseq(req))
1277 * Since seq can easily wrap around over time, subtract
1278 * the last seq at which timeouts were flushed before comparing.
1279 * Assuming not more than 2^31-1 events have happened since,
1280 * these subtractions won't have wrapped, so we can check if
1281 * target is in [last_seq, current_seq] by comparing the two.
1283 events_needed = timeout->target_seq - ctx->cq_last_tm_flush;
1284 events_got = seq - ctx->cq_last_tm_flush;
1285 if (events_got < events_needed)
1288 io_kill_timeout(req, 0);
1290 ctx->cq_last_tm_flush = seq;
1291 spin_unlock_irq(&ctx->timeout_lock);
1294 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1296 /* order cqe stores with ring update */
1297 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1300 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1302 if (ctx->off_timeout_used || ctx->drain_active) {
1303 spin_lock(&ctx->completion_lock);
1304 if (ctx->off_timeout_used)
1305 io_flush_timeouts(ctx);
1306 if (ctx->drain_active)
1307 io_queue_deferred(ctx);
1308 io_commit_cqring(ctx);
1309 spin_unlock(&ctx->completion_lock);
1312 io_eventfd_signal(ctx);
1315 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1317 struct io_rings *r = ctx->rings;
1319 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1322 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1324 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1328 * writes to the cq entry need to come after reading head; the
1329 * control dependency is enough as we're using WRITE_ONCE to
1332 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1334 struct io_rings *rings = ctx->rings;
1335 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1336 unsigned int shift = 0;
1337 unsigned int free, queued, len;
1339 if (ctx->flags & IORING_SETUP_CQE32)
1342 /* userspace may cheat modifying the tail, be safe and do min */
1343 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
1344 free = ctx->cq_entries - queued;
1345 /* we need a contiguous range, limit based on the current array offset */
1346 len = min(free, ctx->cq_entries - off);
1350 ctx->cached_cq_tail++;
1351 ctx->cqe_cached = &rings->cqes[off];
1352 ctx->cqe_sentinel = ctx->cqe_cached + len;
1354 return &rings->cqes[off << shift];
1357 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1359 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
1360 struct io_uring_cqe *cqe = ctx->cqe_cached;
1362 if (ctx->flags & IORING_SETUP_CQE32) {
1363 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
1368 ctx->cached_cq_tail++;
1373 return __io_get_cqe(ctx);
1376 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1378 struct io_ev_fd *ev_fd;
1382 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1383 * and eventfd_signal
1385 ev_fd = rcu_dereference(ctx->io_ev_fd);
1388 * Check again if ev_fd exists incase an io_eventfd_unregister call
1389 * completed between the NULL check of ctx->io_ev_fd at the start of
1390 * the function and rcu_read_lock.
1392 if (unlikely(!ev_fd))
1394 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1397 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1398 eventfd_signal(ev_fd->cq_ev_fd, 1);
1403 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1406 * wake_up_all() may seem excessive, but io_wake_function() and
1407 * io_should_wake() handle the termination of the loop and only
1408 * wake as many waiters as we need to.
1410 if (wq_has_sleeper(&ctx->cq_wait))
1411 wake_up_all(&ctx->cq_wait);
1415 * This should only get called when at least one event has been posted.
1416 * Some applications rely on the eventfd notification count only changing
1417 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1418 * 1:1 relationship between how many times this function is called (and
1419 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1421 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1423 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1425 __io_commit_cqring_flush(ctx);
1427 io_cqring_wake(ctx);
1430 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1432 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1434 __io_commit_cqring_flush(ctx);
1436 if (ctx->flags & IORING_SETUP_SQPOLL)
1437 io_cqring_wake(ctx);
1440 /* Returns true if there are no backlogged entries after the flush */
1441 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1443 bool all_flushed, posted;
1444 size_t cqe_size = sizeof(struct io_uring_cqe);
1446 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1449 if (ctx->flags & IORING_SETUP_CQE32)
1453 spin_lock(&ctx->completion_lock);
1454 while (!list_empty(&ctx->cq_overflow_list)) {
1455 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1456 struct io_overflow_cqe *ocqe;
1460 ocqe = list_first_entry(&ctx->cq_overflow_list,
1461 struct io_overflow_cqe, list);
1463 memcpy(cqe, &ocqe->cqe, cqe_size);
1465 io_account_cq_overflow(ctx);
1468 list_del(&ocqe->list);
1472 all_flushed = list_empty(&ctx->cq_overflow_list);
1474 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1475 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1478 io_commit_cqring(ctx);
1479 spin_unlock(&ctx->completion_lock);
1481 io_cqring_ev_posted(ctx);
1485 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1489 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
1490 /* iopoll syncs against uring_lock, not completion_lock */
1491 if (ctx->flags & IORING_SETUP_IOPOLL)
1492 mutex_lock(&ctx->uring_lock);
1493 ret = __io_cqring_overflow_flush(ctx, false);
1494 if (ctx->flags & IORING_SETUP_IOPOLL)
1495 mutex_unlock(&ctx->uring_lock);
1501 static void __io_put_task(struct task_struct *task, int nr)
1503 struct io_uring_task *tctx = task->io_uring;
1505 percpu_counter_sub(&tctx->inflight, nr);
1506 if (unlikely(atomic_read(&tctx->in_idle)))
1507 wake_up(&tctx->wait);
1508 put_task_struct_many(task, nr);
1511 /* must to be called somewhat shortly after putting a request */
1512 static inline void io_put_task(struct task_struct *task, int nr)
1514 if (likely(task == current))
1515 task->io_uring->cached_refs += nr;
1517 __io_put_task(task, nr);
1520 static void io_task_refs_refill(struct io_uring_task *tctx)
1522 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1524 percpu_counter_add(&tctx->inflight, refill);
1525 refcount_add(refill, ¤t->usage);
1526 tctx->cached_refs += refill;
1529 static inline void io_get_task_refs(int nr)
1531 struct io_uring_task *tctx = current->io_uring;
1533 tctx->cached_refs -= nr;
1534 if (unlikely(tctx->cached_refs < 0))
1535 io_task_refs_refill(tctx);
1538 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1540 struct io_uring_task *tctx = task->io_uring;
1541 unsigned int refs = tctx->cached_refs;
1544 tctx->cached_refs = 0;
1545 percpu_counter_sub(&tctx->inflight, refs);
1546 put_task_struct_many(task, refs);
1550 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1551 s32 res, u32 cflags, u64 extra1,
1554 struct io_overflow_cqe *ocqe;
1555 size_t ocq_size = sizeof(struct io_overflow_cqe);
1556 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
1559 ocq_size += sizeof(struct io_uring_cqe);
1561 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
1562 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
1565 * If we're in ring overflow flush mode, or in task cancel mode,
1566 * or cannot allocate an overflow entry, then we need to drop it
1569 io_account_cq_overflow(ctx);
1570 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
1573 if (list_empty(&ctx->cq_overflow_list)) {
1574 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1575 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1578 ocqe->cqe.user_data = user_data;
1579 ocqe->cqe.res = res;
1580 ocqe->cqe.flags = cflags;
1582 ocqe->cqe.big_cqe[0] = extra1;
1583 ocqe->cqe.big_cqe[1] = extra2;
1585 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1589 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
1590 struct io_kiocb *req)
1592 struct io_uring_cqe *cqe;
1594 if (!(ctx->flags & IORING_SETUP_CQE32)) {
1595 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1596 req->cqe.res, req->cqe.flags, 0, 0);
1599 * If we can't get a cq entry, userspace overflowed the
1600 * submission (by quite a lot). Increment the overflow count in
1603 cqe = io_get_cqe(ctx);
1605 memcpy(cqe, &req->cqe, sizeof(*cqe));
1609 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1610 req->cqe.res, req->cqe.flags,
1613 u64 extra1 = 0, extra2 = 0;
1615 if (req->flags & REQ_F_CQE32_INIT) {
1616 extra1 = req->extra1;
1617 extra2 = req->extra2;
1620 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1621 req->cqe.res, req->cqe.flags, extra1, extra2);
1624 * If we can't get a cq entry, userspace overflowed the
1625 * submission (by quite a lot). Increment the overflow count in
1628 cqe = io_get_cqe(ctx);
1630 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
1631 WRITE_ONCE(cqe->big_cqe[0], extra1);
1632 WRITE_ONCE(cqe->big_cqe[1], extra2);
1636 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1637 req->cqe.res, req->cqe.flags,
1642 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1643 s32 res, u32 cflags)
1645 struct io_uring_cqe *cqe;
1648 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
1651 * If we can't get a cq entry, userspace overflowed the
1652 * submission (by quite a lot). Increment the overflow count in
1655 cqe = io_get_cqe(ctx);
1657 WRITE_ONCE(cqe->user_data, user_data);
1658 WRITE_ONCE(cqe->res, res);
1659 WRITE_ONCE(cqe->flags, cflags);
1661 if (ctx->flags & IORING_SETUP_CQE32) {
1662 WRITE_ONCE(cqe->big_cqe[0], 0);
1663 WRITE_ONCE(cqe->big_cqe[1], 0);
1667 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
1670 static void __io_req_complete_put(struct io_kiocb *req)
1673 * If we're the last reference to this request, add to our locked
1676 if (req_ref_put_and_test(req)) {
1677 struct io_ring_ctx *ctx = req->ctx;
1679 if (req->flags & IO_REQ_LINK_FLAGS) {
1680 if (req->flags & IO_DISARM_MASK)
1681 io_disarm_next(req);
1683 io_req_task_queue(req->link);
1687 io_req_put_rsrc(req);
1689 * Selected buffer deallocation in io_clean_op() assumes that
1690 * we don't hold ->completion_lock. Clean them here to avoid
1693 io_put_kbuf_comp(req);
1694 io_dismantle_req(req);
1695 io_put_task(req->task, 1);
1696 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1697 ctx->locked_free_nr++;
1701 static void __io_req_complete_post(struct io_kiocb *req)
1703 if (!(req->flags & REQ_F_CQE_SKIP))
1704 __io_fill_cqe_req(req->ctx, req);
1705 __io_req_complete_put(req);
1708 static void io_req_complete_post(struct io_kiocb *req)
1710 struct io_ring_ctx *ctx = req->ctx;
1712 spin_lock(&ctx->completion_lock);
1713 __io_req_complete_post(req);
1714 io_commit_cqring(ctx);
1715 spin_unlock(&ctx->completion_lock);
1716 io_cqring_ev_posted(ctx);
1719 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
1721 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1722 req->flags |= REQ_F_COMPLETE_INLINE;
1724 io_req_complete_post(req);
1727 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1730 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1731 io_req_complete_post(req);
1735 * Don't initialise the fields below on every allocation, but do that in
1736 * advance and keep them valid across allocations.
1738 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1742 req->async_data = NULL;
1743 /* not necessary, but safer to zero */
1747 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1748 struct io_submit_state *state)
1750 spin_lock(&ctx->completion_lock);
1751 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1752 ctx->locked_free_nr = 0;
1753 spin_unlock(&ctx->completion_lock);
1756 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
1758 return !ctx->submit_state.free_list.next;
1762 * A request might get retired back into the request caches even before opcode
1763 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1764 * Because of that, io_alloc_req() should be called only under ->uring_lock
1765 * and with extra caution to not get a request that is still worked on.
1767 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1768 __must_hold(&ctx->uring_lock)
1770 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1771 void *reqs[IO_REQ_ALLOC_BATCH];
1775 * If we have more than a batch's worth of requests in our IRQ side
1776 * locked cache, grab the lock and move them over to our submission
1779 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1780 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1781 if (!io_req_cache_empty(ctx))
1785 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1788 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1789 * retry single alloc to be on the safe side.
1791 if (unlikely(ret <= 0)) {
1792 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1798 percpu_ref_get_many(&ctx->refs, ret);
1799 for (i = 0; i < ret; i++) {
1800 struct io_kiocb *req = reqs[i];
1802 io_preinit_req(req, ctx);
1803 io_req_add_to_cache(req, ctx);
1808 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
1810 if (unlikely(io_req_cache_empty(ctx)))
1811 return __io_alloc_req_refill(ctx);
1815 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1817 struct io_wq_work_node *node;
1819 node = wq_stack_extract(&ctx->submit_state.free_list);
1820 return container_of(node, struct io_kiocb, comp_list);
1823 static inline void io_dismantle_req(struct io_kiocb *req)
1825 unsigned int flags = req->flags;
1827 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
1829 if (!(flags & REQ_F_FIXED_FILE))
1830 io_put_file(req->file);
1833 static __cold void io_free_req(struct io_kiocb *req)
1835 struct io_ring_ctx *ctx = req->ctx;
1837 io_req_put_rsrc(req);
1838 io_dismantle_req(req);
1839 io_put_task(req->task, 1);
1841 spin_lock(&ctx->completion_lock);
1842 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1843 ctx->locked_free_nr++;
1844 spin_unlock(&ctx->completion_lock);
1847 static inline void io_remove_next_linked(struct io_kiocb *req)
1849 struct io_kiocb *nxt = req->link;
1851 req->link = nxt->link;
1855 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
1856 __must_hold(&req->ctx->completion_lock)
1857 __must_hold(&req->ctx->timeout_lock)
1859 struct io_kiocb *link = req->link;
1861 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1862 struct io_timeout_data *io = link->async_data;
1863 struct io_timeout *timeout = io_kiocb_to_cmd(link);
1865 io_remove_next_linked(req);
1866 timeout->head = NULL;
1867 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1868 list_del(&timeout->list);
1875 static void io_fail_links(struct io_kiocb *req)
1876 __must_hold(&req->ctx->completion_lock)
1878 struct io_kiocb *nxt, *link = req->link;
1879 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
1883 long res = -ECANCELED;
1885 if (link->flags & REQ_F_FAIL)
1886 res = link->cqe.res;
1891 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
1895 link->flags |= REQ_F_CQE_SKIP;
1897 link->flags &= ~REQ_F_CQE_SKIP;
1898 io_req_set_res(link, res, 0);
1899 __io_req_complete_post(link);
1904 static bool io_disarm_next(struct io_kiocb *req)
1905 __must_hold(&req->ctx->completion_lock)
1907 struct io_kiocb *link = NULL;
1908 bool posted = false;
1910 if (req->flags & REQ_F_ARM_LTIMEOUT) {
1912 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1913 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1914 io_remove_next_linked(req);
1915 io_req_tw_post_queue(link, -ECANCELED, 0);
1918 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
1919 struct io_ring_ctx *ctx = req->ctx;
1921 spin_lock_irq(&ctx->timeout_lock);
1922 link = io_disarm_linked_timeout(req);
1923 spin_unlock_irq(&ctx->timeout_lock);
1926 io_req_tw_post_queue(link, -ECANCELED, 0);
1929 if (unlikely((req->flags & REQ_F_FAIL) &&
1930 !(req->flags & REQ_F_HARDLINK))) {
1931 posted |= (req->link != NULL);
1937 static void __io_req_find_next_prep(struct io_kiocb *req)
1939 struct io_ring_ctx *ctx = req->ctx;
1942 spin_lock(&ctx->completion_lock);
1943 posted = io_disarm_next(req);
1944 io_commit_cqring(ctx);
1945 spin_unlock(&ctx->completion_lock);
1947 io_cqring_ev_posted(ctx);
1950 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1952 struct io_kiocb *nxt;
1955 * If LINK is set, we have dependent requests in this chain. If we
1956 * didn't fail this request, queue the first one up, moving any other
1957 * dependencies to the next request. In case of failure, fail the rest
1960 if (unlikely(req->flags & IO_DISARM_MASK))
1961 __io_req_find_next_prep(req);
1967 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
1971 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1972 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1974 io_submit_flush_completions(ctx);
1975 mutex_unlock(&ctx->uring_lock);
1978 percpu_ref_put(&ctx->refs);
1981 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
1983 io_commit_cqring(ctx);
1984 spin_unlock(&ctx->completion_lock);
1985 io_cqring_ev_posted(ctx);
1988 static void handle_prev_tw_list(struct io_wq_work_node *node,
1989 struct io_ring_ctx **ctx, bool *uring_locked)
1991 if (*ctx && !*uring_locked)
1992 spin_lock(&(*ctx)->completion_lock);
1995 struct io_wq_work_node *next = node->next;
1996 struct io_kiocb *req = container_of(node, struct io_kiocb,
1999 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2001 if (req->ctx != *ctx) {
2002 if (unlikely(!*uring_locked && *ctx))
2003 ctx_commit_and_unlock(*ctx);
2005 ctx_flush_and_put(*ctx, uring_locked);
2007 /* if not contended, grab and improve batching */
2008 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2009 percpu_ref_get(&(*ctx)->refs);
2010 if (unlikely(!*uring_locked))
2011 spin_lock(&(*ctx)->completion_lock);
2013 if (likely(*uring_locked)) {
2014 req->io_task_work.func(req, uring_locked);
2016 req->cqe.flags = io_put_kbuf_comp(req);
2017 __io_req_complete_post(req);
2022 if (unlikely(!*uring_locked))
2023 ctx_commit_and_unlock(*ctx);
2026 static void handle_tw_list(struct io_wq_work_node *node,
2027 struct io_ring_ctx **ctx, bool *locked)
2030 struct io_wq_work_node *next = node->next;
2031 struct io_kiocb *req = container_of(node, struct io_kiocb,
2034 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2036 if (req->ctx != *ctx) {
2037 ctx_flush_and_put(*ctx, locked);
2039 /* if not contended, grab and improve batching */
2040 *locked = mutex_trylock(&(*ctx)->uring_lock);
2041 percpu_ref_get(&(*ctx)->refs);
2043 req->io_task_work.func(req, locked);
2048 static void tctx_task_work(struct callback_head *cb)
2050 bool uring_locked = false;
2051 struct io_ring_ctx *ctx = NULL;
2052 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2056 struct io_wq_work_node *node1, *node2;
2058 spin_lock_irq(&tctx->task_lock);
2059 node1 = tctx->prio_task_list.first;
2060 node2 = tctx->task_list.first;
2061 INIT_WQ_LIST(&tctx->task_list);
2062 INIT_WQ_LIST(&tctx->prio_task_list);
2063 if (!node2 && !node1)
2064 tctx->task_running = false;
2065 spin_unlock_irq(&tctx->task_lock);
2066 if (!node2 && !node1)
2070 handle_prev_tw_list(node1, &ctx, &uring_locked);
2072 handle_tw_list(node2, &ctx, &uring_locked);
2075 if (data_race(!tctx->task_list.first) &&
2076 data_race(!tctx->prio_task_list.first) && uring_locked)
2077 io_submit_flush_completions(ctx);
2080 ctx_flush_and_put(ctx, &uring_locked);
2082 /* relaxed read is enough as only the task itself sets ->in_idle */
2083 if (unlikely(atomic_read(&tctx->in_idle)))
2084 io_uring_drop_tctx_refs(current);
2087 static void __io_req_task_work_add(struct io_kiocb *req,
2088 struct io_uring_task *tctx,
2089 struct io_wq_work_list *list)
2091 struct io_ring_ctx *ctx = req->ctx;
2092 struct io_wq_work_node *node;
2093 unsigned long flags;
2096 spin_lock_irqsave(&tctx->task_lock, flags);
2097 wq_list_add_tail(&req->io_task_work.node, list);
2098 running = tctx->task_running;
2100 tctx->task_running = true;
2101 spin_unlock_irqrestore(&tctx->task_lock, flags);
2103 /* task_work already pending, we're done */
2107 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2108 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2110 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2113 spin_lock_irqsave(&tctx->task_lock, flags);
2114 tctx->task_running = false;
2115 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2116 spin_unlock_irqrestore(&tctx->task_lock, flags);
2119 req = container_of(node, struct io_kiocb, io_task_work.node);
2121 if (llist_add(&req->io_task_work.fallback_node,
2122 &req->ctx->fallback_llist))
2123 schedule_delayed_work(&req->ctx->fallback_work, 1);
2127 void io_req_task_work_add(struct io_kiocb *req)
2129 struct io_uring_task *tctx = req->task->io_uring;
2131 __io_req_task_work_add(req, tctx, &tctx->task_list);
2134 static void io_req_task_prio_work_add(struct io_kiocb *req)
2136 struct io_uring_task *tctx = req->task->io_uring;
2138 if (req->ctx->flags & IORING_SETUP_SQPOLL)
2139 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
2141 __io_req_task_work_add(req, tctx, &tctx->task_list);
2144 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2146 io_req_complete_post(req);
2149 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2151 io_req_set_res(req, res, cflags);
2152 req->io_task_work.func = io_req_tw_post;
2153 io_req_task_work_add(req);
2156 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2158 /* not needed for normal modes, but SQPOLL depends on it */
2159 io_tw_lock(req->ctx, locked);
2160 io_req_complete_failed(req, req->cqe.res);
2163 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2165 io_tw_lock(req->ctx, locked);
2166 /* req->task == current here, checking PF_EXITING is safe */
2167 if (likely(!(req->task->flags & PF_EXITING)))
2170 io_req_complete_failed(req, -EFAULT);
2173 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2175 io_req_set_res(req, ret, 0);
2176 req->io_task_work.func = io_req_task_cancel;
2177 io_req_task_work_add(req);
2180 static void io_req_task_queue(struct io_kiocb *req)
2182 req->io_task_work.func = io_req_task_submit;
2183 io_req_task_work_add(req);
2186 static void io_req_task_queue_reissue(struct io_kiocb *req)
2188 req->io_task_work.func = io_queue_iowq;
2189 io_req_task_work_add(req);
2192 static void io_queue_next(struct io_kiocb *req)
2194 struct io_kiocb *nxt = io_req_find_next(req);
2197 io_req_task_queue(nxt);
2200 static void io_free_batch_list(struct io_ring_ctx *ctx,
2201 struct io_wq_work_node *node)
2202 __must_hold(&ctx->uring_lock)
2204 struct task_struct *task = NULL;
2208 struct io_kiocb *req = container_of(node, struct io_kiocb,
2211 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2212 if (req->flags & REQ_F_REFCOUNT) {
2213 node = req->comp_list.next;
2214 if (!req_ref_put_and_test(req))
2217 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2218 struct async_poll *apoll = req->apoll;
2220 if (apoll->double_poll)
2221 kfree(apoll->double_poll);
2222 list_add(&apoll->poll.wait.entry,
2224 req->flags &= ~REQ_F_POLLED;
2226 if (req->flags & IO_REQ_LINK_FLAGS)
2228 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2231 if (!(req->flags & REQ_F_FIXED_FILE))
2232 io_put_file(req->file);
2234 io_req_put_rsrc_locked(req, ctx);
2236 if (req->task != task) {
2238 io_put_task(task, task_refs);
2243 node = req->comp_list.next;
2244 io_req_add_to_cache(req, ctx);
2248 io_put_task(task, task_refs);
2251 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2252 __must_hold(&ctx->uring_lock)
2254 struct io_wq_work_node *node, *prev;
2255 struct io_submit_state *state = &ctx->submit_state;
2257 if (state->flush_cqes) {
2258 spin_lock(&ctx->completion_lock);
2259 wq_list_for_each(node, prev, &state->compl_reqs) {
2260 struct io_kiocb *req = container_of(node, struct io_kiocb,
2263 if (!(req->flags & REQ_F_CQE_SKIP))
2264 __io_fill_cqe_req(ctx, req);
2267 io_commit_cqring(ctx);
2268 spin_unlock(&ctx->completion_lock);
2269 io_cqring_ev_posted(ctx);
2270 state->flush_cqes = false;
2273 io_free_batch_list(ctx, state->compl_reqs.first);
2274 INIT_WQ_LIST(&state->compl_reqs);
2278 * Drop reference to request, return next in chain (if there is one) if this
2279 * was the last reference to this request.
2281 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2283 struct io_kiocb *nxt = NULL;
2285 if (req_ref_put_and_test(req)) {
2286 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2287 nxt = io_req_find_next(req);
2293 static inline void io_put_req(struct io_kiocb *req)
2295 if (req_ref_put_and_test(req)) {
2301 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2303 /* See comment at the top of this file */
2305 return __io_cqring_events(ctx);
2308 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2310 struct io_rings *rings = ctx->rings;
2312 /* make sure SQ entry isn't read before tail */
2313 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2316 static inline bool io_run_task_work(void)
2318 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2319 __set_current_state(TASK_RUNNING);
2320 clear_notify_signal();
2321 if (task_work_pending(current))
2329 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2331 struct io_wq_work_node *pos, *start, *prev;
2332 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2333 DEFINE_IO_COMP_BATCH(iob);
2337 * Only spin for completions if we don't have multiple devices hanging
2338 * off our complete list.
2340 if (ctx->poll_multi_queue || force_nonspin)
2341 poll_flags |= BLK_POLL_ONESHOT;
2343 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2344 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2345 struct io_rw *rw = io_kiocb_to_cmd(req);
2349 * Move completed and retryable entries to our local lists.
2350 * If we find a request that requires polling, break out
2351 * and complete those lists first, if we have entries there.
2353 if (READ_ONCE(req->iopoll_completed))
2356 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
2357 if (unlikely(ret < 0))
2360 poll_flags |= BLK_POLL_ONESHOT;
2362 /* iopoll may have completed current req */
2363 if (!rq_list_empty(iob.req_list) ||
2364 READ_ONCE(req->iopoll_completed))
2368 if (!rq_list_empty(iob.req_list))
2374 wq_list_for_each_resume(pos, prev) {
2375 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2377 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2378 if (!smp_load_acquire(&req->iopoll_completed))
2381 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2384 req->cqe.flags = io_put_kbuf(req, 0);
2385 __io_fill_cqe_req(req->ctx, req);
2388 if (unlikely(!nr_events))
2391 io_commit_cqring(ctx);
2392 io_cqring_ev_posted_iopoll(ctx);
2393 pos = start ? start->next : ctx->iopoll_list.first;
2394 wq_list_cut(&ctx->iopoll_list, prev, start);
2395 io_free_batch_list(ctx, pos);
2400 * We can't just wait for polled events to come to us, we have to actively
2401 * find and complete them.
2403 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2405 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2408 mutex_lock(&ctx->uring_lock);
2409 while (!wq_list_empty(&ctx->iopoll_list)) {
2410 /* let it sleep and repeat later if can't complete a request */
2411 if (io_do_iopoll(ctx, true) == 0)
2414 * Ensure we allow local-to-the-cpu processing to take place,
2415 * in this case we need to ensure that we reap all events.
2416 * Also let task_work, etc. to progress by releasing the mutex
2418 if (need_resched()) {
2419 mutex_unlock(&ctx->uring_lock);
2421 mutex_lock(&ctx->uring_lock);
2424 mutex_unlock(&ctx->uring_lock);
2427 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2429 unsigned int nr_events = 0;
2431 unsigned long check_cq;
2434 * Don't enter poll loop if we already have events pending.
2435 * If we do, we can potentially be spinning for commands that
2436 * already triggered a CQE (eg in error).
2438 check_cq = READ_ONCE(ctx->check_cq);
2439 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2440 __io_cqring_overflow_flush(ctx, false);
2441 if (io_cqring_events(ctx))
2445 * Similarly do not spin if we have not informed the user of any
2448 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
2453 * If a submit got punted to a workqueue, we can have the
2454 * application entering polling for a command before it gets
2455 * issued. That app will hold the uring_lock for the duration
2456 * of the poll right here, so we need to take a breather every
2457 * now and then to ensure that the issue has a chance to add
2458 * the poll to the issued list. Otherwise we can spin here
2459 * forever, while the workqueue is stuck trying to acquire the
2462 if (wq_list_empty(&ctx->iopoll_list)) {
2463 u32 tail = ctx->cached_cq_tail;
2465 mutex_unlock(&ctx->uring_lock);
2467 mutex_lock(&ctx->uring_lock);
2469 /* some requests don't go through iopoll_list */
2470 if (tail != ctx->cached_cq_tail ||
2471 wq_list_empty(&ctx->iopoll_list))
2474 ret = io_do_iopoll(ctx, !min);
2479 } while (nr_events < min && !need_resched());
2484 static void kiocb_end_write(struct io_kiocb *req)
2487 * Tell lockdep we inherited freeze protection from submission
2490 if (req->flags & REQ_F_ISREG) {
2491 struct super_block *sb = file_inode(req->file)->i_sb;
2493 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2499 static bool io_resubmit_prep(struct io_kiocb *req)
2501 struct io_async_rw *io = req->async_data;
2503 if (!req_has_async_data(req))
2504 return !io_req_prep_async(req);
2505 iov_iter_restore(&io->s.iter, &io->s.iter_state);
2509 static bool io_rw_should_reissue(struct io_kiocb *req)
2511 umode_t mode = file_inode(req->file)->i_mode;
2512 struct io_ring_ctx *ctx = req->ctx;
2514 if (!S_ISBLK(mode) && !S_ISREG(mode))
2516 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2517 !(ctx->flags & IORING_SETUP_IOPOLL)))
2520 * If ref is dying, we might be running poll reap from the exit work.
2521 * Don't attempt to reissue from that path, just let it fail with
2524 if (percpu_ref_is_dying(&ctx->refs))
2527 * Play it safe and assume not safe to re-import and reissue if we're
2528 * not in the original thread group (or in task context).
2530 if (!same_thread_group(req->task, current) || !in_task())
2535 static bool io_resubmit_prep(struct io_kiocb *req)
2539 static bool io_rw_should_reissue(struct io_kiocb *req)
2545 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2547 struct io_rw *rw = io_kiocb_to_cmd(req);
2549 if (rw->kiocb.ki_flags & IOCB_WRITE) {
2550 kiocb_end_write(req);
2551 fsnotify_modify(req->file);
2553 fsnotify_access(req->file);
2555 if (unlikely(res != req->cqe.res)) {
2556 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2557 io_rw_should_reissue(req)) {
2558 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2567 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2570 req->cqe.flags |= io_put_kbuf(req, 0);
2571 req->flags |= REQ_F_COMPLETE_INLINE;
2572 io_req_add_compl_list(req);
2574 req->cqe.flags |= io_put_kbuf(req, IO_URING_F_UNLOCKED);
2575 io_req_complete_post(req);
2579 static void __io_complete_rw(struct io_kiocb *req, long res,
2580 unsigned int issue_flags)
2582 if (__io_complete_rw_common(req, res))
2584 io_req_set_res(req, req->cqe.res, io_put_kbuf(req, issue_flags));
2585 __io_req_complete(req, issue_flags);
2588 static void io_complete_rw(struct kiocb *kiocb, long res)
2590 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
2591 struct io_kiocb *req = cmd_to_io_kiocb(rw);
2593 if (__io_complete_rw_common(req, res))
2595 io_req_set_res(req, res, 0);
2596 req->io_task_work.func = io_req_task_complete;
2597 io_req_task_prio_work_add(req);
2600 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
2602 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
2603 struct io_kiocb *req = cmd_to_io_kiocb(rw);
2605 if (kiocb->ki_flags & IOCB_WRITE)
2606 kiocb_end_write(req);
2607 if (unlikely(res != req->cqe.res)) {
2608 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2609 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2615 /* order with io_iopoll_complete() checking ->iopoll_completed */
2616 smp_store_release(&req->iopoll_completed, 1);
2620 * After the iocb has been issued, it's safe to be found on the poll list.
2621 * Adding the kiocb to the list AFTER submission ensures that we don't
2622 * find it from a io_do_iopoll() thread before the issuer is done
2623 * accessing the kiocb cookie.
2625 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2627 struct io_ring_ctx *ctx = req->ctx;
2628 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2630 /* workqueue context doesn't hold uring_lock, grab it now */
2631 if (unlikely(needs_lock))
2632 mutex_lock(&ctx->uring_lock);
2635 * Track whether we have multiple files in our lists. This will impact
2636 * how we do polling eventually, not spinning if we're on potentially
2637 * different devices.
2639 if (wq_list_empty(&ctx->iopoll_list)) {
2640 ctx->poll_multi_queue = false;
2641 } else if (!ctx->poll_multi_queue) {
2642 struct io_kiocb *list_req;
2644 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2646 if (list_req->file != req->file)
2647 ctx->poll_multi_queue = true;
2651 * For fast devices, IO may have already completed. If it has, add
2652 * it to the front so we find it first.
2654 if (READ_ONCE(req->iopoll_completed))
2655 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2657 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2659 if (unlikely(needs_lock)) {
2661 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2662 * in sq thread task context or in io worker task context. If
2663 * current task context is sq thread, we don't need to check
2664 * whether should wake up sq thread.
2666 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2667 wq_has_sleeper(&ctx->sq_data->wait))
2668 wake_up(&ctx->sq_data->wait);
2670 mutex_unlock(&ctx->uring_lock);
2674 static bool io_bdev_nowait(struct block_device *bdev)
2676 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2680 * If we tracked the file through the SCM inflight mechanism, we could support
2681 * any file. For now, just ensure that anything potentially problematic is done
2684 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2686 if (S_ISBLK(mode)) {
2687 if (IS_ENABLED(CONFIG_BLOCK) &&
2688 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2694 if (S_ISREG(mode)) {
2695 if (IS_ENABLED(CONFIG_BLOCK) &&
2696 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2697 file->f_op != &io_uring_fops)
2702 /* any ->read/write should understand O_NONBLOCK */
2703 if (file->f_flags & O_NONBLOCK)
2705 return file->f_mode & FMODE_NOWAIT;
2709 * If we tracked the file through the SCM inflight mechanism, we could support
2710 * any file. For now, just ensure that anything potentially problematic is done
2713 static unsigned int io_file_get_flags(struct file *file)
2715 umode_t mode = file_inode(file)->i_mode;
2716 unsigned int res = 0;
2720 if (__io_file_supports_nowait(file, mode))
2722 if (io_file_need_scm(file))
2727 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2729 return req->flags & REQ_F_SUPPORT_NOWAIT;
2732 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2734 struct io_rw *rw = io_kiocb_to_cmd(req);
2738 rw->kiocb.ki_pos = READ_ONCE(sqe->off);
2739 /* used for fixed read/write too - just read unconditionally */
2740 req->buf_index = READ_ONCE(sqe->buf_index);
2742 if (req->opcode == IORING_OP_READ_FIXED ||
2743 req->opcode == IORING_OP_WRITE_FIXED) {
2744 struct io_ring_ctx *ctx = req->ctx;
2747 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
2749 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
2750 req->imu = ctx->user_bufs[index];
2751 io_req_set_rsrc_node(req, ctx, 0);
2754 ioprio = READ_ONCE(sqe->ioprio);
2756 ret = ioprio_check_cap(ioprio);
2760 rw->kiocb.ki_ioprio = ioprio;
2762 rw->kiocb.ki_ioprio = get_current_ioprio();
2765 rw->addr = READ_ONCE(sqe->addr);
2766 rw->len = READ_ONCE(sqe->len);
2767 rw->flags = READ_ONCE(sqe->rw_flags);
2771 static void io_readv_writev_cleanup(struct io_kiocb *req)
2773 struct io_async_rw *io = req->async_data;
2775 kfree(io->free_iovec);
2778 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2784 case -ERESTARTNOINTR:
2785 case -ERESTARTNOHAND:
2786 case -ERESTART_RESTARTBLOCK:
2788 * We can't just restart the syscall, since previously
2789 * submitted sqes may already be in progress. Just fail this
2795 kiocb->ki_complete(kiocb, ret);
2799 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
2801 struct io_rw *rw = io_kiocb_to_cmd(req);
2803 if (rw->kiocb.ki_pos != -1)
2804 return &rw->kiocb.ki_pos;
2806 if (!(req->file->f_mode & FMODE_STREAM)) {
2807 req->flags |= REQ_F_CUR_POS;
2808 rw->kiocb.ki_pos = req->file->f_pos;
2809 return &rw->kiocb.ki_pos;
2812 rw->kiocb.ki_pos = 0;
2816 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
2817 unsigned int issue_flags)
2819 struct io_async_rw *io = req->async_data;
2820 struct io_rw *rw = io_kiocb_to_cmd(req);
2822 /* add previously done IO, if any */
2823 if (req_has_async_data(req) && io->bytes_done > 0) {
2825 ret = io->bytes_done;
2827 ret += io->bytes_done;
2830 if (req->flags & REQ_F_CUR_POS)
2831 req->file->f_pos = rw->kiocb.ki_pos;
2832 if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
2833 __io_complete_rw(req, ret, issue_flags);
2835 io_rw_done(&rw->kiocb, ret);
2837 if (req->flags & REQ_F_REISSUE) {
2838 req->flags &= ~REQ_F_REISSUE;
2839 if (io_resubmit_prep(req))
2840 io_req_task_queue_reissue(req);
2842 io_req_task_queue_fail(req, ret);
2846 static int __io_import_fixed(struct io_kiocb *req, int ddir,
2847 struct iov_iter *iter, struct io_mapped_ubuf *imu)
2849 struct io_rw *rw = io_kiocb_to_cmd(req);
2850 size_t len = rw->len;
2851 u64 buf_end, buf_addr = rw->addr;
2854 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2856 /* not inside the mapped region */
2857 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2861 * May not be a start of buffer, set size appropriately
2862 * and advance us to the beginning.
2864 offset = buf_addr - imu->ubuf;
2865 iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
2869 * Don't use iov_iter_advance() here, as it's really slow for
2870 * using the latter parts of a big fixed buffer - it iterates
2871 * over each segment manually. We can cheat a bit here, because
2874 * 1) it's a BVEC iter, we set it up
2875 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2876 * first and last bvec
2878 * So just find our index, and adjust the iterator afterwards.
2879 * If the offset is within the first bvec (or the whole first
2880 * bvec, just use iov_iter_advance(). This makes it easier
2881 * since we can just skip the first segment, which may not
2882 * be PAGE_SIZE aligned.
2884 const struct bio_vec *bvec = imu->bvec;
2886 if (offset <= bvec->bv_len) {
2887 iov_iter_advance(iter, offset);
2889 unsigned long seg_skip;
2891 /* skip first vec */
2892 offset -= bvec->bv_len;
2893 seg_skip = 1 + (offset >> PAGE_SHIFT);
2895 iter->bvec = bvec + seg_skip;
2896 iter->nr_segs -= seg_skip;
2897 iter->count -= bvec->bv_len + offset;
2898 iter->iov_offset = offset & ~PAGE_MASK;
2905 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2906 unsigned int issue_flags)
2908 if (WARN_ON_ONCE(!req->imu))
2910 return __io_import_fixed(req, rw, iter, req->imu);
2913 static int io_buffer_add_list(struct io_ring_ctx *ctx,
2914 struct io_buffer_list *bl, unsigned int bgid)
2917 if (bgid < BGID_ARRAY)
2920 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
2923 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
2924 struct io_buffer_list *bl)
2926 if (!list_empty(&bl->buf_list)) {
2927 struct io_buffer *kbuf;
2929 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
2930 list_del(&kbuf->list);
2931 if (*len > kbuf->len)
2933 req->flags |= REQ_F_BUFFER_SELECTED;
2935 req->buf_index = kbuf->bid;
2936 return u64_to_user_ptr(kbuf->addr);
2941 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
2942 struct io_buffer_list *bl,
2943 unsigned int issue_flags)
2945 struct io_uring_buf_ring *br = bl->buf_ring;
2946 struct io_uring_buf *buf;
2947 __u16 head = bl->head;
2949 if (unlikely(smp_load_acquire(&br->tail) == head))
2953 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
2954 buf = &br->bufs[head];
2956 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
2957 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
2958 buf = page_address(bl->buf_pages[index]);
2961 if (*len > buf->len)
2963 req->flags |= REQ_F_BUFFER_RING;
2965 req->buf_index = buf->bid;
2967 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
2969 * If we came in unlocked, we have no choice but to consume the
2970 * buffer here. This does mean it'll be pinned until the IO
2971 * completes. But coming in unlocked means we're in io-wq
2972 * context, hence there should be no further retry. For the
2973 * locked case, the caller must ensure to call the commit when
2974 * the transfer completes (or if we get -EAGAIN and must poll
2977 req->buf_list = NULL;
2980 return u64_to_user_ptr(buf->addr);
2983 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
2984 unsigned int issue_flags)
2986 struct io_ring_ctx *ctx = req->ctx;
2987 struct io_buffer_list *bl;
2988 void __user *ret = NULL;
2990 io_ring_submit_lock(req->ctx, issue_flags);
2992 bl = io_buffer_get_list(ctx, req->buf_index);
2994 if (bl->buf_nr_pages)
2995 ret = io_ring_buffer_select(req, len, bl, issue_flags);
2997 ret = io_provided_buffer_select(req, len, bl);
2999 io_ring_submit_unlock(req->ctx, issue_flags);
3003 #ifdef CONFIG_COMPAT
3004 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3005 unsigned int issue_flags)
3007 struct io_rw *rw = io_kiocb_to_cmd(req);
3008 struct compat_iovec __user *uiov;
3009 compat_ssize_t clen;
3013 uiov = u64_to_user_ptr(rw->addr);
3014 if (!access_ok(uiov, sizeof(*uiov)))
3016 if (__get_user(clen, &uiov->iov_len))
3022 buf = io_buffer_select(req, &len, issue_flags);
3025 rw->addr = (unsigned long) buf;
3026 iov[0].iov_base = buf;
3027 rw->len = iov[0].iov_len = (compat_size_t) len;
3032 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3033 unsigned int issue_flags)
3035 struct io_rw *rw = io_kiocb_to_cmd(req);
3036 struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
3040 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3043 len = iov[0].iov_len;
3046 buf = io_buffer_select(req, &len, issue_flags);
3049 rw->addr = (unsigned long) buf;
3050 iov[0].iov_base = buf;
3051 rw->len = iov[0].iov_len = len;
3055 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3056 unsigned int issue_flags)
3058 struct io_rw *rw = io_kiocb_to_cmd(req);
3060 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3061 iov[0].iov_base = u64_to_user_ptr(rw->addr);
3062 iov[0].iov_len = rw->len;
3068 #ifdef CONFIG_COMPAT
3069 if (req->ctx->compat)
3070 return io_compat_import(req, iov, issue_flags);
3073 return __io_iov_buffer_select(req, iov, issue_flags);
3076 static inline bool io_do_buffer_select(struct io_kiocb *req)
3078 if (!(req->flags & REQ_F_BUFFER_SELECT))
3080 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3083 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
3084 struct io_rw_state *s,
3085 unsigned int issue_flags)
3087 struct io_rw *rw = io_kiocb_to_cmd(req);
3088 struct iov_iter *iter = &s->iter;
3089 u8 opcode = req->opcode;
3090 struct iovec *iovec;
3095 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3096 ret = io_import_fixed(req, ddir, iter, issue_flags);
3098 return ERR_PTR(ret);
3102 buf = u64_to_user_ptr(rw->addr);
3105 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3106 if (io_do_buffer_select(req)) {
3107 buf = io_buffer_select(req, &sqe_len, issue_flags);
3109 return ERR_PTR(-ENOBUFS);
3110 rw->addr = (unsigned long) buf;
3114 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
3116 return ERR_PTR(ret);
3120 iovec = s->fast_iov;
3121 if (req->flags & REQ_F_BUFFER_SELECT) {
3122 ret = io_iov_buffer_select(req, iovec, issue_flags);
3124 return ERR_PTR(ret);
3125 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
3129 ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3131 if (unlikely(ret < 0))
3132 return ERR_PTR(ret);
3136 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3137 struct iovec **iovec, struct io_rw_state *s,
3138 unsigned int issue_flags)
3140 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3141 if (unlikely(IS_ERR(*iovec)))
3142 return PTR_ERR(*iovec);
3144 iov_iter_save_state(&s->iter, &s->iter_state);
3148 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3150 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3154 * For files that don't have ->read_iter() and ->write_iter(), handle them
3155 * by looping over ->read() or ->write() manually.
3157 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
3159 struct kiocb *kiocb = &rw->kiocb;
3160 struct file *file = kiocb->ki_filp;
3165 * Don't support polled IO through this interface, and we can't
3166 * support non-blocking either. For the latter, this just causes
3167 * the kiocb to be handled from an async context.
3169 if (kiocb->ki_flags & IOCB_HIPRI)
3171 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3172 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3175 ppos = io_kiocb_ppos(kiocb);
3177 while (iov_iter_count(iter)) {
3181 if (!iov_iter_is_bvec(iter)) {
3182 iovec = iov_iter_iovec(iter);
3184 iovec.iov_base = u64_to_user_ptr(rw->addr);
3185 iovec.iov_len = rw->len;
3189 nr = file->f_op->read(file, iovec.iov_base,
3190 iovec.iov_len, ppos);
3192 nr = file->f_op->write(file, iovec.iov_base,
3193 iovec.iov_len, ppos);
3202 if (!iov_iter_is_bvec(iter)) {
3203 iov_iter_advance(iter, nr);
3210 if (nr != iovec.iov_len)
3217 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3218 const struct iovec *fast_iov, struct iov_iter *iter)
3220 struct io_async_rw *io = req->async_data;
3222 memcpy(&io->s.iter, iter, sizeof(*iter));
3223 io->free_iovec = iovec;
3225 /* can only be fixed buffers, no need to do anything */
3226 if (iov_iter_is_bvec(iter))
3229 unsigned iov_off = 0;
3231 io->s.iter.iov = io->s.fast_iov;
3232 if (iter->iov != fast_iov) {
3233 iov_off = iter->iov - fast_iov;
3234 io->s.iter.iov += iov_off;
3236 if (io->s.fast_iov != fast_iov)
3237 memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
3238 sizeof(struct iovec) * iter->nr_segs);
3240 req->flags |= REQ_F_NEED_CLEANUP;
3244 bool io_alloc_async_data(struct io_kiocb *req)
3246 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3247 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3248 if (req->async_data) {
3249 req->flags |= REQ_F_ASYNC_DATA;
3255 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3256 struct io_rw_state *s, bool force)
3258 if (!force && !io_op_defs[req->opcode].prep_async)
3260 if (!req_has_async_data(req)) {
3261 struct io_async_rw *iorw;
3263 if (io_alloc_async_data(req)) {
3268 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3269 iorw = req->async_data;
3270 /* we've copied and mapped the iter, ensure state is saved */
3271 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3276 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3278 struct io_async_rw *iorw = req->async_data;
3282 /* submission path, ->uring_lock should already be taken */
3283 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3284 if (unlikely(ret < 0))
3287 iorw->bytes_done = 0;
3288 iorw->free_iovec = iov;
3290 req->flags |= REQ_F_NEED_CLEANUP;
3294 static int io_readv_prep_async(struct io_kiocb *req)
3296 return io_rw_prep_async(req, READ);
3299 static int io_writev_prep_async(struct io_kiocb *req)
3301 return io_rw_prep_async(req, WRITE);
3305 * This is our waitqueue callback handler, registered through __folio_lock_async()
3306 * when we initially tried to do the IO with the iocb armed our waitqueue.
3307 * This gets called when the page is unlocked, and we generally expect that to
3308 * happen when the page IO is completed and the page is now uptodate. This will
3309 * queue a task_work based retry of the operation, attempting to copy the data
3310 * again. If the latter fails because the page was NOT uptodate, then we will
3311 * do a thread based blocking retry of the operation. That's the unexpected
3314 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3315 int sync, void *arg)
3317 struct wait_page_queue *wpq;
3318 struct io_kiocb *req = wait->private;
3319 struct io_rw *rw = io_kiocb_to_cmd(req);
3320 struct wait_page_key *key = arg;
3322 wpq = container_of(wait, struct wait_page_queue, wait);
3324 if (!wake_page_match(wpq, key))
3327 rw->kiocb.ki_flags &= ~IOCB_WAITQ;
3328 list_del_init(&wait->entry);
3329 io_req_task_queue(req);
3334 * This controls whether a given IO request should be armed for async page
3335 * based retry. If we return false here, the request is handed to the async
3336 * worker threads for retry. If we're doing buffered reads on a regular file,
3337 * we prepare a private wait_page_queue entry and retry the operation. This
3338 * will either succeed because the page is now uptodate and unlocked, or it
3339 * will register a callback when the page is unlocked at IO completion. Through
3340 * that callback, io_uring uses task_work to setup a retry of the operation.
3341 * That retry will attempt the buffered read again. The retry will generally
3342 * succeed, or in rare cases where it fails, we then fall back to using the
3343 * async worker threads for a blocking retry.
3345 static bool io_rw_should_retry(struct io_kiocb *req)
3347 struct io_async_rw *io = req->async_data;
3348 struct wait_page_queue *wait = &io->wpq;
3349 struct io_rw *rw = io_kiocb_to_cmd(req);
3350 struct kiocb *kiocb = &rw->kiocb;
3352 /* never retry for NOWAIT, we just complete with -EAGAIN */
3353 if (req->flags & REQ_F_NOWAIT)
3356 /* Only for buffered IO */
3357 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3361 * just use poll if we can, and don't attempt if the fs doesn't
3362 * support callback based unlocks
3364 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3367 wait->wait.func = io_async_buf_func;
3368 wait->wait.private = req;
3369 wait->wait.flags = 0;
3370 INIT_LIST_HEAD(&wait->wait.entry);
3371 kiocb->ki_flags |= IOCB_WAITQ;
3372 kiocb->ki_flags &= ~IOCB_NOWAIT;
3373 kiocb->ki_waitq = wait;
3377 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
3379 struct file *file = rw->kiocb.ki_filp;
3381 if (likely(file->f_op->read_iter))
3382 return call_read_iter(file, &rw->kiocb, iter);
3383 else if (file->f_op->read)
3384 return loop_rw_iter(READ, rw, iter);
3389 static bool need_read_all(struct io_kiocb *req)
3391 return req->flags & REQ_F_ISREG ||
3392 S_ISBLK(file_inode(req->file)->i_mode);
3395 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3397 struct io_rw *rw = io_kiocb_to_cmd(req);
3398 struct kiocb *kiocb = &rw->kiocb;
3399 struct io_ring_ctx *ctx = req->ctx;
3400 struct file *file = req->file;
3403 if (unlikely(!file || !(file->f_mode & mode)))
3406 if (!io_req_ffs_set(req))
3407 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3409 kiocb->ki_flags = iocb_flags(file);
3410 ret = kiocb_set_rw_flags(kiocb, rw->flags);
3415 * If the file is marked O_NONBLOCK, still allow retry for it if it
3416 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3417 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3419 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3420 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3421 req->flags |= REQ_F_NOWAIT;
3423 if (ctx->flags & IORING_SETUP_IOPOLL) {
3424 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3427 kiocb->private = NULL;
3428 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3429 kiocb->ki_complete = io_complete_rw_iopoll;
3430 req->iopoll_completed = 0;
3432 if (kiocb->ki_flags & IOCB_HIPRI)
3434 kiocb->ki_complete = io_complete_rw;
3440 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3442 struct io_rw *rw = io_kiocb_to_cmd(req);
3443 struct io_rw_state __s, *s = &__s;
3444 struct iovec *iovec;
3445 struct kiocb *kiocb = &rw->kiocb;
3446 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3447 struct io_async_rw *io;
3451 if (!req_has_async_data(req)) {
3452 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3453 if (unlikely(ret < 0))
3456 io = req->async_data;
3460 * Safe and required to re-import if we're using provided
3461 * buffers, as we dropped the selected one before retry.
3463 if (io_do_buffer_select(req)) {
3464 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3465 if (unlikely(ret < 0))
3470 * We come here from an earlier attempt, restore our state to
3471 * match in case it doesn't. It's cheap enough that we don't
3472 * need to make this conditional.
3474 iov_iter_restore(&s->iter, &s->iter_state);
3477 ret = io_rw_init_file(req, FMODE_READ);
3478 if (unlikely(ret)) {
3482 req->cqe.res = iov_iter_count(&s->iter);
3484 if (force_nonblock) {
3485 /* If the file doesn't support async, just async punt */
3486 if (unlikely(!io_file_supports_nowait(req))) {
3487 ret = io_setup_async_rw(req, iovec, s, true);
3488 return ret ?: -EAGAIN;
3490 kiocb->ki_flags |= IOCB_NOWAIT;
3492 /* Ensure we clear previously set non-block flag */
3493 kiocb->ki_flags &= ~IOCB_NOWAIT;
3496 ppos = io_kiocb_update_pos(req);
3498 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
3499 if (unlikely(ret)) {
3504 ret = io_iter_do_read(rw, &s->iter);
3506 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3507 req->flags &= ~REQ_F_REISSUE;
3508 /* if we can poll, just do that */
3509 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3511 /* IOPOLL retry should happen for io-wq threads */
3512 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3514 /* no retry on NONBLOCK nor RWF_NOWAIT */
3515 if (req->flags & REQ_F_NOWAIT)
3518 } else if (ret == -EIOCBQUEUED) {
3520 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
3521 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3522 /* read all, failed, already did sync or don't want to retry */
3527 * Don't depend on the iter state matching what was consumed, or being
3528 * untouched in case of error. Restore it and we'll advance it
3529 * manually if we need to.
3531 iov_iter_restore(&s->iter, &s->iter_state);
3533 ret2 = io_setup_async_rw(req, iovec, s, true);
3538 io = req->async_data;
3541 * Now use our persistent iterator and state, if we aren't already.
3542 * We've restored and mapped the iter to match.
3547 * We end up here because of a partial read, either from
3548 * above or inside this loop. Advance the iter by the bytes
3549 * that were consumed.
3551 iov_iter_advance(&s->iter, ret);
3552 if (!iov_iter_count(&s->iter))
3554 io->bytes_done += ret;
3555 iov_iter_save_state(&s->iter, &s->iter_state);
3557 /* if we can retry, do so with the callbacks armed */
3558 if (!io_rw_should_retry(req)) {
3559 kiocb->ki_flags &= ~IOCB_WAITQ;
3564 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3565 * we get -EIOCBQUEUED, then we'll get a notification when the
3566 * desired page gets unlocked. We can also get a partial read
3567 * here, and if we do, then just retry at the new offset.
3569 ret = io_iter_do_read(rw, &s->iter);
3570 if (ret == -EIOCBQUEUED)
3571 return IOU_ISSUE_SKIP_COMPLETE;
3572 /* we got some bytes, but not all. retry. */
3573 kiocb->ki_flags &= ~IOCB_WAITQ;
3574 iov_iter_restore(&s->iter, &s->iter_state);
3577 kiocb_done(req, ret, issue_flags);
3579 /* it's faster to check here then delegate to kfree */
3582 return IOU_ISSUE_SKIP_COMPLETE;
3585 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3587 struct io_rw *rw = io_kiocb_to_cmd(req);
3588 struct io_rw_state __s, *s = &__s;
3589 struct iovec *iovec;
3590 struct kiocb *kiocb = &rw->kiocb;
3591 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3595 if (!req_has_async_data(req)) {
3596 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3597 if (unlikely(ret < 0))
3600 struct io_async_rw *io = req->async_data;
3603 iov_iter_restore(&s->iter, &s->iter_state);
3606 ret = io_rw_init_file(req, FMODE_WRITE);
3607 if (unlikely(ret)) {
3611 req->cqe.res = iov_iter_count(&s->iter);
3613 if (force_nonblock) {
3614 /* If the file doesn't support async, just async punt */
3615 if (unlikely(!io_file_supports_nowait(req)))
3618 /* file path doesn't support NOWAIT for non-direct_IO */
3619 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3620 (req->flags & REQ_F_ISREG))
3623 kiocb->ki_flags |= IOCB_NOWAIT;
3625 /* Ensure we clear previously set non-block flag */
3626 kiocb->ki_flags &= ~IOCB_NOWAIT;
3629 ppos = io_kiocb_update_pos(req);
3631 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
3636 * Open-code file_start_write here to grab freeze protection,
3637 * which will be released by another thread in
3638 * io_complete_rw(). Fool lockdep by telling it the lock got
3639 * released so that it doesn't complain about the held lock when
3640 * we return to userspace.
3642 if (req->flags & REQ_F_ISREG) {
3643 sb_start_write(file_inode(req->file)->i_sb);
3644 __sb_writers_release(file_inode(req->file)->i_sb,
3647 kiocb->ki_flags |= IOCB_WRITE;
3649 if (likely(req->file->f_op->write_iter))
3650 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3651 else if (req->file->f_op->write)
3652 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
3656 if (req->flags & REQ_F_REISSUE) {
3657 req->flags &= ~REQ_F_REISSUE;
3662 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3663 * retry them without IOCB_NOWAIT.
3665 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3667 /* no retry on NONBLOCK nor RWF_NOWAIT */
3668 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3670 if (!force_nonblock || ret2 != -EAGAIN) {
3671 /* IOPOLL retry should happen for io-wq threads */
3672 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3675 kiocb_done(req, ret2, issue_flags);
3676 ret = IOU_ISSUE_SKIP_COMPLETE;
3679 iov_iter_restore(&s->iter, &s->iter_state);
3680 ret = io_setup_async_rw(req, iovec, s, false);
3681 return ret ?: -EAGAIN;
3684 /* it's reportedly faster than delegating the null check to kfree() */
3690 static int io_msg_ring_prep(struct io_kiocb *req,
3691 const struct io_uring_sqe *sqe)
3693 struct io_msg *msg = io_kiocb_to_cmd(req);
3695 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
3696 sqe->buf_index || sqe->personality))
3699 msg->user_data = READ_ONCE(sqe->off);
3700 msg->len = READ_ONCE(sqe->len);
3704 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
3706 struct io_msg *msg = io_kiocb_to_cmd(req);
3707 struct io_ring_ctx *target_ctx;
3712 if (req->file->f_op != &io_uring_fops)
3716 target_ctx = req->file->private_data;
3718 spin_lock(&target_ctx->completion_lock);
3719 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
3720 io_commit_cqring(target_ctx);
3721 spin_unlock(&target_ctx->completion_lock);
3724 io_cqring_ev_posted(target_ctx);
3731 io_req_set_res(req, ret, 0);
3732 /* put file to avoid an attempt to IOPOLL the req */
3733 io_put_file(req->file);
3739 * Note when io_fixed_fd_install() returns error value, it will ensure
3740 * fput() is called correspondingly.
3742 int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
3743 struct file *file, unsigned int file_slot)
3745 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
3746 struct io_ring_ctx *ctx = req->ctx;
3749 io_ring_submit_lock(ctx, issue_flags);
3752 ret = io_file_bitmap_get(ctx);
3753 if (unlikely(ret < 0))
3760 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
3761 if (!ret && alloc_slot)
3764 io_ring_submit_unlock(ctx, issue_flags);
3765 if (unlikely(ret < 0))
3770 static int io_remove_buffers_prep(struct io_kiocb *req,
3771 const struct io_uring_sqe *sqe)
3773 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3776 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
3780 tmp = READ_ONCE(sqe->fd);
3781 if (!tmp || tmp > USHRT_MAX)
3784 memset(p, 0, sizeof(*p));
3786 p->bgid = READ_ONCE(sqe->buf_group);
3790 static int __io_remove_buffers(struct io_ring_ctx *ctx,
3791 struct io_buffer_list *bl, unsigned nbufs)
3795 /* shouldn't happen */
3799 if (bl->buf_nr_pages) {
3802 i = bl->buf_ring->tail - bl->head;
3803 for (j = 0; j < bl->buf_nr_pages; j++)
3804 unpin_user_page(bl->buf_pages[j]);
3805 kvfree(bl->buf_pages);
3806 bl->buf_pages = NULL;
3807 bl->buf_nr_pages = 0;
3808 /* make sure it's seen as empty */
3809 INIT_LIST_HEAD(&bl->buf_list);
3813 /* the head kbuf is the list itself */
3814 while (!list_empty(&bl->buf_list)) {
3815 struct io_buffer *nxt;
3817 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
3818 list_del(&nxt->list);
3828 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3830 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3831 struct io_ring_ctx *ctx = req->ctx;
3832 struct io_buffer_list *bl;
3835 io_ring_submit_lock(ctx, issue_flags);
3838 bl = io_buffer_get_list(ctx, p->bgid);
3841 /* can't use provide/remove buffers command on mapped buffers */
3842 if (!bl->buf_nr_pages)
3843 ret = __io_remove_buffers(ctx, bl, p->nbufs);
3848 /* complete before unlock, IOPOLL may need the lock */
3849 io_req_set_res(req, ret, 0);
3850 __io_req_complete(req, issue_flags);
3851 io_ring_submit_unlock(ctx, issue_flags);
3852 return IOU_ISSUE_SKIP_COMPLETE;
3855 static int io_provide_buffers_prep(struct io_kiocb *req,
3856 const struct io_uring_sqe *sqe)
3858 unsigned long size, tmp_check;
3859 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3862 if (sqe->rw_flags || sqe->splice_fd_in)
3865 tmp = READ_ONCE(sqe->fd);
3866 if (!tmp || tmp > USHRT_MAX)
3869 p->addr = READ_ONCE(sqe->addr);
3870 p->len = READ_ONCE(sqe->len);
3872 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3875 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3878 size = (unsigned long)p->len * p->nbufs;
3879 if (!access_ok(u64_to_user_ptr(p->addr), size))
3882 p->bgid = READ_ONCE(sqe->buf_group);
3883 tmp = READ_ONCE(sqe->off);
3884 if (tmp > USHRT_MAX)
3890 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
3892 struct io_buffer *buf;
3897 * Completions that don't happen inline (eg not under uring_lock) will
3898 * add to ->io_buffers_comp. If we don't have any free buffers, check
3899 * the completion list and splice those entries first.
3901 if (!list_empty_careful(&ctx->io_buffers_comp)) {
3902 spin_lock(&ctx->completion_lock);
3903 if (!list_empty(&ctx->io_buffers_comp)) {
3904 list_splice_init(&ctx->io_buffers_comp,
3905 &ctx->io_buffers_cache);
3906 spin_unlock(&ctx->completion_lock);
3909 spin_unlock(&ctx->completion_lock);
3913 * No free buffers and no completion entries either. Allocate a new
3914 * page worth of buffer entries and add those to our freelist.
3916 page = alloc_page(GFP_KERNEL_ACCOUNT);
3920 list_add(&page->lru, &ctx->io_buffers_pages);
3922 buf = page_address(page);
3923 bufs_in_page = PAGE_SIZE / sizeof(*buf);
3924 while (bufs_in_page) {
3925 list_add_tail(&buf->list, &ctx->io_buffers_cache);
3933 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
3934 struct io_buffer_list *bl)
3936 struct io_buffer *buf;
3937 u64 addr = pbuf->addr;
3938 int i, bid = pbuf->bid;
3940 for (i = 0; i < pbuf->nbufs; i++) {
3941 if (list_empty(&ctx->io_buffers_cache) &&
3942 io_refill_buffer_cache(ctx))
3944 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
3946 list_move_tail(&buf->list, &bl->buf_list);
3948 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
3950 buf->bgid = pbuf->bgid;
3956 return i ? 0 : -ENOMEM;
3959 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
3963 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
3968 for (i = 0; i < BGID_ARRAY; i++) {
3969 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
3970 ctx->io_bl[i].bgid = i;
3976 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3978 struct io_provide_buf *p = io_kiocb_to_cmd(req);
3979 struct io_ring_ctx *ctx = req->ctx;
3980 struct io_buffer_list *bl;
3983 io_ring_submit_lock(ctx, issue_flags);
3985 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
3986 ret = io_init_bl_list(ctx);
3991 bl = io_buffer_get_list(ctx, p->bgid);
3992 if (unlikely(!bl)) {
3993 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
3998 INIT_LIST_HEAD(&bl->buf_list);
3999 ret = io_buffer_add_list(ctx, bl, p->bgid);
4005 /* can't add buffers via this command for a mapped buffer ring */
4006 if (bl->buf_nr_pages) {
4011 ret = io_add_buffers(ctx, p, bl);
4015 /* complete before unlock, IOPOLL may need the lock */
4016 io_req_set_res(req, ret, 0);
4017 __io_req_complete(req, issue_flags);
4018 io_ring_submit_unlock(ctx, issue_flags);
4019 return IOU_ISSUE_SKIP_COMPLETE;
4022 static __maybe_unused int io_eopnotsupp_prep(struct io_kiocb *kiocb,
4023 const struct io_uring_sqe *sqe)
4028 #if defined(CONFIG_NET)
4029 static int io_shutdown_prep(struct io_kiocb *req,
4030 const struct io_uring_sqe *sqe)
4032 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
4034 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
4035 sqe->buf_index || sqe->splice_fd_in))
4038 shutdown->how = READ_ONCE(sqe->len);
4042 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4044 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
4045 struct socket *sock;
4048 if (issue_flags & IO_URING_F_NONBLOCK)
4051 sock = sock_from_file(req->file);
4052 if (unlikely(!sock))
4055 ret = __sys_shutdown_sock(sock, shutdown->how);
4056 io_req_set_res(req, ret, 0);
4060 static bool io_net_retry(struct socket *sock, int flags)
4062 if (!(flags & MSG_WAITALL))
4064 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4067 static int io_setup_async_msg(struct io_kiocb *req,
4068 struct io_async_msghdr *kmsg)
4070 struct io_async_msghdr *async_msg = req->async_data;
4074 if (io_alloc_async_data(req)) {
4075 kfree(kmsg->free_iov);
4078 async_msg = req->async_data;
4079 req->flags |= REQ_F_NEED_CLEANUP;
4080 memcpy(async_msg, kmsg, sizeof(*kmsg));
4081 async_msg->msg.msg_name = &async_msg->addr;
4082 /* if were using fast_iov, set it to the new one */
4083 if (!async_msg->free_iov)
4084 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4089 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4090 struct io_async_msghdr *iomsg)
4092 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4094 iomsg->msg.msg_name = &iomsg->addr;
4095 iomsg->free_iov = iomsg->fast_iov;
4096 return sendmsg_copy_msghdr(&iomsg->msg, sr->umsg, sr->msg_flags,
4100 static int io_sendmsg_prep_async(struct io_kiocb *req)
4104 ret = io_sendmsg_copy_hdr(req, req->async_data);
4106 req->flags |= REQ_F_NEED_CLEANUP;
4110 static void io_sendmsg_recvmsg_cleanup(struct io_kiocb *req)
4112 struct io_async_msghdr *io = req->async_data;
4114 kfree(io->free_iov);
4117 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4119 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4121 if (unlikely(sqe->file_index || sqe->addr2))
4124 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4125 sr->len = READ_ONCE(sqe->len);
4126 sr->flags = READ_ONCE(sqe->ioprio);
4127 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
4129 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4130 if (sr->msg_flags & MSG_DONTWAIT)
4131 req->flags |= REQ_F_NOWAIT;
4133 #ifdef CONFIG_COMPAT
4134 if (req->ctx->compat)
4135 sr->msg_flags |= MSG_CMSG_COMPAT;
4141 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4143 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4144 struct io_async_msghdr iomsg, *kmsg;
4145 struct socket *sock;
4150 sock = sock_from_file(req->file);
4151 if (unlikely(!sock))
4154 if (req_has_async_data(req)) {
4155 kmsg = req->async_data;
4157 ret = io_sendmsg_copy_hdr(req, &iomsg);
4163 if (!(req->flags & REQ_F_POLLED) &&
4164 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4165 return io_setup_async_msg(req, kmsg);
4167 flags = sr->msg_flags;
4168 if (issue_flags & IO_URING_F_NONBLOCK)
4169 flags |= MSG_DONTWAIT;
4170 if (flags & MSG_WAITALL)
4171 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4173 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4175 if (ret < min_ret) {
4176 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4177 return io_setup_async_msg(req, kmsg);
4178 if (ret == -ERESTARTSYS)
4180 if (ret > 0 && io_net_retry(sock, flags)) {
4182 req->flags |= REQ_F_PARTIAL_IO;
4183 return io_setup_async_msg(req, kmsg);
4187 /* fast path, check for non-NULL to avoid function call */
4189 kfree(kmsg->free_iov);
4190 req->flags &= ~REQ_F_NEED_CLEANUP;
4193 else if (sr->done_io)
4195 io_req_set_res(req, ret, 0);
4199 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4201 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4204 struct socket *sock;
4209 if (!(req->flags & REQ_F_POLLED) &&
4210 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4213 sock = sock_from_file(req->file);
4214 if (unlikely(!sock))
4217 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4221 msg.msg_name = NULL;
4222 msg.msg_control = NULL;
4223 msg.msg_controllen = 0;
4224 msg.msg_namelen = 0;
4226 flags = sr->msg_flags;
4227 if (issue_flags & IO_URING_F_NONBLOCK)
4228 flags |= MSG_DONTWAIT;
4229 if (flags & MSG_WAITALL)
4230 min_ret = iov_iter_count(&msg.msg_iter);
4232 msg.msg_flags = flags;
4233 ret = sock_sendmsg(sock, &msg);
4234 if (ret < min_ret) {
4235 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4237 if (ret == -ERESTARTSYS)
4239 if (ret > 0 && io_net_retry(sock, flags)) {
4243 req->flags |= REQ_F_PARTIAL_IO;
4250 else if (sr->done_io)
4252 io_req_set_res(req, ret, 0);
4256 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4257 struct io_async_msghdr *iomsg)
4259 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4260 struct iovec __user *uiov;
4264 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4265 &iomsg->uaddr, &uiov, &iov_len);
4269 if (req->flags & REQ_F_BUFFER_SELECT) {
4272 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4274 sr->len = iomsg->fast_iov[0].iov_len;
4275 iomsg->free_iov = NULL;
4277 iomsg->free_iov = iomsg->fast_iov;
4278 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4279 &iomsg->free_iov, &iomsg->msg.msg_iter,
4288 #ifdef CONFIG_COMPAT
4289 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4290 struct io_async_msghdr *iomsg)
4292 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4293 struct compat_iovec __user *uiov;
4298 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4303 uiov = compat_ptr(ptr);
4304 if (req->flags & REQ_F_BUFFER_SELECT) {
4305 compat_ssize_t clen;
4309 if (!access_ok(uiov, sizeof(*uiov)))
4311 if (__get_user(clen, &uiov->iov_len))
4316 iomsg->free_iov = NULL;
4318 iomsg->free_iov = iomsg->fast_iov;
4319 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4320 UIO_FASTIOV, &iomsg->free_iov,
4321 &iomsg->msg.msg_iter, true);
4330 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4331 struct io_async_msghdr *iomsg)
4333 iomsg->msg.msg_name = &iomsg->addr;
4335 #ifdef CONFIG_COMPAT
4336 if (req->ctx->compat)
4337 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4340 return __io_recvmsg_copy_hdr(req, iomsg);
4343 static int io_recvmsg_prep_async(struct io_kiocb *req)
4347 ret = io_recvmsg_copy_hdr(req, req->async_data);
4349 req->flags |= REQ_F_NEED_CLEANUP;
4353 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4355 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4357 if (unlikely(sqe->file_index || sqe->addr2))
4360 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4361 sr->len = READ_ONCE(sqe->len);
4362 sr->flags = READ_ONCE(sqe->ioprio);
4363 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
4365 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4366 if (sr->msg_flags & MSG_DONTWAIT)
4367 req->flags |= REQ_F_NOWAIT;
4368 if (sr->msg_flags & MSG_ERRQUEUE)
4369 req->flags |= REQ_F_CLEAR_POLLIN;
4371 #ifdef CONFIG_COMPAT
4372 if (req->ctx->compat)
4373 sr->msg_flags |= MSG_CMSG_COMPAT;
4379 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4381 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4382 struct io_async_msghdr iomsg, *kmsg;
4383 struct socket *sock;
4384 unsigned int cflags;
4386 int ret, min_ret = 0;
4387 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4389 sock = sock_from_file(req->file);
4390 if (unlikely(!sock))
4393 if (req_has_async_data(req)) {
4394 kmsg = req->async_data;
4396 ret = io_recvmsg_copy_hdr(req, &iomsg);
4402 if (!(req->flags & REQ_F_POLLED) &&
4403 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4404 return io_setup_async_msg(req, kmsg);
4406 if (io_do_buffer_select(req)) {
4409 buf = io_buffer_select(req, &sr->len, issue_flags);
4412 kmsg->fast_iov[0].iov_base = buf;
4413 kmsg->fast_iov[0].iov_len = sr->len;
4414 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
4418 flags = sr->msg_flags;
4420 flags |= MSG_DONTWAIT;
4421 if (flags & MSG_WAITALL)
4422 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4424 kmsg->msg.msg_get_inq = 1;
4425 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
4426 if (ret < min_ret) {
4427 if (ret == -EAGAIN && force_nonblock)
4428 return io_setup_async_msg(req, kmsg);
4429 if (ret == -ERESTARTSYS)
4431 if (ret > 0 && io_net_retry(sock, flags)) {
4433 req->flags |= REQ_F_PARTIAL_IO;
4434 return io_setup_async_msg(req, kmsg);
4437 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
4441 /* fast path, check for non-NULL to avoid function call */
4443 kfree(kmsg->free_iov);
4444 req->flags &= ~REQ_F_NEED_CLEANUP;
4447 else if (sr->done_io)
4449 cflags = io_put_kbuf(req, issue_flags);
4450 if (kmsg->msg.msg_inq)
4451 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
4452 io_req_set_res(req, ret, cflags);
4456 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4458 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4460 struct socket *sock;
4462 unsigned int cflags;
4464 int ret, min_ret = 0;
4465 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4467 if (!(req->flags & REQ_F_POLLED) &&
4468 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4471 sock = sock_from_file(req->file);
4472 if (unlikely(!sock))
4475 if (io_do_buffer_select(req)) {
4478 buf = io_buffer_select(req, &sr->len, issue_flags);
4484 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
4488 msg.msg_name = NULL;
4489 msg.msg_namelen = 0;
4490 msg.msg_control = NULL;
4491 msg.msg_get_inq = 1;
4493 msg.msg_controllen = 0;
4494 msg.msg_iocb = NULL;
4496 flags = sr->msg_flags;
4498 flags |= MSG_DONTWAIT;
4499 if (flags & MSG_WAITALL)
4500 min_ret = iov_iter_count(&msg.msg_iter);
4502 ret = sock_recvmsg(sock, &msg, flags);
4503 if (ret < min_ret) {
4504 if (ret == -EAGAIN && force_nonblock)
4506 if (ret == -ERESTARTSYS)
4508 if (ret > 0 && io_net_retry(sock, flags)) {
4512 req->flags |= REQ_F_PARTIAL_IO;
4516 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
4523 else if (sr->done_io)
4525 cflags = io_put_kbuf(req, issue_flags);
4527 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
4528 io_req_set_res(req, ret, cflags);
4532 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4534 struct io_accept *accept = io_kiocb_to_cmd(req);
4537 if (sqe->len || sqe->buf_index)
4540 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4541 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4542 accept->flags = READ_ONCE(sqe->accept_flags);
4543 accept->nofile = rlimit(RLIMIT_NOFILE);
4544 flags = READ_ONCE(sqe->ioprio);
4545 if (flags & ~IORING_ACCEPT_MULTISHOT)
4548 accept->file_slot = READ_ONCE(sqe->file_index);
4549 if (accept->file_slot) {
4550 if (accept->flags & SOCK_CLOEXEC)
4552 if (flags & IORING_ACCEPT_MULTISHOT &&
4553 accept->file_slot != IORING_FILE_INDEX_ALLOC)
4556 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4558 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
4559 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
4560 if (flags & IORING_ACCEPT_MULTISHOT)
4561 req->flags |= REQ_F_APOLL_MULTISHOT;
4565 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4567 struct io_ring_ctx *ctx = req->ctx;
4568 struct io_accept *accept = io_kiocb_to_cmd(req);
4569 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4570 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4571 bool fixed = !!accept->file_slot;
4577 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
4578 if (unlikely(fd < 0))
4581 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
4586 ret = PTR_ERR(file);
4587 if (ret == -EAGAIN && force_nonblock) {
4589 * if it's multishot and polled, we don't need to
4590 * return EAGAIN to arm the poll infra since it
4591 * has already been done
4593 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
4594 IO_APOLL_MULTI_POLLED)
4595 ret = IOU_ISSUE_SKIP_COMPLETE;
4598 if (ret == -ERESTARTSYS)
4601 } else if (!fixed) {
4602 fd_install(fd, file);
4605 ret = io_fixed_fd_install(req, issue_flags, file,
4609 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
4610 io_req_set_res(req, ret, 0);
4616 spin_lock(&ctx->completion_lock);
4617 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
4619 io_commit_cqring(ctx);
4620 spin_unlock(&ctx->completion_lock);
4622 io_cqring_ev_posted(ctx);
4631 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4633 struct io_socket *sock = io_kiocb_to_cmd(req);
4635 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
4638 sock->domain = READ_ONCE(sqe->fd);
4639 sock->type = READ_ONCE(sqe->off);
4640 sock->protocol = READ_ONCE(sqe->len);
4641 sock->file_slot = READ_ONCE(sqe->file_index);
4642 sock->nofile = rlimit(RLIMIT_NOFILE);
4644 sock->flags = sock->type & ~SOCK_TYPE_MASK;
4645 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
4647 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4652 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
4654 struct io_socket *sock = io_kiocb_to_cmd(req);
4655 bool fixed = !!sock->file_slot;
4660 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
4661 if (unlikely(fd < 0))
4664 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
4668 ret = PTR_ERR(file);
4669 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4671 if (ret == -ERESTARTSYS)
4674 } else if (!fixed) {
4675 fd_install(fd, file);
4678 ret = io_fixed_fd_install(req, issue_flags, file,
4681 io_req_set_res(req, ret, 0);
4685 static int io_connect_prep_async(struct io_kiocb *req)
4687 struct io_async_connect *io = req->async_data;
4688 struct io_connect *conn = io_kiocb_to_cmd(req);
4690 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4693 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4695 struct io_connect *conn = io_kiocb_to_cmd(req);
4697 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
4700 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4701 conn->addr_len = READ_ONCE(sqe->addr2);
4705 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4707 struct io_connect *connect = io_kiocb_to_cmd(req);
4708 struct io_async_connect __io, *io;
4709 unsigned file_flags;
4711 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4713 if (req_has_async_data(req)) {
4714 io = req->async_data;
4716 ret = move_addr_to_kernel(connect->addr,
4724 file_flags = force_nonblock ? O_NONBLOCK : 0;
4726 ret = __sys_connect_file(req->file, &io->address,
4727 connect->addr_len, file_flags);
4728 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4729 if (req_has_async_data(req))
4731 if (io_alloc_async_data(req)) {
4735 memcpy(req->async_data, &__io, sizeof(__io));
4738 if (ret == -ERESTARTSYS)
4743 io_req_set_res(req, ret, 0);
4746 #else /* !CONFIG_NET */
4747 #define IO_NETOP_FN(op) \
4748 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4750 return -EOPNOTSUPP; \
4753 #define IO_NETOP_PREP(op) \
4755 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4757 return -EOPNOTSUPP; \
4760 #define IO_NETOP_PREP_ASYNC(op) \
4762 static int io_##op##_prep_async(struct io_kiocb *req) \
4764 return -EOPNOTSUPP; \
4767 IO_NETOP_PREP_ASYNC(sendmsg);
4768 IO_NETOP_PREP_ASYNC(recvmsg);
4769 IO_NETOP_PREP_ASYNC(connect);
4770 IO_NETOP_PREP(accept);
4771 IO_NETOP_PREP(socket);
4772 IO_NETOP_PREP(shutdown);
4775 #endif /* CONFIG_NET */
4777 struct io_poll_table {
4778 struct poll_table_struct pt;
4779 struct io_kiocb *req;
4784 #define IO_POLL_CANCEL_FLAG BIT(31)
4785 #define IO_POLL_REF_MASK GENMASK(30, 0)
4788 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
4789 * bump it and acquire ownership. It's disallowed to modify requests while not
4790 * owning it, that prevents from races for enqueueing task_work's and b/w
4791 * arming poll and wakeups.
4793 static inline bool io_poll_get_ownership(struct io_kiocb *req)
4795 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
4798 static void io_poll_mark_cancelled(struct io_kiocb *req)
4800 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
4803 static struct io_poll *io_poll_get_double(struct io_kiocb *req)
4805 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4806 if (req->opcode == IORING_OP_POLL_ADD)
4807 return req->async_data;
4808 return req->apoll->double_poll;
4811 static struct io_poll *io_poll_get_single(struct io_kiocb *req)
4813 if (req->opcode == IORING_OP_POLL_ADD)
4814 return io_kiocb_to_cmd(req);
4815 return &req->apoll->poll;
4818 static void io_poll_req_insert(struct io_kiocb *req)
4820 struct io_ring_ctx *ctx = req->ctx;
4821 struct hlist_head *list;
4823 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
4824 hlist_add_head(&req->hash_node, list);
4827 static void io_init_poll_iocb(struct io_poll *poll, __poll_t events,
4828 wait_queue_func_t wake_func)
4831 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4832 /* mask in events that we always want/need */
4833 poll->events = events | IO_POLL_UNMASK;
4834 INIT_LIST_HEAD(&poll->wait.entry);
4835 init_waitqueue_func_entry(&poll->wait, wake_func);
4838 static inline void io_poll_remove_entry(struct io_poll *poll)
4840 struct wait_queue_head *head = smp_load_acquire(&poll->head);
4843 spin_lock_irq(&head->lock);
4844 list_del_init(&poll->wait.entry);
4846 spin_unlock_irq(&head->lock);
4850 static void io_poll_remove_entries(struct io_kiocb *req)
4853 * Nothing to do if neither of those flags are set. Avoid dipping
4854 * into the poll/apoll/double cachelines if we can.
4856 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
4860 * While we hold the waitqueue lock and the waitqueue is nonempty,
4861 * wake_up_pollfree() will wait for us. However, taking the waitqueue
4862 * lock in the first place can race with the waitqueue being freed.
4864 * We solve this as eventpoll does: by taking advantage of the fact that
4865 * all users of wake_up_pollfree() will RCU-delay the actual free. If
4866 * we enter rcu_read_lock() and see that the pointer to the queue is
4867 * non-NULL, we can then lock it without the memory being freed out from
4870 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
4871 * case the caller deletes the entry from the queue, leaving it empty.
4872 * In that case, only RCU prevents the queue memory from being freed.
4875 if (req->flags & REQ_F_SINGLE_POLL)
4876 io_poll_remove_entry(io_poll_get_single(req));
4877 if (req->flags & REQ_F_DOUBLE_POLL)
4878 io_poll_remove_entry(io_poll_get_double(req));
4882 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
4884 * All poll tw should go through this. Checks for poll events, manages
4885 * references, does rewait, etc.
4887 * Returns a negative error on failure. >0 when no action require, which is
4888 * either spurious wakeup or multishot CQE is served. 0 when it's done with
4889 * the request, then the mask is stored in req->cqe.res.
4891 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
4893 struct io_ring_ctx *ctx = req->ctx;
4896 /* req->task == current here, checking PF_EXITING is safe */
4897 if (unlikely(req->task->flags & PF_EXITING))
4901 v = atomic_read(&req->poll_refs);
4903 /* tw handler should be the owner, and so have some references */
4904 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
4906 if (v & IO_POLL_CANCEL_FLAG)
4909 if (!req->cqe.res) {
4910 struct poll_table_struct pt = { ._key = req->apoll_events };
4911 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
4914 if ((unlikely(!req->cqe.res)))
4916 if (req->apoll_events & EPOLLONESHOT)
4919 /* multishot, just fill a CQE and proceed */
4920 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
4921 __poll_t mask = mangle_poll(req->cqe.res &
4925 spin_lock(&ctx->completion_lock);
4926 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
4927 mask, IORING_CQE_F_MORE);
4928 io_commit_cqring(ctx);
4929 spin_unlock(&ctx->completion_lock);
4931 io_cqring_ev_posted(ctx);
4937 io_tw_lock(req->ctx, locked);
4938 if (unlikely(req->task->flags & PF_EXITING))
4940 ret = io_issue_sqe(req,
4941 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
4946 * Release all references, retry if someone tried to restart
4947 * task_work while we were executing it.
4949 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
4954 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
4956 struct io_ring_ctx *ctx = req->ctx;
4959 ret = io_poll_check_events(req, locked);
4964 struct io_poll *poll = io_kiocb_to_cmd(req);
4966 req->cqe.res = mangle_poll(req->cqe.res & poll->events);
4972 io_poll_remove_entries(req);
4973 spin_lock(&ctx->completion_lock);
4974 hash_del(&req->hash_node);
4976 __io_req_complete_post(req);
4977 io_commit_cqring(ctx);
4978 spin_unlock(&ctx->completion_lock);
4979 io_cqring_ev_posted(ctx);
4982 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
4984 struct io_ring_ctx *ctx = req->ctx;
4987 ret = io_poll_check_events(req, locked);
4991 io_poll_remove_entries(req);
4992 spin_lock(&ctx->completion_lock);
4993 hash_del(&req->hash_node);
4994 spin_unlock(&ctx->completion_lock);
4997 io_req_task_submit(req, locked);
4999 io_req_complete_failed(req, ret);
5002 static void __io_poll_execute(struct io_kiocb *req, int mask,
5003 __poll_t __maybe_unused events)
5005 io_req_set_res(req, mask, 0);
5007 * This is useful for poll that is armed on behalf of another
5008 * request, and where the wakeup path could be on a different
5009 * CPU. We want to avoid pulling in req->apoll->events for that
5012 if (req->opcode == IORING_OP_POLL_ADD)
5013 req->io_task_work.func = io_poll_task_func;
5015 req->io_task_work.func = io_apoll_task_func;
5017 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
5018 io_req_task_work_add(req);
5021 static inline void io_poll_execute(struct io_kiocb *req, int res,
5024 if (io_poll_get_ownership(req))
5025 __io_poll_execute(req, res, events);
5028 static void io_poll_cancel_req(struct io_kiocb *req)
5030 io_poll_mark_cancelled(req);
5031 /* kick tw, which should complete the request */
5032 io_poll_execute(req, 0, 0);
5035 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
5036 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
5037 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
5039 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5042 struct io_kiocb *req = wqe_to_req(wait);
5043 struct io_poll *poll = container_of(wait, struct io_poll, wait);
5044 __poll_t mask = key_to_poll(key);
5046 if (unlikely(mask & POLLFREE)) {
5047 io_poll_mark_cancelled(req);
5048 /* we have to kick tw in case it's not already */
5049 io_poll_execute(req, 0, poll->events);
5052 * If the waitqueue is being freed early but someone is already
5053 * holds ownership over it, we have to tear down the request as
5054 * best we can. That means immediately removing the request from
5055 * its waitqueue and preventing all further accesses to the
5056 * waitqueue via the request.
5058 list_del_init(&poll->wait.entry);
5061 * Careful: this *must* be the last step, since as soon
5062 * as req->head is NULL'ed out, the request can be
5063 * completed and freed, since aio_poll_complete_work()
5064 * will no longer need to take the waitqueue lock.
5066 smp_store_release(&poll->head, NULL);
5070 /* for instances that support it check for an event match first */
5071 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
5074 if (io_poll_get_ownership(req)) {
5075 /* optional, saves extra locking for removal in tw handler */
5076 if (mask && poll->events & EPOLLONESHOT) {
5077 list_del_init(&poll->wait.entry);
5079 if (wqe_is_double(wait))
5080 req->flags &= ~REQ_F_DOUBLE_POLL;
5082 req->flags &= ~REQ_F_SINGLE_POLL;
5084 __io_poll_execute(req, mask, poll->events);
5089 static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt,
5090 struct wait_queue_head *head,
5091 struct io_poll **poll_ptr)
5093 struct io_kiocb *req = pt->req;
5094 unsigned long wqe_private = (unsigned long) req;
5097 * The file being polled uses multiple waitqueues for poll handling
5098 * (e.g. one for read, one for write). Setup a separate io_poll
5101 if (unlikely(pt->nr_entries)) {
5102 struct io_poll *first = poll;
5104 /* double add on the same waitqueue head, ignore */
5105 if (first->head == head)
5107 /* already have a 2nd entry, fail a third attempt */
5109 if ((*poll_ptr)->head == head)
5111 pt->error = -EINVAL;
5115 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5117 pt->error = -ENOMEM;
5120 /* mark as double wq entry */
5122 req->flags |= REQ_F_DOUBLE_POLL;
5123 io_init_poll_iocb(poll, first->events, first->wait.func);
5125 if (req->opcode == IORING_OP_POLL_ADD)
5126 req->flags |= REQ_F_ASYNC_DATA;
5129 req->flags |= REQ_F_SINGLE_POLL;
5132 poll->wait.private = (void *) wqe_private;
5134 if (poll->events & EPOLLEXCLUSIVE)
5135 add_wait_queue_exclusive(head, &poll->wait);
5137 add_wait_queue(head, &poll->wait);
5140 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5141 struct poll_table_struct *p)
5143 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5144 struct io_poll *poll = io_kiocb_to_cmd(pt->req);
5146 __io_queue_proc(poll, pt, head,
5147 (struct io_poll **) &pt->req->async_data);
5150 static int __io_arm_poll_handler(struct io_kiocb *req,
5151 struct io_poll *poll,
5152 struct io_poll_table *ipt, __poll_t mask)
5154 struct io_ring_ctx *ctx = req->ctx;
5157 INIT_HLIST_NODE(&req->hash_node);
5158 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
5159 io_init_poll_iocb(poll, mask, io_poll_wake);
5160 poll->file = req->file;
5162 req->apoll_events = poll->events;
5164 ipt->pt._key = mask;
5167 ipt->nr_entries = 0;
5170 * Take the ownership to delay any tw execution up until we're done
5171 * with poll arming. see io_poll_get_ownership().
5173 atomic_set(&req->poll_refs, 1);
5174 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5176 if (mask && (poll->events & EPOLLONESHOT)) {
5177 io_poll_remove_entries(req);
5178 /* no one else has access to the req, forget about the ref */
5181 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5182 io_poll_remove_entries(req);
5184 ipt->error = -EINVAL;
5188 spin_lock(&ctx->completion_lock);
5189 io_poll_req_insert(req);
5190 spin_unlock(&ctx->completion_lock);
5193 /* can't multishot if failed, just queue the event we've got */
5194 if (unlikely(ipt->error || !ipt->nr_entries)) {
5195 poll->events |= EPOLLONESHOT;
5196 req->apoll_events |= EPOLLONESHOT;
5199 __io_poll_execute(req, mask, poll->events);
5204 * Release ownership. If someone tried to queue a tw while it was
5205 * locked, kick it off for them.
5207 v = atomic_dec_return(&req->poll_refs);
5208 if (unlikely(v & IO_POLL_REF_MASK))
5209 __io_poll_execute(req, 0, poll->events);
5213 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5214 struct poll_table_struct *p)
5216 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5217 struct async_poll *apoll = pt->req->apoll;
5219 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5228 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
5230 const struct io_op_def *def = &io_op_defs[req->opcode];
5231 struct io_ring_ctx *ctx = req->ctx;
5232 struct async_poll *apoll;
5233 struct io_poll_table ipt;
5234 __poll_t mask = POLLPRI | POLLERR;
5237 if (!def->pollin && !def->pollout)
5238 return IO_APOLL_ABORTED;
5239 if (!file_can_poll(req->file))
5240 return IO_APOLL_ABORTED;
5241 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
5242 return IO_APOLL_ABORTED;
5243 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
5244 mask |= EPOLLONESHOT;
5247 mask |= EPOLLIN | EPOLLRDNORM;
5249 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5250 if (req->flags & REQ_F_CLEAR_POLLIN)
5253 mask |= EPOLLOUT | EPOLLWRNORM;
5255 if (def->poll_exclusive)
5256 mask |= EPOLLEXCLUSIVE;
5257 if (req->flags & REQ_F_POLLED) {
5259 kfree(apoll->double_poll);
5260 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
5261 !list_empty(&ctx->apoll_cache)) {
5262 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
5264 list_del_init(&apoll->poll.wait.entry);
5266 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5267 if (unlikely(!apoll))
5268 return IO_APOLL_ABORTED;
5270 apoll->double_poll = NULL;
5272 req->flags |= REQ_F_POLLED;
5273 ipt.pt._qproc = io_async_queue_proc;
5275 io_kbuf_recycle(req, issue_flags);
5277 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5278 if (ret || ipt.error)
5279 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5281 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
5282 mask, apoll->poll.events);
5287 * Returns true if we found and killed one or more poll requests
5289 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
5290 struct task_struct *tsk, bool cancel_all)
5292 struct hlist_node *tmp;
5293 struct io_kiocb *req;
5297 spin_lock(&ctx->completion_lock);
5298 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5299 struct hlist_head *list;
5301 list = &ctx->cancel_hash[i];
5302 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5303 if (io_match_task_safe(req, tsk, cancel_all)) {
5304 hlist_del_init(&req->hash_node);
5305 io_poll_cancel_req(req);
5310 spin_unlock(&ctx->completion_lock);
5314 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
5315 struct io_cancel_data *cd)
5316 __must_hold(&ctx->completion_lock)
5318 struct hlist_head *list;
5319 struct io_kiocb *req;
5321 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
5322 hlist_for_each_entry(req, list, hash_node) {
5323 if (cd->data != req->cqe.user_data)
5325 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5327 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
5328 if (cd->seq == req->work.cancel_seq)
5330 req->work.cancel_seq = cd->seq;
5337 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
5338 struct io_cancel_data *cd)
5339 __must_hold(&ctx->completion_lock)
5341 struct io_kiocb *req;
5344 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5345 struct hlist_head *list;
5347 list = &ctx->cancel_hash[i];
5348 hlist_for_each_entry(req, list, hash_node) {
5349 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
5350 req->file != cd->file)
5352 if (cd->seq == req->work.cancel_seq)
5354 req->work.cancel_seq = cd->seq;
5361 static bool io_poll_disarm(struct io_kiocb *req)
5362 __must_hold(&ctx->completion_lock)
5364 if (!io_poll_get_ownership(req))
5366 io_poll_remove_entries(req);
5367 hash_del(&req->hash_node);
5371 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
5372 __must_hold(&ctx->completion_lock)
5374 struct io_kiocb *req;
5376 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
5377 req = io_poll_file_find(ctx, cd);
5379 req = io_poll_find(ctx, false, cd);
5382 io_poll_cancel_req(req);
5386 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5391 events = READ_ONCE(sqe->poll32_events);
5393 events = swahw32(events);
5395 if (!(flags & IORING_POLL_ADD_MULTI))
5396 events |= EPOLLONESHOT;
5397 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5400 static int io_poll_remove_prep(struct io_kiocb *req,
5401 const struct io_uring_sqe *sqe)
5403 struct io_poll_update *upd = io_kiocb_to_cmd(req);
5406 if (sqe->buf_index || sqe->splice_fd_in)
5408 flags = READ_ONCE(sqe->len);
5409 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5410 IORING_POLL_ADD_MULTI))
5412 /* meaningless without update */
5413 if (flags == IORING_POLL_ADD_MULTI)
5416 upd->old_user_data = READ_ONCE(sqe->addr);
5417 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5418 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5420 upd->new_user_data = READ_ONCE(sqe->off);
5421 if (!upd->update_user_data && upd->new_user_data)
5423 if (upd->update_events)
5424 upd->events = io_poll_parse_events(sqe, flags);
5425 else if (sqe->poll32_events)
5431 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5433 struct io_poll *poll = io_kiocb_to_cmd(req);
5436 if (sqe->buf_index || sqe->off || sqe->addr)
5438 flags = READ_ONCE(sqe->len);
5439 if (flags & ~IORING_POLL_ADD_MULTI)
5441 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
5444 io_req_set_refcount(req);
5445 poll->events = io_poll_parse_events(sqe, flags);
5449 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5451 struct io_poll *poll = io_kiocb_to_cmd(req);
5452 struct io_poll_table ipt;
5455 ipt.pt._qproc = io_poll_queue_proc;
5457 ret = __io_arm_poll_handler(req, poll, &ipt, poll->events);
5459 io_req_set_res(req, ret, 0);
5467 return IOU_ISSUE_SKIP_COMPLETE;
5470 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5472 struct io_poll_update *poll_update = io_kiocb_to_cmd(req);
5473 struct io_cancel_data cd = { .data = poll_update->old_user_data, };
5474 struct io_ring_ctx *ctx = req->ctx;
5475 struct io_kiocb *preq;
5479 spin_lock(&ctx->completion_lock);
5480 preq = io_poll_find(ctx, true, &cd);
5481 if (!preq || !io_poll_disarm(preq)) {
5482 spin_unlock(&ctx->completion_lock);
5483 ret = preq ? -EALREADY : -ENOENT;
5486 spin_unlock(&ctx->completion_lock);
5488 if (poll_update->update_events || poll_update->update_user_data) {
5489 /* only mask one event flags, keep behavior flags */
5490 if (poll_update->update_events) {
5491 struct io_poll *poll = io_kiocb_to_cmd(preq);
5493 poll->events &= ~0xffff;
5494 poll->events |= poll_update->events & 0xffff;
5495 poll->events |= IO_POLL_UNMASK;
5497 if (poll_update->update_user_data)
5498 preq->cqe.user_data = poll_update->new_user_data;
5500 ret2 = io_poll_add(preq, issue_flags);
5501 /* successfully updated, don't complete poll request */
5502 if (!ret2 || ret2 == -EIOCBQUEUED)
5507 io_req_set_res(preq, -ECANCELED, 0);
5508 locked = !(issue_flags & IO_URING_F_UNLOCKED);
5509 io_req_task_complete(preq, &locked);
5515 /* complete update request, we're done with it */
5516 io_req_set_res(req, ret, 0);
5520 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5522 struct io_timeout_data *data = container_of(timer,
5523 struct io_timeout_data, timer);
5524 struct io_kiocb *req = data->req;
5525 struct io_timeout *timeout = io_kiocb_to_cmd(req);
5526 struct io_ring_ctx *ctx = req->ctx;
5527 unsigned long flags;
5529 spin_lock_irqsave(&ctx->timeout_lock, flags);
5530 list_del_init(&timeout->list);
5531 atomic_set(&req->ctx->cq_timeouts,
5532 atomic_read(&req->ctx->cq_timeouts) + 1);
5533 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5535 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
5538 io_req_set_res(req, -ETIME, 0);
5539 req->io_task_work.func = io_req_task_complete;
5540 io_req_task_work_add(req);
5541 return HRTIMER_NORESTART;
5544 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5545 struct io_cancel_data *cd)
5546 __must_hold(&ctx->timeout_lock)
5548 struct io_timeout *timeout;
5549 struct io_timeout_data *io;
5550 struct io_kiocb *req = NULL;
5552 list_for_each_entry(timeout, &ctx->timeout_list, list) {
5553 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
5555 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
5556 cd->data != tmp->cqe.user_data)
5558 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
5559 if (cd->seq == tmp->work.cancel_seq)
5561 tmp->work.cancel_seq = cd->seq;
5567 return ERR_PTR(-ENOENT);
5569 io = req->async_data;
5570 if (hrtimer_try_to_cancel(&io->timer) == -1)
5571 return ERR_PTR(-EALREADY);
5572 timeout = io_kiocb_to_cmd(req);
5573 list_del_init(&timeout->list);
5577 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
5578 __must_hold(&ctx->completion_lock)
5580 struct io_kiocb *req;
5582 spin_lock_irq(&ctx->timeout_lock);
5583 req = io_timeout_extract(ctx, cd);
5584 spin_unlock_irq(&ctx->timeout_lock);
5587 return PTR_ERR(req);
5588 io_req_task_queue_fail(req, -ECANCELED);
5592 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5594 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5595 case IORING_TIMEOUT_BOOTTIME:
5596 return CLOCK_BOOTTIME;
5597 case IORING_TIMEOUT_REALTIME:
5598 return CLOCK_REALTIME;
5600 /* can't happen, vetted at prep time */
5604 return CLOCK_MONOTONIC;
5608 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5609 struct timespec64 *ts, enum hrtimer_mode mode)
5610 __must_hold(&ctx->timeout_lock)
5612 struct io_timeout_data *io;
5613 struct io_timeout *timeout;
5614 struct io_kiocb *req = NULL;
5616 list_for_each_entry(timeout, &ctx->ltimeout_list, list) {
5617 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
5619 if (user_data == tmp->cqe.user_data) {
5627 io = req->async_data;
5628 if (hrtimer_try_to_cancel(&io->timer) == -1)
5630 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5631 io->timer.function = io_link_timeout_fn;
5632 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5636 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5637 struct timespec64 *ts, enum hrtimer_mode mode)
5638 __must_hold(&ctx->timeout_lock)
5640 struct io_cancel_data cd = { .data = user_data, };
5641 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
5642 struct io_timeout *timeout = io_kiocb_to_cmd(req);
5643 struct io_timeout_data *data;
5646 return PTR_ERR(req);
5648 timeout->off = 0; /* noseq */
5649 data = req->async_data;
5650 list_add_tail(&timeout->list, &ctx->timeout_list);
5651 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5652 data->timer.function = io_timeout_fn;
5653 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5657 static int io_timeout_remove_prep(struct io_kiocb *req,
5658 const struct io_uring_sqe *sqe)
5660 struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
5662 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5664 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
5667 tr->ltimeout = false;
5668 tr->addr = READ_ONCE(sqe->addr);
5669 tr->flags = READ_ONCE(sqe->timeout_flags);
5670 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5671 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5673 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5674 tr->ltimeout = true;
5675 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5677 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5679 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
5681 } else if (tr->flags) {
5682 /* timeout removal doesn't support flags */
5689 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5691 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5696 * Remove or update an existing timeout command
5698 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5700 struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
5701 struct io_ring_ctx *ctx = req->ctx;
5704 if (!(tr->flags & IORING_TIMEOUT_UPDATE)) {
5705 struct io_cancel_data cd = { .data = tr->addr, };
5707 spin_lock(&ctx->completion_lock);
5708 ret = io_timeout_cancel(ctx, &cd);
5709 spin_unlock(&ctx->completion_lock);
5711 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
5713 spin_lock_irq(&ctx->timeout_lock);
5715 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
5717 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5718 spin_unlock_irq(&ctx->timeout_lock);
5723 io_req_set_res(req, ret, 0);
5727 static int __io_timeout_prep(struct io_kiocb *req,
5728 const struct io_uring_sqe *sqe,
5729 bool is_timeout_link)
5731 struct io_timeout *timeout = io_kiocb_to_cmd(req);
5732 struct io_timeout_data *data;
5734 u32 off = READ_ONCE(sqe->off);
5736 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
5738 if (off && is_timeout_link)
5740 flags = READ_ONCE(sqe->timeout_flags);
5741 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
5742 IORING_TIMEOUT_ETIME_SUCCESS))
5744 /* more than one clock specified is invalid, obviously */
5745 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5748 INIT_LIST_HEAD(&timeout->list);
5750 if (unlikely(off && !req->ctx->off_timeout_used))
5751 req->ctx->off_timeout_used = true;
5753 if (WARN_ON_ONCE(req_has_async_data(req)))
5755 if (io_alloc_async_data(req))
5758 data = req->async_data;
5760 data->flags = flags;
5762 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5765 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
5768 INIT_LIST_HEAD(&timeout->list);
5769 data->mode = io_translate_timeout_mode(flags);
5770 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
5772 if (is_timeout_link) {
5773 struct io_submit_link *link = &req->ctx->submit_state.link;
5777 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5779 timeout->head = link->last;
5780 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5785 static int io_timeout_prep(struct io_kiocb *req,
5786 const struct io_uring_sqe *sqe)
5788 return __io_timeout_prep(req, sqe, false);
5791 static int io_link_timeout_prep(struct io_kiocb *req,
5792 const struct io_uring_sqe *sqe)
5794 return __io_timeout_prep(req, sqe, true);
5797 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5799 struct io_timeout *timeout = io_kiocb_to_cmd(req);
5800 struct io_ring_ctx *ctx = req->ctx;
5801 struct io_timeout_data *data = req->async_data;
5802 struct list_head *entry;
5803 u32 tail, off = timeout->off;
5805 spin_lock_irq(&ctx->timeout_lock);
5808 * sqe->off holds how many events that need to occur for this
5809 * timeout event to be satisfied. If it isn't set, then this is
5810 * a pure timeout request, sequence isn't used.
5812 if (io_is_timeout_noseq(req)) {
5813 entry = ctx->timeout_list.prev;
5817 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5818 timeout->target_seq = tail + off;
5820 /* Update the last seq here in case io_flush_timeouts() hasn't.
5821 * This is safe because ->completion_lock is held, and submissions
5822 * and completions are never mixed in the same ->completion_lock section.
5824 ctx->cq_last_tm_flush = tail;
5827 * Insertion sort, ensuring the first entry in the list is always
5828 * the one we need first.
5830 list_for_each_prev(entry, &ctx->timeout_list) {
5831 struct io_timeout *nextt = list_entry(entry, struct io_timeout, list);
5832 struct io_kiocb *nxt = cmd_to_io_kiocb(nextt);
5834 if (io_is_timeout_noseq(nxt))
5836 /* nxt.seq is behind @tail, otherwise would've been completed */
5837 if (off >= nextt->target_seq - tail)
5841 list_add(&timeout->list, entry);
5842 data->timer.function = io_timeout_fn;
5843 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5844 spin_unlock_irq(&ctx->timeout_lock);
5845 return IOU_ISSUE_SKIP_COMPLETE;
5848 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5850 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5851 struct io_cancel_data *cd = data;
5853 if (req->ctx != cd->ctx)
5855 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
5857 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
5858 if (req->file != cd->file)
5861 if (req->cqe.user_data != cd->data)
5864 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
5865 if (cd->seq == req->work.cancel_seq)
5867 req->work.cancel_seq = cd->seq;
5872 static int io_async_cancel_one(struct io_uring_task *tctx,
5873 struct io_cancel_data *cd)
5875 enum io_wq_cancel cancel_ret;
5879 if (!tctx || !tctx->io_wq)
5882 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
5883 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
5884 switch (cancel_ret) {
5885 case IO_WQ_CANCEL_OK:
5888 case IO_WQ_CANCEL_RUNNING:
5891 case IO_WQ_CANCEL_NOTFOUND:
5899 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
5901 struct io_ring_ctx *ctx = req->ctx;
5904 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
5906 ret = io_async_cancel_one(req->task->io_uring, cd);
5908 * Fall-through even for -EALREADY, as we may have poll armed
5909 * that need unarming.
5914 spin_lock(&ctx->completion_lock);
5915 ret = io_poll_cancel(ctx, cd);
5918 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
5919 ret = io_timeout_cancel(ctx, cd);
5921 spin_unlock(&ctx->completion_lock);
5925 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
5926 IORING_ASYNC_CANCEL_ANY)
5928 static int io_async_cancel_prep(struct io_kiocb *req,
5929 const struct io_uring_sqe *sqe)
5931 struct io_cancel *cancel = io_kiocb_to_cmd(req);
5933 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
5935 if (sqe->off || sqe->len || sqe->splice_fd_in)
5938 cancel->addr = READ_ONCE(sqe->addr);
5939 cancel->flags = READ_ONCE(sqe->cancel_flags);
5940 if (cancel->flags & ~CANCEL_FLAGS)
5942 if (cancel->flags & IORING_ASYNC_CANCEL_FD) {
5943 if (cancel->flags & IORING_ASYNC_CANCEL_ANY)
5945 cancel->fd = READ_ONCE(sqe->fd);
5951 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
5952 unsigned int issue_flags)
5954 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
5955 struct io_ring_ctx *ctx = cd->ctx;
5956 struct io_tctx_node *node;
5960 ret = io_try_cancel(req, cd);
5968 /* slow path, try all io-wq's */
5969 io_ring_submit_lock(ctx, issue_flags);
5971 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5972 struct io_uring_task *tctx = node->task->io_uring;
5974 ret = io_async_cancel_one(tctx, cd);
5975 if (ret != -ENOENT) {
5981 io_ring_submit_unlock(ctx, issue_flags);
5982 return all ? nr : ret;
5985 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5987 struct io_cancel *cancel = io_kiocb_to_cmd(req);
5988 struct io_cancel_data cd = {
5990 .data = cancel->addr,
5991 .flags = cancel->flags,
5992 .seq = atomic_inc_return(&req->ctx->cancel_seq),
5996 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
5997 if (req->flags & REQ_F_FIXED_FILE)
5998 req->file = io_file_get_fixed(req, cancel->fd,
6001 req->file = io_file_get_normal(req, cancel->fd);
6006 cd.file = req->file;
6009 ret = __io_async_cancel(&cd, req, issue_flags);
6013 io_req_set_res(req, ret, 0);
6017 static int io_files_update_prep(struct io_kiocb *req,
6018 const struct io_uring_sqe *sqe)
6020 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6022 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6024 if (sqe->rw_flags || sqe->splice_fd_in)
6027 up->offset = READ_ONCE(sqe->off);
6028 up->nr_args = READ_ONCE(sqe->len);
6031 up->arg = READ_ONCE(sqe->addr);
6035 static int io_files_update_with_index_alloc(struct io_kiocb *req,
6036 unsigned int issue_flags)
6038 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6039 __s32 __user *fds = u64_to_user_ptr(up->arg);
6044 if (!req->ctx->file_data)
6047 for (done = 0; done < up->nr_args; done++) {
6048 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6058 ret = io_fixed_fd_install(req, issue_flags, file,
6059 IORING_FILE_INDEX_ALLOC);
6062 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
6063 __io_close_fixed(req, issue_flags, ret);
6074 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6076 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6077 struct io_ring_ctx *ctx = req->ctx;
6078 struct io_uring_rsrc_update2 up2;
6081 up2.offset = up->offset;
6088 if (up->offset == IORING_FILE_INDEX_ALLOC) {
6089 ret = io_files_update_with_index_alloc(req, issue_flags);
6091 io_ring_submit_lock(ctx, issue_flags);
6092 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6094 io_ring_submit_unlock(ctx, issue_flags);
6099 io_req_set_res(req, ret, 0);
6103 static int io_req_prep_async(struct io_kiocb *req)
6105 const struct io_op_def *def = &io_op_defs[req->opcode];
6107 /* assign early for deferred execution for non-fixed file */
6108 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
6109 req->file = io_file_get_normal(req, req->cqe.fd);
6110 if (!def->prep_async)
6112 if (WARN_ON_ONCE(req_has_async_data(req)))
6114 if (io_alloc_async_data(req))
6117 return def->prep_async(req);
6120 static u32 io_get_sequence(struct io_kiocb *req)
6122 u32 seq = req->ctx->cached_sq_head;
6123 struct io_kiocb *cur;
6125 /* need original cached_sq_head, but it was increased for each req */
6126 io_for_each_link(cur, req)
6131 static __cold void io_drain_req(struct io_kiocb *req)
6133 struct io_ring_ctx *ctx = req->ctx;
6134 struct io_defer_entry *de;
6136 u32 seq = io_get_sequence(req);
6138 /* Still need defer if there is pending req in defer list. */
6139 spin_lock(&ctx->completion_lock);
6140 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6141 spin_unlock(&ctx->completion_lock);
6143 ctx->drain_active = false;
6144 io_req_task_queue(req);
6147 spin_unlock(&ctx->completion_lock);
6149 ret = io_req_prep_async(req);
6152 io_req_complete_failed(req, ret);
6155 io_prep_async_link(req);
6156 de = kmalloc(sizeof(*de), GFP_KERNEL);
6162 spin_lock(&ctx->completion_lock);
6163 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6164 spin_unlock(&ctx->completion_lock);
6169 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
6172 list_add_tail(&de->list, &ctx->defer_list);
6173 spin_unlock(&ctx->completion_lock);
6176 static void io_clean_op(struct io_kiocb *req)
6178 if (req->flags & REQ_F_BUFFER_SELECTED) {
6179 spin_lock(&req->ctx->completion_lock);
6180 io_put_kbuf_comp(req);
6181 spin_unlock(&req->ctx->completion_lock);
6184 if (req->flags & REQ_F_NEED_CLEANUP) {
6185 const struct io_op_def *def = &io_op_defs[req->opcode];
6190 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6191 kfree(req->apoll->double_poll);
6195 if (req->flags & REQ_F_INFLIGHT) {
6196 struct io_uring_task *tctx = req->task->io_uring;
6198 atomic_dec(&tctx->inflight_tracked);
6200 if (req->flags & REQ_F_CREDS)
6201 put_cred(req->creds);
6202 if (req->flags & REQ_F_ASYNC_DATA) {
6203 kfree(req->async_data);
6204 req->async_data = NULL;
6206 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6209 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
6211 if (req->file || !io_op_defs[req->opcode].needs_file)
6214 if (req->flags & REQ_F_FIXED_FILE)
6215 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
6217 req->file = io_file_get_normal(req, req->cqe.fd);
6222 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6224 const struct io_op_def *def = &io_op_defs[req->opcode];
6225 const struct cred *creds = NULL;
6228 if (unlikely(!io_assign_file(req, issue_flags)))
6231 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
6232 creds = override_creds(req->creds);
6234 if (!def->audit_skip)
6235 audit_uring_entry(req->opcode);
6237 ret = def->issue(req, issue_flags);
6239 if (!def->audit_skip)
6240 audit_uring_exit(!ret, ret);
6243 revert_creds(creds);
6246 __io_req_complete(req, issue_flags);
6247 else if (ret != IOU_ISSUE_SKIP_COMPLETE)
6250 /* If the op doesn't have a file, we're not polling for it */
6251 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6252 io_iopoll_req_issued(req, issue_flags);
6257 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6259 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6261 req = io_put_req_find_next(req);
6262 return req ? &req->work : NULL;
6265 static void io_wq_submit_work(struct io_wq_work *work)
6267 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6268 const struct io_op_def *def = &io_op_defs[req->opcode];
6269 unsigned int issue_flags = IO_URING_F_UNLOCKED;
6270 bool needs_poll = false;
6271 int ret = 0, err = -ECANCELED;
6273 /* one will be dropped by ->io_free_work() after returning to io-wq */
6274 if (!(req->flags & REQ_F_REFCOUNT))
6275 __io_req_set_refcount(req, 2);
6279 io_arm_ltimeout(req);
6281 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6282 if (work->flags & IO_WQ_WORK_CANCEL) {
6284 io_req_task_queue_fail(req, err);
6287 if (!io_assign_file(req, issue_flags)) {
6289 work->flags |= IO_WQ_WORK_CANCEL;
6293 if (req->flags & REQ_F_FORCE_ASYNC) {
6294 bool opcode_poll = def->pollin || def->pollout;
6296 if (opcode_poll && file_can_poll(req->file)) {
6298 issue_flags |= IO_URING_F_NONBLOCK;
6303 ret = io_issue_sqe(req, issue_flags);
6307 * We can get EAGAIN for iopolled IO even though we're
6308 * forcing a sync submission from here, since we can't
6309 * wait for request slots on the block side.
6312 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
6318 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
6320 /* aborted or ready, in either case retry blocking */
6322 issue_flags &= ~IO_URING_F_NONBLOCK;
6325 /* avoid locking problems by failing it from a clean context */
6327 io_req_task_queue_fail(req, ret);
6330 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6333 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6335 return (struct file *) (slot->file_ptr & FFS_MASK);
6338 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6340 unsigned long file_ptr = (unsigned long) file;
6342 file_ptr |= io_file_get_flags(file);
6343 file_slot->file_ptr = file_ptr;
6346 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
6347 unsigned int issue_flags)
6349 struct io_ring_ctx *ctx = req->ctx;
6350 struct file *file = NULL;
6351 unsigned long file_ptr;
6353 io_ring_submit_lock(ctx, issue_flags);
6355 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6357 fd = array_index_nospec(fd, ctx->nr_user_files);
6358 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6359 file = (struct file *) (file_ptr & FFS_MASK);
6360 file_ptr &= ~FFS_MASK;
6361 /* mask in overlapping REQ_F and FFS bits */
6362 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
6363 io_req_set_rsrc_node(req, ctx, 0);
6364 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
6366 io_ring_submit_unlock(ctx, issue_flags);
6370 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
6372 struct file *file = fget(fd);
6374 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
6376 /* we don't allow fixed io_uring files */
6377 if (file && file->f_op == &io_uring_fops)
6378 io_req_track_inflight(req);
6382 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6384 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6385 struct io_kiocb *prev = timeout->prev;
6389 if (!(req->task->flags & PF_EXITING)) {
6390 struct io_cancel_data cd = {
6392 .data = prev->cqe.user_data,
6395 ret = io_try_cancel(req, &cd);
6397 io_req_set_res(req, ret ?: -ETIME, 0);
6398 io_req_complete_post(req);
6401 io_req_set_res(req, -ETIME, 0);
6402 io_req_complete_post(req);
6406 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6408 struct io_timeout_data *data = container_of(timer,
6409 struct io_timeout_data, timer);
6410 struct io_kiocb *prev, *req = data->req;
6411 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6412 struct io_ring_ctx *ctx = req->ctx;
6413 unsigned long flags;
6415 spin_lock_irqsave(&ctx->timeout_lock, flags);
6416 prev = timeout->head;
6417 timeout->head = NULL;
6420 * We don't expect the list to be empty, that will only happen if we
6421 * race with the completion of the linked work.
6424 io_remove_next_linked(prev);
6425 if (!req_ref_inc_not_zero(prev))
6428 list_del(&timeout->list);
6429 timeout->prev = prev;
6430 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6432 req->io_task_work.func = io_req_task_link_timeout;
6433 io_req_task_work_add(req);
6434 return HRTIMER_NORESTART;
6437 static void io_queue_linked_timeout(struct io_kiocb *req)
6439 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6440 struct io_ring_ctx *ctx = req->ctx;
6442 spin_lock_irq(&ctx->timeout_lock);
6444 * If the back reference is NULL, then our linked request finished
6445 * before we got a chance to setup the timer
6447 if (timeout->head) {
6448 struct io_timeout_data *data = req->async_data;
6450 data->timer.function = io_link_timeout_fn;
6451 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6453 list_add_tail(&timeout->list, &ctx->ltimeout_list);
6455 spin_unlock_irq(&ctx->timeout_lock);
6456 /* drop submission reference */
6460 static void io_queue_async(struct io_kiocb *req, int ret)
6461 __must_hold(&req->ctx->uring_lock)
6463 struct io_kiocb *linked_timeout;
6465 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
6466 io_req_complete_failed(req, ret);
6470 linked_timeout = io_prep_linked_timeout(req);
6472 switch (io_arm_poll_handler(req, 0)) {
6473 case IO_APOLL_READY:
6474 io_req_task_queue(req);
6476 case IO_APOLL_ABORTED:
6478 * Queued up for async execution, worker will release
6479 * submit reference when the iocb is actually submitted.
6481 io_kbuf_recycle(req, 0);
6482 io_queue_iowq(req, NULL);
6489 io_queue_linked_timeout(linked_timeout);
6492 static inline void io_queue_sqe(struct io_kiocb *req)
6493 __must_hold(&req->ctx->uring_lock)
6497 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6499 if (req->flags & REQ_F_COMPLETE_INLINE) {
6500 io_req_add_compl_list(req);
6504 * We async punt it if the file wasn't marked NOWAIT, or if the file
6505 * doesn't support non-blocking read/write attempts
6508 io_arm_ltimeout(req);
6510 io_queue_async(req, ret);
6513 static void io_queue_sqe_fallback(struct io_kiocb *req)
6514 __must_hold(&req->ctx->uring_lock)
6516 if (unlikely(req->flags & REQ_F_FAIL)) {
6518 * We don't submit, fail them all, for that replace hardlinks
6519 * with normal links. Extra REQ_F_LINK is tolerated.
6521 req->flags &= ~REQ_F_HARDLINK;
6522 req->flags |= REQ_F_LINK;
6523 io_req_complete_failed(req, req->cqe.res);
6524 } else if (unlikely(req->ctx->drain_active)) {
6527 int ret = io_req_prep_async(req);
6530 io_req_complete_failed(req, ret);
6532 io_queue_iowq(req, NULL);
6537 * Check SQE restrictions (opcode and flags).
6539 * Returns 'true' if SQE is allowed, 'false' otherwise.
6541 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6542 struct io_kiocb *req,
6543 unsigned int sqe_flags)
6545 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6548 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6549 ctx->restrictions.sqe_flags_required)
6552 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6553 ctx->restrictions.sqe_flags_required))
6559 static void io_init_req_drain(struct io_kiocb *req)
6561 struct io_ring_ctx *ctx = req->ctx;
6562 struct io_kiocb *head = ctx->submit_state.link.head;
6564 ctx->drain_active = true;
6567 * If we need to drain a request in the middle of a link, drain
6568 * the head request and the next request/link after the current
6569 * link. Considering sequential execution of links,
6570 * REQ_F_IO_DRAIN will be maintained for every request of our
6573 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
6574 ctx->drain_next = true;
6578 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6579 const struct io_uring_sqe *sqe)
6580 __must_hold(&ctx->uring_lock)
6582 const struct io_op_def *def;
6583 unsigned int sqe_flags;
6587 /* req is partially pre-initialised, see io_preinit_req() */
6588 req->opcode = opcode = READ_ONCE(sqe->opcode);
6589 /* same numerical values with corresponding REQ_F_*, safe to copy */
6590 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6591 req->cqe.user_data = READ_ONCE(sqe->user_data);
6593 req->rsrc_node = NULL;
6594 req->task = current;
6596 if (unlikely(opcode >= IORING_OP_LAST)) {
6600 def = &io_op_defs[opcode];
6601 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
6602 /* enforce forwards compatibility on users */
6603 if (sqe_flags & ~SQE_VALID_FLAGS)
6605 if (sqe_flags & IOSQE_BUFFER_SELECT) {
6606 if (!def->buffer_select)
6608 req->buf_index = READ_ONCE(sqe->buf_group);
6610 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
6611 ctx->drain_disabled = true;
6612 if (sqe_flags & IOSQE_IO_DRAIN) {
6613 if (ctx->drain_disabled)
6615 io_init_req_drain(req);
6618 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
6619 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
6621 /* knock it to the slow queue path, will be drained there */
6622 if (ctx->drain_active)
6623 req->flags |= REQ_F_FORCE_ASYNC;
6624 /* if there is no link, we're at "next" request and need to drain */
6625 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
6626 ctx->drain_next = false;
6627 ctx->drain_active = true;
6628 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
6632 if (!def->ioprio && sqe->ioprio)
6634 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
6637 if (def->needs_file) {
6638 struct io_submit_state *state = &ctx->submit_state;
6640 req->cqe.fd = READ_ONCE(sqe->fd);
6643 * Plug now if we have more than 2 IO left after this, and the
6644 * target is potentially a read/write to block based storage.
6646 if (state->need_plug && def->plug) {
6647 state->plug_started = true;
6648 state->need_plug = false;
6649 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
6653 personality = READ_ONCE(sqe->personality);
6657 req->creds = xa_load(&ctx->personalities, personality);
6660 get_cred(req->creds);
6661 ret = security_uring_override_creds(req->creds);
6663 put_cred(req->creds);
6666 req->flags |= REQ_F_CREDS;
6669 return def->prep(req, sqe);
6672 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
6673 struct io_kiocb *req, int ret)
6675 struct io_ring_ctx *ctx = req->ctx;
6676 struct io_submit_link *link = &ctx->submit_state.link;
6677 struct io_kiocb *head = link->head;
6679 trace_io_uring_req_failed(sqe, ctx, req, ret);
6682 * Avoid breaking links in the middle as it renders links with SQPOLL
6683 * unusable. Instead of failing eagerly, continue assembling the link if
6684 * applicable and mark the head with REQ_F_FAIL. The link flushing code
6685 * should find the flag and handle the rest.
6687 req_fail_link_node(req, ret);
6688 if (head && !(head->flags & REQ_F_FAIL))
6689 req_fail_link_node(head, -ECANCELED);
6691 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
6693 link->last->link = req;
6697 io_queue_sqe_fallback(req);
6702 link->last->link = req;
6709 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6710 const struct io_uring_sqe *sqe)
6711 __must_hold(&ctx->uring_lock)
6713 struct io_submit_link *link = &ctx->submit_state.link;
6716 ret = io_init_req(ctx, req, sqe);
6718 return io_submit_fail_init(sqe, req, ret);
6720 /* don't need @sqe from now on */
6721 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
6723 ctx->flags & IORING_SETUP_SQPOLL);
6726 * If we already have a head request, queue this one for async
6727 * submittal once the head completes. If we don't have a head but
6728 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6729 * submitted sync once the chain is complete. If none of those
6730 * conditions are true (normal request), then just queue it.
6732 if (unlikely(link->head)) {
6733 ret = io_req_prep_async(req);
6735 return io_submit_fail_init(sqe, req, ret);
6737 trace_io_uring_link(ctx, req, link->head);
6738 link->last->link = req;
6741 if (req->flags & IO_REQ_LINK_FLAGS)
6743 /* last request of the link, flush it */
6746 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
6749 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
6750 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
6751 if (req->flags & IO_REQ_LINK_FLAGS) {
6756 io_queue_sqe_fallback(req);
6766 * Batched submission is done, ensure local IO is flushed out.
6768 static void io_submit_state_end(struct io_ring_ctx *ctx)
6770 struct io_submit_state *state = &ctx->submit_state;
6772 if (unlikely(state->link.head))
6773 io_queue_sqe_fallback(state->link.head);
6774 /* flush only after queuing links as they can generate completions */
6775 io_submit_flush_completions(ctx);
6776 if (state->plug_started)
6777 blk_finish_plug(&state->plug);
6781 * Start submission side cache.
6783 static void io_submit_state_start(struct io_submit_state *state,
6784 unsigned int max_ios)
6786 state->plug_started = false;
6787 state->need_plug = max_ios > 2;
6788 state->submit_nr = max_ios;
6789 /* set only head, no need to init link_last in advance */
6790 state->link.head = NULL;
6793 static void io_commit_sqring(struct io_ring_ctx *ctx)
6795 struct io_rings *rings = ctx->rings;
6798 * Ensure any loads from the SQEs are done at this point,
6799 * since once we write the new head, the application could
6800 * write new data to them.
6802 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6806 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6807 * that is mapped by userspace. This means that care needs to be taken to
6808 * ensure that reads are stable, as we cannot rely on userspace always
6809 * being a good citizen. If members of the sqe are validated and then later
6810 * used, it's important that those reads are done through READ_ONCE() to
6811 * prevent a re-load down the line.
6813 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6815 unsigned head, mask = ctx->sq_entries - 1;
6816 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6819 * The cached sq head (or cq tail) serves two purposes:
6821 * 1) allows us to batch the cost of updating the user visible
6823 * 2) allows the kernel side to track the head on its own, even
6824 * though the application is the one updating it.
6826 head = READ_ONCE(ctx->sq_array[sq_idx]);
6827 if (likely(head < ctx->sq_entries)) {
6828 /* double index for 128-byte SQEs, twice as long */
6829 if (ctx->flags & IORING_SETUP_SQE128)
6831 return &ctx->sq_sqes[head];
6834 /* drop invalid entries */
6836 WRITE_ONCE(ctx->rings->sq_dropped,
6837 READ_ONCE(ctx->rings->sq_dropped) + 1);
6841 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6842 __must_hold(&ctx->uring_lock)
6844 unsigned int entries = io_sqring_entries(ctx);
6848 if (unlikely(!entries))
6850 /* make sure SQ entry isn't read before tail */
6851 ret = left = min3(nr, ctx->sq_entries, entries);
6852 io_get_task_refs(left);
6853 io_submit_state_start(&ctx->submit_state, left);
6856 const struct io_uring_sqe *sqe;
6857 struct io_kiocb *req;
6859 if (unlikely(!io_alloc_req_refill(ctx)))
6861 req = io_alloc_req(ctx);
6862 sqe = io_get_sqe(ctx);
6863 if (unlikely(!sqe)) {
6864 io_req_add_to_cache(req, ctx);
6869 * Continue submitting even for sqe failure if the
6870 * ring was setup with IORING_SETUP_SUBMIT_ALL
6872 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
6873 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
6879 if (unlikely(left)) {
6881 /* try again if it submitted nothing and can't allocate a req */
6882 if (!ret && io_req_cache_empty(ctx))
6884 current->io_uring->cached_refs += left;
6887 io_submit_state_end(ctx);
6888 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6889 io_commit_sqring(ctx);
6893 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
6895 return READ_ONCE(sqd->state);
6898 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6900 unsigned int to_submit;
6903 to_submit = io_sqring_entries(ctx);
6904 /* if we're handling multiple rings, cap submit size for fairness */
6905 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
6906 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
6908 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
6909 const struct cred *creds = NULL;
6911 if (ctx->sq_creds != current_cred())
6912 creds = override_creds(ctx->sq_creds);
6914 mutex_lock(&ctx->uring_lock);
6915 if (!wq_list_empty(&ctx->iopoll_list))
6916 io_do_iopoll(ctx, true);
6919 * Don't submit if refs are dying, good for io_uring_register(),
6920 * but also it is relied upon by io_ring_exit_work()
6922 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6923 !(ctx->flags & IORING_SETUP_R_DISABLED))
6924 ret = io_submit_sqes(ctx, to_submit);
6925 mutex_unlock(&ctx->uring_lock);
6927 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
6928 wake_up(&ctx->sqo_sq_wait);
6930 revert_creds(creds);
6936 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6938 struct io_ring_ctx *ctx;
6939 unsigned sq_thread_idle = 0;
6941 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6942 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6943 sqd->sq_thread_idle = sq_thread_idle;
6946 static bool io_sqd_handle_event(struct io_sq_data *sqd)
6948 bool did_sig = false;
6949 struct ksignal ksig;
6951 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6952 signal_pending(current)) {
6953 mutex_unlock(&sqd->lock);
6954 if (signal_pending(current))
6955 did_sig = get_signal(&ksig);
6957 mutex_lock(&sqd->lock);
6959 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6962 static int io_sq_thread(void *data)
6964 struct io_sq_data *sqd = data;
6965 struct io_ring_ctx *ctx;
6966 unsigned long timeout = 0;
6967 char buf[TASK_COMM_LEN];
6970 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6971 set_task_comm(current, buf);
6973 if (sqd->sq_cpu != -1)
6974 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6976 set_cpus_allowed_ptr(current, cpu_online_mask);
6977 current->flags |= PF_NO_SETAFFINITY;
6979 audit_alloc_kernel(current);
6981 mutex_lock(&sqd->lock);
6983 bool cap_entries, sqt_spin = false;
6985 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
6986 if (io_sqd_handle_event(sqd))
6988 timeout = jiffies + sqd->sq_thread_idle;
6991 cap_entries = !list_is_singular(&sqd->ctx_list);
6992 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6993 int ret = __io_sq_thread(ctx, cap_entries);
6995 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
6998 if (io_run_task_work())
7001 if (sqt_spin || !time_after(jiffies, timeout)) {
7004 timeout = jiffies + sqd->sq_thread_idle;
7008 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7009 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
7010 bool needs_sched = true;
7012 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7013 atomic_or(IORING_SQ_NEED_WAKEUP,
7014 &ctx->rings->sq_flags);
7015 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7016 !wq_list_empty(&ctx->iopoll_list)) {
7017 needs_sched = false;
7022 * Ensure the store of the wakeup flag is not
7023 * reordered with the load of the SQ tail
7025 smp_mb__after_atomic();
7027 if (io_sqring_entries(ctx)) {
7028 needs_sched = false;
7034 mutex_unlock(&sqd->lock);
7036 mutex_lock(&sqd->lock);
7038 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7039 atomic_andnot(IORING_SQ_NEED_WAKEUP,
7040 &ctx->rings->sq_flags);
7043 finish_wait(&sqd->wait, &wait);
7044 timeout = jiffies + sqd->sq_thread_idle;
7047 io_uring_cancel_generic(true, sqd);
7049 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7050 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
7052 mutex_unlock(&sqd->lock);
7054 audit_free(current);
7056 complete(&sqd->exited);
7060 struct io_wait_queue {
7061 struct wait_queue_entry wq;
7062 struct io_ring_ctx *ctx;
7064 unsigned nr_timeouts;
7067 static inline bool io_should_wake(struct io_wait_queue *iowq)
7069 struct io_ring_ctx *ctx = iowq->ctx;
7070 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7073 * Wake up if we have enough events, or if a timeout occurred since we
7074 * started waiting. For timeouts, we always want to return to userspace,
7075 * regardless of event count.
7077 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7080 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7081 int wake_flags, void *key)
7083 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7087 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7088 * the task, and the next invocation will do it.
7090 if (io_should_wake(iowq) ||
7091 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
7092 return autoremove_wake_function(curr, mode, wake_flags, key);
7096 static int io_run_task_work_sig(void)
7098 if (io_run_task_work())
7100 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7101 return -ERESTARTSYS;
7102 if (task_sigpending(current))
7107 /* when returns >0, the caller should retry */
7108 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7109 struct io_wait_queue *iowq,
7113 unsigned long check_cq;
7115 /* make sure we run task_work before checking for signals */
7116 ret = io_run_task_work_sig();
7117 if (ret || io_should_wake(iowq))
7119 check_cq = READ_ONCE(ctx->check_cq);
7120 /* let the caller flush overflows, retry */
7121 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
7123 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
7125 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
7131 * Wait until events become available, if we don't already have some. The
7132 * application must reap them itself, as they reside on the shared cq ring.
7134 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7135 const sigset_t __user *sig, size_t sigsz,
7136 struct __kernel_timespec __user *uts)
7138 struct io_wait_queue iowq;
7139 struct io_rings *rings = ctx->rings;
7140 ktime_t timeout = KTIME_MAX;
7144 io_cqring_overflow_flush(ctx);
7145 if (io_cqring_events(ctx) >= min_events)
7147 if (!io_run_task_work())
7152 #ifdef CONFIG_COMPAT
7153 if (in_compat_syscall())
7154 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7158 ret = set_user_sigmask(sig, sigsz);
7165 struct timespec64 ts;
7167 if (get_timespec64(&ts, uts))
7169 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7172 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7173 iowq.wq.private = current;
7174 INIT_LIST_HEAD(&iowq.wq.entry);
7176 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7177 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7179 trace_io_uring_cqring_wait(ctx, min_events);
7181 /* if we can't even flush overflow, don't wait for more */
7182 if (!io_cqring_overflow_flush(ctx)) {
7186 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7187 TASK_INTERRUPTIBLE);
7188 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
7192 finish_wait(&ctx->cq_wait, &iowq.wq);
7193 restore_saved_sigmask_unless(ret == -EINTR);
7195 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7198 static void io_free_page_table(void **table, size_t size)
7200 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7202 for (i = 0; i < nr_tables; i++)
7207 static __cold void **io_alloc_page_table(size_t size)
7209 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7210 size_t init_size = size;
7213 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7217 for (i = 0; i < nr_tables; i++) {
7218 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7220 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7222 io_free_page_table(table, init_size);
7230 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7232 percpu_ref_exit(&ref_node->refs);
7236 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7238 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7239 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7240 unsigned long flags;
7241 bool first_add = false;
7242 unsigned long delay = HZ;
7244 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7247 /* if we are mid-quiesce then do not delay */
7248 if (node->rsrc_data->quiesce)
7251 while (!list_empty(&ctx->rsrc_ref_list)) {
7252 node = list_first_entry(&ctx->rsrc_ref_list,
7253 struct io_rsrc_node, node);
7254 /* recycle ref nodes in order */
7257 list_del(&node->node);
7258 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7260 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7263 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7266 static struct io_rsrc_node *io_rsrc_node_alloc(void)
7268 struct io_rsrc_node *ref_node;
7270 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7274 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7279 INIT_LIST_HEAD(&ref_node->node);
7280 INIT_LIST_HEAD(&ref_node->rsrc_list);
7281 ref_node->done = false;
7285 void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7286 struct io_rsrc_data *data_to_kill)
7287 __must_hold(&ctx->uring_lock)
7289 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7290 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7292 io_rsrc_refs_drop(ctx);
7295 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7297 rsrc_node->rsrc_data = data_to_kill;
7298 spin_lock_irq(&ctx->rsrc_ref_lock);
7299 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7300 spin_unlock_irq(&ctx->rsrc_ref_lock);
7302 atomic_inc(&data_to_kill->refs);
7303 percpu_ref_kill(&rsrc_node->refs);
7304 ctx->rsrc_node = NULL;
7307 if (!ctx->rsrc_node) {
7308 ctx->rsrc_node = ctx->rsrc_backup_node;
7309 ctx->rsrc_backup_node = NULL;
7313 int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7315 if (ctx->rsrc_backup_node)
7317 ctx->rsrc_backup_node = io_rsrc_node_alloc();
7318 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7321 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
7322 struct io_ring_ctx *ctx)
7326 /* As we may drop ->uring_lock, other task may have started quiesce */
7330 data->quiesce = true;
7332 ret = io_rsrc_node_switch_start(ctx);
7335 io_rsrc_node_switch(ctx, data);
7337 /* kill initial ref, already quiesced if zero */
7338 if (atomic_dec_and_test(&data->refs))
7340 mutex_unlock(&ctx->uring_lock);
7341 flush_delayed_work(&ctx->rsrc_put_work);
7342 ret = wait_for_completion_interruptible(&data->done);
7344 mutex_lock(&ctx->uring_lock);
7345 if (atomic_read(&data->refs) > 0) {
7347 * it has been revived by another thread while
7350 mutex_unlock(&ctx->uring_lock);
7356 atomic_inc(&data->refs);
7357 /* wait for all works potentially completing data->done */
7358 flush_delayed_work(&ctx->rsrc_put_work);
7359 reinit_completion(&data->done);
7361 ret = io_run_task_work_sig();
7362 mutex_lock(&ctx->uring_lock);
7364 data->quiesce = false;
7369 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7371 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7372 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7374 return &data->tags[table_idx][off];
7377 static void io_rsrc_data_free(struct io_rsrc_data *data)
7379 size_t size = data->nr * sizeof(data->tags[0][0]);
7382 io_free_page_table((void **)data->tags, size);
7386 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7387 u64 __user *utags, unsigned nr,
7388 struct io_rsrc_data **pdata)
7390 struct io_rsrc_data *data;
7394 data = kzalloc(sizeof(*data), GFP_KERNEL);
7397 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7405 data->do_put = do_put;
7408 for (i = 0; i < nr; i++) {
7409 u64 *tag_slot = io_get_tag_slot(data, i);
7411 if (copy_from_user(tag_slot, &utags[i],
7417 atomic_set(&data->refs, 1);
7418 init_completion(&data->done);
7422 io_rsrc_data_free(data);
7426 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7428 #if !defined(IO_URING_SCM_ALL)
7431 for (i = 0; i < ctx->nr_user_files; i++) {
7432 struct file *file = io_file_from_index(ctx, i);
7436 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
7438 io_file_bitmap_clear(&ctx->file_table, i);
7443 #if defined(CONFIG_UNIX)
7444 if (ctx->ring_sock) {
7445 struct sock *sock = ctx->ring_sock->sk;
7446 struct sk_buff *skb;
7448 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7452 io_free_file_tables(&ctx->file_table);
7453 io_rsrc_data_free(ctx->file_data);
7454 ctx->file_data = NULL;
7455 ctx->nr_user_files = 0;
7458 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7460 unsigned nr = ctx->nr_user_files;
7463 if (!ctx->file_data)
7467 * Quiesce may unlock ->uring_lock, and while it's not held
7468 * prevent new requests using the table.
7470 ctx->nr_user_files = 0;
7471 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7472 ctx->nr_user_files = nr;
7474 __io_sqe_files_unregister(ctx);
7478 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7479 __releases(&sqd->lock)
7481 WARN_ON_ONCE(sqd->thread == current);
7484 * Do the dance but not conditional clear_bit() because it'd race with
7485 * other threads incrementing park_pending and setting the bit.
7487 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7488 if (atomic_dec_return(&sqd->park_pending))
7489 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7490 mutex_unlock(&sqd->lock);
7493 static void io_sq_thread_park(struct io_sq_data *sqd)
7494 __acquires(&sqd->lock)
7496 WARN_ON_ONCE(sqd->thread == current);
7498 atomic_inc(&sqd->park_pending);
7499 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7500 mutex_lock(&sqd->lock);
7502 wake_up_process(sqd->thread);
7505 static void io_sq_thread_stop(struct io_sq_data *sqd)
7507 WARN_ON_ONCE(sqd->thread == current);
7508 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7510 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7511 mutex_lock(&sqd->lock);
7513 wake_up_process(sqd->thread);
7514 mutex_unlock(&sqd->lock);
7515 wait_for_completion(&sqd->exited);
7518 static void io_put_sq_data(struct io_sq_data *sqd)
7520 if (refcount_dec_and_test(&sqd->refs)) {
7521 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7523 io_sq_thread_stop(sqd);
7528 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7530 struct io_sq_data *sqd = ctx->sq_data;
7533 io_sq_thread_park(sqd);
7534 list_del_init(&ctx->sqd_list);
7535 io_sqd_update_thread_idle(sqd);
7536 io_sq_thread_unpark(sqd);
7538 io_put_sq_data(sqd);
7539 ctx->sq_data = NULL;
7543 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7545 struct io_ring_ctx *ctx_attach;
7546 struct io_sq_data *sqd;
7549 f = fdget(p->wq_fd);
7551 return ERR_PTR(-ENXIO);
7552 if (f.file->f_op != &io_uring_fops) {
7554 return ERR_PTR(-EINVAL);
7557 ctx_attach = f.file->private_data;
7558 sqd = ctx_attach->sq_data;
7561 return ERR_PTR(-EINVAL);
7563 if (sqd->task_tgid != current->tgid) {
7565 return ERR_PTR(-EPERM);
7568 refcount_inc(&sqd->refs);
7573 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7576 struct io_sq_data *sqd;
7579 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7580 sqd = io_attach_sq_data(p);
7585 /* fall through for EPERM case, setup new sqd/task */
7586 if (PTR_ERR(sqd) != -EPERM)
7590 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7592 return ERR_PTR(-ENOMEM);
7594 atomic_set(&sqd->park_pending, 0);
7595 refcount_set(&sqd->refs, 1);
7596 INIT_LIST_HEAD(&sqd->ctx_list);
7597 mutex_init(&sqd->lock);
7598 init_waitqueue_head(&sqd->wait);
7599 init_completion(&sqd->exited);
7604 * Ensure the UNIX gc is aware of our file set, so we are certain that
7605 * the io_uring can be safely unregistered on process exit, even if we have
7606 * loops in the file referencing. We account only files that can hold other
7607 * files because otherwise they can't form a loop and so are not interesting
7610 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
7612 #if defined(CONFIG_UNIX)
7613 struct sock *sk = ctx->ring_sock->sk;
7614 struct sk_buff_head *head = &sk->sk_receive_queue;
7615 struct scm_fp_list *fpl;
7616 struct sk_buff *skb;
7618 if (likely(!io_file_need_scm(file)))
7622 * See if we can merge this file into an existing skb SCM_RIGHTS
7623 * file set. If there's no room, fall back to allocating a new skb
7624 * and filling it in.
7626 spin_lock_irq(&head->lock);
7627 skb = skb_peek(head);
7628 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
7629 __skb_unlink(skb, head);
7632 spin_unlock_irq(&head->lock);
7635 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7639 skb = alloc_skb(0, GFP_KERNEL);
7645 fpl->user = get_uid(current_user());
7646 fpl->max = SCM_MAX_FD;
7649 UNIXCB(skb).fp = fpl;
7651 skb->destructor = unix_destruct_scm;
7652 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7655 fpl = UNIXCB(skb).fp;
7656 fpl->fp[fpl->count++] = get_file(file);
7657 unix_inflight(fpl->user, file);
7658 skb_queue_head(head, skb);
7664 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7666 struct file *file = prsrc->file;
7667 #if defined(CONFIG_UNIX)
7668 struct sock *sock = ctx->ring_sock->sk;
7669 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7670 struct sk_buff *skb;
7673 if (!io_file_need_scm(file)) {
7678 __skb_queue_head_init(&list);
7681 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7682 * remove this entry and rearrange the file array.
7684 skb = skb_dequeue(head);
7686 struct scm_fp_list *fp;
7688 fp = UNIXCB(skb).fp;
7689 for (i = 0; i < fp->count; i++) {
7692 if (fp->fp[i] != file)
7695 unix_notinflight(fp->user, fp->fp[i]);
7696 left = fp->count - 1 - i;
7698 memmove(&fp->fp[i], &fp->fp[i + 1],
7699 left * sizeof(struct file *));
7706 __skb_queue_tail(&list, skb);
7716 __skb_queue_tail(&list, skb);
7718 skb = skb_dequeue(head);
7721 if (skb_peek(&list)) {
7722 spin_lock_irq(&head->lock);
7723 while ((skb = __skb_dequeue(&list)) != NULL)
7724 __skb_queue_tail(head, skb);
7725 spin_unlock_irq(&head->lock);
7732 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7734 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7735 struct io_ring_ctx *ctx = rsrc_data->ctx;
7736 struct io_rsrc_put *prsrc, *tmp;
7738 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7739 list_del(&prsrc->list);
7742 if (ctx->flags & IORING_SETUP_IOPOLL)
7743 mutex_lock(&ctx->uring_lock);
7745 spin_lock(&ctx->completion_lock);
7746 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
7747 io_commit_cqring(ctx);
7748 spin_unlock(&ctx->completion_lock);
7749 io_cqring_ev_posted(ctx);
7751 if (ctx->flags & IORING_SETUP_IOPOLL)
7752 mutex_unlock(&ctx->uring_lock);
7755 rsrc_data->do_put(ctx, prsrc);
7759 io_rsrc_node_destroy(ref_node);
7760 if (atomic_dec_and_test(&rsrc_data->refs))
7761 complete(&rsrc_data->done);
7764 static void io_rsrc_put_work(struct work_struct *work)
7766 struct io_ring_ctx *ctx;
7767 struct llist_node *node;
7769 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7770 node = llist_del_all(&ctx->rsrc_put_llist);
7773 struct io_rsrc_node *ref_node;
7774 struct llist_node *next = node->next;
7776 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7777 __io_rsrc_put_work(ref_node);
7782 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7783 unsigned nr_args, u64 __user *tags)
7785 __s32 __user *fds = (__s32 __user *) arg;
7794 if (nr_args > IORING_MAX_FIXED_FILES)
7796 if (nr_args > rlimit(RLIMIT_NOFILE))
7798 ret = io_rsrc_node_switch_start(ctx);
7801 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7806 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
7807 io_rsrc_data_free(ctx->file_data);
7808 ctx->file_data = NULL;
7812 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7813 struct io_fixed_file *file_slot;
7815 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
7819 /* allow sparse sets */
7820 if (!fds || fd == -1) {
7822 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7829 if (unlikely(!file))
7833 * Don't allow io_uring instances to be registered. If UNIX
7834 * isn't enabled, then this causes a reference cycle and this
7835 * instance can never get freed. If UNIX is enabled we'll
7836 * handle it just fine, but there's still no point in allowing
7837 * a ring fd as it doesn't support regular read/write anyway.
7839 if (file->f_op == &io_uring_fops) {
7843 ret = io_scm_file_account(ctx, file);
7848 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7849 io_fixed_file_set(file_slot, file);
7850 io_file_bitmap_set(&ctx->file_table, i);
7853 io_rsrc_node_switch(ctx, NULL);
7856 __io_sqe_files_unregister(ctx);
7860 int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7861 struct io_rsrc_node *node, void *rsrc)
7863 u64 *tag_slot = io_get_tag_slot(data, idx);
7864 struct io_rsrc_put *prsrc;
7866 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7870 prsrc->tag = *tag_slot;
7873 list_add(&prsrc->list, &node->rsrc_list);
7877 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
7878 unsigned int issue_flags, u32 slot_index)
7879 __must_hold(&req->ctx->uring_lock)
7881 struct io_ring_ctx *ctx = req->ctx;
7882 bool needs_switch = false;
7883 struct io_fixed_file *file_slot;
7886 if (file->f_op == &io_uring_fops)
7888 if (!ctx->file_data)
7890 if (slot_index >= ctx->nr_user_files)
7893 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
7894 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
7896 if (file_slot->file_ptr) {
7897 struct file *old_file;
7899 ret = io_rsrc_node_switch_start(ctx);
7903 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7904 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
7905 ctx->rsrc_node, old_file);
7908 file_slot->file_ptr = 0;
7909 io_file_bitmap_clear(&ctx->file_table, slot_index);
7910 needs_switch = true;
7913 ret = io_scm_file_account(ctx, file);
7915 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
7916 io_fixed_file_set(file_slot, file);
7917 io_file_bitmap_set(&ctx->file_table, slot_index);
7921 io_rsrc_node_switch(ctx, ctx->file_data);
7927 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7928 struct io_uring_rsrc_update2 *up,
7931 u64 __user *tags = u64_to_user_ptr(up->tags);
7932 __s32 __user *fds = u64_to_user_ptr(up->data);
7933 struct io_rsrc_data *data = ctx->file_data;
7934 struct io_fixed_file *file_slot;
7938 bool needs_switch = false;
7940 if (!ctx->file_data)
7942 if (up->offset + nr_args > ctx->nr_user_files)
7945 for (done = 0; done < nr_args; done++) {
7948 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7949 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7953 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7957 if (fd == IORING_REGISTER_FILES_SKIP)
7960 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7961 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7963 if (file_slot->file_ptr) {
7964 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7965 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
7968 file_slot->file_ptr = 0;
7969 io_file_bitmap_clear(&ctx->file_table, i);
7970 needs_switch = true;
7979 * Don't allow io_uring instances to be registered. If
7980 * UNIX isn't enabled, then this causes a reference
7981 * cycle and this instance can never get freed. If UNIX
7982 * is enabled we'll handle it just fine, but there's
7983 * still no point in allowing a ring fd as it doesn't
7984 * support regular read/write anyway.
7986 if (file->f_op == &io_uring_fops) {
7991 err = io_scm_file_account(ctx, file);
7996 *io_get_tag_slot(data, i) = tag;
7997 io_fixed_file_set(file_slot, file);
7998 io_file_bitmap_set(&ctx->file_table, i);
8003 io_rsrc_node_switch(ctx, data);
8004 return done ? done : err;
8007 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8008 struct task_struct *task)
8010 struct io_wq_hash *hash;
8011 struct io_wq_data data;
8012 unsigned int concurrency;
8014 mutex_lock(&ctx->uring_lock);
8015 hash = ctx->hash_map;
8017 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8019 mutex_unlock(&ctx->uring_lock);
8020 return ERR_PTR(-ENOMEM);
8022 refcount_set(&hash->refs, 1);
8023 init_waitqueue_head(&hash->wait);
8024 ctx->hash_map = hash;
8026 mutex_unlock(&ctx->uring_lock);
8030 data.free_work = io_wq_free_work;
8031 data.do_work = io_wq_submit_work;
8033 /* Do QD, or 4 * CPUS, whatever is smallest */
8034 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8036 return io_wq_create(concurrency, &data);
8039 static __cold int io_uring_alloc_task_context(struct task_struct *task,
8040 struct io_ring_ctx *ctx)
8042 struct io_uring_task *tctx;
8045 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8046 if (unlikely(!tctx))
8049 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
8050 sizeof(struct file *), GFP_KERNEL);
8051 if (unlikely(!tctx->registered_rings)) {
8056 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8057 if (unlikely(ret)) {
8058 kfree(tctx->registered_rings);
8063 tctx->io_wq = io_init_wq_offload(ctx, task);
8064 if (IS_ERR(tctx->io_wq)) {
8065 ret = PTR_ERR(tctx->io_wq);
8066 percpu_counter_destroy(&tctx->inflight);
8067 kfree(tctx->registered_rings);
8073 init_waitqueue_head(&tctx->wait);
8074 atomic_set(&tctx->in_idle, 0);
8075 atomic_set(&tctx->inflight_tracked, 0);
8076 task->io_uring = tctx;
8077 spin_lock_init(&tctx->task_lock);
8078 INIT_WQ_LIST(&tctx->task_list);
8079 INIT_WQ_LIST(&tctx->prio_task_list);
8080 init_task_work(&tctx->task_work, tctx_task_work);
8084 void __io_uring_free(struct task_struct *tsk)
8086 struct io_uring_task *tctx = tsk->io_uring;
8088 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8089 WARN_ON_ONCE(tctx->io_wq);
8090 WARN_ON_ONCE(tctx->cached_refs);
8092 kfree(tctx->registered_rings);
8093 percpu_counter_destroy(&tctx->inflight);
8095 tsk->io_uring = NULL;
8098 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
8099 struct io_uring_params *p)
8103 /* Retain compatibility with failing for an invalid attach attempt */
8104 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8105 IORING_SETUP_ATTACH_WQ) {
8108 f = fdget(p->wq_fd);
8111 if (f.file->f_op != &io_uring_fops) {
8117 if (ctx->flags & IORING_SETUP_SQPOLL) {
8118 struct task_struct *tsk;
8119 struct io_sq_data *sqd;
8122 ret = security_uring_sqpoll();
8126 sqd = io_get_sq_data(p, &attached);
8132 ctx->sq_creds = get_current_cred();
8134 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8135 if (!ctx->sq_thread_idle)
8136 ctx->sq_thread_idle = HZ;
8138 io_sq_thread_park(sqd);
8139 list_add(&ctx->sqd_list, &sqd->ctx_list);
8140 io_sqd_update_thread_idle(sqd);
8141 /* don't attach to a dying SQPOLL thread, would be racy */
8142 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8143 io_sq_thread_unpark(sqd);
8150 if (p->flags & IORING_SETUP_SQ_AFF) {
8151 int cpu = p->sq_thread_cpu;
8154 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8161 sqd->task_pid = current->pid;
8162 sqd->task_tgid = current->tgid;
8163 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8170 ret = io_uring_alloc_task_context(tsk, ctx);
8171 wake_up_new_task(tsk);
8174 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8175 /* Can't have SQ_AFF without SQPOLL */
8182 complete(&ctx->sq_data->exited);
8184 io_sq_thread_finish(ctx);
8188 static inline void __io_unaccount_mem(struct user_struct *user,
8189 unsigned long nr_pages)
8191 atomic_long_sub(nr_pages, &user->locked_vm);
8194 static inline int __io_account_mem(struct user_struct *user,
8195 unsigned long nr_pages)
8197 unsigned long page_limit, cur_pages, new_pages;
8199 /* Don't allow more pages than we can safely lock */
8200 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8203 cur_pages = atomic_long_read(&user->locked_vm);
8204 new_pages = cur_pages + nr_pages;
8205 if (new_pages > page_limit)
8207 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8208 new_pages) != cur_pages);
8213 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8216 __io_unaccount_mem(ctx->user, nr_pages);
8218 if (ctx->mm_account)
8219 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8222 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8227 ret = __io_account_mem(ctx->user, nr_pages);
8232 if (ctx->mm_account)
8233 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8238 static void io_mem_free(void *ptr)
8245 page = virt_to_head_page(ptr);
8246 if (put_page_testzero(page))
8247 free_compound_page(page);
8250 static void *io_mem_alloc(size_t size)
8252 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
8254 return (void *) __get_free_pages(gfp, get_order(size));
8257 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
8258 unsigned int cq_entries, size_t *sq_offset)
8260 struct io_rings *rings;
8261 size_t off, sq_array_size;
8263 off = struct_size(rings, cqes, cq_entries);
8264 if (off == SIZE_MAX)
8266 if (ctx->flags & IORING_SETUP_CQE32) {
8267 if (check_shl_overflow(off, 1, &off))
8272 off = ALIGN(off, SMP_CACHE_BYTES);
8280 sq_array_size = array_size(sizeof(u32), sq_entries);
8281 if (sq_array_size == SIZE_MAX)
8284 if (check_add_overflow(off, sq_array_size, &off))
8290 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8292 struct io_mapped_ubuf *imu = *slot;
8295 if (imu != ctx->dummy_ubuf) {
8296 for (i = 0; i < imu->nr_bvecs; i++)
8297 unpin_user_page(imu->bvec[i].bv_page);
8298 if (imu->acct_pages)
8299 io_unaccount_mem(ctx, imu->acct_pages);
8305 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8307 io_buffer_unmap(ctx, &prsrc->buf);
8311 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8315 for (i = 0; i < ctx->nr_user_bufs; i++)
8316 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8317 kfree(ctx->user_bufs);
8318 io_rsrc_data_free(ctx->buf_data);
8319 ctx->user_bufs = NULL;
8320 ctx->buf_data = NULL;
8321 ctx->nr_user_bufs = 0;
8324 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8326 unsigned nr = ctx->nr_user_bufs;
8333 * Quiesce may unlock ->uring_lock, and while it's not held
8334 * prevent new requests using the table.
8336 ctx->nr_user_bufs = 0;
8337 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8338 ctx->nr_user_bufs = nr;
8340 __io_sqe_buffers_unregister(ctx);
8344 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8345 void __user *arg, unsigned index)
8347 struct iovec __user *src;
8349 #ifdef CONFIG_COMPAT
8351 struct compat_iovec __user *ciovs;
8352 struct compat_iovec ciov;
8354 ciovs = (struct compat_iovec __user *) arg;
8355 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8358 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8359 dst->iov_len = ciov.iov_len;
8363 src = (struct iovec __user *) arg;
8364 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8370 * Not super efficient, but this is just a registration time. And we do cache
8371 * the last compound head, so generally we'll only do a full search if we don't
8374 * We check if the given compound head page has already been accounted, to
8375 * avoid double accounting it. This allows us to account the full size of the
8376 * page, not just the constituent pages of a huge page.
8378 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8379 int nr_pages, struct page *hpage)
8383 /* check current page array */
8384 for (i = 0; i < nr_pages; i++) {
8385 if (!PageCompound(pages[i]))
8387 if (compound_head(pages[i]) == hpage)
8391 /* check previously registered pages */
8392 for (i = 0; i < ctx->nr_user_bufs; i++) {
8393 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8395 for (j = 0; j < imu->nr_bvecs; j++) {
8396 if (!PageCompound(imu->bvec[j].bv_page))
8398 if (compound_head(imu->bvec[j].bv_page) == hpage)
8406 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8407 int nr_pages, struct io_mapped_ubuf *imu,
8408 struct page **last_hpage)
8412 imu->acct_pages = 0;
8413 for (i = 0; i < nr_pages; i++) {
8414 if (!PageCompound(pages[i])) {
8419 hpage = compound_head(pages[i]);
8420 if (hpage == *last_hpage)
8422 *last_hpage = hpage;
8423 if (headpage_already_acct(ctx, pages, i, hpage))
8425 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8429 if (!imu->acct_pages)
8432 ret = io_account_mem(ctx, imu->acct_pages);
8434 imu->acct_pages = 0;
8438 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
8441 unsigned long start, end, nr_pages;
8442 struct vm_area_struct **vmas = NULL;
8443 struct page **pages = NULL;
8444 int i, pret, ret = -ENOMEM;
8446 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8447 start = ubuf >> PAGE_SHIFT;
8448 nr_pages = end - start;
8450 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8454 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8460 mmap_read_lock(current->mm);
8461 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8463 if (pret == nr_pages) {
8464 /* don't support file backed memory */
8465 for (i = 0; i < nr_pages; i++) {
8466 struct vm_area_struct *vma = vmas[i];
8468 if (vma_is_shmem(vma))
8471 !is_file_hugepages(vma->vm_file)) {
8478 ret = pret < 0 ? pret : -EFAULT;
8480 mmap_read_unlock(current->mm);
8483 * if we did partial map, or found file backed vmas,
8484 * release any pages we did get
8487 unpin_user_pages(pages, pret);
8495 pages = ERR_PTR(ret);
8500 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8501 struct io_mapped_ubuf **pimu,
8502 struct page **last_hpage)
8504 struct io_mapped_ubuf *imu = NULL;
8505 struct page **pages = NULL;
8508 int ret, nr_pages, i;
8510 if (!iov->iov_base) {
8511 *pimu = ctx->dummy_ubuf;
8518 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
8520 if (IS_ERR(pages)) {
8521 ret = PTR_ERR(pages);
8526 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8530 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
8532 unpin_user_pages(pages, nr_pages);
8536 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
8537 size = iov->iov_len;
8538 for (i = 0; i < nr_pages; i++) {
8541 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8542 imu->bvec[i].bv_page = pages[i];
8543 imu->bvec[i].bv_len = vec_len;
8544 imu->bvec[i].bv_offset = off;
8548 /* store original address for later verification */
8549 imu->ubuf = (unsigned long) iov->iov_base;
8550 imu->ubuf_end = imu->ubuf + iov->iov_len;
8551 imu->nr_bvecs = nr_pages;
8561 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8563 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8564 return ctx->user_bufs ? 0 : -ENOMEM;
8567 static int io_buffer_validate(struct iovec *iov)
8569 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8572 * Don't impose further limits on the size and buffer
8573 * constraints here, we'll -EINVAL later when IO is
8574 * submitted if they are wrong.
8577 return iov->iov_len ? -EFAULT : 0;
8581 /* arbitrary limit, but we need something */
8582 if (iov->iov_len > SZ_1G)
8585 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8591 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8592 unsigned int nr_args, u64 __user *tags)
8594 struct page *last_hpage = NULL;
8595 struct io_rsrc_data *data;
8601 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8603 ret = io_rsrc_node_switch_start(ctx);
8606 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8609 ret = io_buffers_map_alloc(ctx, nr_args);
8611 io_rsrc_data_free(data);
8615 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8617 ret = io_copy_iov(ctx, &iov, arg, i);
8620 ret = io_buffer_validate(&iov);
8624 memset(&iov, 0, sizeof(iov));
8627 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8632 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8638 WARN_ON_ONCE(ctx->buf_data);
8640 ctx->buf_data = data;
8642 __io_sqe_buffers_unregister(ctx);
8644 io_rsrc_node_switch(ctx, NULL);
8648 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8649 struct io_uring_rsrc_update2 *up,
8650 unsigned int nr_args)
8652 u64 __user *tags = u64_to_user_ptr(up->tags);
8653 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8654 struct page *last_hpage = NULL;
8655 bool needs_switch = false;
8661 if (up->offset + nr_args > ctx->nr_user_bufs)
8664 for (done = 0; done < nr_args; done++) {
8665 struct io_mapped_ubuf *imu;
8666 int offset = up->offset + done;
8669 err = io_copy_iov(ctx, &iov, iovs, done);
8672 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8676 err = io_buffer_validate(&iov);
8679 if (!iov.iov_base && tag) {
8683 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8687 i = array_index_nospec(offset, ctx->nr_user_bufs);
8688 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8689 err = io_queue_rsrc_removal(ctx->buf_data, i,
8690 ctx->rsrc_node, ctx->user_bufs[i]);
8691 if (unlikely(err)) {
8692 io_buffer_unmap(ctx, &imu);
8695 ctx->user_bufs[i] = NULL;
8696 needs_switch = true;
8699 ctx->user_bufs[i] = imu;
8700 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8704 io_rsrc_node_switch(ctx, ctx->buf_data);
8705 return done ? done : err;
8708 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
8709 unsigned int eventfd_async)
8711 struct io_ev_fd *ev_fd;
8712 __s32 __user *fds = arg;
8715 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
8716 lockdep_is_held(&ctx->uring_lock));
8720 if (copy_from_user(&fd, fds, sizeof(*fds)))
8723 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
8727 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
8728 if (IS_ERR(ev_fd->cq_ev_fd)) {
8729 int ret = PTR_ERR(ev_fd->cq_ev_fd);
8733 ev_fd->eventfd_async = eventfd_async;
8734 ctx->has_evfd = true;
8735 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
8739 static void io_eventfd_put(struct rcu_head *rcu)
8741 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
8743 eventfd_ctx_put(ev_fd->cq_ev_fd);
8747 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8749 struct io_ev_fd *ev_fd;
8751 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
8752 lockdep_is_held(&ctx->uring_lock));
8754 ctx->has_evfd = false;
8755 rcu_assign_pointer(ctx->io_ev_fd, NULL);
8756 call_rcu(&ev_fd->rcu, io_eventfd_put);
8763 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8765 struct io_buffer_list *bl;
8766 unsigned long index;
8769 for (i = 0; i < BGID_ARRAY; i++) {
8772 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
8775 xa_for_each(&ctx->io_bl_xa, index, bl) {
8776 xa_erase(&ctx->io_bl_xa, bl->bgid);
8777 __io_remove_buffers(ctx, bl, -1U);
8781 while (!list_empty(&ctx->io_buffers_pages)) {
8784 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
8785 list_del_init(&page->lru);
8790 static void io_req_caches_free(struct io_ring_ctx *ctx)
8792 struct io_submit_state *state = &ctx->submit_state;
8795 mutex_lock(&ctx->uring_lock);
8796 io_flush_cached_locked_reqs(ctx, state);
8798 while (!io_req_cache_empty(ctx)) {
8799 struct io_wq_work_node *node;
8800 struct io_kiocb *req;
8802 node = wq_stack_extract(&state->free_list);
8803 req = container_of(node, struct io_kiocb, comp_list);
8804 kmem_cache_free(req_cachep, req);
8808 percpu_ref_put_many(&ctx->refs, nr);
8809 mutex_unlock(&ctx->uring_lock);
8812 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8814 if (data && !atomic_dec_and_test(&data->refs))
8815 wait_for_completion(&data->done);
8818 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
8820 struct async_poll *apoll;
8822 while (!list_empty(&ctx->apoll_cache)) {
8823 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
8825 list_del(&apoll->poll.wait.entry);
8830 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
8832 io_sq_thread_finish(ctx);
8834 if (ctx->mm_account) {
8835 mmdrop(ctx->mm_account);
8836 ctx->mm_account = NULL;
8839 io_rsrc_refs_drop(ctx);
8840 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8841 io_wait_rsrc_data(ctx->buf_data);
8842 io_wait_rsrc_data(ctx->file_data);
8844 mutex_lock(&ctx->uring_lock);
8846 __io_sqe_buffers_unregister(ctx);
8848 __io_sqe_files_unregister(ctx);
8850 __io_cqring_overflow_flush(ctx, true);
8851 io_eventfd_unregister(ctx);
8852 io_flush_apoll_cache(ctx);
8853 mutex_unlock(&ctx->uring_lock);
8854 io_destroy_buffers(ctx);
8856 put_cred(ctx->sq_creds);
8858 /* there are no registered resources left, nobody uses it */
8860 io_rsrc_node_destroy(ctx->rsrc_node);
8861 if (ctx->rsrc_backup_node)
8862 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8863 flush_delayed_work(&ctx->rsrc_put_work);
8864 flush_delayed_work(&ctx->fallback_work);
8866 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8867 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8869 #if defined(CONFIG_UNIX)
8870 if (ctx->ring_sock) {
8871 ctx->ring_sock->file = NULL; /* so that iput() is called */
8872 sock_release(ctx->ring_sock);
8875 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
8877 io_mem_free(ctx->rings);
8878 io_mem_free(ctx->sq_sqes);
8880 percpu_ref_exit(&ctx->refs);
8881 free_uid(ctx->user);
8882 io_req_caches_free(ctx);
8884 io_wq_put_hash(ctx->hash_map);
8885 kfree(ctx->cancel_hash);
8886 kfree(ctx->dummy_ubuf);
8888 xa_destroy(&ctx->io_bl_xa);
8892 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8894 struct io_ring_ctx *ctx = file->private_data;
8897 poll_wait(file, &ctx->cq_wait, wait);
8899 * synchronizes with barrier from wq_has_sleeper call in
8903 if (!io_sqring_full(ctx))
8904 mask |= EPOLLOUT | EPOLLWRNORM;
8907 * Don't flush cqring overflow list here, just do a simple check.
8908 * Otherwise there could possible be ABBA deadlock:
8911 * lock(&ctx->uring_lock);
8913 * lock(&ctx->uring_lock);
8916 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8917 * pushs them to do the flush.
8919 if (io_cqring_events(ctx) ||
8920 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
8921 mask |= EPOLLIN | EPOLLRDNORM;
8926 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8928 const struct cred *creds;
8930 creds = xa_erase(&ctx->personalities, id);
8939 struct io_tctx_exit {
8940 struct callback_head task_work;
8941 struct completion completion;
8942 struct io_ring_ctx *ctx;
8945 static __cold void io_tctx_exit_cb(struct callback_head *cb)
8947 struct io_uring_task *tctx = current->io_uring;
8948 struct io_tctx_exit *work;
8950 work = container_of(cb, struct io_tctx_exit, task_work);
8952 * When @in_idle, we're in cancellation and it's racy to remove the
8953 * node. It'll be removed by the end of cancellation, just ignore it.
8955 if (!atomic_read(&tctx->in_idle))
8956 io_uring_del_tctx_node((unsigned long)work->ctx);
8957 complete(&work->completion);
8960 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8962 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8964 return req->ctx == data;
8967 static __cold void io_ring_exit_work(struct work_struct *work)
8969 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8970 unsigned long timeout = jiffies + HZ * 60 * 5;
8971 unsigned long interval = HZ / 20;
8972 struct io_tctx_exit exit;
8973 struct io_tctx_node *node;
8977 * If we're doing polled IO and end up having requests being
8978 * submitted async (out-of-line), then completions can come in while
8979 * we're waiting for refs to drop. We need to reap these manually,
8980 * as nobody else will be looking for them.
8983 io_uring_try_cancel_requests(ctx, NULL, true);
8985 struct io_sq_data *sqd = ctx->sq_data;
8986 struct task_struct *tsk;
8988 io_sq_thread_park(sqd);
8990 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8991 io_wq_cancel_cb(tsk->io_uring->io_wq,
8992 io_cancel_ctx_cb, ctx, true);
8993 io_sq_thread_unpark(sqd);
8996 io_req_caches_free(ctx);
8998 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
8999 /* there is little hope left, don't run it too often */
9002 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9004 init_completion(&exit.completion);
9005 init_task_work(&exit.task_work, io_tctx_exit_cb);
9008 * Some may use context even when all refs and requests have been put,
9009 * and they are free to do so while still holding uring_lock or
9010 * completion_lock, see io_req_task_submit(). Apart from other work,
9011 * this lock/unlock section also waits them to finish.
9013 mutex_lock(&ctx->uring_lock);
9014 while (!list_empty(&ctx->tctx_list)) {
9015 WARN_ON_ONCE(time_after(jiffies, timeout));
9017 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9019 /* don't spin on a single task if cancellation failed */
9020 list_rotate_left(&ctx->tctx_list);
9021 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9022 if (WARN_ON_ONCE(ret))
9025 mutex_unlock(&ctx->uring_lock);
9026 wait_for_completion(&exit.completion);
9027 mutex_lock(&ctx->uring_lock);
9029 mutex_unlock(&ctx->uring_lock);
9030 spin_lock(&ctx->completion_lock);
9031 spin_unlock(&ctx->completion_lock);
9033 io_ring_ctx_free(ctx);
9036 /* Returns true if we found and killed one or more timeouts */
9037 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
9038 struct task_struct *tsk, bool cancel_all)
9040 struct io_timeout *timeout, *tmp;
9043 spin_lock(&ctx->completion_lock);
9044 spin_lock_irq(&ctx->timeout_lock);
9045 list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
9046 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
9048 if (io_match_task(req, tsk, cancel_all)) {
9049 io_kill_timeout(req, -ECANCELED);
9053 spin_unlock_irq(&ctx->timeout_lock);
9054 io_commit_cqring(ctx);
9055 spin_unlock(&ctx->completion_lock);
9057 io_cqring_ev_posted(ctx);
9058 return canceled != 0;
9061 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9063 unsigned long index;
9064 struct creds *creds;
9066 mutex_lock(&ctx->uring_lock);
9067 percpu_ref_kill(&ctx->refs);
9069 __io_cqring_overflow_flush(ctx, true);
9070 xa_for_each(&ctx->personalities, index, creds)
9071 io_unregister_personality(ctx, index);
9072 mutex_unlock(&ctx->uring_lock);
9074 /* failed during ring init, it couldn't have issued any requests */
9076 io_kill_timeouts(ctx, NULL, true);
9077 io_poll_remove_all(ctx, NULL, true);
9078 /* if we failed setting up the ctx, we might not have any rings */
9079 io_iopoll_try_reap_events(ctx);
9082 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9084 * Use system_unbound_wq to avoid spawning tons of event kworkers
9085 * if we're exiting a ton of rings at the same time. It just adds
9086 * noise and overhead, there's no discernable change in runtime
9087 * over using system_wq.
9089 queue_work(system_unbound_wq, &ctx->exit_work);
9092 static int io_uring_release(struct inode *inode, struct file *file)
9094 struct io_ring_ctx *ctx = file->private_data;
9096 file->private_data = NULL;
9097 io_ring_ctx_wait_and_kill(ctx);
9101 struct io_task_cancel {
9102 struct task_struct *task;
9106 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9108 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9109 struct io_task_cancel *cancel = data;
9111 return io_match_task_safe(req, cancel->task, cancel->all);
9114 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9115 struct task_struct *task,
9118 struct io_defer_entry *de;
9121 spin_lock(&ctx->completion_lock);
9122 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9123 if (io_match_task_safe(de->req, task, cancel_all)) {
9124 list_cut_position(&list, &ctx->defer_list, &de->list);
9128 spin_unlock(&ctx->completion_lock);
9129 if (list_empty(&list))
9132 while (!list_empty(&list)) {
9133 de = list_first_entry(&list, struct io_defer_entry, list);
9134 list_del_init(&de->list);
9135 io_req_complete_failed(de->req, -ECANCELED);
9141 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9143 struct io_tctx_node *node;
9144 enum io_wq_cancel cret;
9147 mutex_lock(&ctx->uring_lock);
9148 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9149 struct io_uring_task *tctx = node->task->io_uring;
9152 * io_wq will stay alive while we hold uring_lock, because it's
9153 * killed after ctx nodes, which requires to take the lock.
9155 if (!tctx || !tctx->io_wq)
9157 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9158 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9160 mutex_unlock(&ctx->uring_lock);
9165 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9166 struct task_struct *task,
9169 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9170 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9172 /* failed during ring init, it couldn't have issued any requests */
9177 enum io_wq_cancel cret;
9181 ret |= io_uring_try_cancel_iowq(ctx);
9182 } else if (tctx && tctx->io_wq) {
9184 * Cancels requests of all rings, not only @ctx, but
9185 * it's fine as the task is in exit/exec.
9187 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9189 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9192 /* SQPOLL thread does its own polling */
9193 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9194 (ctx->sq_data && ctx->sq_data->thread == current)) {
9195 while (!wq_list_empty(&ctx->iopoll_list)) {
9196 io_iopoll_try_reap_events(ctx);
9201 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9202 ret |= io_poll_remove_all(ctx, task, cancel_all);
9203 ret |= io_kill_timeouts(ctx, task, cancel_all);
9205 ret |= io_run_task_work();
9212 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9214 struct io_uring_task *tctx = current->io_uring;
9215 struct io_tctx_node *node;
9218 if (unlikely(!tctx)) {
9219 ret = io_uring_alloc_task_context(current, ctx);
9223 tctx = current->io_uring;
9224 if (ctx->iowq_limits_set) {
9225 unsigned int limits[2] = { ctx->iowq_limits[0],
9226 ctx->iowq_limits[1], };
9228 ret = io_wq_max_workers(tctx->io_wq, limits);
9233 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9234 node = kmalloc(sizeof(*node), GFP_KERNEL);
9238 node->task = current;
9240 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9247 mutex_lock(&ctx->uring_lock);
9248 list_add(&node->ctx_node, &ctx->tctx_list);
9249 mutex_unlock(&ctx->uring_lock);
9256 * Note that this task has used io_uring. We use it for cancelation purposes.
9258 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9260 struct io_uring_task *tctx = current->io_uring;
9262 if (likely(tctx && tctx->last == ctx))
9264 return __io_uring_add_tctx_node(ctx);
9268 * Remove this io_uring_file -> task mapping.
9270 static __cold void io_uring_del_tctx_node(unsigned long index)
9272 struct io_uring_task *tctx = current->io_uring;
9273 struct io_tctx_node *node;
9277 node = xa_erase(&tctx->xa, index);
9281 WARN_ON_ONCE(current != node->task);
9282 WARN_ON_ONCE(list_empty(&node->ctx_node));
9284 mutex_lock(&node->ctx->uring_lock);
9285 list_del(&node->ctx_node);
9286 mutex_unlock(&node->ctx->uring_lock);
9288 if (tctx->last == node->ctx)
9293 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
9295 struct io_wq *wq = tctx->io_wq;
9296 struct io_tctx_node *node;
9297 unsigned long index;
9299 xa_for_each(&tctx->xa, index, node) {
9300 io_uring_del_tctx_node(index);
9305 * Must be after io_uring_del_tctx_node() (removes nodes under
9306 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9308 io_wq_put_and_exit(wq);
9313 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9316 return atomic_read(&tctx->inflight_tracked);
9317 return percpu_counter_sum(&tctx->inflight);
9321 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9322 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9324 static __cold void io_uring_cancel_generic(bool cancel_all,
9325 struct io_sq_data *sqd)
9327 struct io_uring_task *tctx = current->io_uring;
9328 struct io_ring_ctx *ctx;
9332 WARN_ON_ONCE(sqd && sqd->thread != current);
9334 if (!current->io_uring)
9337 io_wq_exit_start(tctx->io_wq);
9339 atomic_inc(&tctx->in_idle);
9341 io_uring_drop_tctx_refs(current);
9342 /* read completions before cancelations */
9343 inflight = tctx_inflight(tctx, !cancel_all);
9348 struct io_tctx_node *node;
9349 unsigned long index;
9351 xa_for_each(&tctx->xa, index, node) {
9352 /* sqpoll task will cancel all its requests */
9353 if (node->ctx->sq_data)
9355 io_uring_try_cancel_requests(node->ctx, current,
9359 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9360 io_uring_try_cancel_requests(ctx, current,
9364 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9366 io_uring_drop_tctx_refs(current);
9369 * If we've seen completions, retry without waiting. This
9370 * avoids a race where a completion comes in before we did
9371 * prepare_to_wait().
9373 if (inflight == tctx_inflight(tctx, !cancel_all))
9375 finish_wait(&tctx->wait, &wait);
9378 io_uring_clean_tctx(tctx);
9381 * We shouldn't run task_works after cancel, so just leave
9382 * ->in_idle set for normal exit.
9384 atomic_dec(&tctx->in_idle);
9385 /* for exec all current's requests should be gone, kill tctx */
9386 __io_uring_free(current);
9390 void __io_uring_cancel(bool cancel_all)
9392 io_uring_cancel_generic(cancel_all, NULL);
9395 void io_uring_unreg_ringfd(void)
9397 struct io_uring_task *tctx = current->io_uring;
9400 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
9401 if (tctx->registered_rings[i]) {
9402 fput(tctx->registered_rings[i]);
9403 tctx->registered_rings[i] = NULL;
9408 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
9414 for (offset = start; offset < end; offset++) {
9415 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
9416 if (tctx->registered_rings[offset])
9422 } else if (file->f_op != &io_uring_fops) {
9426 tctx->registered_rings[offset] = file;
9434 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
9435 * invocation. User passes in an array of struct io_uring_rsrc_update
9436 * with ->data set to the ring_fd, and ->offset given for the desired
9437 * index. If no index is desired, application may set ->offset == -1U
9438 * and we'll find an available index. Returns number of entries
9439 * successfully processed, or < 0 on error if none were processed.
9441 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
9444 struct io_uring_rsrc_update __user *arg = __arg;
9445 struct io_uring_rsrc_update reg;
9446 struct io_uring_task *tctx;
9449 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
9452 mutex_unlock(&ctx->uring_lock);
9453 ret = io_uring_add_tctx_node(ctx);
9454 mutex_lock(&ctx->uring_lock);
9458 tctx = current->io_uring;
9459 for (i = 0; i < nr_args; i++) {
9462 if (copy_from_user(®, &arg[i], sizeof(reg))) {
9472 if (reg.offset == -1U) {
9474 end = IO_RINGFD_REG_MAX;
9476 if (reg.offset >= IO_RINGFD_REG_MAX) {
9484 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
9489 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
9490 fput(tctx->registered_rings[reg.offset]);
9491 tctx->registered_rings[reg.offset] = NULL;
9500 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
9503 struct io_uring_rsrc_update __user *arg = __arg;
9504 struct io_uring_task *tctx = current->io_uring;
9505 struct io_uring_rsrc_update reg;
9508 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
9513 for (i = 0; i < nr_args; i++) {
9514 if (copy_from_user(®, &arg[i], sizeof(reg))) {
9518 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
9523 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
9524 if (tctx->registered_rings[reg.offset]) {
9525 fput(tctx->registered_rings[reg.offset]);
9526 tctx->registered_rings[reg.offset] = NULL;
9533 static void *io_uring_validate_mmap_request(struct file *file,
9534 loff_t pgoff, size_t sz)
9536 struct io_ring_ctx *ctx = file->private_data;
9537 loff_t offset = pgoff << PAGE_SHIFT;
9542 case IORING_OFF_SQ_RING:
9543 case IORING_OFF_CQ_RING:
9546 case IORING_OFF_SQES:
9550 return ERR_PTR(-EINVAL);
9553 page = virt_to_head_page(ptr);
9554 if (sz > page_size(page))
9555 return ERR_PTR(-EINVAL);
9562 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9564 size_t sz = vma->vm_end - vma->vm_start;
9568 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9570 return PTR_ERR(ptr);
9572 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9573 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9576 #else /* !CONFIG_MMU */
9578 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9580 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9583 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9585 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9588 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9589 unsigned long addr, unsigned long len,
9590 unsigned long pgoff, unsigned long flags)
9594 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9596 return PTR_ERR(ptr);
9598 return (unsigned long) ptr;
9601 #endif /* !CONFIG_MMU */
9603 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9608 if (!io_sqring_full(ctx))
9610 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9612 if (!io_sqring_full(ctx))
9615 } while (!signal_pending(current));
9617 finish_wait(&ctx->sqo_sq_wait, &wait);
9621 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
9623 if (flags & IORING_ENTER_EXT_ARG) {
9624 struct io_uring_getevents_arg arg;
9626 if (argsz != sizeof(arg))
9628 if (copy_from_user(&arg, argp, sizeof(arg)))
9634 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9635 struct __kernel_timespec __user **ts,
9636 const sigset_t __user **sig)
9638 struct io_uring_getevents_arg arg;
9641 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9642 * is just a pointer to the sigset_t.
9644 if (!(flags & IORING_ENTER_EXT_ARG)) {
9645 *sig = (const sigset_t __user *) argp;
9651 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9652 * timespec and sigset_t pointers if good.
9654 if (*argsz != sizeof(arg))
9656 if (copy_from_user(&arg, argp, sizeof(arg)))
9660 *sig = u64_to_user_ptr(arg.sigmask);
9661 *argsz = arg.sigmask_sz;
9662 *ts = u64_to_user_ptr(arg.ts);
9666 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9667 u32, min_complete, u32, flags, const void __user *, argp,
9670 struct io_ring_ctx *ctx;
9676 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9677 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
9678 IORING_ENTER_REGISTERED_RING)))
9682 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
9683 * need only dereference our task private array to find it.
9685 if (flags & IORING_ENTER_REGISTERED_RING) {
9686 struct io_uring_task *tctx = current->io_uring;
9688 if (!tctx || fd >= IO_RINGFD_REG_MAX)
9690 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
9691 f.file = tctx->registered_rings[fd];
9697 if (unlikely(!f.file))
9701 if (unlikely(f.file->f_op != &io_uring_fops))
9705 ctx = f.file->private_data;
9706 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9710 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9714 * For SQ polling, the thread will do all submissions and completions.
9715 * Just return the requested submit count, and wake the thread if
9719 if (ctx->flags & IORING_SETUP_SQPOLL) {
9720 io_cqring_overflow_flush(ctx);
9722 if (unlikely(ctx->sq_data->thread == NULL)) {
9726 if (flags & IORING_ENTER_SQ_WAKEUP)
9727 wake_up(&ctx->sq_data->wait);
9728 if (flags & IORING_ENTER_SQ_WAIT) {
9729 ret = io_sqpoll_wait_sq(ctx);
9734 } else if (to_submit) {
9735 ret = io_uring_add_tctx_node(ctx);
9739 mutex_lock(&ctx->uring_lock);
9740 ret = io_submit_sqes(ctx, to_submit);
9741 if (ret != to_submit) {
9742 mutex_unlock(&ctx->uring_lock);
9745 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
9747 mutex_unlock(&ctx->uring_lock);
9749 if (flags & IORING_ENTER_GETEVENTS) {
9751 if (ctx->syscall_iopoll) {
9753 * We disallow the app entering submit/complete with
9754 * polling, but we still need to lock the ring to
9755 * prevent racing with polled issue that got punted to
9758 mutex_lock(&ctx->uring_lock);
9760 ret2 = io_validate_ext_arg(flags, argp, argsz);
9761 if (likely(!ret2)) {
9762 min_complete = min(min_complete,
9764 ret2 = io_iopoll_check(ctx, min_complete);
9766 mutex_unlock(&ctx->uring_lock);
9768 const sigset_t __user *sig;
9769 struct __kernel_timespec __user *ts;
9771 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9772 if (likely(!ret2)) {
9773 min_complete = min(min_complete,
9775 ret2 = io_cqring_wait(ctx, min_complete, sig,
9784 * EBADR indicates that one or more CQE were dropped.
9785 * Once the user has been informed we can clear the bit
9786 * as they are obviously ok with those drops.
9788 if (unlikely(ret2 == -EBADR))
9789 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
9795 percpu_ref_put(&ctx->refs);
9801 #ifdef CONFIG_PROC_FS
9802 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
9803 const struct cred *cred)
9805 struct user_namespace *uns = seq_user_ns(m);
9806 struct group_info *gi;
9811 seq_printf(m, "%5d\n", id);
9812 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9813 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9814 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9815 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9816 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9817 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9818 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9819 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9820 seq_puts(m, "\n\tGroups:\t");
9821 gi = cred->group_info;
9822 for (g = 0; g < gi->ngroups; g++) {
9823 seq_put_decimal_ull(m, g ? " " : "",
9824 from_kgid_munged(uns, gi->gid[g]));
9826 seq_puts(m, "\n\tCapEff:\t");
9827 cap = cred->cap_effective;
9828 CAP_FOR_EACH_U32(__capi)
9829 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9834 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
9837 struct io_sq_data *sq = NULL;
9838 struct io_overflow_cqe *ocqe;
9839 struct io_rings *r = ctx->rings;
9840 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
9841 unsigned int sq_head = READ_ONCE(r->sq.head);
9842 unsigned int sq_tail = READ_ONCE(r->sq.tail);
9843 unsigned int cq_head = READ_ONCE(r->cq.head);
9844 unsigned int cq_tail = READ_ONCE(r->cq.tail);
9845 unsigned int cq_shift = 0;
9846 unsigned int sq_entries, cq_entries;
9848 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
9855 * we may get imprecise sqe and cqe info if uring is actively running
9856 * since we get cached_sq_head and cached_cq_tail without uring_lock
9857 * and sq_tail and cq_head are changed by userspace. But it's ok since
9858 * we usually use these info when it is stuck.
9860 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
9861 seq_printf(m, "SqHead:\t%u\n", sq_head);
9862 seq_printf(m, "SqTail:\t%u\n", sq_tail);
9863 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
9864 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
9865 seq_printf(m, "CqHead:\t%u\n", cq_head);
9866 seq_printf(m, "CqTail:\t%u\n", cq_tail);
9867 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
9868 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
9869 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
9870 for (i = 0; i < sq_entries; i++) {
9871 unsigned int entry = i + sq_head;
9872 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
9873 struct io_uring_sqe *sqe;
9875 if (sq_idx > sq_mask)
9877 sqe = &ctx->sq_sqes[sq_idx];
9878 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
9879 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
9882 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
9883 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
9884 for (i = 0; i < cq_entries; i++) {
9885 unsigned int entry = i + cq_head;
9886 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
9889 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
9890 entry & cq_mask, cqe->user_data, cqe->res,
9893 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
9894 "extra1:%llu, extra2:%llu\n",
9895 entry & cq_mask, cqe->user_data, cqe->res,
9896 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
9901 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9902 * since fdinfo case grabs it in the opposite direction of normal use
9903 * cases. If we fail to get the lock, we just don't iterate any
9904 * structures that could be going away outside the io_uring mutex.
9906 has_lock = mutex_trylock(&ctx->uring_lock);
9908 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9914 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9915 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9916 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9917 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9918 struct file *f = io_file_from_index(ctx, i);
9921 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9923 seq_printf(m, "%5u: <none>\n", i);
9925 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9926 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9927 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9928 unsigned int len = buf->ubuf_end - buf->ubuf;
9930 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9932 if (has_lock && !xa_empty(&ctx->personalities)) {
9933 unsigned long index;
9934 const struct cred *cred;
9936 seq_printf(m, "Personalities:\n");
9937 xa_for_each(&ctx->personalities, index, cred)
9938 io_uring_show_cred(m, index, cred);
9941 mutex_unlock(&ctx->uring_lock);
9943 seq_puts(m, "PollList:\n");
9944 spin_lock(&ctx->completion_lock);
9945 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9946 struct hlist_head *list = &ctx->cancel_hash[i];
9947 struct io_kiocb *req;
9949 hlist_for_each_entry(req, list, hash_node)
9950 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9951 task_work_pending(req->task));
9954 seq_puts(m, "CqOverflowList:\n");
9955 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
9956 struct io_uring_cqe *cqe = &ocqe->cqe;
9958 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
9959 cqe->user_data, cqe->res, cqe->flags);
9963 spin_unlock(&ctx->completion_lock);
9966 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9968 struct io_ring_ctx *ctx = f->private_data;
9970 if (percpu_ref_tryget(&ctx->refs)) {
9971 __io_uring_show_fdinfo(ctx, m);
9972 percpu_ref_put(&ctx->refs);
9977 static const struct file_operations io_uring_fops = {
9978 .release = io_uring_release,
9979 .mmap = io_uring_mmap,
9981 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9982 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9984 .poll = io_uring_poll,
9985 #ifdef CONFIG_PROC_FS
9986 .show_fdinfo = io_uring_show_fdinfo,
9990 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9991 struct io_uring_params *p)
9993 struct io_rings *rings;
9994 size_t size, sq_array_offset;
9996 /* make sure these are sane, as we already accounted them */
9997 ctx->sq_entries = p->sq_entries;
9998 ctx->cq_entries = p->cq_entries;
10000 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
10001 if (size == SIZE_MAX)
10004 rings = io_mem_alloc(size);
10008 ctx->rings = rings;
10009 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10010 rings->sq_ring_mask = p->sq_entries - 1;
10011 rings->cq_ring_mask = p->cq_entries - 1;
10012 rings->sq_ring_entries = p->sq_entries;
10013 rings->cq_ring_entries = p->cq_entries;
10015 if (p->flags & IORING_SETUP_SQE128)
10016 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
10018 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10019 if (size == SIZE_MAX) {
10020 io_mem_free(ctx->rings);
10025 ctx->sq_sqes = io_mem_alloc(size);
10026 if (!ctx->sq_sqes) {
10027 io_mem_free(ctx->rings);
10035 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10039 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10043 ret = io_uring_add_tctx_node(ctx);
10048 fd_install(fd, file);
10053 * Allocate an anonymous fd, this is what constitutes the application
10054 * visible backing of an io_uring instance. The application mmaps this
10055 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10056 * we have to tie this fd to a socket for file garbage collection purposes.
10058 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10061 #if defined(CONFIG_UNIX)
10064 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10067 return ERR_PTR(ret);
10070 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
10071 O_RDWR | O_CLOEXEC, NULL);
10072 #if defined(CONFIG_UNIX)
10073 if (IS_ERR(file)) {
10074 sock_release(ctx->ring_sock);
10075 ctx->ring_sock = NULL;
10077 ctx->ring_sock->file = file;
10083 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
10084 struct io_uring_params __user *params)
10086 struct io_ring_ctx *ctx;
10092 if (entries > IORING_MAX_ENTRIES) {
10093 if (!(p->flags & IORING_SETUP_CLAMP))
10095 entries = IORING_MAX_ENTRIES;
10099 * Use twice as many entries for the CQ ring. It's possible for the
10100 * application to drive a higher depth than the size of the SQ ring,
10101 * since the sqes are only used at submission time. This allows for
10102 * some flexibility in overcommitting a bit. If the application has
10103 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10104 * of CQ ring entries manually.
10106 p->sq_entries = roundup_pow_of_two(entries);
10107 if (p->flags & IORING_SETUP_CQSIZE) {
10109 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10110 * to a power-of-two, if it isn't already. We do NOT impose
10111 * any cq vs sq ring sizing.
10113 if (!p->cq_entries)
10115 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10116 if (!(p->flags & IORING_SETUP_CLAMP))
10118 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10120 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10121 if (p->cq_entries < p->sq_entries)
10124 p->cq_entries = 2 * p->sq_entries;
10127 ctx = io_ring_ctx_alloc(p);
10132 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10133 * space applications don't need to do io completion events
10134 * polling again, they can rely on io_sq_thread to do polling
10135 * work, which can reduce cpu usage and uring_lock contention.
10137 if (ctx->flags & IORING_SETUP_IOPOLL &&
10138 !(ctx->flags & IORING_SETUP_SQPOLL))
10139 ctx->syscall_iopoll = 1;
10141 ctx->compat = in_compat_syscall();
10142 if (!capable(CAP_IPC_LOCK))
10143 ctx->user = get_uid(current_user());
10146 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
10147 * COOP_TASKRUN is set, then IPIs are never needed by the app.
10150 if (ctx->flags & IORING_SETUP_SQPOLL) {
10151 /* IPI related flags don't make sense with SQPOLL */
10152 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
10153 IORING_SETUP_TASKRUN_FLAG))
10155 ctx->notify_method = TWA_SIGNAL_NO_IPI;
10156 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
10157 ctx->notify_method = TWA_SIGNAL_NO_IPI;
10159 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
10161 ctx->notify_method = TWA_SIGNAL;
10165 * This is just grabbed for accounting purposes. When a process exits,
10166 * the mm is exited and dropped before the files, hence we need to hang
10167 * on to this mm purely for the purposes of being able to unaccount
10168 * memory (locked/pinned vm). It's not used for anything else.
10170 mmgrab(current->mm);
10171 ctx->mm_account = current->mm;
10173 ret = io_allocate_scq_urings(ctx, p);
10177 ret = io_sq_offload_create(ctx, p);
10180 /* always set a rsrc node */
10181 ret = io_rsrc_node_switch_start(ctx);
10184 io_rsrc_node_switch(ctx, NULL);
10186 memset(&p->sq_off, 0, sizeof(p->sq_off));
10187 p->sq_off.head = offsetof(struct io_rings, sq.head);
10188 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10189 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10190 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10191 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10192 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10193 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10195 memset(&p->cq_off, 0, sizeof(p->cq_off));
10196 p->cq_off.head = offsetof(struct io_rings, cq.head);
10197 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10198 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10199 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10200 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10201 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10202 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10204 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10205 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10206 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10207 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10208 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10209 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
10210 IORING_FEAT_LINKED_FILE;
10212 if (copy_to_user(params, p, sizeof(*p))) {
10217 file = io_uring_get_file(ctx);
10218 if (IS_ERR(file)) {
10219 ret = PTR_ERR(file);
10224 * Install ring fd as the very last thing, so we don't risk someone
10225 * having closed it before we finish setup
10227 ret = io_uring_install_fd(ctx, file);
10229 /* fput will clean it up */
10234 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10237 io_ring_ctx_wait_and_kill(ctx);
10242 * Sets up an aio uring context, and returns the fd. Applications asks for a
10243 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10244 * params structure passed in.
10246 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10248 struct io_uring_params p;
10251 if (copy_from_user(&p, params, sizeof(p)))
10253 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10258 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10259 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10260 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10261 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
10262 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
10263 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
10266 return io_uring_create(entries, &p, params);
10269 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10270 struct io_uring_params __user *, params)
10272 return io_uring_setup(entries, params);
10275 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
10278 struct io_uring_probe *p;
10282 size = struct_size(p, ops, nr_args);
10283 if (size == SIZE_MAX)
10285 p = kzalloc(size, GFP_KERNEL);
10290 if (copy_from_user(p, arg, size))
10293 if (memchr_inv(p, 0, size))
10296 p->last_op = IORING_OP_LAST - 1;
10297 if (nr_args > IORING_OP_LAST)
10298 nr_args = IORING_OP_LAST;
10300 for (i = 0; i < nr_args; i++) {
10302 if (!io_op_defs[i].not_supported)
10303 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10308 if (copy_to_user(arg, p, size))
10315 static int io_register_personality(struct io_ring_ctx *ctx)
10317 const struct cred *creds;
10321 creds = get_current_cred();
10323 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10324 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10332 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
10333 void __user *arg, unsigned int nr_args)
10335 struct io_uring_restriction *res;
10339 /* Restrictions allowed only if rings started disabled */
10340 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10343 /* We allow only a single restrictions registration */
10344 if (ctx->restrictions.registered)
10347 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10350 size = array_size(nr_args, sizeof(*res));
10351 if (size == SIZE_MAX)
10354 res = memdup_user(arg, size);
10356 return PTR_ERR(res);
10360 for (i = 0; i < nr_args; i++) {
10361 switch (res[i].opcode) {
10362 case IORING_RESTRICTION_REGISTER_OP:
10363 if (res[i].register_op >= IORING_REGISTER_LAST) {
10368 __set_bit(res[i].register_op,
10369 ctx->restrictions.register_op);
10371 case IORING_RESTRICTION_SQE_OP:
10372 if (res[i].sqe_op >= IORING_OP_LAST) {
10377 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10379 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10380 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10382 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10383 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10392 /* Reset all restrictions if an error happened */
10394 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10396 ctx->restrictions.registered = true;
10402 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10404 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10407 if (ctx->restrictions.registered)
10408 ctx->restricted = 1;
10410 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10411 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10412 wake_up(&ctx->sq_data->wait);
10416 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10417 struct io_uring_rsrc_update2 *up,
10423 if (check_add_overflow(up->offset, nr_args, &tmp))
10425 err = io_rsrc_node_switch_start(ctx);
10430 case IORING_RSRC_FILE:
10431 return __io_sqe_files_update(ctx, up, nr_args);
10432 case IORING_RSRC_BUFFER:
10433 return __io_sqe_buffers_update(ctx, up, nr_args);
10438 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10441 struct io_uring_rsrc_update2 up;
10445 memset(&up, 0, sizeof(up));
10446 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10448 if (up.resv || up.resv2)
10450 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10453 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10454 unsigned size, unsigned type)
10456 struct io_uring_rsrc_update2 up;
10458 if (size != sizeof(up))
10460 if (copy_from_user(&up, arg, sizeof(up)))
10462 if (!up.nr || up.resv || up.resv2)
10464 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10467 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10468 unsigned int size, unsigned int type)
10470 struct io_uring_rsrc_register rr;
10472 /* keep it extendible */
10473 if (size != sizeof(rr))
10476 memset(&rr, 0, sizeof(rr));
10477 if (copy_from_user(&rr, arg, size))
10479 if (!rr.nr || rr.resv2)
10481 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
10485 case IORING_RSRC_FILE:
10486 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
10488 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10489 rr.nr, u64_to_user_ptr(rr.tags));
10490 case IORING_RSRC_BUFFER:
10491 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
10493 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10494 rr.nr, u64_to_user_ptr(rr.tags));
10499 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
10500 void __user *arg, unsigned len)
10502 struct io_uring_task *tctx = current->io_uring;
10503 cpumask_var_t new_mask;
10506 if (!tctx || !tctx->io_wq)
10509 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10512 cpumask_clear(new_mask);
10513 if (len > cpumask_size())
10514 len = cpumask_size();
10516 if (in_compat_syscall()) {
10517 ret = compat_get_bitmap(cpumask_bits(new_mask),
10518 (const compat_ulong_t __user *)arg,
10519 len * 8 /* CHAR_BIT */);
10521 ret = copy_from_user(new_mask, arg, len);
10525 free_cpumask_var(new_mask);
10529 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10530 free_cpumask_var(new_mask);
10534 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10536 struct io_uring_task *tctx = current->io_uring;
10538 if (!tctx || !tctx->io_wq)
10541 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10544 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10546 __must_hold(&ctx->uring_lock)
10548 struct io_tctx_node *node;
10549 struct io_uring_task *tctx = NULL;
10550 struct io_sq_data *sqd = NULL;
10551 __u32 new_count[2];
10554 if (copy_from_user(new_count, arg, sizeof(new_count)))
10556 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10557 if (new_count[i] > INT_MAX)
10560 if (ctx->flags & IORING_SETUP_SQPOLL) {
10561 sqd = ctx->sq_data;
10564 * Observe the correct sqd->lock -> ctx->uring_lock
10565 * ordering. Fine to drop uring_lock here, we hold
10566 * a ref to the ctx.
10568 refcount_inc(&sqd->refs);
10569 mutex_unlock(&ctx->uring_lock);
10570 mutex_lock(&sqd->lock);
10571 mutex_lock(&ctx->uring_lock);
10573 tctx = sqd->thread->io_uring;
10576 tctx = current->io_uring;
10579 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10581 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10583 ctx->iowq_limits[i] = new_count[i];
10584 ctx->iowq_limits_set = true;
10586 if (tctx && tctx->io_wq) {
10587 ret = io_wq_max_workers(tctx->io_wq, new_count);
10591 memset(new_count, 0, sizeof(new_count));
10595 mutex_unlock(&sqd->lock);
10596 io_put_sq_data(sqd);
10599 if (copy_to_user(arg, new_count, sizeof(new_count)))
10602 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10606 /* now propagate the restriction to all registered users */
10607 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10608 struct io_uring_task *tctx = node->task->io_uring;
10610 if (WARN_ON_ONCE(!tctx->io_wq))
10613 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10614 new_count[i] = ctx->iowq_limits[i];
10615 /* ignore errors, it always returns zero anyway */
10616 (void)io_wq_max_workers(tctx->io_wq, new_count);
10621 mutex_unlock(&sqd->lock);
10622 io_put_sq_data(sqd);
10627 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
10629 struct io_uring_buf_ring *br;
10630 struct io_uring_buf_reg reg;
10631 struct io_buffer_list *bl, *free_bl = NULL;
10632 struct page **pages;
10635 if (copy_from_user(®, arg, sizeof(reg)))
10638 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
10640 if (!reg.ring_addr)
10642 if (reg.ring_addr & ~PAGE_MASK)
10644 if (!is_power_of_2(reg.ring_entries))
10647 /* cannot disambiguate full vs empty due to head/tail size */
10648 if (reg.ring_entries >= 65536)
10651 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
10652 int ret = io_init_bl_list(ctx);
10657 bl = io_buffer_get_list(ctx, reg.bgid);
10659 /* if mapped buffer ring OR classic exists, don't allow */
10660 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
10663 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
10668 pages = io_pin_pages(reg.ring_addr,
10669 struct_size(br, bufs, reg.ring_entries),
10671 if (IS_ERR(pages)) {
10673 return PTR_ERR(pages);
10676 br = page_address(pages[0]);
10677 bl->buf_pages = pages;
10678 bl->buf_nr_pages = nr_pages;
10679 bl->nr_entries = reg.ring_entries;
10681 bl->mask = reg.ring_entries - 1;
10682 io_buffer_add_list(ctx, bl, reg.bgid);
10686 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
10688 struct io_uring_buf_reg reg;
10689 struct io_buffer_list *bl;
10691 if (copy_from_user(®, arg, sizeof(reg)))
10693 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
10696 bl = io_buffer_get_list(ctx, reg.bgid);
10699 if (!bl->buf_nr_pages)
10702 __io_remove_buffers(ctx, bl, -1U);
10703 if (bl->bgid >= BGID_ARRAY) {
10704 xa_erase(&ctx->io_bl_xa, bl->bgid);
10710 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10711 void __user *arg, unsigned nr_args)
10712 __releases(ctx->uring_lock)
10713 __acquires(ctx->uring_lock)
10718 * We're inside the ring mutex, if the ref is already dying, then
10719 * someone else killed the ctx or is already going through
10720 * io_uring_register().
10722 if (percpu_ref_is_dying(&ctx->refs))
10725 if (ctx->restricted) {
10726 if (opcode >= IORING_REGISTER_LAST)
10728 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10729 if (!test_bit(opcode, ctx->restrictions.register_op))
10734 case IORING_REGISTER_BUFFERS:
10738 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10740 case IORING_UNREGISTER_BUFFERS:
10742 if (arg || nr_args)
10744 ret = io_sqe_buffers_unregister(ctx);
10746 case IORING_REGISTER_FILES:
10750 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10752 case IORING_UNREGISTER_FILES:
10754 if (arg || nr_args)
10756 ret = io_sqe_files_unregister(ctx);
10758 case IORING_REGISTER_FILES_UPDATE:
10759 ret = io_register_files_update(ctx, arg, nr_args);
10761 case IORING_REGISTER_EVENTFD:
10765 ret = io_eventfd_register(ctx, arg, 0);
10767 case IORING_REGISTER_EVENTFD_ASYNC:
10771 ret = io_eventfd_register(ctx, arg, 1);
10773 case IORING_UNREGISTER_EVENTFD:
10775 if (arg || nr_args)
10777 ret = io_eventfd_unregister(ctx);
10779 case IORING_REGISTER_PROBE:
10781 if (!arg || nr_args > 256)
10783 ret = io_probe(ctx, arg, nr_args);
10785 case IORING_REGISTER_PERSONALITY:
10787 if (arg || nr_args)
10789 ret = io_register_personality(ctx);
10791 case IORING_UNREGISTER_PERSONALITY:
10795 ret = io_unregister_personality(ctx, nr_args);
10797 case IORING_REGISTER_ENABLE_RINGS:
10799 if (arg || nr_args)
10801 ret = io_register_enable_rings(ctx);
10803 case IORING_REGISTER_RESTRICTIONS:
10804 ret = io_register_restrictions(ctx, arg, nr_args);
10806 case IORING_REGISTER_FILES2:
10807 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10809 case IORING_REGISTER_FILES_UPDATE2:
10810 ret = io_register_rsrc_update(ctx, arg, nr_args,
10813 case IORING_REGISTER_BUFFERS2:
10814 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10816 case IORING_REGISTER_BUFFERS_UPDATE:
10817 ret = io_register_rsrc_update(ctx, arg, nr_args,
10818 IORING_RSRC_BUFFER);
10820 case IORING_REGISTER_IOWQ_AFF:
10822 if (!arg || !nr_args)
10824 ret = io_register_iowq_aff(ctx, arg, nr_args);
10826 case IORING_UNREGISTER_IOWQ_AFF:
10828 if (arg || nr_args)
10830 ret = io_unregister_iowq_aff(ctx);
10832 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10834 if (!arg || nr_args != 2)
10836 ret = io_register_iowq_max_workers(ctx, arg);
10838 case IORING_REGISTER_RING_FDS:
10839 ret = io_ringfd_register(ctx, arg, nr_args);
10841 case IORING_UNREGISTER_RING_FDS:
10842 ret = io_ringfd_unregister(ctx, arg, nr_args);
10844 case IORING_REGISTER_PBUF_RING:
10846 if (!arg || nr_args != 1)
10848 ret = io_register_pbuf_ring(ctx, arg);
10850 case IORING_UNREGISTER_PBUF_RING:
10852 if (!arg || nr_args != 1)
10854 ret = io_unregister_pbuf_ring(ctx, arg);
10864 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10865 void __user *, arg, unsigned int, nr_args)
10867 struct io_ring_ctx *ctx;
10876 if (f.file->f_op != &io_uring_fops)
10879 ctx = f.file->private_data;
10881 io_run_task_work();
10883 mutex_lock(&ctx->uring_lock);
10884 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10885 mutex_unlock(&ctx->uring_lock);
10886 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
10892 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
10898 static const struct io_op_def io_op_defs[] = {
10899 [IORING_OP_NOP] = {
10902 .prep = io_nop_prep,
10905 [IORING_OP_READV] = {
10907 .unbound_nonreg_file = 1,
10909 .buffer_select = 1,
10914 .async_size = sizeof(struct io_async_rw),
10915 .prep = io_prep_rw,
10917 .prep_async = io_readv_prep_async,
10918 .cleanup = io_readv_writev_cleanup,
10920 [IORING_OP_WRITEV] = {
10922 .hash_reg_file = 1,
10923 .unbound_nonreg_file = 1,
10929 .async_size = sizeof(struct io_async_rw),
10930 .prep = io_prep_rw,
10932 .prep_async = io_writev_prep_async,
10933 .cleanup = io_readv_writev_cleanup,
10935 [IORING_OP_FSYNC] = {
10938 .prep = io_fsync_prep,
10941 [IORING_OP_READ_FIXED] = {
10943 .unbound_nonreg_file = 1,
10949 .async_size = sizeof(struct io_async_rw),
10950 .prep = io_prep_rw,
10953 [IORING_OP_WRITE_FIXED] = {
10955 .hash_reg_file = 1,
10956 .unbound_nonreg_file = 1,
10962 .async_size = sizeof(struct io_async_rw),
10963 .prep = io_prep_rw,
10966 [IORING_OP_POLL_ADD] = {
10968 .unbound_nonreg_file = 1,
10970 .prep = io_poll_add_prep,
10971 .issue = io_poll_add,
10973 [IORING_OP_POLL_REMOVE] = {
10975 .prep = io_poll_remove_prep,
10976 .issue = io_poll_remove,
10978 [IORING_OP_SYNC_FILE_RANGE] = {
10981 .prep = io_sfr_prep,
10982 .issue = io_sync_file_range,
10984 [IORING_OP_SENDMSG] = {
10986 .unbound_nonreg_file = 1,
10989 .async_size = sizeof(struct io_async_msghdr),
10990 .prep = io_sendmsg_prep,
10991 .issue = io_sendmsg,
10992 .prep_async = io_sendmsg_prep_async,
10993 #if defined(CONFIG_NET)
10994 .cleanup = io_sendmsg_recvmsg_cleanup,
10997 [IORING_OP_RECVMSG] = {
10999 .unbound_nonreg_file = 1,
11001 .buffer_select = 1,
11003 .async_size = sizeof(struct io_async_msghdr),
11004 .prep = io_recvmsg_prep,
11005 .issue = io_recvmsg,
11006 .prep_async = io_recvmsg_prep_async,
11007 #if defined(CONFIG_NET)
11008 .cleanup = io_sendmsg_recvmsg_cleanup,
11011 [IORING_OP_TIMEOUT] = {
11013 .async_size = sizeof(struct io_timeout_data),
11014 .prep = io_timeout_prep,
11015 .issue = io_timeout,
11017 [IORING_OP_TIMEOUT_REMOVE] = {
11018 /* used by timeout updates' prep() */
11020 .prep = io_timeout_remove_prep,
11021 .issue = io_timeout_remove,
11023 [IORING_OP_ACCEPT] = {
11025 .unbound_nonreg_file = 1,
11027 .poll_exclusive = 1,
11028 .ioprio = 1, /* used for flags */
11029 .prep = io_accept_prep,
11030 .issue = io_accept,
11032 [IORING_OP_ASYNC_CANCEL] = {
11034 .prep = io_async_cancel_prep,
11035 .issue = io_async_cancel,
11037 [IORING_OP_LINK_TIMEOUT] = {
11039 .async_size = sizeof(struct io_timeout_data),
11040 .prep = io_link_timeout_prep,
11041 .issue = io_no_issue,
11043 [IORING_OP_CONNECT] = {
11045 .unbound_nonreg_file = 1,
11047 .async_size = sizeof(struct io_async_connect),
11048 .prep = io_connect_prep,
11049 .issue = io_connect,
11050 .prep_async = io_connect_prep_async,
11052 [IORING_OP_FALLOCATE] = {
11054 .prep = io_fallocate_prep,
11055 .issue = io_fallocate,
11057 [IORING_OP_OPENAT] = {
11058 .prep = io_openat_prep,
11059 .issue = io_openat,
11060 .cleanup = io_open_cleanup,
11062 [IORING_OP_CLOSE] = {
11063 .prep = io_close_prep,
11066 [IORING_OP_FILES_UPDATE] = {
11069 .prep = io_files_update_prep,
11070 .issue = io_files_update,
11072 [IORING_OP_STATX] = {
11074 .prep = io_statx_prep,
11076 .cleanup = io_statx_cleanup,
11078 [IORING_OP_READ] = {
11080 .unbound_nonreg_file = 1,
11082 .buffer_select = 1,
11087 .async_size = sizeof(struct io_async_rw),
11088 .prep = io_prep_rw,
11091 [IORING_OP_WRITE] = {
11093 .hash_reg_file = 1,
11094 .unbound_nonreg_file = 1,
11100 .async_size = sizeof(struct io_async_rw),
11101 .prep = io_prep_rw,
11104 [IORING_OP_FADVISE] = {
11107 .prep = io_fadvise_prep,
11108 .issue = io_fadvise,
11110 [IORING_OP_MADVISE] = {
11111 .prep = io_madvise_prep,
11112 .issue = io_madvise,
11114 [IORING_OP_SEND] = {
11116 .unbound_nonreg_file = 1,
11120 .prep = io_sendmsg_prep,
11123 [IORING_OP_RECV] = {
11125 .unbound_nonreg_file = 1,
11127 .buffer_select = 1,
11130 .prep = io_recvmsg_prep,
11133 [IORING_OP_OPENAT2] = {
11134 .prep = io_openat2_prep,
11135 .issue = io_openat2,
11136 .cleanup = io_open_cleanup,
11138 [IORING_OP_EPOLL_CTL] = {
11139 .unbound_nonreg_file = 1,
11141 #if defined(CONFIG_EPOLL)
11142 .prep = io_epoll_ctl_prep,
11143 .issue = io_epoll_ctl,
11145 .prep = io_eopnotsupp_prep,
11148 [IORING_OP_SPLICE] = {
11150 .hash_reg_file = 1,
11151 .unbound_nonreg_file = 1,
11153 .prep = io_splice_prep,
11154 .issue = io_splice,
11156 [IORING_OP_PROVIDE_BUFFERS] = {
11159 .prep = io_provide_buffers_prep,
11160 .issue = io_provide_buffers,
11162 [IORING_OP_REMOVE_BUFFERS] = {
11165 .prep = io_remove_buffers_prep,
11166 .issue = io_remove_buffers,
11168 [IORING_OP_TEE] = {
11170 .hash_reg_file = 1,
11171 .unbound_nonreg_file = 1,
11173 .prep = io_tee_prep,
11176 [IORING_OP_SHUTDOWN] = {
11178 .prep = io_shutdown_prep,
11179 .issue = io_shutdown,
11181 [IORING_OP_RENAMEAT] = {
11182 .prep = io_renameat_prep,
11183 .issue = io_renameat,
11184 .cleanup = io_renameat_cleanup,
11186 [IORING_OP_UNLINKAT] = {
11187 .prep = io_unlinkat_prep,
11188 .issue = io_unlinkat,
11189 .cleanup = io_unlinkat_cleanup,
11191 [IORING_OP_MKDIRAT] = {
11192 .prep = io_mkdirat_prep,
11193 .issue = io_mkdirat,
11194 .cleanup = io_mkdirat_cleanup,
11196 [IORING_OP_SYMLINKAT] = {
11197 .prep = io_symlinkat_prep,
11198 .issue = io_symlinkat,
11199 .cleanup = io_link_cleanup,
11201 [IORING_OP_LINKAT] = {
11202 .prep = io_linkat_prep,
11203 .issue = io_linkat,
11204 .cleanup = io_link_cleanup,
11206 [IORING_OP_MSG_RING] = {
11209 .prep = io_msg_ring_prep,
11210 .issue = io_msg_ring,
11212 [IORING_OP_FSETXATTR] = {
11214 .prep = io_fsetxattr_prep,
11215 .issue = io_fsetxattr,
11216 .cleanup = io_xattr_cleanup,
11218 [IORING_OP_SETXATTR] = {
11219 .prep = io_setxattr_prep,
11220 .issue = io_setxattr,
11221 .cleanup = io_xattr_cleanup,
11223 [IORING_OP_FGETXATTR] = {
11225 .prep = io_fgetxattr_prep,
11226 .issue = io_fgetxattr,
11227 .cleanup = io_xattr_cleanup,
11229 [IORING_OP_GETXATTR] = {
11230 .prep = io_getxattr_prep,
11231 .issue = io_getxattr,
11232 .cleanup = io_xattr_cleanup,
11234 [IORING_OP_SOCKET] = {
11236 .prep = io_socket_prep,
11237 .issue = io_socket,
11239 [IORING_OP_URING_CMD] = {
11242 .async_size = uring_cmd_pdu_size(1),
11243 .prep = io_uring_cmd_prep,
11244 .issue = io_uring_cmd,
11245 .prep_async = io_uring_cmd_prep_async,
11249 static int __init io_uring_init(void)
11253 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11254 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11255 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11258 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11259 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11260 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11261 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11262 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11263 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11264 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11265 BUILD_BUG_SQE_ELEM(8, __u64, off);
11266 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11267 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11268 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11269 BUILD_BUG_SQE_ELEM(24, __u32, len);
11270 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11271 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11272 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11273 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11274 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11275 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11276 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11277 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11278 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11279 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11280 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11281 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11282 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11283 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11284 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11285 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11286 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11287 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11288 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11289 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11290 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11291 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
11293 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11294 sizeof(struct io_uring_rsrc_update));
11295 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11296 sizeof(struct io_uring_rsrc_update2));
11298 /* ->buf_index is u16 */
11299 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11300 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
11301 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
11302 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
11303 offsetof(struct io_uring_buf_ring, tail));
11305 /* should fit into one byte */
11306 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11307 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11308 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11310 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11311 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11313 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
11315 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
11316 BUG_ON(!io_op_defs[i].prep);
11317 if (io_op_defs[i].prep != io_eopnotsupp_prep)
11318 BUG_ON(!io_op_defs[i].issue);
11321 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11325 __initcall(io_uring_init);