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 <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/mmu_context.h>
59 #include <linux/percpu.h>
60 #include <linux/slab.h>
61 #include <linux/kthread.h>
62 #include <linux/blkdev.h>
63 #include <linux/bvec.h>
64 #include <linux/net.h>
66 #include <net/af_unix.h>
68 #include <linux/anon_inodes.h>
69 #include <linux/sched/mm.h>
70 #include <linux/uaccess.h>
71 #include <linux/nospec.h>
72 #include <linux/sizes.h>
73 #include <linux/hugetlb.h>
74 #include <linux/highmem.h>
75 #include <linux/namei.h>
76 #include <linux/fsnotify.h>
77 #include <linux/fadvise.h>
78 #include <linux/eventpoll.h>
79 #include <linux/fs_struct.h>
80 #include <linux/splice.h>
81 #include <linux/task_work.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
97 #define IORING_FILE_TABLE_SHIFT 9
98 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
99 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
100 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
103 u32 head ____cacheline_aligned_in_smp;
104 u32 tail ____cacheline_aligned_in_smp;
108 * This data is shared with the application through the mmap at offsets
109 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
111 * The offsets to the member fields are published through struct
112 * io_sqring_offsets when calling io_uring_setup.
116 * Head and tail offsets into the ring; the offsets need to be
117 * masked to get valid indices.
119 * The kernel controls head of the sq ring and the tail of the cq ring,
120 * and the application controls tail of the sq ring and the head of the
123 struct io_uring sq, cq;
125 * Bitmasks to apply to head and tail offsets (constant, equals
128 u32 sq_ring_mask, cq_ring_mask;
129 /* Ring sizes (constant, power of 2) */
130 u32 sq_ring_entries, cq_ring_entries;
132 * Number of invalid entries dropped by the kernel due to
133 * invalid index stored in array
135 * Written by the kernel, shouldn't be modified by the
136 * application (i.e. get number of "new events" by comparing to
139 * After a new SQ head value was read by the application this
140 * counter includes all submissions that were dropped reaching
141 * the new SQ head (and possibly more).
147 * Written by the kernel, shouldn't be modified by the
150 * The application needs a full memory barrier before checking
151 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
155 * Number of completion events lost because the queue was full;
156 * this should be avoided by the application by making sure
157 * there are not more requests pending than there is space in
158 * the completion queue.
160 * Written by the kernel, shouldn't be modified by the
161 * application (i.e. get number of "new events" by comparing to
164 * As completion events come in out of order this counter is not
165 * ordered with any other data.
169 * Ring buffer of completion events.
171 * The kernel writes completion events fresh every time they are
172 * produced, so the application is allowed to modify pending
175 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
178 struct io_mapped_ubuf {
181 struct bio_vec *bvec;
182 unsigned int nr_bvecs;
185 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;
195 struct work_struct ref_work;
196 struct completion done;
200 struct list_head list;
208 struct percpu_ref refs;
209 } ____cacheline_aligned_in_smp;
213 unsigned int compat: 1;
214 unsigned int account_mem: 1;
215 unsigned int cq_overflow_flushed: 1;
216 unsigned int drain_next: 1;
217 unsigned int eventfd_async: 1;
220 * Ring buffer of indices into array of io_uring_sqe, which is
221 * mmapped by the application using the IORING_OFF_SQES offset.
223 * This indirection could e.g. be used to assign fixed
224 * io_uring_sqe entries to operations and only submit them to
225 * the queue when needed.
227 * The kernel modifies neither the indices array nor the entries
231 unsigned cached_sq_head;
234 unsigned sq_thread_idle;
235 unsigned cached_sq_dropped;
236 atomic_t cached_cq_overflow;
237 unsigned long sq_check_overflow;
239 struct list_head defer_list;
240 struct list_head timeout_list;
241 struct list_head cq_overflow_list;
243 wait_queue_head_t inflight_wait;
244 struct io_uring_sqe *sq_sqes;
245 } ____cacheline_aligned_in_smp;
247 struct io_rings *rings;
251 struct task_struct *sqo_thread; /* if using sq thread polling */
252 struct mm_struct *sqo_mm;
253 wait_queue_head_t sqo_wait;
256 * If used, fixed file set. Writers must ensure that ->refs is dead,
257 * readers must ensure that ->refs is alive as long as the file* is
258 * used. Only updated through io_uring_register(2).
260 struct fixed_file_data *file_data;
261 unsigned nr_user_files;
263 struct file *ring_file;
265 /* if used, fixed mapped user buffers */
266 unsigned nr_user_bufs;
267 struct io_mapped_ubuf *user_bufs;
269 struct user_struct *user;
271 const struct cred *creds;
273 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
274 struct completion *completions;
276 /* if all else fails... */
277 struct io_kiocb *fallback_req;
279 #if defined(CONFIG_UNIX)
280 struct socket *ring_sock;
283 struct idr io_buffer_idr;
285 struct idr personality_idr;
288 unsigned cached_cq_tail;
291 atomic_t cq_timeouts;
292 unsigned long cq_check_overflow;
293 struct wait_queue_head cq_wait;
294 struct fasync_struct *cq_fasync;
295 struct eventfd_ctx *cq_ev_fd;
296 } ____cacheline_aligned_in_smp;
299 struct mutex uring_lock;
300 wait_queue_head_t wait;
301 } ____cacheline_aligned_in_smp;
304 spinlock_t completion_lock;
307 * ->poll_list is protected by the ctx->uring_lock for
308 * io_uring instances that don't use IORING_SETUP_SQPOLL.
309 * For SQPOLL, only the single threaded io_sq_thread() will
310 * manipulate the list, hence no extra locking is needed there.
312 struct list_head poll_list;
313 struct hlist_head *cancel_hash;
314 unsigned cancel_hash_bits;
315 bool poll_multi_file;
317 spinlock_t inflight_lock;
318 struct list_head inflight_list;
319 } ____cacheline_aligned_in_smp;
323 * First field must be the file pointer in all the
324 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
326 struct io_poll_iocb {
329 struct wait_queue_head *head;
335 struct wait_queue_entry wait;
340 struct file *put_file;
344 struct io_timeout_data {
345 struct io_kiocb *req;
346 struct hrtimer timer;
347 struct timespec64 ts;
348 enum hrtimer_mode mode;
354 struct sockaddr __user *addr;
355 int __user *addr_len;
357 unsigned long nofile;
381 /* NOTE: kiocb has the file as the first member, so don't do it here */
389 struct sockaddr __user *addr;
396 struct user_msghdr __user *msg;
402 struct io_buffer *kbuf;
411 struct filename *filename;
412 struct statx __user *buffer;
414 unsigned long nofile;
417 struct io_files_update {
443 struct epoll_event event;
447 struct file *file_out;
448 struct file *file_in;
455 struct io_provide_buf {
464 struct io_async_connect {
465 struct sockaddr_storage address;
468 struct io_async_msghdr {
469 struct iovec fast_iov[UIO_FASTIOV];
471 struct sockaddr __user *uaddr;
473 struct sockaddr_storage addr;
477 struct iovec fast_iov[UIO_FASTIOV];
483 struct io_async_ctx {
485 struct io_async_rw rw;
486 struct io_async_msghdr msg;
487 struct io_async_connect connect;
488 struct io_timeout_data timeout;
493 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
494 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
495 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
496 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
497 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
498 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
505 REQ_F_IOPOLL_COMPLETED_BIT,
506 REQ_F_LINK_TIMEOUT_BIT,
510 REQ_F_TIMEOUT_NOSEQ_BIT,
511 REQ_F_COMP_LOCKED_BIT,
512 REQ_F_NEED_CLEANUP_BIT,
515 REQ_F_BUFFER_SELECTED_BIT,
517 /* not a real bit, just to check we're not overflowing the space */
523 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
524 /* drain existing IO first */
525 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
527 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
528 /* doesn't sever on completion < 0 */
529 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
531 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
532 /* IOSQE_BUFFER_SELECT */
533 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
535 /* already grabbed next link */
536 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
537 /* fail rest of links */
538 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
539 /* on inflight list */
540 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
541 /* read/write uses file position */
542 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
543 /* must not punt to workers */
544 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
545 /* polled IO has completed */
546 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
547 /* has linked timeout */
548 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
549 /* timeout request */
550 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
552 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
553 /* must be punted even for NONBLOCK */
554 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
555 /* no timeout sequence */
556 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
557 /* completion under lock */
558 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
560 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
561 /* in overflow list */
562 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
563 /* already went through poll handler */
564 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
565 /* buffer already selected */
566 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
570 struct io_poll_iocb poll;
571 struct io_wq_work work;
575 * NOTE! Each of the iocb union members has the file pointer
576 * as the first entry in their struct definition. So you can
577 * access the file pointer through any of the sub-structs,
578 * or directly as just 'ki_filp' in this struct.
584 struct io_poll_iocb poll;
585 struct io_accept accept;
587 struct io_cancel cancel;
588 struct io_timeout timeout;
589 struct io_connect connect;
590 struct io_sr_msg sr_msg;
592 struct io_close close;
593 struct io_files_update files_update;
594 struct io_fadvise fadvise;
595 struct io_madvise madvise;
596 struct io_epoll epoll;
597 struct io_splice splice;
598 struct io_provide_buf pbuf;
601 struct io_async_ctx *io;
602 bool needs_fixed_file;
605 struct io_ring_ctx *ctx;
606 struct list_head list;
610 struct task_struct *task;
617 struct list_head link_list;
619 struct list_head inflight_entry;
623 * Only commands that never go async can use the below fields,
624 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
625 * async armed poll handlers for regular commands. The latter
626 * restore the work, if needed.
629 struct callback_head task_work;
630 struct hlist_node hash_node;
631 struct async_poll *apoll;
634 struct io_wq_work work;
638 #define IO_PLUG_THRESHOLD 2
639 #define IO_IOPOLL_BATCH 8
641 struct io_submit_state {
642 struct blk_plug plug;
645 * io_kiocb alloc cache
647 void *reqs[IO_IOPOLL_BATCH];
648 unsigned int free_reqs;
651 * File reference cache
655 unsigned int has_refs;
656 unsigned int used_refs;
657 unsigned int ios_left;
661 /* needs req->io allocated for deferral/async */
662 unsigned async_ctx : 1;
663 /* needs current->mm setup, does mm access */
664 unsigned needs_mm : 1;
665 /* needs req->file assigned */
666 unsigned needs_file : 1;
667 /* needs req->file assigned IFF fd is >= 0 */
668 unsigned fd_non_neg : 1;
669 /* hash wq insertion if file is a regular file */
670 unsigned hash_reg_file : 1;
671 /* unbound wq insertion if file is a non-regular file */
672 unsigned unbound_nonreg_file : 1;
673 /* opcode is not supported by this kernel */
674 unsigned not_supported : 1;
675 /* needs file table */
676 unsigned file_table : 1;
678 unsigned needs_fs : 1;
679 /* set if opcode supports polled "wait" */
681 unsigned pollout : 1;
682 /* op supports buffer selection */
683 unsigned buffer_select : 1;
686 static const struct io_op_def io_op_defs[] = {
687 [IORING_OP_NOP] = {},
688 [IORING_OP_READV] = {
692 .unbound_nonreg_file = 1,
696 [IORING_OP_WRITEV] = {
701 .unbound_nonreg_file = 1,
704 [IORING_OP_FSYNC] = {
707 [IORING_OP_READ_FIXED] = {
709 .unbound_nonreg_file = 1,
712 [IORING_OP_WRITE_FIXED] = {
715 .unbound_nonreg_file = 1,
718 [IORING_OP_POLL_ADD] = {
720 .unbound_nonreg_file = 1,
722 [IORING_OP_POLL_REMOVE] = {},
723 [IORING_OP_SYNC_FILE_RANGE] = {
726 [IORING_OP_SENDMSG] = {
730 .unbound_nonreg_file = 1,
734 [IORING_OP_RECVMSG] = {
738 .unbound_nonreg_file = 1,
743 [IORING_OP_TIMEOUT] = {
747 [IORING_OP_TIMEOUT_REMOVE] = {},
748 [IORING_OP_ACCEPT] = {
751 .unbound_nonreg_file = 1,
755 [IORING_OP_ASYNC_CANCEL] = {},
756 [IORING_OP_LINK_TIMEOUT] = {
760 [IORING_OP_CONNECT] = {
764 .unbound_nonreg_file = 1,
767 [IORING_OP_FALLOCATE] = {
770 [IORING_OP_OPENAT] = {
776 [IORING_OP_CLOSE] = {
780 [IORING_OP_FILES_UPDATE] = {
784 [IORING_OP_STATX] = {
793 .unbound_nonreg_file = 1,
797 [IORING_OP_WRITE] = {
800 .unbound_nonreg_file = 1,
803 [IORING_OP_FADVISE] = {
806 [IORING_OP_MADVISE] = {
812 .unbound_nonreg_file = 1,
818 .unbound_nonreg_file = 1,
822 [IORING_OP_OPENAT2] = {
828 [IORING_OP_EPOLL_CTL] = {
829 .unbound_nonreg_file = 1,
832 [IORING_OP_SPLICE] = {
835 .unbound_nonreg_file = 1,
837 [IORING_OP_PROVIDE_BUFFERS] = {},
838 [IORING_OP_REMOVE_BUFFERS] = {},
841 static void io_wq_submit_work(struct io_wq_work **workptr);
842 static void io_cqring_fill_event(struct io_kiocb *req, long res);
843 static void io_put_req(struct io_kiocb *req);
844 static void __io_double_put_req(struct io_kiocb *req);
845 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
846 static void io_queue_linked_timeout(struct io_kiocb *req);
847 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
848 struct io_uring_files_update *ip,
850 static int io_grab_files(struct io_kiocb *req);
851 static void io_ring_file_ref_flush(struct fixed_file_data *data);
852 static void io_cleanup_req(struct io_kiocb *req);
853 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
854 int fd, struct file **out_file, bool fixed);
855 static void __io_queue_sqe(struct io_kiocb *req,
856 const struct io_uring_sqe *sqe);
858 static struct kmem_cache *req_cachep;
860 static const struct file_operations io_uring_fops;
862 struct sock *io_uring_get_socket(struct file *file)
864 #if defined(CONFIG_UNIX)
865 if (file->f_op == &io_uring_fops) {
866 struct io_ring_ctx *ctx = file->private_data;
868 return ctx->ring_sock->sk;
873 EXPORT_SYMBOL(io_uring_get_socket);
875 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
877 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
879 complete(&ctx->completions[0]);
882 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
884 struct io_ring_ctx *ctx;
887 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
891 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
892 if (!ctx->fallback_req)
895 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
896 if (!ctx->completions)
900 * Use 5 bits less than the max cq entries, that should give us around
901 * 32 entries per hash list if totally full and uniformly spread.
903 hash_bits = ilog2(p->cq_entries);
907 ctx->cancel_hash_bits = hash_bits;
908 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
910 if (!ctx->cancel_hash)
912 __hash_init(ctx->cancel_hash, 1U << hash_bits);
914 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
915 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
918 ctx->flags = p->flags;
919 init_waitqueue_head(&ctx->cq_wait);
920 INIT_LIST_HEAD(&ctx->cq_overflow_list);
921 init_completion(&ctx->completions[0]);
922 init_completion(&ctx->completions[1]);
923 idr_init(&ctx->io_buffer_idr);
924 idr_init(&ctx->personality_idr);
925 mutex_init(&ctx->uring_lock);
926 init_waitqueue_head(&ctx->wait);
927 spin_lock_init(&ctx->completion_lock);
928 INIT_LIST_HEAD(&ctx->poll_list);
929 INIT_LIST_HEAD(&ctx->defer_list);
930 INIT_LIST_HEAD(&ctx->timeout_list);
931 init_waitqueue_head(&ctx->inflight_wait);
932 spin_lock_init(&ctx->inflight_lock);
933 INIT_LIST_HEAD(&ctx->inflight_list);
936 if (ctx->fallback_req)
937 kmem_cache_free(req_cachep, ctx->fallback_req);
938 kfree(ctx->completions);
939 kfree(ctx->cancel_hash);
944 static inline bool __req_need_defer(struct io_kiocb *req)
946 struct io_ring_ctx *ctx = req->ctx;
948 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
949 + atomic_read(&ctx->cached_cq_overflow);
952 static inline bool req_need_defer(struct io_kiocb *req)
954 if (unlikely(req->flags & REQ_F_IO_DRAIN))
955 return __req_need_defer(req);
960 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
962 struct io_kiocb *req;
964 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
965 if (req && !req_need_defer(req)) {
966 list_del_init(&req->list);
973 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
975 struct io_kiocb *req;
977 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
979 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
981 if (!__req_need_defer(req)) {
982 list_del_init(&req->list);
990 static void __io_commit_cqring(struct io_ring_ctx *ctx)
992 struct io_rings *rings = ctx->rings;
994 /* order cqe stores with ring update */
995 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
997 if (wq_has_sleeper(&ctx->cq_wait)) {
998 wake_up_interruptible(&ctx->cq_wait);
999 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1003 static inline void io_req_work_grab_env(struct io_kiocb *req,
1004 const struct io_op_def *def)
1006 if (!req->work.mm && def->needs_mm) {
1007 mmgrab(current->mm);
1008 req->work.mm = current->mm;
1010 if (!req->work.creds)
1011 req->work.creds = get_current_cred();
1012 if (!req->work.fs && def->needs_fs) {
1013 spin_lock(¤t->fs->lock);
1014 if (!current->fs->in_exec) {
1015 req->work.fs = current->fs;
1016 req->work.fs->users++;
1018 req->work.flags |= IO_WQ_WORK_CANCEL;
1020 spin_unlock(¤t->fs->lock);
1022 if (!req->work.task_pid)
1023 req->work.task_pid = task_pid_vnr(current);
1026 static inline void io_req_work_drop_env(struct io_kiocb *req)
1029 mmdrop(req->work.mm);
1030 req->work.mm = NULL;
1032 if (req->work.creds) {
1033 put_cred(req->work.creds);
1034 req->work.creds = NULL;
1037 struct fs_struct *fs = req->work.fs;
1039 spin_lock(&req->work.fs->lock);
1042 spin_unlock(&req->work.fs->lock);
1048 static inline void io_prep_async_work(struct io_kiocb *req,
1049 struct io_kiocb **link)
1051 const struct io_op_def *def = &io_op_defs[req->opcode];
1053 if (req->flags & REQ_F_ISREG) {
1054 if (def->hash_reg_file)
1055 io_wq_hash_work(&req->work, file_inode(req->file));
1057 if (def->unbound_nonreg_file)
1058 req->work.flags |= IO_WQ_WORK_UNBOUND;
1061 io_req_work_grab_env(req, def);
1063 *link = io_prep_linked_timeout(req);
1066 static inline void io_queue_async_work(struct io_kiocb *req)
1068 struct io_ring_ctx *ctx = req->ctx;
1069 struct io_kiocb *link;
1071 io_prep_async_work(req, &link);
1073 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1074 &req->work, req->flags);
1075 io_wq_enqueue(ctx->io_wq, &req->work);
1078 io_queue_linked_timeout(link);
1081 static void io_kill_timeout(struct io_kiocb *req)
1085 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1087 atomic_inc(&req->ctx->cq_timeouts);
1088 list_del_init(&req->list);
1089 req->flags |= REQ_F_COMP_LOCKED;
1090 io_cqring_fill_event(req, 0);
1095 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1097 struct io_kiocb *req, *tmp;
1099 spin_lock_irq(&ctx->completion_lock);
1100 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1101 io_kill_timeout(req);
1102 spin_unlock_irq(&ctx->completion_lock);
1105 static void io_commit_cqring(struct io_ring_ctx *ctx)
1107 struct io_kiocb *req;
1109 while ((req = io_get_timeout_req(ctx)) != NULL)
1110 io_kill_timeout(req);
1112 __io_commit_cqring(ctx);
1114 while ((req = io_get_deferred_req(ctx)) != NULL)
1115 io_queue_async_work(req);
1118 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1120 struct io_rings *rings = ctx->rings;
1123 tail = ctx->cached_cq_tail;
1125 * writes to the cq entry need to come after reading head; the
1126 * control dependency is enough as we're using WRITE_ONCE to
1129 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1132 ctx->cached_cq_tail++;
1133 return &rings->cqes[tail & ctx->cq_mask];
1136 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1140 if (!ctx->eventfd_async)
1142 return io_wq_current_is_worker();
1145 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1147 if (waitqueue_active(&ctx->wait))
1148 wake_up(&ctx->wait);
1149 if (waitqueue_active(&ctx->sqo_wait))
1150 wake_up(&ctx->sqo_wait);
1151 if (io_should_trigger_evfd(ctx))
1152 eventfd_signal(ctx->cq_ev_fd, 1);
1155 /* Returns true if there are no backlogged entries after the flush */
1156 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1158 struct io_rings *rings = ctx->rings;
1159 struct io_uring_cqe *cqe;
1160 struct io_kiocb *req;
1161 unsigned long flags;
1165 if (list_empty_careful(&ctx->cq_overflow_list))
1167 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1168 rings->cq_ring_entries))
1172 spin_lock_irqsave(&ctx->completion_lock, flags);
1174 /* if force is set, the ring is going away. always drop after that */
1176 ctx->cq_overflow_flushed = 1;
1179 while (!list_empty(&ctx->cq_overflow_list)) {
1180 cqe = io_get_cqring(ctx);
1184 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1186 list_move(&req->list, &list);
1187 req->flags &= ~REQ_F_OVERFLOW;
1189 WRITE_ONCE(cqe->user_data, req->user_data);
1190 WRITE_ONCE(cqe->res, req->result);
1191 WRITE_ONCE(cqe->flags, req->cflags);
1193 WRITE_ONCE(ctx->rings->cq_overflow,
1194 atomic_inc_return(&ctx->cached_cq_overflow));
1198 io_commit_cqring(ctx);
1200 clear_bit(0, &ctx->sq_check_overflow);
1201 clear_bit(0, &ctx->cq_check_overflow);
1203 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1204 io_cqring_ev_posted(ctx);
1206 while (!list_empty(&list)) {
1207 req = list_first_entry(&list, struct io_kiocb, list);
1208 list_del(&req->list);
1215 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1217 struct io_ring_ctx *ctx = req->ctx;
1218 struct io_uring_cqe *cqe;
1220 trace_io_uring_complete(ctx, req->user_data, res);
1223 * If we can't get a cq entry, userspace overflowed the
1224 * submission (by quite a lot). Increment the overflow count in
1227 cqe = io_get_cqring(ctx);
1229 WRITE_ONCE(cqe->user_data, req->user_data);
1230 WRITE_ONCE(cqe->res, res);
1231 WRITE_ONCE(cqe->flags, cflags);
1232 } else if (ctx->cq_overflow_flushed) {
1233 WRITE_ONCE(ctx->rings->cq_overflow,
1234 atomic_inc_return(&ctx->cached_cq_overflow));
1236 if (list_empty(&ctx->cq_overflow_list)) {
1237 set_bit(0, &ctx->sq_check_overflow);
1238 set_bit(0, &ctx->cq_check_overflow);
1240 req->flags |= REQ_F_OVERFLOW;
1241 refcount_inc(&req->refs);
1243 req->cflags = cflags;
1244 list_add_tail(&req->list, &ctx->cq_overflow_list);
1248 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1250 __io_cqring_fill_event(req, res, 0);
1253 static void __io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1255 struct io_ring_ctx *ctx = req->ctx;
1256 unsigned long flags;
1258 spin_lock_irqsave(&ctx->completion_lock, flags);
1259 __io_cqring_fill_event(req, res, cflags);
1260 io_commit_cqring(ctx);
1261 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1263 io_cqring_ev_posted(ctx);
1266 static void io_cqring_add_event(struct io_kiocb *req, long res)
1268 __io_cqring_add_event(req, res, 0);
1271 static inline bool io_is_fallback_req(struct io_kiocb *req)
1273 return req == (struct io_kiocb *)
1274 ((unsigned long) req->ctx->fallback_req & ~1UL);
1277 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1279 struct io_kiocb *req;
1281 req = ctx->fallback_req;
1282 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1288 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1289 struct io_submit_state *state)
1291 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1292 struct io_kiocb *req;
1295 req = kmem_cache_alloc(req_cachep, gfp);
1298 } else if (!state->free_reqs) {
1302 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1303 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1306 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1307 * retry single alloc to be on the safe side.
1309 if (unlikely(ret <= 0)) {
1310 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1311 if (!state->reqs[0])
1315 state->free_reqs = ret - 1;
1316 req = state->reqs[ret - 1];
1319 req = state->reqs[state->free_reqs];
1327 /* one is dropped after submission, the other at completion */
1328 refcount_set(&req->refs, 2);
1330 INIT_IO_WORK(&req->work, io_wq_submit_work);
1333 req = io_get_fallback_req(ctx);
1336 percpu_ref_put(&ctx->refs);
1340 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1344 percpu_ref_put(&req->ctx->file_data->refs);
1349 static void __io_req_do_free(struct io_kiocb *req)
1351 if (likely(!io_is_fallback_req(req)))
1352 kmem_cache_free(req_cachep, req);
1354 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1357 static void __io_req_aux_free(struct io_kiocb *req)
1359 if (req->flags & REQ_F_NEED_CLEANUP)
1360 io_cleanup_req(req);
1364 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1366 io_req_work_drop_env(req);
1369 static void __io_free_req(struct io_kiocb *req)
1371 __io_req_aux_free(req);
1373 if (req->flags & REQ_F_INFLIGHT) {
1374 struct io_ring_ctx *ctx = req->ctx;
1375 unsigned long flags;
1377 spin_lock_irqsave(&ctx->inflight_lock, flags);
1378 list_del(&req->inflight_entry);
1379 if (waitqueue_active(&ctx->inflight_wait))
1380 wake_up(&ctx->inflight_wait);
1381 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1384 percpu_ref_put(&req->ctx->refs);
1385 __io_req_do_free(req);
1389 void *reqs[IO_IOPOLL_BATCH];
1394 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1396 int fixed_refs = rb->to_free;
1400 if (rb->need_iter) {
1401 int i, inflight = 0;
1402 unsigned long flags;
1405 for (i = 0; i < rb->to_free; i++) {
1406 struct io_kiocb *req = rb->reqs[i];
1408 if (req->flags & REQ_F_FIXED_FILE) {
1412 if (req->flags & REQ_F_INFLIGHT)
1414 __io_req_aux_free(req);
1419 spin_lock_irqsave(&ctx->inflight_lock, flags);
1420 for (i = 0; i < rb->to_free; i++) {
1421 struct io_kiocb *req = rb->reqs[i];
1423 if (req->flags & REQ_F_INFLIGHT) {
1424 list_del(&req->inflight_entry);
1429 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1431 if (waitqueue_active(&ctx->inflight_wait))
1432 wake_up(&ctx->inflight_wait);
1435 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1437 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
1438 percpu_ref_put_many(&ctx->refs, rb->to_free);
1439 rb->to_free = rb->need_iter = 0;
1442 static bool io_link_cancel_timeout(struct io_kiocb *req)
1444 struct io_ring_ctx *ctx = req->ctx;
1447 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1449 io_cqring_fill_event(req, -ECANCELED);
1450 io_commit_cqring(ctx);
1451 req->flags &= ~REQ_F_LINK;
1459 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1461 struct io_ring_ctx *ctx = req->ctx;
1462 bool wake_ev = false;
1464 /* Already got next link */
1465 if (req->flags & REQ_F_LINK_NEXT)
1469 * The list should never be empty when we are called here. But could
1470 * potentially happen if the chain is messed up, check to be on the
1473 while (!list_empty(&req->link_list)) {
1474 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1475 struct io_kiocb, link_list);
1477 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1478 (nxt->flags & REQ_F_TIMEOUT))) {
1479 list_del_init(&nxt->link_list);
1480 wake_ev |= io_link_cancel_timeout(nxt);
1481 req->flags &= ~REQ_F_LINK_TIMEOUT;
1485 list_del_init(&req->link_list);
1486 if (!list_empty(&nxt->link_list))
1487 nxt->flags |= REQ_F_LINK;
1492 req->flags |= REQ_F_LINK_NEXT;
1494 io_cqring_ev_posted(ctx);
1498 * Called if REQ_F_LINK is set, and we fail the head request
1500 static void io_fail_links(struct io_kiocb *req)
1502 struct io_ring_ctx *ctx = req->ctx;
1503 unsigned long flags;
1505 spin_lock_irqsave(&ctx->completion_lock, flags);
1507 while (!list_empty(&req->link_list)) {
1508 struct io_kiocb *link = list_first_entry(&req->link_list,
1509 struct io_kiocb, link_list);
1511 list_del_init(&link->link_list);
1512 trace_io_uring_fail_link(req, link);
1514 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1515 link->opcode == IORING_OP_LINK_TIMEOUT) {
1516 io_link_cancel_timeout(link);
1518 io_cqring_fill_event(link, -ECANCELED);
1519 __io_double_put_req(link);
1521 req->flags &= ~REQ_F_LINK_TIMEOUT;
1524 io_commit_cqring(ctx);
1525 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1526 io_cqring_ev_posted(ctx);
1529 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1531 if (likely(!(req->flags & REQ_F_LINK)))
1535 * If LINK is set, we have dependent requests in this chain. If we
1536 * didn't fail this request, queue the first one up, moving any other
1537 * dependencies to the next request. In case of failure, fail the rest
1540 if (req->flags & REQ_F_FAIL_LINK) {
1542 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1543 REQ_F_LINK_TIMEOUT) {
1544 struct io_ring_ctx *ctx = req->ctx;
1545 unsigned long flags;
1548 * If this is a timeout link, we could be racing with the
1549 * timeout timer. Grab the completion lock for this case to
1550 * protect against that.
1552 spin_lock_irqsave(&ctx->completion_lock, flags);
1553 io_req_link_next(req, nxt);
1554 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1556 io_req_link_next(req, nxt);
1560 static void io_free_req(struct io_kiocb *req)
1562 struct io_kiocb *nxt = NULL;
1564 io_req_find_next(req, &nxt);
1568 io_queue_async_work(nxt);
1571 static void io_link_work_cb(struct io_wq_work **workptr)
1573 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
1574 struct io_kiocb *link;
1576 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1577 io_queue_linked_timeout(link);
1578 io_wq_submit_work(workptr);
1581 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
1583 struct io_kiocb *link;
1584 const struct io_op_def *def = &io_op_defs[nxt->opcode];
1586 if ((nxt->flags & REQ_F_ISREG) && def->hash_reg_file)
1587 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1589 *workptr = &nxt->work;
1590 link = io_prep_linked_timeout(nxt);
1592 nxt->work.func = io_link_work_cb;
1596 * Drop reference to request, return next in chain (if there is one) if this
1597 * was the last reference to this request.
1599 __attribute__((nonnull))
1600 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1602 if (refcount_dec_and_test(&req->refs)) {
1603 io_req_find_next(req, nxtptr);
1608 static void io_put_req(struct io_kiocb *req)
1610 if (refcount_dec_and_test(&req->refs))
1614 static void io_steal_work(struct io_kiocb *req,
1615 struct io_wq_work **workptr)
1618 * It's in an io-wq worker, so there always should be at least
1619 * one reference, which will be dropped in io_put_work() just
1620 * after the current handler returns.
1622 * It also means, that if the counter dropped to 1, then there is
1623 * no asynchronous users left, so it's safe to steal the next work.
1625 if (refcount_read(&req->refs) == 1) {
1626 struct io_kiocb *nxt = NULL;
1628 io_req_find_next(req, &nxt);
1630 io_wq_assign_next(workptr, nxt);
1635 * Must only be used if we don't need to care about links, usually from
1636 * within the completion handling itself.
1638 static void __io_double_put_req(struct io_kiocb *req)
1640 /* drop both submit and complete references */
1641 if (refcount_sub_and_test(2, &req->refs))
1645 static void io_double_put_req(struct io_kiocb *req)
1647 /* drop both submit and complete references */
1648 if (refcount_sub_and_test(2, &req->refs))
1652 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1654 struct io_rings *rings = ctx->rings;
1656 if (test_bit(0, &ctx->cq_check_overflow)) {
1658 * noflush == true is from the waitqueue handler, just ensure
1659 * we wake up the task, and the next invocation will flush the
1660 * entries. We cannot safely to it from here.
1662 if (noflush && !list_empty(&ctx->cq_overflow_list))
1665 io_cqring_overflow_flush(ctx, false);
1668 /* See comment at the top of this file */
1670 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1673 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1675 struct io_rings *rings = ctx->rings;
1677 /* make sure SQ entry isn't read before tail */
1678 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1681 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1683 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1686 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1689 rb->reqs[rb->to_free++] = req;
1690 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1691 io_free_req_many(req->ctx, rb);
1695 static int io_put_kbuf(struct io_kiocb *req)
1697 struct io_buffer *kbuf;
1700 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1701 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1702 cflags |= IORING_CQE_F_BUFFER;
1709 * Find and free completed poll iocbs
1711 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1712 struct list_head *done)
1714 struct req_batch rb;
1715 struct io_kiocb *req;
1717 rb.to_free = rb.need_iter = 0;
1718 while (!list_empty(done)) {
1721 req = list_first_entry(done, struct io_kiocb, list);
1722 list_del(&req->list);
1724 if (req->flags & REQ_F_BUFFER_SELECTED)
1725 cflags = io_put_kbuf(req);
1727 __io_cqring_fill_event(req, req->result, cflags);
1730 if (refcount_dec_and_test(&req->refs) &&
1731 !io_req_multi_free(&rb, req))
1735 io_commit_cqring(ctx);
1736 if (ctx->flags & IORING_SETUP_SQPOLL)
1737 io_cqring_ev_posted(ctx);
1738 io_free_req_many(ctx, &rb);
1741 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1744 struct io_kiocb *req, *tmp;
1750 * Only spin for completions if we don't have multiple devices hanging
1751 * off our complete list, and we're under the requested amount.
1753 spin = !ctx->poll_multi_file && *nr_events < min;
1756 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1757 struct kiocb *kiocb = &req->rw.kiocb;
1760 * Move completed entries to our local list. If we find a
1761 * request that requires polling, break out and complete
1762 * the done list first, if we have entries there.
1764 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1765 list_move_tail(&req->list, &done);
1768 if (!list_empty(&done))
1771 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1780 if (!list_empty(&done))
1781 io_iopoll_complete(ctx, nr_events, &done);
1787 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1788 * non-spinning poll check - we'll still enter the driver poll loop, but only
1789 * as a non-spinning completion check.
1791 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1794 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1797 ret = io_do_iopoll(ctx, nr_events, min);
1800 if (!min || *nr_events >= min)
1808 * We can't just wait for polled events to come to us, we have to actively
1809 * find and complete them.
1811 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1813 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1816 mutex_lock(&ctx->uring_lock);
1817 while (!list_empty(&ctx->poll_list)) {
1818 unsigned int nr_events = 0;
1820 io_iopoll_getevents(ctx, &nr_events, 1);
1823 * Ensure we allow local-to-the-cpu processing to take place,
1824 * in this case we need to ensure that we reap all events.
1828 mutex_unlock(&ctx->uring_lock);
1831 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1834 int iters = 0, ret = 0;
1837 * We disallow the app entering submit/complete with polling, but we
1838 * still need to lock the ring to prevent racing with polled issue
1839 * that got punted to a workqueue.
1841 mutex_lock(&ctx->uring_lock);
1846 * Don't enter poll loop if we already have events pending.
1847 * If we do, we can potentially be spinning for commands that
1848 * already triggered a CQE (eg in error).
1850 if (io_cqring_events(ctx, false))
1854 * If a submit got punted to a workqueue, we can have the
1855 * application entering polling for a command before it gets
1856 * issued. That app will hold the uring_lock for the duration
1857 * of the poll right here, so we need to take a breather every
1858 * now and then to ensure that the issue has a chance to add
1859 * the poll to the issued list. Otherwise we can spin here
1860 * forever, while the workqueue is stuck trying to acquire the
1863 if (!(++iters & 7)) {
1864 mutex_unlock(&ctx->uring_lock);
1865 mutex_lock(&ctx->uring_lock);
1868 if (*nr_events < min)
1869 tmin = min - *nr_events;
1871 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1875 } while (min && !*nr_events && !need_resched());
1877 mutex_unlock(&ctx->uring_lock);
1881 static void kiocb_end_write(struct io_kiocb *req)
1884 * Tell lockdep we inherited freeze protection from submission
1887 if (req->flags & REQ_F_ISREG) {
1888 struct inode *inode = file_inode(req->file);
1890 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1892 file_end_write(req->file);
1895 static inline void req_set_fail_links(struct io_kiocb *req)
1897 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1898 req->flags |= REQ_F_FAIL_LINK;
1901 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1903 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1906 if (kiocb->ki_flags & IOCB_WRITE)
1907 kiocb_end_write(req);
1909 if (res != req->result)
1910 req_set_fail_links(req);
1911 if (req->flags & REQ_F_BUFFER_SELECTED)
1912 cflags = io_put_kbuf(req);
1913 __io_cqring_add_event(req, res, cflags);
1916 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1918 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1920 io_complete_rw_common(kiocb, res);
1924 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1926 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1928 if (kiocb->ki_flags & IOCB_WRITE)
1929 kiocb_end_write(req);
1931 if (res != req->result)
1932 req_set_fail_links(req);
1935 req->flags |= REQ_F_IOPOLL_COMPLETED;
1939 * After the iocb has been issued, it's safe to be found on the poll list.
1940 * Adding the kiocb to the list AFTER submission ensures that we don't
1941 * find it from a io_iopoll_getevents() thread before the issuer is done
1942 * accessing the kiocb cookie.
1944 static void io_iopoll_req_issued(struct io_kiocb *req)
1946 struct io_ring_ctx *ctx = req->ctx;
1949 * Track whether we have multiple files in our lists. This will impact
1950 * how we do polling eventually, not spinning if we're on potentially
1951 * different devices.
1953 if (list_empty(&ctx->poll_list)) {
1954 ctx->poll_multi_file = false;
1955 } else if (!ctx->poll_multi_file) {
1956 struct io_kiocb *list_req;
1958 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1960 if (list_req->file != req->file)
1961 ctx->poll_multi_file = true;
1965 * For fast devices, IO may have already completed. If it has, add
1966 * it to the front so we find it first.
1968 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1969 list_add(&req->list, &ctx->poll_list);
1971 list_add_tail(&req->list, &ctx->poll_list);
1973 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1974 wq_has_sleeper(&ctx->sqo_wait))
1975 wake_up(&ctx->sqo_wait);
1978 static void io_file_put(struct io_submit_state *state)
1981 int diff = state->has_refs - state->used_refs;
1984 fput_many(state->file, diff);
1990 * Get as many references to a file as we have IOs left in this submission,
1991 * assuming most submissions are for one file, or at least that each file
1992 * has more than one submission.
1994 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2000 if (state->fd == fd) {
2007 state->file = fget_many(fd, state->ios_left);
2012 state->has_refs = state->ios_left;
2013 state->used_refs = 1;
2019 * If we tracked the file through the SCM inflight mechanism, we could support
2020 * any file. For now, just ensure that anything potentially problematic is done
2023 static bool io_file_supports_async(struct file *file)
2025 umode_t mode = file_inode(file)->i_mode;
2027 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
2029 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
2035 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2036 bool force_nonblock)
2038 struct io_ring_ctx *ctx = req->ctx;
2039 struct kiocb *kiocb = &req->rw.kiocb;
2043 if (S_ISREG(file_inode(req->file)->i_mode))
2044 req->flags |= REQ_F_ISREG;
2046 kiocb->ki_pos = READ_ONCE(sqe->off);
2047 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2048 req->flags |= REQ_F_CUR_POS;
2049 kiocb->ki_pos = req->file->f_pos;
2051 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2052 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2053 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2057 ioprio = READ_ONCE(sqe->ioprio);
2059 ret = ioprio_check_cap(ioprio);
2063 kiocb->ki_ioprio = ioprio;
2065 kiocb->ki_ioprio = get_current_ioprio();
2067 /* don't allow async punt if RWF_NOWAIT was requested */
2068 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2069 (req->file->f_flags & O_NONBLOCK))
2070 req->flags |= REQ_F_NOWAIT;
2073 kiocb->ki_flags |= IOCB_NOWAIT;
2075 if (ctx->flags & IORING_SETUP_IOPOLL) {
2076 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2077 !kiocb->ki_filp->f_op->iopoll)
2080 kiocb->ki_flags |= IOCB_HIPRI;
2081 kiocb->ki_complete = io_complete_rw_iopoll;
2084 if (kiocb->ki_flags & IOCB_HIPRI)
2086 kiocb->ki_complete = io_complete_rw;
2089 req->rw.addr = READ_ONCE(sqe->addr);
2090 req->rw.len = READ_ONCE(sqe->len);
2091 /* we own ->private, reuse it for the buffer index / buffer ID */
2092 req->rw.kiocb.private = (void *) (unsigned long)
2093 READ_ONCE(sqe->buf_index);
2097 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2103 case -ERESTARTNOINTR:
2104 case -ERESTARTNOHAND:
2105 case -ERESTART_RESTARTBLOCK:
2107 * We can't just restart the syscall, since previously
2108 * submitted sqes may already be in progress. Just fail this
2114 kiocb->ki_complete(kiocb, ret, 0);
2118 static void kiocb_done(struct kiocb *kiocb, ssize_t ret)
2120 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2122 if (req->flags & REQ_F_CUR_POS)
2123 req->file->f_pos = kiocb->ki_pos;
2124 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2125 io_complete_rw(kiocb, ret, 0);
2127 io_rw_done(kiocb, ret);
2130 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2131 struct iov_iter *iter)
2133 struct io_ring_ctx *ctx = req->ctx;
2134 size_t len = req->rw.len;
2135 struct io_mapped_ubuf *imu;
2136 unsigned index, buf_index;
2140 /* attempt to use fixed buffers without having provided iovecs */
2141 if (unlikely(!ctx->user_bufs))
2144 buf_index = (unsigned long) req->rw.kiocb.private;
2145 if (unlikely(buf_index >= ctx->nr_user_bufs))
2148 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2149 imu = &ctx->user_bufs[index];
2150 buf_addr = req->rw.addr;
2153 if (buf_addr + len < buf_addr)
2155 /* not inside the mapped region */
2156 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2160 * May not be a start of buffer, set size appropriately
2161 * and advance us to the beginning.
2163 offset = buf_addr - imu->ubuf;
2164 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2168 * Don't use iov_iter_advance() here, as it's really slow for
2169 * using the latter parts of a big fixed buffer - it iterates
2170 * over each segment manually. We can cheat a bit here, because
2173 * 1) it's a BVEC iter, we set it up
2174 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2175 * first and last bvec
2177 * So just find our index, and adjust the iterator afterwards.
2178 * If the offset is within the first bvec (or the whole first
2179 * bvec, just use iov_iter_advance(). This makes it easier
2180 * since we can just skip the first segment, which may not
2181 * be PAGE_SIZE aligned.
2183 const struct bio_vec *bvec = imu->bvec;
2185 if (offset <= bvec->bv_len) {
2186 iov_iter_advance(iter, offset);
2188 unsigned long seg_skip;
2190 /* skip first vec */
2191 offset -= bvec->bv_len;
2192 seg_skip = 1 + (offset >> PAGE_SHIFT);
2194 iter->bvec = bvec + seg_skip;
2195 iter->nr_segs -= seg_skip;
2196 iter->count -= bvec->bv_len + offset;
2197 iter->iov_offset = offset & ~PAGE_MASK;
2204 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2207 mutex_unlock(&ctx->uring_lock);
2210 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2213 * "Normal" inline submissions always hold the uring_lock, since we
2214 * grab it from the system call. Same is true for the SQPOLL offload.
2215 * The only exception is when we've detached the request and issue it
2216 * from an async worker thread, grab the lock for that case.
2219 mutex_lock(&ctx->uring_lock);
2222 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2223 int bgid, struct io_buffer *kbuf,
2226 struct io_buffer *head;
2228 if (req->flags & REQ_F_BUFFER_SELECTED)
2231 io_ring_submit_lock(req->ctx, needs_lock);
2233 lockdep_assert_held(&req->ctx->uring_lock);
2235 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2237 if (!list_empty(&head->list)) {
2238 kbuf = list_last_entry(&head->list, struct io_buffer,
2240 list_del(&kbuf->list);
2243 idr_remove(&req->ctx->io_buffer_idr, bgid);
2245 if (*len > kbuf->len)
2248 kbuf = ERR_PTR(-ENOBUFS);
2251 io_ring_submit_unlock(req->ctx, needs_lock);
2256 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2259 struct io_buffer *kbuf;
2262 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2263 bgid = (int) (unsigned long) req->rw.kiocb.private;
2264 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2267 req->rw.addr = (u64) (unsigned long) kbuf;
2268 req->flags |= REQ_F_BUFFER_SELECTED;
2269 return u64_to_user_ptr(kbuf->addr);
2272 #ifdef CONFIG_COMPAT
2273 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2276 struct compat_iovec __user *uiov;
2277 compat_ssize_t clen;
2281 uiov = u64_to_user_ptr(req->rw.addr);
2282 if (!access_ok(uiov, sizeof(*uiov)))
2284 if (__get_user(clen, &uiov->iov_len))
2290 buf = io_rw_buffer_select(req, &len, needs_lock);
2292 return PTR_ERR(buf);
2293 iov[0].iov_base = buf;
2294 iov[0].iov_len = (compat_size_t) len;
2299 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2302 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2306 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2309 len = iov[0].iov_len;
2312 buf = io_rw_buffer_select(req, &len, needs_lock);
2314 return PTR_ERR(buf);
2315 iov[0].iov_base = buf;
2316 iov[0].iov_len = len;
2320 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2323 if (req->flags & REQ_F_BUFFER_SELECTED)
2327 else if (req->rw.len > 1)
2330 #ifdef CONFIG_COMPAT
2331 if (req->ctx->compat)
2332 return io_compat_import(req, iov, needs_lock);
2335 return __io_iov_buffer_select(req, iov, needs_lock);
2338 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2339 struct iovec **iovec, struct iov_iter *iter,
2342 void __user *buf = u64_to_user_ptr(req->rw.addr);
2343 size_t sqe_len = req->rw.len;
2347 opcode = req->opcode;
2348 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2350 return io_import_fixed(req, rw, iter);
2353 /* buffer index only valid with fixed read/write, or buffer select */
2354 if (req->rw.kiocb.private && !(req->flags & REQ_F_BUFFER_SELECT))
2357 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2358 if (req->flags & REQ_F_BUFFER_SELECT) {
2359 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2362 return PTR_ERR(buf);
2364 req->rw.len = sqe_len;
2367 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2369 return ret < 0 ? ret : sqe_len;
2373 struct io_async_rw *iorw = &req->io->rw;
2376 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2377 if (iorw->iov == iorw->fast_iov)
2382 if (req->flags & REQ_F_BUFFER_SELECT) {
2383 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2385 ret = (*iovec)->iov_len;
2386 iov_iter_init(iter, rw, *iovec, 1, ret);
2392 #ifdef CONFIG_COMPAT
2393 if (req->ctx->compat)
2394 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2398 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2402 * For files that don't have ->read_iter() and ->write_iter(), handle them
2403 * by looping over ->read() or ->write() manually.
2405 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2406 struct iov_iter *iter)
2411 * Don't support polled IO through this interface, and we can't
2412 * support non-blocking either. For the latter, this just causes
2413 * the kiocb to be handled from an async context.
2415 if (kiocb->ki_flags & IOCB_HIPRI)
2417 if (kiocb->ki_flags & IOCB_NOWAIT)
2420 while (iov_iter_count(iter)) {
2424 if (!iov_iter_is_bvec(iter)) {
2425 iovec = iov_iter_iovec(iter);
2427 /* fixed buffers import bvec */
2428 iovec.iov_base = kmap(iter->bvec->bv_page)
2430 iovec.iov_len = min(iter->count,
2431 iter->bvec->bv_len - iter->iov_offset);
2435 nr = file->f_op->read(file, iovec.iov_base,
2436 iovec.iov_len, &kiocb->ki_pos);
2438 nr = file->f_op->write(file, iovec.iov_base,
2439 iovec.iov_len, &kiocb->ki_pos);
2442 if (iov_iter_is_bvec(iter))
2443 kunmap(iter->bvec->bv_page);
2451 if (nr != iovec.iov_len)
2453 iov_iter_advance(iter, nr);
2459 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2460 struct iovec *iovec, struct iovec *fast_iov,
2461 struct iov_iter *iter)
2463 req->io->rw.nr_segs = iter->nr_segs;
2464 req->io->rw.size = io_size;
2465 req->io->rw.iov = iovec;
2466 if (!req->io->rw.iov) {
2467 req->io->rw.iov = req->io->rw.fast_iov;
2468 memcpy(req->io->rw.iov, fast_iov,
2469 sizeof(struct iovec) * iter->nr_segs);
2471 req->flags |= REQ_F_NEED_CLEANUP;
2475 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2477 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2478 return req->io == NULL;
2481 static int io_alloc_async_ctx(struct io_kiocb *req)
2483 if (!io_op_defs[req->opcode].async_ctx)
2486 return __io_alloc_async_ctx(req);
2489 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2490 struct iovec *iovec, struct iovec *fast_iov,
2491 struct iov_iter *iter)
2493 if (!io_op_defs[req->opcode].async_ctx)
2496 if (__io_alloc_async_ctx(req))
2499 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2504 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2505 bool force_nonblock)
2507 struct io_async_ctx *io;
2508 struct iov_iter iter;
2511 ret = io_prep_rw(req, sqe, force_nonblock);
2515 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2518 /* either don't need iovec imported or already have it */
2519 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2523 io->rw.iov = io->rw.fast_iov;
2525 ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2530 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2534 static int io_read(struct io_kiocb *req, bool force_nonblock)
2536 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2537 struct kiocb *kiocb = &req->rw.kiocb;
2538 struct iov_iter iter;
2540 ssize_t io_size, ret;
2542 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2546 /* Ensure we clear previously set non-block flag */
2547 if (!force_nonblock)
2548 kiocb->ki_flags &= ~IOCB_NOWAIT;
2552 if (req->flags & REQ_F_LINK)
2553 req->result = io_size;
2556 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2557 * we know to async punt it even if it was opened O_NONBLOCK
2559 if (force_nonblock && !io_file_supports_async(req->file))
2562 iov_count = iov_iter_count(&iter);
2563 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2567 if (req->file->f_op->read_iter)
2568 ret2 = call_read_iter(req->file, kiocb, &iter);
2570 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2572 /* Catch -EAGAIN return for forced non-blocking submission */
2573 if (!force_nonblock || ret2 != -EAGAIN) {
2574 kiocb_done(kiocb, ret2);
2577 ret = io_setup_async_rw(req, io_size, iovec,
2578 inline_vecs, &iter);
2581 /* any defer here is final, must blocking retry */
2582 if (!(req->flags & REQ_F_NOWAIT))
2583 req->flags |= REQ_F_MUST_PUNT;
2589 req->flags &= ~REQ_F_NEED_CLEANUP;
2593 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2594 bool force_nonblock)
2596 struct io_async_ctx *io;
2597 struct iov_iter iter;
2600 ret = io_prep_rw(req, sqe, force_nonblock);
2604 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2607 req->fsize = rlimit(RLIMIT_FSIZE);
2609 /* either don't need iovec imported or already have it */
2610 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2614 io->rw.iov = io->rw.fast_iov;
2616 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
2621 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2625 static int io_write(struct io_kiocb *req, bool force_nonblock)
2627 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2628 struct kiocb *kiocb = &req->rw.kiocb;
2629 struct iov_iter iter;
2631 ssize_t ret, io_size;
2633 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
2637 /* Ensure we clear previously set non-block flag */
2638 if (!force_nonblock)
2639 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2643 if (req->flags & REQ_F_LINK)
2644 req->result = io_size;
2647 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2648 * we know to async punt it even if it was opened O_NONBLOCK
2650 if (force_nonblock && !io_file_supports_async(req->file))
2653 /* file path doesn't support NOWAIT for non-direct_IO */
2654 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2655 (req->flags & REQ_F_ISREG))
2658 iov_count = iov_iter_count(&iter);
2659 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2664 * Open-code file_start_write here to grab freeze protection,
2665 * which will be released by another thread in
2666 * io_complete_rw(). Fool lockdep by telling it the lock got
2667 * released so that it doesn't complain about the held lock when
2668 * we return to userspace.
2670 if (req->flags & REQ_F_ISREG) {
2671 __sb_start_write(file_inode(req->file)->i_sb,
2672 SB_FREEZE_WRITE, true);
2673 __sb_writers_release(file_inode(req->file)->i_sb,
2676 kiocb->ki_flags |= IOCB_WRITE;
2678 if (!force_nonblock)
2679 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
2681 if (req->file->f_op->write_iter)
2682 ret2 = call_write_iter(req->file, kiocb, &iter);
2684 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2686 if (!force_nonblock)
2687 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
2690 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
2691 * retry them without IOCB_NOWAIT.
2693 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2695 if (!force_nonblock || ret2 != -EAGAIN) {
2696 kiocb_done(kiocb, ret2);
2699 ret = io_setup_async_rw(req, io_size, iovec,
2700 inline_vecs, &iter);
2703 /* any defer here is final, must blocking retry */
2704 req->flags |= REQ_F_MUST_PUNT;
2709 req->flags &= ~REQ_F_NEED_CLEANUP;
2714 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2716 struct io_splice* sp = &req->splice;
2717 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
2720 if (req->flags & REQ_F_NEED_CLEANUP)
2724 sp->off_in = READ_ONCE(sqe->splice_off_in);
2725 sp->off_out = READ_ONCE(sqe->off);
2726 sp->len = READ_ONCE(sqe->len);
2727 sp->flags = READ_ONCE(sqe->splice_flags);
2729 if (unlikely(sp->flags & ~valid_flags))
2732 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
2733 (sp->flags & SPLICE_F_FD_IN_FIXED));
2736 req->flags |= REQ_F_NEED_CLEANUP;
2738 if (!S_ISREG(file_inode(sp->file_in)->i_mode))
2739 req->work.flags |= IO_WQ_WORK_UNBOUND;
2744 static bool io_splice_punt(struct file *file)
2746 if (get_pipe_info(file))
2748 if (!io_file_supports_async(file))
2750 return !(file->f_mode & O_NONBLOCK);
2753 static int io_splice(struct io_kiocb *req, bool force_nonblock)
2755 struct io_splice *sp = &req->splice;
2756 struct file *in = sp->file_in;
2757 struct file *out = sp->file_out;
2758 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
2759 loff_t *poff_in, *poff_out;
2762 if (force_nonblock) {
2763 if (io_splice_punt(in) || io_splice_punt(out))
2765 flags |= SPLICE_F_NONBLOCK;
2768 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
2769 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
2770 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
2771 if (force_nonblock && ret == -EAGAIN)
2774 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
2775 req->flags &= ~REQ_F_NEED_CLEANUP;
2777 io_cqring_add_event(req, ret);
2779 req_set_fail_links(req);
2785 * IORING_OP_NOP just posts a completion event, nothing else.
2787 static int io_nop(struct io_kiocb *req)
2789 struct io_ring_ctx *ctx = req->ctx;
2791 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2794 io_cqring_add_event(req, 0);
2799 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2801 struct io_ring_ctx *ctx = req->ctx;
2806 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2808 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2811 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2812 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2815 req->sync.off = READ_ONCE(sqe->off);
2816 req->sync.len = READ_ONCE(sqe->len);
2820 static bool io_req_cancelled(struct io_kiocb *req)
2822 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2823 req_set_fail_links(req);
2824 io_cqring_add_event(req, -ECANCELED);
2832 static void __io_fsync(struct io_kiocb *req)
2834 loff_t end = req->sync.off + req->sync.len;
2837 ret = vfs_fsync_range(req->file, req->sync.off,
2838 end > 0 ? end : LLONG_MAX,
2839 req->sync.flags & IORING_FSYNC_DATASYNC);
2841 req_set_fail_links(req);
2842 io_cqring_add_event(req, ret);
2846 static void io_fsync_finish(struct io_wq_work **workptr)
2848 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2850 if (io_req_cancelled(req))
2853 io_steal_work(req, workptr);
2856 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
2858 /* fsync always requires a blocking context */
2859 if (force_nonblock) {
2860 req->work.func = io_fsync_finish;
2867 static void __io_fallocate(struct io_kiocb *req)
2871 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
2872 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2874 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
2876 req_set_fail_links(req);
2877 io_cqring_add_event(req, ret);
2881 static void io_fallocate_finish(struct io_wq_work **workptr)
2883 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2885 if (io_req_cancelled(req))
2887 __io_fallocate(req);
2888 io_steal_work(req, workptr);
2891 static int io_fallocate_prep(struct io_kiocb *req,
2892 const struct io_uring_sqe *sqe)
2894 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2897 req->sync.off = READ_ONCE(sqe->off);
2898 req->sync.len = READ_ONCE(sqe->addr);
2899 req->sync.mode = READ_ONCE(sqe->len);
2900 req->fsize = rlimit(RLIMIT_FSIZE);
2904 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
2906 /* fallocate always requiring blocking context */
2907 if (force_nonblock) {
2908 req->work.func = io_fallocate_finish;
2912 __io_fallocate(req);
2916 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2918 const char __user *fname;
2921 if (sqe->ioprio || sqe->buf_index)
2923 if (sqe->flags & IOSQE_FIXED_FILE)
2925 if (req->flags & REQ_F_NEED_CLEANUP)
2928 req->open.dfd = READ_ONCE(sqe->fd);
2929 req->open.how.mode = READ_ONCE(sqe->len);
2930 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2931 req->open.how.flags = READ_ONCE(sqe->open_flags);
2933 req->open.filename = getname(fname);
2934 if (IS_ERR(req->open.filename)) {
2935 ret = PTR_ERR(req->open.filename);
2936 req->open.filename = NULL;
2940 req->open.nofile = rlimit(RLIMIT_NOFILE);
2941 req->flags |= REQ_F_NEED_CLEANUP;
2945 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2947 struct open_how __user *how;
2948 const char __user *fname;
2952 if (sqe->ioprio || sqe->buf_index)
2954 if (sqe->flags & IOSQE_FIXED_FILE)
2956 if (req->flags & REQ_F_NEED_CLEANUP)
2959 req->open.dfd = READ_ONCE(sqe->fd);
2960 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2961 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2962 len = READ_ONCE(sqe->len);
2964 if (len < OPEN_HOW_SIZE_VER0)
2967 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2972 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2973 req->open.how.flags |= O_LARGEFILE;
2975 req->open.filename = getname(fname);
2976 if (IS_ERR(req->open.filename)) {
2977 ret = PTR_ERR(req->open.filename);
2978 req->open.filename = NULL;
2982 req->open.nofile = rlimit(RLIMIT_NOFILE);
2983 req->flags |= REQ_F_NEED_CLEANUP;
2987 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
2989 struct open_flags op;
2996 ret = build_open_flags(&req->open.how, &op);
3000 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3004 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3007 ret = PTR_ERR(file);
3009 fsnotify_open(file);
3010 fd_install(ret, file);
3013 putname(req->open.filename);
3014 req->flags &= ~REQ_F_NEED_CLEANUP;
3016 req_set_fail_links(req);
3017 io_cqring_add_event(req, ret);
3022 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3024 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
3025 return io_openat2(req, force_nonblock);
3028 static int io_remove_buffers_prep(struct io_kiocb *req,
3029 const struct io_uring_sqe *sqe)
3031 struct io_provide_buf *p = &req->pbuf;
3034 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3037 tmp = READ_ONCE(sqe->fd);
3038 if (!tmp || tmp > USHRT_MAX)
3041 memset(p, 0, sizeof(*p));
3043 p->bgid = READ_ONCE(sqe->buf_group);
3047 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3048 int bgid, unsigned nbufs)
3052 /* shouldn't happen */
3056 /* the head kbuf is the list itself */
3057 while (!list_empty(&buf->list)) {
3058 struct io_buffer *nxt;
3060 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3061 list_del(&nxt->list);
3068 idr_remove(&ctx->io_buffer_idr, bgid);
3073 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock)
3075 struct io_provide_buf *p = &req->pbuf;
3076 struct io_ring_ctx *ctx = req->ctx;
3077 struct io_buffer *head;
3080 io_ring_submit_lock(ctx, !force_nonblock);
3082 lockdep_assert_held(&ctx->uring_lock);
3085 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3087 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3089 io_ring_submit_lock(ctx, !force_nonblock);
3091 req_set_fail_links(req);
3092 io_cqring_add_event(req, ret);
3097 static int io_provide_buffers_prep(struct io_kiocb *req,
3098 const struct io_uring_sqe *sqe)
3100 struct io_provide_buf *p = &req->pbuf;
3103 if (sqe->ioprio || sqe->rw_flags)
3106 tmp = READ_ONCE(sqe->fd);
3107 if (!tmp || tmp > USHRT_MAX)
3110 p->addr = READ_ONCE(sqe->addr);
3111 p->len = READ_ONCE(sqe->len);
3113 if (!access_ok(u64_to_user_ptr(p->addr), p->len))
3116 p->bgid = READ_ONCE(sqe->buf_group);
3117 tmp = READ_ONCE(sqe->off);
3118 if (tmp > USHRT_MAX)
3124 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3126 struct io_buffer *buf;
3127 u64 addr = pbuf->addr;
3128 int i, bid = pbuf->bid;
3130 for (i = 0; i < pbuf->nbufs; i++) {
3131 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3136 buf->len = pbuf->len;
3141 INIT_LIST_HEAD(&buf->list);
3144 list_add_tail(&buf->list, &(*head)->list);
3148 return i ? i : -ENOMEM;
3151 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock)
3153 struct io_provide_buf *p = &req->pbuf;
3154 struct io_ring_ctx *ctx = req->ctx;
3155 struct io_buffer *head, *list;
3158 io_ring_submit_lock(ctx, !force_nonblock);
3160 lockdep_assert_held(&ctx->uring_lock);
3162 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3164 ret = io_add_buffers(p, &head);
3169 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3172 __io_remove_buffers(ctx, head, p->bgid, -1U);
3177 io_ring_submit_unlock(ctx, !force_nonblock);
3179 req_set_fail_links(req);
3180 io_cqring_add_event(req, ret);
3185 static int io_epoll_ctl_prep(struct io_kiocb *req,
3186 const struct io_uring_sqe *sqe)
3188 #if defined(CONFIG_EPOLL)
3189 if (sqe->ioprio || sqe->buf_index)
3192 req->epoll.epfd = READ_ONCE(sqe->fd);
3193 req->epoll.op = READ_ONCE(sqe->len);
3194 req->epoll.fd = READ_ONCE(sqe->off);
3196 if (ep_op_has_event(req->epoll.op)) {
3197 struct epoll_event __user *ev;
3199 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3200 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3210 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock)
3212 #if defined(CONFIG_EPOLL)
3213 struct io_epoll *ie = &req->epoll;
3216 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3217 if (force_nonblock && ret == -EAGAIN)
3221 req_set_fail_links(req);
3222 io_cqring_add_event(req, ret);
3230 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3232 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3233 if (sqe->ioprio || sqe->buf_index || sqe->off)
3236 req->madvise.addr = READ_ONCE(sqe->addr);
3237 req->madvise.len = READ_ONCE(sqe->len);
3238 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3245 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3247 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3248 struct io_madvise *ma = &req->madvise;
3254 ret = do_madvise(ma->addr, ma->len, ma->advice);
3256 req_set_fail_links(req);
3257 io_cqring_add_event(req, ret);
3265 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3267 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3270 req->fadvise.offset = READ_ONCE(sqe->off);
3271 req->fadvise.len = READ_ONCE(sqe->len);
3272 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3276 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3278 struct io_fadvise *fa = &req->fadvise;
3281 if (force_nonblock) {
3282 switch (fa->advice) {
3283 case POSIX_FADV_NORMAL:
3284 case POSIX_FADV_RANDOM:
3285 case POSIX_FADV_SEQUENTIAL:
3292 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3294 req_set_fail_links(req);
3295 io_cqring_add_event(req, ret);
3300 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3302 const char __user *fname;
3303 unsigned lookup_flags;
3306 if (sqe->ioprio || sqe->buf_index)
3308 if (sqe->flags & IOSQE_FIXED_FILE)
3310 if (req->flags & REQ_F_NEED_CLEANUP)
3313 req->open.dfd = READ_ONCE(sqe->fd);
3314 req->open.mask = READ_ONCE(sqe->len);
3315 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3316 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3317 req->open.how.flags = READ_ONCE(sqe->statx_flags);
3319 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
3322 req->open.filename = getname_flags(fname, lookup_flags, NULL);
3323 if (IS_ERR(req->open.filename)) {
3324 ret = PTR_ERR(req->open.filename);
3325 req->open.filename = NULL;
3329 req->flags |= REQ_F_NEED_CLEANUP;
3333 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3335 struct io_open *ctx = &req->open;
3336 unsigned lookup_flags;
3344 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
3348 /* filename_lookup() drops it, keep a reference */
3349 ctx->filename->refcnt++;
3351 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
3356 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
3358 if (retry_estale(ret, lookup_flags)) {
3359 lookup_flags |= LOOKUP_REVAL;
3363 ret = cp_statx(&stat, ctx->buffer);
3365 putname(ctx->filename);
3366 req->flags &= ~REQ_F_NEED_CLEANUP;
3368 req_set_fail_links(req);
3369 io_cqring_add_event(req, ret);
3374 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3377 * If we queue this for async, it must not be cancellable. That would
3378 * leave the 'file' in an undeterminate state.
3380 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3382 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3383 sqe->rw_flags || sqe->buf_index)
3385 if (sqe->flags & IOSQE_FIXED_FILE)
3388 req->close.fd = READ_ONCE(sqe->fd);
3389 if (req->file->f_op == &io_uring_fops ||
3390 req->close.fd == req->ctx->ring_fd)
3396 /* only called when __close_fd_get_file() is done */
3397 static void __io_close_finish(struct io_kiocb *req)
3401 ret = filp_close(req->close.put_file, req->work.files);
3403 req_set_fail_links(req);
3404 io_cqring_add_event(req, ret);
3405 fput(req->close.put_file);
3409 static void io_close_finish(struct io_wq_work **workptr)
3411 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3413 /* not cancellable, don't do io_req_cancelled() */
3414 __io_close_finish(req);
3415 io_steal_work(req, workptr);
3418 static int io_close(struct io_kiocb *req, bool force_nonblock)
3422 req->close.put_file = NULL;
3423 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
3427 /* if the file has a flush method, be safe and punt to async */
3428 if (req->close.put_file->f_op->flush && force_nonblock) {
3429 /* submission ref will be dropped, take it for async */
3430 refcount_inc(&req->refs);
3432 req->work.func = io_close_finish;
3434 * Do manual async queue here to avoid grabbing files - we don't
3435 * need the files, and it'll cause io_close_finish() to close
3436 * the file again and cause a double CQE entry for this request
3438 io_queue_async_work(req);
3443 * No ->flush(), safely close from here and just punt the
3444 * fput() to async context.
3446 __io_close_finish(req);
3450 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3452 struct io_ring_ctx *ctx = req->ctx;
3457 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3459 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3462 req->sync.off = READ_ONCE(sqe->off);
3463 req->sync.len = READ_ONCE(sqe->len);
3464 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3468 static void __io_sync_file_range(struct io_kiocb *req)
3472 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3475 req_set_fail_links(req);
3476 io_cqring_add_event(req, ret);
3481 static void io_sync_file_range_finish(struct io_wq_work **workptr)
3483 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3484 struct io_kiocb *nxt = NULL;
3486 if (io_req_cancelled(req))
3488 __io_sync_file_range(req);
3489 io_put_req(req); /* put submission ref */
3491 io_wq_assign_next(workptr, nxt);
3494 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3496 /* sync_file_range always requires a blocking context */
3497 if (force_nonblock) {
3498 req->work.func = io_sync_file_range_finish;
3502 __io_sync_file_range(req);
3506 #if defined(CONFIG_NET)
3507 static int io_setup_async_msg(struct io_kiocb *req,
3508 struct io_async_msghdr *kmsg)
3512 if (io_alloc_async_ctx(req)) {
3513 if (kmsg->iov != kmsg->fast_iov)
3517 req->flags |= REQ_F_NEED_CLEANUP;
3518 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3522 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3524 struct io_sr_msg *sr = &req->sr_msg;
3525 struct io_async_ctx *io = req->io;
3528 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3529 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3530 sr->len = READ_ONCE(sqe->len);
3532 #ifdef CONFIG_COMPAT
3533 if (req->ctx->compat)
3534 sr->msg_flags |= MSG_CMSG_COMPAT;
3537 if (!io || req->opcode == IORING_OP_SEND)
3539 /* iovec is already imported */
3540 if (req->flags & REQ_F_NEED_CLEANUP)
3543 io->msg.iov = io->msg.fast_iov;
3544 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3547 req->flags |= REQ_F_NEED_CLEANUP;
3551 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
3553 struct io_async_msghdr *kmsg = NULL;
3554 struct socket *sock;
3557 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3560 sock = sock_from_file(req->file, &ret);
3562 struct io_async_ctx io;
3566 kmsg = &req->io->msg;
3567 kmsg->msg.msg_name = &req->io->msg.addr;
3568 /* if iov is set, it's allocated already */
3570 kmsg->iov = kmsg->fast_iov;
3571 kmsg->msg.msg_iter.iov = kmsg->iov;
3573 struct io_sr_msg *sr = &req->sr_msg;
3576 kmsg->msg.msg_name = &io.msg.addr;
3578 io.msg.iov = io.msg.fast_iov;
3579 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3580 sr->msg_flags, &io.msg.iov);
3585 flags = req->sr_msg.msg_flags;
3586 if (flags & MSG_DONTWAIT)
3587 req->flags |= REQ_F_NOWAIT;
3588 else if (force_nonblock)
3589 flags |= MSG_DONTWAIT;
3591 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3592 if (force_nonblock && ret == -EAGAIN)
3593 return io_setup_async_msg(req, kmsg);
3594 if (ret == -ERESTARTSYS)
3598 if (kmsg && kmsg->iov != kmsg->fast_iov)
3600 req->flags &= ~REQ_F_NEED_CLEANUP;
3601 io_cqring_add_event(req, ret);
3603 req_set_fail_links(req);
3608 static int io_send(struct io_kiocb *req, bool force_nonblock)
3610 struct socket *sock;
3613 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3616 sock = sock_from_file(req->file, &ret);
3618 struct io_sr_msg *sr = &req->sr_msg;
3623 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3628 msg.msg_name = NULL;
3629 msg.msg_control = NULL;
3630 msg.msg_controllen = 0;
3631 msg.msg_namelen = 0;
3633 flags = req->sr_msg.msg_flags;
3634 if (flags & MSG_DONTWAIT)
3635 req->flags |= REQ_F_NOWAIT;
3636 else if (force_nonblock)
3637 flags |= MSG_DONTWAIT;
3639 msg.msg_flags = flags;
3640 ret = sock_sendmsg(sock, &msg);
3641 if (force_nonblock && ret == -EAGAIN)
3643 if (ret == -ERESTARTSYS)
3647 io_cqring_add_event(req, ret);
3649 req_set_fail_links(req);
3654 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3656 struct io_sr_msg *sr = &req->sr_msg;
3657 struct iovec __user *uiov;
3661 ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
3666 if (req->flags & REQ_F_BUFFER_SELECT) {
3669 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
3671 sr->len = io->msg.iov[0].iov_len;
3672 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
3676 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
3677 &io->msg.iov, &io->msg.msg.msg_iter);
3685 #ifdef CONFIG_COMPAT
3686 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
3687 struct io_async_ctx *io)
3689 struct compat_msghdr __user *msg_compat;
3690 struct io_sr_msg *sr = &req->sr_msg;
3691 struct compat_iovec __user *uiov;
3696 msg_compat = (struct compat_msghdr __user *) sr->msg;
3697 ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
3702 uiov = compat_ptr(ptr);
3703 if (req->flags & REQ_F_BUFFER_SELECT) {
3704 compat_ssize_t clen;
3708 if (!access_ok(uiov, sizeof(*uiov)))
3710 if (__get_user(clen, &uiov->iov_len))
3714 sr->len = io->msg.iov[0].iov_len;
3717 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
3719 &io->msg.msg.msg_iter);
3728 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3730 io->msg.iov = io->msg.fast_iov;
3732 #ifdef CONFIG_COMPAT
3733 if (req->ctx->compat)
3734 return __io_compat_recvmsg_copy_hdr(req, io);
3737 return __io_recvmsg_copy_hdr(req, io);
3740 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
3741 int *cflags, bool needs_lock)
3743 struct io_sr_msg *sr = &req->sr_msg;
3744 struct io_buffer *kbuf;
3746 if (!(req->flags & REQ_F_BUFFER_SELECT))
3749 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
3754 req->flags |= REQ_F_BUFFER_SELECTED;
3756 *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
3757 *cflags |= IORING_CQE_F_BUFFER;
3761 static int io_recvmsg_prep(struct io_kiocb *req,
3762 const struct io_uring_sqe *sqe)
3764 struct io_sr_msg *sr = &req->sr_msg;
3765 struct io_async_ctx *io = req->io;
3768 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3769 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3770 sr->len = READ_ONCE(sqe->len);
3771 sr->bgid = READ_ONCE(sqe->buf_group);
3773 #ifdef CONFIG_COMPAT
3774 if (req->ctx->compat)
3775 sr->msg_flags |= MSG_CMSG_COMPAT;
3778 if (!io || req->opcode == IORING_OP_RECV)
3780 /* iovec is already imported */
3781 if (req->flags & REQ_F_NEED_CLEANUP)
3784 ret = io_recvmsg_copy_hdr(req, io);
3786 req->flags |= REQ_F_NEED_CLEANUP;
3790 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
3792 struct io_async_msghdr *kmsg = NULL;
3793 struct socket *sock;
3794 int ret, cflags = 0;
3796 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3799 sock = sock_from_file(req->file, &ret);
3801 struct io_buffer *kbuf;
3802 struct io_async_ctx io;
3806 kmsg = &req->io->msg;
3807 kmsg->msg.msg_name = &req->io->msg.addr;
3808 /* if iov is set, it's allocated already */
3810 kmsg->iov = kmsg->fast_iov;
3811 kmsg->msg.msg_iter.iov = kmsg->iov;
3814 kmsg->msg.msg_name = &io.msg.addr;
3816 ret = io_recvmsg_copy_hdr(req, &io);
3821 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
3823 return PTR_ERR(kbuf);
3825 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3826 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
3827 1, req->sr_msg.len);
3830 flags = req->sr_msg.msg_flags;
3831 if (flags & MSG_DONTWAIT)
3832 req->flags |= REQ_F_NOWAIT;
3833 else if (force_nonblock)
3834 flags |= MSG_DONTWAIT;
3836 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3837 kmsg->uaddr, flags);
3838 if (force_nonblock && ret == -EAGAIN)
3839 return io_setup_async_msg(req, kmsg);
3840 if (ret == -ERESTARTSYS)
3844 if (kmsg && kmsg->iov != kmsg->fast_iov)
3846 req->flags &= ~REQ_F_NEED_CLEANUP;
3847 __io_cqring_add_event(req, ret, cflags);
3849 req_set_fail_links(req);
3854 static int io_recv(struct io_kiocb *req, bool force_nonblock)
3856 struct io_buffer *kbuf = NULL;
3857 struct socket *sock;
3858 int ret, cflags = 0;
3860 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3863 sock = sock_from_file(req->file, &ret);
3865 struct io_sr_msg *sr = &req->sr_msg;
3866 void __user *buf = sr->buf;
3871 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
3873 return PTR_ERR(kbuf);
3875 buf = u64_to_user_ptr(kbuf->addr);
3877 ret = import_single_range(READ, buf, sr->len, &iov,
3884 req->flags |= REQ_F_NEED_CLEANUP;
3885 msg.msg_name = NULL;
3886 msg.msg_control = NULL;
3887 msg.msg_controllen = 0;
3888 msg.msg_namelen = 0;
3889 msg.msg_iocb = NULL;
3892 flags = req->sr_msg.msg_flags;
3893 if (flags & MSG_DONTWAIT)
3894 req->flags |= REQ_F_NOWAIT;
3895 else if (force_nonblock)
3896 flags |= MSG_DONTWAIT;
3898 ret = sock_recvmsg(sock, &msg, flags);
3899 if (force_nonblock && ret == -EAGAIN)
3901 if (ret == -ERESTARTSYS)
3906 req->flags &= ~REQ_F_NEED_CLEANUP;
3907 __io_cqring_add_event(req, ret, cflags);
3909 req_set_fail_links(req);
3914 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3916 struct io_accept *accept = &req->accept;
3918 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3920 if (sqe->ioprio || sqe->len || sqe->buf_index)
3923 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3924 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3925 accept->flags = READ_ONCE(sqe->accept_flags);
3926 accept->nofile = rlimit(RLIMIT_NOFILE);
3930 static int __io_accept(struct io_kiocb *req, bool force_nonblock)
3932 struct io_accept *accept = &req->accept;
3933 unsigned file_flags;
3936 file_flags = force_nonblock ? O_NONBLOCK : 0;
3937 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3938 accept->addr_len, accept->flags,
3940 if (ret == -EAGAIN && force_nonblock)
3942 if (ret == -ERESTARTSYS)
3945 req_set_fail_links(req);
3946 io_cqring_add_event(req, ret);
3951 static void io_accept_finish(struct io_wq_work **workptr)
3953 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3955 if (io_req_cancelled(req))
3957 __io_accept(req, false);
3958 io_steal_work(req, workptr);
3961 static int io_accept(struct io_kiocb *req, bool force_nonblock)
3965 ret = __io_accept(req, force_nonblock);
3966 if (ret == -EAGAIN && force_nonblock) {
3967 req->work.func = io_accept_finish;
3973 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3975 struct io_connect *conn = &req->connect;
3976 struct io_async_ctx *io = req->io;
3978 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3980 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3983 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3984 conn->addr_len = READ_ONCE(sqe->addr2);
3989 return move_addr_to_kernel(conn->addr, conn->addr_len,
3990 &io->connect.address);
3993 static int io_connect(struct io_kiocb *req, bool force_nonblock)
3995 struct io_async_ctx __io, *io;
3996 unsigned file_flags;
4002 ret = move_addr_to_kernel(req->connect.addr,
4003 req->connect.addr_len,
4004 &__io.connect.address);
4010 file_flags = force_nonblock ? O_NONBLOCK : 0;
4012 ret = __sys_connect_file(req->file, &io->connect.address,
4013 req->connect.addr_len, file_flags);
4014 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4017 if (io_alloc_async_ctx(req)) {
4021 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4024 if (ret == -ERESTARTSYS)
4028 req_set_fail_links(req);
4029 io_cqring_add_event(req, ret);
4033 #else /* !CONFIG_NET */
4034 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4039 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
4044 static int io_send(struct io_kiocb *req, bool force_nonblock)
4049 static int io_recvmsg_prep(struct io_kiocb *req,
4050 const struct io_uring_sqe *sqe)
4055 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
4060 static int io_recv(struct io_kiocb *req, bool force_nonblock)
4065 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4070 static int io_accept(struct io_kiocb *req, bool force_nonblock)
4075 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4080 static int io_connect(struct io_kiocb *req, bool force_nonblock)
4084 #endif /* CONFIG_NET */
4086 struct io_poll_table {
4087 struct poll_table_struct pt;
4088 struct io_kiocb *req;
4092 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4093 struct wait_queue_head *head)
4095 if (unlikely(poll->head)) {
4096 pt->error = -EINVAL;
4102 add_wait_queue(head, &poll->wait);
4105 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4106 struct poll_table_struct *p)
4108 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4110 __io_queue_proc(&pt->req->apoll->poll, pt, head);
4113 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4114 __poll_t mask, task_work_func_t func)
4116 struct task_struct *tsk;
4118 /* for instances that support it check for an event match first: */
4119 if (mask && !(mask & poll->events))
4122 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4124 list_del_init(&poll->wait.entry);
4128 init_task_work(&req->task_work, func);
4130 * If this fails, then the task is exiting. If that is the case, then
4131 * the exit check will ultimately cancel these work items. Hence we
4132 * don't need to check here and handle it specifically.
4134 task_work_add(tsk, &req->task_work, true);
4135 wake_up_process(tsk);
4139 static void io_async_task_func(struct callback_head *cb)
4141 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4142 struct async_poll *apoll = req->apoll;
4143 struct io_ring_ctx *ctx = req->ctx;
4145 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4147 WARN_ON_ONCE(!list_empty(&req->apoll->poll.wait.entry));
4149 if (hash_hashed(&req->hash_node)) {
4150 spin_lock_irq(&ctx->completion_lock);
4151 hash_del(&req->hash_node);
4152 spin_unlock_irq(&ctx->completion_lock);
4155 /* restore ->work in case we need to retry again */
4156 memcpy(&req->work, &apoll->work, sizeof(req->work));
4158 __set_current_state(TASK_RUNNING);
4159 mutex_lock(&ctx->uring_lock);
4160 __io_queue_sqe(req, NULL);
4161 mutex_unlock(&ctx->uring_lock);
4166 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4169 struct io_kiocb *req = wait->private;
4170 struct io_poll_iocb *poll = &req->apoll->poll;
4172 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4175 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4178 static void io_poll_req_insert(struct io_kiocb *req)
4180 struct io_ring_ctx *ctx = req->ctx;
4181 struct hlist_head *list;
4183 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4184 hlist_add_head(&req->hash_node, list);
4187 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4188 struct io_poll_iocb *poll,
4189 struct io_poll_table *ipt, __poll_t mask,
4190 wait_queue_func_t wake_func)
4191 __acquires(&ctx->completion_lock)
4193 struct io_ring_ctx *ctx = req->ctx;
4194 bool cancel = false;
4196 poll->file = req->file;
4198 poll->done = poll->canceled = false;
4199 poll->events = mask;
4201 ipt->pt._key = mask;
4203 ipt->error = -EINVAL;
4205 INIT_LIST_HEAD(&poll->wait.entry);
4206 init_waitqueue_func_entry(&poll->wait, wake_func);
4207 poll->wait.private = req;
4209 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4211 spin_lock_irq(&ctx->completion_lock);
4212 if (likely(poll->head)) {
4213 spin_lock(&poll->head->lock);
4214 if (unlikely(list_empty(&poll->wait.entry))) {
4220 if (mask || ipt->error)
4221 list_del_init(&poll->wait.entry);
4223 WRITE_ONCE(poll->canceled, true);
4224 else if (!poll->done) /* actually waiting for an event */
4225 io_poll_req_insert(req);
4226 spin_unlock(&poll->head->lock);
4232 static bool io_arm_poll_handler(struct io_kiocb *req)
4234 const struct io_op_def *def = &io_op_defs[req->opcode];
4235 struct io_ring_ctx *ctx = req->ctx;
4236 struct async_poll *apoll;
4237 struct io_poll_table ipt;
4240 if (!req->file || !file_can_poll(req->file))
4242 if (req->flags & (REQ_F_MUST_PUNT | REQ_F_POLLED))
4244 if (!def->pollin && !def->pollout)
4247 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4248 if (unlikely(!apoll))
4251 req->flags |= REQ_F_POLLED;
4252 memcpy(&apoll->work, &req->work, sizeof(req->work));
4255 * Don't need a reference here, as we're adding it to the task
4256 * task_works list. If the task exits, the list is pruned.
4258 req->task = current;
4260 INIT_HLIST_NODE(&req->hash_node);
4264 mask |= POLLIN | POLLRDNORM;
4266 mask |= POLLOUT | POLLWRNORM;
4267 mask |= POLLERR | POLLPRI;
4269 ipt.pt._qproc = io_async_queue_proc;
4271 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4275 apoll->poll.done = true;
4276 spin_unlock_irq(&ctx->completion_lock);
4277 memcpy(&req->work, &apoll->work, sizeof(req->work));
4281 spin_unlock_irq(&ctx->completion_lock);
4282 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4283 apoll->poll.events);
4287 static bool __io_poll_remove_one(struct io_kiocb *req,
4288 struct io_poll_iocb *poll)
4290 bool do_complete = false;
4292 spin_lock(&poll->head->lock);
4293 WRITE_ONCE(poll->canceled, true);
4294 if (!list_empty(&poll->wait.entry)) {
4295 list_del_init(&poll->wait.entry);
4298 spin_unlock(&poll->head->lock);
4302 static bool io_poll_remove_one(struct io_kiocb *req)
4306 if (req->opcode == IORING_OP_POLL_ADD) {
4307 do_complete = __io_poll_remove_one(req, &req->poll);
4309 /* non-poll requests have submit ref still */
4310 do_complete = __io_poll_remove_one(req, &req->apoll->poll);
4315 hash_del(&req->hash_node);
4318 io_cqring_fill_event(req, -ECANCELED);
4319 io_commit_cqring(req->ctx);
4320 req->flags |= REQ_F_COMP_LOCKED;
4327 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4329 struct hlist_node *tmp;
4330 struct io_kiocb *req;
4333 spin_lock_irq(&ctx->completion_lock);
4334 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4335 struct hlist_head *list;
4337 list = &ctx->cancel_hash[i];
4338 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4339 io_poll_remove_one(req);
4341 spin_unlock_irq(&ctx->completion_lock);
4343 io_cqring_ev_posted(ctx);
4346 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4348 struct hlist_head *list;
4349 struct io_kiocb *req;
4351 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4352 hlist_for_each_entry(req, list, hash_node) {
4353 if (sqe_addr != req->user_data)
4355 if (io_poll_remove_one(req))
4363 static int io_poll_remove_prep(struct io_kiocb *req,
4364 const struct io_uring_sqe *sqe)
4366 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4368 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4372 req->poll.addr = READ_ONCE(sqe->addr);
4377 * Find a running poll command that matches one specified in sqe->addr,
4378 * and remove it if found.
4380 static int io_poll_remove(struct io_kiocb *req)
4382 struct io_ring_ctx *ctx = req->ctx;
4386 addr = req->poll.addr;
4387 spin_lock_irq(&ctx->completion_lock);
4388 ret = io_poll_cancel(ctx, addr);
4389 spin_unlock_irq(&ctx->completion_lock);
4391 io_cqring_add_event(req, ret);
4393 req_set_fail_links(req);
4398 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4400 struct io_ring_ctx *ctx = req->ctx;
4402 req->poll.done = true;
4403 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4404 io_commit_cqring(ctx);
4407 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4409 struct io_ring_ctx *ctx = req->ctx;
4411 spin_lock_irq(&ctx->completion_lock);
4412 hash_del(&req->hash_node);
4413 io_poll_complete(req, req->result, 0);
4414 req->flags |= REQ_F_COMP_LOCKED;
4415 io_put_req_find_next(req, nxt);
4416 spin_unlock_irq(&ctx->completion_lock);
4418 io_cqring_ev_posted(ctx);
4421 static void io_poll_task_func(struct callback_head *cb)
4423 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4424 struct io_kiocb *nxt = NULL;
4426 io_poll_task_handler(req, &nxt);
4428 struct io_ring_ctx *ctx = nxt->ctx;
4430 mutex_lock(&ctx->uring_lock);
4431 __io_queue_sqe(nxt, NULL);
4432 mutex_unlock(&ctx->uring_lock);
4436 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4439 struct io_kiocb *req = wait->private;
4440 struct io_poll_iocb *poll = &req->poll;
4442 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4445 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4446 struct poll_table_struct *p)
4448 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4450 __io_queue_proc(&pt->req->poll, pt, head);
4453 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4455 struct io_poll_iocb *poll = &req->poll;
4458 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4460 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4465 events = READ_ONCE(sqe->poll_events);
4466 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
4469 * Don't need a reference here, as we're adding it to the task
4470 * task_works list. If the task exits, the list is pruned.
4472 req->task = current;
4476 static int io_poll_add(struct io_kiocb *req)
4478 struct io_poll_iocb *poll = &req->poll;
4479 struct io_ring_ctx *ctx = req->ctx;
4480 struct io_poll_table ipt;
4483 INIT_HLIST_NODE(&req->hash_node);
4484 INIT_LIST_HEAD(&req->list);
4485 ipt.pt._qproc = io_poll_queue_proc;
4487 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4490 if (mask) { /* no async, we'd stolen it */
4492 io_poll_complete(req, mask, 0);
4494 spin_unlock_irq(&ctx->completion_lock);
4497 io_cqring_ev_posted(ctx);
4503 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4505 struct io_timeout_data *data = container_of(timer,
4506 struct io_timeout_data, timer);
4507 struct io_kiocb *req = data->req;
4508 struct io_ring_ctx *ctx = req->ctx;
4509 unsigned long flags;
4511 atomic_inc(&ctx->cq_timeouts);
4513 spin_lock_irqsave(&ctx->completion_lock, flags);
4515 * We could be racing with timeout deletion. If the list is empty,
4516 * then timeout lookup already found it and will be handling it.
4518 if (!list_empty(&req->list)) {
4519 struct io_kiocb *prev;
4522 * Adjust the reqs sequence before the current one because it
4523 * will consume a slot in the cq_ring and the cq_tail
4524 * pointer will be increased, otherwise other timeout reqs may
4525 * return in advance without waiting for enough wait_nr.
4528 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
4530 list_del_init(&req->list);
4533 io_cqring_fill_event(req, -ETIME);
4534 io_commit_cqring(ctx);
4535 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4537 io_cqring_ev_posted(ctx);
4538 req_set_fail_links(req);
4540 return HRTIMER_NORESTART;
4543 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4545 struct io_kiocb *req;
4548 list_for_each_entry(req, &ctx->timeout_list, list) {
4549 if (user_data == req->user_data) {
4550 list_del_init(&req->list);
4559 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
4563 req_set_fail_links(req);
4564 io_cqring_fill_event(req, -ECANCELED);
4569 static int io_timeout_remove_prep(struct io_kiocb *req,
4570 const struct io_uring_sqe *sqe)
4572 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4574 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
4577 req->timeout.addr = READ_ONCE(sqe->addr);
4578 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4579 if (req->timeout.flags)
4586 * Remove or update an existing timeout command
4588 static int io_timeout_remove(struct io_kiocb *req)
4590 struct io_ring_ctx *ctx = req->ctx;
4593 spin_lock_irq(&ctx->completion_lock);
4594 ret = io_timeout_cancel(ctx, req->timeout.addr);
4596 io_cqring_fill_event(req, ret);
4597 io_commit_cqring(ctx);
4598 spin_unlock_irq(&ctx->completion_lock);
4599 io_cqring_ev_posted(ctx);
4601 req_set_fail_links(req);
4606 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4607 bool is_timeout_link)
4609 struct io_timeout_data *data;
4612 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4614 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
4616 if (sqe->off && is_timeout_link)
4618 flags = READ_ONCE(sqe->timeout_flags);
4619 if (flags & ~IORING_TIMEOUT_ABS)
4622 req->timeout.count = READ_ONCE(sqe->off);
4624 if (!req->io && io_alloc_async_ctx(req))
4627 data = &req->io->timeout;
4629 req->flags |= REQ_F_TIMEOUT;
4631 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
4634 if (flags & IORING_TIMEOUT_ABS)
4635 data->mode = HRTIMER_MODE_ABS;
4637 data->mode = HRTIMER_MODE_REL;
4639 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
4643 static int io_timeout(struct io_kiocb *req)
4646 struct io_ring_ctx *ctx = req->ctx;
4647 struct io_timeout_data *data;
4648 struct list_head *entry;
4651 data = &req->io->timeout;
4654 * sqe->off holds how many events that need to occur for this
4655 * timeout event to be satisfied. If it isn't set, then this is
4656 * a pure timeout request, sequence isn't used.
4658 count = req->timeout.count;
4660 req->flags |= REQ_F_TIMEOUT_NOSEQ;
4661 spin_lock_irq(&ctx->completion_lock);
4662 entry = ctx->timeout_list.prev;
4666 req->sequence = ctx->cached_sq_head + count - 1;
4667 data->seq_offset = count;
4670 * Insertion sort, ensuring the first entry in the list is always
4671 * the one we need first.
4673 spin_lock_irq(&ctx->completion_lock);
4674 list_for_each_prev(entry, &ctx->timeout_list) {
4675 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
4676 unsigned nxt_sq_head;
4677 long long tmp, tmp_nxt;
4678 u32 nxt_offset = nxt->io->timeout.seq_offset;
4680 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
4684 * Since cached_sq_head + count - 1 can overflow, use type long
4687 tmp = (long long)ctx->cached_sq_head + count - 1;
4688 nxt_sq_head = nxt->sequence - nxt_offset + 1;
4689 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
4692 * cached_sq_head may overflow, and it will never overflow twice
4693 * once there is some timeout req still be valid.
4695 if (ctx->cached_sq_head < nxt_sq_head)
4702 * Sequence of reqs after the insert one and itself should
4703 * be adjusted because each timeout req consumes a slot.
4708 req->sequence -= span;
4710 list_add(&req->list, entry);
4711 data->timer.function = io_timeout_fn;
4712 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
4713 spin_unlock_irq(&ctx->completion_lock);
4717 static bool io_cancel_cb(struct io_wq_work *work, void *data)
4719 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4721 return req->user_data == (unsigned long) data;
4724 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
4726 enum io_wq_cancel cancel_ret;
4729 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
4730 switch (cancel_ret) {
4731 case IO_WQ_CANCEL_OK:
4734 case IO_WQ_CANCEL_RUNNING:
4737 case IO_WQ_CANCEL_NOTFOUND:
4745 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4746 struct io_kiocb *req, __u64 sqe_addr,
4749 unsigned long flags;
4752 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4753 if (ret != -ENOENT) {
4754 spin_lock_irqsave(&ctx->completion_lock, flags);
4758 spin_lock_irqsave(&ctx->completion_lock, flags);
4759 ret = io_timeout_cancel(ctx, sqe_addr);
4762 ret = io_poll_cancel(ctx, sqe_addr);
4766 io_cqring_fill_event(req, ret);
4767 io_commit_cqring(ctx);
4768 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4769 io_cqring_ev_posted(ctx);
4772 req_set_fail_links(req);
4776 static int io_async_cancel_prep(struct io_kiocb *req,
4777 const struct io_uring_sqe *sqe)
4779 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4781 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4785 req->cancel.addr = READ_ONCE(sqe->addr);
4789 static int io_async_cancel(struct io_kiocb *req)
4791 struct io_ring_ctx *ctx = req->ctx;
4793 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
4797 static int io_files_update_prep(struct io_kiocb *req,
4798 const struct io_uring_sqe *sqe)
4800 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4803 req->files_update.offset = READ_ONCE(sqe->off);
4804 req->files_update.nr_args = READ_ONCE(sqe->len);
4805 if (!req->files_update.nr_args)
4807 req->files_update.arg = READ_ONCE(sqe->addr);
4811 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
4813 struct io_ring_ctx *ctx = req->ctx;
4814 struct io_uring_files_update up;
4820 up.offset = req->files_update.offset;
4821 up.fds = req->files_update.arg;
4823 mutex_lock(&ctx->uring_lock);
4824 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4825 mutex_unlock(&ctx->uring_lock);
4828 req_set_fail_links(req);
4829 io_cqring_add_event(req, ret);
4834 static int io_req_defer_prep(struct io_kiocb *req,
4835 const struct io_uring_sqe *sqe)
4842 if (io_op_defs[req->opcode].file_table) {
4843 ret = io_grab_files(req);
4848 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4850 switch (req->opcode) {
4853 case IORING_OP_READV:
4854 case IORING_OP_READ_FIXED:
4855 case IORING_OP_READ:
4856 ret = io_read_prep(req, sqe, true);
4858 case IORING_OP_WRITEV:
4859 case IORING_OP_WRITE_FIXED:
4860 case IORING_OP_WRITE:
4861 ret = io_write_prep(req, sqe, true);
4863 case IORING_OP_POLL_ADD:
4864 ret = io_poll_add_prep(req, sqe);
4866 case IORING_OP_POLL_REMOVE:
4867 ret = io_poll_remove_prep(req, sqe);
4869 case IORING_OP_FSYNC:
4870 ret = io_prep_fsync(req, sqe);
4872 case IORING_OP_SYNC_FILE_RANGE:
4873 ret = io_prep_sfr(req, sqe);
4875 case IORING_OP_SENDMSG:
4876 case IORING_OP_SEND:
4877 ret = io_sendmsg_prep(req, sqe);
4879 case IORING_OP_RECVMSG:
4880 case IORING_OP_RECV:
4881 ret = io_recvmsg_prep(req, sqe);
4883 case IORING_OP_CONNECT:
4884 ret = io_connect_prep(req, sqe);
4886 case IORING_OP_TIMEOUT:
4887 ret = io_timeout_prep(req, sqe, false);
4889 case IORING_OP_TIMEOUT_REMOVE:
4890 ret = io_timeout_remove_prep(req, sqe);
4892 case IORING_OP_ASYNC_CANCEL:
4893 ret = io_async_cancel_prep(req, sqe);
4895 case IORING_OP_LINK_TIMEOUT:
4896 ret = io_timeout_prep(req, sqe, true);
4898 case IORING_OP_ACCEPT:
4899 ret = io_accept_prep(req, sqe);
4901 case IORING_OP_FALLOCATE:
4902 ret = io_fallocate_prep(req, sqe);
4904 case IORING_OP_OPENAT:
4905 ret = io_openat_prep(req, sqe);
4907 case IORING_OP_CLOSE:
4908 ret = io_close_prep(req, sqe);
4910 case IORING_OP_FILES_UPDATE:
4911 ret = io_files_update_prep(req, sqe);
4913 case IORING_OP_STATX:
4914 ret = io_statx_prep(req, sqe);
4916 case IORING_OP_FADVISE:
4917 ret = io_fadvise_prep(req, sqe);
4919 case IORING_OP_MADVISE:
4920 ret = io_madvise_prep(req, sqe);
4922 case IORING_OP_OPENAT2:
4923 ret = io_openat2_prep(req, sqe);
4925 case IORING_OP_EPOLL_CTL:
4926 ret = io_epoll_ctl_prep(req, sqe);
4928 case IORING_OP_SPLICE:
4929 ret = io_splice_prep(req, sqe);
4931 case IORING_OP_PROVIDE_BUFFERS:
4932 ret = io_provide_buffers_prep(req, sqe);
4934 case IORING_OP_REMOVE_BUFFERS:
4935 ret = io_remove_buffers_prep(req, sqe);
4938 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4947 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4949 struct io_ring_ctx *ctx = req->ctx;
4952 /* Still need defer if there is pending req in defer list. */
4953 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
4956 if (!req->io && io_alloc_async_ctx(req))
4959 ret = io_req_defer_prep(req, sqe);
4963 spin_lock_irq(&ctx->completion_lock);
4964 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
4965 spin_unlock_irq(&ctx->completion_lock);
4969 trace_io_uring_defer(ctx, req, req->user_data);
4970 list_add_tail(&req->list, &ctx->defer_list);
4971 spin_unlock_irq(&ctx->completion_lock);
4972 return -EIOCBQUEUED;
4975 static void io_cleanup_req(struct io_kiocb *req)
4977 struct io_async_ctx *io = req->io;
4979 switch (req->opcode) {
4980 case IORING_OP_READV:
4981 case IORING_OP_READ_FIXED:
4982 case IORING_OP_READ:
4983 if (req->flags & REQ_F_BUFFER_SELECTED)
4984 kfree((void *)(unsigned long)req->rw.addr);
4986 case IORING_OP_WRITEV:
4987 case IORING_OP_WRITE_FIXED:
4988 case IORING_OP_WRITE:
4989 if (io->rw.iov != io->rw.fast_iov)
4992 case IORING_OP_RECVMSG:
4993 if (req->flags & REQ_F_BUFFER_SELECTED)
4994 kfree(req->sr_msg.kbuf);
4996 case IORING_OP_SENDMSG:
4997 if (io->msg.iov != io->msg.fast_iov)
5000 case IORING_OP_RECV:
5001 if (req->flags & REQ_F_BUFFER_SELECTED)
5002 kfree(req->sr_msg.kbuf);
5004 case IORING_OP_OPENAT:
5005 case IORING_OP_OPENAT2:
5006 case IORING_OP_STATX:
5007 putname(req->open.filename);
5009 case IORING_OP_SPLICE:
5010 io_put_file(req, req->splice.file_in,
5011 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5015 req->flags &= ~REQ_F_NEED_CLEANUP;
5018 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5019 bool force_nonblock)
5021 struct io_ring_ctx *ctx = req->ctx;
5024 switch (req->opcode) {
5028 case IORING_OP_READV:
5029 case IORING_OP_READ_FIXED:
5030 case IORING_OP_READ:
5032 ret = io_read_prep(req, sqe, force_nonblock);
5036 ret = io_read(req, force_nonblock);
5038 case IORING_OP_WRITEV:
5039 case IORING_OP_WRITE_FIXED:
5040 case IORING_OP_WRITE:
5042 ret = io_write_prep(req, sqe, force_nonblock);
5046 ret = io_write(req, force_nonblock);
5048 case IORING_OP_FSYNC:
5050 ret = io_prep_fsync(req, sqe);
5054 ret = io_fsync(req, force_nonblock);
5056 case IORING_OP_POLL_ADD:
5058 ret = io_poll_add_prep(req, sqe);
5062 ret = io_poll_add(req);
5064 case IORING_OP_POLL_REMOVE:
5066 ret = io_poll_remove_prep(req, sqe);
5070 ret = io_poll_remove(req);
5072 case IORING_OP_SYNC_FILE_RANGE:
5074 ret = io_prep_sfr(req, sqe);
5078 ret = io_sync_file_range(req, force_nonblock);
5080 case IORING_OP_SENDMSG:
5081 case IORING_OP_SEND:
5083 ret = io_sendmsg_prep(req, sqe);
5087 if (req->opcode == IORING_OP_SENDMSG)
5088 ret = io_sendmsg(req, force_nonblock);
5090 ret = io_send(req, force_nonblock);
5092 case IORING_OP_RECVMSG:
5093 case IORING_OP_RECV:
5095 ret = io_recvmsg_prep(req, sqe);
5099 if (req->opcode == IORING_OP_RECVMSG)
5100 ret = io_recvmsg(req, force_nonblock);
5102 ret = io_recv(req, force_nonblock);
5104 case IORING_OP_TIMEOUT:
5106 ret = io_timeout_prep(req, sqe, false);
5110 ret = io_timeout(req);
5112 case IORING_OP_TIMEOUT_REMOVE:
5114 ret = io_timeout_remove_prep(req, sqe);
5118 ret = io_timeout_remove(req);
5120 case IORING_OP_ACCEPT:
5122 ret = io_accept_prep(req, sqe);
5126 ret = io_accept(req, force_nonblock);
5128 case IORING_OP_CONNECT:
5130 ret = io_connect_prep(req, sqe);
5134 ret = io_connect(req, force_nonblock);
5136 case IORING_OP_ASYNC_CANCEL:
5138 ret = io_async_cancel_prep(req, sqe);
5142 ret = io_async_cancel(req);
5144 case IORING_OP_FALLOCATE:
5146 ret = io_fallocate_prep(req, sqe);
5150 ret = io_fallocate(req, force_nonblock);
5152 case IORING_OP_OPENAT:
5154 ret = io_openat_prep(req, sqe);
5158 ret = io_openat(req, force_nonblock);
5160 case IORING_OP_CLOSE:
5162 ret = io_close_prep(req, sqe);
5166 ret = io_close(req, force_nonblock);
5168 case IORING_OP_FILES_UPDATE:
5170 ret = io_files_update_prep(req, sqe);
5174 ret = io_files_update(req, force_nonblock);
5176 case IORING_OP_STATX:
5178 ret = io_statx_prep(req, sqe);
5182 ret = io_statx(req, force_nonblock);
5184 case IORING_OP_FADVISE:
5186 ret = io_fadvise_prep(req, sqe);
5190 ret = io_fadvise(req, force_nonblock);
5192 case IORING_OP_MADVISE:
5194 ret = io_madvise_prep(req, sqe);
5198 ret = io_madvise(req, force_nonblock);
5200 case IORING_OP_OPENAT2:
5202 ret = io_openat2_prep(req, sqe);
5206 ret = io_openat2(req, force_nonblock);
5208 case IORING_OP_EPOLL_CTL:
5210 ret = io_epoll_ctl_prep(req, sqe);
5214 ret = io_epoll_ctl(req, force_nonblock);
5216 case IORING_OP_SPLICE:
5218 ret = io_splice_prep(req, sqe);
5222 ret = io_splice(req, force_nonblock);
5224 case IORING_OP_PROVIDE_BUFFERS:
5226 ret = io_provide_buffers_prep(req, sqe);
5230 ret = io_provide_buffers(req, force_nonblock);
5232 case IORING_OP_REMOVE_BUFFERS:
5234 ret = io_remove_buffers_prep(req, sqe);
5238 ret = io_remove_buffers(req, force_nonblock);
5248 if (ctx->flags & IORING_SETUP_IOPOLL) {
5249 const bool in_async = io_wq_current_is_worker();
5251 if (req->result == -EAGAIN)
5254 /* workqueue context doesn't hold uring_lock, grab it now */
5256 mutex_lock(&ctx->uring_lock);
5258 io_iopoll_req_issued(req);
5261 mutex_unlock(&ctx->uring_lock);
5267 static void io_wq_submit_work(struct io_wq_work **workptr)
5269 struct io_wq_work *work = *workptr;
5270 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5273 /* if NO_CANCEL is set, we must still run the work */
5274 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5275 IO_WQ_WORK_CANCEL) {
5281 ret = io_issue_sqe(req, NULL, false);
5283 * We can get EAGAIN for polled IO even though we're
5284 * forcing a sync submission from here, since we can't
5285 * wait for request slots on the block side.
5294 req_set_fail_links(req);
5295 io_cqring_add_event(req, ret);
5299 io_steal_work(req, workptr);
5302 static int io_req_needs_file(struct io_kiocb *req, int fd)
5304 if (!io_op_defs[req->opcode].needs_file)
5306 if ((fd == -1 || fd == AT_FDCWD) && io_op_defs[req->opcode].fd_non_neg)
5311 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5314 struct fixed_file_table *table;
5316 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5317 return table->files[index & IORING_FILE_TABLE_MASK];;
5320 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5321 int fd, struct file **out_file, bool fixed)
5323 struct io_ring_ctx *ctx = req->ctx;
5327 if (unlikely(!ctx->file_data ||
5328 (unsigned) fd >= ctx->nr_user_files))
5330 fd = array_index_nospec(fd, ctx->nr_user_files);
5331 file = io_file_from_index(ctx, fd);
5334 percpu_ref_get(&ctx->file_data->refs);
5336 trace_io_uring_file_get(ctx, fd);
5337 file = __io_file_get(state, fd);
5338 if (unlikely(!file))
5346 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5347 const struct io_uring_sqe *sqe)
5353 flags = READ_ONCE(sqe->flags);
5354 fd = READ_ONCE(sqe->fd);
5356 if (!io_req_needs_file(req, fd))
5359 fixed = (flags & IOSQE_FIXED_FILE);
5360 if (unlikely(!fixed && req->needs_fixed_file))
5363 return io_file_get(state, req, fd, &req->file, fixed);
5366 static int io_grab_files(struct io_kiocb *req)
5369 struct io_ring_ctx *ctx = req->ctx;
5371 if (req->work.files)
5373 if (!ctx->ring_file)
5377 spin_lock_irq(&ctx->inflight_lock);
5379 * We use the f_ops->flush() handler to ensure that we can flush
5380 * out work accessing these files if the fd is closed. Check if
5381 * the fd has changed since we started down this path, and disallow
5382 * this operation if it has.
5384 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5385 list_add(&req->inflight_entry, &ctx->inflight_list);
5386 req->flags |= REQ_F_INFLIGHT;
5387 req->work.files = current->files;
5390 spin_unlock_irq(&ctx->inflight_lock);
5396 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5398 struct io_timeout_data *data = container_of(timer,
5399 struct io_timeout_data, timer);
5400 struct io_kiocb *req = data->req;
5401 struct io_ring_ctx *ctx = req->ctx;
5402 struct io_kiocb *prev = NULL;
5403 unsigned long flags;
5405 spin_lock_irqsave(&ctx->completion_lock, flags);
5408 * We don't expect the list to be empty, that will only happen if we
5409 * race with the completion of the linked work.
5411 if (!list_empty(&req->link_list)) {
5412 prev = list_entry(req->link_list.prev, struct io_kiocb,
5414 if (refcount_inc_not_zero(&prev->refs)) {
5415 list_del_init(&req->link_list);
5416 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5421 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5424 req_set_fail_links(prev);
5425 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5428 io_cqring_add_event(req, -ETIME);
5431 return HRTIMER_NORESTART;
5434 static void io_queue_linked_timeout(struct io_kiocb *req)
5436 struct io_ring_ctx *ctx = req->ctx;
5439 * If the list is now empty, then our linked request finished before
5440 * we got a chance to setup the timer
5442 spin_lock_irq(&ctx->completion_lock);
5443 if (!list_empty(&req->link_list)) {
5444 struct io_timeout_data *data = &req->io->timeout;
5446 data->timer.function = io_link_timeout_fn;
5447 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5450 spin_unlock_irq(&ctx->completion_lock);
5452 /* drop submission reference */
5456 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5458 struct io_kiocb *nxt;
5460 if (!(req->flags & REQ_F_LINK))
5462 /* for polled retry, if flag is set, we already went through here */
5463 if (req->flags & REQ_F_POLLED)
5466 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5468 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5471 req->flags |= REQ_F_LINK_TIMEOUT;
5475 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5477 struct io_kiocb *linked_timeout;
5478 struct io_kiocb *nxt;
5479 const struct cred *old_creds = NULL;
5483 linked_timeout = io_prep_linked_timeout(req);
5485 if (req->work.creds && req->work.creds != current_cred()) {
5487 revert_creds(old_creds);
5488 if (old_creds == req->work.creds)
5489 old_creds = NULL; /* restored original creds */
5491 old_creds = override_creds(req->work.creds);
5494 ret = io_issue_sqe(req, sqe, true);
5497 * We async punt it if the file wasn't marked NOWAIT, or if the file
5498 * doesn't support non-blocking read/write attempts
5500 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
5501 (req->flags & REQ_F_MUST_PUNT))) {
5502 if (io_arm_poll_handler(req)) {
5504 io_queue_linked_timeout(linked_timeout);
5508 if (io_op_defs[req->opcode].file_table) {
5509 ret = io_grab_files(req);
5515 * Queued up for async execution, worker will release
5516 * submit reference when the iocb is actually submitted.
5518 io_queue_async_work(req);
5524 /* drop submission reference */
5525 io_put_req_find_next(req, &nxt);
5527 if (linked_timeout) {
5529 io_queue_linked_timeout(linked_timeout);
5531 io_put_req(linked_timeout);
5534 /* and drop final reference, if we failed */
5536 io_cqring_add_event(req, ret);
5537 req_set_fail_links(req);
5543 if (req->flags & REQ_F_FORCE_ASYNC)
5549 revert_creds(old_creds);
5552 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5556 ret = io_req_defer(req, sqe);
5558 if (ret != -EIOCBQUEUED) {
5560 io_cqring_add_event(req, ret);
5561 req_set_fail_links(req);
5562 io_double_put_req(req);
5564 } else if (req->flags & REQ_F_FORCE_ASYNC) {
5565 ret = io_req_defer_prep(req, sqe);
5566 if (unlikely(ret < 0))
5569 * Never try inline submit of IOSQE_ASYNC is set, go straight
5570 * to async execution.
5572 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5573 io_queue_async_work(req);
5575 __io_queue_sqe(req, sqe);
5579 static inline void io_queue_link_head(struct io_kiocb *req)
5581 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
5582 io_cqring_add_event(req, -ECANCELED);
5583 io_double_put_req(req);
5585 io_queue_sqe(req, NULL);
5588 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
5589 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
5590 IOSQE_BUFFER_SELECT)
5592 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5593 struct io_submit_state *state, struct io_kiocb **link)
5595 struct io_ring_ctx *ctx = req->ctx;
5596 unsigned int sqe_flags;
5599 sqe_flags = READ_ONCE(sqe->flags);
5601 /* enforce forwards compatibility on users */
5602 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
5607 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
5608 !io_op_defs[req->opcode].buffer_select) {
5613 id = READ_ONCE(sqe->personality);
5615 req->work.creds = idr_find(&ctx->personality_idr, id);
5616 if (unlikely(!req->work.creds)) {
5620 get_cred(req->work.creds);
5623 /* same numerical values with corresponding REQ_F_*, safe to copy */
5624 req->flags |= sqe_flags & (IOSQE_IO_DRAIN | IOSQE_IO_HARDLINK |
5625 IOSQE_ASYNC | IOSQE_FIXED_FILE |
5626 IOSQE_BUFFER_SELECT);
5628 ret = io_req_set_file(state, req, sqe);
5629 if (unlikely(ret)) {
5631 io_cqring_add_event(req, ret);
5632 io_double_put_req(req);
5637 * If we already have a head request, queue this one for async
5638 * submittal once the head completes. If we don't have a head but
5639 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
5640 * submitted sync once the chain is complete. If none of those
5641 * conditions are true (normal request), then just queue it.
5644 struct io_kiocb *head = *link;
5647 * Taking sequential execution of a link, draining both sides
5648 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
5649 * requests in the link. So, it drains the head and the
5650 * next after the link request. The last one is done via
5651 * drain_next flag to persist the effect across calls.
5653 if (sqe_flags & IOSQE_IO_DRAIN) {
5654 head->flags |= REQ_F_IO_DRAIN;
5655 ctx->drain_next = 1;
5657 if (io_alloc_async_ctx(req)) {
5662 ret = io_req_defer_prep(req, sqe);
5664 /* fail even hard links since we don't submit */
5665 head->flags |= REQ_F_FAIL_LINK;
5668 trace_io_uring_link(ctx, req, head);
5669 list_add_tail(&req->link_list, &head->link_list);
5671 /* last request of a link, enqueue the link */
5672 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
5673 io_queue_link_head(head);
5677 if (unlikely(ctx->drain_next)) {
5678 req->flags |= REQ_F_IO_DRAIN;
5679 req->ctx->drain_next = 0;
5681 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
5682 req->flags |= REQ_F_LINK;
5683 INIT_LIST_HEAD(&req->link_list);
5685 if (io_alloc_async_ctx(req)) {
5689 ret = io_req_defer_prep(req, sqe);
5691 req->flags |= REQ_F_FAIL_LINK;
5694 io_queue_sqe(req, sqe);
5702 * Batched submission is done, ensure local IO is flushed out.
5704 static void io_submit_state_end(struct io_submit_state *state)
5706 blk_finish_plug(&state->plug);
5708 if (state->free_reqs)
5709 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
5713 * Start submission side cache.
5715 static void io_submit_state_start(struct io_submit_state *state,
5716 unsigned int max_ios)
5718 blk_start_plug(&state->plug);
5719 state->free_reqs = 0;
5721 state->ios_left = max_ios;
5724 static void io_commit_sqring(struct io_ring_ctx *ctx)
5726 struct io_rings *rings = ctx->rings;
5729 * Ensure any loads from the SQEs are done at this point,
5730 * since once we write the new head, the application could
5731 * write new data to them.
5733 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
5737 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
5738 * that is mapped by userspace. This means that care needs to be taken to
5739 * ensure that reads are stable, as we cannot rely on userspace always
5740 * being a good citizen. If members of the sqe are validated and then later
5741 * used, it's important that those reads are done through READ_ONCE() to
5742 * prevent a re-load down the line.
5744 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
5745 const struct io_uring_sqe **sqe_ptr)
5747 u32 *sq_array = ctx->sq_array;
5751 * The cached sq head (or cq tail) serves two purposes:
5753 * 1) allows us to batch the cost of updating the user visible
5755 * 2) allows the kernel side to track the head on its own, even
5756 * though the application is the one updating it.
5758 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
5759 if (likely(head < ctx->sq_entries)) {
5761 * All io need record the previous position, if LINK vs DARIN,
5762 * it can be used to mark the position of the first IO in the
5765 req->sequence = ctx->cached_sq_head;
5766 *sqe_ptr = &ctx->sq_sqes[head];
5767 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
5768 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
5769 ctx->cached_sq_head++;
5773 /* drop invalid entries */
5774 ctx->cached_sq_head++;
5775 ctx->cached_sq_dropped++;
5776 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
5780 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
5781 struct file *ring_file, int ring_fd,
5782 struct mm_struct **mm, bool async)
5784 struct io_submit_state state, *statep = NULL;
5785 struct io_kiocb *link = NULL;
5786 int i, submitted = 0;
5787 bool mm_fault = false;
5789 /* if we have a backlog and couldn't flush it all, return BUSY */
5790 if (test_bit(0, &ctx->sq_check_overflow)) {
5791 if (!list_empty(&ctx->cq_overflow_list) &&
5792 !io_cqring_overflow_flush(ctx, false))
5796 /* make sure SQ entry isn't read before tail */
5797 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
5799 if (!percpu_ref_tryget_many(&ctx->refs, nr))
5802 if (nr > IO_PLUG_THRESHOLD) {
5803 io_submit_state_start(&state, nr);
5807 ctx->ring_fd = ring_fd;
5808 ctx->ring_file = ring_file;
5810 for (i = 0; i < nr; i++) {
5811 const struct io_uring_sqe *sqe;
5812 struct io_kiocb *req;
5815 req = io_get_req(ctx, statep);
5816 if (unlikely(!req)) {
5818 submitted = -EAGAIN;
5821 if (!io_get_sqring(ctx, req, &sqe)) {
5822 __io_req_do_free(req);
5826 /* will complete beyond this point, count as submitted */
5829 if (unlikely(req->opcode >= IORING_OP_LAST)) {
5832 io_cqring_add_event(req, err);
5833 io_double_put_req(req);
5837 if (io_op_defs[req->opcode].needs_mm && !*mm) {
5838 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
5839 if (unlikely(mm_fault)) {
5843 use_mm(ctx->sqo_mm);
5847 req->needs_fixed_file = async;
5848 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
5850 if (!io_submit_sqe(req, sqe, statep, &link))
5854 if (unlikely(submitted != nr)) {
5855 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
5857 percpu_ref_put_many(&ctx->refs, nr - ref_used);
5860 io_queue_link_head(link);
5862 io_submit_state_end(&state);
5864 /* Commit SQ ring head once we've consumed and submitted all SQEs */
5865 io_commit_sqring(ctx);
5870 static int io_sq_thread(void *data)
5872 struct io_ring_ctx *ctx = data;
5873 struct mm_struct *cur_mm = NULL;
5874 const struct cred *old_cred;
5875 mm_segment_t old_fs;
5877 unsigned long timeout;
5880 complete(&ctx->completions[1]);
5884 old_cred = override_creds(ctx->creds);
5886 timeout = jiffies + ctx->sq_thread_idle;
5887 while (!kthread_should_park()) {
5888 unsigned int to_submit;
5890 if (!list_empty(&ctx->poll_list)) {
5891 unsigned nr_events = 0;
5893 mutex_lock(&ctx->uring_lock);
5894 if (!list_empty(&ctx->poll_list))
5895 io_iopoll_getevents(ctx, &nr_events, 0);
5897 timeout = jiffies + ctx->sq_thread_idle;
5898 mutex_unlock(&ctx->uring_lock);
5901 to_submit = io_sqring_entries(ctx);
5904 * If submit got -EBUSY, flag us as needing the application
5905 * to enter the kernel to reap and flush events.
5907 if (!to_submit || ret == -EBUSY) {
5909 * Drop cur_mm before scheduling, we can't hold it for
5910 * long periods (or over schedule()). Do this before
5911 * adding ourselves to the waitqueue, as the unuse/drop
5921 * We're polling. If we're within the defined idle
5922 * period, then let us spin without work before going
5923 * to sleep. The exception is if we got EBUSY doing
5924 * more IO, we should wait for the application to
5925 * reap events and wake us up.
5927 if (!list_empty(&ctx->poll_list) ||
5928 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5929 !percpu_ref_is_dying(&ctx->refs))) {
5930 if (current->task_works)
5936 prepare_to_wait(&ctx->sqo_wait, &wait,
5937 TASK_INTERRUPTIBLE);
5940 * While doing polled IO, before going to sleep, we need
5941 * to check if there are new reqs added to poll_list, it
5942 * is because reqs may have been punted to io worker and
5943 * will be added to poll_list later, hence check the
5946 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
5947 !list_empty_careful(&ctx->poll_list)) {
5948 finish_wait(&ctx->sqo_wait, &wait);
5952 /* Tell userspace we may need a wakeup call */
5953 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
5954 /* make sure to read SQ tail after writing flags */
5957 to_submit = io_sqring_entries(ctx);
5958 if (!to_submit || ret == -EBUSY) {
5959 if (kthread_should_park()) {
5960 finish_wait(&ctx->sqo_wait, &wait);
5963 if (current->task_works) {
5967 if (signal_pending(current))
5968 flush_signals(current);
5970 finish_wait(&ctx->sqo_wait, &wait);
5972 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5975 finish_wait(&ctx->sqo_wait, &wait);
5977 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
5980 mutex_lock(&ctx->uring_lock);
5981 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
5982 mutex_unlock(&ctx->uring_lock);
5983 timeout = jiffies + ctx->sq_thread_idle;
5986 if (current->task_works)
5994 revert_creds(old_cred);
6001 struct io_wait_queue {
6002 struct wait_queue_entry wq;
6003 struct io_ring_ctx *ctx;
6005 unsigned nr_timeouts;
6008 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6010 struct io_ring_ctx *ctx = iowq->ctx;
6013 * Wake up if we have enough events, or if a timeout occurred since we
6014 * started waiting. For timeouts, we always want to return to userspace,
6015 * regardless of event count.
6017 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6018 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6021 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6022 int wake_flags, void *key)
6024 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6027 /* use noflush == true, as we can't safely rely on locking context */
6028 if (!io_should_wake(iowq, true))
6031 return autoremove_wake_function(curr, mode, wake_flags, key);
6035 * Wait until events become available, if we don't already have some. The
6036 * application must reap them itself, as they reside on the shared cq ring.
6038 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6039 const sigset_t __user *sig, size_t sigsz)
6041 struct io_wait_queue iowq = {
6044 .func = io_wake_function,
6045 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6048 .to_wait = min_events,
6050 struct io_rings *rings = ctx->rings;
6054 if (io_cqring_events(ctx, false) >= min_events)
6056 if (!current->task_works)
6062 #ifdef CONFIG_COMPAT
6063 if (in_compat_syscall())
6064 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6068 ret = set_user_sigmask(sig, sigsz);
6074 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6075 trace_io_uring_cqring_wait(ctx, min_events);
6077 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6078 TASK_INTERRUPTIBLE);
6079 if (current->task_works)
6081 if (io_should_wake(&iowq, false))
6084 if (signal_pending(current)) {
6089 finish_wait(&ctx->wait, &iowq.wq);
6091 restore_saved_sigmask_unless(ret == -EINTR);
6093 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6096 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6098 #if defined(CONFIG_UNIX)
6099 if (ctx->ring_sock) {
6100 struct sock *sock = ctx->ring_sock->sk;
6101 struct sk_buff *skb;
6103 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6109 for (i = 0; i < ctx->nr_user_files; i++) {
6112 file = io_file_from_index(ctx, i);
6119 static void io_file_ref_kill(struct percpu_ref *ref)
6121 struct fixed_file_data *data;
6123 data = container_of(ref, struct fixed_file_data, refs);
6124 complete(&data->done);
6127 static void io_file_ref_exit_and_free(struct work_struct *work)
6129 struct fixed_file_data *data;
6131 data = container_of(work, struct fixed_file_data, ref_work);
6134 * Ensure any percpu-ref atomic switch callback has run, it could have
6135 * been in progress when the files were being unregistered. Once
6136 * that's done, we can safely exit and free the ref and containing
6140 percpu_ref_exit(&data->refs);
6144 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6146 struct fixed_file_data *data = ctx->file_data;
6147 unsigned nr_tables, i;
6152 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
6153 flush_work(&data->ref_work);
6154 wait_for_completion(&data->done);
6155 io_ring_file_ref_flush(data);
6157 __io_sqe_files_unregister(ctx);
6158 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6159 for (i = 0; i < nr_tables; i++)
6160 kfree(data->table[i].files);
6162 INIT_WORK(&data->ref_work, io_file_ref_exit_and_free);
6163 queue_work(system_wq, &data->ref_work);
6164 ctx->file_data = NULL;
6165 ctx->nr_user_files = 0;
6169 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6171 if (ctx->sqo_thread) {
6172 wait_for_completion(&ctx->completions[1]);
6174 * The park is a bit of a work-around, without it we get
6175 * warning spews on shutdown with SQPOLL set and affinity
6176 * set to a single CPU.
6178 kthread_park(ctx->sqo_thread);
6179 kthread_stop(ctx->sqo_thread);
6180 ctx->sqo_thread = NULL;
6184 static void io_finish_async(struct io_ring_ctx *ctx)
6186 io_sq_thread_stop(ctx);
6189 io_wq_destroy(ctx->io_wq);
6194 #if defined(CONFIG_UNIX)
6196 * Ensure the UNIX gc is aware of our file set, so we are certain that
6197 * the io_uring can be safely unregistered on process exit, even if we have
6198 * loops in the file referencing.
6200 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6202 struct sock *sk = ctx->ring_sock->sk;
6203 struct scm_fp_list *fpl;
6204 struct sk_buff *skb;
6207 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
6208 unsigned long inflight = ctx->user->unix_inflight + nr;
6210 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
6214 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6218 skb = alloc_skb(0, GFP_KERNEL);
6227 fpl->user = get_uid(ctx->user);
6228 for (i = 0; i < nr; i++) {
6229 struct file *file = io_file_from_index(ctx, i + offset);
6233 fpl->fp[nr_files] = get_file(file);
6234 unix_inflight(fpl->user, fpl->fp[nr_files]);
6239 fpl->max = SCM_MAX_FD;
6240 fpl->count = nr_files;
6241 UNIXCB(skb).fp = fpl;
6242 skb->destructor = unix_destruct_scm;
6243 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6244 skb_queue_head(&sk->sk_receive_queue, skb);
6246 for (i = 0; i < nr_files; i++)
6257 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6258 * causes regular reference counting to break down. We rely on the UNIX
6259 * garbage collection to take care of this problem for us.
6261 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6263 unsigned left, total;
6267 left = ctx->nr_user_files;
6269 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6271 ret = __io_sqe_files_scm(ctx, this_files, total);
6275 total += this_files;
6281 while (total < ctx->nr_user_files) {
6282 struct file *file = io_file_from_index(ctx, total);
6292 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6298 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6303 for (i = 0; i < nr_tables; i++) {
6304 struct fixed_file_table *table = &ctx->file_data->table[i];
6305 unsigned this_files;
6307 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6308 table->files = kcalloc(this_files, sizeof(struct file *),
6312 nr_files -= this_files;
6318 for (i = 0; i < nr_tables; i++) {
6319 struct fixed_file_table *table = &ctx->file_data->table[i];
6320 kfree(table->files);
6325 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6327 #if defined(CONFIG_UNIX)
6328 struct sock *sock = ctx->ring_sock->sk;
6329 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6330 struct sk_buff *skb;
6333 __skb_queue_head_init(&list);
6336 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6337 * remove this entry and rearrange the file array.
6339 skb = skb_dequeue(head);
6341 struct scm_fp_list *fp;
6343 fp = UNIXCB(skb).fp;
6344 for (i = 0; i < fp->count; i++) {
6347 if (fp->fp[i] != file)
6350 unix_notinflight(fp->user, fp->fp[i]);
6351 left = fp->count - 1 - i;
6353 memmove(&fp->fp[i], &fp->fp[i + 1],
6354 left * sizeof(struct file *));
6361 __skb_queue_tail(&list, skb);
6371 __skb_queue_tail(&list, skb);
6373 skb = skb_dequeue(head);
6376 if (skb_peek(&list)) {
6377 spin_lock_irq(&head->lock);
6378 while ((skb = __skb_dequeue(&list)) != NULL)
6379 __skb_queue_tail(head, skb);
6380 spin_unlock_irq(&head->lock);
6387 struct io_file_put {
6388 struct llist_node llist;
6392 static void io_ring_file_ref_flush(struct fixed_file_data *data)
6394 struct io_file_put *pfile, *tmp;
6395 struct llist_node *node;
6397 while ((node = llist_del_all(&data->put_llist)) != NULL) {
6398 llist_for_each_entry_safe(pfile, tmp, node, llist) {
6399 io_ring_file_put(data->ctx, pfile->file);
6405 static void io_ring_file_ref_switch(struct work_struct *work)
6407 struct fixed_file_data *data;
6409 data = container_of(work, struct fixed_file_data, ref_work);
6410 io_ring_file_ref_flush(data);
6411 percpu_ref_switch_to_percpu(&data->refs);
6414 static void io_file_data_ref_zero(struct percpu_ref *ref)
6416 struct fixed_file_data *data;
6418 data = container_of(ref, struct fixed_file_data, refs);
6421 * We can't safely switch from inside this context, punt to wq. If
6422 * the table ref is going away, the table is being unregistered.
6423 * Don't queue up the async work for that case, the caller will
6426 if (!percpu_ref_is_dying(&data->refs))
6427 queue_work(system_wq, &data->ref_work);
6430 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6433 __s32 __user *fds = (__s32 __user *) arg;
6443 if (nr_args > IORING_MAX_FIXED_FILES)
6446 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6447 if (!ctx->file_data)
6449 ctx->file_data->ctx = ctx;
6450 init_completion(&ctx->file_data->done);
6452 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6453 ctx->file_data->table = kcalloc(nr_tables,
6454 sizeof(struct fixed_file_table),
6456 if (!ctx->file_data->table) {
6457 kfree(ctx->file_data);
6458 ctx->file_data = NULL;
6462 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
6463 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6464 kfree(ctx->file_data->table);
6465 kfree(ctx->file_data);
6466 ctx->file_data = NULL;
6469 ctx->file_data->put_llist.first = NULL;
6470 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
6472 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6473 percpu_ref_exit(&ctx->file_data->refs);
6474 kfree(ctx->file_data->table);
6475 kfree(ctx->file_data);
6476 ctx->file_data = NULL;
6480 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6481 struct fixed_file_table *table;
6485 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6487 /* allow sparse sets */
6493 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6494 index = i & IORING_FILE_TABLE_MASK;
6502 * Don't allow io_uring instances to be registered. If UNIX
6503 * isn't enabled, then this causes a reference cycle and this
6504 * instance can never get freed. If UNIX is enabled we'll
6505 * handle it just fine, but there's still no point in allowing
6506 * a ring fd as it doesn't support regular read/write anyway.
6508 if (file->f_op == &io_uring_fops) {
6513 table->files[index] = file;
6517 for (i = 0; i < ctx->nr_user_files; i++) {
6518 file = io_file_from_index(ctx, i);
6522 for (i = 0; i < nr_tables; i++)
6523 kfree(ctx->file_data->table[i].files);
6525 kfree(ctx->file_data->table);
6526 kfree(ctx->file_data);
6527 ctx->file_data = NULL;
6528 ctx->nr_user_files = 0;
6532 ret = io_sqe_files_scm(ctx);
6534 io_sqe_files_unregister(ctx);
6539 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
6542 #if defined(CONFIG_UNIX)
6543 struct sock *sock = ctx->ring_sock->sk;
6544 struct sk_buff_head *head = &sock->sk_receive_queue;
6545 struct sk_buff *skb;
6548 * See if we can merge this file into an existing skb SCM_RIGHTS
6549 * file set. If there's no room, fall back to allocating a new skb
6550 * and filling it in.
6552 spin_lock_irq(&head->lock);
6553 skb = skb_peek(head);
6555 struct scm_fp_list *fpl = UNIXCB(skb).fp;
6557 if (fpl->count < SCM_MAX_FD) {
6558 __skb_unlink(skb, head);
6559 spin_unlock_irq(&head->lock);
6560 fpl->fp[fpl->count] = get_file(file);
6561 unix_inflight(fpl->user, fpl->fp[fpl->count]);
6563 spin_lock_irq(&head->lock);
6564 __skb_queue_head(head, skb);
6569 spin_unlock_irq(&head->lock);
6576 return __io_sqe_files_scm(ctx, 1, index);
6582 static void io_atomic_switch(struct percpu_ref *ref)
6584 struct fixed_file_data *data;
6587 * Juggle reference to ensure we hit zero, if needed, so we can
6588 * switch back to percpu mode
6590 data = container_of(ref, struct fixed_file_data, refs);
6591 percpu_ref_put(&data->refs);
6592 percpu_ref_get(&data->refs);
6595 static int io_queue_file_removal(struct fixed_file_data *data,
6598 struct io_file_put *pfile;
6600 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
6605 llist_add(&pfile->llist, &data->put_llist);
6609 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
6610 struct io_uring_files_update *up,
6613 struct fixed_file_data *data = ctx->file_data;
6614 bool ref_switch = false;
6620 if (check_add_overflow(up->offset, nr_args, &done))
6622 if (done > ctx->nr_user_files)
6626 fds = u64_to_user_ptr(up->fds);
6628 struct fixed_file_table *table;
6632 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6636 i = array_index_nospec(up->offset, ctx->nr_user_files);
6637 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6638 index = i & IORING_FILE_TABLE_MASK;
6639 if (table->files[index]) {
6640 file = io_file_from_index(ctx, index);
6641 err = io_queue_file_removal(data, file);
6644 table->files[index] = NULL;
6654 * Don't allow io_uring instances to be registered. If
6655 * UNIX isn't enabled, then this causes a reference
6656 * cycle and this instance can never get freed. If UNIX
6657 * is enabled we'll handle it just fine, but there's
6658 * still no point in allowing a ring fd as it doesn't
6659 * support regular read/write anyway.
6661 if (file->f_op == &io_uring_fops) {
6666 table->files[index] = file;
6667 err = io_sqe_file_register(ctx, file, i);
6677 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
6679 return done ? done : err;
6681 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
6684 struct io_uring_files_update up;
6686 if (!ctx->file_data)
6690 if (copy_from_user(&up, arg, sizeof(up)))
6695 return __io_sqe_files_update(ctx, &up, nr_args);
6698 static void io_free_work(struct io_wq_work *work)
6700 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6702 /* Consider that io_steal_work() relies on this ref */
6706 static int io_init_wq_offload(struct io_ring_ctx *ctx,
6707 struct io_uring_params *p)
6709 struct io_wq_data data;
6711 struct io_ring_ctx *ctx_attach;
6712 unsigned int concurrency;
6715 data.user = ctx->user;
6716 data.free_work = io_free_work;
6718 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
6719 /* Do QD, or 4 * CPUS, whatever is smallest */
6720 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
6722 ctx->io_wq = io_wq_create(concurrency, &data);
6723 if (IS_ERR(ctx->io_wq)) {
6724 ret = PTR_ERR(ctx->io_wq);
6730 f = fdget(p->wq_fd);
6734 if (f.file->f_op != &io_uring_fops) {
6739 ctx_attach = f.file->private_data;
6740 /* @io_wq is protected by holding the fd */
6741 if (!io_wq_get(ctx_attach->io_wq, &data)) {
6746 ctx->io_wq = ctx_attach->io_wq;
6752 static int io_sq_offload_start(struct io_ring_ctx *ctx,
6753 struct io_uring_params *p)
6757 init_waitqueue_head(&ctx->sqo_wait);
6758 mmgrab(current->mm);
6759 ctx->sqo_mm = current->mm;
6761 if (ctx->flags & IORING_SETUP_SQPOLL) {
6763 if (!capable(CAP_SYS_ADMIN))
6766 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
6767 if (!ctx->sq_thread_idle)
6768 ctx->sq_thread_idle = HZ;
6770 if (p->flags & IORING_SETUP_SQ_AFF) {
6771 int cpu = p->sq_thread_cpu;
6774 if (cpu >= nr_cpu_ids)
6776 if (!cpu_online(cpu))
6779 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
6783 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
6786 if (IS_ERR(ctx->sqo_thread)) {
6787 ret = PTR_ERR(ctx->sqo_thread);
6788 ctx->sqo_thread = NULL;
6791 wake_up_process(ctx->sqo_thread);
6792 } else if (p->flags & IORING_SETUP_SQ_AFF) {
6793 /* Can't have SQ_AFF without SQPOLL */
6798 ret = io_init_wq_offload(ctx, p);
6804 io_finish_async(ctx);
6805 mmdrop(ctx->sqo_mm);
6810 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
6812 atomic_long_sub(nr_pages, &user->locked_vm);
6815 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
6817 unsigned long page_limit, cur_pages, new_pages;
6819 /* Don't allow more pages than we can safely lock */
6820 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
6823 cur_pages = atomic_long_read(&user->locked_vm);
6824 new_pages = cur_pages + nr_pages;
6825 if (new_pages > page_limit)
6827 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
6828 new_pages) != cur_pages);
6833 static void io_mem_free(void *ptr)
6840 page = virt_to_head_page(ptr);
6841 if (put_page_testzero(page))
6842 free_compound_page(page);
6845 static void *io_mem_alloc(size_t size)
6847 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
6850 return (void *) __get_free_pages(gfp_flags, get_order(size));
6853 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
6856 struct io_rings *rings;
6857 size_t off, sq_array_size;
6859 off = struct_size(rings, cqes, cq_entries);
6860 if (off == SIZE_MAX)
6864 off = ALIGN(off, SMP_CACHE_BYTES);
6869 sq_array_size = array_size(sizeof(u32), sq_entries);
6870 if (sq_array_size == SIZE_MAX)
6873 if (check_add_overflow(off, sq_array_size, &off))
6882 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
6886 pages = (size_t)1 << get_order(
6887 rings_size(sq_entries, cq_entries, NULL));
6888 pages += (size_t)1 << get_order(
6889 array_size(sizeof(struct io_uring_sqe), sq_entries));
6894 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6898 if (!ctx->user_bufs)
6901 for (i = 0; i < ctx->nr_user_bufs; i++) {
6902 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6904 for (j = 0; j < imu->nr_bvecs; j++)
6905 unpin_user_page(imu->bvec[j].bv_page);
6907 if (ctx->account_mem)
6908 io_unaccount_mem(ctx->user, imu->nr_bvecs);
6913 kfree(ctx->user_bufs);
6914 ctx->user_bufs = NULL;
6915 ctx->nr_user_bufs = 0;
6919 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6920 void __user *arg, unsigned index)
6922 struct iovec __user *src;
6924 #ifdef CONFIG_COMPAT
6926 struct compat_iovec __user *ciovs;
6927 struct compat_iovec ciov;
6929 ciovs = (struct compat_iovec __user *) arg;
6930 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6933 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
6934 dst->iov_len = ciov.iov_len;
6938 src = (struct iovec __user *) arg;
6939 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6944 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6947 struct vm_area_struct **vmas = NULL;
6948 struct page **pages = NULL;
6949 int i, j, got_pages = 0;
6954 if (!nr_args || nr_args > UIO_MAXIOV)
6957 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6959 if (!ctx->user_bufs)
6962 for (i = 0; i < nr_args; i++) {
6963 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6964 unsigned long off, start, end, ubuf;
6969 ret = io_copy_iov(ctx, &iov, arg, i);
6974 * Don't impose further limits on the size and buffer
6975 * constraints here, we'll -EINVAL later when IO is
6976 * submitted if they are wrong.
6979 if (!iov.iov_base || !iov.iov_len)
6982 /* arbitrary limit, but we need something */
6983 if (iov.iov_len > SZ_1G)
6986 ubuf = (unsigned long) iov.iov_base;
6987 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6988 start = ubuf >> PAGE_SHIFT;
6989 nr_pages = end - start;
6991 if (ctx->account_mem) {
6992 ret = io_account_mem(ctx->user, nr_pages);
6998 if (!pages || nr_pages > got_pages) {
7001 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7003 vmas = kvmalloc_array(nr_pages,
7004 sizeof(struct vm_area_struct *),
7006 if (!pages || !vmas) {
7008 if (ctx->account_mem)
7009 io_unaccount_mem(ctx->user, nr_pages);
7012 got_pages = nr_pages;
7015 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7019 if (ctx->account_mem)
7020 io_unaccount_mem(ctx->user, nr_pages);
7025 down_read(¤t->mm->mmap_sem);
7026 pret = pin_user_pages(ubuf, nr_pages,
7027 FOLL_WRITE | FOLL_LONGTERM,
7029 if (pret == nr_pages) {
7030 /* don't support file backed memory */
7031 for (j = 0; j < nr_pages; j++) {
7032 struct vm_area_struct *vma = vmas[j];
7035 !is_file_hugepages(vma->vm_file)) {
7041 ret = pret < 0 ? pret : -EFAULT;
7043 up_read(¤t->mm->mmap_sem);
7046 * if we did partial map, or found file backed vmas,
7047 * release any pages we did get
7050 unpin_user_pages(pages, pret);
7051 if (ctx->account_mem)
7052 io_unaccount_mem(ctx->user, nr_pages);
7057 off = ubuf & ~PAGE_MASK;
7059 for (j = 0; j < nr_pages; j++) {
7062 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7063 imu->bvec[j].bv_page = pages[j];
7064 imu->bvec[j].bv_len = vec_len;
7065 imu->bvec[j].bv_offset = off;
7069 /* store original address for later verification */
7071 imu->len = iov.iov_len;
7072 imu->nr_bvecs = nr_pages;
7074 ctx->nr_user_bufs++;
7082 io_sqe_buffer_unregister(ctx);
7086 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7088 __s32 __user *fds = arg;
7094 if (copy_from_user(&fd, fds, sizeof(*fds)))
7097 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7098 if (IS_ERR(ctx->cq_ev_fd)) {
7099 int ret = PTR_ERR(ctx->cq_ev_fd);
7100 ctx->cq_ev_fd = NULL;
7107 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7109 if (ctx->cq_ev_fd) {
7110 eventfd_ctx_put(ctx->cq_ev_fd);
7111 ctx->cq_ev_fd = NULL;
7118 static int __io_destroy_buffers(int id, void *p, void *data)
7120 struct io_ring_ctx *ctx = data;
7121 struct io_buffer *buf = p;
7123 __io_remove_buffers(ctx, buf, id, -1U);
7127 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7129 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7130 idr_destroy(&ctx->io_buffer_idr);
7133 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7135 io_finish_async(ctx);
7137 mmdrop(ctx->sqo_mm);
7139 io_iopoll_reap_events(ctx);
7140 io_sqe_buffer_unregister(ctx);
7141 io_sqe_files_unregister(ctx);
7142 io_eventfd_unregister(ctx);
7143 io_destroy_buffers(ctx);
7144 idr_destroy(&ctx->personality_idr);
7146 #if defined(CONFIG_UNIX)
7147 if (ctx->ring_sock) {
7148 ctx->ring_sock->file = NULL; /* so that iput() is called */
7149 sock_release(ctx->ring_sock);
7153 io_mem_free(ctx->rings);
7154 io_mem_free(ctx->sq_sqes);
7156 percpu_ref_exit(&ctx->refs);
7157 if (ctx->account_mem)
7158 io_unaccount_mem(ctx->user,
7159 ring_pages(ctx->sq_entries, ctx->cq_entries));
7160 free_uid(ctx->user);
7161 put_cred(ctx->creds);
7162 kfree(ctx->completions);
7163 kfree(ctx->cancel_hash);
7164 kmem_cache_free(req_cachep, ctx->fallback_req);
7168 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7170 struct io_ring_ctx *ctx = file->private_data;
7173 poll_wait(file, &ctx->cq_wait, wait);
7175 * synchronizes with barrier from wq_has_sleeper call in
7179 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7180 ctx->rings->sq_ring_entries)
7181 mask |= EPOLLOUT | EPOLLWRNORM;
7182 if (io_cqring_events(ctx, false))
7183 mask |= EPOLLIN | EPOLLRDNORM;
7188 static int io_uring_fasync(int fd, struct file *file, int on)
7190 struct io_ring_ctx *ctx = file->private_data;
7192 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7195 static int io_remove_personalities(int id, void *p, void *data)
7197 struct io_ring_ctx *ctx = data;
7198 const struct cred *cred;
7200 cred = idr_remove(&ctx->personality_idr, id);
7206 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7208 mutex_lock(&ctx->uring_lock);
7209 percpu_ref_kill(&ctx->refs);
7210 mutex_unlock(&ctx->uring_lock);
7213 * Wait for sq thread to idle, if we have one. It won't spin on new
7214 * work after we've killed the ctx ref above. This is important to do
7215 * before we cancel existing commands, as the thread could otherwise
7216 * be queueing new work post that. If that's work we need to cancel,
7217 * it could cause shutdown to hang.
7219 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
7222 io_kill_timeouts(ctx);
7223 io_poll_remove_all(ctx);
7226 io_wq_cancel_all(ctx->io_wq);
7228 io_iopoll_reap_events(ctx);
7229 /* if we failed setting up the ctx, we might not have any rings */
7231 io_cqring_overflow_flush(ctx, true);
7232 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7233 wait_for_completion(&ctx->completions[0]);
7234 io_ring_ctx_free(ctx);
7237 static int io_uring_release(struct inode *inode, struct file *file)
7239 struct io_ring_ctx *ctx = file->private_data;
7241 file->private_data = NULL;
7242 io_ring_ctx_wait_and_kill(ctx);
7246 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7247 struct files_struct *files)
7249 struct io_kiocb *req;
7252 while (!list_empty_careful(&ctx->inflight_list)) {
7253 struct io_kiocb *cancel_req = NULL;
7255 spin_lock_irq(&ctx->inflight_lock);
7256 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7257 if (req->work.files != files)
7259 /* req is being completed, ignore */
7260 if (!refcount_inc_not_zero(&req->refs))
7266 prepare_to_wait(&ctx->inflight_wait, &wait,
7267 TASK_UNINTERRUPTIBLE);
7268 spin_unlock_irq(&ctx->inflight_lock);
7270 /* We need to keep going until we don't find a matching req */
7274 if (cancel_req->flags & REQ_F_OVERFLOW) {
7275 spin_lock_irq(&ctx->completion_lock);
7276 list_del(&cancel_req->list);
7277 cancel_req->flags &= ~REQ_F_OVERFLOW;
7278 if (list_empty(&ctx->cq_overflow_list)) {
7279 clear_bit(0, &ctx->sq_check_overflow);
7280 clear_bit(0, &ctx->cq_check_overflow);
7282 spin_unlock_irq(&ctx->completion_lock);
7284 WRITE_ONCE(ctx->rings->cq_overflow,
7285 atomic_inc_return(&ctx->cached_cq_overflow));
7288 * Put inflight ref and overflow ref. If that's
7289 * all we had, then we're done with this request.
7291 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7292 io_put_req(cancel_req);
7297 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7298 io_put_req(cancel_req);
7301 finish_wait(&ctx->inflight_wait, &wait);
7304 static int io_uring_flush(struct file *file, void *data)
7306 struct io_ring_ctx *ctx = file->private_data;
7308 io_uring_cancel_files(ctx, data);
7311 * If the task is going away, cancel work it may have pending
7313 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7314 io_wq_cancel_pid(ctx->io_wq, task_pid_vnr(current));
7319 static void *io_uring_validate_mmap_request(struct file *file,
7320 loff_t pgoff, size_t sz)
7322 struct io_ring_ctx *ctx = file->private_data;
7323 loff_t offset = pgoff << PAGE_SHIFT;
7328 case IORING_OFF_SQ_RING:
7329 case IORING_OFF_CQ_RING:
7332 case IORING_OFF_SQES:
7336 return ERR_PTR(-EINVAL);
7339 page = virt_to_head_page(ptr);
7340 if (sz > page_size(page))
7341 return ERR_PTR(-EINVAL);
7348 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7350 size_t sz = vma->vm_end - vma->vm_start;
7354 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7356 return PTR_ERR(ptr);
7358 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7359 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7362 #else /* !CONFIG_MMU */
7364 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7366 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7369 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7371 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7374 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7375 unsigned long addr, unsigned long len,
7376 unsigned long pgoff, unsigned long flags)
7380 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7382 return PTR_ERR(ptr);
7384 return (unsigned long) ptr;
7387 #endif /* !CONFIG_MMU */
7389 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7390 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7393 struct io_ring_ctx *ctx;
7398 if (current->task_works)
7401 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7409 if (f.file->f_op != &io_uring_fops)
7413 ctx = f.file->private_data;
7414 if (!percpu_ref_tryget(&ctx->refs))
7418 * For SQ polling, the thread will do all submissions and completions.
7419 * Just return the requested submit count, and wake the thread if
7423 if (ctx->flags & IORING_SETUP_SQPOLL) {
7424 if (!list_empty_careful(&ctx->cq_overflow_list))
7425 io_cqring_overflow_flush(ctx, false);
7426 if (flags & IORING_ENTER_SQ_WAKEUP)
7427 wake_up(&ctx->sqo_wait);
7428 submitted = to_submit;
7429 } else if (to_submit) {
7430 struct mm_struct *cur_mm;
7432 mutex_lock(&ctx->uring_lock);
7433 /* already have mm, so io_submit_sqes() won't try to grab it */
7434 cur_mm = ctx->sqo_mm;
7435 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
7437 mutex_unlock(&ctx->uring_lock);
7439 if (submitted != to_submit)
7442 if (flags & IORING_ENTER_GETEVENTS) {
7443 unsigned nr_events = 0;
7445 min_complete = min(min_complete, ctx->cq_entries);
7448 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
7449 * space applications don't need to do io completion events
7450 * polling again, they can rely on io_sq_thread to do polling
7451 * work, which can reduce cpu usage and uring_lock contention.
7453 if (ctx->flags & IORING_SETUP_IOPOLL &&
7454 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7455 ret = io_iopoll_check(ctx, &nr_events, min_complete);
7457 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
7462 percpu_ref_put(&ctx->refs);
7465 return submitted ? submitted : ret;
7468 #ifdef CONFIG_PROC_FS
7469 static int io_uring_show_cred(int id, void *p, void *data)
7471 const struct cred *cred = p;
7472 struct seq_file *m = data;
7473 struct user_namespace *uns = seq_user_ns(m);
7474 struct group_info *gi;
7479 seq_printf(m, "%5d\n", id);
7480 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
7481 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
7482 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
7483 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
7484 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
7485 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
7486 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
7487 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
7488 seq_puts(m, "\n\tGroups:\t");
7489 gi = cred->group_info;
7490 for (g = 0; g < gi->ngroups; g++) {
7491 seq_put_decimal_ull(m, g ? " " : "",
7492 from_kgid_munged(uns, gi->gid[g]));
7494 seq_puts(m, "\n\tCapEff:\t");
7495 cap = cred->cap_effective;
7496 CAP_FOR_EACH_U32(__capi)
7497 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
7502 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
7506 mutex_lock(&ctx->uring_lock);
7507 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
7508 for (i = 0; i < ctx->nr_user_files; i++) {
7509 struct fixed_file_table *table;
7512 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7513 f = table->files[i & IORING_FILE_TABLE_MASK];
7515 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
7517 seq_printf(m, "%5u: <none>\n", i);
7519 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
7520 for (i = 0; i < ctx->nr_user_bufs; i++) {
7521 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
7523 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
7524 (unsigned int) buf->len);
7526 if (!idr_is_empty(&ctx->personality_idr)) {
7527 seq_printf(m, "Personalities:\n");
7528 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
7530 seq_printf(m, "PollList:\n");
7531 spin_lock_irq(&ctx->completion_lock);
7532 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7533 struct hlist_head *list = &ctx->cancel_hash[i];
7534 struct io_kiocb *req;
7536 hlist_for_each_entry(req, list, hash_node)
7537 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
7538 req->task->task_works != NULL);
7540 spin_unlock_irq(&ctx->completion_lock);
7541 mutex_unlock(&ctx->uring_lock);
7544 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
7546 struct io_ring_ctx *ctx = f->private_data;
7548 if (percpu_ref_tryget(&ctx->refs)) {
7549 __io_uring_show_fdinfo(ctx, m);
7550 percpu_ref_put(&ctx->refs);
7555 static const struct file_operations io_uring_fops = {
7556 .release = io_uring_release,
7557 .flush = io_uring_flush,
7558 .mmap = io_uring_mmap,
7560 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
7561 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
7563 .poll = io_uring_poll,
7564 .fasync = io_uring_fasync,
7565 #ifdef CONFIG_PROC_FS
7566 .show_fdinfo = io_uring_show_fdinfo,
7570 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
7571 struct io_uring_params *p)
7573 struct io_rings *rings;
7574 size_t size, sq_array_offset;
7576 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
7577 if (size == SIZE_MAX)
7580 rings = io_mem_alloc(size);
7585 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
7586 rings->sq_ring_mask = p->sq_entries - 1;
7587 rings->cq_ring_mask = p->cq_entries - 1;
7588 rings->sq_ring_entries = p->sq_entries;
7589 rings->cq_ring_entries = p->cq_entries;
7590 ctx->sq_mask = rings->sq_ring_mask;
7591 ctx->cq_mask = rings->cq_ring_mask;
7592 ctx->sq_entries = rings->sq_ring_entries;
7593 ctx->cq_entries = rings->cq_ring_entries;
7595 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
7596 if (size == SIZE_MAX) {
7597 io_mem_free(ctx->rings);
7602 ctx->sq_sqes = io_mem_alloc(size);
7603 if (!ctx->sq_sqes) {
7604 io_mem_free(ctx->rings);
7613 * Allocate an anonymous fd, this is what constitutes the application
7614 * visible backing of an io_uring instance. The application mmaps this
7615 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
7616 * we have to tie this fd to a socket for file garbage collection purposes.
7618 static int io_uring_get_fd(struct io_ring_ctx *ctx)
7623 #if defined(CONFIG_UNIX)
7624 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
7630 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
7634 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
7635 O_RDWR | O_CLOEXEC);
7638 ret = PTR_ERR(file);
7642 #if defined(CONFIG_UNIX)
7643 ctx->ring_sock->file = file;
7645 fd_install(ret, file);
7648 #if defined(CONFIG_UNIX)
7649 sock_release(ctx->ring_sock);
7650 ctx->ring_sock = NULL;
7655 static int io_uring_create(unsigned entries, struct io_uring_params *p)
7657 struct user_struct *user = NULL;
7658 struct io_ring_ctx *ctx;
7664 if (entries > IORING_MAX_ENTRIES) {
7665 if (!(p->flags & IORING_SETUP_CLAMP))
7667 entries = IORING_MAX_ENTRIES;
7671 * Use twice as many entries for the CQ ring. It's possible for the
7672 * application to drive a higher depth than the size of the SQ ring,
7673 * since the sqes are only used at submission time. This allows for
7674 * some flexibility in overcommitting a bit. If the application has
7675 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
7676 * of CQ ring entries manually.
7678 p->sq_entries = roundup_pow_of_two(entries);
7679 if (p->flags & IORING_SETUP_CQSIZE) {
7681 * If IORING_SETUP_CQSIZE is set, we do the same roundup
7682 * to a power-of-two, if it isn't already. We do NOT impose
7683 * any cq vs sq ring sizing.
7685 if (p->cq_entries < p->sq_entries)
7687 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
7688 if (!(p->flags & IORING_SETUP_CLAMP))
7690 p->cq_entries = IORING_MAX_CQ_ENTRIES;
7692 p->cq_entries = roundup_pow_of_two(p->cq_entries);
7694 p->cq_entries = 2 * p->sq_entries;
7697 user = get_uid(current_user());
7698 account_mem = !capable(CAP_IPC_LOCK);
7701 ret = io_account_mem(user,
7702 ring_pages(p->sq_entries, p->cq_entries));
7709 ctx = io_ring_ctx_alloc(p);
7712 io_unaccount_mem(user, ring_pages(p->sq_entries,
7717 ctx->compat = in_compat_syscall();
7718 ctx->account_mem = account_mem;
7720 ctx->creds = get_current_cred();
7722 ret = io_allocate_scq_urings(ctx, p);
7726 ret = io_sq_offload_start(ctx, p);
7730 memset(&p->sq_off, 0, sizeof(p->sq_off));
7731 p->sq_off.head = offsetof(struct io_rings, sq.head);
7732 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
7733 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
7734 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
7735 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
7736 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
7737 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
7739 memset(&p->cq_off, 0, sizeof(p->cq_off));
7740 p->cq_off.head = offsetof(struct io_rings, cq.head);
7741 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
7742 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
7743 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
7744 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
7745 p->cq_off.cqes = offsetof(struct io_rings, cqes);
7748 * Install ring fd as the very last thing, so we don't risk someone
7749 * having closed it before we finish setup
7751 ret = io_uring_get_fd(ctx);
7755 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
7756 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
7757 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL;
7758 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
7761 io_ring_ctx_wait_and_kill(ctx);
7766 * Sets up an aio uring context, and returns the fd. Applications asks for a
7767 * ring size, we return the actual sq/cq ring sizes (among other things) in the
7768 * params structure passed in.
7770 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
7772 struct io_uring_params p;
7776 if (copy_from_user(&p, params, sizeof(p)))
7778 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
7783 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
7784 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
7785 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
7788 ret = io_uring_create(entries, &p);
7792 if (copy_to_user(params, &p, sizeof(p)))
7798 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
7799 struct io_uring_params __user *, params)
7801 return io_uring_setup(entries, params);
7804 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
7806 struct io_uring_probe *p;
7810 size = struct_size(p, ops, nr_args);
7811 if (size == SIZE_MAX)
7813 p = kzalloc(size, GFP_KERNEL);
7818 if (copy_from_user(p, arg, size))
7821 if (memchr_inv(p, 0, size))
7824 p->last_op = IORING_OP_LAST - 1;
7825 if (nr_args > IORING_OP_LAST)
7826 nr_args = IORING_OP_LAST;
7828 for (i = 0; i < nr_args; i++) {
7830 if (!io_op_defs[i].not_supported)
7831 p->ops[i].flags = IO_URING_OP_SUPPORTED;
7836 if (copy_to_user(arg, p, size))
7843 static int io_register_personality(struct io_ring_ctx *ctx)
7845 const struct cred *creds = get_current_cred();
7848 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
7849 USHRT_MAX, GFP_KERNEL);
7855 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
7857 const struct cred *old_creds;
7859 old_creds = idr_remove(&ctx->personality_idr, id);
7861 put_cred(old_creds);
7868 static bool io_register_op_must_quiesce(int op)
7871 case IORING_UNREGISTER_FILES:
7872 case IORING_REGISTER_FILES_UPDATE:
7873 case IORING_REGISTER_PROBE:
7874 case IORING_REGISTER_PERSONALITY:
7875 case IORING_UNREGISTER_PERSONALITY:
7882 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
7883 void __user *arg, unsigned nr_args)
7884 __releases(ctx->uring_lock)
7885 __acquires(ctx->uring_lock)
7890 * We're inside the ring mutex, if the ref is already dying, then
7891 * someone else killed the ctx or is already going through
7892 * io_uring_register().
7894 if (percpu_ref_is_dying(&ctx->refs))
7897 if (io_register_op_must_quiesce(opcode)) {
7898 percpu_ref_kill(&ctx->refs);
7901 * Drop uring mutex before waiting for references to exit. If
7902 * another thread is currently inside io_uring_enter() it might
7903 * need to grab the uring_lock to make progress. If we hold it
7904 * here across the drain wait, then we can deadlock. It's safe
7905 * to drop the mutex here, since no new references will come in
7906 * after we've killed the percpu ref.
7908 mutex_unlock(&ctx->uring_lock);
7909 ret = wait_for_completion_interruptible(&ctx->completions[0]);
7910 mutex_lock(&ctx->uring_lock);
7912 percpu_ref_resurrect(&ctx->refs);
7919 case IORING_REGISTER_BUFFERS:
7920 ret = io_sqe_buffer_register(ctx, arg, nr_args);
7922 case IORING_UNREGISTER_BUFFERS:
7926 ret = io_sqe_buffer_unregister(ctx);
7928 case IORING_REGISTER_FILES:
7929 ret = io_sqe_files_register(ctx, arg, nr_args);
7931 case IORING_UNREGISTER_FILES:
7935 ret = io_sqe_files_unregister(ctx);
7937 case IORING_REGISTER_FILES_UPDATE:
7938 ret = io_sqe_files_update(ctx, arg, nr_args);
7940 case IORING_REGISTER_EVENTFD:
7941 case IORING_REGISTER_EVENTFD_ASYNC:
7945 ret = io_eventfd_register(ctx, arg);
7948 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
7949 ctx->eventfd_async = 1;
7951 ctx->eventfd_async = 0;
7953 case IORING_UNREGISTER_EVENTFD:
7957 ret = io_eventfd_unregister(ctx);
7959 case IORING_REGISTER_PROBE:
7961 if (!arg || nr_args > 256)
7963 ret = io_probe(ctx, arg, nr_args);
7965 case IORING_REGISTER_PERSONALITY:
7969 ret = io_register_personality(ctx);
7971 case IORING_UNREGISTER_PERSONALITY:
7975 ret = io_unregister_personality(ctx, nr_args);
7982 if (io_register_op_must_quiesce(opcode)) {
7983 /* bring the ctx back to life */
7984 percpu_ref_reinit(&ctx->refs);
7986 reinit_completion(&ctx->completions[0]);
7991 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7992 void __user *, arg, unsigned int, nr_args)
7994 struct io_ring_ctx *ctx;
8003 if (f.file->f_op != &io_uring_fops)
8006 ctx = f.file->private_data;
8008 mutex_lock(&ctx->uring_lock);
8009 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8010 mutex_unlock(&ctx->uring_lock);
8011 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8012 ctx->cq_ev_fd != NULL, ret);
8018 static int __init io_uring_init(void)
8020 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8021 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8022 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8025 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8026 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8027 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8028 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8029 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8030 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8031 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8032 BUILD_BUG_SQE_ELEM(8, __u64, off);
8033 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8034 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8035 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8036 BUILD_BUG_SQE_ELEM(24, __u32, len);
8037 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8038 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8039 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8040 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8041 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
8042 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8043 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8044 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8045 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8046 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8047 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8048 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8049 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8050 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8051 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8052 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8053 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8054 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8056 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8057 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8058 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8061 __initcall(io_uring_init);