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"
102 #define IORING_MAX_ENTRIES 32768
103 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
104 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
106 /* only define max */
107 #define IORING_MAX_FIXED_FILES (1U << 20)
108 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
109 IORING_REGISTER_LAST + IORING_OP_LAST)
111 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
112 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
113 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
115 #define IORING_MAX_REG_BUFFERS (1U << 14)
117 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
118 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
120 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
121 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
123 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
124 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
127 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
130 #define IO_APOLL_MULTI_POLLED (REQ_F_APOLL_MULTISHOT | REQ_F_POLLED)
132 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
134 struct io_mapped_ubuf {
137 unsigned int nr_bvecs;
138 unsigned long acct_pages;
139 struct bio_vec bvec[];
144 struct io_overflow_cqe {
145 struct list_head list;
146 struct io_uring_cqe cqe;
150 * FFS_SCM is only available on 64-bit archs, for 32-bit we just define it as 0
151 * and define IO_URING_SCM_ALL. For this case, we use SCM for all files as we
152 * can't safely always dereference the file when the task has exited and ring
153 * cleanup is done. If a file is tracked and part of SCM, then unix gc on
154 * process exit may reap it before __io_sqe_files_unregister() is run.
156 #define FFS_NOWAIT 0x1UL
157 #define FFS_ISREG 0x2UL
158 #if defined(CONFIG_64BIT)
159 #define FFS_SCM 0x4UL
161 #define IO_URING_SCM_ALL
162 #define FFS_SCM 0x0UL
164 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG|FFS_SCM)
166 struct io_fixed_file {
167 /* file * with additional FFS_* flags */
168 unsigned long file_ptr;
172 struct list_head list;
177 struct io_mapped_ubuf *buf;
181 struct io_rsrc_node {
182 struct percpu_ref refs;
183 struct list_head node;
184 struct list_head rsrc_list;
185 struct io_rsrc_data *rsrc_data;
186 struct llist_node llist;
190 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
192 struct io_rsrc_data {
193 struct io_ring_ctx *ctx;
199 struct completion done;
203 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
204 struct io_buffer_list {
206 * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
207 * then these are classic provided buffers and ->buf_list is used.
210 struct list_head buf_list;
212 struct page **buf_pages;
213 struct io_uring_buf_ring *buf_ring;
218 /* below is for ring provided buffers */
226 struct list_head list;
234 IO_SQ_THREAD_SHOULD_STOP = 0,
235 IO_SQ_THREAD_SHOULD_PARK,
240 atomic_t park_pending;
243 /* ctx's that are using this sqd */
244 struct list_head ctx_list;
246 struct task_struct *thread;
247 struct wait_queue_head wait;
249 unsigned sq_thread_idle;
255 struct completion exited;
258 #define IO_COMPL_BATCH 32
259 #define IO_REQ_CACHE_SIZE 32
260 #define IO_REQ_ALLOC_BATCH 8
262 #define BGID_ARRAY 64
265 * Arbitrary limit, can be raised if need be
267 #define IO_RINGFD_REG_MAX 16
269 struct io_uring_task {
270 /* submission side */
273 struct wait_queue_head wait;
274 const struct io_ring_ctx *last;
276 struct percpu_counter inflight;
277 atomic_t inflight_tracked;
280 spinlock_t task_lock;
281 struct io_wq_work_list task_list;
282 struct io_wq_work_list prio_task_list;
283 struct callback_head task_work;
284 struct file **registered_rings;
289 * First field must be the file pointer in all the
290 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
294 struct wait_queue_head *head;
296 struct wait_queue_entry wait;
299 struct io_poll_update {
305 bool update_user_data;
314 struct io_timeout_data {
315 struct io_kiocb *req;
316 struct hrtimer timer;
317 struct timespec64 ts;
318 enum hrtimer_mode mode;
324 struct sockaddr __user *addr;
325 int __user *addr_len;
328 unsigned long nofile;
338 unsigned long nofile;
352 struct list_head list;
353 /* head of the link, used by linked timeouts only */
354 struct io_kiocb *head;
355 /* for linked completions */
356 struct io_kiocb *prev;
359 struct io_timeout_rem {
364 struct timespec64 ts;
370 /* NOTE: kiocb has the file as the first member, so don't do it here */
379 struct sockaddr __user *addr;
386 struct compat_msghdr __user *umsg_compat;
387 struct user_msghdr __user *umsg;
400 struct filename *filename;
402 unsigned long nofile;
405 struct io_rsrc_update {
417 struct epoll_event event;
420 struct io_provide_buf {
434 struct filename *filename;
435 struct statx __user *buffer;
449 struct io_async_connect {
450 struct sockaddr_storage address;
453 struct io_async_msghdr {
454 struct iovec fast_iov[UIO_FASTIOV];
455 /* points to an allocated iov, if NULL we use fast_iov instead */
456 struct iovec *free_iov;
457 struct sockaddr __user *uaddr;
459 struct sockaddr_storage addr;
463 struct iov_iter iter;
464 struct iov_iter_state iter_state;
465 struct iovec fast_iov[UIO_FASTIOV];
469 struct io_rw_state s;
470 const struct iovec *free_iovec;
472 struct wait_page_queue wpq;
477 struct io_poll *double_poll;
481 IORING_RSRC_FILE = 0,
482 IORING_RSRC_BUFFER = 1,
486 IO_CHECK_CQ_OVERFLOW_BIT,
487 IO_CHECK_CQ_DROPPED_BIT,
490 struct io_tctx_node {
491 struct list_head ctx_node;
492 struct task_struct *task;
493 struct io_ring_ctx *ctx;
496 struct io_defer_entry {
497 struct list_head list;
498 struct io_kiocb *req;
502 struct io_cancel_data {
503 struct io_ring_ctx *ctx;
513 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
514 * the following sqe if SQE128 is used.
516 #define uring_cmd_pdu_size(is_sqe128) \
517 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
518 offsetof(struct io_uring_sqe, cmd))
521 /* needs req->file assigned */
522 unsigned needs_file : 1;
523 /* should block plug */
525 /* hash wq insertion if file is a regular file */
526 unsigned hash_reg_file : 1;
527 /* unbound wq insertion if file is a non-regular file */
528 unsigned unbound_nonreg_file : 1;
529 /* set if opcode supports polled "wait" */
531 unsigned pollout : 1;
532 unsigned poll_exclusive : 1;
533 /* op supports buffer selection */
534 unsigned buffer_select : 1;
535 /* opcode is not supported by this kernel */
536 unsigned not_supported : 1;
538 unsigned audit_skip : 1;
539 /* supports ioprio */
541 /* supports iopoll */
543 /* size of async data needed, if any */
544 unsigned short async_size;
546 int (*prep)(struct io_kiocb *, const struct io_uring_sqe *);
547 int (*issue)(struct io_kiocb *, unsigned int);
548 int (*prep_async)(struct io_kiocb *);
549 void (*cleanup)(struct io_kiocb *);
552 static const struct io_op_def io_op_defs[];
554 /* requests with any of those set should undergo io_disarm_next() */
555 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
556 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
558 static bool io_disarm_next(struct io_kiocb *req);
559 static void io_uring_del_tctx_node(unsigned long index);
560 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
561 struct task_struct *task,
563 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
565 static void io_dismantle_req(struct io_kiocb *req);
566 static void io_queue_linked_timeout(struct io_kiocb *req);
567 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
568 struct io_uring_rsrc_update2 *up,
570 static void io_clean_op(struct io_kiocb *req);
571 static void io_queue_sqe(struct io_kiocb *req);
572 static void io_rsrc_put_work(struct work_struct *work);
574 static void io_req_task_queue(struct io_kiocb *req);
575 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
576 static int io_req_prep_async(struct io_kiocb *req);
578 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
579 unsigned int issue_flags, u32 slot_index);
580 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
581 unsigned int offset);
582 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
584 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
585 static void io_eventfd_signal(struct io_ring_ctx *ctx);
586 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
588 static struct kmem_cache *req_cachep;
590 static const struct file_operations io_uring_fops;
592 const char *io_uring_get_opcode(u8 opcode)
594 switch ((enum io_uring_op)opcode) {
597 case IORING_OP_READV:
599 case IORING_OP_WRITEV:
601 case IORING_OP_FSYNC:
603 case IORING_OP_READ_FIXED:
605 case IORING_OP_WRITE_FIXED:
606 return "WRITE_FIXED";
607 case IORING_OP_POLL_ADD:
609 case IORING_OP_POLL_REMOVE:
610 return "POLL_REMOVE";
611 case IORING_OP_SYNC_FILE_RANGE:
612 return "SYNC_FILE_RANGE";
613 case IORING_OP_SENDMSG:
615 case IORING_OP_RECVMSG:
617 case IORING_OP_TIMEOUT:
619 case IORING_OP_TIMEOUT_REMOVE:
620 return "TIMEOUT_REMOVE";
621 case IORING_OP_ACCEPT:
623 case IORING_OP_ASYNC_CANCEL:
624 return "ASYNC_CANCEL";
625 case IORING_OP_LINK_TIMEOUT:
626 return "LINK_TIMEOUT";
627 case IORING_OP_CONNECT:
629 case IORING_OP_FALLOCATE:
631 case IORING_OP_OPENAT:
633 case IORING_OP_CLOSE:
635 case IORING_OP_FILES_UPDATE:
636 return "FILES_UPDATE";
637 case IORING_OP_STATX:
641 case IORING_OP_WRITE:
643 case IORING_OP_FADVISE:
645 case IORING_OP_MADVISE:
651 case IORING_OP_OPENAT2:
653 case IORING_OP_EPOLL_CTL:
655 case IORING_OP_SPLICE:
657 case IORING_OP_PROVIDE_BUFFERS:
658 return "PROVIDE_BUFFERS";
659 case IORING_OP_REMOVE_BUFFERS:
660 return "REMOVE_BUFFERS";
663 case IORING_OP_SHUTDOWN:
665 case IORING_OP_RENAMEAT:
667 case IORING_OP_UNLINKAT:
669 case IORING_OP_MKDIRAT:
671 case IORING_OP_SYMLINKAT:
673 case IORING_OP_LINKAT:
675 case IORING_OP_MSG_RING:
677 case IORING_OP_FSETXATTR:
679 case IORING_OP_SETXATTR:
681 case IORING_OP_FGETXATTR:
683 case IORING_OP_GETXATTR:
685 case IORING_OP_SOCKET:
687 case IORING_OP_URING_CMD:
695 struct sock *io_uring_get_socket(struct file *file)
697 #if defined(CONFIG_UNIX)
698 if (file->f_op == &io_uring_fops) {
699 struct io_ring_ctx *ctx = file->private_data;
701 return ctx->ring_sock->sk;
706 EXPORT_SYMBOL(io_uring_get_socket);
708 #if defined(CONFIG_UNIX)
709 static inline bool io_file_need_scm(struct file *filp)
711 #if defined(IO_URING_SCM_ALL)
714 return !!unix_get_socket(filp);
718 static inline bool io_file_need_scm(struct file *filp)
724 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
726 lockdep_assert_held(&ctx->uring_lock);
727 if (issue_flags & IO_URING_F_UNLOCKED)
728 mutex_unlock(&ctx->uring_lock);
731 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
734 * "Normal" inline submissions always hold the uring_lock, since we
735 * grab it from the system call. Same is true for the SQPOLL offload.
736 * The only exception is when we've detached the request and issue it
737 * from an async worker thread, grab the lock for that case.
739 if (issue_flags & IO_URING_F_UNLOCKED)
740 mutex_lock(&ctx->uring_lock);
741 lockdep_assert_held(&ctx->uring_lock);
744 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
747 mutex_lock(&ctx->uring_lock);
752 #define io_for_each_link(pos, head) \
753 for (pos = (head); pos; pos = pos->link)
756 * Shamelessly stolen from the mm implementation of page reference checking,
757 * see commit f958d7b528b1 for details.
759 #define req_ref_zero_or_close_to_overflow(req) \
760 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
762 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
764 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
765 return atomic_inc_not_zero(&req->refs);
768 static inline bool req_ref_put_and_test(struct io_kiocb *req)
770 if (likely(!(req->flags & REQ_F_REFCOUNT)))
773 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
774 return atomic_dec_and_test(&req->refs);
777 static inline void req_ref_get(struct io_kiocb *req)
779 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
780 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
781 atomic_inc(&req->refs);
784 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
786 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
787 __io_submit_flush_completions(ctx);
790 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
792 if (!(req->flags & REQ_F_REFCOUNT)) {
793 req->flags |= REQ_F_REFCOUNT;
794 atomic_set(&req->refs, nr);
798 static inline void io_req_set_refcount(struct io_kiocb *req)
800 __io_req_set_refcount(req, 1);
803 #define IO_RSRC_REF_BATCH 100
805 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
807 percpu_ref_put_many(&node->refs, nr);
810 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
811 struct io_ring_ctx *ctx)
812 __must_hold(&ctx->uring_lock)
814 struct io_rsrc_node *node = req->rsrc_node;
817 if (node == ctx->rsrc_node)
818 ctx->rsrc_cached_refs++;
820 io_rsrc_put_node(node, 1);
824 static inline void io_req_put_rsrc(struct io_kiocb *req)
827 io_rsrc_put_node(req->rsrc_node, 1);
830 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
831 __must_hold(&ctx->uring_lock)
833 if (ctx->rsrc_cached_refs) {
834 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
835 ctx->rsrc_cached_refs = 0;
839 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
840 __must_hold(&ctx->uring_lock)
842 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
843 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
846 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
847 struct io_ring_ctx *ctx,
848 unsigned int issue_flags)
850 if (!req->rsrc_node) {
851 req->rsrc_node = ctx->rsrc_node;
853 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
854 lockdep_assert_held(&ctx->uring_lock);
855 ctx->rsrc_cached_refs--;
856 if (unlikely(ctx->rsrc_cached_refs < 0))
857 io_rsrc_refs_refill(ctx);
859 percpu_ref_get(&req->rsrc_node->refs);
864 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
866 if (req->flags & REQ_F_BUFFER_RING) {
868 req->buf_list->head++;
869 req->flags &= ~REQ_F_BUFFER_RING;
871 list_add(&req->kbuf->list, list);
872 req->flags &= ~REQ_F_BUFFER_SELECTED;
875 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
878 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
880 lockdep_assert_held(&req->ctx->completion_lock);
882 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
884 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
887 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
888 unsigned issue_flags)
892 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
896 * We can add this buffer back to two lists:
898 * 1) The io_buffers_cache list. This one is protected by the
899 * ctx->uring_lock. If we already hold this lock, add back to this
900 * list as we can grab it from issue as well.
901 * 2) The io_buffers_comp list. This one is protected by the
902 * ctx->completion_lock.
904 * We migrate buffers from the comp_list to the issue cache list
907 if (req->flags & REQ_F_BUFFER_RING) {
908 /* no buffers to recycle for this case */
909 cflags = __io_put_kbuf(req, NULL);
910 } else if (issue_flags & IO_URING_F_UNLOCKED) {
911 struct io_ring_ctx *ctx = req->ctx;
913 spin_lock(&ctx->completion_lock);
914 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
915 spin_unlock(&ctx->completion_lock);
917 lockdep_assert_held(&req->ctx->uring_lock);
919 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
925 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
928 if (ctx->io_bl && bgid < BGID_ARRAY)
929 return &ctx->io_bl[bgid];
931 return xa_load(&ctx->io_bl_xa, bgid);
934 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
936 struct io_ring_ctx *ctx = req->ctx;
937 struct io_buffer_list *bl;
938 struct io_buffer *buf;
940 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
943 * For legacy provided buffer mode, don't recycle if we already did
944 * IO to this buffer. For ring-mapped provided buffer mode, we should
945 * increment ring->head to explicitly monopolize the buffer to avoid
948 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
949 (req->flags & REQ_F_PARTIAL_IO))
953 * READV uses fields in `struct io_rw` (len/addr) to stash the selected
954 * buffer data. However if that buffer is recycled the original request
955 * data stored in addr is lost. Therefore forbid recycling for now.
957 if (req->opcode == IORING_OP_READV)
961 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
962 * the flag and hence ensure that bl->head doesn't get incremented.
963 * If the tail has already been incremented, hang on to it.
965 if (req->flags & REQ_F_BUFFER_RING) {
967 if (req->flags & REQ_F_PARTIAL_IO) {
968 req->buf_list->head++;
969 req->buf_list = NULL;
971 req->buf_index = req->buf_list->bgid;
972 req->flags &= ~REQ_F_BUFFER_RING;
978 io_ring_submit_lock(ctx, issue_flags);
981 bl = io_buffer_get_list(ctx, buf->bgid);
982 list_add(&buf->list, &bl->buf_list);
983 req->flags &= ~REQ_F_BUFFER_SELECTED;
984 req->buf_index = buf->bgid;
986 io_ring_submit_unlock(ctx, issue_flags);
989 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
991 __must_hold(&req->ctx->timeout_lock)
993 struct io_kiocb *req;
995 if (task && head->task != task)
1000 io_for_each_link(req, head) {
1001 if (req->flags & REQ_F_INFLIGHT)
1007 static bool io_match_linked(struct io_kiocb *head)
1009 struct io_kiocb *req;
1011 io_for_each_link(req, head) {
1012 if (req->flags & REQ_F_INFLIGHT)
1019 * As io_match_task() but protected against racing with linked timeouts.
1020 * User must not hold timeout_lock.
1022 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1027 if (task && head->task != task)
1032 if (head->flags & REQ_F_LINK_TIMEOUT) {
1033 struct io_ring_ctx *ctx = head->ctx;
1035 /* protect against races with linked timeouts */
1036 spin_lock_irq(&ctx->timeout_lock);
1037 matched = io_match_linked(head);
1038 spin_unlock_irq(&ctx->timeout_lock);
1040 matched = io_match_linked(head);
1045 static inline bool req_has_async_data(struct io_kiocb *req)
1047 return req->flags & REQ_F_ASYNC_DATA;
1050 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1053 io_req_set_res(req, res, 0);
1056 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1058 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1061 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1063 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1065 complete(&ctx->ref_comp);
1068 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1070 struct io_timeout *timeout = io_kiocb_to_cmd(req);
1072 return !timeout->off;
1075 static __cold void io_fallback_req_func(struct work_struct *work)
1077 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1078 fallback_work.work);
1079 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1080 struct io_kiocb *req, *tmp;
1081 bool locked = false;
1083 percpu_ref_get(&ctx->refs);
1084 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1085 req->io_task_work.func(req, &locked);
1088 io_submit_flush_completions(ctx);
1089 mutex_unlock(&ctx->uring_lock);
1091 percpu_ref_put(&ctx->refs);
1094 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1096 struct io_ring_ctx *ctx;
1099 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1103 xa_init(&ctx->io_bl_xa);
1106 * Use 5 bits less than the max cq entries, that should give us around
1107 * 32 entries per hash list if totally full and uniformly spread.
1109 hash_bits = ilog2(p->cq_entries);
1113 ctx->cancel_hash_bits = hash_bits;
1114 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1116 if (!ctx->cancel_hash)
1118 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1120 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1121 if (!ctx->dummy_ubuf)
1123 /* set invalid range, so io_import_fixed() fails meeting it */
1124 ctx->dummy_ubuf->ubuf = -1UL;
1126 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1127 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1130 ctx->flags = p->flags;
1131 init_waitqueue_head(&ctx->sqo_sq_wait);
1132 INIT_LIST_HEAD(&ctx->sqd_list);
1133 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1134 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1135 INIT_LIST_HEAD(&ctx->apoll_cache);
1136 init_completion(&ctx->ref_comp);
1137 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1138 mutex_init(&ctx->uring_lock);
1139 init_waitqueue_head(&ctx->cq_wait);
1140 spin_lock_init(&ctx->completion_lock);
1141 spin_lock_init(&ctx->timeout_lock);
1142 INIT_WQ_LIST(&ctx->iopoll_list);
1143 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1144 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1145 INIT_LIST_HEAD(&ctx->defer_list);
1146 INIT_LIST_HEAD(&ctx->timeout_list);
1147 INIT_LIST_HEAD(&ctx->ltimeout_list);
1148 spin_lock_init(&ctx->rsrc_ref_lock);
1149 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1150 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1151 init_llist_head(&ctx->rsrc_put_llist);
1152 INIT_LIST_HEAD(&ctx->tctx_list);
1153 ctx->submit_state.free_list.next = NULL;
1154 INIT_WQ_LIST(&ctx->locked_free_list);
1155 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1156 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1159 kfree(ctx->dummy_ubuf);
1160 kfree(ctx->cancel_hash);
1162 xa_destroy(&ctx->io_bl_xa);
1167 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1169 struct io_rings *r = ctx->rings;
1171 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1175 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1177 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1178 struct io_ring_ctx *ctx = req->ctx;
1180 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1186 static inline bool io_req_ffs_set(struct io_kiocb *req)
1188 return req->flags & REQ_F_FIXED_FILE;
1191 static inline void io_req_track_inflight(struct io_kiocb *req)
1193 if (!(req->flags & REQ_F_INFLIGHT)) {
1194 req->flags |= REQ_F_INFLIGHT;
1195 atomic_inc(&req->task->io_uring->inflight_tracked);
1199 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1201 if (WARN_ON_ONCE(!req->link))
1204 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1205 req->flags |= REQ_F_LINK_TIMEOUT;
1207 /* linked timeouts should have two refs once prep'ed */
1208 io_req_set_refcount(req);
1209 __io_req_set_refcount(req->link, 2);
1213 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1215 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1217 return __io_prep_linked_timeout(req);
1220 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1222 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1225 static inline void io_arm_ltimeout(struct io_kiocb *req)
1227 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1228 __io_arm_ltimeout(req);
1231 static void io_prep_async_work(struct io_kiocb *req)
1233 const struct io_op_def *def = &io_op_defs[req->opcode];
1234 struct io_ring_ctx *ctx = req->ctx;
1236 if (!(req->flags & REQ_F_CREDS)) {
1237 req->flags |= REQ_F_CREDS;
1238 req->creds = get_current_cred();
1241 req->work.list.next = NULL;
1242 req->work.flags = 0;
1243 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1244 if (req->flags & REQ_F_FORCE_ASYNC)
1245 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1247 if (req->flags & REQ_F_ISREG) {
1248 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1249 io_wq_hash_work(&req->work, file_inode(req->file));
1250 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1251 if (def->unbound_nonreg_file)
1252 req->work.flags |= IO_WQ_WORK_UNBOUND;
1256 static void io_prep_async_link(struct io_kiocb *req)
1258 struct io_kiocb *cur;
1260 if (req->flags & REQ_F_LINK_TIMEOUT) {
1261 struct io_ring_ctx *ctx = req->ctx;
1263 spin_lock_irq(&ctx->timeout_lock);
1264 io_for_each_link(cur, req)
1265 io_prep_async_work(cur);
1266 spin_unlock_irq(&ctx->timeout_lock);
1268 io_for_each_link(cur, req)
1269 io_prep_async_work(cur);
1273 static inline void io_req_add_compl_list(struct io_kiocb *req)
1275 struct io_submit_state *state = &req->ctx->submit_state;
1277 if (!(req->flags & REQ_F_CQE_SKIP))
1278 state->flush_cqes = true;
1279 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1282 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1284 struct io_kiocb *link = io_prep_linked_timeout(req);
1285 struct io_uring_task *tctx = req->task->io_uring;
1288 BUG_ON(!tctx->io_wq);
1290 /* init ->work of the whole link before punting */
1291 io_prep_async_link(req);
1294 * Not expected to happen, but if we do have a bug where this _can_
1295 * happen, catch it here and ensure the request is marked as
1296 * canceled. That will make io-wq go through the usual work cancel
1297 * procedure rather than attempt to run this request (or create a new
1300 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1301 req->work.flags |= IO_WQ_WORK_CANCEL;
1303 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1304 req->opcode, req->flags, &req->work,
1305 io_wq_is_hashed(&req->work));
1306 io_wq_enqueue(tctx->io_wq, &req->work);
1308 io_queue_linked_timeout(link);
1311 static void io_kill_timeout(struct io_kiocb *req, int status)
1312 __must_hold(&req->ctx->completion_lock)
1313 __must_hold(&req->ctx->timeout_lock)
1315 struct io_timeout_data *io = req->async_data;
1317 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1318 struct io_timeout *timeout = io_kiocb_to_cmd(req);
1322 atomic_set(&req->ctx->cq_timeouts,
1323 atomic_read(&req->ctx->cq_timeouts) + 1);
1324 list_del_init(&timeout->list);
1325 io_req_tw_post_queue(req, status, 0);
1329 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1331 while (!list_empty(&ctx->defer_list)) {
1332 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1333 struct io_defer_entry, list);
1335 if (req_need_defer(de->req, de->seq))
1337 list_del_init(&de->list);
1338 io_req_task_queue(de->req);
1343 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1344 __must_hold(&ctx->completion_lock)
1346 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1347 struct io_timeout *timeout, *tmp;
1349 spin_lock_irq(&ctx->timeout_lock);
1350 list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
1351 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
1352 u32 events_needed, events_got;
1354 if (io_is_timeout_noseq(req))
1358 * Since seq can easily wrap around over time, subtract
1359 * the last seq at which timeouts were flushed before comparing.
1360 * Assuming not more than 2^31-1 events have happened since,
1361 * these subtractions won't have wrapped, so we can check if
1362 * target is in [last_seq, current_seq] by comparing the two.
1364 events_needed = timeout->target_seq - ctx->cq_last_tm_flush;
1365 events_got = seq - ctx->cq_last_tm_flush;
1366 if (events_got < events_needed)
1369 io_kill_timeout(req, 0);
1371 ctx->cq_last_tm_flush = seq;
1372 spin_unlock_irq(&ctx->timeout_lock);
1375 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1377 /* order cqe stores with ring update */
1378 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1381 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1383 if (ctx->off_timeout_used || ctx->drain_active) {
1384 spin_lock(&ctx->completion_lock);
1385 if (ctx->off_timeout_used)
1386 io_flush_timeouts(ctx);
1387 if (ctx->drain_active)
1388 io_queue_deferred(ctx);
1389 io_commit_cqring(ctx);
1390 spin_unlock(&ctx->completion_lock);
1393 io_eventfd_signal(ctx);
1396 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1398 struct io_rings *r = ctx->rings;
1400 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1403 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1405 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1409 * writes to the cq entry need to come after reading head; the
1410 * control dependency is enough as we're using WRITE_ONCE to
1413 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1415 struct io_rings *rings = ctx->rings;
1416 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1417 unsigned int shift = 0;
1418 unsigned int free, queued, len;
1420 if (ctx->flags & IORING_SETUP_CQE32)
1423 /* userspace may cheat modifying the tail, be safe and do min */
1424 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
1425 free = ctx->cq_entries - queued;
1426 /* we need a contiguous range, limit based on the current array offset */
1427 len = min(free, ctx->cq_entries - off);
1431 ctx->cached_cq_tail++;
1432 ctx->cqe_cached = &rings->cqes[off];
1433 ctx->cqe_sentinel = ctx->cqe_cached + len;
1435 return &rings->cqes[off << shift];
1438 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1440 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
1441 struct io_uring_cqe *cqe = ctx->cqe_cached;
1443 if (ctx->flags & IORING_SETUP_CQE32) {
1444 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
1449 ctx->cached_cq_tail++;
1454 return __io_get_cqe(ctx);
1457 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1459 struct io_ev_fd *ev_fd;
1463 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1464 * and eventfd_signal
1466 ev_fd = rcu_dereference(ctx->io_ev_fd);
1469 * Check again if ev_fd exists incase an io_eventfd_unregister call
1470 * completed between the NULL check of ctx->io_ev_fd at the start of
1471 * the function and rcu_read_lock.
1473 if (unlikely(!ev_fd))
1475 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1478 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1479 eventfd_signal(ev_fd->cq_ev_fd, 1);
1484 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1487 * wake_up_all() may seem excessive, but io_wake_function() and
1488 * io_should_wake() handle the termination of the loop and only
1489 * wake as many waiters as we need to.
1491 if (wq_has_sleeper(&ctx->cq_wait))
1492 wake_up_all(&ctx->cq_wait);
1496 * This should only get called when at least one event has been posted.
1497 * Some applications rely on the eventfd notification count only changing
1498 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1499 * 1:1 relationship between how many times this function is called (and
1500 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1502 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1504 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1506 __io_commit_cqring_flush(ctx);
1508 io_cqring_wake(ctx);
1511 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1513 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1515 __io_commit_cqring_flush(ctx);
1517 if (ctx->flags & IORING_SETUP_SQPOLL)
1518 io_cqring_wake(ctx);
1521 /* Returns true if there are no backlogged entries after the flush */
1522 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1524 bool all_flushed, posted;
1525 size_t cqe_size = sizeof(struct io_uring_cqe);
1527 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1530 if (ctx->flags & IORING_SETUP_CQE32)
1534 spin_lock(&ctx->completion_lock);
1535 while (!list_empty(&ctx->cq_overflow_list)) {
1536 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1537 struct io_overflow_cqe *ocqe;
1541 ocqe = list_first_entry(&ctx->cq_overflow_list,
1542 struct io_overflow_cqe, list);
1544 memcpy(cqe, &ocqe->cqe, cqe_size);
1546 io_account_cq_overflow(ctx);
1549 list_del(&ocqe->list);
1553 all_flushed = list_empty(&ctx->cq_overflow_list);
1555 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1556 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1559 io_commit_cqring(ctx);
1560 spin_unlock(&ctx->completion_lock);
1562 io_cqring_ev_posted(ctx);
1566 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1570 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
1571 /* iopoll syncs against uring_lock, not completion_lock */
1572 if (ctx->flags & IORING_SETUP_IOPOLL)
1573 mutex_lock(&ctx->uring_lock);
1574 ret = __io_cqring_overflow_flush(ctx, false);
1575 if (ctx->flags & IORING_SETUP_IOPOLL)
1576 mutex_unlock(&ctx->uring_lock);
1582 static void __io_put_task(struct task_struct *task, int nr)
1584 struct io_uring_task *tctx = task->io_uring;
1586 percpu_counter_sub(&tctx->inflight, nr);
1587 if (unlikely(atomic_read(&tctx->in_idle)))
1588 wake_up(&tctx->wait);
1589 put_task_struct_many(task, nr);
1592 /* must to be called somewhat shortly after putting a request */
1593 static inline void io_put_task(struct task_struct *task, int nr)
1595 if (likely(task == current))
1596 task->io_uring->cached_refs += nr;
1598 __io_put_task(task, nr);
1601 static void io_task_refs_refill(struct io_uring_task *tctx)
1603 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1605 percpu_counter_add(&tctx->inflight, refill);
1606 refcount_add(refill, ¤t->usage);
1607 tctx->cached_refs += refill;
1610 static inline void io_get_task_refs(int nr)
1612 struct io_uring_task *tctx = current->io_uring;
1614 tctx->cached_refs -= nr;
1615 if (unlikely(tctx->cached_refs < 0))
1616 io_task_refs_refill(tctx);
1619 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1621 struct io_uring_task *tctx = task->io_uring;
1622 unsigned int refs = tctx->cached_refs;
1625 tctx->cached_refs = 0;
1626 percpu_counter_sub(&tctx->inflight, refs);
1627 put_task_struct_many(task, refs);
1631 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1632 s32 res, u32 cflags, u64 extra1,
1635 struct io_overflow_cqe *ocqe;
1636 size_t ocq_size = sizeof(struct io_overflow_cqe);
1637 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
1640 ocq_size += sizeof(struct io_uring_cqe);
1642 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
1643 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
1646 * If we're in ring overflow flush mode, or in task cancel mode,
1647 * or cannot allocate an overflow entry, then we need to drop it
1650 io_account_cq_overflow(ctx);
1651 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
1654 if (list_empty(&ctx->cq_overflow_list)) {
1655 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1656 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1659 ocqe->cqe.user_data = user_data;
1660 ocqe->cqe.res = res;
1661 ocqe->cqe.flags = cflags;
1663 ocqe->cqe.big_cqe[0] = extra1;
1664 ocqe->cqe.big_cqe[1] = extra2;
1666 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1670 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
1671 struct io_kiocb *req)
1673 struct io_uring_cqe *cqe;
1675 if (!(ctx->flags & IORING_SETUP_CQE32)) {
1676 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1677 req->cqe.res, req->cqe.flags, 0, 0);
1680 * If we can't get a cq entry, userspace overflowed the
1681 * submission (by quite a lot). Increment the overflow count in
1684 cqe = io_get_cqe(ctx);
1686 memcpy(cqe, &req->cqe, sizeof(*cqe));
1690 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1691 req->cqe.res, req->cqe.flags,
1694 u64 extra1 = 0, extra2 = 0;
1696 if (req->flags & REQ_F_CQE32_INIT) {
1697 extra1 = req->extra1;
1698 extra2 = req->extra2;
1701 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1702 req->cqe.res, req->cqe.flags, extra1, extra2);
1705 * If we can't get a cq entry, userspace overflowed the
1706 * submission (by quite a lot). Increment the overflow count in
1709 cqe = io_get_cqe(ctx);
1711 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
1712 WRITE_ONCE(cqe->big_cqe[0], extra1);
1713 WRITE_ONCE(cqe->big_cqe[1], extra2);
1717 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1718 req->cqe.res, req->cqe.flags,
1723 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1724 s32 res, u32 cflags)
1726 struct io_uring_cqe *cqe;
1729 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
1732 * If we can't get a cq entry, userspace overflowed the
1733 * submission (by quite a lot). Increment the overflow count in
1736 cqe = io_get_cqe(ctx);
1738 WRITE_ONCE(cqe->user_data, user_data);
1739 WRITE_ONCE(cqe->res, res);
1740 WRITE_ONCE(cqe->flags, cflags);
1742 if (ctx->flags & IORING_SETUP_CQE32) {
1743 WRITE_ONCE(cqe->big_cqe[0], 0);
1744 WRITE_ONCE(cqe->big_cqe[1], 0);
1748 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
1751 static void __io_req_complete_put(struct io_kiocb *req)
1754 * If we're the last reference to this request, add to our locked
1757 if (req_ref_put_and_test(req)) {
1758 struct io_ring_ctx *ctx = req->ctx;
1760 if (req->flags & IO_REQ_LINK_FLAGS) {
1761 if (req->flags & IO_DISARM_MASK)
1762 io_disarm_next(req);
1764 io_req_task_queue(req->link);
1768 io_req_put_rsrc(req);
1770 * Selected buffer deallocation in io_clean_op() assumes that
1771 * we don't hold ->completion_lock. Clean them here to avoid
1774 io_put_kbuf_comp(req);
1775 io_dismantle_req(req);
1776 io_put_task(req->task, 1);
1777 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1778 ctx->locked_free_nr++;
1782 static void __io_req_complete_post(struct io_kiocb *req)
1784 if (!(req->flags & REQ_F_CQE_SKIP))
1785 __io_fill_cqe_req(req->ctx, req);
1786 __io_req_complete_put(req);
1789 static void io_req_complete_post(struct io_kiocb *req)
1791 struct io_ring_ctx *ctx = req->ctx;
1793 spin_lock(&ctx->completion_lock);
1794 __io_req_complete_post(req);
1795 io_commit_cqring(ctx);
1796 spin_unlock(&ctx->completion_lock);
1797 io_cqring_ev_posted(ctx);
1800 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
1802 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1803 req->flags |= REQ_F_COMPLETE_INLINE;
1805 io_req_complete_post(req);
1808 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1811 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1812 io_req_complete_post(req);
1816 * Don't initialise the fields below on every allocation, but do that in
1817 * advance and keep them valid across allocations.
1819 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1823 req->async_data = NULL;
1824 /* not necessary, but safer to zero */
1828 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1829 struct io_submit_state *state)
1831 spin_lock(&ctx->completion_lock);
1832 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1833 ctx->locked_free_nr = 0;
1834 spin_unlock(&ctx->completion_lock);
1837 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
1839 return !ctx->submit_state.free_list.next;
1843 * A request might get retired back into the request caches even before opcode
1844 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1845 * Because of that, io_alloc_req() should be called only under ->uring_lock
1846 * and with extra caution to not get a request that is still worked on.
1848 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1849 __must_hold(&ctx->uring_lock)
1851 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1852 void *reqs[IO_REQ_ALLOC_BATCH];
1856 * If we have more than a batch's worth of requests in our IRQ side
1857 * locked cache, grab the lock and move them over to our submission
1860 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1861 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1862 if (!io_req_cache_empty(ctx))
1866 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1869 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1870 * retry single alloc to be on the safe side.
1872 if (unlikely(ret <= 0)) {
1873 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1879 percpu_ref_get_many(&ctx->refs, ret);
1880 for (i = 0; i < ret; i++) {
1881 struct io_kiocb *req = reqs[i];
1883 io_preinit_req(req, ctx);
1884 io_req_add_to_cache(req, ctx);
1889 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
1891 if (unlikely(io_req_cache_empty(ctx)))
1892 return __io_alloc_req_refill(ctx);
1896 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1898 struct io_wq_work_node *node;
1900 node = wq_stack_extract(&ctx->submit_state.free_list);
1901 return container_of(node, struct io_kiocb, comp_list);
1904 static inline void io_dismantle_req(struct io_kiocb *req)
1906 unsigned int flags = req->flags;
1908 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
1910 if (!(flags & REQ_F_FIXED_FILE))
1911 io_put_file(req->file);
1914 static __cold void io_free_req(struct io_kiocb *req)
1916 struct io_ring_ctx *ctx = req->ctx;
1918 io_req_put_rsrc(req);
1919 io_dismantle_req(req);
1920 io_put_task(req->task, 1);
1922 spin_lock(&ctx->completion_lock);
1923 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1924 ctx->locked_free_nr++;
1925 spin_unlock(&ctx->completion_lock);
1928 static inline void io_remove_next_linked(struct io_kiocb *req)
1930 struct io_kiocb *nxt = req->link;
1932 req->link = nxt->link;
1936 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
1937 __must_hold(&req->ctx->completion_lock)
1938 __must_hold(&req->ctx->timeout_lock)
1940 struct io_kiocb *link = req->link;
1942 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1943 struct io_timeout_data *io = link->async_data;
1944 struct io_timeout *timeout = io_kiocb_to_cmd(link);
1946 io_remove_next_linked(req);
1947 timeout->head = NULL;
1948 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1949 list_del(&timeout->list);
1956 static void io_fail_links(struct io_kiocb *req)
1957 __must_hold(&req->ctx->completion_lock)
1959 struct io_kiocb *nxt, *link = req->link;
1960 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
1964 long res = -ECANCELED;
1966 if (link->flags & REQ_F_FAIL)
1967 res = link->cqe.res;
1972 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
1976 link->flags |= REQ_F_CQE_SKIP;
1978 link->flags &= ~REQ_F_CQE_SKIP;
1979 io_req_set_res(link, res, 0);
1980 __io_req_complete_post(link);
1985 static bool io_disarm_next(struct io_kiocb *req)
1986 __must_hold(&req->ctx->completion_lock)
1988 struct io_kiocb *link = NULL;
1989 bool posted = false;
1991 if (req->flags & REQ_F_ARM_LTIMEOUT) {
1993 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1994 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1995 io_remove_next_linked(req);
1996 io_req_tw_post_queue(link, -ECANCELED, 0);
1999 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2000 struct io_ring_ctx *ctx = req->ctx;
2002 spin_lock_irq(&ctx->timeout_lock);
2003 link = io_disarm_linked_timeout(req);
2004 spin_unlock_irq(&ctx->timeout_lock);
2007 io_req_tw_post_queue(link, -ECANCELED, 0);
2010 if (unlikely((req->flags & REQ_F_FAIL) &&
2011 !(req->flags & REQ_F_HARDLINK))) {
2012 posted |= (req->link != NULL);
2018 static void __io_req_find_next_prep(struct io_kiocb *req)
2020 struct io_ring_ctx *ctx = req->ctx;
2023 spin_lock(&ctx->completion_lock);
2024 posted = io_disarm_next(req);
2025 io_commit_cqring(ctx);
2026 spin_unlock(&ctx->completion_lock);
2028 io_cqring_ev_posted(ctx);
2031 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2033 struct io_kiocb *nxt;
2036 * If LINK is set, we have dependent requests in this chain. If we
2037 * didn't fail this request, queue the first one up, moving any other
2038 * dependencies to the next request. In case of failure, fail the rest
2041 if (unlikely(req->flags & IO_DISARM_MASK))
2042 __io_req_find_next_prep(req);
2048 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2052 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2053 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2055 io_submit_flush_completions(ctx);
2056 mutex_unlock(&ctx->uring_lock);
2059 percpu_ref_put(&ctx->refs);
2062 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2064 io_commit_cqring(ctx);
2065 spin_unlock(&ctx->completion_lock);
2066 io_cqring_ev_posted(ctx);
2069 static void handle_prev_tw_list(struct io_wq_work_node *node,
2070 struct io_ring_ctx **ctx, bool *uring_locked)
2072 if (*ctx && !*uring_locked)
2073 spin_lock(&(*ctx)->completion_lock);
2076 struct io_wq_work_node *next = node->next;
2077 struct io_kiocb *req = container_of(node, struct io_kiocb,
2080 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2082 if (req->ctx != *ctx) {
2083 if (unlikely(!*uring_locked && *ctx))
2084 ctx_commit_and_unlock(*ctx);
2086 ctx_flush_and_put(*ctx, uring_locked);
2088 /* if not contended, grab and improve batching */
2089 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2090 percpu_ref_get(&(*ctx)->refs);
2091 if (unlikely(!*uring_locked))
2092 spin_lock(&(*ctx)->completion_lock);
2094 if (likely(*uring_locked)) {
2095 req->io_task_work.func(req, uring_locked);
2097 req->cqe.flags = io_put_kbuf_comp(req);
2098 __io_req_complete_post(req);
2103 if (unlikely(!*uring_locked))
2104 ctx_commit_and_unlock(*ctx);
2107 static void handle_tw_list(struct io_wq_work_node *node,
2108 struct io_ring_ctx **ctx, bool *locked)
2111 struct io_wq_work_node *next = node->next;
2112 struct io_kiocb *req = container_of(node, struct io_kiocb,
2115 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2117 if (req->ctx != *ctx) {
2118 ctx_flush_and_put(*ctx, locked);
2120 /* if not contended, grab and improve batching */
2121 *locked = mutex_trylock(&(*ctx)->uring_lock);
2122 percpu_ref_get(&(*ctx)->refs);
2124 req->io_task_work.func(req, locked);
2129 static void tctx_task_work(struct callback_head *cb)
2131 bool uring_locked = false;
2132 struct io_ring_ctx *ctx = NULL;
2133 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2137 struct io_wq_work_node *node1, *node2;
2139 spin_lock_irq(&tctx->task_lock);
2140 node1 = tctx->prio_task_list.first;
2141 node2 = tctx->task_list.first;
2142 INIT_WQ_LIST(&tctx->task_list);
2143 INIT_WQ_LIST(&tctx->prio_task_list);
2144 if (!node2 && !node1)
2145 tctx->task_running = false;
2146 spin_unlock_irq(&tctx->task_lock);
2147 if (!node2 && !node1)
2151 handle_prev_tw_list(node1, &ctx, &uring_locked);
2153 handle_tw_list(node2, &ctx, &uring_locked);
2156 if (data_race(!tctx->task_list.first) &&
2157 data_race(!tctx->prio_task_list.first) && uring_locked)
2158 io_submit_flush_completions(ctx);
2161 ctx_flush_and_put(ctx, &uring_locked);
2163 /* relaxed read is enough as only the task itself sets ->in_idle */
2164 if (unlikely(atomic_read(&tctx->in_idle)))
2165 io_uring_drop_tctx_refs(current);
2168 static void __io_req_task_work_add(struct io_kiocb *req,
2169 struct io_uring_task *tctx,
2170 struct io_wq_work_list *list)
2172 struct io_ring_ctx *ctx = req->ctx;
2173 struct io_wq_work_node *node;
2174 unsigned long flags;
2177 spin_lock_irqsave(&tctx->task_lock, flags);
2178 wq_list_add_tail(&req->io_task_work.node, list);
2179 running = tctx->task_running;
2181 tctx->task_running = true;
2182 spin_unlock_irqrestore(&tctx->task_lock, flags);
2184 /* task_work already pending, we're done */
2188 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2189 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2191 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2194 spin_lock_irqsave(&tctx->task_lock, flags);
2195 tctx->task_running = false;
2196 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2197 spin_unlock_irqrestore(&tctx->task_lock, flags);
2200 req = container_of(node, struct io_kiocb, io_task_work.node);
2202 if (llist_add(&req->io_task_work.fallback_node,
2203 &req->ctx->fallback_llist))
2204 schedule_delayed_work(&req->ctx->fallback_work, 1);
2208 static void io_req_task_work_add(struct io_kiocb *req)
2210 struct io_uring_task *tctx = req->task->io_uring;
2212 __io_req_task_work_add(req, tctx, &tctx->task_list);
2215 static void io_req_task_prio_work_add(struct io_kiocb *req)
2217 struct io_uring_task *tctx = req->task->io_uring;
2219 if (req->ctx->flags & IORING_SETUP_SQPOLL)
2220 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
2222 __io_req_task_work_add(req, tctx, &tctx->task_list);
2225 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2227 io_req_complete_post(req);
2230 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2232 io_req_set_res(req, res, cflags);
2233 req->io_task_work.func = io_req_tw_post;
2234 io_req_task_work_add(req);
2237 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2239 /* not needed for normal modes, but SQPOLL depends on it */
2240 io_tw_lock(req->ctx, locked);
2241 io_req_complete_failed(req, req->cqe.res);
2244 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2246 io_tw_lock(req->ctx, locked);
2247 /* req->task == current here, checking PF_EXITING is safe */
2248 if (likely(!(req->task->flags & PF_EXITING)))
2251 io_req_complete_failed(req, -EFAULT);
2254 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2256 io_req_set_res(req, ret, 0);
2257 req->io_task_work.func = io_req_task_cancel;
2258 io_req_task_work_add(req);
2261 static void io_req_task_queue(struct io_kiocb *req)
2263 req->io_task_work.func = io_req_task_submit;
2264 io_req_task_work_add(req);
2267 static void io_req_task_queue_reissue(struct io_kiocb *req)
2269 req->io_task_work.func = io_queue_iowq;
2270 io_req_task_work_add(req);
2273 static void io_queue_next(struct io_kiocb *req)
2275 struct io_kiocb *nxt = io_req_find_next(req);
2278 io_req_task_queue(nxt);
2281 static void io_free_batch_list(struct io_ring_ctx *ctx,
2282 struct io_wq_work_node *node)
2283 __must_hold(&ctx->uring_lock)
2285 struct task_struct *task = NULL;
2289 struct io_kiocb *req = container_of(node, struct io_kiocb,
2292 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2293 if (req->flags & REQ_F_REFCOUNT) {
2294 node = req->comp_list.next;
2295 if (!req_ref_put_and_test(req))
2298 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2299 struct async_poll *apoll = req->apoll;
2301 if (apoll->double_poll)
2302 kfree(apoll->double_poll);
2303 list_add(&apoll->poll.wait.entry,
2305 req->flags &= ~REQ_F_POLLED;
2307 if (req->flags & IO_REQ_LINK_FLAGS)
2309 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2312 if (!(req->flags & REQ_F_FIXED_FILE))
2313 io_put_file(req->file);
2315 io_req_put_rsrc_locked(req, ctx);
2317 if (req->task != task) {
2319 io_put_task(task, task_refs);
2324 node = req->comp_list.next;
2325 io_req_add_to_cache(req, ctx);
2329 io_put_task(task, task_refs);
2332 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2333 __must_hold(&ctx->uring_lock)
2335 struct io_wq_work_node *node, *prev;
2336 struct io_submit_state *state = &ctx->submit_state;
2338 if (state->flush_cqes) {
2339 spin_lock(&ctx->completion_lock);
2340 wq_list_for_each(node, prev, &state->compl_reqs) {
2341 struct io_kiocb *req = container_of(node, struct io_kiocb,
2344 if (!(req->flags & REQ_F_CQE_SKIP))
2345 __io_fill_cqe_req(ctx, req);
2348 io_commit_cqring(ctx);
2349 spin_unlock(&ctx->completion_lock);
2350 io_cqring_ev_posted(ctx);
2351 state->flush_cqes = false;
2354 io_free_batch_list(ctx, state->compl_reqs.first);
2355 INIT_WQ_LIST(&state->compl_reqs);
2359 * Drop reference to request, return next in chain (if there is one) if this
2360 * was the last reference to this request.
2362 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2364 struct io_kiocb *nxt = NULL;
2366 if (req_ref_put_and_test(req)) {
2367 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2368 nxt = io_req_find_next(req);
2374 static inline void io_put_req(struct io_kiocb *req)
2376 if (req_ref_put_and_test(req)) {
2382 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2384 /* See comment at the top of this file */
2386 return __io_cqring_events(ctx);
2389 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2391 struct io_rings *rings = ctx->rings;
2393 /* make sure SQ entry isn't read before tail */
2394 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2397 static inline bool io_run_task_work(void)
2399 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2400 __set_current_state(TASK_RUNNING);
2401 clear_notify_signal();
2402 if (task_work_pending(current))
2410 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2412 struct io_wq_work_node *pos, *start, *prev;
2413 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2414 DEFINE_IO_COMP_BATCH(iob);
2418 * Only spin for completions if we don't have multiple devices hanging
2419 * off our complete list.
2421 if (ctx->poll_multi_queue || force_nonspin)
2422 poll_flags |= BLK_POLL_ONESHOT;
2424 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2425 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2426 struct io_rw *rw = io_kiocb_to_cmd(req);
2430 * Move completed and retryable entries to our local lists.
2431 * If we find a request that requires polling, break out
2432 * and complete those lists first, if we have entries there.
2434 if (READ_ONCE(req->iopoll_completed))
2437 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
2438 if (unlikely(ret < 0))
2441 poll_flags |= BLK_POLL_ONESHOT;
2443 /* iopoll may have completed current req */
2444 if (!rq_list_empty(iob.req_list) ||
2445 READ_ONCE(req->iopoll_completed))
2449 if (!rq_list_empty(iob.req_list))
2455 wq_list_for_each_resume(pos, prev) {
2456 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2458 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2459 if (!smp_load_acquire(&req->iopoll_completed))
2462 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2465 req->cqe.flags = io_put_kbuf(req, 0);
2466 __io_fill_cqe_req(req->ctx, req);
2469 if (unlikely(!nr_events))
2472 io_commit_cqring(ctx);
2473 io_cqring_ev_posted_iopoll(ctx);
2474 pos = start ? start->next : ctx->iopoll_list.first;
2475 wq_list_cut(&ctx->iopoll_list, prev, start);
2476 io_free_batch_list(ctx, pos);
2481 * We can't just wait for polled events to come to us, we have to actively
2482 * find and complete them.
2484 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2486 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2489 mutex_lock(&ctx->uring_lock);
2490 while (!wq_list_empty(&ctx->iopoll_list)) {
2491 /* let it sleep and repeat later if can't complete a request */
2492 if (io_do_iopoll(ctx, true) == 0)
2495 * Ensure we allow local-to-the-cpu processing to take place,
2496 * in this case we need to ensure that we reap all events.
2497 * Also let task_work, etc. to progress by releasing the mutex
2499 if (need_resched()) {
2500 mutex_unlock(&ctx->uring_lock);
2502 mutex_lock(&ctx->uring_lock);
2505 mutex_unlock(&ctx->uring_lock);
2508 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2510 unsigned int nr_events = 0;
2512 unsigned long check_cq;
2515 * Don't enter poll loop if we already have events pending.
2516 * If we do, we can potentially be spinning for commands that
2517 * already triggered a CQE (eg in error).
2519 check_cq = READ_ONCE(ctx->check_cq);
2520 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2521 __io_cqring_overflow_flush(ctx, false);
2522 if (io_cqring_events(ctx))
2526 * Similarly do not spin if we have not informed the user of any
2529 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
2534 * If a submit got punted to a workqueue, we can have the
2535 * application entering polling for a command before it gets
2536 * issued. That app will hold the uring_lock for the duration
2537 * of the poll right here, so we need to take a breather every
2538 * now and then to ensure that the issue has a chance to add
2539 * the poll to the issued list. Otherwise we can spin here
2540 * forever, while the workqueue is stuck trying to acquire the
2543 if (wq_list_empty(&ctx->iopoll_list)) {
2544 u32 tail = ctx->cached_cq_tail;
2546 mutex_unlock(&ctx->uring_lock);
2548 mutex_lock(&ctx->uring_lock);
2550 /* some requests don't go through iopoll_list */
2551 if (tail != ctx->cached_cq_tail ||
2552 wq_list_empty(&ctx->iopoll_list))
2555 ret = io_do_iopoll(ctx, !min);
2560 } while (nr_events < min && !need_resched());
2565 static void kiocb_end_write(struct io_kiocb *req)
2568 * Tell lockdep we inherited freeze protection from submission
2571 if (req->flags & REQ_F_ISREG) {
2572 struct super_block *sb = file_inode(req->file)->i_sb;
2574 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2580 static bool io_resubmit_prep(struct io_kiocb *req)
2582 struct io_async_rw *io = req->async_data;
2584 if (!req_has_async_data(req))
2585 return !io_req_prep_async(req);
2586 iov_iter_restore(&io->s.iter, &io->s.iter_state);
2590 static bool io_rw_should_reissue(struct io_kiocb *req)
2592 umode_t mode = file_inode(req->file)->i_mode;
2593 struct io_ring_ctx *ctx = req->ctx;
2595 if (!S_ISBLK(mode) && !S_ISREG(mode))
2597 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2598 !(ctx->flags & IORING_SETUP_IOPOLL)))
2601 * If ref is dying, we might be running poll reap from the exit work.
2602 * Don't attempt to reissue from that path, just let it fail with
2605 if (percpu_ref_is_dying(&ctx->refs))
2608 * Play it safe and assume not safe to re-import and reissue if we're
2609 * not in the original thread group (or in task context).
2611 if (!same_thread_group(req->task, current) || !in_task())
2616 static bool io_resubmit_prep(struct io_kiocb *req)
2620 static bool io_rw_should_reissue(struct io_kiocb *req)
2626 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2628 struct io_rw *rw = io_kiocb_to_cmd(req);
2630 if (rw->kiocb.ki_flags & IOCB_WRITE) {
2631 kiocb_end_write(req);
2632 fsnotify_modify(req->file);
2634 fsnotify_access(req->file);
2636 if (unlikely(res != req->cqe.res)) {
2637 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2638 io_rw_should_reissue(req)) {
2639 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2648 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2651 req->cqe.flags |= io_put_kbuf(req, 0);
2652 req->flags |= REQ_F_COMPLETE_INLINE;
2653 io_req_add_compl_list(req);
2655 req->cqe.flags |= io_put_kbuf(req, IO_URING_F_UNLOCKED);
2656 io_req_complete_post(req);
2660 static void __io_complete_rw(struct io_kiocb *req, long res,
2661 unsigned int issue_flags)
2663 if (__io_complete_rw_common(req, res))
2665 io_req_set_res(req, req->cqe.res, io_put_kbuf(req, issue_flags));
2666 __io_req_complete(req, issue_flags);
2669 static void io_complete_rw(struct kiocb *kiocb, long res)
2671 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
2672 struct io_kiocb *req = cmd_to_io_kiocb(rw);
2674 if (__io_complete_rw_common(req, res))
2676 io_req_set_res(req, res, 0);
2677 req->io_task_work.func = io_req_task_complete;
2678 io_req_task_prio_work_add(req);
2681 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
2683 struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
2684 struct io_kiocb *req = cmd_to_io_kiocb(rw);
2686 if (kiocb->ki_flags & IOCB_WRITE)
2687 kiocb_end_write(req);
2688 if (unlikely(res != req->cqe.res)) {
2689 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2690 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2696 /* order with io_iopoll_complete() checking ->iopoll_completed */
2697 smp_store_release(&req->iopoll_completed, 1);
2701 * After the iocb has been issued, it's safe to be found on the poll list.
2702 * Adding the kiocb to the list AFTER submission ensures that we don't
2703 * find it from a io_do_iopoll() thread before the issuer is done
2704 * accessing the kiocb cookie.
2706 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2708 struct io_ring_ctx *ctx = req->ctx;
2709 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2711 /* workqueue context doesn't hold uring_lock, grab it now */
2712 if (unlikely(needs_lock))
2713 mutex_lock(&ctx->uring_lock);
2716 * Track whether we have multiple files in our lists. This will impact
2717 * how we do polling eventually, not spinning if we're on potentially
2718 * different devices.
2720 if (wq_list_empty(&ctx->iopoll_list)) {
2721 ctx->poll_multi_queue = false;
2722 } else if (!ctx->poll_multi_queue) {
2723 struct io_kiocb *list_req;
2725 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2727 if (list_req->file != req->file)
2728 ctx->poll_multi_queue = true;
2732 * For fast devices, IO may have already completed. If it has, add
2733 * it to the front so we find it first.
2735 if (READ_ONCE(req->iopoll_completed))
2736 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2738 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2740 if (unlikely(needs_lock)) {
2742 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2743 * in sq thread task context or in io worker task context. If
2744 * current task context is sq thread, we don't need to check
2745 * whether should wake up sq thread.
2747 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2748 wq_has_sleeper(&ctx->sq_data->wait))
2749 wake_up(&ctx->sq_data->wait);
2751 mutex_unlock(&ctx->uring_lock);
2755 static bool io_bdev_nowait(struct block_device *bdev)
2757 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2761 * If we tracked the file through the SCM inflight mechanism, we could support
2762 * any file. For now, just ensure that anything potentially problematic is done
2765 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2767 if (S_ISBLK(mode)) {
2768 if (IS_ENABLED(CONFIG_BLOCK) &&
2769 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2775 if (S_ISREG(mode)) {
2776 if (IS_ENABLED(CONFIG_BLOCK) &&
2777 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2778 file->f_op != &io_uring_fops)
2783 /* any ->read/write should understand O_NONBLOCK */
2784 if (file->f_flags & O_NONBLOCK)
2786 return file->f_mode & FMODE_NOWAIT;
2790 * If we tracked the file through the SCM inflight mechanism, we could support
2791 * any file. For now, just ensure that anything potentially problematic is done
2794 static unsigned int io_file_get_flags(struct file *file)
2796 umode_t mode = file_inode(file)->i_mode;
2797 unsigned int res = 0;
2801 if (__io_file_supports_nowait(file, mode))
2803 if (io_file_need_scm(file))
2808 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2810 return req->flags & REQ_F_SUPPORT_NOWAIT;
2813 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2815 struct io_rw *rw = io_kiocb_to_cmd(req);
2819 rw->kiocb.ki_pos = READ_ONCE(sqe->off);
2820 /* used for fixed read/write too - just read unconditionally */
2821 req->buf_index = READ_ONCE(sqe->buf_index);
2823 if (req->opcode == IORING_OP_READ_FIXED ||
2824 req->opcode == IORING_OP_WRITE_FIXED) {
2825 struct io_ring_ctx *ctx = req->ctx;
2828 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
2830 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
2831 req->imu = ctx->user_bufs[index];
2832 io_req_set_rsrc_node(req, ctx, 0);
2835 ioprio = READ_ONCE(sqe->ioprio);
2837 ret = ioprio_check_cap(ioprio);
2841 rw->kiocb.ki_ioprio = ioprio;
2843 rw->kiocb.ki_ioprio = get_current_ioprio();
2846 rw->addr = READ_ONCE(sqe->addr);
2847 rw->len = READ_ONCE(sqe->len);
2848 rw->flags = READ_ONCE(sqe->rw_flags);
2852 static void io_readv_writev_cleanup(struct io_kiocb *req)
2854 struct io_async_rw *io = req->async_data;
2856 kfree(io->free_iovec);
2859 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2865 case -ERESTARTNOINTR:
2866 case -ERESTARTNOHAND:
2867 case -ERESTART_RESTARTBLOCK:
2869 * We can't just restart the syscall, since previously
2870 * submitted sqes may already be in progress. Just fail this
2876 kiocb->ki_complete(kiocb, ret);
2880 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
2882 struct io_rw *rw = io_kiocb_to_cmd(req);
2884 if (rw->kiocb.ki_pos != -1)
2885 return &rw->kiocb.ki_pos;
2887 if (!(req->file->f_mode & FMODE_STREAM)) {
2888 req->flags |= REQ_F_CUR_POS;
2889 rw->kiocb.ki_pos = req->file->f_pos;
2890 return &rw->kiocb.ki_pos;
2893 rw->kiocb.ki_pos = 0;
2897 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
2898 unsigned int issue_flags)
2900 struct io_async_rw *io = req->async_data;
2901 struct io_rw *rw = io_kiocb_to_cmd(req);
2903 /* add previously done IO, if any */
2904 if (req_has_async_data(req) && io->bytes_done > 0) {
2906 ret = io->bytes_done;
2908 ret += io->bytes_done;
2911 if (req->flags & REQ_F_CUR_POS)
2912 req->file->f_pos = rw->kiocb.ki_pos;
2913 if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
2914 __io_complete_rw(req, ret, issue_flags);
2916 io_rw_done(&rw->kiocb, ret);
2918 if (req->flags & REQ_F_REISSUE) {
2919 req->flags &= ~REQ_F_REISSUE;
2920 if (io_resubmit_prep(req))
2921 io_req_task_queue_reissue(req);
2923 io_req_task_queue_fail(req, ret);
2927 static int __io_import_fixed(struct io_kiocb *req, int ddir,
2928 struct iov_iter *iter, struct io_mapped_ubuf *imu)
2930 struct io_rw *rw = io_kiocb_to_cmd(req);
2931 size_t len = rw->len;
2932 u64 buf_end, buf_addr = rw->addr;
2935 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2937 /* not inside the mapped region */
2938 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2942 * May not be a start of buffer, set size appropriately
2943 * and advance us to the beginning.
2945 offset = buf_addr - imu->ubuf;
2946 iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
2950 * Don't use iov_iter_advance() here, as it's really slow for
2951 * using the latter parts of a big fixed buffer - it iterates
2952 * over each segment manually. We can cheat a bit here, because
2955 * 1) it's a BVEC iter, we set it up
2956 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2957 * first and last bvec
2959 * So just find our index, and adjust the iterator afterwards.
2960 * If the offset is within the first bvec (or the whole first
2961 * bvec, just use iov_iter_advance(). This makes it easier
2962 * since we can just skip the first segment, which may not
2963 * be PAGE_SIZE aligned.
2965 const struct bio_vec *bvec = imu->bvec;
2967 if (offset <= bvec->bv_len) {
2968 iov_iter_advance(iter, offset);
2970 unsigned long seg_skip;
2972 /* skip first vec */
2973 offset -= bvec->bv_len;
2974 seg_skip = 1 + (offset >> PAGE_SHIFT);
2976 iter->bvec = bvec + seg_skip;
2977 iter->nr_segs -= seg_skip;
2978 iter->count -= bvec->bv_len + offset;
2979 iter->iov_offset = offset & ~PAGE_MASK;
2986 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2987 unsigned int issue_flags)
2989 if (WARN_ON_ONCE(!req->imu))
2991 return __io_import_fixed(req, rw, iter, req->imu);
2994 static int io_buffer_add_list(struct io_ring_ctx *ctx,
2995 struct io_buffer_list *bl, unsigned int bgid)
2998 if (bgid < BGID_ARRAY)
3001 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3004 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3005 struct io_buffer_list *bl)
3007 if (!list_empty(&bl->buf_list)) {
3008 struct io_buffer *kbuf;
3010 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3011 list_del(&kbuf->list);
3012 if (*len > kbuf->len)
3014 req->flags |= REQ_F_BUFFER_SELECTED;
3016 req->buf_index = kbuf->bid;
3017 return u64_to_user_ptr(kbuf->addr);
3022 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3023 struct io_buffer_list *bl,
3024 unsigned int issue_flags)
3026 struct io_uring_buf_ring *br = bl->buf_ring;
3027 struct io_uring_buf *buf;
3028 __u16 head = bl->head;
3030 if (unlikely(smp_load_acquire(&br->tail) == head))
3034 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3035 buf = &br->bufs[head];
3037 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3038 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3039 buf = page_address(bl->buf_pages[index]);
3042 if (*len > buf->len)
3044 req->flags |= REQ_F_BUFFER_RING;
3046 req->buf_index = buf->bid;
3048 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3050 * If we came in unlocked, we have no choice but to consume the
3051 * buffer here. This does mean it'll be pinned until the IO
3052 * completes. But coming in unlocked means we're in io-wq
3053 * context, hence there should be no further retry. For the
3054 * locked case, the caller must ensure to call the commit when
3055 * the transfer completes (or if we get -EAGAIN and must poll
3058 req->buf_list = NULL;
3061 return u64_to_user_ptr(buf->addr);
3064 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3065 unsigned int issue_flags)
3067 struct io_ring_ctx *ctx = req->ctx;
3068 struct io_buffer_list *bl;
3069 void __user *ret = NULL;
3071 io_ring_submit_lock(req->ctx, issue_flags);
3073 bl = io_buffer_get_list(ctx, req->buf_index);
3075 if (bl->buf_nr_pages)
3076 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3078 ret = io_provided_buffer_select(req, len, bl);
3080 io_ring_submit_unlock(req->ctx, issue_flags);
3084 #ifdef CONFIG_COMPAT
3085 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3086 unsigned int issue_flags)
3088 struct io_rw *rw = io_kiocb_to_cmd(req);
3089 struct compat_iovec __user *uiov;
3090 compat_ssize_t clen;
3094 uiov = u64_to_user_ptr(rw->addr);
3095 if (!access_ok(uiov, sizeof(*uiov)))
3097 if (__get_user(clen, &uiov->iov_len))
3103 buf = io_buffer_select(req, &len, issue_flags);
3106 rw->addr = (unsigned long) buf;
3107 iov[0].iov_base = buf;
3108 rw->len = iov[0].iov_len = (compat_size_t) len;
3113 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3114 unsigned int issue_flags)
3116 struct io_rw *rw = io_kiocb_to_cmd(req);
3117 struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
3121 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3124 len = iov[0].iov_len;
3127 buf = io_buffer_select(req, &len, issue_flags);
3130 rw->addr = (unsigned long) buf;
3131 iov[0].iov_base = buf;
3132 rw->len = iov[0].iov_len = len;
3136 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3137 unsigned int issue_flags)
3139 struct io_rw *rw = io_kiocb_to_cmd(req);
3141 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3142 iov[0].iov_base = u64_to_user_ptr(rw->addr);
3143 iov[0].iov_len = rw->len;
3149 #ifdef CONFIG_COMPAT
3150 if (req->ctx->compat)
3151 return io_compat_import(req, iov, issue_flags);
3154 return __io_iov_buffer_select(req, iov, issue_flags);
3157 static inline bool io_do_buffer_select(struct io_kiocb *req)
3159 if (!(req->flags & REQ_F_BUFFER_SELECT))
3161 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3164 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
3165 struct io_rw_state *s,
3166 unsigned int issue_flags)
3168 struct io_rw *rw = io_kiocb_to_cmd(req);
3169 struct iov_iter *iter = &s->iter;
3170 u8 opcode = req->opcode;
3171 struct iovec *iovec;
3176 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3177 ret = io_import_fixed(req, ddir, iter, issue_flags);
3179 return ERR_PTR(ret);
3183 buf = u64_to_user_ptr(rw->addr);
3186 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3187 if (io_do_buffer_select(req)) {
3188 buf = io_buffer_select(req, &sqe_len, issue_flags);
3190 return ERR_PTR(-ENOBUFS);
3191 rw->addr = (unsigned long) buf;
3195 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
3197 return ERR_PTR(ret);
3201 iovec = s->fast_iov;
3202 if (req->flags & REQ_F_BUFFER_SELECT) {
3203 ret = io_iov_buffer_select(req, iovec, issue_flags);
3205 return ERR_PTR(ret);
3206 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
3210 ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3212 if (unlikely(ret < 0))
3213 return ERR_PTR(ret);
3217 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3218 struct iovec **iovec, struct io_rw_state *s,
3219 unsigned int issue_flags)
3221 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3222 if (unlikely(IS_ERR(*iovec)))
3223 return PTR_ERR(*iovec);
3225 iov_iter_save_state(&s->iter, &s->iter_state);
3229 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3231 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3235 * For files that don't have ->read_iter() and ->write_iter(), handle them
3236 * by looping over ->read() or ->write() manually.
3238 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
3240 struct kiocb *kiocb = &rw->kiocb;
3241 struct file *file = kiocb->ki_filp;
3246 * Don't support polled IO through this interface, and we can't
3247 * support non-blocking either. For the latter, this just causes
3248 * the kiocb to be handled from an async context.
3250 if (kiocb->ki_flags & IOCB_HIPRI)
3252 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3253 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3256 ppos = io_kiocb_ppos(kiocb);
3258 while (iov_iter_count(iter)) {
3262 if (!iov_iter_is_bvec(iter)) {
3263 iovec = iov_iter_iovec(iter);
3265 iovec.iov_base = u64_to_user_ptr(rw->addr);
3266 iovec.iov_len = rw->len;
3270 nr = file->f_op->read(file, iovec.iov_base,
3271 iovec.iov_len, ppos);
3273 nr = file->f_op->write(file, iovec.iov_base,
3274 iovec.iov_len, ppos);
3283 if (!iov_iter_is_bvec(iter)) {
3284 iov_iter_advance(iter, nr);
3291 if (nr != iovec.iov_len)
3298 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3299 const struct iovec *fast_iov, struct iov_iter *iter)
3301 struct io_async_rw *io = req->async_data;
3303 memcpy(&io->s.iter, iter, sizeof(*iter));
3304 io->free_iovec = iovec;
3306 /* can only be fixed buffers, no need to do anything */
3307 if (iov_iter_is_bvec(iter))
3310 unsigned iov_off = 0;
3312 io->s.iter.iov = io->s.fast_iov;
3313 if (iter->iov != fast_iov) {
3314 iov_off = iter->iov - fast_iov;
3315 io->s.iter.iov += iov_off;
3317 if (io->s.fast_iov != fast_iov)
3318 memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
3319 sizeof(struct iovec) * iter->nr_segs);
3321 req->flags |= REQ_F_NEED_CLEANUP;
3325 static inline bool io_alloc_async_data(struct io_kiocb *req)
3327 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3328 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3329 if (req->async_data) {
3330 req->flags |= REQ_F_ASYNC_DATA;
3336 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3337 struct io_rw_state *s, bool force)
3339 if (!force && !io_op_defs[req->opcode].prep_async)
3341 if (!req_has_async_data(req)) {
3342 struct io_async_rw *iorw;
3344 if (io_alloc_async_data(req)) {
3349 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3350 iorw = req->async_data;
3351 /* we've copied and mapped the iter, ensure state is saved */
3352 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3357 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3359 struct io_async_rw *iorw = req->async_data;
3363 /* submission path, ->uring_lock should already be taken */
3364 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3365 if (unlikely(ret < 0))
3368 iorw->bytes_done = 0;
3369 iorw->free_iovec = iov;
3371 req->flags |= REQ_F_NEED_CLEANUP;
3375 static int io_readv_prep_async(struct io_kiocb *req)
3377 return io_rw_prep_async(req, READ);
3380 static int io_writev_prep_async(struct io_kiocb *req)
3382 return io_rw_prep_async(req, WRITE);
3386 * This is our waitqueue callback handler, registered through __folio_lock_async()
3387 * when we initially tried to do the IO with the iocb armed our waitqueue.
3388 * This gets called when the page is unlocked, and we generally expect that to
3389 * happen when the page IO is completed and the page is now uptodate. This will
3390 * queue a task_work based retry of the operation, attempting to copy the data
3391 * again. If the latter fails because the page was NOT uptodate, then we will
3392 * do a thread based blocking retry of the operation. That's the unexpected
3395 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3396 int sync, void *arg)
3398 struct wait_page_queue *wpq;
3399 struct io_kiocb *req = wait->private;
3400 struct io_rw *rw = io_kiocb_to_cmd(req);
3401 struct wait_page_key *key = arg;
3403 wpq = container_of(wait, struct wait_page_queue, wait);
3405 if (!wake_page_match(wpq, key))
3408 rw->kiocb.ki_flags &= ~IOCB_WAITQ;
3409 list_del_init(&wait->entry);
3410 io_req_task_queue(req);
3415 * This controls whether a given IO request should be armed for async page
3416 * based retry. If we return false here, the request is handed to the async
3417 * worker threads for retry. If we're doing buffered reads on a regular file,
3418 * we prepare a private wait_page_queue entry and retry the operation. This
3419 * will either succeed because the page is now uptodate and unlocked, or it
3420 * will register a callback when the page is unlocked at IO completion. Through
3421 * that callback, io_uring uses task_work to setup a retry of the operation.
3422 * That retry will attempt the buffered read again. The retry will generally
3423 * succeed, or in rare cases where it fails, we then fall back to using the
3424 * async worker threads for a blocking retry.
3426 static bool io_rw_should_retry(struct io_kiocb *req)
3428 struct io_async_rw *io = req->async_data;
3429 struct wait_page_queue *wait = &io->wpq;
3430 struct io_rw *rw = io_kiocb_to_cmd(req);
3431 struct kiocb *kiocb = &rw->kiocb;
3433 /* never retry for NOWAIT, we just complete with -EAGAIN */
3434 if (req->flags & REQ_F_NOWAIT)
3437 /* Only for buffered IO */
3438 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3442 * just use poll if we can, and don't attempt if the fs doesn't
3443 * support callback based unlocks
3445 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3448 wait->wait.func = io_async_buf_func;
3449 wait->wait.private = req;
3450 wait->wait.flags = 0;
3451 INIT_LIST_HEAD(&wait->wait.entry);
3452 kiocb->ki_flags |= IOCB_WAITQ;
3453 kiocb->ki_flags &= ~IOCB_NOWAIT;
3454 kiocb->ki_waitq = wait;
3458 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
3460 struct file *file = rw->kiocb.ki_filp;
3462 if (likely(file->f_op->read_iter))
3463 return call_read_iter(file, &rw->kiocb, iter);
3464 else if (file->f_op->read)
3465 return loop_rw_iter(READ, rw, iter);
3470 static bool need_read_all(struct io_kiocb *req)
3472 return req->flags & REQ_F_ISREG ||
3473 S_ISBLK(file_inode(req->file)->i_mode);
3476 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3478 struct io_rw *rw = io_kiocb_to_cmd(req);
3479 struct kiocb *kiocb = &rw->kiocb;
3480 struct io_ring_ctx *ctx = req->ctx;
3481 struct file *file = req->file;
3484 if (unlikely(!file || !(file->f_mode & mode)))
3487 if (!io_req_ffs_set(req))
3488 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3490 kiocb->ki_flags = iocb_flags(file);
3491 ret = kiocb_set_rw_flags(kiocb, rw->flags);
3496 * If the file is marked O_NONBLOCK, still allow retry for it if it
3497 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3498 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3500 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3501 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3502 req->flags |= REQ_F_NOWAIT;
3504 if (ctx->flags & IORING_SETUP_IOPOLL) {
3505 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3508 kiocb->private = NULL;
3509 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3510 kiocb->ki_complete = io_complete_rw_iopoll;
3511 req->iopoll_completed = 0;
3513 if (kiocb->ki_flags & IOCB_HIPRI)
3515 kiocb->ki_complete = io_complete_rw;
3521 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3523 struct io_rw *rw = io_kiocb_to_cmd(req);
3524 struct io_rw_state __s, *s = &__s;
3525 struct iovec *iovec;
3526 struct kiocb *kiocb = &rw->kiocb;
3527 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3528 struct io_async_rw *io;
3532 if (!req_has_async_data(req)) {
3533 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3534 if (unlikely(ret < 0))
3537 io = req->async_data;
3541 * Safe and required to re-import if we're using provided
3542 * buffers, as we dropped the selected one before retry.
3544 if (io_do_buffer_select(req)) {
3545 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3546 if (unlikely(ret < 0))
3551 * We come here from an earlier attempt, restore our state to
3552 * match in case it doesn't. It's cheap enough that we don't
3553 * need to make this conditional.
3555 iov_iter_restore(&s->iter, &s->iter_state);
3558 ret = io_rw_init_file(req, FMODE_READ);
3559 if (unlikely(ret)) {
3563 req->cqe.res = iov_iter_count(&s->iter);
3565 if (force_nonblock) {
3566 /* If the file doesn't support async, just async punt */
3567 if (unlikely(!io_file_supports_nowait(req))) {
3568 ret = io_setup_async_rw(req, iovec, s, true);
3569 return ret ?: -EAGAIN;
3571 kiocb->ki_flags |= IOCB_NOWAIT;
3573 /* Ensure we clear previously set non-block flag */
3574 kiocb->ki_flags &= ~IOCB_NOWAIT;
3577 ppos = io_kiocb_update_pos(req);
3579 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
3580 if (unlikely(ret)) {
3585 ret = io_iter_do_read(rw, &s->iter);
3587 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3588 req->flags &= ~REQ_F_REISSUE;
3589 /* if we can poll, just do that */
3590 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3592 /* IOPOLL retry should happen for io-wq threads */
3593 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3595 /* no retry on NONBLOCK nor RWF_NOWAIT */
3596 if (req->flags & REQ_F_NOWAIT)
3599 } else if (ret == -EIOCBQUEUED) {
3601 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
3602 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3603 /* read all, failed, already did sync or don't want to retry */
3608 * Don't depend on the iter state matching what was consumed, or being
3609 * untouched in case of error. Restore it and we'll advance it
3610 * manually if we need to.
3612 iov_iter_restore(&s->iter, &s->iter_state);
3614 ret2 = io_setup_async_rw(req, iovec, s, true);
3619 io = req->async_data;
3622 * Now use our persistent iterator and state, if we aren't already.
3623 * We've restored and mapped the iter to match.
3628 * We end up here because of a partial read, either from
3629 * above or inside this loop. Advance the iter by the bytes
3630 * that were consumed.
3632 iov_iter_advance(&s->iter, ret);
3633 if (!iov_iter_count(&s->iter))
3635 io->bytes_done += ret;
3636 iov_iter_save_state(&s->iter, &s->iter_state);
3638 /* if we can retry, do so with the callbacks armed */
3639 if (!io_rw_should_retry(req)) {
3640 kiocb->ki_flags &= ~IOCB_WAITQ;
3645 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3646 * we get -EIOCBQUEUED, then we'll get a notification when the
3647 * desired page gets unlocked. We can also get a partial read
3648 * here, and if we do, then just retry at the new offset.
3650 ret = io_iter_do_read(rw, &s->iter);
3651 if (ret == -EIOCBQUEUED)
3652 return IOU_ISSUE_SKIP_COMPLETE;
3653 /* we got some bytes, but not all. retry. */
3654 kiocb->ki_flags &= ~IOCB_WAITQ;
3655 iov_iter_restore(&s->iter, &s->iter_state);
3658 kiocb_done(req, ret, issue_flags);
3660 /* it's faster to check here then delegate to kfree */
3663 return IOU_ISSUE_SKIP_COMPLETE;
3666 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3668 struct io_rw *rw = io_kiocb_to_cmd(req);
3669 struct io_rw_state __s, *s = &__s;
3670 struct iovec *iovec;
3671 struct kiocb *kiocb = &rw->kiocb;
3672 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3676 if (!req_has_async_data(req)) {
3677 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3678 if (unlikely(ret < 0))
3681 struct io_async_rw *io = req->async_data;
3684 iov_iter_restore(&s->iter, &s->iter_state);
3687 ret = io_rw_init_file(req, FMODE_WRITE);
3688 if (unlikely(ret)) {
3692 req->cqe.res = iov_iter_count(&s->iter);
3694 if (force_nonblock) {
3695 /* If the file doesn't support async, just async punt */
3696 if (unlikely(!io_file_supports_nowait(req)))
3699 /* file path doesn't support NOWAIT for non-direct_IO */
3700 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3701 (req->flags & REQ_F_ISREG))
3704 kiocb->ki_flags |= IOCB_NOWAIT;
3706 /* Ensure we clear previously set non-block flag */
3707 kiocb->ki_flags &= ~IOCB_NOWAIT;
3710 ppos = io_kiocb_update_pos(req);
3712 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
3717 * Open-code file_start_write here to grab freeze protection,
3718 * which will be released by another thread in
3719 * io_complete_rw(). Fool lockdep by telling it the lock got
3720 * released so that it doesn't complain about the held lock when
3721 * we return to userspace.
3723 if (req->flags & REQ_F_ISREG) {
3724 sb_start_write(file_inode(req->file)->i_sb);
3725 __sb_writers_release(file_inode(req->file)->i_sb,
3728 kiocb->ki_flags |= IOCB_WRITE;
3730 if (likely(req->file->f_op->write_iter))
3731 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3732 else if (req->file->f_op->write)
3733 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
3737 if (req->flags & REQ_F_REISSUE) {
3738 req->flags &= ~REQ_F_REISSUE;
3743 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3744 * retry them without IOCB_NOWAIT.
3746 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3748 /* no retry on NONBLOCK nor RWF_NOWAIT */
3749 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3751 if (!force_nonblock || ret2 != -EAGAIN) {
3752 /* IOPOLL retry should happen for io-wq threads */
3753 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3756 kiocb_done(req, ret2, issue_flags);
3757 ret = IOU_ISSUE_SKIP_COMPLETE;
3760 iov_iter_restore(&s->iter, &s->iter_state);
3761 ret = io_setup_async_rw(req, iovec, s, false);
3762 return ret ?: -EAGAIN;
3765 /* it's reportedly faster than delegating the null check to kfree() */
3771 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
3773 struct io_uring_cmd *ioucmd = io_kiocb_to_cmd(req);
3775 ioucmd->task_work_cb(ioucmd);
3778 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
3779 void (*task_work_cb)(struct io_uring_cmd *))
3781 struct io_kiocb *req = cmd_to_io_kiocb(ioucmd);
3783 ioucmd->task_work_cb = task_work_cb;
3784 req->io_task_work.func = io_uring_cmd_work;
3785 io_req_task_work_add(req);
3787 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
3789 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
3790 u64 extra1, u64 extra2)
3792 req->extra1 = extra1;
3793 req->extra2 = extra2;
3794 req->flags |= REQ_F_CQE32_INIT;
3798 * Called by consumers of io_uring_cmd, if they originally returned
3799 * -EIOCBQUEUED upon receiving the command.
3801 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
3803 struct io_kiocb *req = cmd_to_io_kiocb(ioucmd);
3808 io_req_set_res(req, 0, ret);
3809 if (req->ctx->flags & IORING_SETUP_CQE32)
3810 io_req_set_cqe32_extra(req, res2, 0);
3811 __io_req_complete(req, 0);
3813 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
3815 static int io_uring_cmd_prep_async(struct io_kiocb *req)
3817 struct io_uring_cmd *ioucmd = io_kiocb_to_cmd(req);
3820 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
3822 memcpy(req->async_data, ioucmd->cmd, cmd_size);
3826 static int io_uring_cmd_prep(struct io_kiocb *req,
3827 const struct io_uring_sqe *sqe)
3829 struct io_uring_cmd *ioucmd = io_kiocb_to_cmd(req);
3831 if (sqe->rw_flags || sqe->__pad1)
3833 ioucmd->cmd = sqe->cmd;
3834 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
3838 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
3840 struct io_uring_cmd *ioucmd = io_kiocb_to_cmd(req);
3841 struct io_ring_ctx *ctx = req->ctx;
3842 struct file *file = req->file;
3845 if (!req->file->f_op->uring_cmd)
3848 if (ctx->flags & IORING_SETUP_SQE128)
3849 issue_flags |= IO_URING_F_SQE128;
3850 if (ctx->flags & IORING_SETUP_CQE32)
3851 issue_flags |= IO_URING_F_CQE32;
3852 if (ctx->flags & IORING_SETUP_IOPOLL)
3853 issue_flags |= IO_URING_F_IOPOLL;
3855 if (req_has_async_data(req))
3856 ioucmd->cmd = req->async_data;
3858 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
3859 if (ret == -EAGAIN) {
3860 if (!req_has_async_data(req)) {
3861 if (io_alloc_async_data(req))
3863 io_uring_cmd_prep_async(req);
3868 if (ret != -EIOCBQUEUED) {
3869 io_uring_cmd_done(ioucmd, ret, 0);
3873 return IOU_ISSUE_SKIP_COMPLETE;
3876 static int io_msg_ring_prep(struct io_kiocb *req,
3877 const struct io_uring_sqe *sqe)
3879 struct io_msg *msg = io_kiocb_to_cmd(req);
3881 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
3882 sqe->buf_index || sqe->personality))
3885 msg->user_data = READ_ONCE(sqe->off);
3886 msg->len = READ_ONCE(sqe->len);
3890 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
3892 struct io_msg *msg = io_kiocb_to_cmd(req);
3893 struct io_ring_ctx *target_ctx;
3898 if (req->file->f_op != &io_uring_fops)
3902 target_ctx = req->file->private_data;
3904 spin_lock(&target_ctx->completion_lock);
3905 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
3906 io_commit_cqring(target_ctx);
3907 spin_unlock(&target_ctx->completion_lock);
3910 io_cqring_ev_posted(target_ctx);
3917 io_req_set_res(req, ret, 0);
3918 /* put file to avoid an attempt to IOPOLL the req */
3919 io_put_file(req->file);
3924 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3926 struct io_open *open = io_kiocb_to_cmd(req);
3927 const char __user *fname;
3930 if (unlikely(sqe->buf_index))
3932 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3935 /* open.how should be already initialised */
3936 if (!(open->how.flags & O_PATH) && force_o_largefile())
3937 open->how.flags |= O_LARGEFILE;
3939 open->dfd = READ_ONCE(sqe->fd);
3940 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3941 open->filename = getname(fname);
3942 if (IS_ERR(open->filename)) {
3943 ret = PTR_ERR(open->filename);
3944 open->filename = NULL;
3948 open->file_slot = READ_ONCE(sqe->file_index);
3949 if (open->file_slot && (open->how.flags & O_CLOEXEC))
3952 open->nofile = rlimit(RLIMIT_NOFILE);
3953 req->flags |= REQ_F_NEED_CLEANUP;
3957 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3959 struct io_open *open = io_kiocb_to_cmd(req);
3960 u64 mode = READ_ONCE(sqe->len);
3961 u64 flags = READ_ONCE(sqe->open_flags);
3963 open->how = build_open_how(flags, mode);
3964 return __io_openat_prep(req, sqe);
3967 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3969 struct io_open *open = io_kiocb_to_cmd(req);
3970 struct open_how __user *how;
3974 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3975 len = READ_ONCE(sqe->len);
3976 if (len < OPEN_HOW_SIZE_VER0)
3979 ret = copy_struct_from_user(&open->how, sizeof(open->how), how, len);
3983 return __io_openat_prep(req, sqe);
3986 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
3988 struct io_file_table *table = &ctx->file_table;
3989 unsigned long nr = ctx->nr_user_files;
3993 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
3997 if (!table->alloc_hint)
4000 nr = table->alloc_hint;
4001 table->alloc_hint = 0;
4008 * Note when io_fixed_fd_install() returns error value, it will ensure
4009 * fput() is called correspondingly.
4011 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
4012 struct file *file, unsigned int file_slot)
4014 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
4015 struct io_ring_ctx *ctx = req->ctx;
4018 io_ring_submit_lock(ctx, issue_flags);
4021 ret = io_file_bitmap_get(ctx);
4022 if (unlikely(ret < 0))
4029 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
4030 if (!ret && alloc_slot)
4033 io_ring_submit_unlock(ctx, issue_flags);
4034 if (unlikely(ret < 0))
4039 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4041 struct io_open *open = io_kiocb_to_cmd(req);
4042 struct open_flags op;
4044 bool resolve_nonblock, nonblock_set;
4045 bool fixed = !!open->file_slot;
4048 ret = build_open_flags(&open->how, &op);
4051 nonblock_set = op.open_flag & O_NONBLOCK;
4052 resolve_nonblock = open->how.resolve & RESOLVE_CACHED;
4053 if (issue_flags & IO_URING_F_NONBLOCK) {
4055 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4056 * it'll always -EAGAIN
4058 if (open->how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4060 op.lookup_flags |= LOOKUP_CACHED;
4061 op.open_flag |= O_NONBLOCK;
4065 ret = __get_unused_fd_flags(open->how.flags, open->nofile);
4070 file = do_filp_open(open->dfd, open->filename, &op);
4073 * We could hang on to this 'fd' on retrying, but seems like
4074 * marginal gain for something that is now known to be a slower
4075 * path. So just put it, and we'll get a new one when we retry.
4080 ret = PTR_ERR(file);
4081 /* only retry if RESOLVE_CACHED wasn't already set by application */
4082 if (ret == -EAGAIN &&
4083 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4088 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4089 file->f_flags &= ~O_NONBLOCK;
4090 fsnotify_open(file);
4093 fd_install(ret, file);
4095 ret = io_fixed_fd_install(req, issue_flags, file,
4098 putname(open->filename);
4099 req->flags &= ~REQ_F_NEED_CLEANUP;
4102 io_req_set_res(req, ret, 0);
4106 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4108 return io_openat2(req, issue_flags);
4111 static void io_open_cleanup(struct io_kiocb *req)
4113 struct io_open *open = io_kiocb_to_cmd(req);
4116 putname(open->filename);
4119 static int io_remove_buffers_prep(struct io_kiocb *req,
4120 const struct io_uring_sqe *sqe)
4122 struct io_provide_buf *p = io_kiocb_to_cmd(req);
4125 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4129 tmp = READ_ONCE(sqe->fd);
4130 if (!tmp || tmp > USHRT_MAX)
4133 memset(p, 0, sizeof(*p));
4135 p->bgid = READ_ONCE(sqe->buf_group);
4139 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4140 struct io_buffer_list *bl, unsigned nbufs)
4144 /* shouldn't happen */
4148 if (bl->buf_nr_pages) {
4151 i = bl->buf_ring->tail - bl->head;
4152 for (j = 0; j < bl->buf_nr_pages; j++)
4153 unpin_user_page(bl->buf_pages[j]);
4154 kvfree(bl->buf_pages);
4155 bl->buf_pages = NULL;
4156 bl->buf_nr_pages = 0;
4157 /* make sure it's seen as empty */
4158 INIT_LIST_HEAD(&bl->buf_list);
4162 /* the head kbuf is the list itself */
4163 while (!list_empty(&bl->buf_list)) {
4164 struct io_buffer *nxt;
4166 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4167 list_del(&nxt->list);
4177 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4179 struct io_provide_buf *p = io_kiocb_to_cmd(req);
4180 struct io_ring_ctx *ctx = req->ctx;
4181 struct io_buffer_list *bl;
4184 io_ring_submit_lock(ctx, issue_flags);
4187 bl = io_buffer_get_list(ctx, p->bgid);
4190 /* can't use provide/remove buffers command on mapped buffers */
4191 if (!bl->buf_nr_pages)
4192 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4197 /* complete before unlock, IOPOLL may need the lock */
4198 io_req_set_res(req, ret, 0);
4199 __io_req_complete(req, issue_flags);
4200 io_ring_submit_unlock(ctx, issue_flags);
4201 return IOU_ISSUE_SKIP_COMPLETE;
4204 static int io_provide_buffers_prep(struct io_kiocb *req,
4205 const struct io_uring_sqe *sqe)
4207 unsigned long size, tmp_check;
4208 struct io_provide_buf *p = io_kiocb_to_cmd(req);
4211 if (sqe->rw_flags || sqe->splice_fd_in)
4214 tmp = READ_ONCE(sqe->fd);
4215 if (!tmp || tmp > USHRT_MAX)
4218 p->addr = READ_ONCE(sqe->addr);
4219 p->len = READ_ONCE(sqe->len);
4221 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4224 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4227 size = (unsigned long)p->len * p->nbufs;
4228 if (!access_ok(u64_to_user_ptr(p->addr), size))
4231 p->bgid = READ_ONCE(sqe->buf_group);
4232 tmp = READ_ONCE(sqe->off);
4233 if (tmp > USHRT_MAX)
4239 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4241 struct io_buffer *buf;
4246 * Completions that don't happen inline (eg not under uring_lock) will
4247 * add to ->io_buffers_comp. If we don't have any free buffers, check
4248 * the completion list and splice those entries first.
4250 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4251 spin_lock(&ctx->completion_lock);
4252 if (!list_empty(&ctx->io_buffers_comp)) {
4253 list_splice_init(&ctx->io_buffers_comp,
4254 &ctx->io_buffers_cache);
4255 spin_unlock(&ctx->completion_lock);
4258 spin_unlock(&ctx->completion_lock);
4262 * No free buffers and no completion entries either. Allocate a new
4263 * page worth of buffer entries and add those to our freelist.
4265 page = alloc_page(GFP_KERNEL_ACCOUNT);
4269 list_add(&page->lru, &ctx->io_buffers_pages);
4271 buf = page_address(page);
4272 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4273 while (bufs_in_page) {
4274 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4282 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4283 struct io_buffer_list *bl)
4285 struct io_buffer *buf;
4286 u64 addr = pbuf->addr;
4287 int i, bid = pbuf->bid;
4289 for (i = 0; i < pbuf->nbufs; i++) {
4290 if (list_empty(&ctx->io_buffers_cache) &&
4291 io_refill_buffer_cache(ctx))
4293 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4295 list_move_tail(&buf->list, &bl->buf_list);
4297 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4299 buf->bgid = pbuf->bgid;
4305 return i ? 0 : -ENOMEM;
4308 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
4312 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
4317 for (i = 0; i < BGID_ARRAY; i++) {
4318 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
4319 ctx->io_bl[i].bgid = i;
4325 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4327 struct io_provide_buf *p = io_kiocb_to_cmd(req);
4328 struct io_ring_ctx *ctx = req->ctx;
4329 struct io_buffer_list *bl;
4332 io_ring_submit_lock(ctx, issue_flags);
4334 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
4335 ret = io_init_bl_list(ctx);
4340 bl = io_buffer_get_list(ctx, p->bgid);
4341 if (unlikely(!bl)) {
4342 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
4347 INIT_LIST_HEAD(&bl->buf_list);
4348 ret = io_buffer_add_list(ctx, bl, p->bgid);
4354 /* can't add buffers via this command for a mapped buffer ring */
4355 if (bl->buf_nr_pages) {
4360 ret = io_add_buffers(ctx, p, bl);
4364 /* complete before unlock, IOPOLL may need the lock */
4365 io_req_set_res(req, ret, 0);
4366 __io_req_complete(req, issue_flags);
4367 io_ring_submit_unlock(ctx, issue_flags);
4368 return IOU_ISSUE_SKIP_COMPLETE;
4371 static int io_epoll_ctl_prep(struct io_kiocb *req,
4372 const struct io_uring_sqe *sqe)
4374 #if defined(CONFIG_EPOLL)
4375 struct io_epoll *epoll = io_kiocb_to_cmd(req);
4377 if (sqe->buf_index || sqe->splice_fd_in)
4380 epoll->epfd = READ_ONCE(sqe->fd);
4381 epoll->op = READ_ONCE(sqe->len);
4382 epoll->fd = READ_ONCE(sqe->off);
4384 if (ep_op_has_event(epoll->op)) {
4385 struct epoll_event __user *ev;
4387 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4388 if (copy_from_user(&epoll->event, ev, sizeof(*ev)))
4398 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4400 #if defined(CONFIG_EPOLL)
4401 struct io_epoll *ie = io_kiocb_to_cmd(req);
4403 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4405 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4406 if (force_nonblock && ret == -EAGAIN)
4411 io_req_set_res(req, ret, 0);
4418 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4420 struct io_statx *sx = io_kiocb_to_cmd(req);
4421 const char __user *path;
4423 if (sqe->buf_index || sqe->splice_fd_in)
4425 if (req->flags & REQ_F_FIXED_FILE)
4428 sx->dfd = READ_ONCE(sqe->fd);
4429 sx->mask = READ_ONCE(sqe->len);
4430 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
4431 sx->buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4432 sx->flags = READ_ONCE(sqe->statx_flags);
4434 sx->filename = getname_flags(path,
4435 getname_statx_lookup_flags(sx->flags),
4438 if (IS_ERR(sx->filename)) {
4439 int ret = PTR_ERR(sx->filename);
4441 sx->filename = NULL;
4445 req->flags |= REQ_F_NEED_CLEANUP;
4449 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4451 struct io_statx *sx = io_kiocb_to_cmd(req);
4454 if (issue_flags & IO_URING_F_NONBLOCK)
4457 ret = do_statx(sx->dfd, sx->filename, sx->flags, sx->mask, sx->buffer);
4458 io_req_set_res(req, ret, 0);
4462 static void io_statx_cleanup(struct io_kiocb *req)
4464 struct io_statx *sx = io_kiocb_to_cmd(req);
4467 putname(sx->filename);
4470 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4472 struct io_close *close = io_kiocb_to_cmd(req);
4474 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
4476 if (req->flags & REQ_F_FIXED_FILE)
4479 close->fd = READ_ONCE(sqe->fd);
4480 close->file_slot = READ_ONCE(sqe->file_index);
4481 if (close->file_slot && close->fd)
4487 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4489 struct files_struct *files = current->files;
4490 struct io_close *close = io_kiocb_to_cmd(req);
4491 struct fdtable *fdt;
4495 if (close->file_slot) {
4496 ret = io_close_fixed(req, issue_flags);
4500 spin_lock(&files->file_lock);
4501 fdt = files_fdtable(files);
4502 if (close->fd >= fdt->max_fds) {
4503 spin_unlock(&files->file_lock);
4506 file = rcu_dereference_protected(fdt->fd[close->fd],
4507 lockdep_is_held(&files->file_lock));
4508 if (!file || file->f_op == &io_uring_fops) {
4509 spin_unlock(&files->file_lock);
4513 /* if the file has a flush method, be safe and punt to async */
4514 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4515 spin_unlock(&files->file_lock);
4519 file = __close_fd_get_file(close->fd);
4520 spin_unlock(&files->file_lock);
4524 /* No ->flush() or already async, safely close from here */
4525 ret = filp_close(file, current->files);
4529 io_req_set_res(req, ret, 0);
4533 #if defined(CONFIG_NET)
4534 static int io_shutdown_prep(struct io_kiocb *req,
4535 const struct io_uring_sqe *sqe)
4537 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
4539 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
4540 sqe->buf_index || sqe->splice_fd_in))
4543 shutdown->how = READ_ONCE(sqe->len);
4547 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4549 struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
4550 struct socket *sock;
4553 if (issue_flags & IO_URING_F_NONBLOCK)
4556 sock = sock_from_file(req->file);
4557 if (unlikely(!sock))
4560 ret = __sys_shutdown_sock(sock, shutdown->how);
4561 io_req_set_res(req, ret, 0);
4565 static bool io_net_retry(struct socket *sock, int flags)
4567 if (!(flags & MSG_WAITALL))
4569 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4572 static int io_setup_async_msg(struct io_kiocb *req,
4573 struct io_async_msghdr *kmsg)
4575 struct io_async_msghdr *async_msg = req->async_data;
4579 if (io_alloc_async_data(req)) {
4580 kfree(kmsg->free_iov);
4583 async_msg = req->async_data;
4584 req->flags |= REQ_F_NEED_CLEANUP;
4585 memcpy(async_msg, kmsg, sizeof(*kmsg));
4586 async_msg->msg.msg_name = &async_msg->addr;
4587 /* if were using fast_iov, set it to the new one */
4588 if (!async_msg->free_iov)
4589 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4594 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4595 struct io_async_msghdr *iomsg)
4597 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4599 iomsg->msg.msg_name = &iomsg->addr;
4600 iomsg->free_iov = iomsg->fast_iov;
4601 return sendmsg_copy_msghdr(&iomsg->msg, sr->umsg, sr->msg_flags,
4605 static int io_sendmsg_prep_async(struct io_kiocb *req)
4609 ret = io_sendmsg_copy_hdr(req, req->async_data);
4611 req->flags |= REQ_F_NEED_CLEANUP;
4615 static void io_sendmsg_recvmsg_cleanup(struct io_kiocb *req)
4617 struct io_async_msghdr *io = req->async_data;
4619 kfree(io->free_iov);
4622 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4624 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4626 if (unlikely(sqe->file_index || sqe->addr2))
4629 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4630 sr->len = READ_ONCE(sqe->len);
4631 sr->flags = READ_ONCE(sqe->ioprio);
4632 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
4634 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4635 if (sr->msg_flags & MSG_DONTWAIT)
4636 req->flags |= REQ_F_NOWAIT;
4638 #ifdef CONFIG_COMPAT
4639 if (req->ctx->compat)
4640 sr->msg_flags |= MSG_CMSG_COMPAT;
4646 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4648 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4649 struct io_async_msghdr iomsg, *kmsg;
4650 struct socket *sock;
4655 sock = sock_from_file(req->file);
4656 if (unlikely(!sock))
4659 if (req_has_async_data(req)) {
4660 kmsg = req->async_data;
4662 ret = io_sendmsg_copy_hdr(req, &iomsg);
4668 if (!(req->flags & REQ_F_POLLED) &&
4669 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4670 return io_setup_async_msg(req, kmsg);
4672 flags = sr->msg_flags;
4673 if (issue_flags & IO_URING_F_NONBLOCK)
4674 flags |= MSG_DONTWAIT;
4675 if (flags & MSG_WAITALL)
4676 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4678 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4680 if (ret < min_ret) {
4681 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4682 return io_setup_async_msg(req, kmsg);
4683 if (ret == -ERESTARTSYS)
4685 if (ret > 0 && io_net_retry(sock, flags)) {
4687 req->flags |= REQ_F_PARTIAL_IO;
4688 return io_setup_async_msg(req, kmsg);
4692 /* fast path, check for non-NULL to avoid function call */
4694 kfree(kmsg->free_iov);
4695 req->flags &= ~REQ_F_NEED_CLEANUP;
4698 else if (sr->done_io)
4700 io_req_set_res(req, ret, 0);
4704 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4706 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4709 struct socket *sock;
4714 if (!(req->flags & REQ_F_POLLED) &&
4715 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4718 sock = sock_from_file(req->file);
4719 if (unlikely(!sock))
4722 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4726 msg.msg_name = NULL;
4727 msg.msg_control = NULL;
4728 msg.msg_controllen = 0;
4729 msg.msg_namelen = 0;
4731 flags = sr->msg_flags;
4732 if (issue_flags & IO_URING_F_NONBLOCK)
4733 flags |= MSG_DONTWAIT;
4734 if (flags & MSG_WAITALL)
4735 min_ret = iov_iter_count(&msg.msg_iter);
4737 msg.msg_flags = flags;
4738 ret = sock_sendmsg(sock, &msg);
4739 if (ret < min_ret) {
4740 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4742 if (ret == -ERESTARTSYS)
4744 if (ret > 0 && io_net_retry(sock, flags)) {
4748 req->flags |= REQ_F_PARTIAL_IO;
4755 else if (sr->done_io)
4757 io_req_set_res(req, ret, 0);
4761 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4762 struct io_async_msghdr *iomsg)
4764 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4765 struct iovec __user *uiov;
4769 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4770 &iomsg->uaddr, &uiov, &iov_len);
4774 if (req->flags & REQ_F_BUFFER_SELECT) {
4777 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4779 sr->len = iomsg->fast_iov[0].iov_len;
4780 iomsg->free_iov = NULL;
4782 iomsg->free_iov = iomsg->fast_iov;
4783 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4784 &iomsg->free_iov, &iomsg->msg.msg_iter,
4793 #ifdef CONFIG_COMPAT
4794 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4795 struct io_async_msghdr *iomsg)
4797 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4798 struct compat_iovec __user *uiov;
4803 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4808 uiov = compat_ptr(ptr);
4809 if (req->flags & REQ_F_BUFFER_SELECT) {
4810 compat_ssize_t clen;
4814 if (!access_ok(uiov, sizeof(*uiov)))
4816 if (__get_user(clen, &uiov->iov_len))
4821 iomsg->free_iov = NULL;
4823 iomsg->free_iov = iomsg->fast_iov;
4824 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4825 UIO_FASTIOV, &iomsg->free_iov,
4826 &iomsg->msg.msg_iter, true);
4835 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4836 struct io_async_msghdr *iomsg)
4838 iomsg->msg.msg_name = &iomsg->addr;
4840 #ifdef CONFIG_COMPAT
4841 if (req->ctx->compat)
4842 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4845 return __io_recvmsg_copy_hdr(req, iomsg);
4848 static int io_recvmsg_prep_async(struct io_kiocb *req)
4852 ret = io_recvmsg_copy_hdr(req, req->async_data);
4854 req->flags |= REQ_F_NEED_CLEANUP;
4858 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4860 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4862 if (unlikely(sqe->file_index || sqe->addr2))
4865 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4866 sr->len = READ_ONCE(sqe->len);
4867 sr->flags = READ_ONCE(sqe->ioprio);
4868 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
4870 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4871 if (sr->msg_flags & MSG_DONTWAIT)
4872 req->flags |= REQ_F_NOWAIT;
4873 if (sr->msg_flags & MSG_ERRQUEUE)
4874 req->flags |= REQ_F_CLEAR_POLLIN;
4876 #ifdef CONFIG_COMPAT
4877 if (req->ctx->compat)
4878 sr->msg_flags |= MSG_CMSG_COMPAT;
4884 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4886 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4887 struct io_async_msghdr iomsg, *kmsg;
4888 struct socket *sock;
4889 unsigned int cflags;
4891 int ret, min_ret = 0;
4892 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4894 sock = sock_from_file(req->file);
4895 if (unlikely(!sock))
4898 if (req_has_async_data(req)) {
4899 kmsg = req->async_data;
4901 ret = io_recvmsg_copy_hdr(req, &iomsg);
4907 if (!(req->flags & REQ_F_POLLED) &&
4908 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4909 return io_setup_async_msg(req, kmsg);
4911 if (io_do_buffer_select(req)) {
4914 buf = io_buffer_select(req, &sr->len, issue_flags);
4917 kmsg->fast_iov[0].iov_base = buf;
4918 kmsg->fast_iov[0].iov_len = sr->len;
4919 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
4923 flags = sr->msg_flags;
4925 flags |= MSG_DONTWAIT;
4926 if (flags & MSG_WAITALL)
4927 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4929 kmsg->msg.msg_get_inq = 1;
4930 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
4931 if (ret < min_ret) {
4932 if (ret == -EAGAIN && force_nonblock)
4933 return io_setup_async_msg(req, kmsg);
4934 if (ret == -ERESTARTSYS)
4936 if (ret > 0 && io_net_retry(sock, flags)) {
4938 req->flags |= REQ_F_PARTIAL_IO;
4939 return io_setup_async_msg(req, kmsg);
4942 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
4946 /* fast path, check for non-NULL to avoid function call */
4948 kfree(kmsg->free_iov);
4949 req->flags &= ~REQ_F_NEED_CLEANUP;
4952 else if (sr->done_io)
4954 cflags = io_put_kbuf(req, issue_flags);
4955 if (kmsg->msg.msg_inq)
4956 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
4957 io_req_set_res(req, ret, cflags);
4961 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4963 struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4965 struct socket *sock;
4967 unsigned int cflags;
4969 int ret, min_ret = 0;
4970 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4972 if (!(req->flags & REQ_F_POLLED) &&
4973 (sr->flags & IORING_RECVSEND_POLL_FIRST))
4976 sock = sock_from_file(req->file);
4977 if (unlikely(!sock))
4980 if (io_do_buffer_select(req)) {
4983 buf = io_buffer_select(req, &sr->len, issue_flags);
4989 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
4993 msg.msg_name = NULL;
4994 msg.msg_namelen = 0;
4995 msg.msg_control = NULL;
4996 msg.msg_get_inq = 1;
4998 msg.msg_controllen = 0;
4999 msg.msg_iocb = NULL;
5001 flags = sr->msg_flags;
5003 flags |= MSG_DONTWAIT;
5004 if (flags & MSG_WAITALL)
5005 min_ret = iov_iter_count(&msg.msg_iter);
5007 ret = sock_recvmsg(sock, &msg, flags);
5008 if (ret < min_ret) {
5009 if (ret == -EAGAIN && force_nonblock)
5011 if (ret == -ERESTARTSYS)
5013 if (ret > 0 && io_net_retry(sock, flags)) {
5017 req->flags |= REQ_F_PARTIAL_IO;
5021 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5028 else if (sr->done_io)
5030 cflags = io_put_kbuf(req, issue_flags);
5032 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
5033 io_req_set_res(req, ret, cflags);
5037 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5039 struct io_accept *accept = io_kiocb_to_cmd(req);
5042 if (sqe->len || sqe->buf_index)
5045 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5046 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5047 accept->flags = READ_ONCE(sqe->accept_flags);
5048 accept->nofile = rlimit(RLIMIT_NOFILE);
5049 flags = READ_ONCE(sqe->ioprio);
5050 if (flags & ~IORING_ACCEPT_MULTISHOT)
5053 accept->file_slot = READ_ONCE(sqe->file_index);
5054 if (accept->file_slot) {
5055 if (accept->flags & SOCK_CLOEXEC)
5057 if (flags & IORING_ACCEPT_MULTISHOT &&
5058 accept->file_slot != IORING_FILE_INDEX_ALLOC)
5061 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5063 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5064 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5065 if (flags & IORING_ACCEPT_MULTISHOT)
5066 req->flags |= REQ_F_APOLL_MULTISHOT;
5070 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5072 struct io_ring_ctx *ctx = req->ctx;
5073 struct io_accept *accept = io_kiocb_to_cmd(req);
5074 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5075 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5076 bool fixed = !!accept->file_slot;
5082 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5083 if (unlikely(fd < 0))
5086 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5091 ret = PTR_ERR(file);
5092 if (ret == -EAGAIN && force_nonblock) {
5094 * if it's multishot and polled, we don't need to
5095 * return EAGAIN to arm the poll infra since it
5096 * has already been done
5098 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
5099 IO_APOLL_MULTI_POLLED)
5100 ret = IOU_ISSUE_SKIP_COMPLETE;
5103 if (ret == -ERESTARTSYS)
5106 } else if (!fixed) {
5107 fd_install(fd, file);
5110 ret = io_fixed_fd_install(req, issue_flags, file,
5114 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
5115 io_req_set_res(req, ret, 0);
5121 spin_lock(&ctx->completion_lock);
5122 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
5124 io_commit_cqring(ctx);
5125 spin_unlock(&ctx->completion_lock);
5127 io_cqring_ev_posted(ctx);
5136 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5138 struct io_socket *sock = io_kiocb_to_cmd(req);
5140 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
5143 sock->domain = READ_ONCE(sqe->fd);
5144 sock->type = READ_ONCE(sqe->off);
5145 sock->protocol = READ_ONCE(sqe->len);
5146 sock->file_slot = READ_ONCE(sqe->file_index);
5147 sock->nofile = rlimit(RLIMIT_NOFILE);
5149 sock->flags = sock->type & ~SOCK_TYPE_MASK;
5150 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
5152 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5157 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
5159 struct io_socket *sock = io_kiocb_to_cmd(req);
5160 bool fixed = !!sock->file_slot;
5165 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
5166 if (unlikely(fd < 0))
5169 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
5173 ret = PTR_ERR(file);
5174 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5176 if (ret == -ERESTARTSYS)
5179 } else if (!fixed) {
5180 fd_install(fd, file);
5183 ret = io_fixed_fd_install(req, issue_flags, file,
5186 io_req_set_res(req, ret, 0);
5190 static int io_connect_prep_async(struct io_kiocb *req)
5192 struct io_async_connect *io = req->async_data;
5193 struct io_connect *conn = io_kiocb_to_cmd(req);
5195 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5198 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5200 struct io_connect *conn = io_kiocb_to_cmd(req);
5202 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5205 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5206 conn->addr_len = READ_ONCE(sqe->addr2);
5210 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5212 struct io_connect *connect = io_kiocb_to_cmd(req);
5213 struct io_async_connect __io, *io;
5214 unsigned file_flags;
5216 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5218 if (req_has_async_data(req)) {
5219 io = req->async_data;
5221 ret = move_addr_to_kernel(connect->addr,
5229 file_flags = force_nonblock ? O_NONBLOCK : 0;
5231 ret = __sys_connect_file(req->file, &io->address,
5232 connect->addr_len, file_flags);
5233 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5234 if (req_has_async_data(req))
5236 if (io_alloc_async_data(req)) {
5240 memcpy(req->async_data, &__io, sizeof(__io));
5243 if (ret == -ERESTARTSYS)
5248 io_req_set_res(req, ret, 0);
5251 #else /* !CONFIG_NET */
5252 #define IO_NETOP_FN(op) \
5253 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5255 return -EOPNOTSUPP; \
5258 #define IO_NETOP_PREP(op) \
5260 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5262 return -EOPNOTSUPP; \
5265 #define IO_NETOP_PREP_ASYNC(op) \
5267 static int io_##op##_prep_async(struct io_kiocb *req) \
5269 return -EOPNOTSUPP; \
5272 IO_NETOP_PREP_ASYNC(sendmsg);
5273 IO_NETOP_PREP_ASYNC(recvmsg);
5274 IO_NETOP_PREP_ASYNC(connect);
5275 IO_NETOP_PREP(accept);
5276 IO_NETOP_PREP(socket);
5277 IO_NETOP_PREP(shutdown);
5280 #endif /* CONFIG_NET */
5282 struct io_poll_table {
5283 struct poll_table_struct pt;
5284 struct io_kiocb *req;
5289 #define IO_POLL_CANCEL_FLAG BIT(31)
5290 #define IO_POLL_REF_MASK GENMASK(30, 0)
5293 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5294 * bump it and acquire ownership. It's disallowed to modify requests while not
5295 * owning it, that prevents from races for enqueueing task_work's and b/w
5296 * arming poll and wakeups.
5298 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5300 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5303 static void io_poll_mark_cancelled(struct io_kiocb *req)
5305 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5308 static struct io_poll *io_poll_get_double(struct io_kiocb *req)
5310 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5311 if (req->opcode == IORING_OP_POLL_ADD)
5312 return req->async_data;
5313 return req->apoll->double_poll;
5316 static struct io_poll *io_poll_get_single(struct io_kiocb *req)
5318 if (req->opcode == IORING_OP_POLL_ADD)
5319 return io_kiocb_to_cmd(req);
5320 return &req->apoll->poll;
5323 static void io_poll_req_insert(struct io_kiocb *req)
5325 struct io_ring_ctx *ctx = req->ctx;
5326 struct hlist_head *list;
5328 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
5329 hlist_add_head(&req->hash_node, list);
5332 static void io_init_poll_iocb(struct io_poll *poll, __poll_t events,
5333 wait_queue_func_t wake_func)
5336 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5337 /* mask in events that we always want/need */
5338 poll->events = events | IO_POLL_UNMASK;
5339 INIT_LIST_HEAD(&poll->wait.entry);
5340 init_waitqueue_func_entry(&poll->wait, wake_func);
5343 static inline void io_poll_remove_entry(struct io_poll *poll)
5345 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5348 spin_lock_irq(&head->lock);
5349 list_del_init(&poll->wait.entry);
5351 spin_unlock_irq(&head->lock);
5355 static void io_poll_remove_entries(struct io_kiocb *req)
5358 * Nothing to do if neither of those flags are set. Avoid dipping
5359 * into the poll/apoll/double cachelines if we can.
5361 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5365 * While we hold the waitqueue lock and the waitqueue is nonempty,
5366 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5367 * lock in the first place can race with the waitqueue being freed.
5369 * We solve this as eventpoll does: by taking advantage of the fact that
5370 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5371 * we enter rcu_read_lock() and see that the pointer to the queue is
5372 * non-NULL, we can then lock it without the memory being freed out from
5375 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5376 * case the caller deletes the entry from the queue, leaving it empty.
5377 * In that case, only RCU prevents the queue memory from being freed.
5380 if (req->flags & REQ_F_SINGLE_POLL)
5381 io_poll_remove_entry(io_poll_get_single(req));
5382 if (req->flags & REQ_F_DOUBLE_POLL)
5383 io_poll_remove_entry(io_poll_get_double(req));
5387 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
5389 * All poll tw should go through this. Checks for poll events, manages
5390 * references, does rewait, etc.
5392 * Returns a negative error on failure. >0 when no action require, which is
5393 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5394 * the request, then the mask is stored in req->cqe.res.
5396 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
5398 struct io_ring_ctx *ctx = req->ctx;
5401 /* req->task == current here, checking PF_EXITING is safe */
5402 if (unlikely(req->task->flags & PF_EXITING))
5406 v = atomic_read(&req->poll_refs);
5408 /* tw handler should be the owner, and so have some references */
5409 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5411 if (v & IO_POLL_CANCEL_FLAG)
5414 if (!req->cqe.res) {
5415 struct poll_table_struct pt = { ._key = req->apoll_events };
5416 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
5419 if ((unlikely(!req->cqe.res)))
5421 if (req->apoll_events & EPOLLONESHOT)
5424 /* multishot, just fill a CQE and proceed */
5425 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
5426 __poll_t mask = mangle_poll(req->cqe.res &
5430 spin_lock(&ctx->completion_lock);
5431 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
5432 mask, IORING_CQE_F_MORE);
5433 io_commit_cqring(ctx);
5434 spin_unlock(&ctx->completion_lock);
5436 io_cqring_ev_posted(ctx);
5442 io_tw_lock(req->ctx, locked);
5443 if (unlikely(req->task->flags & PF_EXITING))
5445 ret = io_issue_sqe(req,
5446 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
5451 * Release all references, retry if someone tried to restart
5452 * task_work while we were executing it.
5454 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5459 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5461 struct io_ring_ctx *ctx = req->ctx;
5464 ret = io_poll_check_events(req, locked);
5469 struct io_poll *poll = io_kiocb_to_cmd(req);
5471 req->cqe.res = mangle_poll(req->cqe.res & poll->events);
5477 io_poll_remove_entries(req);
5478 spin_lock(&ctx->completion_lock);
5479 hash_del(&req->hash_node);
5481 __io_req_complete_post(req);
5482 io_commit_cqring(ctx);
5483 spin_unlock(&ctx->completion_lock);
5484 io_cqring_ev_posted(ctx);
5487 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5489 struct io_ring_ctx *ctx = req->ctx;
5492 ret = io_poll_check_events(req, locked);
5496 io_poll_remove_entries(req);
5497 spin_lock(&ctx->completion_lock);
5498 hash_del(&req->hash_node);
5499 spin_unlock(&ctx->completion_lock);
5502 io_req_task_submit(req, locked);
5504 io_req_complete_failed(req, ret);
5507 static void __io_poll_execute(struct io_kiocb *req, int mask,
5508 __poll_t __maybe_unused events)
5510 io_req_set_res(req, mask, 0);
5512 * This is useful for poll that is armed on behalf of another
5513 * request, and where the wakeup path could be on a different
5514 * CPU. We want to avoid pulling in req->apoll->events for that
5517 if (req->opcode == IORING_OP_POLL_ADD)
5518 req->io_task_work.func = io_poll_task_func;
5520 req->io_task_work.func = io_apoll_task_func;
5522 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
5523 io_req_task_work_add(req);
5526 static inline void io_poll_execute(struct io_kiocb *req, int res,
5529 if (io_poll_get_ownership(req))
5530 __io_poll_execute(req, res, events);
5533 static void io_poll_cancel_req(struct io_kiocb *req)
5535 io_poll_mark_cancelled(req);
5536 /* kick tw, which should complete the request */
5537 io_poll_execute(req, 0, 0);
5540 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
5541 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
5542 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
5544 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5547 struct io_kiocb *req = wqe_to_req(wait);
5548 struct io_poll *poll = container_of(wait, struct io_poll, wait);
5549 __poll_t mask = key_to_poll(key);
5551 if (unlikely(mask & POLLFREE)) {
5552 io_poll_mark_cancelled(req);
5553 /* we have to kick tw in case it's not already */
5554 io_poll_execute(req, 0, poll->events);
5557 * If the waitqueue is being freed early but someone is already
5558 * holds ownership over it, we have to tear down the request as
5559 * best we can. That means immediately removing the request from
5560 * its waitqueue and preventing all further accesses to the
5561 * waitqueue via the request.
5563 list_del_init(&poll->wait.entry);
5566 * Careful: this *must* be the last step, since as soon
5567 * as req->head is NULL'ed out, the request can be
5568 * completed and freed, since aio_poll_complete_work()
5569 * will no longer need to take the waitqueue lock.
5571 smp_store_release(&poll->head, NULL);
5575 /* for instances that support it check for an event match first */
5576 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
5579 if (io_poll_get_ownership(req)) {
5580 /* optional, saves extra locking for removal in tw handler */
5581 if (mask && poll->events & EPOLLONESHOT) {
5582 list_del_init(&poll->wait.entry);
5584 if (wqe_is_double(wait))
5585 req->flags &= ~REQ_F_DOUBLE_POLL;
5587 req->flags &= ~REQ_F_SINGLE_POLL;
5589 __io_poll_execute(req, mask, poll->events);
5594 static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt,
5595 struct wait_queue_head *head,
5596 struct io_poll **poll_ptr)
5598 struct io_kiocb *req = pt->req;
5599 unsigned long wqe_private = (unsigned long) req;
5602 * The file being polled uses multiple waitqueues for poll handling
5603 * (e.g. one for read, one for write). Setup a separate io_poll
5606 if (unlikely(pt->nr_entries)) {
5607 struct io_poll *first = poll;
5609 /* double add on the same waitqueue head, ignore */
5610 if (first->head == head)
5612 /* already have a 2nd entry, fail a third attempt */
5614 if ((*poll_ptr)->head == head)
5616 pt->error = -EINVAL;
5620 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5622 pt->error = -ENOMEM;
5625 /* mark as double wq entry */
5627 req->flags |= REQ_F_DOUBLE_POLL;
5628 io_init_poll_iocb(poll, first->events, first->wait.func);
5630 if (req->opcode == IORING_OP_POLL_ADD)
5631 req->flags |= REQ_F_ASYNC_DATA;
5634 req->flags |= REQ_F_SINGLE_POLL;
5637 poll->wait.private = (void *) wqe_private;
5639 if (poll->events & EPOLLEXCLUSIVE)
5640 add_wait_queue_exclusive(head, &poll->wait);
5642 add_wait_queue(head, &poll->wait);
5645 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5646 struct poll_table_struct *p)
5648 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5649 struct io_poll *poll = io_kiocb_to_cmd(pt->req);
5651 __io_queue_proc(poll, pt, head,
5652 (struct io_poll **) &pt->req->async_data);
5655 static int __io_arm_poll_handler(struct io_kiocb *req,
5656 struct io_poll *poll,
5657 struct io_poll_table *ipt, __poll_t mask)
5659 struct io_ring_ctx *ctx = req->ctx;
5662 INIT_HLIST_NODE(&req->hash_node);
5663 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
5664 io_init_poll_iocb(poll, mask, io_poll_wake);
5665 poll->file = req->file;
5667 req->apoll_events = poll->events;
5669 ipt->pt._key = mask;
5672 ipt->nr_entries = 0;
5675 * Take the ownership to delay any tw execution up until we're done
5676 * with poll arming. see io_poll_get_ownership().
5678 atomic_set(&req->poll_refs, 1);
5679 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5681 if (mask && (poll->events & EPOLLONESHOT)) {
5682 io_poll_remove_entries(req);
5683 /* no one else has access to the req, forget about the ref */
5686 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5687 io_poll_remove_entries(req);
5689 ipt->error = -EINVAL;
5693 spin_lock(&ctx->completion_lock);
5694 io_poll_req_insert(req);
5695 spin_unlock(&ctx->completion_lock);
5698 /* can't multishot if failed, just queue the event we've got */
5699 if (unlikely(ipt->error || !ipt->nr_entries)) {
5700 poll->events |= EPOLLONESHOT;
5701 req->apoll_events |= EPOLLONESHOT;
5704 __io_poll_execute(req, mask, poll->events);
5709 * Release ownership. If someone tried to queue a tw while it was
5710 * locked, kick it off for them.
5712 v = atomic_dec_return(&req->poll_refs);
5713 if (unlikely(v & IO_POLL_REF_MASK))
5714 __io_poll_execute(req, 0, poll->events);
5718 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5719 struct poll_table_struct *p)
5721 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5722 struct async_poll *apoll = pt->req->apoll;
5724 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5733 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
5735 const struct io_op_def *def = &io_op_defs[req->opcode];
5736 struct io_ring_ctx *ctx = req->ctx;
5737 struct async_poll *apoll;
5738 struct io_poll_table ipt;
5739 __poll_t mask = POLLPRI | POLLERR;
5742 if (!def->pollin && !def->pollout)
5743 return IO_APOLL_ABORTED;
5744 if (!file_can_poll(req->file))
5745 return IO_APOLL_ABORTED;
5746 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
5747 return IO_APOLL_ABORTED;
5748 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
5749 mask |= EPOLLONESHOT;
5752 mask |= EPOLLIN | EPOLLRDNORM;
5754 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5755 if (req->flags & REQ_F_CLEAR_POLLIN)
5758 mask |= EPOLLOUT | EPOLLWRNORM;
5760 if (def->poll_exclusive)
5761 mask |= EPOLLEXCLUSIVE;
5762 if (req->flags & REQ_F_POLLED) {
5764 kfree(apoll->double_poll);
5765 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
5766 !list_empty(&ctx->apoll_cache)) {
5767 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
5769 list_del_init(&apoll->poll.wait.entry);
5771 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5772 if (unlikely(!apoll))
5773 return IO_APOLL_ABORTED;
5775 apoll->double_poll = NULL;
5777 req->flags |= REQ_F_POLLED;
5778 ipt.pt._qproc = io_async_queue_proc;
5780 io_kbuf_recycle(req, issue_flags);
5782 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5783 if (ret || ipt.error)
5784 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5786 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
5787 mask, apoll->poll.events);
5792 * Returns true if we found and killed one or more poll requests
5794 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
5795 struct task_struct *tsk, bool cancel_all)
5797 struct hlist_node *tmp;
5798 struct io_kiocb *req;
5802 spin_lock(&ctx->completion_lock);
5803 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5804 struct hlist_head *list;
5806 list = &ctx->cancel_hash[i];
5807 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5808 if (io_match_task_safe(req, tsk, cancel_all)) {
5809 hlist_del_init(&req->hash_node);
5810 io_poll_cancel_req(req);
5815 spin_unlock(&ctx->completion_lock);
5819 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
5820 struct io_cancel_data *cd)
5821 __must_hold(&ctx->completion_lock)
5823 struct hlist_head *list;
5824 struct io_kiocb *req;
5826 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
5827 hlist_for_each_entry(req, list, hash_node) {
5828 if (cd->data != req->cqe.user_data)
5830 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5832 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
5833 if (cd->seq == req->work.cancel_seq)
5835 req->work.cancel_seq = cd->seq;
5842 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
5843 struct io_cancel_data *cd)
5844 __must_hold(&ctx->completion_lock)
5846 struct io_kiocb *req;
5849 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5850 struct hlist_head *list;
5852 list = &ctx->cancel_hash[i];
5853 hlist_for_each_entry(req, list, hash_node) {
5854 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
5855 req->file != cd->file)
5857 if (cd->seq == req->work.cancel_seq)
5859 req->work.cancel_seq = cd->seq;
5866 static bool io_poll_disarm(struct io_kiocb *req)
5867 __must_hold(&ctx->completion_lock)
5869 if (!io_poll_get_ownership(req))
5871 io_poll_remove_entries(req);
5872 hash_del(&req->hash_node);
5876 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
5877 __must_hold(&ctx->completion_lock)
5879 struct io_kiocb *req;
5881 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
5882 req = io_poll_file_find(ctx, cd);
5884 req = io_poll_find(ctx, false, cd);
5887 io_poll_cancel_req(req);
5891 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5896 events = READ_ONCE(sqe->poll32_events);
5898 events = swahw32(events);
5900 if (!(flags & IORING_POLL_ADD_MULTI))
5901 events |= EPOLLONESHOT;
5902 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5905 static int io_poll_remove_prep(struct io_kiocb *req,
5906 const struct io_uring_sqe *sqe)
5908 struct io_poll_update *upd = io_kiocb_to_cmd(req);
5911 if (sqe->buf_index || sqe->splice_fd_in)
5913 flags = READ_ONCE(sqe->len);
5914 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5915 IORING_POLL_ADD_MULTI))
5917 /* meaningless without update */
5918 if (flags == IORING_POLL_ADD_MULTI)
5921 upd->old_user_data = READ_ONCE(sqe->addr);
5922 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5923 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5925 upd->new_user_data = READ_ONCE(sqe->off);
5926 if (!upd->update_user_data && upd->new_user_data)
5928 if (upd->update_events)
5929 upd->events = io_poll_parse_events(sqe, flags);
5930 else if (sqe->poll32_events)
5936 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5938 struct io_poll *poll = io_kiocb_to_cmd(req);
5941 if (sqe->buf_index || sqe->off || sqe->addr)
5943 flags = READ_ONCE(sqe->len);
5944 if (flags & ~IORING_POLL_ADD_MULTI)
5946 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
5949 io_req_set_refcount(req);
5950 poll->events = io_poll_parse_events(sqe, flags);
5954 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5956 struct io_poll *poll = io_kiocb_to_cmd(req);
5957 struct io_poll_table ipt;
5960 ipt.pt._qproc = io_poll_queue_proc;
5962 ret = __io_arm_poll_handler(req, poll, &ipt, poll->events);
5964 io_req_set_res(req, ret, 0);
5972 return IOU_ISSUE_SKIP_COMPLETE;
5975 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5977 struct io_poll_update *poll_update = io_kiocb_to_cmd(req);
5978 struct io_cancel_data cd = { .data = poll_update->old_user_data, };
5979 struct io_ring_ctx *ctx = req->ctx;
5980 struct io_kiocb *preq;
5984 spin_lock(&ctx->completion_lock);
5985 preq = io_poll_find(ctx, true, &cd);
5986 if (!preq || !io_poll_disarm(preq)) {
5987 spin_unlock(&ctx->completion_lock);
5988 ret = preq ? -EALREADY : -ENOENT;
5991 spin_unlock(&ctx->completion_lock);
5993 if (poll_update->update_events || poll_update->update_user_data) {
5994 /* only mask one event flags, keep behavior flags */
5995 if (poll_update->update_events) {
5996 struct io_poll *poll = io_kiocb_to_cmd(preq);
5998 poll->events &= ~0xffff;
5999 poll->events |= poll_update->events & 0xffff;
6000 poll->events |= IO_POLL_UNMASK;
6002 if (poll_update->update_user_data)
6003 preq->cqe.user_data = poll_update->new_user_data;
6005 ret2 = io_poll_add(preq, issue_flags);
6006 /* successfully updated, don't complete poll request */
6007 if (!ret2 || ret2 == -EIOCBQUEUED)
6012 io_req_set_res(preq, -ECANCELED, 0);
6013 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6014 io_req_task_complete(preq, &locked);
6020 /* complete update request, we're done with it */
6021 io_req_set_res(req, ret, 0);
6025 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6027 struct io_timeout_data *data = container_of(timer,
6028 struct io_timeout_data, timer);
6029 struct io_kiocb *req = data->req;
6030 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6031 struct io_ring_ctx *ctx = req->ctx;
6032 unsigned long flags;
6034 spin_lock_irqsave(&ctx->timeout_lock, flags);
6035 list_del_init(&timeout->list);
6036 atomic_set(&req->ctx->cq_timeouts,
6037 atomic_read(&req->ctx->cq_timeouts) + 1);
6038 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6040 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6043 io_req_set_res(req, -ETIME, 0);
6044 req->io_task_work.func = io_req_task_complete;
6045 io_req_task_work_add(req);
6046 return HRTIMER_NORESTART;
6049 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6050 struct io_cancel_data *cd)
6051 __must_hold(&ctx->timeout_lock)
6053 struct io_timeout *timeout;
6054 struct io_timeout_data *io;
6055 struct io_kiocb *req = NULL;
6057 list_for_each_entry(timeout, &ctx->timeout_list, list) {
6058 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
6060 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
6061 cd->data != tmp->cqe.user_data)
6063 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
6064 if (cd->seq == tmp->work.cancel_seq)
6066 tmp->work.cancel_seq = cd->seq;
6072 return ERR_PTR(-ENOENT);
6074 io = req->async_data;
6075 if (hrtimer_try_to_cancel(&io->timer) == -1)
6076 return ERR_PTR(-EALREADY);
6077 timeout = io_kiocb_to_cmd(req);
6078 list_del_init(&timeout->list);
6082 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
6083 __must_hold(&ctx->completion_lock)
6085 struct io_kiocb *req;
6087 spin_lock_irq(&ctx->timeout_lock);
6088 req = io_timeout_extract(ctx, cd);
6089 spin_unlock_irq(&ctx->timeout_lock);
6092 return PTR_ERR(req);
6093 io_req_task_queue_fail(req, -ECANCELED);
6097 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6099 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6100 case IORING_TIMEOUT_BOOTTIME:
6101 return CLOCK_BOOTTIME;
6102 case IORING_TIMEOUT_REALTIME:
6103 return CLOCK_REALTIME;
6105 /* can't happen, vetted at prep time */
6109 return CLOCK_MONOTONIC;
6113 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6114 struct timespec64 *ts, enum hrtimer_mode mode)
6115 __must_hold(&ctx->timeout_lock)
6117 struct io_timeout_data *io;
6118 struct io_timeout *timeout;
6119 struct io_kiocb *req = NULL;
6121 list_for_each_entry(timeout, &ctx->ltimeout_list, list) {
6122 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
6124 if (user_data == tmp->cqe.user_data) {
6132 io = req->async_data;
6133 if (hrtimer_try_to_cancel(&io->timer) == -1)
6135 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6136 io->timer.function = io_link_timeout_fn;
6137 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6141 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6142 struct timespec64 *ts, enum hrtimer_mode mode)
6143 __must_hold(&ctx->timeout_lock)
6145 struct io_cancel_data cd = { .data = user_data, };
6146 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
6147 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6148 struct io_timeout_data *data;
6151 return PTR_ERR(req);
6153 timeout->off = 0; /* noseq */
6154 data = req->async_data;
6155 list_add_tail(&timeout->list, &ctx->timeout_list);
6156 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6157 data->timer.function = io_timeout_fn;
6158 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6162 static int io_timeout_remove_prep(struct io_kiocb *req,
6163 const struct io_uring_sqe *sqe)
6165 struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
6167 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6169 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
6172 tr->ltimeout = false;
6173 tr->addr = READ_ONCE(sqe->addr);
6174 tr->flags = READ_ONCE(sqe->timeout_flags);
6175 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6176 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6178 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6179 tr->ltimeout = true;
6180 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6182 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6184 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6186 } else if (tr->flags) {
6187 /* timeout removal doesn't support flags */
6194 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6196 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6201 * Remove or update an existing timeout command
6203 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6205 struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
6206 struct io_ring_ctx *ctx = req->ctx;
6209 if (!(tr->flags & IORING_TIMEOUT_UPDATE)) {
6210 struct io_cancel_data cd = { .data = tr->addr, };
6212 spin_lock(&ctx->completion_lock);
6213 ret = io_timeout_cancel(ctx, &cd);
6214 spin_unlock(&ctx->completion_lock);
6216 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6218 spin_lock_irq(&ctx->timeout_lock);
6220 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6222 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6223 spin_unlock_irq(&ctx->timeout_lock);
6228 io_req_set_res(req, ret, 0);
6232 static int __io_timeout_prep(struct io_kiocb *req,
6233 const struct io_uring_sqe *sqe,
6234 bool is_timeout_link)
6236 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6237 struct io_timeout_data *data;
6239 u32 off = READ_ONCE(sqe->off);
6241 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
6243 if (off && is_timeout_link)
6245 flags = READ_ONCE(sqe->timeout_flags);
6246 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6247 IORING_TIMEOUT_ETIME_SUCCESS))
6249 /* more than one clock specified is invalid, obviously */
6250 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6253 INIT_LIST_HEAD(&timeout->list);
6255 if (unlikely(off && !req->ctx->off_timeout_used))
6256 req->ctx->off_timeout_used = true;
6258 if (WARN_ON_ONCE(req_has_async_data(req)))
6260 if (io_alloc_async_data(req))
6263 data = req->async_data;
6265 data->flags = flags;
6267 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6270 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6273 INIT_LIST_HEAD(&timeout->list);
6274 data->mode = io_translate_timeout_mode(flags);
6275 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6277 if (is_timeout_link) {
6278 struct io_submit_link *link = &req->ctx->submit_state.link;
6282 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6284 timeout->head = link->last;
6285 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6290 static int io_timeout_prep(struct io_kiocb *req,
6291 const struct io_uring_sqe *sqe)
6293 return __io_timeout_prep(req, sqe, false);
6296 static int io_link_timeout_prep(struct io_kiocb *req,
6297 const struct io_uring_sqe *sqe)
6299 return __io_timeout_prep(req, sqe, true);
6302 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6304 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6305 struct io_ring_ctx *ctx = req->ctx;
6306 struct io_timeout_data *data = req->async_data;
6307 struct list_head *entry;
6308 u32 tail, off = timeout->off;
6310 spin_lock_irq(&ctx->timeout_lock);
6313 * sqe->off holds how many events that need to occur for this
6314 * timeout event to be satisfied. If it isn't set, then this is
6315 * a pure timeout request, sequence isn't used.
6317 if (io_is_timeout_noseq(req)) {
6318 entry = ctx->timeout_list.prev;
6322 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6323 timeout->target_seq = tail + off;
6325 /* Update the last seq here in case io_flush_timeouts() hasn't.
6326 * This is safe because ->completion_lock is held, and submissions
6327 * and completions are never mixed in the same ->completion_lock section.
6329 ctx->cq_last_tm_flush = tail;
6332 * Insertion sort, ensuring the first entry in the list is always
6333 * the one we need first.
6335 list_for_each_prev(entry, &ctx->timeout_list) {
6336 struct io_timeout *nextt = list_entry(entry, struct io_timeout, list);
6337 struct io_kiocb *nxt = cmd_to_io_kiocb(nextt);
6339 if (io_is_timeout_noseq(nxt))
6341 /* nxt.seq is behind @tail, otherwise would've been completed */
6342 if (off >= nextt->target_seq - tail)
6346 list_add(&timeout->list, entry);
6347 data->timer.function = io_timeout_fn;
6348 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6349 spin_unlock_irq(&ctx->timeout_lock);
6350 return IOU_ISSUE_SKIP_COMPLETE;
6353 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6355 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6356 struct io_cancel_data *cd = data;
6358 if (req->ctx != cd->ctx)
6360 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
6362 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
6363 if (req->file != cd->file)
6366 if (req->cqe.user_data != cd->data)
6369 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
6370 if (cd->seq == req->work.cancel_seq)
6372 req->work.cancel_seq = cd->seq;
6377 static int io_async_cancel_one(struct io_uring_task *tctx,
6378 struct io_cancel_data *cd)
6380 enum io_wq_cancel cancel_ret;
6384 if (!tctx || !tctx->io_wq)
6387 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
6388 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
6389 switch (cancel_ret) {
6390 case IO_WQ_CANCEL_OK:
6393 case IO_WQ_CANCEL_RUNNING:
6396 case IO_WQ_CANCEL_NOTFOUND:
6404 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
6406 struct io_ring_ctx *ctx = req->ctx;
6409 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6411 ret = io_async_cancel_one(req->task->io_uring, cd);
6413 * Fall-through even for -EALREADY, as we may have poll armed
6414 * that need unarming.
6419 spin_lock(&ctx->completion_lock);
6420 ret = io_poll_cancel(ctx, cd);
6423 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
6424 ret = io_timeout_cancel(ctx, cd);
6426 spin_unlock(&ctx->completion_lock);
6430 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
6431 IORING_ASYNC_CANCEL_ANY)
6433 static int io_async_cancel_prep(struct io_kiocb *req,
6434 const struct io_uring_sqe *sqe)
6436 struct io_cancel *cancel = io_kiocb_to_cmd(req);
6438 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
6440 if (sqe->off || sqe->len || sqe->splice_fd_in)
6443 cancel->addr = READ_ONCE(sqe->addr);
6444 cancel->flags = READ_ONCE(sqe->cancel_flags);
6445 if (cancel->flags & ~CANCEL_FLAGS)
6447 if (cancel->flags & IORING_ASYNC_CANCEL_FD) {
6448 if (cancel->flags & IORING_ASYNC_CANCEL_ANY)
6450 cancel->fd = READ_ONCE(sqe->fd);
6456 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
6457 unsigned int issue_flags)
6459 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
6460 struct io_ring_ctx *ctx = cd->ctx;
6461 struct io_tctx_node *node;
6465 ret = io_try_cancel(req, cd);
6473 /* slow path, try all io-wq's */
6474 io_ring_submit_lock(ctx, issue_flags);
6476 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6477 struct io_uring_task *tctx = node->task->io_uring;
6479 ret = io_async_cancel_one(tctx, cd);
6480 if (ret != -ENOENT) {
6486 io_ring_submit_unlock(ctx, issue_flags);
6487 return all ? nr : ret;
6490 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6492 struct io_cancel *cancel = io_kiocb_to_cmd(req);
6493 struct io_cancel_data cd = {
6495 .data = cancel->addr,
6496 .flags = cancel->flags,
6497 .seq = atomic_inc_return(&req->ctx->cancel_seq),
6501 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
6502 if (req->flags & REQ_F_FIXED_FILE)
6503 req->file = io_file_get_fixed(req, cancel->fd,
6506 req->file = io_file_get_normal(req, cancel->fd);
6511 cd.file = req->file;
6514 ret = __io_async_cancel(&cd, req, issue_flags);
6518 io_req_set_res(req, ret, 0);
6522 static int io_files_update_prep(struct io_kiocb *req,
6523 const struct io_uring_sqe *sqe)
6525 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6527 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6529 if (sqe->rw_flags || sqe->splice_fd_in)
6532 up->offset = READ_ONCE(sqe->off);
6533 up->nr_args = READ_ONCE(sqe->len);
6536 up->arg = READ_ONCE(sqe->addr);
6540 static int io_files_update_with_index_alloc(struct io_kiocb *req,
6541 unsigned int issue_flags)
6543 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6544 __s32 __user *fds = u64_to_user_ptr(up->arg);
6549 if (!req->ctx->file_data)
6552 for (done = 0; done < up->nr_args; done++) {
6553 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6563 ret = io_fixed_fd_install(req, issue_flags, file,
6564 IORING_FILE_INDEX_ALLOC);
6567 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
6568 __io_close_fixed(req, issue_flags, ret);
6579 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6581 struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6582 struct io_ring_ctx *ctx = req->ctx;
6583 struct io_uring_rsrc_update2 up2;
6586 up2.offset = up->offset;
6593 if (up->offset == IORING_FILE_INDEX_ALLOC) {
6594 ret = io_files_update_with_index_alloc(req, issue_flags);
6596 io_ring_submit_lock(ctx, issue_flags);
6597 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6599 io_ring_submit_unlock(ctx, issue_flags);
6604 io_req_set_res(req, ret, 0);
6608 static int io_req_prep_async(struct io_kiocb *req)
6610 const struct io_op_def *def = &io_op_defs[req->opcode];
6612 /* assign early for deferred execution for non-fixed file */
6613 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
6614 req->file = io_file_get_normal(req, req->cqe.fd);
6615 if (!def->prep_async)
6617 if (WARN_ON_ONCE(req_has_async_data(req)))
6619 if (io_alloc_async_data(req))
6622 return def->prep_async(req);
6625 static u32 io_get_sequence(struct io_kiocb *req)
6627 u32 seq = req->ctx->cached_sq_head;
6628 struct io_kiocb *cur;
6630 /* need original cached_sq_head, but it was increased for each req */
6631 io_for_each_link(cur, req)
6636 static __cold void io_drain_req(struct io_kiocb *req)
6638 struct io_ring_ctx *ctx = req->ctx;
6639 struct io_defer_entry *de;
6641 u32 seq = io_get_sequence(req);
6643 /* Still need defer if there is pending req in defer list. */
6644 spin_lock(&ctx->completion_lock);
6645 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6646 spin_unlock(&ctx->completion_lock);
6648 ctx->drain_active = false;
6649 io_req_task_queue(req);
6652 spin_unlock(&ctx->completion_lock);
6654 ret = io_req_prep_async(req);
6657 io_req_complete_failed(req, ret);
6660 io_prep_async_link(req);
6661 de = kmalloc(sizeof(*de), GFP_KERNEL);
6667 spin_lock(&ctx->completion_lock);
6668 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6669 spin_unlock(&ctx->completion_lock);
6674 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
6677 list_add_tail(&de->list, &ctx->defer_list);
6678 spin_unlock(&ctx->completion_lock);
6681 static void io_clean_op(struct io_kiocb *req)
6683 if (req->flags & REQ_F_BUFFER_SELECTED) {
6684 spin_lock(&req->ctx->completion_lock);
6685 io_put_kbuf_comp(req);
6686 spin_unlock(&req->ctx->completion_lock);
6689 if (req->flags & REQ_F_NEED_CLEANUP) {
6690 const struct io_op_def *def = &io_op_defs[req->opcode];
6695 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6696 kfree(req->apoll->double_poll);
6700 if (req->flags & REQ_F_INFLIGHT) {
6701 struct io_uring_task *tctx = req->task->io_uring;
6703 atomic_dec(&tctx->inflight_tracked);
6705 if (req->flags & REQ_F_CREDS)
6706 put_cred(req->creds);
6707 if (req->flags & REQ_F_ASYNC_DATA) {
6708 kfree(req->async_data);
6709 req->async_data = NULL;
6711 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6714 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
6716 if (req->file || !io_op_defs[req->opcode].needs_file)
6719 if (req->flags & REQ_F_FIXED_FILE)
6720 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
6722 req->file = io_file_get_normal(req, req->cqe.fd);
6727 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6729 const struct io_op_def *def = &io_op_defs[req->opcode];
6730 const struct cred *creds = NULL;
6733 if (unlikely(!io_assign_file(req, issue_flags)))
6736 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
6737 creds = override_creds(req->creds);
6739 if (!def->audit_skip)
6740 audit_uring_entry(req->opcode);
6742 ret = def->issue(req, issue_flags);
6744 if (!def->audit_skip)
6745 audit_uring_exit(!ret, ret);
6748 revert_creds(creds);
6751 __io_req_complete(req, issue_flags);
6752 else if (ret != IOU_ISSUE_SKIP_COMPLETE)
6755 /* If the op doesn't have a file, we're not polling for it */
6756 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6757 io_iopoll_req_issued(req, issue_flags);
6762 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6764 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6766 req = io_put_req_find_next(req);
6767 return req ? &req->work : NULL;
6770 static void io_wq_submit_work(struct io_wq_work *work)
6772 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6773 const struct io_op_def *def = &io_op_defs[req->opcode];
6774 unsigned int issue_flags = IO_URING_F_UNLOCKED;
6775 bool needs_poll = false;
6776 int ret = 0, err = -ECANCELED;
6778 /* one will be dropped by ->io_free_work() after returning to io-wq */
6779 if (!(req->flags & REQ_F_REFCOUNT))
6780 __io_req_set_refcount(req, 2);
6784 io_arm_ltimeout(req);
6786 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6787 if (work->flags & IO_WQ_WORK_CANCEL) {
6789 io_req_task_queue_fail(req, err);
6792 if (!io_assign_file(req, issue_flags)) {
6794 work->flags |= IO_WQ_WORK_CANCEL;
6798 if (req->flags & REQ_F_FORCE_ASYNC) {
6799 bool opcode_poll = def->pollin || def->pollout;
6801 if (opcode_poll && file_can_poll(req->file)) {
6803 issue_flags |= IO_URING_F_NONBLOCK;
6808 ret = io_issue_sqe(req, issue_flags);
6812 * We can get EAGAIN for iopolled IO even though we're
6813 * forcing a sync submission from here, since we can't
6814 * wait for request slots on the block side.
6817 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
6823 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
6825 /* aborted or ready, in either case retry blocking */
6827 issue_flags &= ~IO_URING_F_NONBLOCK;
6830 /* avoid locking problems by failing it from a clean context */
6832 io_req_task_queue_fail(req, ret);
6835 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6838 return &table->files[i];
6841 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6844 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6846 return (struct file *) (slot->file_ptr & FFS_MASK);
6849 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6851 unsigned long file_ptr = (unsigned long) file;
6853 file_ptr |= io_file_get_flags(file);
6854 file_slot->file_ptr = file_ptr;
6857 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
6858 unsigned int issue_flags)
6860 struct io_ring_ctx *ctx = req->ctx;
6861 struct file *file = NULL;
6862 unsigned long file_ptr;
6864 io_ring_submit_lock(ctx, issue_flags);
6866 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6868 fd = array_index_nospec(fd, ctx->nr_user_files);
6869 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6870 file = (struct file *) (file_ptr & FFS_MASK);
6871 file_ptr &= ~FFS_MASK;
6872 /* mask in overlapping REQ_F and FFS bits */
6873 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
6874 io_req_set_rsrc_node(req, ctx, 0);
6875 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
6877 io_ring_submit_unlock(ctx, issue_flags);
6881 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
6883 struct file *file = fget(fd);
6885 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
6887 /* we don't allow fixed io_uring files */
6888 if (file && file->f_op == &io_uring_fops)
6889 io_req_track_inflight(req);
6893 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6895 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6896 struct io_kiocb *prev = timeout->prev;
6900 if (!(req->task->flags & PF_EXITING)) {
6901 struct io_cancel_data cd = {
6903 .data = prev->cqe.user_data,
6906 ret = io_try_cancel(req, &cd);
6908 io_req_set_res(req, ret ?: -ETIME, 0);
6909 io_req_complete_post(req);
6912 io_req_set_res(req, -ETIME, 0);
6913 io_req_complete_post(req);
6917 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6919 struct io_timeout_data *data = container_of(timer,
6920 struct io_timeout_data, timer);
6921 struct io_kiocb *prev, *req = data->req;
6922 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6923 struct io_ring_ctx *ctx = req->ctx;
6924 unsigned long flags;
6926 spin_lock_irqsave(&ctx->timeout_lock, flags);
6927 prev = timeout->head;
6928 timeout->head = NULL;
6931 * We don't expect the list to be empty, that will only happen if we
6932 * race with the completion of the linked work.
6935 io_remove_next_linked(prev);
6936 if (!req_ref_inc_not_zero(prev))
6939 list_del(&timeout->list);
6940 timeout->prev = prev;
6941 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6943 req->io_task_work.func = io_req_task_link_timeout;
6944 io_req_task_work_add(req);
6945 return HRTIMER_NORESTART;
6948 static void io_queue_linked_timeout(struct io_kiocb *req)
6950 struct io_timeout *timeout = io_kiocb_to_cmd(req);
6951 struct io_ring_ctx *ctx = req->ctx;
6953 spin_lock_irq(&ctx->timeout_lock);
6955 * If the back reference is NULL, then our linked request finished
6956 * before we got a chance to setup the timer
6958 if (timeout->head) {
6959 struct io_timeout_data *data = req->async_data;
6961 data->timer.function = io_link_timeout_fn;
6962 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6964 list_add_tail(&timeout->list, &ctx->ltimeout_list);
6966 spin_unlock_irq(&ctx->timeout_lock);
6967 /* drop submission reference */
6971 static void io_queue_async(struct io_kiocb *req, int ret)
6972 __must_hold(&req->ctx->uring_lock)
6974 struct io_kiocb *linked_timeout;
6976 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
6977 io_req_complete_failed(req, ret);
6981 linked_timeout = io_prep_linked_timeout(req);
6983 switch (io_arm_poll_handler(req, 0)) {
6984 case IO_APOLL_READY:
6985 io_req_task_queue(req);
6987 case IO_APOLL_ABORTED:
6989 * Queued up for async execution, worker will release
6990 * submit reference when the iocb is actually submitted.
6992 io_kbuf_recycle(req, 0);
6993 io_queue_iowq(req, NULL);
7000 io_queue_linked_timeout(linked_timeout);
7003 static inline void io_queue_sqe(struct io_kiocb *req)
7004 __must_hold(&req->ctx->uring_lock)
7008 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7010 if (req->flags & REQ_F_COMPLETE_INLINE) {
7011 io_req_add_compl_list(req);
7015 * We async punt it if the file wasn't marked NOWAIT, or if the file
7016 * doesn't support non-blocking read/write attempts
7019 io_arm_ltimeout(req);
7021 io_queue_async(req, ret);
7024 static void io_queue_sqe_fallback(struct io_kiocb *req)
7025 __must_hold(&req->ctx->uring_lock)
7027 if (unlikely(req->flags & REQ_F_FAIL)) {
7029 * We don't submit, fail them all, for that replace hardlinks
7030 * with normal links. Extra REQ_F_LINK is tolerated.
7032 req->flags &= ~REQ_F_HARDLINK;
7033 req->flags |= REQ_F_LINK;
7034 io_req_complete_failed(req, req->cqe.res);
7035 } else if (unlikely(req->ctx->drain_active)) {
7038 int ret = io_req_prep_async(req);
7041 io_req_complete_failed(req, ret);
7043 io_queue_iowq(req, NULL);
7048 * Check SQE restrictions (opcode and flags).
7050 * Returns 'true' if SQE is allowed, 'false' otherwise.
7052 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7053 struct io_kiocb *req,
7054 unsigned int sqe_flags)
7056 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7059 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7060 ctx->restrictions.sqe_flags_required)
7063 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7064 ctx->restrictions.sqe_flags_required))
7070 static void io_init_req_drain(struct io_kiocb *req)
7072 struct io_ring_ctx *ctx = req->ctx;
7073 struct io_kiocb *head = ctx->submit_state.link.head;
7075 ctx->drain_active = true;
7078 * If we need to drain a request in the middle of a link, drain
7079 * the head request and the next request/link after the current
7080 * link. Considering sequential execution of links,
7081 * REQ_F_IO_DRAIN will be maintained for every request of our
7084 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7085 ctx->drain_next = true;
7089 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7090 const struct io_uring_sqe *sqe)
7091 __must_hold(&ctx->uring_lock)
7093 const struct io_op_def *def;
7094 unsigned int sqe_flags;
7098 /* req is partially pre-initialised, see io_preinit_req() */
7099 req->opcode = opcode = READ_ONCE(sqe->opcode);
7100 /* same numerical values with corresponding REQ_F_*, safe to copy */
7101 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7102 req->cqe.user_data = READ_ONCE(sqe->user_data);
7104 req->rsrc_node = NULL;
7105 req->task = current;
7107 if (unlikely(opcode >= IORING_OP_LAST)) {
7111 def = &io_op_defs[opcode];
7112 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7113 /* enforce forwards compatibility on users */
7114 if (sqe_flags & ~SQE_VALID_FLAGS)
7116 if (sqe_flags & IOSQE_BUFFER_SELECT) {
7117 if (!def->buffer_select)
7119 req->buf_index = READ_ONCE(sqe->buf_group);
7121 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7122 ctx->drain_disabled = true;
7123 if (sqe_flags & IOSQE_IO_DRAIN) {
7124 if (ctx->drain_disabled)
7126 io_init_req_drain(req);
7129 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7130 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7132 /* knock it to the slow queue path, will be drained there */
7133 if (ctx->drain_active)
7134 req->flags |= REQ_F_FORCE_ASYNC;
7135 /* if there is no link, we're at "next" request and need to drain */
7136 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7137 ctx->drain_next = false;
7138 ctx->drain_active = true;
7139 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7143 if (!def->ioprio && sqe->ioprio)
7145 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
7148 if (def->needs_file) {
7149 struct io_submit_state *state = &ctx->submit_state;
7151 req->cqe.fd = READ_ONCE(sqe->fd);
7154 * Plug now if we have more than 2 IO left after this, and the
7155 * target is potentially a read/write to block based storage.
7157 if (state->need_plug && def->plug) {
7158 state->plug_started = true;
7159 state->need_plug = false;
7160 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7164 personality = READ_ONCE(sqe->personality);
7168 req->creds = xa_load(&ctx->personalities, personality);
7171 get_cred(req->creds);
7172 ret = security_uring_override_creds(req->creds);
7174 put_cred(req->creds);
7177 req->flags |= REQ_F_CREDS;
7180 return def->prep(req, sqe);
7183 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
7184 struct io_kiocb *req, int ret)
7186 struct io_ring_ctx *ctx = req->ctx;
7187 struct io_submit_link *link = &ctx->submit_state.link;
7188 struct io_kiocb *head = link->head;
7190 trace_io_uring_req_failed(sqe, ctx, req, ret);
7193 * Avoid breaking links in the middle as it renders links with SQPOLL
7194 * unusable. Instead of failing eagerly, continue assembling the link if
7195 * applicable and mark the head with REQ_F_FAIL. The link flushing code
7196 * should find the flag and handle the rest.
7198 req_fail_link_node(req, ret);
7199 if (head && !(head->flags & REQ_F_FAIL))
7200 req_fail_link_node(head, -ECANCELED);
7202 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
7204 link->last->link = req;
7208 io_queue_sqe_fallback(req);
7213 link->last->link = req;
7220 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7221 const struct io_uring_sqe *sqe)
7222 __must_hold(&ctx->uring_lock)
7224 struct io_submit_link *link = &ctx->submit_state.link;
7227 ret = io_init_req(ctx, req, sqe);
7229 return io_submit_fail_init(sqe, req, ret);
7231 /* don't need @sqe from now on */
7232 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
7234 ctx->flags & IORING_SETUP_SQPOLL);
7237 * If we already have a head request, queue this one for async
7238 * submittal once the head completes. If we don't have a head but
7239 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7240 * submitted sync once the chain is complete. If none of those
7241 * conditions are true (normal request), then just queue it.
7243 if (unlikely(link->head)) {
7244 ret = io_req_prep_async(req);
7246 return io_submit_fail_init(sqe, req, ret);
7248 trace_io_uring_link(ctx, req, link->head);
7249 link->last->link = req;
7252 if (req->flags & IO_REQ_LINK_FLAGS)
7254 /* last request of the link, flush it */
7257 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
7260 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
7261 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
7262 if (req->flags & IO_REQ_LINK_FLAGS) {
7267 io_queue_sqe_fallback(req);
7277 * Batched submission is done, ensure local IO is flushed out.
7279 static void io_submit_state_end(struct io_ring_ctx *ctx)
7281 struct io_submit_state *state = &ctx->submit_state;
7283 if (unlikely(state->link.head))
7284 io_queue_sqe_fallback(state->link.head);
7285 /* flush only after queuing links as they can generate completions */
7286 io_submit_flush_completions(ctx);
7287 if (state->plug_started)
7288 blk_finish_plug(&state->plug);
7292 * Start submission side cache.
7294 static void io_submit_state_start(struct io_submit_state *state,
7295 unsigned int max_ios)
7297 state->plug_started = false;
7298 state->need_plug = max_ios > 2;
7299 state->submit_nr = max_ios;
7300 /* set only head, no need to init link_last in advance */
7301 state->link.head = NULL;
7304 static void io_commit_sqring(struct io_ring_ctx *ctx)
7306 struct io_rings *rings = ctx->rings;
7309 * Ensure any loads from the SQEs are done at this point,
7310 * since once we write the new head, the application could
7311 * write new data to them.
7313 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7317 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7318 * that is mapped by userspace. This means that care needs to be taken to
7319 * ensure that reads are stable, as we cannot rely on userspace always
7320 * being a good citizen. If members of the sqe are validated and then later
7321 * used, it's important that those reads are done through READ_ONCE() to
7322 * prevent a re-load down the line.
7324 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7326 unsigned head, mask = ctx->sq_entries - 1;
7327 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7330 * The cached sq head (or cq tail) serves two purposes:
7332 * 1) allows us to batch the cost of updating the user visible
7334 * 2) allows the kernel side to track the head on its own, even
7335 * though the application is the one updating it.
7337 head = READ_ONCE(ctx->sq_array[sq_idx]);
7338 if (likely(head < ctx->sq_entries)) {
7339 /* double index for 128-byte SQEs, twice as long */
7340 if (ctx->flags & IORING_SETUP_SQE128)
7342 return &ctx->sq_sqes[head];
7345 /* drop invalid entries */
7347 WRITE_ONCE(ctx->rings->sq_dropped,
7348 READ_ONCE(ctx->rings->sq_dropped) + 1);
7352 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7353 __must_hold(&ctx->uring_lock)
7355 unsigned int entries = io_sqring_entries(ctx);
7359 if (unlikely(!entries))
7361 /* make sure SQ entry isn't read before tail */
7362 ret = left = min3(nr, ctx->sq_entries, entries);
7363 io_get_task_refs(left);
7364 io_submit_state_start(&ctx->submit_state, left);
7367 const struct io_uring_sqe *sqe;
7368 struct io_kiocb *req;
7370 if (unlikely(!io_alloc_req_refill(ctx)))
7372 req = io_alloc_req(ctx);
7373 sqe = io_get_sqe(ctx);
7374 if (unlikely(!sqe)) {
7375 io_req_add_to_cache(req, ctx);
7380 * Continue submitting even for sqe failure if the
7381 * ring was setup with IORING_SETUP_SUBMIT_ALL
7383 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
7384 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
7390 if (unlikely(left)) {
7392 /* try again if it submitted nothing and can't allocate a req */
7393 if (!ret && io_req_cache_empty(ctx))
7395 current->io_uring->cached_refs += left;
7398 io_submit_state_end(ctx);
7399 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7400 io_commit_sqring(ctx);
7404 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7406 return READ_ONCE(sqd->state);
7409 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7411 unsigned int to_submit;
7414 to_submit = io_sqring_entries(ctx);
7415 /* if we're handling multiple rings, cap submit size for fairness */
7416 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7417 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7419 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7420 const struct cred *creds = NULL;
7422 if (ctx->sq_creds != current_cred())
7423 creds = override_creds(ctx->sq_creds);
7425 mutex_lock(&ctx->uring_lock);
7426 if (!wq_list_empty(&ctx->iopoll_list))
7427 io_do_iopoll(ctx, true);
7430 * Don't submit if refs are dying, good for io_uring_register(),
7431 * but also it is relied upon by io_ring_exit_work()
7433 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7434 !(ctx->flags & IORING_SETUP_R_DISABLED))
7435 ret = io_submit_sqes(ctx, to_submit);
7436 mutex_unlock(&ctx->uring_lock);
7438 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7439 wake_up(&ctx->sqo_sq_wait);
7441 revert_creds(creds);
7447 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7449 struct io_ring_ctx *ctx;
7450 unsigned sq_thread_idle = 0;
7452 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7453 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7454 sqd->sq_thread_idle = sq_thread_idle;
7457 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7459 bool did_sig = false;
7460 struct ksignal ksig;
7462 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7463 signal_pending(current)) {
7464 mutex_unlock(&sqd->lock);
7465 if (signal_pending(current))
7466 did_sig = get_signal(&ksig);
7468 mutex_lock(&sqd->lock);
7470 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7473 static int io_sq_thread(void *data)
7475 struct io_sq_data *sqd = data;
7476 struct io_ring_ctx *ctx;
7477 unsigned long timeout = 0;
7478 char buf[TASK_COMM_LEN];
7481 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7482 set_task_comm(current, buf);
7484 if (sqd->sq_cpu != -1)
7485 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7487 set_cpus_allowed_ptr(current, cpu_online_mask);
7488 current->flags |= PF_NO_SETAFFINITY;
7490 audit_alloc_kernel(current);
7492 mutex_lock(&sqd->lock);
7494 bool cap_entries, sqt_spin = false;
7496 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7497 if (io_sqd_handle_event(sqd))
7499 timeout = jiffies + sqd->sq_thread_idle;
7502 cap_entries = !list_is_singular(&sqd->ctx_list);
7503 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7504 int ret = __io_sq_thread(ctx, cap_entries);
7506 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7509 if (io_run_task_work())
7512 if (sqt_spin || !time_after(jiffies, timeout)) {
7515 timeout = jiffies + sqd->sq_thread_idle;
7519 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7520 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
7521 bool needs_sched = true;
7523 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7524 atomic_or(IORING_SQ_NEED_WAKEUP,
7525 &ctx->rings->sq_flags);
7526 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7527 !wq_list_empty(&ctx->iopoll_list)) {
7528 needs_sched = false;
7533 * Ensure the store of the wakeup flag is not
7534 * reordered with the load of the SQ tail
7536 smp_mb__after_atomic();
7538 if (io_sqring_entries(ctx)) {
7539 needs_sched = false;
7545 mutex_unlock(&sqd->lock);
7547 mutex_lock(&sqd->lock);
7549 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7550 atomic_andnot(IORING_SQ_NEED_WAKEUP,
7551 &ctx->rings->sq_flags);
7554 finish_wait(&sqd->wait, &wait);
7555 timeout = jiffies + sqd->sq_thread_idle;
7558 io_uring_cancel_generic(true, sqd);
7560 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7561 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
7563 mutex_unlock(&sqd->lock);
7565 audit_free(current);
7567 complete(&sqd->exited);
7571 struct io_wait_queue {
7572 struct wait_queue_entry wq;
7573 struct io_ring_ctx *ctx;
7575 unsigned nr_timeouts;
7578 static inline bool io_should_wake(struct io_wait_queue *iowq)
7580 struct io_ring_ctx *ctx = iowq->ctx;
7581 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7584 * Wake up if we have enough events, or if a timeout occurred since we
7585 * started waiting. For timeouts, we always want to return to userspace,
7586 * regardless of event count.
7588 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7591 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7592 int wake_flags, void *key)
7594 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7598 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7599 * the task, and the next invocation will do it.
7601 if (io_should_wake(iowq) ||
7602 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
7603 return autoremove_wake_function(curr, mode, wake_flags, key);
7607 static int io_run_task_work_sig(void)
7609 if (io_run_task_work())
7611 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7612 return -ERESTARTSYS;
7613 if (task_sigpending(current))
7618 /* when returns >0, the caller should retry */
7619 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7620 struct io_wait_queue *iowq,
7624 unsigned long check_cq;
7626 /* make sure we run task_work before checking for signals */
7627 ret = io_run_task_work_sig();
7628 if (ret || io_should_wake(iowq))
7630 check_cq = READ_ONCE(ctx->check_cq);
7631 /* let the caller flush overflows, retry */
7632 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
7634 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
7636 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
7642 * Wait until events become available, if we don't already have some. The
7643 * application must reap them itself, as they reside on the shared cq ring.
7645 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7646 const sigset_t __user *sig, size_t sigsz,
7647 struct __kernel_timespec __user *uts)
7649 struct io_wait_queue iowq;
7650 struct io_rings *rings = ctx->rings;
7651 ktime_t timeout = KTIME_MAX;
7655 io_cqring_overflow_flush(ctx);
7656 if (io_cqring_events(ctx) >= min_events)
7658 if (!io_run_task_work())
7663 #ifdef CONFIG_COMPAT
7664 if (in_compat_syscall())
7665 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7669 ret = set_user_sigmask(sig, sigsz);
7676 struct timespec64 ts;
7678 if (get_timespec64(&ts, uts))
7680 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7683 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7684 iowq.wq.private = current;
7685 INIT_LIST_HEAD(&iowq.wq.entry);
7687 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7688 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7690 trace_io_uring_cqring_wait(ctx, min_events);
7692 /* if we can't even flush overflow, don't wait for more */
7693 if (!io_cqring_overflow_flush(ctx)) {
7697 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7698 TASK_INTERRUPTIBLE);
7699 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
7703 finish_wait(&ctx->cq_wait, &iowq.wq);
7704 restore_saved_sigmask_unless(ret == -EINTR);
7706 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7709 static void io_free_page_table(void **table, size_t size)
7711 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7713 for (i = 0; i < nr_tables; i++)
7718 static __cold void **io_alloc_page_table(size_t size)
7720 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7721 size_t init_size = size;
7724 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7728 for (i = 0; i < nr_tables; i++) {
7729 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7731 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7733 io_free_page_table(table, init_size);
7741 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7743 percpu_ref_exit(&ref_node->refs);
7747 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7749 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7750 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7751 unsigned long flags;
7752 bool first_add = false;
7753 unsigned long delay = HZ;
7755 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7758 /* if we are mid-quiesce then do not delay */
7759 if (node->rsrc_data->quiesce)
7762 while (!list_empty(&ctx->rsrc_ref_list)) {
7763 node = list_first_entry(&ctx->rsrc_ref_list,
7764 struct io_rsrc_node, node);
7765 /* recycle ref nodes in order */
7768 list_del(&node->node);
7769 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7771 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7774 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7777 static struct io_rsrc_node *io_rsrc_node_alloc(void)
7779 struct io_rsrc_node *ref_node;
7781 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7785 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7790 INIT_LIST_HEAD(&ref_node->node);
7791 INIT_LIST_HEAD(&ref_node->rsrc_list);
7792 ref_node->done = false;
7796 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7797 struct io_rsrc_data *data_to_kill)
7798 __must_hold(&ctx->uring_lock)
7800 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7801 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7803 io_rsrc_refs_drop(ctx);
7806 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7808 rsrc_node->rsrc_data = data_to_kill;
7809 spin_lock_irq(&ctx->rsrc_ref_lock);
7810 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7811 spin_unlock_irq(&ctx->rsrc_ref_lock);
7813 atomic_inc(&data_to_kill->refs);
7814 percpu_ref_kill(&rsrc_node->refs);
7815 ctx->rsrc_node = NULL;
7818 if (!ctx->rsrc_node) {
7819 ctx->rsrc_node = ctx->rsrc_backup_node;
7820 ctx->rsrc_backup_node = NULL;
7824 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7826 if (ctx->rsrc_backup_node)
7828 ctx->rsrc_backup_node = io_rsrc_node_alloc();
7829 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7832 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
7833 struct io_ring_ctx *ctx)
7837 /* As we may drop ->uring_lock, other task may have started quiesce */
7841 data->quiesce = true;
7843 ret = io_rsrc_node_switch_start(ctx);
7846 io_rsrc_node_switch(ctx, data);
7848 /* kill initial ref, already quiesced if zero */
7849 if (atomic_dec_and_test(&data->refs))
7851 mutex_unlock(&ctx->uring_lock);
7852 flush_delayed_work(&ctx->rsrc_put_work);
7853 ret = wait_for_completion_interruptible(&data->done);
7855 mutex_lock(&ctx->uring_lock);
7856 if (atomic_read(&data->refs) > 0) {
7858 * it has been revived by another thread while
7861 mutex_unlock(&ctx->uring_lock);
7867 atomic_inc(&data->refs);
7868 /* wait for all works potentially completing data->done */
7869 flush_delayed_work(&ctx->rsrc_put_work);
7870 reinit_completion(&data->done);
7872 ret = io_run_task_work_sig();
7873 mutex_lock(&ctx->uring_lock);
7875 data->quiesce = false;
7880 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7882 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7883 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7885 return &data->tags[table_idx][off];
7888 static void io_rsrc_data_free(struct io_rsrc_data *data)
7890 size_t size = data->nr * sizeof(data->tags[0][0]);
7893 io_free_page_table((void **)data->tags, size);
7897 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7898 u64 __user *utags, unsigned nr,
7899 struct io_rsrc_data **pdata)
7901 struct io_rsrc_data *data;
7905 data = kzalloc(sizeof(*data), GFP_KERNEL);
7908 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7916 data->do_put = do_put;
7919 for (i = 0; i < nr; i++) {
7920 u64 *tag_slot = io_get_tag_slot(data, i);
7922 if (copy_from_user(tag_slot, &utags[i],
7928 atomic_set(&data->refs, 1);
7929 init_completion(&data->done);
7933 io_rsrc_data_free(data);
7937 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7939 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7940 GFP_KERNEL_ACCOUNT);
7941 if (unlikely(!table->files))
7944 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
7945 if (unlikely(!table->bitmap)) {
7946 kvfree(table->files);
7953 static void io_free_file_tables(struct io_file_table *table)
7955 kvfree(table->files);
7956 bitmap_free(table->bitmap);
7957 table->files = NULL;
7958 table->bitmap = NULL;
7961 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
7963 WARN_ON_ONCE(test_bit(bit, table->bitmap));
7964 __set_bit(bit, table->bitmap);
7965 table->alloc_hint = bit + 1;
7968 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
7970 __clear_bit(bit, table->bitmap);
7971 table->alloc_hint = bit;
7974 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7976 #if !defined(IO_URING_SCM_ALL)
7979 for (i = 0; i < ctx->nr_user_files; i++) {
7980 struct file *file = io_file_from_index(ctx, i);
7984 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
7986 io_file_bitmap_clear(&ctx->file_table, i);
7991 #if defined(CONFIG_UNIX)
7992 if (ctx->ring_sock) {
7993 struct sock *sock = ctx->ring_sock->sk;
7994 struct sk_buff *skb;
7996 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8000 io_free_file_tables(&ctx->file_table);
8001 io_rsrc_data_free(ctx->file_data);
8002 ctx->file_data = NULL;
8003 ctx->nr_user_files = 0;
8006 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8008 unsigned nr = ctx->nr_user_files;
8011 if (!ctx->file_data)
8015 * Quiesce may unlock ->uring_lock, and while it's not held
8016 * prevent new requests using the table.
8018 ctx->nr_user_files = 0;
8019 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8020 ctx->nr_user_files = nr;
8022 __io_sqe_files_unregister(ctx);
8026 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8027 __releases(&sqd->lock)
8029 WARN_ON_ONCE(sqd->thread == current);
8032 * Do the dance but not conditional clear_bit() because it'd race with
8033 * other threads incrementing park_pending and setting the bit.
8035 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8036 if (atomic_dec_return(&sqd->park_pending))
8037 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8038 mutex_unlock(&sqd->lock);
8041 static void io_sq_thread_park(struct io_sq_data *sqd)
8042 __acquires(&sqd->lock)
8044 WARN_ON_ONCE(sqd->thread == current);
8046 atomic_inc(&sqd->park_pending);
8047 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8048 mutex_lock(&sqd->lock);
8050 wake_up_process(sqd->thread);
8053 static void io_sq_thread_stop(struct io_sq_data *sqd)
8055 WARN_ON_ONCE(sqd->thread == current);
8056 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8058 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8059 mutex_lock(&sqd->lock);
8061 wake_up_process(sqd->thread);
8062 mutex_unlock(&sqd->lock);
8063 wait_for_completion(&sqd->exited);
8066 static void io_put_sq_data(struct io_sq_data *sqd)
8068 if (refcount_dec_and_test(&sqd->refs)) {
8069 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8071 io_sq_thread_stop(sqd);
8076 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8078 struct io_sq_data *sqd = ctx->sq_data;
8081 io_sq_thread_park(sqd);
8082 list_del_init(&ctx->sqd_list);
8083 io_sqd_update_thread_idle(sqd);
8084 io_sq_thread_unpark(sqd);
8086 io_put_sq_data(sqd);
8087 ctx->sq_data = NULL;
8091 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8093 struct io_ring_ctx *ctx_attach;
8094 struct io_sq_data *sqd;
8097 f = fdget(p->wq_fd);
8099 return ERR_PTR(-ENXIO);
8100 if (f.file->f_op != &io_uring_fops) {
8102 return ERR_PTR(-EINVAL);
8105 ctx_attach = f.file->private_data;
8106 sqd = ctx_attach->sq_data;
8109 return ERR_PTR(-EINVAL);
8111 if (sqd->task_tgid != current->tgid) {
8113 return ERR_PTR(-EPERM);
8116 refcount_inc(&sqd->refs);
8121 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8124 struct io_sq_data *sqd;
8127 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8128 sqd = io_attach_sq_data(p);
8133 /* fall through for EPERM case, setup new sqd/task */
8134 if (PTR_ERR(sqd) != -EPERM)
8138 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8140 return ERR_PTR(-ENOMEM);
8142 atomic_set(&sqd->park_pending, 0);
8143 refcount_set(&sqd->refs, 1);
8144 INIT_LIST_HEAD(&sqd->ctx_list);
8145 mutex_init(&sqd->lock);
8146 init_waitqueue_head(&sqd->wait);
8147 init_completion(&sqd->exited);
8152 * Ensure the UNIX gc is aware of our file set, so we are certain that
8153 * the io_uring can be safely unregistered on process exit, even if we have
8154 * loops in the file referencing. We account only files that can hold other
8155 * files because otherwise they can't form a loop and so are not interesting
8158 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
8160 #if defined(CONFIG_UNIX)
8161 struct sock *sk = ctx->ring_sock->sk;
8162 struct sk_buff_head *head = &sk->sk_receive_queue;
8163 struct scm_fp_list *fpl;
8164 struct sk_buff *skb;
8166 if (likely(!io_file_need_scm(file)))
8170 * See if we can merge this file into an existing skb SCM_RIGHTS
8171 * file set. If there's no room, fall back to allocating a new skb
8172 * and filling it in.
8174 spin_lock_irq(&head->lock);
8175 skb = skb_peek(head);
8176 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
8177 __skb_unlink(skb, head);
8180 spin_unlock_irq(&head->lock);
8183 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8187 skb = alloc_skb(0, GFP_KERNEL);
8193 fpl->user = get_uid(current_user());
8194 fpl->max = SCM_MAX_FD;
8197 UNIXCB(skb).fp = fpl;
8199 skb->destructor = unix_destruct_scm;
8200 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8203 fpl = UNIXCB(skb).fp;
8204 fpl->fp[fpl->count++] = get_file(file);
8205 unix_inflight(fpl->user, file);
8206 skb_queue_head(head, skb);
8212 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8214 struct file *file = prsrc->file;
8215 #if defined(CONFIG_UNIX)
8216 struct sock *sock = ctx->ring_sock->sk;
8217 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8218 struct sk_buff *skb;
8221 if (!io_file_need_scm(file)) {
8226 __skb_queue_head_init(&list);
8229 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8230 * remove this entry and rearrange the file array.
8232 skb = skb_dequeue(head);
8234 struct scm_fp_list *fp;
8236 fp = UNIXCB(skb).fp;
8237 for (i = 0; i < fp->count; i++) {
8240 if (fp->fp[i] != file)
8243 unix_notinflight(fp->user, fp->fp[i]);
8244 left = fp->count - 1 - i;
8246 memmove(&fp->fp[i], &fp->fp[i + 1],
8247 left * sizeof(struct file *));
8254 __skb_queue_tail(&list, skb);
8264 __skb_queue_tail(&list, skb);
8266 skb = skb_dequeue(head);
8269 if (skb_peek(&list)) {
8270 spin_lock_irq(&head->lock);
8271 while ((skb = __skb_dequeue(&list)) != NULL)
8272 __skb_queue_tail(head, skb);
8273 spin_unlock_irq(&head->lock);
8280 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8282 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8283 struct io_ring_ctx *ctx = rsrc_data->ctx;
8284 struct io_rsrc_put *prsrc, *tmp;
8286 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8287 list_del(&prsrc->list);
8290 if (ctx->flags & IORING_SETUP_IOPOLL)
8291 mutex_lock(&ctx->uring_lock);
8293 spin_lock(&ctx->completion_lock);
8294 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8295 io_commit_cqring(ctx);
8296 spin_unlock(&ctx->completion_lock);
8297 io_cqring_ev_posted(ctx);
8299 if (ctx->flags & IORING_SETUP_IOPOLL)
8300 mutex_unlock(&ctx->uring_lock);
8303 rsrc_data->do_put(ctx, prsrc);
8307 io_rsrc_node_destroy(ref_node);
8308 if (atomic_dec_and_test(&rsrc_data->refs))
8309 complete(&rsrc_data->done);
8312 static void io_rsrc_put_work(struct work_struct *work)
8314 struct io_ring_ctx *ctx;
8315 struct llist_node *node;
8317 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8318 node = llist_del_all(&ctx->rsrc_put_llist);
8321 struct io_rsrc_node *ref_node;
8322 struct llist_node *next = node->next;
8324 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8325 __io_rsrc_put_work(ref_node);
8330 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8331 unsigned nr_args, u64 __user *tags)
8333 __s32 __user *fds = (__s32 __user *) arg;
8342 if (nr_args > IORING_MAX_FIXED_FILES)
8344 if (nr_args > rlimit(RLIMIT_NOFILE))
8346 ret = io_rsrc_node_switch_start(ctx);
8349 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8354 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
8355 io_rsrc_data_free(ctx->file_data);
8356 ctx->file_data = NULL;
8360 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8361 struct io_fixed_file *file_slot;
8363 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
8367 /* allow sparse sets */
8368 if (!fds || fd == -1) {
8370 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8377 if (unlikely(!file))
8381 * Don't allow io_uring instances to be registered. If UNIX
8382 * isn't enabled, then this causes a reference cycle and this
8383 * instance can never get freed. If UNIX is enabled we'll
8384 * handle it just fine, but there's still no point in allowing
8385 * a ring fd as it doesn't support regular read/write anyway.
8387 if (file->f_op == &io_uring_fops) {
8391 ret = io_scm_file_account(ctx, file);
8396 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8397 io_fixed_file_set(file_slot, file);
8398 io_file_bitmap_set(&ctx->file_table, i);
8401 io_rsrc_node_switch(ctx, NULL);
8404 __io_sqe_files_unregister(ctx);
8408 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8409 struct io_rsrc_node *node, void *rsrc)
8411 u64 *tag_slot = io_get_tag_slot(data, idx);
8412 struct io_rsrc_put *prsrc;
8414 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8418 prsrc->tag = *tag_slot;
8421 list_add(&prsrc->list, &node->rsrc_list);
8425 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8426 unsigned int issue_flags, u32 slot_index)
8427 __must_hold(&req->ctx->uring_lock)
8429 struct io_ring_ctx *ctx = req->ctx;
8430 bool needs_switch = false;
8431 struct io_fixed_file *file_slot;
8434 if (file->f_op == &io_uring_fops)
8436 if (!ctx->file_data)
8438 if (slot_index >= ctx->nr_user_files)
8441 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8442 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8444 if (file_slot->file_ptr) {
8445 struct file *old_file;
8447 ret = io_rsrc_node_switch_start(ctx);
8451 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8452 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8453 ctx->rsrc_node, old_file);
8456 file_slot->file_ptr = 0;
8457 io_file_bitmap_clear(&ctx->file_table, slot_index);
8458 needs_switch = true;
8461 ret = io_scm_file_account(ctx, file);
8463 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8464 io_fixed_file_set(file_slot, file);
8465 io_file_bitmap_set(&ctx->file_table, slot_index);
8469 io_rsrc_node_switch(ctx, ctx->file_data);
8475 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
8476 unsigned int offset)
8478 struct io_ring_ctx *ctx = req->ctx;
8479 struct io_fixed_file *file_slot;
8483 io_ring_submit_lock(ctx, issue_flags);
8485 if (unlikely(!ctx->file_data))
8488 if (offset >= ctx->nr_user_files)
8490 ret = io_rsrc_node_switch_start(ctx);
8494 offset = array_index_nospec(offset, ctx->nr_user_files);
8495 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8497 if (!file_slot->file_ptr)
8500 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8501 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8505 file_slot->file_ptr = 0;
8506 io_file_bitmap_clear(&ctx->file_table, offset);
8507 io_rsrc_node_switch(ctx, ctx->file_data);
8510 io_ring_submit_unlock(ctx, issue_flags);
8514 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8516 struct io_close *close = io_kiocb_to_cmd(req);
8518 return __io_close_fixed(req, issue_flags, close->file_slot - 1);
8521 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8522 struct io_uring_rsrc_update2 *up,
8525 u64 __user *tags = u64_to_user_ptr(up->tags);
8526 __s32 __user *fds = u64_to_user_ptr(up->data);
8527 struct io_rsrc_data *data = ctx->file_data;
8528 struct io_fixed_file *file_slot;
8532 bool needs_switch = false;
8534 if (!ctx->file_data)
8536 if (up->offset + nr_args > ctx->nr_user_files)
8539 for (done = 0; done < nr_args; done++) {
8542 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8543 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8547 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8551 if (fd == IORING_REGISTER_FILES_SKIP)
8554 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8555 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8557 if (file_slot->file_ptr) {
8558 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8559 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
8562 file_slot->file_ptr = 0;
8563 io_file_bitmap_clear(&ctx->file_table, i);
8564 needs_switch = true;
8573 * Don't allow io_uring instances to be registered. If
8574 * UNIX isn't enabled, then this causes a reference
8575 * cycle and this instance can never get freed. If UNIX
8576 * is enabled we'll handle it just fine, but there's
8577 * still no point in allowing a ring fd as it doesn't
8578 * support regular read/write anyway.
8580 if (file->f_op == &io_uring_fops) {
8585 err = io_scm_file_account(ctx, file);
8590 *io_get_tag_slot(data, i) = tag;
8591 io_fixed_file_set(file_slot, file);
8592 io_file_bitmap_set(&ctx->file_table, i);
8597 io_rsrc_node_switch(ctx, data);
8598 return done ? done : err;
8601 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8602 struct task_struct *task)
8604 struct io_wq_hash *hash;
8605 struct io_wq_data data;
8606 unsigned int concurrency;
8608 mutex_lock(&ctx->uring_lock);
8609 hash = ctx->hash_map;
8611 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8613 mutex_unlock(&ctx->uring_lock);
8614 return ERR_PTR(-ENOMEM);
8616 refcount_set(&hash->refs, 1);
8617 init_waitqueue_head(&hash->wait);
8618 ctx->hash_map = hash;
8620 mutex_unlock(&ctx->uring_lock);
8624 data.free_work = io_wq_free_work;
8625 data.do_work = io_wq_submit_work;
8627 /* Do QD, or 4 * CPUS, whatever is smallest */
8628 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8630 return io_wq_create(concurrency, &data);
8633 static __cold int io_uring_alloc_task_context(struct task_struct *task,
8634 struct io_ring_ctx *ctx)
8636 struct io_uring_task *tctx;
8639 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8640 if (unlikely(!tctx))
8643 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
8644 sizeof(struct file *), GFP_KERNEL);
8645 if (unlikely(!tctx->registered_rings)) {
8650 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8651 if (unlikely(ret)) {
8652 kfree(tctx->registered_rings);
8657 tctx->io_wq = io_init_wq_offload(ctx, task);
8658 if (IS_ERR(tctx->io_wq)) {
8659 ret = PTR_ERR(tctx->io_wq);
8660 percpu_counter_destroy(&tctx->inflight);
8661 kfree(tctx->registered_rings);
8667 init_waitqueue_head(&tctx->wait);
8668 atomic_set(&tctx->in_idle, 0);
8669 atomic_set(&tctx->inflight_tracked, 0);
8670 task->io_uring = tctx;
8671 spin_lock_init(&tctx->task_lock);
8672 INIT_WQ_LIST(&tctx->task_list);
8673 INIT_WQ_LIST(&tctx->prio_task_list);
8674 init_task_work(&tctx->task_work, tctx_task_work);
8678 void __io_uring_free(struct task_struct *tsk)
8680 struct io_uring_task *tctx = tsk->io_uring;
8682 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8683 WARN_ON_ONCE(tctx->io_wq);
8684 WARN_ON_ONCE(tctx->cached_refs);
8686 kfree(tctx->registered_rings);
8687 percpu_counter_destroy(&tctx->inflight);
8689 tsk->io_uring = NULL;
8692 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
8693 struct io_uring_params *p)
8697 /* Retain compatibility with failing for an invalid attach attempt */
8698 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8699 IORING_SETUP_ATTACH_WQ) {
8702 f = fdget(p->wq_fd);
8705 if (f.file->f_op != &io_uring_fops) {
8711 if (ctx->flags & IORING_SETUP_SQPOLL) {
8712 struct task_struct *tsk;
8713 struct io_sq_data *sqd;
8716 ret = security_uring_sqpoll();
8720 sqd = io_get_sq_data(p, &attached);
8726 ctx->sq_creds = get_current_cred();
8728 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8729 if (!ctx->sq_thread_idle)
8730 ctx->sq_thread_idle = HZ;
8732 io_sq_thread_park(sqd);
8733 list_add(&ctx->sqd_list, &sqd->ctx_list);
8734 io_sqd_update_thread_idle(sqd);
8735 /* don't attach to a dying SQPOLL thread, would be racy */
8736 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8737 io_sq_thread_unpark(sqd);
8744 if (p->flags & IORING_SETUP_SQ_AFF) {
8745 int cpu = p->sq_thread_cpu;
8748 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8755 sqd->task_pid = current->pid;
8756 sqd->task_tgid = current->tgid;
8757 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8764 ret = io_uring_alloc_task_context(tsk, ctx);
8765 wake_up_new_task(tsk);
8768 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8769 /* Can't have SQ_AFF without SQPOLL */
8776 complete(&ctx->sq_data->exited);
8778 io_sq_thread_finish(ctx);
8782 static inline void __io_unaccount_mem(struct user_struct *user,
8783 unsigned long nr_pages)
8785 atomic_long_sub(nr_pages, &user->locked_vm);
8788 static inline int __io_account_mem(struct user_struct *user,
8789 unsigned long nr_pages)
8791 unsigned long page_limit, cur_pages, new_pages;
8793 /* Don't allow more pages than we can safely lock */
8794 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8797 cur_pages = atomic_long_read(&user->locked_vm);
8798 new_pages = cur_pages + nr_pages;
8799 if (new_pages > page_limit)
8801 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8802 new_pages) != cur_pages);
8807 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8810 __io_unaccount_mem(ctx->user, nr_pages);
8812 if (ctx->mm_account)
8813 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8816 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8821 ret = __io_account_mem(ctx->user, nr_pages);
8826 if (ctx->mm_account)
8827 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8832 static void io_mem_free(void *ptr)
8839 page = virt_to_head_page(ptr);
8840 if (put_page_testzero(page))
8841 free_compound_page(page);
8844 static void *io_mem_alloc(size_t size)
8846 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
8848 return (void *) __get_free_pages(gfp, get_order(size));
8851 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
8852 unsigned int cq_entries, size_t *sq_offset)
8854 struct io_rings *rings;
8855 size_t off, sq_array_size;
8857 off = struct_size(rings, cqes, cq_entries);
8858 if (off == SIZE_MAX)
8860 if (ctx->flags & IORING_SETUP_CQE32) {
8861 if (check_shl_overflow(off, 1, &off))
8866 off = ALIGN(off, SMP_CACHE_BYTES);
8874 sq_array_size = array_size(sizeof(u32), sq_entries);
8875 if (sq_array_size == SIZE_MAX)
8878 if (check_add_overflow(off, sq_array_size, &off))
8884 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8886 struct io_mapped_ubuf *imu = *slot;
8889 if (imu != ctx->dummy_ubuf) {
8890 for (i = 0; i < imu->nr_bvecs; i++)
8891 unpin_user_page(imu->bvec[i].bv_page);
8892 if (imu->acct_pages)
8893 io_unaccount_mem(ctx, imu->acct_pages);
8899 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8901 io_buffer_unmap(ctx, &prsrc->buf);
8905 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8909 for (i = 0; i < ctx->nr_user_bufs; i++)
8910 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8911 kfree(ctx->user_bufs);
8912 io_rsrc_data_free(ctx->buf_data);
8913 ctx->user_bufs = NULL;
8914 ctx->buf_data = NULL;
8915 ctx->nr_user_bufs = 0;
8918 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8920 unsigned nr = ctx->nr_user_bufs;
8927 * Quiesce may unlock ->uring_lock, and while it's not held
8928 * prevent new requests using the table.
8930 ctx->nr_user_bufs = 0;
8931 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8932 ctx->nr_user_bufs = nr;
8934 __io_sqe_buffers_unregister(ctx);
8938 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8939 void __user *arg, unsigned index)
8941 struct iovec __user *src;
8943 #ifdef CONFIG_COMPAT
8945 struct compat_iovec __user *ciovs;
8946 struct compat_iovec ciov;
8948 ciovs = (struct compat_iovec __user *) arg;
8949 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8952 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8953 dst->iov_len = ciov.iov_len;
8957 src = (struct iovec __user *) arg;
8958 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8964 * Not super efficient, but this is just a registration time. And we do cache
8965 * the last compound head, so generally we'll only do a full search if we don't
8968 * We check if the given compound head page has already been accounted, to
8969 * avoid double accounting it. This allows us to account the full size of the
8970 * page, not just the constituent pages of a huge page.
8972 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8973 int nr_pages, struct page *hpage)
8977 /* check current page array */
8978 for (i = 0; i < nr_pages; i++) {
8979 if (!PageCompound(pages[i]))
8981 if (compound_head(pages[i]) == hpage)
8985 /* check previously registered pages */
8986 for (i = 0; i < ctx->nr_user_bufs; i++) {
8987 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8989 for (j = 0; j < imu->nr_bvecs; j++) {
8990 if (!PageCompound(imu->bvec[j].bv_page))
8992 if (compound_head(imu->bvec[j].bv_page) == hpage)
9000 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9001 int nr_pages, struct io_mapped_ubuf *imu,
9002 struct page **last_hpage)
9006 imu->acct_pages = 0;
9007 for (i = 0; i < nr_pages; i++) {
9008 if (!PageCompound(pages[i])) {
9013 hpage = compound_head(pages[i]);
9014 if (hpage == *last_hpage)
9016 *last_hpage = hpage;
9017 if (headpage_already_acct(ctx, pages, i, hpage))
9019 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9023 if (!imu->acct_pages)
9026 ret = io_account_mem(ctx, imu->acct_pages);
9028 imu->acct_pages = 0;
9032 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
9035 unsigned long start, end, nr_pages;
9036 struct vm_area_struct **vmas = NULL;
9037 struct page **pages = NULL;
9038 int i, pret, ret = -ENOMEM;
9040 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9041 start = ubuf >> PAGE_SHIFT;
9042 nr_pages = end - start;
9044 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9048 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9054 mmap_read_lock(current->mm);
9055 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9057 if (pret == nr_pages) {
9058 /* don't support file backed memory */
9059 for (i = 0; i < nr_pages; i++) {
9060 struct vm_area_struct *vma = vmas[i];
9062 if (vma_is_shmem(vma))
9065 !is_file_hugepages(vma->vm_file)) {
9072 ret = pret < 0 ? pret : -EFAULT;
9074 mmap_read_unlock(current->mm);
9077 * if we did partial map, or found file backed vmas,
9078 * release any pages we did get
9081 unpin_user_pages(pages, pret);
9089 pages = ERR_PTR(ret);
9094 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9095 struct io_mapped_ubuf **pimu,
9096 struct page **last_hpage)
9098 struct io_mapped_ubuf *imu = NULL;
9099 struct page **pages = NULL;
9102 int ret, nr_pages, i;
9104 if (!iov->iov_base) {
9105 *pimu = ctx->dummy_ubuf;
9112 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
9114 if (IS_ERR(pages)) {
9115 ret = PTR_ERR(pages);
9120 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9124 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
9126 unpin_user_pages(pages, nr_pages);
9130 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
9131 size = iov->iov_len;
9132 for (i = 0; i < nr_pages; i++) {
9135 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9136 imu->bvec[i].bv_page = pages[i];
9137 imu->bvec[i].bv_len = vec_len;
9138 imu->bvec[i].bv_offset = off;
9142 /* store original address for later verification */
9143 imu->ubuf = (unsigned long) iov->iov_base;
9144 imu->ubuf_end = imu->ubuf + iov->iov_len;
9145 imu->nr_bvecs = nr_pages;
9155 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9157 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9158 return ctx->user_bufs ? 0 : -ENOMEM;
9161 static int io_buffer_validate(struct iovec *iov)
9163 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9166 * Don't impose further limits on the size and buffer
9167 * constraints here, we'll -EINVAL later when IO is
9168 * submitted if they are wrong.
9171 return iov->iov_len ? -EFAULT : 0;
9175 /* arbitrary limit, but we need something */
9176 if (iov->iov_len > SZ_1G)
9179 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9185 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9186 unsigned int nr_args, u64 __user *tags)
9188 struct page *last_hpage = NULL;
9189 struct io_rsrc_data *data;
9195 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9197 ret = io_rsrc_node_switch_start(ctx);
9200 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9203 ret = io_buffers_map_alloc(ctx, nr_args);
9205 io_rsrc_data_free(data);
9209 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9211 ret = io_copy_iov(ctx, &iov, arg, i);
9214 ret = io_buffer_validate(&iov);
9218 memset(&iov, 0, sizeof(iov));
9221 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9226 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9232 WARN_ON_ONCE(ctx->buf_data);
9234 ctx->buf_data = data;
9236 __io_sqe_buffers_unregister(ctx);
9238 io_rsrc_node_switch(ctx, NULL);
9242 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9243 struct io_uring_rsrc_update2 *up,
9244 unsigned int nr_args)
9246 u64 __user *tags = u64_to_user_ptr(up->tags);
9247 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9248 struct page *last_hpage = NULL;
9249 bool needs_switch = false;
9255 if (up->offset + nr_args > ctx->nr_user_bufs)
9258 for (done = 0; done < nr_args; done++) {
9259 struct io_mapped_ubuf *imu;
9260 int offset = up->offset + done;
9263 err = io_copy_iov(ctx, &iov, iovs, done);
9266 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9270 err = io_buffer_validate(&iov);
9273 if (!iov.iov_base && tag) {
9277 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9281 i = array_index_nospec(offset, ctx->nr_user_bufs);
9282 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9283 err = io_queue_rsrc_removal(ctx->buf_data, i,
9284 ctx->rsrc_node, ctx->user_bufs[i]);
9285 if (unlikely(err)) {
9286 io_buffer_unmap(ctx, &imu);
9289 ctx->user_bufs[i] = NULL;
9290 needs_switch = true;
9293 ctx->user_bufs[i] = imu;
9294 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9298 io_rsrc_node_switch(ctx, ctx->buf_data);
9299 return done ? done : err;
9302 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9303 unsigned int eventfd_async)
9305 struct io_ev_fd *ev_fd;
9306 __s32 __user *fds = arg;
9309 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9310 lockdep_is_held(&ctx->uring_lock));
9314 if (copy_from_user(&fd, fds, sizeof(*fds)))
9317 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9321 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9322 if (IS_ERR(ev_fd->cq_ev_fd)) {
9323 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9327 ev_fd->eventfd_async = eventfd_async;
9328 ctx->has_evfd = true;
9329 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9333 static void io_eventfd_put(struct rcu_head *rcu)
9335 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9337 eventfd_ctx_put(ev_fd->cq_ev_fd);
9341 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9343 struct io_ev_fd *ev_fd;
9345 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9346 lockdep_is_held(&ctx->uring_lock));
9348 ctx->has_evfd = false;
9349 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9350 call_rcu(&ev_fd->rcu, io_eventfd_put);
9357 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9359 struct io_buffer_list *bl;
9360 unsigned long index;
9363 for (i = 0; i < BGID_ARRAY; i++) {
9366 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
9369 xa_for_each(&ctx->io_bl_xa, index, bl) {
9370 xa_erase(&ctx->io_bl_xa, bl->bgid);
9371 __io_remove_buffers(ctx, bl, -1U);
9375 while (!list_empty(&ctx->io_buffers_pages)) {
9378 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9379 list_del_init(&page->lru);
9384 static void io_req_caches_free(struct io_ring_ctx *ctx)
9386 struct io_submit_state *state = &ctx->submit_state;
9389 mutex_lock(&ctx->uring_lock);
9390 io_flush_cached_locked_reqs(ctx, state);
9392 while (!io_req_cache_empty(ctx)) {
9393 struct io_wq_work_node *node;
9394 struct io_kiocb *req;
9396 node = wq_stack_extract(&state->free_list);
9397 req = container_of(node, struct io_kiocb, comp_list);
9398 kmem_cache_free(req_cachep, req);
9402 percpu_ref_put_many(&ctx->refs, nr);
9403 mutex_unlock(&ctx->uring_lock);
9406 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9408 if (data && !atomic_dec_and_test(&data->refs))
9409 wait_for_completion(&data->done);
9412 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
9414 struct async_poll *apoll;
9416 while (!list_empty(&ctx->apoll_cache)) {
9417 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
9419 list_del(&apoll->poll.wait.entry);
9424 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9426 io_sq_thread_finish(ctx);
9428 if (ctx->mm_account) {
9429 mmdrop(ctx->mm_account);
9430 ctx->mm_account = NULL;
9433 io_rsrc_refs_drop(ctx);
9434 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9435 io_wait_rsrc_data(ctx->buf_data);
9436 io_wait_rsrc_data(ctx->file_data);
9438 mutex_lock(&ctx->uring_lock);
9440 __io_sqe_buffers_unregister(ctx);
9442 __io_sqe_files_unregister(ctx);
9444 __io_cqring_overflow_flush(ctx, true);
9445 io_eventfd_unregister(ctx);
9446 io_flush_apoll_cache(ctx);
9447 mutex_unlock(&ctx->uring_lock);
9448 io_destroy_buffers(ctx);
9450 put_cred(ctx->sq_creds);
9452 /* there are no registered resources left, nobody uses it */
9454 io_rsrc_node_destroy(ctx->rsrc_node);
9455 if (ctx->rsrc_backup_node)
9456 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9457 flush_delayed_work(&ctx->rsrc_put_work);
9458 flush_delayed_work(&ctx->fallback_work);
9460 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9461 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9463 #if defined(CONFIG_UNIX)
9464 if (ctx->ring_sock) {
9465 ctx->ring_sock->file = NULL; /* so that iput() is called */
9466 sock_release(ctx->ring_sock);
9469 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9471 io_mem_free(ctx->rings);
9472 io_mem_free(ctx->sq_sqes);
9474 percpu_ref_exit(&ctx->refs);
9475 free_uid(ctx->user);
9476 io_req_caches_free(ctx);
9478 io_wq_put_hash(ctx->hash_map);
9479 kfree(ctx->cancel_hash);
9480 kfree(ctx->dummy_ubuf);
9482 xa_destroy(&ctx->io_bl_xa);
9486 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9488 struct io_ring_ctx *ctx = file->private_data;
9491 poll_wait(file, &ctx->cq_wait, wait);
9493 * synchronizes with barrier from wq_has_sleeper call in
9497 if (!io_sqring_full(ctx))
9498 mask |= EPOLLOUT | EPOLLWRNORM;
9501 * Don't flush cqring overflow list here, just do a simple check.
9502 * Otherwise there could possible be ABBA deadlock:
9505 * lock(&ctx->uring_lock);
9507 * lock(&ctx->uring_lock);
9510 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9511 * pushs them to do the flush.
9513 if (io_cqring_events(ctx) ||
9514 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
9515 mask |= EPOLLIN | EPOLLRDNORM;
9520 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9522 const struct cred *creds;
9524 creds = xa_erase(&ctx->personalities, id);
9533 struct io_tctx_exit {
9534 struct callback_head task_work;
9535 struct completion completion;
9536 struct io_ring_ctx *ctx;
9539 static __cold void io_tctx_exit_cb(struct callback_head *cb)
9541 struct io_uring_task *tctx = current->io_uring;
9542 struct io_tctx_exit *work;
9544 work = container_of(cb, struct io_tctx_exit, task_work);
9546 * When @in_idle, we're in cancellation and it's racy to remove the
9547 * node. It'll be removed by the end of cancellation, just ignore it.
9549 if (!atomic_read(&tctx->in_idle))
9550 io_uring_del_tctx_node((unsigned long)work->ctx);
9551 complete(&work->completion);
9554 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9556 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9558 return req->ctx == data;
9561 static __cold void io_ring_exit_work(struct work_struct *work)
9563 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9564 unsigned long timeout = jiffies + HZ * 60 * 5;
9565 unsigned long interval = HZ / 20;
9566 struct io_tctx_exit exit;
9567 struct io_tctx_node *node;
9571 * If we're doing polled IO and end up having requests being
9572 * submitted async (out-of-line), then completions can come in while
9573 * we're waiting for refs to drop. We need to reap these manually,
9574 * as nobody else will be looking for them.
9577 io_uring_try_cancel_requests(ctx, NULL, true);
9579 struct io_sq_data *sqd = ctx->sq_data;
9580 struct task_struct *tsk;
9582 io_sq_thread_park(sqd);
9584 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9585 io_wq_cancel_cb(tsk->io_uring->io_wq,
9586 io_cancel_ctx_cb, ctx, true);
9587 io_sq_thread_unpark(sqd);
9590 io_req_caches_free(ctx);
9592 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9593 /* there is little hope left, don't run it too often */
9596 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9598 init_completion(&exit.completion);
9599 init_task_work(&exit.task_work, io_tctx_exit_cb);
9602 * Some may use context even when all refs and requests have been put,
9603 * and they are free to do so while still holding uring_lock or
9604 * completion_lock, see io_req_task_submit(). Apart from other work,
9605 * this lock/unlock section also waits them to finish.
9607 mutex_lock(&ctx->uring_lock);
9608 while (!list_empty(&ctx->tctx_list)) {
9609 WARN_ON_ONCE(time_after(jiffies, timeout));
9611 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9613 /* don't spin on a single task if cancellation failed */
9614 list_rotate_left(&ctx->tctx_list);
9615 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9616 if (WARN_ON_ONCE(ret))
9619 mutex_unlock(&ctx->uring_lock);
9620 wait_for_completion(&exit.completion);
9621 mutex_lock(&ctx->uring_lock);
9623 mutex_unlock(&ctx->uring_lock);
9624 spin_lock(&ctx->completion_lock);
9625 spin_unlock(&ctx->completion_lock);
9627 io_ring_ctx_free(ctx);
9630 /* Returns true if we found and killed one or more timeouts */
9631 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
9632 struct task_struct *tsk, bool cancel_all)
9634 struct io_timeout *timeout, *tmp;
9637 spin_lock(&ctx->completion_lock);
9638 spin_lock_irq(&ctx->timeout_lock);
9639 list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
9640 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
9642 if (io_match_task(req, tsk, cancel_all)) {
9643 io_kill_timeout(req, -ECANCELED);
9647 spin_unlock_irq(&ctx->timeout_lock);
9648 io_commit_cqring(ctx);
9649 spin_unlock(&ctx->completion_lock);
9651 io_cqring_ev_posted(ctx);
9652 return canceled != 0;
9655 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9657 unsigned long index;
9658 struct creds *creds;
9660 mutex_lock(&ctx->uring_lock);
9661 percpu_ref_kill(&ctx->refs);
9663 __io_cqring_overflow_flush(ctx, true);
9664 xa_for_each(&ctx->personalities, index, creds)
9665 io_unregister_personality(ctx, index);
9666 mutex_unlock(&ctx->uring_lock);
9668 /* failed during ring init, it couldn't have issued any requests */
9670 io_kill_timeouts(ctx, NULL, true);
9671 io_poll_remove_all(ctx, NULL, true);
9672 /* if we failed setting up the ctx, we might not have any rings */
9673 io_iopoll_try_reap_events(ctx);
9676 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9678 * Use system_unbound_wq to avoid spawning tons of event kworkers
9679 * if we're exiting a ton of rings at the same time. It just adds
9680 * noise and overhead, there's no discernable change in runtime
9681 * over using system_wq.
9683 queue_work(system_unbound_wq, &ctx->exit_work);
9686 static int io_uring_release(struct inode *inode, struct file *file)
9688 struct io_ring_ctx *ctx = file->private_data;
9690 file->private_data = NULL;
9691 io_ring_ctx_wait_and_kill(ctx);
9695 struct io_task_cancel {
9696 struct task_struct *task;
9700 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9702 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9703 struct io_task_cancel *cancel = data;
9705 return io_match_task_safe(req, cancel->task, cancel->all);
9708 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9709 struct task_struct *task,
9712 struct io_defer_entry *de;
9715 spin_lock(&ctx->completion_lock);
9716 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9717 if (io_match_task_safe(de->req, task, cancel_all)) {
9718 list_cut_position(&list, &ctx->defer_list, &de->list);
9722 spin_unlock(&ctx->completion_lock);
9723 if (list_empty(&list))
9726 while (!list_empty(&list)) {
9727 de = list_first_entry(&list, struct io_defer_entry, list);
9728 list_del_init(&de->list);
9729 io_req_complete_failed(de->req, -ECANCELED);
9735 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9737 struct io_tctx_node *node;
9738 enum io_wq_cancel cret;
9741 mutex_lock(&ctx->uring_lock);
9742 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9743 struct io_uring_task *tctx = node->task->io_uring;
9746 * io_wq will stay alive while we hold uring_lock, because it's
9747 * killed after ctx nodes, which requires to take the lock.
9749 if (!tctx || !tctx->io_wq)
9751 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9752 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9754 mutex_unlock(&ctx->uring_lock);
9759 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9760 struct task_struct *task,
9763 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9764 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9766 /* failed during ring init, it couldn't have issued any requests */
9771 enum io_wq_cancel cret;
9775 ret |= io_uring_try_cancel_iowq(ctx);
9776 } else if (tctx && tctx->io_wq) {
9778 * Cancels requests of all rings, not only @ctx, but
9779 * it's fine as the task is in exit/exec.
9781 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9783 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9786 /* SQPOLL thread does its own polling */
9787 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9788 (ctx->sq_data && ctx->sq_data->thread == current)) {
9789 while (!wq_list_empty(&ctx->iopoll_list)) {
9790 io_iopoll_try_reap_events(ctx);
9795 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9796 ret |= io_poll_remove_all(ctx, task, cancel_all);
9797 ret |= io_kill_timeouts(ctx, task, cancel_all);
9799 ret |= io_run_task_work();
9806 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9808 struct io_uring_task *tctx = current->io_uring;
9809 struct io_tctx_node *node;
9812 if (unlikely(!tctx)) {
9813 ret = io_uring_alloc_task_context(current, ctx);
9817 tctx = current->io_uring;
9818 if (ctx->iowq_limits_set) {
9819 unsigned int limits[2] = { ctx->iowq_limits[0],
9820 ctx->iowq_limits[1], };
9822 ret = io_wq_max_workers(tctx->io_wq, limits);
9827 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9828 node = kmalloc(sizeof(*node), GFP_KERNEL);
9832 node->task = current;
9834 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9841 mutex_lock(&ctx->uring_lock);
9842 list_add(&node->ctx_node, &ctx->tctx_list);
9843 mutex_unlock(&ctx->uring_lock);
9850 * Note that this task has used io_uring. We use it for cancelation purposes.
9852 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9854 struct io_uring_task *tctx = current->io_uring;
9856 if (likely(tctx && tctx->last == ctx))
9858 return __io_uring_add_tctx_node(ctx);
9862 * Remove this io_uring_file -> task mapping.
9864 static __cold void io_uring_del_tctx_node(unsigned long index)
9866 struct io_uring_task *tctx = current->io_uring;
9867 struct io_tctx_node *node;
9871 node = xa_erase(&tctx->xa, index);
9875 WARN_ON_ONCE(current != node->task);
9876 WARN_ON_ONCE(list_empty(&node->ctx_node));
9878 mutex_lock(&node->ctx->uring_lock);
9879 list_del(&node->ctx_node);
9880 mutex_unlock(&node->ctx->uring_lock);
9882 if (tctx->last == node->ctx)
9887 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
9889 struct io_wq *wq = tctx->io_wq;
9890 struct io_tctx_node *node;
9891 unsigned long index;
9893 xa_for_each(&tctx->xa, index, node) {
9894 io_uring_del_tctx_node(index);
9899 * Must be after io_uring_del_tctx_node() (removes nodes under
9900 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9902 io_wq_put_and_exit(wq);
9907 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9910 return atomic_read(&tctx->inflight_tracked);
9911 return percpu_counter_sum(&tctx->inflight);
9915 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9916 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9918 static __cold void io_uring_cancel_generic(bool cancel_all,
9919 struct io_sq_data *sqd)
9921 struct io_uring_task *tctx = current->io_uring;
9922 struct io_ring_ctx *ctx;
9926 WARN_ON_ONCE(sqd && sqd->thread != current);
9928 if (!current->io_uring)
9931 io_wq_exit_start(tctx->io_wq);
9933 atomic_inc(&tctx->in_idle);
9935 io_uring_drop_tctx_refs(current);
9936 /* read completions before cancelations */
9937 inflight = tctx_inflight(tctx, !cancel_all);
9942 struct io_tctx_node *node;
9943 unsigned long index;
9945 xa_for_each(&tctx->xa, index, node) {
9946 /* sqpoll task will cancel all its requests */
9947 if (node->ctx->sq_data)
9949 io_uring_try_cancel_requests(node->ctx, current,
9953 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9954 io_uring_try_cancel_requests(ctx, current,
9958 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9960 io_uring_drop_tctx_refs(current);
9963 * If we've seen completions, retry without waiting. This
9964 * avoids a race where a completion comes in before we did
9965 * prepare_to_wait().
9967 if (inflight == tctx_inflight(tctx, !cancel_all))
9969 finish_wait(&tctx->wait, &wait);
9972 io_uring_clean_tctx(tctx);
9975 * We shouldn't run task_works after cancel, so just leave
9976 * ->in_idle set for normal exit.
9978 atomic_dec(&tctx->in_idle);
9979 /* for exec all current's requests should be gone, kill tctx */
9980 __io_uring_free(current);
9984 void __io_uring_cancel(bool cancel_all)
9986 io_uring_cancel_generic(cancel_all, NULL);
9989 void io_uring_unreg_ringfd(void)
9991 struct io_uring_task *tctx = current->io_uring;
9994 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
9995 if (tctx->registered_rings[i]) {
9996 fput(tctx->registered_rings[i]);
9997 tctx->registered_rings[i] = NULL;
10002 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10003 int start, int end)
10008 for (offset = start; offset < end; offset++) {
10009 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10010 if (tctx->registered_rings[offset])
10016 } else if (file->f_op != &io_uring_fops) {
10018 return -EOPNOTSUPP;
10020 tctx->registered_rings[offset] = file;
10028 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10029 * invocation. User passes in an array of struct io_uring_rsrc_update
10030 * with ->data set to the ring_fd, and ->offset given for the desired
10031 * index. If no index is desired, application may set ->offset == -1U
10032 * and we'll find an available index. Returns number of entries
10033 * successfully processed, or < 0 on error if none were processed.
10035 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10038 struct io_uring_rsrc_update __user *arg = __arg;
10039 struct io_uring_rsrc_update reg;
10040 struct io_uring_task *tctx;
10043 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10046 mutex_unlock(&ctx->uring_lock);
10047 ret = io_uring_add_tctx_node(ctx);
10048 mutex_lock(&ctx->uring_lock);
10052 tctx = current->io_uring;
10053 for (i = 0; i < nr_args; i++) {
10056 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10066 if (reg.offset == -1U) {
10068 end = IO_RINGFD_REG_MAX;
10070 if (reg.offset >= IO_RINGFD_REG_MAX) {
10074 start = reg.offset;
10078 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10083 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10084 fput(tctx->registered_rings[reg.offset]);
10085 tctx->registered_rings[reg.offset] = NULL;
10091 return i ? i : ret;
10094 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10097 struct io_uring_rsrc_update __user *arg = __arg;
10098 struct io_uring_task *tctx = current->io_uring;
10099 struct io_uring_rsrc_update reg;
10102 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10107 for (i = 0; i < nr_args; i++) {
10108 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10112 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
10117 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10118 if (tctx->registered_rings[reg.offset]) {
10119 fput(tctx->registered_rings[reg.offset]);
10120 tctx->registered_rings[reg.offset] = NULL;
10124 return i ? i : ret;
10127 static void *io_uring_validate_mmap_request(struct file *file,
10128 loff_t pgoff, size_t sz)
10130 struct io_ring_ctx *ctx = file->private_data;
10131 loff_t offset = pgoff << PAGE_SHIFT;
10136 case IORING_OFF_SQ_RING:
10137 case IORING_OFF_CQ_RING:
10140 case IORING_OFF_SQES:
10141 ptr = ctx->sq_sqes;
10144 return ERR_PTR(-EINVAL);
10147 page = virt_to_head_page(ptr);
10148 if (sz > page_size(page))
10149 return ERR_PTR(-EINVAL);
10156 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10158 size_t sz = vma->vm_end - vma->vm_start;
10162 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10164 return PTR_ERR(ptr);
10166 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10167 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10170 #else /* !CONFIG_MMU */
10172 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10174 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10177 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10179 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10182 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10183 unsigned long addr, unsigned long len,
10184 unsigned long pgoff, unsigned long flags)
10188 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10190 return PTR_ERR(ptr);
10192 return (unsigned long) ptr;
10195 #endif /* !CONFIG_MMU */
10197 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10202 if (!io_sqring_full(ctx))
10204 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10206 if (!io_sqring_full(ctx))
10209 } while (!signal_pending(current));
10211 finish_wait(&ctx->sqo_sq_wait, &wait);
10215 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
10217 if (flags & IORING_ENTER_EXT_ARG) {
10218 struct io_uring_getevents_arg arg;
10220 if (argsz != sizeof(arg))
10222 if (copy_from_user(&arg, argp, sizeof(arg)))
10228 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10229 struct __kernel_timespec __user **ts,
10230 const sigset_t __user **sig)
10232 struct io_uring_getevents_arg arg;
10235 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10236 * is just a pointer to the sigset_t.
10238 if (!(flags & IORING_ENTER_EXT_ARG)) {
10239 *sig = (const sigset_t __user *) argp;
10245 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10246 * timespec and sigset_t pointers if good.
10248 if (*argsz != sizeof(arg))
10250 if (copy_from_user(&arg, argp, sizeof(arg)))
10254 *sig = u64_to_user_ptr(arg.sigmask);
10255 *argsz = arg.sigmask_sz;
10256 *ts = u64_to_user_ptr(arg.ts);
10260 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10261 u32, min_complete, u32, flags, const void __user *, argp,
10264 struct io_ring_ctx *ctx;
10268 io_run_task_work();
10270 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10271 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10272 IORING_ENTER_REGISTERED_RING)))
10276 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10277 * need only dereference our task private array to find it.
10279 if (flags & IORING_ENTER_REGISTERED_RING) {
10280 struct io_uring_task *tctx = current->io_uring;
10282 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10284 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10285 f.file = tctx->registered_rings[fd];
10291 if (unlikely(!f.file))
10295 if (unlikely(f.file->f_op != &io_uring_fops))
10299 ctx = f.file->private_data;
10300 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10304 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10308 * For SQ polling, the thread will do all submissions and completions.
10309 * Just return the requested submit count, and wake the thread if
10310 * we were asked to.
10313 if (ctx->flags & IORING_SETUP_SQPOLL) {
10314 io_cqring_overflow_flush(ctx);
10316 if (unlikely(ctx->sq_data->thread == NULL)) {
10320 if (flags & IORING_ENTER_SQ_WAKEUP)
10321 wake_up(&ctx->sq_data->wait);
10322 if (flags & IORING_ENTER_SQ_WAIT) {
10323 ret = io_sqpoll_wait_sq(ctx);
10328 } else if (to_submit) {
10329 ret = io_uring_add_tctx_node(ctx);
10333 mutex_lock(&ctx->uring_lock);
10334 ret = io_submit_sqes(ctx, to_submit);
10335 if (ret != to_submit) {
10336 mutex_unlock(&ctx->uring_lock);
10339 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
10340 goto iopoll_locked;
10341 mutex_unlock(&ctx->uring_lock);
10343 if (flags & IORING_ENTER_GETEVENTS) {
10345 if (ctx->syscall_iopoll) {
10347 * We disallow the app entering submit/complete with
10348 * polling, but we still need to lock the ring to
10349 * prevent racing with polled issue that got punted to
10352 mutex_lock(&ctx->uring_lock);
10354 ret2 = io_validate_ext_arg(flags, argp, argsz);
10355 if (likely(!ret2)) {
10356 min_complete = min(min_complete,
10358 ret2 = io_iopoll_check(ctx, min_complete);
10360 mutex_unlock(&ctx->uring_lock);
10362 const sigset_t __user *sig;
10363 struct __kernel_timespec __user *ts;
10365 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10366 if (likely(!ret2)) {
10367 min_complete = min(min_complete,
10369 ret2 = io_cqring_wait(ctx, min_complete, sig,
10378 * EBADR indicates that one or more CQE were dropped.
10379 * Once the user has been informed we can clear the bit
10380 * as they are obviously ok with those drops.
10382 if (unlikely(ret2 == -EBADR))
10383 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
10389 percpu_ref_put(&ctx->refs);
10395 #ifdef CONFIG_PROC_FS
10396 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10397 const struct cred *cred)
10399 struct user_namespace *uns = seq_user_ns(m);
10400 struct group_info *gi;
10405 seq_printf(m, "%5d\n", id);
10406 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10407 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10408 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10409 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10410 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10411 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10412 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10413 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10414 seq_puts(m, "\n\tGroups:\t");
10415 gi = cred->group_info;
10416 for (g = 0; g < gi->ngroups; g++) {
10417 seq_put_decimal_ull(m, g ? " " : "",
10418 from_kgid_munged(uns, gi->gid[g]));
10420 seq_puts(m, "\n\tCapEff:\t");
10421 cap = cred->cap_effective;
10422 CAP_FOR_EACH_U32(__capi)
10423 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10428 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10429 struct seq_file *m)
10431 struct io_sq_data *sq = NULL;
10432 struct io_overflow_cqe *ocqe;
10433 struct io_rings *r = ctx->rings;
10434 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10435 unsigned int sq_head = READ_ONCE(r->sq.head);
10436 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10437 unsigned int cq_head = READ_ONCE(r->cq.head);
10438 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10439 unsigned int cq_shift = 0;
10440 unsigned int sq_entries, cq_entries;
10442 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
10449 * we may get imprecise sqe and cqe info if uring is actively running
10450 * since we get cached_sq_head and cached_cq_tail without uring_lock
10451 * and sq_tail and cq_head are changed by userspace. But it's ok since
10452 * we usually use these info when it is stuck.
10454 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10455 seq_printf(m, "SqHead:\t%u\n", sq_head);
10456 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10457 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10458 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10459 seq_printf(m, "CqHead:\t%u\n", cq_head);
10460 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10461 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10462 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10463 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10464 for (i = 0; i < sq_entries; i++) {
10465 unsigned int entry = i + sq_head;
10466 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10467 struct io_uring_sqe *sqe;
10469 if (sq_idx > sq_mask)
10471 sqe = &ctx->sq_sqes[sq_idx];
10472 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10473 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10476 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10477 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10478 for (i = 0; i < cq_entries; i++) {
10479 unsigned int entry = i + cq_head;
10480 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
10483 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10484 entry & cq_mask, cqe->user_data, cqe->res,
10487 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
10488 "extra1:%llu, extra2:%llu\n",
10489 entry & cq_mask, cqe->user_data, cqe->res,
10490 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
10495 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10496 * since fdinfo case grabs it in the opposite direction of normal use
10497 * cases. If we fail to get the lock, we just don't iterate any
10498 * structures that could be going away outside the io_uring mutex.
10500 has_lock = mutex_trylock(&ctx->uring_lock);
10502 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10508 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10509 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10510 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10511 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10512 struct file *f = io_file_from_index(ctx, i);
10515 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10517 seq_printf(m, "%5u: <none>\n", i);
10519 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10520 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10521 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10522 unsigned int len = buf->ubuf_end - buf->ubuf;
10524 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10526 if (has_lock && !xa_empty(&ctx->personalities)) {
10527 unsigned long index;
10528 const struct cred *cred;
10530 seq_printf(m, "Personalities:\n");
10531 xa_for_each(&ctx->personalities, index, cred)
10532 io_uring_show_cred(m, index, cred);
10535 mutex_unlock(&ctx->uring_lock);
10537 seq_puts(m, "PollList:\n");
10538 spin_lock(&ctx->completion_lock);
10539 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10540 struct hlist_head *list = &ctx->cancel_hash[i];
10541 struct io_kiocb *req;
10543 hlist_for_each_entry(req, list, hash_node)
10544 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10545 task_work_pending(req->task));
10548 seq_puts(m, "CqOverflowList:\n");
10549 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10550 struct io_uring_cqe *cqe = &ocqe->cqe;
10552 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10553 cqe->user_data, cqe->res, cqe->flags);
10557 spin_unlock(&ctx->completion_lock);
10560 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10562 struct io_ring_ctx *ctx = f->private_data;
10564 if (percpu_ref_tryget(&ctx->refs)) {
10565 __io_uring_show_fdinfo(ctx, m);
10566 percpu_ref_put(&ctx->refs);
10571 static const struct file_operations io_uring_fops = {
10572 .release = io_uring_release,
10573 .mmap = io_uring_mmap,
10575 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10576 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10578 .poll = io_uring_poll,
10579 #ifdef CONFIG_PROC_FS
10580 .show_fdinfo = io_uring_show_fdinfo,
10584 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10585 struct io_uring_params *p)
10587 struct io_rings *rings;
10588 size_t size, sq_array_offset;
10590 /* make sure these are sane, as we already accounted them */
10591 ctx->sq_entries = p->sq_entries;
10592 ctx->cq_entries = p->cq_entries;
10594 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
10595 if (size == SIZE_MAX)
10598 rings = io_mem_alloc(size);
10602 ctx->rings = rings;
10603 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10604 rings->sq_ring_mask = p->sq_entries - 1;
10605 rings->cq_ring_mask = p->cq_entries - 1;
10606 rings->sq_ring_entries = p->sq_entries;
10607 rings->cq_ring_entries = p->cq_entries;
10609 if (p->flags & IORING_SETUP_SQE128)
10610 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
10612 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10613 if (size == SIZE_MAX) {
10614 io_mem_free(ctx->rings);
10619 ctx->sq_sqes = io_mem_alloc(size);
10620 if (!ctx->sq_sqes) {
10621 io_mem_free(ctx->rings);
10629 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10633 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10637 ret = io_uring_add_tctx_node(ctx);
10642 fd_install(fd, file);
10647 * Allocate an anonymous fd, this is what constitutes the application
10648 * visible backing of an io_uring instance. The application mmaps this
10649 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10650 * we have to tie this fd to a socket for file garbage collection purposes.
10652 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10655 #if defined(CONFIG_UNIX)
10658 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10661 return ERR_PTR(ret);
10664 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
10665 O_RDWR | O_CLOEXEC, NULL);
10666 #if defined(CONFIG_UNIX)
10667 if (IS_ERR(file)) {
10668 sock_release(ctx->ring_sock);
10669 ctx->ring_sock = NULL;
10671 ctx->ring_sock->file = file;
10677 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
10678 struct io_uring_params __user *params)
10680 struct io_ring_ctx *ctx;
10686 if (entries > IORING_MAX_ENTRIES) {
10687 if (!(p->flags & IORING_SETUP_CLAMP))
10689 entries = IORING_MAX_ENTRIES;
10693 * Use twice as many entries for the CQ ring. It's possible for the
10694 * application to drive a higher depth than the size of the SQ ring,
10695 * since the sqes are only used at submission time. This allows for
10696 * some flexibility in overcommitting a bit. If the application has
10697 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10698 * of CQ ring entries manually.
10700 p->sq_entries = roundup_pow_of_two(entries);
10701 if (p->flags & IORING_SETUP_CQSIZE) {
10703 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10704 * to a power-of-two, if it isn't already. We do NOT impose
10705 * any cq vs sq ring sizing.
10707 if (!p->cq_entries)
10709 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10710 if (!(p->flags & IORING_SETUP_CLAMP))
10712 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10714 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10715 if (p->cq_entries < p->sq_entries)
10718 p->cq_entries = 2 * p->sq_entries;
10721 ctx = io_ring_ctx_alloc(p);
10726 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10727 * space applications don't need to do io completion events
10728 * polling again, they can rely on io_sq_thread to do polling
10729 * work, which can reduce cpu usage and uring_lock contention.
10731 if (ctx->flags & IORING_SETUP_IOPOLL &&
10732 !(ctx->flags & IORING_SETUP_SQPOLL))
10733 ctx->syscall_iopoll = 1;
10735 ctx->compat = in_compat_syscall();
10736 if (!capable(CAP_IPC_LOCK))
10737 ctx->user = get_uid(current_user());
10740 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
10741 * COOP_TASKRUN is set, then IPIs are never needed by the app.
10744 if (ctx->flags & IORING_SETUP_SQPOLL) {
10745 /* IPI related flags don't make sense with SQPOLL */
10746 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
10747 IORING_SETUP_TASKRUN_FLAG))
10749 ctx->notify_method = TWA_SIGNAL_NO_IPI;
10750 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
10751 ctx->notify_method = TWA_SIGNAL_NO_IPI;
10753 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
10755 ctx->notify_method = TWA_SIGNAL;
10759 * This is just grabbed for accounting purposes. When a process exits,
10760 * the mm is exited and dropped before the files, hence we need to hang
10761 * on to this mm purely for the purposes of being able to unaccount
10762 * memory (locked/pinned vm). It's not used for anything else.
10764 mmgrab(current->mm);
10765 ctx->mm_account = current->mm;
10767 ret = io_allocate_scq_urings(ctx, p);
10771 ret = io_sq_offload_create(ctx, p);
10774 /* always set a rsrc node */
10775 ret = io_rsrc_node_switch_start(ctx);
10778 io_rsrc_node_switch(ctx, NULL);
10780 memset(&p->sq_off, 0, sizeof(p->sq_off));
10781 p->sq_off.head = offsetof(struct io_rings, sq.head);
10782 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10783 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10784 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10785 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10786 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10787 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10789 memset(&p->cq_off, 0, sizeof(p->cq_off));
10790 p->cq_off.head = offsetof(struct io_rings, cq.head);
10791 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10792 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10793 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10794 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10795 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10796 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10798 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10799 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10800 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10801 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10802 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10803 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
10804 IORING_FEAT_LINKED_FILE;
10806 if (copy_to_user(params, p, sizeof(*p))) {
10811 file = io_uring_get_file(ctx);
10812 if (IS_ERR(file)) {
10813 ret = PTR_ERR(file);
10818 * Install ring fd as the very last thing, so we don't risk someone
10819 * having closed it before we finish setup
10821 ret = io_uring_install_fd(ctx, file);
10823 /* fput will clean it up */
10828 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10831 io_ring_ctx_wait_and_kill(ctx);
10836 * Sets up an aio uring context, and returns the fd. Applications asks for a
10837 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10838 * params structure passed in.
10840 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10842 struct io_uring_params p;
10845 if (copy_from_user(&p, params, sizeof(p)))
10847 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10852 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10853 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10854 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10855 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
10856 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
10857 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
10860 return io_uring_create(entries, &p, params);
10863 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10864 struct io_uring_params __user *, params)
10866 return io_uring_setup(entries, params);
10869 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
10872 struct io_uring_probe *p;
10876 size = struct_size(p, ops, nr_args);
10877 if (size == SIZE_MAX)
10879 p = kzalloc(size, GFP_KERNEL);
10884 if (copy_from_user(p, arg, size))
10887 if (memchr_inv(p, 0, size))
10890 p->last_op = IORING_OP_LAST - 1;
10891 if (nr_args > IORING_OP_LAST)
10892 nr_args = IORING_OP_LAST;
10894 for (i = 0; i < nr_args; i++) {
10896 if (!io_op_defs[i].not_supported)
10897 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10902 if (copy_to_user(arg, p, size))
10909 static int io_register_personality(struct io_ring_ctx *ctx)
10911 const struct cred *creds;
10915 creds = get_current_cred();
10917 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10918 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10926 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
10927 void __user *arg, unsigned int nr_args)
10929 struct io_uring_restriction *res;
10933 /* Restrictions allowed only if rings started disabled */
10934 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10937 /* We allow only a single restrictions registration */
10938 if (ctx->restrictions.registered)
10941 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10944 size = array_size(nr_args, sizeof(*res));
10945 if (size == SIZE_MAX)
10948 res = memdup_user(arg, size);
10950 return PTR_ERR(res);
10954 for (i = 0; i < nr_args; i++) {
10955 switch (res[i].opcode) {
10956 case IORING_RESTRICTION_REGISTER_OP:
10957 if (res[i].register_op >= IORING_REGISTER_LAST) {
10962 __set_bit(res[i].register_op,
10963 ctx->restrictions.register_op);
10965 case IORING_RESTRICTION_SQE_OP:
10966 if (res[i].sqe_op >= IORING_OP_LAST) {
10971 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10973 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10974 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10976 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10977 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10986 /* Reset all restrictions if an error happened */
10988 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10990 ctx->restrictions.registered = true;
10996 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10998 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11001 if (ctx->restrictions.registered)
11002 ctx->restricted = 1;
11004 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11005 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11006 wake_up(&ctx->sq_data->wait);
11010 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11011 struct io_uring_rsrc_update2 *up,
11017 if (check_add_overflow(up->offset, nr_args, &tmp))
11019 err = io_rsrc_node_switch_start(ctx);
11024 case IORING_RSRC_FILE:
11025 return __io_sqe_files_update(ctx, up, nr_args);
11026 case IORING_RSRC_BUFFER:
11027 return __io_sqe_buffers_update(ctx, up, nr_args);
11032 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11035 struct io_uring_rsrc_update2 up;
11039 memset(&up, 0, sizeof(up));
11040 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11042 if (up.resv || up.resv2)
11044 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11047 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11048 unsigned size, unsigned type)
11050 struct io_uring_rsrc_update2 up;
11052 if (size != sizeof(up))
11054 if (copy_from_user(&up, arg, sizeof(up)))
11056 if (!up.nr || up.resv || up.resv2)
11058 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11061 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11062 unsigned int size, unsigned int type)
11064 struct io_uring_rsrc_register rr;
11066 /* keep it extendible */
11067 if (size != sizeof(rr))
11070 memset(&rr, 0, sizeof(rr));
11071 if (copy_from_user(&rr, arg, size))
11073 if (!rr.nr || rr.resv2)
11075 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
11079 case IORING_RSRC_FILE:
11080 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
11082 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11083 rr.nr, u64_to_user_ptr(rr.tags));
11084 case IORING_RSRC_BUFFER:
11085 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
11087 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11088 rr.nr, u64_to_user_ptr(rr.tags));
11093 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11094 void __user *arg, unsigned len)
11096 struct io_uring_task *tctx = current->io_uring;
11097 cpumask_var_t new_mask;
11100 if (!tctx || !tctx->io_wq)
11103 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11106 cpumask_clear(new_mask);
11107 if (len > cpumask_size())
11108 len = cpumask_size();
11110 if (in_compat_syscall()) {
11111 ret = compat_get_bitmap(cpumask_bits(new_mask),
11112 (const compat_ulong_t __user *)arg,
11113 len * 8 /* CHAR_BIT */);
11115 ret = copy_from_user(new_mask, arg, len);
11119 free_cpumask_var(new_mask);
11123 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11124 free_cpumask_var(new_mask);
11128 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11130 struct io_uring_task *tctx = current->io_uring;
11132 if (!tctx || !tctx->io_wq)
11135 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11138 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11140 __must_hold(&ctx->uring_lock)
11142 struct io_tctx_node *node;
11143 struct io_uring_task *tctx = NULL;
11144 struct io_sq_data *sqd = NULL;
11145 __u32 new_count[2];
11148 if (copy_from_user(new_count, arg, sizeof(new_count)))
11150 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11151 if (new_count[i] > INT_MAX)
11154 if (ctx->flags & IORING_SETUP_SQPOLL) {
11155 sqd = ctx->sq_data;
11158 * Observe the correct sqd->lock -> ctx->uring_lock
11159 * ordering. Fine to drop uring_lock here, we hold
11160 * a ref to the ctx.
11162 refcount_inc(&sqd->refs);
11163 mutex_unlock(&ctx->uring_lock);
11164 mutex_lock(&sqd->lock);
11165 mutex_lock(&ctx->uring_lock);
11167 tctx = sqd->thread->io_uring;
11170 tctx = current->io_uring;
11173 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11175 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11177 ctx->iowq_limits[i] = new_count[i];
11178 ctx->iowq_limits_set = true;
11180 if (tctx && tctx->io_wq) {
11181 ret = io_wq_max_workers(tctx->io_wq, new_count);
11185 memset(new_count, 0, sizeof(new_count));
11189 mutex_unlock(&sqd->lock);
11190 io_put_sq_data(sqd);
11193 if (copy_to_user(arg, new_count, sizeof(new_count)))
11196 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11200 /* now propagate the restriction to all registered users */
11201 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11202 struct io_uring_task *tctx = node->task->io_uring;
11204 if (WARN_ON_ONCE(!tctx->io_wq))
11207 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11208 new_count[i] = ctx->iowq_limits[i];
11209 /* ignore errors, it always returns zero anyway */
11210 (void)io_wq_max_workers(tctx->io_wq, new_count);
11215 mutex_unlock(&sqd->lock);
11216 io_put_sq_data(sqd);
11221 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
11223 struct io_uring_buf_ring *br;
11224 struct io_uring_buf_reg reg;
11225 struct io_buffer_list *bl, *free_bl = NULL;
11226 struct page **pages;
11229 if (copy_from_user(®, arg, sizeof(reg)))
11232 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
11234 if (!reg.ring_addr)
11236 if (reg.ring_addr & ~PAGE_MASK)
11238 if (!is_power_of_2(reg.ring_entries))
11241 /* cannot disambiguate full vs empty due to head/tail size */
11242 if (reg.ring_entries >= 65536)
11245 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
11246 int ret = io_init_bl_list(ctx);
11251 bl = io_buffer_get_list(ctx, reg.bgid);
11253 /* if mapped buffer ring OR classic exists, don't allow */
11254 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
11257 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
11262 pages = io_pin_pages(reg.ring_addr,
11263 struct_size(br, bufs, reg.ring_entries),
11265 if (IS_ERR(pages)) {
11267 return PTR_ERR(pages);
11270 br = page_address(pages[0]);
11271 bl->buf_pages = pages;
11272 bl->buf_nr_pages = nr_pages;
11273 bl->nr_entries = reg.ring_entries;
11275 bl->mask = reg.ring_entries - 1;
11276 io_buffer_add_list(ctx, bl, reg.bgid);
11280 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
11282 struct io_uring_buf_reg reg;
11283 struct io_buffer_list *bl;
11285 if (copy_from_user(®, arg, sizeof(reg)))
11287 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
11290 bl = io_buffer_get_list(ctx, reg.bgid);
11293 if (!bl->buf_nr_pages)
11296 __io_remove_buffers(ctx, bl, -1U);
11297 if (bl->bgid >= BGID_ARRAY) {
11298 xa_erase(&ctx->io_bl_xa, bl->bgid);
11304 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11305 void __user *arg, unsigned nr_args)
11306 __releases(ctx->uring_lock)
11307 __acquires(ctx->uring_lock)
11312 * We're inside the ring mutex, if the ref is already dying, then
11313 * someone else killed the ctx or is already going through
11314 * io_uring_register().
11316 if (percpu_ref_is_dying(&ctx->refs))
11319 if (ctx->restricted) {
11320 if (opcode >= IORING_REGISTER_LAST)
11322 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11323 if (!test_bit(opcode, ctx->restrictions.register_op))
11328 case IORING_REGISTER_BUFFERS:
11332 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11334 case IORING_UNREGISTER_BUFFERS:
11336 if (arg || nr_args)
11338 ret = io_sqe_buffers_unregister(ctx);
11340 case IORING_REGISTER_FILES:
11344 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11346 case IORING_UNREGISTER_FILES:
11348 if (arg || nr_args)
11350 ret = io_sqe_files_unregister(ctx);
11352 case IORING_REGISTER_FILES_UPDATE:
11353 ret = io_register_files_update(ctx, arg, nr_args);
11355 case IORING_REGISTER_EVENTFD:
11359 ret = io_eventfd_register(ctx, arg, 0);
11361 case IORING_REGISTER_EVENTFD_ASYNC:
11365 ret = io_eventfd_register(ctx, arg, 1);
11367 case IORING_UNREGISTER_EVENTFD:
11369 if (arg || nr_args)
11371 ret = io_eventfd_unregister(ctx);
11373 case IORING_REGISTER_PROBE:
11375 if (!arg || nr_args > 256)
11377 ret = io_probe(ctx, arg, nr_args);
11379 case IORING_REGISTER_PERSONALITY:
11381 if (arg || nr_args)
11383 ret = io_register_personality(ctx);
11385 case IORING_UNREGISTER_PERSONALITY:
11389 ret = io_unregister_personality(ctx, nr_args);
11391 case IORING_REGISTER_ENABLE_RINGS:
11393 if (arg || nr_args)
11395 ret = io_register_enable_rings(ctx);
11397 case IORING_REGISTER_RESTRICTIONS:
11398 ret = io_register_restrictions(ctx, arg, nr_args);
11400 case IORING_REGISTER_FILES2:
11401 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11403 case IORING_REGISTER_FILES_UPDATE2:
11404 ret = io_register_rsrc_update(ctx, arg, nr_args,
11407 case IORING_REGISTER_BUFFERS2:
11408 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11410 case IORING_REGISTER_BUFFERS_UPDATE:
11411 ret = io_register_rsrc_update(ctx, arg, nr_args,
11412 IORING_RSRC_BUFFER);
11414 case IORING_REGISTER_IOWQ_AFF:
11416 if (!arg || !nr_args)
11418 ret = io_register_iowq_aff(ctx, arg, nr_args);
11420 case IORING_UNREGISTER_IOWQ_AFF:
11422 if (arg || nr_args)
11424 ret = io_unregister_iowq_aff(ctx);
11426 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11428 if (!arg || nr_args != 2)
11430 ret = io_register_iowq_max_workers(ctx, arg);
11432 case IORING_REGISTER_RING_FDS:
11433 ret = io_ringfd_register(ctx, arg, nr_args);
11435 case IORING_UNREGISTER_RING_FDS:
11436 ret = io_ringfd_unregister(ctx, arg, nr_args);
11438 case IORING_REGISTER_PBUF_RING:
11440 if (!arg || nr_args != 1)
11442 ret = io_register_pbuf_ring(ctx, arg);
11444 case IORING_UNREGISTER_PBUF_RING:
11446 if (!arg || nr_args != 1)
11448 ret = io_unregister_pbuf_ring(ctx, arg);
11458 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11459 void __user *, arg, unsigned int, nr_args)
11461 struct io_ring_ctx *ctx;
11470 if (f.file->f_op != &io_uring_fops)
11473 ctx = f.file->private_data;
11475 io_run_task_work();
11477 mutex_lock(&ctx->uring_lock);
11478 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11479 mutex_unlock(&ctx->uring_lock);
11480 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11486 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
11492 static const struct io_op_def io_op_defs[] = {
11493 [IORING_OP_NOP] = {
11496 .prep = io_nop_prep,
11499 [IORING_OP_READV] = {
11501 .unbound_nonreg_file = 1,
11503 .buffer_select = 1,
11508 .async_size = sizeof(struct io_async_rw),
11509 .prep = io_prep_rw,
11511 .prep_async = io_readv_prep_async,
11512 .cleanup = io_readv_writev_cleanup,
11514 [IORING_OP_WRITEV] = {
11516 .hash_reg_file = 1,
11517 .unbound_nonreg_file = 1,
11523 .async_size = sizeof(struct io_async_rw),
11524 .prep = io_prep_rw,
11526 .prep_async = io_writev_prep_async,
11527 .cleanup = io_readv_writev_cleanup,
11529 [IORING_OP_FSYNC] = {
11532 .prep = io_fsync_prep,
11535 [IORING_OP_READ_FIXED] = {
11537 .unbound_nonreg_file = 1,
11543 .async_size = sizeof(struct io_async_rw),
11544 .prep = io_prep_rw,
11547 [IORING_OP_WRITE_FIXED] = {
11549 .hash_reg_file = 1,
11550 .unbound_nonreg_file = 1,
11556 .async_size = sizeof(struct io_async_rw),
11557 .prep = io_prep_rw,
11560 [IORING_OP_POLL_ADD] = {
11562 .unbound_nonreg_file = 1,
11564 .prep = io_poll_add_prep,
11565 .issue = io_poll_add,
11567 [IORING_OP_POLL_REMOVE] = {
11569 .prep = io_poll_remove_prep,
11570 .issue = io_poll_remove,
11572 [IORING_OP_SYNC_FILE_RANGE] = {
11575 .prep = io_sfr_prep,
11576 .issue = io_sync_file_range,
11578 [IORING_OP_SENDMSG] = {
11580 .unbound_nonreg_file = 1,
11583 .async_size = sizeof(struct io_async_msghdr),
11584 .prep = io_sendmsg_prep,
11585 .issue = io_sendmsg,
11586 .prep_async = io_sendmsg_prep_async,
11587 #if defined(CONFIG_NET)
11588 .cleanup = io_sendmsg_recvmsg_cleanup,
11591 [IORING_OP_RECVMSG] = {
11593 .unbound_nonreg_file = 1,
11595 .buffer_select = 1,
11597 .async_size = sizeof(struct io_async_msghdr),
11598 .prep = io_recvmsg_prep,
11599 .issue = io_recvmsg,
11600 .prep_async = io_recvmsg_prep_async,
11601 #if defined(CONFIG_NET)
11602 .cleanup = io_sendmsg_recvmsg_cleanup,
11605 [IORING_OP_TIMEOUT] = {
11607 .async_size = sizeof(struct io_timeout_data),
11608 .prep = io_timeout_prep,
11609 .issue = io_timeout,
11611 [IORING_OP_TIMEOUT_REMOVE] = {
11612 /* used by timeout updates' prep() */
11614 .prep = io_timeout_remove_prep,
11615 .issue = io_timeout_remove,
11617 [IORING_OP_ACCEPT] = {
11619 .unbound_nonreg_file = 1,
11621 .poll_exclusive = 1,
11622 .ioprio = 1, /* used for flags */
11623 .prep = io_accept_prep,
11624 .issue = io_accept,
11626 [IORING_OP_ASYNC_CANCEL] = {
11628 .prep = io_async_cancel_prep,
11629 .issue = io_async_cancel,
11631 [IORING_OP_LINK_TIMEOUT] = {
11633 .async_size = sizeof(struct io_timeout_data),
11634 .prep = io_link_timeout_prep,
11635 .issue = io_no_issue,
11637 [IORING_OP_CONNECT] = {
11639 .unbound_nonreg_file = 1,
11641 .async_size = sizeof(struct io_async_connect),
11642 .prep = io_connect_prep,
11643 .issue = io_connect,
11644 .prep_async = io_connect_prep_async,
11646 [IORING_OP_FALLOCATE] = {
11648 .prep = io_fallocate_prep,
11649 .issue = io_fallocate,
11651 [IORING_OP_OPENAT] = {
11652 .prep = io_openat_prep,
11653 .issue = io_openat,
11654 .cleanup = io_open_cleanup,
11656 [IORING_OP_CLOSE] = {
11657 .prep = io_close_prep,
11660 [IORING_OP_FILES_UPDATE] = {
11663 .prep = io_files_update_prep,
11664 .issue = io_files_update,
11666 [IORING_OP_STATX] = {
11668 .prep = io_statx_prep,
11670 .cleanup = io_statx_cleanup,
11672 [IORING_OP_READ] = {
11674 .unbound_nonreg_file = 1,
11676 .buffer_select = 1,
11681 .async_size = sizeof(struct io_async_rw),
11682 .prep = io_prep_rw,
11685 [IORING_OP_WRITE] = {
11687 .hash_reg_file = 1,
11688 .unbound_nonreg_file = 1,
11694 .async_size = sizeof(struct io_async_rw),
11695 .prep = io_prep_rw,
11698 [IORING_OP_FADVISE] = {
11701 .prep = io_fadvise_prep,
11702 .issue = io_fadvise,
11704 [IORING_OP_MADVISE] = {
11705 .prep = io_madvise_prep,
11706 .issue = io_madvise,
11708 [IORING_OP_SEND] = {
11710 .unbound_nonreg_file = 1,
11714 .prep = io_sendmsg_prep,
11717 [IORING_OP_RECV] = {
11719 .unbound_nonreg_file = 1,
11721 .buffer_select = 1,
11724 .prep = io_recvmsg_prep,
11727 [IORING_OP_OPENAT2] = {
11728 .prep = io_openat2_prep,
11729 .issue = io_openat2,
11730 .cleanup = io_open_cleanup,
11732 [IORING_OP_EPOLL_CTL] = {
11733 .unbound_nonreg_file = 1,
11735 .prep = io_epoll_ctl_prep,
11736 .issue = io_epoll_ctl,
11738 [IORING_OP_SPLICE] = {
11740 .hash_reg_file = 1,
11741 .unbound_nonreg_file = 1,
11743 .prep = io_splice_prep,
11744 .issue = io_splice,
11746 [IORING_OP_PROVIDE_BUFFERS] = {
11749 .prep = io_provide_buffers_prep,
11750 .issue = io_provide_buffers,
11752 [IORING_OP_REMOVE_BUFFERS] = {
11755 .prep = io_remove_buffers_prep,
11756 .issue = io_remove_buffers,
11758 [IORING_OP_TEE] = {
11760 .hash_reg_file = 1,
11761 .unbound_nonreg_file = 1,
11763 .prep = io_tee_prep,
11766 [IORING_OP_SHUTDOWN] = {
11768 .prep = io_shutdown_prep,
11769 .issue = io_shutdown,
11771 [IORING_OP_RENAMEAT] = {
11772 .prep = io_renameat_prep,
11773 .issue = io_renameat,
11774 .cleanup = io_renameat_cleanup,
11776 [IORING_OP_UNLINKAT] = {
11777 .prep = io_unlinkat_prep,
11778 .issue = io_unlinkat,
11779 .cleanup = io_unlinkat_cleanup,
11781 [IORING_OP_MKDIRAT] = {
11782 .prep = io_mkdirat_prep,
11783 .issue = io_mkdirat,
11784 .cleanup = io_mkdirat_cleanup,
11786 [IORING_OP_SYMLINKAT] = {
11787 .prep = io_symlinkat_prep,
11788 .issue = io_symlinkat,
11789 .cleanup = io_link_cleanup,
11791 [IORING_OP_LINKAT] = {
11792 .prep = io_linkat_prep,
11793 .issue = io_linkat,
11794 .cleanup = io_link_cleanup,
11796 [IORING_OP_MSG_RING] = {
11799 .prep = io_msg_ring_prep,
11800 .issue = io_msg_ring,
11802 [IORING_OP_FSETXATTR] = {
11804 .prep = io_fsetxattr_prep,
11805 .issue = io_fsetxattr,
11806 .cleanup = io_xattr_cleanup,
11808 [IORING_OP_SETXATTR] = {
11809 .prep = io_setxattr_prep,
11810 .issue = io_setxattr,
11811 .cleanup = io_xattr_cleanup,
11813 [IORING_OP_FGETXATTR] = {
11815 .prep = io_fgetxattr_prep,
11816 .issue = io_fgetxattr,
11817 .cleanup = io_xattr_cleanup,
11819 [IORING_OP_GETXATTR] = {
11820 .prep = io_getxattr_prep,
11821 .issue = io_getxattr,
11822 .cleanup = io_xattr_cleanup,
11824 [IORING_OP_SOCKET] = {
11826 .prep = io_socket_prep,
11827 .issue = io_socket,
11829 [IORING_OP_URING_CMD] = {
11832 .async_size = uring_cmd_pdu_size(1),
11833 .prep = io_uring_cmd_prep,
11834 .issue = io_uring_cmd,
11835 .prep_async = io_uring_cmd_prep_async,
11839 static int __init io_uring_init(void)
11843 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11844 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11845 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11848 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11849 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11850 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11851 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11852 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11853 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11854 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11855 BUILD_BUG_SQE_ELEM(8, __u64, off);
11856 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11857 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11858 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11859 BUILD_BUG_SQE_ELEM(24, __u32, len);
11860 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11861 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11862 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11863 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11864 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11865 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11866 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11867 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11868 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11869 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11870 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11871 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11872 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11873 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11874 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11875 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11876 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11877 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11878 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11879 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11880 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11881 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
11883 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11884 sizeof(struct io_uring_rsrc_update));
11885 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11886 sizeof(struct io_uring_rsrc_update2));
11888 /* ->buf_index is u16 */
11889 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11890 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
11891 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
11892 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
11893 offsetof(struct io_uring_buf_ring, tail));
11895 /* should fit into one byte */
11896 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11897 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11898 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11900 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11901 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11903 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
11905 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
11907 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
11908 BUG_ON(!io_op_defs[i].prep);
11909 BUG_ON(!io_op_defs[i].issue);
11912 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11916 __initcall(io_uring_init);