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/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.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.
157 * Written by the application, shouldn't be modified by the
162 * Number of completion events lost because the queue was full;
163 * this should be avoided by the application by making sure
164 * there are not more requests pending than there is space in
165 * the completion queue.
167 * Written by the kernel, shouldn't be modified by the
168 * application (i.e. get number of "new events" by comparing to
171 * As completion events come in out of order this counter is not
172 * ordered with any other data.
176 * Ring buffer of completion events.
178 * The kernel writes completion events fresh every time they are
179 * produced, so the application is allowed to modify pending
182 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
185 struct io_mapped_ubuf {
188 struct bio_vec *bvec;
189 unsigned int nr_bvecs;
192 struct fixed_file_table {
196 struct fixed_file_ref_node {
197 struct percpu_ref refs;
198 struct list_head node;
199 struct list_head file_list;
200 struct fixed_file_data *file_data;
201 struct llist_node llist;
204 struct fixed_file_data {
205 struct fixed_file_table *table;
206 struct io_ring_ctx *ctx;
208 struct percpu_ref *cur_refs;
209 struct percpu_ref refs;
210 struct completion done;
211 struct list_head ref_list;
216 struct list_head list;
224 struct percpu_ref refs;
225 } ____cacheline_aligned_in_smp;
229 unsigned int compat: 1;
230 unsigned int limit_mem: 1;
231 unsigned int cq_overflow_flushed: 1;
232 unsigned int drain_next: 1;
233 unsigned int eventfd_async: 1;
236 * Ring buffer of indices into array of io_uring_sqe, which is
237 * mmapped by the application using the IORING_OFF_SQES offset.
239 * This indirection could e.g. be used to assign fixed
240 * io_uring_sqe entries to operations and only submit them to
241 * the queue when needed.
243 * The kernel modifies neither the indices array nor the entries
247 unsigned cached_sq_head;
250 unsigned sq_thread_idle;
251 unsigned cached_sq_dropped;
252 atomic_t cached_cq_overflow;
253 unsigned long sq_check_overflow;
255 struct list_head defer_list;
256 struct list_head timeout_list;
257 struct list_head cq_overflow_list;
259 wait_queue_head_t inflight_wait;
260 struct io_uring_sqe *sq_sqes;
261 } ____cacheline_aligned_in_smp;
263 struct io_rings *rings;
267 struct task_struct *sqo_thread; /* if using sq thread polling */
268 struct mm_struct *sqo_mm;
269 wait_queue_head_t sqo_wait;
272 * If used, fixed file set. Writers must ensure that ->refs is dead,
273 * readers must ensure that ->refs is alive as long as the file* is
274 * used. Only updated through io_uring_register(2).
276 struct fixed_file_data *file_data;
277 unsigned nr_user_files;
279 struct file *ring_file;
281 /* if used, fixed mapped user buffers */
282 unsigned nr_user_bufs;
283 struct io_mapped_ubuf *user_bufs;
285 struct user_struct *user;
287 const struct cred *creds;
289 struct completion ref_comp;
290 struct completion sq_thread_comp;
292 /* if all else fails... */
293 struct io_kiocb *fallback_req;
295 #if defined(CONFIG_UNIX)
296 struct socket *ring_sock;
299 struct idr io_buffer_idr;
301 struct idr personality_idr;
304 unsigned cached_cq_tail;
307 atomic_t cq_timeouts;
308 unsigned long cq_check_overflow;
309 struct wait_queue_head cq_wait;
310 struct fasync_struct *cq_fasync;
311 struct eventfd_ctx *cq_ev_fd;
312 } ____cacheline_aligned_in_smp;
315 struct mutex uring_lock;
316 wait_queue_head_t wait;
317 } ____cacheline_aligned_in_smp;
320 spinlock_t completion_lock;
323 * ->poll_list is protected by the ctx->uring_lock for
324 * io_uring instances that don't use IORING_SETUP_SQPOLL.
325 * For SQPOLL, only the single threaded io_sq_thread() will
326 * manipulate the list, hence no extra locking is needed there.
328 struct list_head poll_list;
329 struct hlist_head *cancel_hash;
330 unsigned cancel_hash_bits;
331 bool poll_multi_file;
333 spinlock_t inflight_lock;
334 struct list_head inflight_list;
335 } ____cacheline_aligned_in_smp;
337 struct delayed_work file_put_work;
338 struct llist_head file_put_llist;
340 struct work_struct exit_work;
344 * First field must be the file pointer in all the
345 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
347 struct io_poll_iocb {
350 struct wait_queue_head *head;
356 struct wait_queue_entry wait;
361 struct file *put_file;
365 struct io_timeout_data {
366 struct io_kiocb *req;
367 struct hrtimer timer;
368 struct timespec64 ts;
369 enum hrtimer_mode mode;
374 struct sockaddr __user *addr;
375 int __user *addr_len;
377 unsigned long nofile;
402 /* NOTE: kiocb has the file as the first member, so don't do it here */
410 struct sockaddr __user *addr;
417 struct user_msghdr __user *msg;
423 struct io_buffer *kbuf;
429 struct filename *filename;
431 unsigned long nofile;
434 struct io_files_update {
460 struct epoll_event event;
464 struct file *file_out;
465 struct file *file_in;
472 struct io_provide_buf {
486 const char __user *filename;
487 struct statx __user *buffer;
490 struct io_async_connect {
491 struct sockaddr_storage address;
494 struct io_async_msghdr {
495 struct iovec fast_iov[UIO_FASTIOV];
497 struct sockaddr __user *uaddr;
499 struct sockaddr_storage addr;
503 struct iovec fast_iov[UIO_FASTIOV];
507 struct wait_page_queue wpq;
508 struct callback_head task_work;
511 struct io_async_ctx {
513 struct io_async_rw rw;
514 struct io_async_msghdr msg;
515 struct io_async_connect connect;
516 struct io_timeout_data timeout;
521 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
522 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
523 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
524 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
525 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
526 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
534 REQ_F_LINK_TIMEOUT_BIT,
537 REQ_F_TIMEOUT_NOSEQ_BIT,
538 REQ_F_COMP_LOCKED_BIT,
539 REQ_F_NEED_CLEANUP_BIT,
542 REQ_F_BUFFER_SELECTED_BIT,
543 REQ_F_NO_FILE_TABLE_BIT,
544 REQ_F_QUEUE_TIMEOUT_BIT,
545 REQ_F_WORK_INITIALIZED_BIT,
546 REQ_F_TASK_PINNED_BIT,
548 /* not a real bit, just to check we're not overflowing the space */
554 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
555 /* drain existing IO first */
556 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
558 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
559 /* doesn't sever on completion < 0 */
560 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
562 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
563 /* IOSQE_BUFFER_SELECT */
564 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
567 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
568 /* already grabbed next link */
569 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
570 /* fail rest of links */
571 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
572 /* on inflight list */
573 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
574 /* read/write uses file position */
575 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
576 /* must not punt to workers */
577 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
578 /* has linked timeout */
579 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
580 /* timeout request */
581 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
583 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
584 /* no timeout sequence */
585 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
586 /* completion under lock */
587 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
589 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
590 /* in overflow list */
591 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
592 /* already went through poll handler */
593 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
594 /* buffer already selected */
595 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
596 /* doesn't need file table for this request */
597 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
598 /* needs to queue linked timeout */
599 REQ_F_QUEUE_TIMEOUT = BIT(REQ_F_QUEUE_TIMEOUT_BIT),
600 /* io_wq_work is initialized */
601 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
602 /* req->task is refcounted */
603 REQ_F_TASK_PINNED = BIT(REQ_F_TASK_PINNED_BIT),
607 struct io_poll_iocb poll;
608 struct io_wq_work work;
612 * NOTE! Each of the iocb union members has the file pointer
613 * as the first entry in their struct definition. So you can
614 * access the file pointer through any of the sub-structs,
615 * or directly as just 'ki_filp' in this struct.
621 struct io_poll_iocb poll;
622 struct io_accept accept;
624 struct io_cancel cancel;
625 struct io_timeout timeout;
626 struct io_connect connect;
627 struct io_sr_msg sr_msg;
629 struct io_close close;
630 struct io_files_update files_update;
631 struct io_fadvise fadvise;
632 struct io_madvise madvise;
633 struct io_epoll epoll;
634 struct io_splice splice;
635 struct io_provide_buf pbuf;
636 struct io_statx statx;
639 struct io_async_ctx *io;
642 /* polled IO has completed */
647 struct io_ring_ctx *ctx;
648 struct list_head list;
651 struct task_struct *task;
657 struct list_head link_list;
659 struct list_head inflight_entry;
661 struct percpu_ref *fixed_file_refs;
665 * Only commands that never go async can use the below fields,
666 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
667 * async armed poll handlers for regular commands. The latter
668 * restore the work, if needed.
671 struct callback_head task_work;
672 struct hlist_node hash_node;
673 struct async_poll *apoll;
675 struct io_wq_work work;
679 #define IO_IOPOLL_BATCH 8
681 struct io_comp_state {
683 struct list_head list;
684 struct io_ring_ctx *ctx;
687 struct io_submit_state {
688 struct blk_plug plug;
691 * io_kiocb alloc cache
693 void *reqs[IO_IOPOLL_BATCH];
694 unsigned int free_reqs;
697 * Batch completion logic
699 struct io_comp_state comp;
702 * File reference cache
706 unsigned int has_refs;
707 unsigned int used_refs;
708 unsigned int ios_left;
712 /* needs req->io allocated for deferral/async */
713 unsigned async_ctx : 1;
714 /* needs current->mm setup, does mm access */
715 unsigned needs_mm : 1;
716 /* needs req->file assigned */
717 unsigned needs_file : 1;
718 /* don't fail if file grab fails */
719 unsigned needs_file_no_error : 1;
720 /* hash wq insertion if file is a regular file */
721 unsigned hash_reg_file : 1;
722 /* unbound wq insertion if file is a non-regular file */
723 unsigned unbound_nonreg_file : 1;
724 /* opcode is not supported by this kernel */
725 unsigned not_supported : 1;
726 /* needs file table */
727 unsigned file_table : 1;
729 unsigned needs_fs : 1;
730 /* set if opcode supports polled "wait" */
732 unsigned pollout : 1;
733 /* op supports buffer selection */
734 unsigned buffer_select : 1;
737 static const struct io_op_def io_op_defs[] = {
738 [IORING_OP_NOP] = {},
739 [IORING_OP_READV] = {
743 .unbound_nonreg_file = 1,
747 [IORING_OP_WRITEV] = {
752 .unbound_nonreg_file = 1,
755 [IORING_OP_FSYNC] = {
758 [IORING_OP_READ_FIXED] = {
760 .unbound_nonreg_file = 1,
763 [IORING_OP_WRITE_FIXED] = {
766 .unbound_nonreg_file = 1,
769 [IORING_OP_POLL_ADD] = {
771 .unbound_nonreg_file = 1,
773 [IORING_OP_POLL_REMOVE] = {},
774 [IORING_OP_SYNC_FILE_RANGE] = {
777 [IORING_OP_SENDMSG] = {
781 .unbound_nonreg_file = 1,
785 [IORING_OP_RECVMSG] = {
789 .unbound_nonreg_file = 1,
794 [IORING_OP_TIMEOUT] = {
798 [IORING_OP_TIMEOUT_REMOVE] = {},
799 [IORING_OP_ACCEPT] = {
802 .unbound_nonreg_file = 1,
806 [IORING_OP_ASYNC_CANCEL] = {},
807 [IORING_OP_LINK_TIMEOUT] = {
811 [IORING_OP_CONNECT] = {
815 .unbound_nonreg_file = 1,
818 [IORING_OP_FALLOCATE] = {
821 [IORING_OP_OPENAT] = {
825 [IORING_OP_CLOSE] = {
827 .needs_file_no_error = 1,
830 [IORING_OP_FILES_UPDATE] = {
834 [IORING_OP_STATX] = {
842 .unbound_nonreg_file = 1,
846 [IORING_OP_WRITE] = {
849 .unbound_nonreg_file = 1,
852 [IORING_OP_FADVISE] = {
855 [IORING_OP_MADVISE] = {
861 .unbound_nonreg_file = 1,
867 .unbound_nonreg_file = 1,
871 [IORING_OP_OPENAT2] = {
875 [IORING_OP_EPOLL_CTL] = {
876 .unbound_nonreg_file = 1,
879 [IORING_OP_SPLICE] = {
882 .unbound_nonreg_file = 1,
884 [IORING_OP_PROVIDE_BUFFERS] = {},
885 [IORING_OP_REMOVE_BUFFERS] = {},
889 .unbound_nonreg_file = 1,
893 enum io_mem_account {
898 static void io_wq_submit_work(struct io_wq_work **workptr);
899 static void io_cqring_fill_event(struct io_kiocb *req, long res);
900 static void io_put_req(struct io_kiocb *req);
901 static void __io_double_put_req(struct io_kiocb *req);
902 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
903 static void io_queue_linked_timeout(struct io_kiocb *req);
904 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
905 struct io_uring_files_update *ip,
907 static int io_grab_files(struct io_kiocb *req);
908 static void io_cleanup_req(struct io_kiocb *req);
909 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
910 int fd, struct file **out_file, bool fixed);
911 static void __io_queue_sqe(struct io_kiocb *req,
912 const struct io_uring_sqe *sqe,
913 struct io_comp_state *cs);
915 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
916 struct iovec **iovec, struct iov_iter *iter,
918 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
919 struct iovec *iovec, struct iovec *fast_iov,
920 struct iov_iter *iter);
922 static struct kmem_cache *req_cachep;
924 static const struct file_operations io_uring_fops;
926 struct sock *io_uring_get_socket(struct file *file)
928 #if defined(CONFIG_UNIX)
929 if (file->f_op == &io_uring_fops) {
930 struct io_ring_ctx *ctx = file->private_data;
932 return ctx->ring_sock->sk;
937 EXPORT_SYMBOL(io_uring_get_socket);
939 static void io_get_req_task(struct io_kiocb *req)
941 if (req->flags & REQ_F_TASK_PINNED)
943 get_task_struct(req->task);
944 req->flags |= REQ_F_TASK_PINNED;
947 /* not idempotent -- it doesn't clear REQ_F_TASK_PINNED */
948 static void __io_put_req_task(struct io_kiocb *req)
950 if (req->flags & REQ_F_TASK_PINNED)
951 put_task_struct(req->task);
954 static void io_file_put_work(struct work_struct *work);
957 * Note: must call io_req_init_async() for the first time you
958 * touch any members of io_wq_work.
960 static inline void io_req_init_async(struct io_kiocb *req)
962 if (req->flags & REQ_F_WORK_INITIALIZED)
965 memset(&req->work, 0, sizeof(req->work));
966 req->flags |= REQ_F_WORK_INITIALIZED;
969 static inline bool io_async_submit(struct io_ring_ctx *ctx)
971 return ctx->flags & IORING_SETUP_SQPOLL;
974 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
976 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
978 complete(&ctx->ref_comp);
981 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
983 struct io_ring_ctx *ctx;
986 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
990 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
991 if (!ctx->fallback_req)
995 * Use 5 bits less than the max cq entries, that should give us around
996 * 32 entries per hash list if totally full and uniformly spread.
998 hash_bits = ilog2(p->cq_entries);
1002 ctx->cancel_hash_bits = hash_bits;
1003 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1005 if (!ctx->cancel_hash)
1007 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1009 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1010 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1013 ctx->flags = p->flags;
1014 init_waitqueue_head(&ctx->sqo_wait);
1015 init_waitqueue_head(&ctx->cq_wait);
1016 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1017 init_completion(&ctx->ref_comp);
1018 init_completion(&ctx->sq_thread_comp);
1019 idr_init(&ctx->io_buffer_idr);
1020 idr_init(&ctx->personality_idr);
1021 mutex_init(&ctx->uring_lock);
1022 init_waitqueue_head(&ctx->wait);
1023 spin_lock_init(&ctx->completion_lock);
1024 INIT_LIST_HEAD(&ctx->poll_list);
1025 INIT_LIST_HEAD(&ctx->defer_list);
1026 INIT_LIST_HEAD(&ctx->timeout_list);
1027 init_waitqueue_head(&ctx->inflight_wait);
1028 spin_lock_init(&ctx->inflight_lock);
1029 INIT_LIST_HEAD(&ctx->inflight_list);
1030 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1031 init_llist_head(&ctx->file_put_llist);
1034 if (ctx->fallback_req)
1035 kmem_cache_free(req_cachep, ctx->fallback_req);
1036 kfree(ctx->cancel_hash);
1041 static inline bool __req_need_defer(struct io_kiocb *req)
1043 struct io_ring_ctx *ctx = req->ctx;
1045 return req->sequence != ctx->cached_cq_tail
1046 + atomic_read(&ctx->cached_cq_overflow);
1049 static inline bool req_need_defer(struct io_kiocb *req)
1051 if (unlikely(req->flags & REQ_F_IO_DRAIN))
1052 return __req_need_defer(req);
1057 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1059 struct io_rings *rings = ctx->rings;
1061 /* order cqe stores with ring update */
1062 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1064 if (wq_has_sleeper(&ctx->cq_wait)) {
1065 wake_up_interruptible(&ctx->cq_wait);
1066 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1070 static inline void io_req_work_grab_env(struct io_kiocb *req,
1071 const struct io_op_def *def)
1073 if (!req->work.mm && def->needs_mm) {
1074 mmgrab(current->mm);
1075 req->work.mm = current->mm;
1077 if (!req->work.creds)
1078 req->work.creds = get_current_cred();
1079 if (!req->work.fs && def->needs_fs) {
1080 spin_lock(¤t->fs->lock);
1081 if (!current->fs->in_exec) {
1082 req->work.fs = current->fs;
1083 req->work.fs->users++;
1085 req->work.flags |= IO_WQ_WORK_CANCEL;
1087 spin_unlock(¤t->fs->lock);
1091 static inline void io_req_work_drop_env(struct io_kiocb *req)
1093 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1097 mmdrop(req->work.mm);
1098 req->work.mm = NULL;
1100 if (req->work.creds) {
1101 put_cred(req->work.creds);
1102 req->work.creds = NULL;
1105 struct fs_struct *fs = req->work.fs;
1107 spin_lock(&req->work.fs->lock);
1110 spin_unlock(&req->work.fs->lock);
1116 static inline void io_prep_async_work(struct io_kiocb *req,
1117 struct io_kiocb **link)
1119 const struct io_op_def *def = &io_op_defs[req->opcode];
1121 if (req->flags & REQ_F_ISREG) {
1122 if (def->hash_reg_file)
1123 io_wq_hash_work(&req->work, file_inode(req->file));
1125 if (def->unbound_nonreg_file)
1126 req->work.flags |= IO_WQ_WORK_UNBOUND;
1129 io_req_init_async(req);
1130 io_req_work_grab_env(req, def);
1132 *link = io_prep_linked_timeout(req);
1135 static inline void io_queue_async_work(struct io_kiocb *req)
1137 struct io_ring_ctx *ctx = req->ctx;
1138 struct io_kiocb *link;
1140 io_prep_async_work(req, &link);
1142 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1143 &req->work, req->flags);
1144 io_wq_enqueue(ctx->io_wq, &req->work);
1147 io_queue_linked_timeout(link);
1150 static void io_kill_timeout(struct io_kiocb *req)
1154 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1156 atomic_inc(&req->ctx->cq_timeouts);
1157 list_del_init(&req->list);
1158 req->flags |= REQ_F_COMP_LOCKED;
1159 io_cqring_fill_event(req, 0);
1164 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1166 struct io_kiocb *req, *tmp;
1168 spin_lock_irq(&ctx->completion_lock);
1169 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1170 io_kill_timeout(req);
1171 spin_unlock_irq(&ctx->completion_lock);
1174 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1177 struct io_kiocb *req = list_first_entry(&ctx->defer_list,
1178 struct io_kiocb, list);
1180 if (req_need_defer(req))
1182 list_del_init(&req->list);
1183 io_queue_async_work(req);
1184 } while (!list_empty(&ctx->defer_list));
1187 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1189 while (!list_empty(&ctx->timeout_list)) {
1190 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1191 struct io_kiocb, list);
1193 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
1195 if (req->timeout.target_seq != ctx->cached_cq_tail
1196 - atomic_read(&ctx->cq_timeouts))
1199 list_del_init(&req->list);
1200 io_kill_timeout(req);
1204 static void io_commit_cqring(struct io_ring_ctx *ctx)
1206 io_flush_timeouts(ctx);
1207 __io_commit_cqring(ctx);
1209 if (unlikely(!list_empty(&ctx->defer_list)))
1210 __io_queue_deferred(ctx);
1213 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1215 struct io_rings *rings = ctx->rings;
1218 tail = ctx->cached_cq_tail;
1220 * writes to the cq entry need to come after reading head; the
1221 * control dependency is enough as we're using WRITE_ONCE to
1224 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1227 ctx->cached_cq_tail++;
1228 return &rings->cqes[tail & ctx->cq_mask];
1231 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1235 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1237 if (!ctx->eventfd_async)
1239 return io_wq_current_is_worker();
1242 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1244 if (waitqueue_active(&ctx->wait))
1245 wake_up(&ctx->wait);
1246 if (waitqueue_active(&ctx->sqo_wait))
1247 wake_up(&ctx->sqo_wait);
1248 if (io_should_trigger_evfd(ctx))
1249 eventfd_signal(ctx->cq_ev_fd, 1);
1252 /* Returns true if there are no backlogged entries after the flush */
1253 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1255 struct io_rings *rings = ctx->rings;
1256 struct io_uring_cqe *cqe;
1257 struct io_kiocb *req;
1258 unsigned long flags;
1262 if (list_empty_careful(&ctx->cq_overflow_list))
1264 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1265 rings->cq_ring_entries))
1269 spin_lock_irqsave(&ctx->completion_lock, flags);
1271 /* if force is set, the ring is going away. always drop after that */
1273 ctx->cq_overflow_flushed = 1;
1276 while (!list_empty(&ctx->cq_overflow_list)) {
1277 cqe = io_get_cqring(ctx);
1281 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1283 list_move(&req->list, &list);
1284 req->flags &= ~REQ_F_OVERFLOW;
1286 WRITE_ONCE(cqe->user_data, req->user_data);
1287 WRITE_ONCE(cqe->res, req->result);
1288 WRITE_ONCE(cqe->flags, req->cflags);
1290 WRITE_ONCE(ctx->rings->cq_overflow,
1291 atomic_inc_return(&ctx->cached_cq_overflow));
1295 io_commit_cqring(ctx);
1297 clear_bit(0, &ctx->sq_check_overflow);
1298 clear_bit(0, &ctx->cq_check_overflow);
1300 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1301 io_cqring_ev_posted(ctx);
1303 while (!list_empty(&list)) {
1304 req = list_first_entry(&list, struct io_kiocb, list);
1305 list_del(&req->list);
1312 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1314 struct io_ring_ctx *ctx = req->ctx;
1315 struct io_uring_cqe *cqe;
1317 trace_io_uring_complete(ctx, req->user_data, res);
1320 * If we can't get a cq entry, userspace overflowed the
1321 * submission (by quite a lot). Increment the overflow count in
1324 cqe = io_get_cqring(ctx);
1326 WRITE_ONCE(cqe->user_data, req->user_data);
1327 WRITE_ONCE(cqe->res, res);
1328 WRITE_ONCE(cqe->flags, cflags);
1329 } else if (ctx->cq_overflow_flushed) {
1330 WRITE_ONCE(ctx->rings->cq_overflow,
1331 atomic_inc_return(&ctx->cached_cq_overflow));
1333 if (list_empty(&ctx->cq_overflow_list)) {
1334 set_bit(0, &ctx->sq_check_overflow);
1335 set_bit(0, &ctx->cq_check_overflow);
1337 req->flags |= REQ_F_OVERFLOW;
1338 refcount_inc(&req->refs);
1340 req->cflags = cflags;
1341 list_add_tail(&req->list, &ctx->cq_overflow_list);
1345 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1347 __io_cqring_fill_event(req, res, 0);
1350 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1352 struct io_ring_ctx *ctx = req->ctx;
1353 unsigned long flags;
1355 spin_lock_irqsave(&ctx->completion_lock, flags);
1356 __io_cqring_fill_event(req, res, cflags);
1357 io_commit_cqring(ctx);
1358 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1360 io_cqring_ev_posted(ctx);
1363 static void io_submit_flush_completions(struct io_comp_state *cs)
1365 struct io_ring_ctx *ctx = cs->ctx;
1367 spin_lock_irq(&ctx->completion_lock);
1368 while (!list_empty(&cs->list)) {
1369 struct io_kiocb *req;
1371 req = list_first_entry(&cs->list, struct io_kiocb, list);
1372 list_del(&req->list);
1373 io_cqring_fill_event(req, req->result);
1374 if (!(req->flags & REQ_F_LINK_HEAD)) {
1375 req->flags |= REQ_F_COMP_LOCKED;
1378 spin_unlock_irq(&ctx->completion_lock);
1380 spin_lock_irq(&ctx->completion_lock);
1383 io_commit_cqring(ctx);
1384 spin_unlock_irq(&ctx->completion_lock);
1386 io_cqring_ev_posted(ctx);
1390 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1391 struct io_comp_state *cs)
1394 io_cqring_add_event(req, res, cflags);
1398 list_add_tail(&req->list, &cs->list);
1400 io_submit_flush_completions(cs);
1404 static void io_req_complete(struct io_kiocb *req, long res)
1406 __io_req_complete(req, res, 0, NULL);
1409 static inline bool io_is_fallback_req(struct io_kiocb *req)
1411 return req == (struct io_kiocb *)
1412 ((unsigned long) req->ctx->fallback_req & ~1UL);
1415 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1417 struct io_kiocb *req;
1419 req = ctx->fallback_req;
1420 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1426 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1427 struct io_submit_state *state)
1429 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1430 struct io_kiocb *req;
1432 if (!state->free_reqs) {
1436 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1437 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1440 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1441 * retry single alloc to be on the safe side.
1443 if (unlikely(ret <= 0)) {
1444 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1445 if (!state->reqs[0])
1449 state->free_reqs = ret - 1;
1450 req = state->reqs[ret - 1];
1453 req = state->reqs[state->free_reqs];
1458 return io_get_fallback_req(ctx);
1461 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1465 percpu_ref_put(req->fixed_file_refs);
1470 static void __io_req_aux_free(struct io_kiocb *req)
1472 if (req->flags & REQ_F_NEED_CLEANUP)
1473 io_cleanup_req(req);
1477 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1478 __io_put_req_task(req);
1479 io_req_work_drop_env(req);
1482 static void __io_free_req(struct io_kiocb *req)
1484 __io_req_aux_free(req);
1486 if (req->flags & REQ_F_INFLIGHT) {
1487 struct io_ring_ctx *ctx = req->ctx;
1488 unsigned long flags;
1490 spin_lock_irqsave(&ctx->inflight_lock, flags);
1491 list_del(&req->inflight_entry);
1492 if (waitqueue_active(&ctx->inflight_wait))
1493 wake_up(&ctx->inflight_wait);
1494 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1497 percpu_ref_put(&req->ctx->refs);
1498 if (likely(!io_is_fallback_req(req)))
1499 kmem_cache_free(req_cachep, req);
1501 clear_bit_unlock(0, (unsigned long *) &req->ctx->fallback_req);
1505 void *reqs[IO_IOPOLL_BATCH];
1510 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1514 if (rb->need_iter) {
1515 int i, inflight = 0;
1516 unsigned long flags;
1518 for (i = 0; i < rb->to_free; i++) {
1519 struct io_kiocb *req = rb->reqs[i];
1521 if (req->flags & REQ_F_INFLIGHT)
1523 __io_req_aux_free(req);
1528 spin_lock_irqsave(&ctx->inflight_lock, flags);
1529 for (i = 0; i < rb->to_free; i++) {
1530 struct io_kiocb *req = rb->reqs[i];
1532 if (req->flags & REQ_F_INFLIGHT) {
1533 list_del(&req->inflight_entry);
1538 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1540 if (waitqueue_active(&ctx->inflight_wait))
1541 wake_up(&ctx->inflight_wait);
1544 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1545 percpu_ref_put_many(&ctx->refs, rb->to_free);
1546 rb->to_free = rb->need_iter = 0;
1549 static bool io_link_cancel_timeout(struct io_kiocb *req)
1551 struct io_ring_ctx *ctx = req->ctx;
1554 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1556 io_cqring_fill_event(req, -ECANCELED);
1557 io_commit_cqring(ctx);
1558 req->flags &= ~REQ_F_LINK_HEAD;
1566 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1568 struct io_ring_ctx *ctx = req->ctx;
1569 bool wake_ev = false;
1571 /* Already got next link */
1572 if (req->flags & REQ_F_LINK_NEXT)
1576 * The list should never be empty when we are called here. But could
1577 * potentially happen if the chain is messed up, check to be on the
1580 while (!list_empty(&req->link_list)) {
1581 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1582 struct io_kiocb, link_list);
1584 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1585 (nxt->flags & REQ_F_TIMEOUT))) {
1586 list_del_init(&nxt->link_list);
1587 wake_ev |= io_link_cancel_timeout(nxt);
1588 req->flags &= ~REQ_F_LINK_TIMEOUT;
1592 list_del_init(&req->link_list);
1593 if (!list_empty(&nxt->link_list))
1594 nxt->flags |= REQ_F_LINK_HEAD;
1599 req->flags |= REQ_F_LINK_NEXT;
1601 io_cqring_ev_posted(ctx);
1605 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1607 static void io_fail_links(struct io_kiocb *req)
1609 struct io_ring_ctx *ctx = req->ctx;
1610 unsigned long flags;
1612 spin_lock_irqsave(&ctx->completion_lock, flags);
1614 while (!list_empty(&req->link_list)) {
1615 struct io_kiocb *link = list_first_entry(&req->link_list,
1616 struct io_kiocb, link_list);
1618 list_del_init(&link->link_list);
1619 trace_io_uring_fail_link(req, link);
1621 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1622 link->opcode == IORING_OP_LINK_TIMEOUT) {
1623 io_link_cancel_timeout(link);
1625 io_cqring_fill_event(link, -ECANCELED);
1626 __io_double_put_req(link);
1628 req->flags &= ~REQ_F_LINK_TIMEOUT;
1631 io_commit_cqring(ctx);
1632 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1633 io_cqring_ev_posted(ctx);
1636 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1638 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1642 * If LINK is set, we have dependent requests in this chain. If we
1643 * didn't fail this request, queue the first one up, moving any other
1644 * dependencies to the next request. In case of failure, fail the rest
1647 if (req->flags & REQ_F_FAIL_LINK) {
1649 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1650 REQ_F_LINK_TIMEOUT) {
1651 struct io_ring_ctx *ctx = req->ctx;
1652 unsigned long flags;
1655 * If this is a timeout link, we could be racing with the
1656 * timeout timer. Grab the completion lock for this case to
1657 * protect against that.
1659 spin_lock_irqsave(&ctx->completion_lock, flags);
1660 io_req_link_next(req, nxt);
1661 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1663 io_req_link_next(req, nxt);
1667 static void io_free_req(struct io_kiocb *req)
1669 struct io_kiocb *nxt = NULL;
1671 io_req_find_next(req, &nxt);
1675 io_queue_async_work(nxt);
1678 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
1680 struct io_kiocb *link;
1681 const struct io_op_def *def = &io_op_defs[nxt->opcode];
1683 if ((nxt->flags & REQ_F_ISREG) && def->hash_reg_file)
1684 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1686 *workptr = &nxt->work;
1687 link = io_prep_linked_timeout(nxt);
1689 nxt->flags |= REQ_F_QUEUE_TIMEOUT;
1693 * Drop reference to request, return next in chain (if there is one) if this
1694 * was the last reference to this request.
1696 __attribute__((nonnull))
1697 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1699 if (refcount_dec_and_test(&req->refs)) {
1700 io_req_find_next(req, nxtptr);
1705 static void io_put_req(struct io_kiocb *req)
1707 if (refcount_dec_and_test(&req->refs))
1711 static void io_steal_work(struct io_kiocb *req,
1712 struct io_wq_work **workptr)
1715 * It's in an io-wq worker, so there always should be at least
1716 * one reference, which will be dropped in io_put_work() just
1717 * after the current handler returns.
1719 * It also means, that if the counter dropped to 1, then there is
1720 * no asynchronous users left, so it's safe to steal the next work.
1722 if (refcount_read(&req->refs) == 1) {
1723 struct io_kiocb *nxt = NULL;
1725 io_req_find_next(req, &nxt);
1727 io_wq_assign_next(workptr, nxt);
1732 * Must only be used if we don't need to care about links, usually from
1733 * within the completion handling itself.
1735 static void __io_double_put_req(struct io_kiocb *req)
1737 /* drop both submit and complete references */
1738 if (refcount_sub_and_test(2, &req->refs))
1742 static void io_double_put_req(struct io_kiocb *req)
1744 /* drop both submit and complete references */
1745 if (refcount_sub_and_test(2, &req->refs))
1749 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1751 struct io_rings *rings = ctx->rings;
1753 if (test_bit(0, &ctx->cq_check_overflow)) {
1755 * noflush == true is from the waitqueue handler, just ensure
1756 * we wake up the task, and the next invocation will flush the
1757 * entries. We cannot safely to it from here.
1759 if (noflush && !list_empty(&ctx->cq_overflow_list))
1762 io_cqring_overflow_flush(ctx, false);
1765 /* See comment at the top of this file */
1767 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1770 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1772 struct io_rings *rings = ctx->rings;
1774 /* make sure SQ entry isn't read before tail */
1775 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1778 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1780 if ((req->flags & REQ_F_LINK_HEAD) || io_is_fallback_req(req))
1783 if (req->file || req->io)
1786 rb->reqs[rb->to_free++] = req;
1787 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1788 io_free_req_many(req->ctx, rb);
1792 static int io_put_kbuf(struct io_kiocb *req)
1794 struct io_buffer *kbuf;
1797 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1798 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1799 cflags |= IORING_CQE_F_BUFFER;
1805 static void io_iopoll_queue(struct list_head *again)
1807 struct io_kiocb *req;
1810 req = list_first_entry(again, struct io_kiocb, list);
1811 list_del(&req->list);
1812 refcount_inc(&req->refs);
1813 io_queue_async_work(req);
1814 } while (!list_empty(again));
1818 * Find and free completed poll iocbs
1820 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1821 struct list_head *done)
1823 struct req_batch rb;
1824 struct io_kiocb *req;
1827 /* order with ->result store in io_complete_rw_iopoll() */
1830 rb.to_free = rb.need_iter = 0;
1831 while (!list_empty(done)) {
1834 req = list_first_entry(done, struct io_kiocb, list);
1835 if (READ_ONCE(req->result) == -EAGAIN) {
1836 req->iopoll_completed = 0;
1837 list_move_tail(&req->list, &again);
1840 list_del(&req->list);
1842 if (req->flags & REQ_F_BUFFER_SELECTED)
1843 cflags = io_put_kbuf(req);
1845 __io_cqring_fill_event(req, req->result, cflags);
1848 if (refcount_dec_and_test(&req->refs) &&
1849 !io_req_multi_free(&rb, req))
1853 io_commit_cqring(ctx);
1854 if (ctx->flags & IORING_SETUP_SQPOLL)
1855 io_cqring_ev_posted(ctx);
1856 io_free_req_many(ctx, &rb);
1858 if (!list_empty(&again))
1859 io_iopoll_queue(&again);
1862 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1865 struct io_kiocb *req, *tmp;
1871 * Only spin for completions if we don't have multiple devices hanging
1872 * off our complete list, and we're under the requested amount.
1874 spin = !ctx->poll_multi_file && *nr_events < min;
1877 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1878 struct kiocb *kiocb = &req->rw.kiocb;
1881 * Move completed and retryable entries to our local lists.
1882 * If we find a request that requires polling, break out
1883 * and complete those lists first, if we have entries there.
1885 if (READ_ONCE(req->iopoll_completed)) {
1886 list_move_tail(&req->list, &done);
1889 if (!list_empty(&done))
1892 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1901 if (!list_empty(&done))
1902 io_iopoll_complete(ctx, nr_events, &done);
1908 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1909 * non-spinning poll check - we'll still enter the driver poll loop, but only
1910 * as a non-spinning completion check.
1912 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1915 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1918 ret = io_do_iopoll(ctx, nr_events, min);
1921 if (!min || *nr_events >= min)
1929 * We can't just wait for polled events to come to us, we have to actively
1930 * find and complete them.
1932 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1934 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1937 mutex_lock(&ctx->uring_lock);
1938 while (!list_empty(&ctx->poll_list)) {
1939 unsigned int nr_events = 0;
1941 io_iopoll_getevents(ctx, &nr_events, 1);
1944 * Ensure we allow local-to-the-cpu processing to take place,
1945 * in this case we need to ensure that we reap all events.
1949 mutex_unlock(&ctx->uring_lock);
1952 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1955 int iters = 0, ret = 0;
1958 * We disallow the app entering submit/complete with polling, but we
1959 * still need to lock the ring to prevent racing with polled issue
1960 * that got punted to a workqueue.
1962 mutex_lock(&ctx->uring_lock);
1967 * Don't enter poll loop if we already have events pending.
1968 * If we do, we can potentially be spinning for commands that
1969 * already triggered a CQE (eg in error).
1971 if (io_cqring_events(ctx, false))
1975 * If a submit got punted to a workqueue, we can have the
1976 * application entering polling for a command before it gets
1977 * issued. That app will hold the uring_lock for the duration
1978 * of the poll right here, so we need to take a breather every
1979 * now and then to ensure that the issue has a chance to add
1980 * the poll to the issued list. Otherwise we can spin here
1981 * forever, while the workqueue is stuck trying to acquire the
1984 if (!(++iters & 7)) {
1985 mutex_unlock(&ctx->uring_lock);
1986 mutex_lock(&ctx->uring_lock);
1989 if (*nr_events < min)
1990 tmin = min - *nr_events;
1992 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1996 } while (min && !*nr_events && !need_resched());
1998 mutex_unlock(&ctx->uring_lock);
2002 static void kiocb_end_write(struct io_kiocb *req)
2005 * Tell lockdep we inherited freeze protection from submission
2008 if (req->flags & REQ_F_ISREG) {
2009 struct inode *inode = file_inode(req->file);
2011 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2013 file_end_write(req->file);
2016 static inline void req_set_fail_links(struct io_kiocb *req)
2018 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
2019 req->flags |= REQ_F_FAIL_LINK;
2022 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2023 struct io_comp_state *cs)
2025 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2028 if (kiocb->ki_flags & IOCB_WRITE)
2029 kiocb_end_write(req);
2031 if (res != req->result)
2032 req_set_fail_links(req);
2033 if (req->flags & REQ_F_BUFFER_SELECTED)
2034 cflags = io_put_kbuf(req);
2035 __io_req_complete(req, res, cflags, cs);
2038 static void io_sq_thread_drop_mm(struct io_ring_ctx *ctx)
2040 struct mm_struct *mm = current->mm;
2043 kthread_unuse_mm(mm);
2048 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
2051 if (unlikely(!mmget_not_zero(ctx->sqo_mm)))
2053 kthread_use_mm(ctx->sqo_mm);
2059 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
2060 struct io_kiocb *req)
2062 if (!io_op_defs[req->opcode].needs_mm)
2064 return __io_sq_thread_acquire_mm(ctx);
2068 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2070 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2071 ssize_t ret = -ECANCELED;
2072 struct iov_iter iter;
2080 switch (req->opcode) {
2081 case IORING_OP_READV:
2082 case IORING_OP_READ_FIXED:
2083 case IORING_OP_READ:
2086 case IORING_OP_WRITEV:
2087 case IORING_OP_WRITE_FIXED:
2088 case IORING_OP_WRITE:
2092 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2097 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2100 ret = io_setup_async_rw(req, ret, iovec, inline_vecs, &iter);
2105 req_set_fail_links(req);
2106 io_req_complete(req, ret);
2110 static void io_rw_resubmit(struct callback_head *cb)
2112 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2113 struct io_ring_ctx *ctx = req->ctx;
2116 __set_current_state(TASK_RUNNING);
2118 err = io_sq_thread_acquire_mm(ctx, req);
2120 if (io_resubmit_prep(req, err)) {
2121 refcount_inc(&req->refs);
2122 io_queue_async_work(req);
2127 static bool io_rw_reissue(struct io_kiocb *req, long res)
2130 struct task_struct *tsk;
2133 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2137 init_task_work(&req->task_work, io_rw_resubmit);
2138 ret = task_work_add(tsk, &req->task_work, true);
2145 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2146 struct io_comp_state *cs)
2148 if (!io_rw_reissue(req, res))
2149 io_complete_rw_common(&req->rw.kiocb, res, cs);
2152 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2154 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2156 __io_complete_rw(req, res, res2, NULL);
2159 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2161 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2163 if (kiocb->ki_flags & IOCB_WRITE)
2164 kiocb_end_write(req);
2166 if (res != -EAGAIN && res != req->result)
2167 req_set_fail_links(req);
2169 WRITE_ONCE(req->result, res);
2170 /* order with io_poll_complete() checking ->result */
2171 if (res != -EAGAIN) {
2173 WRITE_ONCE(req->iopoll_completed, 1);
2178 * After the iocb has been issued, it's safe to be found on the poll list.
2179 * Adding the kiocb to the list AFTER submission ensures that we don't
2180 * find it from a io_iopoll_getevents() thread before the issuer is done
2181 * accessing the kiocb cookie.
2183 static void io_iopoll_req_issued(struct io_kiocb *req)
2185 struct io_ring_ctx *ctx = req->ctx;
2188 * Track whether we have multiple files in our lists. This will impact
2189 * how we do polling eventually, not spinning if we're on potentially
2190 * different devices.
2192 if (list_empty(&ctx->poll_list)) {
2193 ctx->poll_multi_file = false;
2194 } else if (!ctx->poll_multi_file) {
2195 struct io_kiocb *list_req;
2197 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
2199 if (list_req->file != req->file)
2200 ctx->poll_multi_file = true;
2204 * For fast devices, IO may have already completed. If it has, add
2205 * it to the front so we find it first.
2207 if (READ_ONCE(req->iopoll_completed))
2208 list_add(&req->list, &ctx->poll_list);
2210 list_add_tail(&req->list, &ctx->poll_list);
2212 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2213 wq_has_sleeper(&ctx->sqo_wait))
2214 wake_up(&ctx->sqo_wait);
2217 static void __io_state_file_put(struct io_submit_state *state)
2219 int diff = state->has_refs - state->used_refs;
2222 fput_many(state->file, diff);
2226 static inline void io_state_file_put(struct io_submit_state *state)
2229 __io_state_file_put(state);
2233 * Get as many references to a file as we have IOs left in this submission,
2234 * assuming most submissions are for one file, or at least that each file
2235 * has more than one submission.
2237 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2243 if (state->fd == fd) {
2248 __io_state_file_put(state);
2250 state->file = fget_many(fd, state->ios_left);
2255 state->has_refs = state->ios_left;
2256 state->used_refs = 1;
2261 static bool io_bdev_nowait(struct block_device *bdev)
2264 return !bdev || queue_is_mq(bdev_get_queue(bdev));
2271 * If we tracked the file through the SCM inflight mechanism, we could support
2272 * any file. For now, just ensure that anything potentially problematic is done
2275 static bool io_file_supports_async(struct file *file, int rw)
2277 umode_t mode = file_inode(file)->i_mode;
2279 if (S_ISBLK(mode)) {
2280 if (io_bdev_nowait(file->f_inode->i_bdev))
2284 if (S_ISCHR(mode) || S_ISSOCK(mode))
2286 if (S_ISREG(mode)) {
2287 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2288 file->f_op != &io_uring_fops)
2293 /* any ->read/write should understand O_NONBLOCK */
2294 if (file->f_flags & O_NONBLOCK)
2297 if (!(file->f_mode & FMODE_NOWAIT))
2301 return file->f_op->read_iter != NULL;
2303 return file->f_op->write_iter != NULL;
2306 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2307 bool force_nonblock)
2309 struct io_ring_ctx *ctx = req->ctx;
2310 struct kiocb *kiocb = &req->rw.kiocb;
2314 if (S_ISREG(file_inode(req->file)->i_mode))
2315 req->flags |= REQ_F_ISREG;
2317 kiocb->ki_pos = READ_ONCE(sqe->off);
2318 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2319 req->flags |= REQ_F_CUR_POS;
2320 kiocb->ki_pos = req->file->f_pos;
2322 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2323 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2324 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2328 ioprio = READ_ONCE(sqe->ioprio);
2330 ret = ioprio_check_cap(ioprio);
2334 kiocb->ki_ioprio = ioprio;
2336 kiocb->ki_ioprio = get_current_ioprio();
2338 /* don't allow async punt if RWF_NOWAIT was requested */
2339 if (kiocb->ki_flags & IOCB_NOWAIT)
2340 req->flags |= REQ_F_NOWAIT;
2342 if (kiocb->ki_flags & IOCB_DIRECT)
2343 io_get_req_task(req);
2346 kiocb->ki_flags |= IOCB_NOWAIT;
2348 if (ctx->flags & IORING_SETUP_IOPOLL) {
2349 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2350 !kiocb->ki_filp->f_op->iopoll)
2353 kiocb->ki_flags |= IOCB_HIPRI;
2354 kiocb->ki_complete = io_complete_rw_iopoll;
2356 req->iopoll_completed = 0;
2358 if (kiocb->ki_flags & IOCB_HIPRI)
2360 kiocb->ki_complete = io_complete_rw;
2363 req->rw.addr = READ_ONCE(sqe->addr);
2364 req->rw.len = READ_ONCE(sqe->len);
2365 req->buf_index = READ_ONCE(sqe->buf_index);
2369 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2375 case -ERESTARTNOINTR:
2376 case -ERESTARTNOHAND:
2377 case -ERESTART_RESTARTBLOCK:
2379 * We can't just restart the syscall, since previously
2380 * submitted sqes may already be in progress. Just fail this
2386 kiocb->ki_complete(kiocb, ret, 0);
2390 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2391 struct io_comp_state *cs)
2393 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2395 if (req->flags & REQ_F_CUR_POS)
2396 req->file->f_pos = kiocb->ki_pos;
2397 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2398 __io_complete_rw(req, ret, 0, cs);
2400 io_rw_done(kiocb, ret);
2403 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2404 struct iov_iter *iter)
2406 struct io_ring_ctx *ctx = req->ctx;
2407 size_t len = req->rw.len;
2408 struct io_mapped_ubuf *imu;
2409 u16 index, buf_index;
2413 /* attempt to use fixed buffers without having provided iovecs */
2414 if (unlikely(!ctx->user_bufs))
2417 buf_index = req->buf_index;
2418 if (unlikely(buf_index >= ctx->nr_user_bufs))
2421 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2422 imu = &ctx->user_bufs[index];
2423 buf_addr = req->rw.addr;
2426 if (buf_addr + len < buf_addr)
2428 /* not inside the mapped region */
2429 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2433 * May not be a start of buffer, set size appropriately
2434 * and advance us to the beginning.
2436 offset = buf_addr - imu->ubuf;
2437 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2441 * Don't use iov_iter_advance() here, as it's really slow for
2442 * using the latter parts of a big fixed buffer - it iterates
2443 * over each segment manually. We can cheat a bit here, because
2446 * 1) it's a BVEC iter, we set it up
2447 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2448 * first and last bvec
2450 * So just find our index, and adjust the iterator afterwards.
2451 * If the offset is within the first bvec (or the whole first
2452 * bvec, just use iov_iter_advance(). This makes it easier
2453 * since we can just skip the first segment, which may not
2454 * be PAGE_SIZE aligned.
2456 const struct bio_vec *bvec = imu->bvec;
2458 if (offset <= bvec->bv_len) {
2459 iov_iter_advance(iter, offset);
2461 unsigned long seg_skip;
2463 /* skip first vec */
2464 offset -= bvec->bv_len;
2465 seg_skip = 1 + (offset >> PAGE_SHIFT);
2467 iter->bvec = bvec + seg_skip;
2468 iter->nr_segs -= seg_skip;
2469 iter->count -= bvec->bv_len + offset;
2470 iter->iov_offset = offset & ~PAGE_MASK;
2477 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2480 mutex_unlock(&ctx->uring_lock);
2483 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2486 * "Normal" inline submissions always hold the uring_lock, since we
2487 * grab it from the system call. Same is true for the SQPOLL offload.
2488 * The only exception is when we've detached the request and issue it
2489 * from an async worker thread, grab the lock for that case.
2492 mutex_lock(&ctx->uring_lock);
2495 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2496 int bgid, struct io_buffer *kbuf,
2499 struct io_buffer *head;
2501 if (req->flags & REQ_F_BUFFER_SELECTED)
2504 io_ring_submit_lock(req->ctx, needs_lock);
2506 lockdep_assert_held(&req->ctx->uring_lock);
2508 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2510 if (!list_empty(&head->list)) {
2511 kbuf = list_last_entry(&head->list, struct io_buffer,
2513 list_del(&kbuf->list);
2516 idr_remove(&req->ctx->io_buffer_idr, bgid);
2518 if (*len > kbuf->len)
2521 kbuf = ERR_PTR(-ENOBUFS);
2524 io_ring_submit_unlock(req->ctx, needs_lock);
2529 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2532 struct io_buffer *kbuf;
2535 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2536 bgid = req->buf_index;
2537 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2540 req->rw.addr = (u64) (unsigned long) kbuf;
2541 req->flags |= REQ_F_BUFFER_SELECTED;
2542 return u64_to_user_ptr(kbuf->addr);
2545 #ifdef CONFIG_COMPAT
2546 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2549 struct compat_iovec __user *uiov;
2550 compat_ssize_t clen;
2554 uiov = u64_to_user_ptr(req->rw.addr);
2555 if (!access_ok(uiov, sizeof(*uiov)))
2557 if (__get_user(clen, &uiov->iov_len))
2563 buf = io_rw_buffer_select(req, &len, needs_lock);
2565 return PTR_ERR(buf);
2566 iov[0].iov_base = buf;
2567 iov[0].iov_len = (compat_size_t) len;
2572 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2575 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2579 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2582 len = iov[0].iov_len;
2585 buf = io_rw_buffer_select(req, &len, needs_lock);
2587 return PTR_ERR(buf);
2588 iov[0].iov_base = buf;
2589 iov[0].iov_len = len;
2593 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2596 if (req->flags & REQ_F_BUFFER_SELECTED) {
2597 struct io_buffer *kbuf;
2599 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2600 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2601 iov[0].iov_len = kbuf->len;
2606 else if (req->rw.len > 1)
2609 #ifdef CONFIG_COMPAT
2610 if (req->ctx->compat)
2611 return io_compat_import(req, iov, needs_lock);
2614 return __io_iov_buffer_select(req, iov, needs_lock);
2617 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2618 struct iovec **iovec, struct iov_iter *iter,
2621 void __user *buf = u64_to_user_ptr(req->rw.addr);
2622 size_t sqe_len = req->rw.len;
2626 opcode = req->opcode;
2627 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2629 return io_import_fixed(req, rw, iter);
2632 /* buffer index only valid with fixed read/write, or buffer select */
2633 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2636 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2637 if (req->flags & REQ_F_BUFFER_SELECT) {
2638 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2641 return PTR_ERR(buf);
2643 req->rw.len = sqe_len;
2646 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2648 return ret < 0 ? ret : sqe_len;
2652 struct io_async_rw *iorw = &req->io->rw;
2655 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2656 if (iorw->iov == iorw->fast_iov)
2661 if (req->flags & REQ_F_BUFFER_SELECT) {
2662 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2664 ret = (*iovec)->iov_len;
2665 iov_iter_init(iter, rw, *iovec, 1, ret);
2671 #ifdef CONFIG_COMPAT
2672 if (req->ctx->compat)
2673 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2677 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2681 * For files that don't have ->read_iter() and ->write_iter(), handle them
2682 * by looping over ->read() or ->write() manually.
2684 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2685 struct iov_iter *iter)
2690 * Don't support polled IO through this interface, and we can't
2691 * support non-blocking either. For the latter, this just causes
2692 * the kiocb to be handled from an async context.
2694 if (kiocb->ki_flags & IOCB_HIPRI)
2696 if (kiocb->ki_flags & IOCB_NOWAIT)
2699 while (iov_iter_count(iter)) {
2703 if (!iov_iter_is_bvec(iter)) {
2704 iovec = iov_iter_iovec(iter);
2706 /* fixed buffers import bvec */
2707 iovec.iov_base = kmap(iter->bvec->bv_page)
2709 iovec.iov_len = min(iter->count,
2710 iter->bvec->bv_len - iter->iov_offset);
2714 nr = file->f_op->read(file, iovec.iov_base,
2715 iovec.iov_len, &kiocb->ki_pos);
2717 nr = file->f_op->write(file, iovec.iov_base,
2718 iovec.iov_len, &kiocb->ki_pos);
2721 if (iov_iter_is_bvec(iter))
2722 kunmap(iter->bvec->bv_page);
2730 if (nr != iovec.iov_len)
2732 iov_iter_advance(iter, nr);
2738 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2739 struct iovec *iovec, struct iovec *fast_iov,
2740 struct iov_iter *iter)
2742 req->io->rw.nr_segs = iter->nr_segs;
2743 req->io->rw.size = io_size;
2744 req->io->rw.iov = iovec;
2745 if (!req->io->rw.iov) {
2746 req->io->rw.iov = req->io->rw.fast_iov;
2747 if (req->io->rw.iov != fast_iov)
2748 memcpy(req->io->rw.iov, fast_iov,
2749 sizeof(struct iovec) * iter->nr_segs);
2751 req->flags |= REQ_F_NEED_CLEANUP;
2755 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2757 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2758 return req->io == NULL;
2761 static int io_alloc_async_ctx(struct io_kiocb *req)
2763 if (!io_op_defs[req->opcode].async_ctx)
2766 return __io_alloc_async_ctx(req);
2769 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2770 struct iovec *iovec, struct iovec *fast_iov,
2771 struct iov_iter *iter)
2773 if (!io_op_defs[req->opcode].async_ctx)
2776 if (__io_alloc_async_ctx(req))
2779 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2784 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2785 bool force_nonblock)
2787 struct io_async_ctx *io;
2788 struct iov_iter iter;
2791 ret = io_prep_rw(req, sqe, force_nonblock);
2795 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2798 /* either don't need iovec imported or already have it */
2799 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2803 io->rw.iov = io->rw.fast_iov;
2805 ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2810 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2814 static void __io_async_buf_error(struct io_kiocb *req, int error)
2816 struct io_ring_ctx *ctx = req->ctx;
2818 spin_lock_irq(&ctx->completion_lock);
2819 io_cqring_fill_event(req, error);
2820 io_commit_cqring(ctx);
2821 spin_unlock_irq(&ctx->completion_lock);
2823 io_cqring_ev_posted(ctx);
2824 req_set_fail_links(req);
2825 io_double_put_req(req);
2828 static void io_async_buf_cancel(struct callback_head *cb)
2830 struct io_async_rw *rw;
2831 struct io_kiocb *req;
2833 rw = container_of(cb, struct io_async_rw, task_work);
2834 req = rw->wpq.wait.private;
2835 __io_async_buf_error(req, -ECANCELED);
2838 static void io_async_buf_retry(struct callback_head *cb)
2840 struct io_async_rw *rw;
2841 struct io_ring_ctx *ctx;
2842 struct io_kiocb *req;
2844 rw = container_of(cb, struct io_async_rw, task_work);
2845 req = rw->wpq.wait.private;
2848 __set_current_state(TASK_RUNNING);
2849 if (!__io_sq_thread_acquire_mm(ctx)) {
2850 mutex_lock(&ctx->uring_lock);
2851 __io_queue_sqe(req, NULL, NULL);
2852 mutex_unlock(&ctx->uring_lock);
2854 __io_async_buf_error(req, -EFAULT);
2858 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2859 int sync, void *arg)
2861 struct wait_page_queue *wpq;
2862 struct io_kiocb *req = wait->private;
2863 struct io_async_rw *rw = &req->io->rw;
2864 struct wait_page_key *key = arg;
2865 struct task_struct *tsk;
2868 wpq = container_of(wait, struct wait_page_queue, wait);
2870 ret = wake_page_match(wpq, key);
2874 list_del_init(&wait->entry);
2876 init_task_work(&rw->task_work, io_async_buf_retry);
2877 /* submit ref gets dropped, acquire a new one */
2878 refcount_inc(&req->refs);
2880 ret = task_work_add(tsk, &rw->task_work, true);
2881 if (unlikely(ret)) {
2882 /* queue just for cancelation */
2883 init_task_work(&rw->task_work, io_async_buf_cancel);
2884 tsk = io_wq_get_task(req->ctx->io_wq);
2885 task_work_add(tsk, &rw->task_work, true);
2887 wake_up_process(tsk);
2891 static bool io_rw_should_retry(struct io_kiocb *req)
2893 struct kiocb *kiocb = &req->rw.kiocb;
2896 /* never retry for NOWAIT, we just complete with -EAGAIN */
2897 if (req->flags & REQ_F_NOWAIT)
2900 /* already tried, or we're doing O_DIRECT */
2901 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_WAITQ))
2904 * just use poll if we can, and don't attempt if the fs doesn't
2905 * support callback based unlocks
2907 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2911 * If request type doesn't require req->io to defer in general,
2912 * we need to allocate it here
2914 if (!req->io && __io_alloc_async_ctx(req))
2917 ret = kiocb_wait_page_queue_init(kiocb, &req->io->rw.wpq,
2918 io_async_buf_func, req);
2920 io_get_req_task(req);
2927 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
2929 if (req->file->f_op->read_iter)
2930 return call_read_iter(req->file, &req->rw.kiocb, iter);
2931 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
2934 static int io_read(struct io_kiocb *req, bool force_nonblock,
2935 struct io_comp_state *cs)
2937 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2938 struct kiocb *kiocb = &req->rw.kiocb;
2939 struct iov_iter iter;
2941 ssize_t io_size, ret;
2943 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2947 /* Ensure we clear previously set non-block flag */
2948 if (!force_nonblock)
2949 kiocb->ki_flags &= ~IOCB_NOWAIT;
2953 if (req->flags & REQ_F_LINK_HEAD)
2954 req->result = io_size;
2956 /* If the file doesn't support async, just async punt */
2957 if (force_nonblock && !io_file_supports_async(req->file, READ))
2960 iov_count = iov_iter_count(&iter);
2961 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2963 unsigned long nr_segs = iter.nr_segs;
2966 ret2 = io_iter_do_read(req, &iter);
2968 /* Catch -EAGAIN return for forced non-blocking submission */
2969 if (!force_nonblock || (ret2 != -EAGAIN && ret2 != -EIO)) {
2970 kiocb_done(kiocb, ret2, cs);
2972 iter.count = iov_count;
2973 iter.nr_segs = nr_segs;
2975 ret = io_setup_async_rw(req, io_size, iovec,
2976 inline_vecs, &iter);
2979 /* if we can retry, do so with the callbacks armed */
2980 if (io_rw_should_retry(req)) {
2981 ret2 = io_iter_do_read(req, &iter);
2982 if (ret2 == -EIOCBQUEUED) {
2984 } else if (ret2 != -EAGAIN) {
2985 kiocb_done(kiocb, ret2, cs);
2989 kiocb->ki_flags &= ~IOCB_WAITQ;
2994 if (!(req->flags & REQ_F_NEED_CLEANUP))
2999 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3000 bool force_nonblock)
3002 struct io_async_ctx *io;
3003 struct iov_iter iter;
3006 ret = io_prep_rw(req, sqe, force_nonblock);
3010 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3013 req->fsize = rlimit(RLIMIT_FSIZE);
3015 /* either don't need iovec imported or already have it */
3016 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3020 io->rw.iov = io->rw.fast_iov;
3022 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
3027 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
3031 static int io_write(struct io_kiocb *req, bool force_nonblock,
3032 struct io_comp_state *cs)
3034 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3035 struct kiocb *kiocb = &req->rw.kiocb;
3036 struct iov_iter iter;
3038 ssize_t ret, io_size;
3040 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
3044 /* Ensure we clear previously set non-block flag */
3045 if (!force_nonblock)
3046 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
3050 if (req->flags & REQ_F_LINK_HEAD)
3051 req->result = io_size;
3053 /* If the file doesn't support async, just async punt */
3054 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3057 /* file path doesn't support NOWAIT for non-direct_IO */
3058 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3059 (req->flags & REQ_F_ISREG))
3062 iov_count = iov_iter_count(&iter);
3063 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
3065 unsigned long nr_segs = iter.nr_segs;
3069 * Open-code file_start_write here to grab freeze protection,
3070 * which will be released by another thread in
3071 * io_complete_rw(). Fool lockdep by telling it the lock got
3072 * released so that it doesn't complain about the held lock when
3073 * we return to userspace.
3075 if (req->flags & REQ_F_ISREG) {
3076 __sb_start_write(file_inode(req->file)->i_sb,
3077 SB_FREEZE_WRITE, true);
3078 __sb_writers_release(file_inode(req->file)->i_sb,
3081 kiocb->ki_flags |= IOCB_WRITE;
3083 if (!force_nonblock)
3084 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3086 if (req->file->f_op->write_iter)
3087 ret2 = call_write_iter(req->file, kiocb, &iter);
3089 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
3091 if (!force_nonblock)
3092 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3095 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3096 * retry them without IOCB_NOWAIT.
3098 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3100 if (!force_nonblock || ret2 != -EAGAIN) {
3101 kiocb_done(kiocb, ret2, cs);
3103 iter.count = iov_count;
3104 iter.nr_segs = nr_segs;
3106 ret = io_setup_async_rw(req, io_size, iovec,
3107 inline_vecs, &iter);
3114 if (!(req->flags & REQ_F_NEED_CLEANUP))
3119 static int __io_splice_prep(struct io_kiocb *req,
3120 const struct io_uring_sqe *sqe)
3122 struct io_splice* sp = &req->splice;
3123 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3126 if (req->flags & REQ_F_NEED_CLEANUP)
3128 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3132 sp->len = READ_ONCE(sqe->len);
3133 sp->flags = READ_ONCE(sqe->splice_flags);
3135 if (unlikely(sp->flags & ~valid_flags))
3138 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
3139 (sp->flags & SPLICE_F_FD_IN_FIXED));
3142 req->flags |= REQ_F_NEED_CLEANUP;
3144 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3146 * Splice operation will be punted aync, and here need to
3147 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3149 io_req_init_async(req);
3150 req->work.flags |= IO_WQ_WORK_UNBOUND;
3156 static int io_tee_prep(struct io_kiocb *req,
3157 const struct io_uring_sqe *sqe)
3159 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3161 return __io_splice_prep(req, sqe);
3164 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3166 struct io_splice *sp = &req->splice;
3167 struct file *in = sp->file_in;
3168 struct file *out = sp->file_out;
3169 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3175 ret = do_tee(in, out, sp->len, flags);
3177 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3178 req->flags &= ~REQ_F_NEED_CLEANUP;
3181 req_set_fail_links(req);
3182 io_req_complete(req, ret);
3186 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3188 struct io_splice* sp = &req->splice;
3190 sp->off_in = READ_ONCE(sqe->splice_off_in);
3191 sp->off_out = READ_ONCE(sqe->off);
3192 return __io_splice_prep(req, sqe);
3195 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3197 struct io_splice *sp = &req->splice;
3198 struct file *in = sp->file_in;
3199 struct file *out = sp->file_out;
3200 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3201 loff_t *poff_in, *poff_out;
3207 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3208 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3211 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3213 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3214 req->flags &= ~REQ_F_NEED_CLEANUP;
3217 req_set_fail_links(req);
3218 io_req_complete(req, ret);
3223 * IORING_OP_NOP just posts a completion event, nothing else.
3225 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3227 struct io_ring_ctx *ctx = req->ctx;
3229 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3232 __io_req_complete(req, 0, 0, cs);
3236 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3238 struct io_ring_ctx *ctx = req->ctx;
3243 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3245 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3248 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3249 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3252 req->sync.off = READ_ONCE(sqe->off);
3253 req->sync.len = READ_ONCE(sqe->len);
3257 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3259 loff_t end = req->sync.off + req->sync.len;
3262 /* fsync always requires a blocking context */
3266 ret = vfs_fsync_range(req->file, req->sync.off,
3267 end > 0 ? end : LLONG_MAX,
3268 req->sync.flags & IORING_FSYNC_DATASYNC);
3270 req_set_fail_links(req);
3271 io_req_complete(req, ret);
3275 static int io_fallocate_prep(struct io_kiocb *req,
3276 const struct io_uring_sqe *sqe)
3278 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3280 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3283 req->sync.off = READ_ONCE(sqe->off);
3284 req->sync.len = READ_ONCE(sqe->addr);
3285 req->sync.mode = READ_ONCE(sqe->len);
3286 req->fsize = rlimit(RLIMIT_FSIZE);
3290 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3294 /* fallocate always requiring blocking context */
3298 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3299 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3301 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3303 req_set_fail_links(req);
3304 io_req_complete(req, ret);
3308 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3310 const char __user *fname;
3313 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3315 if (unlikely(sqe->ioprio || sqe->buf_index))
3317 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3320 /* open.how should be already initialised */
3321 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3322 req->open.how.flags |= O_LARGEFILE;
3324 req->open.dfd = READ_ONCE(sqe->fd);
3325 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3326 req->open.filename = getname(fname);
3327 if (IS_ERR(req->open.filename)) {
3328 ret = PTR_ERR(req->open.filename);
3329 req->open.filename = NULL;
3332 req->open.nofile = rlimit(RLIMIT_NOFILE);
3333 req->flags |= REQ_F_NEED_CLEANUP;
3337 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3341 if (req->flags & REQ_F_NEED_CLEANUP)
3343 mode = READ_ONCE(sqe->len);
3344 flags = READ_ONCE(sqe->open_flags);
3345 req->open.how = build_open_how(flags, mode);
3346 return __io_openat_prep(req, sqe);
3349 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3351 struct open_how __user *how;
3355 if (req->flags & REQ_F_NEED_CLEANUP)
3357 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3358 len = READ_ONCE(sqe->len);
3359 if (len < OPEN_HOW_SIZE_VER0)
3362 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3367 return __io_openat_prep(req, sqe);
3370 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3372 struct open_flags op;
3379 ret = build_open_flags(&req->open.how, &op);
3383 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3387 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3390 ret = PTR_ERR(file);
3392 fsnotify_open(file);
3393 fd_install(ret, file);
3396 putname(req->open.filename);
3397 req->flags &= ~REQ_F_NEED_CLEANUP;
3399 req_set_fail_links(req);
3400 io_req_complete(req, ret);
3404 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3406 return io_openat2(req, force_nonblock);
3409 static int io_remove_buffers_prep(struct io_kiocb *req,
3410 const struct io_uring_sqe *sqe)
3412 struct io_provide_buf *p = &req->pbuf;
3415 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3418 tmp = READ_ONCE(sqe->fd);
3419 if (!tmp || tmp > USHRT_MAX)
3422 memset(p, 0, sizeof(*p));
3424 p->bgid = READ_ONCE(sqe->buf_group);
3428 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3429 int bgid, unsigned nbufs)
3433 /* shouldn't happen */
3437 /* the head kbuf is the list itself */
3438 while (!list_empty(&buf->list)) {
3439 struct io_buffer *nxt;
3441 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3442 list_del(&nxt->list);
3449 idr_remove(&ctx->io_buffer_idr, bgid);
3454 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3455 struct io_comp_state *cs)
3457 struct io_provide_buf *p = &req->pbuf;
3458 struct io_ring_ctx *ctx = req->ctx;
3459 struct io_buffer *head;
3462 io_ring_submit_lock(ctx, !force_nonblock);
3464 lockdep_assert_held(&ctx->uring_lock);
3467 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3469 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3471 io_ring_submit_lock(ctx, !force_nonblock);
3473 req_set_fail_links(req);
3474 __io_req_complete(req, ret, 0, cs);
3478 static int io_provide_buffers_prep(struct io_kiocb *req,
3479 const struct io_uring_sqe *sqe)
3481 struct io_provide_buf *p = &req->pbuf;
3484 if (sqe->ioprio || sqe->rw_flags)
3487 tmp = READ_ONCE(sqe->fd);
3488 if (!tmp || tmp > USHRT_MAX)
3491 p->addr = READ_ONCE(sqe->addr);
3492 p->len = READ_ONCE(sqe->len);
3494 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3497 p->bgid = READ_ONCE(sqe->buf_group);
3498 tmp = READ_ONCE(sqe->off);
3499 if (tmp > USHRT_MAX)
3505 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3507 struct io_buffer *buf;
3508 u64 addr = pbuf->addr;
3509 int i, bid = pbuf->bid;
3511 for (i = 0; i < pbuf->nbufs; i++) {
3512 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3517 buf->len = pbuf->len;
3522 INIT_LIST_HEAD(&buf->list);
3525 list_add_tail(&buf->list, &(*head)->list);
3529 return i ? i : -ENOMEM;
3532 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3533 struct io_comp_state *cs)
3535 struct io_provide_buf *p = &req->pbuf;
3536 struct io_ring_ctx *ctx = req->ctx;
3537 struct io_buffer *head, *list;
3540 io_ring_submit_lock(ctx, !force_nonblock);
3542 lockdep_assert_held(&ctx->uring_lock);
3544 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3546 ret = io_add_buffers(p, &head);
3551 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3554 __io_remove_buffers(ctx, head, p->bgid, -1U);
3559 io_ring_submit_unlock(ctx, !force_nonblock);
3561 req_set_fail_links(req);
3562 __io_req_complete(req, ret, 0, cs);
3566 static int io_epoll_ctl_prep(struct io_kiocb *req,
3567 const struct io_uring_sqe *sqe)
3569 #if defined(CONFIG_EPOLL)
3570 if (sqe->ioprio || sqe->buf_index)
3572 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3575 req->epoll.epfd = READ_ONCE(sqe->fd);
3576 req->epoll.op = READ_ONCE(sqe->len);
3577 req->epoll.fd = READ_ONCE(sqe->off);
3579 if (ep_op_has_event(req->epoll.op)) {
3580 struct epoll_event __user *ev;
3582 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3583 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3593 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3594 struct io_comp_state *cs)
3596 #if defined(CONFIG_EPOLL)
3597 struct io_epoll *ie = &req->epoll;
3600 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3601 if (force_nonblock && ret == -EAGAIN)
3605 req_set_fail_links(req);
3606 __io_req_complete(req, ret, 0, cs);
3613 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3615 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3616 if (sqe->ioprio || sqe->buf_index || sqe->off)
3618 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3621 req->madvise.addr = READ_ONCE(sqe->addr);
3622 req->madvise.len = READ_ONCE(sqe->len);
3623 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3630 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3632 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3633 struct io_madvise *ma = &req->madvise;
3639 ret = do_madvise(ma->addr, ma->len, ma->advice);
3641 req_set_fail_links(req);
3642 io_req_complete(req, ret);
3649 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3651 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3653 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3656 req->fadvise.offset = READ_ONCE(sqe->off);
3657 req->fadvise.len = READ_ONCE(sqe->len);
3658 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3662 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3664 struct io_fadvise *fa = &req->fadvise;
3667 if (force_nonblock) {
3668 switch (fa->advice) {
3669 case POSIX_FADV_NORMAL:
3670 case POSIX_FADV_RANDOM:
3671 case POSIX_FADV_SEQUENTIAL:
3678 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3680 req_set_fail_links(req);
3681 io_req_complete(req, ret);
3685 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3687 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3689 if (sqe->ioprio || sqe->buf_index)
3691 if (req->flags & REQ_F_FIXED_FILE)
3694 req->statx.dfd = READ_ONCE(sqe->fd);
3695 req->statx.mask = READ_ONCE(sqe->len);
3696 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
3697 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3698 req->statx.flags = READ_ONCE(sqe->statx_flags);
3703 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3705 struct io_statx *ctx = &req->statx;
3708 if (force_nonblock) {
3709 /* only need file table for an actual valid fd */
3710 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3711 req->flags |= REQ_F_NO_FILE_TABLE;
3715 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3719 req_set_fail_links(req);
3720 io_req_complete(req, ret);
3724 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3727 * If we queue this for async, it must not be cancellable. That would
3728 * leave the 'file' in an undeterminate state, and here need to modify
3729 * io_wq_work.flags, so initialize io_wq_work firstly.
3731 io_req_init_async(req);
3732 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3734 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3736 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3737 sqe->rw_flags || sqe->buf_index)
3739 if (req->flags & REQ_F_FIXED_FILE)
3742 req->close.fd = READ_ONCE(sqe->fd);
3743 if ((req->file && req->file->f_op == &io_uring_fops) ||
3744 req->close.fd == req->ctx->ring_fd)
3747 req->close.put_file = NULL;
3751 static int io_close(struct io_kiocb *req, bool force_nonblock,
3752 struct io_comp_state *cs)
3754 struct io_close *close = &req->close;
3757 /* might be already done during nonblock submission */
3758 if (!close->put_file) {
3759 ret = __close_fd_get_file(close->fd, &close->put_file);
3761 return (ret == -ENOENT) ? -EBADF : ret;
3764 /* if the file has a flush method, be safe and punt to async */
3765 if (close->put_file->f_op->flush && force_nonblock) {
3766 /* was never set, but play safe */
3767 req->flags &= ~REQ_F_NOWAIT;
3768 /* avoid grabbing files - we don't need the files */
3769 req->flags |= REQ_F_NO_FILE_TABLE;
3773 /* No ->flush() or already async, safely close from here */
3774 ret = filp_close(close->put_file, req->work.files);
3776 req_set_fail_links(req);
3777 fput(close->put_file);
3778 close->put_file = NULL;
3779 __io_req_complete(req, ret, 0, cs);
3783 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3785 struct io_ring_ctx *ctx = req->ctx;
3790 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3792 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3795 req->sync.off = READ_ONCE(sqe->off);
3796 req->sync.len = READ_ONCE(sqe->len);
3797 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3801 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3805 /* sync_file_range always requires a blocking context */
3809 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3812 req_set_fail_links(req);
3813 io_req_complete(req, ret);
3817 #if defined(CONFIG_NET)
3818 static int io_setup_async_msg(struct io_kiocb *req,
3819 struct io_async_msghdr *kmsg)
3823 if (io_alloc_async_ctx(req)) {
3824 if (kmsg->iov != kmsg->fast_iov)
3828 req->flags |= REQ_F_NEED_CLEANUP;
3829 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3833 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3835 struct io_sr_msg *sr = &req->sr_msg;
3836 struct io_async_ctx *io = req->io;
3839 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3842 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3843 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3844 sr->len = READ_ONCE(sqe->len);
3846 #ifdef CONFIG_COMPAT
3847 if (req->ctx->compat)
3848 sr->msg_flags |= MSG_CMSG_COMPAT;
3851 if (!io || req->opcode == IORING_OP_SEND)
3853 /* iovec is already imported */
3854 if (req->flags & REQ_F_NEED_CLEANUP)
3857 io->msg.iov = io->msg.fast_iov;
3858 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3861 req->flags |= REQ_F_NEED_CLEANUP;
3865 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
3866 struct io_comp_state *cs)
3868 struct io_async_msghdr *kmsg = NULL;
3869 struct socket *sock;
3872 sock = sock_from_file(req->file, &ret);
3874 struct io_async_ctx io;
3878 kmsg = &req->io->msg;
3879 kmsg->msg.msg_name = &req->io->msg.addr;
3880 /* if iov is set, it's allocated already */
3882 kmsg->iov = kmsg->fast_iov;
3883 kmsg->msg.msg_iter.iov = kmsg->iov;
3885 struct io_sr_msg *sr = &req->sr_msg;
3888 kmsg->msg.msg_name = &io.msg.addr;
3890 io.msg.iov = io.msg.fast_iov;
3891 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3892 sr->msg_flags, &io.msg.iov);
3897 flags = req->sr_msg.msg_flags;
3898 if (flags & MSG_DONTWAIT)
3899 req->flags |= REQ_F_NOWAIT;
3900 else if (force_nonblock)
3901 flags |= MSG_DONTWAIT;
3903 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3904 if (force_nonblock && ret == -EAGAIN)
3905 return io_setup_async_msg(req, kmsg);
3906 if (ret == -ERESTARTSYS)
3910 if (kmsg && kmsg->iov != kmsg->fast_iov)
3912 req->flags &= ~REQ_F_NEED_CLEANUP;
3914 req_set_fail_links(req);
3915 __io_req_complete(req, ret, 0, cs);
3919 static int io_send(struct io_kiocb *req, bool force_nonblock,
3920 struct io_comp_state *cs)
3922 struct socket *sock;
3925 sock = sock_from_file(req->file, &ret);
3927 struct io_sr_msg *sr = &req->sr_msg;
3932 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3937 msg.msg_name = NULL;
3938 msg.msg_control = NULL;
3939 msg.msg_controllen = 0;
3940 msg.msg_namelen = 0;
3942 flags = req->sr_msg.msg_flags;
3943 if (flags & MSG_DONTWAIT)
3944 req->flags |= REQ_F_NOWAIT;
3945 else if (force_nonblock)
3946 flags |= MSG_DONTWAIT;
3948 msg.msg_flags = flags;
3949 ret = sock_sendmsg(sock, &msg);
3950 if (force_nonblock && ret == -EAGAIN)
3952 if (ret == -ERESTARTSYS)
3957 req_set_fail_links(req);
3958 __io_req_complete(req, ret, 0, cs);
3962 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3964 struct io_sr_msg *sr = &req->sr_msg;
3965 struct iovec __user *uiov;
3969 ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
3974 if (req->flags & REQ_F_BUFFER_SELECT) {
3977 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
3979 sr->len = io->msg.iov[0].iov_len;
3980 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
3984 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
3985 &io->msg.iov, &io->msg.msg.msg_iter);
3993 #ifdef CONFIG_COMPAT
3994 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
3995 struct io_async_ctx *io)
3997 struct compat_msghdr __user *msg_compat;
3998 struct io_sr_msg *sr = &req->sr_msg;
3999 struct compat_iovec __user *uiov;
4004 msg_compat = (struct compat_msghdr __user *) sr->msg;
4005 ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
4010 uiov = compat_ptr(ptr);
4011 if (req->flags & REQ_F_BUFFER_SELECT) {
4012 compat_ssize_t clen;
4016 if (!access_ok(uiov, sizeof(*uiov)))
4018 if (__get_user(clen, &uiov->iov_len))
4022 sr->len = io->msg.iov[0].iov_len;
4025 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
4027 &io->msg.msg.msg_iter);
4036 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
4038 io->msg.iov = io->msg.fast_iov;
4040 #ifdef CONFIG_COMPAT
4041 if (req->ctx->compat)
4042 return __io_compat_recvmsg_copy_hdr(req, io);
4045 return __io_recvmsg_copy_hdr(req, io);
4048 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4049 int *cflags, bool needs_lock)
4051 struct io_sr_msg *sr = &req->sr_msg;
4052 struct io_buffer *kbuf;
4054 if (!(req->flags & REQ_F_BUFFER_SELECT))
4057 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4062 req->flags |= REQ_F_BUFFER_SELECTED;
4064 *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
4065 *cflags |= IORING_CQE_F_BUFFER;
4069 static int io_recvmsg_prep(struct io_kiocb *req,
4070 const struct io_uring_sqe *sqe)
4072 struct io_sr_msg *sr = &req->sr_msg;
4073 struct io_async_ctx *io = req->io;
4076 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4079 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4080 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4081 sr->len = READ_ONCE(sqe->len);
4082 sr->bgid = READ_ONCE(sqe->buf_group);
4084 #ifdef CONFIG_COMPAT
4085 if (req->ctx->compat)
4086 sr->msg_flags |= MSG_CMSG_COMPAT;
4089 if (!io || req->opcode == IORING_OP_RECV)
4091 /* iovec is already imported */
4092 if (req->flags & REQ_F_NEED_CLEANUP)
4095 ret = io_recvmsg_copy_hdr(req, io);
4097 req->flags |= REQ_F_NEED_CLEANUP;
4101 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4102 struct io_comp_state *cs)
4104 struct io_async_msghdr *kmsg = NULL;
4105 struct socket *sock;
4106 int ret, cflags = 0;
4108 sock = sock_from_file(req->file, &ret);
4110 struct io_buffer *kbuf;
4111 struct io_async_ctx io;
4115 kmsg = &req->io->msg;
4116 kmsg->msg.msg_name = &req->io->msg.addr;
4117 /* if iov is set, it's allocated already */
4119 kmsg->iov = kmsg->fast_iov;
4120 kmsg->msg.msg_iter.iov = kmsg->iov;
4123 kmsg->msg.msg_name = &io.msg.addr;
4125 ret = io_recvmsg_copy_hdr(req, &io);
4130 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4132 return PTR_ERR(kbuf);
4134 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4135 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4136 1, req->sr_msg.len);
4139 flags = req->sr_msg.msg_flags;
4140 if (flags & MSG_DONTWAIT)
4141 req->flags |= REQ_F_NOWAIT;
4142 else if (force_nonblock)
4143 flags |= MSG_DONTWAIT;
4145 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
4146 kmsg->uaddr, flags);
4147 if (force_nonblock && ret == -EAGAIN)
4148 return io_setup_async_msg(req, kmsg);
4149 if (ret == -ERESTARTSYS)
4153 if (kmsg && kmsg->iov != kmsg->fast_iov)
4155 req->flags &= ~REQ_F_NEED_CLEANUP;
4157 req_set_fail_links(req);
4158 __io_req_complete(req, ret, cflags, cs);
4162 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4163 struct io_comp_state *cs)
4165 struct io_buffer *kbuf = NULL;
4166 struct socket *sock;
4167 int ret, cflags = 0;
4169 sock = sock_from_file(req->file, &ret);
4171 struct io_sr_msg *sr = &req->sr_msg;
4172 void __user *buf = sr->buf;
4177 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4179 return PTR_ERR(kbuf);
4181 buf = u64_to_user_ptr(kbuf->addr);
4183 ret = import_single_range(READ, buf, sr->len, &iov,
4190 req->flags |= REQ_F_NEED_CLEANUP;
4191 msg.msg_name = NULL;
4192 msg.msg_control = NULL;
4193 msg.msg_controllen = 0;
4194 msg.msg_namelen = 0;
4195 msg.msg_iocb = NULL;
4198 flags = req->sr_msg.msg_flags;
4199 if (flags & MSG_DONTWAIT)
4200 req->flags |= REQ_F_NOWAIT;
4201 else if (force_nonblock)
4202 flags |= MSG_DONTWAIT;
4204 ret = sock_recvmsg(sock, &msg, flags);
4205 if (force_nonblock && ret == -EAGAIN)
4207 if (ret == -ERESTARTSYS)
4212 req->flags &= ~REQ_F_NEED_CLEANUP;
4214 req_set_fail_links(req);
4215 __io_req_complete(req, ret, cflags, cs);
4219 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4221 struct io_accept *accept = &req->accept;
4223 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4225 if (sqe->ioprio || sqe->len || sqe->buf_index)
4228 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4229 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4230 accept->flags = READ_ONCE(sqe->accept_flags);
4231 accept->nofile = rlimit(RLIMIT_NOFILE);
4235 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4236 struct io_comp_state *cs)
4238 struct io_accept *accept = &req->accept;
4239 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4242 if (req->file->f_flags & O_NONBLOCK)
4243 req->flags |= REQ_F_NOWAIT;
4245 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4246 accept->addr_len, accept->flags,
4248 if (ret == -EAGAIN && force_nonblock)
4251 if (ret == -ERESTARTSYS)
4253 req_set_fail_links(req);
4255 __io_req_complete(req, ret, 0, cs);
4259 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4261 struct io_connect *conn = &req->connect;
4262 struct io_async_ctx *io = req->io;
4264 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4266 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4269 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4270 conn->addr_len = READ_ONCE(sqe->addr2);
4275 return move_addr_to_kernel(conn->addr, conn->addr_len,
4276 &io->connect.address);
4279 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4280 struct io_comp_state *cs)
4282 struct io_async_ctx __io, *io;
4283 unsigned file_flags;
4289 ret = move_addr_to_kernel(req->connect.addr,
4290 req->connect.addr_len,
4291 &__io.connect.address);
4297 file_flags = force_nonblock ? O_NONBLOCK : 0;
4299 ret = __sys_connect_file(req->file, &io->connect.address,
4300 req->connect.addr_len, file_flags);
4301 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4304 if (io_alloc_async_ctx(req)) {
4308 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4311 if (ret == -ERESTARTSYS)
4315 req_set_fail_links(req);
4316 __io_req_complete(req, ret, 0, cs);
4319 #else /* !CONFIG_NET */
4320 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4325 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
4330 static int io_send(struct io_kiocb *req, bool force_nonblock)
4335 static int io_recvmsg_prep(struct io_kiocb *req,
4336 const struct io_uring_sqe *sqe)
4341 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
4346 static int io_recv(struct io_kiocb *req, bool force_nonblock)
4351 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4356 static int io_accept(struct io_kiocb *req, bool force_nonblock)
4361 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4366 static int io_connect(struct io_kiocb *req, bool force_nonblock)
4370 #endif /* CONFIG_NET */
4372 struct io_poll_table {
4373 struct poll_table_struct pt;
4374 struct io_kiocb *req;
4378 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4379 __poll_t mask, task_work_func_t func)
4381 struct task_struct *tsk;
4384 /* for instances that support it check for an event match first: */
4385 if (mask && !(mask & poll->events))
4388 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4390 list_del_init(&poll->wait.entry);
4394 init_task_work(&req->task_work, func);
4396 * If this fails, then the task is exiting. When a task exits, the
4397 * work gets canceled, so just cancel this request as well instead
4398 * of executing it. We can't safely execute it anyway, as we may not
4399 * have the needed state needed for it anyway.
4401 ret = task_work_add(tsk, &req->task_work, true);
4402 if (unlikely(ret)) {
4403 WRITE_ONCE(poll->canceled, true);
4404 tsk = io_wq_get_task(req->ctx->io_wq);
4405 task_work_add(tsk, &req->task_work, true);
4407 wake_up_process(tsk);
4411 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4412 __acquires(&req->ctx->completion_lock)
4414 struct io_ring_ctx *ctx = req->ctx;
4416 if (!req->result && !READ_ONCE(poll->canceled)) {
4417 struct poll_table_struct pt = { ._key = poll->events };
4419 req->result = vfs_poll(req->file, &pt) & poll->events;
4422 spin_lock_irq(&ctx->completion_lock);
4423 if (!req->result && !READ_ONCE(poll->canceled)) {
4424 add_wait_queue(poll->head, &poll->wait);
4431 static void io_poll_remove_double(struct io_kiocb *req)
4433 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4435 lockdep_assert_held(&req->ctx->completion_lock);
4437 if (poll && poll->head) {
4438 struct wait_queue_head *head = poll->head;
4440 spin_lock(&head->lock);
4441 list_del_init(&poll->wait.entry);
4442 if (poll->wait.private)
4443 refcount_dec(&req->refs);
4445 spin_unlock(&head->lock);
4449 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4451 struct io_ring_ctx *ctx = req->ctx;
4453 io_poll_remove_double(req);
4454 req->poll.done = true;
4455 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4456 io_commit_cqring(ctx);
4459 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4461 struct io_ring_ctx *ctx = req->ctx;
4463 if (io_poll_rewait(req, &req->poll)) {
4464 spin_unlock_irq(&ctx->completion_lock);
4468 hash_del(&req->hash_node);
4469 io_poll_complete(req, req->result, 0);
4470 req->flags |= REQ_F_COMP_LOCKED;
4471 io_put_req_find_next(req, nxt);
4472 spin_unlock_irq(&ctx->completion_lock);
4474 io_cqring_ev_posted(ctx);
4477 static void io_poll_task_func(struct callback_head *cb)
4479 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4480 struct io_kiocb *nxt = NULL;
4482 io_poll_task_handler(req, &nxt);
4484 struct io_ring_ctx *ctx = nxt->ctx;
4486 mutex_lock(&ctx->uring_lock);
4487 __io_queue_sqe(nxt, NULL, NULL);
4488 mutex_unlock(&ctx->uring_lock);
4492 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4493 int sync, void *key)
4495 struct io_kiocb *req = wait->private;
4496 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4497 __poll_t mask = key_to_poll(key);
4499 /* for instances that support it check for an event match first: */
4500 if (mask && !(mask & poll->events))
4503 if (req->poll.head) {
4506 spin_lock(&req->poll.head->lock);
4507 done = list_empty(&req->poll.wait.entry);
4509 list_del_init(&req->poll.wait.entry);
4510 spin_unlock(&req->poll.head->lock);
4512 __io_async_wake(req, poll, mask, io_poll_task_func);
4514 refcount_dec(&req->refs);
4518 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4519 wait_queue_func_t wake_func)
4523 poll->canceled = false;
4524 poll->events = events;
4525 INIT_LIST_HEAD(&poll->wait.entry);
4526 init_waitqueue_func_entry(&poll->wait, wake_func);
4529 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4530 struct wait_queue_head *head)
4532 struct io_kiocb *req = pt->req;
4535 * If poll->head is already set, it's because the file being polled
4536 * uses multiple waitqueues for poll handling (eg one for read, one
4537 * for write). Setup a separate io_poll_iocb if this happens.
4539 if (unlikely(poll->head)) {
4540 /* already have a 2nd entry, fail a third attempt */
4542 pt->error = -EINVAL;
4545 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4547 pt->error = -ENOMEM;
4550 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4551 refcount_inc(&req->refs);
4552 poll->wait.private = req;
4553 req->io = (void *) poll;
4559 if (poll->events & EPOLLEXCLUSIVE)
4560 add_wait_queue_exclusive(head, &poll->wait);
4562 add_wait_queue(head, &poll->wait);
4565 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4566 struct poll_table_struct *p)
4568 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4570 __io_queue_proc(&pt->req->apoll->poll, pt, head);
4573 static void io_async_task_func(struct callback_head *cb)
4575 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4576 struct async_poll *apoll = req->apoll;
4577 struct io_ring_ctx *ctx = req->ctx;
4578 bool canceled = false;
4580 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4582 if (io_poll_rewait(req, &apoll->poll)) {
4583 spin_unlock_irq(&ctx->completion_lock);
4587 /* If req is still hashed, it cannot have been canceled. Don't check. */
4588 if (hash_hashed(&req->hash_node)) {
4589 hash_del(&req->hash_node);
4591 canceled = READ_ONCE(apoll->poll.canceled);
4593 io_cqring_fill_event(req, -ECANCELED);
4594 io_commit_cqring(ctx);
4598 spin_unlock_irq(&ctx->completion_lock);
4600 /* restore ->work in case we need to retry again */
4601 if (req->flags & REQ_F_WORK_INITIALIZED)
4602 memcpy(&req->work, &apoll->work, sizeof(req->work));
4606 __set_current_state(TASK_RUNNING);
4607 if (io_sq_thread_acquire_mm(ctx, req)) {
4608 io_cqring_add_event(req, -EFAULT, 0);
4611 mutex_lock(&ctx->uring_lock);
4612 __io_queue_sqe(req, NULL, NULL);
4613 mutex_unlock(&ctx->uring_lock);
4615 io_cqring_ev_posted(ctx);
4617 req_set_fail_links(req);
4618 io_double_put_req(req);
4622 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4625 struct io_kiocb *req = wait->private;
4626 struct io_poll_iocb *poll = &req->apoll->poll;
4628 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4631 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4634 static void io_poll_req_insert(struct io_kiocb *req)
4636 struct io_ring_ctx *ctx = req->ctx;
4637 struct hlist_head *list;
4639 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4640 hlist_add_head(&req->hash_node, list);
4643 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4644 struct io_poll_iocb *poll,
4645 struct io_poll_table *ipt, __poll_t mask,
4646 wait_queue_func_t wake_func)
4647 __acquires(&ctx->completion_lock)
4649 struct io_ring_ctx *ctx = req->ctx;
4650 bool cancel = false;
4652 io_init_poll_iocb(poll, mask, wake_func);
4653 poll->file = req->file;
4654 poll->wait.private = req;
4656 ipt->pt._key = mask;
4658 ipt->error = -EINVAL;
4660 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4662 spin_lock_irq(&ctx->completion_lock);
4663 if (likely(poll->head)) {
4664 spin_lock(&poll->head->lock);
4665 if (unlikely(list_empty(&poll->wait.entry))) {
4671 if (mask || ipt->error)
4672 list_del_init(&poll->wait.entry);
4674 WRITE_ONCE(poll->canceled, true);
4675 else if (!poll->done) /* actually waiting for an event */
4676 io_poll_req_insert(req);
4677 spin_unlock(&poll->head->lock);
4683 static bool io_arm_poll_handler(struct io_kiocb *req)
4685 const struct io_op_def *def = &io_op_defs[req->opcode];
4686 struct io_ring_ctx *ctx = req->ctx;
4687 struct async_poll *apoll;
4688 struct io_poll_table ipt;
4692 if (!req->file || !file_can_poll(req->file))
4694 if (req->flags & REQ_F_POLLED)
4696 if (!def->pollin && !def->pollout)
4699 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4700 if (unlikely(!apoll))
4703 req->flags |= REQ_F_POLLED;
4704 if (req->flags & REQ_F_WORK_INITIALIZED)
4705 memcpy(&apoll->work, &req->work, sizeof(req->work));
4706 had_io = req->io != NULL;
4708 io_get_req_task(req);
4710 INIT_HLIST_NODE(&req->hash_node);
4714 mask |= POLLIN | POLLRDNORM;
4716 mask |= POLLOUT | POLLWRNORM;
4717 mask |= POLLERR | POLLPRI;
4719 ipt.pt._qproc = io_async_queue_proc;
4721 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4725 /* only remove double add if we did it here */
4727 io_poll_remove_double(req);
4728 spin_unlock_irq(&ctx->completion_lock);
4729 if (req->flags & REQ_F_WORK_INITIALIZED)
4730 memcpy(&req->work, &apoll->work, sizeof(req->work));
4734 spin_unlock_irq(&ctx->completion_lock);
4735 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4736 apoll->poll.events);
4740 static bool __io_poll_remove_one(struct io_kiocb *req,
4741 struct io_poll_iocb *poll)
4743 bool do_complete = false;
4745 spin_lock(&poll->head->lock);
4746 WRITE_ONCE(poll->canceled, true);
4747 if (!list_empty(&poll->wait.entry)) {
4748 list_del_init(&poll->wait.entry);
4751 spin_unlock(&poll->head->lock);
4752 hash_del(&req->hash_node);
4756 static bool io_poll_remove_one(struct io_kiocb *req)
4760 if (req->opcode == IORING_OP_POLL_ADD) {
4761 io_poll_remove_double(req);
4762 do_complete = __io_poll_remove_one(req, &req->poll);
4764 struct async_poll *apoll = req->apoll;
4766 /* non-poll requests have submit ref still */
4767 do_complete = __io_poll_remove_one(req, &apoll->poll);
4771 * restore ->work because we will call
4772 * io_req_work_drop_env below when dropping the
4775 if (req->flags & REQ_F_WORK_INITIALIZED)
4776 memcpy(&req->work, &apoll->work,
4783 io_cqring_fill_event(req, -ECANCELED);
4784 io_commit_cqring(req->ctx);
4785 req->flags |= REQ_F_COMP_LOCKED;
4792 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4794 struct hlist_node *tmp;
4795 struct io_kiocb *req;
4798 spin_lock_irq(&ctx->completion_lock);
4799 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4800 struct hlist_head *list;
4802 list = &ctx->cancel_hash[i];
4803 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4804 posted += io_poll_remove_one(req);
4806 spin_unlock_irq(&ctx->completion_lock);
4809 io_cqring_ev_posted(ctx);
4812 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4814 struct hlist_head *list;
4815 struct io_kiocb *req;
4817 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4818 hlist_for_each_entry(req, list, hash_node) {
4819 if (sqe_addr != req->user_data)
4821 if (io_poll_remove_one(req))
4829 static int io_poll_remove_prep(struct io_kiocb *req,
4830 const struct io_uring_sqe *sqe)
4832 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4834 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4838 req->poll.addr = READ_ONCE(sqe->addr);
4843 * Find a running poll command that matches one specified in sqe->addr,
4844 * and remove it if found.
4846 static int io_poll_remove(struct io_kiocb *req)
4848 struct io_ring_ctx *ctx = req->ctx;
4852 addr = req->poll.addr;
4853 spin_lock_irq(&ctx->completion_lock);
4854 ret = io_poll_cancel(ctx, addr);
4855 spin_unlock_irq(&ctx->completion_lock);
4858 req_set_fail_links(req);
4859 io_req_complete(req, ret);
4863 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4866 struct io_kiocb *req = wait->private;
4867 struct io_poll_iocb *poll = &req->poll;
4869 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4872 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4873 struct poll_table_struct *p)
4875 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4877 __io_queue_proc(&pt->req->poll, pt, head);
4880 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4882 struct io_poll_iocb *poll = &req->poll;
4885 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4887 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4892 events = READ_ONCE(sqe->poll32_events);
4894 events = swahw32(events);
4896 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
4897 (events & EPOLLEXCLUSIVE);
4899 io_get_req_task(req);
4903 static int io_poll_add(struct io_kiocb *req)
4905 struct io_poll_iocb *poll = &req->poll;
4906 struct io_ring_ctx *ctx = req->ctx;
4907 struct io_poll_table ipt;
4910 INIT_HLIST_NODE(&req->hash_node);
4911 INIT_LIST_HEAD(&req->list);
4912 ipt.pt._qproc = io_poll_queue_proc;
4914 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4917 if (mask) { /* no async, we'd stolen it */
4919 io_poll_complete(req, mask, 0);
4921 spin_unlock_irq(&ctx->completion_lock);
4924 io_cqring_ev_posted(ctx);
4930 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4932 struct io_timeout_data *data = container_of(timer,
4933 struct io_timeout_data, timer);
4934 struct io_kiocb *req = data->req;
4935 struct io_ring_ctx *ctx = req->ctx;
4936 unsigned long flags;
4938 atomic_inc(&ctx->cq_timeouts);
4940 spin_lock_irqsave(&ctx->completion_lock, flags);
4942 * We could be racing with timeout deletion. If the list is empty,
4943 * then timeout lookup already found it and will be handling it.
4945 if (!list_empty(&req->list))
4946 list_del_init(&req->list);
4948 io_cqring_fill_event(req, -ETIME);
4949 io_commit_cqring(ctx);
4950 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4952 io_cqring_ev_posted(ctx);
4953 req_set_fail_links(req);
4955 return HRTIMER_NORESTART;
4958 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4960 struct io_kiocb *req;
4963 list_for_each_entry(req, &ctx->timeout_list, list) {
4964 if (user_data == req->user_data) {
4965 list_del_init(&req->list);
4974 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
4978 req_set_fail_links(req);
4979 io_cqring_fill_event(req, -ECANCELED);
4984 static int io_timeout_remove_prep(struct io_kiocb *req,
4985 const struct io_uring_sqe *sqe)
4987 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4989 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
4992 req->timeout.addr = READ_ONCE(sqe->addr);
4993 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4994 if (req->timeout.flags)
5001 * Remove or update an existing timeout command
5003 static int io_timeout_remove(struct io_kiocb *req)
5005 struct io_ring_ctx *ctx = req->ctx;
5008 spin_lock_irq(&ctx->completion_lock);
5009 ret = io_timeout_cancel(ctx, req->timeout.addr);
5011 io_cqring_fill_event(req, ret);
5012 io_commit_cqring(ctx);
5013 spin_unlock_irq(&ctx->completion_lock);
5014 io_cqring_ev_posted(ctx);
5016 req_set_fail_links(req);
5021 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5022 bool is_timeout_link)
5024 struct io_timeout_data *data;
5026 u32 off = READ_ONCE(sqe->off);
5028 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5030 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5032 if (off && is_timeout_link)
5034 flags = READ_ONCE(sqe->timeout_flags);
5035 if (flags & ~IORING_TIMEOUT_ABS)
5038 req->timeout.off = off;
5040 if (!req->io && io_alloc_async_ctx(req))
5043 data = &req->io->timeout;
5045 req->flags |= REQ_F_TIMEOUT;
5047 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5050 if (flags & IORING_TIMEOUT_ABS)
5051 data->mode = HRTIMER_MODE_ABS;
5053 data->mode = HRTIMER_MODE_REL;
5055 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5059 static int io_timeout(struct io_kiocb *req)
5061 struct io_ring_ctx *ctx = req->ctx;
5062 struct io_timeout_data *data = &req->io->timeout;
5063 struct list_head *entry;
5064 u32 tail, off = req->timeout.off;
5066 spin_lock_irq(&ctx->completion_lock);
5069 * sqe->off holds how many events that need to occur for this
5070 * timeout event to be satisfied. If it isn't set, then this is
5071 * a pure timeout request, sequence isn't used.
5074 req->flags |= REQ_F_TIMEOUT_NOSEQ;
5075 entry = ctx->timeout_list.prev;
5079 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5080 req->timeout.target_seq = tail + off;
5083 * Insertion sort, ensuring the first entry in the list is always
5084 * the one we need first.
5086 list_for_each_prev(entry, &ctx->timeout_list) {
5087 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5089 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
5091 /* nxt.seq is behind @tail, otherwise would've been completed */
5092 if (off >= nxt->timeout.target_seq - tail)
5096 list_add(&req->list, entry);
5097 data->timer.function = io_timeout_fn;
5098 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5099 spin_unlock_irq(&ctx->completion_lock);
5103 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5105 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5107 return req->user_data == (unsigned long) data;
5110 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5112 enum io_wq_cancel cancel_ret;
5115 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5116 switch (cancel_ret) {
5117 case IO_WQ_CANCEL_OK:
5120 case IO_WQ_CANCEL_RUNNING:
5123 case IO_WQ_CANCEL_NOTFOUND:
5131 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5132 struct io_kiocb *req, __u64 sqe_addr,
5135 unsigned long flags;
5138 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5139 if (ret != -ENOENT) {
5140 spin_lock_irqsave(&ctx->completion_lock, flags);
5144 spin_lock_irqsave(&ctx->completion_lock, flags);
5145 ret = io_timeout_cancel(ctx, sqe_addr);
5148 ret = io_poll_cancel(ctx, sqe_addr);
5152 io_cqring_fill_event(req, ret);
5153 io_commit_cqring(ctx);
5154 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5155 io_cqring_ev_posted(ctx);
5158 req_set_fail_links(req);
5162 static int io_async_cancel_prep(struct io_kiocb *req,
5163 const struct io_uring_sqe *sqe)
5165 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5167 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
5171 req->cancel.addr = READ_ONCE(sqe->addr);
5175 static int io_async_cancel(struct io_kiocb *req)
5177 struct io_ring_ctx *ctx = req->ctx;
5179 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5183 static int io_files_update_prep(struct io_kiocb *req,
5184 const struct io_uring_sqe *sqe)
5186 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
5189 req->files_update.offset = READ_ONCE(sqe->off);
5190 req->files_update.nr_args = READ_ONCE(sqe->len);
5191 if (!req->files_update.nr_args)
5193 req->files_update.arg = READ_ONCE(sqe->addr);
5197 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5198 struct io_comp_state *cs)
5200 struct io_ring_ctx *ctx = req->ctx;
5201 struct io_uring_files_update up;
5207 up.offset = req->files_update.offset;
5208 up.fds = req->files_update.arg;
5210 mutex_lock(&ctx->uring_lock);
5211 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5212 mutex_unlock(&ctx->uring_lock);
5215 req_set_fail_links(req);
5216 __io_req_complete(req, ret, 0, cs);
5220 static int io_req_defer_prep(struct io_kiocb *req,
5221 const struct io_uring_sqe *sqe)
5228 io_req_init_async(req);
5230 if (io_op_defs[req->opcode].file_table) {
5231 ret = io_grab_files(req);
5236 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
5238 switch (req->opcode) {
5241 case IORING_OP_READV:
5242 case IORING_OP_READ_FIXED:
5243 case IORING_OP_READ:
5244 ret = io_read_prep(req, sqe, true);
5246 case IORING_OP_WRITEV:
5247 case IORING_OP_WRITE_FIXED:
5248 case IORING_OP_WRITE:
5249 ret = io_write_prep(req, sqe, true);
5251 case IORING_OP_POLL_ADD:
5252 ret = io_poll_add_prep(req, sqe);
5254 case IORING_OP_POLL_REMOVE:
5255 ret = io_poll_remove_prep(req, sqe);
5257 case IORING_OP_FSYNC:
5258 ret = io_prep_fsync(req, sqe);
5260 case IORING_OP_SYNC_FILE_RANGE:
5261 ret = io_prep_sfr(req, sqe);
5263 case IORING_OP_SENDMSG:
5264 case IORING_OP_SEND:
5265 ret = io_sendmsg_prep(req, sqe);
5267 case IORING_OP_RECVMSG:
5268 case IORING_OP_RECV:
5269 ret = io_recvmsg_prep(req, sqe);
5271 case IORING_OP_CONNECT:
5272 ret = io_connect_prep(req, sqe);
5274 case IORING_OP_TIMEOUT:
5275 ret = io_timeout_prep(req, sqe, false);
5277 case IORING_OP_TIMEOUT_REMOVE:
5278 ret = io_timeout_remove_prep(req, sqe);
5280 case IORING_OP_ASYNC_CANCEL:
5281 ret = io_async_cancel_prep(req, sqe);
5283 case IORING_OP_LINK_TIMEOUT:
5284 ret = io_timeout_prep(req, sqe, true);
5286 case IORING_OP_ACCEPT:
5287 ret = io_accept_prep(req, sqe);
5289 case IORING_OP_FALLOCATE:
5290 ret = io_fallocate_prep(req, sqe);
5292 case IORING_OP_OPENAT:
5293 ret = io_openat_prep(req, sqe);
5295 case IORING_OP_CLOSE:
5296 ret = io_close_prep(req, sqe);
5298 case IORING_OP_FILES_UPDATE:
5299 ret = io_files_update_prep(req, sqe);
5301 case IORING_OP_STATX:
5302 ret = io_statx_prep(req, sqe);
5304 case IORING_OP_FADVISE:
5305 ret = io_fadvise_prep(req, sqe);
5307 case IORING_OP_MADVISE:
5308 ret = io_madvise_prep(req, sqe);
5310 case IORING_OP_OPENAT2:
5311 ret = io_openat2_prep(req, sqe);
5313 case IORING_OP_EPOLL_CTL:
5314 ret = io_epoll_ctl_prep(req, sqe);
5316 case IORING_OP_SPLICE:
5317 ret = io_splice_prep(req, sqe);
5319 case IORING_OP_PROVIDE_BUFFERS:
5320 ret = io_provide_buffers_prep(req, sqe);
5322 case IORING_OP_REMOVE_BUFFERS:
5323 ret = io_remove_buffers_prep(req, sqe);
5326 ret = io_tee_prep(req, sqe);
5329 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5338 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5340 struct io_ring_ctx *ctx = req->ctx;
5343 /* Still need defer if there is pending req in defer list. */
5344 if (!req_need_defer(req) && list_empty_careful(&ctx->defer_list))
5348 if (io_alloc_async_ctx(req))
5350 ret = io_req_defer_prep(req, sqe);
5355 spin_lock_irq(&ctx->completion_lock);
5356 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
5357 spin_unlock_irq(&ctx->completion_lock);
5361 trace_io_uring_defer(ctx, req, req->user_data);
5362 list_add_tail(&req->list, &ctx->defer_list);
5363 spin_unlock_irq(&ctx->completion_lock);
5364 return -EIOCBQUEUED;
5367 static void io_cleanup_req(struct io_kiocb *req)
5369 struct io_async_ctx *io = req->io;
5371 switch (req->opcode) {
5372 case IORING_OP_READV:
5373 case IORING_OP_READ_FIXED:
5374 case IORING_OP_READ:
5375 if (req->flags & REQ_F_BUFFER_SELECTED)
5376 kfree((void *)(unsigned long)req->rw.addr);
5378 case IORING_OP_WRITEV:
5379 case IORING_OP_WRITE_FIXED:
5380 case IORING_OP_WRITE:
5381 if (io->rw.iov != io->rw.fast_iov)
5384 case IORING_OP_RECVMSG:
5385 if (req->flags & REQ_F_BUFFER_SELECTED)
5386 kfree(req->sr_msg.kbuf);
5388 case IORING_OP_SENDMSG:
5389 if (io->msg.iov != io->msg.fast_iov)
5392 case IORING_OP_RECV:
5393 if (req->flags & REQ_F_BUFFER_SELECTED)
5394 kfree(req->sr_msg.kbuf);
5396 case IORING_OP_OPENAT:
5397 case IORING_OP_OPENAT2:
5399 case IORING_OP_SPLICE:
5401 io_put_file(req, req->splice.file_in,
5402 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5406 req->flags &= ~REQ_F_NEED_CLEANUP;
5409 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5410 bool force_nonblock, struct io_comp_state *cs)
5412 struct io_ring_ctx *ctx = req->ctx;
5415 switch (req->opcode) {
5417 ret = io_nop(req, cs);
5419 case IORING_OP_READV:
5420 case IORING_OP_READ_FIXED:
5421 case IORING_OP_READ:
5423 ret = io_read_prep(req, sqe, force_nonblock);
5427 ret = io_read(req, force_nonblock, cs);
5429 case IORING_OP_WRITEV:
5430 case IORING_OP_WRITE_FIXED:
5431 case IORING_OP_WRITE:
5433 ret = io_write_prep(req, sqe, force_nonblock);
5437 ret = io_write(req, force_nonblock, cs);
5439 case IORING_OP_FSYNC:
5441 ret = io_prep_fsync(req, sqe);
5445 ret = io_fsync(req, force_nonblock);
5447 case IORING_OP_POLL_ADD:
5449 ret = io_poll_add_prep(req, sqe);
5453 ret = io_poll_add(req);
5455 case IORING_OP_POLL_REMOVE:
5457 ret = io_poll_remove_prep(req, sqe);
5461 ret = io_poll_remove(req);
5463 case IORING_OP_SYNC_FILE_RANGE:
5465 ret = io_prep_sfr(req, sqe);
5469 ret = io_sync_file_range(req, force_nonblock);
5471 case IORING_OP_SENDMSG:
5472 case IORING_OP_SEND:
5474 ret = io_sendmsg_prep(req, sqe);
5478 if (req->opcode == IORING_OP_SENDMSG)
5479 ret = io_sendmsg(req, force_nonblock, cs);
5481 ret = io_send(req, force_nonblock, cs);
5483 case IORING_OP_RECVMSG:
5484 case IORING_OP_RECV:
5486 ret = io_recvmsg_prep(req, sqe);
5490 if (req->opcode == IORING_OP_RECVMSG)
5491 ret = io_recvmsg(req, force_nonblock, cs);
5493 ret = io_recv(req, force_nonblock, cs);
5495 case IORING_OP_TIMEOUT:
5497 ret = io_timeout_prep(req, sqe, false);
5501 ret = io_timeout(req);
5503 case IORING_OP_TIMEOUT_REMOVE:
5505 ret = io_timeout_remove_prep(req, sqe);
5509 ret = io_timeout_remove(req);
5511 case IORING_OP_ACCEPT:
5513 ret = io_accept_prep(req, sqe);
5517 ret = io_accept(req, force_nonblock, cs);
5519 case IORING_OP_CONNECT:
5521 ret = io_connect_prep(req, sqe);
5525 ret = io_connect(req, force_nonblock, cs);
5527 case IORING_OP_ASYNC_CANCEL:
5529 ret = io_async_cancel_prep(req, sqe);
5533 ret = io_async_cancel(req);
5535 case IORING_OP_FALLOCATE:
5537 ret = io_fallocate_prep(req, sqe);
5541 ret = io_fallocate(req, force_nonblock);
5543 case IORING_OP_OPENAT:
5545 ret = io_openat_prep(req, sqe);
5549 ret = io_openat(req, force_nonblock);
5551 case IORING_OP_CLOSE:
5553 ret = io_close_prep(req, sqe);
5557 ret = io_close(req, force_nonblock, cs);
5559 case IORING_OP_FILES_UPDATE:
5561 ret = io_files_update_prep(req, sqe);
5565 ret = io_files_update(req, force_nonblock, cs);
5567 case IORING_OP_STATX:
5569 ret = io_statx_prep(req, sqe);
5573 ret = io_statx(req, force_nonblock);
5575 case IORING_OP_FADVISE:
5577 ret = io_fadvise_prep(req, sqe);
5581 ret = io_fadvise(req, force_nonblock);
5583 case IORING_OP_MADVISE:
5585 ret = io_madvise_prep(req, sqe);
5589 ret = io_madvise(req, force_nonblock);
5591 case IORING_OP_OPENAT2:
5593 ret = io_openat2_prep(req, sqe);
5597 ret = io_openat2(req, force_nonblock);
5599 case IORING_OP_EPOLL_CTL:
5601 ret = io_epoll_ctl_prep(req, sqe);
5605 ret = io_epoll_ctl(req, force_nonblock, cs);
5607 case IORING_OP_SPLICE:
5609 ret = io_splice_prep(req, sqe);
5613 ret = io_splice(req, force_nonblock);
5615 case IORING_OP_PROVIDE_BUFFERS:
5617 ret = io_provide_buffers_prep(req, sqe);
5621 ret = io_provide_buffers(req, force_nonblock, cs);
5623 case IORING_OP_REMOVE_BUFFERS:
5625 ret = io_remove_buffers_prep(req, sqe);
5629 ret = io_remove_buffers(req, force_nonblock, cs);
5633 ret = io_tee_prep(req, sqe);
5637 ret = io_tee(req, force_nonblock);
5647 /* If the op doesn't have a file, we're not polling for it */
5648 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5649 const bool in_async = io_wq_current_is_worker();
5651 if (req->result == -EAGAIN)
5654 /* workqueue context doesn't hold uring_lock, grab it now */
5656 mutex_lock(&ctx->uring_lock);
5658 io_iopoll_req_issued(req);
5661 mutex_unlock(&ctx->uring_lock);
5667 static void io_arm_async_linked_timeout(struct io_kiocb *req)
5669 struct io_kiocb *link;
5671 /* link head's timeout is queued in io_queue_async_work() */
5672 if (!(req->flags & REQ_F_QUEUE_TIMEOUT))
5675 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
5676 io_queue_linked_timeout(link);
5679 static void io_wq_submit_work(struct io_wq_work **workptr)
5681 struct io_wq_work *work = *workptr;
5682 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5685 io_arm_async_linked_timeout(req);
5687 /* if NO_CANCEL is set, we must still run the work */
5688 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5689 IO_WQ_WORK_CANCEL) {
5695 ret = io_issue_sqe(req, NULL, false, NULL);
5697 * We can get EAGAIN for polled IO even though we're
5698 * forcing a sync submission from here, since we can't
5699 * wait for request slots on the block side.
5708 req_set_fail_links(req);
5709 io_req_complete(req, ret);
5712 io_steal_work(req, workptr);
5715 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5718 struct fixed_file_table *table;
5720 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5721 return table->files[index & IORING_FILE_TABLE_MASK];
5724 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5725 int fd, struct file **out_file, bool fixed)
5727 struct io_ring_ctx *ctx = req->ctx;
5731 if (unlikely(!ctx->file_data ||
5732 (unsigned) fd >= ctx->nr_user_files))
5734 fd = array_index_nospec(fd, ctx->nr_user_files);
5735 file = io_file_from_index(ctx, fd);
5737 req->fixed_file_refs = ctx->file_data->cur_refs;
5738 percpu_ref_get(req->fixed_file_refs);
5741 trace_io_uring_file_get(ctx, fd);
5742 file = __io_file_get(state, fd);
5745 if (file || io_op_defs[req->opcode].needs_file_no_error) {
5752 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5757 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5758 if (unlikely(!fixed && io_async_submit(req->ctx)))
5761 return io_file_get(state, req, fd, &req->file, fixed);
5764 static int io_grab_files(struct io_kiocb *req)
5767 struct io_ring_ctx *ctx = req->ctx;
5769 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5771 if (!ctx->ring_file)
5775 spin_lock_irq(&ctx->inflight_lock);
5777 * We use the f_ops->flush() handler to ensure that we can flush
5778 * out work accessing these files if the fd is closed. Check if
5779 * the fd has changed since we started down this path, and disallow
5780 * this operation if it has.
5782 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5783 list_add(&req->inflight_entry, &ctx->inflight_list);
5784 req->flags |= REQ_F_INFLIGHT;
5785 req->work.files = current->files;
5788 spin_unlock_irq(&ctx->inflight_lock);
5794 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5796 struct io_timeout_data *data = container_of(timer,
5797 struct io_timeout_data, timer);
5798 struct io_kiocb *req = data->req;
5799 struct io_ring_ctx *ctx = req->ctx;
5800 struct io_kiocb *prev = NULL;
5801 unsigned long flags;
5803 spin_lock_irqsave(&ctx->completion_lock, flags);
5806 * We don't expect the list to be empty, that will only happen if we
5807 * race with the completion of the linked work.
5809 if (!list_empty(&req->link_list)) {
5810 prev = list_entry(req->link_list.prev, struct io_kiocb,
5812 if (refcount_inc_not_zero(&prev->refs)) {
5813 list_del_init(&req->link_list);
5814 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5819 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5822 req_set_fail_links(prev);
5823 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5826 io_req_complete(req, -ETIME);
5828 return HRTIMER_NORESTART;
5831 static void io_queue_linked_timeout(struct io_kiocb *req)
5833 struct io_ring_ctx *ctx = req->ctx;
5836 * If the list is now empty, then our linked request finished before
5837 * we got a chance to setup the timer
5839 spin_lock_irq(&ctx->completion_lock);
5840 if (!list_empty(&req->link_list)) {
5841 struct io_timeout_data *data = &req->io->timeout;
5843 data->timer.function = io_link_timeout_fn;
5844 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5847 spin_unlock_irq(&ctx->completion_lock);
5849 /* drop submission reference */
5853 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5855 struct io_kiocb *nxt;
5857 if (!(req->flags & REQ_F_LINK_HEAD))
5859 /* for polled retry, if flag is set, we already went through here */
5860 if (req->flags & REQ_F_POLLED)
5863 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5865 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5868 req->flags |= REQ_F_LINK_TIMEOUT;
5872 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5873 struct io_comp_state *cs)
5875 struct io_kiocb *linked_timeout;
5876 struct io_kiocb *nxt;
5877 const struct cred *old_creds = NULL;
5881 linked_timeout = io_prep_linked_timeout(req);
5883 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
5884 req->work.creds != current_cred()) {
5886 revert_creds(old_creds);
5887 if (old_creds == req->work.creds)
5888 old_creds = NULL; /* restored original creds */
5890 old_creds = override_creds(req->work.creds);
5893 ret = io_issue_sqe(req, sqe, true, cs);
5896 * We async punt it if the file wasn't marked NOWAIT, or if the file
5897 * doesn't support non-blocking read/write attempts
5899 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
5900 if (io_arm_poll_handler(req)) {
5902 io_queue_linked_timeout(linked_timeout);
5906 io_req_init_async(req);
5908 if (io_op_defs[req->opcode].file_table) {
5909 ret = io_grab_files(req);
5915 * Queued up for async execution, worker will release
5916 * submit reference when the iocb is actually submitted.
5918 io_queue_async_work(req);
5924 /* drop submission reference */
5925 io_put_req_find_next(req, &nxt);
5927 if (linked_timeout) {
5929 io_queue_linked_timeout(linked_timeout);
5931 io_put_req(linked_timeout);
5934 /* and drop final reference, if we failed */
5936 req_set_fail_links(req);
5937 io_req_complete(req, ret);
5942 if (req->flags & REQ_F_FORCE_ASYNC)
5948 revert_creds(old_creds);
5951 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5952 struct io_comp_state *cs)
5956 ret = io_req_defer(req, sqe);
5958 if (ret != -EIOCBQUEUED) {
5960 req_set_fail_links(req);
5962 io_req_complete(req, ret);
5964 } else if (req->flags & REQ_F_FORCE_ASYNC) {
5967 if (io_alloc_async_ctx(req))
5969 ret = io_req_defer_prep(req, sqe);
5970 if (unlikely(ret < 0))
5975 * Never try inline submit of IOSQE_ASYNC is set, go straight
5976 * to async execution.
5978 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5979 io_queue_async_work(req);
5981 __io_queue_sqe(req, sqe, cs);
5985 static inline void io_queue_link_head(struct io_kiocb *req,
5986 struct io_comp_state *cs)
5988 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
5990 io_req_complete(req, -ECANCELED);
5992 io_queue_sqe(req, NULL, cs);
5995 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5996 struct io_kiocb **link, struct io_comp_state *cs)
5998 struct io_ring_ctx *ctx = req->ctx;
6002 * If we already have a head request, queue this one for async
6003 * submittal once the head completes. If we don't have a head but
6004 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6005 * submitted sync once the chain is complete. If none of those
6006 * conditions are true (normal request), then just queue it.
6009 struct io_kiocb *head = *link;
6012 * Taking sequential execution of a link, draining both sides
6013 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6014 * requests in the link. So, it drains the head and the
6015 * next after the link request. The last one is done via
6016 * drain_next flag to persist the effect across calls.
6018 if (req->flags & REQ_F_IO_DRAIN) {
6019 head->flags |= REQ_F_IO_DRAIN;
6020 ctx->drain_next = 1;
6022 if (io_alloc_async_ctx(req))
6025 ret = io_req_defer_prep(req, sqe);
6027 /* fail even hard links since we don't submit */
6028 head->flags |= REQ_F_FAIL_LINK;
6031 trace_io_uring_link(ctx, req, head);
6032 list_add_tail(&req->link_list, &head->link_list);
6034 /* last request of a link, enqueue the link */
6035 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6036 io_queue_link_head(head, cs);
6040 if (unlikely(ctx->drain_next)) {
6041 req->flags |= REQ_F_IO_DRAIN;
6042 ctx->drain_next = 0;
6044 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6045 req->flags |= REQ_F_LINK_HEAD;
6046 INIT_LIST_HEAD(&req->link_list);
6048 if (io_alloc_async_ctx(req))
6051 ret = io_req_defer_prep(req, sqe);
6053 req->flags |= REQ_F_FAIL_LINK;
6056 io_queue_sqe(req, sqe, cs);
6064 * Batched submission is done, ensure local IO is flushed out.
6066 static void io_submit_state_end(struct io_submit_state *state)
6068 if (!list_empty(&state->comp.list))
6069 io_submit_flush_completions(&state->comp);
6070 blk_finish_plug(&state->plug);
6071 io_state_file_put(state);
6072 if (state->free_reqs)
6073 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6077 * Start submission side cache.
6079 static void io_submit_state_start(struct io_submit_state *state,
6080 struct io_ring_ctx *ctx, unsigned int max_ios)
6082 blk_start_plug(&state->plug);
6084 state->plug.nowait = true;
6087 INIT_LIST_HEAD(&state->comp.list);
6088 state->comp.ctx = ctx;
6089 state->free_reqs = 0;
6091 state->ios_left = max_ios;
6094 static void io_commit_sqring(struct io_ring_ctx *ctx)
6096 struct io_rings *rings = ctx->rings;
6099 * Ensure any loads from the SQEs are done at this point,
6100 * since once we write the new head, the application could
6101 * write new data to them.
6103 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6107 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6108 * that is mapped by userspace. This means that care needs to be taken to
6109 * ensure that reads are stable, as we cannot rely on userspace always
6110 * being a good citizen. If members of the sqe are validated and then later
6111 * used, it's important that those reads are done through READ_ONCE() to
6112 * prevent a re-load down the line.
6114 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6116 u32 *sq_array = ctx->sq_array;
6120 * The cached sq head (or cq tail) serves two purposes:
6122 * 1) allows us to batch the cost of updating the user visible
6124 * 2) allows the kernel side to track the head on its own, even
6125 * though the application is the one updating it.
6127 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6128 if (likely(head < ctx->sq_entries))
6129 return &ctx->sq_sqes[head];
6131 /* drop invalid entries */
6132 ctx->cached_sq_dropped++;
6133 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6137 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6139 ctx->cached_sq_head++;
6142 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6143 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6144 IOSQE_BUFFER_SELECT)
6146 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6147 const struct io_uring_sqe *sqe,
6148 struct io_submit_state *state)
6150 unsigned int sqe_flags;
6154 * All io need record the previous position, if LINK vs DARIN,
6155 * it can be used to mark the position of the first IO in the
6158 req->sequence = ctx->cached_sq_head - ctx->cached_sq_dropped;
6159 req->opcode = READ_ONCE(sqe->opcode);
6160 req->user_data = READ_ONCE(sqe->user_data);
6165 /* one is dropped after submission, the other at completion */
6166 refcount_set(&req->refs, 2);
6167 req->task = current;
6170 if (unlikely(req->opcode >= IORING_OP_LAST))
6173 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6176 sqe_flags = READ_ONCE(sqe->flags);
6177 /* enforce forwards compatibility on users */
6178 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6181 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6182 !io_op_defs[req->opcode].buffer_select)
6185 id = READ_ONCE(sqe->personality);
6187 io_req_init_async(req);
6188 req->work.creds = idr_find(&ctx->personality_idr, id);
6189 if (unlikely(!req->work.creds))
6191 get_cred(req->work.creds);
6194 /* same numerical values with corresponding REQ_F_*, safe to copy */
6195 req->flags |= sqe_flags;
6197 if (!io_op_defs[req->opcode].needs_file)
6200 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
6203 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
6204 struct file *ring_file, int ring_fd)
6206 struct io_submit_state state;
6207 struct io_kiocb *link = NULL;
6208 int i, submitted = 0;
6210 /* if we have a backlog and couldn't flush it all, return BUSY */
6211 if (test_bit(0, &ctx->sq_check_overflow)) {
6212 if (!list_empty(&ctx->cq_overflow_list) &&
6213 !io_cqring_overflow_flush(ctx, false))
6217 /* make sure SQ entry isn't read before tail */
6218 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6220 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6223 io_submit_state_start(&state, ctx, nr);
6225 ctx->ring_fd = ring_fd;
6226 ctx->ring_file = ring_file;
6228 for (i = 0; i < nr; i++) {
6229 const struct io_uring_sqe *sqe;
6230 struct io_kiocb *req;
6233 sqe = io_get_sqe(ctx);
6234 if (unlikely(!sqe)) {
6235 io_consume_sqe(ctx);
6238 req = io_alloc_req(ctx, &state);
6239 if (unlikely(!req)) {
6241 submitted = -EAGAIN;
6245 err = io_init_req(ctx, req, sqe, &state);
6246 io_consume_sqe(ctx);
6247 /* will complete beyond this point, count as submitted */
6250 if (unlikely(err)) {
6253 io_req_complete(req, err);
6257 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6258 true, io_async_submit(ctx));
6259 err = io_submit_sqe(req, sqe, &link, &state.comp);
6264 if (unlikely(submitted != nr)) {
6265 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6267 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6270 io_queue_link_head(link, &state.comp);
6271 io_submit_state_end(&state);
6273 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6274 io_commit_sqring(ctx);
6279 static int io_sq_thread(void *data)
6281 struct io_ring_ctx *ctx = data;
6282 const struct cred *old_cred;
6284 unsigned long timeout;
6287 complete(&ctx->sq_thread_comp);
6289 old_cred = override_creds(ctx->creds);
6291 timeout = jiffies + ctx->sq_thread_idle;
6292 while (!kthread_should_park()) {
6293 unsigned int to_submit;
6295 if (!list_empty(&ctx->poll_list)) {
6296 unsigned nr_events = 0;
6298 mutex_lock(&ctx->uring_lock);
6299 if (!list_empty(&ctx->poll_list))
6300 io_iopoll_getevents(ctx, &nr_events, 0);
6302 timeout = jiffies + ctx->sq_thread_idle;
6303 mutex_unlock(&ctx->uring_lock);
6306 to_submit = io_sqring_entries(ctx);
6309 * If submit got -EBUSY, flag us as needing the application
6310 * to enter the kernel to reap and flush events.
6312 if (!to_submit || ret == -EBUSY) {
6314 * Drop cur_mm before scheduling, we can't hold it for
6315 * long periods (or over schedule()). Do this before
6316 * adding ourselves to the waitqueue, as the unuse/drop
6319 io_sq_thread_drop_mm(ctx);
6322 * We're polling. If we're within the defined idle
6323 * period, then let us spin without work before going
6324 * to sleep. The exception is if we got EBUSY doing
6325 * more IO, we should wait for the application to
6326 * reap events and wake us up.
6328 if (!list_empty(&ctx->poll_list) ||
6329 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6330 !percpu_ref_is_dying(&ctx->refs))) {
6331 if (current->task_works)
6337 prepare_to_wait(&ctx->sqo_wait, &wait,
6338 TASK_INTERRUPTIBLE);
6341 * While doing polled IO, before going to sleep, we need
6342 * to check if there are new reqs added to poll_list, it
6343 * is because reqs may have been punted to io worker and
6344 * will be added to poll_list later, hence check the
6347 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6348 !list_empty_careful(&ctx->poll_list)) {
6349 finish_wait(&ctx->sqo_wait, &wait);
6353 /* Tell userspace we may need a wakeup call */
6354 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6355 /* make sure to read SQ tail after writing flags */
6358 to_submit = io_sqring_entries(ctx);
6359 if (!to_submit || ret == -EBUSY) {
6360 if (kthread_should_park()) {
6361 finish_wait(&ctx->sqo_wait, &wait);
6364 if (current->task_works) {
6366 finish_wait(&ctx->sqo_wait, &wait);
6369 if (signal_pending(current))
6370 flush_signals(current);
6372 finish_wait(&ctx->sqo_wait, &wait);
6374 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6378 finish_wait(&ctx->sqo_wait, &wait);
6380 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6383 mutex_lock(&ctx->uring_lock);
6384 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6385 ret = io_submit_sqes(ctx, to_submit, NULL, -1);
6386 mutex_unlock(&ctx->uring_lock);
6387 timeout = jiffies + ctx->sq_thread_idle;
6390 if (current->task_works)
6393 io_sq_thread_drop_mm(ctx);
6394 revert_creds(old_cred);
6401 struct io_wait_queue {
6402 struct wait_queue_entry wq;
6403 struct io_ring_ctx *ctx;
6405 unsigned nr_timeouts;
6408 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6410 struct io_ring_ctx *ctx = iowq->ctx;
6413 * Wake up if we have enough events, or if a timeout occurred since we
6414 * started waiting. For timeouts, we always want to return to userspace,
6415 * regardless of event count.
6417 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6418 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6421 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6422 int wake_flags, void *key)
6424 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6427 /* use noflush == true, as we can't safely rely on locking context */
6428 if (!io_should_wake(iowq, true))
6431 return autoremove_wake_function(curr, mode, wake_flags, key);
6435 * Wait until events become available, if we don't already have some. The
6436 * application must reap them itself, as they reside on the shared cq ring.
6438 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6439 const sigset_t __user *sig, size_t sigsz)
6441 struct io_wait_queue iowq = {
6444 .func = io_wake_function,
6445 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6448 .to_wait = min_events,
6450 struct io_rings *rings = ctx->rings;
6454 if (io_cqring_events(ctx, false) >= min_events)
6456 if (!current->task_works)
6462 #ifdef CONFIG_COMPAT
6463 if (in_compat_syscall())
6464 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6468 ret = set_user_sigmask(sig, sigsz);
6474 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6475 trace_io_uring_cqring_wait(ctx, min_events);
6477 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6478 TASK_INTERRUPTIBLE);
6479 if (current->task_works)
6481 if (io_should_wake(&iowq, false))
6484 if (signal_pending(current)) {
6489 finish_wait(&ctx->wait, &iowq.wq);
6491 restore_saved_sigmask_unless(ret == -EINTR);
6493 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6496 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6498 #if defined(CONFIG_UNIX)
6499 if (ctx->ring_sock) {
6500 struct sock *sock = ctx->ring_sock->sk;
6501 struct sk_buff *skb;
6503 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6509 for (i = 0; i < ctx->nr_user_files; i++) {
6512 file = io_file_from_index(ctx, i);
6519 static void io_file_ref_kill(struct percpu_ref *ref)
6521 struct fixed_file_data *data;
6523 data = container_of(ref, struct fixed_file_data, refs);
6524 complete(&data->done);
6527 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6529 struct fixed_file_data *data = ctx->file_data;
6530 struct fixed_file_ref_node *ref_node = NULL;
6531 unsigned nr_tables, i;
6536 spin_lock(&data->lock);
6537 if (!list_empty(&data->ref_list))
6538 ref_node = list_first_entry(&data->ref_list,
6539 struct fixed_file_ref_node, node);
6540 spin_unlock(&data->lock);
6542 percpu_ref_kill(&ref_node->refs);
6544 percpu_ref_kill(&data->refs);
6546 /* wait for all refs nodes to complete */
6547 flush_delayed_work(&ctx->file_put_work);
6548 wait_for_completion(&data->done);
6550 __io_sqe_files_unregister(ctx);
6551 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6552 for (i = 0; i < nr_tables; i++)
6553 kfree(data->table[i].files);
6555 percpu_ref_exit(&data->refs);
6557 ctx->file_data = NULL;
6558 ctx->nr_user_files = 0;
6562 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6564 if (ctx->sqo_thread) {
6565 wait_for_completion(&ctx->sq_thread_comp);
6567 * The park is a bit of a work-around, without it we get
6568 * warning spews on shutdown with SQPOLL set and affinity
6569 * set to a single CPU.
6571 kthread_park(ctx->sqo_thread);
6572 kthread_stop(ctx->sqo_thread);
6573 ctx->sqo_thread = NULL;
6577 static void io_finish_async(struct io_ring_ctx *ctx)
6579 io_sq_thread_stop(ctx);
6582 io_wq_destroy(ctx->io_wq);
6587 #if defined(CONFIG_UNIX)
6589 * Ensure the UNIX gc is aware of our file set, so we are certain that
6590 * the io_uring can be safely unregistered on process exit, even if we have
6591 * loops in the file referencing.
6593 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6595 struct sock *sk = ctx->ring_sock->sk;
6596 struct scm_fp_list *fpl;
6597 struct sk_buff *skb;
6600 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6604 skb = alloc_skb(0, GFP_KERNEL);
6613 fpl->user = get_uid(ctx->user);
6614 for (i = 0; i < nr; i++) {
6615 struct file *file = io_file_from_index(ctx, i + offset);
6619 fpl->fp[nr_files] = get_file(file);
6620 unix_inflight(fpl->user, fpl->fp[nr_files]);
6625 fpl->max = SCM_MAX_FD;
6626 fpl->count = nr_files;
6627 UNIXCB(skb).fp = fpl;
6628 skb->destructor = unix_destruct_scm;
6629 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6630 skb_queue_head(&sk->sk_receive_queue, skb);
6632 for (i = 0; i < nr_files; i++)
6643 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6644 * causes regular reference counting to break down. We rely on the UNIX
6645 * garbage collection to take care of this problem for us.
6647 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6649 unsigned left, total;
6653 left = ctx->nr_user_files;
6655 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6657 ret = __io_sqe_files_scm(ctx, this_files, total);
6661 total += this_files;
6667 while (total < ctx->nr_user_files) {
6668 struct file *file = io_file_from_index(ctx, total);
6678 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6684 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6689 for (i = 0; i < nr_tables; i++) {
6690 struct fixed_file_table *table = &ctx->file_data->table[i];
6691 unsigned this_files;
6693 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6694 table->files = kcalloc(this_files, sizeof(struct file *),
6698 nr_files -= this_files;
6704 for (i = 0; i < nr_tables; i++) {
6705 struct fixed_file_table *table = &ctx->file_data->table[i];
6706 kfree(table->files);
6711 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6713 #if defined(CONFIG_UNIX)
6714 struct sock *sock = ctx->ring_sock->sk;
6715 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6716 struct sk_buff *skb;
6719 __skb_queue_head_init(&list);
6722 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6723 * remove this entry and rearrange the file array.
6725 skb = skb_dequeue(head);
6727 struct scm_fp_list *fp;
6729 fp = UNIXCB(skb).fp;
6730 for (i = 0; i < fp->count; i++) {
6733 if (fp->fp[i] != file)
6736 unix_notinflight(fp->user, fp->fp[i]);
6737 left = fp->count - 1 - i;
6739 memmove(&fp->fp[i], &fp->fp[i + 1],
6740 left * sizeof(struct file *));
6747 __skb_queue_tail(&list, skb);
6757 __skb_queue_tail(&list, skb);
6759 skb = skb_dequeue(head);
6762 if (skb_peek(&list)) {
6763 spin_lock_irq(&head->lock);
6764 while ((skb = __skb_dequeue(&list)) != NULL)
6765 __skb_queue_tail(head, skb);
6766 spin_unlock_irq(&head->lock);
6773 struct io_file_put {
6774 struct list_head list;
6778 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
6780 struct fixed_file_data *file_data = ref_node->file_data;
6781 struct io_ring_ctx *ctx = file_data->ctx;
6782 struct io_file_put *pfile, *tmp;
6784 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6785 list_del(&pfile->list);
6786 io_ring_file_put(ctx, pfile->file);
6790 spin_lock(&file_data->lock);
6791 list_del(&ref_node->node);
6792 spin_unlock(&file_data->lock);
6794 percpu_ref_exit(&ref_node->refs);
6796 percpu_ref_put(&file_data->refs);
6799 static void io_file_put_work(struct work_struct *work)
6801 struct io_ring_ctx *ctx;
6802 struct llist_node *node;
6804 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
6805 node = llist_del_all(&ctx->file_put_llist);
6808 struct fixed_file_ref_node *ref_node;
6809 struct llist_node *next = node->next;
6811 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
6812 __io_file_put_work(ref_node);
6817 static void io_file_data_ref_zero(struct percpu_ref *ref)
6819 struct fixed_file_ref_node *ref_node;
6820 struct io_ring_ctx *ctx;
6824 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6825 ctx = ref_node->file_data->ctx;
6827 if (percpu_ref_is_dying(&ctx->file_data->refs))
6830 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
6832 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
6834 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
6837 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6838 struct io_ring_ctx *ctx)
6840 struct fixed_file_ref_node *ref_node;
6842 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6844 return ERR_PTR(-ENOMEM);
6846 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6849 return ERR_PTR(-ENOMEM);
6851 INIT_LIST_HEAD(&ref_node->node);
6852 INIT_LIST_HEAD(&ref_node->file_list);
6853 ref_node->file_data = ctx->file_data;
6857 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6859 percpu_ref_exit(&ref_node->refs);
6863 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6866 __s32 __user *fds = (__s32 __user *) arg;
6871 struct fixed_file_ref_node *ref_node;
6877 if (nr_args > IORING_MAX_FIXED_FILES)
6880 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6881 if (!ctx->file_data)
6883 ctx->file_data->ctx = ctx;
6884 init_completion(&ctx->file_data->done);
6885 INIT_LIST_HEAD(&ctx->file_data->ref_list);
6886 spin_lock_init(&ctx->file_data->lock);
6888 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6889 ctx->file_data->table = kcalloc(nr_tables,
6890 sizeof(struct fixed_file_table),
6892 if (!ctx->file_data->table) {
6893 kfree(ctx->file_data);
6894 ctx->file_data = NULL;
6898 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6899 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6900 kfree(ctx->file_data->table);
6901 kfree(ctx->file_data);
6902 ctx->file_data = NULL;
6906 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6907 percpu_ref_exit(&ctx->file_data->refs);
6908 kfree(ctx->file_data->table);
6909 kfree(ctx->file_data);
6910 ctx->file_data = NULL;
6914 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6915 struct fixed_file_table *table;
6919 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6921 /* allow sparse sets */
6927 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6928 index = i & IORING_FILE_TABLE_MASK;
6936 * Don't allow io_uring instances to be registered. If UNIX
6937 * isn't enabled, then this causes a reference cycle and this
6938 * instance can never get freed. If UNIX is enabled we'll
6939 * handle it just fine, but there's still no point in allowing
6940 * a ring fd as it doesn't support regular read/write anyway.
6942 if (file->f_op == &io_uring_fops) {
6947 table->files[index] = file;
6951 for (i = 0; i < ctx->nr_user_files; i++) {
6952 file = io_file_from_index(ctx, i);
6956 for (i = 0; i < nr_tables; i++)
6957 kfree(ctx->file_data->table[i].files);
6959 kfree(ctx->file_data->table);
6960 kfree(ctx->file_data);
6961 ctx->file_data = NULL;
6962 ctx->nr_user_files = 0;
6966 ret = io_sqe_files_scm(ctx);
6968 io_sqe_files_unregister(ctx);
6972 ref_node = alloc_fixed_file_ref_node(ctx);
6973 if (IS_ERR(ref_node)) {
6974 io_sqe_files_unregister(ctx);
6975 return PTR_ERR(ref_node);
6978 ctx->file_data->cur_refs = &ref_node->refs;
6979 spin_lock(&ctx->file_data->lock);
6980 list_add(&ref_node->node, &ctx->file_data->ref_list);
6981 spin_unlock(&ctx->file_data->lock);
6982 percpu_ref_get(&ctx->file_data->refs);
6986 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
6989 #if defined(CONFIG_UNIX)
6990 struct sock *sock = ctx->ring_sock->sk;
6991 struct sk_buff_head *head = &sock->sk_receive_queue;
6992 struct sk_buff *skb;
6995 * See if we can merge this file into an existing skb SCM_RIGHTS
6996 * file set. If there's no room, fall back to allocating a new skb
6997 * and filling it in.
6999 spin_lock_irq(&head->lock);
7000 skb = skb_peek(head);
7002 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7004 if (fpl->count < SCM_MAX_FD) {
7005 __skb_unlink(skb, head);
7006 spin_unlock_irq(&head->lock);
7007 fpl->fp[fpl->count] = get_file(file);
7008 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7010 spin_lock_irq(&head->lock);
7011 __skb_queue_head(head, skb);
7016 spin_unlock_irq(&head->lock);
7023 return __io_sqe_files_scm(ctx, 1, index);
7029 static int io_queue_file_removal(struct fixed_file_data *data,
7032 struct io_file_put *pfile;
7033 struct percpu_ref *refs = data->cur_refs;
7034 struct fixed_file_ref_node *ref_node;
7036 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7040 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
7042 list_add(&pfile->list, &ref_node->file_list);
7047 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7048 struct io_uring_files_update *up,
7051 struct fixed_file_data *data = ctx->file_data;
7052 struct fixed_file_ref_node *ref_node;
7057 bool needs_switch = false;
7059 if (check_add_overflow(up->offset, nr_args, &done))
7061 if (done > ctx->nr_user_files)
7064 ref_node = alloc_fixed_file_ref_node(ctx);
7065 if (IS_ERR(ref_node))
7066 return PTR_ERR(ref_node);
7069 fds = u64_to_user_ptr(up->fds);
7071 struct fixed_file_table *table;
7075 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7079 i = array_index_nospec(up->offset, ctx->nr_user_files);
7080 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7081 index = i & IORING_FILE_TABLE_MASK;
7082 if (table->files[index]) {
7083 file = io_file_from_index(ctx, index);
7084 err = io_queue_file_removal(data, file);
7087 table->files[index] = NULL;
7088 needs_switch = true;
7097 * Don't allow io_uring instances to be registered. If
7098 * UNIX isn't enabled, then this causes a reference
7099 * cycle and this instance can never get freed. If UNIX
7100 * is enabled we'll handle it just fine, but there's
7101 * still no point in allowing a ring fd as it doesn't
7102 * support regular read/write anyway.
7104 if (file->f_op == &io_uring_fops) {
7109 table->files[index] = file;
7110 err = io_sqe_file_register(ctx, file, i);
7120 percpu_ref_kill(data->cur_refs);
7121 spin_lock(&data->lock);
7122 list_add(&ref_node->node, &data->ref_list);
7123 data->cur_refs = &ref_node->refs;
7124 spin_unlock(&data->lock);
7125 percpu_ref_get(&ctx->file_data->refs);
7127 destroy_fixed_file_ref_node(ref_node);
7129 return done ? done : err;
7132 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7135 struct io_uring_files_update up;
7137 if (!ctx->file_data)
7141 if (copy_from_user(&up, arg, sizeof(up)))
7146 return __io_sqe_files_update(ctx, &up, nr_args);
7149 static void io_free_work(struct io_wq_work *work)
7151 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7153 /* Consider that io_steal_work() relies on this ref */
7157 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7158 struct io_uring_params *p)
7160 struct io_wq_data data;
7162 struct io_ring_ctx *ctx_attach;
7163 unsigned int concurrency;
7166 data.user = ctx->user;
7167 data.free_work = io_free_work;
7168 data.do_work = io_wq_submit_work;
7170 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7171 /* Do QD, or 4 * CPUS, whatever is smallest */
7172 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7174 ctx->io_wq = io_wq_create(concurrency, &data);
7175 if (IS_ERR(ctx->io_wq)) {
7176 ret = PTR_ERR(ctx->io_wq);
7182 f = fdget(p->wq_fd);
7186 if (f.file->f_op != &io_uring_fops) {
7191 ctx_attach = f.file->private_data;
7192 /* @io_wq is protected by holding the fd */
7193 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7198 ctx->io_wq = ctx_attach->io_wq;
7204 static int io_sq_offload_start(struct io_ring_ctx *ctx,
7205 struct io_uring_params *p)
7209 mmgrab(current->mm);
7210 ctx->sqo_mm = current->mm;
7212 if (ctx->flags & IORING_SETUP_SQPOLL) {
7214 if (!capable(CAP_SYS_ADMIN))
7217 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7218 if (!ctx->sq_thread_idle)
7219 ctx->sq_thread_idle = HZ;
7221 if (p->flags & IORING_SETUP_SQ_AFF) {
7222 int cpu = p->sq_thread_cpu;
7225 if (cpu >= nr_cpu_ids)
7227 if (!cpu_online(cpu))
7230 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
7234 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
7237 if (IS_ERR(ctx->sqo_thread)) {
7238 ret = PTR_ERR(ctx->sqo_thread);
7239 ctx->sqo_thread = NULL;
7242 wake_up_process(ctx->sqo_thread);
7243 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7244 /* Can't have SQ_AFF without SQPOLL */
7249 ret = io_init_wq_offload(ctx, p);
7255 io_finish_async(ctx);
7256 mmdrop(ctx->sqo_mm);
7261 static inline void __io_unaccount_mem(struct user_struct *user,
7262 unsigned long nr_pages)
7264 atomic_long_sub(nr_pages, &user->locked_vm);
7267 static inline int __io_account_mem(struct user_struct *user,
7268 unsigned long nr_pages)
7270 unsigned long page_limit, cur_pages, new_pages;
7272 /* Don't allow more pages than we can safely lock */
7273 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7276 cur_pages = atomic_long_read(&user->locked_vm);
7277 new_pages = cur_pages + nr_pages;
7278 if (new_pages > page_limit)
7280 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7281 new_pages) != cur_pages);
7286 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7287 enum io_mem_account acct)
7290 __io_unaccount_mem(ctx->user, nr_pages);
7293 if (acct == ACCT_LOCKED)
7294 ctx->sqo_mm->locked_vm -= nr_pages;
7295 else if (acct == ACCT_PINNED)
7296 atomic64_sub(nr_pages, &ctx->sqo_mm->pinned_vm);
7300 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7301 enum io_mem_account acct)
7305 if (ctx->limit_mem) {
7306 ret = __io_account_mem(ctx->user, nr_pages);
7312 if (acct == ACCT_LOCKED)
7313 ctx->sqo_mm->locked_vm += nr_pages;
7314 else if (acct == ACCT_PINNED)
7315 atomic64_add(nr_pages, &ctx->sqo_mm->pinned_vm);
7321 static void io_mem_free(void *ptr)
7328 page = virt_to_head_page(ptr);
7329 if (put_page_testzero(page))
7330 free_compound_page(page);
7333 static void *io_mem_alloc(size_t size)
7335 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7338 return (void *) __get_free_pages(gfp_flags, get_order(size));
7341 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7344 struct io_rings *rings;
7345 size_t off, sq_array_size;
7347 off = struct_size(rings, cqes, cq_entries);
7348 if (off == SIZE_MAX)
7352 off = ALIGN(off, SMP_CACHE_BYTES);
7357 sq_array_size = array_size(sizeof(u32), sq_entries);
7358 if (sq_array_size == SIZE_MAX)
7361 if (check_add_overflow(off, sq_array_size, &off))
7370 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7374 pages = (size_t)1 << get_order(
7375 rings_size(sq_entries, cq_entries, NULL));
7376 pages += (size_t)1 << get_order(
7377 array_size(sizeof(struct io_uring_sqe), sq_entries));
7382 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7386 if (!ctx->user_bufs)
7389 for (i = 0; i < ctx->nr_user_bufs; i++) {
7390 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7392 for (j = 0; j < imu->nr_bvecs; j++)
7393 unpin_user_page(imu->bvec[j].bv_page);
7395 io_unaccount_mem(ctx, imu->nr_bvecs, ACCT_PINNED);
7400 kfree(ctx->user_bufs);
7401 ctx->user_bufs = NULL;
7402 ctx->nr_user_bufs = 0;
7406 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7407 void __user *arg, unsigned index)
7409 struct iovec __user *src;
7411 #ifdef CONFIG_COMPAT
7413 struct compat_iovec __user *ciovs;
7414 struct compat_iovec ciov;
7416 ciovs = (struct compat_iovec __user *) arg;
7417 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7420 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7421 dst->iov_len = ciov.iov_len;
7425 src = (struct iovec __user *) arg;
7426 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7431 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7434 struct vm_area_struct **vmas = NULL;
7435 struct page **pages = NULL;
7436 int i, j, got_pages = 0;
7441 if (!nr_args || nr_args > UIO_MAXIOV)
7444 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7446 if (!ctx->user_bufs)
7449 for (i = 0; i < nr_args; i++) {
7450 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7451 unsigned long off, start, end, ubuf;
7456 ret = io_copy_iov(ctx, &iov, arg, i);
7461 * Don't impose further limits on the size and buffer
7462 * constraints here, we'll -EINVAL later when IO is
7463 * submitted if they are wrong.
7466 if (!iov.iov_base || !iov.iov_len)
7469 /* arbitrary limit, but we need something */
7470 if (iov.iov_len > SZ_1G)
7473 ubuf = (unsigned long) iov.iov_base;
7474 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7475 start = ubuf >> PAGE_SHIFT;
7476 nr_pages = end - start;
7478 ret = io_account_mem(ctx, nr_pages, ACCT_PINNED);
7483 if (!pages || nr_pages > got_pages) {
7486 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7488 vmas = kvmalloc_array(nr_pages,
7489 sizeof(struct vm_area_struct *),
7491 if (!pages || !vmas) {
7493 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7496 got_pages = nr_pages;
7499 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7503 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7508 mmap_read_lock(current->mm);
7509 pret = pin_user_pages(ubuf, nr_pages,
7510 FOLL_WRITE | FOLL_LONGTERM,
7512 if (pret == nr_pages) {
7513 /* don't support file backed memory */
7514 for (j = 0; j < nr_pages; j++) {
7515 struct vm_area_struct *vma = vmas[j];
7518 !is_file_hugepages(vma->vm_file)) {
7524 ret = pret < 0 ? pret : -EFAULT;
7526 mmap_read_unlock(current->mm);
7529 * if we did partial map, or found file backed vmas,
7530 * release any pages we did get
7533 unpin_user_pages(pages, pret);
7534 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7539 off = ubuf & ~PAGE_MASK;
7541 for (j = 0; j < nr_pages; j++) {
7544 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7545 imu->bvec[j].bv_page = pages[j];
7546 imu->bvec[j].bv_len = vec_len;
7547 imu->bvec[j].bv_offset = off;
7551 /* store original address for later verification */
7553 imu->len = iov.iov_len;
7554 imu->nr_bvecs = nr_pages;
7556 ctx->nr_user_bufs++;
7564 io_sqe_buffer_unregister(ctx);
7568 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7570 __s32 __user *fds = arg;
7576 if (copy_from_user(&fd, fds, sizeof(*fds)))
7579 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7580 if (IS_ERR(ctx->cq_ev_fd)) {
7581 int ret = PTR_ERR(ctx->cq_ev_fd);
7582 ctx->cq_ev_fd = NULL;
7589 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7591 if (ctx->cq_ev_fd) {
7592 eventfd_ctx_put(ctx->cq_ev_fd);
7593 ctx->cq_ev_fd = NULL;
7600 static int __io_destroy_buffers(int id, void *p, void *data)
7602 struct io_ring_ctx *ctx = data;
7603 struct io_buffer *buf = p;
7605 __io_remove_buffers(ctx, buf, id, -1U);
7609 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7611 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7612 idr_destroy(&ctx->io_buffer_idr);
7615 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7617 io_finish_async(ctx);
7619 mmdrop(ctx->sqo_mm);
7623 io_iopoll_reap_events(ctx);
7624 io_sqe_buffer_unregister(ctx);
7625 io_sqe_files_unregister(ctx);
7626 io_eventfd_unregister(ctx);
7627 io_destroy_buffers(ctx);
7628 idr_destroy(&ctx->personality_idr);
7630 #if defined(CONFIG_UNIX)
7631 if (ctx->ring_sock) {
7632 ctx->ring_sock->file = NULL; /* so that iput() is called */
7633 sock_release(ctx->ring_sock);
7637 io_mem_free(ctx->rings);
7638 io_mem_free(ctx->sq_sqes);
7640 percpu_ref_exit(&ctx->refs);
7641 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
7643 free_uid(ctx->user);
7644 put_cred(ctx->creds);
7645 kfree(ctx->cancel_hash);
7646 kmem_cache_free(req_cachep, ctx->fallback_req);
7650 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7652 struct io_ring_ctx *ctx = file->private_data;
7655 poll_wait(file, &ctx->cq_wait, wait);
7657 * synchronizes with barrier from wq_has_sleeper call in
7661 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7662 ctx->rings->sq_ring_entries)
7663 mask |= EPOLLOUT | EPOLLWRNORM;
7664 if (io_cqring_events(ctx, false))
7665 mask |= EPOLLIN | EPOLLRDNORM;
7670 static int io_uring_fasync(int fd, struct file *file, int on)
7672 struct io_ring_ctx *ctx = file->private_data;
7674 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7677 static int io_remove_personalities(int id, void *p, void *data)
7679 struct io_ring_ctx *ctx = data;
7680 const struct cred *cred;
7682 cred = idr_remove(&ctx->personality_idr, id);
7688 static void io_ring_exit_work(struct work_struct *work)
7690 struct io_ring_ctx *ctx;
7692 ctx = container_of(work, struct io_ring_ctx, exit_work);
7694 io_cqring_overflow_flush(ctx, true);
7697 * If we're doing polled IO and end up having requests being
7698 * submitted async (out-of-line), then completions can come in while
7699 * we're waiting for refs to drop. We need to reap these manually,
7700 * as nobody else will be looking for them.
7702 while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20)) {
7703 io_iopoll_reap_events(ctx);
7705 io_cqring_overflow_flush(ctx, true);
7707 io_ring_ctx_free(ctx);
7710 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7712 mutex_lock(&ctx->uring_lock);
7713 percpu_ref_kill(&ctx->refs);
7714 mutex_unlock(&ctx->uring_lock);
7716 io_kill_timeouts(ctx);
7717 io_poll_remove_all(ctx);
7720 io_wq_cancel_all(ctx->io_wq);
7722 io_iopoll_reap_events(ctx);
7723 /* if we failed setting up the ctx, we might not have any rings */
7725 io_cqring_overflow_flush(ctx, true);
7726 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7727 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7728 queue_work(system_wq, &ctx->exit_work);
7731 static int io_uring_release(struct inode *inode, struct file *file)
7733 struct io_ring_ctx *ctx = file->private_data;
7735 file->private_data = NULL;
7736 io_ring_ctx_wait_and_kill(ctx);
7740 static bool io_wq_files_match(struct io_wq_work *work, void *data)
7742 struct files_struct *files = data;
7744 return work->files == files;
7747 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7748 struct files_struct *files)
7750 if (list_empty_careful(&ctx->inflight_list))
7753 /* cancel all at once, should be faster than doing it one by one*/
7754 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
7756 while (!list_empty_careful(&ctx->inflight_list)) {
7757 struct io_kiocb *cancel_req = NULL, *req;
7760 spin_lock_irq(&ctx->inflight_lock);
7761 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7762 if (req->work.files != files)
7764 /* req is being completed, ignore */
7765 if (!refcount_inc_not_zero(&req->refs))
7771 prepare_to_wait(&ctx->inflight_wait, &wait,
7772 TASK_UNINTERRUPTIBLE);
7773 spin_unlock_irq(&ctx->inflight_lock);
7775 /* We need to keep going until we don't find a matching req */
7779 if (cancel_req->flags & REQ_F_OVERFLOW) {
7780 spin_lock_irq(&ctx->completion_lock);
7781 list_del(&cancel_req->list);
7782 cancel_req->flags &= ~REQ_F_OVERFLOW;
7783 if (list_empty(&ctx->cq_overflow_list)) {
7784 clear_bit(0, &ctx->sq_check_overflow);
7785 clear_bit(0, &ctx->cq_check_overflow);
7787 spin_unlock_irq(&ctx->completion_lock);
7789 WRITE_ONCE(ctx->rings->cq_overflow,
7790 atomic_inc_return(&ctx->cached_cq_overflow));
7793 * Put inflight ref and overflow ref. If that's
7794 * all we had, then we're done with this request.
7796 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7797 io_free_req(cancel_req);
7798 finish_wait(&ctx->inflight_wait, &wait);
7802 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7803 io_put_req(cancel_req);
7807 finish_wait(&ctx->inflight_wait, &wait);
7811 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
7813 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7814 struct task_struct *task = data;
7816 return req->task == task;
7819 static int io_uring_flush(struct file *file, void *data)
7821 struct io_ring_ctx *ctx = file->private_data;
7823 io_uring_cancel_files(ctx, data);
7826 * If the task is going away, cancel work it may have pending
7828 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7829 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, current, true);
7834 static void *io_uring_validate_mmap_request(struct file *file,
7835 loff_t pgoff, size_t sz)
7837 struct io_ring_ctx *ctx = file->private_data;
7838 loff_t offset = pgoff << PAGE_SHIFT;
7843 case IORING_OFF_SQ_RING:
7844 case IORING_OFF_CQ_RING:
7847 case IORING_OFF_SQES:
7851 return ERR_PTR(-EINVAL);
7854 page = virt_to_head_page(ptr);
7855 if (sz > page_size(page))
7856 return ERR_PTR(-EINVAL);
7863 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7865 size_t sz = vma->vm_end - vma->vm_start;
7869 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7871 return PTR_ERR(ptr);
7873 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7874 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7877 #else /* !CONFIG_MMU */
7879 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7881 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7884 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7886 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7889 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7890 unsigned long addr, unsigned long len,
7891 unsigned long pgoff, unsigned long flags)
7895 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7897 return PTR_ERR(ptr);
7899 return (unsigned long) ptr;
7902 #endif /* !CONFIG_MMU */
7904 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7905 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7908 struct io_ring_ctx *ctx;
7913 if (current->task_works)
7916 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7924 if (f.file->f_op != &io_uring_fops)
7928 ctx = f.file->private_data;
7929 if (!percpu_ref_tryget(&ctx->refs))
7933 * For SQ polling, the thread will do all submissions and completions.
7934 * Just return the requested submit count, and wake the thread if
7938 if (ctx->flags & IORING_SETUP_SQPOLL) {
7939 if (!list_empty_careful(&ctx->cq_overflow_list))
7940 io_cqring_overflow_flush(ctx, false);
7941 if (flags & IORING_ENTER_SQ_WAKEUP)
7942 wake_up(&ctx->sqo_wait);
7943 submitted = to_submit;
7944 } else if (to_submit) {
7945 mutex_lock(&ctx->uring_lock);
7946 submitted = io_submit_sqes(ctx, to_submit, f.file, fd);
7947 mutex_unlock(&ctx->uring_lock);
7949 if (submitted != to_submit)
7952 if (flags & IORING_ENTER_GETEVENTS) {
7953 unsigned nr_events = 0;
7955 min_complete = min(min_complete, ctx->cq_entries);
7958 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
7959 * space applications don't need to do io completion events
7960 * polling again, they can rely on io_sq_thread to do polling
7961 * work, which can reduce cpu usage and uring_lock contention.
7963 if (ctx->flags & IORING_SETUP_IOPOLL &&
7964 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7965 ret = io_iopoll_check(ctx, &nr_events, min_complete);
7967 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
7972 percpu_ref_put(&ctx->refs);
7975 return submitted ? submitted : ret;
7978 #ifdef CONFIG_PROC_FS
7979 static int io_uring_show_cred(int id, void *p, void *data)
7981 const struct cred *cred = p;
7982 struct seq_file *m = data;
7983 struct user_namespace *uns = seq_user_ns(m);
7984 struct group_info *gi;
7989 seq_printf(m, "%5d\n", id);
7990 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
7991 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
7992 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
7993 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
7994 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
7995 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
7996 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
7997 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
7998 seq_puts(m, "\n\tGroups:\t");
7999 gi = cred->group_info;
8000 for (g = 0; g < gi->ngroups; g++) {
8001 seq_put_decimal_ull(m, g ? " " : "",
8002 from_kgid_munged(uns, gi->gid[g]));
8004 seq_puts(m, "\n\tCapEff:\t");
8005 cap = cred->cap_effective;
8006 CAP_FOR_EACH_U32(__capi)
8007 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8012 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8016 mutex_lock(&ctx->uring_lock);
8017 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8018 for (i = 0; i < ctx->nr_user_files; i++) {
8019 struct fixed_file_table *table;
8022 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8023 f = table->files[i & IORING_FILE_TABLE_MASK];
8025 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8027 seq_printf(m, "%5u: <none>\n", i);
8029 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8030 for (i = 0; i < ctx->nr_user_bufs; i++) {
8031 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8033 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8034 (unsigned int) buf->len);
8036 if (!idr_is_empty(&ctx->personality_idr)) {
8037 seq_printf(m, "Personalities:\n");
8038 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8040 seq_printf(m, "PollList:\n");
8041 spin_lock_irq(&ctx->completion_lock);
8042 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8043 struct hlist_head *list = &ctx->cancel_hash[i];
8044 struct io_kiocb *req;
8046 hlist_for_each_entry(req, list, hash_node)
8047 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
8048 req->task->task_works != NULL);
8050 spin_unlock_irq(&ctx->completion_lock);
8051 mutex_unlock(&ctx->uring_lock);
8054 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8056 struct io_ring_ctx *ctx = f->private_data;
8058 if (percpu_ref_tryget(&ctx->refs)) {
8059 __io_uring_show_fdinfo(ctx, m);
8060 percpu_ref_put(&ctx->refs);
8065 static const struct file_operations io_uring_fops = {
8066 .release = io_uring_release,
8067 .flush = io_uring_flush,
8068 .mmap = io_uring_mmap,
8070 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8071 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8073 .poll = io_uring_poll,
8074 .fasync = io_uring_fasync,
8075 #ifdef CONFIG_PROC_FS
8076 .show_fdinfo = io_uring_show_fdinfo,
8080 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8081 struct io_uring_params *p)
8083 struct io_rings *rings;
8084 size_t size, sq_array_offset;
8086 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8087 if (size == SIZE_MAX)
8090 rings = io_mem_alloc(size);
8095 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8096 rings->sq_ring_mask = p->sq_entries - 1;
8097 rings->cq_ring_mask = p->cq_entries - 1;
8098 rings->sq_ring_entries = p->sq_entries;
8099 rings->cq_ring_entries = p->cq_entries;
8100 ctx->sq_mask = rings->sq_ring_mask;
8101 ctx->cq_mask = rings->cq_ring_mask;
8102 ctx->sq_entries = rings->sq_ring_entries;
8103 ctx->cq_entries = rings->cq_ring_entries;
8105 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8106 if (size == SIZE_MAX) {
8107 io_mem_free(ctx->rings);
8112 ctx->sq_sqes = io_mem_alloc(size);
8113 if (!ctx->sq_sqes) {
8114 io_mem_free(ctx->rings);
8123 * Allocate an anonymous fd, this is what constitutes the application
8124 * visible backing of an io_uring instance. The application mmaps this
8125 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8126 * we have to tie this fd to a socket for file garbage collection purposes.
8128 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8133 #if defined(CONFIG_UNIX)
8134 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8140 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8144 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8145 O_RDWR | O_CLOEXEC);
8148 ret = PTR_ERR(file);
8152 #if defined(CONFIG_UNIX)
8153 ctx->ring_sock->file = file;
8155 fd_install(ret, file);
8158 #if defined(CONFIG_UNIX)
8159 sock_release(ctx->ring_sock);
8160 ctx->ring_sock = NULL;
8165 static int io_uring_create(unsigned entries, struct io_uring_params *p,
8166 struct io_uring_params __user *params)
8168 struct user_struct *user = NULL;
8169 struct io_ring_ctx *ctx;
8175 if (entries > IORING_MAX_ENTRIES) {
8176 if (!(p->flags & IORING_SETUP_CLAMP))
8178 entries = IORING_MAX_ENTRIES;
8182 * Use twice as many entries for the CQ ring. It's possible for the
8183 * application to drive a higher depth than the size of the SQ ring,
8184 * since the sqes are only used at submission time. This allows for
8185 * some flexibility in overcommitting a bit. If the application has
8186 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
8187 * of CQ ring entries manually.
8189 p->sq_entries = roundup_pow_of_two(entries);
8190 if (p->flags & IORING_SETUP_CQSIZE) {
8192 * If IORING_SETUP_CQSIZE is set, we do the same roundup
8193 * to a power-of-two, if it isn't already. We do NOT impose
8194 * any cq vs sq ring sizing.
8196 if (p->cq_entries < p->sq_entries)
8198 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
8199 if (!(p->flags & IORING_SETUP_CLAMP))
8201 p->cq_entries = IORING_MAX_CQ_ENTRIES;
8203 p->cq_entries = roundup_pow_of_two(p->cq_entries);
8205 p->cq_entries = 2 * p->sq_entries;
8208 user = get_uid(current_user());
8209 limit_mem = !capable(CAP_IPC_LOCK);
8212 ret = __io_account_mem(user,
8213 ring_pages(p->sq_entries, p->cq_entries));
8220 ctx = io_ring_ctx_alloc(p);
8223 __io_unaccount_mem(user, ring_pages(p->sq_entries,
8228 ctx->compat = in_compat_syscall();
8230 ctx->creds = get_current_cred();
8232 ret = io_allocate_scq_urings(ctx, p);
8236 ret = io_sq_offload_start(ctx, p);
8240 memset(&p->sq_off, 0, sizeof(p->sq_off));
8241 p->sq_off.head = offsetof(struct io_rings, sq.head);
8242 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
8243 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
8244 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
8245 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
8246 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
8247 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
8249 memset(&p->cq_off, 0, sizeof(p->cq_off));
8250 p->cq_off.head = offsetof(struct io_rings, cq.head);
8251 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
8252 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
8253 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
8254 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
8255 p->cq_off.cqes = offsetof(struct io_rings, cqes);
8256 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
8258 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
8259 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
8260 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
8261 IORING_FEAT_POLL_32BITS;
8263 if (copy_to_user(params, p, sizeof(*p))) {
8268 * Install ring fd as the very last thing, so we don't risk someone
8269 * having closed it before we finish setup
8271 ret = io_uring_get_fd(ctx);
8275 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
8276 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
8278 ctx->limit_mem = limit_mem;
8281 io_ring_ctx_wait_and_kill(ctx);
8286 * Sets up an aio uring context, and returns the fd. Applications asks for a
8287 * ring size, we return the actual sq/cq ring sizes (among other things) in the
8288 * params structure passed in.
8290 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
8292 struct io_uring_params p;
8295 if (copy_from_user(&p, params, sizeof(p)))
8297 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
8302 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8303 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8304 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8307 return io_uring_create(entries, &p, params);
8310 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8311 struct io_uring_params __user *, params)
8313 return io_uring_setup(entries, params);
8316 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8318 struct io_uring_probe *p;
8322 size = struct_size(p, ops, nr_args);
8323 if (size == SIZE_MAX)
8325 p = kzalloc(size, GFP_KERNEL);
8330 if (copy_from_user(p, arg, size))
8333 if (memchr_inv(p, 0, size))
8336 p->last_op = IORING_OP_LAST - 1;
8337 if (nr_args > IORING_OP_LAST)
8338 nr_args = IORING_OP_LAST;
8340 for (i = 0; i < nr_args; i++) {
8342 if (!io_op_defs[i].not_supported)
8343 p->ops[i].flags = IO_URING_OP_SUPPORTED;
8348 if (copy_to_user(arg, p, size))
8355 static int io_register_personality(struct io_ring_ctx *ctx)
8357 const struct cred *creds = get_current_cred();
8360 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8361 USHRT_MAX, GFP_KERNEL);
8367 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8369 const struct cred *old_creds;
8371 old_creds = idr_remove(&ctx->personality_idr, id);
8373 put_cred(old_creds);
8380 static bool io_register_op_must_quiesce(int op)
8383 case IORING_UNREGISTER_FILES:
8384 case IORING_REGISTER_FILES_UPDATE:
8385 case IORING_REGISTER_PROBE:
8386 case IORING_REGISTER_PERSONALITY:
8387 case IORING_UNREGISTER_PERSONALITY:
8394 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8395 void __user *arg, unsigned nr_args)
8396 __releases(ctx->uring_lock)
8397 __acquires(ctx->uring_lock)
8402 * We're inside the ring mutex, if the ref is already dying, then
8403 * someone else killed the ctx or is already going through
8404 * io_uring_register().
8406 if (percpu_ref_is_dying(&ctx->refs))
8409 if (io_register_op_must_quiesce(opcode)) {
8410 percpu_ref_kill(&ctx->refs);
8413 * Drop uring mutex before waiting for references to exit. If
8414 * another thread is currently inside io_uring_enter() it might
8415 * need to grab the uring_lock to make progress. If we hold it
8416 * here across the drain wait, then we can deadlock. It's safe
8417 * to drop the mutex here, since no new references will come in
8418 * after we've killed the percpu ref.
8420 mutex_unlock(&ctx->uring_lock);
8421 ret = wait_for_completion_interruptible(&ctx->ref_comp);
8422 mutex_lock(&ctx->uring_lock);
8424 percpu_ref_resurrect(&ctx->refs);
8431 case IORING_REGISTER_BUFFERS:
8432 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8434 case IORING_UNREGISTER_BUFFERS:
8438 ret = io_sqe_buffer_unregister(ctx);
8440 case IORING_REGISTER_FILES:
8441 ret = io_sqe_files_register(ctx, arg, nr_args);
8443 case IORING_UNREGISTER_FILES:
8447 ret = io_sqe_files_unregister(ctx);
8449 case IORING_REGISTER_FILES_UPDATE:
8450 ret = io_sqe_files_update(ctx, arg, nr_args);
8452 case IORING_REGISTER_EVENTFD:
8453 case IORING_REGISTER_EVENTFD_ASYNC:
8457 ret = io_eventfd_register(ctx, arg);
8460 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8461 ctx->eventfd_async = 1;
8463 ctx->eventfd_async = 0;
8465 case IORING_UNREGISTER_EVENTFD:
8469 ret = io_eventfd_unregister(ctx);
8471 case IORING_REGISTER_PROBE:
8473 if (!arg || nr_args > 256)
8475 ret = io_probe(ctx, arg, nr_args);
8477 case IORING_REGISTER_PERSONALITY:
8481 ret = io_register_personality(ctx);
8483 case IORING_UNREGISTER_PERSONALITY:
8487 ret = io_unregister_personality(ctx, nr_args);
8494 if (io_register_op_must_quiesce(opcode)) {
8495 /* bring the ctx back to life */
8496 percpu_ref_reinit(&ctx->refs);
8498 reinit_completion(&ctx->ref_comp);
8503 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8504 void __user *, arg, unsigned int, nr_args)
8506 struct io_ring_ctx *ctx;
8515 if (f.file->f_op != &io_uring_fops)
8518 ctx = f.file->private_data;
8520 mutex_lock(&ctx->uring_lock);
8521 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8522 mutex_unlock(&ctx->uring_lock);
8523 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8524 ctx->cq_ev_fd != NULL, ret);
8530 static int __init io_uring_init(void)
8532 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8533 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8534 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8537 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8538 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8539 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8540 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8541 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8542 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8543 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8544 BUILD_BUG_SQE_ELEM(8, __u64, off);
8545 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8546 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8547 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8548 BUILD_BUG_SQE_ELEM(24, __u32, len);
8549 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8550 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8551 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8552 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8553 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
8554 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
8555 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8556 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8557 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8558 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8559 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8560 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8561 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8562 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8563 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8564 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8565 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8566 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8567 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8569 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8570 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8571 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8574 __initcall(io_uring_init);