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;
445 struct sockaddr_storage addr;
449 struct iovec fast_iov[UIO_FASTIOV];
455 struct io_async_ctx {
457 struct io_async_rw rw;
458 struct io_async_msghdr msg;
459 struct io_async_connect connect;
460 struct io_timeout_data timeout;
465 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
466 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
467 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
468 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
469 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
476 REQ_F_IOPOLL_COMPLETED_BIT,
477 REQ_F_LINK_TIMEOUT_BIT,
481 REQ_F_TIMEOUT_NOSEQ_BIT,
482 REQ_F_COMP_LOCKED_BIT,
483 REQ_F_NEED_CLEANUP_BIT,
489 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
490 /* drain existing IO first */
491 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
493 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
494 /* doesn't sever on completion < 0 */
495 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
497 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
499 /* already grabbed next link */
500 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
501 /* fail rest of links */
502 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
503 /* on inflight list */
504 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
505 /* read/write uses file position */
506 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
507 /* must not punt to workers */
508 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
509 /* polled IO has completed */
510 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
511 /* has linked timeout */
512 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
513 /* timeout request */
514 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
516 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
517 /* must be punted even for NONBLOCK */
518 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
519 /* no timeout sequence */
520 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
521 /* completion under lock */
522 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
524 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
525 /* in overflow list */
526 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
530 * NOTE! Each of the iocb union members has the file pointer
531 * as the first entry in their struct definition. So you can
532 * access the file pointer through any of the sub-structs,
533 * or directly as just 'ki_filp' in this struct.
539 struct io_poll_iocb poll;
540 struct io_accept accept;
542 struct io_cancel cancel;
543 struct io_timeout timeout;
544 struct io_connect connect;
545 struct io_sr_msg sr_msg;
547 struct io_close close;
548 struct io_files_update files_update;
549 struct io_fadvise fadvise;
550 struct io_madvise madvise;
551 struct io_epoll epoll;
554 struct io_async_ctx *io;
556 * llist_node is only used for poll deferred completions
558 struct llist_node llist_node;
560 bool needs_fixed_file;
563 struct io_ring_ctx *ctx;
565 struct list_head list;
566 struct hlist_node hash_node;
568 struct list_head link_list;
575 struct list_head inflight_entry;
577 struct io_wq_work work;
580 #define IO_PLUG_THRESHOLD 2
581 #define IO_IOPOLL_BATCH 8
583 struct io_submit_state {
584 struct blk_plug plug;
587 * io_kiocb alloc cache
589 void *reqs[IO_IOPOLL_BATCH];
590 unsigned int free_reqs;
593 * File reference cache
597 unsigned int has_refs;
598 unsigned int used_refs;
599 unsigned int ios_left;
603 /* needs req->io allocated for deferral/async */
604 unsigned async_ctx : 1;
605 /* needs current->mm setup, does mm access */
606 unsigned needs_mm : 1;
607 /* needs req->file assigned */
608 unsigned needs_file : 1;
609 /* needs req->file assigned IFF fd is >= 0 */
610 unsigned fd_non_neg : 1;
611 /* hash wq insertion if file is a regular file */
612 unsigned hash_reg_file : 1;
613 /* unbound wq insertion if file is a non-regular file */
614 unsigned unbound_nonreg_file : 1;
615 /* opcode is not supported by this kernel */
616 unsigned not_supported : 1;
617 /* needs file table */
618 unsigned file_table : 1;
620 unsigned needs_fs : 1;
623 static const struct io_op_def io_op_defs[] = {
624 [IORING_OP_NOP] = {},
625 [IORING_OP_READV] = {
629 .unbound_nonreg_file = 1,
631 [IORING_OP_WRITEV] = {
636 .unbound_nonreg_file = 1,
638 [IORING_OP_FSYNC] = {
641 [IORING_OP_READ_FIXED] = {
643 .unbound_nonreg_file = 1,
645 [IORING_OP_WRITE_FIXED] = {
648 .unbound_nonreg_file = 1,
650 [IORING_OP_POLL_ADD] = {
652 .unbound_nonreg_file = 1,
654 [IORING_OP_POLL_REMOVE] = {},
655 [IORING_OP_SYNC_FILE_RANGE] = {
658 [IORING_OP_SENDMSG] = {
662 .unbound_nonreg_file = 1,
665 [IORING_OP_RECVMSG] = {
669 .unbound_nonreg_file = 1,
672 [IORING_OP_TIMEOUT] = {
676 [IORING_OP_TIMEOUT_REMOVE] = {},
677 [IORING_OP_ACCEPT] = {
680 .unbound_nonreg_file = 1,
683 [IORING_OP_ASYNC_CANCEL] = {},
684 [IORING_OP_LINK_TIMEOUT] = {
688 [IORING_OP_CONNECT] = {
692 .unbound_nonreg_file = 1,
694 [IORING_OP_FALLOCATE] = {
697 [IORING_OP_OPENAT] = {
703 [IORING_OP_CLOSE] = {
707 [IORING_OP_FILES_UPDATE] = {
711 [IORING_OP_STATX] = {
720 .unbound_nonreg_file = 1,
722 [IORING_OP_WRITE] = {
725 .unbound_nonreg_file = 1,
727 [IORING_OP_FADVISE] = {
730 [IORING_OP_MADVISE] = {
736 .unbound_nonreg_file = 1,
741 .unbound_nonreg_file = 1,
743 [IORING_OP_OPENAT2] = {
749 [IORING_OP_EPOLL_CTL] = {
750 .unbound_nonreg_file = 1,
755 static void io_wq_submit_work(struct io_wq_work **workptr);
756 static void io_cqring_fill_event(struct io_kiocb *req, long res);
757 static void io_put_req(struct io_kiocb *req);
758 static void __io_double_put_req(struct io_kiocb *req);
759 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
760 static void io_queue_linked_timeout(struct io_kiocb *req);
761 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
762 struct io_uring_files_update *ip,
764 static int io_grab_files(struct io_kiocb *req);
765 static void io_ring_file_ref_flush(struct fixed_file_data *data);
766 static void io_cleanup_req(struct io_kiocb *req);
768 static struct kmem_cache *req_cachep;
770 static const struct file_operations io_uring_fops;
772 struct sock *io_uring_get_socket(struct file *file)
774 #if defined(CONFIG_UNIX)
775 if (file->f_op == &io_uring_fops) {
776 struct io_ring_ctx *ctx = file->private_data;
778 return ctx->ring_sock->sk;
783 EXPORT_SYMBOL(io_uring_get_socket);
785 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
787 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
789 complete(&ctx->completions[0]);
792 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
794 struct io_ring_ctx *ctx;
797 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
801 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
802 if (!ctx->fallback_req)
805 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
806 if (!ctx->completions)
810 * Use 5 bits less than the max cq entries, that should give us around
811 * 32 entries per hash list if totally full and uniformly spread.
813 hash_bits = ilog2(p->cq_entries);
817 ctx->cancel_hash_bits = hash_bits;
818 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
820 if (!ctx->cancel_hash)
822 __hash_init(ctx->cancel_hash, 1U << hash_bits);
824 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
825 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
828 ctx->flags = p->flags;
829 init_waitqueue_head(&ctx->cq_wait);
830 INIT_LIST_HEAD(&ctx->cq_overflow_list);
831 init_completion(&ctx->completions[0]);
832 init_completion(&ctx->completions[1]);
833 idr_init(&ctx->personality_idr);
834 mutex_init(&ctx->uring_lock);
835 init_waitqueue_head(&ctx->wait);
836 spin_lock_init(&ctx->completion_lock);
837 init_llist_head(&ctx->poll_llist);
838 INIT_LIST_HEAD(&ctx->poll_list);
839 INIT_LIST_HEAD(&ctx->defer_list);
840 INIT_LIST_HEAD(&ctx->timeout_list);
841 init_waitqueue_head(&ctx->inflight_wait);
842 spin_lock_init(&ctx->inflight_lock);
843 INIT_LIST_HEAD(&ctx->inflight_list);
846 if (ctx->fallback_req)
847 kmem_cache_free(req_cachep, ctx->fallback_req);
848 kfree(ctx->completions);
849 kfree(ctx->cancel_hash);
854 static inline bool __req_need_defer(struct io_kiocb *req)
856 struct io_ring_ctx *ctx = req->ctx;
858 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
859 + atomic_read(&ctx->cached_cq_overflow);
862 static inline bool req_need_defer(struct io_kiocb *req)
864 if (unlikely(req->flags & REQ_F_IO_DRAIN))
865 return __req_need_defer(req);
870 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
872 struct io_kiocb *req;
874 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
875 if (req && !req_need_defer(req)) {
876 list_del_init(&req->list);
883 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
885 struct io_kiocb *req;
887 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
889 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
891 if (!__req_need_defer(req)) {
892 list_del_init(&req->list);
900 static void __io_commit_cqring(struct io_ring_ctx *ctx)
902 struct io_rings *rings = ctx->rings;
904 /* order cqe stores with ring update */
905 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
907 if (wq_has_sleeper(&ctx->cq_wait)) {
908 wake_up_interruptible(&ctx->cq_wait);
909 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
913 static inline void io_req_work_grab_env(struct io_kiocb *req,
914 const struct io_op_def *def)
916 if (!req->work.mm && def->needs_mm) {
918 req->work.mm = current->mm;
920 if (!req->work.creds)
921 req->work.creds = get_current_cred();
922 if (!req->work.fs && def->needs_fs) {
923 spin_lock(¤t->fs->lock);
924 if (!current->fs->in_exec) {
925 req->work.fs = current->fs;
926 req->work.fs->users++;
928 req->work.flags |= IO_WQ_WORK_CANCEL;
930 spin_unlock(¤t->fs->lock);
932 if (!req->work.task_pid)
933 req->work.task_pid = task_pid_vnr(current);
936 static inline void io_req_work_drop_env(struct io_kiocb *req)
939 mmdrop(req->work.mm);
942 if (req->work.creds) {
943 put_cred(req->work.creds);
944 req->work.creds = NULL;
947 struct fs_struct *fs = req->work.fs;
949 spin_lock(&req->work.fs->lock);
952 spin_unlock(&req->work.fs->lock);
958 static inline bool io_prep_async_work(struct io_kiocb *req,
959 struct io_kiocb **link)
961 const struct io_op_def *def = &io_op_defs[req->opcode];
962 bool do_hashed = false;
964 if (req->flags & REQ_F_ISREG) {
965 if (def->hash_reg_file)
968 if (def->unbound_nonreg_file)
969 req->work.flags |= IO_WQ_WORK_UNBOUND;
972 io_req_work_grab_env(req, def);
974 *link = io_prep_linked_timeout(req);
978 static inline void io_queue_async_work(struct io_kiocb *req)
980 struct io_ring_ctx *ctx = req->ctx;
981 struct io_kiocb *link;
984 do_hashed = io_prep_async_work(req, &link);
986 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
989 io_wq_enqueue(ctx->io_wq, &req->work);
991 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
992 file_inode(req->file));
996 io_queue_linked_timeout(link);
999 static void io_kill_timeout(struct io_kiocb *req)
1003 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1005 atomic_inc(&req->ctx->cq_timeouts);
1006 list_del_init(&req->list);
1007 io_cqring_fill_event(req, 0);
1012 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1014 struct io_kiocb *req, *tmp;
1016 spin_lock_irq(&ctx->completion_lock);
1017 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1018 io_kill_timeout(req);
1019 spin_unlock_irq(&ctx->completion_lock);
1022 static void io_commit_cqring(struct io_ring_ctx *ctx)
1024 struct io_kiocb *req;
1026 while ((req = io_get_timeout_req(ctx)) != NULL)
1027 io_kill_timeout(req);
1029 __io_commit_cqring(ctx);
1031 while ((req = io_get_deferred_req(ctx)) != NULL)
1032 io_queue_async_work(req);
1035 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1037 struct io_rings *rings = ctx->rings;
1040 tail = ctx->cached_cq_tail;
1042 * writes to the cq entry need to come after reading head; the
1043 * control dependency is enough as we're using WRITE_ONCE to
1046 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1049 ctx->cached_cq_tail++;
1050 return &rings->cqes[tail & ctx->cq_mask];
1053 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1057 if (!ctx->eventfd_async)
1059 return io_wq_current_is_worker() || in_interrupt();
1062 static void __io_cqring_ev_posted(struct io_ring_ctx *ctx, bool trigger_ev)
1064 if (waitqueue_active(&ctx->wait))
1065 wake_up(&ctx->wait);
1066 if (waitqueue_active(&ctx->sqo_wait))
1067 wake_up(&ctx->sqo_wait);
1069 eventfd_signal(ctx->cq_ev_fd, 1);
1072 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1074 __io_cqring_ev_posted(ctx, io_should_trigger_evfd(ctx));
1077 /* Returns true if there are no backlogged entries after the flush */
1078 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1080 struct io_rings *rings = ctx->rings;
1081 struct io_uring_cqe *cqe;
1082 struct io_kiocb *req;
1083 unsigned long flags;
1087 if (list_empty_careful(&ctx->cq_overflow_list))
1089 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1090 rings->cq_ring_entries))
1094 spin_lock_irqsave(&ctx->completion_lock, flags);
1096 /* if force is set, the ring is going away. always drop after that */
1098 ctx->cq_overflow_flushed = 1;
1101 while (!list_empty(&ctx->cq_overflow_list)) {
1102 cqe = io_get_cqring(ctx);
1106 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1108 list_move(&req->list, &list);
1109 req->flags &= ~REQ_F_OVERFLOW;
1111 WRITE_ONCE(cqe->user_data, req->user_data);
1112 WRITE_ONCE(cqe->res, req->result);
1113 WRITE_ONCE(cqe->flags, 0);
1115 WRITE_ONCE(ctx->rings->cq_overflow,
1116 atomic_inc_return(&ctx->cached_cq_overflow));
1120 io_commit_cqring(ctx);
1122 clear_bit(0, &ctx->sq_check_overflow);
1123 clear_bit(0, &ctx->cq_check_overflow);
1125 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1126 io_cqring_ev_posted(ctx);
1128 while (!list_empty(&list)) {
1129 req = list_first_entry(&list, struct io_kiocb, list);
1130 list_del(&req->list);
1137 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1139 struct io_ring_ctx *ctx = req->ctx;
1140 struct io_uring_cqe *cqe;
1142 trace_io_uring_complete(ctx, req->user_data, res);
1145 * If we can't get a cq entry, userspace overflowed the
1146 * submission (by quite a lot). Increment the overflow count in
1149 cqe = io_get_cqring(ctx);
1151 WRITE_ONCE(cqe->user_data, req->user_data);
1152 WRITE_ONCE(cqe->res, res);
1153 WRITE_ONCE(cqe->flags, 0);
1154 } else if (ctx->cq_overflow_flushed) {
1155 WRITE_ONCE(ctx->rings->cq_overflow,
1156 atomic_inc_return(&ctx->cached_cq_overflow));
1158 if (list_empty(&ctx->cq_overflow_list)) {
1159 set_bit(0, &ctx->sq_check_overflow);
1160 set_bit(0, &ctx->cq_check_overflow);
1162 req->flags |= REQ_F_OVERFLOW;
1163 refcount_inc(&req->refs);
1165 list_add_tail(&req->list, &ctx->cq_overflow_list);
1169 static void io_cqring_add_event(struct io_kiocb *req, long res)
1171 struct io_ring_ctx *ctx = req->ctx;
1172 unsigned long flags;
1174 spin_lock_irqsave(&ctx->completion_lock, flags);
1175 io_cqring_fill_event(req, res);
1176 io_commit_cqring(ctx);
1177 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1179 io_cqring_ev_posted(ctx);
1182 static inline bool io_is_fallback_req(struct io_kiocb *req)
1184 return req == (struct io_kiocb *)
1185 ((unsigned long) req->ctx->fallback_req & ~1UL);
1188 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1190 struct io_kiocb *req;
1192 req = ctx->fallback_req;
1193 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1199 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1200 struct io_submit_state *state)
1202 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1203 struct io_kiocb *req;
1206 req = kmem_cache_alloc(req_cachep, gfp);
1209 } else if (!state->free_reqs) {
1213 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1214 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1217 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1218 * retry single alloc to be on the safe side.
1220 if (unlikely(ret <= 0)) {
1221 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1222 if (!state->reqs[0])
1226 state->free_reqs = ret - 1;
1227 req = state->reqs[ret - 1];
1230 req = state->reqs[state->free_reqs];
1238 /* one is dropped after submission, the other at completion */
1239 refcount_set(&req->refs, 2);
1241 INIT_IO_WORK(&req->work, io_wq_submit_work);
1244 req = io_get_fallback_req(ctx);
1247 percpu_ref_put(&ctx->refs);
1251 static void __io_req_do_free(struct io_kiocb *req)
1253 if (likely(!io_is_fallback_req(req)))
1254 kmem_cache_free(req_cachep, req);
1256 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1259 static void __io_req_aux_free(struct io_kiocb *req)
1261 struct io_ring_ctx *ctx = req->ctx;
1263 if (req->flags & REQ_F_NEED_CLEANUP)
1264 io_cleanup_req(req);
1268 if (req->flags & REQ_F_FIXED_FILE)
1269 percpu_ref_put(&ctx->file_data->refs);
1274 io_req_work_drop_env(req);
1277 static void __io_free_req(struct io_kiocb *req)
1279 __io_req_aux_free(req);
1281 if (req->flags & REQ_F_INFLIGHT) {
1282 struct io_ring_ctx *ctx = req->ctx;
1283 unsigned long flags;
1285 spin_lock_irqsave(&ctx->inflight_lock, flags);
1286 list_del(&req->inflight_entry);
1287 if (waitqueue_active(&ctx->inflight_wait))
1288 wake_up(&ctx->inflight_wait);
1289 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1292 percpu_ref_put(&req->ctx->refs);
1293 __io_req_do_free(req);
1297 void *reqs[IO_IOPOLL_BATCH];
1302 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1304 int fixed_refs = rb->to_free;
1308 if (rb->need_iter) {
1309 int i, inflight = 0;
1310 unsigned long flags;
1313 for (i = 0; i < rb->to_free; i++) {
1314 struct io_kiocb *req = rb->reqs[i];
1316 if (req->flags & REQ_F_FIXED_FILE) {
1320 if (req->flags & REQ_F_INFLIGHT)
1322 __io_req_aux_free(req);
1327 spin_lock_irqsave(&ctx->inflight_lock, flags);
1328 for (i = 0; i < rb->to_free; i++) {
1329 struct io_kiocb *req = rb->reqs[i];
1331 if (req->flags & REQ_F_INFLIGHT) {
1332 list_del(&req->inflight_entry);
1337 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1339 if (waitqueue_active(&ctx->inflight_wait))
1340 wake_up(&ctx->inflight_wait);
1343 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1345 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1346 percpu_ref_put_many(&ctx->refs, rb->to_free);
1347 rb->to_free = rb->need_iter = 0;
1350 static bool io_link_cancel_timeout(struct io_kiocb *req)
1352 struct io_ring_ctx *ctx = req->ctx;
1355 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1357 io_cqring_fill_event(req, -ECANCELED);
1358 io_commit_cqring(ctx);
1359 req->flags &= ~REQ_F_LINK;
1367 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1369 struct io_ring_ctx *ctx = req->ctx;
1370 bool wake_ev = false;
1372 /* Already got next link */
1373 if (req->flags & REQ_F_LINK_NEXT)
1377 * The list should never be empty when we are called here. But could
1378 * potentially happen if the chain is messed up, check to be on the
1381 while (!list_empty(&req->link_list)) {
1382 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1383 struct io_kiocb, link_list);
1385 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1386 (nxt->flags & REQ_F_TIMEOUT))) {
1387 list_del_init(&nxt->link_list);
1388 wake_ev |= io_link_cancel_timeout(nxt);
1389 req->flags &= ~REQ_F_LINK_TIMEOUT;
1393 list_del_init(&req->link_list);
1394 if (!list_empty(&nxt->link_list))
1395 nxt->flags |= REQ_F_LINK;
1400 req->flags |= REQ_F_LINK_NEXT;
1402 io_cqring_ev_posted(ctx);
1406 * Called if REQ_F_LINK is set, and we fail the head request
1408 static void io_fail_links(struct io_kiocb *req)
1410 struct io_ring_ctx *ctx = req->ctx;
1411 unsigned long flags;
1413 spin_lock_irqsave(&ctx->completion_lock, flags);
1415 while (!list_empty(&req->link_list)) {
1416 struct io_kiocb *link = list_first_entry(&req->link_list,
1417 struct io_kiocb, link_list);
1419 list_del_init(&link->link_list);
1420 trace_io_uring_fail_link(req, link);
1422 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1423 link->opcode == IORING_OP_LINK_TIMEOUT) {
1424 io_link_cancel_timeout(link);
1426 io_cqring_fill_event(link, -ECANCELED);
1427 __io_double_put_req(link);
1429 req->flags &= ~REQ_F_LINK_TIMEOUT;
1432 io_commit_cqring(ctx);
1433 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1434 io_cqring_ev_posted(ctx);
1437 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1439 if (likely(!(req->flags & REQ_F_LINK)))
1443 * If LINK is set, we have dependent requests in this chain. If we
1444 * didn't fail this request, queue the first one up, moving any other
1445 * dependencies to the next request. In case of failure, fail the rest
1448 if (req->flags & REQ_F_FAIL_LINK) {
1450 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1451 REQ_F_LINK_TIMEOUT) {
1452 struct io_ring_ctx *ctx = req->ctx;
1453 unsigned long flags;
1456 * If this is a timeout link, we could be racing with the
1457 * timeout timer. Grab the completion lock for this case to
1458 * protect against that.
1460 spin_lock_irqsave(&ctx->completion_lock, flags);
1461 io_req_link_next(req, nxt);
1462 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1464 io_req_link_next(req, nxt);
1468 static void io_free_req(struct io_kiocb *req)
1470 struct io_kiocb *nxt = NULL;
1472 io_req_find_next(req, &nxt);
1476 io_queue_async_work(nxt);
1480 * Drop reference to request, return next in chain (if there is one) if this
1481 * was the last reference to this request.
1483 __attribute__((nonnull))
1484 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1486 io_req_find_next(req, nxtptr);
1488 if (refcount_dec_and_test(&req->refs))
1492 static void io_put_req(struct io_kiocb *req)
1494 if (refcount_dec_and_test(&req->refs))
1499 * Must only be used if we don't need to care about links, usually from
1500 * within the completion handling itself.
1502 static void __io_double_put_req(struct io_kiocb *req)
1504 /* drop both submit and complete references */
1505 if (refcount_sub_and_test(2, &req->refs))
1509 static void io_double_put_req(struct io_kiocb *req)
1511 /* drop both submit and complete references */
1512 if (refcount_sub_and_test(2, &req->refs))
1516 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1518 struct io_rings *rings = ctx->rings;
1520 if (test_bit(0, &ctx->cq_check_overflow)) {
1522 * noflush == true is from the waitqueue handler, just ensure
1523 * we wake up the task, and the next invocation will flush the
1524 * entries. We cannot safely to it from here.
1526 if (noflush && !list_empty(&ctx->cq_overflow_list))
1529 io_cqring_overflow_flush(ctx, false);
1532 /* See comment at the top of this file */
1534 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1537 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1539 struct io_rings *rings = ctx->rings;
1541 /* make sure SQ entry isn't read before tail */
1542 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1545 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1547 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1550 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1553 rb->reqs[rb->to_free++] = req;
1554 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1555 io_free_req_many(req->ctx, rb);
1560 * Find and free completed poll iocbs
1562 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1563 struct list_head *done)
1565 struct req_batch rb;
1566 struct io_kiocb *req;
1568 rb.to_free = rb.need_iter = 0;
1569 while (!list_empty(done)) {
1570 req = list_first_entry(done, struct io_kiocb, list);
1571 list_del(&req->list);
1573 io_cqring_fill_event(req, req->result);
1576 if (refcount_dec_and_test(&req->refs) &&
1577 !io_req_multi_free(&rb, req))
1581 io_commit_cqring(ctx);
1582 io_free_req_many(ctx, &rb);
1585 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1588 struct io_kiocb *req, *tmp;
1594 * Only spin for completions if we don't have multiple devices hanging
1595 * off our complete list, and we're under the requested amount.
1597 spin = !ctx->poll_multi_file && *nr_events < min;
1600 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1601 struct kiocb *kiocb = &req->rw.kiocb;
1604 * Move completed entries to our local list. If we find a
1605 * request that requires polling, break out and complete
1606 * the done list first, if we have entries there.
1608 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1609 list_move_tail(&req->list, &done);
1612 if (!list_empty(&done))
1615 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1624 if (!list_empty(&done))
1625 io_iopoll_complete(ctx, nr_events, &done);
1631 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1632 * non-spinning poll check - we'll still enter the driver poll loop, but only
1633 * as a non-spinning completion check.
1635 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1638 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1641 ret = io_do_iopoll(ctx, nr_events, min);
1644 if (!min || *nr_events >= min)
1652 * We can't just wait for polled events to come to us, we have to actively
1653 * find and complete them.
1655 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1657 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1660 mutex_lock(&ctx->uring_lock);
1661 while (!list_empty(&ctx->poll_list)) {
1662 unsigned int nr_events = 0;
1664 io_iopoll_getevents(ctx, &nr_events, 1);
1667 * Ensure we allow local-to-the-cpu processing to take place,
1668 * in this case we need to ensure that we reap all events.
1672 mutex_unlock(&ctx->uring_lock);
1675 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1678 int iters = 0, ret = 0;
1681 * We disallow the app entering submit/complete with polling, but we
1682 * still need to lock the ring to prevent racing with polled issue
1683 * that got punted to a workqueue.
1685 mutex_lock(&ctx->uring_lock);
1690 * Don't enter poll loop if we already have events pending.
1691 * If we do, we can potentially be spinning for commands that
1692 * already triggered a CQE (eg in error).
1694 if (io_cqring_events(ctx, false))
1698 * If a submit got punted to a workqueue, we can have the
1699 * application entering polling for a command before it gets
1700 * issued. That app will hold the uring_lock for the duration
1701 * of the poll right here, so we need to take a breather every
1702 * now and then to ensure that the issue has a chance to add
1703 * the poll to the issued list. Otherwise we can spin here
1704 * forever, while the workqueue is stuck trying to acquire the
1707 if (!(++iters & 7)) {
1708 mutex_unlock(&ctx->uring_lock);
1709 mutex_lock(&ctx->uring_lock);
1712 if (*nr_events < min)
1713 tmin = min - *nr_events;
1715 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1719 } while (min && !*nr_events && !need_resched());
1721 mutex_unlock(&ctx->uring_lock);
1725 static void kiocb_end_write(struct io_kiocb *req)
1728 * Tell lockdep we inherited freeze protection from submission
1731 if (req->flags & REQ_F_ISREG) {
1732 struct inode *inode = file_inode(req->file);
1734 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1736 file_end_write(req->file);
1739 static inline void req_set_fail_links(struct io_kiocb *req)
1741 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1742 req->flags |= REQ_F_FAIL_LINK;
1745 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1747 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1749 if (kiocb->ki_flags & IOCB_WRITE)
1750 kiocb_end_write(req);
1752 if (res != req->result)
1753 req_set_fail_links(req);
1754 io_cqring_add_event(req, res);
1757 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1759 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1761 io_complete_rw_common(kiocb, res);
1765 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1767 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1768 struct io_kiocb *nxt = NULL;
1770 io_complete_rw_common(kiocb, res);
1771 io_put_req_find_next(req, &nxt);
1776 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1778 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1780 if (kiocb->ki_flags & IOCB_WRITE)
1781 kiocb_end_write(req);
1783 if (res != req->result)
1784 req_set_fail_links(req);
1787 req->flags |= REQ_F_IOPOLL_COMPLETED;
1791 * After the iocb has been issued, it's safe to be found on the poll list.
1792 * Adding the kiocb to the list AFTER submission ensures that we don't
1793 * find it from a io_iopoll_getevents() thread before the issuer is done
1794 * accessing the kiocb cookie.
1796 static void io_iopoll_req_issued(struct io_kiocb *req)
1798 struct io_ring_ctx *ctx = req->ctx;
1801 * Track whether we have multiple files in our lists. This will impact
1802 * how we do polling eventually, not spinning if we're on potentially
1803 * different devices.
1805 if (list_empty(&ctx->poll_list)) {
1806 ctx->poll_multi_file = false;
1807 } else if (!ctx->poll_multi_file) {
1808 struct io_kiocb *list_req;
1810 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1812 if (list_req->file != req->file)
1813 ctx->poll_multi_file = true;
1817 * For fast devices, IO may have already completed. If it has, add
1818 * it to the front so we find it first.
1820 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1821 list_add(&req->list, &ctx->poll_list);
1823 list_add_tail(&req->list, &ctx->poll_list);
1825 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1826 wq_has_sleeper(&ctx->sqo_wait))
1827 wake_up(&ctx->sqo_wait);
1830 static void io_file_put(struct io_submit_state *state)
1833 int diff = state->has_refs - state->used_refs;
1836 fput_many(state->file, diff);
1842 * Get as many references to a file as we have IOs left in this submission,
1843 * assuming most submissions are for one file, or at least that each file
1844 * has more than one submission.
1846 static struct file *io_file_get(struct io_submit_state *state, int fd)
1852 if (state->fd == fd) {
1859 state->file = fget_many(fd, state->ios_left);
1864 state->has_refs = state->ios_left;
1865 state->used_refs = 1;
1871 * If we tracked the file through the SCM inflight mechanism, we could support
1872 * any file. For now, just ensure that anything potentially problematic is done
1875 static bool io_file_supports_async(struct file *file)
1877 umode_t mode = file_inode(file)->i_mode;
1879 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1881 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1887 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1888 bool force_nonblock)
1890 struct io_ring_ctx *ctx = req->ctx;
1891 struct kiocb *kiocb = &req->rw.kiocb;
1895 if (S_ISREG(file_inode(req->file)->i_mode))
1896 req->flags |= REQ_F_ISREG;
1898 kiocb->ki_pos = READ_ONCE(sqe->off);
1899 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1900 req->flags |= REQ_F_CUR_POS;
1901 kiocb->ki_pos = req->file->f_pos;
1903 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1904 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1905 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1909 ioprio = READ_ONCE(sqe->ioprio);
1911 ret = ioprio_check_cap(ioprio);
1915 kiocb->ki_ioprio = ioprio;
1917 kiocb->ki_ioprio = get_current_ioprio();
1919 /* don't allow async punt if RWF_NOWAIT was requested */
1920 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1921 (req->file->f_flags & O_NONBLOCK))
1922 req->flags |= REQ_F_NOWAIT;
1925 kiocb->ki_flags |= IOCB_NOWAIT;
1927 if (ctx->flags & IORING_SETUP_IOPOLL) {
1928 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1929 !kiocb->ki_filp->f_op->iopoll)
1932 kiocb->ki_flags |= IOCB_HIPRI;
1933 kiocb->ki_complete = io_complete_rw_iopoll;
1936 if (kiocb->ki_flags & IOCB_HIPRI)
1938 kiocb->ki_complete = io_complete_rw;
1941 req->rw.addr = READ_ONCE(sqe->addr);
1942 req->rw.len = READ_ONCE(sqe->len);
1943 /* we own ->private, reuse it for the buffer index */
1944 req->rw.kiocb.private = (void *) (unsigned long)
1945 READ_ONCE(sqe->buf_index);
1949 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1955 case -ERESTARTNOINTR:
1956 case -ERESTARTNOHAND:
1957 case -ERESTART_RESTARTBLOCK:
1959 * We can't just restart the syscall, since previously
1960 * submitted sqes may already be in progress. Just fail this
1966 kiocb->ki_complete(kiocb, ret, 0);
1970 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1973 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1975 if (req->flags & REQ_F_CUR_POS)
1976 req->file->f_pos = kiocb->ki_pos;
1977 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1978 *nxt = __io_complete_rw(kiocb, ret);
1980 io_rw_done(kiocb, ret);
1983 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1984 struct iov_iter *iter)
1986 struct io_ring_ctx *ctx = req->ctx;
1987 size_t len = req->rw.len;
1988 struct io_mapped_ubuf *imu;
1989 unsigned index, buf_index;
1993 /* attempt to use fixed buffers without having provided iovecs */
1994 if (unlikely(!ctx->user_bufs))
1997 buf_index = (unsigned long) req->rw.kiocb.private;
1998 if (unlikely(buf_index >= ctx->nr_user_bufs))
2001 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2002 imu = &ctx->user_bufs[index];
2003 buf_addr = req->rw.addr;
2006 if (buf_addr + len < buf_addr)
2008 /* not inside the mapped region */
2009 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2013 * May not be a start of buffer, set size appropriately
2014 * and advance us to the beginning.
2016 offset = buf_addr - imu->ubuf;
2017 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2021 * Don't use iov_iter_advance() here, as it's really slow for
2022 * using the latter parts of a big fixed buffer - it iterates
2023 * over each segment manually. We can cheat a bit here, because
2026 * 1) it's a BVEC iter, we set it up
2027 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2028 * first and last bvec
2030 * So just find our index, and adjust the iterator afterwards.
2031 * If the offset is within the first bvec (or the whole first
2032 * bvec, just use iov_iter_advance(). This makes it easier
2033 * since we can just skip the first segment, which may not
2034 * be PAGE_SIZE aligned.
2036 const struct bio_vec *bvec = imu->bvec;
2038 if (offset <= bvec->bv_len) {
2039 iov_iter_advance(iter, offset);
2041 unsigned long seg_skip;
2043 /* skip first vec */
2044 offset -= bvec->bv_len;
2045 seg_skip = 1 + (offset >> PAGE_SHIFT);
2047 iter->bvec = bvec + seg_skip;
2048 iter->nr_segs -= seg_skip;
2049 iter->count -= bvec->bv_len + offset;
2050 iter->iov_offset = offset & ~PAGE_MASK;
2057 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2058 struct iovec **iovec, struct iov_iter *iter)
2060 void __user *buf = u64_to_user_ptr(req->rw.addr);
2061 size_t sqe_len = req->rw.len;
2064 opcode = req->opcode;
2065 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2067 return io_import_fixed(req, rw, iter);
2070 /* buffer index only valid with fixed read/write */
2071 if (req->rw.kiocb.private)
2074 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2076 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2082 struct io_async_rw *iorw = &req->io->rw;
2085 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2086 if (iorw->iov == iorw->fast_iov)
2091 #ifdef CONFIG_COMPAT
2092 if (req->ctx->compat)
2093 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2097 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2101 * For files that don't have ->read_iter() and ->write_iter(), handle them
2102 * by looping over ->read() or ->write() manually.
2104 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2105 struct iov_iter *iter)
2110 * Don't support polled IO through this interface, and we can't
2111 * support non-blocking either. For the latter, this just causes
2112 * the kiocb to be handled from an async context.
2114 if (kiocb->ki_flags & IOCB_HIPRI)
2116 if (kiocb->ki_flags & IOCB_NOWAIT)
2119 while (iov_iter_count(iter)) {
2123 if (!iov_iter_is_bvec(iter)) {
2124 iovec = iov_iter_iovec(iter);
2126 /* fixed buffers import bvec */
2127 iovec.iov_base = kmap(iter->bvec->bv_page)
2129 iovec.iov_len = min(iter->count,
2130 iter->bvec->bv_len - iter->iov_offset);
2134 nr = file->f_op->read(file, iovec.iov_base,
2135 iovec.iov_len, &kiocb->ki_pos);
2137 nr = file->f_op->write(file, iovec.iov_base,
2138 iovec.iov_len, &kiocb->ki_pos);
2141 if (iov_iter_is_bvec(iter))
2142 kunmap(iter->bvec->bv_page);
2150 if (nr != iovec.iov_len)
2152 iov_iter_advance(iter, nr);
2158 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2159 struct iovec *iovec, struct iovec *fast_iov,
2160 struct iov_iter *iter)
2162 req->io->rw.nr_segs = iter->nr_segs;
2163 req->io->rw.size = io_size;
2164 req->io->rw.iov = iovec;
2165 if (!req->io->rw.iov) {
2166 req->io->rw.iov = req->io->rw.fast_iov;
2167 memcpy(req->io->rw.iov, fast_iov,
2168 sizeof(struct iovec) * iter->nr_segs);
2170 req->flags |= REQ_F_NEED_CLEANUP;
2174 static int io_alloc_async_ctx(struct io_kiocb *req)
2176 if (!io_op_defs[req->opcode].async_ctx)
2178 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2179 return req->io == NULL;
2182 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2183 struct iovec *iovec, struct iovec *fast_iov,
2184 struct iov_iter *iter)
2186 if (!io_op_defs[req->opcode].async_ctx)
2189 if (io_alloc_async_ctx(req))
2192 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2197 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2198 bool force_nonblock)
2200 struct io_async_ctx *io;
2201 struct iov_iter iter;
2204 ret = io_prep_rw(req, sqe, force_nonblock);
2208 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2211 /* either don't need iovec imported or already have it */
2212 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2216 io->rw.iov = io->rw.fast_iov;
2218 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2223 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2227 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2228 bool force_nonblock)
2230 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2231 struct kiocb *kiocb = &req->rw.kiocb;
2232 struct iov_iter iter;
2234 ssize_t io_size, ret;
2236 ret = io_import_iovec(READ, req, &iovec, &iter);
2240 /* Ensure we clear previously set non-block flag */
2241 if (!force_nonblock)
2242 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2246 if (req->flags & REQ_F_LINK)
2247 req->result = io_size;
2250 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2251 * we know to async punt it even if it was opened O_NONBLOCK
2253 if (force_nonblock && !io_file_supports_async(req->file)) {
2254 req->flags |= REQ_F_MUST_PUNT;
2258 iov_count = iov_iter_count(&iter);
2259 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2263 if (req->file->f_op->read_iter)
2264 ret2 = call_read_iter(req->file, kiocb, &iter);
2266 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2268 /* Catch -EAGAIN return for forced non-blocking submission */
2269 if (!force_nonblock || ret2 != -EAGAIN) {
2270 kiocb_done(kiocb, ret2, nxt, req->in_async);
2273 ret = io_setup_async_rw(req, io_size, iovec,
2274 inline_vecs, &iter);
2282 req->flags &= ~REQ_F_NEED_CLEANUP;
2286 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2287 bool force_nonblock)
2289 struct io_async_ctx *io;
2290 struct iov_iter iter;
2293 ret = io_prep_rw(req, sqe, force_nonblock);
2297 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2300 /* either don't need iovec imported or already have it */
2301 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2305 io->rw.iov = io->rw.fast_iov;
2307 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2312 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2316 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2317 bool force_nonblock)
2319 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2320 struct kiocb *kiocb = &req->rw.kiocb;
2321 struct iov_iter iter;
2323 ssize_t ret, io_size;
2325 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2329 /* Ensure we clear previously set non-block flag */
2330 if (!force_nonblock)
2331 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2335 if (req->flags & REQ_F_LINK)
2336 req->result = io_size;
2339 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2340 * we know to async punt it even if it was opened O_NONBLOCK
2342 if (force_nonblock && !io_file_supports_async(req->file)) {
2343 req->flags |= REQ_F_MUST_PUNT;
2347 /* file path doesn't support NOWAIT for non-direct_IO */
2348 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2349 (req->flags & REQ_F_ISREG))
2352 iov_count = iov_iter_count(&iter);
2353 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2358 * Open-code file_start_write here to grab freeze protection,
2359 * which will be released by another thread in
2360 * io_complete_rw(). Fool lockdep by telling it the lock got
2361 * released so that it doesn't complain about the held lock when
2362 * we return to userspace.
2364 if (req->flags & REQ_F_ISREG) {
2365 __sb_start_write(file_inode(req->file)->i_sb,
2366 SB_FREEZE_WRITE, true);
2367 __sb_writers_release(file_inode(req->file)->i_sb,
2370 kiocb->ki_flags |= IOCB_WRITE;
2372 if (req->file->f_op->write_iter)
2373 ret2 = call_write_iter(req->file, kiocb, &iter);
2375 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2377 * Raw bdev writes will -EOPNOTSUPP for IOCB_NOWAIT. Just
2378 * retry them without IOCB_NOWAIT.
2380 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2382 if (!force_nonblock || ret2 != -EAGAIN) {
2383 kiocb_done(kiocb, ret2, nxt, req->in_async);
2386 ret = io_setup_async_rw(req, io_size, iovec,
2387 inline_vecs, &iter);
2394 req->flags &= ~REQ_F_NEED_CLEANUP;
2400 * IORING_OP_NOP just posts a completion event, nothing else.
2402 static int io_nop(struct io_kiocb *req)
2404 struct io_ring_ctx *ctx = req->ctx;
2406 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2409 io_cqring_add_event(req, 0);
2414 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2416 struct io_ring_ctx *ctx = req->ctx;
2421 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2423 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2426 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2427 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2430 req->sync.off = READ_ONCE(sqe->off);
2431 req->sync.len = READ_ONCE(sqe->len);
2435 static bool io_req_cancelled(struct io_kiocb *req)
2437 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2438 req_set_fail_links(req);
2439 io_cqring_add_event(req, -ECANCELED);
2447 static void io_link_work_cb(struct io_wq_work **workptr)
2449 struct io_wq_work *work = *workptr;
2450 struct io_kiocb *link = work->data;
2452 io_queue_linked_timeout(link);
2453 work->func = io_wq_submit_work;
2456 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2458 struct io_kiocb *link;
2460 io_prep_async_work(nxt, &link);
2461 *workptr = &nxt->work;
2463 nxt->work.flags |= IO_WQ_WORK_CB;
2464 nxt->work.func = io_link_work_cb;
2465 nxt->work.data = link;
2469 static void io_fsync_finish(struct io_wq_work **workptr)
2471 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2472 loff_t end = req->sync.off + req->sync.len;
2473 struct io_kiocb *nxt = NULL;
2476 if (io_req_cancelled(req))
2479 ret = vfs_fsync_range(req->file, req->sync.off,
2480 end > 0 ? end : LLONG_MAX,
2481 req->sync.flags & IORING_FSYNC_DATASYNC);
2483 req_set_fail_links(req);
2484 io_cqring_add_event(req, ret);
2485 io_put_req_find_next(req, &nxt);
2487 io_wq_assign_next(workptr, nxt);
2490 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2491 bool force_nonblock)
2493 struct io_wq_work *work, *old_work;
2495 /* fsync always requires a blocking context */
2496 if (force_nonblock) {
2498 req->work.func = io_fsync_finish;
2502 work = old_work = &req->work;
2503 io_fsync_finish(&work);
2504 if (work && work != old_work)
2505 *nxt = container_of(work, struct io_kiocb, work);
2509 static void io_fallocate_finish(struct io_wq_work **workptr)
2511 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2512 struct io_kiocb *nxt = NULL;
2515 if (io_req_cancelled(req))
2518 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2521 req_set_fail_links(req);
2522 io_cqring_add_event(req, ret);
2523 io_put_req_find_next(req, &nxt);
2525 io_wq_assign_next(workptr, nxt);
2528 static int io_fallocate_prep(struct io_kiocb *req,
2529 const struct io_uring_sqe *sqe)
2531 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2534 req->sync.off = READ_ONCE(sqe->off);
2535 req->sync.len = READ_ONCE(sqe->addr);
2536 req->sync.mode = READ_ONCE(sqe->len);
2540 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2541 bool force_nonblock)
2543 struct io_wq_work *work, *old_work;
2545 /* fallocate always requiring blocking context */
2546 if (force_nonblock) {
2548 req->work.func = io_fallocate_finish;
2552 work = old_work = &req->work;
2553 io_fallocate_finish(&work);
2554 if (work && work != old_work)
2555 *nxt = container_of(work, struct io_kiocb, work);
2560 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2562 const char __user *fname;
2565 if (sqe->ioprio || sqe->buf_index)
2567 if (sqe->flags & IOSQE_FIXED_FILE)
2569 if (req->flags & REQ_F_NEED_CLEANUP)
2572 req->open.dfd = READ_ONCE(sqe->fd);
2573 req->open.how.mode = READ_ONCE(sqe->len);
2574 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2575 req->open.how.flags = READ_ONCE(sqe->open_flags);
2577 req->open.filename = getname(fname);
2578 if (IS_ERR(req->open.filename)) {
2579 ret = PTR_ERR(req->open.filename);
2580 req->open.filename = NULL;
2584 req->flags |= REQ_F_NEED_CLEANUP;
2588 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2590 struct open_how __user *how;
2591 const char __user *fname;
2595 if (sqe->ioprio || sqe->buf_index)
2597 if (sqe->flags & IOSQE_FIXED_FILE)
2599 if (req->flags & REQ_F_NEED_CLEANUP)
2602 req->open.dfd = READ_ONCE(sqe->fd);
2603 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2604 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2605 len = READ_ONCE(sqe->len);
2607 if (len < OPEN_HOW_SIZE_VER0)
2610 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2615 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2616 req->open.how.flags |= O_LARGEFILE;
2618 req->open.filename = getname(fname);
2619 if (IS_ERR(req->open.filename)) {
2620 ret = PTR_ERR(req->open.filename);
2621 req->open.filename = NULL;
2625 req->flags |= REQ_F_NEED_CLEANUP;
2629 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2630 bool force_nonblock)
2632 struct open_flags op;
2639 ret = build_open_flags(&req->open.how, &op);
2643 ret = get_unused_fd_flags(req->open.how.flags);
2647 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2650 ret = PTR_ERR(file);
2652 fsnotify_open(file);
2653 fd_install(ret, file);
2656 putname(req->open.filename);
2657 req->flags &= ~REQ_F_NEED_CLEANUP;
2659 req_set_fail_links(req);
2660 io_cqring_add_event(req, ret);
2661 io_put_req_find_next(req, nxt);
2665 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2666 bool force_nonblock)
2668 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2669 return io_openat2(req, nxt, force_nonblock);
2672 static int io_epoll_ctl_prep(struct io_kiocb *req,
2673 const struct io_uring_sqe *sqe)
2675 #if defined(CONFIG_EPOLL)
2676 if (sqe->ioprio || sqe->buf_index)
2679 req->epoll.epfd = READ_ONCE(sqe->fd);
2680 req->epoll.op = READ_ONCE(sqe->len);
2681 req->epoll.fd = READ_ONCE(sqe->off);
2683 if (ep_op_has_event(req->epoll.op)) {
2684 struct epoll_event __user *ev;
2686 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
2687 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
2697 static int io_epoll_ctl(struct io_kiocb *req, struct io_kiocb **nxt,
2698 bool force_nonblock)
2700 #if defined(CONFIG_EPOLL)
2701 struct io_epoll *ie = &req->epoll;
2704 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
2705 if (force_nonblock && ret == -EAGAIN)
2709 req_set_fail_links(req);
2710 io_cqring_add_event(req, ret);
2711 io_put_req_find_next(req, nxt);
2718 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2720 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2721 if (sqe->ioprio || sqe->buf_index || sqe->off)
2724 req->madvise.addr = READ_ONCE(sqe->addr);
2725 req->madvise.len = READ_ONCE(sqe->len);
2726 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2733 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2734 bool force_nonblock)
2736 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2737 struct io_madvise *ma = &req->madvise;
2743 ret = do_madvise(ma->addr, ma->len, ma->advice);
2745 req_set_fail_links(req);
2746 io_cqring_add_event(req, ret);
2747 io_put_req_find_next(req, nxt);
2754 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2756 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2759 req->fadvise.offset = READ_ONCE(sqe->off);
2760 req->fadvise.len = READ_ONCE(sqe->len);
2761 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2765 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2766 bool force_nonblock)
2768 struct io_fadvise *fa = &req->fadvise;
2771 if (force_nonblock) {
2772 switch (fa->advice) {
2773 case POSIX_FADV_NORMAL:
2774 case POSIX_FADV_RANDOM:
2775 case POSIX_FADV_SEQUENTIAL:
2782 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2784 req_set_fail_links(req);
2785 io_cqring_add_event(req, ret);
2786 io_put_req_find_next(req, nxt);
2790 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2792 const char __user *fname;
2793 unsigned lookup_flags;
2796 if (sqe->ioprio || sqe->buf_index)
2798 if (sqe->flags & IOSQE_FIXED_FILE)
2800 if (req->flags & REQ_F_NEED_CLEANUP)
2803 req->open.dfd = READ_ONCE(sqe->fd);
2804 req->open.mask = READ_ONCE(sqe->len);
2805 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2806 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2807 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2809 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2812 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2813 if (IS_ERR(req->open.filename)) {
2814 ret = PTR_ERR(req->open.filename);
2815 req->open.filename = NULL;
2819 req->flags |= REQ_F_NEED_CLEANUP;
2823 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2824 bool force_nonblock)
2826 struct io_open *ctx = &req->open;
2827 unsigned lookup_flags;
2835 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2839 /* filename_lookup() drops it, keep a reference */
2840 ctx->filename->refcnt++;
2842 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2847 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2849 if (retry_estale(ret, lookup_flags)) {
2850 lookup_flags |= LOOKUP_REVAL;
2854 ret = cp_statx(&stat, ctx->buffer);
2856 putname(ctx->filename);
2857 req->flags &= ~REQ_F_NEED_CLEANUP;
2859 req_set_fail_links(req);
2860 io_cqring_add_event(req, ret);
2861 io_put_req_find_next(req, nxt);
2865 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2868 * If we queue this for async, it must not be cancellable. That would
2869 * leave the 'file' in an undeterminate state.
2871 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2873 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2874 sqe->rw_flags || sqe->buf_index)
2876 if (sqe->flags & IOSQE_FIXED_FILE)
2879 req->close.fd = READ_ONCE(sqe->fd);
2880 if (req->file->f_op == &io_uring_fops ||
2881 req->close.fd == req->ctx->ring_fd)
2887 /* only called when __close_fd_get_file() is done */
2888 static void __io_close_finish(struct io_kiocb *req, struct io_kiocb **nxt)
2892 ret = filp_close(req->close.put_file, req->work.files);
2894 req_set_fail_links(req);
2895 io_cqring_add_event(req, ret);
2896 fput(req->close.put_file);
2897 io_put_req_find_next(req, nxt);
2900 static void io_close_finish(struct io_wq_work **workptr)
2902 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2903 struct io_kiocb *nxt = NULL;
2905 /* not cancellable, don't do io_req_cancelled() */
2906 __io_close_finish(req, &nxt);
2908 io_wq_assign_next(workptr, nxt);
2911 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2912 bool force_nonblock)
2916 req->close.put_file = NULL;
2917 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2921 /* if the file has a flush method, be safe and punt to async */
2922 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker())
2926 * No ->flush(), safely close from here and just punt the
2927 * fput() to async context.
2929 __io_close_finish(req, nxt);
2932 req->work.func = io_close_finish;
2934 * Do manual async queue here to avoid grabbing files - we don't
2935 * need the files, and it'll cause io_close_finish() to close
2936 * the file again and cause a double CQE entry for this request
2938 io_queue_async_work(req);
2942 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2944 struct io_ring_ctx *ctx = req->ctx;
2949 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2951 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2954 req->sync.off = READ_ONCE(sqe->off);
2955 req->sync.len = READ_ONCE(sqe->len);
2956 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2960 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2962 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2963 struct io_kiocb *nxt = NULL;
2966 if (io_req_cancelled(req))
2969 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2972 req_set_fail_links(req);
2973 io_cqring_add_event(req, ret);
2974 io_put_req_find_next(req, &nxt);
2976 io_wq_assign_next(workptr, nxt);
2979 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2980 bool force_nonblock)
2982 struct io_wq_work *work, *old_work;
2984 /* sync_file_range always requires a blocking context */
2985 if (force_nonblock) {
2987 req->work.func = io_sync_file_range_finish;
2991 work = old_work = &req->work;
2992 io_sync_file_range_finish(&work);
2993 if (work && work != old_work)
2994 *nxt = container_of(work, struct io_kiocb, work);
2998 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3000 #if defined(CONFIG_NET)
3001 struct io_sr_msg *sr = &req->sr_msg;
3002 struct io_async_ctx *io = req->io;
3005 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3006 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3007 sr->len = READ_ONCE(sqe->len);
3009 if (!io || req->opcode == IORING_OP_SEND)
3011 /* iovec is already imported */
3012 if (req->flags & REQ_F_NEED_CLEANUP)
3015 io->msg.iov = io->msg.fast_iov;
3016 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3019 req->flags |= REQ_F_NEED_CLEANUP;
3026 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3027 bool force_nonblock)
3029 #if defined(CONFIG_NET)
3030 struct io_async_msghdr *kmsg = NULL;
3031 struct socket *sock;
3034 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3037 sock = sock_from_file(req->file, &ret);
3039 struct io_async_ctx io;
3043 kmsg = &req->io->msg;
3044 kmsg->msg.msg_name = &req->io->msg.addr;
3045 /* if iov is set, it's allocated already */
3047 kmsg->iov = kmsg->fast_iov;
3048 kmsg->msg.msg_iter.iov = kmsg->iov;
3050 struct io_sr_msg *sr = &req->sr_msg;
3053 kmsg->msg.msg_name = &io.msg.addr;
3055 io.msg.iov = io.msg.fast_iov;
3056 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3057 sr->msg_flags, &io.msg.iov);
3062 flags = req->sr_msg.msg_flags;
3063 if (flags & MSG_DONTWAIT)
3064 req->flags |= REQ_F_NOWAIT;
3065 else if (force_nonblock)
3066 flags |= MSG_DONTWAIT;
3068 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3069 if (force_nonblock && ret == -EAGAIN) {
3072 if (io_alloc_async_ctx(req)) {
3073 if (kmsg->iov != kmsg->fast_iov)
3077 req->flags |= REQ_F_NEED_CLEANUP;
3078 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3081 if (ret == -ERESTARTSYS)
3085 if (kmsg && kmsg->iov != kmsg->fast_iov)
3087 req->flags &= ~REQ_F_NEED_CLEANUP;
3088 io_cqring_add_event(req, ret);
3090 req_set_fail_links(req);
3091 io_put_req_find_next(req, nxt);
3098 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
3099 bool force_nonblock)
3101 #if defined(CONFIG_NET)
3102 struct socket *sock;
3105 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3108 sock = sock_from_file(req->file, &ret);
3110 struct io_sr_msg *sr = &req->sr_msg;
3115 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3120 msg.msg_name = NULL;
3121 msg.msg_control = NULL;
3122 msg.msg_controllen = 0;
3123 msg.msg_namelen = 0;
3125 flags = req->sr_msg.msg_flags;
3126 if (flags & MSG_DONTWAIT)
3127 req->flags |= REQ_F_NOWAIT;
3128 else if (force_nonblock)
3129 flags |= MSG_DONTWAIT;
3131 msg.msg_flags = flags;
3132 ret = sock_sendmsg(sock, &msg);
3133 if (force_nonblock && ret == -EAGAIN)
3135 if (ret == -ERESTARTSYS)
3139 io_cqring_add_event(req, ret);
3141 req_set_fail_links(req);
3142 io_put_req_find_next(req, nxt);
3149 static int io_recvmsg_prep(struct io_kiocb *req,
3150 const struct io_uring_sqe *sqe)
3152 #if defined(CONFIG_NET)
3153 struct io_sr_msg *sr = &req->sr_msg;
3154 struct io_async_ctx *io = req->io;
3157 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3158 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3159 sr->len = READ_ONCE(sqe->len);
3161 if (!io || req->opcode == IORING_OP_RECV)
3163 /* iovec is already imported */
3164 if (req->flags & REQ_F_NEED_CLEANUP)
3167 io->msg.iov = io->msg.fast_iov;
3168 ret = recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3169 &io->msg.uaddr, &io->msg.iov);
3171 req->flags |= REQ_F_NEED_CLEANUP;
3178 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3179 bool force_nonblock)
3181 #if defined(CONFIG_NET)
3182 struct io_async_msghdr *kmsg = NULL;
3183 struct socket *sock;
3186 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3189 sock = sock_from_file(req->file, &ret);
3191 struct io_async_ctx io;
3195 kmsg = &req->io->msg;
3196 kmsg->msg.msg_name = &req->io->msg.addr;
3197 /* if iov is set, it's allocated already */
3199 kmsg->iov = kmsg->fast_iov;
3200 kmsg->msg.msg_iter.iov = kmsg->iov;
3202 struct io_sr_msg *sr = &req->sr_msg;
3205 kmsg->msg.msg_name = &io.msg.addr;
3207 io.msg.iov = io.msg.fast_iov;
3208 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3209 sr->msg_flags, &io.msg.uaddr,
3215 flags = req->sr_msg.msg_flags;
3216 if (flags & MSG_DONTWAIT)
3217 req->flags |= REQ_F_NOWAIT;
3218 else if (force_nonblock)
3219 flags |= MSG_DONTWAIT;
3221 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3222 kmsg->uaddr, flags);
3223 if (force_nonblock && ret == -EAGAIN) {
3226 if (io_alloc_async_ctx(req)) {
3227 if (kmsg->iov != kmsg->fast_iov)
3231 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3232 req->flags |= REQ_F_NEED_CLEANUP;
3235 if (ret == -ERESTARTSYS)
3239 if (kmsg && kmsg->iov != kmsg->fast_iov)
3241 req->flags &= ~REQ_F_NEED_CLEANUP;
3242 io_cqring_add_event(req, ret);
3244 req_set_fail_links(req);
3245 io_put_req_find_next(req, nxt);
3252 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3253 bool force_nonblock)
3255 #if defined(CONFIG_NET)
3256 struct socket *sock;
3259 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3262 sock = sock_from_file(req->file, &ret);
3264 struct io_sr_msg *sr = &req->sr_msg;
3269 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3274 msg.msg_name = NULL;
3275 msg.msg_control = NULL;
3276 msg.msg_controllen = 0;
3277 msg.msg_namelen = 0;
3278 msg.msg_iocb = NULL;
3281 flags = req->sr_msg.msg_flags;
3282 if (flags & MSG_DONTWAIT)
3283 req->flags |= REQ_F_NOWAIT;
3284 else if (force_nonblock)
3285 flags |= MSG_DONTWAIT;
3287 ret = sock_recvmsg(sock, &msg, flags);
3288 if (force_nonblock && ret == -EAGAIN)
3290 if (ret == -ERESTARTSYS)
3294 io_cqring_add_event(req, ret);
3296 req_set_fail_links(req);
3297 io_put_req_find_next(req, nxt);
3305 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3307 #if defined(CONFIG_NET)
3308 struct io_accept *accept = &req->accept;
3310 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3312 if (sqe->ioprio || sqe->len || sqe->buf_index)
3315 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3316 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3317 accept->flags = READ_ONCE(sqe->accept_flags);
3324 #if defined(CONFIG_NET)
3325 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3326 bool force_nonblock)
3328 struct io_accept *accept = &req->accept;
3329 unsigned file_flags;
3332 file_flags = force_nonblock ? O_NONBLOCK : 0;
3333 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3334 accept->addr_len, accept->flags);
3335 if (ret == -EAGAIN && force_nonblock)
3337 if (ret == -ERESTARTSYS)
3340 req_set_fail_links(req);
3341 io_cqring_add_event(req, ret);
3342 io_put_req_find_next(req, nxt);
3346 static void io_accept_finish(struct io_wq_work **workptr)
3348 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3349 struct io_kiocb *nxt = NULL;
3351 if (io_req_cancelled(req))
3353 __io_accept(req, &nxt, false);
3355 io_wq_assign_next(workptr, nxt);
3359 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3360 bool force_nonblock)
3362 #if defined(CONFIG_NET)
3365 ret = __io_accept(req, nxt, force_nonblock);
3366 if (ret == -EAGAIN && force_nonblock) {
3367 req->work.func = io_accept_finish;
3377 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3379 #if defined(CONFIG_NET)
3380 struct io_connect *conn = &req->connect;
3381 struct io_async_ctx *io = req->io;
3383 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3385 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3388 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3389 conn->addr_len = READ_ONCE(sqe->addr2);
3394 return move_addr_to_kernel(conn->addr, conn->addr_len,
3395 &io->connect.address);
3401 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3402 bool force_nonblock)
3404 #if defined(CONFIG_NET)
3405 struct io_async_ctx __io, *io;
3406 unsigned file_flags;
3412 ret = move_addr_to_kernel(req->connect.addr,
3413 req->connect.addr_len,
3414 &__io.connect.address);
3420 file_flags = force_nonblock ? O_NONBLOCK : 0;
3422 ret = __sys_connect_file(req->file, &io->connect.address,
3423 req->connect.addr_len, file_flags);
3424 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3427 if (io_alloc_async_ctx(req)) {
3431 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3434 if (ret == -ERESTARTSYS)
3438 req_set_fail_links(req);
3439 io_cqring_add_event(req, ret);
3440 io_put_req_find_next(req, nxt);
3447 static void io_poll_remove_one(struct io_kiocb *req)
3449 struct io_poll_iocb *poll = &req->poll;
3451 spin_lock(&poll->head->lock);
3452 WRITE_ONCE(poll->canceled, true);
3453 if (!list_empty(&poll->wait.entry)) {
3454 list_del_init(&poll->wait.entry);
3455 io_queue_async_work(req);
3457 spin_unlock(&poll->head->lock);
3458 hash_del(&req->hash_node);
3461 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3463 struct hlist_node *tmp;
3464 struct io_kiocb *req;
3467 spin_lock_irq(&ctx->completion_lock);
3468 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3469 struct hlist_head *list;
3471 list = &ctx->cancel_hash[i];
3472 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3473 io_poll_remove_one(req);
3475 spin_unlock_irq(&ctx->completion_lock);
3478 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3480 struct hlist_head *list;
3481 struct io_kiocb *req;
3483 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3484 hlist_for_each_entry(req, list, hash_node) {
3485 if (sqe_addr == req->user_data) {
3486 io_poll_remove_one(req);
3494 static int io_poll_remove_prep(struct io_kiocb *req,
3495 const struct io_uring_sqe *sqe)
3497 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3499 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3503 req->poll.addr = READ_ONCE(sqe->addr);
3508 * Find a running poll command that matches one specified in sqe->addr,
3509 * and remove it if found.
3511 static int io_poll_remove(struct io_kiocb *req)
3513 struct io_ring_ctx *ctx = req->ctx;
3517 addr = req->poll.addr;
3518 spin_lock_irq(&ctx->completion_lock);
3519 ret = io_poll_cancel(ctx, addr);
3520 spin_unlock_irq(&ctx->completion_lock);
3522 io_cqring_add_event(req, ret);
3524 req_set_fail_links(req);
3529 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3531 struct io_ring_ctx *ctx = req->ctx;
3533 req->poll.done = true;
3535 io_cqring_fill_event(req, error);
3537 io_cqring_fill_event(req, mangle_poll(mask));
3538 io_commit_cqring(ctx);
3541 static void io_poll_complete_work(struct io_wq_work **workptr)
3543 struct io_wq_work *work = *workptr;
3544 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3545 struct io_poll_iocb *poll = &req->poll;
3546 struct poll_table_struct pt = { ._key = poll->events };
3547 struct io_ring_ctx *ctx = req->ctx;
3548 struct io_kiocb *nxt = NULL;
3552 if (work->flags & IO_WQ_WORK_CANCEL) {
3553 WRITE_ONCE(poll->canceled, true);
3555 } else if (READ_ONCE(poll->canceled)) {
3559 if (ret != -ECANCELED)
3560 mask = vfs_poll(poll->file, &pt) & poll->events;
3563 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3564 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3565 * synchronize with them. In the cancellation case the list_del_init
3566 * itself is not actually needed, but harmless so we keep it in to
3567 * avoid further branches in the fast path.
3569 spin_lock_irq(&ctx->completion_lock);
3570 if (!mask && ret != -ECANCELED) {
3571 add_wait_queue(poll->head, &poll->wait);
3572 spin_unlock_irq(&ctx->completion_lock);
3575 hash_del(&req->hash_node);
3576 io_poll_complete(req, mask, ret);
3577 spin_unlock_irq(&ctx->completion_lock);
3579 io_cqring_ev_posted(ctx);
3582 req_set_fail_links(req);
3583 io_put_req_find_next(req, &nxt);
3585 io_wq_assign_next(workptr, nxt);
3588 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3590 struct io_kiocb *req, *tmp;
3591 struct req_batch rb;
3593 rb.to_free = rb.need_iter = 0;
3594 spin_lock_irq(&ctx->completion_lock);
3595 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3596 hash_del(&req->hash_node);
3597 io_poll_complete(req, req->result, 0);
3599 if (refcount_dec_and_test(&req->refs) &&
3600 !io_req_multi_free(&rb, req)) {
3601 req->flags |= REQ_F_COMP_LOCKED;
3605 spin_unlock_irq(&ctx->completion_lock);
3607 io_cqring_ev_posted(ctx);
3608 io_free_req_many(ctx, &rb);
3611 static void io_poll_flush(struct io_wq_work **workptr)
3613 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3614 struct llist_node *nodes;
3616 nodes = llist_del_all(&req->ctx->poll_llist);
3618 __io_poll_flush(req->ctx, nodes);
3621 static void io_poll_trigger_evfd(struct io_wq_work **workptr)
3623 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3625 eventfd_signal(req->ctx->cq_ev_fd, 1);
3629 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3632 struct io_poll_iocb *poll = wait->private;
3633 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3634 struct io_ring_ctx *ctx = req->ctx;
3635 __poll_t mask = key_to_poll(key);
3637 /* for instances that support it check for an event match first: */
3638 if (mask && !(mask & poll->events))
3641 list_del_init(&poll->wait.entry);
3644 * Run completion inline if we can. We're using trylock here because
3645 * we are violating the completion_lock -> poll wq lock ordering.
3646 * If we have a link timeout we're going to need the completion_lock
3647 * for finalizing the request, mark us as having grabbed that already.
3650 unsigned long flags;
3652 if (llist_empty(&ctx->poll_llist) &&
3653 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3656 hash_del(&req->hash_node);
3657 io_poll_complete(req, mask, 0);
3659 trigger_ev = io_should_trigger_evfd(ctx);
3660 if (trigger_ev && eventfd_signal_count()) {
3662 req->work.func = io_poll_trigger_evfd;
3664 req->flags |= REQ_F_COMP_LOCKED;
3668 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3669 __io_cqring_ev_posted(ctx, trigger_ev);
3672 req->llist_node.next = NULL;
3673 /* if the list wasn't empty, we're done */
3674 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3677 req->work.func = io_poll_flush;
3681 io_queue_async_work(req);
3686 struct io_poll_table {
3687 struct poll_table_struct pt;
3688 struct io_kiocb *req;
3692 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3693 struct poll_table_struct *p)
3695 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3697 if (unlikely(pt->req->poll.head)) {
3698 pt->error = -EINVAL;
3703 pt->req->poll.head = head;
3704 add_wait_queue(head, &pt->req->poll.wait);
3707 static void io_poll_req_insert(struct io_kiocb *req)
3709 struct io_ring_ctx *ctx = req->ctx;
3710 struct hlist_head *list;
3712 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3713 hlist_add_head(&req->hash_node, list);
3716 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3718 struct io_poll_iocb *poll = &req->poll;
3721 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3723 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3728 events = READ_ONCE(sqe->poll_events);
3729 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3733 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3735 struct io_poll_iocb *poll = &req->poll;
3736 struct io_ring_ctx *ctx = req->ctx;
3737 struct io_poll_table ipt;
3738 bool cancel = false;
3741 INIT_IO_WORK(&req->work, io_poll_complete_work);
3742 INIT_HLIST_NODE(&req->hash_node);
3746 poll->canceled = false;
3748 ipt.pt._qproc = io_poll_queue_proc;
3749 ipt.pt._key = poll->events;
3751 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3753 /* initialized the list so that we can do list_empty checks */
3754 INIT_LIST_HEAD(&poll->wait.entry);
3755 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3756 poll->wait.private = poll;
3758 INIT_LIST_HEAD(&req->list);
3760 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3762 spin_lock_irq(&ctx->completion_lock);
3763 if (likely(poll->head)) {
3764 spin_lock(&poll->head->lock);
3765 if (unlikely(list_empty(&poll->wait.entry))) {
3771 if (mask || ipt.error)
3772 list_del_init(&poll->wait.entry);
3774 WRITE_ONCE(poll->canceled, true);
3775 else if (!poll->done) /* actually waiting for an event */
3776 io_poll_req_insert(req);
3777 spin_unlock(&poll->head->lock);
3779 if (mask) { /* no async, we'd stolen it */
3781 io_poll_complete(req, mask, 0);
3783 spin_unlock_irq(&ctx->completion_lock);
3786 io_cqring_ev_posted(ctx);
3787 io_put_req_find_next(req, nxt);
3792 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3794 struct io_timeout_data *data = container_of(timer,
3795 struct io_timeout_data, timer);
3796 struct io_kiocb *req = data->req;
3797 struct io_ring_ctx *ctx = req->ctx;
3798 unsigned long flags;
3800 atomic_inc(&ctx->cq_timeouts);
3802 spin_lock_irqsave(&ctx->completion_lock, flags);
3804 * We could be racing with timeout deletion. If the list is empty,
3805 * then timeout lookup already found it and will be handling it.
3807 if (!list_empty(&req->list)) {
3808 struct io_kiocb *prev;
3811 * Adjust the reqs sequence before the current one because it
3812 * will consume a slot in the cq_ring and the cq_tail
3813 * pointer will be increased, otherwise other timeout reqs may
3814 * return in advance without waiting for enough wait_nr.
3817 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3819 list_del_init(&req->list);
3822 io_cqring_fill_event(req, -ETIME);
3823 io_commit_cqring(ctx);
3824 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3826 io_cqring_ev_posted(ctx);
3827 req_set_fail_links(req);
3829 return HRTIMER_NORESTART;
3832 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3834 struct io_kiocb *req;
3837 list_for_each_entry(req, &ctx->timeout_list, list) {
3838 if (user_data == req->user_data) {
3839 list_del_init(&req->list);
3848 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3852 req_set_fail_links(req);
3853 io_cqring_fill_event(req, -ECANCELED);
3858 static int io_timeout_remove_prep(struct io_kiocb *req,
3859 const struct io_uring_sqe *sqe)
3861 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3863 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3866 req->timeout.addr = READ_ONCE(sqe->addr);
3867 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3868 if (req->timeout.flags)
3875 * Remove or update an existing timeout command
3877 static int io_timeout_remove(struct io_kiocb *req)
3879 struct io_ring_ctx *ctx = req->ctx;
3882 spin_lock_irq(&ctx->completion_lock);
3883 ret = io_timeout_cancel(ctx, req->timeout.addr);
3885 io_cqring_fill_event(req, ret);
3886 io_commit_cqring(ctx);
3887 spin_unlock_irq(&ctx->completion_lock);
3888 io_cqring_ev_posted(ctx);
3890 req_set_fail_links(req);
3895 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3896 bool is_timeout_link)
3898 struct io_timeout_data *data;
3901 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3903 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3905 if (sqe->off && is_timeout_link)
3907 flags = READ_ONCE(sqe->timeout_flags);
3908 if (flags & ~IORING_TIMEOUT_ABS)
3911 req->timeout.count = READ_ONCE(sqe->off);
3913 if (!req->io && io_alloc_async_ctx(req))
3916 data = &req->io->timeout;
3918 req->flags |= REQ_F_TIMEOUT;
3920 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3923 if (flags & IORING_TIMEOUT_ABS)
3924 data->mode = HRTIMER_MODE_ABS;
3926 data->mode = HRTIMER_MODE_REL;
3928 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3932 static int io_timeout(struct io_kiocb *req)
3935 struct io_ring_ctx *ctx = req->ctx;
3936 struct io_timeout_data *data;
3937 struct list_head *entry;
3940 data = &req->io->timeout;
3943 * sqe->off holds how many events that need to occur for this
3944 * timeout event to be satisfied. If it isn't set, then this is
3945 * a pure timeout request, sequence isn't used.
3947 count = req->timeout.count;
3949 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3950 spin_lock_irq(&ctx->completion_lock);
3951 entry = ctx->timeout_list.prev;
3955 req->sequence = ctx->cached_sq_head + count - 1;
3956 data->seq_offset = count;
3959 * Insertion sort, ensuring the first entry in the list is always
3960 * the one we need first.
3962 spin_lock_irq(&ctx->completion_lock);
3963 list_for_each_prev(entry, &ctx->timeout_list) {
3964 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3965 unsigned nxt_sq_head;
3966 long long tmp, tmp_nxt;
3967 u32 nxt_offset = nxt->io->timeout.seq_offset;
3969 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3973 * Since cached_sq_head + count - 1 can overflow, use type long
3976 tmp = (long long)ctx->cached_sq_head + count - 1;
3977 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3978 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3981 * cached_sq_head may overflow, and it will never overflow twice
3982 * once there is some timeout req still be valid.
3984 if (ctx->cached_sq_head < nxt_sq_head)
3991 * Sequence of reqs after the insert one and itself should
3992 * be adjusted because each timeout req consumes a slot.
3997 req->sequence -= span;
3999 list_add(&req->list, entry);
4000 data->timer.function = io_timeout_fn;
4001 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
4002 spin_unlock_irq(&ctx->completion_lock);
4006 static bool io_cancel_cb(struct io_wq_work *work, void *data)
4008 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4010 return req->user_data == (unsigned long) data;
4013 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
4015 enum io_wq_cancel cancel_ret;
4018 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
4019 switch (cancel_ret) {
4020 case IO_WQ_CANCEL_OK:
4023 case IO_WQ_CANCEL_RUNNING:
4026 case IO_WQ_CANCEL_NOTFOUND:
4034 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4035 struct io_kiocb *req, __u64 sqe_addr,
4036 struct io_kiocb **nxt, int success_ret)
4038 unsigned long flags;
4041 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4042 if (ret != -ENOENT) {
4043 spin_lock_irqsave(&ctx->completion_lock, flags);
4047 spin_lock_irqsave(&ctx->completion_lock, flags);
4048 ret = io_timeout_cancel(ctx, sqe_addr);
4051 ret = io_poll_cancel(ctx, sqe_addr);
4055 io_cqring_fill_event(req, ret);
4056 io_commit_cqring(ctx);
4057 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4058 io_cqring_ev_posted(ctx);
4061 req_set_fail_links(req);
4062 io_put_req_find_next(req, nxt);
4065 static int io_async_cancel_prep(struct io_kiocb *req,
4066 const struct io_uring_sqe *sqe)
4068 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4070 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4074 req->cancel.addr = READ_ONCE(sqe->addr);
4078 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
4080 struct io_ring_ctx *ctx = req->ctx;
4082 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
4086 static int io_files_update_prep(struct io_kiocb *req,
4087 const struct io_uring_sqe *sqe)
4089 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4092 req->files_update.offset = READ_ONCE(sqe->off);
4093 req->files_update.nr_args = READ_ONCE(sqe->len);
4094 if (!req->files_update.nr_args)
4096 req->files_update.arg = READ_ONCE(sqe->addr);
4100 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
4102 struct io_ring_ctx *ctx = req->ctx;
4103 struct io_uring_files_update up;
4109 up.offset = req->files_update.offset;
4110 up.fds = req->files_update.arg;
4112 mutex_lock(&ctx->uring_lock);
4113 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4114 mutex_unlock(&ctx->uring_lock);
4117 req_set_fail_links(req);
4118 io_cqring_add_event(req, ret);
4123 static int io_req_defer_prep(struct io_kiocb *req,
4124 const struct io_uring_sqe *sqe)
4128 if (io_op_defs[req->opcode].file_table) {
4129 ret = io_grab_files(req);
4134 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4136 switch (req->opcode) {
4139 case IORING_OP_READV:
4140 case IORING_OP_READ_FIXED:
4141 case IORING_OP_READ:
4142 ret = io_read_prep(req, sqe, true);
4144 case IORING_OP_WRITEV:
4145 case IORING_OP_WRITE_FIXED:
4146 case IORING_OP_WRITE:
4147 ret = io_write_prep(req, sqe, true);
4149 case IORING_OP_POLL_ADD:
4150 ret = io_poll_add_prep(req, sqe);
4152 case IORING_OP_POLL_REMOVE:
4153 ret = io_poll_remove_prep(req, sqe);
4155 case IORING_OP_FSYNC:
4156 ret = io_prep_fsync(req, sqe);
4158 case IORING_OP_SYNC_FILE_RANGE:
4159 ret = io_prep_sfr(req, sqe);
4161 case IORING_OP_SENDMSG:
4162 case IORING_OP_SEND:
4163 ret = io_sendmsg_prep(req, sqe);
4165 case IORING_OP_RECVMSG:
4166 case IORING_OP_RECV:
4167 ret = io_recvmsg_prep(req, sqe);
4169 case IORING_OP_CONNECT:
4170 ret = io_connect_prep(req, sqe);
4172 case IORING_OP_TIMEOUT:
4173 ret = io_timeout_prep(req, sqe, false);
4175 case IORING_OP_TIMEOUT_REMOVE:
4176 ret = io_timeout_remove_prep(req, sqe);
4178 case IORING_OP_ASYNC_CANCEL:
4179 ret = io_async_cancel_prep(req, sqe);
4181 case IORING_OP_LINK_TIMEOUT:
4182 ret = io_timeout_prep(req, sqe, true);
4184 case IORING_OP_ACCEPT:
4185 ret = io_accept_prep(req, sqe);
4187 case IORING_OP_FALLOCATE:
4188 ret = io_fallocate_prep(req, sqe);
4190 case IORING_OP_OPENAT:
4191 ret = io_openat_prep(req, sqe);
4193 case IORING_OP_CLOSE:
4194 ret = io_close_prep(req, sqe);
4196 case IORING_OP_FILES_UPDATE:
4197 ret = io_files_update_prep(req, sqe);
4199 case IORING_OP_STATX:
4200 ret = io_statx_prep(req, sqe);
4202 case IORING_OP_FADVISE:
4203 ret = io_fadvise_prep(req, sqe);
4205 case IORING_OP_MADVISE:
4206 ret = io_madvise_prep(req, sqe);
4208 case IORING_OP_OPENAT2:
4209 ret = io_openat2_prep(req, sqe);
4211 case IORING_OP_EPOLL_CTL:
4212 ret = io_epoll_ctl_prep(req, sqe);
4215 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4224 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4226 struct io_ring_ctx *ctx = req->ctx;
4229 /* Still need defer if there is pending req in defer list. */
4230 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4233 if (!req->io && io_alloc_async_ctx(req))
4236 ret = io_req_defer_prep(req, sqe);
4240 spin_lock_irq(&ctx->completion_lock);
4241 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4242 spin_unlock_irq(&ctx->completion_lock);
4246 trace_io_uring_defer(ctx, req, req->user_data);
4247 list_add_tail(&req->list, &ctx->defer_list);
4248 spin_unlock_irq(&ctx->completion_lock);
4249 return -EIOCBQUEUED;
4252 static void io_cleanup_req(struct io_kiocb *req)
4254 struct io_async_ctx *io = req->io;
4256 switch (req->opcode) {
4257 case IORING_OP_READV:
4258 case IORING_OP_READ_FIXED:
4259 case IORING_OP_READ:
4260 case IORING_OP_WRITEV:
4261 case IORING_OP_WRITE_FIXED:
4262 case IORING_OP_WRITE:
4263 if (io->rw.iov != io->rw.fast_iov)
4266 case IORING_OP_SENDMSG:
4267 case IORING_OP_RECVMSG:
4268 if (io->msg.iov != io->msg.fast_iov)
4271 case IORING_OP_OPENAT:
4272 case IORING_OP_OPENAT2:
4273 case IORING_OP_STATX:
4274 putname(req->open.filename);
4278 req->flags &= ~REQ_F_NEED_CLEANUP;
4281 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4282 struct io_kiocb **nxt, bool force_nonblock)
4284 struct io_ring_ctx *ctx = req->ctx;
4287 switch (req->opcode) {
4291 case IORING_OP_READV:
4292 case IORING_OP_READ_FIXED:
4293 case IORING_OP_READ:
4295 ret = io_read_prep(req, sqe, force_nonblock);
4299 ret = io_read(req, nxt, force_nonblock);
4301 case IORING_OP_WRITEV:
4302 case IORING_OP_WRITE_FIXED:
4303 case IORING_OP_WRITE:
4305 ret = io_write_prep(req, sqe, force_nonblock);
4309 ret = io_write(req, nxt, force_nonblock);
4311 case IORING_OP_FSYNC:
4313 ret = io_prep_fsync(req, sqe);
4317 ret = io_fsync(req, nxt, force_nonblock);
4319 case IORING_OP_POLL_ADD:
4321 ret = io_poll_add_prep(req, sqe);
4325 ret = io_poll_add(req, nxt);
4327 case IORING_OP_POLL_REMOVE:
4329 ret = io_poll_remove_prep(req, sqe);
4333 ret = io_poll_remove(req);
4335 case IORING_OP_SYNC_FILE_RANGE:
4337 ret = io_prep_sfr(req, sqe);
4341 ret = io_sync_file_range(req, nxt, force_nonblock);
4343 case IORING_OP_SENDMSG:
4344 case IORING_OP_SEND:
4346 ret = io_sendmsg_prep(req, sqe);
4350 if (req->opcode == IORING_OP_SENDMSG)
4351 ret = io_sendmsg(req, nxt, force_nonblock);
4353 ret = io_send(req, nxt, force_nonblock);
4355 case IORING_OP_RECVMSG:
4356 case IORING_OP_RECV:
4358 ret = io_recvmsg_prep(req, sqe);
4362 if (req->opcode == IORING_OP_RECVMSG)
4363 ret = io_recvmsg(req, nxt, force_nonblock);
4365 ret = io_recv(req, nxt, force_nonblock);
4367 case IORING_OP_TIMEOUT:
4369 ret = io_timeout_prep(req, sqe, false);
4373 ret = io_timeout(req);
4375 case IORING_OP_TIMEOUT_REMOVE:
4377 ret = io_timeout_remove_prep(req, sqe);
4381 ret = io_timeout_remove(req);
4383 case IORING_OP_ACCEPT:
4385 ret = io_accept_prep(req, sqe);
4389 ret = io_accept(req, nxt, force_nonblock);
4391 case IORING_OP_CONNECT:
4393 ret = io_connect_prep(req, sqe);
4397 ret = io_connect(req, nxt, force_nonblock);
4399 case IORING_OP_ASYNC_CANCEL:
4401 ret = io_async_cancel_prep(req, sqe);
4405 ret = io_async_cancel(req, nxt);
4407 case IORING_OP_FALLOCATE:
4409 ret = io_fallocate_prep(req, sqe);
4413 ret = io_fallocate(req, nxt, force_nonblock);
4415 case IORING_OP_OPENAT:
4417 ret = io_openat_prep(req, sqe);
4421 ret = io_openat(req, nxt, force_nonblock);
4423 case IORING_OP_CLOSE:
4425 ret = io_close_prep(req, sqe);
4429 ret = io_close(req, nxt, force_nonblock);
4431 case IORING_OP_FILES_UPDATE:
4433 ret = io_files_update_prep(req, sqe);
4437 ret = io_files_update(req, force_nonblock);
4439 case IORING_OP_STATX:
4441 ret = io_statx_prep(req, sqe);
4445 ret = io_statx(req, nxt, force_nonblock);
4447 case IORING_OP_FADVISE:
4449 ret = io_fadvise_prep(req, sqe);
4453 ret = io_fadvise(req, nxt, force_nonblock);
4455 case IORING_OP_MADVISE:
4457 ret = io_madvise_prep(req, sqe);
4461 ret = io_madvise(req, nxt, force_nonblock);
4463 case IORING_OP_OPENAT2:
4465 ret = io_openat2_prep(req, sqe);
4469 ret = io_openat2(req, nxt, force_nonblock);
4471 case IORING_OP_EPOLL_CTL:
4473 ret = io_epoll_ctl_prep(req, sqe);
4477 ret = io_epoll_ctl(req, nxt, force_nonblock);
4487 if (ctx->flags & IORING_SETUP_IOPOLL) {
4488 const bool in_async = io_wq_current_is_worker();
4490 if (req->result == -EAGAIN)
4493 /* workqueue context doesn't hold uring_lock, grab it now */
4495 mutex_lock(&ctx->uring_lock);
4497 io_iopoll_req_issued(req);
4500 mutex_unlock(&ctx->uring_lock);
4506 static void io_wq_submit_work(struct io_wq_work **workptr)
4508 struct io_wq_work *work = *workptr;
4509 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4510 struct io_kiocb *nxt = NULL;
4513 /* if NO_CANCEL is set, we must still run the work */
4514 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4515 IO_WQ_WORK_CANCEL) {
4520 req->in_async = true;
4522 ret = io_issue_sqe(req, NULL, &nxt, false);
4524 * We can get EAGAIN for polled IO even though we're
4525 * forcing a sync submission from here, since we can't
4526 * wait for request slots on the block side.
4534 /* drop submission reference */
4538 req_set_fail_links(req);
4539 io_cqring_add_event(req, ret);
4543 /* if a dependent link is ready, pass it back */
4545 io_wq_assign_next(workptr, nxt);
4548 static int io_req_needs_file(struct io_kiocb *req, int fd)
4550 if (!io_op_defs[req->opcode].needs_file)
4552 if ((fd == -1 || fd == AT_FDCWD) && io_op_defs[req->opcode].fd_non_neg)
4557 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4560 struct fixed_file_table *table;
4562 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4563 return table->files[index & IORING_FILE_TABLE_MASK];;
4566 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4567 const struct io_uring_sqe *sqe)
4569 struct io_ring_ctx *ctx = req->ctx;
4573 flags = READ_ONCE(sqe->flags);
4574 fd = READ_ONCE(sqe->fd);
4576 if (!io_req_needs_file(req, fd))
4579 if (flags & IOSQE_FIXED_FILE) {
4580 if (unlikely(!ctx->file_data ||
4581 (unsigned) fd >= ctx->nr_user_files))
4583 fd = array_index_nospec(fd, ctx->nr_user_files);
4584 req->file = io_file_from_index(ctx, fd);
4587 req->flags |= REQ_F_FIXED_FILE;
4588 percpu_ref_get(&ctx->file_data->refs);
4590 if (req->needs_fixed_file)
4592 trace_io_uring_file_get(ctx, fd);
4593 req->file = io_file_get(state, fd);
4594 if (unlikely(!req->file))
4601 static int io_grab_files(struct io_kiocb *req)
4604 struct io_ring_ctx *ctx = req->ctx;
4606 if (req->work.files)
4608 if (!ctx->ring_file)
4612 spin_lock_irq(&ctx->inflight_lock);
4614 * We use the f_ops->flush() handler to ensure that we can flush
4615 * out work accessing these files if the fd is closed. Check if
4616 * the fd has changed since we started down this path, and disallow
4617 * this operation if it has.
4619 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4620 list_add(&req->inflight_entry, &ctx->inflight_list);
4621 req->flags |= REQ_F_INFLIGHT;
4622 req->work.files = current->files;
4625 spin_unlock_irq(&ctx->inflight_lock);
4631 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4633 struct io_timeout_data *data = container_of(timer,
4634 struct io_timeout_data, timer);
4635 struct io_kiocb *req = data->req;
4636 struct io_ring_ctx *ctx = req->ctx;
4637 struct io_kiocb *prev = NULL;
4638 unsigned long flags;
4640 spin_lock_irqsave(&ctx->completion_lock, flags);
4643 * We don't expect the list to be empty, that will only happen if we
4644 * race with the completion of the linked work.
4646 if (!list_empty(&req->link_list)) {
4647 prev = list_entry(req->link_list.prev, struct io_kiocb,
4649 if (refcount_inc_not_zero(&prev->refs)) {
4650 list_del_init(&req->link_list);
4651 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4656 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4659 req_set_fail_links(prev);
4660 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4664 io_cqring_add_event(req, -ETIME);
4667 return HRTIMER_NORESTART;
4670 static void io_queue_linked_timeout(struct io_kiocb *req)
4672 struct io_ring_ctx *ctx = req->ctx;
4675 * If the list is now empty, then our linked request finished before
4676 * we got a chance to setup the timer
4678 spin_lock_irq(&ctx->completion_lock);
4679 if (!list_empty(&req->link_list)) {
4680 struct io_timeout_data *data = &req->io->timeout;
4682 data->timer.function = io_link_timeout_fn;
4683 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4686 spin_unlock_irq(&ctx->completion_lock);
4688 /* drop submission reference */
4692 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4694 struct io_kiocb *nxt;
4696 if (!(req->flags & REQ_F_LINK))
4699 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4701 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4704 req->flags |= REQ_F_LINK_TIMEOUT;
4708 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4710 struct io_kiocb *linked_timeout;
4711 struct io_kiocb *nxt = NULL;
4712 const struct cred *old_creds = NULL;
4716 linked_timeout = io_prep_linked_timeout(req);
4718 if (req->work.creds && req->work.creds != current_cred()) {
4720 revert_creds(old_creds);
4721 if (old_creds == req->work.creds)
4722 old_creds = NULL; /* restored original creds */
4724 old_creds = override_creds(req->work.creds);
4727 ret = io_issue_sqe(req, sqe, &nxt, true);
4730 * We async punt it if the file wasn't marked NOWAIT, or if the file
4731 * doesn't support non-blocking read/write attempts
4733 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4734 (req->flags & REQ_F_MUST_PUNT))) {
4736 if (io_op_defs[req->opcode].file_table) {
4737 ret = io_grab_files(req);
4743 * Queued up for async execution, worker will release
4744 * submit reference when the iocb is actually submitted.
4746 io_queue_async_work(req);
4751 /* drop submission reference */
4754 if (linked_timeout) {
4756 io_queue_linked_timeout(linked_timeout);
4758 io_put_req(linked_timeout);
4761 /* and drop final reference, if we failed */
4763 io_cqring_add_event(req, ret);
4764 req_set_fail_links(req);
4772 if (req->flags & REQ_F_FORCE_ASYNC)
4777 revert_creds(old_creds);
4780 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4784 ret = io_req_defer(req, sqe);
4786 if (ret != -EIOCBQUEUED) {
4788 io_cqring_add_event(req, ret);
4789 req_set_fail_links(req);
4790 io_double_put_req(req);
4792 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4793 ret = io_req_defer_prep(req, sqe);
4794 if (unlikely(ret < 0))
4797 * Never try inline submit of IOSQE_ASYNC is set, go straight
4798 * to async execution.
4800 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4801 io_queue_async_work(req);
4803 __io_queue_sqe(req, sqe);
4807 static inline void io_queue_link_head(struct io_kiocb *req)
4809 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4810 io_cqring_add_event(req, -ECANCELED);
4811 io_double_put_req(req);
4813 io_queue_sqe(req, NULL);
4816 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4817 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4819 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4820 struct io_submit_state *state, struct io_kiocb **link)
4822 struct io_ring_ctx *ctx = req->ctx;
4823 unsigned int sqe_flags;
4826 sqe_flags = READ_ONCE(sqe->flags);
4828 /* enforce forwards compatibility on users */
4829 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4834 id = READ_ONCE(sqe->personality);
4836 req->work.creds = idr_find(&ctx->personality_idr, id);
4837 if (unlikely(!req->work.creds)) {
4841 get_cred(req->work.creds);
4844 /* same numerical values with corresponding REQ_F_*, safe to copy */
4845 req->flags |= sqe_flags & (IOSQE_IO_DRAIN|IOSQE_IO_HARDLINK|
4848 ret = io_req_set_file(state, req, sqe);
4849 if (unlikely(ret)) {
4851 io_cqring_add_event(req, ret);
4852 io_double_put_req(req);
4857 * If we already have a head request, queue this one for async
4858 * submittal once the head completes. If we don't have a head but
4859 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4860 * submitted sync once the chain is complete. If none of those
4861 * conditions are true (normal request), then just queue it.
4864 struct io_kiocb *head = *link;
4867 * Taking sequential execution of a link, draining both sides
4868 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
4869 * requests in the link. So, it drains the head and the
4870 * next after the link request. The last one is done via
4871 * drain_next flag to persist the effect across calls.
4873 if (sqe_flags & IOSQE_IO_DRAIN) {
4874 head->flags |= REQ_F_IO_DRAIN;
4875 ctx->drain_next = 1;
4877 if (io_alloc_async_ctx(req)) {
4882 ret = io_req_defer_prep(req, sqe);
4884 /* fail even hard links since we don't submit */
4885 head->flags |= REQ_F_FAIL_LINK;
4888 trace_io_uring_link(ctx, req, head);
4889 list_add_tail(&req->link_list, &head->link_list);
4891 /* last request of a link, enqueue the link */
4892 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4893 io_queue_link_head(head);
4897 if (unlikely(ctx->drain_next)) {
4898 req->flags |= REQ_F_IO_DRAIN;
4899 req->ctx->drain_next = 0;
4901 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4902 req->flags |= REQ_F_LINK;
4903 INIT_LIST_HEAD(&req->link_list);
4904 ret = io_req_defer_prep(req, sqe);
4906 req->flags |= REQ_F_FAIL_LINK;
4909 io_queue_sqe(req, sqe);
4917 * Batched submission is done, ensure local IO is flushed out.
4919 static void io_submit_state_end(struct io_submit_state *state)
4921 blk_finish_plug(&state->plug);
4923 if (state->free_reqs)
4924 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
4928 * Start submission side cache.
4930 static void io_submit_state_start(struct io_submit_state *state,
4931 unsigned int max_ios)
4933 blk_start_plug(&state->plug);
4934 state->free_reqs = 0;
4936 state->ios_left = max_ios;
4939 static void io_commit_sqring(struct io_ring_ctx *ctx)
4941 struct io_rings *rings = ctx->rings;
4944 * Ensure any loads from the SQEs are done at this point,
4945 * since once we write the new head, the application could
4946 * write new data to them.
4948 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4952 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4953 * that is mapped by userspace. This means that care needs to be taken to
4954 * ensure that reads are stable, as we cannot rely on userspace always
4955 * being a good citizen. If members of the sqe are validated and then later
4956 * used, it's important that those reads are done through READ_ONCE() to
4957 * prevent a re-load down the line.
4959 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4960 const struct io_uring_sqe **sqe_ptr)
4962 u32 *sq_array = ctx->sq_array;
4966 * The cached sq head (or cq tail) serves two purposes:
4968 * 1) allows us to batch the cost of updating the user visible
4970 * 2) allows the kernel side to track the head on its own, even
4971 * though the application is the one updating it.
4973 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4974 if (likely(head < ctx->sq_entries)) {
4976 * All io need record the previous position, if LINK vs DARIN,
4977 * it can be used to mark the position of the first IO in the
4980 req->sequence = ctx->cached_sq_head;
4981 *sqe_ptr = &ctx->sq_sqes[head];
4982 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4983 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4984 ctx->cached_sq_head++;
4988 /* drop invalid entries */
4989 ctx->cached_sq_head++;
4990 ctx->cached_sq_dropped++;
4991 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4995 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4996 struct file *ring_file, int ring_fd,
4997 struct mm_struct **mm, bool async)
4999 struct io_submit_state state, *statep = NULL;
5000 struct io_kiocb *link = NULL;
5001 int i, submitted = 0;
5002 bool mm_fault = false;
5004 /* if we have a backlog and couldn't flush it all, return BUSY */
5005 if (test_bit(0, &ctx->sq_check_overflow)) {
5006 if (!list_empty(&ctx->cq_overflow_list) &&
5007 !io_cqring_overflow_flush(ctx, false))
5011 /* make sure SQ entry isn't read before tail */
5012 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
5014 if (!percpu_ref_tryget_many(&ctx->refs, nr))
5017 if (nr > IO_PLUG_THRESHOLD) {
5018 io_submit_state_start(&state, nr);
5022 ctx->ring_fd = ring_fd;
5023 ctx->ring_file = ring_file;
5025 for (i = 0; i < nr; i++) {
5026 const struct io_uring_sqe *sqe;
5027 struct io_kiocb *req;
5030 req = io_get_req(ctx, statep);
5031 if (unlikely(!req)) {
5033 submitted = -EAGAIN;
5036 if (!io_get_sqring(ctx, req, &sqe)) {
5037 __io_req_do_free(req);
5041 /* will complete beyond this point, count as submitted */
5044 if (unlikely(req->opcode >= IORING_OP_LAST)) {
5047 io_cqring_add_event(req, err);
5048 io_double_put_req(req);
5052 if (io_op_defs[req->opcode].needs_mm && !*mm) {
5053 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
5054 if (unlikely(mm_fault)) {
5058 use_mm(ctx->sqo_mm);
5062 req->in_async = async;
5063 req->needs_fixed_file = async;
5064 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
5066 if (!io_submit_sqe(req, sqe, statep, &link))
5070 if (unlikely(submitted != nr)) {
5071 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
5073 percpu_ref_put_many(&ctx->refs, nr - ref_used);
5076 io_queue_link_head(link);
5078 io_submit_state_end(&state);
5080 /* Commit SQ ring head once we've consumed and submitted all SQEs */
5081 io_commit_sqring(ctx);
5086 static int io_sq_thread(void *data)
5088 struct io_ring_ctx *ctx = data;
5089 struct mm_struct *cur_mm = NULL;
5090 const struct cred *old_cred;
5091 mm_segment_t old_fs;
5093 unsigned long timeout;
5096 complete(&ctx->completions[1]);
5100 old_cred = override_creds(ctx->creds);
5102 timeout = jiffies + ctx->sq_thread_idle;
5103 while (!kthread_should_park()) {
5104 unsigned int to_submit;
5106 if (!list_empty(&ctx->poll_list)) {
5107 unsigned nr_events = 0;
5109 mutex_lock(&ctx->uring_lock);
5110 if (!list_empty(&ctx->poll_list))
5111 io_iopoll_getevents(ctx, &nr_events, 0);
5113 timeout = jiffies + ctx->sq_thread_idle;
5114 mutex_unlock(&ctx->uring_lock);
5117 to_submit = io_sqring_entries(ctx);
5120 * If submit got -EBUSY, flag us as needing the application
5121 * to enter the kernel to reap and flush events.
5123 if (!to_submit || ret == -EBUSY) {
5125 * Drop cur_mm before scheduling, we can't hold it for
5126 * long periods (or over schedule()). Do this before
5127 * adding ourselves to the waitqueue, as the unuse/drop
5137 * We're polling. If we're within the defined idle
5138 * period, then let us spin without work before going
5139 * to sleep. The exception is if we got EBUSY doing
5140 * more IO, we should wait for the application to
5141 * reap events and wake us up.
5143 if (!list_empty(&ctx->poll_list) ||
5144 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5145 !percpu_ref_is_dying(&ctx->refs))) {
5150 prepare_to_wait(&ctx->sqo_wait, &wait,
5151 TASK_INTERRUPTIBLE);
5154 * While doing polled IO, before going to sleep, we need
5155 * to check if there are new reqs added to poll_list, it
5156 * is because reqs may have been punted to io worker and
5157 * will be added to poll_list later, hence check the
5160 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
5161 !list_empty_careful(&ctx->poll_list)) {
5162 finish_wait(&ctx->sqo_wait, &wait);
5166 /* Tell userspace we may need a wakeup call */
5167 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
5168 /* make sure to read SQ tail after writing flags */
5171 to_submit = io_sqring_entries(ctx);
5172 if (!to_submit || ret == -EBUSY) {
5173 if (kthread_should_park()) {
5174 finish_wait(&ctx->sqo_wait, &wait);
5177 if (signal_pending(current))
5178 flush_signals(current);
5180 finish_wait(&ctx->sqo_wait, &wait);
5182 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5185 finish_wait(&ctx->sqo_wait, &wait);
5187 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5190 mutex_lock(&ctx->uring_lock);
5191 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
5192 mutex_unlock(&ctx->uring_lock);
5193 timeout = jiffies + ctx->sq_thread_idle;
5201 revert_creds(old_cred);
5208 struct io_wait_queue {
5209 struct wait_queue_entry wq;
5210 struct io_ring_ctx *ctx;
5212 unsigned nr_timeouts;
5215 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
5217 struct io_ring_ctx *ctx = iowq->ctx;
5220 * Wake up if we have enough events, or if a timeout occurred since we
5221 * started waiting. For timeouts, we always want to return to userspace,
5222 * regardless of event count.
5224 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
5225 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5228 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5229 int wake_flags, void *key)
5231 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5234 /* use noflush == true, as we can't safely rely on locking context */
5235 if (!io_should_wake(iowq, true))
5238 return autoremove_wake_function(curr, mode, wake_flags, key);
5242 * Wait until events become available, if we don't already have some. The
5243 * application must reap them itself, as they reside on the shared cq ring.
5245 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5246 const sigset_t __user *sig, size_t sigsz)
5248 struct io_wait_queue iowq = {
5251 .func = io_wake_function,
5252 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5255 .to_wait = min_events,
5257 struct io_rings *rings = ctx->rings;
5260 if (io_cqring_events(ctx, false) >= min_events)
5264 #ifdef CONFIG_COMPAT
5265 if (in_compat_syscall())
5266 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5270 ret = set_user_sigmask(sig, sigsz);
5276 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5277 trace_io_uring_cqring_wait(ctx, min_events);
5279 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5280 TASK_INTERRUPTIBLE);
5281 if (io_should_wake(&iowq, false))
5284 if (signal_pending(current)) {
5289 finish_wait(&ctx->wait, &iowq.wq);
5291 restore_saved_sigmask_unless(ret == -EINTR);
5293 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5296 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5298 #if defined(CONFIG_UNIX)
5299 if (ctx->ring_sock) {
5300 struct sock *sock = ctx->ring_sock->sk;
5301 struct sk_buff *skb;
5303 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5309 for (i = 0; i < ctx->nr_user_files; i++) {
5312 file = io_file_from_index(ctx, i);
5319 static void io_file_ref_kill(struct percpu_ref *ref)
5321 struct fixed_file_data *data;
5323 data = container_of(ref, struct fixed_file_data, refs);
5324 complete(&data->done);
5327 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5329 struct fixed_file_data *data = ctx->file_data;
5330 unsigned nr_tables, i;
5335 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5336 flush_work(&data->ref_work);
5337 wait_for_completion(&data->done);
5338 io_ring_file_ref_flush(data);
5339 percpu_ref_exit(&data->refs);
5341 __io_sqe_files_unregister(ctx);
5342 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5343 for (i = 0; i < nr_tables; i++)
5344 kfree(data->table[i].files);
5347 ctx->file_data = NULL;
5348 ctx->nr_user_files = 0;
5352 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5354 if (ctx->sqo_thread) {
5355 wait_for_completion(&ctx->completions[1]);
5357 * The park is a bit of a work-around, without it we get
5358 * warning spews on shutdown with SQPOLL set and affinity
5359 * set to a single CPU.
5361 kthread_park(ctx->sqo_thread);
5362 kthread_stop(ctx->sqo_thread);
5363 ctx->sqo_thread = NULL;
5367 static void io_finish_async(struct io_ring_ctx *ctx)
5369 io_sq_thread_stop(ctx);
5372 io_wq_destroy(ctx->io_wq);
5377 #if defined(CONFIG_UNIX)
5379 * Ensure the UNIX gc is aware of our file set, so we are certain that
5380 * the io_uring can be safely unregistered on process exit, even if we have
5381 * loops in the file referencing.
5383 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5385 struct sock *sk = ctx->ring_sock->sk;
5386 struct scm_fp_list *fpl;
5387 struct sk_buff *skb;
5390 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5391 unsigned long inflight = ctx->user->unix_inflight + nr;
5393 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5397 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5401 skb = alloc_skb(0, GFP_KERNEL);
5410 fpl->user = get_uid(ctx->user);
5411 for (i = 0; i < nr; i++) {
5412 struct file *file = io_file_from_index(ctx, i + offset);
5416 fpl->fp[nr_files] = get_file(file);
5417 unix_inflight(fpl->user, fpl->fp[nr_files]);
5422 fpl->max = SCM_MAX_FD;
5423 fpl->count = nr_files;
5424 UNIXCB(skb).fp = fpl;
5425 skb->destructor = unix_destruct_scm;
5426 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5427 skb_queue_head(&sk->sk_receive_queue, skb);
5429 for (i = 0; i < nr_files; i++)
5440 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5441 * causes regular reference counting to break down. We rely on the UNIX
5442 * garbage collection to take care of this problem for us.
5444 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5446 unsigned left, total;
5450 left = ctx->nr_user_files;
5452 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
5454 ret = __io_sqe_files_scm(ctx, this_files, total);
5458 total += this_files;
5464 while (total < ctx->nr_user_files) {
5465 struct file *file = io_file_from_index(ctx, total);
5475 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5481 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5486 for (i = 0; i < nr_tables; i++) {
5487 struct fixed_file_table *table = &ctx->file_data->table[i];
5488 unsigned this_files;
5490 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5491 table->files = kcalloc(this_files, sizeof(struct file *),
5495 nr_files -= this_files;
5501 for (i = 0; i < nr_tables; i++) {
5502 struct fixed_file_table *table = &ctx->file_data->table[i];
5503 kfree(table->files);
5508 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5510 #if defined(CONFIG_UNIX)
5511 struct sock *sock = ctx->ring_sock->sk;
5512 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5513 struct sk_buff *skb;
5516 __skb_queue_head_init(&list);
5519 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5520 * remove this entry and rearrange the file array.
5522 skb = skb_dequeue(head);
5524 struct scm_fp_list *fp;
5526 fp = UNIXCB(skb).fp;
5527 for (i = 0; i < fp->count; i++) {
5530 if (fp->fp[i] != file)
5533 unix_notinflight(fp->user, fp->fp[i]);
5534 left = fp->count - 1 - i;
5536 memmove(&fp->fp[i], &fp->fp[i + 1],
5537 left * sizeof(struct file *));
5544 __skb_queue_tail(&list, skb);
5554 __skb_queue_tail(&list, skb);
5556 skb = skb_dequeue(head);
5559 if (skb_peek(&list)) {
5560 spin_lock_irq(&head->lock);
5561 while ((skb = __skb_dequeue(&list)) != NULL)
5562 __skb_queue_tail(head, skb);
5563 spin_unlock_irq(&head->lock);
5570 struct io_file_put {
5571 struct llist_node llist;
5573 struct completion *done;
5576 static void io_ring_file_ref_flush(struct fixed_file_data *data)
5578 struct io_file_put *pfile, *tmp;
5579 struct llist_node *node;
5581 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5582 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5583 io_ring_file_put(data->ctx, pfile->file);
5585 complete(pfile->done);
5592 static void io_ring_file_ref_switch(struct work_struct *work)
5594 struct fixed_file_data *data;
5596 data = container_of(work, struct fixed_file_data, ref_work);
5597 io_ring_file_ref_flush(data);
5598 percpu_ref_get(&data->refs);
5599 percpu_ref_switch_to_percpu(&data->refs);
5602 static void io_file_data_ref_zero(struct percpu_ref *ref)
5604 struct fixed_file_data *data;
5606 data = container_of(ref, struct fixed_file_data, refs);
5609 * We can't safely switch from inside this context, punt to wq. If
5610 * the table ref is going away, the table is being unregistered.
5611 * Don't queue up the async work for that case, the caller will
5614 if (!percpu_ref_is_dying(&data->refs))
5615 queue_work(system_wq, &data->ref_work);
5618 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5621 __s32 __user *fds = (__s32 __user *) arg;
5631 if (nr_args > IORING_MAX_FIXED_FILES)
5634 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5635 if (!ctx->file_data)
5637 ctx->file_data->ctx = ctx;
5638 init_completion(&ctx->file_data->done);
5640 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5641 ctx->file_data->table = kcalloc(nr_tables,
5642 sizeof(struct fixed_file_table),
5644 if (!ctx->file_data->table) {
5645 kfree(ctx->file_data);
5646 ctx->file_data = NULL;
5650 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5651 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5652 kfree(ctx->file_data->table);
5653 kfree(ctx->file_data);
5654 ctx->file_data = NULL;
5657 ctx->file_data->put_llist.first = NULL;
5658 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5660 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5661 percpu_ref_exit(&ctx->file_data->refs);
5662 kfree(ctx->file_data->table);
5663 kfree(ctx->file_data);
5664 ctx->file_data = NULL;
5668 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5669 struct fixed_file_table *table;
5673 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5675 /* allow sparse sets */
5681 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5682 index = i & IORING_FILE_TABLE_MASK;
5690 * Don't allow io_uring instances to be registered. If UNIX
5691 * isn't enabled, then this causes a reference cycle and this
5692 * instance can never get freed. If UNIX is enabled we'll
5693 * handle it just fine, but there's still no point in allowing
5694 * a ring fd as it doesn't support regular read/write anyway.
5696 if (file->f_op == &io_uring_fops) {
5701 table->files[index] = file;
5705 for (i = 0; i < ctx->nr_user_files; i++) {
5706 file = io_file_from_index(ctx, i);
5710 for (i = 0; i < nr_tables; i++)
5711 kfree(ctx->file_data->table[i].files);
5713 kfree(ctx->file_data->table);
5714 kfree(ctx->file_data);
5715 ctx->file_data = NULL;
5716 ctx->nr_user_files = 0;
5720 ret = io_sqe_files_scm(ctx);
5722 io_sqe_files_unregister(ctx);
5727 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5730 #if defined(CONFIG_UNIX)
5731 struct sock *sock = ctx->ring_sock->sk;
5732 struct sk_buff_head *head = &sock->sk_receive_queue;
5733 struct sk_buff *skb;
5736 * See if we can merge this file into an existing skb SCM_RIGHTS
5737 * file set. If there's no room, fall back to allocating a new skb
5738 * and filling it in.
5740 spin_lock_irq(&head->lock);
5741 skb = skb_peek(head);
5743 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5745 if (fpl->count < SCM_MAX_FD) {
5746 __skb_unlink(skb, head);
5747 spin_unlock_irq(&head->lock);
5748 fpl->fp[fpl->count] = get_file(file);
5749 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5751 spin_lock_irq(&head->lock);
5752 __skb_queue_head(head, skb);
5757 spin_unlock_irq(&head->lock);
5764 return __io_sqe_files_scm(ctx, 1, index);
5770 static void io_atomic_switch(struct percpu_ref *ref)
5772 struct fixed_file_data *data;
5774 data = container_of(ref, struct fixed_file_data, refs);
5775 clear_bit(FFD_F_ATOMIC, &data->state);
5778 static bool io_queue_file_removal(struct fixed_file_data *data,
5781 struct io_file_put *pfile, pfile_stack;
5782 DECLARE_COMPLETION_ONSTACK(done);
5785 * If we fail allocating the struct we need for doing async reomval
5786 * of this file, just punt to sync and wait for it.
5788 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5790 pfile = &pfile_stack;
5791 pfile->done = &done;
5795 llist_add(&pfile->llist, &data->put_llist);
5797 if (pfile == &pfile_stack) {
5798 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5799 percpu_ref_put(&data->refs);
5800 percpu_ref_switch_to_atomic(&data->refs,
5803 wait_for_completion(&done);
5804 flush_work(&data->ref_work);
5811 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5812 struct io_uring_files_update *up,
5815 struct fixed_file_data *data = ctx->file_data;
5816 bool ref_switch = false;
5822 if (check_add_overflow(up->offset, nr_args, &done))
5824 if (done > ctx->nr_user_files)
5828 fds = u64_to_user_ptr(up->fds);
5830 struct fixed_file_table *table;
5834 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5838 i = array_index_nospec(up->offset, ctx->nr_user_files);
5839 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5840 index = i & IORING_FILE_TABLE_MASK;
5841 if (table->files[index]) {
5842 file = io_file_from_index(ctx, index);
5843 table->files[index] = NULL;
5844 if (io_queue_file_removal(data, file))
5854 * Don't allow io_uring instances to be registered. If
5855 * UNIX isn't enabled, then this causes a reference
5856 * cycle and this instance can never get freed. If UNIX
5857 * is enabled we'll handle it just fine, but there's
5858 * still no point in allowing a ring fd as it doesn't
5859 * support regular read/write anyway.
5861 if (file->f_op == &io_uring_fops) {
5866 table->files[index] = file;
5867 err = io_sqe_file_register(ctx, file, i);
5876 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5877 percpu_ref_put(&data->refs);
5878 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5881 return done ? done : err;
5883 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5886 struct io_uring_files_update up;
5888 if (!ctx->file_data)
5892 if (copy_from_user(&up, arg, sizeof(up)))
5897 return __io_sqe_files_update(ctx, &up, nr_args);
5900 static void io_put_work(struct io_wq_work *work)
5902 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5907 static void io_get_work(struct io_wq_work *work)
5909 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5911 refcount_inc(&req->refs);
5914 static int io_init_wq_offload(struct io_ring_ctx *ctx,
5915 struct io_uring_params *p)
5917 struct io_wq_data data;
5919 struct io_ring_ctx *ctx_attach;
5920 unsigned int concurrency;
5923 data.user = ctx->user;
5924 data.get_work = io_get_work;
5925 data.put_work = io_put_work;
5927 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
5928 /* Do QD, or 4 * CPUS, whatever is smallest */
5929 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5931 ctx->io_wq = io_wq_create(concurrency, &data);
5932 if (IS_ERR(ctx->io_wq)) {
5933 ret = PTR_ERR(ctx->io_wq);
5939 f = fdget(p->wq_fd);
5943 if (f.file->f_op != &io_uring_fops) {
5948 ctx_attach = f.file->private_data;
5949 /* @io_wq is protected by holding the fd */
5950 if (!io_wq_get(ctx_attach->io_wq, &data)) {
5955 ctx->io_wq = ctx_attach->io_wq;
5961 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5962 struct io_uring_params *p)
5966 init_waitqueue_head(&ctx->sqo_wait);
5967 mmgrab(current->mm);
5968 ctx->sqo_mm = current->mm;
5970 if (ctx->flags & IORING_SETUP_SQPOLL) {
5972 if (!capable(CAP_SYS_ADMIN))
5975 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5976 if (!ctx->sq_thread_idle)
5977 ctx->sq_thread_idle = HZ;
5979 if (p->flags & IORING_SETUP_SQ_AFF) {
5980 int cpu = p->sq_thread_cpu;
5983 if (cpu >= nr_cpu_ids)
5985 if (!cpu_online(cpu))
5988 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5992 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5995 if (IS_ERR(ctx->sqo_thread)) {
5996 ret = PTR_ERR(ctx->sqo_thread);
5997 ctx->sqo_thread = NULL;
6000 wake_up_process(ctx->sqo_thread);
6001 } else if (p->flags & IORING_SETUP_SQ_AFF) {
6002 /* Can't have SQ_AFF without SQPOLL */
6007 ret = io_init_wq_offload(ctx, p);
6013 io_finish_async(ctx);
6014 mmdrop(ctx->sqo_mm);
6019 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
6021 atomic_long_sub(nr_pages, &user->locked_vm);
6024 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
6026 unsigned long page_limit, cur_pages, new_pages;
6028 /* Don't allow more pages than we can safely lock */
6029 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
6032 cur_pages = atomic_long_read(&user->locked_vm);
6033 new_pages = cur_pages + nr_pages;
6034 if (new_pages > page_limit)
6036 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
6037 new_pages) != cur_pages);
6042 static void io_mem_free(void *ptr)
6049 page = virt_to_head_page(ptr);
6050 if (put_page_testzero(page))
6051 free_compound_page(page);
6054 static void *io_mem_alloc(size_t size)
6056 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
6059 return (void *) __get_free_pages(gfp_flags, get_order(size));
6062 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
6065 struct io_rings *rings;
6066 size_t off, sq_array_size;
6068 off = struct_size(rings, cqes, cq_entries);
6069 if (off == SIZE_MAX)
6073 off = ALIGN(off, SMP_CACHE_BYTES);
6078 sq_array_size = array_size(sizeof(u32), sq_entries);
6079 if (sq_array_size == SIZE_MAX)
6082 if (check_add_overflow(off, sq_array_size, &off))
6091 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
6095 pages = (size_t)1 << get_order(
6096 rings_size(sq_entries, cq_entries, NULL));
6097 pages += (size_t)1 << get_order(
6098 array_size(sizeof(struct io_uring_sqe), sq_entries));
6103 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6107 if (!ctx->user_bufs)
6110 for (i = 0; i < ctx->nr_user_bufs; i++) {
6111 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6113 for (j = 0; j < imu->nr_bvecs; j++)
6114 unpin_user_page(imu->bvec[j].bv_page);
6116 if (ctx->account_mem)
6117 io_unaccount_mem(ctx->user, imu->nr_bvecs);
6122 kfree(ctx->user_bufs);
6123 ctx->user_bufs = NULL;
6124 ctx->nr_user_bufs = 0;
6128 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6129 void __user *arg, unsigned index)
6131 struct iovec __user *src;
6133 #ifdef CONFIG_COMPAT
6135 struct compat_iovec __user *ciovs;
6136 struct compat_iovec ciov;
6138 ciovs = (struct compat_iovec __user *) arg;
6139 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6142 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
6143 dst->iov_len = ciov.iov_len;
6147 src = (struct iovec __user *) arg;
6148 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6153 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6156 struct vm_area_struct **vmas = NULL;
6157 struct page **pages = NULL;
6158 int i, j, got_pages = 0;
6163 if (!nr_args || nr_args > UIO_MAXIOV)
6166 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6168 if (!ctx->user_bufs)
6171 for (i = 0; i < nr_args; i++) {
6172 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6173 unsigned long off, start, end, ubuf;
6178 ret = io_copy_iov(ctx, &iov, arg, i);
6183 * Don't impose further limits on the size and buffer
6184 * constraints here, we'll -EINVAL later when IO is
6185 * submitted if they are wrong.
6188 if (!iov.iov_base || !iov.iov_len)
6191 /* arbitrary limit, but we need something */
6192 if (iov.iov_len > SZ_1G)
6195 ubuf = (unsigned long) iov.iov_base;
6196 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6197 start = ubuf >> PAGE_SHIFT;
6198 nr_pages = end - start;
6200 if (ctx->account_mem) {
6201 ret = io_account_mem(ctx->user, nr_pages);
6207 if (!pages || nr_pages > got_pages) {
6210 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
6212 vmas = kvmalloc_array(nr_pages,
6213 sizeof(struct vm_area_struct *),
6215 if (!pages || !vmas) {
6217 if (ctx->account_mem)
6218 io_unaccount_mem(ctx->user, nr_pages);
6221 got_pages = nr_pages;
6224 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
6228 if (ctx->account_mem)
6229 io_unaccount_mem(ctx->user, nr_pages);
6234 down_read(¤t->mm->mmap_sem);
6235 pret = pin_user_pages(ubuf, nr_pages,
6236 FOLL_WRITE | FOLL_LONGTERM,
6238 if (pret == nr_pages) {
6239 /* don't support file backed memory */
6240 for (j = 0; j < nr_pages; j++) {
6241 struct vm_area_struct *vma = vmas[j];
6244 !is_file_hugepages(vma->vm_file)) {
6250 ret = pret < 0 ? pret : -EFAULT;
6252 up_read(¤t->mm->mmap_sem);
6255 * if we did partial map, or found file backed vmas,
6256 * release any pages we did get
6259 unpin_user_pages(pages, pret);
6260 if (ctx->account_mem)
6261 io_unaccount_mem(ctx->user, nr_pages);
6266 off = ubuf & ~PAGE_MASK;
6268 for (j = 0; j < nr_pages; j++) {
6271 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6272 imu->bvec[j].bv_page = pages[j];
6273 imu->bvec[j].bv_len = vec_len;
6274 imu->bvec[j].bv_offset = off;
6278 /* store original address for later verification */
6280 imu->len = iov.iov_len;
6281 imu->nr_bvecs = nr_pages;
6283 ctx->nr_user_bufs++;
6291 io_sqe_buffer_unregister(ctx);
6295 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6297 __s32 __user *fds = arg;
6303 if (copy_from_user(&fd, fds, sizeof(*fds)))
6306 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6307 if (IS_ERR(ctx->cq_ev_fd)) {
6308 int ret = PTR_ERR(ctx->cq_ev_fd);
6309 ctx->cq_ev_fd = NULL;
6316 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6318 if (ctx->cq_ev_fd) {
6319 eventfd_ctx_put(ctx->cq_ev_fd);
6320 ctx->cq_ev_fd = NULL;
6327 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6329 io_finish_async(ctx);
6331 mmdrop(ctx->sqo_mm);
6333 io_iopoll_reap_events(ctx);
6334 io_sqe_buffer_unregister(ctx);
6335 io_sqe_files_unregister(ctx);
6336 io_eventfd_unregister(ctx);
6337 idr_destroy(&ctx->personality_idr);
6339 #if defined(CONFIG_UNIX)
6340 if (ctx->ring_sock) {
6341 ctx->ring_sock->file = NULL; /* so that iput() is called */
6342 sock_release(ctx->ring_sock);
6346 io_mem_free(ctx->rings);
6347 io_mem_free(ctx->sq_sqes);
6349 percpu_ref_exit(&ctx->refs);
6350 if (ctx->account_mem)
6351 io_unaccount_mem(ctx->user,
6352 ring_pages(ctx->sq_entries, ctx->cq_entries));
6353 free_uid(ctx->user);
6354 put_cred(ctx->creds);
6355 kfree(ctx->completions);
6356 kfree(ctx->cancel_hash);
6357 kmem_cache_free(req_cachep, ctx->fallback_req);
6361 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6363 struct io_ring_ctx *ctx = file->private_data;
6366 poll_wait(file, &ctx->cq_wait, wait);
6368 * synchronizes with barrier from wq_has_sleeper call in
6372 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6373 ctx->rings->sq_ring_entries)
6374 mask |= EPOLLOUT | EPOLLWRNORM;
6375 if (io_cqring_events(ctx, false))
6376 mask |= EPOLLIN | EPOLLRDNORM;
6381 static int io_uring_fasync(int fd, struct file *file, int on)
6383 struct io_ring_ctx *ctx = file->private_data;
6385 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6388 static int io_remove_personalities(int id, void *p, void *data)
6390 struct io_ring_ctx *ctx = data;
6391 const struct cred *cred;
6393 cred = idr_remove(&ctx->personality_idr, id);
6399 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6401 mutex_lock(&ctx->uring_lock);
6402 percpu_ref_kill(&ctx->refs);
6403 mutex_unlock(&ctx->uring_lock);
6406 * Wait for sq thread to idle, if we have one. It won't spin on new
6407 * work after we've killed the ctx ref above. This is important to do
6408 * before we cancel existing commands, as the thread could otherwise
6409 * be queueing new work post that. If that's work we need to cancel,
6410 * it could cause shutdown to hang.
6412 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
6415 io_kill_timeouts(ctx);
6416 io_poll_remove_all(ctx);
6419 io_wq_cancel_all(ctx->io_wq);
6421 io_iopoll_reap_events(ctx);
6422 /* if we failed setting up the ctx, we might not have any rings */
6424 io_cqring_overflow_flush(ctx, true);
6425 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
6426 wait_for_completion(&ctx->completions[0]);
6427 io_ring_ctx_free(ctx);
6430 static int io_uring_release(struct inode *inode, struct file *file)
6432 struct io_ring_ctx *ctx = file->private_data;
6434 file->private_data = NULL;
6435 io_ring_ctx_wait_and_kill(ctx);
6439 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6440 struct files_struct *files)
6442 struct io_kiocb *req;
6445 while (!list_empty_careful(&ctx->inflight_list)) {
6446 struct io_kiocb *cancel_req = NULL;
6448 spin_lock_irq(&ctx->inflight_lock);
6449 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
6450 if (req->work.files != files)
6452 /* req is being completed, ignore */
6453 if (!refcount_inc_not_zero(&req->refs))
6459 prepare_to_wait(&ctx->inflight_wait, &wait,
6460 TASK_UNINTERRUPTIBLE);
6461 spin_unlock_irq(&ctx->inflight_lock);
6463 /* We need to keep going until we don't find a matching req */
6467 if (cancel_req->flags & REQ_F_OVERFLOW) {
6468 spin_lock_irq(&ctx->completion_lock);
6469 list_del(&cancel_req->list);
6470 cancel_req->flags &= ~REQ_F_OVERFLOW;
6471 if (list_empty(&ctx->cq_overflow_list)) {
6472 clear_bit(0, &ctx->sq_check_overflow);
6473 clear_bit(0, &ctx->cq_check_overflow);
6475 spin_unlock_irq(&ctx->completion_lock);
6477 WRITE_ONCE(ctx->rings->cq_overflow,
6478 atomic_inc_return(&ctx->cached_cq_overflow));
6481 * Put inflight ref and overflow ref. If that's
6482 * all we had, then we're done with this request.
6484 if (refcount_sub_and_test(2, &cancel_req->refs)) {
6485 io_put_req(cancel_req);
6490 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6491 io_put_req(cancel_req);
6494 finish_wait(&ctx->inflight_wait, &wait);
6497 static int io_uring_flush(struct file *file, void *data)
6499 struct io_ring_ctx *ctx = file->private_data;
6501 io_uring_cancel_files(ctx, data);
6504 * If the task is going away, cancel work it may have pending
6506 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
6507 io_wq_cancel_pid(ctx->io_wq, task_pid_vnr(current));
6512 static void *io_uring_validate_mmap_request(struct file *file,
6513 loff_t pgoff, size_t sz)
6515 struct io_ring_ctx *ctx = file->private_data;
6516 loff_t offset = pgoff << PAGE_SHIFT;
6521 case IORING_OFF_SQ_RING:
6522 case IORING_OFF_CQ_RING:
6525 case IORING_OFF_SQES:
6529 return ERR_PTR(-EINVAL);
6532 page = virt_to_head_page(ptr);
6533 if (sz > page_size(page))
6534 return ERR_PTR(-EINVAL);
6541 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6543 size_t sz = vma->vm_end - vma->vm_start;
6547 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6549 return PTR_ERR(ptr);
6551 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6552 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6555 #else /* !CONFIG_MMU */
6557 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6559 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6562 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6564 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6567 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6568 unsigned long addr, unsigned long len,
6569 unsigned long pgoff, unsigned long flags)
6573 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6575 return PTR_ERR(ptr);
6577 return (unsigned long) ptr;
6580 #endif /* !CONFIG_MMU */
6582 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6583 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6586 struct io_ring_ctx *ctx;
6591 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
6599 if (f.file->f_op != &io_uring_fops)
6603 ctx = f.file->private_data;
6604 if (!percpu_ref_tryget(&ctx->refs))
6608 * For SQ polling, the thread will do all submissions and completions.
6609 * Just return the requested submit count, and wake the thread if
6613 if (ctx->flags & IORING_SETUP_SQPOLL) {
6614 if (!list_empty_careful(&ctx->cq_overflow_list))
6615 io_cqring_overflow_flush(ctx, false);
6616 if (flags & IORING_ENTER_SQ_WAKEUP)
6617 wake_up(&ctx->sqo_wait);
6618 submitted = to_submit;
6619 } else if (to_submit) {
6620 struct mm_struct *cur_mm;
6622 mutex_lock(&ctx->uring_lock);
6623 /* already have mm, so io_submit_sqes() won't try to grab it */
6624 cur_mm = ctx->sqo_mm;
6625 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6627 mutex_unlock(&ctx->uring_lock);
6629 if (submitted != to_submit)
6632 if (flags & IORING_ENTER_GETEVENTS) {
6633 unsigned nr_events = 0;
6635 min_complete = min(min_complete, ctx->cq_entries);
6637 if (ctx->flags & IORING_SETUP_IOPOLL) {
6638 ret = io_iopoll_check(ctx, &nr_events, min_complete);
6640 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6645 percpu_ref_put(&ctx->refs);
6648 return submitted ? submitted : ret;
6651 static int io_uring_show_cred(int id, void *p, void *data)
6653 const struct cred *cred = p;
6654 struct seq_file *m = data;
6655 struct user_namespace *uns = seq_user_ns(m);
6656 struct group_info *gi;
6661 seq_printf(m, "%5d\n", id);
6662 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
6663 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
6664 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
6665 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
6666 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
6667 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
6668 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
6669 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
6670 seq_puts(m, "\n\tGroups:\t");
6671 gi = cred->group_info;
6672 for (g = 0; g < gi->ngroups; g++) {
6673 seq_put_decimal_ull(m, g ? " " : "",
6674 from_kgid_munged(uns, gi->gid[g]));
6676 seq_puts(m, "\n\tCapEff:\t");
6677 cap = cred->cap_effective;
6678 CAP_FOR_EACH_U32(__capi)
6679 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
6684 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
6688 mutex_lock(&ctx->uring_lock);
6689 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
6690 for (i = 0; i < ctx->nr_user_files; i++) {
6691 struct fixed_file_table *table;
6694 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6695 f = table->files[i & IORING_FILE_TABLE_MASK];
6697 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
6699 seq_printf(m, "%5u: <none>\n", i);
6701 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
6702 for (i = 0; i < ctx->nr_user_bufs; i++) {
6703 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
6705 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
6706 (unsigned int) buf->len);
6708 if (!idr_is_empty(&ctx->personality_idr)) {
6709 seq_printf(m, "Personalities:\n");
6710 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
6712 mutex_unlock(&ctx->uring_lock);
6715 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
6717 struct io_ring_ctx *ctx = f->private_data;
6719 if (percpu_ref_tryget(&ctx->refs)) {
6720 __io_uring_show_fdinfo(ctx, m);
6721 percpu_ref_put(&ctx->refs);
6725 static const struct file_operations io_uring_fops = {
6726 .release = io_uring_release,
6727 .flush = io_uring_flush,
6728 .mmap = io_uring_mmap,
6730 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6731 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6733 .poll = io_uring_poll,
6734 .fasync = io_uring_fasync,
6735 .show_fdinfo = io_uring_show_fdinfo,
6738 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6739 struct io_uring_params *p)
6741 struct io_rings *rings;
6742 size_t size, sq_array_offset;
6744 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6745 if (size == SIZE_MAX)
6748 rings = io_mem_alloc(size);
6753 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6754 rings->sq_ring_mask = p->sq_entries - 1;
6755 rings->cq_ring_mask = p->cq_entries - 1;
6756 rings->sq_ring_entries = p->sq_entries;
6757 rings->cq_ring_entries = p->cq_entries;
6758 ctx->sq_mask = rings->sq_ring_mask;
6759 ctx->cq_mask = rings->cq_ring_mask;
6760 ctx->sq_entries = rings->sq_ring_entries;
6761 ctx->cq_entries = rings->cq_ring_entries;
6763 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6764 if (size == SIZE_MAX) {
6765 io_mem_free(ctx->rings);
6770 ctx->sq_sqes = io_mem_alloc(size);
6771 if (!ctx->sq_sqes) {
6772 io_mem_free(ctx->rings);
6781 * Allocate an anonymous fd, this is what constitutes the application
6782 * visible backing of an io_uring instance. The application mmaps this
6783 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6784 * we have to tie this fd to a socket for file garbage collection purposes.
6786 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6791 #if defined(CONFIG_UNIX)
6792 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6798 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6802 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6803 O_RDWR | O_CLOEXEC);
6806 ret = PTR_ERR(file);
6810 #if defined(CONFIG_UNIX)
6811 ctx->ring_sock->file = file;
6813 fd_install(ret, file);
6816 #if defined(CONFIG_UNIX)
6817 sock_release(ctx->ring_sock);
6818 ctx->ring_sock = NULL;
6823 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6825 struct user_struct *user = NULL;
6826 struct io_ring_ctx *ctx;
6832 if (entries > IORING_MAX_ENTRIES) {
6833 if (!(p->flags & IORING_SETUP_CLAMP))
6835 entries = IORING_MAX_ENTRIES;
6839 * Use twice as many entries for the CQ ring. It's possible for the
6840 * application to drive a higher depth than the size of the SQ ring,
6841 * since the sqes are only used at submission time. This allows for
6842 * some flexibility in overcommitting a bit. If the application has
6843 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6844 * of CQ ring entries manually.
6846 p->sq_entries = roundup_pow_of_two(entries);
6847 if (p->flags & IORING_SETUP_CQSIZE) {
6849 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6850 * to a power-of-two, if it isn't already. We do NOT impose
6851 * any cq vs sq ring sizing.
6853 if (p->cq_entries < p->sq_entries)
6855 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6856 if (!(p->flags & IORING_SETUP_CLAMP))
6858 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6860 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6862 p->cq_entries = 2 * p->sq_entries;
6865 user = get_uid(current_user());
6866 account_mem = !capable(CAP_IPC_LOCK);
6869 ret = io_account_mem(user,
6870 ring_pages(p->sq_entries, p->cq_entries));
6877 ctx = io_ring_ctx_alloc(p);
6880 io_unaccount_mem(user, ring_pages(p->sq_entries,
6885 ctx->compat = in_compat_syscall();
6886 ctx->account_mem = account_mem;
6888 ctx->creds = get_current_cred();
6890 ret = io_allocate_scq_urings(ctx, p);
6894 ret = io_sq_offload_start(ctx, p);
6898 memset(&p->sq_off, 0, sizeof(p->sq_off));
6899 p->sq_off.head = offsetof(struct io_rings, sq.head);
6900 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6901 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6902 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6903 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6904 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6905 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6907 memset(&p->cq_off, 0, sizeof(p->cq_off));
6908 p->cq_off.head = offsetof(struct io_rings, cq.head);
6909 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6910 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6911 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6912 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6913 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6916 * Install ring fd as the very last thing, so we don't risk someone
6917 * having closed it before we finish setup
6919 ret = io_uring_get_fd(ctx);
6923 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6924 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6925 IORING_FEAT_CUR_PERSONALITY;
6926 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6929 io_ring_ctx_wait_and_kill(ctx);
6934 * Sets up an aio uring context, and returns the fd. Applications asks for a
6935 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6936 * params structure passed in.
6938 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6940 struct io_uring_params p;
6944 if (copy_from_user(&p, params, sizeof(p)))
6946 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6951 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6952 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6953 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
6956 ret = io_uring_create(entries, &p);
6960 if (copy_to_user(params, &p, sizeof(p)))
6966 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6967 struct io_uring_params __user *, params)
6969 return io_uring_setup(entries, params);
6972 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6974 struct io_uring_probe *p;
6978 size = struct_size(p, ops, nr_args);
6979 if (size == SIZE_MAX)
6981 p = kzalloc(size, GFP_KERNEL);
6986 if (copy_from_user(p, arg, size))
6989 if (memchr_inv(p, 0, size))
6992 p->last_op = IORING_OP_LAST - 1;
6993 if (nr_args > IORING_OP_LAST)
6994 nr_args = IORING_OP_LAST;
6996 for (i = 0; i < nr_args; i++) {
6998 if (!io_op_defs[i].not_supported)
6999 p->ops[i].flags = IO_URING_OP_SUPPORTED;
7004 if (copy_to_user(arg, p, size))
7011 static int io_register_personality(struct io_ring_ctx *ctx)
7013 const struct cred *creds = get_current_cred();
7016 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
7017 USHRT_MAX, GFP_KERNEL);
7023 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
7025 const struct cred *old_creds;
7027 old_creds = idr_remove(&ctx->personality_idr, id);
7029 put_cred(old_creds);
7036 static bool io_register_op_must_quiesce(int op)
7039 case IORING_UNREGISTER_FILES:
7040 case IORING_REGISTER_FILES_UPDATE:
7041 case IORING_REGISTER_PROBE:
7042 case IORING_REGISTER_PERSONALITY:
7043 case IORING_UNREGISTER_PERSONALITY:
7050 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
7051 void __user *arg, unsigned nr_args)
7052 __releases(ctx->uring_lock)
7053 __acquires(ctx->uring_lock)
7058 * We're inside the ring mutex, if the ref is already dying, then
7059 * someone else killed the ctx or is already going through
7060 * io_uring_register().
7062 if (percpu_ref_is_dying(&ctx->refs))
7065 if (io_register_op_must_quiesce(opcode)) {
7066 percpu_ref_kill(&ctx->refs);
7069 * Drop uring mutex before waiting for references to exit. If
7070 * another thread is currently inside io_uring_enter() it might
7071 * need to grab the uring_lock to make progress. If we hold it
7072 * here across the drain wait, then we can deadlock. It's safe
7073 * to drop the mutex here, since no new references will come in
7074 * after we've killed the percpu ref.
7076 mutex_unlock(&ctx->uring_lock);
7077 ret = wait_for_completion_interruptible(&ctx->completions[0]);
7078 mutex_lock(&ctx->uring_lock);
7080 percpu_ref_resurrect(&ctx->refs);
7087 case IORING_REGISTER_BUFFERS:
7088 ret = io_sqe_buffer_register(ctx, arg, nr_args);
7090 case IORING_UNREGISTER_BUFFERS:
7094 ret = io_sqe_buffer_unregister(ctx);
7096 case IORING_REGISTER_FILES:
7097 ret = io_sqe_files_register(ctx, arg, nr_args);
7099 case IORING_UNREGISTER_FILES:
7103 ret = io_sqe_files_unregister(ctx);
7105 case IORING_REGISTER_FILES_UPDATE:
7106 ret = io_sqe_files_update(ctx, arg, nr_args);
7108 case IORING_REGISTER_EVENTFD:
7109 case IORING_REGISTER_EVENTFD_ASYNC:
7113 ret = io_eventfd_register(ctx, arg);
7116 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
7117 ctx->eventfd_async = 1;
7119 ctx->eventfd_async = 0;
7121 case IORING_UNREGISTER_EVENTFD:
7125 ret = io_eventfd_unregister(ctx);
7127 case IORING_REGISTER_PROBE:
7129 if (!arg || nr_args > 256)
7131 ret = io_probe(ctx, arg, nr_args);
7133 case IORING_REGISTER_PERSONALITY:
7137 ret = io_register_personality(ctx);
7139 case IORING_UNREGISTER_PERSONALITY:
7143 ret = io_unregister_personality(ctx, nr_args);
7150 if (io_register_op_must_quiesce(opcode)) {
7151 /* bring the ctx back to life */
7152 percpu_ref_reinit(&ctx->refs);
7154 reinit_completion(&ctx->completions[0]);
7159 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7160 void __user *, arg, unsigned int, nr_args)
7162 struct io_ring_ctx *ctx;
7171 if (f.file->f_op != &io_uring_fops)
7174 ctx = f.file->private_data;
7176 mutex_lock(&ctx->uring_lock);
7177 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7178 mutex_unlock(&ctx->uring_lock);
7179 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
7180 ctx->cq_ev_fd != NULL, ret);
7186 static int __init io_uring_init(void)
7188 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7189 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7190 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7193 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7194 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7195 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7196 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7197 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7198 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7199 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7200 BUILD_BUG_SQE_ELEM(8, __u64, off);
7201 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7202 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7203 BUILD_BUG_SQE_ELEM(24, __u32, len);
7204 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7205 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7206 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7207 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7208 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
7209 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7210 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7211 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7212 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7213 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7214 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7215 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7216 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7217 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7218 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7219 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7221 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7222 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
7225 __initcall(io_uring_init);