1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
49 #include <linux/bits.h>
51 #include <linux/sched/signal.h>
53 #include <linux/file.h>
54 #include <linux/fdtable.h>
56 #include <linux/mman.h>
57 #include <linux/mmu_context.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
79 #define CREATE_TRACE_POINTS
80 #include <trace/events/io_uring.h>
82 #include <uapi/linux/io_uring.h>
87 #define IORING_MAX_ENTRIES 32768
88 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
91 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
93 #define IORING_FILE_TABLE_SHIFT 9
94 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
95 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
96 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
99 u32 head ____cacheline_aligned_in_smp;
100 u32 tail ____cacheline_aligned_in_smp;
104 * This data is shared with the application through the mmap at offsets
105 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
107 * The offsets to the member fields are published through struct
108 * io_sqring_offsets when calling io_uring_setup.
112 * Head and tail offsets into the ring; the offsets need to be
113 * masked to get valid indices.
115 * The kernel controls head of the sq ring and the tail of the cq ring,
116 * and the application controls tail of the sq ring and the head of the
119 struct io_uring sq, cq;
121 * Bitmasks to apply to head and tail offsets (constant, equals
124 u32 sq_ring_mask, cq_ring_mask;
125 /* Ring sizes (constant, power of 2) */
126 u32 sq_ring_entries, cq_ring_entries;
128 * Number of invalid entries dropped by the kernel due to
129 * invalid index stored in array
131 * Written by the kernel, shouldn't be modified by the
132 * application (i.e. get number of "new events" by comparing to
135 * After a new SQ head value was read by the application this
136 * counter includes all submissions that were dropped reaching
137 * the new SQ head (and possibly more).
143 * Written by the kernel, shouldn't be modified by the
146 * The application needs a full memory barrier before checking
147 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
151 * Number of completion events lost because the queue was full;
152 * this should be avoided by the application by making sure
153 * there are not more requests pending than there is space in
154 * the completion queue.
156 * Written by the kernel, shouldn't be modified by the
157 * application (i.e. get number of "new events" by comparing to
160 * As completion events come in out of order this counter is not
161 * ordered with any other data.
165 * Ring buffer of completion events.
167 * The kernel writes completion events fresh every time they are
168 * produced, so the application is allowed to modify pending
171 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
174 struct io_mapped_ubuf {
177 struct bio_vec *bvec;
178 unsigned int nr_bvecs;
181 struct fixed_file_table {
189 struct fixed_file_data {
190 struct fixed_file_table *table;
191 struct io_ring_ctx *ctx;
193 struct percpu_ref refs;
194 struct llist_head put_llist;
196 struct work_struct ref_work;
197 struct completion done;
202 struct percpu_ref refs;
203 } ____cacheline_aligned_in_smp;
209 int cq_overflow_flushed: 1;
211 int eventfd_async: 1;
214 * Ring buffer of indices into array of io_uring_sqe, which is
215 * mmapped by the application using the IORING_OFF_SQES offset.
217 * This indirection could e.g. be used to assign fixed
218 * io_uring_sqe entries to operations and only submit them to
219 * the queue when needed.
221 * The kernel modifies neither the indices array nor the entries
225 unsigned cached_sq_head;
228 unsigned sq_thread_idle;
229 unsigned cached_sq_dropped;
230 atomic_t cached_cq_overflow;
231 unsigned long sq_check_overflow;
233 struct list_head defer_list;
234 struct list_head timeout_list;
235 struct list_head cq_overflow_list;
237 wait_queue_head_t inflight_wait;
238 struct io_uring_sqe *sq_sqes;
239 } ____cacheline_aligned_in_smp;
241 struct io_rings *rings;
245 struct task_struct *sqo_thread; /* if using sq thread polling */
246 struct mm_struct *sqo_mm;
247 wait_queue_head_t sqo_wait;
250 * If used, fixed file set. Writers must ensure that ->refs is dead,
251 * readers must ensure that ->refs is alive as long as the file* is
252 * used. Only updated through io_uring_register(2).
254 struct fixed_file_data *file_data;
255 unsigned nr_user_files;
257 struct file *ring_file;
259 /* if used, fixed mapped user buffers */
260 unsigned nr_user_bufs;
261 struct io_mapped_ubuf *user_bufs;
263 struct user_struct *user;
265 const struct cred *creds;
267 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
268 struct completion *completions;
270 /* if all else fails... */
271 struct io_kiocb *fallback_req;
273 #if defined(CONFIG_UNIX)
274 struct socket *ring_sock;
277 struct idr personality_idr;
280 unsigned cached_cq_tail;
283 atomic_t cq_timeouts;
284 unsigned long cq_check_overflow;
285 struct wait_queue_head cq_wait;
286 struct fasync_struct *cq_fasync;
287 struct eventfd_ctx *cq_ev_fd;
288 } ____cacheline_aligned_in_smp;
291 struct mutex uring_lock;
292 wait_queue_head_t wait;
293 } ____cacheline_aligned_in_smp;
296 spinlock_t completion_lock;
297 struct llist_head poll_llist;
300 * ->poll_list is protected by the ctx->uring_lock for
301 * io_uring instances that don't use IORING_SETUP_SQPOLL.
302 * For SQPOLL, only the single threaded io_sq_thread() will
303 * manipulate the list, hence no extra locking is needed there.
305 struct list_head poll_list;
306 struct hlist_head *cancel_hash;
307 unsigned cancel_hash_bits;
308 bool poll_multi_file;
310 spinlock_t inflight_lock;
311 struct list_head inflight_list;
312 } ____cacheline_aligned_in_smp;
316 * First field must be the file pointer in all the
317 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
319 struct io_poll_iocb {
322 struct wait_queue_head *head;
328 struct wait_queue_entry wait;
333 struct file *put_file;
337 struct io_timeout_data {
338 struct io_kiocb *req;
339 struct hrtimer timer;
340 struct timespec64 ts;
341 enum hrtimer_mode mode;
347 struct sockaddr __user *addr;
348 int __user *addr_len;
373 /* NOTE: kiocb has the file as the first member, so don't do it here */
381 struct sockaddr __user *addr;
388 struct user_msghdr __user *msg;
401 struct filename *filename;
402 struct statx __user *buffer;
406 struct io_files_update {
432 struct epoll_event event;
435 struct io_async_connect {
436 struct sockaddr_storage address;
439 struct io_async_msghdr {
440 struct iovec fast_iov[UIO_FASTIOV];
442 struct sockaddr __user *uaddr;
447 struct iovec fast_iov[UIO_FASTIOV];
453 struct io_async_open {
454 struct filename *filename;
457 struct io_async_ctx {
459 struct io_async_rw rw;
460 struct io_async_msghdr msg;
461 struct io_async_connect connect;
462 struct io_timeout_data timeout;
463 struct io_async_open open;
468 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
469 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
470 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
471 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
472 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
479 REQ_F_IOPOLL_COMPLETED_BIT,
480 REQ_F_LINK_TIMEOUT_BIT,
484 REQ_F_TIMEOUT_NOSEQ_BIT,
485 REQ_F_COMP_LOCKED_BIT,
490 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
491 /* drain existing IO first */
492 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
494 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
495 /* doesn't sever on completion < 0 */
496 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
498 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
500 /* already grabbed next link */
501 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
502 /* fail rest of links */
503 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
504 /* on inflight list */
505 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
506 /* read/write uses file position */
507 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
508 /* must not punt to workers */
509 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
510 /* polled IO has completed */
511 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
512 /* has linked timeout */
513 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
514 /* timeout request */
515 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
517 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
518 /* must be punted even for NONBLOCK */
519 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
520 /* no timeout sequence */
521 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
522 /* completion under lock */
523 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
527 * NOTE! Each of the iocb union members has the file pointer
528 * as the first entry in their struct definition. So you can
529 * access the file pointer through any of the sub-structs,
530 * or directly as just 'ki_filp' in this struct.
536 struct io_poll_iocb poll;
537 struct io_accept accept;
539 struct io_cancel cancel;
540 struct io_timeout timeout;
541 struct io_connect connect;
542 struct io_sr_msg sr_msg;
544 struct io_close close;
545 struct io_files_update files_update;
546 struct io_fadvise fadvise;
547 struct io_madvise madvise;
548 struct io_epoll epoll;
551 struct io_async_ctx *io;
553 * llist_node is only used for poll deferred completions
555 struct llist_node llist_node;
558 bool needs_fixed_file;
561 struct io_ring_ctx *ctx;
563 struct list_head list;
564 struct hlist_node hash_node;
566 struct list_head link_list;
573 struct list_head inflight_entry;
575 struct io_wq_work work;
578 #define IO_PLUG_THRESHOLD 2
579 #define IO_IOPOLL_BATCH 8
581 struct io_submit_state {
582 struct blk_plug plug;
585 * io_kiocb alloc cache
587 void *reqs[IO_IOPOLL_BATCH];
588 unsigned int free_reqs;
591 * File reference cache
595 unsigned int has_refs;
596 unsigned int used_refs;
597 unsigned int ios_left;
601 /* needs req->io allocated for deferral/async */
602 unsigned async_ctx : 1;
603 /* needs current->mm setup, does mm access */
604 unsigned needs_mm : 1;
605 /* needs req->file assigned */
606 unsigned needs_file : 1;
607 /* needs req->file assigned IFF fd is >= 0 */
608 unsigned fd_non_neg : 1;
609 /* hash wq insertion if file is a regular file */
610 unsigned hash_reg_file : 1;
611 /* unbound wq insertion if file is a non-regular file */
612 unsigned unbound_nonreg_file : 1;
613 /* opcode is not supported by this kernel */
614 unsigned not_supported : 1;
615 /* needs file table */
616 unsigned file_table : 1;
619 static const struct io_op_def io_op_defs[] = {
620 [IORING_OP_NOP] = {},
621 [IORING_OP_READV] = {
625 .unbound_nonreg_file = 1,
627 [IORING_OP_WRITEV] = {
632 .unbound_nonreg_file = 1,
634 [IORING_OP_FSYNC] = {
637 [IORING_OP_READ_FIXED] = {
639 .unbound_nonreg_file = 1,
641 [IORING_OP_WRITE_FIXED] = {
644 .unbound_nonreg_file = 1,
646 [IORING_OP_POLL_ADD] = {
648 .unbound_nonreg_file = 1,
650 [IORING_OP_POLL_REMOVE] = {},
651 [IORING_OP_SYNC_FILE_RANGE] = {
654 [IORING_OP_SENDMSG] = {
658 .unbound_nonreg_file = 1,
660 [IORING_OP_RECVMSG] = {
664 .unbound_nonreg_file = 1,
666 [IORING_OP_TIMEOUT] = {
670 [IORING_OP_TIMEOUT_REMOVE] = {},
671 [IORING_OP_ACCEPT] = {
674 .unbound_nonreg_file = 1,
677 [IORING_OP_ASYNC_CANCEL] = {},
678 [IORING_OP_LINK_TIMEOUT] = {
682 [IORING_OP_CONNECT] = {
686 .unbound_nonreg_file = 1,
688 [IORING_OP_FALLOCATE] = {
691 [IORING_OP_OPENAT] = {
696 [IORING_OP_CLOSE] = {
700 [IORING_OP_FILES_UPDATE] = {
704 [IORING_OP_STATX] = {
712 .unbound_nonreg_file = 1,
714 [IORING_OP_WRITE] = {
717 .unbound_nonreg_file = 1,
719 [IORING_OP_FADVISE] = {
722 [IORING_OP_MADVISE] = {
728 .unbound_nonreg_file = 1,
733 .unbound_nonreg_file = 1,
735 [IORING_OP_OPENAT2] = {
740 [IORING_OP_EPOLL_CTL] = {
741 .unbound_nonreg_file = 1,
746 static void io_wq_submit_work(struct io_wq_work **workptr);
747 static void io_cqring_fill_event(struct io_kiocb *req, long res);
748 static void io_put_req(struct io_kiocb *req);
749 static void __io_double_put_req(struct io_kiocb *req);
750 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
751 static void io_queue_linked_timeout(struct io_kiocb *req);
752 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
753 struct io_uring_files_update *ip,
755 static int io_grab_files(struct io_kiocb *req);
756 static void io_ring_file_ref_flush(struct fixed_file_data *data);
758 static struct kmem_cache *req_cachep;
760 static const struct file_operations io_uring_fops;
762 struct sock *io_uring_get_socket(struct file *file)
764 #if defined(CONFIG_UNIX)
765 if (file->f_op == &io_uring_fops) {
766 struct io_ring_ctx *ctx = file->private_data;
768 return ctx->ring_sock->sk;
773 EXPORT_SYMBOL(io_uring_get_socket);
775 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
777 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
779 complete(&ctx->completions[0]);
782 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
784 struct io_ring_ctx *ctx;
787 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
791 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
792 if (!ctx->fallback_req)
795 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
796 if (!ctx->completions)
800 * Use 5 bits less than the max cq entries, that should give us around
801 * 32 entries per hash list if totally full and uniformly spread.
803 hash_bits = ilog2(p->cq_entries);
807 ctx->cancel_hash_bits = hash_bits;
808 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
810 if (!ctx->cancel_hash)
812 __hash_init(ctx->cancel_hash, 1U << hash_bits);
814 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
815 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
818 ctx->flags = p->flags;
819 init_waitqueue_head(&ctx->cq_wait);
820 INIT_LIST_HEAD(&ctx->cq_overflow_list);
821 init_completion(&ctx->completions[0]);
822 init_completion(&ctx->completions[1]);
823 idr_init(&ctx->personality_idr);
824 mutex_init(&ctx->uring_lock);
825 init_waitqueue_head(&ctx->wait);
826 spin_lock_init(&ctx->completion_lock);
827 init_llist_head(&ctx->poll_llist);
828 INIT_LIST_HEAD(&ctx->poll_list);
829 INIT_LIST_HEAD(&ctx->defer_list);
830 INIT_LIST_HEAD(&ctx->timeout_list);
831 init_waitqueue_head(&ctx->inflight_wait);
832 spin_lock_init(&ctx->inflight_lock);
833 INIT_LIST_HEAD(&ctx->inflight_list);
836 if (ctx->fallback_req)
837 kmem_cache_free(req_cachep, ctx->fallback_req);
838 kfree(ctx->completions);
839 kfree(ctx->cancel_hash);
844 static inline bool __req_need_defer(struct io_kiocb *req)
846 struct io_ring_ctx *ctx = req->ctx;
848 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
849 + atomic_read(&ctx->cached_cq_overflow);
852 static inline bool req_need_defer(struct io_kiocb *req)
854 if (unlikely(req->flags & REQ_F_IO_DRAIN))
855 return __req_need_defer(req);
860 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
862 struct io_kiocb *req;
864 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
865 if (req && !req_need_defer(req)) {
866 list_del_init(&req->list);
873 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
875 struct io_kiocb *req;
877 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
879 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
881 if (!__req_need_defer(req)) {
882 list_del_init(&req->list);
890 static void __io_commit_cqring(struct io_ring_ctx *ctx)
892 struct io_rings *rings = ctx->rings;
894 /* order cqe stores with ring update */
895 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
897 if (wq_has_sleeper(&ctx->cq_wait)) {
898 wake_up_interruptible(&ctx->cq_wait);
899 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
903 static inline void io_req_work_grab_env(struct io_kiocb *req,
904 const struct io_op_def *def)
906 if (!req->work.mm && def->needs_mm) {
908 req->work.mm = current->mm;
910 if (!req->work.creds)
911 req->work.creds = get_current_cred();
914 static inline void io_req_work_drop_env(struct io_kiocb *req)
917 mmdrop(req->work.mm);
920 if (req->work.creds) {
921 put_cred(req->work.creds);
922 req->work.creds = NULL;
926 static inline bool io_prep_async_work(struct io_kiocb *req,
927 struct io_kiocb **link)
929 const struct io_op_def *def = &io_op_defs[req->opcode];
930 bool do_hashed = false;
932 if (req->flags & REQ_F_ISREG) {
933 if (def->hash_reg_file)
936 if (def->unbound_nonreg_file)
937 req->work.flags |= IO_WQ_WORK_UNBOUND;
940 io_req_work_grab_env(req, def);
942 *link = io_prep_linked_timeout(req);
946 static inline void io_queue_async_work(struct io_kiocb *req)
948 struct io_ring_ctx *ctx = req->ctx;
949 struct io_kiocb *link;
952 do_hashed = io_prep_async_work(req, &link);
954 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
957 io_wq_enqueue(ctx->io_wq, &req->work);
959 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
960 file_inode(req->file));
964 io_queue_linked_timeout(link);
967 static void io_kill_timeout(struct io_kiocb *req)
971 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
973 atomic_inc(&req->ctx->cq_timeouts);
974 list_del_init(&req->list);
975 io_cqring_fill_event(req, 0);
980 static void io_kill_timeouts(struct io_ring_ctx *ctx)
982 struct io_kiocb *req, *tmp;
984 spin_lock_irq(&ctx->completion_lock);
985 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
986 io_kill_timeout(req);
987 spin_unlock_irq(&ctx->completion_lock);
990 static void io_commit_cqring(struct io_ring_ctx *ctx)
992 struct io_kiocb *req;
994 while ((req = io_get_timeout_req(ctx)) != NULL)
995 io_kill_timeout(req);
997 __io_commit_cqring(ctx);
999 while ((req = io_get_deferred_req(ctx)) != NULL)
1000 io_queue_async_work(req);
1003 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1005 struct io_rings *rings = ctx->rings;
1008 tail = ctx->cached_cq_tail;
1010 * writes to the cq entry need to come after reading head; the
1011 * control dependency is enough as we're using WRITE_ONCE to
1014 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1017 ctx->cached_cq_tail++;
1018 return &rings->cqes[tail & ctx->cq_mask];
1021 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1025 if (!ctx->eventfd_async)
1027 return io_wq_current_is_worker() || in_interrupt();
1030 static void __io_cqring_ev_posted(struct io_ring_ctx *ctx, bool trigger_ev)
1032 if (waitqueue_active(&ctx->wait))
1033 wake_up(&ctx->wait);
1034 if (waitqueue_active(&ctx->sqo_wait))
1035 wake_up(&ctx->sqo_wait);
1037 eventfd_signal(ctx->cq_ev_fd, 1);
1040 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1042 __io_cqring_ev_posted(ctx, io_should_trigger_evfd(ctx));
1045 /* Returns true if there are no backlogged entries after the flush */
1046 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1048 struct io_rings *rings = ctx->rings;
1049 struct io_uring_cqe *cqe;
1050 struct io_kiocb *req;
1051 unsigned long flags;
1055 if (list_empty_careful(&ctx->cq_overflow_list))
1057 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1058 rings->cq_ring_entries))
1062 spin_lock_irqsave(&ctx->completion_lock, flags);
1064 /* if force is set, the ring is going away. always drop after that */
1066 ctx->cq_overflow_flushed = 1;
1069 while (!list_empty(&ctx->cq_overflow_list)) {
1070 cqe = io_get_cqring(ctx);
1074 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1076 list_move(&req->list, &list);
1078 WRITE_ONCE(cqe->user_data, req->user_data);
1079 WRITE_ONCE(cqe->res, req->result);
1080 WRITE_ONCE(cqe->flags, 0);
1082 WRITE_ONCE(ctx->rings->cq_overflow,
1083 atomic_inc_return(&ctx->cached_cq_overflow));
1087 io_commit_cqring(ctx);
1089 clear_bit(0, &ctx->sq_check_overflow);
1090 clear_bit(0, &ctx->cq_check_overflow);
1092 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1093 io_cqring_ev_posted(ctx);
1095 while (!list_empty(&list)) {
1096 req = list_first_entry(&list, struct io_kiocb, list);
1097 list_del(&req->list);
1104 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1106 struct io_ring_ctx *ctx = req->ctx;
1107 struct io_uring_cqe *cqe;
1109 trace_io_uring_complete(ctx, req->user_data, res);
1112 * If we can't get a cq entry, userspace overflowed the
1113 * submission (by quite a lot). Increment the overflow count in
1116 cqe = io_get_cqring(ctx);
1118 WRITE_ONCE(cqe->user_data, req->user_data);
1119 WRITE_ONCE(cqe->res, res);
1120 WRITE_ONCE(cqe->flags, 0);
1121 } else if (ctx->cq_overflow_flushed) {
1122 WRITE_ONCE(ctx->rings->cq_overflow,
1123 atomic_inc_return(&ctx->cached_cq_overflow));
1125 if (list_empty(&ctx->cq_overflow_list)) {
1126 set_bit(0, &ctx->sq_check_overflow);
1127 set_bit(0, &ctx->cq_check_overflow);
1129 refcount_inc(&req->refs);
1131 list_add_tail(&req->list, &ctx->cq_overflow_list);
1135 static void io_cqring_add_event(struct io_kiocb *req, long res)
1137 struct io_ring_ctx *ctx = req->ctx;
1138 unsigned long flags;
1140 spin_lock_irqsave(&ctx->completion_lock, flags);
1141 io_cqring_fill_event(req, res);
1142 io_commit_cqring(ctx);
1143 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1145 io_cqring_ev_posted(ctx);
1148 static inline bool io_is_fallback_req(struct io_kiocb *req)
1150 return req == (struct io_kiocb *)
1151 ((unsigned long) req->ctx->fallback_req & ~1UL);
1154 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1156 struct io_kiocb *req;
1158 req = ctx->fallback_req;
1159 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1165 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1166 struct io_submit_state *state)
1168 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1169 struct io_kiocb *req;
1172 req = kmem_cache_alloc(req_cachep, gfp);
1175 } else if (!state->free_reqs) {
1179 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1180 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1183 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1184 * retry single alloc to be on the safe side.
1186 if (unlikely(ret <= 0)) {
1187 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1188 if (!state->reqs[0])
1192 state->free_reqs = ret - 1;
1193 req = state->reqs[ret - 1];
1196 req = state->reqs[state->free_reqs];
1204 /* one is dropped after submission, the other at completion */
1205 refcount_set(&req->refs, 2);
1207 INIT_IO_WORK(&req->work, io_wq_submit_work);
1210 req = io_get_fallback_req(ctx);
1213 percpu_ref_put(&ctx->refs);
1217 static void __io_req_do_free(struct io_kiocb *req)
1219 if (likely(!io_is_fallback_req(req)))
1220 kmem_cache_free(req_cachep, req);
1222 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1225 static void __io_req_aux_free(struct io_kiocb *req)
1227 struct io_ring_ctx *ctx = req->ctx;
1231 if (req->flags & REQ_F_FIXED_FILE)
1232 percpu_ref_put(&ctx->file_data->refs);
1237 io_req_work_drop_env(req);
1240 static void __io_free_req(struct io_kiocb *req)
1242 __io_req_aux_free(req);
1244 if (req->flags & REQ_F_INFLIGHT) {
1245 struct io_ring_ctx *ctx = req->ctx;
1246 unsigned long flags;
1248 spin_lock_irqsave(&ctx->inflight_lock, flags);
1249 list_del(&req->inflight_entry);
1250 if (waitqueue_active(&ctx->inflight_wait))
1251 wake_up(&ctx->inflight_wait);
1252 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1255 percpu_ref_put(&req->ctx->refs);
1256 __io_req_do_free(req);
1260 void *reqs[IO_IOPOLL_BATCH];
1265 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1267 int fixed_refs = rb->to_free;
1271 if (rb->need_iter) {
1272 int i, inflight = 0;
1273 unsigned long flags;
1276 for (i = 0; i < rb->to_free; i++) {
1277 struct io_kiocb *req = rb->reqs[i];
1279 if (req->flags & REQ_F_FIXED_FILE) {
1283 if (req->flags & REQ_F_INFLIGHT)
1285 __io_req_aux_free(req);
1290 spin_lock_irqsave(&ctx->inflight_lock, flags);
1291 for (i = 0; i < rb->to_free; i++) {
1292 struct io_kiocb *req = rb->reqs[i];
1294 if (req->flags & REQ_F_INFLIGHT) {
1295 list_del(&req->inflight_entry);
1300 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1302 if (waitqueue_active(&ctx->inflight_wait))
1303 wake_up(&ctx->inflight_wait);
1306 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1308 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1309 percpu_ref_put_many(&ctx->refs, rb->to_free);
1310 rb->to_free = rb->need_iter = 0;
1313 static bool io_link_cancel_timeout(struct io_kiocb *req)
1315 struct io_ring_ctx *ctx = req->ctx;
1318 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1320 io_cqring_fill_event(req, -ECANCELED);
1321 io_commit_cqring(ctx);
1322 req->flags &= ~REQ_F_LINK;
1330 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1332 struct io_ring_ctx *ctx = req->ctx;
1333 bool wake_ev = false;
1335 /* Already got next link */
1336 if (req->flags & REQ_F_LINK_NEXT)
1340 * The list should never be empty when we are called here. But could
1341 * potentially happen if the chain is messed up, check to be on the
1344 while (!list_empty(&req->link_list)) {
1345 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1346 struct io_kiocb, link_list);
1348 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1349 (nxt->flags & REQ_F_TIMEOUT))) {
1350 list_del_init(&nxt->link_list);
1351 wake_ev |= io_link_cancel_timeout(nxt);
1352 req->flags &= ~REQ_F_LINK_TIMEOUT;
1356 list_del_init(&req->link_list);
1357 if (!list_empty(&nxt->link_list))
1358 nxt->flags |= REQ_F_LINK;
1363 req->flags |= REQ_F_LINK_NEXT;
1365 io_cqring_ev_posted(ctx);
1369 * Called if REQ_F_LINK is set, and we fail the head request
1371 static void io_fail_links(struct io_kiocb *req)
1373 struct io_ring_ctx *ctx = req->ctx;
1374 unsigned long flags;
1376 spin_lock_irqsave(&ctx->completion_lock, flags);
1378 while (!list_empty(&req->link_list)) {
1379 struct io_kiocb *link = list_first_entry(&req->link_list,
1380 struct io_kiocb, link_list);
1382 list_del_init(&link->link_list);
1383 trace_io_uring_fail_link(req, link);
1385 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1386 link->opcode == IORING_OP_LINK_TIMEOUT) {
1387 io_link_cancel_timeout(link);
1389 io_cqring_fill_event(link, -ECANCELED);
1390 __io_double_put_req(link);
1392 req->flags &= ~REQ_F_LINK_TIMEOUT;
1395 io_commit_cqring(ctx);
1396 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1397 io_cqring_ev_posted(ctx);
1400 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1402 if (likely(!(req->flags & REQ_F_LINK)))
1406 * If LINK is set, we have dependent requests in this chain. If we
1407 * didn't fail this request, queue the first one up, moving any other
1408 * dependencies to the next request. In case of failure, fail the rest
1411 if (req->flags & REQ_F_FAIL_LINK) {
1413 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1414 REQ_F_LINK_TIMEOUT) {
1415 struct io_ring_ctx *ctx = req->ctx;
1416 unsigned long flags;
1419 * If this is a timeout link, we could be racing with the
1420 * timeout timer. Grab the completion lock for this case to
1421 * protect against that.
1423 spin_lock_irqsave(&ctx->completion_lock, flags);
1424 io_req_link_next(req, nxt);
1425 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1427 io_req_link_next(req, nxt);
1431 static void io_free_req(struct io_kiocb *req)
1433 struct io_kiocb *nxt = NULL;
1435 io_req_find_next(req, &nxt);
1439 io_queue_async_work(nxt);
1443 * Drop reference to request, return next in chain (if there is one) if this
1444 * was the last reference to this request.
1446 __attribute__((nonnull))
1447 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1449 io_req_find_next(req, nxtptr);
1451 if (refcount_dec_and_test(&req->refs))
1455 static void io_put_req(struct io_kiocb *req)
1457 if (refcount_dec_and_test(&req->refs))
1462 * Must only be used if we don't need to care about links, usually from
1463 * within the completion handling itself.
1465 static void __io_double_put_req(struct io_kiocb *req)
1467 /* drop both submit and complete references */
1468 if (refcount_sub_and_test(2, &req->refs))
1472 static void io_double_put_req(struct io_kiocb *req)
1474 /* drop both submit and complete references */
1475 if (refcount_sub_and_test(2, &req->refs))
1479 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1481 struct io_rings *rings = ctx->rings;
1483 if (test_bit(0, &ctx->cq_check_overflow)) {
1485 * noflush == true is from the waitqueue handler, just ensure
1486 * we wake up the task, and the next invocation will flush the
1487 * entries. We cannot safely to it from here.
1489 if (noflush && !list_empty(&ctx->cq_overflow_list))
1492 io_cqring_overflow_flush(ctx, false);
1495 /* See comment at the top of this file */
1497 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1500 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1502 struct io_rings *rings = ctx->rings;
1504 /* make sure SQ entry isn't read before tail */
1505 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1508 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1510 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1513 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1516 rb->reqs[rb->to_free++] = req;
1517 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1518 io_free_req_many(req->ctx, rb);
1523 * Find and free completed poll iocbs
1525 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1526 struct list_head *done)
1528 struct req_batch rb;
1529 struct io_kiocb *req;
1531 rb.to_free = rb.need_iter = 0;
1532 while (!list_empty(done)) {
1533 req = list_first_entry(done, struct io_kiocb, list);
1534 list_del(&req->list);
1536 io_cqring_fill_event(req, req->result);
1539 if (refcount_dec_and_test(&req->refs) &&
1540 !io_req_multi_free(&rb, req))
1544 io_commit_cqring(ctx);
1545 io_free_req_many(ctx, &rb);
1548 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1551 struct io_kiocb *req, *tmp;
1557 * Only spin for completions if we don't have multiple devices hanging
1558 * off our complete list, and we're under the requested amount.
1560 spin = !ctx->poll_multi_file && *nr_events < min;
1563 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1564 struct kiocb *kiocb = &req->rw.kiocb;
1567 * Move completed entries to our local list. If we find a
1568 * request that requires polling, break out and complete
1569 * the done list first, if we have entries there.
1571 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1572 list_move_tail(&req->list, &done);
1575 if (!list_empty(&done))
1578 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1587 if (!list_empty(&done))
1588 io_iopoll_complete(ctx, nr_events, &done);
1594 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1595 * non-spinning poll check - we'll still enter the driver poll loop, but only
1596 * as a non-spinning completion check.
1598 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1601 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1604 ret = io_do_iopoll(ctx, nr_events, min);
1607 if (!min || *nr_events >= min)
1615 * We can't just wait for polled events to come to us, we have to actively
1616 * find and complete them.
1618 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1620 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1623 mutex_lock(&ctx->uring_lock);
1624 while (!list_empty(&ctx->poll_list)) {
1625 unsigned int nr_events = 0;
1627 io_iopoll_getevents(ctx, &nr_events, 1);
1630 * Ensure we allow local-to-the-cpu processing to take place,
1631 * in this case we need to ensure that we reap all events.
1635 mutex_unlock(&ctx->uring_lock);
1638 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1641 int iters = 0, ret = 0;
1647 * Don't enter poll loop if we already have events pending.
1648 * If we do, we can potentially be spinning for commands that
1649 * already triggered a CQE (eg in error).
1651 if (io_cqring_events(ctx, false))
1655 * If a submit got punted to a workqueue, we can have the
1656 * application entering polling for a command before it gets
1657 * issued. That app will hold the uring_lock for the duration
1658 * of the poll right here, so we need to take a breather every
1659 * now and then to ensure that the issue has a chance to add
1660 * the poll to the issued list. Otherwise we can spin here
1661 * forever, while the workqueue is stuck trying to acquire the
1664 if (!(++iters & 7)) {
1665 mutex_unlock(&ctx->uring_lock);
1666 mutex_lock(&ctx->uring_lock);
1669 if (*nr_events < min)
1670 tmin = min - *nr_events;
1672 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1676 } while (min && !*nr_events && !need_resched());
1681 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1687 * We disallow the app entering submit/complete with polling, but we
1688 * still need to lock the ring to prevent racing with polled issue
1689 * that got punted to a workqueue.
1691 mutex_lock(&ctx->uring_lock);
1692 ret = __io_iopoll_check(ctx, nr_events, min);
1693 mutex_unlock(&ctx->uring_lock);
1697 static void kiocb_end_write(struct io_kiocb *req)
1700 * Tell lockdep we inherited freeze protection from submission
1703 if (req->flags & REQ_F_ISREG) {
1704 struct inode *inode = file_inode(req->file);
1706 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1708 file_end_write(req->file);
1711 static inline void req_set_fail_links(struct io_kiocb *req)
1713 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1714 req->flags |= REQ_F_FAIL_LINK;
1717 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1719 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1721 if (kiocb->ki_flags & IOCB_WRITE)
1722 kiocb_end_write(req);
1724 if (res != req->result)
1725 req_set_fail_links(req);
1726 io_cqring_add_event(req, res);
1729 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1731 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1733 io_complete_rw_common(kiocb, res);
1737 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1739 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1740 struct io_kiocb *nxt = NULL;
1742 io_complete_rw_common(kiocb, res);
1743 io_put_req_find_next(req, &nxt);
1748 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1750 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1752 if (kiocb->ki_flags & IOCB_WRITE)
1753 kiocb_end_write(req);
1755 if (res != req->result)
1756 req_set_fail_links(req);
1759 req->flags |= REQ_F_IOPOLL_COMPLETED;
1763 * After the iocb has been issued, it's safe to be found on the poll list.
1764 * Adding the kiocb to the list AFTER submission ensures that we don't
1765 * find it from a io_iopoll_getevents() thread before the issuer is done
1766 * accessing the kiocb cookie.
1768 static void io_iopoll_req_issued(struct io_kiocb *req)
1770 struct io_ring_ctx *ctx = req->ctx;
1773 * Track whether we have multiple files in our lists. This will impact
1774 * how we do polling eventually, not spinning if we're on potentially
1775 * different devices.
1777 if (list_empty(&ctx->poll_list)) {
1778 ctx->poll_multi_file = false;
1779 } else if (!ctx->poll_multi_file) {
1780 struct io_kiocb *list_req;
1782 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1784 if (list_req->file != req->file)
1785 ctx->poll_multi_file = true;
1789 * For fast devices, IO may have already completed. If it has, add
1790 * it to the front so we find it first.
1792 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1793 list_add(&req->list, &ctx->poll_list);
1795 list_add_tail(&req->list, &ctx->poll_list);
1798 static void io_file_put(struct io_submit_state *state)
1801 int diff = state->has_refs - state->used_refs;
1804 fput_many(state->file, diff);
1810 * Get as many references to a file as we have IOs left in this submission,
1811 * assuming most submissions are for one file, or at least that each file
1812 * has more than one submission.
1814 static struct file *io_file_get(struct io_submit_state *state, int fd)
1820 if (state->fd == fd) {
1827 state->file = fget_many(fd, state->ios_left);
1832 state->has_refs = state->ios_left;
1833 state->used_refs = 1;
1839 * If we tracked the file through the SCM inflight mechanism, we could support
1840 * any file. For now, just ensure that anything potentially problematic is done
1843 static bool io_file_supports_async(struct file *file)
1845 umode_t mode = file_inode(file)->i_mode;
1847 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1849 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1855 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1856 bool force_nonblock)
1858 struct io_ring_ctx *ctx = req->ctx;
1859 struct kiocb *kiocb = &req->rw.kiocb;
1863 if (S_ISREG(file_inode(req->file)->i_mode))
1864 req->flags |= REQ_F_ISREG;
1866 kiocb->ki_pos = READ_ONCE(sqe->off);
1867 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1868 req->flags |= REQ_F_CUR_POS;
1869 kiocb->ki_pos = req->file->f_pos;
1871 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1872 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1873 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1877 ioprio = READ_ONCE(sqe->ioprio);
1879 ret = ioprio_check_cap(ioprio);
1883 kiocb->ki_ioprio = ioprio;
1885 kiocb->ki_ioprio = get_current_ioprio();
1887 /* don't allow async punt if RWF_NOWAIT was requested */
1888 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1889 (req->file->f_flags & O_NONBLOCK))
1890 req->flags |= REQ_F_NOWAIT;
1893 kiocb->ki_flags |= IOCB_NOWAIT;
1895 if (ctx->flags & IORING_SETUP_IOPOLL) {
1896 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1897 !kiocb->ki_filp->f_op->iopoll)
1900 kiocb->ki_flags |= IOCB_HIPRI;
1901 kiocb->ki_complete = io_complete_rw_iopoll;
1904 if (kiocb->ki_flags & IOCB_HIPRI)
1906 kiocb->ki_complete = io_complete_rw;
1909 req->rw.addr = READ_ONCE(sqe->addr);
1910 req->rw.len = READ_ONCE(sqe->len);
1911 /* we own ->private, reuse it for the buffer index */
1912 req->rw.kiocb.private = (void *) (unsigned long)
1913 READ_ONCE(sqe->buf_index);
1917 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1923 case -ERESTARTNOINTR:
1924 case -ERESTARTNOHAND:
1925 case -ERESTART_RESTARTBLOCK:
1927 * We can't just restart the syscall, since previously
1928 * submitted sqes may already be in progress. Just fail this
1934 kiocb->ki_complete(kiocb, ret, 0);
1938 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1941 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1943 if (req->flags & REQ_F_CUR_POS)
1944 req->file->f_pos = kiocb->ki_pos;
1945 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1946 *nxt = __io_complete_rw(kiocb, ret);
1948 io_rw_done(kiocb, ret);
1951 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1952 struct iov_iter *iter)
1954 struct io_ring_ctx *ctx = req->ctx;
1955 size_t len = req->rw.len;
1956 struct io_mapped_ubuf *imu;
1957 unsigned index, buf_index;
1961 /* attempt to use fixed buffers without having provided iovecs */
1962 if (unlikely(!ctx->user_bufs))
1965 buf_index = (unsigned long) req->rw.kiocb.private;
1966 if (unlikely(buf_index >= ctx->nr_user_bufs))
1969 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1970 imu = &ctx->user_bufs[index];
1971 buf_addr = req->rw.addr;
1974 if (buf_addr + len < buf_addr)
1976 /* not inside the mapped region */
1977 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1981 * May not be a start of buffer, set size appropriately
1982 * and advance us to the beginning.
1984 offset = buf_addr - imu->ubuf;
1985 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1989 * Don't use iov_iter_advance() here, as it's really slow for
1990 * using the latter parts of a big fixed buffer - it iterates
1991 * over each segment manually. We can cheat a bit here, because
1994 * 1) it's a BVEC iter, we set it up
1995 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1996 * first and last bvec
1998 * So just find our index, and adjust the iterator afterwards.
1999 * If the offset is within the first bvec (or the whole first
2000 * bvec, just use iov_iter_advance(). This makes it easier
2001 * since we can just skip the first segment, which may not
2002 * be PAGE_SIZE aligned.
2004 const struct bio_vec *bvec = imu->bvec;
2006 if (offset <= bvec->bv_len) {
2007 iov_iter_advance(iter, offset);
2009 unsigned long seg_skip;
2011 /* skip first vec */
2012 offset -= bvec->bv_len;
2013 seg_skip = 1 + (offset >> PAGE_SHIFT);
2015 iter->bvec = bvec + seg_skip;
2016 iter->nr_segs -= seg_skip;
2017 iter->count -= bvec->bv_len + offset;
2018 iter->iov_offset = offset & ~PAGE_MASK;
2025 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2026 struct iovec **iovec, struct iov_iter *iter)
2028 void __user *buf = u64_to_user_ptr(req->rw.addr);
2029 size_t sqe_len = req->rw.len;
2032 opcode = req->opcode;
2033 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2035 return io_import_fixed(req, rw, iter);
2038 /* buffer index only valid with fixed read/write */
2039 if (req->rw.kiocb.private)
2042 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2044 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2050 struct io_async_rw *iorw = &req->io->rw;
2053 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2054 if (iorw->iov == iorw->fast_iov)
2062 #ifdef CONFIG_COMPAT
2063 if (req->ctx->compat)
2064 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2068 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2072 * For files that don't have ->read_iter() and ->write_iter(), handle them
2073 * by looping over ->read() or ->write() manually.
2075 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2076 struct iov_iter *iter)
2081 * Don't support polled IO through this interface, and we can't
2082 * support non-blocking either. For the latter, this just causes
2083 * the kiocb to be handled from an async context.
2085 if (kiocb->ki_flags & IOCB_HIPRI)
2087 if (kiocb->ki_flags & IOCB_NOWAIT)
2090 while (iov_iter_count(iter)) {
2094 if (!iov_iter_is_bvec(iter)) {
2095 iovec = iov_iter_iovec(iter);
2097 /* fixed buffers import bvec */
2098 iovec.iov_base = kmap(iter->bvec->bv_page)
2100 iovec.iov_len = min(iter->count,
2101 iter->bvec->bv_len - iter->iov_offset);
2105 nr = file->f_op->read(file, iovec.iov_base,
2106 iovec.iov_len, &kiocb->ki_pos);
2108 nr = file->f_op->write(file, iovec.iov_base,
2109 iovec.iov_len, &kiocb->ki_pos);
2112 if (iov_iter_is_bvec(iter))
2113 kunmap(iter->bvec->bv_page);
2121 if (nr != iovec.iov_len)
2123 iov_iter_advance(iter, nr);
2129 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2130 struct iovec *iovec, struct iovec *fast_iov,
2131 struct iov_iter *iter)
2133 req->io->rw.nr_segs = iter->nr_segs;
2134 req->io->rw.size = io_size;
2135 req->io->rw.iov = iovec;
2136 if (!req->io->rw.iov) {
2137 req->io->rw.iov = req->io->rw.fast_iov;
2138 memcpy(req->io->rw.iov, fast_iov,
2139 sizeof(struct iovec) * iter->nr_segs);
2143 static int io_alloc_async_ctx(struct io_kiocb *req)
2145 if (!io_op_defs[req->opcode].async_ctx)
2147 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2148 return req->io == NULL;
2151 static void io_rw_async(struct io_wq_work **workptr)
2153 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2154 struct iovec *iov = NULL;
2156 if (req->io->rw.iov != req->io->rw.fast_iov)
2157 iov = req->io->rw.iov;
2158 io_wq_submit_work(workptr);
2162 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2163 struct iovec *iovec, struct iovec *fast_iov,
2164 struct iov_iter *iter)
2166 if (!io_op_defs[req->opcode].async_ctx)
2169 if (io_alloc_async_ctx(req))
2172 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2174 req->work.func = io_rw_async;
2178 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2179 bool force_nonblock)
2181 struct io_async_ctx *io;
2182 struct iov_iter iter;
2185 ret = io_prep_rw(req, sqe, force_nonblock);
2189 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2196 io->rw.iov = io->rw.fast_iov;
2198 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2203 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2207 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
2208 bool force_nonblock)
2210 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2211 struct kiocb *kiocb = &req->rw.kiocb;
2212 struct iov_iter iter;
2214 ssize_t io_size, ret;
2216 ret = io_import_iovec(READ, req, &iovec, &iter);
2220 /* Ensure we clear previously set non-block flag */
2221 if (!force_nonblock)
2222 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2226 if (req->flags & REQ_F_LINK)
2227 req->result = io_size;
2230 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2231 * we know to async punt it even if it was opened O_NONBLOCK
2233 if (force_nonblock && !io_file_supports_async(req->file)) {
2234 req->flags |= REQ_F_MUST_PUNT;
2238 iov_count = iov_iter_count(&iter);
2239 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2243 if (req->file->f_op->read_iter)
2244 ret2 = call_read_iter(req->file, kiocb, &iter);
2246 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2248 /* Catch -EAGAIN return for forced non-blocking submission */
2249 if (!force_nonblock || ret2 != -EAGAIN) {
2250 kiocb_done(kiocb, ret2, nxt, req->in_async);
2253 ret = io_setup_async_rw(req, io_size, iovec,
2254 inline_vecs, &iter);
2261 if (!io_wq_current_is_worker())
2266 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2267 bool force_nonblock)
2269 struct io_async_ctx *io;
2270 struct iov_iter iter;
2273 ret = io_prep_rw(req, sqe, force_nonblock);
2277 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2284 io->rw.iov = io->rw.fast_iov;
2286 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2291 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2295 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
2296 bool force_nonblock)
2298 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2299 struct kiocb *kiocb = &req->rw.kiocb;
2300 struct iov_iter iter;
2302 ssize_t ret, io_size;
2304 ret = io_import_iovec(WRITE, req, &iovec, &iter);
2308 /* Ensure we clear previously set non-block flag */
2309 if (!force_nonblock)
2310 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2314 if (req->flags & REQ_F_LINK)
2315 req->result = io_size;
2318 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2319 * we know to async punt it even if it was opened O_NONBLOCK
2321 if (force_nonblock && !io_file_supports_async(req->file)) {
2322 req->flags |= REQ_F_MUST_PUNT;
2326 /* file path doesn't support NOWAIT for non-direct_IO */
2327 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2328 (req->flags & REQ_F_ISREG))
2331 iov_count = iov_iter_count(&iter);
2332 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2337 * Open-code file_start_write here to grab freeze protection,
2338 * which will be released by another thread in
2339 * io_complete_rw(). Fool lockdep by telling it the lock got
2340 * released so that it doesn't complain about the held lock when
2341 * we return to userspace.
2343 if (req->flags & REQ_F_ISREG) {
2344 __sb_start_write(file_inode(req->file)->i_sb,
2345 SB_FREEZE_WRITE, true);
2346 __sb_writers_release(file_inode(req->file)->i_sb,
2349 kiocb->ki_flags |= IOCB_WRITE;
2351 if (req->file->f_op->write_iter)
2352 ret2 = call_write_iter(req->file, kiocb, &iter);
2354 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2355 if (!force_nonblock || ret2 != -EAGAIN) {
2356 kiocb_done(kiocb, ret2, nxt, req->in_async);
2359 ret = io_setup_async_rw(req, io_size, iovec,
2360 inline_vecs, &iter);
2367 if (!io_wq_current_is_worker())
2373 * IORING_OP_NOP just posts a completion event, nothing else.
2375 static int io_nop(struct io_kiocb *req)
2377 struct io_ring_ctx *ctx = req->ctx;
2379 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2382 io_cqring_add_event(req, 0);
2387 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2389 struct io_ring_ctx *ctx = req->ctx;
2394 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2396 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2399 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2400 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2403 req->sync.off = READ_ONCE(sqe->off);
2404 req->sync.len = READ_ONCE(sqe->len);
2408 static bool io_req_cancelled(struct io_kiocb *req)
2410 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2411 req_set_fail_links(req);
2412 io_cqring_add_event(req, -ECANCELED);
2420 static void io_link_work_cb(struct io_wq_work **workptr)
2422 struct io_wq_work *work = *workptr;
2423 struct io_kiocb *link = work->data;
2425 io_queue_linked_timeout(link);
2426 work->func = io_wq_submit_work;
2429 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2431 struct io_kiocb *link;
2433 io_prep_async_work(nxt, &link);
2434 *workptr = &nxt->work;
2436 nxt->work.flags |= IO_WQ_WORK_CB;
2437 nxt->work.func = io_link_work_cb;
2438 nxt->work.data = link;
2442 static void io_fsync_finish(struct io_wq_work **workptr)
2444 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2445 loff_t end = req->sync.off + req->sync.len;
2446 struct io_kiocb *nxt = NULL;
2449 if (io_req_cancelled(req))
2452 ret = vfs_fsync_range(req->file, req->sync.off,
2453 end > 0 ? end : LLONG_MAX,
2454 req->sync.flags & IORING_FSYNC_DATASYNC);
2456 req_set_fail_links(req);
2457 io_cqring_add_event(req, ret);
2458 io_put_req_find_next(req, &nxt);
2460 io_wq_assign_next(workptr, nxt);
2463 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2464 bool force_nonblock)
2466 struct io_wq_work *work, *old_work;
2468 /* fsync always requires a blocking context */
2469 if (force_nonblock) {
2471 req->work.func = io_fsync_finish;
2475 work = old_work = &req->work;
2476 io_fsync_finish(&work);
2477 if (work && work != old_work)
2478 *nxt = container_of(work, struct io_kiocb, work);
2482 static void io_fallocate_finish(struct io_wq_work **workptr)
2484 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2485 struct io_kiocb *nxt = NULL;
2488 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2491 req_set_fail_links(req);
2492 io_cqring_add_event(req, ret);
2493 io_put_req_find_next(req, &nxt);
2495 io_wq_assign_next(workptr, nxt);
2498 static int io_fallocate_prep(struct io_kiocb *req,
2499 const struct io_uring_sqe *sqe)
2501 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2504 req->sync.off = READ_ONCE(sqe->off);
2505 req->sync.len = READ_ONCE(sqe->addr);
2506 req->sync.mode = READ_ONCE(sqe->len);
2510 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2511 bool force_nonblock)
2513 struct io_wq_work *work, *old_work;
2515 /* fallocate always requiring blocking context */
2516 if (force_nonblock) {
2518 req->work.func = io_fallocate_finish;
2522 work = old_work = &req->work;
2523 io_fallocate_finish(&work);
2524 if (work && work != old_work)
2525 *nxt = container_of(work, struct io_kiocb, work);
2530 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2532 const char __user *fname;
2535 if (sqe->ioprio || sqe->buf_index)
2538 req->open.dfd = READ_ONCE(sqe->fd);
2539 req->open.how.mode = READ_ONCE(sqe->len);
2540 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2541 req->open.how.flags = READ_ONCE(sqe->open_flags);
2543 req->open.filename = getname(fname);
2544 if (IS_ERR(req->open.filename)) {
2545 ret = PTR_ERR(req->open.filename);
2546 req->open.filename = NULL;
2553 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2555 struct open_how __user *how;
2556 const char __user *fname;
2560 if (sqe->ioprio || sqe->buf_index)
2563 req->open.dfd = READ_ONCE(sqe->fd);
2564 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2565 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2566 len = READ_ONCE(sqe->len);
2568 if (len < OPEN_HOW_SIZE_VER0)
2571 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2576 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2577 req->open.how.flags |= O_LARGEFILE;
2579 req->open.filename = getname(fname);
2580 if (IS_ERR(req->open.filename)) {
2581 ret = PTR_ERR(req->open.filename);
2582 req->open.filename = NULL;
2589 static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2590 bool force_nonblock)
2592 struct open_flags op;
2599 ret = build_open_flags(&req->open.how, &op);
2603 ret = get_unused_fd_flags(req->open.how.flags);
2607 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2610 ret = PTR_ERR(file);
2612 fsnotify_open(file);
2613 fd_install(ret, file);
2616 putname(req->open.filename);
2618 req_set_fail_links(req);
2619 io_cqring_add_event(req, ret);
2620 io_put_req_find_next(req, nxt);
2624 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2625 bool force_nonblock)
2627 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2628 return io_openat2(req, nxt, force_nonblock);
2631 static int io_epoll_ctl_prep(struct io_kiocb *req,
2632 const struct io_uring_sqe *sqe)
2634 #if defined(CONFIG_EPOLL)
2635 if (sqe->ioprio || sqe->buf_index)
2638 req->epoll.epfd = READ_ONCE(sqe->fd);
2639 req->epoll.op = READ_ONCE(sqe->len);
2640 req->epoll.fd = READ_ONCE(sqe->off);
2642 if (ep_op_has_event(req->epoll.op)) {
2643 struct epoll_event __user *ev;
2645 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
2646 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
2656 static int io_epoll_ctl(struct io_kiocb *req, struct io_kiocb **nxt,
2657 bool force_nonblock)
2659 #if defined(CONFIG_EPOLL)
2660 struct io_epoll *ie = &req->epoll;
2663 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
2664 if (force_nonblock && ret == -EAGAIN)
2668 req_set_fail_links(req);
2669 io_cqring_add_event(req, ret);
2670 io_put_req_find_next(req, nxt);
2677 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2679 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2680 if (sqe->ioprio || sqe->buf_index || sqe->off)
2683 req->madvise.addr = READ_ONCE(sqe->addr);
2684 req->madvise.len = READ_ONCE(sqe->len);
2685 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2692 static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2693 bool force_nonblock)
2695 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2696 struct io_madvise *ma = &req->madvise;
2702 ret = do_madvise(ma->addr, ma->len, ma->advice);
2704 req_set_fail_links(req);
2705 io_cqring_add_event(req, ret);
2706 io_put_req_find_next(req, nxt);
2713 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2715 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2718 req->fadvise.offset = READ_ONCE(sqe->off);
2719 req->fadvise.len = READ_ONCE(sqe->len);
2720 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2724 static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2725 bool force_nonblock)
2727 struct io_fadvise *fa = &req->fadvise;
2730 if (force_nonblock) {
2731 switch (fa->advice) {
2732 case POSIX_FADV_NORMAL:
2733 case POSIX_FADV_RANDOM:
2734 case POSIX_FADV_SEQUENTIAL:
2741 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2743 req_set_fail_links(req);
2744 io_cqring_add_event(req, ret);
2745 io_put_req_find_next(req, nxt);
2749 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2751 const char __user *fname;
2752 unsigned lookup_flags;
2755 if (sqe->ioprio || sqe->buf_index)
2758 req->open.dfd = READ_ONCE(sqe->fd);
2759 req->open.mask = READ_ONCE(sqe->len);
2760 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2761 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2762 req->open.how.flags = READ_ONCE(sqe->statx_flags);
2764 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
2767 req->open.filename = getname_flags(fname, lookup_flags, NULL);
2768 if (IS_ERR(req->open.filename)) {
2769 ret = PTR_ERR(req->open.filename);
2770 req->open.filename = NULL;
2777 static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2778 bool force_nonblock)
2780 struct io_open *ctx = &req->open;
2781 unsigned lookup_flags;
2789 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
2793 /* filename_lookup() drops it, keep a reference */
2794 ctx->filename->refcnt++;
2796 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2801 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
2803 if (retry_estale(ret, lookup_flags)) {
2804 lookup_flags |= LOOKUP_REVAL;
2808 ret = cp_statx(&stat, ctx->buffer);
2810 putname(ctx->filename);
2812 req_set_fail_links(req);
2813 io_cqring_add_event(req, ret);
2814 io_put_req_find_next(req, nxt);
2818 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2821 * If we queue this for async, it must not be cancellable. That would
2822 * leave the 'file' in an undeterminate state.
2824 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2826 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2827 sqe->rw_flags || sqe->buf_index)
2829 if (sqe->flags & IOSQE_FIXED_FILE)
2832 req->close.fd = READ_ONCE(sqe->fd);
2833 if (req->file->f_op == &io_uring_fops ||
2834 req->close.fd == req->ctx->ring_fd)
2840 static void io_close_finish(struct io_wq_work **workptr)
2842 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2843 struct io_kiocb *nxt = NULL;
2845 /* Invoked with files, we need to do the close */
2846 if (req->work.files) {
2849 ret = filp_close(req->close.put_file, req->work.files);
2851 req_set_fail_links(req);
2852 io_cqring_add_event(req, ret);
2855 fput(req->close.put_file);
2857 io_put_req_find_next(req, &nxt);
2859 io_wq_assign_next(workptr, nxt);
2862 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2863 bool force_nonblock)
2867 req->close.put_file = NULL;
2868 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2872 /* if the file has a flush method, be safe and punt to async */
2873 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker())
2877 * No ->flush(), safely close from here and just punt the
2878 * fput() to async context.
2880 ret = filp_close(req->close.put_file, current->files);
2883 req_set_fail_links(req);
2884 io_cqring_add_event(req, ret);
2886 if (io_wq_current_is_worker()) {
2887 struct io_wq_work *old_work, *work;
2889 old_work = work = &req->work;
2890 io_close_finish(&work);
2891 if (work && work != old_work)
2892 *nxt = container_of(work, struct io_kiocb, work);
2897 req->work.func = io_close_finish;
2899 * Do manual async queue here to avoid grabbing files - we don't
2900 * need the files, and it'll cause io_close_finish() to close
2901 * the file again and cause a double CQE entry for this request
2903 io_queue_async_work(req);
2907 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2909 struct io_ring_ctx *ctx = req->ctx;
2914 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2916 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2919 req->sync.off = READ_ONCE(sqe->off);
2920 req->sync.len = READ_ONCE(sqe->len);
2921 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2925 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2927 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2928 struct io_kiocb *nxt = NULL;
2931 if (io_req_cancelled(req))
2934 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2937 req_set_fail_links(req);
2938 io_cqring_add_event(req, ret);
2939 io_put_req_find_next(req, &nxt);
2941 io_wq_assign_next(workptr, nxt);
2944 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2945 bool force_nonblock)
2947 struct io_wq_work *work, *old_work;
2949 /* sync_file_range always requires a blocking context */
2950 if (force_nonblock) {
2952 req->work.func = io_sync_file_range_finish;
2956 work = old_work = &req->work;
2957 io_sync_file_range_finish(&work);
2958 if (work && work != old_work)
2959 *nxt = container_of(work, struct io_kiocb, work);
2963 #if defined(CONFIG_NET)
2964 static void io_sendrecv_async(struct io_wq_work **workptr)
2966 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2967 struct iovec *iov = NULL;
2969 if (req->io->rw.iov != req->io->rw.fast_iov)
2970 iov = req->io->msg.iov;
2971 io_wq_submit_work(workptr);
2976 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2978 #if defined(CONFIG_NET)
2979 struct io_sr_msg *sr = &req->sr_msg;
2980 struct io_async_ctx *io = req->io;
2982 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2983 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2984 sr->len = READ_ONCE(sqe->len);
2986 if (!io || req->opcode == IORING_OP_SEND)
2989 io->msg.iov = io->msg.fast_iov;
2990 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2997 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2998 bool force_nonblock)
3000 #if defined(CONFIG_NET)
3001 struct io_async_msghdr *kmsg = NULL;
3002 struct socket *sock;
3005 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3008 sock = sock_from_file(req->file, &ret);
3010 struct io_async_ctx io;
3011 struct sockaddr_storage addr;
3015 kmsg = &req->io->msg;
3016 kmsg->msg.msg_name = &addr;
3017 /* if iov is set, it's allocated already */
3019 kmsg->iov = kmsg->fast_iov;
3020 kmsg->msg.msg_iter.iov = kmsg->iov;
3022 struct io_sr_msg *sr = &req->sr_msg;
3025 kmsg->msg.msg_name = &addr;
3027 io.msg.iov = io.msg.fast_iov;
3028 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3029 sr->msg_flags, &io.msg.iov);
3034 flags = req->sr_msg.msg_flags;
3035 if (flags & MSG_DONTWAIT)
3036 req->flags |= REQ_F_NOWAIT;
3037 else if (force_nonblock)
3038 flags |= MSG_DONTWAIT;
3040 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3041 if (force_nonblock && ret == -EAGAIN) {
3044 if (io_alloc_async_ctx(req))
3046 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3047 req->work.func = io_sendrecv_async;
3050 if (ret == -ERESTARTSYS)
3054 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
3056 io_cqring_add_event(req, ret);
3058 req_set_fail_links(req);
3059 io_put_req_find_next(req, nxt);
3066 static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
3067 bool force_nonblock)
3069 #if defined(CONFIG_NET)
3070 struct socket *sock;
3073 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3076 sock = sock_from_file(req->file, &ret);
3078 struct io_sr_msg *sr = &req->sr_msg;
3083 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3088 msg.msg_name = NULL;
3089 msg.msg_control = NULL;
3090 msg.msg_controllen = 0;
3091 msg.msg_namelen = 0;
3093 flags = req->sr_msg.msg_flags;
3094 if (flags & MSG_DONTWAIT)
3095 req->flags |= REQ_F_NOWAIT;
3096 else if (force_nonblock)
3097 flags |= MSG_DONTWAIT;
3099 msg.msg_flags = flags;
3100 ret = sock_sendmsg(sock, &msg);
3101 if (force_nonblock && ret == -EAGAIN)
3103 if (ret == -ERESTARTSYS)
3107 io_cqring_add_event(req, ret);
3109 req_set_fail_links(req);
3110 io_put_req_find_next(req, nxt);
3117 static int io_recvmsg_prep(struct io_kiocb *req,
3118 const struct io_uring_sqe *sqe)
3120 #if defined(CONFIG_NET)
3121 struct io_sr_msg *sr = &req->sr_msg;
3122 struct io_async_ctx *io = req->io;
3124 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3125 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3126 sr->len = READ_ONCE(sqe->len);
3128 if (!io || req->opcode == IORING_OP_RECV)
3131 io->msg.iov = io->msg.fast_iov;
3132 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3133 &io->msg.uaddr, &io->msg.iov);
3139 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3140 bool force_nonblock)
3142 #if defined(CONFIG_NET)
3143 struct io_async_msghdr *kmsg = NULL;
3144 struct socket *sock;
3147 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3150 sock = sock_from_file(req->file, &ret);
3152 struct io_async_ctx io;
3153 struct sockaddr_storage addr;
3157 kmsg = &req->io->msg;
3158 kmsg->msg.msg_name = &addr;
3159 /* if iov is set, it's allocated already */
3161 kmsg->iov = kmsg->fast_iov;
3162 kmsg->msg.msg_iter.iov = kmsg->iov;
3164 struct io_sr_msg *sr = &req->sr_msg;
3167 kmsg->msg.msg_name = &addr;
3169 io.msg.iov = io.msg.fast_iov;
3170 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3171 sr->msg_flags, &io.msg.uaddr,
3177 flags = req->sr_msg.msg_flags;
3178 if (flags & MSG_DONTWAIT)
3179 req->flags |= REQ_F_NOWAIT;
3180 else if (force_nonblock)
3181 flags |= MSG_DONTWAIT;
3183 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3184 kmsg->uaddr, flags);
3185 if (force_nonblock && ret == -EAGAIN) {
3188 if (io_alloc_async_ctx(req))
3190 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
3191 req->work.func = io_sendrecv_async;
3194 if (ret == -ERESTARTSYS)
3198 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
3200 io_cqring_add_event(req, ret);
3202 req_set_fail_links(req);
3203 io_put_req_find_next(req, nxt);
3210 static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3211 bool force_nonblock)
3213 #if defined(CONFIG_NET)
3214 struct socket *sock;
3217 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3220 sock = sock_from_file(req->file, &ret);
3222 struct io_sr_msg *sr = &req->sr_msg;
3227 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3232 msg.msg_name = NULL;
3233 msg.msg_control = NULL;
3234 msg.msg_controllen = 0;
3235 msg.msg_namelen = 0;
3236 msg.msg_iocb = NULL;
3239 flags = req->sr_msg.msg_flags;
3240 if (flags & MSG_DONTWAIT)
3241 req->flags |= REQ_F_NOWAIT;
3242 else if (force_nonblock)
3243 flags |= MSG_DONTWAIT;
3245 ret = sock_recvmsg(sock, &msg, flags);
3246 if (force_nonblock && ret == -EAGAIN)
3248 if (ret == -ERESTARTSYS)
3252 io_cqring_add_event(req, ret);
3254 req_set_fail_links(req);
3255 io_put_req_find_next(req, nxt);
3263 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3265 #if defined(CONFIG_NET)
3266 struct io_accept *accept = &req->accept;
3268 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3270 if (sqe->ioprio || sqe->len || sqe->buf_index)
3273 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3274 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3275 accept->flags = READ_ONCE(sqe->accept_flags);
3282 #if defined(CONFIG_NET)
3283 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3284 bool force_nonblock)
3286 struct io_accept *accept = &req->accept;
3287 unsigned file_flags;
3290 file_flags = force_nonblock ? O_NONBLOCK : 0;
3291 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3292 accept->addr_len, accept->flags);
3293 if (ret == -EAGAIN && force_nonblock)
3295 if (ret == -ERESTARTSYS)
3298 req_set_fail_links(req);
3299 io_cqring_add_event(req, ret);
3300 io_put_req_find_next(req, nxt);
3304 static void io_accept_finish(struct io_wq_work **workptr)
3306 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3307 struct io_kiocb *nxt = NULL;
3309 if (io_req_cancelled(req))
3311 __io_accept(req, &nxt, false);
3313 io_wq_assign_next(workptr, nxt);
3317 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3318 bool force_nonblock)
3320 #if defined(CONFIG_NET)
3323 ret = __io_accept(req, nxt, force_nonblock);
3324 if (ret == -EAGAIN && force_nonblock) {
3325 req->work.func = io_accept_finish;
3335 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3337 #if defined(CONFIG_NET)
3338 struct io_connect *conn = &req->connect;
3339 struct io_async_ctx *io = req->io;
3341 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3343 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3346 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3347 conn->addr_len = READ_ONCE(sqe->addr2);
3352 return move_addr_to_kernel(conn->addr, conn->addr_len,
3353 &io->connect.address);
3359 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3360 bool force_nonblock)
3362 #if defined(CONFIG_NET)
3363 struct io_async_ctx __io, *io;
3364 unsigned file_flags;
3370 ret = move_addr_to_kernel(req->connect.addr,
3371 req->connect.addr_len,
3372 &__io.connect.address);
3378 file_flags = force_nonblock ? O_NONBLOCK : 0;
3380 ret = __sys_connect_file(req->file, &io->connect.address,
3381 req->connect.addr_len, file_flags);
3382 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
3385 if (io_alloc_async_ctx(req)) {
3389 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
3392 if (ret == -ERESTARTSYS)
3396 req_set_fail_links(req);
3397 io_cqring_add_event(req, ret);
3398 io_put_req_find_next(req, nxt);
3405 static void io_poll_remove_one(struct io_kiocb *req)
3407 struct io_poll_iocb *poll = &req->poll;
3409 spin_lock(&poll->head->lock);
3410 WRITE_ONCE(poll->canceled, true);
3411 if (!list_empty(&poll->wait.entry)) {
3412 list_del_init(&poll->wait.entry);
3413 io_queue_async_work(req);
3415 spin_unlock(&poll->head->lock);
3416 hash_del(&req->hash_node);
3419 static void io_poll_remove_all(struct io_ring_ctx *ctx)
3421 struct hlist_node *tmp;
3422 struct io_kiocb *req;
3425 spin_lock_irq(&ctx->completion_lock);
3426 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3427 struct hlist_head *list;
3429 list = &ctx->cancel_hash[i];
3430 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3431 io_poll_remove_one(req);
3433 spin_unlock_irq(&ctx->completion_lock);
3436 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3438 struct hlist_head *list;
3439 struct io_kiocb *req;
3441 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3442 hlist_for_each_entry(req, list, hash_node) {
3443 if (sqe_addr == req->user_data) {
3444 io_poll_remove_one(req);
3452 static int io_poll_remove_prep(struct io_kiocb *req,
3453 const struct io_uring_sqe *sqe)
3455 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3457 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3461 req->poll.addr = READ_ONCE(sqe->addr);
3466 * Find a running poll command that matches one specified in sqe->addr,
3467 * and remove it if found.
3469 static int io_poll_remove(struct io_kiocb *req)
3471 struct io_ring_ctx *ctx = req->ctx;
3475 addr = req->poll.addr;
3476 spin_lock_irq(&ctx->completion_lock);
3477 ret = io_poll_cancel(ctx, addr);
3478 spin_unlock_irq(&ctx->completion_lock);
3480 io_cqring_add_event(req, ret);
3482 req_set_fail_links(req);
3487 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
3489 struct io_ring_ctx *ctx = req->ctx;
3491 req->poll.done = true;
3493 io_cqring_fill_event(req, error);
3495 io_cqring_fill_event(req, mangle_poll(mask));
3496 io_commit_cqring(ctx);
3499 static void io_poll_complete_work(struct io_wq_work **workptr)
3501 struct io_wq_work *work = *workptr;
3502 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3503 struct io_poll_iocb *poll = &req->poll;
3504 struct poll_table_struct pt = { ._key = poll->events };
3505 struct io_ring_ctx *ctx = req->ctx;
3506 struct io_kiocb *nxt = NULL;
3510 if (work->flags & IO_WQ_WORK_CANCEL) {
3511 WRITE_ONCE(poll->canceled, true);
3513 } else if (READ_ONCE(poll->canceled)) {
3517 if (ret != -ECANCELED)
3518 mask = vfs_poll(poll->file, &pt) & poll->events;
3521 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3522 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3523 * synchronize with them. In the cancellation case the list_del_init
3524 * itself is not actually needed, but harmless so we keep it in to
3525 * avoid further branches in the fast path.
3527 spin_lock_irq(&ctx->completion_lock);
3528 if (!mask && ret != -ECANCELED) {
3529 add_wait_queue(poll->head, &poll->wait);
3530 spin_unlock_irq(&ctx->completion_lock);
3533 hash_del(&req->hash_node);
3534 io_poll_complete(req, mask, ret);
3535 spin_unlock_irq(&ctx->completion_lock);
3537 io_cqring_ev_posted(ctx);
3540 req_set_fail_links(req);
3541 io_put_req_find_next(req, &nxt);
3543 io_wq_assign_next(workptr, nxt);
3546 static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3548 struct io_kiocb *req, *tmp;
3549 struct req_batch rb;
3551 rb.to_free = rb.need_iter = 0;
3552 spin_lock_irq(&ctx->completion_lock);
3553 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3554 hash_del(&req->hash_node);
3555 io_poll_complete(req, req->result, 0);
3557 if (refcount_dec_and_test(&req->refs) &&
3558 !io_req_multi_free(&rb, req)) {
3559 req->flags |= REQ_F_COMP_LOCKED;
3563 spin_unlock_irq(&ctx->completion_lock);
3565 io_cqring_ev_posted(ctx);
3566 io_free_req_many(ctx, &rb);
3569 static void io_poll_flush(struct io_wq_work **workptr)
3571 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3572 struct llist_node *nodes;
3574 nodes = llist_del_all(&req->ctx->poll_llist);
3576 __io_poll_flush(req->ctx, nodes);
3579 static void io_poll_trigger_evfd(struct io_wq_work **workptr)
3581 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3583 eventfd_signal(req->ctx->cq_ev_fd, 1);
3587 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3590 struct io_poll_iocb *poll = wait->private;
3591 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3592 struct io_ring_ctx *ctx = req->ctx;
3593 __poll_t mask = key_to_poll(key);
3595 /* for instances that support it check for an event match first: */
3596 if (mask && !(mask & poll->events))
3599 list_del_init(&poll->wait.entry);
3602 * Run completion inline if we can. We're using trylock here because
3603 * we are violating the completion_lock -> poll wq lock ordering.
3604 * If we have a link timeout we're going to need the completion_lock
3605 * for finalizing the request, mark us as having grabbed that already.
3608 unsigned long flags;
3610 if (llist_empty(&ctx->poll_llist) &&
3611 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
3614 hash_del(&req->hash_node);
3615 io_poll_complete(req, mask, 0);
3617 trigger_ev = io_should_trigger_evfd(ctx);
3618 if (trigger_ev && eventfd_signal_count()) {
3620 req->work.func = io_poll_trigger_evfd;
3622 req->flags |= REQ_F_COMP_LOCKED;
3626 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3627 __io_cqring_ev_posted(ctx, trigger_ev);
3630 req->llist_node.next = NULL;
3631 /* if the list wasn't empty, we're done */
3632 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3635 req->work.func = io_poll_flush;
3639 io_queue_async_work(req);
3644 struct io_poll_table {
3645 struct poll_table_struct pt;
3646 struct io_kiocb *req;
3650 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3651 struct poll_table_struct *p)
3653 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3655 if (unlikely(pt->req->poll.head)) {
3656 pt->error = -EINVAL;
3661 pt->req->poll.head = head;
3662 add_wait_queue(head, &pt->req->poll.wait);
3665 static void io_poll_req_insert(struct io_kiocb *req)
3667 struct io_ring_ctx *ctx = req->ctx;
3668 struct hlist_head *list;
3670 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3671 hlist_add_head(&req->hash_node, list);
3674 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3676 struct io_poll_iocb *poll = &req->poll;
3679 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3681 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3686 events = READ_ONCE(sqe->poll_events);
3687 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
3691 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3693 struct io_poll_iocb *poll = &req->poll;
3694 struct io_ring_ctx *ctx = req->ctx;
3695 struct io_poll_table ipt;
3696 bool cancel = false;
3699 INIT_IO_WORK(&req->work, io_poll_complete_work);
3700 INIT_HLIST_NODE(&req->hash_node);
3704 poll->canceled = false;
3706 ipt.pt._qproc = io_poll_queue_proc;
3707 ipt.pt._key = poll->events;
3709 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3711 /* initialized the list so that we can do list_empty checks */
3712 INIT_LIST_HEAD(&poll->wait.entry);
3713 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3714 poll->wait.private = poll;
3716 INIT_LIST_HEAD(&req->list);
3718 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
3720 spin_lock_irq(&ctx->completion_lock);
3721 if (likely(poll->head)) {
3722 spin_lock(&poll->head->lock);
3723 if (unlikely(list_empty(&poll->wait.entry))) {
3729 if (mask || ipt.error)
3730 list_del_init(&poll->wait.entry);
3732 WRITE_ONCE(poll->canceled, true);
3733 else if (!poll->done) /* actually waiting for an event */
3734 io_poll_req_insert(req);
3735 spin_unlock(&poll->head->lock);
3737 if (mask) { /* no async, we'd stolen it */
3739 io_poll_complete(req, mask, 0);
3741 spin_unlock_irq(&ctx->completion_lock);
3744 io_cqring_ev_posted(ctx);
3745 io_put_req_find_next(req, nxt);
3750 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3752 struct io_timeout_data *data = container_of(timer,
3753 struct io_timeout_data, timer);
3754 struct io_kiocb *req = data->req;
3755 struct io_ring_ctx *ctx = req->ctx;
3756 unsigned long flags;
3758 atomic_inc(&ctx->cq_timeouts);
3760 spin_lock_irqsave(&ctx->completion_lock, flags);
3762 * We could be racing with timeout deletion. If the list is empty,
3763 * then timeout lookup already found it and will be handling it.
3765 if (!list_empty(&req->list)) {
3766 struct io_kiocb *prev;
3769 * Adjust the reqs sequence before the current one because it
3770 * will consume a slot in the cq_ring and the cq_tail
3771 * pointer will be increased, otherwise other timeout reqs may
3772 * return in advance without waiting for enough wait_nr.
3775 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3777 list_del_init(&req->list);
3780 io_cqring_fill_event(req, -ETIME);
3781 io_commit_cqring(ctx);
3782 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3784 io_cqring_ev_posted(ctx);
3785 req_set_fail_links(req);
3787 return HRTIMER_NORESTART;
3790 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3792 struct io_kiocb *req;
3795 list_for_each_entry(req, &ctx->timeout_list, list) {
3796 if (user_data == req->user_data) {
3797 list_del_init(&req->list);
3806 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3810 req_set_fail_links(req);
3811 io_cqring_fill_event(req, -ECANCELED);
3816 static int io_timeout_remove_prep(struct io_kiocb *req,
3817 const struct io_uring_sqe *sqe)
3819 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3821 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3824 req->timeout.addr = READ_ONCE(sqe->addr);
3825 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3826 if (req->timeout.flags)
3833 * Remove or update an existing timeout command
3835 static int io_timeout_remove(struct io_kiocb *req)
3837 struct io_ring_ctx *ctx = req->ctx;
3840 spin_lock_irq(&ctx->completion_lock);
3841 ret = io_timeout_cancel(ctx, req->timeout.addr);
3843 io_cqring_fill_event(req, ret);
3844 io_commit_cqring(ctx);
3845 spin_unlock_irq(&ctx->completion_lock);
3846 io_cqring_ev_posted(ctx);
3848 req_set_fail_links(req);
3853 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3854 bool is_timeout_link)
3856 struct io_timeout_data *data;
3859 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3861 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3863 if (sqe->off && is_timeout_link)
3865 flags = READ_ONCE(sqe->timeout_flags);
3866 if (flags & ~IORING_TIMEOUT_ABS)
3869 req->timeout.count = READ_ONCE(sqe->off);
3871 if (!req->io && io_alloc_async_ctx(req))
3874 data = &req->io->timeout;
3876 req->flags |= REQ_F_TIMEOUT;
3878 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3881 if (flags & IORING_TIMEOUT_ABS)
3882 data->mode = HRTIMER_MODE_ABS;
3884 data->mode = HRTIMER_MODE_REL;
3886 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3890 static int io_timeout(struct io_kiocb *req)
3893 struct io_ring_ctx *ctx = req->ctx;
3894 struct io_timeout_data *data;
3895 struct list_head *entry;
3898 data = &req->io->timeout;
3901 * sqe->off holds how many events that need to occur for this
3902 * timeout event to be satisfied. If it isn't set, then this is
3903 * a pure timeout request, sequence isn't used.
3905 count = req->timeout.count;
3907 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3908 spin_lock_irq(&ctx->completion_lock);
3909 entry = ctx->timeout_list.prev;
3913 req->sequence = ctx->cached_sq_head + count - 1;
3914 data->seq_offset = count;
3917 * Insertion sort, ensuring the first entry in the list is always
3918 * the one we need first.
3920 spin_lock_irq(&ctx->completion_lock);
3921 list_for_each_prev(entry, &ctx->timeout_list) {
3922 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3923 unsigned nxt_sq_head;
3924 long long tmp, tmp_nxt;
3925 u32 nxt_offset = nxt->io->timeout.seq_offset;
3927 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3931 * Since cached_sq_head + count - 1 can overflow, use type long
3934 tmp = (long long)ctx->cached_sq_head + count - 1;
3935 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3936 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3939 * cached_sq_head may overflow, and it will never overflow twice
3940 * once there is some timeout req still be valid.
3942 if (ctx->cached_sq_head < nxt_sq_head)
3949 * Sequence of reqs after the insert one and itself should
3950 * be adjusted because each timeout req consumes a slot.
3955 req->sequence -= span;
3957 list_add(&req->list, entry);
3958 data->timer.function = io_timeout_fn;
3959 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3960 spin_unlock_irq(&ctx->completion_lock);
3964 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3966 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3968 return req->user_data == (unsigned long) data;
3971 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3973 enum io_wq_cancel cancel_ret;
3976 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3977 switch (cancel_ret) {
3978 case IO_WQ_CANCEL_OK:
3981 case IO_WQ_CANCEL_RUNNING:
3984 case IO_WQ_CANCEL_NOTFOUND:
3992 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3993 struct io_kiocb *req, __u64 sqe_addr,
3994 struct io_kiocb **nxt, int success_ret)
3996 unsigned long flags;
3999 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4000 if (ret != -ENOENT) {
4001 spin_lock_irqsave(&ctx->completion_lock, flags);
4005 spin_lock_irqsave(&ctx->completion_lock, flags);
4006 ret = io_timeout_cancel(ctx, sqe_addr);
4009 ret = io_poll_cancel(ctx, sqe_addr);
4013 io_cqring_fill_event(req, ret);
4014 io_commit_cqring(ctx);
4015 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4016 io_cqring_ev_posted(ctx);
4019 req_set_fail_links(req);
4020 io_put_req_find_next(req, nxt);
4023 static int io_async_cancel_prep(struct io_kiocb *req,
4024 const struct io_uring_sqe *sqe)
4026 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4028 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4032 req->cancel.addr = READ_ONCE(sqe->addr);
4036 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
4038 struct io_ring_ctx *ctx = req->ctx;
4040 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
4044 static int io_files_update_prep(struct io_kiocb *req,
4045 const struct io_uring_sqe *sqe)
4047 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4050 req->files_update.offset = READ_ONCE(sqe->off);
4051 req->files_update.nr_args = READ_ONCE(sqe->len);
4052 if (!req->files_update.nr_args)
4054 req->files_update.arg = READ_ONCE(sqe->addr);
4058 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
4060 struct io_ring_ctx *ctx = req->ctx;
4061 struct io_uring_files_update up;
4067 up.offset = req->files_update.offset;
4068 up.fds = req->files_update.arg;
4070 mutex_lock(&ctx->uring_lock);
4071 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4072 mutex_unlock(&ctx->uring_lock);
4075 req_set_fail_links(req);
4076 io_cqring_add_event(req, ret);
4081 static int io_req_defer_prep(struct io_kiocb *req,
4082 const struct io_uring_sqe *sqe)
4086 if (io_op_defs[req->opcode].file_table) {
4087 ret = io_grab_files(req);
4092 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4094 switch (req->opcode) {
4097 case IORING_OP_READV:
4098 case IORING_OP_READ_FIXED:
4099 case IORING_OP_READ:
4100 ret = io_read_prep(req, sqe, true);
4102 case IORING_OP_WRITEV:
4103 case IORING_OP_WRITE_FIXED:
4104 case IORING_OP_WRITE:
4105 ret = io_write_prep(req, sqe, true);
4107 case IORING_OP_POLL_ADD:
4108 ret = io_poll_add_prep(req, sqe);
4110 case IORING_OP_POLL_REMOVE:
4111 ret = io_poll_remove_prep(req, sqe);
4113 case IORING_OP_FSYNC:
4114 ret = io_prep_fsync(req, sqe);
4116 case IORING_OP_SYNC_FILE_RANGE:
4117 ret = io_prep_sfr(req, sqe);
4119 case IORING_OP_SENDMSG:
4120 case IORING_OP_SEND:
4121 ret = io_sendmsg_prep(req, sqe);
4123 case IORING_OP_RECVMSG:
4124 case IORING_OP_RECV:
4125 ret = io_recvmsg_prep(req, sqe);
4127 case IORING_OP_CONNECT:
4128 ret = io_connect_prep(req, sqe);
4130 case IORING_OP_TIMEOUT:
4131 ret = io_timeout_prep(req, sqe, false);
4133 case IORING_OP_TIMEOUT_REMOVE:
4134 ret = io_timeout_remove_prep(req, sqe);
4136 case IORING_OP_ASYNC_CANCEL:
4137 ret = io_async_cancel_prep(req, sqe);
4139 case IORING_OP_LINK_TIMEOUT:
4140 ret = io_timeout_prep(req, sqe, true);
4142 case IORING_OP_ACCEPT:
4143 ret = io_accept_prep(req, sqe);
4145 case IORING_OP_FALLOCATE:
4146 ret = io_fallocate_prep(req, sqe);
4148 case IORING_OP_OPENAT:
4149 ret = io_openat_prep(req, sqe);
4151 case IORING_OP_CLOSE:
4152 ret = io_close_prep(req, sqe);
4154 case IORING_OP_FILES_UPDATE:
4155 ret = io_files_update_prep(req, sqe);
4157 case IORING_OP_STATX:
4158 ret = io_statx_prep(req, sqe);
4160 case IORING_OP_FADVISE:
4161 ret = io_fadvise_prep(req, sqe);
4163 case IORING_OP_MADVISE:
4164 ret = io_madvise_prep(req, sqe);
4166 case IORING_OP_OPENAT2:
4167 ret = io_openat2_prep(req, sqe);
4169 case IORING_OP_EPOLL_CTL:
4170 ret = io_epoll_ctl_prep(req, sqe);
4173 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4182 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4184 struct io_ring_ctx *ctx = req->ctx;
4187 /* Still need defer if there is pending req in defer list. */
4188 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4191 if (!req->io && io_alloc_async_ctx(req))
4194 ret = io_req_defer_prep(req, sqe);
4198 spin_lock_irq(&ctx->completion_lock);
4199 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4200 spin_unlock_irq(&ctx->completion_lock);
4204 trace_io_uring_defer(ctx, req, req->user_data);
4205 list_add_tail(&req->list, &ctx->defer_list);
4206 spin_unlock_irq(&ctx->completion_lock);
4207 return -EIOCBQUEUED;
4210 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4211 struct io_kiocb **nxt, bool force_nonblock)
4213 struct io_ring_ctx *ctx = req->ctx;
4216 switch (req->opcode) {
4220 case IORING_OP_READV:
4221 case IORING_OP_READ_FIXED:
4222 case IORING_OP_READ:
4224 ret = io_read_prep(req, sqe, force_nonblock);
4228 ret = io_read(req, nxt, force_nonblock);
4230 case IORING_OP_WRITEV:
4231 case IORING_OP_WRITE_FIXED:
4232 case IORING_OP_WRITE:
4234 ret = io_write_prep(req, sqe, force_nonblock);
4238 ret = io_write(req, nxt, force_nonblock);
4240 case IORING_OP_FSYNC:
4242 ret = io_prep_fsync(req, sqe);
4246 ret = io_fsync(req, nxt, force_nonblock);
4248 case IORING_OP_POLL_ADD:
4250 ret = io_poll_add_prep(req, sqe);
4254 ret = io_poll_add(req, nxt);
4256 case IORING_OP_POLL_REMOVE:
4258 ret = io_poll_remove_prep(req, sqe);
4262 ret = io_poll_remove(req);
4264 case IORING_OP_SYNC_FILE_RANGE:
4266 ret = io_prep_sfr(req, sqe);
4270 ret = io_sync_file_range(req, nxt, force_nonblock);
4272 case IORING_OP_SENDMSG:
4273 case IORING_OP_SEND:
4275 ret = io_sendmsg_prep(req, sqe);
4279 if (req->opcode == IORING_OP_SENDMSG)
4280 ret = io_sendmsg(req, nxt, force_nonblock);
4282 ret = io_send(req, nxt, force_nonblock);
4284 case IORING_OP_RECVMSG:
4285 case IORING_OP_RECV:
4287 ret = io_recvmsg_prep(req, sqe);
4291 if (req->opcode == IORING_OP_RECVMSG)
4292 ret = io_recvmsg(req, nxt, force_nonblock);
4294 ret = io_recv(req, nxt, force_nonblock);
4296 case IORING_OP_TIMEOUT:
4298 ret = io_timeout_prep(req, sqe, false);
4302 ret = io_timeout(req);
4304 case IORING_OP_TIMEOUT_REMOVE:
4306 ret = io_timeout_remove_prep(req, sqe);
4310 ret = io_timeout_remove(req);
4312 case IORING_OP_ACCEPT:
4314 ret = io_accept_prep(req, sqe);
4318 ret = io_accept(req, nxt, force_nonblock);
4320 case IORING_OP_CONNECT:
4322 ret = io_connect_prep(req, sqe);
4326 ret = io_connect(req, nxt, force_nonblock);
4328 case IORING_OP_ASYNC_CANCEL:
4330 ret = io_async_cancel_prep(req, sqe);
4334 ret = io_async_cancel(req, nxt);
4336 case IORING_OP_FALLOCATE:
4338 ret = io_fallocate_prep(req, sqe);
4342 ret = io_fallocate(req, nxt, force_nonblock);
4344 case IORING_OP_OPENAT:
4346 ret = io_openat_prep(req, sqe);
4350 ret = io_openat(req, nxt, force_nonblock);
4352 case IORING_OP_CLOSE:
4354 ret = io_close_prep(req, sqe);
4358 ret = io_close(req, nxt, force_nonblock);
4360 case IORING_OP_FILES_UPDATE:
4362 ret = io_files_update_prep(req, sqe);
4366 ret = io_files_update(req, force_nonblock);
4368 case IORING_OP_STATX:
4370 ret = io_statx_prep(req, sqe);
4374 ret = io_statx(req, nxt, force_nonblock);
4376 case IORING_OP_FADVISE:
4378 ret = io_fadvise_prep(req, sqe);
4382 ret = io_fadvise(req, nxt, force_nonblock);
4384 case IORING_OP_MADVISE:
4386 ret = io_madvise_prep(req, sqe);
4390 ret = io_madvise(req, nxt, force_nonblock);
4392 case IORING_OP_OPENAT2:
4394 ret = io_openat2_prep(req, sqe);
4398 ret = io_openat2(req, nxt, force_nonblock);
4400 case IORING_OP_EPOLL_CTL:
4402 ret = io_epoll_ctl_prep(req, sqe);
4406 ret = io_epoll_ctl(req, nxt, force_nonblock);
4416 if (ctx->flags & IORING_SETUP_IOPOLL) {
4417 const bool in_async = io_wq_current_is_worker();
4419 if (req->result == -EAGAIN)
4422 /* workqueue context doesn't hold uring_lock, grab it now */
4424 mutex_lock(&ctx->uring_lock);
4426 io_iopoll_req_issued(req);
4429 mutex_unlock(&ctx->uring_lock);
4435 static void io_wq_submit_work(struct io_wq_work **workptr)
4437 struct io_wq_work *work = *workptr;
4438 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4439 struct io_kiocb *nxt = NULL;
4442 /* if NO_CANCEL is set, we must still run the work */
4443 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4444 IO_WQ_WORK_CANCEL) {
4449 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
4450 req->in_async = true;
4452 ret = io_issue_sqe(req, NULL, &nxt, false);
4454 * We can get EAGAIN for polled IO even though we're
4455 * forcing a sync submission from here, since we can't
4456 * wait for request slots on the block side.
4464 /* drop submission reference */
4468 req_set_fail_links(req);
4469 io_cqring_add_event(req, ret);
4473 /* if a dependent link is ready, pass it back */
4475 io_wq_assign_next(workptr, nxt);
4478 static int io_req_needs_file(struct io_kiocb *req, int fd)
4480 if (!io_op_defs[req->opcode].needs_file)
4482 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4487 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4490 struct fixed_file_table *table;
4492 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4493 return table->files[index & IORING_FILE_TABLE_MASK];;
4496 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4497 const struct io_uring_sqe *sqe)
4499 struct io_ring_ctx *ctx = req->ctx;
4503 flags = READ_ONCE(sqe->flags);
4504 fd = READ_ONCE(sqe->fd);
4506 if (!io_req_needs_file(req, fd))
4509 if (flags & IOSQE_FIXED_FILE) {
4510 if (unlikely(!ctx->file_data ||
4511 (unsigned) fd >= ctx->nr_user_files))
4513 fd = array_index_nospec(fd, ctx->nr_user_files);
4514 req->file = io_file_from_index(ctx, fd);
4517 req->flags |= REQ_F_FIXED_FILE;
4518 percpu_ref_get(&ctx->file_data->refs);
4520 if (req->needs_fixed_file)
4522 trace_io_uring_file_get(ctx, fd);
4523 req->file = io_file_get(state, fd);
4524 if (unlikely(!req->file))
4531 static int io_grab_files(struct io_kiocb *req)
4534 struct io_ring_ctx *ctx = req->ctx;
4536 if (req->work.files)
4538 if (!ctx->ring_file)
4542 spin_lock_irq(&ctx->inflight_lock);
4544 * We use the f_ops->flush() handler to ensure that we can flush
4545 * out work accessing these files if the fd is closed. Check if
4546 * the fd has changed since we started down this path, and disallow
4547 * this operation if it has.
4549 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
4550 list_add(&req->inflight_entry, &ctx->inflight_list);
4551 req->flags |= REQ_F_INFLIGHT;
4552 req->work.files = current->files;
4555 spin_unlock_irq(&ctx->inflight_lock);
4561 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
4563 struct io_timeout_data *data = container_of(timer,
4564 struct io_timeout_data, timer);
4565 struct io_kiocb *req = data->req;
4566 struct io_ring_ctx *ctx = req->ctx;
4567 struct io_kiocb *prev = NULL;
4568 unsigned long flags;
4570 spin_lock_irqsave(&ctx->completion_lock, flags);
4573 * We don't expect the list to be empty, that will only happen if we
4574 * race with the completion of the linked work.
4576 if (!list_empty(&req->link_list)) {
4577 prev = list_entry(req->link_list.prev, struct io_kiocb,
4579 if (refcount_inc_not_zero(&prev->refs)) {
4580 list_del_init(&req->link_list);
4581 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4586 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4589 req_set_fail_links(prev);
4590 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4594 io_cqring_add_event(req, -ETIME);
4597 return HRTIMER_NORESTART;
4600 static void io_queue_linked_timeout(struct io_kiocb *req)
4602 struct io_ring_ctx *ctx = req->ctx;
4605 * If the list is now empty, then our linked request finished before
4606 * we got a chance to setup the timer
4608 spin_lock_irq(&ctx->completion_lock);
4609 if (!list_empty(&req->link_list)) {
4610 struct io_timeout_data *data = &req->io->timeout;
4612 data->timer.function = io_link_timeout_fn;
4613 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4616 spin_unlock_irq(&ctx->completion_lock);
4618 /* drop submission reference */
4622 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
4624 struct io_kiocb *nxt;
4626 if (!(req->flags & REQ_F_LINK))
4629 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4631 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
4634 req->flags |= REQ_F_LINK_TIMEOUT;
4638 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4640 struct io_kiocb *linked_timeout;
4641 struct io_kiocb *nxt = NULL;
4645 linked_timeout = io_prep_linked_timeout(req);
4647 ret = io_issue_sqe(req, sqe, &nxt, true);
4650 * We async punt it if the file wasn't marked NOWAIT, or if the file
4651 * doesn't support non-blocking read/write attempts
4653 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4654 (req->flags & REQ_F_MUST_PUNT))) {
4656 if (io_op_defs[req->opcode].file_table) {
4657 ret = io_grab_files(req);
4663 * Queued up for async execution, worker will release
4664 * submit reference when the iocb is actually submitted.
4666 io_queue_async_work(req);
4671 /* drop submission reference */
4674 if (linked_timeout) {
4676 io_queue_linked_timeout(linked_timeout);
4678 io_put_req(linked_timeout);
4681 /* and drop final reference, if we failed */
4683 io_cqring_add_event(req, ret);
4684 req_set_fail_links(req);
4692 if (req->flags & REQ_F_FORCE_ASYNC)
4698 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4702 ret = io_req_defer(req, sqe);
4704 if (ret != -EIOCBQUEUED) {
4706 io_cqring_add_event(req, ret);
4707 req_set_fail_links(req);
4708 io_double_put_req(req);
4710 } else if (req->flags & REQ_F_FORCE_ASYNC) {
4711 ret = io_req_defer_prep(req, sqe);
4712 if (unlikely(ret < 0))
4715 * Never try inline submit of IOSQE_ASYNC is set, go straight
4716 * to async execution.
4718 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4719 io_queue_async_work(req);
4721 __io_queue_sqe(req, sqe);
4725 static inline void io_queue_link_head(struct io_kiocb *req)
4727 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
4728 io_cqring_add_event(req, -ECANCELED);
4729 io_double_put_req(req);
4731 io_queue_sqe(req, NULL);
4734 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
4735 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
4737 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4738 struct io_submit_state *state, struct io_kiocb **link)
4740 const struct cred *old_creds = NULL;
4741 struct io_ring_ctx *ctx = req->ctx;
4742 unsigned int sqe_flags;
4745 sqe_flags = READ_ONCE(sqe->flags);
4747 /* enforce forwards compatibility on users */
4748 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
4753 id = READ_ONCE(sqe->personality);
4755 const struct cred *personality_creds;
4757 personality_creds = idr_find(&ctx->personality_idr, id);
4758 if (unlikely(!personality_creds)) {
4762 old_creds = override_creds(personality_creds);
4765 /* same numerical values with corresponding REQ_F_*, safe to copy */
4766 req->flags |= sqe_flags & (IOSQE_IO_DRAIN|IOSQE_IO_HARDLINK|
4769 ret = io_req_set_file(state, req, sqe);
4770 if (unlikely(ret)) {
4772 io_cqring_add_event(req, ret);
4773 io_double_put_req(req);
4775 revert_creds(old_creds);
4780 * If we already have a head request, queue this one for async
4781 * submittal once the head completes. If we don't have a head but
4782 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4783 * submitted sync once the chain is complete. If none of those
4784 * conditions are true (normal request), then just queue it.
4787 struct io_kiocb *head = *link;
4790 * Taking sequential execution of a link, draining both sides
4791 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
4792 * requests in the link. So, it drains the head and the
4793 * next after the link request. The last one is done via
4794 * drain_next flag to persist the effect across calls.
4796 if (sqe_flags & IOSQE_IO_DRAIN) {
4797 head->flags |= REQ_F_IO_DRAIN;
4798 ctx->drain_next = 1;
4800 if (io_alloc_async_ctx(req)) {
4805 ret = io_req_defer_prep(req, sqe);
4807 /* fail even hard links since we don't submit */
4808 head->flags |= REQ_F_FAIL_LINK;
4811 trace_io_uring_link(ctx, req, head);
4812 list_add_tail(&req->link_list, &head->link_list);
4814 /* last request of a link, enqueue the link */
4815 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4816 io_queue_link_head(head);
4820 if (unlikely(ctx->drain_next)) {
4821 req->flags |= REQ_F_IO_DRAIN;
4822 req->ctx->drain_next = 0;
4824 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4825 req->flags |= REQ_F_LINK;
4826 INIT_LIST_HEAD(&req->link_list);
4827 ret = io_req_defer_prep(req, sqe);
4829 req->flags |= REQ_F_FAIL_LINK;
4832 io_queue_sqe(req, sqe);
4837 revert_creds(old_creds);
4842 * Batched submission is done, ensure local IO is flushed out.
4844 static void io_submit_state_end(struct io_submit_state *state)
4846 blk_finish_plug(&state->plug);
4848 if (state->free_reqs)
4849 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
4853 * Start submission side cache.
4855 static void io_submit_state_start(struct io_submit_state *state,
4856 unsigned int max_ios)
4858 blk_start_plug(&state->plug);
4859 state->free_reqs = 0;
4861 state->ios_left = max_ios;
4864 static void io_commit_sqring(struct io_ring_ctx *ctx)
4866 struct io_rings *rings = ctx->rings;
4869 * Ensure any loads from the SQEs are done at this point,
4870 * since once we write the new head, the application could
4871 * write new data to them.
4873 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4877 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
4878 * that is mapped by userspace. This means that care needs to be taken to
4879 * ensure that reads are stable, as we cannot rely on userspace always
4880 * being a good citizen. If members of the sqe are validated and then later
4881 * used, it's important that those reads are done through READ_ONCE() to
4882 * prevent a re-load down the line.
4884 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4885 const struct io_uring_sqe **sqe_ptr)
4887 u32 *sq_array = ctx->sq_array;
4891 * The cached sq head (or cq tail) serves two purposes:
4893 * 1) allows us to batch the cost of updating the user visible
4895 * 2) allows the kernel side to track the head on its own, even
4896 * though the application is the one updating it.
4898 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
4899 if (likely(head < ctx->sq_entries)) {
4901 * All io need record the previous position, if LINK vs DARIN,
4902 * it can be used to mark the position of the first IO in the
4905 req->sequence = ctx->cached_sq_head;
4906 *sqe_ptr = &ctx->sq_sqes[head];
4907 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4908 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4909 ctx->cached_sq_head++;
4913 /* drop invalid entries */
4914 ctx->cached_sq_head++;
4915 ctx->cached_sq_dropped++;
4916 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
4920 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4921 struct file *ring_file, int ring_fd,
4922 struct mm_struct **mm, bool async)
4924 struct io_submit_state state, *statep = NULL;
4925 struct io_kiocb *link = NULL;
4926 int i, submitted = 0;
4927 bool mm_fault = false;
4929 /* if we have a backlog and couldn't flush it all, return BUSY */
4930 if (test_bit(0, &ctx->sq_check_overflow)) {
4931 if (!list_empty(&ctx->cq_overflow_list) &&
4932 !io_cqring_overflow_flush(ctx, false))
4936 /* make sure SQ entry isn't read before tail */
4937 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
4939 if (!percpu_ref_tryget_many(&ctx->refs, nr))
4942 if (nr > IO_PLUG_THRESHOLD) {
4943 io_submit_state_start(&state, nr);
4947 ctx->ring_fd = ring_fd;
4948 ctx->ring_file = ring_file;
4950 for (i = 0; i < nr; i++) {
4951 const struct io_uring_sqe *sqe;
4952 struct io_kiocb *req;
4954 req = io_get_req(ctx, statep);
4955 if (unlikely(!req)) {
4957 submitted = -EAGAIN;
4960 if (!io_get_sqring(ctx, req, &sqe)) {
4961 __io_req_do_free(req);
4965 /* will complete beyond this point, count as submitted */
4968 if (unlikely(req->opcode >= IORING_OP_LAST)) {
4969 io_cqring_add_event(req, -EINVAL);
4970 io_double_put_req(req);
4974 if (io_op_defs[req->opcode].needs_mm && !*mm) {
4975 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
4977 use_mm(ctx->sqo_mm);
4982 req->has_user = *mm != NULL;
4983 req->in_async = async;
4984 req->needs_fixed_file = async;
4985 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
4987 if (!io_submit_sqe(req, sqe, statep, &link))
4991 if (unlikely(submitted != nr)) {
4992 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
4994 percpu_ref_put_many(&ctx->refs, nr - ref_used);
4997 io_queue_link_head(link);
4999 io_submit_state_end(&state);
5001 /* Commit SQ ring head once we've consumed and submitted all SQEs */
5002 io_commit_sqring(ctx);
5007 static int io_sq_thread(void *data)
5009 struct io_ring_ctx *ctx = data;
5010 struct mm_struct *cur_mm = NULL;
5011 const struct cred *old_cred;
5012 mm_segment_t old_fs;
5015 unsigned long timeout;
5018 complete(&ctx->completions[1]);
5022 old_cred = override_creds(ctx->creds);
5024 ret = timeout = inflight = 0;
5025 while (!kthread_should_park()) {
5026 unsigned int to_submit;
5029 unsigned nr_events = 0;
5031 if (ctx->flags & IORING_SETUP_IOPOLL) {
5033 * inflight is the count of the maximum possible
5034 * entries we submitted, but it can be smaller
5035 * if we dropped some of them. If we don't have
5036 * poll entries available, then we know that we
5037 * have nothing left to poll for. Reset the
5038 * inflight count to zero in that case.
5040 mutex_lock(&ctx->uring_lock);
5041 if (!list_empty(&ctx->poll_list))
5042 __io_iopoll_check(ctx, &nr_events, 0);
5045 mutex_unlock(&ctx->uring_lock);
5048 * Normal IO, just pretend everything completed.
5049 * We don't have to poll completions for that.
5051 nr_events = inflight;
5054 inflight -= nr_events;
5056 timeout = jiffies + ctx->sq_thread_idle;
5059 to_submit = io_sqring_entries(ctx);
5062 * If submit got -EBUSY, flag us as needing the application
5063 * to enter the kernel to reap and flush events.
5065 if (!to_submit || ret == -EBUSY) {
5067 * We're polling. If we're within the defined idle
5068 * period, then let us spin without work before going
5069 * to sleep. The exception is if we got EBUSY doing
5070 * more IO, we should wait for the application to
5071 * reap events and wake us up.
5074 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5075 !percpu_ref_is_dying(&ctx->refs))) {
5081 * Drop cur_mm before scheduling, we can't hold it for
5082 * long periods (or over schedule()). Do this before
5083 * adding ourselves to the waitqueue, as the unuse/drop
5092 prepare_to_wait(&ctx->sqo_wait, &wait,
5093 TASK_INTERRUPTIBLE);
5095 /* Tell userspace we may need a wakeup call */
5096 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
5097 /* make sure to read SQ tail after writing flags */
5100 to_submit = io_sqring_entries(ctx);
5101 if (!to_submit || ret == -EBUSY) {
5102 if (kthread_should_park()) {
5103 finish_wait(&ctx->sqo_wait, &wait);
5106 if (signal_pending(current))
5107 flush_signals(current);
5109 finish_wait(&ctx->sqo_wait, &wait);
5111 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5114 finish_wait(&ctx->sqo_wait, &wait);
5116 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5119 mutex_lock(&ctx->uring_lock);
5120 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
5121 mutex_unlock(&ctx->uring_lock);
5131 revert_creds(old_cred);
5138 struct io_wait_queue {
5139 struct wait_queue_entry wq;
5140 struct io_ring_ctx *ctx;
5142 unsigned nr_timeouts;
5145 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
5147 struct io_ring_ctx *ctx = iowq->ctx;
5150 * Wake up if we have enough events, or if a timeout occurred since we
5151 * started waiting. For timeouts, we always want to return to userspace,
5152 * regardless of event count.
5154 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
5155 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5158 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5159 int wake_flags, void *key)
5161 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5164 /* use noflush == true, as we can't safely rely on locking context */
5165 if (!io_should_wake(iowq, true))
5168 return autoremove_wake_function(curr, mode, wake_flags, key);
5172 * Wait until events become available, if we don't already have some. The
5173 * application must reap them itself, as they reside on the shared cq ring.
5175 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5176 const sigset_t __user *sig, size_t sigsz)
5178 struct io_wait_queue iowq = {
5181 .func = io_wake_function,
5182 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5185 .to_wait = min_events,
5187 struct io_rings *rings = ctx->rings;
5190 if (io_cqring_events(ctx, false) >= min_events)
5194 #ifdef CONFIG_COMPAT
5195 if (in_compat_syscall())
5196 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
5200 ret = set_user_sigmask(sig, sigsz);
5206 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5207 trace_io_uring_cqring_wait(ctx, min_events);
5209 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5210 TASK_INTERRUPTIBLE);
5211 if (io_should_wake(&iowq, false))
5214 if (signal_pending(current)) {
5219 finish_wait(&ctx->wait, &iowq.wq);
5221 restore_saved_sigmask_unless(ret == -EINTR);
5223 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
5226 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5228 #if defined(CONFIG_UNIX)
5229 if (ctx->ring_sock) {
5230 struct sock *sock = ctx->ring_sock->sk;
5231 struct sk_buff *skb;
5233 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5239 for (i = 0; i < ctx->nr_user_files; i++) {
5242 file = io_file_from_index(ctx, i);
5249 static void io_file_ref_kill(struct percpu_ref *ref)
5251 struct fixed_file_data *data;
5253 data = container_of(ref, struct fixed_file_data, refs);
5254 complete(&data->done);
5257 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5259 struct fixed_file_data *data = ctx->file_data;
5260 unsigned nr_tables, i;
5265 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
5266 flush_work(&data->ref_work);
5267 wait_for_completion(&data->done);
5268 io_ring_file_ref_flush(data);
5269 percpu_ref_exit(&data->refs);
5271 __io_sqe_files_unregister(ctx);
5272 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5273 for (i = 0; i < nr_tables; i++)
5274 kfree(data->table[i].files);
5277 ctx->file_data = NULL;
5278 ctx->nr_user_files = 0;
5282 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5284 if (ctx->sqo_thread) {
5285 wait_for_completion(&ctx->completions[1]);
5287 * The park is a bit of a work-around, without it we get
5288 * warning spews on shutdown with SQPOLL set and affinity
5289 * set to a single CPU.
5291 kthread_park(ctx->sqo_thread);
5292 kthread_stop(ctx->sqo_thread);
5293 ctx->sqo_thread = NULL;
5297 static void io_finish_async(struct io_ring_ctx *ctx)
5299 io_sq_thread_stop(ctx);
5302 io_wq_destroy(ctx->io_wq);
5307 #if defined(CONFIG_UNIX)
5309 * Ensure the UNIX gc is aware of our file set, so we are certain that
5310 * the io_uring can be safely unregistered on process exit, even if we have
5311 * loops in the file referencing.
5313 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5315 struct sock *sk = ctx->ring_sock->sk;
5316 struct scm_fp_list *fpl;
5317 struct sk_buff *skb;
5320 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5321 unsigned long inflight = ctx->user->unix_inflight + nr;
5323 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5327 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5331 skb = alloc_skb(0, GFP_KERNEL);
5340 fpl->user = get_uid(ctx->user);
5341 for (i = 0; i < nr; i++) {
5342 struct file *file = io_file_from_index(ctx, i + offset);
5346 fpl->fp[nr_files] = get_file(file);
5347 unix_inflight(fpl->user, fpl->fp[nr_files]);
5352 fpl->max = SCM_MAX_FD;
5353 fpl->count = nr_files;
5354 UNIXCB(skb).fp = fpl;
5355 skb->destructor = unix_destruct_scm;
5356 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5357 skb_queue_head(&sk->sk_receive_queue, skb);
5359 for (i = 0; i < nr_files; i++)
5370 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5371 * causes regular reference counting to break down. We rely on the UNIX
5372 * garbage collection to take care of this problem for us.
5374 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5376 unsigned left, total;
5380 left = ctx->nr_user_files;
5382 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
5384 ret = __io_sqe_files_scm(ctx, this_files, total);
5388 total += this_files;
5394 while (total < ctx->nr_user_files) {
5395 struct file *file = io_file_from_index(ctx, total);
5405 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5411 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5416 for (i = 0; i < nr_tables; i++) {
5417 struct fixed_file_table *table = &ctx->file_data->table[i];
5418 unsigned this_files;
5420 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5421 table->files = kcalloc(this_files, sizeof(struct file *),
5425 nr_files -= this_files;
5431 for (i = 0; i < nr_tables; i++) {
5432 struct fixed_file_table *table = &ctx->file_data->table[i];
5433 kfree(table->files);
5438 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5440 #if defined(CONFIG_UNIX)
5441 struct sock *sock = ctx->ring_sock->sk;
5442 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5443 struct sk_buff *skb;
5446 __skb_queue_head_init(&list);
5449 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5450 * remove this entry and rearrange the file array.
5452 skb = skb_dequeue(head);
5454 struct scm_fp_list *fp;
5456 fp = UNIXCB(skb).fp;
5457 for (i = 0; i < fp->count; i++) {
5460 if (fp->fp[i] != file)
5463 unix_notinflight(fp->user, fp->fp[i]);
5464 left = fp->count - 1 - i;
5466 memmove(&fp->fp[i], &fp->fp[i + 1],
5467 left * sizeof(struct file *));
5474 __skb_queue_tail(&list, skb);
5484 __skb_queue_tail(&list, skb);
5486 skb = skb_dequeue(head);
5489 if (skb_peek(&list)) {
5490 spin_lock_irq(&head->lock);
5491 while ((skb = __skb_dequeue(&list)) != NULL)
5492 __skb_queue_tail(head, skb);
5493 spin_unlock_irq(&head->lock);
5500 struct io_file_put {
5501 struct llist_node llist;
5503 struct completion *done;
5506 static void io_ring_file_ref_flush(struct fixed_file_data *data)
5508 struct io_file_put *pfile, *tmp;
5509 struct llist_node *node;
5511 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5512 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5513 io_ring_file_put(data->ctx, pfile->file);
5515 complete(pfile->done);
5522 static void io_ring_file_ref_switch(struct work_struct *work)
5524 struct fixed_file_data *data;
5526 data = container_of(work, struct fixed_file_data, ref_work);
5527 io_ring_file_ref_flush(data);
5528 percpu_ref_get(&data->refs);
5529 percpu_ref_switch_to_percpu(&data->refs);
5532 static void io_file_data_ref_zero(struct percpu_ref *ref)
5534 struct fixed_file_data *data;
5536 data = container_of(ref, struct fixed_file_data, refs);
5539 * We can't safely switch from inside this context, punt to wq. If
5540 * the table ref is going away, the table is being unregistered.
5541 * Don't queue up the async work for that case, the caller will
5544 if (!percpu_ref_is_dying(&data->refs))
5545 queue_work(system_wq, &data->ref_work);
5548 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5551 __s32 __user *fds = (__s32 __user *) arg;
5561 if (nr_args > IORING_MAX_FIXED_FILES)
5564 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5565 if (!ctx->file_data)
5567 ctx->file_data->ctx = ctx;
5568 init_completion(&ctx->file_data->done);
5570 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
5571 ctx->file_data->table = kcalloc(nr_tables,
5572 sizeof(struct fixed_file_table),
5574 if (!ctx->file_data->table) {
5575 kfree(ctx->file_data);
5576 ctx->file_data = NULL;
5580 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5581 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5582 kfree(ctx->file_data->table);
5583 kfree(ctx->file_data);
5584 ctx->file_data = NULL;
5587 ctx->file_data->put_llist.first = NULL;
5588 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
5590 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
5591 percpu_ref_exit(&ctx->file_data->refs);
5592 kfree(ctx->file_data->table);
5593 kfree(ctx->file_data);
5594 ctx->file_data = NULL;
5598 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
5599 struct fixed_file_table *table;
5603 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5605 /* allow sparse sets */
5611 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5612 index = i & IORING_FILE_TABLE_MASK;
5620 * Don't allow io_uring instances to be registered. If UNIX
5621 * isn't enabled, then this causes a reference cycle and this
5622 * instance can never get freed. If UNIX is enabled we'll
5623 * handle it just fine, but there's still no point in allowing
5624 * a ring fd as it doesn't support regular read/write anyway.
5626 if (file->f_op == &io_uring_fops) {
5631 table->files[index] = file;
5635 for (i = 0; i < ctx->nr_user_files; i++) {
5636 file = io_file_from_index(ctx, i);
5640 for (i = 0; i < nr_tables; i++)
5641 kfree(ctx->file_data->table[i].files);
5643 kfree(ctx->file_data->table);
5644 kfree(ctx->file_data);
5645 ctx->file_data = NULL;
5646 ctx->nr_user_files = 0;
5650 ret = io_sqe_files_scm(ctx);
5652 io_sqe_files_unregister(ctx);
5657 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5660 #if defined(CONFIG_UNIX)
5661 struct sock *sock = ctx->ring_sock->sk;
5662 struct sk_buff_head *head = &sock->sk_receive_queue;
5663 struct sk_buff *skb;
5666 * See if we can merge this file into an existing skb SCM_RIGHTS
5667 * file set. If there's no room, fall back to allocating a new skb
5668 * and filling it in.
5670 spin_lock_irq(&head->lock);
5671 skb = skb_peek(head);
5673 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5675 if (fpl->count < SCM_MAX_FD) {
5676 __skb_unlink(skb, head);
5677 spin_unlock_irq(&head->lock);
5678 fpl->fp[fpl->count] = get_file(file);
5679 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5681 spin_lock_irq(&head->lock);
5682 __skb_queue_head(head, skb);
5687 spin_unlock_irq(&head->lock);
5694 return __io_sqe_files_scm(ctx, 1, index);
5700 static void io_atomic_switch(struct percpu_ref *ref)
5702 struct fixed_file_data *data;
5704 data = container_of(ref, struct fixed_file_data, refs);
5705 clear_bit(FFD_F_ATOMIC, &data->state);
5708 static bool io_queue_file_removal(struct fixed_file_data *data,
5711 struct io_file_put *pfile, pfile_stack;
5712 DECLARE_COMPLETION_ONSTACK(done);
5715 * If we fail allocating the struct we need for doing async reomval
5716 * of this file, just punt to sync and wait for it.
5718 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5720 pfile = &pfile_stack;
5721 pfile->done = &done;
5725 llist_add(&pfile->llist, &data->put_llist);
5727 if (pfile == &pfile_stack) {
5728 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5729 percpu_ref_put(&data->refs);
5730 percpu_ref_switch_to_atomic(&data->refs,
5733 wait_for_completion(&done);
5734 flush_work(&data->ref_work);
5741 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5742 struct io_uring_files_update *up,
5745 struct fixed_file_data *data = ctx->file_data;
5746 bool ref_switch = false;
5752 if (check_add_overflow(up->offset, nr_args, &done))
5754 if (done > ctx->nr_user_files)
5758 fds = u64_to_user_ptr(up->fds);
5760 struct fixed_file_table *table;
5764 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5768 i = array_index_nospec(up->offset, ctx->nr_user_files);
5769 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
5770 index = i & IORING_FILE_TABLE_MASK;
5771 if (table->files[index]) {
5772 file = io_file_from_index(ctx, index);
5773 table->files[index] = NULL;
5774 if (io_queue_file_removal(data, file))
5784 * Don't allow io_uring instances to be registered. If
5785 * UNIX isn't enabled, then this causes a reference
5786 * cycle and this instance can never get freed. If UNIX
5787 * is enabled we'll handle it just fine, but there's
5788 * still no point in allowing a ring fd as it doesn't
5789 * support regular read/write anyway.
5791 if (file->f_op == &io_uring_fops) {
5796 table->files[index] = file;
5797 err = io_sqe_file_register(ctx, file, i);
5806 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5807 percpu_ref_put(&data->refs);
5808 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
5811 return done ? done : err;
5813 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5816 struct io_uring_files_update up;
5818 if (!ctx->file_data)
5822 if (copy_from_user(&up, arg, sizeof(up)))
5827 return __io_sqe_files_update(ctx, &up, nr_args);
5830 static void io_put_work(struct io_wq_work *work)
5832 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5837 static void io_get_work(struct io_wq_work *work)
5839 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5841 refcount_inc(&req->refs);
5844 static int io_init_wq_offload(struct io_ring_ctx *ctx,
5845 struct io_uring_params *p)
5847 struct io_wq_data data;
5849 struct io_ring_ctx *ctx_attach;
5850 unsigned int concurrency;
5853 data.user = ctx->user;
5854 data.get_work = io_get_work;
5855 data.put_work = io_put_work;
5857 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
5858 /* Do QD, or 4 * CPUS, whatever is smallest */
5859 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5861 ctx->io_wq = io_wq_create(concurrency, &data);
5862 if (IS_ERR(ctx->io_wq)) {
5863 ret = PTR_ERR(ctx->io_wq);
5869 f = fdget(p->wq_fd);
5873 if (f.file->f_op != &io_uring_fops) {
5878 ctx_attach = f.file->private_data;
5879 /* @io_wq is protected by holding the fd */
5880 if (!io_wq_get(ctx_attach->io_wq, &data)) {
5885 ctx->io_wq = ctx_attach->io_wq;
5891 static int io_sq_offload_start(struct io_ring_ctx *ctx,
5892 struct io_uring_params *p)
5896 init_waitqueue_head(&ctx->sqo_wait);
5897 mmgrab(current->mm);
5898 ctx->sqo_mm = current->mm;
5900 if (ctx->flags & IORING_SETUP_SQPOLL) {
5902 if (!capable(CAP_SYS_ADMIN))
5905 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5906 if (!ctx->sq_thread_idle)
5907 ctx->sq_thread_idle = HZ;
5909 if (p->flags & IORING_SETUP_SQ_AFF) {
5910 int cpu = p->sq_thread_cpu;
5913 if (cpu >= nr_cpu_ids)
5915 if (!cpu_online(cpu))
5918 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5922 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5925 if (IS_ERR(ctx->sqo_thread)) {
5926 ret = PTR_ERR(ctx->sqo_thread);
5927 ctx->sqo_thread = NULL;
5930 wake_up_process(ctx->sqo_thread);
5931 } else if (p->flags & IORING_SETUP_SQ_AFF) {
5932 /* Can't have SQ_AFF without SQPOLL */
5937 ret = io_init_wq_offload(ctx, p);
5943 io_finish_async(ctx);
5944 mmdrop(ctx->sqo_mm);
5949 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
5951 atomic_long_sub(nr_pages, &user->locked_vm);
5954 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
5956 unsigned long page_limit, cur_pages, new_pages;
5958 /* Don't allow more pages than we can safely lock */
5959 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5962 cur_pages = atomic_long_read(&user->locked_vm);
5963 new_pages = cur_pages + nr_pages;
5964 if (new_pages > page_limit)
5966 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5967 new_pages) != cur_pages);
5972 static void io_mem_free(void *ptr)
5979 page = virt_to_head_page(ptr);
5980 if (put_page_testzero(page))
5981 free_compound_page(page);
5984 static void *io_mem_alloc(size_t size)
5986 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
5989 return (void *) __get_free_pages(gfp_flags, get_order(size));
5992 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
5995 struct io_rings *rings;
5996 size_t off, sq_array_size;
5998 off = struct_size(rings, cqes, cq_entries);
5999 if (off == SIZE_MAX)
6003 off = ALIGN(off, SMP_CACHE_BYTES);
6008 sq_array_size = array_size(sizeof(u32), sq_entries);
6009 if (sq_array_size == SIZE_MAX)
6012 if (check_add_overflow(off, sq_array_size, &off))
6021 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
6025 pages = (size_t)1 << get_order(
6026 rings_size(sq_entries, cq_entries, NULL));
6027 pages += (size_t)1 << get_order(
6028 array_size(sizeof(struct io_uring_sqe), sq_entries));
6033 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6037 if (!ctx->user_bufs)
6040 for (i = 0; i < ctx->nr_user_bufs; i++) {
6041 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6043 for (j = 0; j < imu->nr_bvecs; j++)
6044 unpin_user_page(imu->bvec[j].bv_page);
6046 if (ctx->account_mem)
6047 io_unaccount_mem(ctx->user, imu->nr_bvecs);
6052 kfree(ctx->user_bufs);
6053 ctx->user_bufs = NULL;
6054 ctx->nr_user_bufs = 0;
6058 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6059 void __user *arg, unsigned index)
6061 struct iovec __user *src;
6063 #ifdef CONFIG_COMPAT
6065 struct compat_iovec __user *ciovs;
6066 struct compat_iovec ciov;
6068 ciovs = (struct compat_iovec __user *) arg;
6069 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6072 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
6073 dst->iov_len = ciov.iov_len;
6077 src = (struct iovec __user *) arg;
6078 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6083 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6086 struct vm_area_struct **vmas = NULL;
6087 struct page **pages = NULL;
6088 int i, j, got_pages = 0;
6093 if (!nr_args || nr_args > UIO_MAXIOV)
6096 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6098 if (!ctx->user_bufs)
6101 for (i = 0; i < nr_args; i++) {
6102 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6103 unsigned long off, start, end, ubuf;
6108 ret = io_copy_iov(ctx, &iov, arg, i);
6113 * Don't impose further limits on the size and buffer
6114 * constraints here, we'll -EINVAL later when IO is
6115 * submitted if they are wrong.
6118 if (!iov.iov_base || !iov.iov_len)
6121 /* arbitrary limit, but we need something */
6122 if (iov.iov_len > SZ_1G)
6125 ubuf = (unsigned long) iov.iov_base;
6126 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6127 start = ubuf >> PAGE_SHIFT;
6128 nr_pages = end - start;
6130 if (ctx->account_mem) {
6131 ret = io_account_mem(ctx->user, nr_pages);
6137 if (!pages || nr_pages > got_pages) {
6140 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
6142 vmas = kvmalloc_array(nr_pages,
6143 sizeof(struct vm_area_struct *),
6145 if (!pages || !vmas) {
6147 if (ctx->account_mem)
6148 io_unaccount_mem(ctx->user, nr_pages);
6151 got_pages = nr_pages;
6154 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
6158 if (ctx->account_mem)
6159 io_unaccount_mem(ctx->user, nr_pages);
6164 down_read(¤t->mm->mmap_sem);
6165 pret = pin_user_pages(ubuf, nr_pages,
6166 FOLL_WRITE | FOLL_LONGTERM,
6168 if (pret == nr_pages) {
6169 /* don't support file backed memory */
6170 for (j = 0; j < nr_pages; j++) {
6171 struct vm_area_struct *vma = vmas[j];
6174 !is_file_hugepages(vma->vm_file)) {
6180 ret = pret < 0 ? pret : -EFAULT;
6182 up_read(¤t->mm->mmap_sem);
6185 * if we did partial map, or found file backed vmas,
6186 * release any pages we did get
6189 unpin_user_pages(pages, pret);
6190 if (ctx->account_mem)
6191 io_unaccount_mem(ctx->user, nr_pages);
6196 off = ubuf & ~PAGE_MASK;
6198 for (j = 0; j < nr_pages; j++) {
6201 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6202 imu->bvec[j].bv_page = pages[j];
6203 imu->bvec[j].bv_len = vec_len;
6204 imu->bvec[j].bv_offset = off;
6208 /* store original address for later verification */
6210 imu->len = iov.iov_len;
6211 imu->nr_bvecs = nr_pages;
6213 ctx->nr_user_bufs++;
6221 io_sqe_buffer_unregister(ctx);
6225 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6227 __s32 __user *fds = arg;
6233 if (copy_from_user(&fd, fds, sizeof(*fds)))
6236 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6237 if (IS_ERR(ctx->cq_ev_fd)) {
6238 int ret = PTR_ERR(ctx->cq_ev_fd);
6239 ctx->cq_ev_fd = NULL;
6246 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6248 if (ctx->cq_ev_fd) {
6249 eventfd_ctx_put(ctx->cq_ev_fd);
6250 ctx->cq_ev_fd = NULL;
6257 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6259 io_finish_async(ctx);
6261 mmdrop(ctx->sqo_mm);
6263 io_iopoll_reap_events(ctx);
6264 io_sqe_buffer_unregister(ctx);
6265 io_sqe_files_unregister(ctx);
6266 io_eventfd_unregister(ctx);
6268 #if defined(CONFIG_UNIX)
6269 if (ctx->ring_sock) {
6270 ctx->ring_sock->file = NULL; /* so that iput() is called */
6271 sock_release(ctx->ring_sock);
6275 io_mem_free(ctx->rings);
6276 io_mem_free(ctx->sq_sqes);
6278 percpu_ref_exit(&ctx->refs);
6279 if (ctx->account_mem)
6280 io_unaccount_mem(ctx->user,
6281 ring_pages(ctx->sq_entries, ctx->cq_entries));
6282 free_uid(ctx->user);
6283 put_cred(ctx->creds);
6284 kfree(ctx->completions);
6285 kfree(ctx->cancel_hash);
6286 kmem_cache_free(req_cachep, ctx->fallback_req);
6290 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6292 struct io_ring_ctx *ctx = file->private_data;
6295 poll_wait(file, &ctx->cq_wait, wait);
6297 * synchronizes with barrier from wq_has_sleeper call in
6301 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6302 ctx->rings->sq_ring_entries)
6303 mask |= EPOLLOUT | EPOLLWRNORM;
6304 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
6305 mask |= EPOLLIN | EPOLLRDNORM;
6310 static int io_uring_fasync(int fd, struct file *file, int on)
6312 struct io_ring_ctx *ctx = file->private_data;
6314 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6317 static int io_remove_personalities(int id, void *p, void *data)
6319 struct io_ring_ctx *ctx = data;
6320 const struct cred *cred;
6322 cred = idr_remove(&ctx->personality_idr, id);
6328 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6330 mutex_lock(&ctx->uring_lock);
6331 percpu_ref_kill(&ctx->refs);
6332 mutex_unlock(&ctx->uring_lock);
6335 * Wait for sq thread to idle, if we have one. It won't spin on new
6336 * work after we've killed the ctx ref above. This is important to do
6337 * before we cancel existing commands, as the thread could otherwise
6338 * be queueing new work post that. If that's work we need to cancel,
6339 * it could cause shutdown to hang.
6341 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
6344 io_kill_timeouts(ctx);
6345 io_poll_remove_all(ctx);
6348 io_wq_cancel_all(ctx->io_wq);
6350 io_iopoll_reap_events(ctx);
6351 /* if we failed setting up the ctx, we might not have any rings */
6353 io_cqring_overflow_flush(ctx, true);
6354 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
6355 wait_for_completion(&ctx->completions[0]);
6356 io_ring_ctx_free(ctx);
6359 static int io_uring_release(struct inode *inode, struct file *file)
6361 struct io_ring_ctx *ctx = file->private_data;
6363 file->private_data = NULL;
6364 io_ring_ctx_wait_and_kill(ctx);
6368 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6369 struct files_struct *files)
6371 struct io_kiocb *req;
6374 while (!list_empty_careful(&ctx->inflight_list)) {
6375 struct io_kiocb *cancel_req = NULL;
6377 spin_lock_irq(&ctx->inflight_lock);
6378 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
6379 if (req->work.files != files)
6381 /* req is being completed, ignore */
6382 if (!refcount_inc_not_zero(&req->refs))
6388 prepare_to_wait(&ctx->inflight_wait, &wait,
6389 TASK_UNINTERRUPTIBLE);
6390 spin_unlock_irq(&ctx->inflight_lock);
6392 /* We need to keep going until we don't find a matching req */
6396 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6397 io_put_req(cancel_req);
6400 finish_wait(&ctx->inflight_wait, &wait);
6403 static int io_uring_flush(struct file *file, void *data)
6405 struct io_ring_ctx *ctx = file->private_data;
6407 io_uring_cancel_files(ctx, data);
6411 static void *io_uring_validate_mmap_request(struct file *file,
6412 loff_t pgoff, size_t sz)
6414 struct io_ring_ctx *ctx = file->private_data;
6415 loff_t offset = pgoff << PAGE_SHIFT;
6420 case IORING_OFF_SQ_RING:
6421 case IORING_OFF_CQ_RING:
6424 case IORING_OFF_SQES:
6428 return ERR_PTR(-EINVAL);
6431 page = virt_to_head_page(ptr);
6432 if (sz > page_size(page))
6433 return ERR_PTR(-EINVAL);
6440 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6442 size_t sz = vma->vm_end - vma->vm_start;
6446 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6448 return PTR_ERR(ptr);
6450 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6451 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6454 #else /* !CONFIG_MMU */
6456 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6458 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6461 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6463 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6466 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6467 unsigned long addr, unsigned long len,
6468 unsigned long pgoff, unsigned long flags)
6472 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6474 return PTR_ERR(ptr);
6476 return (unsigned long) ptr;
6479 #endif /* !CONFIG_MMU */
6481 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6482 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6485 struct io_ring_ctx *ctx;
6490 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
6498 if (f.file->f_op != &io_uring_fops)
6502 ctx = f.file->private_data;
6503 if (!percpu_ref_tryget(&ctx->refs))
6507 * For SQ polling, the thread will do all submissions and completions.
6508 * Just return the requested submit count, and wake the thread if
6512 if (ctx->flags & IORING_SETUP_SQPOLL) {
6513 if (!list_empty_careful(&ctx->cq_overflow_list))
6514 io_cqring_overflow_flush(ctx, false);
6515 if (flags & IORING_ENTER_SQ_WAKEUP)
6516 wake_up(&ctx->sqo_wait);
6517 submitted = to_submit;
6518 } else if (to_submit) {
6519 struct mm_struct *cur_mm;
6521 mutex_lock(&ctx->uring_lock);
6522 /* already have mm, so io_submit_sqes() won't try to grab it */
6523 cur_mm = ctx->sqo_mm;
6524 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6526 mutex_unlock(&ctx->uring_lock);
6528 if (submitted != to_submit)
6531 if (flags & IORING_ENTER_GETEVENTS) {
6532 unsigned nr_events = 0;
6534 min_complete = min(min_complete, ctx->cq_entries);
6536 if (ctx->flags & IORING_SETUP_IOPOLL) {
6537 ret = io_iopoll_check(ctx, &nr_events, min_complete);
6539 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6544 percpu_ref_put(&ctx->refs);
6547 return submitted ? submitted : ret;
6550 static int io_uring_show_cred(int id, void *p, void *data)
6552 const struct cred *cred = p;
6553 struct seq_file *m = data;
6554 struct user_namespace *uns = seq_user_ns(m);
6555 struct group_info *gi;
6560 seq_printf(m, "%5d\n", id);
6561 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
6562 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
6563 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
6564 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
6565 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
6566 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
6567 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
6568 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
6569 seq_puts(m, "\n\tGroups:\t");
6570 gi = cred->group_info;
6571 for (g = 0; g < gi->ngroups; g++) {
6572 seq_put_decimal_ull(m, g ? " " : "",
6573 from_kgid_munged(uns, gi->gid[g]));
6575 seq_puts(m, "\n\tCapEff:\t");
6576 cap = cred->cap_effective;
6577 CAP_FOR_EACH_U32(__capi)
6578 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
6583 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
6587 mutex_lock(&ctx->uring_lock);
6588 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
6589 for (i = 0; i < ctx->nr_user_files; i++) {
6590 struct fixed_file_table *table;
6593 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6594 f = table->files[i & IORING_FILE_TABLE_MASK];
6596 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
6598 seq_printf(m, "%5u: <none>\n", i);
6600 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
6601 for (i = 0; i < ctx->nr_user_bufs; i++) {
6602 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
6604 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
6605 (unsigned int) buf->len);
6607 if (!idr_is_empty(&ctx->personality_idr)) {
6608 seq_printf(m, "Personalities:\n");
6609 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
6611 mutex_unlock(&ctx->uring_lock);
6614 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
6616 struct io_ring_ctx *ctx = f->private_data;
6618 if (percpu_ref_tryget(&ctx->refs)) {
6619 __io_uring_show_fdinfo(ctx, m);
6620 percpu_ref_put(&ctx->refs);
6624 static const struct file_operations io_uring_fops = {
6625 .release = io_uring_release,
6626 .flush = io_uring_flush,
6627 .mmap = io_uring_mmap,
6629 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6630 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6632 .poll = io_uring_poll,
6633 .fasync = io_uring_fasync,
6634 .show_fdinfo = io_uring_show_fdinfo,
6637 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6638 struct io_uring_params *p)
6640 struct io_rings *rings;
6641 size_t size, sq_array_offset;
6643 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6644 if (size == SIZE_MAX)
6647 rings = io_mem_alloc(size);
6652 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6653 rings->sq_ring_mask = p->sq_entries - 1;
6654 rings->cq_ring_mask = p->cq_entries - 1;
6655 rings->sq_ring_entries = p->sq_entries;
6656 rings->cq_ring_entries = p->cq_entries;
6657 ctx->sq_mask = rings->sq_ring_mask;
6658 ctx->cq_mask = rings->cq_ring_mask;
6659 ctx->sq_entries = rings->sq_ring_entries;
6660 ctx->cq_entries = rings->cq_ring_entries;
6662 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6663 if (size == SIZE_MAX) {
6664 io_mem_free(ctx->rings);
6669 ctx->sq_sqes = io_mem_alloc(size);
6670 if (!ctx->sq_sqes) {
6671 io_mem_free(ctx->rings);
6680 * Allocate an anonymous fd, this is what constitutes the application
6681 * visible backing of an io_uring instance. The application mmaps this
6682 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6683 * we have to tie this fd to a socket for file garbage collection purposes.
6685 static int io_uring_get_fd(struct io_ring_ctx *ctx)
6690 #if defined(CONFIG_UNIX)
6691 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6697 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6701 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6702 O_RDWR | O_CLOEXEC);
6705 ret = PTR_ERR(file);
6709 #if defined(CONFIG_UNIX)
6710 ctx->ring_sock->file = file;
6712 fd_install(ret, file);
6715 #if defined(CONFIG_UNIX)
6716 sock_release(ctx->ring_sock);
6717 ctx->ring_sock = NULL;
6722 static int io_uring_create(unsigned entries, struct io_uring_params *p)
6724 struct user_struct *user = NULL;
6725 struct io_ring_ctx *ctx;
6731 if (entries > IORING_MAX_ENTRIES) {
6732 if (!(p->flags & IORING_SETUP_CLAMP))
6734 entries = IORING_MAX_ENTRIES;
6738 * Use twice as many entries for the CQ ring. It's possible for the
6739 * application to drive a higher depth than the size of the SQ ring,
6740 * since the sqes are only used at submission time. This allows for
6741 * some flexibility in overcommitting a bit. If the application has
6742 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6743 * of CQ ring entries manually.
6745 p->sq_entries = roundup_pow_of_two(entries);
6746 if (p->flags & IORING_SETUP_CQSIZE) {
6748 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6749 * to a power-of-two, if it isn't already. We do NOT impose
6750 * any cq vs sq ring sizing.
6752 if (p->cq_entries < p->sq_entries)
6754 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6755 if (!(p->flags & IORING_SETUP_CLAMP))
6757 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6759 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6761 p->cq_entries = 2 * p->sq_entries;
6764 user = get_uid(current_user());
6765 account_mem = !capable(CAP_IPC_LOCK);
6768 ret = io_account_mem(user,
6769 ring_pages(p->sq_entries, p->cq_entries));
6776 ctx = io_ring_ctx_alloc(p);
6779 io_unaccount_mem(user, ring_pages(p->sq_entries,
6784 ctx->compat = in_compat_syscall();
6785 ctx->account_mem = account_mem;
6787 ctx->creds = get_current_cred();
6789 ret = io_allocate_scq_urings(ctx, p);
6793 ret = io_sq_offload_start(ctx, p);
6797 memset(&p->sq_off, 0, sizeof(p->sq_off));
6798 p->sq_off.head = offsetof(struct io_rings, sq.head);
6799 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6800 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6801 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6802 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6803 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6804 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6806 memset(&p->cq_off, 0, sizeof(p->cq_off));
6807 p->cq_off.head = offsetof(struct io_rings, cq.head);
6808 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6809 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6810 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6811 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6812 p->cq_off.cqes = offsetof(struct io_rings, cqes);
6815 * Install ring fd as the very last thing, so we don't risk someone
6816 * having closed it before we finish setup
6818 ret = io_uring_get_fd(ctx);
6822 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6823 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6824 IORING_FEAT_CUR_PERSONALITY;
6825 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6828 io_ring_ctx_wait_and_kill(ctx);
6833 * Sets up an aio uring context, and returns the fd. Applications asks for a
6834 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6835 * params structure passed in.
6837 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6839 struct io_uring_params p;
6843 if (copy_from_user(&p, params, sizeof(p)))
6845 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6850 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6851 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6852 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
6855 ret = io_uring_create(entries, &p);
6859 if (copy_to_user(params, &p, sizeof(p)))
6865 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6866 struct io_uring_params __user *, params)
6868 return io_uring_setup(entries, params);
6871 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6873 struct io_uring_probe *p;
6877 size = struct_size(p, ops, nr_args);
6878 if (size == SIZE_MAX)
6880 p = kzalloc(size, GFP_KERNEL);
6885 if (copy_from_user(p, arg, size))
6888 if (memchr_inv(p, 0, size))
6891 p->last_op = IORING_OP_LAST - 1;
6892 if (nr_args > IORING_OP_LAST)
6893 nr_args = IORING_OP_LAST;
6895 for (i = 0; i < nr_args; i++) {
6897 if (!io_op_defs[i].not_supported)
6898 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6903 if (copy_to_user(arg, p, size))
6910 static int io_register_personality(struct io_ring_ctx *ctx)
6912 const struct cred *creds = get_current_cred();
6915 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
6916 USHRT_MAX, GFP_KERNEL);
6922 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
6924 const struct cred *old_creds;
6926 old_creds = idr_remove(&ctx->personality_idr, id);
6928 put_cred(old_creds);
6935 static bool io_register_op_must_quiesce(int op)
6938 case IORING_UNREGISTER_FILES:
6939 case IORING_REGISTER_FILES_UPDATE:
6940 case IORING_REGISTER_PROBE:
6941 case IORING_REGISTER_PERSONALITY:
6942 case IORING_UNREGISTER_PERSONALITY:
6949 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6950 void __user *arg, unsigned nr_args)
6951 __releases(ctx->uring_lock)
6952 __acquires(ctx->uring_lock)
6957 * We're inside the ring mutex, if the ref is already dying, then
6958 * someone else killed the ctx or is already going through
6959 * io_uring_register().
6961 if (percpu_ref_is_dying(&ctx->refs))
6964 if (io_register_op_must_quiesce(opcode)) {
6965 percpu_ref_kill(&ctx->refs);
6968 * Drop uring mutex before waiting for references to exit. If
6969 * another thread is currently inside io_uring_enter() it might
6970 * need to grab the uring_lock to make progress. If we hold it
6971 * here across the drain wait, then we can deadlock. It's safe
6972 * to drop the mutex here, since no new references will come in
6973 * after we've killed the percpu ref.
6975 mutex_unlock(&ctx->uring_lock);
6976 ret = wait_for_completion_interruptible(&ctx->completions[0]);
6977 mutex_lock(&ctx->uring_lock);
6979 percpu_ref_resurrect(&ctx->refs);
6986 case IORING_REGISTER_BUFFERS:
6987 ret = io_sqe_buffer_register(ctx, arg, nr_args);
6989 case IORING_UNREGISTER_BUFFERS:
6993 ret = io_sqe_buffer_unregister(ctx);
6995 case IORING_REGISTER_FILES:
6996 ret = io_sqe_files_register(ctx, arg, nr_args);
6998 case IORING_UNREGISTER_FILES:
7002 ret = io_sqe_files_unregister(ctx);
7004 case IORING_REGISTER_FILES_UPDATE:
7005 ret = io_sqe_files_update(ctx, arg, nr_args);
7007 case IORING_REGISTER_EVENTFD:
7008 case IORING_REGISTER_EVENTFD_ASYNC:
7012 ret = io_eventfd_register(ctx, arg);
7015 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
7016 ctx->eventfd_async = 1;
7018 ctx->eventfd_async = 0;
7020 case IORING_UNREGISTER_EVENTFD:
7024 ret = io_eventfd_unregister(ctx);
7026 case IORING_REGISTER_PROBE:
7028 if (!arg || nr_args > 256)
7030 ret = io_probe(ctx, arg, nr_args);
7032 case IORING_REGISTER_PERSONALITY:
7036 ret = io_register_personality(ctx);
7038 case IORING_UNREGISTER_PERSONALITY:
7042 ret = io_unregister_personality(ctx, nr_args);
7049 if (io_register_op_must_quiesce(opcode)) {
7050 /* bring the ctx back to life */
7051 percpu_ref_reinit(&ctx->refs);
7053 reinit_completion(&ctx->completions[0]);
7058 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7059 void __user *, arg, unsigned int, nr_args)
7061 struct io_ring_ctx *ctx;
7070 if (f.file->f_op != &io_uring_fops)
7073 ctx = f.file->private_data;
7075 mutex_lock(&ctx->uring_lock);
7076 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7077 mutex_unlock(&ctx->uring_lock);
7078 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
7079 ctx->cq_ev_fd != NULL, ret);
7085 static int __init io_uring_init(void)
7087 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7088 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7089 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7092 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7093 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7094 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7095 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7096 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7097 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7098 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7099 BUILD_BUG_SQE_ELEM(8, __u64, off);
7100 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7101 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7102 BUILD_BUG_SQE_ELEM(24, __u32, len);
7103 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7104 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7105 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7106 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7107 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
7108 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7109 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7110 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7111 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7112 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7113 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7114 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7115 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7116 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7117 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7118 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7120 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7121 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
7124 __initcall(io_uring_init);