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>
82 #include <linux/io_uring.h>
83 #include <linux/blk-cgroup.h>
84 #include <linux/audit.h>
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/io_uring.h>
89 #include <uapi/linux/io_uring.h>
94 #define IORING_MAX_ENTRIES 32768
95 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
98 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
100 #define IORING_FILE_TABLE_SHIFT 9
101 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
102 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
103 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
104 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
105 IORING_REGISTER_LAST + IORING_OP_LAST)
107 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
112 u32 head ____cacheline_aligned_in_smp;
113 u32 tail ____cacheline_aligned_in_smp;
117 * This data is shared with the application through the mmap at offsets
118 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
120 * The offsets to the member fields are published through struct
121 * io_sqring_offsets when calling io_uring_setup.
125 * Head and tail offsets into the ring; the offsets need to be
126 * masked to get valid indices.
128 * The kernel controls head of the sq ring and the tail of the cq ring,
129 * and the application controls tail of the sq ring and the head of the
132 struct io_uring sq, cq;
134 * Bitmasks to apply to head and tail offsets (constant, equals
137 u32 sq_ring_mask, cq_ring_mask;
138 /* Ring sizes (constant, power of 2) */
139 u32 sq_ring_entries, cq_ring_entries;
141 * Number of invalid entries dropped by the kernel due to
142 * invalid index stored in array
144 * Written by the kernel, shouldn't be modified by the
145 * application (i.e. get number of "new events" by comparing to
148 * After a new SQ head value was read by the application this
149 * counter includes all submissions that were dropped reaching
150 * the new SQ head (and possibly more).
156 * Written by the kernel, shouldn't be modified by the
159 * The application needs a full memory barrier before checking
160 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
166 * Written by the application, shouldn't be modified by the
171 * Number of completion events lost because the queue was full;
172 * this should be avoided by the application by making sure
173 * there are not more requests pending than there is space in
174 * the completion queue.
176 * Written by the kernel, shouldn't be modified by the
177 * application (i.e. get number of "new events" by comparing to
180 * As completion events come in out of order this counter is not
181 * ordered with any other data.
185 * Ring buffer of completion events.
187 * The kernel writes completion events fresh every time they are
188 * produced, so the application is allowed to modify pending
191 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
194 enum io_uring_cmd_flags {
195 IO_URING_F_NONBLOCK = 1,
196 IO_URING_F_COMPLETE_DEFER = 2,
199 struct io_mapped_ubuf {
202 struct bio_vec *bvec;
203 unsigned int nr_bvecs;
204 unsigned long acct_pages;
210 struct list_head list;
217 struct fixed_rsrc_table {
221 struct fixed_rsrc_ref_node {
222 struct percpu_ref refs;
223 struct list_head node;
224 struct list_head rsrc_list;
225 struct fixed_rsrc_data *rsrc_data;
226 void (*rsrc_put)(struct io_ring_ctx *ctx,
227 struct io_rsrc_put *prsrc);
228 struct llist_node llist;
232 struct fixed_rsrc_data {
233 struct fixed_rsrc_table *table;
234 struct io_ring_ctx *ctx;
236 struct fixed_rsrc_ref_node *node;
237 struct percpu_ref refs;
238 struct completion done;
243 struct list_head list;
249 struct io_restriction {
250 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
251 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
252 u8 sqe_flags_allowed;
253 u8 sqe_flags_required;
261 /* ctx's that are using this sqd */
262 struct list_head ctx_list;
263 struct list_head ctx_new_list;
264 struct mutex ctx_lock;
266 struct task_struct *thread;
267 struct wait_queue_head wait;
269 unsigned sq_thread_idle;
272 #define IO_IOPOLL_BATCH 8
273 #define IO_COMPL_BATCH 32
274 #define IO_REQ_CACHE_SIZE 32
275 #define IO_REQ_ALLOC_BATCH 8
277 struct io_comp_state {
278 struct io_kiocb *reqs[IO_COMPL_BATCH];
280 unsigned int locked_free_nr;
281 /* inline/task_work completion list, under ->uring_lock */
282 struct list_head free_list;
283 /* IRQ completion list, under ->completion_lock */
284 struct list_head locked_free_list;
287 struct io_submit_link {
288 struct io_kiocb *head;
289 struct io_kiocb *last;
292 struct io_submit_state {
293 struct blk_plug plug;
294 struct io_submit_link link;
297 * io_kiocb alloc cache
299 void *reqs[IO_REQ_CACHE_SIZE];
300 unsigned int free_reqs;
305 * Batch completion logic
307 struct io_comp_state comp;
310 * File reference cache
314 unsigned int file_refs;
315 unsigned int ios_left;
320 struct percpu_ref refs;
321 } ____cacheline_aligned_in_smp;
325 unsigned int compat: 1;
326 unsigned int limit_mem: 1;
327 unsigned int cq_overflow_flushed: 1;
328 unsigned int drain_next: 1;
329 unsigned int eventfd_async: 1;
330 unsigned int restricted: 1;
331 unsigned int sqo_dead: 1;
334 * Ring buffer of indices into array of io_uring_sqe, which is
335 * mmapped by the application using the IORING_OFF_SQES offset.
337 * This indirection could e.g. be used to assign fixed
338 * io_uring_sqe entries to operations and only submit them to
339 * the queue when needed.
341 * The kernel modifies neither the indices array nor the entries
345 unsigned cached_sq_head;
348 unsigned sq_thread_idle;
349 unsigned cached_sq_dropped;
350 unsigned cached_cq_overflow;
351 unsigned long sq_check_overflow;
353 struct list_head defer_list;
354 struct list_head timeout_list;
355 struct list_head cq_overflow_list;
357 struct io_uring_sqe *sq_sqes;
358 } ____cacheline_aligned_in_smp;
361 struct mutex uring_lock;
362 wait_queue_head_t wait;
363 } ____cacheline_aligned_in_smp;
365 struct io_submit_state submit_state;
367 struct io_rings *rings;
373 * For SQPOLL usage - we hold a reference to the parent task, so we
374 * have access to the ->files
376 struct task_struct *sqo_task;
378 /* Only used for accounting purposes */
379 struct mm_struct *mm_account;
381 #ifdef CONFIG_BLK_CGROUP
382 struct cgroup_subsys_state *sqo_blkcg_css;
385 struct io_sq_data *sq_data; /* if using sq thread polling */
387 struct wait_queue_head sqo_sq_wait;
388 struct list_head sqd_list;
391 * If used, fixed file set. Writers must ensure that ->refs is dead,
392 * readers must ensure that ->refs is alive as long as the file* is
393 * used. Only updated through io_uring_register(2).
395 struct fixed_rsrc_data *file_data;
396 unsigned nr_user_files;
398 /* if used, fixed mapped user buffers */
399 unsigned nr_user_bufs;
400 struct io_mapped_ubuf *user_bufs;
402 struct user_struct *user;
404 const struct cred *creds;
408 unsigned int sessionid;
411 struct completion ref_comp;
412 struct completion sq_thread_comp;
414 #if defined(CONFIG_UNIX)
415 struct socket *ring_sock;
418 struct idr io_buffer_idr;
420 struct idr personality_idr;
423 unsigned cached_cq_tail;
426 atomic_t cq_timeouts;
427 unsigned cq_last_tm_flush;
428 unsigned long cq_check_overflow;
429 struct wait_queue_head cq_wait;
430 struct fasync_struct *cq_fasync;
431 struct eventfd_ctx *cq_ev_fd;
432 } ____cacheline_aligned_in_smp;
435 spinlock_t completion_lock;
438 * ->iopoll_list is protected by the ctx->uring_lock for
439 * io_uring instances that don't use IORING_SETUP_SQPOLL.
440 * For SQPOLL, only the single threaded io_sq_thread() will
441 * manipulate the list, hence no extra locking is needed there.
443 struct list_head iopoll_list;
444 struct hlist_head *cancel_hash;
445 unsigned cancel_hash_bits;
446 bool poll_multi_file;
448 spinlock_t inflight_lock;
449 struct list_head inflight_list;
450 } ____cacheline_aligned_in_smp;
452 struct delayed_work rsrc_put_work;
453 struct llist_head rsrc_put_llist;
454 struct list_head rsrc_ref_list;
455 spinlock_t rsrc_ref_lock;
457 struct io_restriction restrictions;
459 /* Keep this last, we don't need it for the fast path */
460 struct work_struct exit_work;
464 * First field must be the file pointer in all the
465 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
467 struct io_poll_iocb {
469 struct wait_queue_head *head;
473 struct wait_queue_entry wait;
476 struct io_poll_remove {
486 struct io_timeout_data {
487 struct io_kiocb *req;
488 struct hrtimer timer;
489 struct timespec64 ts;
490 enum hrtimer_mode mode;
495 struct sockaddr __user *addr;
496 int __user *addr_len;
498 unsigned long nofile;
518 struct list_head list;
519 /* head of the link, used by linked timeouts only */
520 struct io_kiocb *head;
523 struct io_timeout_rem {
528 struct timespec64 ts;
533 /* NOTE: kiocb has the file as the first member, so don't do it here */
541 struct sockaddr __user *addr;
548 struct user_msghdr __user *umsg;
554 struct io_buffer *kbuf;
560 struct filename *filename;
562 unsigned long nofile;
565 struct io_rsrc_update {
591 struct epoll_event event;
595 struct file *file_out;
596 struct file *file_in;
603 struct io_provide_buf {
617 const char __user *filename;
618 struct statx __user *buffer;
630 struct filename *oldpath;
631 struct filename *newpath;
639 struct filename *filename;
642 struct io_completion {
644 struct list_head list;
648 struct io_async_connect {
649 struct sockaddr_storage address;
652 struct io_async_msghdr {
653 struct iovec fast_iov[UIO_FASTIOV];
654 /* points to an allocated iov, if NULL we use fast_iov instead */
655 struct iovec *free_iov;
656 struct sockaddr __user *uaddr;
658 struct sockaddr_storage addr;
662 struct iovec fast_iov[UIO_FASTIOV];
663 const struct iovec *free_iovec;
664 struct iov_iter iter;
666 struct wait_page_queue wpq;
670 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
671 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
672 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
673 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
674 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
675 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
681 REQ_F_LINK_TIMEOUT_BIT,
683 REQ_F_NEED_CLEANUP_BIT,
685 REQ_F_BUFFER_SELECTED_BIT,
686 REQ_F_NO_FILE_TABLE_BIT,
687 REQ_F_WORK_INITIALIZED_BIT,
688 REQ_F_LTIMEOUT_ACTIVE_BIT,
689 REQ_F_COMPLETE_INLINE_BIT,
691 /* not a real bit, just to check we're not overflowing the space */
697 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
698 /* drain existing IO first */
699 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
701 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
702 /* doesn't sever on completion < 0 */
703 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
705 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
706 /* IOSQE_BUFFER_SELECT */
707 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
709 /* fail rest of links */
710 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
711 /* on inflight list */
712 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
713 /* read/write uses file position */
714 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
715 /* must not punt to workers */
716 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
717 /* has or had linked timeout */
718 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
720 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
722 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
723 /* already went through poll handler */
724 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
725 /* buffer already selected */
726 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
727 /* doesn't need file table for this request */
728 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
729 /* io_wq_work is initialized */
730 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
731 /* linked timeout is active, i.e. prepared by link's head */
732 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
733 /* completion is deferred through io_comp_state */
734 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
738 struct io_poll_iocb poll;
739 struct io_poll_iocb *double_poll;
742 struct io_task_work {
743 struct io_wq_work_node node;
744 task_work_func_t func;
748 * NOTE! Each of the iocb union members has the file pointer
749 * as the first entry in their struct definition. So you can
750 * access the file pointer through any of the sub-structs,
751 * or directly as just 'ki_filp' in this struct.
757 struct io_poll_iocb poll;
758 struct io_poll_remove poll_remove;
759 struct io_accept accept;
761 struct io_cancel cancel;
762 struct io_timeout timeout;
763 struct io_timeout_rem timeout_rem;
764 struct io_connect connect;
765 struct io_sr_msg sr_msg;
767 struct io_close close;
768 struct io_rsrc_update rsrc_update;
769 struct io_fadvise fadvise;
770 struct io_madvise madvise;
771 struct io_epoll epoll;
772 struct io_splice splice;
773 struct io_provide_buf pbuf;
774 struct io_statx statx;
775 struct io_shutdown shutdown;
776 struct io_rename rename;
777 struct io_unlink unlink;
778 /* use only after cleaning per-op data, see io_clean_op() */
779 struct io_completion compl;
782 /* opcode allocated if it needs to store data for async defer */
785 /* polled IO has completed */
791 struct io_ring_ctx *ctx;
794 struct task_struct *task;
797 struct io_kiocb *link;
798 struct percpu_ref *fixed_rsrc_refs;
801 * 1. used with ctx->iopoll_list with reads/writes
802 * 2. to track reqs with ->files (see io_op_def::file_table)
804 struct list_head inflight_entry;
806 struct io_task_work io_task_work;
807 struct callback_head task_work;
809 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
810 struct hlist_node hash_node;
811 struct async_poll *apoll;
812 struct io_wq_work work;
815 struct io_defer_entry {
816 struct list_head list;
817 struct io_kiocb *req;
822 /* needs req->file assigned */
823 unsigned needs_file : 1;
824 /* hash wq insertion if file is a regular file */
825 unsigned hash_reg_file : 1;
826 /* unbound wq insertion if file is a non-regular file */
827 unsigned unbound_nonreg_file : 1;
828 /* opcode is not supported by this kernel */
829 unsigned not_supported : 1;
830 /* set if opcode supports polled "wait" */
832 unsigned pollout : 1;
833 /* op supports buffer selection */
834 unsigned buffer_select : 1;
835 /* must always have async data allocated */
836 unsigned needs_async_data : 1;
837 /* should block plug */
839 /* size of async data needed, if any */
840 unsigned short async_size;
844 static const struct io_op_def io_op_defs[] = {
845 [IORING_OP_NOP] = {},
846 [IORING_OP_READV] = {
848 .unbound_nonreg_file = 1,
851 .needs_async_data = 1,
853 .async_size = sizeof(struct io_async_rw),
854 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
856 [IORING_OP_WRITEV] = {
859 .unbound_nonreg_file = 1,
861 .needs_async_data = 1,
863 .async_size = sizeof(struct io_async_rw),
864 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
867 [IORING_OP_FSYNC] = {
869 .work_flags = IO_WQ_WORK_BLKCG,
871 [IORING_OP_READ_FIXED] = {
873 .unbound_nonreg_file = 1,
876 .async_size = sizeof(struct io_async_rw),
877 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
879 [IORING_OP_WRITE_FIXED] = {
882 .unbound_nonreg_file = 1,
885 .async_size = sizeof(struct io_async_rw),
886 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
889 [IORING_OP_POLL_ADD] = {
891 .unbound_nonreg_file = 1,
893 [IORING_OP_POLL_REMOVE] = {},
894 [IORING_OP_SYNC_FILE_RANGE] = {
896 .work_flags = IO_WQ_WORK_BLKCG,
898 [IORING_OP_SENDMSG] = {
900 .unbound_nonreg_file = 1,
902 .needs_async_data = 1,
903 .async_size = sizeof(struct io_async_msghdr),
904 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
906 [IORING_OP_RECVMSG] = {
908 .unbound_nonreg_file = 1,
911 .needs_async_data = 1,
912 .async_size = sizeof(struct io_async_msghdr),
913 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
915 [IORING_OP_TIMEOUT] = {
916 .needs_async_data = 1,
917 .async_size = sizeof(struct io_timeout_data),
918 .work_flags = IO_WQ_WORK_MM,
920 [IORING_OP_TIMEOUT_REMOVE] = {
921 /* used by timeout updates' prep() */
922 .work_flags = IO_WQ_WORK_MM,
924 [IORING_OP_ACCEPT] = {
926 .unbound_nonreg_file = 1,
928 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
930 [IORING_OP_ASYNC_CANCEL] = {},
931 [IORING_OP_LINK_TIMEOUT] = {
932 .needs_async_data = 1,
933 .async_size = sizeof(struct io_timeout_data),
934 .work_flags = IO_WQ_WORK_MM,
936 [IORING_OP_CONNECT] = {
938 .unbound_nonreg_file = 1,
940 .needs_async_data = 1,
941 .async_size = sizeof(struct io_async_connect),
942 .work_flags = IO_WQ_WORK_MM,
944 [IORING_OP_FALLOCATE] = {
946 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
948 [IORING_OP_OPENAT] = {
949 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
950 IO_WQ_WORK_FS | IO_WQ_WORK_MM,
952 [IORING_OP_CLOSE] = {
953 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
955 [IORING_OP_FILES_UPDATE] = {
956 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
958 [IORING_OP_STATX] = {
959 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
960 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
964 .unbound_nonreg_file = 1,
968 .async_size = sizeof(struct io_async_rw),
969 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
971 [IORING_OP_WRITE] = {
973 .unbound_nonreg_file = 1,
976 .async_size = sizeof(struct io_async_rw),
977 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
980 [IORING_OP_FADVISE] = {
982 .work_flags = IO_WQ_WORK_BLKCG,
984 [IORING_OP_MADVISE] = {
985 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
989 .unbound_nonreg_file = 1,
991 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
995 .unbound_nonreg_file = 1,
998 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
1000 [IORING_OP_OPENAT2] = {
1001 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
1002 IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
1004 [IORING_OP_EPOLL_CTL] = {
1005 .unbound_nonreg_file = 1,
1006 .work_flags = IO_WQ_WORK_FILES,
1008 [IORING_OP_SPLICE] = {
1011 .unbound_nonreg_file = 1,
1012 .work_flags = IO_WQ_WORK_BLKCG,
1014 [IORING_OP_PROVIDE_BUFFERS] = {},
1015 [IORING_OP_REMOVE_BUFFERS] = {},
1019 .unbound_nonreg_file = 1,
1021 [IORING_OP_SHUTDOWN] = {
1024 [IORING_OP_RENAMEAT] = {
1025 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
1026 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
1028 [IORING_OP_UNLINKAT] = {
1029 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
1030 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
1034 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1035 struct task_struct *task,
1036 struct files_struct *files);
1037 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
1038 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
1039 struct io_ring_ctx *ctx);
1040 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
1042 static bool io_rw_reissue(struct io_kiocb *req);
1043 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1044 static void io_put_req(struct io_kiocb *req);
1045 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1046 static void io_double_put_req(struct io_kiocb *req);
1047 static void io_dismantle_req(struct io_kiocb *req);
1048 static void io_put_task(struct task_struct *task, int nr);
1049 static void io_queue_next(struct io_kiocb *req);
1050 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1051 static void __io_queue_linked_timeout(struct io_kiocb *req);
1052 static void io_queue_linked_timeout(struct io_kiocb *req);
1053 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1054 struct io_uring_rsrc_update *ip,
1056 static void __io_clean_op(struct io_kiocb *req);
1057 static struct file *io_file_get(struct io_submit_state *state,
1058 struct io_kiocb *req, int fd, bool fixed);
1059 static void __io_queue_sqe(struct io_kiocb *req);
1060 static void io_rsrc_put_work(struct work_struct *work);
1062 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1063 struct iov_iter *iter, bool needs_lock);
1064 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1065 const struct iovec *fast_iov,
1066 struct iov_iter *iter, bool force);
1067 static void io_req_task_queue(struct io_kiocb *req);
1068 static void io_submit_flush_completions(struct io_comp_state *cs,
1069 struct io_ring_ctx *ctx);
1071 static struct kmem_cache *req_cachep;
1073 static const struct file_operations io_uring_fops;
1075 struct sock *io_uring_get_socket(struct file *file)
1077 #if defined(CONFIG_UNIX)
1078 if (file->f_op == &io_uring_fops) {
1079 struct io_ring_ctx *ctx = file->private_data;
1081 return ctx->ring_sock->sk;
1086 EXPORT_SYMBOL(io_uring_get_socket);
1088 #define io_for_each_link(pos, head) \
1089 for (pos = (head); pos; pos = pos->link)
1091 static inline void io_clean_op(struct io_kiocb *req)
1093 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1097 static inline void io_set_resource_node(struct io_kiocb *req)
1099 struct io_ring_ctx *ctx = req->ctx;
1101 if (!req->fixed_rsrc_refs) {
1102 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1103 percpu_ref_get(req->fixed_rsrc_refs);
1107 static bool io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1109 if (!percpu_ref_tryget(ref)) {
1110 /* already at zero, wait for ->release() */
1111 if (!try_wait_for_completion(compl))
1116 percpu_ref_resurrect(ref);
1117 reinit_completion(compl);
1118 percpu_ref_put(ref);
1122 static bool io_match_task(struct io_kiocb *head,
1123 struct task_struct *task,
1124 struct files_struct *files)
1126 struct io_kiocb *req;
1128 if (task && head->task != task) {
1129 /* in terms of cancelation, always match if req task is dead */
1130 if (head->task->flags & PF_EXITING)
1137 io_for_each_link(req, head) {
1138 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1140 if (req->file && req->file->f_op == &io_uring_fops)
1142 if ((req->work.flags & IO_WQ_WORK_FILES) &&
1143 req->work.identity->files == files)
1149 static void io_sq_thread_drop_mm_files(void)
1151 struct files_struct *files = current->files;
1152 struct mm_struct *mm = current->mm;
1155 kthread_unuse_mm(mm);
1160 struct nsproxy *nsproxy = current->nsproxy;
1163 current->files = NULL;
1164 current->nsproxy = NULL;
1165 task_unlock(current);
1166 put_files_struct(files);
1167 put_nsproxy(nsproxy);
1171 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1173 if (!current->files) {
1174 struct files_struct *files;
1175 struct nsproxy *nsproxy;
1177 task_lock(ctx->sqo_task);
1178 files = ctx->sqo_task->files;
1180 task_unlock(ctx->sqo_task);
1183 atomic_inc(&files->count);
1184 get_nsproxy(ctx->sqo_task->nsproxy);
1185 nsproxy = ctx->sqo_task->nsproxy;
1186 task_unlock(ctx->sqo_task);
1189 current->files = files;
1190 current->nsproxy = nsproxy;
1191 task_unlock(current);
1196 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1198 struct mm_struct *mm;
1203 task_lock(ctx->sqo_task);
1204 mm = ctx->sqo_task->mm;
1205 if (unlikely(!mm || !mmget_not_zero(mm)))
1207 task_unlock(ctx->sqo_task);
1217 static int __io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1218 struct io_kiocb *req)
1220 const struct io_op_def *def = &io_op_defs[req->opcode];
1223 if (def->work_flags & IO_WQ_WORK_MM) {
1224 ret = __io_sq_thread_acquire_mm(ctx);
1229 if (def->needs_file || (def->work_flags & IO_WQ_WORK_FILES)) {
1230 ret = __io_sq_thread_acquire_files(ctx);
1238 static inline int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1239 struct io_kiocb *req)
1241 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1243 return __io_sq_thread_acquire_mm_files(ctx, req);
1246 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1247 struct cgroup_subsys_state **cur_css)
1250 #ifdef CONFIG_BLK_CGROUP
1251 /* puts the old one when swapping */
1252 if (*cur_css != ctx->sqo_blkcg_css) {
1253 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1254 *cur_css = ctx->sqo_blkcg_css;
1259 static void io_sq_thread_unassociate_blkcg(void)
1261 #ifdef CONFIG_BLK_CGROUP
1262 kthread_associate_blkcg(NULL);
1266 static inline void req_set_fail_links(struct io_kiocb *req)
1268 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1269 req->flags |= REQ_F_FAIL_LINK;
1273 * None of these are dereferenced, they are simply used to check if any of
1274 * them have changed. If we're under current and check they are still the
1275 * same, we're fine to grab references to them for actual out-of-line use.
1277 static void io_init_identity(struct io_identity *id)
1279 id->files = current->files;
1280 id->mm = current->mm;
1281 #ifdef CONFIG_BLK_CGROUP
1283 id->blkcg_css = blkcg_css();
1286 id->creds = current_cred();
1287 id->nsproxy = current->nsproxy;
1288 id->fs = current->fs;
1289 id->fsize = rlimit(RLIMIT_FSIZE);
1291 id->loginuid = current->loginuid;
1292 id->sessionid = current->sessionid;
1294 refcount_set(&id->count, 1);
1297 static inline void __io_req_init_async(struct io_kiocb *req)
1299 memset(&req->work, 0, sizeof(req->work));
1300 req->flags |= REQ_F_WORK_INITIALIZED;
1304 * Note: must call io_req_init_async() for the first time you
1305 * touch any members of io_wq_work.
1307 static inline void io_req_init_async(struct io_kiocb *req)
1309 struct io_uring_task *tctx = current->io_uring;
1311 if (req->flags & REQ_F_WORK_INITIALIZED)
1314 __io_req_init_async(req);
1316 /* Grab a ref if this isn't our static identity */
1317 req->work.identity = tctx->identity;
1318 if (tctx->identity != &tctx->__identity)
1319 refcount_inc(&req->work.identity->count);
1322 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1324 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1326 complete(&ctx->ref_comp);
1329 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1331 return !req->timeout.off;
1334 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1336 struct io_ring_ctx *ctx;
1339 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1344 * Use 5 bits less than the max cq entries, that should give us around
1345 * 32 entries per hash list if totally full and uniformly spread.
1347 hash_bits = ilog2(p->cq_entries);
1351 ctx->cancel_hash_bits = hash_bits;
1352 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1354 if (!ctx->cancel_hash)
1356 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1358 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1359 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1362 ctx->flags = p->flags;
1363 init_waitqueue_head(&ctx->sqo_sq_wait);
1364 INIT_LIST_HEAD(&ctx->sqd_list);
1365 init_waitqueue_head(&ctx->cq_wait);
1366 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1367 init_completion(&ctx->ref_comp);
1368 init_completion(&ctx->sq_thread_comp);
1369 idr_init(&ctx->io_buffer_idr);
1370 idr_init(&ctx->personality_idr);
1371 mutex_init(&ctx->uring_lock);
1372 init_waitqueue_head(&ctx->wait);
1373 spin_lock_init(&ctx->completion_lock);
1374 INIT_LIST_HEAD(&ctx->iopoll_list);
1375 INIT_LIST_HEAD(&ctx->defer_list);
1376 INIT_LIST_HEAD(&ctx->timeout_list);
1377 spin_lock_init(&ctx->inflight_lock);
1378 INIT_LIST_HEAD(&ctx->inflight_list);
1379 spin_lock_init(&ctx->rsrc_ref_lock);
1380 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1381 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1382 init_llist_head(&ctx->rsrc_put_llist);
1383 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1384 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1387 kfree(ctx->cancel_hash);
1392 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1394 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1395 struct io_ring_ctx *ctx = req->ctx;
1397 return seq != ctx->cached_cq_tail
1398 + READ_ONCE(ctx->cached_cq_overflow);
1404 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1406 if (req->work.identity == &tctx->__identity)
1408 if (refcount_dec_and_test(&req->work.identity->count))
1409 kfree(req->work.identity);
1412 static void io_req_clean_work(struct io_kiocb *req)
1414 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1417 if (req->work.flags & IO_WQ_WORK_MM)
1418 mmdrop(req->work.identity->mm);
1419 #ifdef CONFIG_BLK_CGROUP
1420 if (req->work.flags & IO_WQ_WORK_BLKCG)
1421 css_put(req->work.identity->blkcg_css);
1423 if (req->work.flags & IO_WQ_WORK_CREDS)
1424 put_cred(req->work.identity->creds);
1425 if (req->work.flags & IO_WQ_WORK_FS) {
1426 struct fs_struct *fs = req->work.identity->fs;
1428 spin_lock(&req->work.identity->fs->lock);
1431 spin_unlock(&req->work.identity->fs->lock);
1435 if (req->work.flags & IO_WQ_WORK_FILES) {
1436 put_files_struct(req->work.identity->files);
1437 put_nsproxy(req->work.identity->nsproxy);
1439 if (req->flags & REQ_F_INFLIGHT) {
1440 struct io_ring_ctx *ctx = req->ctx;
1441 struct io_uring_task *tctx = req->task->io_uring;
1442 unsigned long flags;
1444 spin_lock_irqsave(&ctx->inflight_lock, flags);
1445 list_del(&req->inflight_entry);
1446 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1447 req->flags &= ~REQ_F_INFLIGHT;
1448 if (atomic_read(&tctx->in_idle))
1449 wake_up(&tctx->wait);
1452 req->flags &= ~REQ_F_WORK_INITIALIZED;
1453 req->work.flags &= ~(IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG | IO_WQ_WORK_FS |
1454 IO_WQ_WORK_CREDS | IO_WQ_WORK_FILES);
1455 io_put_identity(req->task->io_uring, req);
1459 * Create a private copy of io_identity, since some fields don't match
1460 * the current context.
1462 static bool io_identity_cow(struct io_kiocb *req)
1464 struct io_uring_task *tctx = current->io_uring;
1465 const struct cred *creds = NULL;
1466 struct io_identity *id;
1468 if (req->work.flags & IO_WQ_WORK_CREDS)
1469 creds = req->work.identity->creds;
1471 id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1472 if (unlikely(!id)) {
1473 req->work.flags |= IO_WQ_WORK_CANCEL;
1478 * We can safely just re-init the creds we copied Either the field
1479 * matches the current one, or we haven't grabbed it yet. The only
1480 * exception is ->creds, through registered personalities, so handle
1481 * that one separately.
1483 io_init_identity(id);
1487 /* add one for this request */
1488 refcount_inc(&id->count);
1490 /* drop tctx and req identity references, if needed */
1491 if (tctx->identity != &tctx->__identity &&
1492 refcount_dec_and_test(&tctx->identity->count))
1493 kfree(tctx->identity);
1494 if (req->work.identity != &tctx->__identity &&
1495 refcount_dec_and_test(&req->work.identity->count))
1496 kfree(req->work.identity);
1498 req->work.identity = id;
1499 tctx->identity = id;
1503 static void io_req_track_inflight(struct io_kiocb *req)
1505 struct io_ring_ctx *ctx = req->ctx;
1507 if (!(req->flags & REQ_F_INFLIGHT)) {
1508 io_req_init_async(req);
1509 req->flags |= REQ_F_INFLIGHT;
1511 spin_lock_irq(&ctx->inflight_lock);
1512 list_add(&req->inflight_entry, &ctx->inflight_list);
1513 spin_unlock_irq(&ctx->inflight_lock);
1517 static bool io_grab_identity(struct io_kiocb *req)
1519 const struct io_op_def *def = &io_op_defs[req->opcode];
1520 struct io_identity *id = req->work.identity;
1522 if (def->work_flags & IO_WQ_WORK_FSIZE) {
1523 if (id->fsize != rlimit(RLIMIT_FSIZE))
1525 req->work.flags |= IO_WQ_WORK_FSIZE;
1527 #ifdef CONFIG_BLK_CGROUP
1528 if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1529 (def->work_flags & IO_WQ_WORK_BLKCG)) {
1531 if (id->blkcg_css != blkcg_css()) {
1536 * This should be rare, either the cgroup is dying or the task
1537 * is moving cgroups. Just punt to root for the handful of ios.
1539 if (css_tryget_online(id->blkcg_css))
1540 req->work.flags |= IO_WQ_WORK_BLKCG;
1544 if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1545 if (id->creds != current_cred())
1547 get_cred(id->creds);
1548 req->work.flags |= IO_WQ_WORK_CREDS;
1551 if (!uid_eq(current->loginuid, id->loginuid) ||
1552 current->sessionid != id->sessionid)
1555 if (!(req->work.flags & IO_WQ_WORK_FS) &&
1556 (def->work_flags & IO_WQ_WORK_FS)) {
1557 if (current->fs != id->fs)
1559 spin_lock(&id->fs->lock);
1560 if (!id->fs->in_exec) {
1562 req->work.flags |= IO_WQ_WORK_FS;
1564 req->work.flags |= IO_WQ_WORK_CANCEL;
1566 spin_unlock(¤t->fs->lock);
1568 if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1569 (def->work_flags & IO_WQ_WORK_FILES) &&
1570 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1571 if (id->files != current->files ||
1572 id->nsproxy != current->nsproxy)
1574 atomic_inc(&id->files->count);
1575 get_nsproxy(id->nsproxy);
1576 req->work.flags |= IO_WQ_WORK_FILES;
1577 io_req_track_inflight(req);
1579 if (!(req->work.flags & IO_WQ_WORK_MM) &&
1580 (def->work_flags & IO_WQ_WORK_MM)) {
1581 if (id->mm != current->mm)
1584 req->work.flags |= IO_WQ_WORK_MM;
1590 static void io_prep_async_work(struct io_kiocb *req)
1592 const struct io_op_def *def = &io_op_defs[req->opcode];
1593 struct io_ring_ctx *ctx = req->ctx;
1595 io_req_init_async(req);
1597 if (req->flags & REQ_F_FORCE_ASYNC)
1598 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1600 if (req->flags & REQ_F_ISREG) {
1601 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1602 io_wq_hash_work(&req->work, file_inode(req->file));
1604 if (def->unbound_nonreg_file)
1605 req->work.flags |= IO_WQ_WORK_UNBOUND;
1608 /* if we fail grabbing identity, we must COW, regrab, and retry */
1609 if (io_grab_identity(req))
1612 if (!io_identity_cow(req))
1615 /* can't fail at this point */
1616 if (!io_grab_identity(req))
1620 static void io_prep_async_link(struct io_kiocb *req)
1622 struct io_kiocb *cur;
1624 io_for_each_link(cur, req)
1625 io_prep_async_work(cur);
1628 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1630 struct io_ring_ctx *ctx = req->ctx;
1631 struct io_kiocb *link = io_prep_linked_timeout(req);
1633 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1634 &req->work, req->flags);
1635 io_wq_enqueue(ctx->io_wq, &req->work);
1639 static void io_queue_async_work(struct io_kiocb *req)
1641 struct io_kiocb *link;
1643 /* init ->work of the whole link before punting */
1644 io_prep_async_link(req);
1645 link = __io_queue_async_work(req);
1648 io_queue_linked_timeout(link);
1651 static void io_kill_timeout(struct io_kiocb *req)
1653 struct io_timeout_data *io = req->async_data;
1656 ret = hrtimer_try_to_cancel(&io->timer);
1658 atomic_set(&req->ctx->cq_timeouts,
1659 atomic_read(&req->ctx->cq_timeouts) + 1);
1660 list_del_init(&req->timeout.list);
1661 io_cqring_fill_event(req, 0);
1662 io_put_req_deferred(req, 1);
1667 * Returns true if we found and killed one or more timeouts
1669 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1670 struct files_struct *files)
1672 struct io_kiocb *req, *tmp;
1675 spin_lock_irq(&ctx->completion_lock);
1676 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1677 if (io_match_task(req, tsk, files)) {
1678 io_kill_timeout(req);
1682 spin_unlock_irq(&ctx->completion_lock);
1683 return canceled != 0;
1686 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1689 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1690 struct io_defer_entry, list);
1692 if (req_need_defer(de->req, de->seq))
1694 list_del_init(&de->list);
1695 io_req_task_queue(de->req);
1697 } while (!list_empty(&ctx->defer_list));
1700 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1704 if (list_empty(&ctx->timeout_list))
1707 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1710 u32 events_needed, events_got;
1711 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1712 struct io_kiocb, timeout.list);
1714 if (io_is_timeout_noseq(req))
1718 * Since seq can easily wrap around over time, subtract
1719 * the last seq at which timeouts were flushed before comparing.
1720 * Assuming not more than 2^31-1 events have happened since,
1721 * these subtractions won't have wrapped, so we can check if
1722 * target is in [last_seq, current_seq] by comparing the two.
1724 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1725 events_got = seq - ctx->cq_last_tm_flush;
1726 if (events_got < events_needed)
1729 list_del_init(&req->timeout.list);
1730 io_kill_timeout(req);
1731 } while (!list_empty(&ctx->timeout_list));
1733 ctx->cq_last_tm_flush = seq;
1736 static void io_commit_cqring(struct io_ring_ctx *ctx)
1738 io_flush_timeouts(ctx);
1740 /* order cqe stores with ring update */
1741 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1743 if (unlikely(!list_empty(&ctx->defer_list)))
1744 __io_queue_deferred(ctx);
1747 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1749 struct io_rings *r = ctx->rings;
1751 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1754 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1756 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1759 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1761 struct io_rings *rings = ctx->rings;
1765 * writes to the cq entry need to come after reading head; the
1766 * control dependency is enough as we're using WRITE_ONCE to
1769 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1772 tail = ctx->cached_cq_tail++;
1773 return &rings->cqes[tail & ctx->cq_mask];
1776 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1780 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1782 if (!ctx->eventfd_async)
1784 return io_wq_current_is_worker();
1787 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1789 /* see waitqueue_active() comment */
1792 if (waitqueue_active(&ctx->wait))
1793 wake_up(&ctx->wait);
1794 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1795 wake_up(&ctx->sq_data->wait);
1796 if (io_should_trigger_evfd(ctx))
1797 eventfd_signal(ctx->cq_ev_fd, 1);
1798 if (waitqueue_active(&ctx->cq_wait)) {
1799 wake_up_interruptible(&ctx->cq_wait);
1800 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1804 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1806 /* see waitqueue_active() comment */
1809 if (ctx->flags & IORING_SETUP_SQPOLL) {
1810 if (waitqueue_active(&ctx->wait))
1811 wake_up(&ctx->wait);
1813 if (io_should_trigger_evfd(ctx))
1814 eventfd_signal(ctx->cq_ev_fd, 1);
1815 if (waitqueue_active(&ctx->cq_wait)) {
1816 wake_up_interruptible(&ctx->cq_wait);
1817 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1821 /* Returns true if there are no backlogged entries after the flush */
1822 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1823 struct task_struct *tsk,
1824 struct files_struct *files)
1826 struct io_rings *rings = ctx->rings;
1827 struct io_kiocb *req, *tmp;
1828 struct io_uring_cqe *cqe;
1829 unsigned long flags;
1830 bool all_flushed, posted;
1833 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1837 spin_lock_irqsave(&ctx->completion_lock, flags);
1838 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1839 if (!io_match_task(req, tsk, files))
1842 cqe = io_get_cqring(ctx);
1846 list_move(&req->compl.list, &list);
1848 WRITE_ONCE(cqe->user_data, req->user_data);
1849 WRITE_ONCE(cqe->res, req->result);
1850 WRITE_ONCE(cqe->flags, req->compl.cflags);
1852 ctx->cached_cq_overflow++;
1853 WRITE_ONCE(ctx->rings->cq_overflow,
1854 ctx->cached_cq_overflow);
1859 all_flushed = list_empty(&ctx->cq_overflow_list);
1861 clear_bit(0, &ctx->sq_check_overflow);
1862 clear_bit(0, &ctx->cq_check_overflow);
1863 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1867 io_commit_cqring(ctx);
1868 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1870 io_cqring_ev_posted(ctx);
1872 while (!list_empty(&list)) {
1873 req = list_first_entry(&list, struct io_kiocb, compl.list);
1874 list_del(&req->compl.list);
1881 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1882 struct task_struct *tsk,
1883 struct files_struct *files)
1885 if (test_bit(0, &ctx->cq_check_overflow)) {
1886 /* iopoll syncs against uring_lock, not completion_lock */
1887 if (ctx->flags & IORING_SETUP_IOPOLL)
1888 mutex_lock(&ctx->uring_lock);
1889 __io_cqring_overflow_flush(ctx, force, tsk, files);
1890 if (ctx->flags & IORING_SETUP_IOPOLL)
1891 mutex_unlock(&ctx->uring_lock);
1895 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1897 struct io_ring_ctx *ctx = req->ctx;
1898 struct io_uring_cqe *cqe;
1900 trace_io_uring_complete(ctx, req->user_data, res);
1903 * If we can't get a cq entry, userspace overflowed the
1904 * submission (by quite a lot). Increment the overflow count in
1907 cqe = io_get_cqring(ctx);
1909 WRITE_ONCE(cqe->user_data, req->user_data);
1910 WRITE_ONCE(cqe->res, res);
1911 WRITE_ONCE(cqe->flags, cflags);
1912 } else if (ctx->cq_overflow_flushed ||
1913 atomic_read(&req->task->io_uring->in_idle)) {
1915 * If we're in ring overflow flush mode, or in task cancel mode,
1916 * then we cannot store the request for later flushing, we need
1917 * to drop it on the floor.
1919 ctx->cached_cq_overflow++;
1920 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1922 if (list_empty(&ctx->cq_overflow_list)) {
1923 set_bit(0, &ctx->sq_check_overflow);
1924 set_bit(0, &ctx->cq_check_overflow);
1925 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1929 req->compl.cflags = cflags;
1930 refcount_inc(&req->refs);
1931 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1935 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1937 __io_cqring_fill_event(req, res, 0);
1940 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1941 unsigned int cflags)
1943 struct io_ring_ctx *ctx = req->ctx;
1944 unsigned long flags;
1946 spin_lock_irqsave(&ctx->completion_lock, flags);
1947 __io_cqring_fill_event(req, res, cflags);
1948 io_commit_cqring(ctx);
1950 * If we're the last reference to this request, add to our locked
1953 if (refcount_dec_and_test(&req->refs)) {
1954 struct io_comp_state *cs = &ctx->submit_state.comp;
1956 io_dismantle_req(req);
1957 io_put_task(req->task, 1);
1958 list_add(&req->compl.list, &cs->locked_free_list);
1959 cs->locked_free_nr++;
1962 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1964 io_cqring_ev_posted(ctx);
1967 percpu_ref_put(&ctx->refs);
1971 static void io_req_complete_state(struct io_kiocb *req, long res,
1972 unsigned int cflags)
1976 req->compl.cflags = cflags;
1977 req->flags |= REQ_F_COMPLETE_INLINE;
1980 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1981 long res, unsigned cflags)
1983 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1984 io_req_complete_state(req, res, cflags);
1986 io_req_complete_post(req, res, cflags);
1989 static inline void io_req_complete(struct io_kiocb *req, long res)
1991 __io_req_complete(req, 0, res, 0);
1994 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1996 struct io_submit_state *state = &ctx->submit_state;
1997 struct io_comp_state *cs = &state->comp;
1998 struct io_kiocb *req = NULL;
2001 * If we have more than a batch's worth of requests in our IRQ side
2002 * locked cache, grab the lock and move them over to our submission
2005 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
2006 spin_lock_irq(&ctx->completion_lock);
2007 list_splice_init(&cs->locked_free_list, &cs->free_list);
2008 cs->locked_free_nr = 0;
2009 spin_unlock_irq(&ctx->completion_lock);
2012 while (!list_empty(&cs->free_list)) {
2013 req = list_first_entry(&cs->free_list, struct io_kiocb,
2015 list_del(&req->compl.list);
2016 state->reqs[state->free_reqs++] = req;
2017 if (state->free_reqs == ARRAY_SIZE(state->reqs))
2024 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2026 struct io_submit_state *state = &ctx->submit_state;
2028 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
2030 if (!state->free_reqs) {
2031 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2034 if (io_flush_cached_reqs(ctx))
2037 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
2041 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2042 * retry single alloc to be on the safe side.
2044 if (unlikely(ret <= 0)) {
2045 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2046 if (!state->reqs[0])
2050 state->free_reqs = ret;
2054 return state->reqs[state->free_reqs];
2057 static inline void io_put_file(struct io_kiocb *req, struct file *file,
2064 static void io_dismantle_req(struct io_kiocb *req)
2068 if (req->async_data)
2069 kfree(req->async_data);
2071 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
2072 if (req->fixed_rsrc_refs)
2073 percpu_ref_put(req->fixed_rsrc_refs);
2074 io_req_clean_work(req);
2077 static inline void io_put_task(struct task_struct *task, int nr)
2079 struct io_uring_task *tctx = task->io_uring;
2081 percpu_counter_sub(&tctx->inflight, nr);
2082 if (unlikely(atomic_read(&tctx->in_idle)))
2083 wake_up(&tctx->wait);
2084 put_task_struct_many(task, nr);
2087 static void __io_free_req(struct io_kiocb *req)
2089 struct io_ring_ctx *ctx = req->ctx;
2091 io_dismantle_req(req);
2092 io_put_task(req->task, 1);
2094 kmem_cache_free(req_cachep, req);
2095 percpu_ref_put(&ctx->refs);
2098 static inline void io_remove_next_linked(struct io_kiocb *req)
2100 struct io_kiocb *nxt = req->link;
2102 req->link = nxt->link;
2106 static void io_kill_linked_timeout(struct io_kiocb *req)
2108 struct io_ring_ctx *ctx = req->ctx;
2109 struct io_kiocb *link;
2110 bool cancelled = false;
2111 unsigned long flags;
2113 spin_lock_irqsave(&ctx->completion_lock, flags);
2117 * Can happen if a linked timeout fired and link had been like
2118 * req -> link t-out -> link t-out [-> ...]
2120 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
2121 struct io_timeout_data *io = link->async_data;
2124 io_remove_next_linked(req);
2125 link->timeout.head = NULL;
2126 ret = hrtimer_try_to_cancel(&io->timer);
2128 io_cqring_fill_event(link, -ECANCELED);
2129 io_commit_cqring(ctx);
2133 req->flags &= ~REQ_F_LINK_TIMEOUT;
2134 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2137 io_cqring_ev_posted(ctx);
2143 static void io_fail_links(struct io_kiocb *req)
2145 struct io_kiocb *link, *nxt;
2146 struct io_ring_ctx *ctx = req->ctx;
2147 unsigned long flags;
2149 spin_lock_irqsave(&ctx->completion_lock, flags);
2157 trace_io_uring_fail_link(req, link);
2158 io_cqring_fill_event(link, -ECANCELED);
2161 * It's ok to free under spinlock as they're not linked anymore,
2162 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
2165 if (link->flags & REQ_F_WORK_INITIALIZED)
2166 io_put_req_deferred(link, 2);
2168 io_double_put_req(link);
2171 io_commit_cqring(ctx);
2172 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2174 io_cqring_ev_posted(ctx);
2177 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2179 if (req->flags & REQ_F_LINK_TIMEOUT)
2180 io_kill_linked_timeout(req);
2183 * If LINK is set, we have dependent requests in this chain. If we
2184 * didn't fail this request, queue the first one up, moving any other
2185 * dependencies to the next request. In case of failure, fail the rest
2188 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
2189 struct io_kiocb *nxt = req->link;
2198 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2200 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2202 return __io_req_find_next(req);
2205 static bool __tctx_task_work(struct io_uring_task *tctx)
2207 struct io_ring_ctx *ctx = NULL;
2208 struct io_wq_work_list list;
2209 struct io_wq_work_node *node;
2211 if (wq_list_empty(&tctx->task_list))
2214 spin_lock_irq(&tctx->task_lock);
2215 list = tctx->task_list;
2216 INIT_WQ_LIST(&tctx->task_list);
2217 spin_unlock_irq(&tctx->task_lock);
2221 struct io_wq_work_node *next = node->next;
2222 struct io_ring_ctx *this_ctx;
2223 struct io_kiocb *req;
2225 req = container_of(node, struct io_kiocb, io_task_work.node);
2226 this_ctx = req->ctx;
2227 req->task_work.func(&req->task_work);
2232 } else if (ctx != this_ctx) {
2233 mutex_lock(&ctx->uring_lock);
2234 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2235 mutex_unlock(&ctx->uring_lock);
2240 if (ctx && ctx->submit_state.comp.nr) {
2241 mutex_lock(&ctx->uring_lock);
2242 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2243 mutex_unlock(&ctx->uring_lock);
2246 return list.first != NULL;
2249 static void tctx_task_work(struct callback_head *cb)
2251 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
2253 while (__tctx_task_work(tctx))
2256 clear_bit(0, &tctx->task_state);
2259 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
2260 enum task_work_notify_mode notify)
2262 struct io_uring_task *tctx = tsk->io_uring;
2263 struct io_wq_work_node *node, *prev;
2264 unsigned long flags;
2267 WARN_ON_ONCE(!tctx);
2269 spin_lock_irqsave(&tctx->task_lock, flags);
2270 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2271 spin_unlock_irqrestore(&tctx->task_lock, flags);
2273 /* task_work already pending, we're done */
2274 if (test_bit(0, &tctx->task_state) ||
2275 test_and_set_bit(0, &tctx->task_state))
2278 if (!task_work_add(tsk, &tctx->task_work, notify))
2282 * Slow path - we failed, find and delete work. if the work is not
2283 * in the list, it got run and we're fine.
2286 spin_lock_irqsave(&tctx->task_lock, flags);
2287 wq_list_for_each(node, prev, &tctx->task_list) {
2288 if (&req->io_task_work.node == node) {
2289 wq_list_del(&tctx->task_list, node, prev);
2294 spin_unlock_irqrestore(&tctx->task_lock, flags);
2295 clear_bit(0, &tctx->task_state);
2299 static int io_req_task_work_add(struct io_kiocb *req)
2301 struct task_struct *tsk = req->task;
2302 struct io_ring_ctx *ctx = req->ctx;
2303 enum task_work_notify_mode notify;
2306 if (tsk->flags & PF_EXITING)
2310 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2311 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2312 * processing task_work. There's no reliable way to tell if TWA_RESUME
2316 if (!(ctx->flags & IORING_SETUP_SQPOLL))
2317 notify = TWA_SIGNAL;
2319 ret = io_task_work_add(tsk, req, notify);
2321 wake_up_process(tsk);
2326 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2327 task_work_func_t cb)
2329 struct task_struct *tsk = io_wq_get_task(req->ctx->io_wq);
2331 init_task_work(&req->task_work, cb);
2332 task_work_add(tsk, &req->task_work, TWA_NONE);
2333 wake_up_process(tsk);
2336 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2338 struct io_ring_ctx *ctx = req->ctx;
2340 spin_lock_irq(&ctx->completion_lock);
2341 io_cqring_fill_event(req, error);
2342 io_commit_cqring(ctx);
2343 spin_unlock_irq(&ctx->completion_lock);
2345 io_cqring_ev_posted(ctx);
2346 req_set_fail_links(req);
2347 io_double_put_req(req);
2350 static void io_req_task_cancel(struct callback_head *cb)
2352 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2353 struct io_ring_ctx *ctx = req->ctx;
2355 mutex_lock(&ctx->uring_lock);
2356 __io_req_task_cancel(req, req->result);
2357 mutex_unlock(&ctx->uring_lock);
2358 percpu_ref_put(&ctx->refs);
2361 static void __io_req_task_submit(struct io_kiocb *req)
2363 struct io_ring_ctx *ctx = req->ctx;
2365 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2366 mutex_lock(&ctx->uring_lock);
2367 if (!ctx->sqo_dead && !(current->flags & PF_EXITING) &&
2368 !io_sq_thread_acquire_mm_files(ctx, req))
2369 __io_queue_sqe(req);
2371 __io_req_task_cancel(req, -EFAULT);
2372 mutex_unlock(&ctx->uring_lock);
2375 static void io_req_task_submit(struct callback_head *cb)
2377 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2379 __io_req_task_submit(req);
2382 static void io_req_task_queue(struct io_kiocb *req)
2386 req->task_work.func = io_req_task_submit;
2387 ret = io_req_task_work_add(req);
2388 if (unlikely(ret)) {
2389 req->result = -ECANCELED;
2390 percpu_ref_get(&req->ctx->refs);
2391 io_req_task_work_add_fallback(req, io_req_task_cancel);
2395 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2397 percpu_ref_get(&req->ctx->refs);
2399 req->task_work.func = io_req_task_cancel;
2401 if (unlikely(io_req_task_work_add(req)))
2402 io_req_task_work_add_fallback(req, io_req_task_cancel);
2405 static inline void io_queue_next(struct io_kiocb *req)
2407 struct io_kiocb *nxt = io_req_find_next(req);
2410 io_req_task_queue(nxt);
2413 static void io_free_req(struct io_kiocb *req)
2420 struct task_struct *task;
2425 static inline void io_init_req_batch(struct req_batch *rb)
2432 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2433 struct req_batch *rb)
2436 io_put_task(rb->task, rb->task_refs);
2438 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2441 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2442 struct io_submit_state *state)
2446 if (req->task != rb->task) {
2448 io_put_task(rb->task, rb->task_refs);
2449 rb->task = req->task;
2455 io_dismantle_req(req);
2456 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2457 state->reqs[state->free_reqs++] = req;
2459 list_add(&req->compl.list, &state->comp.free_list);
2462 static void io_submit_flush_completions(struct io_comp_state *cs,
2463 struct io_ring_ctx *ctx)
2466 struct io_kiocb *req;
2467 struct req_batch rb;
2469 io_init_req_batch(&rb);
2470 spin_lock_irq(&ctx->completion_lock);
2471 for (i = 0; i < nr; i++) {
2473 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2475 io_commit_cqring(ctx);
2476 spin_unlock_irq(&ctx->completion_lock);
2478 io_cqring_ev_posted(ctx);
2479 for (i = 0; i < nr; i++) {
2482 /* submission and completion refs */
2483 if (refcount_sub_and_test(2, &req->refs))
2484 io_req_free_batch(&rb, req, &ctx->submit_state);
2487 io_req_free_batch_finish(ctx, &rb);
2492 * Drop reference to request, return next in chain (if there is one) if this
2493 * was the last reference to this request.
2495 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2497 struct io_kiocb *nxt = NULL;
2499 if (refcount_dec_and_test(&req->refs)) {
2500 nxt = io_req_find_next(req);
2506 static void io_put_req(struct io_kiocb *req)
2508 if (refcount_dec_and_test(&req->refs))
2512 static void io_put_req_deferred_cb(struct callback_head *cb)
2514 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2519 static void io_free_req_deferred(struct io_kiocb *req)
2523 req->task_work.func = io_put_req_deferred_cb;
2524 ret = io_req_task_work_add(req);
2526 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2529 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2531 if (refcount_sub_and_test(refs, &req->refs))
2532 io_free_req_deferred(req);
2535 static void io_double_put_req(struct io_kiocb *req)
2537 /* drop both submit and complete references */
2538 if (refcount_sub_and_test(2, &req->refs))
2542 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2544 /* See comment at the top of this file */
2546 return __io_cqring_events(ctx);
2549 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2551 struct io_rings *rings = ctx->rings;
2553 /* make sure SQ entry isn't read before tail */
2554 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2557 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2559 unsigned int cflags;
2561 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2562 cflags |= IORING_CQE_F_BUFFER;
2563 req->flags &= ~REQ_F_BUFFER_SELECTED;
2568 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2570 struct io_buffer *kbuf;
2572 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2573 return io_put_kbuf(req, kbuf);
2576 static inline bool io_run_task_work(void)
2579 * Not safe to run on exiting task, and the task_work handling will
2580 * not add work to such a task.
2582 if (unlikely(current->flags & PF_EXITING))
2584 if (current->task_works) {
2585 __set_current_state(TASK_RUNNING);
2594 * Find and free completed poll iocbs
2596 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2597 struct list_head *done)
2599 struct req_batch rb;
2600 struct io_kiocb *req;
2602 /* order with ->result store in io_complete_rw_iopoll() */
2605 io_init_req_batch(&rb);
2606 while (!list_empty(done)) {
2609 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2610 list_del(&req->inflight_entry);
2612 if (READ_ONCE(req->result) == -EAGAIN) {
2613 req->iopoll_completed = 0;
2614 if (io_rw_reissue(req))
2618 if (req->flags & REQ_F_BUFFER_SELECTED)
2619 cflags = io_put_rw_kbuf(req);
2621 __io_cqring_fill_event(req, req->result, cflags);
2624 if (refcount_dec_and_test(&req->refs))
2625 io_req_free_batch(&rb, req, &ctx->submit_state);
2628 io_commit_cqring(ctx);
2629 io_cqring_ev_posted_iopoll(ctx);
2630 io_req_free_batch_finish(ctx, &rb);
2633 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2636 struct io_kiocb *req, *tmp;
2642 * Only spin for completions if we don't have multiple devices hanging
2643 * off our complete list, and we're under the requested amount.
2645 spin = !ctx->poll_multi_file && *nr_events < min;
2648 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2649 struct kiocb *kiocb = &req->rw.kiocb;
2652 * Move completed and retryable entries to our local lists.
2653 * If we find a request that requires polling, break out
2654 * and complete those lists first, if we have entries there.
2656 if (READ_ONCE(req->iopoll_completed)) {
2657 list_move_tail(&req->inflight_entry, &done);
2660 if (!list_empty(&done))
2663 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2667 /* iopoll may have completed current req */
2668 if (READ_ONCE(req->iopoll_completed))
2669 list_move_tail(&req->inflight_entry, &done);
2676 if (!list_empty(&done))
2677 io_iopoll_complete(ctx, nr_events, &done);
2683 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2684 * non-spinning poll check - we'll still enter the driver poll loop, but only
2685 * as a non-spinning completion check.
2687 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2690 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2693 ret = io_do_iopoll(ctx, nr_events, min);
2696 if (*nr_events >= min)
2704 * We can't just wait for polled events to come to us, we have to actively
2705 * find and complete them.
2707 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2709 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2712 mutex_lock(&ctx->uring_lock);
2713 while (!list_empty(&ctx->iopoll_list)) {
2714 unsigned int nr_events = 0;
2716 io_do_iopoll(ctx, &nr_events, 0);
2718 /* let it sleep and repeat later if can't complete a request */
2722 * Ensure we allow local-to-the-cpu processing to take place,
2723 * in this case we need to ensure that we reap all events.
2724 * Also let task_work, etc. to progress by releasing the mutex
2726 if (need_resched()) {
2727 mutex_unlock(&ctx->uring_lock);
2729 mutex_lock(&ctx->uring_lock);
2732 mutex_unlock(&ctx->uring_lock);
2735 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2737 unsigned int nr_events = 0;
2738 int iters = 0, ret = 0;
2741 * We disallow the app entering submit/complete with polling, but we
2742 * still need to lock the ring to prevent racing with polled issue
2743 * that got punted to a workqueue.
2745 mutex_lock(&ctx->uring_lock);
2748 * Don't enter poll loop if we already have events pending.
2749 * If we do, we can potentially be spinning for commands that
2750 * already triggered a CQE (eg in error).
2752 if (test_bit(0, &ctx->cq_check_overflow))
2753 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2754 if (io_cqring_events(ctx))
2758 * If a submit got punted to a workqueue, we can have the
2759 * application entering polling for a command before it gets
2760 * issued. That app will hold the uring_lock for the duration
2761 * of the poll right here, so we need to take a breather every
2762 * now and then to ensure that the issue has a chance to add
2763 * the poll to the issued list. Otherwise we can spin here
2764 * forever, while the workqueue is stuck trying to acquire the
2767 if (!(++iters & 7)) {
2768 mutex_unlock(&ctx->uring_lock);
2770 mutex_lock(&ctx->uring_lock);
2773 ret = io_iopoll_getevents(ctx, &nr_events, min);
2777 } while (min && !nr_events && !need_resched());
2779 mutex_unlock(&ctx->uring_lock);
2783 static void kiocb_end_write(struct io_kiocb *req)
2786 * Tell lockdep we inherited freeze protection from submission
2789 if (req->flags & REQ_F_ISREG) {
2790 struct inode *inode = file_inode(req->file);
2792 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2794 file_end_write(req->file);
2798 static bool io_resubmit_prep(struct io_kiocb *req)
2800 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2802 struct iov_iter iter;
2804 /* already prepared */
2805 if (req->async_data)
2808 switch (req->opcode) {
2809 case IORING_OP_READV:
2810 case IORING_OP_READ_FIXED:
2811 case IORING_OP_READ:
2814 case IORING_OP_WRITEV:
2815 case IORING_OP_WRITE_FIXED:
2816 case IORING_OP_WRITE:
2820 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2825 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2828 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2832 static bool io_rw_reissue(struct io_kiocb *req)
2835 umode_t mode = file_inode(req->file)->i_mode;
2838 if (!S_ISBLK(mode) && !S_ISREG(mode))
2840 if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2843 * If ref is dying, we might be running poll reap from the exit work.
2844 * Don't attempt to reissue from that path, just let it fail with
2847 if (percpu_ref_is_dying(&req->ctx->refs))
2850 lockdep_assert_held(&req->ctx->uring_lock);
2852 ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2854 if (!ret && io_resubmit_prep(req)) {
2855 refcount_inc(&req->refs);
2856 io_queue_async_work(req);
2859 req_set_fail_links(req);
2864 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2865 unsigned int issue_flags)
2869 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2871 if (res != req->result)
2872 req_set_fail_links(req);
2874 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2875 kiocb_end_write(req);
2876 if (req->flags & REQ_F_BUFFER_SELECTED)
2877 cflags = io_put_rw_kbuf(req);
2878 __io_req_complete(req, issue_flags, res, cflags);
2881 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2883 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2885 __io_complete_rw(req, res, res2, 0);
2888 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2890 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2892 if (kiocb->ki_flags & IOCB_WRITE)
2893 kiocb_end_write(req);
2895 if (res != -EAGAIN && res != req->result)
2896 req_set_fail_links(req);
2898 WRITE_ONCE(req->result, res);
2899 /* order with io_poll_complete() checking ->result */
2901 WRITE_ONCE(req->iopoll_completed, 1);
2905 * After the iocb has been issued, it's safe to be found on the poll list.
2906 * Adding the kiocb to the list AFTER submission ensures that we don't
2907 * find it from a io_iopoll_getevents() thread before the issuer is done
2908 * accessing the kiocb cookie.
2910 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2912 struct io_ring_ctx *ctx = req->ctx;
2915 * Track whether we have multiple files in our lists. This will impact
2916 * how we do polling eventually, not spinning if we're on potentially
2917 * different devices.
2919 if (list_empty(&ctx->iopoll_list)) {
2920 ctx->poll_multi_file = false;
2921 } else if (!ctx->poll_multi_file) {
2922 struct io_kiocb *list_req;
2924 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2926 if (list_req->file != req->file)
2927 ctx->poll_multi_file = true;
2931 * For fast devices, IO may have already completed. If it has, add
2932 * it to the front so we find it first.
2934 if (READ_ONCE(req->iopoll_completed))
2935 list_add(&req->inflight_entry, &ctx->iopoll_list);
2937 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2940 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2941 * task context or in io worker task context. If current task context is
2942 * sq thread, we don't need to check whether should wake up sq thread.
2944 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2945 wq_has_sleeper(&ctx->sq_data->wait))
2946 wake_up(&ctx->sq_data->wait);
2949 static inline void io_state_file_put(struct io_submit_state *state)
2951 if (state->file_refs) {
2952 fput_many(state->file, state->file_refs);
2953 state->file_refs = 0;
2958 * Get as many references to a file as we have IOs left in this submission,
2959 * assuming most submissions are for one file, or at least that each file
2960 * has more than one submission.
2962 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2967 if (state->file_refs) {
2968 if (state->fd == fd) {
2972 io_state_file_put(state);
2974 state->file = fget_many(fd, state->ios_left);
2975 if (unlikely(!state->file))
2979 state->file_refs = state->ios_left - 1;
2983 static bool io_bdev_nowait(struct block_device *bdev)
2985 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2989 * If we tracked the file through the SCM inflight mechanism, we could support
2990 * any file. For now, just ensure that anything potentially problematic is done
2993 static bool io_file_supports_async(struct file *file, int rw)
2995 umode_t mode = file_inode(file)->i_mode;
2997 if (S_ISBLK(mode)) {
2998 if (IS_ENABLED(CONFIG_BLOCK) &&
2999 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3003 if (S_ISCHR(mode) || S_ISSOCK(mode))
3005 if (S_ISREG(mode)) {
3006 if (IS_ENABLED(CONFIG_BLOCK) &&
3007 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3008 file->f_op != &io_uring_fops)
3013 /* any ->read/write should understand O_NONBLOCK */
3014 if (file->f_flags & O_NONBLOCK)
3017 if (!(file->f_mode & FMODE_NOWAIT))
3021 return file->f_op->read_iter != NULL;
3023 return file->f_op->write_iter != NULL;
3026 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3028 struct io_ring_ctx *ctx = req->ctx;
3029 struct kiocb *kiocb = &req->rw.kiocb;
3030 struct file *file = req->file;
3034 if (S_ISREG(file_inode(file)->i_mode))
3035 req->flags |= REQ_F_ISREG;
3037 kiocb->ki_pos = READ_ONCE(sqe->off);
3038 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
3039 req->flags |= REQ_F_CUR_POS;
3040 kiocb->ki_pos = file->f_pos;
3042 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
3043 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
3044 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3048 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
3049 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
3050 req->flags |= REQ_F_NOWAIT;
3052 ioprio = READ_ONCE(sqe->ioprio);
3054 ret = ioprio_check_cap(ioprio);
3058 kiocb->ki_ioprio = ioprio;
3060 kiocb->ki_ioprio = get_current_ioprio();
3062 if (ctx->flags & IORING_SETUP_IOPOLL) {
3063 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
3064 !kiocb->ki_filp->f_op->iopoll)
3067 kiocb->ki_flags |= IOCB_HIPRI;
3068 kiocb->ki_complete = io_complete_rw_iopoll;
3069 req->iopoll_completed = 0;
3071 if (kiocb->ki_flags & IOCB_HIPRI)
3073 kiocb->ki_complete = io_complete_rw;
3076 req->rw.addr = READ_ONCE(sqe->addr);
3077 req->rw.len = READ_ONCE(sqe->len);
3078 req->buf_index = READ_ONCE(sqe->buf_index);
3082 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3088 case -ERESTARTNOINTR:
3089 case -ERESTARTNOHAND:
3090 case -ERESTART_RESTARTBLOCK:
3092 * We can't just restart the syscall, since previously
3093 * submitted sqes may already be in progress. Just fail this
3099 kiocb->ki_complete(kiocb, ret, 0);
3103 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3104 unsigned int issue_flags)
3106 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3107 struct io_async_rw *io = req->async_data;
3109 /* add previously done IO, if any */
3110 if (io && io->bytes_done > 0) {
3112 ret = io->bytes_done;
3114 ret += io->bytes_done;
3117 if (req->flags & REQ_F_CUR_POS)
3118 req->file->f_pos = kiocb->ki_pos;
3119 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
3120 __io_complete_rw(req, ret, 0, issue_flags);
3122 io_rw_done(kiocb, ret);
3125 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3127 struct io_ring_ctx *ctx = req->ctx;
3128 size_t len = req->rw.len;
3129 struct io_mapped_ubuf *imu;
3130 u16 index, buf_index = req->buf_index;
3134 if (unlikely(buf_index >= ctx->nr_user_bufs))
3136 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3137 imu = &ctx->user_bufs[index];
3138 buf_addr = req->rw.addr;
3141 if (buf_addr + len < buf_addr)
3143 /* not inside the mapped region */
3144 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
3148 * May not be a start of buffer, set size appropriately
3149 * and advance us to the beginning.
3151 offset = buf_addr - imu->ubuf;
3152 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3156 * Don't use iov_iter_advance() here, as it's really slow for
3157 * using the latter parts of a big fixed buffer - it iterates
3158 * over each segment manually. We can cheat a bit here, because
3161 * 1) it's a BVEC iter, we set it up
3162 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3163 * first and last bvec
3165 * So just find our index, and adjust the iterator afterwards.
3166 * If the offset is within the first bvec (or the whole first
3167 * bvec, just use iov_iter_advance(). This makes it easier
3168 * since we can just skip the first segment, which may not
3169 * be PAGE_SIZE aligned.
3171 const struct bio_vec *bvec = imu->bvec;
3173 if (offset <= bvec->bv_len) {
3174 iov_iter_advance(iter, offset);
3176 unsigned long seg_skip;
3178 /* skip first vec */
3179 offset -= bvec->bv_len;
3180 seg_skip = 1 + (offset >> PAGE_SHIFT);
3182 iter->bvec = bvec + seg_skip;
3183 iter->nr_segs -= seg_skip;
3184 iter->count -= bvec->bv_len + offset;
3185 iter->iov_offset = offset & ~PAGE_MASK;
3192 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3195 mutex_unlock(&ctx->uring_lock);
3198 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3201 * "Normal" inline submissions always hold the uring_lock, since we
3202 * grab it from the system call. Same is true for the SQPOLL offload.
3203 * The only exception is when we've detached the request and issue it
3204 * from an async worker thread, grab the lock for that case.
3207 mutex_lock(&ctx->uring_lock);
3210 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3211 int bgid, struct io_buffer *kbuf,
3214 struct io_buffer *head;
3216 if (req->flags & REQ_F_BUFFER_SELECTED)
3219 io_ring_submit_lock(req->ctx, needs_lock);
3221 lockdep_assert_held(&req->ctx->uring_lock);
3223 head = idr_find(&req->ctx->io_buffer_idr, bgid);
3225 if (!list_empty(&head->list)) {
3226 kbuf = list_last_entry(&head->list, struct io_buffer,
3228 list_del(&kbuf->list);
3231 idr_remove(&req->ctx->io_buffer_idr, bgid);
3233 if (*len > kbuf->len)
3236 kbuf = ERR_PTR(-ENOBUFS);
3239 io_ring_submit_unlock(req->ctx, needs_lock);
3244 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3247 struct io_buffer *kbuf;
3250 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3251 bgid = req->buf_index;
3252 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3255 req->rw.addr = (u64) (unsigned long) kbuf;
3256 req->flags |= REQ_F_BUFFER_SELECTED;
3257 return u64_to_user_ptr(kbuf->addr);
3260 #ifdef CONFIG_COMPAT
3261 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3264 struct compat_iovec __user *uiov;
3265 compat_ssize_t clen;
3269 uiov = u64_to_user_ptr(req->rw.addr);
3270 if (!access_ok(uiov, sizeof(*uiov)))
3272 if (__get_user(clen, &uiov->iov_len))
3278 buf = io_rw_buffer_select(req, &len, needs_lock);
3280 return PTR_ERR(buf);
3281 iov[0].iov_base = buf;
3282 iov[0].iov_len = (compat_size_t) len;
3287 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3290 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3294 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3297 len = iov[0].iov_len;
3300 buf = io_rw_buffer_select(req, &len, needs_lock);
3302 return PTR_ERR(buf);
3303 iov[0].iov_base = buf;
3304 iov[0].iov_len = len;
3308 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3311 if (req->flags & REQ_F_BUFFER_SELECTED) {
3312 struct io_buffer *kbuf;
3314 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3315 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3316 iov[0].iov_len = kbuf->len;
3319 if (req->rw.len != 1)
3322 #ifdef CONFIG_COMPAT
3323 if (req->ctx->compat)
3324 return io_compat_import(req, iov, needs_lock);
3327 return __io_iov_buffer_select(req, iov, needs_lock);
3330 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3331 struct iov_iter *iter, bool needs_lock)
3333 void __user *buf = u64_to_user_ptr(req->rw.addr);
3334 size_t sqe_len = req->rw.len;
3335 u8 opcode = req->opcode;
3338 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3340 return io_import_fixed(req, rw, iter);
3343 /* buffer index only valid with fixed read/write, or buffer select */
3344 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3347 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3348 if (req->flags & REQ_F_BUFFER_SELECT) {
3349 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3351 return PTR_ERR(buf);
3352 req->rw.len = sqe_len;
3355 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3360 if (req->flags & REQ_F_BUFFER_SELECT) {
3361 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3363 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3368 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3372 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3374 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3378 * For files that don't have ->read_iter() and ->write_iter(), handle them
3379 * by looping over ->read() or ->write() manually.
3381 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3383 struct kiocb *kiocb = &req->rw.kiocb;
3384 struct file *file = req->file;
3388 * Don't support polled IO through this interface, and we can't
3389 * support non-blocking either. For the latter, this just causes
3390 * the kiocb to be handled from an async context.
3392 if (kiocb->ki_flags & IOCB_HIPRI)
3394 if (kiocb->ki_flags & IOCB_NOWAIT)
3397 while (iov_iter_count(iter)) {
3401 if (!iov_iter_is_bvec(iter)) {
3402 iovec = iov_iter_iovec(iter);
3404 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3405 iovec.iov_len = req->rw.len;
3409 nr = file->f_op->read(file, iovec.iov_base,
3410 iovec.iov_len, io_kiocb_ppos(kiocb));
3412 nr = file->f_op->write(file, iovec.iov_base,
3413 iovec.iov_len, io_kiocb_ppos(kiocb));
3422 if (nr != iovec.iov_len)
3426 iov_iter_advance(iter, nr);
3432 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3433 const struct iovec *fast_iov, struct iov_iter *iter)
3435 struct io_async_rw *rw = req->async_data;
3437 memcpy(&rw->iter, iter, sizeof(*iter));
3438 rw->free_iovec = iovec;
3440 /* can only be fixed buffers, no need to do anything */
3441 if (iov_iter_is_bvec(iter))
3444 unsigned iov_off = 0;
3446 rw->iter.iov = rw->fast_iov;
3447 if (iter->iov != fast_iov) {
3448 iov_off = iter->iov - fast_iov;
3449 rw->iter.iov += iov_off;
3451 if (rw->fast_iov != fast_iov)
3452 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3453 sizeof(struct iovec) * iter->nr_segs);
3455 req->flags |= REQ_F_NEED_CLEANUP;
3459 static inline int __io_alloc_async_data(struct io_kiocb *req)
3461 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3462 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3463 return req->async_data == NULL;
3466 static int io_alloc_async_data(struct io_kiocb *req)
3468 if (!io_op_defs[req->opcode].needs_async_data)
3471 return __io_alloc_async_data(req);
3474 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3475 const struct iovec *fast_iov,
3476 struct iov_iter *iter, bool force)
3478 if (!force && !io_op_defs[req->opcode].needs_async_data)
3480 if (!req->async_data) {
3481 if (__io_alloc_async_data(req)) {
3486 io_req_map_rw(req, iovec, fast_iov, iter);
3491 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3493 struct io_async_rw *iorw = req->async_data;
3494 struct iovec *iov = iorw->fast_iov;
3497 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3498 if (unlikely(ret < 0))
3501 iorw->bytes_done = 0;
3502 iorw->free_iovec = iov;
3504 req->flags |= REQ_F_NEED_CLEANUP;
3508 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3510 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3512 return io_prep_rw(req, sqe);
3516 * This is our waitqueue callback handler, registered through lock_page_async()
3517 * when we initially tried to do the IO with the iocb armed our waitqueue.
3518 * This gets called when the page is unlocked, and we generally expect that to
3519 * happen when the page IO is completed and the page is now uptodate. This will
3520 * queue a task_work based retry of the operation, attempting to copy the data
3521 * again. If the latter fails because the page was NOT uptodate, then we will
3522 * do a thread based blocking retry of the operation. That's the unexpected
3525 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3526 int sync, void *arg)
3528 struct wait_page_queue *wpq;
3529 struct io_kiocb *req = wait->private;
3530 struct wait_page_key *key = arg;
3532 wpq = container_of(wait, struct wait_page_queue, wait);
3534 if (!wake_page_match(wpq, key))
3537 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3538 list_del_init(&wait->entry);
3540 /* submit ref gets dropped, acquire a new one */
3541 refcount_inc(&req->refs);
3542 io_req_task_queue(req);
3547 * This controls whether a given IO request should be armed for async page
3548 * based retry. If we return false here, the request is handed to the async
3549 * worker threads for retry. If we're doing buffered reads on a regular file,
3550 * we prepare a private wait_page_queue entry and retry the operation. This
3551 * will either succeed because the page is now uptodate and unlocked, or it
3552 * will register a callback when the page is unlocked at IO completion. Through
3553 * that callback, io_uring uses task_work to setup a retry of the operation.
3554 * That retry will attempt the buffered read again. The retry will generally
3555 * succeed, or in rare cases where it fails, we then fall back to using the
3556 * async worker threads for a blocking retry.
3558 static bool io_rw_should_retry(struct io_kiocb *req)
3560 struct io_async_rw *rw = req->async_data;
3561 struct wait_page_queue *wait = &rw->wpq;
3562 struct kiocb *kiocb = &req->rw.kiocb;
3564 /* never retry for NOWAIT, we just complete with -EAGAIN */
3565 if (req->flags & REQ_F_NOWAIT)
3568 /* Only for buffered IO */
3569 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3573 * just use poll if we can, and don't attempt if the fs doesn't
3574 * support callback based unlocks
3576 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3579 wait->wait.func = io_async_buf_func;
3580 wait->wait.private = req;
3581 wait->wait.flags = 0;
3582 INIT_LIST_HEAD(&wait->wait.entry);
3583 kiocb->ki_flags |= IOCB_WAITQ;
3584 kiocb->ki_flags &= ~IOCB_NOWAIT;
3585 kiocb->ki_waitq = wait;
3589 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3591 if (req->file->f_op->read_iter)
3592 return call_read_iter(req->file, &req->rw.kiocb, iter);
3593 else if (req->file->f_op->read)
3594 return loop_rw_iter(READ, req, iter);
3599 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3601 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3602 struct kiocb *kiocb = &req->rw.kiocb;
3603 struct iov_iter __iter, *iter = &__iter;
3604 struct io_async_rw *rw = req->async_data;
3605 ssize_t io_size, ret, ret2;
3606 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3612 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3616 io_size = iov_iter_count(iter);
3617 req->result = io_size;
3619 /* Ensure we clear previously set non-block flag */
3620 if (!force_nonblock)
3621 kiocb->ki_flags &= ~IOCB_NOWAIT;
3623 kiocb->ki_flags |= IOCB_NOWAIT;
3625 /* If the file doesn't support async, just async punt */
3626 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3627 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3628 return ret ?: -EAGAIN;
3631 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3632 if (unlikely(ret)) {
3637 ret = io_iter_do_read(req, iter);
3639 if (ret == -EIOCBQUEUED) {
3641 } else if (ret == -EAGAIN) {
3642 /* IOPOLL retry should happen for io-wq threads */
3643 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3645 /* no retry on NONBLOCK nor RWF_NOWAIT */
3646 if (req->flags & REQ_F_NOWAIT)
3648 /* some cases will consume bytes even on error returns */
3649 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3651 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3652 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3653 /* read all, failed, already did sync or don't want to retry */
3657 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3662 rw = req->async_data;
3663 /* now use our persistent iterator, if we aren't already */
3668 rw->bytes_done += ret;
3669 /* if we can retry, do so with the callbacks armed */
3670 if (!io_rw_should_retry(req)) {
3671 kiocb->ki_flags &= ~IOCB_WAITQ;
3676 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3677 * we get -EIOCBQUEUED, then we'll get a notification when the
3678 * desired page gets unlocked. We can also get a partial read
3679 * here, and if we do, then just retry at the new offset.
3681 ret = io_iter_do_read(req, iter);
3682 if (ret == -EIOCBQUEUED)
3684 /* we got some bytes, but not all. retry. */
3685 } while (ret > 0 && ret < io_size);
3687 kiocb_done(kiocb, ret, issue_flags);
3689 /* it's faster to check here then delegate to kfree */
3695 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3697 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3699 return io_prep_rw(req, sqe);
3702 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3704 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3705 struct kiocb *kiocb = &req->rw.kiocb;
3706 struct iov_iter __iter, *iter = &__iter;
3707 struct io_async_rw *rw = req->async_data;
3708 ssize_t ret, ret2, io_size;
3709 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3715 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3719 io_size = iov_iter_count(iter);
3720 req->result = io_size;
3722 /* Ensure we clear previously set non-block flag */
3723 if (!force_nonblock)
3724 kiocb->ki_flags &= ~IOCB_NOWAIT;
3726 kiocb->ki_flags |= IOCB_NOWAIT;
3728 /* If the file doesn't support async, just async punt */
3729 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3732 /* file path doesn't support NOWAIT for non-direct_IO */
3733 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3734 (req->flags & REQ_F_ISREG))
3737 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3742 * Open-code file_start_write here to grab freeze protection,
3743 * which will be released by another thread in
3744 * io_complete_rw(). Fool lockdep by telling it the lock got
3745 * released so that it doesn't complain about the held lock when
3746 * we return to userspace.
3748 if (req->flags & REQ_F_ISREG) {
3749 sb_start_write(file_inode(req->file)->i_sb);
3750 __sb_writers_release(file_inode(req->file)->i_sb,
3753 kiocb->ki_flags |= IOCB_WRITE;
3755 if (req->file->f_op->write_iter)
3756 ret2 = call_write_iter(req->file, kiocb, iter);
3757 else if (req->file->f_op->write)
3758 ret2 = loop_rw_iter(WRITE, req, iter);
3763 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3764 * retry them without IOCB_NOWAIT.
3766 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3768 /* no retry on NONBLOCK nor RWF_NOWAIT */
3769 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3771 if (!force_nonblock || ret2 != -EAGAIN) {
3772 /* IOPOLL retry should happen for io-wq threads */
3773 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3776 kiocb_done(kiocb, ret2, issue_flags);
3779 /* some cases will consume bytes even on error returns */
3780 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3781 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3782 return ret ?: -EAGAIN;
3785 /* it's reportedly faster than delegating the null check to kfree() */
3791 static int io_renameat_prep(struct io_kiocb *req,
3792 const struct io_uring_sqe *sqe)
3794 struct io_rename *ren = &req->rename;
3795 const char __user *oldf, *newf;
3797 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3800 ren->old_dfd = READ_ONCE(sqe->fd);
3801 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3802 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3803 ren->new_dfd = READ_ONCE(sqe->len);
3804 ren->flags = READ_ONCE(sqe->rename_flags);
3806 ren->oldpath = getname(oldf);
3807 if (IS_ERR(ren->oldpath))
3808 return PTR_ERR(ren->oldpath);
3810 ren->newpath = getname(newf);
3811 if (IS_ERR(ren->newpath)) {
3812 putname(ren->oldpath);
3813 return PTR_ERR(ren->newpath);
3816 req->flags |= REQ_F_NEED_CLEANUP;
3820 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3822 struct io_rename *ren = &req->rename;
3825 if (issue_flags & IO_URING_F_NONBLOCK)
3828 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3829 ren->newpath, ren->flags);
3831 req->flags &= ~REQ_F_NEED_CLEANUP;
3833 req_set_fail_links(req);
3834 io_req_complete(req, ret);
3838 static int io_unlinkat_prep(struct io_kiocb *req,
3839 const struct io_uring_sqe *sqe)
3841 struct io_unlink *un = &req->unlink;
3842 const char __user *fname;
3844 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3847 un->dfd = READ_ONCE(sqe->fd);
3849 un->flags = READ_ONCE(sqe->unlink_flags);
3850 if (un->flags & ~AT_REMOVEDIR)
3853 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3854 un->filename = getname(fname);
3855 if (IS_ERR(un->filename))
3856 return PTR_ERR(un->filename);
3858 req->flags |= REQ_F_NEED_CLEANUP;
3862 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3864 struct io_unlink *un = &req->unlink;
3867 if (issue_flags & IO_URING_F_NONBLOCK)
3870 if (un->flags & AT_REMOVEDIR)
3871 ret = do_rmdir(un->dfd, un->filename);
3873 ret = do_unlinkat(un->dfd, un->filename);
3875 req->flags &= ~REQ_F_NEED_CLEANUP;
3877 req_set_fail_links(req);
3878 io_req_complete(req, ret);
3882 static int io_shutdown_prep(struct io_kiocb *req,
3883 const struct io_uring_sqe *sqe)
3885 #if defined(CONFIG_NET)
3886 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3888 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3892 req->shutdown.how = READ_ONCE(sqe->len);
3899 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3901 #if defined(CONFIG_NET)
3902 struct socket *sock;
3905 if (issue_flags & IO_URING_F_NONBLOCK)
3908 sock = sock_from_file(req->file);
3909 if (unlikely(!sock))
3912 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3914 req_set_fail_links(req);
3915 io_req_complete(req, ret);
3922 static int __io_splice_prep(struct io_kiocb *req,
3923 const struct io_uring_sqe *sqe)
3925 struct io_splice* sp = &req->splice;
3926 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3928 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3932 sp->len = READ_ONCE(sqe->len);
3933 sp->flags = READ_ONCE(sqe->splice_flags);
3935 if (unlikely(sp->flags & ~valid_flags))
3938 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3939 (sp->flags & SPLICE_F_FD_IN_FIXED));
3942 req->flags |= REQ_F_NEED_CLEANUP;
3944 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3946 * Splice operation will be punted aync, and here need to
3947 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3949 io_req_init_async(req);
3950 req->work.flags |= IO_WQ_WORK_UNBOUND;
3956 static int io_tee_prep(struct io_kiocb *req,
3957 const struct io_uring_sqe *sqe)
3959 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3961 return __io_splice_prep(req, sqe);
3964 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3966 struct io_splice *sp = &req->splice;
3967 struct file *in = sp->file_in;
3968 struct file *out = sp->file_out;
3969 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3972 if (issue_flags & IO_URING_F_NONBLOCK)
3975 ret = do_tee(in, out, sp->len, flags);
3977 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3978 req->flags &= ~REQ_F_NEED_CLEANUP;
3981 req_set_fail_links(req);
3982 io_req_complete(req, ret);
3986 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3988 struct io_splice* sp = &req->splice;
3990 sp->off_in = READ_ONCE(sqe->splice_off_in);
3991 sp->off_out = READ_ONCE(sqe->off);
3992 return __io_splice_prep(req, sqe);
3995 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3997 struct io_splice *sp = &req->splice;
3998 struct file *in = sp->file_in;
3999 struct file *out = sp->file_out;
4000 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4001 loff_t *poff_in, *poff_out;
4004 if (issue_flags & IO_URING_F_NONBLOCK)
4007 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4008 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4011 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4013 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
4014 req->flags &= ~REQ_F_NEED_CLEANUP;
4017 req_set_fail_links(req);
4018 io_req_complete(req, ret);
4023 * IORING_OP_NOP just posts a completion event, nothing else.
4025 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4027 struct io_ring_ctx *ctx = req->ctx;
4029 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4032 __io_req_complete(req, issue_flags, 0, 0);
4036 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4038 struct io_ring_ctx *ctx = req->ctx;
4043 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4045 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4048 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4049 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4052 req->sync.off = READ_ONCE(sqe->off);
4053 req->sync.len = READ_ONCE(sqe->len);
4057 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4059 loff_t end = req->sync.off + req->sync.len;
4062 /* fsync always requires a blocking context */
4063 if (issue_flags & IO_URING_F_NONBLOCK)
4066 ret = vfs_fsync_range(req->file, req->sync.off,
4067 end > 0 ? end : LLONG_MAX,
4068 req->sync.flags & IORING_FSYNC_DATASYNC);
4070 req_set_fail_links(req);
4071 io_req_complete(req, ret);
4075 static int io_fallocate_prep(struct io_kiocb *req,
4076 const struct io_uring_sqe *sqe)
4078 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
4080 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4083 req->sync.off = READ_ONCE(sqe->off);
4084 req->sync.len = READ_ONCE(sqe->addr);
4085 req->sync.mode = READ_ONCE(sqe->len);
4089 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4093 /* fallocate always requiring blocking context */
4094 if (issue_flags & IO_URING_F_NONBLOCK)
4096 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4099 req_set_fail_links(req);
4100 io_req_complete(req, ret);
4104 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4106 const char __user *fname;
4109 if (unlikely(sqe->ioprio || sqe->buf_index))
4111 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4114 /* open.how should be already initialised */
4115 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4116 req->open.how.flags |= O_LARGEFILE;
4118 req->open.dfd = READ_ONCE(sqe->fd);
4119 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4120 req->open.filename = getname(fname);
4121 if (IS_ERR(req->open.filename)) {
4122 ret = PTR_ERR(req->open.filename);
4123 req->open.filename = NULL;
4126 req->open.nofile = rlimit(RLIMIT_NOFILE);
4127 req->flags |= REQ_F_NEED_CLEANUP;
4131 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4135 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4137 mode = READ_ONCE(sqe->len);
4138 flags = READ_ONCE(sqe->open_flags);
4139 req->open.how = build_open_how(flags, mode);
4140 return __io_openat_prep(req, sqe);
4143 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4145 struct open_how __user *how;
4149 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4151 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4152 len = READ_ONCE(sqe->len);
4153 if (len < OPEN_HOW_SIZE_VER0)
4156 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4161 return __io_openat_prep(req, sqe);
4164 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4166 struct open_flags op;
4169 bool resolve_nonblock;
4172 ret = build_open_flags(&req->open.how, &op);
4175 nonblock_set = op.open_flag & O_NONBLOCK;
4176 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4177 if (issue_flags & IO_URING_F_NONBLOCK) {
4179 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4180 * it'll always -EAGAIN
4182 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4184 op.lookup_flags |= LOOKUP_CACHED;
4185 op.open_flag |= O_NONBLOCK;
4188 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4192 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4193 /* only retry if RESOLVE_CACHED wasn't already set by application */
4194 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
4195 file == ERR_PTR(-EAGAIN)) {
4197 * We could hang on to this 'fd', but seems like marginal
4198 * gain for something that is now known to be a slower path.
4199 * So just put it, and we'll get a new one when we retry.
4207 ret = PTR_ERR(file);
4209 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4210 file->f_flags &= ~O_NONBLOCK;
4211 fsnotify_open(file);
4212 fd_install(ret, file);
4215 putname(req->open.filename);
4216 req->flags &= ~REQ_F_NEED_CLEANUP;
4218 req_set_fail_links(req);
4219 io_req_complete(req, ret);
4223 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4225 return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
4228 static int io_remove_buffers_prep(struct io_kiocb *req,
4229 const struct io_uring_sqe *sqe)
4231 struct io_provide_buf *p = &req->pbuf;
4234 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4237 tmp = READ_ONCE(sqe->fd);
4238 if (!tmp || tmp > USHRT_MAX)
4241 memset(p, 0, sizeof(*p));
4243 p->bgid = READ_ONCE(sqe->buf_group);
4247 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4248 int bgid, unsigned nbufs)
4252 /* shouldn't happen */
4256 /* the head kbuf is the list itself */
4257 while (!list_empty(&buf->list)) {
4258 struct io_buffer *nxt;
4260 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4261 list_del(&nxt->list);
4268 idr_remove(&ctx->io_buffer_idr, bgid);
4273 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4275 struct io_provide_buf *p = &req->pbuf;
4276 struct io_ring_ctx *ctx = req->ctx;
4277 struct io_buffer *head;
4279 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4281 io_ring_submit_lock(ctx, !force_nonblock);
4283 lockdep_assert_held(&ctx->uring_lock);
4286 head = idr_find(&ctx->io_buffer_idr, p->bgid);
4288 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4290 req_set_fail_links(req);
4292 /* need to hold the lock to complete IOPOLL requests */
4293 if (ctx->flags & IORING_SETUP_IOPOLL) {
4294 __io_req_complete(req, issue_flags, ret, 0);
4295 io_ring_submit_unlock(ctx, !force_nonblock);
4297 io_ring_submit_unlock(ctx, !force_nonblock);
4298 __io_req_complete(req, issue_flags, ret, 0);
4303 static int io_provide_buffers_prep(struct io_kiocb *req,
4304 const struct io_uring_sqe *sqe)
4306 struct io_provide_buf *p = &req->pbuf;
4309 if (sqe->ioprio || sqe->rw_flags)
4312 tmp = READ_ONCE(sqe->fd);
4313 if (!tmp || tmp > USHRT_MAX)
4316 p->addr = READ_ONCE(sqe->addr);
4317 p->len = READ_ONCE(sqe->len);
4319 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4322 p->bgid = READ_ONCE(sqe->buf_group);
4323 tmp = READ_ONCE(sqe->off);
4324 if (tmp > USHRT_MAX)
4330 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4332 struct io_buffer *buf;
4333 u64 addr = pbuf->addr;
4334 int i, bid = pbuf->bid;
4336 for (i = 0; i < pbuf->nbufs; i++) {
4337 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4342 buf->len = pbuf->len;
4347 INIT_LIST_HEAD(&buf->list);
4350 list_add_tail(&buf->list, &(*head)->list);
4354 return i ? i : -ENOMEM;
4357 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4359 struct io_provide_buf *p = &req->pbuf;
4360 struct io_ring_ctx *ctx = req->ctx;
4361 struct io_buffer *head, *list;
4363 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4365 io_ring_submit_lock(ctx, !force_nonblock);
4367 lockdep_assert_held(&ctx->uring_lock);
4369 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4371 ret = io_add_buffers(p, &head);
4376 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4379 __io_remove_buffers(ctx, head, p->bgid, -1U);
4385 req_set_fail_links(req);
4387 /* need to hold the lock to complete IOPOLL requests */
4388 if (ctx->flags & IORING_SETUP_IOPOLL) {
4389 __io_req_complete(req, issue_flags, ret, 0);
4390 io_ring_submit_unlock(ctx, !force_nonblock);
4392 io_ring_submit_unlock(ctx, !force_nonblock);
4393 __io_req_complete(req, issue_flags, ret, 0);
4398 static int io_epoll_ctl_prep(struct io_kiocb *req,
4399 const struct io_uring_sqe *sqe)
4401 #if defined(CONFIG_EPOLL)
4402 if (sqe->ioprio || sqe->buf_index)
4404 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4407 req->epoll.epfd = READ_ONCE(sqe->fd);
4408 req->epoll.op = READ_ONCE(sqe->len);
4409 req->epoll.fd = READ_ONCE(sqe->off);
4411 if (ep_op_has_event(req->epoll.op)) {
4412 struct epoll_event __user *ev;
4414 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4415 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4425 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4427 #if defined(CONFIG_EPOLL)
4428 struct io_epoll *ie = &req->epoll;
4430 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4432 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4433 if (force_nonblock && ret == -EAGAIN)
4437 req_set_fail_links(req);
4438 __io_req_complete(req, issue_flags, ret, 0);
4445 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4447 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4448 if (sqe->ioprio || sqe->buf_index || sqe->off)
4450 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4453 req->madvise.addr = READ_ONCE(sqe->addr);
4454 req->madvise.len = READ_ONCE(sqe->len);
4455 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4462 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4464 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4465 struct io_madvise *ma = &req->madvise;
4468 if (issue_flags & IO_URING_F_NONBLOCK)
4471 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4473 req_set_fail_links(req);
4474 io_req_complete(req, ret);
4481 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4483 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4485 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4488 req->fadvise.offset = READ_ONCE(sqe->off);
4489 req->fadvise.len = READ_ONCE(sqe->len);
4490 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4494 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4496 struct io_fadvise *fa = &req->fadvise;
4499 if (issue_flags & IO_URING_F_NONBLOCK) {
4500 switch (fa->advice) {
4501 case POSIX_FADV_NORMAL:
4502 case POSIX_FADV_RANDOM:
4503 case POSIX_FADV_SEQUENTIAL:
4510 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4512 req_set_fail_links(req);
4513 io_req_complete(req, ret);
4517 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4519 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4521 if (sqe->ioprio || sqe->buf_index)
4523 if (req->flags & REQ_F_FIXED_FILE)
4526 req->statx.dfd = READ_ONCE(sqe->fd);
4527 req->statx.mask = READ_ONCE(sqe->len);
4528 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4529 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4530 req->statx.flags = READ_ONCE(sqe->statx_flags);
4535 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4537 struct io_statx *ctx = &req->statx;
4540 if (issue_flags & IO_URING_F_NONBLOCK) {
4541 /* only need file table for an actual valid fd */
4542 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4543 req->flags |= REQ_F_NO_FILE_TABLE;
4547 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4551 req_set_fail_links(req);
4552 io_req_complete(req, ret);
4556 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4558 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4560 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4561 sqe->rw_flags || sqe->buf_index)
4563 if (req->flags & REQ_F_FIXED_FILE)
4566 req->close.fd = READ_ONCE(sqe->fd);
4570 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4572 struct files_struct *files = current->files;
4573 struct io_close *close = &req->close;
4574 struct fdtable *fdt;
4580 spin_lock(&files->file_lock);
4581 fdt = files_fdtable(files);
4582 if (close->fd >= fdt->max_fds) {
4583 spin_unlock(&files->file_lock);
4586 file = fdt->fd[close->fd];
4588 spin_unlock(&files->file_lock);
4592 if (file->f_op == &io_uring_fops) {
4593 spin_unlock(&files->file_lock);
4598 /* if the file has a flush method, be safe and punt to async */
4599 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4600 spin_unlock(&files->file_lock);
4604 ret = __close_fd_get_file(close->fd, &file);
4605 spin_unlock(&files->file_lock);
4612 /* No ->flush() or already async, safely close from here */
4613 ret = filp_close(file, current->files);
4616 req_set_fail_links(req);
4619 __io_req_complete(req, issue_flags, ret, 0);
4623 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4625 struct io_ring_ctx *ctx = req->ctx;
4627 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4629 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4632 req->sync.off = READ_ONCE(sqe->off);
4633 req->sync.len = READ_ONCE(sqe->len);
4634 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4638 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4642 /* sync_file_range always requires a blocking context */
4643 if (issue_flags & IO_URING_F_NONBLOCK)
4646 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4649 req_set_fail_links(req);
4650 io_req_complete(req, ret);
4654 #if defined(CONFIG_NET)
4655 static int io_setup_async_msg(struct io_kiocb *req,
4656 struct io_async_msghdr *kmsg)
4658 struct io_async_msghdr *async_msg = req->async_data;
4662 if (io_alloc_async_data(req)) {
4663 kfree(kmsg->free_iov);
4666 async_msg = req->async_data;
4667 req->flags |= REQ_F_NEED_CLEANUP;
4668 memcpy(async_msg, kmsg, sizeof(*kmsg));
4669 async_msg->msg.msg_name = &async_msg->addr;
4670 /* if were using fast_iov, set it to the new one */
4671 if (!async_msg->free_iov)
4672 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4677 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4678 struct io_async_msghdr *iomsg)
4680 iomsg->msg.msg_name = &iomsg->addr;
4681 iomsg->free_iov = iomsg->fast_iov;
4682 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4683 req->sr_msg.msg_flags, &iomsg->free_iov);
4686 static int io_sendmsg_prep_async(struct io_kiocb *req)
4690 if (!io_op_defs[req->opcode].needs_async_data)
4692 ret = io_sendmsg_copy_hdr(req, req->async_data);
4694 req->flags |= REQ_F_NEED_CLEANUP;
4698 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4700 struct io_sr_msg *sr = &req->sr_msg;
4702 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4705 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4706 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4707 sr->len = READ_ONCE(sqe->len);
4709 #ifdef CONFIG_COMPAT
4710 if (req->ctx->compat)
4711 sr->msg_flags |= MSG_CMSG_COMPAT;
4716 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4718 struct io_async_msghdr iomsg, *kmsg;
4719 struct socket *sock;
4723 sock = sock_from_file(req->file);
4724 if (unlikely(!sock))
4727 kmsg = req->async_data;
4729 ret = io_sendmsg_copy_hdr(req, &iomsg);
4735 flags = req->sr_msg.msg_flags;
4736 if (flags & MSG_DONTWAIT)
4737 req->flags |= REQ_F_NOWAIT;
4738 else if (issue_flags & IO_URING_F_NONBLOCK)
4739 flags |= MSG_DONTWAIT;
4741 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4742 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4743 return io_setup_async_msg(req, kmsg);
4744 if (ret == -ERESTARTSYS)
4747 /* fast path, check for non-NULL to avoid function call */
4749 kfree(kmsg->free_iov);
4750 req->flags &= ~REQ_F_NEED_CLEANUP;
4752 req_set_fail_links(req);
4753 __io_req_complete(req, issue_flags, ret, 0);
4757 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4759 struct io_sr_msg *sr = &req->sr_msg;
4762 struct socket *sock;
4766 sock = sock_from_file(req->file);
4767 if (unlikely(!sock))
4770 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4774 msg.msg_name = NULL;
4775 msg.msg_control = NULL;
4776 msg.msg_controllen = 0;
4777 msg.msg_namelen = 0;
4779 flags = req->sr_msg.msg_flags;
4780 if (flags & MSG_DONTWAIT)
4781 req->flags |= REQ_F_NOWAIT;
4782 else if (issue_flags & IO_URING_F_NONBLOCK)
4783 flags |= MSG_DONTWAIT;
4785 msg.msg_flags = flags;
4786 ret = sock_sendmsg(sock, &msg);
4787 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4789 if (ret == -ERESTARTSYS)
4793 req_set_fail_links(req);
4794 __io_req_complete(req, issue_flags, ret, 0);
4798 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4799 struct io_async_msghdr *iomsg)
4801 struct io_sr_msg *sr = &req->sr_msg;
4802 struct iovec __user *uiov;
4806 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4807 &iomsg->uaddr, &uiov, &iov_len);
4811 if (req->flags & REQ_F_BUFFER_SELECT) {
4814 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4816 sr->len = iomsg->fast_iov[0].iov_len;
4817 iomsg->free_iov = NULL;
4819 iomsg->free_iov = iomsg->fast_iov;
4820 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4821 &iomsg->free_iov, &iomsg->msg.msg_iter,
4830 #ifdef CONFIG_COMPAT
4831 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4832 struct io_async_msghdr *iomsg)
4834 struct compat_msghdr __user *msg_compat;
4835 struct io_sr_msg *sr = &req->sr_msg;
4836 struct compat_iovec __user *uiov;
4841 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4842 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4847 uiov = compat_ptr(ptr);
4848 if (req->flags & REQ_F_BUFFER_SELECT) {
4849 compat_ssize_t clen;
4853 if (!access_ok(uiov, sizeof(*uiov)))
4855 if (__get_user(clen, &uiov->iov_len))
4860 iomsg->free_iov = NULL;
4862 iomsg->free_iov = iomsg->fast_iov;
4863 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4864 UIO_FASTIOV, &iomsg->free_iov,
4865 &iomsg->msg.msg_iter, true);
4874 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4875 struct io_async_msghdr *iomsg)
4877 iomsg->msg.msg_name = &iomsg->addr;
4879 #ifdef CONFIG_COMPAT
4880 if (req->ctx->compat)
4881 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4884 return __io_recvmsg_copy_hdr(req, iomsg);
4887 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4890 struct io_sr_msg *sr = &req->sr_msg;
4891 struct io_buffer *kbuf;
4893 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4898 req->flags |= REQ_F_BUFFER_SELECTED;
4902 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4904 return io_put_kbuf(req, req->sr_msg.kbuf);
4907 static int io_recvmsg_prep_async(struct io_kiocb *req)
4911 if (!io_op_defs[req->opcode].needs_async_data)
4913 ret = io_recvmsg_copy_hdr(req, req->async_data);
4915 req->flags |= REQ_F_NEED_CLEANUP;
4919 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4921 struct io_sr_msg *sr = &req->sr_msg;
4923 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4926 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4927 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4928 sr->len = READ_ONCE(sqe->len);
4929 sr->bgid = READ_ONCE(sqe->buf_group);
4931 #ifdef CONFIG_COMPAT
4932 if (req->ctx->compat)
4933 sr->msg_flags |= MSG_CMSG_COMPAT;
4938 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4940 struct io_async_msghdr iomsg, *kmsg;
4941 struct socket *sock;
4942 struct io_buffer *kbuf;
4944 int ret, cflags = 0;
4945 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4947 sock = sock_from_file(req->file);
4948 if (unlikely(!sock))
4951 kmsg = req->async_data;
4953 ret = io_recvmsg_copy_hdr(req, &iomsg);
4959 if (req->flags & REQ_F_BUFFER_SELECT) {
4960 kbuf = io_recv_buffer_select(req, !force_nonblock);
4962 return PTR_ERR(kbuf);
4963 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4964 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4965 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4966 1, req->sr_msg.len);
4969 flags = req->sr_msg.msg_flags;
4970 if (flags & MSG_DONTWAIT)
4971 req->flags |= REQ_F_NOWAIT;
4972 else if (force_nonblock)
4973 flags |= MSG_DONTWAIT;
4975 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4976 kmsg->uaddr, flags);
4977 if (force_nonblock && ret == -EAGAIN)
4978 return io_setup_async_msg(req, kmsg);
4979 if (ret == -ERESTARTSYS)
4982 if (req->flags & REQ_F_BUFFER_SELECTED)
4983 cflags = io_put_recv_kbuf(req);
4984 /* fast path, check for non-NULL to avoid function call */
4986 kfree(kmsg->free_iov);
4987 req->flags &= ~REQ_F_NEED_CLEANUP;
4989 req_set_fail_links(req);
4990 __io_req_complete(req, issue_flags, ret, cflags);
4994 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4996 struct io_buffer *kbuf;
4997 struct io_sr_msg *sr = &req->sr_msg;
4999 void __user *buf = sr->buf;
5000 struct socket *sock;
5003 int ret, cflags = 0;
5004 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5006 sock = sock_from_file(req->file);
5007 if (unlikely(!sock))
5010 if (req->flags & REQ_F_BUFFER_SELECT) {
5011 kbuf = io_recv_buffer_select(req, !force_nonblock);
5013 return PTR_ERR(kbuf);
5014 buf = u64_to_user_ptr(kbuf->addr);
5017 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5021 msg.msg_name = NULL;
5022 msg.msg_control = NULL;
5023 msg.msg_controllen = 0;
5024 msg.msg_namelen = 0;
5025 msg.msg_iocb = NULL;
5028 flags = req->sr_msg.msg_flags;
5029 if (flags & MSG_DONTWAIT)
5030 req->flags |= REQ_F_NOWAIT;
5031 else if (force_nonblock)
5032 flags |= MSG_DONTWAIT;
5034 ret = sock_recvmsg(sock, &msg, flags);
5035 if (force_nonblock && ret == -EAGAIN)
5037 if (ret == -ERESTARTSYS)
5040 if (req->flags & REQ_F_BUFFER_SELECTED)
5041 cflags = io_put_recv_kbuf(req);
5043 req_set_fail_links(req);
5044 __io_req_complete(req, issue_flags, ret, cflags);
5048 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5050 struct io_accept *accept = &req->accept;
5052 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5054 if (sqe->ioprio || sqe->len || sqe->buf_index)
5057 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5058 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5059 accept->flags = READ_ONCE(sqe->accept_flags);
5060 accept->nofile = rlimit(RLIMIT_NOFILE);
5064 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5066 struct io_accept *accept = &req->accept;
5067 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5068 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5071 if (req->file->f_flags & O_NONBLOCK)
5072 req->flags |= REQ_F_NOWAIT;
5074 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
5075 accept->addr_len, accept->flags,
5077 if (ret == -EAGAIN && force_nonblock)
5080 if (ret == -ERESTARTSYS)
5082 req_set_fail_links(req);
5084 __io_req_complete(req, issue_flags, ret, 0);
5088 static int io_connect_prep_async(struct io_kiocb *req)
5090 struct io_async_connect *io = req->async_data;
5091 struct io_connect *conn = &req->connect;
5093 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5096 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5098 struct io_connect *conn = &req->connect;
5100 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5102 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
5105 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5106 conn->addr_len = READ_ONCE(sqe->addr2);
5110 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5112 struct io_async_connect __io, *io;
5113 unsigned file_flags;
5115 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5117 if (req->async_data) {
5118 io = req->async_data;
5120 ret = move_addr_to_kernel(req->connect.addr,
5121 req->connect.addr_len,
5128 file_flags = force_nonblock ? O_NONBLOCK : 0;
5130 ret = __sys_connect_file(req->file, &io->address,
5131 req->connect.addr_len, file_flags);
5132 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5133 if (req->async_data)
5135 if (io_alloc_async_data(req)) {
5139 io = req->async_data;
5140 memcpy(req->async_data, &__io, sizeof(__io));
5143 if (ret == -ERESTARTSYS)
5147 req_set_fail_links(req);
5148 __io_req_complete(req, issue_flags, ret, 0);
5151 #else /* !CONFIG_NET */
5152 #define IO_NETOP_FN(op) \
5153 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5155 return -EOPNOTSUPP; \
5158 #define IO_NETOP_PREP(op) \
5160 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5162 return -EOPNOTSUPP; \
5165 #define IO_NETOP_PREP_ASYNC(op) \
5167 static int io_##op##_prep_async(struct io_kiocb *req) \
5169 return -EOPNOTSUPP; \
5172 IO_NETOP_PREP_ASYNC(sendmsg);
5173 IO_NETOP_PREP_ASYNC(recvmsg);
5174 IO_NETOP_PREP_ASYNC(connect);
5175 IO_NETOP_PREP(accept);
5178 #endif /* CONFIG_NET */
5180 struct io_poll_table {
5181 struct poll_table_struct pt;
5182 struct io_kiocb *req;
5186 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5187 __poll_t mask, task_work_func_t func)
5191 /* for instances that support it check for an event match first: */
5192 if (mask && !(mask & poll->events))
5195 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5197 list_del_init(&poll->wait.entry);
5200 req->task_work.func = func;
5201 percpu_ref_get(&req->ctx->refs);
5204 * If this fails, then the task is exiting. When a task exits, the
5205 * work gets canceled, so just cancel this request as well instead
5206 * of executing it. We can't safely execute it anyway, as we may not
5207 * have the needed state needed for it anyway.
5209 ret = io_req_task_work_add(req);
5210 if (unlikely(ret)) {
5211 WRITE_ONCE(poll->canceled, true);
5212 io_req_task_work_add_fallback(req, func);
5217 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5218 __acquires(&req->ctx->completion_lock)
5220 struct io_ring_ctx *ctx = req->ctx;
5222 if (!req->result && !READ_ONCE(poll->canceled)) {
5223 struct poll_table_struct pt = { ._key = poll->events };
5225 req->result = vfs_poll(req->file, &pt) & poll->events;
5228 spin_lock_irq(&ctx->completion_lock);
5229 if (!req->result && !READ_ONCE(poll->canceled)) {
5230 add_wait_queue(poll->head, &poll->wait);
5237 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5239 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5240 if (req->opcode == IORING_OP_POLL_ADD)
5241 return req->async_data;
5242 return req->apoll->double_poll;
5245 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5247 if (req->opcode == IORING_OP_POLL_ADD)
5249 return &req->apoll->poll;
5252 static void io_poll_remove_double(struct io_kiocb *req)
5254 struct io_poll_iocb *poll = io_poll_get_double(req);
5256 lockdep_assert_held(&req->ctx->completion_lock);
5258 if (poll && poll->head) {
5259 struct wait_queue_head *head = poll->head;
5261 spin_lock(&head->lock);
5262 list_del_init(&poll->wait.entry);
5263 if (poll->wait.private)
5264 refcount_dec(&req->refs);
5266 spin_unlock(&head->lock);
5270 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5272 struct io_ring_ctx *ctx = req->ctx;
5274 io_poll_remove_double(req);
5275 req->poll.done = true;
5276 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5277 io_commit_cqring(ctx);
5280 static void io_poll_task_func(struct callback_head *cb)
5282 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5283 struct io_ring_ctx *ctx = req->ctx;
5284 struct io_kiocb *nxt;
5286 if (io_poll_rewait(req, &req->poll)) {
5287 spin_unlock_irq(&ctx->completion_lock);
5289 hash_del(&req->hash_node);
5290 io_poll_complete(req, req->result, 0);
5291 spin_unlock_irq(&ctx->completion_lock);
5293 nxt = io_put_req_find_next(req);
5294 io_cqring_ev_posted(ctx);
5296 __io_req_task_submit(nxt);
5299 percpu_ref_put(&ctx->refs);
5302 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5303 int sync, void *key)
5305 struct io_kiocb *req = wait->private;
5306 struct io_poll_iocb *poll = io_poll_get_single(req);
5307 __poll_t mask = key_to_poll(key);
5309 /* for instances that support it check for an event match first: */
5310 if (mask && !(mask & poll->events))
5313 list_del_init(&wait->entry);
5315 if (poll && poll->head) {
5318 spin_lock(&poll->head->lock);
5319 done = list_empty(&poll->wait.entry);
5321 list_del_init(&poll->wait.entry);
5322 /* make sure double remove sees this as being gone */
5323 wait->private = NULL;
5324 spin_unlock(&poll->head->lock);
5326 /* use wait func handler, so it matches the rq type */
5327 poll->wait.func(&poll->wait, mode, sync, key);
5330 refcount_dec(&req->refs);
5334 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5335 wait_queue_func_t wake_func)
5339 poll->canceled = false;
5340 poll->events = events;
5341 INIT_LIST_HEAD(&poll->wait.entry);
5342 init_waitqueue_func_entry(&poll->wait, wake_func);
5345 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5346 struct wait_queue_head *head,
5347 struct io_poll_iocb **poll_ptr)
5349 struct io_kiocb *req = pt->req;
5352 * If poll->head is already set, it's because the file being polled
5353 * uses multiple waitqueues for poll handling (eg one for read, one
5354 * for write). Setup a separate io_poll_iocb if this happens.
5356 if (unlikely(poll->head)) {
5357 struct io_poll_iocb *poll_one = poll;
5359 /* already have a 2nd entry, fail a third attempt */
5361 pt->error = -EINVAL;
5364 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5366 pt->error = -ENOMEM;
5369 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5370 refcount_inc(&req->refs);
5371 poll->wait.private = req;
5378 if (poll->events & EPOLLEXCLUSIVE)
5379 add_wait_queue_exclusive(head, &poll->wait);
5381 add_wait_queue(head, &poll->wait);
5384 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5385 struct poll_table_struct *p)
5387 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5388 struct async_poll *apoll = pt->req->apoll;
5390 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5393 static void io_async_task_func(struct callback_head *cb)
5395 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5396 struct async_poll *apoll = req->apoll;
5397 struct io_ring_ctx *ctx = req->ctx;
5399 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5401 if (io_poll_rewait(req, &apoll->poll)) {
5402 spin_unlock_irq(&ctx->completion_lock);
5403 percpu_ref_put(&ctx->refs);
5407 /* If req is still hashed, it cannot have been canceled. Don't check. */
5408 if (hash_hashed(&req->hash_node))
5409 hash_del(&req->hash_node);
5411 io_poll_remove_double(req);
5412 spin_unlock_irq(&ctx->completion_lock);
5414 if (!READ_ONCE(apoll->poll.canceled))
5415 __io_req_task_submit(req);
5417 __io_req_task_cancel(req, -ECANCELED);
5419 percpu_ref_put(&ctx->refs);
5420 kfree(apoll->double_poll);
5424 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5427 struct io_kiocb *req = wait->private;
5428 struct io_poll_iocb *poll = &req->apoll->poll;
5430 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5433 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5436 static void io_poll_req_insert(struct io_kiocb *req)
5438 struct io_ring_ctx *ctx = req->ctx;
5439 struct hlist_head *list;
5441 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5442 hlist_add_head(&req->hash_node, list);
5445 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5446 struct io_poll_iocb *poll,
5447 struct io_poll_table *ipt, __poll_t mask,
5448 wait_queue_func_t wake_func)
5449 __acquires(&ctx->completion_lock)
5451 struct io_ring_ctx *ctx = req->ctx;
5452 bool cancel = false;
5454 INIT_HLIST_NODE(&req->hash_node);
5455 io_init_poll_iocb(poll, mask, wake_func);
5456 poll->file = req->file;
5457 poll->wait.private = req;
5459 ipt->pt._key = mask;
5461 ipt->error = -EINVAL;
5463 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5465 spin_lock_irq(&ctx->completion_lock);
5466 if (likely(poll->head)) {
5467 spin_lock(&poll->head->lock);
5468 if (unlikely(list_empty(&poll->wait.entry))) {
5474 if (mask || ipt->error)
5475 list_del_init(&poll->wait.entry);
5477 WRITE_ONCE(poll->canceled, true);
5478 else if (!poll->done) /* actually waiting for an event */
5479 io_poll_req_insert(req);
5480 spin_unlock(&poll->head->lock);
5486 static bool io_arm_poll_handler(struct io_kiocb *req)
5488 const struct io_op_def *def = &io_op_defs[req->opcode];
5489 struct io_ring_ctx *ctx = req->ctx;
5490 struct async_poll *apoll;
5491 struct io_poll_table ipt;
5495 if (!req->file || !file_can_poll(req->file))
5497 if (req->flags & REQ_F_POLLED)
5501 else if (def->pollout)
5505 /* if we can't nonblock try, then no point in arming a poll handler */
5506 if (!io_file_supports_async(req->file, rw))
5509 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5510 if (unlikely(!apoll))
5512 apoll->double_poll = NULL;
5514 req->flags |= REQ_F_POLLED;
5519 mask |= POLLIN | POLLRDNORM;
5521 mask |= POLLOUT | POLLWRNORM;
5523 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5524 if ((req->opcode == IORING_OP_RECVMSG) &&
5525 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5528 mask |= POLLERR | POLLPRI;
5530 ipt.pt._qproc = io_async_queue_proc;
5532 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5534 if (ret || ipt.error) {
5535 io_poll_remove_double(req);
5536 spin_unlock_irq(&ctx->completion_lock);
5537 kfree(apoll->double_poll);
5541 spin_unlock_irq(&ctx->completion_lock);
5542 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5543 apoll->poll.events);
5547 static bool __io_poll_remove_one(struct io_kiocb *req,
5548 struct io_poll_iocb *poll)
5550 bool do_complete = false;
5552 spin_lock(&poll->head->lock);
5553 WRITE_ONCE(poll->canceled, true);
5554 if (!list_empty(&poll->wait.entry)) {
5555 list_del_init(&poll->wait.entry);
5558 spin_unlock(&poll->head->lock);
5559 hash_del(&req->hash_node);
5563 static bool io_poll_remove_one(struct io_kiocb *req)
5567 io_poll_remove_double(req);
5569 if (req->opcode == IORING_OP_POLL_ADD) {
5570 do_complete = __io_poll_remove_one(req, &req->poll);
5572 struct async_poll *apoll = req->apoll;
5574 /* non-poll requests have submit ref still */
5575 do_complete = __io_poll_remove_one(req, &apoll->poll);
5578 kfree(apoll->double_poll);
5584 io_cqring_fill_event(req, -ECANCELED);
5585 io_commit_cqring(req->ctx);
5586 req_set_fail_links(req);
5587 io_put_req_deferred(req, 1);
5594 * Returns true if we found and killed one or more poll requests
5596 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5597 struct files_struct *files)
5599 struct hlist_node *tmp;
5600 struct io_kiocb *req;
5603 spin_lock_irq(&ctx->completion_lock);
5604 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5605 struct hlist_head *list;
5607 list = &ctx->cancel_hash[i];
5608 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5609 if (io_match_task(req, tsk, files))
5610 posted += io_poll_remove_one(req);
5613 spin_unlock_irq(&ctx->completion_lock);
5616 io_cqring_ev_posted(ctx);
5621 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5623 struct hlist_head *list;
5624 struct io_kiocb *req;
5626 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5627 hlist_for_each_entry(req, list, hash_node) {
5628 if (sqe_addr != req->user_data)
5630 if (io_poll_remove_one(req))
5638 static int io_poll_remove_prep(struct io_kiocb *req,
5639 const struct io_uring_sqe *sqe)
5641 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5643 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5647 req->poll_remove.addr = READ_ONCE(sqe->addr);
5652 * Find a running poll command that matches one specified in sqe->addr,
5653 * and remove it if found.
5655 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5657 struct io_ring_ctx *ctx = req->ctx;
5660 spin_lock_irq(&ctx->completion_lock);
5661 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5662 spin_unlock_irq(&ctx->completion_lock);
5665 req_set_fail_links(req);
5666 io_req_complete(req, ret);
5670 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5673 struct io_kiocb *req = wait->private;
5674 struct io_poll_iocb *poll = &req->poll;
5676 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5679 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5680 struct poll_table_struct *p)
5682 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5684 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5687 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5689 struct io_poll_iocb *poll = &req->poll;
5692 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5694 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5697 events = READ_ONCE(sqe->poll32_events);
5699 events = swahw32(events);
5701 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5702 (events & EPOLLEXCLUSIVE);
5706 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5708 struct io_poll_iocb *poll = &req->poll;
5709 struct io_ring_ctx *ctx = req->ctx;
5710 struct io_poll_table ipt;
5713 ipt.pt._qproc = io_poll_queue_proc;
5715 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5718 if (mask) { /* no async, we'd stolen it */
5720 io_poll_complete(req, mask, 0);
5722 spin_unlock_irq(&ctx->completion_lock);
5725 io_cqring_ev_posted(ctx);
5731 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5733 struct io_timeout_data *data = container_of(timer,
5734 struct io_timeout_data, timer);
5735 struct io_kiocb *req = data->req;
5736 struct io_ring_ctx *ctx = req->ctx;
5737 unsigned long flags;
5739 spin_lock_irqsave(&ctx->completion_lock, flags);
5740 list_del_init(&req->timeout.list);
5741 atomic_set(&req->ctx->cq_timeouts,
5742 atomic_read(&req->ctx->cq_timeouts) + 1);
5744 io_cqring_fill_event(req, -ETIME);
5745 io_commit_cqring(ctx);
5746 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5748 io_cqring_ev_posted(ctx);
5749 req_set_fail_links(req);
5751 return HRTIMER_NORESTART;
5754 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5757 struct io_timeout_data *io;
5758 struct io_kiocb *req;
5761 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5762 if (user_data == req->user_data) {
5769 return ERR_PTR(ret);
5771 io = req->async_data;
5772 ret = hrtimer_try_to_cancel(&io->timer);
5774 return ERR_PTR(-EALREADY);
5775 list_del_init(&req->timeout.list);
5779 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5781 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5784 return PTR_ERR(req);
5786 req_set_fail_links(req);
5787 io_cqring_fill_event(req, -ECANCELED);
5788 io_put_req_deferred(req, 1);
5792 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5793 struct timespec64 *ts, enum hrtimer_mode mode)
5795 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5796 struct io_timeout_data *data;
5799 return PTR_ERR(req);
5801 req->timeout.off = 0; /* noseq */
5802 data = req->async_data;
5803 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5804 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5805 data->timer.function = io_timeout_fn;
5806 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5810 static int io_timeout_remove_prep(struct io_kiocb *req,
5811 const struct io_uring_sqe *sqe)
5813 struct io_timeout_rem *tr = &req->timeout_rem;
5815 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5817 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5819 if (sqe->ioprio || sqe->buf_index || sqe->len)
5822 tr->addr = READ_ONCE(sqe->addr);
5823 tr->flags = READ_ONCE(sqe->timeout_flags);
5824 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5825 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5827 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5829 } else if (tr->flags) {
5830 /* timeout removal doesn't support flags */
5837 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5839 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5844 * Remove or update an existing timeout command
5846 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5848 struct io_timeout_rem *tr = &req->timeout_rem;
5849 struct io_ring_ctx *ctx = req->ctx;
5852 spin_lock_irq(&ctx->completion_lock);
5853 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5854 ret = io_timeout_cancel(ctx, tr->addr);
5856 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5857 io_translate_timeout_mode(tr->flags));
5859 io_cqring_fill_event(req, ret);
5860 io_commit_cqring(ctx);
5861 spin_unlock_irq(&ctx->completion_lock);
5862 io_cqring_ev_posted(ctx);
5864 req_set_fail_links(req);
5869 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5870 bool is_timeout_link)
5872 struct io_timeout_data *data;
5874 u32 off = READ_ONCE(sqe->off);
5876 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5878 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5880 if (off && is_timeout_link)
5882 flags = READ_ONCE(sqe->timeout_flags);
5883 if (flags & ~IORING_TIMEOUT_ABS)
5886 req->timeout.off = off;
5888 if (!req->async_data && io_alloc_async_data(req))
5891 data = req->async_data;
5894 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5897 data->mode = io_translate_timeout_mode(flags);
5898 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5902 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5904 struct io_ring_ctx *ctx = req->ctx;
5905 struct io_timeout_data *data = req->async_data;
5906 struct list_head *entry;
5907 u32 tail, off = req->timeout.off;
5909 spin_lock_irq(&ctx->completion_lock);
5912 * sqe->off holds how many events that need to occur for this
5913 * timeout event to be satisfied. If it isn't set, then this is
5914 * a pure timeout request, sequence isn't used.
5916 if (io_is_timeout_noseq(req)) {
5917 entry = ctx->timeout_list.prev;
5921 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5922 req->timeout.target_seq = tail + off;
5924 /* Update the last seq here in case io_flush_timeouts() hasn't.
5925 * This is safe because ->completion_lock is held, and submissions
5926 * and completions are never mixed in the same ->completion_lock section.
5928 ctx->cq_last_tm_flush = tail;
5931 * Insertion sort, ensuring the first entry in the list is always
5932 * the one we need first.
5934 list_for_each_prev(entry, &ctx->timeout_list) {
5935 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5938 if (io_is_timeout_noseq(nxt))
5940 /* nxt.seq is behind @tail, otherwise would've been completed */
5941 if (off >= nxt->timeout.target_seq - tail)
5945 list_add(&req->timeout.list, entry);
5946 data->timer.function = io_timeout_fn;
5947 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5948 spin_unlock_irq(&ctx->completion_lock);
5952 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5954 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5956 return req->user_data == (unsigned long) data;
5959 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5961 enum io_wq_cancel cancel_ret;
5964 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5965 switch (cancel_ret) {
5966 case IO_WQ_CANCEL_OK:
5969 case IO_WQ_CANCEL_RUNNING:
5972 case IO_WQ_CANCEL_NOTFOUND:
5980 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5981 struct io_kiocb *req, __u64 sqe_addr,
5984 unsigned long flags;
5987 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5988 if (ret != -ENOENT) {
5989 spin_lock_irqsave(&ctx->completion_lock, flags);
5993 spin_lock_irqsave(&ctx->completion_lock, flags);
5994 ret = io_timeout_cancel(ctx, sqe_addr);
5997 ret = io_poll_cancel(ctx, sqe_addr);
6001 io_cqring_fill_event(req, ret);
6002 io_commit_cqring(ctx);
6003 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6004 io_cqring_ev_posted(ctx);
6007 req_set_fail_links(req);
6011 static int io_async_cancel_prep(struct io_kiocb *req,
6012 const struct io_uring_sqe *sqe)
6014 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6016 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6018 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
6021 req->cancel.addr = READ_ONCE(sqe->addr);
6025 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6027 struct io_ring_ctx *ctx = req->ctx;
6029 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
6033 static int io_rsrc_update_prep(struct io_kiocb *req,
6034 const struct io_uring_sqe *sqe)
6036 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
6038 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6040 if (sqe->ioprio || sqe->rw_flags)
6043 req->rsrc_update.offset = READ_ONCE(sqe->off);
6044 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6045 if (!req->rsrc_update.nr_args)
6047 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6051 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6053 struct io_ring_ctx *ctx = req->ctx;
6054 struct io_uring_rsrc_update up;
6057 if (issue_flags & IO_URING_F_NONBLOCK)
6060 up.offset = req->rsrc_update.offset;
6061 up.data = req->rsrc_update.arg;
6063 mutex_lock(&ctx->uring_lock);
6064 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
6065 mutex_unlock(&ctx->uring_lock);
6068 req_set_fail_links(req);
6069 __io_req_complete(req, issue_flags, ret, 0);
6073 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6075 switch (req->opcode) {
6078 case IORING_OP_READV:
6079 case IORING_OP_READ_FIXED:
6080 case IORING_OP_READ:
6081 return io_read_prep(req, sqe);
6082 case IORING_OP_WRITEV:
6083 case IORING_OP_WRITE_FIXED:
6084 case IORING_OP_WRITE:
6085 return io_write_prep(req, sqe);
6086 case IORING_OP_POLL_ADD:
6087 return io_poll_add_prep(req, sqe);
6088 case IORING_OP_POLL_REMOVE:
6089 return io_poll_remove_prep(req, sqe);
6090 case IORING_OP_FSYNC:
6091 return io_fsync_prep(req, sqe);
6092 case IORING_OP_SYNC_FILE_RANGE:
6093 return io_sfr_prep(req, sqe);
6094 case IORING_OP_SENDMSG:
6095 case IORING_OP_SEND:
6096 return io_sendmsg_prep(req, sqe);
6097 case IORING_OP_RECVMSG:
6098 case IORING_OP_RECV:
6099 return io_recvmsg_prep(req, sqe);
6100 case IORING_OP_CONNECT:
6101 return io_connect_prep(req, sqe);
6102 case IORING_OP_TIMEOUT:
6103 return io_timeout_prep(req, sqe, false);
6104 case IORING_OP_TIMEOUT_REMOVE:
6105 return io_timeout_remove_prep(req, sqe);
6106 case IORING_OP_ASYNC_CANCEL:
6107 return io_async_cancel_prep(req, sqe);
6108 case IORING_OP_LINK_TIMEOUT:
6109 return io_timeout_prep(req, sqe, true);
6110 case IORING_OP_ACCEPT:
6111 return io_accept_prep(req, sqe);
6112 case IORING_OP_FALLOCATE:
6113 return io_fallocate_prep(req, sqe);
6114 case IORING_OP_OPENAT:
6115 return io_openat_prep(req, sqe);
6116 case IORING_OP_CLOSE:
6117 return io_close_prep(req, sqe);
6118 case IORING_OP_FILES_UPDATE:
6119 return io_rsrc_update_prep(req, sqe);
6120 case IORING_OP_STATX:
6121 return io_statx_prep(req, sqe);
6122 case IORING_OP_FADVISE:
6123 return io_fadvise_prep(req, sqe);
6124 case IORING_OP_MADVISE:
6125 return io_madvise_prep(req, sqe);
6126 case IORING_OP_OPENAT2:
6127 return io_openat2_prep(req, sqe);
6128 case IORING_OP_EPOLL_CTL:
6129 return io_epoll_ctl_prep(req, sqe);
6130 case IORING_OP_SPLICE:
6131 return io_splice_prep(req, sqe);
6132 case IORING_OP_PROVIDE_BUFFERS:
6133 return io_provide_buffers_prep(req, sqe);
6134 case IORING_OP_REMOVE_BUFFERS:
6135 return io_remove_buffers_prep(req, sqe);
6137 return io_tee_prep(req, sqe);
6138 case IORING_OP_SHUTDOWN:
6139 return io_shutdown_prep(req, sqe);
6140 case IORING_OP_RENAMEAT:
6141 return io_renameat_prep(req, sqe);
6142 case IORING_OP_UNLINKAT:
6143 return io_unlinkat_prep(req, sqe);
6146 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6151 static int io_req_prep_async(struct io_kiocb *req)
6153 switch (req->opcode) {
6154 case IORING_OP_READV:
6155 case IORING_OP_READ_FIXED:
6156 case IORING_OP_READ:
6157 return io_rw_prep_async(req, READ);
6158 case IORING_OP_WRITEV:
6159 case IORING_OP_WRITE_FIXED:
6160 case IORING_OP_WRITE:
6161 return io_rw_prep_async(req, WRITE);
6162 case IORING_OP_SENDMSG:
6163 case IORING_OP_SEND:
6164 return io_sendmsg_prep_async(req);
6165 case IORING_OP_RECVMSG:
6166 case IORING_OP_RECV:
6167 return io_recvmsg_prep_async(req);
6168 case IORING_OP_CONNECT:
6169 return io_connect_prep_async(req);
6174 static int io_req_defer_prep(struct io_kiocb *req)
6176 if (!io_op_defs[req->opcode].needs_async_data)
6178 /* some opcodes init it during the inital prep */
6179 if (req->async_data)
6181 if (__io_alloc_async_data(req))
6183 return io_req_prep_async(req);
6186 static u32 io_get_sequence(struct io_kiocb *req)
6188 struct io_kiocb *pos;
6189 struct io_ring_ctx *ctx = req->ctx;
6190 u32 total_submitted, nr_reqs = 0;
6192 io_for_each_link(pos, req)
6195 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6196 return total_submitted - nr_reqs;
6199 static int io_req_defer(struct io_kiocb *req)
6201 struct io_ring_ctx *ctx = req->ctx;
6202 struct io_defer_entry *de;
6206 /* Still need defer if there is pending req in defer list. */
6207 if (likely(list_empty_careful(&ctx->defer_list) &&
6208 !(req->flags & REQ_F_IO_DRAIN)))
6211 seq = io_get_sequence(req);
6212 /* Still a chance to pass the sequence check */
6213 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6216 ret = io_req_defer_prep(req);
6219 io_prep_async_link(req);
6220 de = kmalloc(sizeof(*de), GFP_KERNEL);
6224 spin_lock_irq(&ctx->completion_lock);
6225 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6226 spin_unlock_irq(&ctx->completion_lock);
6228 io_queue_async_work(req);
6229 return -EIOCBQUEUED;
6232 trace_io_uring_defer(ctx, req, req->user_data);
6235 list_add_tail(&de->list, &ctx->defer_list);
6236 spin_unlock_irq(&ctx->completion_lock);
6237 return -EIOCBQUEUED;
6240 static void __io_clean_op(struct io_kiocb *req)
6242 if (req->flags & REQ_F_BUFFER_SELECTED) {
6243 switch (req->opcode) {
6244 case IORING_OP_READV:
6245 case IORING_OP_READ_FIXED:
6246 case IORING_OP_READ:
6247 kfree((void *)(unsigned long)req->rw.addr);
6249 case IORING_OP_RECVMSG:
6250 case IORING_OP_RECV:
6251 kfree(req->sr_msg.kbuf);
6254 req->flags &= ~REQ_F_BUFFER_SELECTED;
6257 if (req->flags & REQ_F_NEED_CLEANUP) {
6258 switch (req->opcode) {
6259 case IORING_OP_READV:
6260 case IORING_OP_READ_FIXED:
6261 case IORING_OP_READ:
6262 case IORING_OP_WRITEV:
6263 case IORING_OP_WRITE_FIXED:
6264 case IORING_OP_WRITE: {
6265 struct io_async_rw *io = req->async_data;
6267 kfree(io->free_iovec);
6270 case IORING_OP_RECVMSG:
6271 case IORING_OP_SENDMSG: {
6272 struct io_async_msghdr *io = req->async_data;
6274 kfree(io->free_iov);
6277 case IORING_OP_SPLICE:
6279 io_put_file(req, req->splice.file_in,
6280 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6282 case IORING_OP_OPENAT:
6283 case IORING_OP_OPENAT2:
6284 if (req->open.filename)
6285 putname(req->open.filename);
6287 case IORING_OP_RENAMEAT:
6288 putname(req->rename.oldpath);
6289 putname(req->rename.newpath);
6291 case IORING_OP_UNLINKAT:
6292 putname(req->unlink.filename);
6295 req->flags &= ~REQ_F_NEED_CLEANUP;
6299 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6301 struct io_ring_ctx *ctx = req->ctx;
6304 switch (req->opcode) {
6306 ret = io_nop(req, issue_flags);
6308 case IORING_OP_READV:
6309 case IORING_OP_READ_FIXED:
6310 case IORING_OP_READ:
6311 ret = io_read(req, issue_flags);
6313 case IORING_OP_WRITEV:
6314 case IORING_OP_WRITE_FIXED:
6315 case IORING_OP_WRITE:
6316 ret = io_write(req, issue_flags);
6318 case IORING_OP_FSYNC:
6319 ret = io_fsync(req, issue_flags);
6321 case IORING_OP_POLL_ADD:
6322 ret = io_poll_add(req, issue_flags);
6324 case IORING_OP_POLL_REMOVE:
6325 ret = io_poll_remove(req, issue_flags);
6327 case IORING_OP_SYNC_FILE_RANGE:
6328 ret = io_sync_file_range(req, issue_flags);
6330 case IORING_OP_SENDMSG:
6331 ret = io_sendmsg(req, issue_flags);
6333 case IORING_OP_SEND:
6334 ret = io_send(req, issue_flags);
6336 case IORING_OP_RECVMSG:
6337 ret = io_recvmsg(req, issue_flags);
6339 case IORING_OP_RECV:
6340 ret = io_recv(req, issue_flags);
6342 case IORING_OP_TIMEOUT:
6343 ret = io_timeout(req, issue_flags);
6345 case IORING_OP_TIMEOUT_REMOVE:
6346 ret = io_timeout_remove(req, issue_flags);
6348 case IORING_OP_ACCEPT:
6349 ret = io_accept(req, issue_flags);
6351 case IORING_OP_CONNECT:
6352 ret = io_connect(req, issue_flags);
6354 case IORING_OP_ASYNC_CANCEL:
6355 ret = io_async_cancel(req, issue_flags);
6357 case IORING_OP_FALLOCATE:
6358 ret = io_fallocate(req, issue_flags);
6360 case IORING_OP_OPENAT:
6361 ret = io_openat(req, issue_flags);
6363 case IORING_OP_CLOSE:
6364 ret = io_close(req, issue_flags);
6366 case IORING_OP_FILES_UPDATE:
6367 ret = io_files_update(req, issue_flags);
6369 case IORING_OP_STATX:
6370 ret = io_statx(req, issue_flags);
6372 case IORING_OP_FADVISE:
6373 ret = io_fadvise(req, issue_flags);
6375 case IORING_OP_MADVISE:
6376 ret = io_madvise(req, issue_flags);
6378 case IORING_OP_OPENAT2:
6379 ret = io_openat2(req, issue_flags);
6381 case IORING_OP_EPOLL_CTL:
6382 ret = io_epoll_ctl(req, issue_flags);
6384 case IORING_OP_SPLICE:
6385 ret = io_splice(req, issue_flags);
6387 case IORING_OP_PROVIDE_BUFFERS:
6388 ret = io_provide_buffers(req, issue_flags);
6390 case IORING_OP_REMOVE_BUFFERS:
6391 ret = io_remove_buffers(req, issue_flags);
6394 ret = io_tee(req, issue_flags);
6396 case IORING_OP_SHUTDOWN:
6397 ret = io_shutdown(req, issue_flags);
6399 case IORING_OP_RENAMEAT:
6400 ret = io_renameat(req, issue_flags);
6402 case IORING_OP_UNLINKAT:
6403 ret = io_unlinkat(req, issue_flags);
6413 /* If the op doesn't have a file, we're not polling for it */
6414 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6415 const bool in_async = io_wq_current_is_worker();
6417 /* workqueue context doesn't hold uring_lock, grab it now */
6419 mutex_lock(&ctx->uring_lock);
6421 io_iopoll_req_issued(req, in_async);
6424 mutex_unlock(&ctx->uring_lock);
6430 static void io_wq_submit_work(struct io_wq_work *work)
6432 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6433 struct io_kiocb *timeout;
6436 timeout = io_prep_linked_timeout(req);
6438 io_queue_linked_timeout(timeout);
6440 if (work->flags & IO_WQ_WORK_CANCEL)
6445 ret = io_issue_sqe(req, 0);
6447 * We can get EAGAIN for polled IO even though we're
6448 * forcing a sync submission from here, since we can't
6449 * wait for request slots on the block side.
6457 /* avoid locking problems by failing it from a clean context */
6459 /* io-wq is going to take one down */
6460 refcount_inc(&req->refs);
6461 io_req_task_queue_fail(req, ret);
6465 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6468 struct fixed_rsrc_table *table;
6470 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6471 return table->files[index & IORING_FILE_TABLE_MASK];
6474 static struct file *io_file_get(struct io_submit_state *state,
6475 struct io_kiocb *req, int fd, bool fixed)
6477 struct io_ring_ctx *ctx = req->ctx;
6481 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6483 fd = array_index_nospec(fd, ctx->nr_user_files);
6484 file = io_file_from_index(ctx, fd);
6485 io_set_resource_node(req);
6487 trace_io_uring_file_get(ctx, fd);
6488 file = __io_file_get(state, fd);
6491 if (file && unlikely(file->f_op == &io_uring_fops))
6492 io_req_track_inflight(req);
6496 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6498 struct io_timeout_data *data = container_of(timer,
6499 struct io_timeout_data, timer);
6500 struct io_kiocb *prev, *req = data->req;
6501 struct io_ring_ctx *ctx = req->ctx;
6502 unsigned long flags;
6504 spin_lock_irqsave(&ctx->completion_lock, flags);
6505 prev = req->timeout.head;
6506 req->timeout.head = NULL;
6509 * We don't expect the list to be empty, that will only happen if we
6510 * race with the completion of the linked work.
6512 if (prev && refcount_inc_not_zero(&prev->refs))
6513 io_remove_next_linked(prev);
6516 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6519 req_set_fail_links(prev);
6520 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6521 io_put_req_deferred(prev, 1);
6523 io_req_complete_post(req, -ETIME, 0);
6524 io_put_req_deferred(req, 1);
6526 return HRTIMER_NORESTART;
6529 static void __io_queue_linked_timeout(struct io_kiocb *req)
6532 * If the back reference is NULL, then our linked request finished
6533 * before we got a chance to setup the timer
6535 if (req->timeout.head) {
6536 struct io_timeout_data *data = req->async_data;
6538 data->timer.function = io_link_timeout_fn;
6539 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6544 static void io_queue_linked_timeout(struct io_kiocb *req)
6546 struct io_ring_ctx *ctx = req->ctx;
6548 spin_lock_irq(&ctx->completion_lock);
6549 __io_queue_linked_timeout(req);
6550 spin_unlock_irq(&ctx->completion_lock);
6552 /* drop submission reference */
6556 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6558 struct io_kiocb *nxt = req->link;
6560 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6561 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6564 nxt->timeout.head = req;
6565 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6566 req->flags |= REQ_F_LINK_TIMEOUT;
6570 static void __io_queue_sqe(struct io_kiocb *req)
6572 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6573 const struct cred *old_creds = NULL;
6576 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6577 (req->work.flags & IO_WQ_WORK_CREDS) &&
6578 req->work.identity->creds != current_cred())
6579 old_creds = override_creds(req->work.identity->creds);
6581 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6584 revert_creds(old_creds);
6587 * We async punt it if the file wasn't marked NOWAIT, or if the file
6588 * doesn't support non-blocking read/write attempts
6590 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6591 if (!io_arm_poll_handler(req)) {
6593 * Queued up for async execution, worker will release
6594 * submit reference when the iocb is actually submitted.
6596 io_queue_async_work(req);
6598 } else if (likely(!ret)) {
6599 /* drop submission reference */
6600 if (req->flags & REQ_F_COMPLETE_INLINE) {
6601 struct io_ring_ctx *ctx = req->ctx;
6602 struct io_comp_state *cs = &ctx->submit_state.comp;
6604 cs->reqs[cs->nr++] = req;
6605 if (cs->nr == ARRAY_SIZE(cs->reqs))
6606 io_submit_flush_completions(cs, ctx);
6611 req_set_fail_links(req);
6613 io_req_complete(req, ret);
6616 io_queue_linked_timeout(linked_timeout);
6619 static void io_queue_sqe(struct io_kiocb *req)
6623 ret = io_req_defer(req);
6625 if (ret != -EIOCBQUEUED) {
6627 req_set_fail_links(req);
6629 io_req_complete(req, ret);
6631 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6632 ret = io_req_defer_prep(req);
6635 io_queue_async_work(req);
6637 __io_queue_sqe(req);
6642 * Check SQE restrictions (opcode and flags).
6644 * Returns 'true' if SQE is allowed, 'false' otherwise.
6646 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6647 struct io_kiocb *req,
6648 unsigned int sqe_flags)
6650 if (!ctx->restricted)
6653 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6656 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6657 ctx->restrictions.sqe_flags_required)
6660 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6661 ctx->restrictions.sqe_flags_required))
6667 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6668 const struct io_uring_sqe *sqe)
6670 struct io_submit_state *state;
6671 unsigned int sqe_flags;
6674 req->opcode = READ_ONCE(sqe->opcode);
6675 /* same numerical values with corresponding REQ_F_*, safe to copy */
6676 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6677 req->user_data = READ_ONCE(sqe->user_data);
6678 req->async_data = NULL;
6682 req->fixed_rsrc_refs = NULL;
6683 /* one is dropped after submission, the other at completion */
6684 refcount_set(&req->refs, 2);
6685 req->task = current;
6688 /* enforce forwards compatibility on users */
6689 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6694 if (unlikely(req->opcode >= IORING_OP_LAST))
6697 if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6700 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6703 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6704 !io_op_defs[req->opcode].buffer_select)
6707 id = READ_ONCE(sqe->personality);
6709 struct io_identity *iod;
6711 iod = idr_find(&ctx->personality_idr, id);
6714 refcount_inc(&iod->count);
6716 __io_req_init_async(req);
6717 get_cred(iod->creds);
6718 req->work.identity = iod;
6719 req->work.flags |= IO_WQ_WORK_CREDS;
6722 state = &ctx->submit_state;
6725 * Plug now if we have more than 1 IO left after this, and the target
6726 * is potentially a read/write to block based storage.
6728 if (!state->plug_started && state->ios_left > 1 &&
6729 io_op_defs[req->opcode].plug) {
6730 blk_start_plug(&state->plug);
6731 state->plug_started = true;
6734 if (io_op_defs[req->opcode].needs_file) {
6735 bool fixed = req->flags & REQ_F_FIXED_FILE;
6737 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6738 if (unlikely(!req->file))
6746 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6747 const struct io_uring_sqe *sqe)
6749 struct io_submit_link *link = &ctx->submit_state.link;
6752 ret = io_init_req(ctx, req, sqe);
6753 if (unlikely(ret)) {
6756 io_req_complete(req, ret);
6758 /* fail even hard links since we don't submit */
6759 link->head->flags |= REQ_F_FAIL_LINK;
6760 io_put_req(link->head);
6761 io_req_complete(link->head, -ECANCELED);
6766 ret = io_req_prep(req, sqe);
6770 /* don't need @sqe from now on */
6771 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6772 true, ctx->flags & IORING_SETUP_SQPOLL);
6775 * If we already have a head request, queue this one for async
6776 * submittal once the head completes. If we don't have a head but
6777 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6778 * submitted sync once the chain is complete. If none of those
6779 * conditions are true (normal request), then just queue it.
6782 struct io_kiocb *head = link->head;
6785 * Taking sequential execution of a link, draining both sides
6786 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6787 * requests in the link. So, it drains the head and the
6788 * next after the link request. The last one is done via
6789 * drain_next flag to persist the effect across calls.
6791 if (req->flags & REQ_F_IO_DRAIN) {
6792 head->flags |= REQ_F_IO_DRAIN;
6793 ctx->drain_next = 1;
6795 ret = io_req_defer_prep(req);
6798 trace_io_uring_link(ctx, req, head);
6799 link->last->link = req;
6802 /* last request of a link, enqueue the link */
6803 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6808 if (unlikely(ctx->drain_next)) {
6809 req->flags |= REQ_F_IO_DRAIN;
6810 ctx->drain_next = 0;
6812 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6824 * Batched submission is done, ensure local IO is flushed out.
6826 static void io_submit_state_end(struct io_submit_state *state,
6827 struct io_ring_ctx *ctx)
6829 if (state->link.head)
6830 io_queue_sqe(state->link.head);
6832 io_submit_flush_completions(&state->comp, ctx);
6833 if (state->plug_started)
6834 blk_finish_plug(&state->plug);
6835 io_state_file_put(state);
6839 * Start submission side cache.
6841 static void io_submit_state_start(struct io_submit_state *state,
6842 unsigned int max_ios)
6844 state->plug_started = false;
6845 state->ios_left = max_ios;
6846 /* set only head, no need to init link_last in advance */
6847 state->link.head = NULL;
6850 static void io_commit_sqring(struct io_ring_ctx *ctx)
6852 struct io_rings *rings = ctx->rings;
6855 * Ensure any loads from the SQEs are done at this point,
6856 * since once we write the new head, the application could
6857 * write new data to them.
6859 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6863 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6864 * that is mapped by userspace. This means that care needs to be taken to
6865 * ensure that reads are stable, as we cannot rely on userspace always
6866 * being a good citizen. If members of the sqe are validated and then later
6867 * used, it's important that those reads are done through READ_ONCE() to
6868 * prevent a re-load down the line.
6870 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6872 u32 *sq_array = ctx->sq_array;
6876 * The cached sq head (or cq tail) serves two purposes:
6878 * 1) allows us to batch the cost of updating the user visible
6880 * 2) allows the kernel side to track the head on its own, even
6881 * though the application is the one updating it.
6883 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6884 if (likely(head < ctx->sq_entries))
6885 return &ctx->sq_sqes[head];
6887 /* drop invalid entries */
6888 ctx->cached_sq_dropped++;
6889 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6893 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6897 /* if we have a backlog and couldn't flush it all, return BUSY */
6898 if (test_bit(0, &ctx->sq_check_overflow)) {
6899 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6903 /* make sure SQ entry isn't read before tail */
6904 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6906 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6909 percpu_counter_add(¤t->io_uring->inflight, nr);
6910 refcount_add(nr, ¤t->usage);
6911 io_submit_state_start(&ctx->submit_state, nr);
6913 while (submitted < nr) {
6914 const struct io_uring_sqe *sqe;
6915 struct io_kiocb *req;
6917 req = io_alloc_req(ctx);
6918 if (unlikely(!req)) {
6920 submitted = -EAGAIN;
6923 sqe = io_get_sqe(ctx);
6924 if (unlikely(!sqe)) {
6925 kmem_cache_free(req_cachep, req);
6928 /* will complete beyond this point, count as submitted */
6930 if (io_submit_sqe(ctx, req, sqe))
6934 if (unlikely(submitted != nr)) {
6935 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6936 struct io_uring_task *tctx = current->io_uring;
6937 int unused = nr - ref_used;
6939 percpu_ref_put_many(&ctx->refs, unused);
6940 percpu_counter_sub(&tctx->inflight, unused);
6941 put_task_struct_many(current, unused);
6944 io_submit_state_end(&ctx->submit_state, ctx);
6945 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6946 io_commit_sqring(ctx);
6951 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6953 /* Tell userspace we may need a wakeup call */
6954 spin_lock_irq(&ctx->completion_lock);
6955 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6956 spin_unlock_irq(&ctx->completion_lock);
6959 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6961 spin_lock_irq(&ctx->completion_lock);
6962 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6963 spin_unlock_irq(&ctx->completion_lock);
6966 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6968 unsigned int to_submit;
6971 to_submit = io_sqring_entries(ctx);
6972 /* if we're handling multiple rings, cap submit size for fairness */
6973 if (cap_entries && to_submit > 8)
6976 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6977 unsigned nr_events = 0;
6979 mutex_lock(&ctx->uring_lock);
6980 if (!list_empty(&ctx->iopoll_list))
6981 io_do_iopoll(ctx, &nr_events, 0);
6983 if (to_submit && !ctx->sqo_dead &&
6984 likely(!percpu_ref_is_dying(&ctx->refs)))
6985 ret = io_submit_sqes(ctx, to_submit);
6986 mutex_unlock(&ctx->uring_lock);
6989 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6990 wake_up(&ctx->sqo_sq_wait);
6995 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6997 struct io_ring_ctx *ctx;
6998 unsigned sq_thread_idle = 0;
7000 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7001 if (sq_thread_idle < ctx->sq_thread_idle)
7002 sq_thread_idle = ctx->sq_thread_idle;
7005 sqd->sq_thread_idle = sq_thread_idle;
7008 static void io_sqd_init_new(struct io_sq_data *sqd)
7010 struct io_ring_ctx *ctx;
7012 while (!list_empty(&sqd->ctx_new_list)) {
7013 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
7014 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
7015 complete(&ctx->sq_thread_comp);
7018 io_sqd_update_thread_idle(sqd);
7021 static int io_sq_thread(void *data)
7023 struct cgroup_subsys_state *cur_css = NULL;
7024 struct files_struct *old_files = current->files;
7025 struct nsproxy *old_nsproxy = current->nsproxy;
7026 const struct cred *old_cred = NULL;
7027 struct io_sq_data *sqd = data;
7028 struct io_ring_ctx *ctx;
7029 unsigned long timeout = 0;
7033 current->files = NULL;
7034 current->nsproxy = NULL;
7035 task_unlock(current);
7037 while (!kthread_should_stop()) {
7039 bool cap_entries, sqt_spin, needs_sched;
7042 * Any changes to the sqd lists are synchronized through the
7043 * kthread parking. This synchronizes the thread vs users,
7044 * the users are synchronized on the sqd->ctx_lock.
7046 if (kthread_should_park()) {
7049 * When sq thread is unparked, in case the previous park operation
7050 * comes from io_put_sq_data(), which means that sq thread is going
7051 * to be stopped, so here needs to have a check.
7053 if (kthread_should_stop())
7057 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
7058 io_sqd_init_new(sqd);
7059 timeout = jiffies + sqd->sq_thread_idle;
7063 cap_entries = !list_is_singular(&sqd->ctx_list);
7064 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7065 if (current->cred != ctx->creds) {
7067 revert_creds(old_cred);
7068 old_cred = override_creds(ctx->creds);
7070 io_sq_thread_associate_blkcg(ctx, &cur_css);
7072 current->loginuid = ctx->loginuid;
7073 current->sessionid = ctx->sessionid;
7076 ret = __io_sq_thread(ctx, cap_entries);
7077 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7080 io_sq_thread_drop_mm_files();
7083 if (sqt_spin || !time_after(jiffies, timeout)) {
7085 io_sq_thread_drop_mm_files();
7088 timeout = jiffies + sqd->sq_thread_idle;
7093 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7094 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7095 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7096 !list_empty_careful(&ctx->iopoll_list)) {
7097 needs_sched = false;
7100 if (io_sqring_entries(ctx)) {
7101 needs_sched = false;
7106 if (needs_sched && !kthread_should_park()) {
7107 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7108 io_ring_set_wakeup_flag(ctx);
7111 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7112 io_ring_clear_wakeup_flag(ctx);
7115 finish_wait(&sqd->wait, &wait);
7116 timeout = jiffies + sqd->sq_thread_idle;
7120 io_sq_thread_drop_mm_files();
7123 io_sq_thread_unassociate_blkcg();
7125 revert_creds(old_cred);
7128 current->files = old_files;
7129 current->nsproxy = old_nsproxy;
7130 task_unlock(current);
7137 struct io_wait_queue {
7138 struct wait_queue_entry wq;
7139 struct io_ring_ctx *ctx;
7141 unsigned nr_timeouts;
7144 static inline bool io_should_wake(struct io_wait_queue *iowq)
7146 struct io_ring_ctx *ctx = iowq->ctx;
7149 * Wake up if we have enough events, or if a timeout occurred since we
7150 * started waiting. For timeouts, we always want to return to userspace,
7151 * regardless of event count.
7153 return io_cqring_events(ctx) >= iowq->to_wait ||
7154 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7157 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7158 int wake_flags, void *key)
7160 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7164 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7165 * the task, and the next invocation will do it.
7167 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
7168 return autoremove_wake_function(curr, mode, wake_flags, key);
7172 static int io_run_task_work_sig(void)
7174 if (io_run_task_work())
7176 if (!signal_pending(current))
7178 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
7179 return -ERESTARTSYS;
7183 /* when returns >0, the caller should retry */
7184 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7185 struct io_wait_queue *iowq,
7186 signed long *timeout)
7190 /* make sure we run task_work before checking for signals */
7191 ret = io_run_task_work_sig();
7192 if (ret || io_should_wake(iowq))
7194 /* let the caller flush overflows, retry */
7195 if (test_bit(0, &ctx->cq_check_overflow))
7198 *timeout = schedule_timeout(*timeout);
7199 return !*timeout ? -ETIME : 1;
7203 * Wait until events become available, if we don't already have some. The
7204 * application must reap them itself, as they reside on the shared cq ring.
7206 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7207 const sigset_t __user *sig, size_t sigsz,
7208 struct __kernel_timespec __user *uts)
7210 struct io_wait_queue iowq = {
7213 .func = io_wake_function,
7214 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7217 .to_wait = min_events,
7219 struct io_rings *rings = ctx->rings;
7220 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7224 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7225 if (io_cqring_events(ctx) >= min_events)
7227 if (!io_run_task_work())
7232 #ifdef CONFIG_COMPAT
7233 if (in_compat_syscall())
7234 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7238 ret = set_user_sigmask(sig, sigsz);
7245 struct timespec64 ts;
7247 if (get_timespec64(&ts, uts))
7249 timeout = timespec64_to_jiffies(&ts);
7252 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7253 trace_io_uring_cqring_wait(ctx, min_events);
7255 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7256 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7257 TASK_INTERRUPTIBLE);
7258 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7259 finish_wait(&ctx->wait, &iowq.wq);
7262 restore_saved_sigmask_unless(ret == -EINTR);
7264 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7267 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7269 #if defined(CONFIG_UNIX)
7270 if (ctx->ring_sock) {
7271 struct sock *sock = ctx->ring_sock->sk;
7272 struct sk_buff *skb;
7274 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7280 for (i = 0; i < ctx->nr_user_files; i++) {
7283 file = io_file_from_index(ctx, i);
7290 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7292 struct fixed_rsrc_data *data;
7294 data = container_of(ref, struct fixed_rsrc_data, refs);
7295 complete(&data->done);
7298 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7300 spin_lock_bh(&ctx->rsrc_ref_lock);
7303 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7305 spin_unlock_bh(&ctx->rsrc_ref_lock);
7308 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
7309 struct fixed_rsrc_data *rsrc_data,
7310 struct fixed_rsrc_ref_node *ref_node)
7312 io_rsrc_ref_lock(ctx);
7313 rsrc_data->node = ref_node;
7314 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
7315 io_rsrc_ref_unlock(ctx);
7316 percpu_ref_get(&rsrc_data->refs);
7319 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
7321 struct fixed_rsrc_ref_node *ref_node = NULL;
7323 io_rsrc_ref_lock(ctx);
7324 ref_node = data->node;
7326 io_rsrc_ref_unlock(ctx);
7328 percpu_ref_kill(&ref_node->refs);
7331 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
7332 struct io_ring_ctx *ctx,
7333 void (*rsrc_put)(struct io_ring_ctx *ctx,
7334 struct io_rsrc_put *prsrc))
7336 struct fixed_rsrc_ref_node *backup_node;
7342 data->quiesce = true;
7345 backup_node = alloc_fixed_rsrc_ref_node(ctx);
7348 backup_node->rsrc_data = data;
7349 backup_node->rsrc_put = rsrc_put;
7351 io_sqe_rsrc_kill_node(ctx, data);
7352 percpu_ref_kill(&data->refs);
7353 flush_delayed_work(&ctx->rsrc_put_work);
7355 ret = wait_for_completion_interruptible(&data->done);
7356 if (!ret || !io_refs_resurrect(&data->refs, &data->done))
7359 io_sqe_rsrc_set_node(ctx, data, backup_node);
7361 mutex_unlock(&ctx->uring_lock);
7362 ret = io_run_task_work_sig();
7363 mutex_lock(&ctx->uring_lock);
7365 data->quiesce = false;
7368 destroy_fixed_rsrc_ref_node(backup_node);
7372 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7374 struct fixed_rsrc_data *data;
7376 data = kzalloc(sizeof(*data), GFP_KERNEL);
7380 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7381 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7386 init_completion(&data->done);
7390 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7392 percpu_ref_exit(&data->refs);
7397 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7399 struct fixed_rsrc_data *data = ctx->file_data;
7400 unsigned nr_tables, i;
7404 * percpu_ref_is_dying() is to stop parallel files unregister
7405 * Since we possibly drop uring lock later in this function to
7408 if (!data || percpu_ref_is_dying(&data->refs))
7410 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7414 __io_sqe_files_unregister(ctx);
7415 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7416 for (i = 0; i < nr_tables; i++)
7417 kfree(data->table[i].files);
7418 free_fixed_rsrc_data(data);
7419 ctx->file_data = NULL;
7420 ctx->nr_user_files = 0;
7424 static void io_put_sq_data(struct io_sq_data *sqd)
7426 if (refcount_dec_and_test(&sqd->refs)) {
7428 * The park is a bit of a work-around, without it we get
7429 * warning spews on shutdown with SQPOLL set and affinity
7430 * set to a single CPU.
7433 kthread_park(sqd->thread);
7434 kthread_stop(sqd->thread);
7441 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7443 struct io_ring_ctx *ctx_attach;
7444 struct io_sq_data *sqd;
7447 f = fdget(p->wq_fd);
7449 return ERR_PTR(-ENXIO);
7450 if (f.file->f_op != &io_uring_fops) {
7452 return ERR_PTR(-EINVAL);
7455 ctx_attach = f.file->private_data;
7456 sqd = ctx_attach->sq_data;
7459 return ERR_PTR(-EINVAL);
7462 refcount_inc(&sqd->refs);
7467 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7469 struct io_sq_data *sqd;
7471 if (p->flags & IORING_SETUP_ATTACH_WQ)
7472 return io_attach_sq_data(p);
7474 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7476 return ERR_PTR(-ENOMEM);
7478 refcount_set(&sqd->refs, 1);
7479 INIT_LIST_HEAD(&sqd->ctx_list);
7480 INIT_LIST_HEAD(&sqd->ctx_new_list);
7481 mutex_init(&sqd->ctx_lock);
7482 mutex_init(&sqd->lock);
7483 init_waitqueue_head(&sqd->wait);
7487 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7488 __releases(&sqd->lock)
7492 kthread_unpark(sqd->thread);
7493 mutex_unlock(&sqd->lock);
7496 static void io_sq_thread_park(struct io_sq_data *sqd)
7497 __acquires(&sqd->lock)
7501 mutex_lock(&sqd->lock);
7502 kthread_park(sqd->thread);
7505 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7507 struct io_sq_data *sqd = ctx->sq_data;
7512 * We may arrive here from the error branch in
7513 * io_sq_offload_create() where the kthread is created
7514 * without being waked up, thus wake it up now to make
7515 * sure the wait will complete.
7517 wake_up_process(sqd->thread);
7518 wait_for_completion(&ctx->sq_thread_comp);
7520 io_sq_thread_park(sqd);
7523 mutex_lock(&sqd->ctx_lock);
7524 list_del(&ctx->sqd_list);
7525 io_sqd_update_thread_idle(sqd);
7526 mutex_unlock(&sqd->ctx_lock);
7529 io_sq_thread_unpark(sqd);
7531 io_put_sq_data(sqd);
7532 ctx->sq_data = NULL;
7536 static void io_finish_async(struct io_ring_ctx *ctx)
7538 io_sq_thread_stop(ctx);
7541 io_wq_destroy(ctx->io_wq);
7546 #if defined(CONFIG_UNIX)
7548 * Ensure the UNIX gc is aware of our file set, so we are certain that
7549 * the io_uring can be safely unregistered on process exit, even if we have
7550 * loops in the file referencing.
7552 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7554 struct sock *sk = ctx->ring_sock->sk;
7555 struct scm_fp_list *fpl;
7556 struct sk_buff *skb;
7559 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7563 skb = alloc_skb(0, GFP_KERNEL);
7572 fpl->user = get_uid(ctx->user);
7573 for (i = 0; i < nr; i++) {
7574 struct file *file = io_file_from_index(ctx, i + offset);
7578 fpl->fp[nr_files] = get_file(file);
7579 unix_inflight(fpl->user, fpl->fp[nr_files]);
7584 fpl->max = SCM_MAX_FD;
7585 fpl->count = nr_files;
7586 UNIXCB(skb).fp = fpl;
7587 skb->destructor = unix_destruct_scm;
7588 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7589 skb_queue_head(&sk->sk_receive_queue, skb);
7591 for (i = 0; i < nr_files; i++)
7602 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7603 * causes regular reference counting to break down. We rely on the UNIX
7604 * garbage collection to take care of this problem for us.
7606 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7608 unsigned left, total;
7612 left = ctx->nr_user_files;
7614 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7616 ret = __io_sqe_files_scm(ctx, this_files, total);
7620 total += this_files;
7626 while (total < ctx->nr_user_files) {
7627 struct file *file = io_file_from_index(ctx, total);
7637 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7643 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7644 unsigned nr_tables, unsigned nr_files)
7648 for (i = 0; i < nr_tables; i++) {
7649 struct fixed_rsrc_table *table = &file_data->table[i];
7650 unsigned this_files;
7652 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7653 table->files = kcalloc(this_files, sizeof(struct file *),
7657 nr_files -= this_files;
7663 for (i = 0; i < nr_tables; i++) {
7664 struct fixed_rsrc_table *table = &file_data->table[i];
7665 kfree(table->files);
7670 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7672 struct file *file = prsrc->file;
7673 #if defined(CONFIG_UNIX)
7674 struct sock *sock = ctx->ring_sock->sk;
7675 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7676 struct sk_buff *skb;
7679 __skb_queue_head_init(&list);
7682 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7683 * remove this entry and rearrange the file array.
7685 skb = skb_dequeue(head);
7687 struct scm_fp_list *fp;
7689 fp = UNIXCB(skb).fp;
7690 for (i = 0; i < fp->count; i++) {
7693 if (fp->fp[i] != file)
7696 unix_notinflight(fp->user, fp->fp[i]);
7697 left = fp->count - 1 - i;
7699 memmove(&fp->fp[i], &fp->fp[i + 1],
7700 left * sizeof(struct file *));
7707 __skb_queue_tail(&list, skb);
7717 __skb_queue_tail(&list, skb);
7719 skb = skb_dequeue(head);
7722 if (skb_peek(&list)) {
7723 spin_lock_irq(&head->lock);
7724 while ((skb = __skb_dequeue(&list)) != NULL)
7725 __skb_queue_tail(head, skb);
7726 spin_unlock_irq(&head->lock);
7733 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7735 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7736 struct io_ring_ctx *ctx = rsrc_data->ctx;
7737 struct io_rsrc_put *prsrc, *tmp;
7739 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7740 list_del(&prsrc->list);
7741 ref_node->rsrc_put(ctx, prsrc);
7745 percpu_ref_exit(&ref_node->refs);
7747 percpu_ref_put(&rsrc_data->refs);
7750 static void io_rsrc_put_work(struct work_struct *work)
7752 struct io_ring_ctx *ctx;
7753 struct llist_node *node;
7755 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7756 node = llist_del_all(&ctx->rsrc_put_llist);
7759 struct fixed_rsrc_ref_node *ref_node;
7760 struct llist_node *next = node->next;
7762 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7763 __io_rsrc_put_work(ref_node);
7768 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7771 struct fixed_rsrc_table *table;
7773 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7774 return &table->files[i & IORING_FILE_TABLE_MASK];
7777 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7779 struct fixed_rsrc_ref_node *ref_node;
7780 struct fixed_rsrc_data *data;
7781 struct io_ring_ctx *ctx;
7782 bool first_add = false;
7785 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7786 data = ref_node->rsrc_data;
7789 io_rsrc_ref_lock(ctx);
7790 ref_node->done = true;
7792 while (!list_empty(&ctx->rsrc_ref_list)) {
7793 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7794 struct fixed_rsrc_ref_node, node);
7795 /* recycle ref nodes in order */
7796 if (!ref_node->done)
7798 list_del(&ref_node->node);
7799 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7801 io_rsrc_ref_unlock(ctx);
7803 if (percpu_ref_is_dying(&data->refs))
7807 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7809 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7812 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7813 struct io_ring_ctx *ctx)
7815 struct fixed_rsrc_ref_node *ref_node;
7817 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7821 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7826 INIT_LIST_HEAD(&ref_node->node);
7827 INIT_LIST_HEAD(&ref_node->rsrc_list);
7828 ref_node->done = false;
7832 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7833 struct fixed_rsrc_ref_node *ref_node)
7835 ref_node->rsrc_data = ctx->file_data;
7836 ref_node->rsrc_put = io_ring_file_put;
7839 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7841 percpu_ref_exit(&ref_node->refs);
7846 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7849 __s32 __user *fds = (__s32 __user *) arg;
7850 unsigned nr_tables, i;
7852 int fd, ret = -ENOMEM;
7853 struct fixed_rsrc_ref_node *ref_node;
7854 struct fixed_rsrc_data *file_data;
7860 if (nr_args > IORING_MAX_FIXED_FILES)
7863 file_data = alloc_fixed_rsrc_data(ctx);
7866 ctx->file_data = file_data;
7868 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7869 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7871 if (!file_data->table)
7874 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7877 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7878 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7882 /* allow sparse sets */
7892 * Don't allow io_uring instances to be registered. If UNIX
7893 * isn't enabled, then this causes a reference cycle and this
7894 * instance can never get freed. If UNIX is enabled we'll
7895 * handle it just fine, but there's still no point in allowing
7896 * a ring fd as it doesn't support regular read/write anyway.
7898 if (file->f_op == &io_uring_fops) {
7902 *io_fixed_file_slot(file_data, i) = file;
7905 ret = io_sqe_files_scm(ctx);
7907 io_sqe_files_unregister(ctx);
7911 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7913 io_sqe_files_unregister(ctx);
7916 init_fixed_file_ref_node(ctx, ref_node);
7918 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7921 for (i = 0; i < ctx->nr_user_files; i++) {
7922 file = io_file_from_index(ctx, i);
7926 for (i = 0; i < nr_tables; i++)
7927 kfree(file_data->table[i].files);
7928 ctx->nr_user_files = 0;
7930 free_fixed_rsrc_data(ctx->file_data);
7931 ctx->file_data = NULL;
7935 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7938 #if defined(CONFIG_UNIX)
7939 struct sock *sock = ctx->ring_sock->sk;
7940 struct sk_buff_head *head = &sock->sk_receive_queue;
7941 struct sk_buff *skb;
7944 * See if we can merge this file into an existing skb SCM_RIGHTS
7945 * file set. If there's no room, fall back to allocating a new skb
7946 * and filling it in.
7948 spin_lock_irq(&head->lock);
7949 skb = skb_peek(head);
7951 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7953 if (fpl->count < SCM_MAX_FD) {
7954 __skb_unlink(skb, head);
7955 spin_unlock_irq(&head->lock);
7956 fpl->fp[fpl->count] = get_file(file);
7957 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7959 spin_lock_irq(&head->lock);
7960 __skb_queue_head(head, skb);
7965 spin_unlock_irq(&head->lock);
7972 return __io_sqe_files_scm(ctx, 1, index);
7978 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7980 struct io_rsrc_put *prsrc;
7981 struct fixed_rsrc_ref_node *ref_node = data->node;
7983 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7988 list_add(&prsrc->list, &ref_node->rsrc_list);
7993 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7996 return io_queue_rsrc_removal(data, (void *)file);
7999 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8000 struct io_uring_rsrc_update *up,
8003 struct fixed_rsrc_data *data = ctx->file_data;
8004 struct fixed_rsrc_ref_node *ref_node;
8005 struct file *file, **file_slot;
8009 bool needs_switch = false;
8011 if (check_add_overflow(up->offset, nr_args, &done))
8013 if (done > ctx->nr_user_files)
8016 ref_node = alloc_fixed_rsrc_ref_node(ctx);
8019 init_fixed_file_ref_node(ctx, ref_node);
8021 fds = u64_to_user_ptr(up->data);
8022 for (done = 0; done < nr_args; done++) {
8024 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
8028 if (fd == IORING_REGISTER_FILES_SKIP)
8031 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8032 file_slot = io_fixed_file_slot(ctx->file_data, i);
8035 err = io_queue_file_removal(data, *file_slot);
8039 needs_switch = true;
8048 * Don't allow io_uring instances to be registered. If
8049 * UNIX isn't enabled, then this causes a reference
8050 * cycle and this instance can never get freed. If UNIX
8051 * is enabled we'll handle it just fine, but there's
8052 * still no point in allowing a ring fd as it doesn't
8053 * support regular read/write anyway.
8055 if (file->f_op == &io_uring_fops) {
8061 err = io_sqe_file_register(ctx, file, i);
8071 percpu_ref_kill(&data->node->refs);
8072 io_sqe_rsrc_set_node(ctx, data, ref_node);
8074 destroy_fixed_rsrc_ref_node(ref_node);
8076 return done ? done : err;
8079 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
8082 struct io_uring_rsrc_update up;
8084 if (!ctx->file_data)
8088 if (copy_from_user(&up, arg, sizeof(up)))
8093 return __io_sqe_files_update(ctx, &up, nr_args);
8096 static struct io_wq_work *io_free_work(struct io_wq_work *work)
8098 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8100 req = io_put_req_find_next(req);
8101 return req ? &req->work : NULL;
8104 static int io_init_wq_offload(struct io_ring_ctx *ctx,
8105 struct io_uring_params *p)
8107 struct io_wq_data data;
8109 struct io_ring_ctx *ctx_attach;
8110 unsigned int concurrency;
8113 data.user = ctx->user;
8114 data.free_work = io_free_work;
8115 data.do_work = io_wq_submit_work;
8117 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
8118 /* Do QD, or 4 * CPUS, whatever is smallest */
8119 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8121 ctx->io_wq = io_wq_create(concurrency, &data);
8122 if (IS_ERR(ctx->io_wq)) {
8123 ret = PTR_ERR(ctx->io_wq);
8129 f = fdget(p->wq_fd);
8133 if (f.file->f_op != &io_uring_fops) {
8138 ctx_attach = f.file->private_data;
8139 /* @io_wq is protected by holding the fd */
8140 if (!io_wq_get(ctx_attach->io_wq, &data)) {
8145 ctx->io_wq = ctx_attach->io_wq;
8151 static int io_uring_alloc_task_context(struct task_struct *task)
8153 struct io_uring_task *tctx;
8156 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
8157 if (unlikely(!tctx))
8160 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8161 if (unlikely(ret)) {
8167 init_waitqueue_head(&tctx->wait);
8169 atomic_set(&tctx->in_idle, 0);
8170 tctx->sqpoll = false;
8171 io_init_identity(&tctx->__identity);
8172 tctx->identity = &tctx->__identity;
8173 task->io_uring = tctx;
8174 spin_lock_init(&tctx->task_lock);
8175 INIT_WQ_LIST(&tctx->task_list);
8176 tctx->task_state = 0;
8177 init_task_work(&tctx->task_work, tctx_task_work);
8181 void __io_uring_free(struct task_struct *tsk)
8183 struct io_uring_task *tctx = tsk->io_uring;
8185 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8186 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
8187 if (tctx->identity != &tctx->__identity)
8188 kfree(tctx->identity);
8189 percpu_counter_destroy(&tctx->inflight);
8191 tsk->io_uring = NULL;
8194 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8195 struct io_uring_params *p)
8199 if (ctx->flags & IORING_SETUP_SQPOLL) {
8200 struct io_sq_data *sqd;
8203 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
8206 sqd = io_get_sq_data(p);
8213 io_sq_thread_park(sqd);
8214 mutex_lock(&sqd->ctx_lock);
8215 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
8216 mutex_unlock(&sqd->ctx_lock);
8217 io_sq_thread_unpark(sqd);
8219 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8220 if (!ctx->sq_thread_idle)
8221 ctx->sq_thread_idle = HZ;
8226 if (p->flags & IORING_SETUP_SQ_AFF) {
8227 int cpu = p->sq_thread_cpu;
8230 if (cpu >= nr_cpu_ids)
8232 if (!cpu_online(cpu))
8235 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8236 cpu, "io_uring-sq");
8238 sqd->thread = kthread_create(io_sq_thread, sqd,
8241 if (IS_ERR(sqd->thread)) {
8242 ret = PTR_ERR(sqd->thread);
8246 ret = io_uring_alloc_task_context(sqd->thread);
8249 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8250 /* Can't have SQ_AFF without SQPOLL */
8256 ret = io_init_wq_offload(ctx, p);
8262 io_finish_async(ctx);
8266 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8268 struct io_sq_data *sqd = ctx->sq_data;
8270 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8271 wake_up_process(sqd->thread);
8274 static inline void __io_unaccount_mem(struct user_struct *user,
8275 unsigned long nr_pages)
8277 atomic_long_sub(nr_pages, &user->locked_vm);
8280 static inline int __io_account_mem(struct user_struct *user,
8281 unsigned long nr_pages)
8283 unsigned long page_limit, cur_pages, new_pages;
8285 /* Don't allow more pages than we can safely lock */
8286 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8289 cur_pages = atomic_long_read(&user->locked_vm);
8290 new_pages = cur_pages + nr_pages;
8291 if (new_pages > page_limit)
8293 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8294 new_pages) != cur_pages);
8299 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8302 __io_unaccount_mem(ctx->user, nr_pages);
8304 if (ctx->mm_account)
8305 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8308 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8312 if (ctx->limit_mem) {
8313 ret = __io_account_mem(ctx->user, nr_pages);
8318 if (ctx->mm_account)
8319 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8324 static void io_mem_free(void *ptr)
8331 page = virt_to_head_page(ptr);
8332 if (put_page_testzero(page))
8333 free_compound_page(page);
8336 static void *io_mem_alloc(size_t size)
8338 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8339 __GFP_NORETRY | __GFP_ACCOUNT;
8341 return (void *) __get_free_pages(gfp_flags, get_order(size));
8344 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8347 struct io_rings *rings;
8348 size_t off, sq_array_size;
8350 off = struct_size(rings, cqes, cq_entries);
8351 if (off == SIZE_MAX)
8355 off = ALIGN(off, SMP_CACHE_BYTES);
8363 sq_array_size = array_size(sizeof(u32), sq_entries);
8364 if (sq_array_size == SIZE_MAX)
8367 if (check_add_overflow(off, sq_array_size, &off))
8373 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8377 if (!ctx->user_bufs)
8380 for (i = 0; i < ctx->nr_user_bufs; i++) {
8381 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8383 for (j = 0; j < imu->nr_bvecs; j++)
8384 unpin_user_page(imu->bvec[j].bv_page);
8386 if (imu->acct_pages)
8387 io_unaccount_mem(ctx, imu->acct_pages);
8392 kfree(ctx->user_bufs);
8393 ctx->user_bufs = NULL;
8394 ctx->nr_user_bufs = 0;
8398 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8399 void __user *arg, unsigned index)
8401 struct iovec __user *src;
8403 #ifdef CONFIG_COMPAT
8405 struct compat_iovec __user *ciovs;
8406 struct compat_iovec ciov;
8408 ciovs = (struct compat_iovec __user *) arg;
8409 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8412 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8413 dst->iov_len = ciov.iov_len;
8417 src = (struct iovec __user *) arg;
8418 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8424 * Not super efficient, but this is just a registration time. And we do cache
8425 * the last compound head, so generally we'll only do a full search if we don't
8428 * We check if the given compound head page has already been accounted, to
8429 * avoid double accounting it. This allows us to account the full size of the
8430 * page, not just the constituent pages of a huge page.
8432 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8433 int nr_pages, struct page *hpage)
8437 /* check current page array */
8438 for (i = 0; i < nr_pages; i++) {
8439 if (!PageCompound(pages[i]))
8441 if (compound_head(pages[i]) == hpage)
8445 /* check previously registered pages */
8446 for (i = 0; i < ctx->nr_user_bufs; i++) {
8447 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8449 for (j = 0; j < imu->nr_bvecs; j++) {
8450 if (!PageCompound(imu->bvec[j].bv_page))
8452 if (compound_head(imu->bvec[j].bv_page) == hpage)
8460 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8461 int nr_pages, struct io_mapped_ubuf *imu,
8462 struct page **last_hpage)
8466 for (i = 0; i < nr_pages; i++) {
8467 if (!PageCompound(pages[i])) {
8472 hpage = compound_head(pages[i]);
8473 if (hpage == *last_hpage)
8475 *last_hpage = hpage;
8476 if (headpage_already_acct(ctx, pages, i, hpage))
8478 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8482 if (!imu->acct_pages)
8485 ret = io_account_mem(ctx, imu->acct_pages);
8487 imu->acct_pages = 0;
8491 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8492 struct io_mapped_ubuf *imu,
8493 struct page **last_hpage)
8495 struct vm_area_struct **vmas = NULL;
8496 struct page **pages = NULL;
8497 unsigned long off, start, end, ubuf;
8499 int ret, pret, nr_pages, i;
8501 ubuf = (unsigned long) iov->iov_base;
8502 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8503 start = ubuf >> PAGE_SHIFT;
8504 nr_pages = end - start;
8508 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8512 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8517 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8523 mmap_read_lock(current->mm);
8524 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8526 if (pret == nr_pages) {
8527 /* don't support file backed memory */
8528 for (i = 0; i < nr_pages; i++) {
8529 struct vm_area_struct *vma = vmas[i];
8532 !is_file_hugepages(vma->vm_file)) {
8538 ret = pret < 0 ? pret : -EFAULT;
8540 mmap_read_unlock(current->mm);
8543 * if we did partial map, or found file backed vmas,
8544 * release any pages we did get
8547 unpin_user_pages(pages, pret);
8552 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8554 unpin_user_pages(pages, pret);
8559 off = ubuf & ~PAGE_MASK;
8560 size = iov->iov_len;
8561 for (i = 0; i < nr_pages; i++) {
8564 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8565 imu->bvec[i].bv_page = pages[i];
8566 imu->bvec[i].bv_len = vec_len;
8567 imu->bvec[i].bv_offset = off;
8571 /* store original address for later verification */
8573 imu->len = iov->iov_len;
8574 imu->nr_bvecs = nr_pages;
8582 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8586 if (!nr_args || nr_args > UIO_MAXIOV)
8589 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8591 if (!ctx->user_bufs)
8597 static int io_buffer_validate(struct iovec *iov)
8600 * Don't impose further limits on the size and buffer
8601 * constraints here, we'll -EINVAL later when IO is
8602 * submitted if they are wrong.
8604 if (!iov->iov_base || !iov->iov_len)
8607 /* arbitrary limit, but we need something */
8608 if (iov->iov_len > SZ_1G)
8614 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8615 unsigned int nr_args)
8619 struct page *last_hpage = NULL;
8621 ret = io_buffers_map_alloc(ctx, nr_args);
8625 for (i = 0; i < nr_args; i++) {
8626 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8628 ret = io_copy_iov(ctx, &iov, arg, i);
8632 ret = io_buffer_validate(&iov);
8636 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8640 ctx->nr_user_bufs++;
8644 io_sqe_buffers_unregister(ctx);
8649 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8651 __s32 __user *fds = arg;
8657 if (copy_from_user(&fd, fds, sizeof(*fds)))
8660 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8661 if (IS_ERR(ctx->cq_ev_fd)) {
8662 int ret = PTR_ERR(ctx->cq_ev_fd);
8663 ctx->cq_ev_fd = NULL;
8670 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8672 if (ctx->cq_ev_fd) {
8673 eventfd_ctx_put(ctx->cq_ev_fd);
8674 ctx->cq_ev_fd = NULL;
8681 static int __io_destroy_buffers(int id, void *p, void *data)
8683 struct io_ring_ctx *ctx = data;
8684 struct io_buffer *buf = p;
8686 __io_remove_buffers(ctx, buf, id, -1U);
8690 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8692 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8693 idr_destroy(&ctx->io_buffer_idr);
8696 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8698 struct io_kiocb *req, *nxt;
8700 list_for_each_entry_safe(req, nxt, list, compl.list) {
8701 if (tsk && req->task != tsk)
8703 list_del(&req->compl.list);
8704 kmem_cache_free(req_cachep, req);
8708 static void io_req_caches_free(struct io_ring_ctx *ctx, struct task_struct *tsk)
8710 struct io_submit_state *submit_state = &ctx->submit_state;
8711 struct io_comp_state *cs = &ctx->submit_state.comp;
8713 mutex_lock(&ctx->uring_lock);
8715 if (submit_state->free_reqs) {
8716 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8717 submit_state->reqs);
8718 submit_state->free_reqs = 0;
8721 spin_lock_irq(&ctx->completion_lock);
8722 list_splice_init(&cs->locked_free_list, &cs->free_list);
8723 cs->locked_free_nr = 0;
8724 spin_unlock_irq(&ctx->completion_lock);
8726 io_req_cache_free(&cs->free_list, NULL);
8728 mutex_unlock(&ctx->uring_lock);
8731 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8734 * Some may use context even when all refs and requests have been put,
8735 * and they are free to do so while still holding uring_lock, see
8736 * __io_req_task_submit(). Wait for them to finish.
8738 mutex_lock(&ctx->uring_lock);
8739 mutex_unlock(&ctx->uring_lock);
8741 io_finish_async(ctx);
8742 io_sqe_buffers_unregister(ctx);
8744 if (ctx->sqo_task) {
8745 put_task_struct(ctx->sqo_task);
8746 ctx->sqo_task = NULL;
8747 mmdrop(ctx->mm_account);
8748 ctx->mm_account = NULL;
8751 #ifdef CONFIG_BLK_CGROUP
8752 if (ctx->sqo_blkcg_css)
8753 css_put(ctx->sqo_blkcg_css);
8756 mutex_lock(&ctx->uring_lock);
8757 io_sqe_files_unregister(ctx);
8758 mutex_unlock(&ctx->uring_lock);
8759 io_eventfd_unregister(ctx);
8760 io_destroy_buffers(ctx);
8761 idr_destroy(&ctx->personality_idr);
8763 #if defined(CONFIG_UNIX)
8764 if (ctx->ring_sock) {
8765 ctx->ring_sock->file = NULL; /* so that iput() is called */
8766 sock_release(ctx->ring_sock);
8770 io_mem_free(ctx->rings);
8771 io_mem_free(ctx->sq_sqes);
8773 percpu_ref_exit(&ctx->refs);
8774 free_uid(ctx->user);
8775 put_cred(ctx->creds);
8776 io_req_caches_free(ctx, NULL);
8777 kfree(ctx->cancel_hash);
8781 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8783 struct io_ring_ctx *ctx = file->private_data;
8786 poll_wait(file, &ctx->cq_wait, wait);
8788 * synchronizes with barrier from wq_has_sleeper call in
8792 if (!io_sqring_full(ctx))
8793 mask |= EPOLLOUT | EPOLLWRNORM;
8796 * Don't flush cqring overflow list here, just do a simple check.
8797 * Otherwise there could possible be ABBA deadlock:
8800 * lock(&ctx->uring_lock);
8802 * lock(&ctx->uring_lock);
8805 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8806 * pushs them to do the flush.
8808 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8809 mask |= EPOLLIN | EPOLLRDNORM;
8814 static int io_uring_fasync(int fd, struct file *file, int on)
8816 struct io_ring_ctx *ctx = file->private_data;
8818 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8821 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8823 struct io_identity *iod;
8825 iod = idr_remove(&ctx->personality_idr, id);
8827 put_cred(iod->creds);
8828 if (refcount_dec_and_test(&iod->count))
8836 static int io_remove_personalities(int id, void *p, void *data)
8838 struct io_ring_ctx *ctx = data;
8840 io_unregister_personality(ctx, id);
8844 static void io_ring_exit_work(struct work_struct *work)
8846 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8850 * If we're doing polled IO and end up having requests being
8851 * submitted async (out-of-line), then completions can come in while
8852 * we're waiting for refs to drop. We need to reap these manually,
8853 * as nobody else will be looking for them.
8856 io_uring_try_cancel_requests(ctx, NULL, NULL);
8857 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8858 io_ring_ctx_free(ctx);
8861 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8863 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8865 return req->ctx == data;
8868 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8870 mutex_lock(&ctx->uring_lock);
8871 percpu_ref_kill(&ctx->refs);
8873 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8876 /* if force is set, the ring is going away. always drop after that */
8877 ctx->cq_overflow_flushed = 1;
8879 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8880 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8881 mutex_unlock(&ctx->uring_lock);
8883 io_kill_timeouts(ctx, NULL, NULL);
8884 io_poll_remove_all(ctx, NULL, NULL);
8887 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8889 /* if we failed setting up the ctx, we might not have any rings */
8890 io_iopoll_try_reap_events(ctx);
8892 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8894 * Use system_unbound_wq to avoid spawning tons of event kworkers
8895 * if we're exiting a ton of rings at the same time. It just adds
8896 * noise and overhead, there's no discernable change in runtime
8897 * over using system_wq.
8899 queue_work(system_unbound_wq, &ctx->exit_work);
8902 static int io_uring_release(struct inode *inode, struct file *file)
8904 struct io_ring_ctx *ctx = file->private_data;
8906 file->private_data = NULL;
8907 io_ring_ctx_wait_and_kill(ctx);
8911 struct io_task_cancel {
8912 struct task_struct *task;
8913 struct files_struct *files;
8916 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8918 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8919 struct io_task_cancel *cancel = data;
8922 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8923 unsigned long flags;
8924 struct io_ring_ctx *ctx = req->ctx;
8926 /* protect against races with linked timeouts */
8927 spin_lock_irqsave(&ctx->completion_lock, flags);
8928 ret = io_match_task(req, cancel->task, cancel->files);
8929 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8931 ret = io_match_task(req, cancel->task, cancel->files);
8936 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8937 struct task_struct *task,
8938 struct files_struct *files)
8940 struct io_defer_entry *de = NULL;
8943 spin_lock_irq(&ctx->completion_lock);
8944 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8945 if (io_match_task(de->req, task, files)) {
8946 list_cut_position(&list, &ctx->defer_list, &de->list);
8950 spin_unlock_irq(&ctx->completion_lock);
8952 while (!list_empty(&list)) {
8953 de = list_first_entry(&list, struct io_defer_entry, list);
8954 list_del_init(&de->list);
8955 req_set_fail_links(de->req);
8956 io_put_req(de->req);
8957 io_req_complete(de->req, -ECANCELED);
8962 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8963 struct task_struct *task,
8964 struct files_struct *files)
8966 struct io_task_cancel cancel = { .task = task, .files = files, };
8969 enum io_wq_cancel cret;
8973 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb,
8975 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8978 /* SQPOLL thread does its own polling */
8979 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8980 while (!list_empty_careful(&ctx->iopoll_list)) {
8981 io_iopoll_try_reap_events(ctx);
8986 ret |= io_poll_remove_all(ctx, task, files);
8987 ret |= io_kill_timeouts(ctx, task, files);
8988 ret |= io_run_task_work();
8989 io_cqring_overflow_flush(ctx, true, task, files);
8996 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8997 struct task_struct *task,
8998 struct files_struct *files)
9000 struct io_kiocb *req;
9003 spin_lock_irq(&ctx->inflight_lock);
9004 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
9005 cnt += io_match_task(req, task, files);
9006 spin_unlock_irq(&ctx->inflight_lock);
9010 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
9011 struct task_struct *task,
9012 struct files_struct *files)
9014 while (!list_empty_careful(&ctx->inflight_list)) {
9018 inflight = io_uring_count_inflight(ctx, task, files);
9022 io_uring_try_cancel_requests(ctx, task, files);
9025 io_sq_thread_unpark(ctx->sq_data);
9026 prepare_to_wait(&task->io_uring->wait, &wait,
9027 TASK_UNINTERRUPTIBLE);
9028 if (inflight == io_uring_count_inflight(ctx, task, files))
9030 finish_wait(&task->io_uring->wait, &wait);
9032 io_sq_thread_park(ctx->sq_data);
9036 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
9038 mutex_lock(&ctx->uring_lock);
9040 mutex_unlock(&ctx->uring_lock);
9042 /* make sure callers enter the ring to get error */
9044 io_ring_set_wakeup_flag(ctx);
9048 * We need to iteratively cancel requests, in case a request has dependent
9049 * hard links. These persist even for failure of cancelations, hence keep
9050 * looping until none are found.
9052 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
9053 struct files_struct *files)
9055 struct task_struct *task = current;
9057 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9058 io_disable_sqo_submit(ctx);
9059 task = ctx->sq_data->thread;
9060 atomic_inc(&task->io_uring->in_idle);
9061 io_sq_thread_park(ctx->sq_data);
9064 io_cancel_defer_files(ctx, task, files);
9066 io_uring_cancel_files(ctx, task, files);
9068 io_uring_try_cancel_requests(ctx, task, NULL);
9070 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9071 atomic_dec(&task->io_uring->in_idle);
9073 * If the files that are going away are the ones in the thread
9074 * identity, clear them out.
9076 if (task->io_uring->identity->files == files)
9077 task->io_uring->identity->files = NULL;
9078 io_sq_thread_unpark(ctx->sq_data);
9083 * Note that this task has used io_uring. We use it for cancelation purposes.
9085 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
9087 struct io_uring_task *tctx = current->io_uring;
9090 if (unlikely(!tctx)) {
9091 ret = io_uring_alloc_task_context(current);
9094 tctx = current->io_uring;
9096 if (tctx->last != file) {
9097 void *old = xa_load(&tctx->xa, (unsigned long)file);
9101 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
9108 /* one and only SQPOLL file note, held by sqo_task */
9109 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
9110 current != ctx->sqo_task);
9116 * This is race safe in that the task itself is doing this, hence it
9117 * cannot be going through the exit/cancel paths at the same time.
9118 * This cannot be modified while exit/cancel is running.
9120 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
9121 tctx->sqpoll = true;
9127 * Remove this io_uring_file -> task mapping.
9129 static void io_uring_del_task_file(struct file *file)
9131 struct io_uring_task *tctx = current->io_uring;
9133 if (tctx->last == file)
9135 file = xa_erase(&tctx->xa, (unsigned long)file);
9140 static void io_uring_remove_task_files(struct io_uring_task *tctx)
9143 unsigned long index;
9145 xa_for_each(&tctx->xa, index, file)
9146 io_uring_del_task_file(file);
9149 void __io_uring_files_cancel(struct files_struct *files)
9151 struct io_uring_task *tctx = current->io_uring;
9153 unsigned long index;
9155 /* make sure overflow events are dropped */
9156 atomic_inc(&tctx->in_idle);
9157 xa_for_each(&tctx->xa, index, file)
9158 io_uring_cancel_task_requests(file->private_data, files);
9159 atomic_dec(&tctx->in_idle);
9162 io_uring_remove_task_files(tctx);
9165 static s64 tctx_inflight(struct io_uring_task *tctx)
9167 return percpu_counter_sum(&tctx->inflight);
9170 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
9172 struct io_uring_task *tctx;
9178 tctx = ctx->sq_data->thread->io_uring;
9179 io_disable_sqo_submit(ctx);
9181 atomic_inc(&tctx->in_idle);
9183 /* read completions before cancelations */
9184 inflight = tctx_inflight(tctx);
9187 io_uring_cancel_task_requests(ctx, NULL);
9189 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9191 * If we've seen completions, retry without waiting. This
9192 * avoids a race where a completion comes in before we did
9193 * prepare_to_wait().
9195 if (inflight == tctx_inflight(tctx))
9197 finish_wait(&tctx->wait, &wait);
9199 atomic_dec(&tctx->in_idle);
9203 * Find any io_uring fd that this task has registered or done IO on, and cancel
9206 void __io_uring_task_cancel(void)
9208 struct io_uring_task *tctx = current->io_uring;
9212 /* make sure overflow events are dropped */
9213 atomic_inc(&tctx->in_idle);
9215 /* trigger io_disable_sqo_submit() */
9218 unsigned long index;
9220 xa_for_each(&tctx->xa, index, file)
9221 io_uring_cancel_sqpoll(file->private_data);
9225 /* read completions before cancelations */
9226 inflight = tctx_inflight(tctx);
9229 __io_uring_files_cancel(NULL);
9231 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9234 * If we've seen completions, retry without waiting. This
9235 * avoids a race where a completion comes in before we did
9236 * prepare_to_wait().
9238 if (inflight == tctx_inflight(tctx))
9240 finish_wait(&tctx->wait, &wait);
9243 atomic_dec(&tctx->in_idle);
9245 io_uring_remove_task_files(tctx);
9248 static int io_uring_flush(struct file *file, void *data)
9250 struct io_uring_task *tctx = current->io_uring;
9251 struct io_ring_ctx *ctx = file->private_data;
9253 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
9254 io_uring_cancel_task_requests(ctx, NULL);
9255 io_req_caches_free(ctx, current);
9261 /* we should have cancelled and erased it before PF_EXITING */
9262 WARN_ON_ONCE((current->flags & PF_EXITING) &&
9263 xa_load(&tctx->xa, (unsigned long)file));
9266 * fput() is pending, will be 2 if the only other ref is our potential
9267 * task file note. If the task is exiting, drop regardless of count.
9269 if (atomic_long_read(&file->f_count) != 2)
9272 if (ctx->flags & IORING_SETUP_SQPOLL) {
9273 /* there is only one file note, which is owned by sqo_task */
9274 WARN_ON_ONCE(ctx->sqo_task != current &&
9275 xa_load(&tctx->xa, (unsigned long)file));
9276 /* sqo_dead check is for when this happens after cancellation */
9277 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
9278 !xa_load(&tctx->xa, (unsigned long)file));
9280 io_disable_sqo_submit(ctx);
9283 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
9284 io_uring_del_task_file(file);
9288 static void *io_uring_validate_mmap_request(struct file *file,
9289 loff_t pgoff, size_t sz)
9291 struct io_ring_ctx *ctx = file->private_data;
9292 loff_t offset = pgoff << PAGE_SHIFT;
9297 case IORING_OFF_SQ_RING:
9298 case IORING_OFF_CQ_RING:
9301 case IORING_OFF_SQES:
9305 return ERR_PTR(-EINVAL);
9308 page = virt_to_head_page(ptr);
9309 if (sz > page_size(page))
9310 return ERR_PTR(-EINVAL);
9317 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9319 size_t sz = vma->vm_end - vma->vm_start;
9323 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9325 return PTR_ERR(ptr);
9327 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9328 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9331 #else /* !CONFIG_MMU */
9333 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9335 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9338 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9340 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9343 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9344 unsigned long addr, unsigned long len,
9345 unsigned long pgoff, unsigned long flags)
9349 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9351 return PTR_ERR(ptr);
9353 return (unsigned long) ptr;
9356 #endif /* !CONFIG_MMU */
9358 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9364 if (!io_sqring_full(ctx))
9367 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9369 if (unlikely(ctx->sqo_dead)) {
9374 if (!io_sqring_full(ctx))
9378 } while (!signal_pending(current));
9380 finish_wait(&ctx->sqo_sq_wait, &wait);
9385 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9386 struct __kernel_timespec __user **ts,
9387 const sigset_t __user **sig)
9389 struct io_uring_getevents_arg arg;
9392 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9393 * is just a pointer to the sigset_t.
9395 if (!(flags & IORING_ENTER_EXT_ARG)) {
9396 *sig = (const sigset_t __user *) argp;
9402 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9403 * timespec and sigset_t pointers if good.
9405 if (*argsz != sizeof(arg))
9407 if (copy_from_user(&arg, argp, sizeof(arg)))
9409 *sig = u64_to_user_ptr(arg.sigmask);
9410 *argsz = arg.sigmask_sz;
9411 *ts = u64_to_user_ptr(arg.ts);
9415 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9416 u32, min_complete, u32, flags, const void __user *, argp,
9419 struct io_ring_ctx *ctx;
9426 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9427 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9435 if (f.file->f_op != &io_uring_fops)
9439 ctx = f.file->private_data;
9440 if (!percpu_ref_tryget(&ctx->refs))
9444 if (ctx->flags & IORING_SETUP_R_DISABLED)
9448 * For SQ polling, the thread will do all submissions and completions.
9449 * Just return the requested submit count, and wake the thread if
9453 if (ctx->flags & IORING_SETUP_SQPOLL) {
9454 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9457 if (unlikely(ctx->sqo_dead))
9459 if (flags & IORING_ENTER_SQ_WAKEUP)
9460 wake_up(&ctx->sq_data->wait);
9461 if (flags & IORING_ENTER_SQ_WAIT) {
9462 ret = io_sqpoll_wait_sq(ctx);
9466 submitted = to_submit;
9467 } else if (to_submit) {
9468 ret = io_uring_add_task_file(ctx, f.file);
9471 mutex_lock(&ctx->uring_lock);
9472 submitted = io_submit_sqes(ctx, to_submit);
9473 mutex_unlock(&ctx->uring_lock);
9475 if (submitted != to_submit)
9478 if (flags & IORING_ENTER_GETEVENTS) {
9479 const sigset_t __user *sig;
9480 struct __kernel_timespec __user *ts;
9482 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9486 min_complete = min(min_complete, ctx->cq_entries);
9489 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9490 * space applications don't need to do io completion events
9491 * polling again, they can rely on io_sq_thread to do polling
9492 * work, which can reduce cpu usage and uring_lock contention.
9494 if (ctx->flags & IORING_SETUP_IOPOLL &&
9495 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9496 ret = io_iopoll_check(ctx, min_complete);
9498 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9503 percpu_ref_put(&ctx->refs);
9506 return submitted ? submitted : ret;
9509 #ifdef CONFIG_PROC_FS
9510 static int io_uring_show_cred(int id, void *p, void *data)
9512 struct io_identity *iod = p;
9513 const struct cred *cred = iod->creds;
9514 struct seq_file *m = data;
9515 struct user_namespace *uns = seq_user_ns(m);
9516 struct group_info *gi;
9521 seq_printf(m, "%5d\n", id);
9522 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9523 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9524 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9525 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9526 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9527 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9528 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9529 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9530 seq_puts(m, "\n\tGroups:\t");
9531 gi = cred->group_info;
9532 for (g = 0; g < gi->ngroups; g++) {
9533 seq_put_decimal_ull(m, g ? " " : "",
9534 from_kgid_munged(uns, gi->gid[g]));
9536 seq_puts(m, "\n\tCapEff:\t");
9537 cap = cred->cap_effective;
9538 CAP_FOR_EACH_U32(__capi)
9539 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9544 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9546 struct io_sq_data *sq = NULL;
9551 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9552 * since fdinfo case grabs it in the opposite direction of normal use
9553 * cases. If we fail to get the lock, we just don't iterate any
9554 * structures that could be going away outside the io_uring mutex.
9556 has_lock = mutex_trylock(&ctx->uring_lock);
9558 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9561 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9562 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9563 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9564 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9565 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9568 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9570 seq_printf(m, "%5u: <none>\n", i);
9572 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9573 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9574 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9576 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9577 (unsigned int) buf->len);
9579 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9580 seq_printf(m, "Personalities:\n");
9581 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9583 seq_printf(m, "PollList:\n");
9584 spin_lock_irq(&ctx->completion_lock);
9585 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9586 struct hlist_head *list = &ctx->cancel_hash[i];
9587 struct io_kiocb *req;
9589 hlist_for_each_entry(req, list, hash_node)
9590 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9591 req->task->task_works != NULL);
9593 spin_unlock_irq(&ctx->completion_lock);
9595 mutex_unlock(&ctx->uring_lock);
9598 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9600 struct io_ring_ctx *ctx = f->private_data;
9602 if (percpu_ref_tryget(&ctx->refs)) {
9603 __io_uring_show_fdinfo(ctx, m);
9604 percpu_ref_put(&ctx->refs);
9609 static const struct file_operations io_uring_fops = {
9610 .release = io_uring_release,
9611 .flush = io_uring_flush,
9612 .mmap = io_uring_mmap,
9614 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9615 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9617 .poll = io_uring_poll,
9618 .fasync = io_uring_fasync,
9619 #ifdef CONFIG_PROC_FS
9620 .show_fdinfo = io_uring_show_fdinfo,
9624 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9625 struct io_uring_params *p)
9627 struct io_rings *rings;
9628 size_t size, sq_array_offset;
9630 /* make sure these are sane, as we already accounted them */
9631 ctx->sq_entries = p->sq_entries;
9632 ctx->cq_entries = p->cq_entries;
9634 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9635 if (size == SIZE_MAX)
9638 rings = io_mem_alloc(size);
9643 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9644 rings->sq_ring_mask = p->sq_entries - 1;
9645 rings->cq_ring_mask = p->cq_entries - 1;
9646 rings->sq_ring_entries = p->sq_entries;
9647 rings->cq_ring_entries = p->cq_entries;
9648 ctx->sq_mask = rings->sq_ring_mask;
9649 ctx->cq_mask = rings->cq_ring_mask;
9651 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9652 if (size == SIZE_MAX) {
9653 io_mem_free(ctx->rings);
9658 ctx->sq_sqes = io_mem_alloc(size);
9659 if (!ctx->sq_sqes) {
9660 io_mem_free(ctx->rings);
9668 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9672 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9676 ret = io_uring_add_task_file(ctx, file);
9681 fd_install(fd, file);
9686 * Allocate an anonymous fd, this is what constitutes the application
9687 * visible backing of an io_uring instance. The application mmaps this
9688 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9689 * we have to tie this fd to a socket for file garbage collection purposes.
9691 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9694 #if defined(CONFIG_UNIX)
9697 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9700 return ERR_PTR(ret);
9703 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9704 O_RDWR | O_CLOEXEC);
9705 #if defined(CONFIG_UNIX)
9707 sock_release(ctx->ring_sock);
9708 ctx->ring_sock = NULL;
9710 ctx->ring_sock->file = file;
9716 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9717 struct io_uring_params __user *params)
9719 struct user_struct *user = NULL;
9720 struct io_ring_ctx *ctx;
9726 if (entries > IORING_MAX_ENTRIES) {
9727 if (!(p->flags & IORING_SETUP_CLAMP))
9729 entries = IORING_MAX_ENTRIES;
9733 * Use twice as many entries for the CQ ring. It's possible for the
9734 * application to drive a higher depth than the size of the SQ ring,
9735 * since the sqes are only used at submission time. This allows for
9736 * some flexibility in overcommitting a bit. If the application has
9737 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9738 * of CQ ring entries manually.
9740 p->sq_entries = roundup_pow_of_two(entries);
9741 if (p->flags & IORING_SETUP_CQSIZE) {
9743 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9744 * to a power-of-two, if it isn't already. We do NOT impose
9745 * any cq vs sq ring sizing.
9749 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9750 if (!(p->flags & IORING_SETUP_CLAMP))
9752 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9754 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9755 if (p->cq_entries < p->sq_entries)
9758 p->cq_entries = 2 * p->sq_entries;
9761 user = get_uid(current_user());
9763 ctx = io_ring_ctx_alloc(p);
9768 ctx->compat = in_compat_syscall();
9769 ctx->limit_mem = !capable(CAP_IPC_LOCK);
9771 ctx->creds = get_current_cred();
9773 ctx->loginuid = current->loginuid;
9774 ctx->sessionid = current->sessionid;
9776 ctx->sqo_task = get_task_struct(current);
9779 * This is just grabbed for accounting purposes. When a process exits,
9780 * the mm is exited and dropped before the files, hence we need to hang
9781 * on to this mm purely for the purposes of being able to unaccount
9782 * memory (locked/pinned vm). It's not used for anything else.
9784 mmgrab(current->mm);
9785 ctx->mm_account = current->mm;
9787 #ifdef CONFIG_BLK_CGROUP
9789 * The sq thread will belong to the original cgroup it was inited in.
9790 * If the cgroup goes offline (e.g. disabling the io controller), then
9791 * issued bios will be associated with the closest cgroup later in the
9795 ctx->sqo_blkcg_css = blkcg_css();
9796 ret = css_tryget_online(ctx->sqo_blkcg_css);
9799 /* don't init against a dying cgroup, have the user try again */
9800 ctx->sqo_blkcg_css = NULL;
9805 ret = io_allocate_scq_urings(ctx, p);
9809 ret = io_sq_offload_create(ctx, p);
9813 if (!(p->flags & IORING_SETUP_R_DISABLED))
9814 io_sq_offload_start(ctx);
9816 memset(&p->sq_off, 0, sizeof(p->sq_off));
9817 p->sq_off.head = offsetof(struct io_rings, sq.head);
9818 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9819 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9820 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9821 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9822 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9823 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9825 memset(&p->cq_off, 0, sizeof(p->cq_off));
9826 p->cq_off.head = offsetof(struct io_rings, cq.head);
9827 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9828 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9829 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9830 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9831 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9832 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9834 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9835 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9836 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9837 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9838 IORING_FEAT_EXT_ARG;
9840 if (copy_to_user(params, p, sizeof(*p))) {
9845 file = io_uring_get_file(ctx);
9847 ret = PTR_ERR(file);
9852 * Install ring fd as the very last thing, so we don't risk someone
9853 * having closed it before we finish setup
9855 ret = io_uring_install_fd(ctx, file);
9857 io_disable_sqo_submit(ctx);
9858 /* fput will clean it up */
9863 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9866 io_disable_sqo_submit(ctx);
9867 io_ring_ctx_wait_and_kill(ctx);
9872 * Sets up an aio uring context, and returns the fd. Applications asks for a
9873 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9874 * params structure passed in.
9876 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9878 struct io_uring_params p;
9881 if (copy_from_user(&p, params, sizeof(p)))
9883 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9888 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9889 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9890 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9891 IORING_SETUP_R_DISABLED))
9894 return io_uring_create(entries, &p, params);
9897 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9898 struct io_uring_params __user *, params)
9900 return io_uring_setup(entries, params);
9903 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9905 struct io_uring_probe *p;
9909 size = struct_size(p, ops, nr_args);
9910 if (size == SIZE_MAX)
9912 p = kzalloc(size, GFP_KERNEL);
9917 if (copy_from_user(p, arg, size))
9920 if (memchr_inv(p, 0, size))
9923 p->last_op = IORING_OP_LAST - 1;
9924 if (nr_args > IORING_OP_LAST)
9925 nr_args = IORING_OP_LAST;
9927 for (i = 0; i < nr_args; i++) {
9929 if (!io_op_defs[i].not_supported)
9930 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9935 if (copy_to_user(arg, p, size))
9942 static int io_register_personality(struct io_ring_ctx *ctx)
9944 struct io_identity *id;
9947 id = kmalloc(sizeof(*id), GFP_KERNEL);
9951 io_init_identity(id);
9952 id->creds = get_current_cred();
9954 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9956 put_cred(id->creds);
9962 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9963 unsigned int nr_args)
9965 struct io_uring_restriction *res;
9969 /* Restrictions allowed only if rings started disabled */
9970 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9973 /* We allow only a single restrictions registration */
9974 if (ctx->restrictions.registered)
9977 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9980 size = array_size(nr_args, sizeof(*res));
9981 if (size == SIZE_MAX)
9984 res = memdup_user(arg, size);
9986 return PTR_ERR(res);
9990 for (i = 0; i < nr_args; i++) {
9991 switch (res[i].opcode) {
9992 case IORING_RESTRICTION_REGISTER_OP:
9993 if (res[i].register_op >= IORING_REGISTER_LAST) {
9998 __set_bit(res[i].register_op,
9999 ctx->restrictions.register_op);
10001 case IORING_RESTRICTION_SQE_OP:
10002 if (res[i].sqe_op >= IORING_OP_LAST) {
10007 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10009 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10010 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10012 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10013 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10022 /* Reset all restrictions if an error happened */
10024 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10026 ctx->restrictions.registered = true;
10032 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10034 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10037 if (ctx->restrictions.registered)
10038 ctx->restricted = 1;
10040 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10042 io_sq_offload_start(ctx);
10047 static bool io_register_op_must_quiesce(int op)
10050 case IORING_UNREGISTER_FILES:
10051 case IORING_REGISTER_FILES_UPDATE:
10052 case IORING_REGISTER_PROBE:
10053 case IORING_REGISTER_PERSONALITY:
10054 case IORING_UNREGISTER_PERSONALITY:
10061 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10062 void __user *arg, unsigned nr_args)
10063 __releases(ctx->uring_lock)
10064 __acquires(ctx->uring_lock)
10069 * We're inside the ring mutex, if the ref is already dying, then
10070 * someone else killed the ctx or is already going through
10071 * io_uring_register().
10073 if (percpu_ref_is_dying(&ctx->refs))
10076 if (io_register_op_must_quiesce(opcode)) {
10077 percpu_ref_kill(&ctx->refs);
10080 * Drop uring mutex before waiting for references to exit. If
10081 * another thread is currently inside io_uring_enter() it might
10082 * need to grab the uring_lock to make progress. If we hold it
10083 * here across the drain wait, then we can deadlock. It's safe
10084 * to drop the mutex here, since no new references will come in
10085 * after we've killed the percpu ref.
10087 mutex_unlock(&ctx->uring_lock);
10089 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10092 ret = io_run_task_work_sig();
10097 mutex_lock(&ctx->uring_lock);
10099 if (ret && io_refs_resurrect(&ctx->refs, &ctx->ref_comp))
10103 if (ctx->restricted) {
10104 if (opcode >= IORING_REGISTER_LAST) {
10109 if (!test_bit(opcode, ctx->restrictions.register_op)) {
10116 case IORING_REGISTER_BUFFERS:
10117 ret = io_sqe_buffers_register(ctx, arg, nr_args);
10119 case IORING_UNREGISTER_BUFFERS:
10121 if (arg || nr_args)
10123 ret = io_sqe_buffers_unregister(ctx);
10125 case IORING_REGISTER_FILES:
10126 ret = io_sqe_files_register(ctx, arg, nr_args);
10128 case IORING_UNREGISTER_FILES:
10130 if (arg || nr_args)
10132 ret = io_sqe_files_unregister(ctx);
10134 case IORING_REGISTER_FILES_UPDATE:
10135 ret = io_sqe_files_update(ctx, arg, nr_args);
10137 case IORING_REGISTER_EVENTFD:
10138 case IORING_REGISTER_EVENTFD_ASYNC:
10142 ret = io_eventfd_register(ctx, arg);
10145 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10146 ctx->eventfd_async = 1;
10148 ctx->eventfd_async = 0;
10150 case IORING_UNREGISTER_EVENTFD:
10152 if (arg || nr_args)
10154 ret = io_eventfd_unregister(ctx);
10156 case IORING_REGISTER_PROBE:
10158 if (!arg || nr_args > 256)
10160 ret = io_probe(ctx, arg, nr_args);
10162 case IORING_REGISTER_PERSONALITY:
10164 if (arg || nr_args)
10166 ret = io_register_personality(ctx);
10168 case IORING_UNREGISTER_PERSONALITY:
10172 ret = io_unregister_personality(ctx, nr_args);
10174 case IORING_REGISTER_ENABLE_RINGS:
10176 if (arg || nr_args)
10178 ret = io_register_enable_rings(ctx);
10180 case IORING_REGISTER_RESTRICTIONS:
10181 ret = io_register_restrictions(ctx, arg, nr_args);
10189 if (io_register_op_must_quiesce(opcode)) {
10190 /* bring the ctx back to life */
10191 percpu_ref_reinit(&ctx->refs);
10192 reinit_completion(&ctx->ref_comp);
10197 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10198 void __user *, arg, unsigned int, nr_args)
10200 struct io_ring_ctx *ctx;
10209 if (f.file->f_op != &io_uring_fops)
10212 ctx = f.file->private_data;
10214 io_run_task_work();
10216 mutex_lock(&ctx->uring_lock);
10217 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10218 mutex_unlock(&ctx->uring_lock);
10219 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10220 ctx->cq_ev_fd != NULL, ret);
10226 static int __init io_uring_init(void)
10228 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10229 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10230 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10233 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10234 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10235 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10236 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10237 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10238 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10239 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10240 BUILD_BUG_SQE_ELEM(8, __u64, off);
10241 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10242 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10243 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10244 BUILD_BUG_SQE_ELEM(24, __u32, len);
10245 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10246 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10247 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10248 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10249 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10250 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10251 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10252 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10253 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10254 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10255 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10256 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10257 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10258 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10259 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10260 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10261 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10262 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10263 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10265 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10266 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10267 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10271 __initcall(io_uring_init);