1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
49 #include <linux/bits.h>
51 #include <linux/sched/signal.h>
53 #include <linux/file.h>
54 #include <linux/fdtable.h>
56 #include <linux/mman.h>
57 #include <linux/mmu_context.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
79 #define CREATE_TRACE_POINTS
80 #include <trace/events/io_uring.h>
82 #include <uapi/linux/io_uring.h>
87 #define IORING_MAX_ENTRIES 32768
88 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
91 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
93 #define IORING_FILE_TABLE_SHIFT 9
94 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
95 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
96 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
99 u32 head ____cacheline_aligned_in_smp;
100 u32 tail ____cacheline_aligned_in_smp;
104 * This data is shared with the application through the mmap at offsets
105 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
107 * The offsets to the member fields are published through struct
108 * io_sqring_offsets when calling io_uring_setup.
112 * Head and tail offsets into the ring; the offsets need to be
113 * masked to get valid indices.
115 * The kernel controls head of the sq ring and the tail of the cq ring,
116 * and the application controls tail of the sq ring and the head of the
119 struct io_uring sq, cq;
121 * Bitmasks to apply to head and tail offsets (constant, equals
124 u32 sq_ring_mask, cq_ring_mask;
125 /* Ring sizes (constant, power of 2) */
126 u32 sq_ring_entries, cq_ring_entries;
128 * Number of invalid entries dropped by the kernel due to
129 * invalid index stored in array
131 * Written by the kernel, shouldn't be modified by the
132 * application (i.e. get number of "new events" by comparing to
135 * After a new SQ head value was read by the application this
136 * counter includes all submissions that were dropped reaching
137 * the new SQ head (and possibly more).
143 * Written by the kernel, shouldn't be modified by the
146 * The application needs a full memory barrier before checking
147 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
151 * Number of completion events lost because the queue was full;
152 * this should be avoided by the application by making sure
153 * there are not more requests pending than there is space in
154 * the completion queue.
156 * Written by the kernel, shouldn't be modified by the
157 * application (i.e. get number of "new events" by comparing to
160 * As completion events come in out of order this counter is not
161 * ordered with any other data.
165 * Ring buffer of completion events.
167 * The kernel writes completion events fresh every time they are
168 * produced, so the application is allowed to modify pending
171 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
174 struct io_mapped_ubuf {
177 struct bio_vec *bvec;
178 unsigned int nr_bvecs;
181 struct fixed_file_table {
189 struct fixed_file_data {
190 struct fixed_file_table *table;
191 struct io_ring_ctx *ctx;
193 struct percpu_ref refs;
194 struct llist_head put_llist;
196 struct work_struct ref_work;
197 struct completion done;
202 struct percpu_ref refs;
203 } ____cacheline_aligned_in_smp;
207 unsigned int compat: 1;
208 unsigned int account_mem: 1;
209 unsigned int cq_overflow_flushed: 1;
210 unsigned int drain_next: 1;
211 unsigned int eventfd_async: 1;
214 * Ring buffer of indices into array of io_uring_sqe, which is
215 * mmapped by the application using the IORING_OFF_SQES offset.
217 * This indirection could e.g. be used to assign fixed
218 * io_uring_sqe entries to operations and only submit them to
219 * the queue when needed.
221 * The kernel modifies neither the indices array nor the entries
225 unsigned cached_sq_head;
228 unsigned sq_thread_idle;
229 unsigned cached_sq_dropped;
230 atomic_t cached_cq_overflow;
231 unsigned long sq_check_overflow;
233 struct list_head defer_list;
234 struct list_head timeout_list;
235 struct list_head cq_overflow_list;
237 wait_queue_head_t inflight_wait;
238 struct io_uring_sqe *sq_sqes;
239 } ____cacheline_aligned_in_smp;
241 struct io_rings *rings;
245 struct task_struct *sqo_thread; /* if using sq thread polling */
246 struct mm_struct *sqo_mm;
247 wait_queue_head_t sqo_wait;
250 * If used, fixed file set. Writers must ensure that ->refs is dead,
251 * readers must ensure that ->refs is alive as long as the file* is
252 * used. Only updated through io_uring_register(2).
254 struct fixed_file_data *file_data;
255 unsigned nr_user_files;
257 struct file *ring_file;
259 /* if used, fixed mapped user buffers */
260 unsigned nr_user_bufs;
261 struct io_mapped_ubuf *user_bufs;
263 struct user_struct *user;
265 const struct cred *creds;
267 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
268 struct completion *completions;
270 /* if all else fails... */
271 struct io_kiocb *fallback_req;
273 #if defined(CONFIG_UNIX)
274 struct socket *ring_sock;
277 struct idr personality_idr;
280 unsigned cached_cq_tail;
283 atomic_t cq_timeouts;
284 unsigned long cq_check_overflow;
285 struct wait_queue_head cq_wait;
286 struct fasync_struct *cq_fasync;
287 struct eventfd_ctx *cq_ev_fd;
288 } ____cacheline_aligned_in_smp;
291 struct mutex uring_lock;
292 wait_queue_head_t wait;
293 } ____cacheline_aligned_in_smp;
296 spinlock_t completion_lock;
297 struct llist_head poll_llist;
300 * ->poll_list is protected by the ctx->uring_lock for
301 * io_uring instances that don't use IORING_SETUP_SQPOLL.
302 * For SQPOLL, only the single threaded io_sq_thread() will
303 * manipulate the list, hence no extra locking is needed there.
305 struct list_head poll_list;
306 struct hlist_head *cancel_hash;
307 unsigned cancel_hash_bits;
308 bool poll_multi_file;
310 spinlock_t inflight_lock;
311 struct list_head inflight_list;
312 } ____cacheline_aligned_in_smp;
316 * First field must be the file pointer in all the
317 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
319 struct io_poll_iocb {
322 struct wait_queue_head *head;
328 struct wait_queue_entry wait;
333 struct file *put_file;
337 struct io_timeout_data {
338 struct io_kiocb *req;
339 struct hrtimer timer;
340 struct timespec64 ts;
341 enum hrtimer_mode mode;
347 struct sockaddr __user *addr;
348 int __user *addr_len;
373 /* NOTE: kiocb has the file as the first member, so don't do it here */
381 struct sockaddr __user *addr;
388 struct user_msghdr __user *msg;
401 struct filename *filename;
402 struct statx __user *buffer;
406 struct io_files_update {
432 struct epoll_event event;
435 struct io_async_connect {
436 struct sockaddr_storage address;
439 struct io_async_msghdr {
440 struct iovec fast_iov[UIO_FASTIOV];
442 struct sockaddr __user *uaddr;
447 struct iovec fast_iov[UIO_FASTIOV];
453 struct io_async_ctx {
455 struct io_async_rw rw;
456 struct io_async_msghdr msg;
457 struct io_async_connect connect;
458 struct io_timeout_data timeout;
463 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
464 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
465 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
466 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
467 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
474 REQ_F_IOPOLL_COMPLETED_BIT,
475 REQ_F_LINK_TIMEOUT_BIT,
479 REQ_F_TIMEOUT_NOSEQ_BIT,
480 REQ_F_COMP_LOCKED_BIT,
481 REQ_F_NEED_CLEANUP_BIT,
486 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
487 /* drain existing IO first */
488 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
490 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
491 /* doesn't sever on completion < 0 */
492 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
494 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
496 /* already grabbed next link */
497 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
498 /* fail rest of links */
499 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
500 /* on inflight list */
501 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
502 /* read/write uses file position */
503 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
504 /* must not punt to workers */
505 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
506 /* polled IO has completed */
507 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
508 /* has linked timeout */
509 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
510 /* timeout request */
511 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
513 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
514 /* must be punted even for NONBLOCK */
515 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
516 /* no timeout sequence */
517 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
518 /* completion under lock */
519 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
521 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
525 * NOTE! Each of the iocb union members has the file pointer
526 * as the first entry in their struct definition. So you can
527 * access the file pointer through any of the sub-structs,
528 * or directly as just 'ki_filp' in this struct.
534 struct io_poll_iocb poll;
535 struct io_accept accept;
537 struct io_cancel cancel;
538 struct io_timeout timeout;
539 struct io_connect connect;
540 struct io_sr_msg sr_msg;
542 struct io_close close;
543 struct io_files_update files_update;
544 struct io_fadvise fadvise;
545 struct io_madvise madvise;
546 struct io_epoll epoll;
549 struct io_async_ctx *io;
551 * llist_node is only used for poll deferred completions
553 struct llist_node llist_node;
555 bool needs_fixed_file;
558 struct io_ring_ctx *ctx;
560 struct list_head list;
561 struct hlist_node hash_node;
563 struct list_head link_list;
570 struct list_head inflight_entry;
572 struct io_wq_work work;
575 #define IO_PLUG_THRESHOLD 2
576 #define IO_IOPOLL_BATCH 8
578 struct io_submit_state {
579 struct blk_plug plug;
582 * io_kiocb alloc cache
584 void *reqs[IO_IOPOLL_BATCH];
585 unsigned int free_reqs;
588 * File reference cache
592 unsigned int has_refs;
593 unsigned int used_refs;
594 unsigned int ios_left;
598 /* needs req->io allocated for deferral/async */
599 unsigned async_ctx : 1;
600 /* needs current->mm setup, does mm access */
601 unsigned needs_mm : 1;
602 /* needs req->file assigned */
603 unsigned needs_file : 1;
604 /* needs req->file assigned IFF fd is >= 0 */
605 unsigned fd_non_neg : 1;
606 /* hash wq insertion if file is a regular file */
607 unsigned hash_reg_file : 1;
608 /* unbound wq insertion if file is a non-regular file */
609 unsigned unbound_nonreg_file : 1;
610 /* opcode is not supported by this kernel */
611 unsigned not_supported : 1;
612 /* needs file table */
613 unsigned file_table : 1;
616 static const struct io_op_def io_op_defs[] = {
617 [IORING_OP_NOP] = {},
618 [IORING_OP_READV] = {
622 .unbound_nonreg_file = 1,
624 [IORING_OP_WRITEV] = {
629 .unbound_nonreg_file = 1,
631 [IORING_OP_FSYNC] = {
634 [IORING_OP_READ_FIXED] = {
636 .unbound_nonreg_file = 1,
638 [IORING_OP_WRITE_FIXED] = {
641 .unbound_nonreg_file = 1,
643 [IORING_OP_POLL_ADD] = {
645 .unbound_nonreg_file = 1,
647 [IORING_OP_POLL_REMOVE] = {},
648 [IORING_OP_SYNC_FILE_RANGE] = {
651 [IORING_OP_SENDMSG] = {
655 .unbound_nonreg_file = 1,
657 [IORING_OP_RECVMSG] = {
661 .unbound_nonreg_file = 1,
663 [IORING_OP_TIMEOUT] = {
667 [IORING_OP_TIMEOUT_REMOVE] = {},
668 [IORING_OP_ACCEPT] = {
671 .unbound_nonreg_file = 1,
674 [IORING_OP_ASYNC_CANCEL] = {},
675 [IORING_OP_LINK_TIMEOUT] = {
679 [IORING_OP_CONNECT] = {
683 .unbound_nonreg_file = 1,
685 [IORING_OP_FALLOCATE] = {
688 [IORING_OP_OPENAT] = {
693 [IORING_OP_CLOSE] = {
697 [IORING_OP_FILES_UPDATE] = {
701 [IORING_OP_STATX] = {
709 .unbound_nonreg_file = 1,
711 [IORING_OP_WRITE] = {
714 .unbound_nonreg_file = 1,
716 [IORING_OP_FADVISE] = {
719 [IORING_OP_MADVISE] = {
725 .unbound_nonreg_file = 1,
730 .unbound_nonreg_file = 1,
732 [IORING_OP_OPENAT2] = {
737 [IORING_OP_EPOLL_CTL] = {
738 .unbound_nonreg_file = 1,
743 static void io_wq_submit_work(struct io_wq_work **workptr);
744 static void io_cqring_fill_event(struct io_kiocb *req, long res);
745 static void io_put_req(struct io_kiocb *req);
746 static void __io_double_put_req(struct io_kiocb *req);
747 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
748 static void io_queue_linked_timeout(struct io_kiocb *req);
749 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
750 struct io_uring_files_update *ip,
752 static int io_grab_files(struct io_kiocb *req);
753 static void io_ring_file_ref_flush(struct fixed_file_data *data);
754 static void io_cleanup_req(struct io_kiocb *req);
756 static struct kmem_cache *req_cachep;
758 static const struct file_operations io_uring_fops;
760 struct sock *io_uring_get_socket(struct file *file)
762 #if defined(CONFIG_UNIX)
763 if (file->f_op == &io_uring_fops) {
764 struct io_ring_ctx *ctx = file->private_data;
766 return ctx->ring_sock->sk;
771 EXPORT_SYMBOL(io_uring_get_socket);
773 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
775 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
777 complete(&ctx->completions[0]);
780 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
782 struct io_ring_ctx *ctx;
785 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
789 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
790 if (!ctx->fallback_req)
793 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
794 if (!ctx->completions)
798 * Use 5 bits less than the max cq entries, that should give us around
799 * 32 entries per hash list if totally full and uniformly spread.
801 hash_bits = ilog2(p->cq_entries);
805 ctx->cancel_hash_bits = hash_bits;
806 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
808 if (!ctx->cancel_hash)
810 __hash_init(ctx->cancel_hash, 1U << hash_bits);
812 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
813 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
816 ctx->flags = p->flags;
817 init_waitqueue_head(&ctx->cq_wait);
818 INIT_LIST_HEAD(&ctx->cq_overflow_list);
819 init_completion(&ctx->completions[0]);
820 init_completion(&ctx->completions[1]);
821 idr_init(&ctx->personality_idr);
822 mutex_init(&ctx->uring_lock);
823 init_waitqueue_head(&ctx->wait);
824 spin_lock_init(&ctx->completion_lock);
825 init_llist_head(&ctx->poll_llist);
826 INIT_LIST_HEAD(&ctx->poll_list);
827 INIT_LIST_HEAD(&ctx->defer_list);
828 INIT_LIST_HEAD(&ctx->timeout_list);
829 init_waitqueue_head(&ctx->inflight_wait);
830 spin_lock_init(&ctx->inflight_lock);
831 INIT_LIST_HEAD(&ctx->inflight_list);
834 if (ctx->fallback_req)
835 kmem_cache_free(req_cachep, ctx->fallback_req);
836 kfree(ctx->completions);
837 kfree(ctx->cancel_hash);
842 static inline bool __req_need_defer(struct io_kiocb *req)
844 struct io_ring_ctx *ctx = req->ctx;
846 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
847 + atomic_read(&ctx->cached_cq_overflow);
850 static inline bool req_need_defer(struct io_kiocb *req)
852 if (unlikely(req->flags & REQ_F_IO_DRAIN))
853 return __req_need_defer(req);
858 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
860 struct io_kiocb *req;
862 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
863 if (req && !req_need_defer(req)) {
864 list_del_init(&req->list);
871 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
873 struct io_kiocb *req;
875 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
877 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
879 if (!__req_need_defer(req)) {
880 list_del_init(&req->list);
888 static void __io_commit_cqring(struct io_ring_ctx *ctx)
890 struct io_rings *rings = ctx->rings;
892 /* order cqe stores with ring update */
893 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
895 if (wq_has_sleeper(&ctx->cq_wait)) {
896 wake_up_interruptible(&ctx->cq_wait);
897 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
901 static inline void io_req_work_grab_env(struct io_kiocb *req,
902 const struct io_op_def *def)
904 if (!req->work.mm && def->needs_mm) {
906 req->work.mm = current->mm;
908 if (!req->work.creds)
909 req->work.creds = get_current_cred();
912 static inline void io_req_work_drop_env(struct io_kiocb *req)
915 mmdrop(req->work.mm);
918 if (req->work.creds) {
919 put_cred(req->work.creds);
920 req->work.creds = NULL;
924 static inline bool io_prep_async_work(struct io_kiocb *req,
925 struct io_kiocb **link)
927 const struct io_op_def *def = &io_op_defs[req->opcode];
928 bool do_hashed = false;
930 if (req->flags & REQ_F_ISREG) {
931 if (def->hash_reg_file)
934 if (def->unbound_nonreg_file)
935 req->work.flags |= IO_WQ_WORK_UNBOUND;
938 io_req_work_grab_env(req, def);
940 *link = io_prep_linked_timeout(req);
944 static inline void io_queue_async_work(struct io_kiocb *req)
946 struct io_ring_ctx *ctx = req->ctx;
947 struct io_kiocb *link;
950 do_hashed = io_prep_async_work(req, &link);
952 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
955 io_wq_enqueue(ctx->io_wq, &req->work);
957 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
958 file_inode(req->file));
962 io_queue_linked_timeout(link);
965 static void io_kill_timeout(struct io_kiocb *req)
969 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
971 atomic_inc(&req->ctx->cq_timeouts);
972 list_del_init(&req->list);
973 io_cqring_fill_event(req, 0);
978 static void io_kill_timeouts(struct io_ring_ctx *ctx)
980 struct io_kiocb *req, *tmp;
982 spin_lock_irq(&ctx->completion_lock);
983 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
984 io_kill_timeout(req);
985 spin_unlock_irq(&ctx->completion_lock);
988 static void io_commit_cqring(struct io_ring_ctx *ctx)
990 struct io_kiocb *req;
992 while ((req = io_get_timeout_req(ctx)) != NULL)
993 io_kill_timeout(req);
995 __io_commit_cqring(ctx);
997 while ((req = io_get_deferred_req(ctx)) != NULL)
998 io_queue_async_work(req);
1001 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1003 struct io_rings *rings = ctx->rings;
1006 tail = ctx->cached_cq_tail;
1008 * writes to the cq entry need to come after reading head; the
1009 * control dependency is enough as we're using WRITE_ONCE to
1012 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1015 ctx->cached_cq_tail++;
1016 return &rings->cqes[tail & ctx->cq_mask];
1019 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1023 if (!ctx->eventfd_async)
1025 return io_wq_current_is_worker() || in_interrupt();
1028 static void __io_cqring_ev_posted(struct io_ring_ctx *ctx, bool trigger_ev)
1030 if (waitqueue_active(&ctx->wait))
1031 wake_up(&ctx->wait);
1032 if (waitqueue_active(&ctx->sqo_wait))
1033 wake_up(&ctx->sqo_wait);
1035 eventfd_signal(ctx->cq_ev_fd, 1);
1038 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1040 __io_cqring_ev_posted(ctx, io_should_trigger_evfd(ctx));
1043 /* Returns true if there are no backlogged entries after the flush */
1044 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1046 struct io_rings *rings = ctx->rings;
1047 struct io_uring_cqe *cqe;
1048 struct io_kiocb *req;
1049 unsigned long flags;
1053 if (list_empty_careful(&ctx->cq_overflow_list))
1055 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1056 rings->cq_ring_entries))
1060 spin_lock_irqsave(&ctx->completion_lock, flags);
1062 /* if force is set, the ring is going away. always drop after that */
1064 ctx->cq_overflow_flushed = 1;
1067 while (!list_empty(&ctx->cq_overflow_list)) {
1068 cqe = io_get_cqring(ctx);
1072 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1074 list_move(&req->list, &list);
1076 WRITE_ONCE(cqe->user_data, req->user_data);
1077 WRITE_ONCE(cqe->res, req->result);
1078 WRITE_ONCE(cqe->flags, 0);
1080 WRITE_ONCE(ctx->rings->cq_overflow,
1081 atomic_inc_return(&ctx->cached_cq_overflow));
1085 io_commit_cqring(ctx);
1087 clear_bit(0, &ctx->sq_check_overflow);
1088 clear_bit(0, &ctx->cq_check_overflow);
1090 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1091 io_cqring_ev_posted(ctx);
1093 while (!list_empty(&list)) {
1094 req = list_first_entry(&list, struct io_kiocb, list);
1095 list_del(&req->list);
1102 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1104 struct io_ring_ctx *ctx = req->ctx;
1105 struct io_uring_cqe *cqe;
1107 trace_io_uring_complete(ctx, req->user_data, res);
1110 * If we can't get a cq entry, userspace overflowed the
1111 * submission (by quite a lot). Increment the overflow count in
1114 cqe = io_get_cqring(ctx);
1116 WRITE_ONCE(cqe->user_data, req->user_data);
1117 WRITE_ONCE(cqe->res, res);
1118 WRITE_ONCE(cqe->flags, 0);
1119 } else if (ctx->cq_overflow_flushed) {
1120 WRITE_ONCE(ctx->rings->cq_overflow,
1121 atomic_inc_return(&ctx->cached_cq_overflow));
1123 if (list_empty(&ctx->cq_overflow_list)) {
1124 set_bit(0, &ctx->sq_check_overflow);
1125 set_bit(0, &ctx->cq_check_overflow);
1127 refcount_inc(&req->refs);
1129 list_add_tail(&req->list, &ctx->cq_overflow_list);
1133 static void io_cqring_add_event(struct io_kiocb *req, long res)
1135 struct io_ring_ctx *ctx = req->ctx;
1136 unsigned long flags;
1138 spin_lock_irqsave(&ctx->completion_lock, flags);
1139 io_cqring_fill_event(req, res);
1140 io_commit_cqring(ctx);
1141 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1143 io_cqring_ev_posted(ctx);
1146 static inline bool io_is_fallback_req(struct io_kiocb *req)
1148 return req == (struct io_kiocb *)
1149 ((unsigned long) req->ctx->fallback_req & ~1UL);
1152 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1154 struct io_kiocb *req;
1156 req = ctx->fallback_req;
1157 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1163 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1164 struct io_submit_state *state)
1166 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1167 struct io_kiocb *req;
1170 req = kmem_cache_alloc(req_cachep, gfp);
1173 } else if (!state->free_reqs) {
1177 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1178 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1181 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1182 * retry single alloc to be on the safe side.
1184 if (unlikely(ret <= 0)) {
1185 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1186 if (!state->reqs[0])
1190 state->free_reqs = ret - 1;
1191 req = state->reqs[ret - 1];
1194 req = state->reqs[state->free_reqs];
1202 /* one is dropped after submission, the other at completion */
1203 refcount_set(&req->refs, 2);
1205 INIT_IO_WORK(&req->work, io_wq_submit_work);
1208 req = io_get_fallback_req(ctx);
1211 percpu_ref_put(&ctx->refs);
1215 static void __io_req_do_free(struct io_kiocb *req)
1217 if (likely(!io_is_fallback_req(req)))
1218 kmem_cache_free(req_cachep, req);
1220 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1223 static void __io_req_aux_free(struct io_kiocb *req)
1225 struct io_ring_ctx *ctx = req->ctx;
1229 if (req->flags & REQ_F_FIXED_FILE)
1230 percpu_ref_put(&ctx->file_data->refs);
1235 io_req_work_drop_env(req);
1238 static void __io_free_req(struct io_kiocb *req)
1240 __io_req_aux_free(req);
1242 if (req->flags & REQ_F_NEED_CLEANUP)
1243 io_cleanup_req(req);
1245 if (req->flags & REQ_F_INFLIGHT) {
1246 struct io_ring_ctx *ctx = req->ctx;
1247 unsigned long flags;
1249 spin_lock_irqsave(&ctx->inflight_lock, flags);
1250 list_del(&req->inflight_entry);
1251 if (waitqueue_active(&ctx->inflight_wait))
1252 wake_up(&ctx->inflight_wait);
1253 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1256 percpu_ref_put(&req->ctx->refs);
1257 __io_req_do_free(req);
1261 void *reqs[IO_IOPOLL_BATCH];
1266 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1268 int fixed_refs = rb->to_free;
1272 if (rb->need_iter) {
1273 int i, inflight = 0;
1274 unsigned long flags;
1277 for (i = 0; i < rb->to_free; i++) {
1278 struct io_kiocb *req = rb->reqs[i];
1280 if (req->flags & REQ_F_FIXED_FILE) {
1284 if (req->flags & REQ_F_INFLIGHT)
1286 __io_req_aux_free(req);
1291 spin_lock_irqsave(&ctx->inflight_lock, flags);
1292 for (i = 0; i < rb->to_free; i++) {
1293 struct io_kiocb *req = rb->reqs[i];
1295 if (req->flags & REQ_F_INFLIGHT) {
1296 list_del(&req->inflight_entry);
1301 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1303 if (waitqueue_active(&ctx->inflight_wait))
1304 wake_up(&ctx->inflight_wait);
1307 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1309 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1310 percpu_ref_put_many(&ctx->refs, rb->to_free);
1311 rb->to_free = rb->need_iter = 0;
1314 static bool io_link_cancel_timeout(struct io_kiocb *req)
1316 struct io_ring_ctx *ctx = req->ctx;
1319 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1321 io_cqring_fill_event(req, -ECANCELED);
1322 io_commit_cqring(ctx);
1323 req->flags &= ~REQ_F_LINK;
1331 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1333 struct io_ring_ctx *ctx = req->ctx;
1334 bool wake_ev = false;
1336 /* Already got next link */
1337 if (req->flags & REQ_F_LINK_NEXT)
1341 * The list should never be empty when we are called here. But could
1342 * potentially happen if the chain is messed up, check to be on the
1345 while (!list_empty(&req->link_list)) {
1346 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1347 struct io_kiocb, link_list);
1349 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1350 (nxt->flags & REQ_F_TIMEOUT))) {
1351 list_del_init(&nxt->link_list);
1352 wake_ev |= io_link_cancel_timeout(nxt);
1353 req->flags &= ~REQ_F_LINK_TIMEOUT;
1357 list_del_init(&req->link_list);
1358 if (!list_empty(&nxt->link_list))
1359 nxt->flags |= REQ_F_LINK;
1364 req->flags |= REQ_F_LINK_NEXT;
1366 io_cqring_ev_posted(ctx);
1370 * Called if REQ_F_LINK is set, and we fail the head request
1372 static void io_fail_links(struct io_kiocb *req)
1374 struct io_ring_ctx *ctx = req->ctx;
1375 unsigned long flags;
1377 spin_lock_irqsave(&ctx->completion_lock, flags);
1379 while (!list_empty(&req->link_list)) {
1380 struct io_kiocb *link = list_first_entry(&req->link_list,
1381 struct io_kiocb, link_list);
1383 list_del_init(&link->link_list);
1384 trace_io_uring_fail_link(req, link);
1386 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1387 link->opcode == IORING_OP_LINK_TIMEOUT) {
1388 io_link_cancel_timeout(link);
1390 io_cqring_fill_event(link, -ECANCELED);
1391 __io_double_put_req(link);
1393 req->flags &= ~REQ_F_LINK_TIMEOUT;
1396 io_commit_cqring(ctx);
1397 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1398 io_cqring_ev_posted(ctx);
1401 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1403 if (likely(!(req->flags & REQ_F_LINK)))
1407 * If LINK is set, we have dependent requests in this chain. If we
1408 * didn't fail this request, queue the first one up, moving any other
1409 * dependencies to the next request. In case of failure, fail the rest
1412 if (req->flags & REQ_F_FAIL_LINK) {
1414 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1415 REQ_F_LINK_TIMEOUT) {
1416 struct io_ring_ctx *ctx = req->ctx;
1417 unsigned long flags;
1420 * If this is a timeout link, we could be racing with the
1421 * timeout timer. Grab the completion lock for this case to
1422 * protect against that.
1424 spin_lock_irqsave(&ctx->completion_lock, flags);
1425 io_req_link_next(req, nxt);
1426 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1428 io_req_link_next(req, nxt);
1432 static void io_free_req(struct io_kiocb *req)
1434 struct io_kiocb *nxt = NULL;
1436 io_req_find_next(req, &nxt);
1440 io_queue_async_work(nxt);
1444 * Drop reference to request, return next in chain (if there is one) if this
1445 * was the last reference to this request.
1447 __attribute__((nonnull))
1448 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1450 io_req_find_next(req, nxtptr);
1452 if (refcount_dec_and_test(&req->refs))
1456 static void io_put_req(struct io_kiocb *req)
1458 if (refcount_dec_and_test(&req->refs))
1463 * Must only be used if we don't need to care about links, usually from
1464 * within the completion handling itself.
1466 static void __io_double_put_req(struct io_kiocb *req)
1468 /* drop both submit and complete references */
1469 if (refcount_sub_and_test(2, &req->refs))
1473 static void io_double_put_req(struct io_kiocb *req)
1475 /* drop both submit and complete references */
1476 if (refcount_sub_and_test(2, &req->refs))
1480 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1482 struct io_rings *rings = ctx->rings;
1484 if (test_bit(0, &ctx->cq_check_overflow)) {
1486 * noflush == true is from the waitqueue handler, just ensure
1487 * we wake up the task, and the next invocation will flush the
1488 * entries. We cannot safely to it from here.
1490 if (noflush && !list_empty(&ctx->cq_overflow_list))
1493 io_cqring_overflow_flush(ctx, false);
1496 /* See comment at the top of this file */
1498 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1501 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1503 struct io_rings *rings = ctx->rings;
1505 /* make sure SQ entry isn't read before tail */
1506 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1509 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1511 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1514 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1517 rb->reqs[rb->to_free++] = req;
1518 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1519 io_free_req_many(req->ctx, rb);
1524 * Find and free completed poll iocbs
1526 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1527 struct list_head *done)
1529 struct req_batch rb;
1530 struct io_kiocb *req;
1532 rb.to_free = rb.need_iter = 0;
1533 while (!list_empty(done)) {
1534 req = list_first_entry(done, struct io_kiocb, list);
1535 list_del(&req->list);
1537 io_cqring_fill_event(req, req->result);
1540 if (refcount_dec_and_test(&req->refs) &&
1541 !io_req_multi_free(&rb, req))
1545 io_commit_cqring(ctx);
1546 io_free_req_many(ctx, &rb);
1549 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1552 struct io_kiocb *req, *tmp;
1558 * Only spin for completions if we don't have multiple devices hanging
1559 * off our complete list, and we're under the requested amount.
1561 spin = !ctx->poll_multi_file && *nr_events < min;
1564 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1565 struct kiocb *kiocb = &req->rw.kiocb;
1568 * Move completed entries to our local list. If we find a
1569 * request that requires polling, break out and complete
1570 * the done list first, if we have entries there.
1572 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1573 list_move_tail(&req->list, &done);
1576 if (!list_empty(&done))
1579 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1588 if (!list_empty(&done))
1589 io_iopoll_complete(ctx, nr_events, &done);
1595 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1596 * non-spinning poll check - we'll still enter the driver poll loop, but only
1597 * as a non-spinning completion check.
1599 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1602 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1605 ret = io_do_iopoll(ctx, nr_events, min);
1608 if (!min || *nr_events >= min)
1616 * We can't just wait for polled events to come to us, we have to actively
1617 * find and complete them.
1619 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1621 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1624 mutex_lock(&ctx->uring_lock);
1625 while (!list_empty(&ctx->poll_list)) {
1626 unsigned int nr_events = 0;
1628 io_iopoll_getevents(ctx, &nr_events, 1);
1631 * Ensure we allow local-to-the-cpu processing to take place,
1632 * in this case we need to ensure that we reap all events.
1636 mutex_unlock(&ctx->uring_lock);
1639 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1642 int iters = 0, ret = 0;
1648 * Don't enter poll loop if we already have events pending.
1649 * If we do, we can potentially be spinning for commands that
1650 * already triggered a CQE (eg in error).
1652 if (io_cqring_events(ctx, false))
1656 * If a submit got punted to a workqueue, we can have the
1657 * application entering polling for a command before it gets
1658 * issued. That app will hold the uring_lock for the duration
1659 * of the poll right here, so we need to take a breather every
1660 * now and then to ensure that the issue has a chance to add
1661 * the poll to the issued list. Otherwise we can spin here
1662 * forever, while the workqueue is stuck trying to acquire the
1665 if (!(++iters & 7)) {
1666 mutex_unlock(&ctx->uring_lock);
1667 mutex_lock(&ctx->uring_lock);
1670 if (*nr_events < min)
1671 tmin = min - *nr_events;
1673 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1677 } while (min && !*nr_events && !need_resched());
1682 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1688 * We disallow the app entering submit/complete with polling, but we
1689 * still need to lock the ring to prevent racing with polled issue
1690 * that got punted to a workqueue.
1692 mutex_lock(&ctx->uring_lock);
1693 ret = __io_iopoll_check(ctx, nr_events, min);
1694 mutex_unlock(&ctx->uring_lock);
1698 static void kiocb_end_write(struct io_kiocb *req)
1701 * Tell lockdep we inherited freeze protection from submission
1704 if (req->flags & REQ_F_ISREG) {
1705 struct inode *inode = file_inode(req->file);
1707 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1709 file_end_write(req->file);
1712 static inline void req_set_fail_links(struct io_kiocb *req)
1714 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1715 req->flags |= REQ_F_FAIL_LINK;
1718 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1720 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1722 if (kiocb->ki_flags & IOCB_WRITE)
1723 kiocb_end_write(req);
1725 if (res != req->result)
1726 req_set_fail_links(req);
1727 io_cqring_add_event(req, res);
1730 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1732 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1734 io_complete_rw_common(kiocb, res);
1738 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1740 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1741 struct io_kiocb *nxt = NULL;
1743 io_complete_rw_common(kiocb, res);
1744 io_put_req_find_next(req, &nxt);
1749 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1751 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1753 if (kiocb->ki_flags & IOCB_WRITE)
1754 kiocb_end_write(req);
1756 if (res != req->result)
1757 req_set_fail_links(req);
1760 req->flags |= REQ_F_IOPOLL_COMPLETED;
1764 * After the iocb has been issued, it's safe to be found on the poll list.
1765 * Adding the kiocb to the list AFTER submission ensures that we don't
1766 * find it from a io_iopoll_getevents() thread before the issuer is done
1767 * accessing the kiocb cookie.
1769 static void io_iopoll_req_issued(struct io_kiocb *req)
1771 struct io_ring_ctx *ctx = req->ctx;
1774 * Track whether we have multiple files in our lists. This will impact
1775 * how we do polling eventually, not spinning if we're on potentially
1776 * different devices.
1778 if (list_empty(&ctx->poll_list)) {
1779 ctx->poll_multi_file = false;
1780 } else if (!ctx->poll_multi_file) {
1781 struct io_kiocb *list_req;
1783 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1785 if (list_req->file != req->file)
1786 ctx->poll_multi_file = true;
1790 * For fast devices, IO may have already completed. If it has, add
1791 * it to the front so we find it first.
1793 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1794 list_add(&req->list, &ctx->poll_list);
1796 list_add_tail(&req->list, &ctx->poll_list);
1799 static void io_file_put(struct io_submit_state *state)
1802 int diff = state->has_refs - state->used_refs;
1805 fput_many(state->file, diff);
1811 * Get as many references to a file as we have IOs left in this submission,
1812 * assuming most submissions are for one file, or at least that each file
1813 * has more than one submission.
1815 static struct file *io_file_get(struct io_submit_state *state, int fd)
1821 if (state->fd == fd) {
1828 state->file = fget_many(fd, state->ios_left);
1833 state->has_refs = state->ios_left;
1834 state->used_refs = 1;
1840 * If we tracked the file through the SCM inflight mechanism, we could support
1841 * any file. For now, just ensure that anything potentially problematic is done
1844 static bool io_file_supports_async(struct file *file)
1846 umode_t mode = file_inode(file)->i_mode;
1848 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1850 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1856 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1857 bool force_nonblock)
1859 struct io_ring_ctx *ctx = req->ctx;
1860 struct kiocb *kiocb = &req->rw.kiocb;
1864 if (S_ISREG(file_inode(req->file)->i_mode))
1865 req->flags |= REQ_F_ISREG;
1867 kiocb->ki_pos = READ_ONCE(sqe->off);
1868 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1869 req->flags |= REQ_F_CUR_POS;
1870 kiocb->ki_pos = req->file->f_pos;
1872 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1873 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1874 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1878 ioprio = READ_ONCE(sqe->ioprio);
1880 ret = ioprio_check_cap(ioprio);
1884 kiocb->ki_ioprio = ioprio;
1886 kiocb->ki_ioprio = get_current_ioprio();
1888 /* don't allow async punt if RWF_NOWAIT was requested */
1889 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1890 (req->file->f_flags & O_NONBLOCK))
1891 req->flags |= REQ_F_NOWAIT;
1894 kiocb->ki_flags |= IOCB_NOWAIT;
1896 if (ctx->flags & IORING_SETUP_IOPOLL) {
1897 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1898 !kiocb->ki_filp->f_op->iopoll)
1901 kiocb->ki_flags |= IOCB_HIPRI;
1902 kiocb->ki_complete = io_complete_rw_iopoll;
1905 if (kiocb->ki_flags & IOCB_HIPRI)
1907 kiocb->ki_complete = io_complete_rw;
1910 req->rw.addr = READ_ONCE(sqe->addr);
1911 req->rw.len = READ_ONCE(sqe->len);
1912 /* we own ->private, reuse it for the buffer index */
1913 req->rw.kiocb.private = (void *) (unsigned long)
1914 READ_ONCE(sqe->buf_index);
1918 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1924 case -ERESTARTNOINTR:
1925 case -ERESTARTNOHAND:
1926 case -ERESTART_RESTARTBLOCK:
1928 * We can't just restart the syscall, since previously
1929 * submitted sqes may already be in progress. Just fail this
1935 kiocb->ki_complete(kiocb, ret, 0);
1939 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1942 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1944 if (req->flags & REQ_F_CUR_POS)
1945 req->file->f_pos = kiocb->ki_pos;
1946 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1947 *nxt = __io_complete_rw(kiocb, ret);
1949 io_rw_done(kiocb, ret);
1952 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1953 struct iov_iter *iter)
1955 struct io_ring_ctx *ctx = req->ctx;
1956 size_t len = req->rw.len;
1957 struct io_mapped_ubuf *imu;
1958 unsigned index, buf_index;
1962 /* attempt to use fixed buffers without having provided iovecs */
1963 if (unlikely(!ctx->user_bufs))
1966 buf_index = (unsigned long) req->rw.kiocb.private;
1967 if (unlikely(buf_index >= ctx->nr_user_bufs))
1970 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1971 imu = &ctx->user_bufs[index];
1972 buf_addr = req->rw.addr;
1975 if (buf_addr + len < buf_addr)
1977 /* not inside the mapped region */
1978 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1982 * May not be a start of buffer, set size appropriately
1983 * and advance us to the beginning.
1985 offset = buf_addr - imu->ubuf;
1986 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1990 * Don't use iov_iter_advance() here, as it's really slow for
1991 * using the latter parts of a big fixed buffer - it iterates
1992 * over each segment manually. We can cheat a bit here, because
1995 * 1) it's a BVEC iter, we set it up
1996 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1997 * first and last bvec
1999 * So just find our index, and adjust the iterator afterwards.
2000 * If the offset is within the first bvec (or the whole first
2001 * bvec, just use iov_iter_advance(). This makes it easier
2002 * since we can just skip the first segment, which may not
2003 * be PAGE_SIZE aligned.
2005 const struct bio_vec *bvec = imu->bvec;
2007 if (offset <= bvec->bv_len) {
2008 iov_iter_advance(iter, offset);
2010 unsigned long seg_skip;
2012 /* skip first vec */
2013 offset -= bvec->bv_len;
2014 seg_skip = 1 + (offset >> PAGE_SHIFT);
2016 iter->bvec = bvec + seg_skip;
2017 iter->nr_segs -= seg_skip;
2018 iter->count -= bvec->bv_len + offset;
2019 iter->iov_offset = offset & ~PAGE_MASK;
2026 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2027 struct iovec **iovec, struct iov_iter *iter)
2029 void __user *buf = u64_to_user_ptr(req->rw.addr);
2030 size_t sqe_len = req->rw.len;
2033 opcode = req->opcode;
2034 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2036 return io_import_fixed(req, rw, iter);
2039 /* buffer index only valid with fixed read/write */
2040 if (req->rw.kiocb.private)
2043 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2045 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2051 struct io_async_rw *iorw = &req->io->rw;
2054 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2055 if (iorw->iov == iorw->fast_iov)
2060 #ifdef CONFIG_COMPAT
2061 if (req->ctx->compat)
2062 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2066 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2070 * For files that don't have ->read_iter() and ->write_iter(), handle them
2071 * by looping over ->read() or ->write() manually.
2073 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2074 struct iov_iter *iter)
2079 * Don't support polled IO through this interface, and we can't
2080 * support non-blocking either. For the latter, this just causes
2081 * the kiocb to be handled from an async context.
2083 if (kiocb->ki_flags & IOCB_HIPRI)
2085 if (kiocb->ki_flags & IOCB_NOWAIT)
2088 while (iov_iter_count(iter)) {
2092 if (!iov_iter_is_bvec(iter)) {
2093 iovec = iov_iter_iovec(iter);
2095 /* fixed buffers import bvec */
2096 iovec.iov_base = kmap(iter->bvec->bv_page)
2098 iovec.iov_len = min(iter->count,
2099 iter->bvec->bv_len - iter->iov_offset);
2103 nr = file->f_op->read(file, iovec.iov_base,
2104 iovec.iov_len, &kiocb->ki_pos);
2106 nr = file->f_op->write(file, iovec.iov_base,
2107 iovec.iov_len, &kiocb->ki_pos);
2110 if (iov_iter_is_bvec(iter))
2111 kunmap(iter->bvec->bv_page);
2119 if (nr != iovec.iov_len)
2121 iov_iter_advance(iter, nr);
2127 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2128 struct iovec *iovec, struct iovec *fast_iov,
2129 struct iov_iter *iter)
2131 req->io->rw.nr_segs = iter->nr_segs;
2132 req->io->rw.size = io_size;
2133 req->io->rw.iov = iovec;
2134 if (!req->io->rw.iov) {
2135 req->io->rw.iov = req->io->rw.fast_iov;
2136 memcpy(req->io->rw.iov, fast_iov,
2137 sizeof(struct iovec) * iter->nr_segs);
2139 req->flags |= REQ_F_NEED_CLEANUP;
2143 static int io_alloc_async_ctx(struct io_kiocb *req)
2145 if (!io_op_defs[req->opcode].async_ctx)
2147 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2148 return req->io == NULL;
2151 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2152 struct iovec *iovec, struct iovec *fast_iov,
2153 struct iov_iter *iter)
2155 if (!io_op_defs[req->opcode].async_ctx)
2158 if (io_alloc_async_ctx(req))
2161 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2166 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2167 bool force_nonblock)
2169 struct io_async_ctx *io;
2170 struct iov_iter iter;
2173 ret = io_prep_rw(req, sqe, force_nonblock);
2177 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2184 io->rw.iov = io->rw.fast_iov;
2186 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2191 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2195 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2196 bool force_nonblock)
2198 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2199 struct kiocb *kiocb = &req->rw.kiocb;
2200 struct iov_iter iter;
2202 ssize_t io_size, ret;
2204 ret = io_import_iovec(READ, req, &iovec, &iter);
2208 /* Ensure we clear previously set non-block flag */
2209 if (!force_nonblock)
2210 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2214 if (req->flags & REQ_F_LINK)
2215 req->result = io_size;
2218 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2219 * we know to async punt it even if it was opened O_NONBLOCK
2221 if (force_nonblock && !io_file_supports_async(req->file)) {
2222 req->flags |= REQ_F_MUST_PUNT;
2226 iov_count = iov_iter_count(&iter);
2227 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2231 if (req->file->f_op->read_iter)
2232 ret2 = call_read_iter(req->file, kiocb, &iter);
2234 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2236 /* Catch -EAGAIN return for forced non-blocking submission */
2237 if (!force_nonblock || ret2 != -EAGAIN) {
2238 kiocb_done(kiocb, ret2, nxt, req->in_async);
2241 ret = io_setup_async_rw(req, io_size, iovec,
2242 inline_vecs, &iter);
2250 req->flags &= ~REQ_F_NEED_CLEANUP;
2254 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2255 bool force_nonblock)
2257 struct io_async_ctx *io;
2258 struct iov_iter iter;
2261 ret = io_prep_rw(req, sqe, force_nonblock);
2265 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2272 io->rw.iov = io->rw.fast_iov;
2274 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2279 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2283 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2284 bool force_nonblock)
2286 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2287 struct kiocb *kiocb = &req->rw.kiocb;
2288 struct iov_iter iter;
2290 ssize_t ret, io_size;
2292 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2296 /* Ensure we clear previously set non-block flag */
2297 if (!force_nonblock)
2298 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2302 if (req->flags & REQ_F_LINK)
2303 req->result = io_size;
2306 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2307 * we know to async punt it even if it was opened O_NONBLOCK
2309 if (force_nonblock && !io_file_supports_async(req->file)) {
2310 req->flags |= REQ_F_MUST_PUNT;
2314 /* file path doesn't support NOWAIT for non-direct_IO */
2315 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2316 (req->flags & REQ_F_ISREG))
2319 iov_count = iov_iter_count(&iter);
2320 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2325 * Open-code file_start_write here to grab freeze protection,
2326 * which will be released by another thread in
2327 * io_complete_rw(). Fool lockdep by telling it the lock got
2328 * released so that it doesn't complain about the held lock when
2329 * we return to userspace.
2331 if (req->flags & REQ_F_ISREG) {
2332 __sb_start_write(file_inode(req->file)->i_sb,
2333 SB_FREEZE_WRITE, true);
2334 __sb_writers_release(file_inode(req->file)->i_sb,
2337 kiocb->ki_flags |= IOCB_WRITE;
2339 if (req->file->f_op->write_iter)
2340 ret2 = call_write_iter(req->file, kiocb, &iter);
2342 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2344 * Raw bdev writes will -EOPNOTSUPP for IOCB_NOWAIT. Just
2345 * retry them without IOCB_NOWAIT.
2347 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2349 if (!force_nonblock || ret2 != -EAGAIN) {
2350 kiocb_done(kiocb, ret2, nxt, req->in_async);
2353 ret = io_setup_async_rw(req, io_size, iovec,
2354 inline_vecs, &iter);
2361 req->flags &= ~REQ_F_NEED_CLEANUP;
2367 * IORING_OP_NOP just posts a completion event, nothing else.
2369 static int io_nop(struct io_kiocb *req)
2371 struct io_ring_ctx *ctx = req->ctx;
2373 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2376 io_cqring_add_event(req, 0);
2381 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2383 struct io_ring_ctx *ctx = req->ctx;
2388 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2390 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2393 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2394 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2397 req->sync.off = READ_ONCE(sqe->off);
2398 req->sync.len = READ_ONCE(sqe->len);
2402 static bool io_req_cancelled(struct io_kiocb *req)
2404 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2405 req_set_fail_links(req);
2406 io_cqring_add_event(req, -ECANCELED);
2414 static void io_link_work_cb(struct io_wq_work **workptr)
2416 struct io_wq_work *work = *workptr;
2417 struct io_kiocb *link = work->data;
2419 io_queue_linked_timeout(link);
2420 work->func = io_wq_submit_work;
2423 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2425 struct io_kiocb *link;
2427 io_prep_async_work(nxt, &link);
2428 *workptr = &nxt->work;
2430 nxt->work.flags |= IO_WQ_WORK_CB;
2431 nxt->work.func = io_link_work_cb;
2432 nxt->work.data = link;
2436 static void io_fsync_finish(struct io_wq_work **workptr)
2438 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2439 loff_t end = req->sync.off + req->sync.len;
2440 struct io_kiocb *nxt = NULL;
2443 if (io_req_cancelled(req))
2446 ret = vfs_fsync_range(req->file, req->sync.off,
2447 end > 0 ? end : LLONG_MAX,
2448 req->sync.flags & IORING_FSYNC_DATASYNC);
2450 req_set_fail_links(req);
2451 io_cqring_add_event(req, ret);
2452 io_put_req_find_next(req, &nxt);
2454 io_wq_assign_next(workptr, nxt);
2457 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2458 bool force_nonblock)
2460 struct io_wq_work *work, *old_work;
2462 /* fsync always requires a blocking context */
2463 if (force_nonblock) {
2465 req->work.func = io_fsync_finish;
2469 work = old_work = &req->work;
2470 io_fsync_finish(&work);
2471 if (work && work != old_work)
2472 *nxt = container_of(work, struct io_kiocb, work);
2476 static void io_fallocate_finish(struct io_wq_work **workptr)
2478 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2479 struct io_kiocb *nxt = NULL;
2482 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2485 req_set_fail_links(req);
2486 io_cqring_add_event(req, ret);
2487 io_put_req_find_next(req, &nxt);
2489 io_wq_assign_next(workptr, nxt);
2492 static int io_fallocate_prep(struct io_kiocb *req,
2493 const struct io_uring_sqe *sqe)
2495 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2498 req->sync.off = READ_ONCE(sqe->off);
2499 req->sync.len = READ_ONCE(sqe->addr);
2500 req->sync.mode = READ_ONCE(sqe->len);
2504 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2505 bool force_nonblock)
2507 struct io_wq_work *work, *old_work;
2509 /* fallocate always requiring blocking context */
2510 if (force_nonblock) {
2512 req->work.func = io_fallocate_finish;
2516 work = old_work = &req->work;
2517 io_fallocate_finish(&work);
2518 if (work && work != old_work)
2519 *nxt = container_of(work, struct io_kiocb, work);
2524 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2526 const char __user *fname;
2529 if (sqe->ioprio || sqe->buf_index)
2531 if (sqe->flags & IOSQE_FIXED_FILE)
2534 req->open.dfd = READ_ONCE(sqe->fd);
2535 req->open.how.mode = READ_ONCE(sqe->len);
2536 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2537 req->open.how.flags = READ_ONCE(sqe->open_flags);
2539 req->open.filename = getname(fname);
2540 if (IS_ERR(req->open.filename)) {
2541 ret = PTR_ERR(req->open.filename);
2542 req->open.filename = NULL;
2546 req->flags |= REQ_F_NEED_CLEANUP;
2550 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2552 struct open_how __user *how;
2553 const char __user *fname;
2557 if (sqe->ioprio || sqe->buf_index)
2559 if (sqe->flags & IOSQE_FIXED_FILE)
2562 req->open.dfd = READ_ONCE(sqe->fd);
2563 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2564 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2565 len = READ_ONCE(sqe->len);
2567 if (len < OPEN_HOW_SIZE_VER0)
2570 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2575 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2576 req->open.how.flags |= O_LARGEFILE;
2578 req->open.filename = getname(fname);
2579 if (IS_ERR(req->open.filename)) {
2580 ret = PTR_ERR(req->open.filename);
2581 req->open.filename = NULL;
2585 req->flags |= REQ_F_NEED_CLEANUP;
2589 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2590 bool force_nonblock)
2592 struct open_flags op;
2599 ret = build_open_flags(&req->open.how, &op);
2603 ret = get_unused_fd_flags(req->open.how.flags);
2607 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2610 ret = PTR_ERR(file);
2612 fsnotify_open(file);
2613 fd_install(ret, file);
2616 putname(req->open.filename);
2617 req->flags &= ~REQ_F_NEED_CLEANUP;
2619 req_set_fail_links(req);
2620 io_cqring_add_event(req, ret);
2621 io_put_req_find_next(req, nxt);
2625 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2626 bool force_nonblock)
2628 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2629 return io_openat2(req, nxt, force_nonblock);
2632 static int io_epoll_ctl_prep(struct io_kiocb *req,
2633 const struct io_uring_sqe *sqe)
2635 #if defined(CONFIG_EPOLL)
2636 if (sqe->ioprio || sqe->buf_index)
2639 req->epoll.epfd = READ_ONCE(sqe->fd);
2640 req->epoll.op = READ_ONCE(sqe->len);
2641 req->epoll.fd = READ_ONCE(sqe->off);
2643 if (ep_op_has_event(req->epoll.op)) {
2644 struct epoll_event __user *ev;
2646 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
2647 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
2657 static int io_epoll_ctl(struct io_kiocb *req, struct io_kiocb **nxt,
2658 bool force_nonblock)
2660 #if defined(CONFIG_EPOLL)
2661 struct io_epoll *ie = &req->epoll;
2664 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
2665 if (force_nonblock && ret == -EAGAIN)
2669 req_set_fail_links(req);
2670 io_cqring_add_event(req, ret);
2671 io_put_req_find_next(req, nxt);
2678 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2680 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2681 if (sqe->ioprio || sqe->buf_index || sqe->off)
2684 req->madvise.addr = READ_ONCE(sqe->addr);
2685 req->madvise.len = READ_ONCE(sqe->len);
2686 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2693 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2694 bool force_nonblock)
2696 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2697 struct io_madvise *ma = &req->madvise;
2703 ret = do_madvise(ma->addr, ma->len, ma->advice);
2705 req_set_fail_links(req);
2706 io_cqring_add_event(req, ret);
2707 io_put_req_find_next(req, nxt);
2714 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2716 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2719 req->fadvise.offset = READ_ONCE(sqe->off);
2720 req->fadvise.len = READ_ONCE(sqe->len);
2721 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2725 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2726 bool force_nonblock)
2728 struct io_fadvise *fa = &req->fadvise;
2731 if (force_nonblock) {
2732 switch (fa->advice) {
2733 case POSIX_FADV_NORMAL:
2734 case POSIX_FADV_RANDOM:
2735 case POSIX_FADV_SEQUENTIAL:
2742 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2744 req_set_fail_links(req);
2745 io_cqring_add_event(req, ret);
2746 io_put_req_find_next(req, nxt);
2750 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2752 const char __user *fname;
2753 unsigned lookup_flags;
2756 if (sqe->ioprio || sqe->buf_index)
2758 if (sqe->flags & IOSQE_FIXED_FILE)
2761 req->open.dfd = READ_ONCE(sqe->fd);
2762 req->open.mask = READ_ONCE(sqe->len);
2763 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2764 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2765 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2767 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2770 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2771 if (IS_ERR(req->open.filename)) {
2772 ret = PTR_ERR(req->open.filename);
2773 req->open.filename = NULL;
2777 req->flags |= REQ_F_NEED_CLEANUP;
2781 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2782 bool force_nonblock)
2784 struct io_open *ctx = &req->open;
2785 unsigned lookup_flags;
2793 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2797 /* filename_lookup() drops it, keep a reference */
2798 ctx->filename->refcnt++;
2800 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2805 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2807 if (retry_estale(ret, lookup_flags)) {
2808 lookup_flags |= LOOKUP_REVAL;
2812 ret = cp_statx(&stat, ctx->buffer);
2814 putname(ctx->filename);
2815 req->flags &= ~REQ_F_NEED_CLEANUP;
2817 req_set_fail_links(req);
2818 io_cqring_add_event(req, ret);
2819 io_put_req_find_next(req, nxt);
2823 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2826 * If we queue this for async, it must not be cancellable. That would
2827 * leave the 'file' in an undeterminate state.
2829 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2831 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2832 sqe->rw_flags || sqe->buf_index)
2834 if (sqe->flags & IOSQE_FIXED_FILE)
2837 req->close.fd = READ_ONCE(sqe->fd);
2838 if (req->file->f_op == &io_uring_fops ||
2839 req->close.fd == req->ctx->ring_fd)
2845 static void io_close_finish(struct io_wq_work **workptr)
2847 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2848 struct io_kiocb *nxt = NULL;
2850 /* Invoked with files, we need to do the close */
2851 if (req->work.files) {
2854 ret = filp_close(req->close.put_file, req->work.files);
2856 req_set_fail_links(req);
2857 io_cqring_add_event(req, ret);
2860 fput(req->close.put_file);
2862 io_put_req_find_next(req, &nxt);
2864 io_wq_assign_next(workptr, nxt);
2867 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2868 bool force_nonblock)
2872 req->close.put_file = NULL;
2873 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2877 /* if the file has a flush method, be safe and punt to async */
2878 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker())
2882 * No ->flush(), safely close from here and just punt the
2883 * fput() to async context.
2885 ret = filp_close(req->close.put_file, current->files);
2888 req_set_fail_links(req);
2889 io_cqring_add_event(req, ret);
2891 if (io_wq_current_is_worker()) {
2892 struct io_wq_work *old_work, *work;
2894 old_work = work = &req->work;
2895 io_close_finish(&work);
2896 if (work && work != old_work)
2897 *nxt = container_of(work, struct io_kiocb, work);
2902 req->work.func = io_close_finish;
2904 * Do manual async queue here to avoid grabbing files - we don't
2905 * need the files, and it'll cause io_close_finish() to close
2906 * the file again and cause a double CQE entry for this request
2908 io_queue_async_work(req);
2912 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2914 struct io_ring_ctx *ctx = req->ctx;
2919 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2921 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2924 req->sync.off = READ_ONCE(sqe->off);
2925 req->sync.len = READ_ONCE(sqe->len);
2926 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2930 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2932 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2933 struct io_kiocb *nxt = NULL;
2936 if (io_req_cancelled(req))
2939 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2942 req_set_fail_links(req);
2943 io_cqring_add_event(req, ret);
2944 io_put_req_find_next(req, &nxt);
2946 io_wq_assign_next(workptr, nxt);
2949 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2950 bool force_nonblock)
2952 struct io_wq_work *work, *old_work;
2954 /* sync_file_range always requires a blocking context */
2955 if (force_nonblock) {
2957 req->work.func = io_sync_file_range_finish;
2961 work = old_work = &req->work;
2962 io_sync_file_range_finish(&work);
2963 if (work && work != old_work)
2964 *nxt = container_of(work, struct io_kiocb, work);
2968 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2970 #if defined(CONFIG_NET)
2971 struct io_sr_msg *sr = &req->sr_msg;
2972 struct io_async_ctx *io = req->io;
2975 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2976 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2977 sr->len = READ_ONCE(sqe->len);
2979 if (!io || req->opcode == IORING_OP_SEND)
2982 io->msg.iov = io->msg.fast_iov;
2983 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2986 req->flags |= REQ_F_NEED_CLEANUP;
2993 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2994 bool force_nonblock)
2996 #if defined(CONFIG_NET)
2997 struct io_async_msghdr *kmsg = NULL;
2998 struct socket *sock;
3001 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3004 sock = sock_from_file(req->file, &ret);
3006 struct io_async_ctx io;
3007 struct sockaddr_storage addr;
3011 kmsg = &req->io->msg;
3012 kmsg->msg.msg_name = &addr;
3013 /* if iov is set, it's allocated already */
3015 kmsg->iov = kmsg->fast_iov;
3016 kmsg->msg.msg_iter.iov = kmsg->iov;
3018 struct io_sr_msg *sr = &req->sr_msg;
3021 kmsg->msg.msg_name = &addr;
3023 io.msg.iov = io.msg.fast_iov;
3024 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3025 sr->msg_flags, &io.msg.iov);
3030 flags = req->sr_msg.msg_flags;
3031 if (flags & MSG_DONTWAIT)
3032 req->flags |= REQ_F_NOWAIT;
3033 else if (force_nonblock)
3034 flags |= MSG_DONTWAIT;
3036 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3037 if (force_nonblock && ret == -EAGAIN) {
3040 if (io_alloc_async_ctx(req)) {
3041 if (kmsg && kmsg->iov != kmsg->fast_iov)
3045 req->flags |= REQ_F_NEED_CLEANUP;
3046 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3049 if (ret == -ERESTARTSYS)
3053 if (kmsg && kmsg->iov != kmsg->fast_iov)
3055 req->flags &= ~REQ_F_NEED_CLEANUP;
3056 io_cqring_add_event(req, ret);
3058 req_set_fail_links(req);
3059 io_put_req_find_next(req, nxt);
3066 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
3067 bool force_nonblock)
3069 #if defined(CONFIG_NET)
3070 struct socket *sock;
3073 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3076 sock = sock_from_file(req->file, &ret);
3078 struct io_sr_msg *sr = &req->sr_msg;
3083 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3088 msg.msg_name = NULL;
3089 msg.msg_control = NULL;
3090 msg.msg_controllen = 0;
3091 msg.msg_namelen = 0;
3093 flags = req->sr_msg.msg_flags;
3094 if (flags & MSG_DONTWAIT)
3095 req->flags |= REQ_F_NOWAIT;
3096 else if (force_nonblock)
3097 flags |= MSG_DONTWAIT;
3099 msg.msg_flags = flags;
3100 ret = sock_sendmsg(sock, &msg);
3101 if (force_nonblock && ret == -EAGAIN)
3103 if (ret == -ERESTARTSYS)
3107 io_cqring_add_event(req, ret);
3109 req_set_fail_links(req);
3110 io_put_req_find_next(req, nxt);
3117 static int io_recvmsg_prep(struct io_kiocb *req,
3118 const struct io_uring_sqe *sqe)
3120 #if defined(CONFIG_NET)
3121 struct io_sr_msg *sr = &req->sr_msg;
3122 struct io_async_ctx *io = req->io;
3125 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3126 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3127 sr->len = READ_ONCE(sqe->len);
3129 if (!io || req->opcode == IORING_OP_RECV)
3132 io->msg.iov = io->msg.fast_iov;
3133 ret = recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3134 &io->msg.uaddr, &io->msg.iov);
3136 req->flags |= REQ_F_NEED_CLEANUP;
3143 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3144 bool force_nonblock)
3146 #if defined(CONFIG_NET)
3147 struct io_async_msghdr *kmsg = NULL;
3148 struct socket *sock;
3151 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3154 sock = sock_from_file(req->file, &ret);
3156 struct io_async_ctx io;
3157 struct sockaddr_storage addr;
3161 kmsg = &req->io->msg;
3162 kmsg->msg.msg_name = &addr;
3163 /* if iov is set, it's allocated already */
3165 kmsg->iov = kmsg->fast_iov;
3166 kmsg->msg.msg_iter.iov = kmsg->iov;
3168 struct io_sr_msg *sr = &req->sr_msg;
3171 kmsg->msg.msg_name = &addr;
3173 io.msg.iov = io.msg.fast_iov;
3174 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3175 sr->msg_flags, &io.msg.uaddr,
3181 flags = req->sr_msg.msg_flags;
3182 if (flags & MSG_DONTWAIT)
3183 req->flags |= REQ_F_NOWAIT;
3184 else if (force_nonblock)
3185 flags |= MSG_DONTWAIT;
3187 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3188 kmsg->uaddr, flags);
3189 if (force_nonblock && ret == -EAGAIN) {
3192 if (io_alloc_async_ctx(req)) {
3193 if (kmsg && kmsg->iov != kmsg->fast_iov)
3197 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3198 req->flags |= REQ_F_NEED_CLEANUP;
3201 if (ret == -ERESTARTSYS)
3205 if (kmsg && kmsg->iov != kmsg->fast_iov)
3207 req->flags &= ~REQ_F_NEED_CLEANUP;
3208 io_cqring_add_event(req, ret);
3210 req_set_fail_links(req);
3211 io_put_req_find_next(req, nxt);
3218 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3219 bool force_nonblock)
3221 #if defined(CONFIG_NET)
3222 struct socket *sock;
3225 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3228 sock = sock_from_file(req->file, &ret);
3230 struct io_sr_msg *sr = &req->sr_msg;
3235 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3240 msg.msg_name = NULL;
3241 msg.msg_control = NULL;
3242 msg.msg_controllen = 0;
3243 msg.msg_namelen = 0;
3244 msg.msg_iocb = NULL;
3247 flags = req->sr_msg.msg_flags;
3248 if (flags & MSG_DONTWAIT)
3249 req->flags |= REQ_F_NOWAIT;
3250 else if (force_nonblock)
3251 flags |= MSG_DONTWAIT;
3253 ret = sock_recvmsg(sock, &msg, flags);
3254 if (force_nonblock && ret == -EAGAIN)
3256 if (ret == -ERESTARTSYS)
3260 io_cqring_add_event(req, ret);
3262 req_set_fail_links(req);
3263 io_put_req_find_next(req, nxt);
3271 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3273 #if defined(CONFIG_NET)
3274 struct io_accept *accept = &req->accept;
3276 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3278 if (sqe->ioprio || sqe->len || sqe->buf_index)
3281 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3282 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3283 accept->flags = READ_ONCE(sqe->accept_flags);
3290 #if defined(CONFIG_NET)
3291 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3292 bool force_nonblock)
3294 struct io_accept *accept = &req->accept;
3295 unsigned file_flags;
3298 file_flags = force_nonblock ? O_NONBLOCK : 0;
3299 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3300 accept->addr_len, accept->flags);
3301 if (ret == -EAGAIN && force_nonblock)
3303 if (ret == -ERESTARTSYS)
3306 req_set_fail_links(req);
3307 io_cqring_add_event(req, ret);
3308 io_put_req_find_next(req, nxt);
3312 static void io_accept_finish(struct io_wq_work **workptr)
3314 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3315 struct io_kiocb *nxt = NULL;
3317 if (io_req_cancelled(req))
3319 __io_accept(req, &nxt, false);
3321 io_wq_assign_next(workptr, nxt);
3325 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3326 bool force_nonblock)
3328 #if defined(CONFIG_NET)
3331 ret = __io_accept(req, nxt, force_nonblock);
3332 if (ret == -EAGAIN && force_nonblock) {
3333 req->work.func = io_accept_finish;
3343 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3345 #if defined(CONFIG_NET)
3346 struct io_connect *conn = &req->connect;
3347 struct io_async_ctx *io = req->io;
3349 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3351 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3354 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3355 conn->addr_len = READ_ONCE(sqe->addr2);
3360 return move_addr_to_kernel(conn->addr, conn->addr_len,
3361 &io->connect.address);
3367 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3368 bool force_nonblock)
3370 #if defined(CONFIG_NET)
3371 struct io_async_ctx __io, *io;
3372 unsigned file_flags;
3378 ret = move_addr_to_kernel(req->connect.addr,
3379 req->connect.addr_len,
3380 &__io.connect.address);
3386 file_flags = force_nonblock ? O_NONBLOCK : 0;
3388 ret = __sys_connect_file(req->file, &io->connect.address,
3389 req->connect.addr_len, file_flags);
3390 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3393 if (io_alloc_async_ctx(req)) {
3397 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3400 if (ret == -ERESTARTSYS)
3404 req_set_fail_links(req);
3405 io_cqring_add_event(req, ret);
3406 io_put_req_find_next(req, nxt);
3413 static void io_poll_remove_one(struct io_kiocb *req)
3415 struct io_poll_iocb *poll = &req->poll;
3417 spin_lock(&poll->head->lock);
3418 WRITE_ONCE(poll->canceled, true);
3419 if (!list_empty(&poll->wait.entry)) {
3420 list_del_init(&poll->wait.entry);
3421 io_queue_async_work(req);
3423 spin_unlock(&poll->head->lock);
3424 hash_del(&req->hash_node);
3427 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3429 struct hlist_node *tmp;
3430 struct io_kiocb *req;
3433 spin_lock_irq(&ctx->completion_lock);
3434 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3435 struct hlist_head *list;
3437 list = &ctx->cancel_hash[i];
3438 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3439 io_poll_remove_one(req);
3441 spin_unlock_irq(&ctx->completion_lock);
3444 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3446 struct hlist_head *list;
3447 struct io_kiocb *req;
3449 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3450 hlist_for_each_entry(req, list, hash_node) {
3451 if (sqe_addr == req->user_data) {
3452 io_poll_remove_one(req);
3460 static int io_poll_remove_prep(struct io_kiocb *req,
3461 const struct io_uring_sqe *sqe)
3463 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3465 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3469 req->poll.addr = READ_ONCE(sqe->addr);
3474 * Find a running poll command that matches one specified in sqe->addr,
3475 * and remove it if found.
3477 static int io_poll_remove(struct io_kiocb *req)
3479 struct io_ring_ctx *ctx = req->ctx;
3483 addr = req->poll.addr;
3484 spin_lock_irq(&ctx->completion_lock);
3485 ret = io_poll_cancel(ctx, addr);
3486 spin_unlock_irq(&ctx->completion_lock);
3488 io_cqring_add_event(req, ret);
3490 req_set_fail_links(req);
3495 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3497 struct io_ring_ctx *ctx = req->ctx;
3499 req->poll.done = true;
3501 io_cqring_fill_event(req, error);
3503 io_cqring_fill_event(req, mangle_poll(mask));
3504 io_commit_cqring(ctx);
3507 static void io_poll_complete_work(struct io_wq_work **workptr)
3509 struct io_wq_work *work = *workptr;
3510 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3511 struct io_poll_iocb *poll = &req->poll;
3512 struct poll_table_struct pt = { ._key = poll->events };
3513 struct io_ring_ctx *ctx = req->ctx;
3514 struct io_kiocb *nxt = NULL;
3518 if (work->flags & IO_WQ_WORK_CANCEL) {
3519 WRITE_ONCE(poll->canceled, true);
3521 } else if (READ_ONCE(poll->canceled)) {
3525 if (ret != -ECANCELED)
3526 mask = vfs_poll(poll->file, &pt) & poll->events;
3529 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3530 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3531 * synchronize with them. In the cancellation case the list_del_init
3532 * itself is not actually needed, but harmless so we keep it in to
3533 * avoid further branches in the fast path.
3535 spin_lock_irq(&ctx->completion_lock);
3536 if (!mask && ret != -ECANCELED) {
3537 add_wait_queue(poll->head, &poll->wait);
3538 spin_unlock_irq(&ctx->completion_lock);
3541 hash_del(&req->hash_node);
3542 io_poll_complete(req, mask, ret);
3543 spin_unlock_irq(&ctx->completion_lock);
3545 io_cqring_ev_posted(ctx);
3548 req_set_fail_links(req);
3549 io_put_req_find_next(req, &nxt);
3551 io_wq_assign_next(workptr, nxt);
3554 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3556 struct io_kiocb *req, *tmp;
3557 struct req_batch rb;
3559 rb.to_free = rb.need_iter = 0;
3560 spin_lock_irq(&ctx->completion_lock);
3561 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3562 hash_del(&req->hash_node);
3563 io_poll_complete(req, req->result, 0);
3565 if (refcount_dec_and_test(&req->refs) &&
3566 !io_req_multi_free(&rb, req)) {
3567 req->flags |= REQ_F_COMP_LOCKED;
3571 spin_unlock_irq(&ctx->completion_lock);
3573 io_cqring_ev_posted(ctx);
3574 io_free_req_many(ctx, &rb);
3577 static void io_poll_flush(struct io_wq_work **workptr)
3579 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3580 struct llist_node *nodes;
3582 nodes = llist_del_all(&req->ctx->poll_llist);
3584 __io_poll_flush(req->ctx, nodes);
3587 static void io_poll_trigger_evfd(struct io_wq_work **workptr)
3589 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3591 eventfd_signal(req->ctx->cq_ev_fd, 1);
3595 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3598 struct io_poll_iocb *poll = wait->private;
3599 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3600 struct io_ring_ctx *ctx = req->ctx;
3601 __poll_t mask = key_to_poll(key);
3603 /* for instances that support it check for an event match first: */
3604 if (mask && !(mask & poll->events))
3607 list_del_init(&poll->wait.entry);
3610 * Run completion inline if we can. We're using trylock here because
3611 * we are violating the completion_lock -> poll wq lock ordering.
3612 * If we have a link timeout we're going to need the completion_lock
3613 * for finalizing the request, mark us as having grabbed that already.
3616 unsigned long flags;
3618 if (llist_empty(&ctx->poll_llist) &&
3619 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3622 hash_del(&req->hash_node);
3623 io_poll_complete(req, mask, 0);
3625 trigger_ev = io_should_trigger_evfd(ctx);
3626 if (trigger_ev && eventfd_signal_count()) {
3628 req->work.func = io_poll_trigger_evfd;
3630 req->flags |= REQ_F_COMP_LOCKED;
3634 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3635 __io_cqring_ev_posted(ctx, trigger_ev);
3638 req->llist_node.next = NULL;
3639 /* if the list wasn't empty, we're done */
3640 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3643 req->work.func = io_poll_flush;
3647 io_queue_async_work(req);
3652 struct io_poll_table {
3653 struct poll_table_struct pt;
3654 struct io_kiocb *req;
3658 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3659 struct poll_table_struct *p)
3661 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3663 if (unlikely(pt->req->poll.head)) {
3664 pt->error = -EINVAL;
3669 pt->req->poll.head = head;
3670 add_wait_queue(head, &pt->req->poll.wait);
3673 static void io_poll_req_insert(struct io_kiocb *req)
3675 struct io_ring_ctx *ctx = req->ctx;
3676 struct hlist_head *list;
3678 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3679 hlist_add_head(&req->hash_node, list);
3682 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3684 struct io_poll_iocb *poll = &req->poll;
3687 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3689 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3694 events = READ_ONCE(sqe->poll_events);
3695 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3699 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3701 struct io_poll_iocb *poll = &req->poll;
3702 struct io_ring_ctx *ctx = req->ctx;
3703 struct io_poll_table ipt;
3704 bool cancel = false;
3707 INIT_IO_WORK(&req->work, io_poll_complete_work);
3708 INIT_HLIST_NODE(&req->hash_node);
3712 poll->canceled = false;
3714 ipt.pt._qproc = io_poll_queue_proc;
3715 ipt.pt._key = poll->events;
3717 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3719 /* initialized the list so that we can do list_empty checks */
3720 INIT_LIST_HEAD(&poll->wait.entry);
3721 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3722 poll->wait.private = poll;
3724 INIT_LIST_HEAD(&req->list);
3726 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3728 spin_lock_irq(&ctx->completion_lock);
3729 if (likely(poll->head)) {
3730 spin_lock(&poll->head->lock);
3731 if (unlikely(list_empty(&poll->wait.entry))) {
3737 if (mask || ipt.error)
3738 list_del_init(&poll->wait.entry);
3740 WRITE_ONCE(poll->canceled, true);
3741 else if (!poll->done) /* actually waiting for an event */
3742 io_poll_req_insert(req);
3743 spin_unlock(&poll->head->lock);
3745 if (mask) { /* no async, we'd stolen it */
3747 io_poll_complete(req, mask, 0);
3749 spin_unlock_irq(&ctx->completion_lock);
3752 io_cqring_ev_posted(ctx);
3753 io_put_req_find_next(req, nxt);
3758 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3760 struct io_timeout_data *data = container_of(timer,
3761 struct io_timeout_data, timer);
3762 struct io_kiocb *req = data->req;
3763 struct io_ring_ctx *ctx = req->ctx;
3764 unsigned long flags;
3766 atomic_inc(&ctx->cq_timeouts);
3768 spin_lock_irqsave(&ctx->completion_lock, flags);
3770 * We could be racing with timeout deletion. If the list is empty,
3771 * then timeout lookup already found it and will be handling it.
3773 if (!list_empty(&req->list)) {
3774 struct io_kiocb *prev;
3777 * Adjust the reqs sequence before the current one because it
3778 * will consume a slot in the cq_ring and the cq_tail
3779 * pointer will be increased, otherwise other timeout reqs may
3780 * return in advance without waiting for enough wait_nr.
3783 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3785 list_del_init(&req->list);
3788 io_cqring_fill_event(req, -ETIME);
3789 io_commit_cqring(ctx);
3790 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3792 io_cqring_ev_posted(ctx);
3793 req_set_fail_links(req);
3795 return HRTIMER_NORESTART;
3798 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3800 struct io_kiocb *req;
3803 list_for_each_entry(req, &ctx->timeout_list, list) {
3804 if (user_data == req->user_data) {
3805 list_del_init(&req->list);
3814 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3818 req_set_fail_links(req);
3819 io_cqring_fill_event(req, -ECANCELED);
3824 static int io_timeout_remove_prep(struct io_kiocb *req,
3825 const struct io_uring_sqe *sqe)
3827 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3829 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3832 req->timeout.addr = READ_ONCE(sqe->addr);
3833 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3834 if (req->timeout.flags)
3841 * Remove or update an existing timeout command
3843 static int io_timeout_remove(struct io_kiocb *req)
3845 struct io_ring_ctx *ctx = req->ctx;
3848 spin_lock_irq(&ctx->completion_lock);
3849 ret = io_timeout_cancel(ctx, req->timeout.addr);
3851 io_cqring_fill_event(req, ret);
3852 io_commit_cqring(ctx);
3853 spin_unlock_irq(&ctx->completion_lock);
3854 io_cqring_ev_posted(ctx);
3856 req_set_fail_links(req);
3861 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3862 bool is_timeout_link)
3864 struct io_timeout_data *data;
3867 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3869 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3871 if (sqe->off && is_timeout_link)
3873 flags = READ_ONCE(sqe->timeout_flags);
3874 if (flags & ~IORING_TIMEOUT_ABS)
3877 req->timeout.count = READ_ONCE(sqe->off);
3879 if (!req->io && io_alloc_async_ctx(req))
3882 data = &req->io->timeout;
3884 req->flags |= REQ_F_TIMEOUT;
3886 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3889 if (flags & IORING_TIMEOUT_ABS)
3890 data->mode = HRTIMER_MODE_ABS;
3892 data->mode = HRTIMER_MODE_REL;
3894 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3898 static int io_timeout(struct io_kiocb *req)
3901 struct io_ring_ctx *ctx = req->ctx;
3902 struct io_timeout_data *data;
3903 struct list_head *entry;
3906 data = &req->io->timeout;
3909 * sqe->off holds how many events that need to occur for this
3910 * timeout event to be satisfied. If it isn't set, then this is
3911 * a pure timeout request, sequence isn't used.
3913 count = req->timeout.count;
3915 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3916 spin_lock_irq(&ctx->completion_lock);
3917 entry = ctx->timeout_list.prev;
3921 req->sequence = ctx->cached_sq_head + count - 1;
3922 data->seq_offset = count;
3925 * Insertion sort, ensuring the first entry in the list is always
3926 * the one we need first.
3928 spin_lock_irq(&ctx->completion_lock);
3929 list_for_each_prev(entry, &ctx->timeout_list) {
3930 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3931 unsigned nxt_sq_head;
3932 long long tmp, tmp_nxt;
3933 u32 nxt_offset = nxt->io->timeout.seq_offset;
3935 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3939 * Since cached_sq_head + count - 1 can overflow, use type long
3942 tmp = (long long)ctx->cached_sq_head + count - 1;
3943 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3944 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3947 * cached_sq_head may overflow, and it will never overflow twice
3948 * once there is some timeout req still be valid.
3950 if (ctx->cached_sq_head < nxt_sq_head)
3957 * Sequence of reqs after the insert one and itself should
3958 * be adjusted because each timeout req consumes a slot.
3963 req->sequence -= span;
3965 list_add(&req->list, entry);
3966 data->timer.function = io_timeout_fn;
3967 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3968 spin_unlock_irq(&ctx->completion_lock);
3972 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3974 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3976 return req->user_data == (unsigned long) data;
3979 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3981 enum io_wq_cancel cancel_ret;
3984 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3985 switch (cancel_ret) {
3986 case IO_WQ_CANCEL_OK:
3989 case IO_WQ_CANCEL_RUNNING:
3992 case IO_WQ_CANCEL_NOTFOUND:
4000 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4001 struct io_kiocb *req, __u64 sqe_addr,
4002 struct io_kiocb **nxt, int success_ret)
4004 unsigned long flags;
4007 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4008 if (ret != -ENOENT) {
4009 spin_lock_irqsave(&ctx->completion_lock, flags);
4013 spin_lock_irqsave(&ctx->completion_lock, flags);
4014 ret = io_timeout_cancel(ctx, sqe_addr);
4017 ret = io_poll_cancel(ctx, sqe_addr);
4021 io_cqring_fill_event(req, ret);
4022 io_commit_cqring(ctx);
4023 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4024 io_cqring_ev_posted(ctx);
4027 req_set_fail_links(req);
4028 io_put_req_find_next(req, nxt);
4031 static int io_async_cancel_prep(struct io_kiocb *req,
4032 const struct io_uring_sqe *sqe)
4034 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4036 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4040 req->cancel.addr = READ_ONCE(sqe->addr);
4044 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
4046 struct io_ring_ctx *ctx = req->ctx;
4048 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
4052 static int io_files_update_prep(struct io_kiocb *req,
4053 const struct io_uring_sqe *sqe)
4055 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4058 req->files_update.offset = READ_ONCE(sqe->off);
4059 req->files_update.nr_args = READ_ONCE(sqe->len);
4060 if (!req->files_update.nr_args)
4062 req->files_update.arg = READ_ONCE(sqe->addr);
4066 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
4068 struct io_ring_ctx *ctx = req->ctx;
4069 struct io_uring_files_update up;
4075 up.offset = req->files_update.offset;
4076 up.fds = req->files_update.arg;
4078 mutex_lock(&ctx->uring_lock);
4079 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4080 mutex_unlock(&ctx->uring_lock);
4083 req_set_fail_links(req);
4084 io_cqring_add_event(req, ret);
4089 static int io_req_defer_prep(struct io_kiocb *req,
4090 const struct io_uring_sqe *sqe)
4094 if (io_op_defs[req->opcode].file_table) {
4095 ret = io_grab_files(req);
4100 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4102 switch (req->opcode) {
4105 case IORING_OP_READV:
4106 case IORING_OP_READ_FIXED:
4107 case IORING_OP_READ:
4108 ret = io_read_prep(req, sqe, true);
4110 case IORING_OP_WRITEV:
4111 case IORING_OP_WRITE_FIXED:
4112 case IORING_OP_WRITE:
4113 ret = io_write_prep(req, sqe, true);
4115 case IORING_OP_POLL_ADD:
4116 ret = io_poll_add_prep(req, sqe);
4118 case IORING_OP_POLL_REMOVE:
4119 ret = io_poll_remove_prep(req, sqe);
4121 case IORING_OP_FSYNC:
4122 ret = io_prep_fsync(req, sqe);
4124 case IORING_OP_SYNC_FILE_RANGE:
4125 ret = io_prep_sfr(req, sqe);
4127 case IORING_OP_SENDMSG:
4128 case IORING_OP_SEND:
4129 ret = io_sendmsg_prep(req, sqe);
4131 case IORING_OP_RECVMSG:
4132 case IORING_OP_RECV:
4133 ret = io_recvmsg_prep(req, sqe);
4135 case IORING_OP_CONNECT:
4136 ret = io_connect_prep(req, sqe);
4138 case IORING_OP_TIMEOUT:
4139 ret = io_timeout_prep(req, sqe, false);
4141 case IORING_OP_TIMEOUT_REMOVE:
4142 ret = io_timeout_remove_prep(req, sqe);
4144 case IORING_OP_ASYNC_CANCEL:
4145 ret = io_async_cancel_prep(req, sqe);
4147 case IORING_OP_LINK_TIMEOUT:
4148 ret = io_timeout_prep(req, sqe, true);
4150 case IORING_OP_ACCEPT:
4151 ret = io_accept_prep(req, sqe);
4153 case IORING_OP_FALLOCATE:
4154 ret = io_fallocate_prep(req, sqe);
4156 case IORING_OP_OPENAT:
4157 ret = io_openat_prep(req, sqe);
4159 case IORING_OP_CLOSE:
4160 ret = io_close_prep(req, sqe);
4162 case IORING_OP_FILES_UPDATE:
4163 ret = io_files_update_prep(req, sqe);
4165 case IORING_OP_STATX:
4166 ret = io_statx_prep(req, sqe);
4168 case IORING_OP_FADVISE:
4169 ret = io_fadvise_prep(req, sqe);
4171 case IORING_OP_MADVISE:
4172 ret = io_madvise_prep(req, sqe);
4174 case IORING_OP_OPENAT2:
4175 ret = io_openat2_prep(req, sqe);
4177 case IORING_OP_EPOLL_CTL:
4178 ret = io_epoll_ctl_prep(req, sqe);
4181 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4190 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4192 struct io_ring_ctx *ctx = req->ctx;
4195 /* Still need defer if there is pending req in defer list. */
4196 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4199 if (!req->io && io_alloc_async_ctx(req))
4202 ret = io_req_defer_prep(req, sqe);
4206 spin_lock_irq(&ctx->completion_lock);
4207 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4208 spin_unlock_irq(&ctx->completion_lock);
4212 trace_io_uring_defer(ctx, req, req->user_data);
4213 list_add_tail(&req->list, &ctx->defer_list);
4214 spin_unlock_irq(&ctx->completion_lock);
4215 return -EIOCBQUEUED;
4218 static void io_cleanup_req(struct io_kiocb *req)
4220 struct io_async_ctx *io = req->io;
4222 switch (req->opcode) {
4223 case IORING_OP_READV:
4224 case IORING_OP_READ_FIXED:
4225 case IORING_OP_READ:
4226 case IORING_OP_WRITEV:
4227 case IORING_OP_WRITE_FIXED:
4228 case IORING_OP_WRITE:
4229 if (io->rw.iov != io->rw.fast_iov)
4232 case IORING_OP_SENDMSG:
4233 case IORING_OP_RECVMSG:
4234 if (io->msg.iov != io->msg.fast_iov)
4237 case IORING_OP_OPENAT:
4238 case IORING_OP_OPENAT2:
4239 case IORING_OP_STATX:
4240 putname(req->open.filename);
4244 req->flags &= ~REQ_F_NEED_CLEANUP;
4247 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4248 struct io_kiocb **nxt, bool force_nonblock)
4250 struct io_ring_ctx *ctx = req->ctx;
4253 switch (req->opcode) {
4257 case IORING_OP_READV:
4258 case IORING_OP_READ_FIXED:
4259 case IORING_OP_READ:
4261 ret = io_read_prep(req, sqe, force_nonblock);
4265 ret = io_read(req, nxt, force_nonblock);
4267 case IORING_OP_WRITEV:
4268 case IORING_OP_WRITE_FIXED:
4269 case IORING_OP_WRITE:
4271 ret = io_write_prep(req, sqe, force_nonblock);
4275 ret = io_write(req, nxt, force_nonblock);
4277 case IORING_OP_FSYNC:
4279 ret = io_prep_fsync(req, sqe);
4283 ret = io_fsync(req, nxt, force_nonblock);
4285 case IORING_OP_POLL_ADD:
4287 ret = io_poll_add_prep(req, sqe);
4291 ret = io_poll_add(req, nxt);
4293 case IORING_OP_POLL_REMOVE:
4295 ret = io_poll_remove_prep(req, sqe);
4299 ret = io_poll_remove(req);
4301 case IORING_OP_SYNC_FILE_RANGE:
4303 ret = io_prep_sfr(req, sqe);
4307 ret = io_sync_file_range(req, nxt, force_nonblock);
4309 case IORING_OP_SENDMSG:
4310 case IORING_OP_SEND:
4312 ret = io_sendmsg_prep(req, sqe);
4316 if (req->opcode == IORING_OP_SENDMSG)
4317 ret = io_sendmsg(req, nxt, force_nonblock);
4319 ret = io_send(req, nxt, force_nonblock);
4321 case IORING_OP_RECVMSG:
4322 case IORING_OP_RECV:
4324 ret = io_recvmsg_prep(req, sqe);
4328 if (req->opcode == IORING_OP_RECVMSG)
4329 ret = io_recvmsg(req, nxt, force_nonblock);
4331 ret = io_recv(req, nxt, force_nonblock);
4333 case IORING_OP_TIMEOUT:
4335 ret = io_timeout_prep(req, sqe, false);
4339 ret = io_timeout(req);
4341 case IORING_OP_TIMEOUT_REMOVE:
4343 ret = io_timeout_remove_prep(req, sqe);
4347 ret = io_timeout_remove(req);
4349 case IORING_OP_ACCEPT:
4351 ret = io_accept_prep(req, sqe);
4355 ret = io_accept(req, nxt, force_nonblock);
4357 case IORING_OP_CONNECT:
4359 ret = io_connect_prep(req, sqe);
4363 ret = io_connect(req, nxt, force_nonblock);
4365 case IORING_OP_ASYNC_CANCEL:
4367 ret = io_async_cancel_prep(req, sqe);
4371 ret = io_async_cancel(req, nxt);
4373 case IORING_OP_FALLOCATE:
4375 ret = io_fallocate_prep(req, sqe);
4379 ret = io_fallocate(req, nxt, force_nonblock);
4381 case IORING_OP_OPENAT:
4383 ret = io_openat_prep(req, sqe);
4387 ret = io_openat(req, nxt, force_nonblock);
4389 case IORING_OP_CLOSE:
4391 ret = io_close_prep(req, sqe);
4395 ret = io_close(req, nxt, force_nonblock);
4397 case IORING_OP_FILES_UPDATE:
4399 ret = io_files_update_prep(req, sqe);
4403 ret = io_files_update(req, force_nonblock);
4405 case IORING_OP_STATX:
4407 ret = io_statx_prep(req, sqe);
4411 ret = io_statx(req, nxt, force_nonblock);
4413 case IORING_OP_FADVISE:
4415 ret = io_fadvise_prep(req, sqe);
4419 ret = io_fadvise(req, nxt, force_nonblock);
4421 case IORING_OP_MADVISE:
4423 ret = io_madvise_prep(req, sqe);
4427 ret = io_madvise(req, nxt, force_nonblock);
4429 case IORING_OP_OPENAT2:
4431 ret = io_openat2_prep(req, sqe);
4435 ret = io_openat2(req, nxt, force_nonblock);
4437 case IORING_OP_EPOLL_CTL:
4439 ret = io_epoll_ctl_prep(req, sqe);
4443 ret = io_epoll_ctl(req, nxt, force_nonblock);
4453 if (ctx->flags & IORING_SETUP_IOPOLL) {
4454 const bool in_async = io_wq_current_is_worker();
4456 if (req->result == -EAGAIN)
4459 /* workqueue context doesn't hold uring_lock, grab it now */
4461 mutex_lock(&ctx->uring_lock);
4463 io_iopoll_req_issued(req);
4466 mutex_unlock(&ctx->uring_lock);
4472 static void io_wq_submit_work(struct io_wq_work **workptr)
4474 struct io_wq_work *work = *workptr;
4475 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4476 struct io_kiocb *nxt = NULL;
4479 /* if NO_CANCEL is set, we must still run the work */
4480 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4481 IO_WQ_WORK_CANCEL) {
4486 req->in_async = true;
4488 ret = io_issue_sqe(req, NULL, &nxt, false);
4490 * We can get EAGAIN for polled IO even though we're
4491 * forcing a sync submission from here, since we can't
4492 * wait for request slots on the block side.
4500 /* drop submission reference */
4504 req_set_fail_links(req);
4505 io_cqring_add_event(req, ret);
4509 /* if a dependent link is ready, pass it back */
4511 io_wq_assign_next(workptr, nxt);
4514 static int io_req_needs_file(struct io_kiocb *req, int fd)
4516 if (!io_op_defs[req->opcode].needs_file)
4518 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4523 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4526 struct fixed_file_table *table;
4528 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4529 return table->files[index & IORING_FILE_TABLE_MASK];;
4532 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4533 const struct io_uring_sqe *sqe)
4535 struct io_ring_ctx *ctx = req->ctx;
4539 flags = READ_ONCE(sqe->flags);
4540 fd = READ_ONCE(sqe->fd);
4542 if (!io_req_needs_file(req, fd))
4545 if (flags & IOSQE_FIXED_FILE) {
4546 if (unlikely(!ctx->file_data ||
4547 (unsigned) fd >= ctx->nr_user_files))
4549 fd = array_index_nospec(fd, ctx->nr_user_files);
4550 req->file = io_file_from_index(ctx, fd);
4553 req->flags |= REQ_F_FIXED_FILE;
4554 percpu_ref_get(&ctx->file_data->refs);
4556 if (req->needs_fixed_file)
4558 trace_io_uring_file_get(ctx, fd);
4559 req->file = io_file_get(state, fd);
4560 if (unlikely(!req->file))
4567 static int io_grab_files(struct io_kiocb *req)
4570 struct io_ring_ctx *ctx = req->ctx;
4572 if (req->work.files)
4574 if (!ctx->ring_file)
4578 spin_lock_irq(&ctx->inflight_lock);
4580 * We use the f_ops->flush() handler to ensure that we can flush
4581 * out work accessing these files if the fd is closed. Check if
4582 * the fd has changed since we started down this path, and disallow
4583 * this operation if it has.
4585 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4586 list_add(&req->inflight_entry, &ctx->inflight_list);
4587 req->flags |= REQ_F_INFLIGHT;
4588 req->work.files = current->files;
4591 spin_unlock_irq(&ctx->inflight_lock);
4597 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4599 struct io_timeout_data *data = container_of(timer,
4600 struct io_timeout_data, timer);
4601 struct io_kiocb *req = data->req;
4602 struct io_ring_ctx *ctx = req->ctx;
4603 struct io_kiocb *prev = NULL;
4604 unsigned long flags;
4606 spin_lock_irqsave(&ctx->completion_lock, flags);
4609 * We don't expect the list to be empty, that will only happen if we
4610 * race with the completion of the linked work.
4612 if (!list_empty(&req->link_list)) {
4613 prev = list_entry(req->link_list.prev, struct io_kiocb,
4615 if (refcount_inc_not_zero(&prev->refs)) {
4616 list_del_init(&req->link_list);
4617 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4622 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4625 req_set_fail_links(prev);
4626 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4630 io_cqring_add_event(req, -ETIME);
4633 return HRTIMER_NORESTART;
4636 static void io_queue_linked_timeout(struct io_kiocb *req)
4638 struct io_ring_ctx *ctx = req->ctx;
4641 * If the list is now empty, then our linked request finished before
4642 * we got a chance to setup the timer
4644 spin_lock_irq(&ctx->completion_lock);
4645 if (!list_empty(&req->link_list)) {
4646 struct io_timeout_data *data = &req->io->timeout;
4648 data->timer.function = io_link_timeout_fn;
4649 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4652 spin_unlock_irq(&ctx->completion_lock);
4654 /* drop submission reference */
4658 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4660 struct io_kiocb *nxt;
4662 if (!(req->flags & REQ_F_LINK))
4665 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4667 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4670 req->flags |= REQ_F_LINK_TIMEOUT;
4674 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4676 struct io_kiocb *linked_timeout;
4677 struct io_kiocb *nxt = NULL;
4681 linked_timeout = io_prep_linked_timeout(req);
4683 ret = io_issue_sqe(req, sqe, &nxt, true);
4686 * We async punt it if the file wasn't marked NOWAIT, or if the file
4687 * doesn't support non-blocking read/write attempts
4689 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4690 (req->flags & REQ_F_MUST_PUNT))) {
4692 if (io_op_defs[req->opcode].file_table) {
4693 ret = io_grab_files(req);
4699 * Queued up for async execution, worker will release
4700 * submit reference when the iocb is actually submitted.
4702 io_queue_async_work(req);
4707 /* drop submission reference */
4710 if (linked_timeout) {
4712 io_queue_linked_timeout(linked_timeout);
4714 io_put_req(linked_timeout);
4717 /* and drop final reference, if we failed */
4719 io_cqring_add_event(req, ret);
4720 req_set_fail_links(req);
4728 if (req->flags & REQ_F_FORCE_ASYNC)
4734 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4738 ret = io_req_defer(req, sqe);
4740 if (ret != -EIOCBQUEUED) {
4742 io_cqring_add_event(req, ret);
4743 req_set_fail_links(req);
4744 io_double_put_req(req);
4746 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4747 ret = io_req_defer_prep(req, sqe);
4748 if (unlikely(ret < 0))
4751 * Never try inline submit of IOSQE_ASYNC is set, go straight
4752 * to async execution.
4754 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4755 io_queue_async_work(req);
4757 __io_queue_sqe(req, sqe);
4761 static inline void io_queue_link_head(struct io_kiocb *req)
4763 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4764 io_cqring_add_event(req, -ECANCELED);
4765 io_double_put_req(req);
4767 io_queue_sqe(req, NULL);
4770 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4771 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4773 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4774 struct io_submit_state *state, struct io_kiocb **link)
4776 const struct cred *old_creds = NULL;
4777 struct io_ring_ctx *ctx = req->ctx;
4778 unsigned int sqe_flags;
4781 sqe_flags = READ_ONCE(sqe->flags);
4783 /* enforce forwards compatibility on users */
4784 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4789 id = READ_ONCE(sqe->personality);
4791 const struct cred *personality_creds;
4793 personality_creds = idr_find(&ctx->personality_idr, id);
4794 if (unlikely(!personality_creds)) {
4798 old_creds = override_creds(personality_creds);
4801 /* same numerical values with corresponding REQ_F_*, safe to copy */
4802 req->flags |= sqe_flags & (IOSQE_IO_DRAIN|IOSQE_IO_HARDLINK|
4805 ret = io_req_set_file(state, req, sqe);
4806 if (unlikely(ret)) {
4808 io_cqring_add_event(req, ret);
4809 io_double_put_req(req);
4811 revert_creds(old_creds);
4816 * If we already have a head request, queue this one for async
4817 * submittal once the head completes. If we don't have a head but
4818 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4819 * submitted sync once the chain is complete. If none of those
4820 * conditions are true (normal request), then just queue it.
4823 struct io_kiocb *head = *link;
4826 * Taking sequential execution of a link, draining both sides
4827 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
4828 * requests in the link. So, it drains the head and the
4829 * next after the link request. The last one is done via
4830 * drain_next flag to persist the effect across calls.
4832 if (sqe_flags & IOSQE_IO_DRAIN) {
4833 head->flags |= REQ_F_IO_DRAIN;
4834 ctx->drain_next = 1;
4836 if (io_alloc_async_ctx(req)) {
4841 ret = io_req_defer_prep(req, sqe);
4843 /* fail even hard links since we don't submit */
4844 head->flags |= REQ_F_FAIL_LINK;
4847 trace_io_uring_link(ctx, req, head);
4848 list_add_tail(&req->link_list, &head->link_list);
4850 /* last request of a link, enqueue the link */
4851 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4852 io_queue_link_head(head);
4856 if (unlikely(ctx->drain_next)) {
4857 req->flags |= REQ_F_IO_DRAIN;
4858 req->ctx->drain_next = 0;
4860 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4861 req->flags |= REQ_F_LINK;
4862 INIT_LIST_HEAD(&req->link_list);
4863 ret = io_req_defer_prep(req, sqe);
4865 req->flags |= REQ_F_FAIL_LINK;
4868 io_queue_sqe(req, sqe);
4873 revert_creds(old_creds);
4878 * Batched submission is done, ensure local IO is flushed out.
4880 static void io_submit_state_end(struct io_submit_state *state)
4882 blk_finish_plug(&state->plug);
4884 if (state->free_reqs)
4885 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
4889 * Start submission side cache.
4891 static void io_submit_state_start(struct io_submit_state *state,
4892 unsigned int max_ios)
4894 blk_start_plug(&state->plug);
4895 state->free_reqs = 0;
4897 state->ios_left = max_ios;
4900 static void io_commit_sqring(struct io_ring_ctx *ctx)
4902 struct io_rings *rings = ctx->rings;
4905 * Ensure any loads from the SQEs are done at this point,
4906 * since once we write the new head, the application could
4907 * write new data to them.
4909 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4913 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4914 * that is mapped by userspace. This means that care needs to be taken to
4915 * ensure that reads are stable, as we cannot rely on userspace always
4916 * being a good citizen. If members of the sqe are validated and then later
4917 * used, it's important that those reads are done through READ_ONCE() to
4918 * prevent a re-load down the line.
4920 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4921 const struct io_uring_sqe **sqe_ptr)
4923 u32 *sq_array = ctx->sq_array;
4927 * The cached sq head (or cq tail) serves two purposes:
4929 * 1) allows us to batch the cost of updating the user visible
4931 * 2) allows the kernel side to track the head on its own, even
4932 * though the application is the one updating it.
4934 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4935 if (likely(head < ctx->sq_entries)) {
4937 * All io need record the previous position, if LINK vs DARIN,
4938 * it can be used to mark the position of the first IO in the
4941 req->sequence = ctx->cached_sq_head;
4942 *sqe_ptr = &ctx->sq_sqes[head];
4943 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4944 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4945 ctx->cached_sq_head++;
4949 /* drop invalid entries */
4950 ctx->cached_sq_head++;
4951 ctx->cached_sq_dropped++;
4952 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4956 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4957 struct file *ring_file, int ring_fd,
4958 struct mm_struct **mm, bool async)
4960 struct io_submit_state state, *statep = NULL;
4961 struct io_kiocb *link = NULL;
4962 int i, submitted = 0;
4963 bool mm_fault = false;
4965 /* if we have a backlog and couldn't flush it all, return BUSY */
4966 if (test_bit(0, &ctx->sq_check_overflow)) {
4967 if (!list_empty(&ctx->cq_overflow_list) &&
4968 !io_cqring_overflow_flush(ctx, false))
4972 /* make sure SQ entry isn't read before tail */
4973 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
4975 if (!percpu_ref_tryget_many(&ctx->refs, nr))
4978 if (nr > IO_PLUG_THRESHOLD) {
4979 io_submit_state_start(&state, nr);
4983 ctx->ring_fd = ring_fd;
4984 ctx->ring_file = ring_file;
4986 for (i = 0; i < nr; i++) {
4987 const struct io_uring_sqe *sqe;
4988 struct io_kiocb *req;
4991 req = io_get_req(ctx, statep);
4992 if (unlikely(!req)) {
4994 submitted = -EAGAIN;
4997 if (!io_get_sqring(ctx, req, &sqe)) {
4998 __io_req_do_free(req);
5002 /* will complete beyond this point, count as submitted */
5005 if (unlikely(req->opcode >= IORING_OP_LAST)) {
5008 io_cqring_add_event(req, err);
5009 io_double_put_req(req);
5013 if (io_op_defs[req->opcode].needs_mm && !*mm) {
5014 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
5015 if (unlikely(mm_fault)) {
5019 use_mm(ctx->sqo_mm);
5023 req->in_async = async;
5024 req->needs_fixed_file = async;
5025 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
5027 if (!io_submit_sqe(req, sqe, statep, &link))
5031 if (unlikely(submitted != nr)) {
5032 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
5034 percpu_ref_put_many(&ctx->refs, nr - ref_used);
5037 io_queue_link_head(link);
5039 io_submit_state_end(&state);
5041 /* Commit SQ ring head once we've consumed and submitted all SQEs */
5042 io_commit_sqring(ctx);
5047 static int io_sq_thread(void *data)
5049 struct io_ring_ctx *ctx = data;
5050 struct mm_struct *cur_mm = NULL;
5051 const struct cred *old_cred;
5052 mm_segment_t old_fs;
5055 unsigned long timeout;
5058 complete(&ctx->completions[1]);
5062 old_cred = override_creds(ctx->creds);
5064 ret = timeout = inflight = 0;
5065 while (!kthread_should_park()) {
5066 unsigned int to_submit;
5069 unsigned nr_events = 0;
5071 if (ctx->flags & IORING_SETUP_IOPOLL) {
5073 * inflight is the count of the maximum possible
5074 * entries we submitted, but it can be smaller
5075 * if we dropped some of them. If we don't have
5076 * poll entries available, then we know that we
5077 * have nothing left to poll for. Reset the
5078 * inflight count to zero in that case.
5080 mutex_lock(&ctx->uring_lock);
5081 if (!list_empty(&ctx->poll_list))
5082 __io_iopoll_check(ctx, &nr_events, 0);
5085 mutex_unlock(&ctx->uring_lock);
5088 * Normal IO, just pretend everything completed.
5089 * We don't have to poll completions for that.
5091 nr_events = inflight;
5094 inflight -= nr_events;
5096 timeout = jiffies + ctx->sq_thread_idle;
5099 to_submit = io_sqring_entries(ctx);
5102 * If submit got -EBUSY, flag us as needing the application
5103 * to enter the kernel to reap and flush events.
5105 if (!to_submit || ret == -EBUSY) {
5107 * We're polling. If we're within the defined idle
5108 * period, then let us spin without work before going
5109 * to sleep. The exception is if we got EBUSY doing
5110 * more IO, we should wait for the application to
5111 * reap events and wake us up.
5114 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5115 !percpu_ref_is_dying(&ctx->refs))) {
5121 * Drop cur_mm before scheduling, we can't hold it for
5122 * long periods (or over schedule()). Do this before
5123 * adding ourselves to the waitqueue, as the unuse/drop
5132 prepare_to_wait(&ctx->sqo_wait, &wait,
5133 TASK_INTERRUPTIBLE);
5135 /* Tell userspace we may need a wakeup call */
5136 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
5137 /* make sure to read SQ tail after writing flags */
5140 to_submit = io_sqring_entries(ctx);
5141 if (!to_submit || ret == -EBUSY) {
5142 if (kthread_should_park()) {
5143 finish_wait(&ctx->sqo_wait, &wait);
5146 if (signal_pending(current))
5147 flush_signals(current);
5149 finish_wait(&ctx->sqo_wait, &wait);
5151 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5154 finish_wait(&ctx->sqo_wait, &wait);
5156 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5159 mutex_lock(&ctx->uring_lock);
5160 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
5161 mutex_unlock(&ctx->uring_lock);
5171 revert_creds(old_cred);
5178 struct io_wait_queue {
5179 struct wait_queue_entry wq;
5180 struct io_ring_ctx *ctx;
5182 unsigned nr_timeouts;
5185 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
5187 struct io_ring_ctx *ctx = iowq->ctx;
5190 * Wake up if we have enough events, or if a timeout occurred since we
5191 * started waiting. For timeouts, we always want to return to userspace,
5192 * regardless of event count.
5194 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
5195 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5198 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5199 int wake_flags, void *key)
5201 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5204 /* use noflush == true, as we can't safely rely on locking context */
5205 if (!io_should_wake(iowq, true))
5208 return autoremove_wake_function(curr, mode, wake_flags, key);
5212 * Wait until events become available, if we don't already have some. The
5213 * application must reap them itself, as they reside on the shared cq ring.
5215 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5216 const sigset_t __user *sig, size_t sigsz)
5218 struct io_wait_queue iowq = {
5221 .func = io_wake_function,
5222 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5225 .to_wait = min_events,
5227 struct io_rings *rings = ctx->rings;
5230 if (io_cqring_events(ctx, false) >= min_events)
5234 #ifdef CONFIG_COMPAT
5235 if (in_compat_syscall())
5236 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5240 ret = set_user_sigmask(sig, sigsz);
5246 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5247 trace_io_uring_cqring_wait(ctx, min_events);
5249 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5250 TASK_INTERRUPTIBLE);
5251 if (io_should_wake(&iowq, false))
5254 if (signal_pending(current)) {
5259 finish_wait(&ctx->wait, &iowq.wq);
5261 restore_saved_sigmask_unless(ret == -EINTR);
5263 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5266 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5268 #if defined(CONFIG_UNIX)
5269 if (ctx->ring_sock) {
5270 struct sock *sock = ctx->ring_sock->sk;
5271 struct sk_buff *skb;
5273 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5279 for (i = 0; i < ctx->nr_user_files; i++) {
5282 file = io_file_from_index(ctx, i);
5289 static void io_file_ref_kill(struct percpu_ref *ref)
5291 struct fixed_file_data *data;
5293 data = container_of(ref, struct fixed_file_data, refs);
5294 complete(&data->done);
5297 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5299 struct fixed_file_data *data = ctx->file_data;
5300 unsigned nr_tables, i;
5305 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5306 flush_work(&data->ref_work);
5307 wait_for_completion(&data->done);
5308 io_ring_file_ref_flush(data);
5309 percpu_ref_exit(&data->refs);
5311 __io_sqe_files_unregister(ctx);
5312 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5313 for (i = 0; i < nr_tables; i++)
5314 kfree(data->table[i].files);
5317 ctx->file_data = NULL;
5318 ctx->nr_user_files = 0;
5322 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5324 if (ctx->sqo_thread) {
5325 wait_for_completion(&ctx->completions[1]);
5327 * The park is a bit of a work-around, without it we get
5328 * warning spews on shutdown with SQPOLL set and affinity
5329 * set to a single CPU.
5331 kthread_park(ctx->sqo_thread);
5332 kthread_stop(ctx->sqo_thread);
5333 ctx->sqo_thread = NULL;
5337 static void io_finish_async(struct io_ring_ctx *ctx)
5339 io_sq_thread_stop(ctx);
5342 io_wq_destroy(ctx->io_wq);
5347 #if defined(CONFIG_UNIX)
5349 * Ensure the UNIX gc is aware of our file set, so we are certain that
5350 * the io_uring can be safely unregistered on process exit, even if we have
5351 * loops in the file referencing.
5353 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5355 struct sock *sk = ctx->ring_sock->sk;
5356 struct scm_fp_list *fpl;
5357 struct sk_buff *skb;
5360 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5361 unsigned long inflight = ctx->user->unix_inflight + nr;
5363 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5367 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5371 skb = alloc_skb(0, GFP_KERNEL);
5380 fpl->user = get_uid(ctx->user);
5381 for (i = 0; i < nr; i++) {
5382 struct file *file = io_file_from_index(ctx, i + offset);
5386 fpl->fp[nr_files] = get_file(file);
5387 unix_inflight(fpl->user, fpl->fp[nr_files]);
5392 fpl->max = SCM_MAX_FD;
5393 fpl->count = nr_files;
5394 UNIXCB(skb).fp = fpl;
5395 skb->destructor = unix_destruct_scm;
5396 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5397 skb_queue_head(&sk->sk_receive_queue, skb);
5399 for (i = 0; i < nr_files; i++)
5410 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5411 * causes regular reference counting to break down. We rely on the UNIX
5412 * garbage collection to take care of this problem for us.
5414 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5416 unsigned left, total;
5420 left = ctx->nr_user_files;
5422 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
5424 ret = __io_sqe_files_scm(ctx, this_files, total);
5428 total += this_files;
5434 while (total < ctx->nr_user_files) {
5435 struct file *file = io_file_from_index(ctx, total);
5445 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5451 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5456 for (i = 0; i < nr_tables; i++) {
5457 struct fixed_file_table *table = &ctx->file_data->table[i];
5458 unsigned this_files;
5460 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5461 table->files = kcalloc(this_files, sizeof(struct file *),
5465 nr_files -= this_files;
5471 for (i = 0; i < nr_tables; i++) {
5472 struct fixed_file_table *table = &ctx->file_data->table[i];
5473 kfree(table->files);
5478 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5480 #if defined(CONFIG_UNIX)
5481 struct sock *sock = ctx->ring_sock->sk;
5482 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5483 struct sk_buff *skb;
5486 __skb_queue_head_init(&list);
5489 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5490 * remove this entry and rearrange the file array.
5492 skb = skb_dequeue(head);
5494 struct scm_fp_list *fp;
5496 fp = UNIXCB(skb).fp;
5497 for (i = 0; i < fp->count; i++) {
5500 if (fp->fp[i] != file)
5503 unix_notinflight(fp->user, fp->fp[i]);
5504 left = fp->count - 1 - i;
5506 memmove(&fp->fp[i], &fp->fp[i + 1],
5507 left * sizeof(struct file *));
5514 __skb_queue_tail(&list, skb);
5524 __skb_queue_tail(&list, skb);
5526 skb = skb_dequeue(head);
5529 if (skb_peek(&list)) {
5530 spin_lock_irq(&head->lock);
5531 while ((skb = __skb_dequeue(&list)) != NULL)
5532 __skb_queue_tail(head, skb);
5533 spin_unlock_irq(&head->lock);
5540 struct io_file_put {
5541 struct llist_node llist;
5543 struct completion *done;
5546 static void io_ring_file_ref_flush(struct fixed_file_data *data)
5548 struct io_file_put *pfile, *tmp;
5549 struct llist_node *node;
5551 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5552 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5553 io_ring_file_put(data->ctx, pfile->file);
5555 complete(pfile->done);
5562 static void io_ring_file_ref_switch(struct work_struct *work)
5564 struct fixed_file_data *data;
5566 data = container_of(work, struct fixed_file_data, ref_work);
5567 io_ring_file_ref_flush(data);
5568 percpu_ref_get(&data->refs);
5569 percpu_ref_switch_to_percpu(&data->refs);
5572 static void io_file_data_ref_zero(struct percpu_ref *ref)
5574 struct fixed_file_data *data;
5576 data = container_of(ref, struct fixed_file_data, refs);
5579 * We can't safely switch from inside this context, punt to wq. If
5580 * the table ref is going away, the table is being unregistered.
5581 * Don't queue up the async work for that case, the caller will
5584 if (!percpu_ref_is_dying(&data->refs))
5585 queue_work(system_wq, &data->ref_work);
5588 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5591 __s32 __user *fds = (__s32 __user *) arg;
5601 if (nr_args > IORING_MAX_FIXED_FILES)
5604 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5605 if (!ctx->file_data)
5607 ctx->file_data->ctx = ctx;
5608 init_completion(&ctx->file_data->done);
5610 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5611 ctx->file_data->table = kcalloc(nr_tables,
5612 sizeof(struct fixed_file_table),
5614 if (!ctx->file_data->table) {
5615 kfree(ctx->file_data);
5616 ctx->file_data = NULL;
5620 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5621 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5622 kfree(ctx->file_data->table);
5623 kfree(ctx->file_data);
5624 ctx->file_data = NULL;
5627 ctx->file_data->put_llist.first = NULL;
5628 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5630 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5631 percpu_ref_exit(&ctx->file_data->refs);
5632 kfree(ctx->file_data->table);
5633 kfree(ctx->file_data);
5634 ctx->file_data = NULL;
5638 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5639 struct fixed_file_table *table;
5643 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5645 /* allow sparse sets */
5651 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5652 index = i & IORING_FILE_TABLE_MASK;
5660 * Don't allow io_uring instances to be registered. If UNIX
5661 * isn't enabled, then this causes a reference cycle and this
5662 * instance can never get freed. If UNIX is enabled we'll
5663 * handle it just fine, but there's still no point in allowing
5664 * a ring fd as it doesn't support regular read/write anyway.
5666 if (file->f_op == &io_uring_fops) {
5671 table->files[index] = file;
5675 for (i = 0; i < ctx->nr_user_files; i++) {
5676 file = io_file_from_index(ctx, i);
5680 for (i = 0; i < nr_tables; i++)
5681 kfree(ctx->file_data->table[i].files);
5683 kfree(ctx->file_data->table);
5684 kfree(ctx->file_data);
5685 ctx->file_data = NULL;
5686 ctx->nr_user_files = 0;
5690 ret = io_sqe_files_scm(ctx);
5692 io_sqe_files_unregister(ctx);
5697 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5700 #if defined(CONFIG_UNIX)
5701 struct sock *sock = ctx->ring_sock->sk;
5702 struct sk_buff_head *head = &sock->sk_receive_queue;
5703 struct sk_buff *skb;
5706 * See if we can merge this file into an existing skb SCM_RIGHTS
5707 * file set. If there's no room, fall back to allocating a new skb
5708 * and filling it in.
5710 spin_lock_irq(&head->lock);
5711 skb = skb_peek(head);
5713 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5715 if (fpl->count < SCM_MAX_FD) {
5716 __skb_unlink(skb, head);
5717 spin_unlock_irq(&head->lock);
5718 fpl->fp[fpl->count] = get_file(file);
5719 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5721 spin_lock_irq(&head->lock);
5722 __skb_queue_head(head, skb);
5727 spin_unlock_irq(&head->lock);
5734 return __io_sqe_files_scm(ctx, 1, index);
5740 static void io_atomic_switch(struct percpu_ref *ref)
5742 struct fixed_file_data *data;
5744 data = container_of(ref, struct fixed_file_data, refs);
5745 clear_bit(FFD_F_ATOMIC, &data->state);
5748 static bool io_queue_file_removal(struct fixed_file_data *data,
5751 struct io_file_put *pfile, pfile_stack;
5752 DECLARE_COMPLETION_ONSTACK(done);
5755 * If we fail allocating the struct we need for doing async reomval
5756 * of this file, just punt to sync and wait for it.
5758 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5760 pfile = &pfile_stack;
5761 pfile->done = &done;
5765 llist_add(&pfile->llist, &data->put_llist);
5767 if (pfile == &pfile_stack) {
5768 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5769 percpu_ref_put(&data->refs);
5770 percpu_ref_switch_to_atomic(&data->refs,
5773 wait_for_completion(&done);
5774 flush_work(&data->ref_work);
5781 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5782 struct io_uring_files_update *up,
5785 struct fixed_file_data *data = ctx->file_data;
5786 bool ref_switch = false;
5792 if (check_add_overflow(up->offset, nr_args, &done))
5794 if (done > ctx->nr_user_files)
5798 fds = u64_to_user_ptr(up->fds);
5800 struct fixed_file_table *table;
5804 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5808 i = array_index_nospec(up->offset, ctx->nr_user_files);
5809 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5810 index = i & IORING_FILE_TABLE_MASK;
5811 if (table->files[index]) {
5812 file = io_file_from_index(ctx, index);
5813 table->files[index] = NULL;
5814 if (io_queue_file_removal(data, file))
5824 * Don't allow io_uring instances to be registered. If
5825 * UNIX isn't enabled, then this causes a reference
5826 * cycle and this instance can never get freed. If UNIX
5827 * is enabled we'll handle it just fine, but there's
5828 * still no point in allowing a ring fd as it doesn't
5829 * support regular read/write anyway.
5831 if (file->f_op == &io_uring_fops) {
5836 table->files[index] = file;
5837 err = io_sqe_file_register(ctx, file, i);
5846 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5847 percpu_ref_put(&data->refs);
5848 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5851 return done ? done : err;
5853 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5856 struct io_uring_files_update up;
5858 if (!ctx->file_data)
5862 if (copy_from_user(&up, arg, sizeof(up)))
5867 return __io_sqe_files_update(ctx, &up, nr_args);
5870 static void io_put_work(struct io_wq_work *work)
5872 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5877 static void io_get_work(struct io_wq_work *work)
5879 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5881 refcount_inc(&req->refs);
5884 static int io_init_wq_offload(struct io_ring_ctx *ctx,
5885 struct io_uring_params *p)
5887 struct io_wq_data data;
5889 struct io_ring_ctx *ctx_attach;
5890 unsigned int concurrency;
5893 data.user = ctx->user;
5894 data.get_work = io_get_work;
5895 data.put_work = io_put_work;
5897 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
5898 /* Do QD, or 4 * CPUS, whatever is smallest */
5899 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5901 ctx->io_wq = io_wq_create(concurrency, &data);
5902 if (IS_ERR(ctx->io_wq)) {
5903 ret = PTR_ERR(ctx->io_wq);
5909 f = fdget(p->wq_fd);
5913 if (f.file->f_op != &io_uring_fops) {
5918 ctx_attach = f.file->private_data;
5919 /* @io_wq is protected by holding the fd */
5920 if (!io_wq_get(ctx_attach->io_wq, &data)) {
5925 ctx->io_wq = ctx_attach->io_wq;
5931 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5932 struct io_uring_params *p)
5936 init_waitqueue_head(&ctx->sqo_wait);
5937 mmgrab(current->mm);
5938 ctx->sqo_mm = current->mm;
5940 if (ctx->flags & IORING_SETUP_SQPOLL) {
5942 if (!capable(CAP_SYS_ADMIN))
5945 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5946 if (!ctx->sq_thread_idle)
5947 ctx->sq_thread_idle = HZ;
5949 if (p->flags & IORING_SETUP_SQ_AFF) {
5950 int cpu = p->sq_thread_cpu;
5953 if (cpu >= nr_cpu_ids)
5955 if (!cpu_online(cpu))
5958 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5962 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5965 if (IS_ERR(ctx->sqo_thread)) {
5966 ret = PTR_ERR(ctx->sqo_thread);
5967 ctx->sqo_thread = NULL;
5970 wake_up_process(ctx->sqo_thread);
5971 } else if (p->flags & IORING_SETUP_SQ_AFF) {
5972 /* Can't have SQ_AFF without SQPOLL */
5977 ret = io_init_wq_offload(ctx, p);
5983 io_finish_async(ctx);
5984 mmdrop(ctx->sqo_mm);
5989 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
5991 atomic_long_sub(nr_pages, &user->locked_vm);
5994 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
5996 unsigned long page_limit, cur_pages, new_pages;
5998 /* Don't allow more pages than we can safely lock */
5999 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
6002 cur_pages = atomic_long_read(&user->locked_vm);
6003 new_pages = cur_pages + nr_pages;
6004 if (new_pages > page_limit)
6006 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
6007 new_pages) != cur_pages);
6012 static void io_mem_free(void *ptr)
6019 page = virt_to_head_page(ptr);
6020 if (put_page_testzero(page))
6021 free_compound_page(page);
6024 static void *io_mem_alloc(size_t size)
6026 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
6029 return (void *) __get_free_pages(gfp_flags, get_order(size));
6032 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
6035 struct io_rings *rings;
6036 size_t off, sq_array_size;
6038 off = struct_size(rings, cqes, cq_entries);
6039 if (off == SIZE_MAX)
6043 off = ALIGN(off, SMP_CACHE_BYTES);
6048 sq_array_size = array_size(sizeof(u32), sq_entries);
6049 if (sq_array_size == SIZE_MAX)
6052 if (check_add_overflow(off, sq_array_size, &off))
6061 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
6065 pages = (size_t)1 << get_order(
6066 rings_size(sq_entries, cq_entries, NULL));
6067 pages += (size_t)1 << get_order(
6068 array_size(sizeof(struct io_uring_sqe), sq_entries));
6073 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6077 if (!ctx->user_bufs)
6080 for (i = 0; i < ctx->nr_user_bufs; i++) {
6081 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6083 for (j = 0; j < imu->nr_bvecs; j++)
6084 unpin_user_page(imu->bvec[j].bv_page);
6086 if (ctx->account_mem)
6087 io_unaccount_mem(ctx->user, imu->nr_bvecs);
6092 kfree(ctx->user_bufs);
6093 ctx->user_bufs = NULL;
6094 ctx->nr_user_bufs = 0;
6098 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6099 void __user *arg, unsigned index)
6101 struct iovec __user *src;
6103 #ifdef CONFIG_COMPAT
6105 struct compat_iovec __user *ciovs;
6106 struct compat_iovec ciov;
6108 ciovs = (struct compat_iovec __user *) arg;
6109 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6112 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
6113 dst->iov_len = ciov.iov_len;
6117 src = (struct iovec __user *) arg;
6118 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6123 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6126 struct vm_area_struct **vmas = NULL;
6127 struct page **pages = NULL;
6128 int i, j, got_pages = 0;
6133 if (!nr_args || nr_args > UIO_MAXIOV)
6136 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6138 if (!ctx->user_bufs)
6141 for (i = 0; i < nr_args; i++) {
6142 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6143 unsigned long off, start, end, ubuf;
6148 ret = io_copy_iov(ctx, &iov, arg, i);
6153 * Don't impose further limits on the size and buffer
6154 * constraints here, we'll -EINVAL later when IO is
6155 * submitted if they are wrong.
6158 if (!iov.iov_base || !iov.iov_len)
6161 /* arbitrary limit, but we need something */
6162 if (iov.iov_len > SZ_1G)
6165 ubuf = (unsigned long) iov.iov_base;
6166 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6167 start = ubuf >> PAGE_SHIFT;
6168 nr_pages = end - start;
6170 if (ctx->account_mem) {
6171 ret = io_account_mem(ctx->user, nr_pages);
6177 if (!pages || nr_pages > got_pages) {
6180 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
6182 vmas = kvmalloc_array(nr_pages,
6183 sizeof(struct vm_area_struct *),
6185 if (!pages || !vmas) {
6187 if (ctx->account_mem)
6188 io_unaccount_mem(ctx->user, nr_pages);
6191 got_pages = nr_pages;
6194 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
6198 if (ctx->account_mem)
6199 io_unaccount_mem(ctx->user, nr_pages);
6204 down_read(¤t->mm->mmap_sem);
6205 pret = pin_user_pages(ubuf, nr_pages,
6206 FOLL_WRITE | FOLL_LONGTERM,
6208 if (pret == nr_pages) {
6209 /* don't support file backed memory */
6210 for (j = 0; j < nr_pages; j++) {
6211 struct vm_area_struct *vma = vmas[j];
6214 !is_file_hugepages(vma->vm_file)) {
6220 ret = pret < 0 ? pret : -EFAULT;
6222 up_read(¤t->mm->mmap_sem);
6225 * if we did partial map, or found file backed vmas,
6226 * release any pages we did get
6229 unpin_user_pages(pages, pret);
6230 if (ctx->account_mem)
6231 io_unaccount_mem(ctx->user, nr_pages);
6236 off = ubuf & ~PAGE_MASK;
6238 for (j = 0; j < nr_pages; j++) {
6241 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6242 imu->bvec[j].bv_page = pages[j];
6243 imu->bvec[j].bv_len = vec_len;
6244 imu->bvec[j].bv_offset = off;
6248 /* store original address for later verification */
6250 imu->len = iov.iov_len;
6251 imu->nr_bvecs = nr_pages;
6253 ctx->nr_user_bufs++;
6261 io_sqe_buffer_unregister(ctx);
6265 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6267 __s32 __user *fds = arg;
6273 if (copy_from_user(&fd, fds, sizeof(*fds)))
6276 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6277 if (IS_ERR(ctx->cq_ev_fd)) {
6278 int ret = PTR_ERR(ctx->cq_ev_fd);
6279 ctx->cq_ev_fd = NULL;
6286 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6288 if (ctx->cq_ev_fd) {
6289 eventfd_ctx_put(ctx->cq_ev_fd);
6290 ctx->cq_ev_fd = NULL;
6297 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6299 io_finish_async(ctx);
6301 mmdrop(ctx->sqo_mm);
6303 io_iopoll_reap_events(ctx);
6304 io_sqe_buffer_unregister(ctx);
6305 io_sqe_files_unregister(ctx);
6306 io_eventfd_unregister(ctx);
6308 #if defined(CONFIG_UNIX)
6309 if (ctx->ring_sock) {
6310 ctx->ring_sock->file = NULL; /* so that iput() is called */
6311 sock_release(ctx->ring_sock);
6315 io_mem_free(ctx->rings);
6316 io_mem_free(ctx->sq_sqes);
6318 percpu_ref_exit(&ctx->refs);
6319 if (ctx->account_mem)
6320 io_unaccount_mem(ctx->user,
6321 ring_pages(ctx->sq_entries, ctx->cq_entries));
6322 free_uid(ctx->user);
6323 put_cred(ctx->creds);
6324 kfree(ctx->completions);
6325 kfree(ctx->cancel_hash);
6326 kmem_cache_free(req_cachep, ctx->fallback_req);
6330 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6332 struct io_ring_ctx *ctx = file->private_data;
6335 poll_wait(file, &ctx->cq_wait, wait);
6337 * synchronizes with barrier from wq_has_sleeper call in
6341 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6342 ctx->rings->sq_ring_entries)
6343 mask |= EPOLLOUT | EPOLLWRNORM;
6344 if (io_cqring_events(ctx, false))
6345 mask |= EPOLLIN | EPOLLRDNORM;
6350 static int io_uring_fasync(int fd, struct file *file, int on)
6352 struct io_ring_ctx *ctx = file->private_data;
6354 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6357 static int io_remove_personalities(int id, void *p, void *data)
6359 struct io_ring_ctx *ctx = data;
6360 const struct cred *cred;
6362 cred = idr_remove(&ctx->personality_idr, id);
6368 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6370 mutex_lock(&ctx->uring_lock);
6371 percpu_ref_kill(&ctx->refs);
6372 mutex_unlock(&ctx->uring_lock);
6375 * Wait for sq thread to idle, if we have one. It won't spin on new
6376 * work after we've killed the ctx ref above. This is important to do
6377 * before we cancel existing commands, as the thread could otherwise
6378 * be queueing new work post that. If that's work we need to cancel,
6379 * it could cause shutdown to hang.
6381 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
6384 io_kill_timeouts(ctx);
6385 io_poll_remove_all(ctx);
6388 io_wq_cancel_all(ctx->io_wq);
6390 io_iopoll_reap_events(ctx);
6391 /* if we failed setting up the ctx, we might not have any rings */
6393 io_cqring_overflow_flush(ctx, true);
6394 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
6395 wait_for_completion(&ctx->completions[0]);
6396 io_ring_ctx_free(ctx);
6399 static int io_uring_release(struct inode *inode, struct file *file)
6401 struct io_ring_ctx *ctx = file->private_data;
6403 file->private_data = NULL;
6404 io_ring_ctx_wait_and_kill(ctx);
6408 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6409 struct files_struct *files)
6411 struct io_kiocb *req;
6414 while (!list_empty_careful(&ctx->inflight_list)) {
6415 struct io_kiocb *cancel_req = NULL;
6417 spin_lock_irq(&ctx->inflight_lock);
6418 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
6419 if (req->work.files != files)
6421 /* req is being completed, ignore */
6422 if (!refcount_inc_not_zero(&req->refs))
6428 prepare_to_wait(&ctx->inflight_wait, &wait,
6429 TASK_UNINTERRUPTIBLE);
6430 spin_unlock_irq(&ctx->inflight_lock);
6432 /* We need to keep going until we don't find a matching req */
6436 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6437 io_put_req(cancel_req);
6440 finish_wait(&ctx->inflight_wait, &wait);
6443 static int io_uring_flush(struct file *file, void *data)
6445 struct io_ring_ctx *ctx = file->private_data;
6447 io_uring_cancel_files(ctx, data);
6451 static void *io_uring_validate_mmap_request(struct file *file,
6452 loff_t pgoff, size_t sz)
6454 struct io_ring_ctx *ctx = file->private_data;
6455 loff_t offset = pgoff << PAGE_SHIFT;
6460 case IORING_OFF_SQ_RING:
6461 case IORING_OFF_CQ_RING:
6464 case IORING_OFF_SQES:
6468 return ERR_PTR(-EINVAL);
6471 page = virt_to_head_page(ptr);
6472 if (sz > page_size(page))
6473 return ERR_PTR(-EINVAL);
6480 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6482 size_t sz = vma->vm_end - vma->vm_start;
6486 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6488 return PTR_ERR(ptr);
6490 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6491 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6494 #else /* !CONFIG_MMU */
6496 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6498 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6501 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6503 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6506 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6507 unsigned long addr, unsigned long len,
6508 unsigned long pgoff, unsigned long flags)
6512 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6514 return PTR_ERR(ptr);
6516 return (unsigned long) ptr;
6519 #endif /* !CONFIG_MMU */
6521 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6522 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6525 struct io_ring_ctx *ctx;
6530 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
6538 if (f.file->f_op != &io_uring_fops)
6542 ctx = f.file->private_data;
6543 if (!percpu_ref_tryget(&ctx->refs))
6547 * For SQ polling, the thread will do all submissions and completions.
6548 * Just return the requested submit count, and wake the thread if
6552 if (ctx->flags & IORING_SETUP_SQPOLL) {
6553 if (!list_empty_careful(&ctx->cq_overflow_list))
6554 io_cqring_overflow_flush(ctx, false);
6555 if (flags & IORING_ENTER_SQ_WAKEUP)
6556 wake_up(&ctx->sqo_wait);
6557 submitted = to_submit;
6558 } else if (to_submit) {
6559 struct mm_struct *cur_mm;
6561 mutex_lock(&ctx->uring_lock);
6562 /* already have mm, so io_submit_sqes() won't try to grab it */
6563 cur_mm = ctx->sqo_mm;
6564 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6566 mutex_unlock(&ctx->uring_lock);
6568 if (submitted != to_submit)
6571 if (flags & IORING_ENTER_GETEVENTS) {
6572 unsigned nr_events = 0;
6574 min_complete = min(min_complete, ctx->cq_entries);
6576 if (ctx->flags & IORING_SETUP_IOPOLL) {
6577 ret = io_iopoll_check(ctx, &nr_events, min_complete);
6579 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6584 percpu_ref_put(&ctx->refs);
6587 return submitted ? submitted : ret;
6590 static int io_uring_show_cred(int id, void *p, void *data)
6592 const struct cred *cred = p;
6593 struct seq_file *m = data;
6594 struct user_namespace *uns = seq_user_ns(m);
6595 struct group_info *gi;
6600 seq_printf(m, "%5d\n", id);
6601 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
6602 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
6603 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
6604 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
6605 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
6606 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
6607 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
6608 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
6609 seq_puts(m, "\n\tGroups:\t");
6610 gi = cred->group_info;
6611 for (g = 0; g < gi->ngroups; g++) {
6612 seq_put_decimal_ull(m, g ? " " : "",
6613 from_kgid_munged(uns, gi->gid[g]));
6615 seq_puts(m, "\n\tCapEff:\t");
6616 cap = cred->cap_effective;
6617 CAP_FOR_EACH_U32(__capi)
6618 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
6623 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
6627 mutex_lock(&ctx->uring_lock);
6628 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
6629 for (i = 0; i < ctx->nr_user_files; i++) {
6630 struct fixed_file_table *table;
6633 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6634 f = table->files[i & IORING_FILE_TABLE_MASK];
6636 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
6638 seq_printf(m, "%5u: <none>\n", i);
6640 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
6641 for (i = 0; i < ctx->nr_user_bufs; i++) {
6642 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
6644 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
6645 (unsigned int) buf->len);
6647 if (!idr_is_empty(&ctx->personality_idr)) {
6648 seq_printf(m, "Personalities:\n");
6649 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
6651 mutex_unlock(&ctx->uring_lock);
6654 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
6656 struct io_ring_ctx *ctx = f->private_data;
6658 if (percpu_ref_tryget(&ctx->refs)) {
6659 __io_uring_show_fdinfo(ctx, m);
6660 percpu_ref_put(&ctx->refs);
6664 static const struct file_operations io_uring_fops = {
6665 .release = io_uring_release,
6666 .flush = io_uring_flush,
6667 .mmap = io_uring_mmap,
6669 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6670 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6672 .poll = io_uring_poll,
6673 .fasync = io_uring_fasync,
6674 .show_fdinfo = io_uring_show_fdinfo,
6677 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6678 struct io_uring_params *p)
6680 struct io_rings *rings;
6681 size_t size, sq_array_offset;
6683 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6684 if (size == SIZE_MAX)
6687 rings = io_mem_alloc(size);
6692 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6693 rings->sq_ring_mask = p->sq_entries - 1;
6694 rings->cq_ring_mask = p->cq_entries - 1;
6695 rings->sq_ring_entries = p->sq_entries;
6696 rings->cq_ring_entries = p->cq_entries;
6697 ctx->sq_mask = rings->sq_ring_mask;
6698 ctx->cq_mask = rings->cq_ring_mask;
6699 ctx->sq_entries = rings->sq_ring_entries;
6700 ctx->cq_entries = rings->cq_ring_entries;
6702 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6703 if (size == SIZE_MAX) {
6704 io_mem_free(ctx->rings);
6709 ctx->sq_sqes = io_mem_alloc(size);
6710 if (!ctx->sq_sqes) {
6711 io_mem_free(ctx->rings);
6720 * Allocate an anonymous fd, this is what constitutes the application
6721 * visible backing of an io_uring instance. The application mmaps this
6722 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6723 * we have to tie this fd to a socket for file garbage collection purposes.
6725 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6730 #if defined(CONFIG_UNIX)
6731 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6737 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6741 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6742 O_RDWR | O_CLOEXEC);
6745 ret = PTR_ERR(file);
6749 #if defined(CONFIG_UNIX)
6750 ctx->ring_sock->file = file;
6752 fd_install(ret, file);
6755 #if defined(CONFIG_UNIX)
6756 sock_release(ctx->ring_sock);
6757 ctx->ring_sock = NULL;
6762 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6764 struct user_struct *user = NULL;
6765 struct io_ring_ctx *ctx;
6771 if (entries > IORING_MAX_ENTRIES) {
6772 if (!(p->flags & IORING_SETUP_CLAMP))
6774 entries = IORING_MAX_ENTRIES;
6778 * Use twice as many entries for the CQ ring. It's possible for the
6779 * application to drive a higher depth than the size of the SQ ring,
6780 * since the sqes are only used at submission time. This allows for
6781 * some flexibility in overcommitting a bit. If the application has
6782 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6783 * of CQ ring entries manually.
6785 p->sq_entries = roundup_pow_of_two(entries);
6786 if (p->flags & IORING_SETUP_CQSIZE) {
6788 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6789 * to a power-of-two, if it isn't already. We do NOT impose
6790 * any cq vs sq ring sizing.
6792 if (p->cq_entries < p->sq_entries)
6794 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6795 if (!(p->flags & IORING_SETUP_CLAMP))
6797 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6799 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6801 p->cq_entries = 2 * p->sq_entries;
6804 user = get_uid(current_user());
6805 account_mem = !capable(CAP_IPC_LOCK);
6808 ret = io_account_mem(user,
6809 ring_pages(p->sq_entries, p->cq_entries));
6816 ctx = io_ring_ctx_alloc(p);
6819 io_unaccount_mem(user, ring_pages(p->sq_entries,
6824 ctx->compat = in_compat_syscall();
6825 ctx->account_mem = account_mem;
6827 ctx->creds = get_current_cred();
6829 ret = io_allocate_scq_urings(ctx, p);
6833 ret = io_sq_offload_start(ctx, p);
6837 memset(&p->sq_off, 0, sizeof(p->sq_off));
6838 p->sq_off.head = offsetof(struct io_rings, sq.head);
6839 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6840 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6841 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6842 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6843 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6844 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6846 memset(&p->cq_off, 0, sizeof(p->cq_off));
6847 p->cq_off.head = offsetof(struct io_rings, cq.head);
6848 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6849 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6850 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6851 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6852 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6855 * Install ring fd as the very last thing, so we don't risk someone
6856 * having closed it before we finish setup
6858 ret = io_uring_get_fd(ctx);
6862 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6863 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6864 IORING_FEAT_CUR_PERSONALITY;
6865 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6868 io_ring_ctx_wait_and_kill(ctx);
6873 * Sets up an aio uring context, and returns the fd. Applications asks for a
6874 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6875 * params structure passed in.
6877 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6879 struct io_uring_params p;
6883 if (copy_from_user(&p, params, sizeof(p)))
6885 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6890 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6891 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6892 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
6895 ret = io_uring_create(entries, &p);
6899 if (copy_to_user(params, &p, sizeof(p)))
6905 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6906 struct io_uring_params __user *, params)
6908 return io_uring_setup(entries, params);
6911 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6913 struct io_uring_probe *p;
6917 size = struct_size(p, ops, nr_args);
6918 if (size == SIZE_MAX)
6920 p = kzalloc(size, GFP_KERNEL);
6925 if (copy_from_user(p, arg, size))
6928 if (memchr_inv(p, 0, size))
6931 p->last_op = IORING_OP_LAST - 1;
6932 if (nr_args > IORING_OP_LAST)
6933 nr_args = IORING_OP_LAST;
6935 for (i = 0; i < nr_args; i++) {
6937 if (!io_op_defs[i].not_supported)
6938 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6943 if (copy_to_user(arg, p, size))
6950 static int io_register_personality(struct io_ring_ctx *ctx)
6952 const struct cred *creds = get_current_cred();
6955 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
6956 USHRT_MAX, GFP_KERNEL);
6962 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
6964 const struct cred *old_creds;
6966 old_creds = idr_remove(&ctx->personality_idr, id);
6968 put_cred(old_creds);
6975 static bool io_register_op_must_quiesce(int op)
6978 case IORING_UNREGISTER_FILES:
6979 case IORING_REGISTER_FILES_UPDATE:
6980 case IORING_REGISTER_PROBE:
6981 case IORING_REGISTER_PERSONALITY:
6982 case IORING_UNREGISTER_PERSONALITY:
6989 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6990 void __user *arg, unsigned nr_args)
6991 __releases(ctx->uring_lock)
6992 __acquires(ctx->uring_lock)
6997 * We're inside the ring mutex, if the ref is already dying, then
6998 * someone else killed the ctx or is already going through
6999 * io_uring_register().
7001 if (percpu_ref_is_dying(&ctx->refs))
7004 if (io_register_op_must_quiesce(opcode)) {
7005 percpu_ref_kill(&ctx->refs);
7008 * Drop uring mutex before waiting for references to exit. If
7009 * another thread is currently inside io_uring_enter() it might
7010 * need to grab the uring_lock to make progress. If we hold it
7011 * here across the drain wait, then we can deadlock. It's safe
7012 * to drop the mutex here, since no new references will come in
7013 * after we've killed the percpu ref.
7015 mutex_unlock(&ctx->uring_lock);
7016 ret = wait_for_completion_interruptible(&ctx->completions[0]);
7017 mutex_lock(&ctx->uring_lock);
7019 percpu_ref_resurrect(&ctx->refs);
7026 case IORING_REGISTER_BUFFERS:
7027 ret = io_sqe_buffer_register(ctx, arg, nr_args);
7029 case IORING_UNREGISTER_BUFFERS:
7033 ret = io_sqe_buffer_unregister(ctx);
7035 case IORING_REGISTER_FILES:
7036 ret = io_sqe_files_register(ctx, arg, nr_args);
7038 case IORING_UNREGISTER_FILES:
7042 ret = io_sqe_files_unregister(ctx);
7044 case IORING_REGISTER_FILES_UPDATE:
7045 ret = io_sqe_files_update(ctx, arg, nr_args);
7047 case IORING_REGISTER_EVENTFD:
7048 case IORING_REGISTER_EVENTFD_ASYNC:
7052 ret = io_eventfd_register(ctx, arg);
7055 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
7056 ctx->eventfd_async = 1;
7058 ctx->eventfd_async = 0;
7060 case IORING_UNREGISTER_EVENTFD:
7064 ret = io_eventfd_unregister(ctx);
7066 case IORING_REGISTER_PROBE:
7068 if (!arg || nr_args > 256)
7070 ret = io_probe(ctx, arg, nr_args);
7072 case IORING_REGISTER_PERSONALITY:
7076 ret = io_register_personality(ctx);
7078 case IORING_UNREGISTER_PERSONALITY:
7082 ret = io_unregister_personality(ctx, nr_args);
7089 if (io_register_op_must_quiesce(opcode)) {
7090 /* bring the ctx back to life */
7091 percpu_ref_reinit(&ctx->refs);
7093 reinit_completion(&ctx->completions[0]);
7098 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7099 void __user *, arg, unsigned int, nr_args)
7101 struct io_ring_ctx *ctx;
7110 if (f.file->f_op != &io_uring_fops)
7113 ctx = f.file->private_data;
7115 mutex_lock(&ctx->uring_lock);
7116 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7117 mutex_unlock(&ctx->uring_lock);
7118 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
7119 ctx->cq_ev_fd != NULL, ret);
7125 static int __init io_uring_init(void)
7127 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7128 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7129 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7132 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7133 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7134 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7135 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7136 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7137 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7138 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7139 BUILD_BUG_SQE_ELEM(8, __u64, off);
7140 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7141 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7142 BUILD_BUG_SQE_ELEM(24, __u32, len);
7143 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7144 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7145 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7146 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7147 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
7148 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7149 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7150 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7151 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7152 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7153 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7154 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7155 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7156 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7157 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7158 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7160 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7161 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
7164 __initcall(io_uring_init);