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>
78 #include <linux/fs_struct.h>
80 #define CREATE_TRACE_POINTS
81 #include <trace/events/io_uring.h>
83 #include <uapi/linux/io_uring.h>
88 #define IORING_MAX_ENTRIES 32768
89 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
92 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
94 #define IORING_FILE_TABLE_SHIFT 9
95 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
96 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
97 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
100 u32 head ____cacheline_aligned_in_smp;
101 u32 tail ____cacheline_aligned_in_smp;
105 * This data is shared with the application through the mmap at offsets
106 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
108 * The offsets to the member fields are published through struct
109 * io_sqring_offsets when calling io_uring_setup.
113 * Head and tail offsets into the ring; the offsets need to be
114 * masked to get valid indices.
116 * The kernel controls head of the sq ring and the tail of the cq ring,
117 * and the application controls tail of the sq ring and the head of the
120 struct io_uring sq, cq;
122 * Bitmasks to apply to head and tail offsets (constant, equals
125 u32 sq_ring_mask, cq_ring_mask;
126 /* Ring sizes (constant, power of 2) */
127 u32 sq_ring_entries, cq_ring_entries;
129 * Number of invalid entries dropped by the kernel due to
130 * invalid index stored in array
132 * Written by the kernel, shouldn't be modified by the
133 * application (i.e. get number of "new events" by comparing to
136 * After a new SQ head value was read by the application this
137 * counter includes all submissions that were dropped reaching
138 * the new SQ head (and possibly more).
144 * Written by the kernel, shouldn't be modified by the
147 * The application needs a full memory barrier before checking
148 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
152 * Number of completion events lost because the queue was full;
153 * this should be avoided by the application by making sure
154 * there are not more requests pending than there is space in
155 * the completion queue.
157 * Written by the kernel, shouldn't be modified by the
158 * application (i.e. get number of "new events" by comparing to
161 * As completion events come in out of order this counter is not
162 * ordered with any other data.
166 * Ring buffer of completion events.
168 * The kernel writes completion events fresh every time they are
169 * produced, so the application is allowed to modify pending
172 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
175 struct io_mapped_ubuf {
178 struct bio_vec *bvec;
179 unsigned int nr_bvecs;
182 struct fixed_file_table {
190 struct fixed_file_data {
191 struct fixed_file_table *table;
192 struct io_ring_ctx *ctx;
194 struct percpu_ref refs;
195 struct llist_head put_llist;
197 struct work_struct ref_work;
198 struct completion done;
203 struct percpu_ref refs;
204 } ____cacheline_aligned_in_smp;
208 unsigned int compat: 1;
209 unsigned int account_mem: 1;
210 unsigned int cq_overflow_flushed: 1;
211 unsigned int drain_next: 1;
212 unsigned int eventfd_async: 1;
215 * Ring buffer of indices into array of io_uring_sqe, which is
216 * mmapped by the application using the IORING_OFF_SQES offset.
218 * This indirection could e.g. be used to assign fixed
219 * io_uring_sqe entries to operations and only submit them to
220 * the queue when needed.
222 * The kernel modifies neither the indices array nor the entries
226 unsigned cached_sq_head;
229 unsigned sq_thread_idle;
230 unsigned cached_sq_dropped;
231 atomic_t cached_cq_overflow;
232 unsigned long sq_check_overflow;
234 struct list_head defer_list;
235 struct list_head timeout_list;
236 struct list_head cq_overflow_list;
238 wait_queue_head_t inflight_wait;
239 struct io_uring_sqe *sq_sqes;
240 } ____cacheline_aligned_in_smp;
242 struct io_rings *rings;
246 struct task_struct *sqo_thread; /* if using sq thread polling */
247 struct mm_struct *sqo_mm;
248 wait_queue_head_t sqo_wait;
251 * If used, fixed file set. Writers must ensure that ->refs is dead,
252 * readers must ensure that ->refs is alive as long as the file* is
253 * used. Only updated through io_uring_register(2).
255 struct fixed_file_data *file_data;
256 unsigned nr_user_files;
258 struct file *ring_file;
260 /* if used, fixed mapped user buffers */
261 unsigned nr_user_bufs;
262 struct io_mapped_ubuf *user_bufs;
264 struct user_struct *user;
266 const struct cred *creds;
268 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
269 struct completion *completions;
271 /* if all else fails... */
272 struct io_kiocb *fallback_req;
274 #if defined(CONFIG_UNIX)
275 struct socket *ring_sock;
278 struct idr personality_idr;
281 unsigned cached_cq_tail;
284 atomic_t cq_timeouts;
285 unsigned long cq_check_overflow;
286 struct wait_queue_head cq_wait;
287 struct fasync_struct *cq_fasync;
288 struct eventfd_ctx *cq_ev_fd;
289 } ____cacheline_aligned_in_smp;
292 struct mutex uring_lock;
293 wait_queue_head_t wait;
294 } ____cacheline_aligned_in_smp;
297 spinlock_t completion_lock;
298 struct llist_head poll_llist;
301 * ->poll_list is protected by the ctx->uring_lock for
302 * io_uring instances that don't use IORING_SETUP_SQPOLL.
303 * For SQPOLL, only the single threaded io_sq_thread() will
304 * manipulate the list, hence no extra locking is needed there.
306 struct list_head poll_list;
307 struct hlist_head *cancel_hash;
308 unsigned cancel_hash_bits;
309 bool poll_multi_file;
311 spinlock_t inflight_lock;
312 struct list_head inflight_list;
313 } ____cacheline_aligned_in_smp;
317 * First field must be the file pointer in all the
318 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
320 struct io_poll_iocb {
323 struct wait_queue_head *head;
329 struct wait_queue_entry wait;
334 struct file *put_file;
338 struct io_timeout_data {
339 struct io_kiocb *req;
340 struct hrtimer timer;
341 struct timespec64 ts;
342 enum hrtimer_mode mode;
348 struct sockaddr __user *addr;
349 int __user *addr_len;
374 /* NOTE: kiocb has the file as the first member, so don't do it here */
382 struct sockaddr __user *addr;
389 struct user_msghdr __user *msg;
402 struct filename *filename;
403 struct statx __user *buffer;
407 struct io_files_update {
433 struct epoll_event event;
436 struct io_async_connect {
437 struct sockaddr_storage address;
440 struct io_async_msghdr {
441 struct iovec fast_iov[UIO_FASTIOV];
443 struct sockaddr __user *uaddr;
448 struct iovec fast_iov[UIO_FASTIOV];
454 struct io_async_ctx {
456 struct io_async_rw rw;
457 struct io_async_msghdr msg;
458 struct io_async_connect connect;
459 struct io_timeout_data timeout;
464 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
465 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
466 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
467 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
468 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
475 REQ_F_IOPOLL_COMPLETED_BIT,
476 REQ_F_LINK_TIMEOUT_BIT,
480 REQ_F_TIMEOUT_NOSEQ_BIT,
481 REQ_F_COMP_LOCKED_BIT,
482 REQ_F_NEED_CLEANUP_BIT,
487 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
488 /* drain existing IO first */
489 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
491 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
492 /* doesn't sever on completion < 0 */
493 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
495 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
497 /* already grabbed next link */
498 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
499 /* fail rest of links */
500 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
501 /* on inflight list */
502 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
503 /* read/write uses file position */
504 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
505 /* must not punt to workers */
506 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
507 /* polled IO has completed */
508 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
509 /* has linked timeout */
510 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
511 /* timeout request */
512 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
514 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
515 /* must be punted even for NONBLOCK */
516 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
517 /* no timeout sequence */
518 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
519 /* completion under lock */
520 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
522 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
526 * NOTE! Each of the iocb union members has the file pointer
527 * as the first entry in their struct definition. So you can
528 * access the file pointer through any of the sub-structs,
529 * or directly as just 'ki_filp' in this struct.
535 struct io_poll_iocb poll;
536 struct io_accept accept;
538 struct io_cancel cancel;
539 struct io_timeout timeout;
540 struct io_connect connect;
541 struct io_sr_msg sr_msg;
543 struct io_close close;
544 struct io_files_update files_update;
545 struct io_fadvise fadvise;
546 struct io_madvise madvise;
547 struct io_epoll epoll;
550 struct io_async_ctx *io;
552 * llist_node is only used for poll deferred completions
554 struct llist_node llist_node;
556 bool needs_fixed_file;
559 struct io_ring_ctx *ctx;
561 struct list_head list;
562 struct hlist_node hash_node;
564 struct list_head link_list;
571 struct list_head inflight_entry;
573 struct io_wq_work work;
576 #define IO_PLUG_THRESHOLD 2
577 #define IO_IOPOLL_BATCH 8
579 struct io_submit_state {
580 struct blk_plug plug;
583 * io_kiocb alloc cache
585 void *reqs[IO_IOPOLL_BATCH];
586 unsigned int free_reqs;
589 * File reference cache
593 unsigned int has_refs;
594 unsigned int used_refs;
595 unsigned int ios_left;
599 /* needs req->io allocated for deferral/async */
600 unsigned async_ctx : 1;
601 /* needs current->mm setup, does mm access */
602 unsigned needs_mm : 1;
603 /* needs req->file assigned */
604 unsigned needs_file : 1;
605 /* needs req->file assigned IFF fd is >= 0 */
606 unsigned fd_non_neg : 1;
607 /* hash wq insertion if file is a regular file */
608 unsigned hash_reg_file : 1;
609 /* unbound wq insertion if file is a non-regular file */
610 unsigned unbound_nonreg_file : 1;
611 /* opcode is not supported by this kernel */
612 unsigned not_supported : 1;
613 /* needs file table */
614 unsigned file_table : 1;
616 unsigned needs_fs : 1;
619 static const struct io_op_def io_op_defs[] = {
620 [IORING_OP_NOP] = {},
621 [IORING_OP_READV] = {
625 .unbound_nonreg_file = 1,
627 [IORING_OP_WRITEV] = {
632 .unbound_nonreg_file = 1,
634 [IORING_OP_FSYNC] = {
637 [IORING_OP_READ_FIXED] = {
639 .unbound_nonreg_file = 1,
641 [IORING_OP_WRITE_FIXED] = {
644 .unbound_nonreg_file = 1,
646 [IORING_OP_POLL_ADD] = {
648 .unbound_nonreg_file = 1,
650 [IORING_OP_POLL_REMOVE] = {},
651 [IORING_OP_SYNC_FILE_RANGE] = {
654 [IORING_OP_SENDMSG] = {
658 .unbound_nonreg_file = 1,
661 [IORING_OP_RECVMSG] = {
665 .unbound_nonreg_file = 1,
668 [IORING_OP_TIMEOUT] = {
672 [IORING_OP_TIMEOUT_REMOVE] = {},
673 [IORING_OP_ACCEPT] = {
676 .unbound_nonreg_file = 1,
679 [IORING_OP_ASYNC_CANCEL] = {},
680 [IORING_OP_LINK_TIMEOUT] = {
684 [IORING_OP_CONNECT] = {
688 .unbound_nonreg_file = 1,
690 [IORING_OP_FALLOCATE] = {
693 [IORING_OP_OPENAT] = {
699 [IORING_OP_CLOSE] = {
703 [IORING_OP_FILES_UPDATE] = {
707 [IORING_OP_STATX] = {
716 .unbound_nonreg_file = 1,
718 [IORING_OP_WRITE] = {
721 .unbound_nonreg_file = 1,
723 [IORING_OP_FADVISE] = {
726 [IORING_OP_MADVISE] = {
732 .unbound_nonreg_file = 1,
737 .unbound_nonreg_file = 1,
739 [IORING_OP_OPENAT2] = {
745 [IORING_OP_EPOLL_CTL] = {
746 .unbound_nonreg_file = 1,
751 static void io_wq_submit_work(struct io_wq_work **workptr);
752 static void io_cqring_fill_event(struct io_kiocb *req, long res);
753 static void io_put_req(struct io_kiocb *req);
754 static void __io_double_put_req(struct io_kiocb *req);
755 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
756 static void io_queue_linked_timeout(struct io_kiocb *req);
757 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
758 struct io_uring_files_update *ip,
760 static int io_grab_files(struct io_kiocb *req);
761 static void io_ring_file_ref_flush(struct fixed_file_data *data);
762 static void io_cleanup_req(struct io_kiocb *req);
764 static struct kmem_cache *req_cachep;
766 static const struct file_operations io_uring_fops;
768 struct sock *io_uring_get_socket(struct file *file)
770 #if defined(CONFIG_UNIX)
771 if (file->f_op == &io_uring_fops) {
772 struct io_ring_ctx *ctx = file->private_data;
774 return ctx->ring_sock->sk;
779 EXPORT_SYMBOL(io_uring_get_socket);
781 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
783 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
785 complete(&ctx->completions[0]);
788 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
790 struct io_ring_ctx *ctx;
793 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
797 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
798 if (!ctx->fallback_req)
801 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
802 if (!ctx->completions)
806 * Use 5 bits less than the max cq entries, that should give us around
807 * 32 entries per hash list if totally full and uniformly spread.
809 hash_bits = ilog2(p->cq_entries);
813 ctx->cancel_hash_bits = hash_bits;
814 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
816 if (!ctx->cancel_hash)
818 __hash_init(ctx->cancel_hash, 1U << hash_bits);
820 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
821 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
824 ctx->flags = p->flags;
825 init_waitqueue_head(&ctx->cq_wait);
826 INIT_LIST_HEAD(&ctx->cq_overflow_list);
827 init_completion(&ctx->completions[0]);
828 init_completion(&ctx->completions[1]);
829 idr_init(&ctx->personality_idr);
830 mutex_init(&ctx->uring_lock);
831 init_waitqueue_head(&ctx->wait);
832 spin_lock_init(&ctx->completion_lock);
833 init_llist_head(&ctx->poll_llist);
834 INIT_LIST_HEAD(&ctx->poll_list);
835 INIT_LIST_HEAD(&ctx->defer_list);
836 INIT_LIST_HEAD(&ctx->timeout_list);
837 init_waitqueue_head(&ctx->inflight_wait);
838 spin_lock_init(&ctx->inflight_lock);
839 INIT_LIST_HEAD(&ctx->inflight_list);
842 if (ctx->fallback_req)
843 kmem_cache_free(req_cachep, ctx->fallback_req);
844 kfree(ctx->completions);
845 kfree(ctx->cancel_hash);
850 static inline bool __req_need_defer(struct io_kiocb *req)
852 struct io_ring_ctx *ctx = req->ctx;
854 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
855 + atomic_read(&ctx->cached_cq_overflow);
858 static inline bool req_need_defer(struct io_kiocb *req)
860 if (unlikely(req->flags & REQ_F_IO_DRAIN))
861 return __req_need_defer(req);
866 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
868 struct io_kiocb *req;
870 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
871 if (req && !req_need_defer(req)) {
872 list_del_init(&req->list);
879 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
881 struct io_kiocb *req;
883 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
885 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
887 if (!__req_need_defer(req)) {
888 list_del_init(&req->list);
896 static void __io_commit_cqring(struct io_ring_ctx *ctx)
898 struct io_rings *rings = ctx->rings;
900 /* order cqe stores with ring update */
901 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
903 if (wq_has_sleeper(&ctx->cq_wait)) {
904 wake_up_interruptible(&ctx->cq_wait);
905 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
909 static inline void io_req_work_grab_env(struct io_kiocb *req,
910 const struct io_op_def *def)
912 if (!req->work.mm && def->needs_mm) {
914 req->work.mm = current->mm;
916 if (!req->work.creds)
917 req->work.creds = get_current_cred();
918 if (!req->work.fs && def->needs_fs) {
919 spin_lock(¤t->fs->lock);
920 if (!current->fs->in_exec) {
921 req->work.fs = current->fs;
922 req->work.fs->users++;
924 req->work.flags |= IO_WQ_WORK_CANCEL;
926 spin_unlock(¤t->fs->lock);
930 static inline void io_req_work_drop_env(struct io_kiocb *req)
933 mmdrop(req->work.mm);
936 if (req->work.creds) {
937 put_cred(req->work.creds);
938 req->work.creds = NULL;
941 struct fs_struct *fs = req->work.fs;
943 spin_lock(&req->work.fs->lock);
946 spin_unlock(&req->work.fs->lock);
952 static inline bool io_prep_async_work(struct io_kiocb *req,
953 struct io_kiocb **link)
955 const struct io_op_def *def = &io_op_defs[req->opcode];
956 bool do_hashed = false;
958 if (req->flags & REQ_F_ISREG) {
959 if (def->hash_reg_file)
962 if (def->unbound_nonreg_file)
963 req->work.flags |= IO_WQ_WORK_UNBOUND;
966 io_req_work_grab_env(req, def);
968 *link = io_prep_linked_timeout(req);
972 static inline void io_queue_async_work(struct io_kiocb *req)
974 struct io_ring_ctx *ctx = req->ctx;
975 struct io_kiocb *link;
978 do_hashed = io_prep_async_work(req, &link);
980 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
983 io_wq_enqueue(ctx->io_wq, &req->work);
985 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
986 file_inode(req->file));
990 io_queue_linked_timeout(link);
993 static void io_kill_timeout(struct io_kiocb *req)
997 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
999 atomic_inc(&req->ctx->cq_timeouts);
1000 list_del_init(&req->list);
1001 io_cqring_fill_event(req, 0);
1006 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1008 struct io_kiocb *req, *tmp;
1010 spin_lock_irq(&ctx->completion_lock);
1011 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1012 io_kill_timeout(req);
1013 spin_unlock_irq(&ctx->completion_lock);
1016 static void io_commit_cqring(struct io_ring_ctx *ctx)
1018 struct io_kiocb *req;
1020 while ((req = io_get_timeout_req(ctx)) != NULL)
1021 io_kill_timeout(req);
1023 __io_commit_cqring(ctx);
1025 while ((req = io_get_deferred_req(ctx)) != NULL)
1026 io_queue_async_work(req);
1029 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1031 struct io_rings *rings = ctx->rings;
1034 tail = ctx->cached_cq_tail;
1036 * writes to the cq entry need to come after reading head; the
1037 * control dependency is enough as we're using WRITE_ONCE to
1040 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1043 ctx->cached_cq_tail++;
1044 return &rings->cqes[tail & ctx->cq_mask];
1047 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1051 if (!ctx->eventfd_async)
1053 return io_wq_current_is_worker() || in_interrupt();
1056 static void __io_cqring_ev_posted(struct io_ring_ctx *ctx, bool trigger_ev)
1058 if (waitqueue_active(&ctx->wait))
1059 wake_up(&ctx->wait);
1060 if (waitqueue_active(&ctx->sqo_wait))
1061 wake_up(&ctx->sqo_wait);
1063 eventfd_signal(ctx->cq_ev_fd, 1);
1066 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1068 __io_cqring_ev_posted(ctx, io_should_trigger_evfd(ctx));
1071 /* Returns true if there are no backlogged entries after the flush */
1072 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1074 struct io_rings *rings = ctx->rings;
1075 struct io_uring_cqe *cqe;
1076 struct io_kiocb *req;
1077 unsigned long flags;
1081 if (list_empty_careful(&ctx->cq_overflow_list))
1083 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1084 rings->cq_ring_entries))
1088 spin_lock_irqsave(&ctx->completion_lock, flags);
1090 /* if force is set, the ring is going away. always drop after that */
1092 ctx->cq_overflow_flushed = 1;
1095 while (!list_empty(&ctx->cq_overflow_list)) {
1096 cqe = io_get_cqring(ctx);
1100 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1102 list_move(&req->list, &list);
1104 WRITE_ONCE(cqe->user_data, req->user_data);
1105 WRITE_ONCE(cqe->res, req->result);
1106 WRITE_ONCE(cqe->flags, 0);
1108 WRITE_ONCE(ctx->rings->cq_overflow,
1109 atomic_inc_return(&ctx->cached_cq_overflow));
1113 io_commit_cqring(ctx);
1115 clear_bit(0, &ctx->sq_check_overflow);
1116 clear_bit(0, &ctx->cq_check_overflow);
1118 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1119 io_cqring_ev_posted(ctx);
1121 while (!list_empty(&list)) {
1122 req = list_first_entry(&list, struct io_kiocb, list);
1123 list_del(&req->list);
1130 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1132 struct io_ring_ctx *ctx = req->ctx;
1133 struct io_uring_cqe *cqe;
1135 trace_io_uring_complete(ctx, req->user_data, res);
1138 * If we can't get a cq entry, userspace overflowed the
1139 * submission (by quite a lot). Increment the overflow count in
1142 cqe = io_get_cqring(ctx);
1144 WRITE_ONCE(cqe->user_data, req->user_data);
1145 WRITE_ONCE(cqe->res, res);
1146 WRITE_ONCE(cqe->flags, 0);
1147 } else if (ctx->cq_overflow_flushed) {
1148 WRITE_ONCE(ctx->rings->cq_overflow,
1149 atomic_inc_return(&ctx->cached_cq_overflow));
1151 if (list_empty(&ctx->cq_overflow_list)) {
1152 set_bit(0, &ctx->sq_check_overflow);
1153 set_bit(0, &ctx->cq_check_overflow);
1155 refcount_inc(&req->refs);
1157 list_add_tail(&req->list, &ctx->cq_overflow_list);
1161 static void io_cqring_add_event(struct io_kiocb *req, long res)
1163 struct io_ring_ctx *ctx = req->ctx;
1164 unsigned long flags;
1166 spin_lock_irqsave(&ctx->completion_lock, flags);
1167 io_cqring_fill_event(req, res);
1168 io_commit_cqring(ctx);
1169 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1171 io_cqring_ev_posted(ctx);
1174 static inline bool io_is_fallback_req(struct io_kiocb *req)
1176 return req == (struct io_kiocb *)
1177 ((unsigned long) req->ctx->fallback_req & ~1UL);
1180 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1182 struct io_kiocb *req;
1184 req = ctx->fallback_req;
1185 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1191 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1192 struct io_submit_state *state)
1194 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1195 struct io_kiocb *req;
1198 req = kmem_cache_alloc(req_cachep, gfp);
1201 } else if (!state->free_reqs) {
1205 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1206 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1209 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1210 * retry single alloc to be on the safe side.
1212 if (unlikely(ret <= 0)) {
1213 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1214 if (!state->reqs[0])
1218 state->free_reqs = ret - 1;
1219 req = state->reqs[ret - 1];
1222 req = state->reqs[state->free_reqs];
1230 /* one is dropped after submission, the other at completion */
1231 refcount_set(&req->refs, 2);
1233 INIT_IO_WORK(&req->work, io_wq_submit_work);
1236 req = io_get_fallback_req(ctx);
1239 percpu_ref_put(&ctx->refs);
1243 static void __io_req_do_free(struct io_kiocb *req)
1245 if (likely(!io_is_fallback_req(req)))
1246 kmem_cache_free(req_cachep, req);
1248 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1251 static void __io_req_aux_free(struct io_kiocb *req)
1253 struct io_ring_ctx *ctx = req->ctx;
1257 if (req->flags & REQ_F_FIXED_FILE)
1258 percpu_ref_put(&ctx->file_data->refs);
1263 io_req_work_drop_env(req);
1266 static void __io_free_req(struct io_kiocb *req)
1268 __io_req_aux_free(req);
1270 if (req->flags & REQ_F_NEED_CLEANUP)
1271 io_cleanup_req(req);
1273 if (req->flags & REQ_F_INFLIGHT) {
1274 struct io_ring_ctx *ctx = req->ctx;
1275 unsigned long flags;
1277 spin_lock_irqsave(&ctx->inflight_lock, flags);
1278 list_del(&req->inflight_entry);
1279 if (waitqueue_active(&ctx->inflight_wait))
1280 wake_up(&ctx->inflight_wait);
1281 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1284 percpu_ref_put(&req->ctx->refs);
1285 __io_req_do_free(req);
1289 void *reqs[IO_IOPOLL_BATCH];
1294 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1296 int fixed_refs = rb->to_free;
1300 if (rb->need_iter) {
1301 int i, inflight = 0;
1302 unsigned long flags;
1305 for (i = 0; i < rb->to_free; i++) {
1306 struct io_kiocb *req = rb->reqs[i];
1308 if (req->flags & REQ_F_FIXED_FILE) {
1312 if (req->flags & REQ_F_INFLIGHT)
1314 __io_req_aux_free(req);
1319 spin_lock_irqsave(&ctx->inflight_lock, flags);
1320 for (i = 0; i < rb->to_free; i++) {
1321 struct io_kiocb *req = rb->reqs[i];
1323 if (req->flags & REQ_F_INFLIGHT) {
1324 list_del(&req->inflight_entry);
1329 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1331 if (waitqueue_active(&ctx->inflight_wait))
1332 wake_up(&ctx->inflight_wait);
1335 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1337 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1338 percpu_ref_put_many(&ctx->refs, rb->to_free);
1339 rb->to_free = rb->need_iter = 0;
1342 static bool io_link_cancel_timeout(struct io_kiocb *req)
1344 struct io_ring_ctx *ctx = req->ctx;
1347 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1349 io_cqring_fill_event(req, -ECANCELED);
1350 io_commit_cqring(ctx);
1351 req->flags &= ~REQ_F_LINK;
1359 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1361 struct io_ring_ctx *ctx = req->ctx;
1362 bool wake_ev = false;
1364 /* Already got next link */
1365 if (req->flags & REQ_F_LINK_NEXT)
1369 * The list should never be empty when we are called here. But could
1370 * potentially happen if the chain is messed up, check to be on the
1373 while (!list_empty(&req->link_list)) {
1374 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1375 struct io_kiocb, link_list);
1377 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1378 (nxt->flags & REQ_F_TIMEOUT))) {
1379 list_del_init(&nxt->link_list);
1380 wake_ev |= io_link_cancel_timeout(nxt);
1381 req->flags &= ~REQ_F_LINK_TIMEOUT;
1385 list_del_init(&req->link_list);
1386 if (!list_empty(&nxt->link_list))
1387 nxt->flags |= REQ_F_LINK;
1392 req->flags |= REQ_F_LINK_NEXT;
1394 io_cqring_ev_posted(ctx);
1398 * Called if REQ_F_LINK is set, and we fail the head request
1400 static void io_fail_links(struct io_kiocb *req)
1402 struct io_ring_ctx *ctx = req->ctx;
1403 unsigned long flags;
1405 spin_lock_irqsave(&ctx->completion_lock, flags);
1407 while (!list_empty(&req->link_list)) {
1408 struct io_kiocb *link = list_first_entry(&req->link_list,
1409 struct io_kiocb, link_list);
1411 list_del_init(&link->link_list);
1412 trace_io_uring_fail_link(req, link);
1414 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1415 link->opcode == IORING_OP_LINK_TIMEOUT) {
1416 io_link_cancel_timeout(link);
1418 io_cqring_fill_event(link, -ECANCELED);
1419 __io_double_put_req(link);
1421 req->flags &= ~REQ_F_LINK_TIMEOUT;
1424 io_commit_cqring(ctx);
1425 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1426 io_cqring_ev_posted(ctx);
1429 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1431 if (likely(!(req->flags & REQ_F_LINK)))
1435 * If LINK is set, we have dependent requests in this chain. If we
1436 * didn't fail this request, queue the first one up, moving any other
1437 * dependencies to the next request. In case of failure, fail the rest
1440 if (req->flags & REQ_F_FAIL_LINK) {
1442 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1443 REQ_F_LINK_TIMEOUT) {
1444 struct io_ring_ctx *ctx = req->ctx;
1445 unsigned long flags;
1448 * If this is a timeout link, we could be racing with the
1449 * timeout timer. Grab the completion lock for this case to
1450 * protect against that.
1452 spin_lock_irqsave(&ctx->completion_lock, flags);
1453 io_req_link_next(req, nxt);
1454 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1456 io_req_link_next(req, nxt);
1460 static void io_free_req(struct io_kiocb *req)
1462 struct io_kiocb *nxt = NULL;
1464 io_req_find_next(req, &nxt);
1468 io_queue_async_work(nxt);
1472 * Drop reference to request, return next in chain (if there is one) if this
1473 * was the last reference to this request.
1475 __attribute__((nonnull))
1476 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1478 io_req_find_next(req, nxtptr);
1480 if (refcount_dec_and_test(&req->refs))
1484 static void io_put_req(struct io_kiocb *req)
1486 if (refcount_dec_and_test(&req->refs))
1491 * Must only be used if we don't need to care about links, usually from
1492 * within the completion handling itself.
1494 static void __io_double_put_req(struct io_kiocb *req)
1496 /* drop both submit and complete references */
1497 if (refcount_sub_and_test(2, &req->refs))
1501 static void io_double_put_req(struct io_kiocb *req)
1503 /* drop both submit and complete references */
1504 if (refcount_sub_and_test(2, &req->refs))
1508 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1510 struct io_rings *rings = ctx->rings;
1512 if (test_bit(0, &ctx->cq_check_overflow)) {
1514 * noflush == true is from the waitqueue handler, just ensure
1515 * we wake up the task, and the next invocation will flush the
1516 * entries. We cannot safely to it from here.
1518 if (noflush && !list_empty(&ctx->cq_overflow_list))
1521 io_cqring_overflow_flush(ctx, false);
1524 /* See comment at the top of this file */
1526 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1529 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1531 struct io_rings *rings = ctx->rings;
1533 /* make sure SQ entry isn't read before tail */
1534 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1537 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1539 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1542 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1545 rb->reqs[rb->to_free++] = req;
1546 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1547 io_free_req_many(req->ctx, rb);
1552 * Find and free completed poll iocbs
1554 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1555 struct list_head *done)
1557 struct req_batch rb;
1558 struct io_kiocb *req;
1560 rb.to_free = rb.need_iter = 0;
1561 while (!list_empty(done)) {
1562 req = list_first_entry(done, struct io_kiocb, list);
1563 list_del(&req->list);
1565 io_cqring_fill_event(req, req->result);
1568 if (refcount_dec_and_test(&req->refs) &&
1569 !io_req_multi_free(&rb, req))
1573 io_commit_cqring(ctx);
1574 io_free_req_many(ctx, &rb);
1577 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1580 struct io_kiocb *req, *tmp;
1586 * Only spin for completions if we don't have multiple devices hanging
1587 * off our complete list, and we're under the requested amount.
1589 spin = !ctx->poll_multi_file && *nr_events < min;
1592 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1593 struct kiocb *kiocb = &req->rw.kiocb;
1596 * Move completed entries to our local list. If we find a
1597 * request that requires polling, break out and complete
1598 * the done list first, if we have entries there.
1600 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1601 list_move_tail(&req->list, &done);
1604 if (!list_empty(&done))
1607 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1616 if (!list_empty(&done))
1617 io_iopoll_complete(ctx, nr_events, &done);
1623 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1624 * non-spinning poll check - we'll still enter the driver poll loop, but only
1625 * as a non-spinning completion check.
1627 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1630 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1633 ret = io_do_iopoll(ctx, nr_events, min);
1636 if (!min || *nr_events >= min)
1644 * We can't just wait for polled events to come to us, we have to actively
1645 * find and complete them.
1647 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1649 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1652 mutex_lock(&ctx->uring_lock);
1653 while (!list_empty(&ctx->poll_list)) {
1654 unsigned int nr_events = 0;
1656 io_iopoll_getevents(ctx, &nr_events, 1);
1659 * Ensure we allow local-to-the-cpu processing to take place,
1660 * in this case we need to ensure that we reap all events.
1664 mutex_unlock(&ctx->uring_lock);
1667 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1670 int iters = 0, ret = 0;
1676 * Don't enter poll loop if we already have events pending.
1677 * If we do, we can potentially be spinning for commands that
1678 * already triggered a CQE (eg in error).
1680 if (io_cqring_events(ctx, false))
1684 * If a submit got punted to a workqueue, we can have the
1685 * application entering polling for a command before it gets
1686 * issued. That app will hold the uring_lock for the duration
1687 * of the poll right here, so we need to take a breather every
1688 * now and then to ensure that the issue has a chance to add
1689 * the poll to the issued list. Otherwise we can spin here
1690 * forever, while the workqueue is stuck trying to acquire the
1693 if (!(++iters & 7)) {
1694 mutex_unlock(&ctx->uring_lock);
1695 mutex_lock(&ctx->uring_lock);
1698 if (*nr_events < min)
1699 tmin = min - *nr_events;
1701 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1705 } while (min && !*nr_events && !need_resched());
1710 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1716 * We disallow the app entering submit/complete with polling, but we
1717 * still need to lock the ring to prevent racing with polled issue
1718 * that got punted to a workqueue.
1720 mutex_lock(&ctx->uring_lock);
1721 ret = __io_iopoll_check(ctx, nr_events, min);
1722 mutex_unlock(&ctx->uring_lock);
1726 static void kiocb_end_write(struct io_kiocb *req)
1729 * Tell lockdep we inherited freeze protection from submission
1732 if (req->flags & REQ_F_ISREG) {
1733 struct inode *inode = file_inode(req->file);
1735 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1737 file_end_write(req->file);
1740 static inline void req_set_fail_links(struct io_kiocb *req)
1742 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1743 req->flags |= REQ_F_FAIL_LINK;
1746 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1748 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1750 if (kiocb->ki_flags & IOCB_WRITE)
1751 kiocb_end_write(req);
1753 if (res != req->result)
1754 req_set_fail_links(req);
1755 io_cqring_add_event(req, res);
1758 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1760 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1762 io_complete_rw_common(kiocb, res);
1766 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1768 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1769 struct io_kiocb *nxt = NULL;
1771 io_complete_rw_common(kiocb, res);
1772 io_put_req_find_next(req, &nxt);
1777 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1779 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1781 if (kiocb->ki_flags & IOCB_WRITE)
1782 kiocb_end_write(req);
1784 if (res != req->result)
1785 req_set_fail_links(req);
1788 req->flags |= REQ_F_IOPOLL_COMPLETED;
1792 * After the iocb has been issued, it's safe to be found on the poll list.
1793 * Adding the kiocb to the list AFTER submission ensures that we don't
1794 * find it from a io_iopoll_getevents() thread before the issuer is done
1795 * accessing the kiocb cookie.
1797 static void io_iopoll_req_issued(struct io_kiocb *req)
1799 struct io_ring_ctx *ctx = req->ctx;
1802 * Track whether we have multiple files in our lists. This will impact
1803 * how we do polling eventually, not spinning if we're on potentially
1804 * different devices.
1806 if (list_empty(&ctx->poll_list)) {
1807 ctx->poll_multi_file = false;
1808 } else if (!ctx->poll_multi_file) {
1809 struct io_kiocb *list_req;
1811 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1813 if (list_req->file != req->file)
1814 ctx->poll_multi_file = true;
1818 * For fast devices, IO may have already completed. If it has, add
1819 * it to the front so we find it first.
1821 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1822 list_add(&req->list, &ctx->poll_list);
1824 list_add_tail(&req->list, &ctx->poll_list);
1827 static void io_file_put(struct io_submit_state *state)
1830 int diff = state->has_refs - state->used_refs;
1833 fput_many(state->file, diff);
1839 * Get as many references to a file as we have IOs left in this submission,
1840 * assuming most submissions are for one file, or at least that each file
1841 * has more than one submission.
1843 static struct file *io_file_get(struct io_submit_state *state, int fd)
1849 if (state->fd == fd) {
1856 state->file = fget_many(fd, state->ios_left);
1861 state->has_refs = state->ios_left;
1862 state->used_refs = 1;
1868 * If we tracked the file through the SCM inflight mechanism, we could support
1869 * any file. For now, just ensure that anything potentially problematic is done
1872 static bool io_file_supports_async(struct file *file)
1874 umode_t mode = file_inode(file)->i_mode;
1876 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1878 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1884 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1885 bool force_nonblock)
1887 struct io_ring_ctx *ctx = req->ctx;
1888 struct kiocb *kiocb = &req->rw.kiocb;
1892 if (S_ISREG(file_inode(req->file)->i_mode))
1893 req->flags |= REQ_F_ISREG;
1895 kiocb->ki_pos = READ_ONCE(sqe->off);
1896 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1897 req->flags |= REQ_F_CUR_POS;
1898 kiocb->ki_pos = req->file->f_pos;
1900 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1901 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1902 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1906 ioprio = READ_ONCE(sqe->ioprio);
1908 ret = ioprio_check_cap(ioprio);
1912 kiocb->ki_ioprio = ioprio;
1914 kiocb->ki_ioprio = get_current_ioprio();
1916 /* don't allow async punt if RWF_NOWAIT was requested */
1917 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1918 (req->file->f_flags & O_NONBLOCK))
1919 req->flags |= REQ_F_NOWAIT;
1922 kiocb->ki_flags |= IOCB_NOWAIT;
1924 if (ctx->flags & IORING_SETUP_IOPOLL) {
1925 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1926 !kiocb->ki_filp->f_op->iopoll)
1929 kiocb->ki_flags |= IOCB_HIPRI;
1930 kiocb->ki_complete = io_complete_rw_iopoll;
1933 if (kiocb->ki_flags & IOCB_HIPRI)
1935 kiocb->ki_complete = io_complete_rw;
1938 req->rw.addr = READ_ONCE(sqe->addr);
1939 req->rw.len = READ_ONCE(sqe->len);
1940 /* we own ->private, reuse it for the buffer index */
1941 req->rw.kiocb.private = (void *) (unsigned long)
1942 READ_ONCE(sqe->buf_index);
1946 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1952 case -ERESTARTNOINTR:
1953 case -ERESTARTNOHAND:
1954 case -ERESTART_RESTARTBLOCK:
1956 * We can't just restart the syscall, since previously
1957 * submitted sqes may already be in progress. Just fail this
1963 kiocb->ki_complete(kiocb, ret, 0);
1967 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1970 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1972 if (req->flags & REQ_F_CUR_POS)
1973 req->file->f_pos = kiocb->ki_pos;
1974 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1975 *nxt = __io_complete_rw(kiocb, ret);
1977 io_rw_done(kiocb, ret);
1980 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1981 struct iov_iter *iter)
1983 struct io_ring_ctx *ctx = req->ctx;
1984 size_t len = req->rw.len;
1985 struct io_mapped_ubuf *imu;
1986 unsigned index, buf_index;
1990 /* attempt to use fixed buffers without having provided iovecs */
1991 if (unlikely(!ctx->user_bufs))
1994 buf_index = (unsigned long) req->rw.kiocb.private;
1995 if (unlikely(buf_index >= ctx->nr_user_bufs))
1998 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1999 imu = &ctx->user_bufs[index];
2000 buf_addr = req->rw.addr;
2003 if (buf_addr + len < buf_addr)
2005 /* not inside the mapped region */
2006 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2010 * May not be a start of buffer, set size appropriately
2011 * and advance us to the beginning.
2013 offset = buf_addr - imu->ubuf;
2014 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2018 * Don't use iov_iter_advance() here, as it's really slow for
2019 * using the latter parts of a big fixed buffer - it iterates
2020 * over each segment manually. We can cheat a bit here, because
2023 * 1) it's a BVEC iter, we set it up
2024 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2025 * first and last bvec
2027 * So just find our index, and adjust the iterator afterwards.
2028 * If the offset is within the first bvec (or the whole first
2029 * bvec, just use iov_iter_advance(). This makes it easier
2030 * since we can just skip the first segment, which may not
2031 * be PAGE_SIZE aligned.
2033 const struct bio_vec *bvec = imu->bvec;
2035 if (offset <= bvec->bv_len) {
2036 iov_iter_advance(iter, offset);
2038 unsigned long seg_skip;
2040 /* skip first vec */
2041 offset -= bvec->bv_len;
2042 seg_skip = 1 + (offset >> PAGE_SHIFT);
2044 iter->bvec = bvec + seg_skip;
2045 iter->nr_segs -= seg_skip;
2046 iter->count -= bvec->bv_len + offset;
2047 iter->iov_offset = offset & ~PAGE_MASK;
2054 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2055 struct iovec **iovec, struct iov_iter *iter)
2057 void __user *buf = u64_to_user_ptr(req->rw.addr);
2058 size_t sqe_len = req->rw.len;
2061 opcode = req->opcode;
2062 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2064 return io_import_fixed(req, rw, iter);
2067 /* buffer index only valid with fixed read/write */
2068 if (req->rw.kiocb.private)
2071 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2073 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2079 struct io_async_rw *iorw = &req->io->rw;
2082 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2083 if (iorw->iov == iorw->fast_iov)
2088 #ifdef CONFIG_COMPAT
2089 if (req->ctx->compat)
2090 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2094 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2098 * For files that don't have ->read_iter() and ->write_iter(), handle them
2099 * by looping over ->read() or ->write() manually.
2101 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2102 struct iov_iter *iter)
2107 * Don't support polled IO through this interface, and we can't
2108 * support non-blocking either. For the latter, this just causes
2109 * the kiocb to be handled from an async context.
2111 if (kiocb->ki_flags & IOCB_HIPRI)
2113 if (kiocb->ki_flags & IOCB_NOWAIT)
2116 while (iov_iter_count(iter)) {
2120 if (!iov_iter_is_bvec(iter)) {
2121 iovec = iov_iter_iovec(iter);
2123 /* fixed buffers import bvec */
2124 iovec.iov_base = kmap(iter->bvec->bv_page)
2126 iovec.iov_len = min(iter->count,
2127 iter->bvec->bv_len - iter->iov_offset);
2131 nr = file->f_op->read(file, iovec.iov_base,
2132 iovec.iov_len, &kiocb->ki_pos);
2134 nr = file->f_op->write(file, iovec.iov_base,
2135 iovec.iov_len, &kiocb->ki_pos);
2138 if (iov_iter_is_bvec(iter))
2139 kunmap(iter->bvec->bv_page);
2147 if (nr != iovec.iov_len)
2149 iov_iter_advance(iter, nr);
2155 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2156 struct iovec *iovec, struct iovec *fast_iov,
2157 struct iov_iter *iter)
2159 req->io->rw.nr_segs = iter->nr_segs;
2160 req->io->rw.size = io_size;
2161 req->io->rw.iov = iovec;
2162 if (!req->io->rw.iov) {
2163 req->io->rw.iov = req->io->rw.fast_iov;
2164 memcpy(req->io->rw.iov, fast_iov,
2165 sizeof(struct iovec) * iter->nr_segs);
2167 req->flags |= REQ_F_NEED_CLEANUP;
2171 static int io_alloc_async_ctx(struct io_kiocb *req)
2173 if (!io_op_defs[req->opcode].async_ctx)
2175 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2176 return req->io == NULL;
2179 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2180 struct iovec *iovec, struct iovec *fast_iov,
2181 struct iov_iter *iter)
2183 if (!io_op_defs[req->opcode].async_ctx)
2186 if (io_alloc_async_ctx(req))
2189 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2194 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2195 bool force_nonblock)
2197 struct io_async_ctx *io;
2198 struct iov_iter iter;
2201 ret = io_prep_rw(req, sqe, force_nonblock);
2205 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2212 io->rw.iov = io->rw.fast_iov;
2214 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2219 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2223 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2224 bool force_nonblock)
2226 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2227 struct kiocb *kiocb = &req->rw.kiocb;
2228 struct iov_iter iter;
2230 ssize_t io_size, ret;
2232 ret = io_import_iovec(READ, req, &iovec, &iter);
2236 /* Ensure we clear previously set non-block flag */
2237 if (!force_nonblock)
2238 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2242 if (req->flags & REQ_F_LINK)
2243 req->result = io_size;
2246 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2247 * we know to async punt it even if it was opened O_NONBLOCK
2249 if (force_nonblock && !io_file_supports_async(req->file)) {
2250 req->flags |= REQ_F_MUST_PUNT;
2254 iov_count = iov_iter_count(&iter);
2255 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2259 if (req->file->f_op->read_iter)
2260 ret2 = call_read_iter(req->file, kiocb, &iter);
2262 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2264 /* Catch -EAGAIN return for forced non-blocking submission */
2265 if (!force_nonblock || ret2 != -EAGAIN) {
2266 kiocb_done(kiocb, ret2, nxt, req->in_async);
2269 ret = io_setup_async_rw(req, io_size, iovec,
2270 inline_vecs, &iter);
2278 req->flags &= ~REQ_F_NEED_CLEANUP;
2282 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2283 bool force_nonblock)
2285 struct io_async_ctx *io;
2286 struct iov_iter iter;
2289 ret = io_prep_rw(req, sqe, force_nonblock);
2293 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2300 io->rw.iov = io->rw.fast_iov;
2302 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2307 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2311 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2312 bool force_nonblock)
2314 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2315 struct kiocb *kiocb = &req->rw.kiocb;
2316 struct iov_iter iter;
2318 ssize_t ret, io_size;
2320 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2324 /* Ensure we clear previously set non-block flag */
2325 if (!force_nonblock)
2326 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2330 if (req->flags & REQ_F_LINK)
2331 req->result = io_size;
2334 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2335 * we know to async punt it even if it was opened O_NONBLOCK
2337 if (force_nonblock && !io_file_supports_async(req->file)) {
2338 req->flags |= REQ_F_MUST_PUNT;
2342 /* file path doesn't support NOWAIT for non-direct_IO */
2343 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2344 (req->flags & REQ_F_ISREG))
2347 iov_count = iov_iter_count(&iter);
2348 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2353 * Open-code file_start_write here to grab freeze protection,
2354 * which will be released by another thread in
2355 * io_complete_rw(). Fool lockdep by telling it the lock got
2356 * released so that it doesn't complain about the held lock when
2357 * we return to userspace.
2359 if (req->flags & REQ_F_ISREG) {
2360 __sb_start_write(file_inode(req->file)->i_sb,
2361 SB_FREEZE_WRITE, true);
2362 __sb_writers_release(file_inode(req->file)->i_sb,
2365 kiocb->ki_flags |= IOCB_WRITE;
2367 if (req->file->f_op->write_iter)
2368 ret2 = call_write_iter(req->file, kiocb, &iter);
2370 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2372 * Raw bdev writes will -EOPNOTSUPP for IOCB_NOWAIT. Just
2373 * retry them without IOCB_NOWAIT.
2375 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2377 if (!force_nonblock || ret2 != -EAGAIN) {
2378 kiocb_done(kiocb, ret2, nxt, req->in_async);
2381 ret = io_setup_async_rw(req, io_size, iovec,
2382 inline_vecs, &iter);
2389 req->flags &= ~REQ_F_NEED_CLEANUP;
2395 * IORING_OP_NOP just posts a completion event, nothing else.
2397 static int io_nop(struct io_kiocb *req)
2399 struct io_ring_ctx *ctx = req->ctx;
2401 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2404 io_cqring_add_event(req, 0);
2409 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2411 struct io_ring_ctx *ctx = req->ctx;
2416 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2418 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2421 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2422 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2425 req->sync.off = READ_ONCE(sqe->off);
2426 req->sync.len = READ_ONCE(sqe->len);
2430 static bool io_req_cancelled(struct io_kiocb *req)
2432 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2433 req_set_fail_links(req);
2434 io_cqring_add_event(req, -ECANCELED);
2442 static void io_link_work_cb(struct io_wq_work **workptr)
2444 struct io_wq_work *work = *workptr;
2445 struct io_kiocb *link = work->data;
2447 io_queue_linked_timeout(link);
2448 work->func = io_wq_submit_work;
2451 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2453 struct io_kiocb *link;
2455 io_prep_async_work(nxt, &link);
2456 *workptr = &nxt->work;
2458 nxt->work.flags |= IO_WQ_WORK_CB;
2459 nxt->work.func = io_link_work_cb;
2460 nxt->work.data = link;
2464 static void io_fsync_finish(struct io_wq_work **workptr)
2466 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2467 loff_t end = req->sync.off + req->sync.len;
2468 struct io_kiocb *nxt = NULL;
2471 if (io_req_cancelled(req))
2474 ret = vfs_fsync_range(req->file, req->sync.off,
2475 end > 0 ? end : LLONG_MAX,
2476 req->sync.flags & IORING_FSYNC_DATASYNC);
2478 req_set_fail_links(req);
2479 io_cqring_add_event(req, ret);
2480 io_put_req_find_next(req, &nxt);
2482 io_wq_assign_next(workptr, nxt);
2485 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2486 bool force_nonblock)
2488 struct io_wq_work *work, *old_work;
2490 /* fsync always requires a blocking context */
2491 if (force_nonblock) {
2493 req->work.func = io_fsync_finish;
2497 work = old_work = &req->work;
2498 io_fsync_finish(&work);
2499 if (work && work != old_work)
2500 *nxt = container_of(work, struct io_kiocb, work);
2504 static void io_fallocate_finish(struct io_wq_work **workptr)
2506 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2507 struct io_kiocb *nxt = NULL;
2510 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2513 req_set_fail_links(req);
2514 io_cqring_add_event(req, ret);
2515 io_put_req_find_next(req, &nxt);
2517 io_wq_assign_next(workptr, nxt);
2520 static int io_fallocate_prep(struct io_kiocb *req,
2521 const struct io_uring_sqe *sqe)
2523 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2526 req->sync.off = READ_ONCE(sqe->off);
2527 req->sync.len = READ_ONCE(sqe->addr);
2528 req->sync.mode = READ_ONCE(sqe->len);
2532 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2533 bool force_nonblock)
2535 struct io_wq_work *work, *old_work;
2537 /* fallocate always requiring blocking context */
2538 if (force_nonblock) {
2540 req->work.func = io_fallocate_finish;
2544 work = old_work = &req->work;
2545 io_fallocate_finish(&work);
2546 if (work && work != old_work)
2547 *nxt = container_of(work, struct io_kiocb, work);
2552 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2554 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 req->open.how.mode = READ_ONCE(sqe->len);
2564 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2565 req->open.how.flags = READ_ONCE(sqe->open_flags);
2567 req->open.filename = getname(fname);
2568 if (IS_ERR(req->open.filename)) {
2569 ret = PTR_ERR(req->open.filename);
2570 req->open.filename = NULL;
2574 req->flags |= REQ_F_NEED_CLEANUP;
2578 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2580 struct open_how __user *how;
2581 const char __user *fname;
2585 if (sqe->ioprio || sqe->buf_index)
2587 if (sqe->flags & IOSQE_FIXED_FILE)
2590 req->open.dfd = READ_ONCE(sqe->fd);
2591 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2592 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2593 len = READ_ONCE(sqe->len);
2595 if (len < OPEN_HOW_SIZE_VER0)
2598 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2603 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2604 req->open.how.flags |= O_LARGEFILE;
2606 req->open.filename = getname(fname);
2607 if (IS_ERR(req->open.filename)) {
2608 ret = PTR_ERR(req->open.filename);
2609 req->open.filename = NULL;
2613 req->flags |= REQ_F_NEED_CLEANUP;
2617 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2618 bool force_nonblock)
2620 struct open_flags op;
2627 ret = build_open_flags(&req->open.how, &op);
2631 ret = get_unused_fd_flags(req->open.how.flags);
2635 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2638 ret = PTR_ERR(file);
2640 fsnotify_open(file);
2641 fd_install(ret, file);
2644 putname(req->open.filename);
2645 req->flags &= ~REQ_F_NEED_CLEANUP;
2647 req_set_fail_links(req);
2648 io_cqring_add_event(req, ret);
2649 io_put_req_find_next(req, nxt);
2653 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2654 bool force_nonblock)
2656 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2657 return io_openat2(req, nxt, force_nonblock);
2660 static int io_epoll_ctl_prep(struct io_kiocb *req,
2661 const struct io_uring_sqe *sqe)
2663 #if defined(CONFIG_EPOLL)
2664 if (sqe->ioprio || sqe->buf_index)
2667 req->epoll.epfd = READ_ONCE(sqe->fd);
2668 req->epoll.op = READ_ONCE(sqe->len);
2669 req->epoll.fd = READ_ONCE(sqe->off);
2671 if (ep_op_has_event(req->epoll.op)) {
2672 struct epoll_event __user *ev;
2674 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
2675 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
2685 static int io_epoll_ctl(struct io_kiocb *req, struct io_kiocb **nxt,
2686 bool force_nonblock)
2688 #if defined(CONFIG_EPOLL)
2689 struct io_epoll *ie = &req->epoll;
2692 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
2693 if (force_nonblock && ret == -EAGAIN)
2697 req_set_fail_links(req);
2698 io_cqring_add_event(req, ret);
2699 io_put_req_find_next(req, nxt);
2706 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2708 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2709 if (sqe->ioprio || sqe->buf_index || sqe->off)
2712 req->madvise.addr = READ_ONCE(sqe->addr);
2713 req->madvise.len = READ_ONCE(sqe->len);
2714 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2721 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2722 bool force_nonblock)
2724 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2725 struct io_madvise *ma = &req->madvise;
2731 ret = do_madvise(ma->addr, ma->len, ma->advice);
2733 req_set_fail_links(req);
2734 io_cqring_add_event(req, ret);
2735 io_put_req_find_next(req, nxt);
2742 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2744 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2747 req->fadvise.offset = READ_ONCE(sqe->off);
2748 req->fadvise.len = READ_ONCE(sqe->len);
2749 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2753 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2754 bool force_nonblock)
2756 struct io_fadvise *fa = &req->fadvise;
2759 if (force_nonblock) {
2760 switch (fa->advice) {
2761 case POSIX_FADV_NORMAL:
2762 case POSIX_FADV_RANDOM:
2763 case POSIX_FADV_SEQUENTIAL:
2770 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2772 req_set_fail_links(req);
2773 io_cqring_add_event(req, ret);
2774 io_put_req_find_next(req, nxt);
2778 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2780 const char __user *fname;
2781 unsigned lookup_flags;
2784 if (sqe->ioprio || sqe->buf_index)
2786 if (sqe->flags & IOSQE_FIXED_FILE)
2789 req->open.dfd = READ_ONCE(sqe->fd);
2790 req->open.mask = READ_ONCE(sqe->len);
2791 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2792 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2793 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2795 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2798 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2799 if (IS_ERR(req->open.filename)) {
2800 ret = PTR_ERR(req->open.filename);
2801 req->open.filename = NULL;
2805 req->flags |= REQ_F_NEED_CLEANUP;
2809 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2810 bool force_nonblock)
2812 struct io_open *ctx = &req->open;
2813 unsigned lookup_flags;
2821 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2825 /* filename_lookup() drops it, keep a reference */
2826 ctx->filename->refcnt++;
2828 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2833 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2835 if (retry_estale(ret, lookup_flags)) {
2836 lookup_flags |= LOOKUP_REVAL;
2840 ret = cp_statx(&stat, ctx->buffer);
2842 putname(ctx->filename);
2843 req->flags &= ~REQ_F_NEED_CLEANUP;
2845 req_set_fail_links(req);
2846 io_cqring_add_event(req, ret);
2847 io_put_req_find_next(req, nxt);
2851 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2854 * If we queue this for async, it must not be cancellable. That would
2855 * leave the 'file' in an undeterminate state.
2857 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2859 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2860 sqe->rw_flags || sqe->buf_index)
2862 if (sqe->flags & IOSQE_FIXED_FILE)
2865 req->close.fd = READ_ONCE(sqe->fd);
2866 if (req->file->f_op == &io_uring_fops ||
2867 req->close.fd == req->ctx->ring_fd)
2873 static void io_close_finish(struct io_wq_work **workptr)
2875 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2876 struct io_kiocb *nxt = NULL;
2878 /* Invoked with files, we need to do the close */
2879 if (req->work.files) {
2882 ret = filp_close(req->close.put_file, req->work.files);
2884 req_set_fail_links(req);
2885 io_cqring_add_event(req, ret);
2888 fput(req->close.put_file);
2890 io_put_req_find_next(req, &nxt);
2892 io_wq_assign_next(workptr, nxt);
2895 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2896 bool force_nonblock)
2900 req->close.put_file = NULL;
2901 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2905 /* if the file has a flush method, be safe and punt to async */
2906 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker())
2910 * No ->flush(), safely close from here and just punt the
2911 * fput() to async context.
2913 ret = filp_close(req->close.put_file, current->files);
2916 req_set_fail_links(req);
2917 io_cqring_add_event(req, ret);
2919 if (io_wq_current_is_worker()) {
2920 struct io_wq_work *old_work, *work;
2922 old_work = work = &req->work;
2923 io_close_finish(&work);
2924 if (work && work != old_work)
2925 *nxt = container_of(work, struct io_kiocb, work);
2930 req->work.func = io_close_finish;
2932 * Do manual async queue here to avoid grabbing files - we don't
2933 * need the files, and it'll cause io_close_finish() to close
2934 * the file again and cause a double CQE entry for this request
2936 io_queue_async_work(req);
2940 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2942 struct io_ring_ctx *ctx = req->ctx;
2947 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2949 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2952 req->sync.off = READ_ONCE(sqe->off);
2953 req->sync.len = READ_ONCE(sqe->len);
2954 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2958 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2960 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2961 struct io_kiocb *nxt = NULL;
2964 if (io_req_cancelled(req))
2967 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2970 req_set_fail_links(req);
2971 io_cqring_add_event(req, ret);
2972 io_put_req_find_next(req, &nxt);
2974 io_wq_assign_next(workptr, nxt);
2977 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2978 bool force_nonblock)
2980 struct io_wq_work *work, *old_work;
2982 /* sync_file_range always requires a blocking context */
2983 if (force_nonblock) {
2985 req->work.func = io_sync_file_range_finish;
2989 work = old_work = &req->work;
2990 io_sync_file_range_finish(&work);
2991 if (work && work != old_work)
2992 *nxt = container_of(work, struct io_kiocb, work);
2996 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2998 #if defined(CONFIG_NET)
2999 struct io_sr_msg *sr = &req->sr_msg;
3000 struct io_async_ctx *io = req->io;
3003 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3004 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3005 sr->len = READ_ONCE(sqe->len);
3007 if (!io || req->opcode == IORING_OP_SEND)
3010 io->msg.iov = io->msg.fast_iov;
3011 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3014 req->flags |= REQ_F_NEED_CLEANUP;
3021 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3022 bool force_nonblock)
3024 #if defined(CONFIG_NET)
3025 struct io_async_msghdr *kmsg = NULL;
3026 struct socket *sock;
3029 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3032 sock = sock_from_file(req->file, &ret);
3034 struct io_async_ctx io;
3035 struct sockaddr_storage addr;
3039 kmsg = &req->io->msg;
3040 kmsg->msg.msg_name = &addr;
3041 /* if iov is set, it's allocated already */
3043 kmsg->iov = kmsg->fast_iov;
3044 kmsg->msg.msg_iter.iov = kmsg->iov;
3046 struct io_sr_msg *sr = &req->sr_msg;
3049 kmsg->msg.msg_name = &addr;
3051 io.msg.iov = io.msg.fast_iov;
3052 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3053 sr->msg_flags, &io.msg.iov);
3058 flags = req->sr_msg.msg_flags;
3059 if (flags & MSG_DONTWAIT)
3060 req->flags |= REQ_F_NOWAIT;
3061 else if (force_nonblock)
3062 flags |= MSG_DONTWAIT;
3064 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3065 if (force_nonblock && ret == -EAGAIN) {
3068 if (io_alloc_async_ctx(req)) {
3069 if (kmsg && kmsg->iov != kmsg->fast_iov)
3073 req->flags |= REQ_F_NEED_CLEANUP;
3074 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3077 if (ret == -ERESTARTSYS)
3081 if (kmsg && kmsg->iov != kmsg->fast_iov)
3083 req->flags &= ~REQ_F_NEED_CLEANUP;
3084 io_cqring_add_event(req, ret);
3086 req_set_fail_links(req);
3087 io_put_req_find_next(req, nxt);
3094 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
3095 bool force_nonblock)
3097 #if defined(CONFIG_NET)
3098 struct socket *sock;
3101 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3104 sock = sock_from_file(req->file, &ret);
3106 struct io_sr_msg *sr = &req->sr_msg;
3111 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3116 msg.msg_name = NULL;
3117 msg.msg_control = NULL;
3118 msg.msg_controllen = 0;
3119 msg.msg_namelen = 0;
3121 flags = req->sr_msg.msg_flags;
3122 if (flags & MSG_DONTWAIT)
3123 req->flags |= REQ_F_NOWAIT;
3124 else if (force_nonblock)
3125 flags |= MSG_DONTWAIT;
3127 msg.msg_flags = flags;
3128 ret = sock_sendmsg(sock, &msg);
3129 if (force_nonblock && ret == -EAGAIN)
3131 if (ret == -ERESTARTSYS)
3135 io_cqring_add_event(req, ret);
3137 req_set_fail_links(req);
3138 io_put_req_find_next(req, nxt);
3145 static int io_recvmsg_prep(struct io_kiocb *req,
3146 const struct io_uring_sqe *sqe)
3148 #if defined(CONFIG_NET)
3149 struct io_sr_msg *sr = &req->sr_msg;
3150 struct io_async_ctx *io = req->io;
3153 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3154 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3155 sr->len = READ_ONCE(sqe->len);
3157 if (!io || req->opcode == IORING_OP_RECV)
3160 io->msg.iov = io->msg.fast_iov;
3161 ret = recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3162 &io->msg.uaddr, &io->msg.iov);
3164 req->flags |= REQ_F_NEED_CLEANUP;
3171 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3172 bool force_nonblock)
3174 #if defined(CONFIG_NET)
3175 struct io_async_msghdr *kmsg = NULL;
3176 struct socket *sock;
3179 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3182 sock = sock_from_file(req->file, &ret);
3184 struct io_async_ctx io;
3185 struct sockaddr_storage addr;
3189 kmsg = &req->io->msg;
3190 kmsg->msg.msg_name = &addr;
3191 /* if iov is set, it's allocated already */
3193 kmsg->iov = kmsg->fast_iov;
3194 kmsg->msg.msg_iter.iov = kmsg->iov;
3196 struct io_sr_msg *sr = &req->sr_msg;
3199 kmsg->msg.msg_name = &addr;
3201 io.msg.iov = io.msg.fast_iov;
3202 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3203 sr->msg_flags, &io.msg.uaddr,
3209 flags = req->sr_msg.msg_flags;
3210 if (flags & MSG_DONTWAIT)
3211 req->flags |= REQ_F_NOWAIT;
3212 else if (force_nonblock)
3213 flags |= MSG_DONTWAIT;
3215 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3216 kmsg->uaddr, flags);
3217 if (force_nonblock && ret == -EAGAIN) {
3220 if (io_alloc_async_ctx(req)) {
3221 if (kmsg && kmsg->iov != kmsg->fast_iov)
3225 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3226 req->flags |= REQ_F_NEED_CLEANUP;
3229 if (ret == -ERESTARTSYS)
3233 if (kmsg && kmsg->iov != kmsg->fast_iov)
3235 req->flags &= ~REQ_F_NEED_CLEANUP;
3236 io_cqring_add_event(req, ret);
3238 req_set_fail_links(req);
3239 io_put_req_find_next(req, nxt);
3246 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3247 bool force_nonblock)
3249 #if defined(CONFIG_NET)
3250 struct socket *sock;
3253 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3256 sock = sock_from_file(req->file, &ret);
3258 struct io_sr_msg *sr = &req->sr_msg;
3263 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3268 msg.msg_name = NULL;
3269 msg.msg_control = NULL;
3270 msg.msg_controllen = 0;
3271 msg.msg_namelen = 0;
3272 msg.msg_iocb = NULL;
3275 flags = req->sr_msg.msg_flags;
3276 if (flags & MSG_DONTWAIT)
3277 req->flags |= REQ_F_NOWAIT;
3278 else if (force_nonblock)
3279 flags |= MSG_DONTWAIT;
3281 ret = sock_recvmsg(sock, &msg, flags);
3282 if (force_nonblock && ret == -EAGAIN)
3284 if (ret == -ERESTARTSYS)
3288 io_cqring_add_event(req, ret);
3290 req_set_fail_links(req);
3291 io_put_req_find_next(req, nxt);
3299 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3301 #if defined(CONFIG_NET)
3302 struct io_accept *accept = &req->accept;
3304 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3306 if (sqe->ioprio || sqe->len || sqe->buf_index)
3309 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3310 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3311 accept->flags = READ_ONCE(sqe->accept_flags);
3318 #if defined(CONFIG_NET)
3319 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3320 bool force_nonblock)
3322 struct io_accept *accept = &req->accept;
3323 unsigned file_flags;
3326 file_flags = force_nonblock ? O_NONBLOCK : 0;
3327 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3328 accept->addr_len, accept->flags);
3329 if (ret == -EAGAIN && force_nonblock)
3331 if (ret == -ERESTARTSYS)
3334 req_set_fail_links(req);
3335 io_cqring_add_event(req, ret);
3336 io_put_req_find_next(req, nxt);
3340 static void io_accept_finish(struct io_wq_work **workptr)
3342 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3343 struct io_kiocb *nxt = NULL;
3345 if (io_req_cancelled(req))
3347 __io_accept(req, &nxt, false);
3349 io_wq_assign_next(workptr, nxt);
3353 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3354 bool force_nonblock)
3356 #if defined(CONFIG_NET)
3359 ret = __io_accept(req, nxt, force_nonblock);
3360 if (ret == -EAGAIN && force_nonblock) {
3361 req->work.func = io_accept_finish;
3371 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3373 #if defined(CONFIG_NET)
3374 struct io_connect *conn = &req->connect;
3375 struct io_async_ctx *io = req->io;
3377 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3379 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3382 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3383 conn->addr_len = READ_ONCE(sqe->addr2);
3388 return move_addr_to_kernel(conn->addr, conn->addr_len,
3389 &io->connect.address);
3395 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3396 bool force_nonblock)
3398 #if defined(CONFIG_NET)
3399 struct io_async_ctx __io, *io;
3400 unsigned file_flags;
3406 ret = move_addr_to_kernel(req->connect.addr,
3407 req->connect.addr_len,
3408 &__io.connect.address);
3414 file_flags = force_nonblock ? O_NONBLOCK : 0;
3416 ret = __sys_connect_file(req->file, &io->connect.address,
3417 req->connect.addr_len, file_flags);
3418 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3421 if (io_alloc_async_ctx(req)) {
3425 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3428 if (ret == -ERESTARTSYS)
3432 req_set_fail_links(req);
3433 io_cqring_add_event(req, ret);
3434 io_put_req_find_next(req, nxt);
3441 static void io_poll_remove_one(struct io_kiocb *req)
3443 struct io_poll_iocb *poll = &req->poll;
3445 spin_lock(&poll->head->lock);
3446 WRITE_ONCE(poll->canceled, true);
3447 if (!list_empty(&poll->wait.entry)) {
3448 list_del_init(&poll->wait.entry);
3449 io_queue_async_work(req);
3451 spin_unlock(&poll->head->lock);
3452 hash_del(&req->hash_node);
3455 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3457 struct hlist_node *tmp;
3458 struct io_kiocb *req;
3461 spin_lock_irq(&ctx->completion_lock);
3462 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3463 struct hlist_head *list;
3465 list = &ctx->cancel_hash[i];
3466 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3467 io_poll_remove_one(req);
3469 spin_unlock_irq(&ctx->completion_lock);
3472 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3474 struct hlist_head *list;
3475 struct io_kiocb *req;
3477 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3478 hlist_for_each_entry(req, list, hash_node) {
3479 if (sqe_addr == req->user_data) {
3480 io_poll_remove_one(req);
3488 static int io_poll_remove_prep(struct io_kiocb *req,
3489 const struct io_uring_sqe *sqe)
3491 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3493 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3497 req->poll.addr = READ_ONCE(sqe->addr);
3502 * Find a running poll command that matches one specified in sqe->addr,
3503 * and remove it if found.
3505 static int io_poll_remove(struct io_kiocb *req)
3507 struct io_ring_ctx *ctx = req->ctx;
3511 addr = req->poll.addr;
3512 spin_lock_irq(&ctx->completion_lock);
3513 ret = io_poll_cancel(ctx, addr);
3514 spin_unlock_irq(&ctx->completion_lock);
3516 io_cqring_add_event(req, ret);
3518 req_set_fail_links(req);
3523 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3525 struct io_ring_ctx *ctx = req->ctx;
3527 req->poll.done = true;
3529 io_cqring_fill_event(req, error);
3531 io_cqring_fill_event(req, mangle_poll(mask));
3532 io_commit_cqring(ctx);
3535 static void io_poll_complete_work(struct io_wq_work **workptr)
3537 struct io_wq_work *work = *workptr;
3538 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3539 struct io_poll_iocb *poll = &req->poll;
3540 struct poll_table_struct pt = { ._key = poll->events };
3541 struct io_ring_ctx *ctx = req->ctx;
3542 struct io_kiocb *nxt = NULL;
3546 if (work->flags & IO_WQ_WORK_CANCEL) {
3547 WRITE_ONCE(poll->canceled, true);
3549 } else if (READ_ONCE(poll->canceled)) {
3553 if (ret != -ECANCELED)
3554 mask = vfs_poll(poll->file, &pt) & poll->events;
3557 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3558 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3559 * synchronize with them. In the cancellation case the list_del_init
3560 * itself is not actually needed, but harmless so we keep it in to
3561 * avoid further branches in the fast path.
3563 spin_lock_irq(&ctx->completion_lock);
3564 if (!mask && ret != -ECANCELED) {
3565 add_wait_queue(poll->head, &poll->wait);
3566 spin_unlock_irq(&ctx->completion_lock);
3569 hash_del(&req->hash_node);
3570 io_poll_complete(req, mask, ret);
3571 spin_unlock_irq(&ctx->completion_lock);
3573 io_cqring_ev_posted(ctx);
3576 req_set_fail_links(req);
3577 io_put_req_find_next(req, &nxt);
3579 io_wq_assign_next(workptr, nxt);
3582 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3584 struct io_kiocb *req, *tmp;
3585 struct req_batch rb;
3587 rb.to_free = rb.need_iter = 0;
3588 spin_lock_irq(&ctx->completion_lock);
3589 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3590 hash_del(&req->hash_node);
3591 io_poll_complete(req, req->result, 0);
3593 if (refcount_dec_and_test(&req->refs) &&
3594 !io_req_multi_free(&rb, req)) {
3595 req->flags |= REQ_F_COMP_LOCKED;
3599 spin_unlock_irq(&ctx->completion_lock);
3601 io_cqring_ev_posted(ctx);
3602 io_free_req_many(ctx, &rb);
3605 static void io_poll_flush(struct io_wq_work **workptr)
3607 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3608 struct llist_node *nodes;
3610 nodes = llist_del_all(&req->ctx->poll_llist);
3612 __io_poll_flush(req->ctx, nodes);
3615 static void io_poll_trigger_evfd(struct io_wq_work **workptr)
3617 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3619 eventfd_signal(req->ctx->cq_ev_fd, 1);
3623 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3626 struct io_poll_iocb *poll = wait->private;
3627 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3628 struct io_ring_ctx *ctx = req->ctx;
3629 __poll_t mask = key_to_poll(key);
3631 /* for instances that support it check for an event match first: */
3632 if (mask && !(mask & poll->events))
3635 list_del_init(&poll->wait.entry);
3638 * Run completion inline if we can. We're using trylock here because
3639 * we are violating the completion_lock -> poll wq lock ordering.
3640 * If we have a link timeout we're going to need the completion_lock
3641 * for finalizing the request, mark us as having grabbed that already.
3644 unsigned long flags;
3646 if (llist_empty(&ctx->poll_llist) &&
3647 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3650 hash_del(&req->hash_node);
3651 io_poll_complete(req, mask, 0);
3653 trigger_ev = io_should_trigger_evfd(ctx);
3654 if (trigger_ev && eventfd_signal_count()) {
3656 req->work.func = io_poll_trigger_evfd;
3658 req->flags |= REQ_F_COMP_LOCKED;
3662 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3663 __io_cqring_ev_posted(ctx, trigger_ev);
3666 req->llist_node.next = NULL;
3667 /* if the list wasn't empty, we're done */
3668 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3671 req->work.func = io_poll_flush;
3675 io_queue_async_work(req);
3680 struct io_poll_table {
3681 struct poll_table_struct pt;
3682 struct io_kiocb *req;
3686 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3687 struct poll_table_struct *p)
3689 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3691 if (unlikely(pt->req->poll.head)) {
3692 pt->error = -EINVAL;
3697 pt->req->poll.head = head;
3698 add_wait_queue(head, &pt->req->poll.wait);
3701 static void io_poll_req_insert(struct io_kiocb *req)
3703 struct io_ring_ctx *ctx = req->ctx;
3704 struct hlist_head *list;
3706 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3707 hlist_add_head(&req->hash_node, list);
3710 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3712 struct io_poll_iocb *poll = &req->poll;
3715 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3717 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3722 events = READ_ONCE(sqe->poll_events);
3723 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3727 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3729 struct io_poll_iocb *poll = &req->poll;
3730 struct io_ring_ctx *ctx = req->ctx;
3731 struct io_poll_table ipt;
3732 bool cancel = false;
3735 INIT_IO_WORK(&req->work, io_poll_complete_work);
3736 INIT_HLIST_NODE(&req->hash_node);
3740 poll->canceled = false;
3742 ipt.pt._qproc = io_poll_queue_proc;
3743 ipt.pt._key = poll->events;
3745 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3747 /* initialized the list so that we can do list_empty checks */
3748 INIT_LIST_HEAD(&poll->wait.entry);
3749 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3750 poll->wait.private = poll;
3752 INIT_LIST_HEAD(&req->list);
3754 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3756 spin_lock_irq(&ctx->completion_lock);
3757 if (likely(poll->head)) {
3758 spin_lock(&poll->head->lock);
3759 if (unlikely(list_empty(&poll->wait.entry))) {
3765 if (mask || ipt.error)
3766 list_del_init(&poll->wait.entry);
3768 WRITE_ONCE(poll->canceled, true);
3769 else if (!poll->done) /* actually waiting for an event */
3770 io_poll_req_insert(req);
3771 spin_unlock(&poll->head->lock);
3773 if (mask) { /* no async, we'd stolen it */
3775 io_poll_complete(req, mask, 0);
3777 spin_unlock_irq(&ctx->completion_lock);
3780 io_cqring_ev_posted(ctx);
3781 io_put_req_find_next(req, nxt);
3786 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3788 struct io_timeout_data *data = container_of(timer,
3789 struct io_timeout_data, timer);
3790 struct io_kiocb *req = data->req;
3791 struct io_ring_ctx *ctx = req->ctx;
3792 unsigned long flags;
3794 atomic_inc(&ctx->cq_timeouts);
3796 spin_lock_irqsave(&ctx->completion_lock, flags);
3798 * We could be racing with timeout deletion. If the list is empty,
3799 * then timeout lookup already found it and will be handling it.
3801 if (!list_empty(&req->list)) {
3802 struct io_kiocb *prev;
3805 * Adjust the reqs sequence before the current one because it
3806 * will consume a slot in the cq_ring and the cq_tail
3807 * pointer will be increased, otherwise other timeout reqs may
3808 * return in advance without waiting for enough wait_nr.
3811 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3813 list_del_init(&req->list);
3816 io_cqring_fill_event(req, -ETIME);
3817 io_commit_cqring(ctx);
3818 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3820 io_cqring_ev_posted(ctx);
3821 req_set_fail_links(req);
3823 return HRTIMER_NORESTART;
3826 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3828 struct io_kiocb *req;
3831 list_for_each_entry(req, &ctx->timeout_list, list) {
3832 if (user_data == req->user_data) {
3833 list_del_init(&req->list);
3842 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3846 req_set_fail_links(req);
3847 io_cqring_fill_event(req, -ECANCELED);
3852 static int io_timeout_remove_prep(struct io_kiocb *req,
3853 const struct io_uring_sqe *sqe)
3855 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3857 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3860 req->timeout.addr = READ_ONCE(sqe->addr);
3861 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3862 if (req->timeout.flags)
3869 * Remove or update an existing timeout command
3871 static int io_timeout_remove(struct io_kiocb *req)
3873 struct io_ring_ctx *ctx = req->ctx;
3876 spin_lock_irq(&ctx->completion_lock);
3877 ret = io_timeout_cancel(ctx, req->timeout.addr);
3879 io_cqring_fill_event(req, ret);
3880 io_commit_cqring(ctx);
3881 spin_unlock_irq(&ctx->completion_lock);
3882 io_cqring_ev_posted(ctx);
3884 req_set_fail_links(req);
3889 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3890 bool is_timeout_link)
3892 struct io_timeout_data *data;
3895 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3897 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3899 if (sqe->off && is_timeout_link)
3901 flags = READ_ONCE(sqe->timeout_flags);
3902 if (flags & ~IORING_TIMEOUT_ABS)
3905 req->timeout.count = READ_ONCE(sqe->off);
3907 if (!req->io && io_alloc_async_ctx(req))
3910 data = &req->io->timeout;
3912 req->flags |= REQ_F_TIMEOUT;
3914 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3917 if (flags & IORING_TIMEOUT_ABS)
3918 data->mode = HRTIMER_MODE_ABS;
3920 data->mode = HRTIMER_MODE_REL;
3922 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3926 static int io_timeout(struct io_kiocb *req)
3929 struct io_ring_ctx *ctx = req->ctx;
3930 struct io_timeout_data *data;
3931 struct list_head *entry;
3934 data = &req->io->timeout;
3937 * sqe->off holds how many events that need to occur for this
3938 * timeout event to be satisfied. If it isn't set, then this is
3939 * a pure timeout request, sequence isn't used.
3941 count = req->timeout.count;
3943 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3944 spin_lock_irq(&ctx->completion_lock);
3945 entry = ctx->timeout_list.prev;
3949 req->sequence = ctx->cached_sq_head + count - 1;
3950 data->seq_offset = count;
3953 * Insertion sort, ensuring the first entry in the list is always
3954 * the one we need first.
3956 spin_lock_irq(&ctx->completion_lock);
3957 list_for_each_prev(entry, &ctx->timeout_list) {
3958 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3959 unsigned nxt_sq_head;
3960 long long tmp, tmp_nxt;
3961 u32 nxt_offset = nxt->io->timeout.seq_offset;
3963 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3967 * Since cached_sq_head + count - 1 can overflow, use type long
3970 tmp = (long long)ctx->cached_sq_head + count - 1;
3971 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3972 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3975 * cached_sq_head may overflow, and it will never overflow twice
3976 * once there is some timeout req still be valid.
3978 if (ctx->cached_sq_head < nxt_sq_head)
3985 * Sequence of reqs after the insert one and itself should
3986 * be adjusted because each timeout req consumes a slot.
3991 req->sequence -= span;
3993 list_add(&req->list, entry);
3994 data->timer.function = io_timeout_fn;
3995 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3996 spin_unlock_irq(&ctx->completion_lock);
4000 static bool io_cancel_cb(struct io_wq_work *work, void *data)
4002 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4004 return req->user_data == (unsigned long) data;
4007 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
4009 enum io_wq_cancel cancel_ret;
4012 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
4013 switch (cancel_ret) {
4014 case IO_WQ_CANCEL_OK:
4017 case IO_WQ_CANCEL_RUNNING:
4020 case IO_WQ_CANCEL_NOTFOUND:
4028 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4029 struct io_kiocb *req, __u64 sqe_addr,
4030 struct io_kiocb **nxt, int success_ret)
4032 unsigned long flags;
4035 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4036 if (ret != -ENOENT) {
4037 spin_lock_irqsave(&ctx->completion_lock, flags);
4041 spin_lock_irqsave(&ctx->completion_lock, flags);
4042 ret = io_timeout_cancel(ctx, sqe_addr);
4045 ret = io_poll_cancel(ctx, sqe_addr);
4049 io_cqring_fill_event(req, ret);
4050 io_commit_cqring(ctx);
4051 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4052 io_cqring_ev_posted(ctx);
4055 req_set_fail_links(req);
4056 io_put_req_find_next(req, nxt);
4059 static int io_async_cancel_prep(struct io_kiocb *req,
4060 const struct io_uring_sqe *sqe)
4062 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4064 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4068 req->cancel.addr = READ_ONCE(sqe->addr);
4072 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
4074 struct io_ring_ctx *ctx = req->ctx;
4076 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
4080 static int io_files_update_prep(struct io_kiocb *req,
4081 const struct io_uring_sqe *sqe)
4083 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4086 req->files_update.offset = READ_ONCE(sqe->off);
4087 req->files_update.nr_args = READ_ONCE(sqe->len);
4088 if (!req->files_update.nr_args)
4090 req->files_update.arg = READ_ONCE(sqe->addr);
4094 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
4096 struct io_ring_ctx *ctx = req->ctx;
4097 struct io_uring_files_update up;
4103 up.offset = req->files_update.offset;
4104 up.fds = req->files_update.arg;
4106 mutex_lock(&ctx->uring_lock);
4107 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4108 mutex_unlock(&ctx->uring_lock);
4111 req_set_fail_links(req);
4112 io_cqring_add_event(req, ret);
4117 static int io_req_defer_prep(struct io_kiocb *req,
4118 const struct io_uring_sqe *sqe)
4122 if (io_op_defs[req->opcode].file_table) {
4123 ret = io_grab_files(req);
4128 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4130 switch (req->opcode) {
4133 case IORING_OP_READV:
4134 case IORING_OP_READ_FIXED:
4135 case IORING_OP_READ:
4136 ret = io_read_prep(req, sqe, true);
4138 case IORING_OP_WRITEV:
4139 case IORING_OP_WRITE_FIXED:
4140 case IORING_OP_WRITE:
4141 ret = io_write_prep(req, sqe, true);
4143 case IORING_OP_POLL_ADD:
4144 ret = io_poll_add_prep(req, sqe);
4146 case IORING_OP_POLL_REMOVE:
4147 ret = io_poll_remove_prep(req, sqe);
4149 case IORING_OP_FSYNC:
4150 ret = io_prep_fsync(req, sqe);
4152 case IORING_OP_SYNC_FILE_RANGE:
4153 ret = io_prep_sfr(req, sqe);
4155 case IORING_OP_SENDMSG:
4156 case IORING_OP_SEND:
4157 ret = io_sendmsg_prep(req, sqe);
4159 case IORING_OP_RECVMSG:
4160 case IORING_OP_RECV:
4161 ret = io_recvmsg_prep(req, sqe);
4163 case IORING_OP_CONNECT:
4164 ret = io_connect_prep(req, sqe);
4166 case IORING_OP_TIMEOUT:
4167 ret = io_timeout_prep(req, sqe, false);
4169 case IORING_OP_TIMEOUT_REMOVE:
4170 ret = io_timeout_remove_prep(req, sqe);
4172 case IORING_OP_ASYNC_CANCEL:
4173 ret = io_async_cancel_prep(req, sqe);
4175 case IORING_OP_LINK_TIMEOUT:
4176 ret = io_timeout_prep(req, sqe, true);
4178 case IORING_OP_ACCEPT:
4179 ret = io_accept_prep(req, sqe);
4181 case IORING_OP_FALLOCATE:
4182 ret = io_fallocate_prep(req, sqe);
4184 case IORING_OP_OPENAT:
4185 ret = io_openat_prep(req, sqe);
4187 case IORING_OP_CLOSE:
4188 ret = io_close_prep(req, sqe);
4190 case IORING_OP_FILES_UPDATE:
4191 ret = io_files_update_prep(req, sqe);
4193 case IORING_OP_STATX:
4194 ret = io_statx_prep(req, sqe);
4196 case IORING_OP_FADVISE:
4197 ret = io_fadvise_prep(req, sqe);
4199 case IORING_OP_MADVISE:
4200 ret = io_madvise_prep(req, sqe);
4202 case IORING_OP_OPENAT2:
4203 ret = io_openat2_prep(req, sqe);
4205 case IORING_OP_EPOLL_CTL:
4206 ret = io_epoll_ctl_prep(req, sqe);
4209 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4218 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4220 struct io_ring_ctx *ctx = req->ctx;
4223 /* Still need defer if there is pending req in defer list. */
4224 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4227 if (!req->io && io_alloc_async_ctx(req))
4230 ret = io_req_defer_prep(req, sqe);
4234 spin_lock_irq(&ctx->completion_lock);
4235 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4236 spin_unlock_irq(&ctx->completion_lock);
4240 trace_io_uring_defer(ctx, req, req->user_data);
4241 list_add_tail(&req->list, &ctx->defer_list);
4242 spin_unlock_irq(&ctx->completion_lock);
4243 return -EIOCBQUEUED;
4246 static void io_cleanup_req(struct io_kiocb *req)
4248 struct io_async_ctx *io = req->io;
4250 switch (req->opcode) {
4251 case IORING_OP_READV:
4252 case IORING_OP_READ_FIXED:
4253 case IORING_OP_READ:
4254 case IORING_OP_WRITEV:
4255 case IORING_OP_WRITE_FIXED:
4256 case IORING_OP_WRITE:
4257 if (io->rw.iov != io->rw.fast_iov)
4260 case IORING_OP_SENDMSG:
4261 case IORING_OP_RECVMSG:
4262 if (io->msg.iov != io->msg.fast_iov)
4265 case IORING_OP_OPENAT:
4266 case IORING_OP_OPENAT2:
4267 case IORING_OP_STATX:
4268 putname(req->open.filename);
4272 req->flags &= ~REQ_F_NEED_CLEANUP;
4275 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4276 struct io_kiocb **nxt, bool force_nonblock)
4278 struct io_ring_ctx *ctx = req->ctx;
4281 switch (req->opcode) {
4285 case IORING_OP_READV:
4286 case IORING_OP_READ_FIXED:
4287 case IORING_OP_READ:
4289 ret = io_read_prep(req, sqe, force_nonblock);
4293 ret = io_read(req, nxt, force_nonblock);
4295 case IORING_OP_WRITEV:
4296 case IORING_OP_WRITE_FIXED:
4297 case IORING_OP_WRITE:
4299 ret = io_write_prep(req, sqe, force_nonblock);
4303 ret = io_write(req, nxt, force_nonblock);
4305 case IORING_OP_FSYNC:
4307 ret = io_prep_fsync(req, sqe);
4311 ret = io_fsync(req, nxt, force_nonblock);
4313 case IORING_OP_POLL_ADD:
4315 ret = io_poll_add_prep(req, sqe);
4319 ret = io_poll_add(req, nxt);
4321 case IORING_OP_POLL_REMOVE:
4323 ret = io_poll_remove_prep(req, sqe);
4327 ret = io_poll_remove(req);
4329 case IORING_OP_SYNC_FILE_RANGE:
4331 ret = io_prep_sfr(req, sqe);
4335 ret = io_sync_file_range(req, nxt, force_nonblock);
4337 case IORING_OP_SENDMSG:
4338 case IORING_OP_SEND:
4340 ret = io_sendmsg_prep(req, sqe);
4344 if (req->opcode == IORING_OP_SENDMSG)
4345 ret = io_sendmsg(req, nxt, force_nonblock);
4347 ret = io_send(req, nxt, force_nonblock);
4349 case IORING_OP_RECVMSG:
4350 case IORING_OP_RECV:
4352 ret = io_recvmsg_prep(req, sqe);
4356 if (req->opcode == IORING_OP_RECVMSG)
4357 ret = io_recvmsg(req, nxt, force_nonblock);
4359 ret = io_recv(req, nxt, force_nonblock);
4361 case IORING_OP_TIMEOUT:
4363 ret = io_timeout_prep(req, sqe, false);
4367 ret = io_timeout(req);
4369 case IORING_OP_TIMEOUT_REMOVE:
4371 ret = io_timeout_remove_prep(req, sqe);
4375 ret = io_timeout_remove(req);
4377 case IORING_OP_ACCEPT:
4379 ret = io_accept_prep(req, sqe);
4383 ret = io_accept(req, nxt, force_nonblock);
4385 case IORING_OP_CONNECT:
4387 ret = io_connect_prep(req, sqe);
4391 ret = io_connect(req, nxt, force_nonblock);
4393 case IORING_OP_ASYNC_CANCEL:
4395 ret = io_async_cancel_prep(req, sqe);
4399 ret = io_async_cancel(req, nxt);
4401 case IORING_OP_FALLOCATE:
4403 ret = io_fallocate_prep(req, sqe);
4407 ret = io_fallocate(req, nxt, force_nonblock);
4409 case IORING_OP_OPENAT:
4411 ret = io_openat_prep(req, sqe);
4415 ret = io_openat(req, nxt, force_nonblock);
4417 case IORING_OP_CLOSE:
4419 ret = io_close_prep(req, sqe);
4423 ret = io_close(req, nxt, force_nonblock);
4425 case IORING_OP_FILES_UPDATE:
4427 ret = io_files_update_prep(req, sqe);
4431 ret = io_files_update(req, force_nonblock);
4433 case IORING_OP_STATX:
4435 ret = io_statx_prep(req, sqe);
4439 ret = io_statx(req, nxt, force_nonblock);
4441 case IORING_OP_FADVISE:
4443 ret = io_fadvise_prep(req, sqe);
4447 ret = io_fadvise(req, nxt, force_nonblock);
4449 case IORING_OP_MADVISE:
4451 ret = io_madvise_prep(req, sqe);
4455 ret = io_madvise(req, nxt, force_nonblock);
4457 case IORING_OP_OPENAT2:
4459 ret = io_openat2_prep(req, sqe);
4463 ret = io_openat2(req, nxt, force_nonblock);
4465 case IORING_OP_EPOLL_CTL:
4467 ret = io_epoll_ctl_prep(req, sqe);
4471 ret = io_epoll_ctl(req, nxt, force_nonblock);
4481 if (ctx->flags & IORING_SETUP_IOPOLL) {
4482 const bool in_async = io_wq_current_is_worker();
4484 if (req->result == -EAGAIN)
4487 /* workqueue context doesn't hold uring_lock, grab it now */
4489 mutex_lock(&ctx->uring_lock);
4491 io_iopoll_req_issued(req);
4494 mutex_unlock(&ctx->uring_lock);
4500 static void io_wq_submit_work(struct io_wq_work **workptr)
4502 struct io_wq_work *work = *workptr;
4503 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4504 struct io_kiocb *nxt = NULL;
4507 /* if NO_CANCEL is set, we must still run the work */
4508 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4509 IO_WQ_WORK_CANCEL) {
4514 req->in_async = true;
4516 ret = io_issue_sqe(req, NULL, &nxt, false);
4518 * We can get EAGAIN for polled IO even though we're
4519 * forcing a sync submission from here, since we can't
4520 * wait for request slots on the block side.
4528 /* drop submission reference */
4532 req_set_fail_links(req);
4533 io_cqring_add_event(req, ret);
4537 /* if a dependent link is ready, pass it back */
4539 io_wq_assign_next(workptr, nxt);
4542 static int io_req_needs_file(struct io_kiocb *req, int fd)
4544 if (!io_op_defs[req->opcode].needs_file)
4546 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4551 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4554 struct fixed_file_table *table;
4556 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4557 return table->files[index & IORING_FILE_TABLE_MASK];;
4560 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4561 const struct io_uring_sqe *sqe)
4563 struct io_ring_ctx *ctx = req->ctx;
4567 flags = READ_ONCE(sqe->flags);
4568 fd = READ_ONCE(sqe->fd);
4570 if (!io_req_needs_file(req, fd))
4573 if (flags & IOSQE_FIXED_FILE) {
4574 if (unlikely(!ctx->file_data ||
4575 (unsigned) fd >= ctx->nr_user_files))
4577 fd = array_index_nospec(fd, ctx->nr_user_files);
4578 req->file = io_file_from_index(ctx, fd);
4581 req->flags |= REQ_F_FIXED_FILE;
4582 percpu_ref_get(&ctx->file_data->refs);
4584 if (req->needs_fixed_file)
4586 trace_io_uring_file_get(ctx, fd);
4587 req->file = io_file_get(state, fd);
4588 if (unlikely(!req->file))
4595 static int io_grab_files(struct io_kiocb *req)
4598 struct io_ring_ctx *ctx = req->ctx;
4600 if (req->work.files)
4602 if (!ctx->ring_file)
4606 spin_lock_irq(&ctx->inflight_lock);
4608 * We use the f_ops->flush() handler to ensure that we can flush
4609 * out work accessing these files if the fd is closed. Check if
4610 * the fd has changed since we started down this path, and disallow
4611 * this operation if it has.
4613 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4614 list_add(&req->inflight_entry, &ctx->inflight_list);
4615 req->flags |= REQ_F_INFLIGHT;
4616 req->work.files = current->files;
4619 spin_unlock_irq(&ctx->inflight_lock);
4625 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4627 struct io_timeout_data *data = container_of(timer,
4628 struct io_timeout_data, timer);
4629 struct io_kiocb *req = data->req;
4630 struct io_ring_ctx *ctx = req->ctx;
4631 struct io_kiocb *prev = NULL;
4632 unsigned long flags;
4634 spin_lock_irqsave(&ctx->completion_lock, flags);
4637 * We don't expect the list to be empty, that will only happen if we
4638 * race with the completion of the linked work.
4640 if (!list_empty(&req->link_list)) {
4641 prev = list_entry(req->link_list.prev, struct io_kiocb,
4643 if (refcount_inc_not_zero(&prev->refs)) {
4644 list_del_init(&req->link_list);
4645 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4650 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4653 req_set_fail_links(prev);
4654 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4658 io_cqring_add_event(req, -ETIME);
4661 return HRTIMER_NORESTART;
4664 static void io_queue_linked_timeout(struct io_kiocb *req)
4666 struct io_ring_ctx *ctx = req->ctx;
4669 * If the list is now empty, then our linked request finished before
4670 * we got a chance to setup the timer
4672 spin_lock_irq(&ctx->completion_lock);
4673 if (!list_empty(&req->link_list)) {
4674 struct io_timeout_data *data = &req->io->timeout;
4676 data->timer.function = io_link_timeout_fn;
4677 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4680 spin_unlock_irq(&ctx->completion_lock);
4682 /* drop submission reference */
4686 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4688 struct io_kiocb *nxt;
4690 if (!(req->flags & REQ_F_LINK))
4693 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4695 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4698 req->flags |= REQ_F_LINK_TIMEOUT;
4702 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4704 struct io_kiocb *linked_timeout;
4705 struct io_kiocb *nxt = NULL;
4709 linked_timeout = io_prep_linked_timeout(req);
4711 ret = io_issue_sqe(req, sqe, &nxt, true);
4714 * We async punt it if the file wasn't marked NOWAIT, or if the file
4715 * doesn't support non-blocking read/write attempts
4717 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4718 (req->flags & REQ_F_MUST_PUNT))) {
4720 if (io_op_defs[req->opcode].file_table) {
4721 ret = io_grab_files(req);
4727 * Queued up for async execution, worker will release
4728 * submit reference when the iocb is actually submitted.
4730 io_queue_async_work(req);
4735 /* drop submission reference */
4738 if (linked_timeout) {
4740 io_queue_linked_timeout(linked_timeout);
4742 io_put_req(linked_timeout);
4745 /* and drop final reference, if we failed */
4747 io_cqring_add_event(req, ret);
4748 req_set_fail_links(req);
4756 if (req->flags & REQ_F_FORCE_ASYNC)
4762 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4766 ret = io_req_defer(req, sqe);
4768 if (ret != -EIOCBQUEUED) {
4770 io_cqring_add_event(req, ret);
4771 req_set_fail_links(req);
4772 io_double_put_req(req);
4774 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4775 ret = io_req_defer_prep(req, sqe);
4776 if (unlikely(ret < 0))
4779 * Never try inline submit of IOSQE_ASYNC is set, go straight
4780 * to async execution.
4782 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4783 io_queue_async_work(req);
4785 __io_queue_sqe(req, sqe);
4789 static inline void io_queue_link_head(struct io_kiocb *req)
4791 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4792 io_cqring_add_event(req, -ECANCELED);
4793 io_double_put_req(req);
4795 io_queue_sqe(req, NULL);
4798 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4799 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4801 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4802 struct io_submit_state *state, struct io_kiocb **link)
4804 const struct cred *old_creds = NULL;
4805 struct io_ring_ctx *ctx = req->ctx;
4806 unsigned int sqe_flags;
4809 sqe_flags = READ_ONCE(sqe->flags);
4811 /* enforce forwards compatibility on users */
4812 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4817 id = READ_ONCE(sqe->personality);
4819 const struct cred *personality_creds;
4821 personality_creds = idr_find(&ctx->personality_idr, id);
4822 if (unlikely(!personality_creds)) {
4826 old_creds = override_creds(personality_creds);
4829 /* same numerical values with corresponding REQ_F_*, safe to copy */
4830 req->flags |= sqe_flags & (IOSQE_IO_DRAIN|IOSQE_IO_HARDLINK|
4833 ret = io_req_set_file(state, req, sqe);
4834 if (unlikely(ret)) {
4836 io_cqring_add_event(req, ret);
4837 io_double_put_req(req);
4839 revert_creds(old_creds);
4844 * If we already have a head request, queue this one for async
4845 * submittal once the head completes. If we don't have a head but
4846 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4847 * submitted sync once the chain is complete. If none of those
4848 * conditions are true (normal request), then just queue it.
4851 struct io_kiocb *head = *link;
4854 * Taking sequential execution of a link, draining both sides
4855 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
4856 * requests in the link. So, it drains the head and the
4857 * next after the link request. The last one is done via
4858 * drain_next flag to persist the effect across calls.
4860 if (sqe_flags & IOSQE_IO_DRAIN) {
4861 head->flags |= REQ_F_IO_DRAIN;
4862 ctx->drain_next = 1;
4864 if (io_alloc_async_ctx(req)) {
4869 ret = io_req_defer_prep(req, sqe);
4871 /* fail even hard links since we don't submit */
4872 head->flags |= REQ_F_FAIL_LINK;
4875 trace_io_uring_link(ctx, req, head);
4876 list_add_tail(&req->link_list, &head->link_list);
4878 /* last request of a link, enqueue the link */
4879 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4880 io_queue_link_head(head);
4884 if (unlikely(ctx->drain_next)) {
4885 req->flags |= REQ_F_IO_DRAIN;
4886 req->ctx->drain_next = 0;
4888 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4889 req->flags |= REQ_F_LINK;
4890 INIT_LIST_HEAD(&req->link_list);
4891 ret = io_req_defer_prep(req, sqe);
4893 req->flags |= REQ_F_FAIL_LINK;
4896 io_queue_sqe(req, sqe);
4901 revert_creds(old_creds);
4906 * Batched submission is done, ensure local IO is flushed out.
4908 static void io_submit_state_end(struct io_submit_state *state)
4910 blk_finish_plug(&state->plug);
4912 if (state->free_reqs)
4913 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
4917 * Start submission side cache.
4919 static void io_submit_state_start(struct io_submit_state *state,
4920 unsigned int max_ios)
4922 blk_start_plug(&state->plug);
4923 state->free_reqs = 0;
4925 state->ios_left = max_ios;
4928 static void io_commit_sqring(struct io_ring_ctx *ctx)
4930 struct io_rings *rings = ctx->rings;
4933 * Ensure any loads from the SQEs are done at this point,
4934 * since once we write the new head, the application could
4935 * write new data to them.
4937 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4941 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4942 * that is mapped by userspace. This means that care needs to be taken to
4943 * ensure that reads are stable, as we cannot rely on userspace always
4944 * being a good citizen. If members of the sqe are validated and then later
4945 * used, it's important that those reads are done through READ_ONCE() to
4946 * prevent a re-load down the line.
4948 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4949 const struct io_uring_sqe **sqe_ptr)
4951 u32 *sq_array = ctx->sq_array;
4955 * The cached sq head (or cq tail) serves two purposes:
4957 * 1) allows us to batch the cost of updating the user visible
4959 * 2) allows the kernel side to track the head on its own, even
4960 * though the application is the one updating it.
4962 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4963 if (likely(head < ctx->sq_entries)) {
4965 * All io need record the previous position, if LINK vs DARIN,
4966 * it can be used to mark the position of the first IO in the
4969 req->sequence = ctx->cached_sq_head;
4970 *sqe_ptr = &ctx->sq_sqes[head];
4971 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4972 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4973 ctx->cached_sq_head++;
4977 /* drop invalid entries */
4978 ctx->cached_sq_head++;
4979 ctx->cached_sq_dropped++;
4980 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4984 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4985 struct file *ring_file, int ring_fd,
4986 struct mm_struct **mm, bool async)
4988 struct io_submit_state state, *statep = NULL;
4989 struct io_kiocb *link = NULL;
4990 int i, submitted = 0;
4991 bool mm_fault = false;
4993 /* if we have a backlog and couldn't flush it all, return BUSY */
4994 if (test_bit(0, &ctx->sq_check_overflow)) {
4995 if (!list_empty(&ctx->cq_overflow_list) &&
4996 !io_cqring_overflow_flush(ctx, false))
5000 /* make sure SQ entry isn't read before tail */
5001 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
5003 if (!percpu_ref_tryget_many(&ctx->refs, nr))
5006 if (nr > IO_PLUG_THRESHOLD) {
5007 io_submit_state_start(&state, nr);
5011 ctx->ring_fd = ring_fd;
5012 ctx->ring_file = ring_file;
5014 for (i = 0; i < nr; i++) {
5015 const struct io_uring_sqe *sqe;
5016 struct io_kiocb *req;
5019 req = io_get_req(ctx, statep);
5020 if (unlikely(!req)) {
5022 submitted = -EAGAIN;
5025 if (!io_get_sqring(ctx, req, &sqe)) {
5026 __io_req_do_free(req);
5030 /* will complete beyond this point, count as submitted */
5033 if (unlikely(req->opcode >= IORING_OP_LAST)) {
5036 io_cqring_add_event(req, err);
5037 io_double_put_req(req);
5041 if (io_op_defs[req->opcode].needs_mm && !*mm) {
5042 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
5043 if (unlikely(mm_fault)) {
5047 use_mm(ctx->sqo_mm);
5051 req->in_async = async;
5052 req->needs_fixed_file = async;
5053 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
5055 if (!io_submit_sqe(req, sqe, statep, &link))
5059 if (unlikely(submitted != nr)) {
5060 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
5062 percpu_ref_put_many(&ctx->refs, nr - ref_used);
5065 io_queue_link_head(link);
5067 io_submit_state_end(&state);
5069 /* Commit SQ ring head once we've consumed and submitted all SQEs */
5070 io_commit_sqring(ctx);
5075 static int io_sq_thread(void *data)
5077 struct io_ring_ctx *ctx = data;
5078 struct mm_struct *cur_mm = NULL;
5079 const struct cred *old_cred;
5080 mm_segment_t old_fs;
5083 unsigned long timeout;
5086 complete(&ctx->completions[1]);
5090 old_cred = override_creds(ctx->creds);
5092 ret = timeout = inflight = 0;
5093 while (!kthread_should_park()) {
5094 unsigned int to_submit;
5097 unsigned nr_events = 0;
5099 if (ctx->flags & IORING_SETUP_IOPOLL) {
5101 * inflight is the count of the maximum possible
5102 * entries we submitted, but it can be smaller
5103 * if we dropped some of them. If we don't have
5104 * poll entries available, then we know that we
5105 * have nothing left to poll for. Reset the
5106 * inflight count to zero in that case.
5108 mutex_lock(&ctx->uring_lock);
5109 if (!list_empty(&ctx->poll_list))
5110 __io_iopoll_check(ctx, &nr_events, 0);
5113 mutex_unlock(&ctx->uring_lock);
5116 * Normal IO, just pretend everything completed.
5117 * We don't have to poll completions for that.
5119 nr_events = inflight;
5122 inflight -= nr_events;
5124 timeout = jiffies + ctx->sq_thread_idle;
5127 to_submit = io_sqring_entries(ctx);
5130 * If submit got -EBUSY, flag us as needing the application
5131 * to enter the kernel to reap and flush events.
5133 if (!to_submit || ret == -EBUSY) {
5135 * We're polling. If we're within the defined idle
5136 * period, then let us spin without work before going
5137 * to sleep. The exception is if we got EBUSY doing
5138 * more IO, we should wait for the application to
5139 * reap events and wake us up.
5142 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5143 !percpu_ref_is_dying(&ctx->refs))) {
5149 * Drop cur_mm before scheduling, we can't hold it for
5150 * long periods (or over schedule()). Do this before
5151 * adding ourselves to the waitqueue, as the unuse/drop
5160 prepare_to_wait(&ctx->sqo_wait, &wait,
5161 TASK_INTERRUPTIBLE);
5163 /* Tell userspace we may need a wakeup call */
5164 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
5165 /* make sure to read SQ tail after writing flags */
5168 to_submit = io_sqring_entries(ctx);
5169 if (!to_submit || ret == -EBUSY) {
5170 if (kthread_should_park()) {
5171 finish_wait(&ctx->sqo_wait, &wait);
5174 if (signal_pending(current))
5175 flush_signals(current);
5177 finish_wait(&ctx->sqo_wait, &wait);
5179 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5182 finish_wait(&ctx->sqo_wait, &wait);
5184 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5187 mutex_lock(&ctx->uring_lock);
5188 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
5189 mutex_unlock(&ctx->uring_lock);
5199 revert_creds(old_cred);
5206 struct io_wait_queue {
5207 struct wait_queue_entry wq;
5208 struct io_ring_ctx *ctx;
5210 unsigned nr_timeouts;
5213 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
5215 struct io_ring_ctx *ctx = iowq->ctx;
5218 * Wake up if we have enough events, or if a timeout occurred since we
5219 * started waiting. For timeouts, we always want to return to userspace,
5220 * regardless of event count.
5222 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
5223 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5226 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5227 int wake_flags, void *key)
5229 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5232 /* use noflush == true, as we can't safely rely on locking context */
5233 if (!io_should_wake(iowq, true))
5236 return autoremove_wake_function(curr, mode, wake_flags, key);
5240 * Wait until events become available, if we don't already have some. The
5241 * application must reap them itself, as they reside on the shared cq ring.
5243 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5244 const sigset_t __user *sig, size_t sigsz)
5246 struct io_wait_queue iowq = {
5249 .func = io_wake_function,
5250 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5253 .to_wait = min_events,
5255 struct io_rings *rings = ctx->rings;
5258 if (io_cqring_events(ctx, false) >= min_events)
5262 #ifdef CONFIG_COMPAT
5263 if (in_compat_syscall())
5264 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5268 ret = set_user_sigmask(sig, sigsz);
5274 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5275 trace_io_uring_cqring_wait(ctx, min_events);
5277 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5278 TASK_INTERRUPTIBLE);
5279 if (io_should_wake(&iowq, false))
5282 if (signal_pending(current)) {
5287 finish_wait(&ctx->wait, &iowq.wq);
5289 restore_saved_sigmask_unless(ret == -EINTR);
5291 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5294 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5296 #if defined(CONFIG_UNIX)
5297 if (ctx->ring_sock) {
5298 struct sock *sock = ctx->ring_sock->sk;
5299 struct sk_buff *skb;
5301 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5307 for (i = 0; i < ctx->nr_user_files; i++) {
5310 file = io_file_from_index(ctx, i);
5317 static void io_file_ref_kill(struct percpu_ref *ref)
5319 struct fixed_file_data *data;
5321 data = container_of(ref, struct fixed_file_data, refs);
5322 complete(&data->done);
5325 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5327 struct fixed_file_data *data = ctx->file_data;
5328 unsigned nr_tables, i;
5333 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5334 flush_work(&data->ref_work);
5335 wait_for_completion(&data->done);
5336 io_ring_file_ref_flush(data);
5337 percpu_ref_exit(&data->refs);
5339 __io_sqe_files_unregister(ctx);
5340 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5341 for (i = 0; i < nr_tables; i++)
5342 kfree(data->table[i].files);
5345 ctx->file_data = NULL;
5346 ctx->nr_user_files = 0;
5350 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5352 if (ctx->sqo_thread) {
5353 wait_for_completion(&ctx->completions[1]);
5355 * The park is a bit of a work-around, without it we get
5356 * warning spews on shutdown with SQPOLL set and affinity
5357 * set to a single CPU.
5359 kthread_park(ctx->sqo_thread);
5360 kthread_stop(ctx->sqo_thread);
5361 ctx->sqo_thread = NULL;
5365 static void io_finish_async(struct io_ring_ctx *ctx)
5367 io_sq_thread_stop(ctx);
5370 io_wq_destroy(ctx->io_wq);
5375 #if defined(CONFIG_UNIX)
5377 * Ensure the UNIX gc is aware of our file set, so we are certain that
5378 * the io_uring can be safely unregistered on process exit, even if we have
5379 * loops in the file referencing.
5381 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5383 struct sock *sk = ctx->ring_sock->sk;
5384 struct scm_fp_list *fpl;
5385 struct sk_buff *skb;
5388 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5389 unsigned long inflight = ctx->user->unix_inflight + nr;
5391 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5395 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5399 skb = alloc_skb(0, GFP_KERNEL);
5408 fpl->user = get_uid(ctx->user);
5409 for (i = 0; i < nr; i++) {
5410 struct file *file = io_file_from_index(ctx, i + offset);
5414 fpl->fp[nr_files] = get_file(file);
5415 unix_inflight(fpl->user, fpl->fp[nr_files]);
5420 fpl->max = SCM_MAX_FD;
5421 fpl->count = nr_files;
5422 UNIXCB(skb).fp = fpl;
5423 skb->destructor = unix_destruct_scm;
5424 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5425 skb_queue_head(&sk->sk_receive_queue, skb);
5427 for (i = 0; i < nr_files; i++)
5438 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5439 * causes regular reference counting to break down. We rely on the UNIX
5440 * garbage collection to take care of this problem for us.
5442 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5444 unsigned left, total;
5448 left = ctx->nr_user_files;
5450 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
5452 ret = __io_sqe_files_scm(ctx, this_files, total);
5456 total += this_files;
5462 while (total < ctx->nr_user_files) {
5463 struct file *file = io_file_from_index(ctx, total);
5473 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5479 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5484 for (i = 0; i < nr_tables; i++) {
5485 struct fixed_file_table *table = &ctx->file_data->table[i];
5486 unsigned this_files;
5488 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5489 table->files = kcalloc(this_files, sizeof(struct file *),
5493 nr_files -= this_files;
5499 for (i = 0; i < nr_tables; i++) {
5500 struct fixed_file_table *table = &ctx->file_data->table[i];
5501 kfree(table->files);
5506 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5508 #if defined(CONFIG_UNIX)
5509 struct sock *sock = ctx->ring_sock->sk;
5510 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5511 struct sk_buff *skb;
5514 __skb_queue_head_init(&list);
5517 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5518 * remove this entry and rearrange the file array.
5520 skb = skb_dequeue(head);
5522 struct scm_fp_list *fp;
5524 fp = UNIXCB(skb).fp;
5525 for (i = 0; i < fp->count; i++) {
5528 if (fp->fp[i] != file)
5531 unix_notinflight(fp->user, fp->fp[i]);
5532 left = fp->count - 1 - i;
5534 memmove(&fp->fp[i], &fp->fp[i + 1],
5535 left * sizeof(struct file *));
5542 __skb_queue_tail(&list, skb);
5552 __skb_queue_tail(&list, skb);
5554 skb = skb_dequeue(head);
5557 if (skb_peek(&list)) {
5558 spin_lock_irq(&head->lock);
5559 while ((skb = __skb_dequeue(&list)) != NULL)
5560 __skb_queue_tail(head, skb);
5561 spin_unlock_irq(&head->lock);
5568 struct io_file_put {
5569 struct llist_node llist;
5571 struct completion *done;
5574 static void io_ring_file_ref_flush(struct fixed_file_data *data)
5576 struct io_file_put *pfile, *tmp;
5577 struct llist_node *node;
5579 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5580 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5581 io_ring_file_put(data->ctx, pfile->file);
5583 complete(pfile->done);
5590 static void io_ring_file_ref_switch(struct work_struct *work)
5592 struct fixed_file_data *data;
5594 data = container_of(work, struct fixed_file_data, ref_work);
5595 io_ring_file_ref_flush(data);
5596 percpu_ref_get(&data->refs);
5597 percpu_ref_switch_to_percpu(&data->refs);
5600 static void io_file_data_ref_zero(struct percpu_ref *ref)
5602 struct fixed_file_data *data;
5604 data = container_of(ref, struct fixed_file_data, refs);
5607 * We can't safely switch from inside this context, punt to wq. If
5608 * the table ref is going away, the table is being unregistered.
5609 * Don't queue up the async work for that case, the caller will
5612 if (!percpu_ref_is_dying(&data->refs))
5613 queue_work(system_wq, &data->ref_work);
5616 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5619 __s32 __user *fds = (__s32 __user *) arg;
5629 if (nr_args > IORING_MAX_FIXED_FILES)
5632 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5633 if (!ctx->file_data)
5635 ctx->file_data->ctx = ctx;
5636 init_completion(&ctx->file_data->done);
5638 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5639 ctx->file_data->table = kcalloc(nr_tables,
5640 sizeof(struct fixed_file_table),
5642 if (!ctx->file_data->table) {
5643 kfree(ctx->file_data);
5644 ctx->file_data = NULL;
5648 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5649 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5650 kfree(ctx->file_data->table);
5651 kfree(ctx->file_data);
5652 ctx->file_data = NULL;
5655 ctx->file_data->put_llist.first = NULL;
5656 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5658 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5659 percpu_ref_exit(&ctx->file_data->refs);
5660 kfree(ctx->file_data->table);
5661 kfree(ctx->file_data);
5662 ctx->file_data = NULL;
5666 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5667 struct fixed_file_table *table;
5671 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5673 /* allow sparse sets */
5679 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5680 index = i & IORING_FILE_TABLE_MASK;
5688 * Don't allow io_uring instances to be registered. If UNIX
5689 * isn't enabled, then this causes a reference cycle and this
5690 * instance can never get freed. If UNIX is enabled we'll
5691 * handle it just fine, but there's still no point in allowing
5692 * a ring fd as it doesn't support regular read/write anyway.
5694 if (file->f_op == &io_uring_fops) {
5699 table->files[index] = file;
5703 for (i = 0; i < ctx->nr_user_files; i++) {
5704 file = io_file_from_index(ctx, i);
5708 for (i = 0; i < nr_tables; i++)
5709 kfree(ctx->file_data->table[i].files);
5711 kfree(ctx->file_data->table);
5712 kfree(ctx->file_data);
5713 ctx->file_data = NULL;
5714 ctx->nr_user_files = 0;
5718 ret = io_sqe_files_scm(ctx);
5720 io_sqe_files_unregister(ctx);
5725 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5728 #if defined(CONFIG_UNIX)
5729 struct sock *sock = ctx->ring_sock->sk;
5730 struct sk_buff_head *head = &sock->sk_receive_queue;
5731 struct sk_buff *skb;
5734 * See if we can merge this file into an existing skb SCM_RIGHTS
5735 * file set. If there's no room, fall back to allocating a new skb
5736 * and filling it in.
5738 spin_lock_irq(&head->lock);
5739 skb = skb_peek(head);
5741 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5743 if (fpl->count < SCM_MAX_FD) {
5744 __skb_unlink(skb, head);
5745 spin_unlock_irq(&head->lock);
5746 fpl->fp[fpl->count] = get_file(file);
5747 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5749 spin_lock_irq(&head->lock);
5750 __skb_queue_head(head, skb);
5755 spin_unlock_irq(&head->lock);
5762 return __io_sqe_files_scm(ctx, 1, index);
5768 static void io_atomic_switch(struct percpu_ref *ref)
5770 struct fixed_file_data *data;
5772 data = container_of(ref, struct fixed_file_data, refs);
5773 clear_bit(FFD_F_ATOMIC, &data->state);
5776 static bool io_queue_file_removal(struct fixed_file_data *data,
5779 struct io_file_put *pfile, pfile_stack;
5780 DECLARE_COMPLETION_ONSTACK(done);
5783 * If we fail allocating the struct we need for doing async reomval
5784 * of this file, just punt to sync and wait for it.
5786 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5788 pfile = &pfile_stack;
5789 pfile->done = &done;
5793 llist_add(&pfile->llist, &data->put_llist);
5795 if (pfile == &pfile_stack) {
5796 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5797 percpu_ref_put(&data->refs);
5798 percpu_ref_switch_to_atomic(&data->refs,
5801 wait_for_completion(&done);
5802 flush_work(&data->ref_work);
5809 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5810 struct io_uring_files_update *up,
5813 struct fixed_file_data *data = ctx->file_data;
5814 bool ref_switch = false;
5820 if (check_add_overflow(up->offset, nr_args, &done))
5822 if (done > ctx->nr_user_files)
5826 fds = u64_to_user_ptr(up->fds);
5828 struct fixed_file_table *table;
5832 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5836 i = array_index_nospec(up->offset, ctx->nr_user_files);
5837 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5838 index = i & IORING_FILE_TABLE_MASK;
5839 if (table->files[index]) {
5840 file = io_file_from_index(ctx, index);
5841 table->files[index] = NULL;
5842 if (io_queue_file_removal(data, file))
5852 * Don't allow io_uring instances to be registered. If
5853 * UNIX isn't enabled, then this causes a reference
5854 * cycle and this instance can never get freed. If UNIX
5855 * is enabled we'll handle it just fine, but there's
5856 * still no point in allowing a ring fd as it doesn't
5857 * support regular read/write anyway.
5859 if (file->f_op == &io_uring_fops) {
5864 table->files[index] = file;
5865 err = io_sqe_file_register(ctx, file, i);
5874 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5875 percpu_ref_put(&data->refs);
5876 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5879 return done ? done : err;
5881 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5884 struct io_uring_files_update up;
5886 if (!ctx->file_data)
5890 if (copy_from_user(&up, arg, sizeof(up)))
5895 return __io_sqe_files_update(ctx, &up, nr_args);
5898 static void io_put_work(struct io_wq_work *work)
5900 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5905 static void io_get_work(struct io_wq_work *work)
5907 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5909 refcount_inc(&req->refs);
5912 static int io_init_wq_offload(struct io_ring_ctx *ctx,
5913 struct io_uring_params *p)
5915 struct io_wq_data data;
5917 struct io_ring_ctx *ctx_attach;
5918 unsigned int concurrency;
5921 data.user = ctx->user;
5922 data.get_work = io_get_work;
5923 data.put_work = io_put_work;
5925 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
5926 /* Do QD, or 4 * CPUS, whatever is smallest */
5927 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5929 ctx->io_wq = io_wq_create(concurrency, &data);
5930 if (IS_ERR(ctx->io_wq)) {
5931 ret = PTR_ERR(ctx->io_wq);
5937 f = fdget(p->wq_fd);
5941 if (f.file->f_op != &io_uring_fops) {
5946 ctx_attach = f.file->private_data;
5947 /* @io_wq is protected by holding the fd */
5948 if (!io_wq_get(ctx_attach->io_wq, &data)) {
5953 ctx->io_wq = ctx_attach->io_wq;
5959 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5960 struct io_uring_params *p)
5964 init_waitqueue_head(&ctx->sqo_wait);
5965 mmgrab(current->mm);
5966 ctx->sqo_mm = current->mm;
5968 if (ctx->flags & IORING_SETUP_SQPOLL) {
5970 if (!capable(CAP_SYS_ADMIN))
5973 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5974 if (!ctx->sq_thread_idle)
5975 ctx->sq_thread_idle = HZ;
5977 if (p->flags & IORING_SETUP_SQ_AFF) {
5978 int cpu = p->sq_thread_cpu;
5981 if (cpu >= nr_cpu_ids)
5983 if (!cpu_online(cpu))
5986 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5990 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5993 if (IS_ERR(ctx->sqo_thread)) {
5994 ret = PTR_ERR(ctx->sqo_thread);
5995 ctx->sqo_thread = NULL;
5998 wake_up_process(ctx->sqo_thread);
5999 } else if (p->flags & IORING_SETUP_SQ_AFF) {
6000 /* Can't have SQ_AFF without SQPOLL */
6005 ret = io_init_wq_offload(ctx, p);
6011 io_finish_async(ctx);
6012 mmdrop(ctx->sqo_mm);
6017 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
6019 atomic_long_sub(nr_pages, &user->locked_vm);
6022 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
6024 unsigned long page_limit, cur_pages, new_pages;
6026 /* Don't allow more pages than we can safely lock */
6027 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
6030 cur_pages = atomic_long_read(&user->locked_vm);
6031 new_pages = cur_pages + nr_pages;
6032 if (new_pages > page_limit)
6034 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
6035 new_pages) != cur_pages);
6040 static void io_mem_free(void *ptr)
6047 page = virt_to_head_page(ptr);
6048 if (put_page_testzero(page))
6049 free_compound_page(page);
6052 static void *io_mem_alloc(size_t size)
6054 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
6057 return (void *) __get_free_pages(gfp_flags, get_order(size));
6060 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
6063 struct io_rings *rings;
6064 size_t off, sq_array_size;
6066 off = struct_size(rings, cqes, cq_entries);
6067 if (off == SIZE_MAX)
6071 off = ALIGN(off, SMP_CACHE_BYTES);
6076 sq_array_size = array_size(sizeof(u32), sq_entries);
6077 if (sq_array_size == SIZE_MAX)
6080 if (check_add_overflow(off, sq_array_size, &off))
6089 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
6093 pages = (size_t)1 << get_order(
6094 rings_size(sq_entries, cq_entries, NULL));
6095 pages += (size_t)1 << get_order(
6096 array_size(sizeof(struct io_uring_sqe), sq_entries));
6101 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6105 if (!ctx->user_bufs)
6108 for (i = 0; i < ctx->nr_user_bufs; i++) {
6109 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6111 for (j = 0; j < imu->nr_bvecs; j++)
6112 unpin_user_page(imu->bvec[j].bv_page);
6114 if (ctx->account_mem)
6115 io_unaccount_mem(ctx->user, imu->nr_bvecs);
6120 kfree(ctx->user_bufs);
6121 ctx->user_bufs = NULL;
6122 ctx->nr_user_bufs = 0;
6126 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6127 void __user *arg, unsigned index)
6129 struct iovec __user *src;
6131 #ifdef CONFIG_COMPAT
6133 struct compat_iovec __user *ciovs;
6134 struct compat_iovec ciov;
6136 ciovs = (struct compat_iovec __user *) arg;
6137 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6140 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
6141 dst->iov_len = ciov.iov_len;
6145 src = (struct iovec __user *) arg;
6146 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6151 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6154 struct vm_area_struct **vmas = NULL;
6155 struct page **pages = NULL;
6156 int i, j, got_pages = 0;
6161 if (!nr_args || nr_args > UIO_MAXIOV)
6164 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6166 if (!ctx->user_bufs)
6169 for (i = 0; i < nr_args; i++) {
6170 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6171 unsigned long off, start, end, ubuf;
6176 ret = io_copy_iov(ctx, &iov, arg, i);
6181 * Don't impose further limits on the size and buffer
6182 * constraints here, we'll -EINVAL later when IO is
6183 * submitted if they are wrong.
6186 if (!iov.iov_base || !iov.iov_len)
6189 /* arbitrary limit, but we need something */
6190 if (iov.iov_len > SZ_1G)
6193 ubuf = (unsigned long) iov.iov_base;
6194 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6195 start = ubuf >> PAGE_SHIFT;
6196 nr_pages = end - start;
6198 if (ctx->account_mem) {
6199 ret = io_account_mem(ctx->user, nr_pages);
6205 if (!pages || nr_pages > got_pages) {
6208 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
6210 vmas = kvmalloc_array(nr_pages,
6211 sizeof(struct vm_area_struct *),
6213 if (!pages || !vmas) {
6215 if (ctx->account_mem)
6216 io_unaccount_mem(ctx->user, nr_pages);
6219 got_pages = nr_pages;
6222 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
6226 if (ctx->account_mem)
6227 io_unaccount_mem(ctx->user, nr_pages);
6232 down_read(¤t->mm->mmap_sem);
6233 pret = pin_user_pages(ubuf, nr_pages,
6234 FOLL_WRITE | FOLL_LONGTERM,
6236 if (pret == nr_pages) {
6237 /* don't support file backed memory */
6238 for (j = 0; j < nr_pages; j++) {
6239 struct vm_area_struct *vma = vmas[j];
6242 !is_file_hugepages(vma->vm_file)) {
6248 ret = pret < 0 ? pret : -EFAULT;
6250 up_read(¤t->mm->mmap_sem);
6253 * if we did partial map, or found file backed vmas,
6254 * release any pages we did get
6257 unpin_user_pages(pages, pret);
6258 if (ctx->account_mem)
6259 io_unaccount_mem(ctx->user, nr_pages);
6264 off = ubuf & ~PAGE_MASK;
6266 for (j = 0; j < nr_pages; j++) {
6269 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6270 imu->bvec[j].bv_page = pages[j];
6271 imu->bvec[j].bv_len = vec_len;
6272 imu->bvec[j].bv_offset = off;
6276 /* store original address for later verification */
6278 imu->len = iov.iov_len;
6279 imu->nr_bvecs = nr_pages;
6281 ctx->nr_user_bufs++;
6289 io_sqe_buffer_unregister(ctx);
6293 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6295 __s32 __user *fds = arg;
6301 if (copy_from_user(&fd, fds, sizeof(*fds)))
6304 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6305 if (IS_ERR(ctx->cq_ev_fd)) {
6306 int ret = PTR_ERR(ctx->cq_ev_fd);
6307 ctx->cq_ev_fd = NULL;
6314 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6316 if (ctx->cq_ev_fd) {
6317 eventfd_ctx_put(ctx->cq_ev_fd);
6318 ctx->cq_ev_fd = NULL;
6325 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6327 io_finish_async(ctx);
6329 mmdrop(ctx->sqo_mm);
6331 io_iopoll_reap_events(ctx);
6332 io_sqe_buffer_unregister(ctx);
6333 io_sqe_files_unregister(ctx);
6334 io_eventfd_unregister(ctx);
6336 #if defined(CONFIG_UNIX)
6337 if (ctx->ring_sock) {
6338 ctx->ring_sock->file = NULL; /* so that iput() is called */
6339 sock_release(ctx->ring_sock);
6343 io_mem_free(ctx->rings);
6344 io_mem_free(ctx->sq_sqes);
6346 percpu_ref_exit(&ctx->refs);
6347 if (ctx->account_mem)
6348 io_unaccount_mem(ctx->user,
6349 ring_pages(ctx->sq_entries, ctx->cq_entries));
6350 free_uid(ctx->user);
6351 put_cred(ctx->creds);
6352 kfree(ctx->completions);
6353 kfree(ctx->cancel_hash);
6354 kmem_cache_free(req_cachep, ctx->fallback_req);
6358 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6360 struct io_ring_ctx *ctx = file->private_data;
6363 poll_wait(file, &ctx->cq_wait, wait);
6365 * synchronizes with barrier from wq_has_sleeper call in
6369 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6370 ctx->rings->sq_ring_entries)
6371 mask |= EPOLLOUT | EPOLLWRNORM;
6372 if (io_cqring_events(ctx, false))
6373 mask |= EPOLLIN | EPOLLRDNORM;
6378 static int io_uring_fasync(int fd, struct file *file, int on)
6380 struct io_ring_ctx *ctx = file->private_data;
6382 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6385 static int io_remove_personalities(int id, void *p, void *data)
6387 struct io_ring_ctx *ctx = data;
6388 const struct cred *cred;
6390 cred = idr_remove(&ctx->personality_idr, id);
6396 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6398 mutex_lock(&ctx->uring_lock);
6399 percpu_ref_kill(&ctx->refs);
6400 mutex_unlock(&ctx->uring_lock);
6403 * Wait for sq thread to idle, if we have one. It won't spin on new
6404 * work after we've killed the ctx ref above. This is important to do
6405 * before we cancel existing commands, as the thread could otherwise
6406 * be queueing new work post that. If that's work we need to cancel,
6407 * it could cause shutdown to hang.
6409 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
6412 io_kill_timeouts(ctx);
6413 io_poll_remove_all(ctx);
6416 io_wq_cancel_all(ctx->io_wq);
6418 io_iopoll_reap_events(ctx);
6419 /* if we failed setting up the ctx, we might not have any rings */
6421 io_cqring_overflow_flush(ctx, true);
6422 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
6423 wait_for_completion(&ctx->completions[0]);
6424 io_ring_ctx_free(ctx);
6427 static int io_uring_release(struct inode *inode, struct file *file)
6429 struct io_ring_ctx *ctx = file->private_data;
6431 file->private_data = NULL;
6432 io_ring_ctx_wait_and_kill(ctx);
6436 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6437 struct files_struct *files)
6439 struct io_kiocb *req;
6442 while (!list_empty_careful(&ctx->inflight_list)) {
6443 struct io_kiocb *cancel_req = NULL;
6445 spin_lock_irq(&ctx->inflight_lock);
6446 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
6447 if (req->work.files != files)
6449 /* req is being completed, ignore */
6450 if (!refcount_inc_not_zero(&req->refs))
6456 prepare_to_wait(&ctx->inflight_wait, &wait,
6457 TASK_UNINTERRUPTIBLE);
6458 spin_unlock_irq(&ctx->inflight_lock);
6460 /* We need to keep going until we don't find a matching req */
6464 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6465 io_put_req(cancel_req);
6468 finish_wait(&ctx->inflight_wait, &wait);
6471 static int io_uring_flush(struct file *file, void *data)
6473 struct io_ring_ctx *ctx = file->private_data;
6475 io_uring_cancel_files(ctx, data);
6479 static void *io_uring_validate_mmap_request(struct file *file,
6480 loff_t pgoff, size_t sz)
6482 struct io_ring_ctx *ctx = file->private_data;
6483 loff_t offset = pgoff << PAGE_SHIFT;
6488 case IORING_OFF_SQ_RING:
6489 case IORING_OFF_CQ_RING:
6492 case IORING_OFF_SQES:
6496 return ERR_PTR(-EINVAL);
6499 page = virt_to_head_page(ptr);
6500 if (sz > page_size(page))
6501 return ERR_PTR(-EINVAL);
6508 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6510 size_t sz = vma->vm_end - vma->vm_start;
6514 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6516 return PTR_ERR(ptr);
6518 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6519 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6522 #else /* !CONFIG_MMU */
6524 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6526 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6529 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6531 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6534 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6535 unsigned long addr, unsigned long len,
6536 unsigned long pgoff, unsigned long flags)
6540 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6542 return PTR_ERR(ptr);
6544 return (unsigned long) ptr;
6547 #endif /* !CONFIG_MMU */
6549 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6550 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6553 struct io_ring_ctx *ctx;
6558 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
6566 if (f.file->f_op != &io_uring_fops)
6570 ctx = f.file->private_data;
6571 if (!percpu_ref_tryget(&ctx->refs))
6575 * For SQ polling, the thread will do all submissions and completions.
6576 * Just return the requested submit count, and wake the thread if
6580 if (ctx->flags & IORING_SETUP_SQPOLL) {
6581 if (!list_empty_careful(&ctx->cq_overflow_list))
6582 io_cqring_overflow_flush(ctx, false);
6583 if (flags & IORING_ENTER_SQ_WAKEUP)
6584 wake_up(&ctx->sqo_wait);
6585 submitted = to_submit;
6586 } else if (to_submit) {
6587 struct mm_struct *cur_mm;
6589 mutex_lock(&ctx->uring_lock);
6590 /* already have mm, so io_submit_sqes() won't try to grab it */
6591 cur_mm = ctx->sqo_mm;
6592 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6594 mutex_unlock(&ctx->uring_lock);
6596 if (submitted != to_submit)
6599 if (flags & IORING_ENTER_GETEVENTS) {
6600 unsigned nr_events = 0;
6602 min_complete = min(min_complete, ctx->cq_entries);
6604 if (ctx->flags & IORING_SETUP_IOPOLL) {
6605 ret = io_iopoll_check(ctx, &nr_events, min_complete);
6607 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6612 percpu_ref_put(&ctx->refs);
6615 return submitted ? submitted : ret;
6618 static int io_uring_show_cred(int id, void *p, void *data)
6620 const struct cred *cred = p;
6621 struct seq_file *m = data;
6622 struct user_namespace *uns = seq_user_ns(m);
6623 struct group_info *gi;
6628 seq_printf(m, "%5d\n", id);
6629 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
6630 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
6631 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
6632 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
6633 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
6634 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
6635 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
6636 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
6637 seq_puts(m, "\n\tGroups:\t");
6638 gi = cred->group_info;
6639 for (g = 0; g < gi->ngroups; g++) {
6640 seq_put_decimal_ull(m, g ? " " : "",
6641 from_kgid_munged(uns, gi->gid[g]));
6643 seq_puts(m, "\n\tCapEff:\t");
6644 cap = cred->cap_effective;
6645 CAP_FOR_EACH_U32(__capi)
6646 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
6651 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
6655 mutex_lock(&ctx->uring_lock);
6656 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
6657 for (i = 0; i < ctx->nr_user_files; i++) {
6658 struct fixed_file_table *table;
6661 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6662 f = table->files[i & IORING_FILE_TABLE_MASK];
6664 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
6666 seq_printf(m, "%5u: <none>\n", i);
6668 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
6669 for (i = 0; i < ctx->nr_user_bufs; i++) {
6670 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
6672 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
6673 (unsigned int) buf->len);
6675 if (!idr_is_empty(&ctx->personality_idr)) {
6676 seq_printf(m, "Personalities:\n");
6677 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
6679 mutex_unlock(&ctx->uring_lock);
6682 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
6684 struct io_ring_ctx *ctx = f->private_data;
6686 if (percpu_ref_tryget(&ctx->refs)) {
6687 __io_uring_show_fdinfo(ctx, m);
6688 percpu_ref_put(&ctx->refs);
6692 static const struct file_operations io_uring_fops = {
6693 .release = io_uring_release,
6694 .flush = io_uring_flush,
6695 .mmap = io_uring_mmap,
6697 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6698 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6700 .poll = io_uring_poll,
6701 .fasync = io_uring_fasync,
6702 .show_fdinfo = io_uring_show_fdinfo,
6705 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6706 struct io_uring_params *p)
6708 struct io_rings *rings;
6709 size_t size, sq_array_offset;
6711 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6712 if (size == SIZE_MAX)
6715 rings = io_mem_alloc(size);
6720 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6721 rings->sq_ring_mask = p->sq_entries - 1;
6722 rings->cq_ring_mask = p->cq_entries - 1;
6723 rings->sq_ring_entries = p->sq_entries;
6724 rings->cq_ring_entries = p->cq_entries;
6725 ctx->sq_mask = rings->sq_ring_mask;
6726 ctx->cq_mask = rings->cq_ring_mask;
6727 ctx->sq_entries = rings->sq_ring_entries;
6728 ctx->cq_entries = rings->cq_ring_entries;
6730 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6731 if (size == SIZE_MAX) {
6732 io_mem_free(ctx->rings);
6737 ctx->sq_sqes = io_mem_alloc(size);
6738 if (!ctx->sq_sqes) {
6739 io_mem_free(ctx->rings);
6748 * Allocate an anonymous fd, this is what constitutes the application
6749 * visible backing of an io_uring instance. The application mmaps this
6750 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6751 * we have to tie this fd to a socket for file garbage collection purposes.
6753 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6758 #if defined(CONFIG_UNIX)
6759 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6765 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6769 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6770 O_RDWR | O_CLOEXEC);
6773 ret = PTR_ERR(file);
6777 #if defined(CONFIG_UNIX)
6778 ctx->ring_sock->file = file;
6780 fd_install(ret, file);
6783 #if defined(CONFIG_UNIX)
6784 sock_release(ctx->ring_sock);
6785 ctx->ring_sock = NULL;
6790 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6792 struct user_struct *user = NULL;
6793 struct io_ring_ctx *ctx;
6799 if (entries > IORING_MAX_ENTRIES) {
6800 if (!(p->flags & IORING_SETUP_CLAMP))
6802 entries = IORING_MAX_ENTRIES;
6806 * Use twice as many entries for the CQ ring. It's possible for the
6807 * application to drive a higher depth than the size of the SQ ring,
6808 * since the sqes are only used at submission time. This allows for
6809 * some flexibility in overcommitting a bit. If the application has
6810 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6811 * of CQ ring entries manually.
6813 p->sq_entries = roundup_pow_of_two(entries);
6814 if (p->flags & IORING_SETUP_CQSIZE) {
6816 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6817 * to a power-of-two, if it isn't already. We do NOT impose
6818 * any cq vs sq ring sizing.
6820 if (p->cq_entries < p->sq_entries)
6822 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6823 if (!(p->flags & IORING_SETUP_CLAMP))
6825 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6827 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6829 p->cq_entries = 2 * p->sq_entries;
6832 user = get_uid(current_user());
6833 account_mem = !capable(CAP_IPC_LOCK);
6836 ret = io_account_mem(user,
6837 ring_pages(p->sq_entries, p->cq_entries));
6844 ctx = io_ring_ctx_alloc(p);
6847 io_unaccount_mem(user, ring_pages(p->sq_entries,
6852 ctx->compat = in_compat_syscall();
6853 ctx->account_mem = account_mem;
6855 ctx->creds = get_current_cred();
6857 ret = io_allocate_scq_urings(ctx, p);
6861 ret = io_sq_offload_start(ctx, p);
6865 memset(&p->sq_off, 0, sizeof(p->sq_off));
6866 p->sq_off.head = offsetof(struct io_rings, sq.head);
6867 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6868 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6869 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6870 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6871 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6872 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6874 memset(&p->cq_off, 0, sizeof(p->cq_off));
6875 p->cq_off.head = offsetof(struct io_rings, cq.head);
6876 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6877 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6878 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6879 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6880 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6883 * Install ring fd as the very last thing, so we don't risk someone
6884 * having closed it before we finish setup
6886 ret = io_uring_get_fd(ctx);
6890 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6891 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6892 IORING_FEAT_CUR_PERSONALITY;
6893 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6896 io_ring_ctx_wait_and_kill(ctx);
6901 * Sets up an aio uring context, and returns the fd. Applications asks for a
6902 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6903 * params structure passed in.
6905 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6907 struct io_uring_params p;
6911 if (copy_from_user(&p, params, sizeof(p)))
6913 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6918 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6919 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6920 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
6923 ret = io_uring_create(entries, &p);
6927 if (copy_to_user(params, &p, sizeof(p)))
6933 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6934 struct io_uring_params __user *, params)
6936 return io_uring_setup(entries, params);
6939 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6941 struct io_uring_probe *p;
6945 size = struct_size(p, ops, nr_args);
6946 if (size == SIZE_MAX)
6948 p = kzalloc(size, GFP_KERNEL);
6953 if (copy_from_user(p, arg, size))
6956 if (memchr_inv(p, 0, size))
6959 p->last_op = IORING_OP_LAST - 1;
6960 if (nr_args > IORING_OP_LAST)
6961 nr_args = IORING_OP_LAST;
6963 for (i = 0; i < nr_args; i++) {
6965 if (!io_op_defs[i].not_supported)
6966 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6971 if (copy_to_user(arg, p, size))
6978 static int io_register_personality(struct io_ring_ctx *ctx)
6980 const struct cred *creds = get_current_cred();
6983 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
6984 USHRT_MAX, GFP_KERNEL);
6990 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
6992 const struct cred *old_creds;
6994 old_creds = idr_remove(&ctx->personality_idr, id);
6996 put_cred(old_creds);
7003 static bool io_register_op_must_quiesce(int op)
7006 case IORING_UNREGISTER_FILES:
7007 case IORING_REGISTER_FILES_UPDATE:
7008 case IORING_REGISTER_PROBE:
7009 case IORING_REGISTER_PERSONALITY:
7010 case IORING_UNREGISTER_PERSONALITY:
7017 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
7018 void __user *arg, unsigned nr_args)
7019 __releases(ctx->uring_lock)
7020 __acquires(ctx->uring_lock)
7025 * We're inside the ring mutex, if the ref is already dying, then
7026 * someone else killed the ctx or is already going through
7027 * io_uring_register().
7029 if (percpu_ref_is_dying(&ctx->refs))
7032 if (io_register_op_must_quiesce(opcode)) {
7033 percpu_ref_kill(&ctx->refs);
7036 * Drop uring mutex before waiting for references to exit. If
7037 * another thread is currently inside io_uring_enter() it might
7038 * need to grab the uring_lock to make progress. If we hold it
7039 * here across the drain wait, then we can deadlock. It's safe
7040 * to drop the mutex here, since no new references will come in
7041 * after we've killed the percpu ref.
7043 mutex_unlock(&ctx->uring_lock);
7044 ret = wait_for_completion_interruptible(&ctx->completions[0]);
7045 mutex_lock(&ctx->uring_lock);
7047 percpu_ref_resurrect(&ctx->refs);
7054 case IORING_REGISTER_BUFFERS:
7055 ret = io_sqe_buffer_register(ctx, arg, nr_args);
7057 case IORING_UNREGISTER_BUFFERS:
7061 ret = io_sqe_buffer_unregister(ctx);
7063 case IORING_REGISTER_FILES:
7064 ret = io_sqe_files_register(ctx, arg, nr_args);
7066 case IORING_UNREGISTER_FILES:
7070 ret = io_sqe_files_unregister(ctx);
7072 case IORING_REGISTER_FILES_UPDATE:
7073 ret = io_sqe_files_update(ctx, arg, nr_args);
7075 case IORING_REGISTER_EVENTFD:
7076 case IORING_REGISTER_EVENTFD_ASYNC:
7080 ret = io_eventfd_register(ctx, arg);
7083 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
7084 ctx->eventfd_async = 1;
7086 ctx->eventfd_async = 0;
7088 case IORING_UNREGISTER_EVENTFD:
7092 ret = io_eventfd_unregister(ctx);
7094 case IORING_REGISTER_PROBE:
7096 if (!arg || nr_args > 256)
7098 ret = io_probe(ctx, arg, nr_args);
7100 case IORING_REGISTER_PERSONALITY:
7104 ret = io_register_personality(ctx);
7106 case IORING_UNREGISTER_PERSONALITY:
7110 ret = io_unregister_personality(ctx, nr_args);
7117 if (io_register_op_must_quiesce(opcode)) {
7118 /* bring the ctx back to life */
7119 percpu_ref_reinit(&ctx->refs);
7121 reinit_completion(&ctx->completions[0]);
7126 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7127 void __user *, arg, unsigned int, nr_args)
7129 struct io_ring_ctx *ctx;
7138 if (f.file->f_op != &io_uring_fops)
7141 ctx = f.file->private_data;
7143 mutex_lock(&ctx->uring_lock);
7144 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7145 mutex_unlock(&ctx->uring_lock);
7146 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
7147 ctx->cq_ev_fd != NULL, ret);
7153 static int __init io_uring_init(void)
7155 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7156 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7157 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7160 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7161 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7162 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7163 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7164 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7165 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7166 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7167 BUILD_BUG_SQE_ELEM(8, __u64, off);
7168 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7169 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7170 BUILD_BUG_SQE_ELEM(24, __u32, len);
7171 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7172 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7173 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7174 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7175 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
7176 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7177 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7178 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7179 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7180 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7181 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7182 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7183 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7184 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7185 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7186 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7188 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7189 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
7192 __initcall(io_uring_init);