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)
108 u32 head ____cacheline_aligned_in_smp;
109 u32 tail ____cacheline_aligned_in_smp;
113 * This data is shared with the application through the mmap at offsets
114 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
116 * The offsets to the member fields are published through struct
117 * io_sqring_offsets when calling io_uring_setup.
121 * Head and tail offsets into the ring; the offsets need to be
122 * masked to get valid indices.
124 * The kernel controls head of the sq ring and the tail of the cq ring,
125 * and the application controls tail of the sq ring and the head of the
128 struct io_uring sq, cq;
130 * Bitmasks to apply to head and tail offsets (constant, equals
133 u32 sq_ring_mask, cq_ring_mask;
134 /* Ring sizes (constant, power of 2) */
135 u32 sq_ring_entries, cq_ring_entries;
137 * Number of invalid entries dropped by the kernel due to
138 * invalid index stored in array
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
144 * After a new SQ head value was read by the application this
145 * counter includes all submissions that were dropped reaching
146 * the new SQ head (and possibly more).
152 * Written by the kernel, shouldn't be modified by the
155 * The application needs a full memory barrier before checking
156 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
162 * Written by the application, shouldn't be modified by the
167 * Number of completion events lost because the queue was full;
168 * this should be avoided by the application by making sure
169 * there are not more requests pending than there is space in
170 * the completion queue.
172 * Written by the kernel, shouldn't be modified by the
173 * application (i.e. get number of "new events" by comparing to
176 * As completion events come in out of order this counter is not
177 * ordered with any other data.
181 * Ring buffer of completion events.
183 * The kernel writes completion events fresh every time they are
184 * produced, so the application is allowed to modify pending
187 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
190 enum io_uring_cmd_flags {
191 IO_URING_F_NONBLOCK = 1,
192 IO_URING_F_COMPLETE_DEFER = 2,
195 struct io_mapped_ubuf {
198 struct bio_vec *bvec;
199 unsigned int nr_bvecs;
200 unsigned long acct_pages;
206 struct list_head list;
213 struct fixed_rsrc_table {
217 struct fixed_rsrc_ref_node {
218 struct percpu_ref refs;
219 struct list_head node;
220 struct list_head rsrc_list;
221 struct fixed_rsrc_data *rsrc_data;
222 void (*rsrc_put)(struct io_ring_ctx *ctx,
223 struct io_rsrc_put *prsrc);
224 struct llist_node llist;
228 struct fixed_rsrc_data {
229 struct fixed_rsrc_table *table;
230 struct io_ring_ctx *ctx;
232 struct fixed_rsrc_ref_node *node;
233 struct percpu_ref refs;
234 struct completion done;
238 struct list_head list;
244 struct io_restriction {
245 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
246 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
247 u8 sqe_flags_allowed;
248 u8 sqe_flags_required;
256 /* ctx's that are using this sqd */
257 struct list_head ctx_list;
258 struct list_head ctx_new_list;
259 struct mutex ctx_lock;
261 struct task_struct *thread;
262 struct wait_queue_head wait;
264 unsigned sq_thread_idle;
267 #define IO_IOPOLL_BATCH 8
268 #define IO_COMPL_BATCH 32
269 #define IO_REQ_CACHE_SIZE 32
270 #define IO_REQ_ALLOC_BATCH 8
272 struct io_comp_state {
273 struct io_kiocb *reqs[IO_COMPL_BATCH];
275 unsigned int locked_free_nr;
276 /* inline/task_work completion list, under ->uring_lock */
277 struct list_head free_list;
278 /* IRQ completion list, under ->completion_lock */
279 struct list_head locked_free_list;
282 struct io_submit_state {
283 struct blk_plug plug;
286 * io_kiocb alloc cache
288 void *reqs[IO_REQ_CACHE_SIZE];
289 unsigned int free_reqs;
294 * Batch completion logic
296 struct io_comp_state comp;
299 * File reference cache
303 unsigned int file_refs;
304 unsigned int ios_left;
309 struct percpu_ref refs;
310 } ____cacheline_aligned_in_smp;
314 unsigned int compat: 1;
315 unsigned int limit_mem: 1;
316 unsigned int cq_overflow_flushed: 1;
317 unsigned int drain_next: 1;
318 unsigned int eventfd_async: 1;
319 unsigned int restricted: 1;
320 unsigned int sqo_dead: 1;
323 * Ring buffer of indices into array of io_uring_sqe, which is
324 * mmapped by the application using the IORING_OFF_SQES offset.
326 * This indirection could e.g. be used to assign fixed
327 * io_uring_sqe entries to operations and only submit them to
328 * the queue when needed.
330 * The kernel modifies neither the indices array nor the entries
334 unsigned cached_sq_head;
337 unsigned sq_thread_idle;
338 unsigned cached_sq_dropped;
339 unsigned cached_cq_overflow;
340 unsigned long sq_check_overflow;
342 struct list_head defer_list;
343 struct list_head timeout_list;
344 struct list_head cq_overflow_list;
346 struct io_uring_sqe *sq_sqes;
347 } ____cacheline_aligned_in_smp;
350 struct mutex uring_lock;
351 wait_queue_head_t wait;
352 } ____cacheline_aligned_in_smp;
354 struct io_submit_state submit_state;
356 struct io_rings *rings;
362 * For SQPOLL usage - we hold a reference to the parent task, so we
363 * have access to the ->files
365 struct task_struct *sqo_task;
367 /* Only used for accounting purposes */
368 struct mm_struct *mm_account;
370 #ifdef CONFIG_BLK_CGROUP
371 struct cgroup_subsys_state *sqo_blkcg_css;
374 struct io_sq_data *sq_data; /* if using sq thread polling */
376 struct wait_queue_head sqo_sq_wait;
377 struct list_head sqd_list;
380 * If used, fixed file set. Writers must ensure that ->refs is dead,
381 * readers must ensure that ->refs is alive as long as the file* is
382 * used. Only updated through io_uring_register(2).
384 struct fixed_rsrc_data *file_data;
385 unsigned nr_user_files;
387 /* if used, fixed mapped user buffers */
388 unsigned nr_user_bufs;
389 struct io_mapped_ubuf *user_bufs;
391 struct user_struct *user;
393 const struct cred *creds;
397 unsigned int sessionid;
400 struct completion ref_comp;
401 struct completion sq_thread_comp;
403 #if defined(CONFIG_UNIX)
404 struct socket *ring_sock;
407 struct idr io_buffer_idr;
409 struct idr personality_idr;
412 unsigned cached_cq_tail;
415 atomic_t cq_timeouts;
416 unsigned cq_last_tm_flush;
417 unsigned long cq_check_overflow;
418 struct wait_queue_head cq_wait;
419 struct fasync_struct *cq_fasync;
420 struct eventfd_ctx *cq_ev_fd;
421 } ____cacheline_aligned_in_smp;
424 spinlock_t completion_lock;
427 * ->iopoll_list is protected by the ctx->uring_lock for
428 * io_uring instances that don't use IORING_SETUP_SQPOLL.
429 * For SQPOLL, only the single threaded io_sq_thread() will
430 * manipulate the list, hence no extra locking is needed there.
432 struct list_head iopoll_list;
433 struct hlist_head *cancel_hash;
434 unsigned cancel_hash_bits;
435 bool poll_multi_file;
437 spinlock_t inflight_lock;
438 struct list_head inflight_list;
439 } ____cacheline_aligned_in_smp;
441 struct delayed_work rsrc_put_work;
442 struct llist_head rsrc_put_llist;
443 struct list_head rsrc_ref_list;
444 spinlock_t rsrc_ref_lock;
446 struct io_restriction restrictions;
448 /* Keep this last, we don't need it for the fast path */
449 struct work_struct exit_work;
453 * First field must be the file pointer in all the
454 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
456 struct io_poll_iocb {
458 struct wait_queue_head *head;
462 struct wait_queue_entry wait;
465 struct io_poll_remove {
475 struct io_timeout_data {
476 struct io_kiocb *req;
477 struct hrtimer timer;
478 struct timespec64 ts;
479 enum hrtimer_mode mode;
484 struct sockaddr __user *addr;
485 int __user *addr_len;
487 unsigned long nofile;
507 struct list_head list;
508 /* head of the link, used by linked timeouts only */
509 struct io_kiocb *head;
512 struct io_timeout_rem {
517 struct timespec64 ts;
522 /* NOTE: kiocb has the file as the first member, so don't do it here */
530 struct sockaddr __user *addr;
537 struct user_msghdr __user *umsg;
543 struct io_buffer *kbuf;
549 struct filename *filename;
551 unsigned long nofile;
554 struct io_rsrc_update {
580 struct epoll_event event;
584 struct file *file_out;
585 struct file *file_in;
592 struct io_provide_buf {
606 const char __user *filename;
607 struct statx __user *buffer;
619 struct filename *oldpath;
620 struct filename *newpath;
628 struct filename *filename;
631 struct io_completion {
633 struct list_head list;
637 struct io_async_connect {
638 struct sockaddr_storage address;
641 struct io_async_msghdr {
642 struct iovec fast_iov[UIO_FASTIOV];
643 /* points to an allocated iov, if NULL we use fast_iov instead */
644 struct iovec *free_iov;
645 struct sockaddr __user *uaddr;
647 struct sockaddr_storage addr;
651 struct iovec fast_iov[UIO_FASTIOV];
652 const struct iovec *free_iovec;
653 struct iov_iter iter;
655 struct wait_page_queue wpq;
659 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
660 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
661 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
662 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
663 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
664 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
670 REQ_F_LINK_TIMEOUT_BIT,
672 REQ_F_NEED_CLEANUP_BIT,
674 REQ_F_BUFFER_SELECTED_BIT,
675 REQ_F_NO_FILE_TABLE_BIT,
676 REQ_F_WORK_INITIALIZED_BIT,
677 REQ_F_LTIMEOUT_ACTIVE_BIT,
678 REQ_F_COMPLETE_INLINE_BIT,
680 /* not a real bit, just to check we're not overflowing the space */
686 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
687 /* drain existing IO first */
688 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
690 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
691 /* doesn't sever on completion < 0 */
692 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
694 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
695 /* IOSQE_BUFFER_SELECT */
696 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
698 /* fail rest of links */
699 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
700 /* on inflight list */
701 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
702 /* read/write uses file position */
703 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
704 /* must not punt to workers */
705 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
706 /* has or had linked timeout */
707 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
709 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
711 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
712 /* already went through poll handler */
713 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
714 /* buffer already selected */
715 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
716 /* doesn't need file table for this request */
717 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
718 /* io_wq_work is initialized */
719 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
720 /* linked timeout is active, i.e. prepared by link's head */
721 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
722 /* completion is deferred through io_comp_state */
723 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
727 struct io_poll_iocb poll;
728 struct io_poll_iocb *double_poll;
731 struct io_task_work {
732 struct io_wq_work_node node;
733 task_work_func_t func;
737 * NOTE! Each of the iocb union members has the file pointer
738 * as the first entry in their struct definition. So you can
739 * access the file pointer through any of the sub-structs,
740 * or directly as just 'ki_filp' in this struct.
746 struct io_poll_iocb poll;
747 struct io_poll_remove poll_remove;
748 struct io_accept accept;
750 struct io_cancel cancel;
751 struct io_timeout timeout;
752 struct io_timeout_rem timeout_rem;
753 struct io_connect connect;
754 struct io_sr_msg sr_msg;
756 struct io_close close;
757 struct io_rsrc_update rsrc_update;
758 struct io_fadvise fadvise;
759 struct io_madvise madvise;
760 struct io_epoll epoll;
761 struct io_splice splice;
762 struct io_provide_buf pbuf;
763 struct io_statx statx;
764 struct io_shutdown shutdown;
765 struct io_rename rename;
766 struct io_unlink unlink;
767 /* use only after cleaning per-op data, see io_clean_op() */
768 struct io_completion compl;
771 /* opcode allocated if it needs to store data for async defer */
774 /* polled IO has completed */
780 struct io_ring_ctx *ctx;
783 struct task_struct *task;
786 struct io_kiocb *link;
787 struct percpu_ref *fixed_rsrc_refs;
790 * 1. used with ctx->iopoll_list with reads/writes
791 * 2. to track reqs with ->files (see io_op_def::file_table)
793 struct list_head inflight_entry;
795 struct io_task_work io_task_work;
796 struct callback_head task_work;
798 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
799 struct hlist_node hash_node;
800 struct async_poll *apoll;
801 struct io_wq_work work;
804 struct io_defer_entry {
805 struct list_head list;
806 struct io_kiocb *req;
811 /* needs req->file assigned */
812 unsigned needs_file : 1;
813 /* hash wq insertion if file is a regular file */
814 unsigned hash_reg_file : 1;
815 /* unbound wq insertion if file is a non-regular file */
816 unsigned unbound_nonreg_file : 1;
817 /* opcode is not supported by this kernel */
818 unsigned not_supported : 1;
819 /* set if opcode supports polled "wait" */
821 unsigned pollout : 1;
822 /* op supports buffer selection */
823 unsigned buffer_select : 1;
824 /* must always have async data allocated */
825 unsigned needs_async_data : 1;
826 /* should block plug */
828 /* size of async data needed, if any */
829 unsigned short async_size;
833 static const struct io_op_def io_op_defs[] = {
834 [IORING_OP_NOP] = {},
835 [IORING_OP_READV] = {
837 .unbound_nonreg_file = 1,
840 .needs_async_data = 1,
842 .async_size = sizeof(struct io_async_rw),
843 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
845 [IORING_OP_WRITEV] = {
848 .unbound_nonreg_file = 1,
850 .needs_async_data = 1,
852 .async_size = sizeof(struct io_async_rw),
853 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
856 [IORING_OP_FSYNC] = {
858 .work_flags = IO_WQ_WORK_BLKCG,
860 [IORING_OP_READ_FIXED] = {
862 .unbound_nonreg_file = 1,
865 .async_size = sizeof(struct io_async_rw),
866 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
868 [IORING_OP_WRITE_FIXED] = {
871 .unbound_nonreg_file = 1,
874 .async_size = sizeof(struct io_async_rw),
875 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
878 [IORING_OP_POLL_ADD] = {
880 .unbound_nonreg_file = 1,
882 [IORING_OP_POLL_REMOVE] = {},
883 [IORING_OP_SYNC_FILE_RANGE] = {
885 .work_flags = IO_WQ_WORK_BLKCG,
887 [IORING_OP_SENDMSG] = {
889 .unbound_nonreg_file = 1,
891 .needs_async_data = 1,
892 .async_size = sizeof(struct io_async_msghdr),
893 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
895 [IORING_OP_RECVMSG] = {
897 .unbound_nonreg_file = 1,
900 .needs_async_data = 1,
901 .async_size = sizeof(struct io_async_msghdr),
902 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
904 [IORING_OP_TIMEOUT] = {
905 .needs_async_data = 1,
906 .async_size = sizeof(struct io_timeout_data),
907 .work_flags = IO_WQ_WORK_MM,
909 [IORING_OP_TIMEOUT_REMOVE] = {
910 /* used by timeout updates' prep() */
911 .work_flags = IO_WQ_WORK_MM,
913 [IORING_OP_ACCEPT] = {
915 .unbound_nonreg_file = 1,
917 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
919 [IORING_OP_ASYNC_CANCEL] = {},
920 [IORING_OP_LINK_TIMEOUT] = {
921 .needs_async_data = 1,
922 .async_size = sizeof(struct io_timeout_data),
923 .work_flags = IO_WQ_WORK_MM,
925 [IORING_OP_CONNECT] = {
927 .unbound_nonreg_file = 1,
929 .needs_async_data = 1,
930 .async_size = sizeof(struct io_async_connect),
931 .work_flags = IO_WQ_WORK_MM,
933 [IORING_OP_FALLOCATE] = {
935 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
937 [IORING_OP_OPENAT] = {
938 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
939 IO_WQ_WORK_FS | IO_WQ_WORK_MM,
941 [IORING_OP_CLOSE] = {
942 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
944 [IORING_OP_FILES_UPDATE] = {
945 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
947 [IORING_OP_STATX] = {
948 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
949 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
953 .unbound_nonreg_file = 1,
957 .async_size = sizeof(struct io_async_rw),
958 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
960 [IORING_OP_WRITE] = {
962 .unbound_nonreg_file = 1,
965 .async_size = sizeof(struct io_async_rw),
966 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
969 [IORING_OP_FADVISE] = {
971 .work_flags = IO_WQ_WORK_BLKCG,
973 [IORING_OP_MADVISE] = {
974 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
978 .unbound_nonreg_file = 1,
980 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
984 .unbound_nonreg_file = 1,
987 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
989 [IORING_OP_OPENAT2] = {
990 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
991 IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
993 [IORING_OP_EPOLL_CTL] = {
994 .unbound_nonreg_file = 1,
995 .work_flags = IO_WQ_WORK_FILES,
997 [IORING_OP_SPLICE] = {
1000 .unbound_nonreg_file = 1,
1001 .work_flags = IO_WQ_WORK_BLKCG,
1003 [IORING_OP_PROVIDE_BUFFERS] = {},
1004 [IORING_OP_REMOVE_BUFFERS] = {},
1008 .unbound_nonreg_file = 1,
1010 [IORING_OP_SHUTDOWN] = {
1013 [IORING_OP_RENAMEAT] = {
1014 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
1015 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
1017 [IORING_OP_UNLINKAT] = {
1018 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
1019 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
1023 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1024 struct task_struct *task,
1025 struct files_struct *files);
1026 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
1027 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
1028 struct io_ring_ctx *ctx);
1029 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
1030 struct fixed_rsrc_ref_node *ref_node);
1032 static bool io_rw_reissue(struct io_kiocb *req);
1033 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1034 static void io_put_req(struct io_kiocb *req);
1035 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1036 static void io_double_put_req(struct io_kiocb *req);
1037 static void io_dismantle_req(struct io_kiocb *req);
1038 static void io_put_task(struct task_struct *task, int nr);
1039 static void io_queue_next(struct io_kiocb *req);
1040 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1041 static void __io_queue_linked_timeout(struct io_kiocb *req);
1042 static void io_queue_linked_timeout(struct io_kiocb *req);
1043 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1044 struct io_uring_rsrc_update *ip,
1046 static void __io_clean_op(struct io_kiocb *req);
1047 static struct file *io_file_get(struct io_submit_state *state,
1048 struct io_kiocb *req, int fd, bool fixed);
1049 static void __io_queue_sqe(struct io_kiocb *req);
1050 static void io_rsrc_put_work(struct work_struct *work);
1052 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1053 struct iov_iter *iter, bool needs_lock);
1054 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1055 const struct iovec *fast_iov,
1056 struct iov_iter *iter, bool force);
1057 static void io_req_task_queue(struct io_kiocb *req);
1058 static void io_submit_flush_completions(struct io_comp_state *cs,
1059 struct io_ring_ctx *ctx);
1061 static struct kmem_cache *req_cachep;
1063 static const struct file_operations io_uring_fops;
1065 struct sock *io_uring_get_socket(struct file *file)
1067 #if defined(CONFIG_UNIX)
1068 if (file->f_op == &io_uring_fops) {
1069 struct io_ring_ctx *ctx = file->private_data;
1071 return ctx->ring_sock->sk;
1076 EXPORT_SYMBOL(io_uring_get_socket);
1078 #define io_for_each_link(pos, head) \
1079 for (pos = (head); pos; pos = pos->link)
1081 static inline void io_clean_op(struct io_kiocb *req)
1083 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1087 static inline void io_set_resource_node(struct io_kiocb *req)
1089 struct io_ring_ctx *ctx = req->ctx;
1091 if (!req->fixed_rsrc_refs) {
1092 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1093 percpu_ref_get(req->fixed_rsrc_refs);
1097 static bool io_match_task(struct io_kiocb *head,
1098 struct task_struct *task,
1099 struct files_struct *files)
1101 struct io_kiocb *req;
1103 if (task && head->task != task) {
1104 /* in terms of cancelation, always match if req task is dead */
1105 if (head->task->flags & PF_EXITING)
1112 io_for_each_link(req, head) {
1113 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1115 if (req->file && req->file->f_op == &io_uring_fops)
1117 if ((req->work.flags & IO_WQ_WORK_FILES) &&
1118 req->work.identity->files == files)
1124 static void io_sq_thread_drop_mm_files(void)
1126 struct files_struct *files = current->files;
1127 struct mm_struct *mm = current->mm;
1130 kthread_unuse_mm(mm);
1135 struct nsproxy *nsproxy = current->nsproxy;
1138 current->files = NULL;
1139 current->nsproxy = NULL;
1140 task_unlock(current);
1141 put_files_struct(files);
1142 put_nsproxy(nsproxy);
1146 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1148 if (!current->files) {
1149 struct files_struct *files;
1150 struct nsproxy *nsproxy;
1152 task_lock(ctx->sqo_task);
1153 files = ctx->sqo_task->files;
1155 task_unlock(ctx->sqo_task);
1158 atomic_inc(&files->count);
1159 get_nsproxy(ctx->sqo_task->nsproxy);
1160 nsproxy = ctx->sqo_task->nsproxy;
1161 task_unlock(ctx->sqo_task);
1164 current->files = files;
1165 current->nsproxy = nsproxy;
1166 task_unlock(current);
1171 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1173 struct mm_struct *mm;
1178 task_lock(ctx->sqo_task);
1179 mm = ctx->sqo_task->mm;
1180 if (unlikely(!mm || !mmget_not_zero(mm)))
1182 task_unlock(ctx->sqo_task);
1192 static int __io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1193 struct io_kiocb *req)
1195 const struct io_op_def *def = &io_op_defs[req->opcode];
1198 if (def->work_flags & IO_WQ_WORK_MM) {
1199 ret = __io_sq_thread_acquire_mm(ctx);
1204 if (def->needs_file || (def->work_flags & IO_WQ_WORK_FILES)) {
1205 ret = __io_sq_thread_acquire_files(ctx);
1213 static inline int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1214 struct io_kiocb *req)
1216 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1218 return __io_sq_thread_acquire_mm_files(ctx, req);
1221 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1222 struct cgroup_subsys_state **cur_css)
1225 #ifdef CONFIG_BLK_CGROUP
1226 /* puts the old one when swapping */
1227 if (*cur_css != ctx->sqo_blkcg_css) {
1228 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1229 *cur_css = ctx->sqo_blkcg_css;
1234 static void io_sq_thread_unassociate_blkcg(void)
1236 #ifdef CONFIG_BLK_CGROUP
1237 kthread_associate_blkcg(NULL);
1241 static inline void req_set_fail_links(struct io_kiocb *req)
1243 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1244 req->flags |= REQ_F_FAIL_LINK;
1248 * None of these are dereferenced, they are simply used to check if any of
1249 * them have changed. If we're under current and check they are still the
1250 * same, we're fine to grab references to them for actual out-of-line use.
1252 static void io_init_identity(struct io_identity *id)
1254 id->files = current->files;
1255 id->mm = current->mm;
1256 #ifdef CONFIG_BLK_CGROUP
1258 id->blkcg_css = blkcg_css();
1261 id->creds = current_cred();
1262 id->nsproxy = current->nsproxy;
1263 id->fs = current->fs;
1264 id->fsize = rlimit(RLIMIT_FSIZE);
1266 id->loginuid = current->loginuid;
1267 id->sessionid = current->sessionid;
1269 refcount_set(&id->count, 1);
1272 static inline void __io_req_init_async(struct io_kiocb *req)
1274 memset(&req->work, 0, sizeof(req->work));
1275 req->flags |= REQ_F_WORK_INITIALIZED;
1279 * Note: must call io_req_init_async() for the first time you
1280 * touch any members of io_wq_work.
1282 static inline void io_req_init_async(struct io_kiocb *req)
1284 struct io_uring_task *tctx = current->io_uring;
1286 if (req->flags & REQ_F_WORK_INITIALIZED)
1289 __io_req_init_async(req);
1291 /* Grab a ref if this isn't our static identity */
1292 req->work.identity = tctx->identity;
1293 if (tctx->identity != &tctx->__identity)
1294 refcount_inc(&req->work.identity->count);
1297 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1299 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1301 complete(&ctx->ref_comp);
1304 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1306 return !req->timeout.off;
1309 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1311 struct io_ring_ctx *ctx;
1314 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1319 * Use 5 bits less than the max cq entries, that should give us around
1320 * 32 entries per hash list if totally full and uniformly spread.
1322 hash_bits = ilog2(p->cq_entries);
1326 ctx->cancel_hash_bits = hash_bits;
1327 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1329 if (!ctx->cancel_hash)
1331 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1333 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1334 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1337 ctx->flags = p->flags;
1338 init_waitqueue_head(&ctx->sqo_sq_wait);
1339 INIT_LIST_HEAD(&ctx->sqd_list);
1340 init_waitqueue_head(&ctx->cq_wait);
1341 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1342 init_completion(&ctx->ref_comp);
1343 init_completion(&ctx->sq_thread_comp);
1344 idr_init(&ctx->io_buffer_idr);
1345 idr_init(&ctx->personality_idr);
1346 mutex_init(&ctx->uring_lock);
1347 init_waitqueue_head(&ctx->wait);
1348 spin_lock_init(&ctx->completion_lock);
1349 INIT_LIST_HEAD(&ctx->iopoll_list);
1350 INIT_LIST_HEAD(&ctx->defer_list);
1351 INIT_LIST_HEAD(&ctx->timeout_list);
1352 spin_lock_init(&ctx->inflight_lock);
1353 INIT_LIST_HEAD(&ctx->inflight_list);
1354 spin_lock_init(&ctx->rsrc_ref_lock);
1355 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1356 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1357 init_llist_head(&ctx->rsrc_put_llist);
1358 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1359 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1362 kfree(ctx->cancel_hash);
1367 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1369 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1370 struct io_ring_ctx *ctx = req->ctx;
1372 return seq != ctx->cached_cq_tail
1373 + READ_ONCE(ctx->cached_cq_overflow);
1379 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1381 if (req->work.identity == &tctx->__identity)
1383 if (refcount_dec_and_test(&req->work.identity->count))
1384 kfree(req->work.identity);
1387 static void io_req_clean_work(struct io_kiocb *req)
1389 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1392 if (req->work.flags & IO_WQ_WORK_MM)
1393 mmdrop(req->work.identity->mm);
1394 #ifdef CONFIG_BLK_CGROUP
1395 if (req->work.flags & IO_WQ_WORK_BLKCG)
1396 css_put(req->work.identity->blkcg_css);
1398 if (req->work.flags & IO_WQ_WORK_CREDS)
1399 put_cred(req->work.identity->creds);
1400 if (req->work.flags & IO_WQ_WORK_FS) {
1401 struct fs_struct *fs = req->work.identity->fs;
1403 spin_lock(&req->work.identity->fs->lock);
1406 spin_unlock(&req->work.identity->fs->lock);
1410 if (req->work.flags & IO_WQ_WORK_FILES) {
1411 put_files_struct(req->work.identity->files);
1412 put_nsproxy(req->work.identity->nsproxy);
1414 if (req->flags & REQ_F_INFLIGHT) {
1415 struct io_ring_ctx *ctx = req->ctx;
1416 struct io_uring_task *tctx = req->task->io_uring;
1417 unsigned long flags;
1419 spin_lock_irqsave(&ctx->inflight_lock, flags);
1420 list_del(&req->inflight_entry);
1421 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1422 req->flags &= ~REQ_F_INFLIGHT;
1423 if (atomic_read(&tctx->in_idle))
1424 wake_up(&tctx->wait);
1427 req->flags &= ~REQ_F_WORK_INITIALIZED;
1428 req->work.flags &= ~(IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG | IO_WQ_WORK_FS |
1429 IO_WQ_WORK_CREDS | IO_WQ_WORK_FILES);
1430 io_put_identity(req->task->io_uring, req);
1434 * Create a private copy of io_identity, since some fields don't match
1435 * the current context.
1437 static bool io_identity_cow(struct io_kiocb *req)
1439 struct io_uring_task *tctx = current->io_uring;
1440 const struct cred *creds = NULL;
1441 struct io_identity *id;
1443 if (req->work.flags & IO_WQ_WORK_CREDS)
1444 creds = req->work.identity->creds;
1446 id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1447 if (unlikely(!id)) {
1448 req->work.flags |= IO_WQ_WORK_CANCEL;
1453 * We can safely just re-init the creds we copied Either the field
1454 * matches the current one, or we haven't grabbed it yet. The only
1455 * exception is ->creds, through registered personalities, so handle
1456 * that one separately.
1458 io_init_identity(id);
1462 /* add one for this request */
1463 refcount_inc(&id->count);
1465 /* drop tctx and req identity references, if needed */
1466 if (tctx->identity != &tctx->__identity &&
1467 refcount_dec_and_test(&tctx->identity->count))
1468 kfree(tctx->identity);
1469 if (req->work.identity != &tctx->__identity &&
1470 refcount_dec_and_test(&req->work.identity->count))
1471 kfree(req->work.identity);
1473 req->work.identity = id;
1474 tctx->identity = id;
1478 static void io_req_track_inflight(struct io_kiocb *req)
1480 struct io_ring_ctx *ctx = req->ctx;
1482 if (!(req->flags & REQ_F_INFLIGHT)) {
1483 io_req_init_async(req);
1484 req->flags |= REQ_F_INFLIGHT;
1486 spin_lock_irq(&ctx->inflight_lock);
1487 list_add(&req->inflight_entry, &ctx->inflight_list);
1488 spin_unlock_irq(&ctx->inflight_lock);
1492 static bool io_grab_identity(struct io_kiocb *req)
1494 const struct io_op_def *def = &io_op_defs[req->opcode];
1495 struct io_identity *id = req->work.identity;
1497 if (def->work_flags & IO_WQ_WORK_FSIZE) {
1498 if (id->fsize != rlimit(RLIMIT_FSIZE))
1500 req->work.flags |= IO_WQ_WORK_FSIZE;
1502 #ifdef CONFIG_BLK_CGROUP
1503 if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1504 (def->work_flags & IO_WQ_WORK_BLKCG)) {
1506 if (id->blkcg_css != blkcg_css()) {
1511 * This should be rare, either the cgroup is dying or the task
1512 * is moving cgroups. Just punt to root for the handful of ios.
1514 if (css_tryget_online(id->blkcg_css))
1515 req->work.flags |= IO_WQ_WORK_BLKCG;
1519 if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1520 if (id->creds != current_cred())
1522 get_cred(id->creds);
1523 req->work.flags |= IO_WQ_WORK_CREDS;
1526 if (!uid_eq(current->loginuid, id->loginuid) ||
1527 current->sessionid != id->sessionid)
1530 if (!(req->work.flags & IO_WQ_WORK_FS) &&
1531 (def->work_flags & IO_WQ_WORK_FS)) {
1532 if (current->fs != id->fs)
1534 spin_lock(&id->fs->lock);
1535 if (!id->fs->in_exec) {
1537 req->work.flags |= IO_WQ_WORK_FS;
1539 req->work.flags |= IO_WQ_WORK_CANCEL;
1541 spin_unlock(¤t->fs->lock);
1543 if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1544 (def->work_flags & IO_WQ_WORK_FILES) &&
1545 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1546 if (id->files != current->files ||
1547 id->nsproxy != current->nsproxy)
1549 atomic_inc(&id->files->count);
1550 get_nsproxy(id->nsproxy);
1551 req->work.flags |= IO_WQ_WORK_FILES;
1552 io_req_track_inflight(req);
1554 if (!(req->work.flags & IO_WQ_WORK_MM) &&
1555 (def->work_flags & IO_WQ_WORK_MM)) {
1556 if (id->mm != current->mm)
1559 req->work.flags |= IO_WQ_WORK_MM;
1565 static void io_prep_async_work(struct io_kiocb *req)
1567 const struct io_op_def *def = &io_op_defs[req->opcode];
1568 struct io_ring_ctx *ctx = req->ctx;
1570 io_req_init_async(req);
1572 if (req->flags & REQ_F_FORCE_ASYNC)
1573 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1575 if (req->flags & REQ_F_ISREG) {
1576 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1577 io_wq_hash_work(&req->work, file_inode(req->file));
1579 if (def->unbound_nonreg_file)
1580 req->work.flags |= IO_WQ_WORK_UNBOUND;
1583 /* if we fail grabbing identity, we must COW, regrab, and retry */
1584 if (io_grab_identity(req))
1587 if (!io_identity_cow(req))
1590 /* can't fail at this point */
1591 if (!io_grab_identity(req))
1595 static void io_prep_async_link(struct io_kiocb *req)
1597 struct io_kiocb *cur;
1599 io_for_each_link(cur, req)
1600 io_prep_async_work(cur);
1603 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1605 struct io_ring_ctx *ctx = req->ctx;
1606 struct io_kiocb *link = io_prep_linked_timeout(req);
1608 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1609 &req->work, req->flags);
1610 io_wq_enqueue(ctx->io_wq, &req->work);
1614 static void io_queue_async_work(struct io_kiocb *req)
1616 struct io_kiocb *link;
1618 /* init ->work of the whole link before punting */
1619 io_prep_async_link(req);
1620 link = __io_queue_async_work(req);
1623 io_queue_linked_timeout(link);
1626 static void io_kill_timeout(struct io_kiocb *req)
1628 struct io_timeout_data *io = req->async_data;
1631 ret = hrtimer_try_to_cancel(&io->timer);
1633 atomic_set(&req->ctx->cq_timeouts,
1634 atomic_read(&req->ctx->cq_timeouts) + 1);
1635 list_del_init(&req->timeout.list);
1636 io_cqring_fill_event(req, 0);
1637 io_put_req_deferred(req, 1);
1642 * Returns true if we found and killed one or more timeouts
1644 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1645 struct files_struct *files)
1647 struct io_kiocb *req, *tmp;
1650 spin_lock_irq(&ctx->completion_lock);
1651 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1652 if (io_match_task(req, tsk, files)) {
1653 io_kill_timeout(req);
1657 spin_unlock_irq(&ctx->completion_lock);
1658 return canceled != 0;
1661 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1664 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1665 struct io_defer_entry, list);
1667 if (req_need_defer(de->req, de->seq))
1669 list_del_init(&de->list);
1670 io_req_task_queue(de->req);
1672 } while (!list_empty(&ctx->defer_list));
1675 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1679 if (list_empty(&ctx->timeout_list))
1682 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1685 u32 events_needed, events_got;
1686 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1687 struct io_kiocb, timeout.list);
1689 if (io_is_timeout_noseq(req))
1693 * Since seq can easily wrap around over time, subtract
1694 * the last seq at which timeouts were flushed before comparing.
1695 * Assuming not more than 2^31-1 events have happened since,
1696 * these subtractions won't have wrapped, so we can check if
1697 * target is in [last_seq, current_seq] by comparing the two.
1699 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1700 events_got = seq - ctx->cq_last_tm_flush;
1701 if (events_got < events_needed)
1704 list_del_init(&req->timeout.list);
1705 io_kill_timeout(req);
1706 } while (!list_empty(&ctx->timeout_list));
1708 ctx->cq_last_tm_flush = seq;
1711 static void io_commit_cqring(struct io_ring_ctx *ctx)
1713 io_flush_timeouts(ctx);
1715 /* order cqe stores with ring update */
1716 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1718 if (unlikely(!list_empty(&ctx->defer_list)))
1719 __io_queue_deferred(ctx);
1722 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1724 struct io_rings *r = ctx->rings;
1726 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1729 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1731 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1734 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1736 struct io_rings *rings = ctx->rings;
1740 * writes to the cq entry need to come after reading head; the
1741 * control dependency is enough as we're using WRITE_ONCE to
1744 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1747 tail = ctx->cached_cq_tail++;
1748 return &rings->cqes[tail & ctx->cq_mask];
1751 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1755 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1757 if (!ctx->eventfd_async)
1759 return io_wq_current_is_worker();
1762 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1764 /* see waitqueue_active() comment */
1767 if (waitqueue_active(&ctx->wait))
1768 wake_up(&ctx->wait);
1769 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1770 wake_up(&ctx->sq_data->wait);
1771 if (io_should_trigger_evfd(ctx))
1772 eventfd_signal(ctx->cq_ev_fd, 1);
1773 if (waitqueue_active(&ctx->cq_wait)) {
1774 wake_up_interruptible(&ctx->cq_wait);
1775 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1779 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1781 /* see waitqueue_active() comment */
1784 if (ctx->flags & IORING_SETUP_SQPOLL) {
1785 if (waitqueue_active(&ctx->wait))
1786 wake_up(&ctx->wait);
1788 if (io_should_trigger_evfd(ctx))
1789 eventfd_signal(ctx->cq_ev_fd, 1);
1790 if (waitqueue_active(&ctx->cq_wait)) {
1791 wake_up_interruptible(&ctx->cq_wait);
1792 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1796 /* Returns true if there are no backlogged entries after the flush */
1797 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1798 struct task_struct *tsk,
1799 struct files_struct *files)
1801 struct io_rings *rings = ctx->rings;
1802 struct io_kiocb *req, *tmp;
1803 struct io_uring_cqe *cqe;
1804 unsigned long flags;
1805 bool all_flushed, posted;
1808 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1812 spin_lock_irqsave(&ctx->completion_lock, flags);
1813 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1814 if (!io_match_task(req, tsk, files))
1817 cqe = io_get_cqring(ctx);
1821 list_move(&req->compl.list, &list);
1823 WRITE_ONCE(cqe->user_data, req->user_data);
1824 WRITE_ONCE(cqe->res, req->result);
1825 WRITE_ONCE(cqe->flags, req->compl.cflags);
1827 ctx->cached_cq_overflow++;
1828 WRITE_ONCE(ctx->rings->cq_overflow,
1829 ctx->cached_cq_overflow);
1834 all_flushed = list_empty(&ctx->cq_overflow_list);
1836 clear_bit(0, &ctx->sq_check_overflow);
1837 clear_bit(0, &ctx->cq_check_overflow);
1838 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1842 io_commit_cqring(ctx);
1843 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1845 io_cqring_ev_posted(ctx);
1847 while (!list_empty(&list)) {
1848 req = list_first_entry(&list, struct io_kiocb, compl.list);
1849 list_del(&req->compl.list);
1856 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1857 struct task_struct *tsk,
1858 struct files_struct *files)
1860 if (test_bit(0, &ctx->cq_check_overflow)) {
1861 /* iopoll syncs against uring_lock, not completion_lock */
1862 if (ctx->flags & IORING_SETUP_IOPOLL)
1863 mutex_lock(&ctx->uring_lock);
1864 __io_cqring_overflow_flush(ctx, force, tsk, files);
1865 if (ctx->flags & IORING_SETUP_IOPOLL)
1866 mutex_unlock(&ctx->uring_lock);
1870 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1872 struct io_ring_ctx *ctx = req->ctx;
1873 struct io_uring_cqe *cqe;
1875 trace_io_uring_complete(ctx, req->user_data, res);
1878 * If we can't get a cq entry, userspace overflowed the
1879 * submission (by quite a lot). Increment the overflow count in
1882 cqe = io_get_cqring(ctx);
1884 WRITE_ONCE(cqe->user_data, req->user_data);
1885 WRITE_ONCE(cqe->res, res);
1886 WRITE_ONCE(cqe->flags, cflags);
1887 } else if (ctx->cq_overflow_flushed ||
1888 atomic_read(&req->task->io_uring->in_idle)) {
1890 * If we're in ring overflow flush mode, or in task cancel mode,
1891 * then we cannot store the request for later flushing, we need
1892 * to drop it on the floor.
1894 ctx->cached_cq_overflow++;
1895 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1897 if (list_empty(&ctx->cq_overflow_list)) {
1898 set_bit(0, &ctx->sq_check_overflow);
1899 set_bit(0, &ctx->cq_check_overflow);
1900 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1904 req->compl.cflags = cflags;
1905 refcount_inc(&req->refs);
1906 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1910 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1912 __io_cqring_fill_event(req, res, 0);
1915 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1916 unsigned int cflags)
1918 struct io_ring_ctx *ctx = req->ctx;
1919 unsigned long flags;
1921 spin_lock_irqsave(&ctx->completion_lock, flags);
1922 __io_cqring_fill_event(req, res, cflags);
1923 io_commit_cqring(ctx);
1925 * If we're the last reference to this request, add to our locked
1928 if (refcount_dec_and_test(&req->refs)) {
1929 struct io_comp_state *cs = &ctx->submit_state.comp;
1931 io_dismantle_req(req);
1932 io_put_task(req->task, 1);
1933 list_add(&req->compl.list, &cs->locked_free_list);
1934 cs->locked_free_nr++;
1937 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1939 io_cqring_ev_posted(ctx);
1942 percpu_ref_put(&ctx->refs);
1946 static void io_req_complete_state(struct io_kiocb *req, long res,
1947 unsigned int cflags)
1951 req->compl.cflags = cflags;
1952 req->flags |= REQ_F_COMPLETE_INLINE;
1955 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1956 long res, unsigned cflags)
1958 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1959 io_req_complete_state(req, res, cflags);
1961 io_req_complete_post(req, res, cflags);
1964 static inline void io_req_complete(struct io_kiocb *req, long res)
1966 __io_req_complete(req, 0, res, 0);
1969 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1971 struct io_submit_state *state = &ctx->submit_state;
1972 struct io_comp_state *cs = &state->comp;
1973 struct io_kiocb *req = NULL;
1976 * If we have more than a batch's worth of requests in our IRQ side
1977 * locked cache, grab the lock and move them over to our submission
1980 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1981 spin_lock_irq(&ctx->completion_lock);
1982 list_splice_init(&cs->locked_free_list, &cs->free_list);
1983 cs->locked_free_nr = 0;
1984 spin_unlock_irq(&ctx->completion_lock);
1987 while (!list_empty(&cs->free_list)) {
1988 req = list_first_entry(&cs->free_list, struct io_kiocb,
1990 list_del(&req->compl.list);
1991 state->reqs[state->free_reqs++] = req;
1992 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1999 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2001 struct io_submit_state *state = &ctx->submit_state;
2003 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
2005 if (!state->free_reqs) {
2006 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2009 if (io_flush_cached_reqs(ctx))
2012 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
2016 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2017 * retry single alloc to be on the safe side.
2019 if (unlikely(ret <= 0)) {
2020 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2021 if (!state->reqs[0])
2025 state->free_reqs = ret;
2029 return state->reqs[state->free_reqs];
2032 static inline void io_put_file(struct io_kiocb *req, struct file *file,
2039 static void io_dismantle_req(struct io_kiocb *req)
2043 if (req->async_data)
2044 kfree(req->async_data);
2046 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
2047 if (req->fixed_rsrc_refs)
2048 percpu_ref_put(req->fixed_rsrc_refs);
2049 io_req_clean_work(req);
2052 static inline void io_put_task(struct task_struct *task, int nr)
2054 struct io_uring_task *tctx = task->io_uring;
2056 percpu_counter_sub(&tctx->inflight, nr);
2057 if (unlikely(atomic_read(&tctx->in_idle)))
2058 wake_up(&tctx->wait);
2059 put_task_struct_many(task, nr);
2062 static void __io_free_req(struct io_kiocb *req)
2064 struct io_ring_ctx *ctx = req->ctx;
2066 io_dismantle_req(req);
2067 io_put_task(req->task, 1);
2069 kmem_cache_free(req_cachep, req);
2070 percpu_ref_put(&ctx->refs);
2073 static inline void io_remove_next_linked(struct io_kiocb *req)
2075 struct io_kiocb *nxt = req->link;
2077 req->link = nxt->link;
2081 static void io_kill_linked_timeout(struct io_kiocb *req)
2083 struct io_ring_ctx *ctx = req->ctx;
2084 struct io_kiocb *link;
2085 bool cancelled = false;
2086 unsigned long flags;
2088 spin_lock_irqsave(&ctx->completion_lock, flags);
2092 * Can happen if a linked timeout fired and link had been like
2093 * req -> link t-out -> link t-out [-> ...]
2095 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
2096 struct io_timeout_data *io = link->async_data;
2099 io_remove_next_linked(req);
2100 link->timeout.head = NULL;
2101 ret = hrtimer_try_to_cancel(&io->timer);
2103 io_cqring_fill_event(link, -ECANCELED);
2104 io_commit_cqring(ctx);
2108 req->flags &= ~REQ_F_LINK_TIMEOUT;
2109 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2112 io_cqring_ev_posted(ctx);
2118 static void io_fail_links(struct io_kiocb *req)
2120 struct io_kiocb *link, *nxt;
2121 struct io_ring_ctx *ctx = req->ctx;
2122 unsigned long flags;
2124 spin_lock_irqsave(&ctx->completion_lock, flags);
2132 trace_io_uring_fail_link(req, link);
2133 io_cqring_fill_event(link, -ECANCELED);
2136 * It's ok to free under spinlock as they're not linked anymore,
2137 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
2140 if (link->flags & REQ_F_WORK_INITIALIZED)
2141 io_put_req_deferred(link, 2);
2143 io_double_put_req(link);
2146 io_commit_cqring(ctx);
2147 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2149 io_cqring_ev_posted(ctx);
2152 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2154 if (req->flags & REQ_F_LINK_TIMEOUT)
2155 io_kill_linked_timeout(req);
2158 * If LINK is set, we have dependent requests in this chain. If we
2159 * didn't fail this request, queue the first one up, moving any other
2160 * dependencies to the next request. In case of failure, fail the rest
2163 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
2164 struct io_kiocb *nxt = req->link;
2173 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2175 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2177 return __io_req_find_next(req);
2180 static bool __tctx_task_work(struct io_uring_task *tctx)
2182 struct io_ring_ctx *ctx = NULL;
2183 struct io_wq_work_list list;
2184 struct io_wq_work_node *node;
2186 if (wq_list_empty(&tctx->task_list))
2189 spin_lock(&tctx->task_lock);
2190 list = tctx->task_list;
2191 INIT_WQ_LIST(&tctx->task_list);
2192 spin_unlock(&tctx->task_lock);
2196 struct io_wq_work_node *next = node->next;
2197 struct io_ring_ctx *this_ctx;
2198 struct io_kiocb *req;
2200 req = container_of(node, struct io_kiocb, io_task_work.node);
2201 this_ctx = req->ctx;
2202 req->task_work.func(&req->task_work);
2207 } else if (ctx != this_ctx) {
2208 mutex_lock(&ctx->uring_lock);
2209 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2210 mutex_unlock(&ctx->uring_lock);
2215 if (ctx && ctx->submit_state.comp.nr) {
2216 mutex_lock(&ctx->uring_lock);
2217 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
2218 mutex_unlock(&ctx->uring_lock);
2221 return list.first != NULL;
2224 static void tctx_task_work(struct callback_head *cb)
2226 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
2228 while (__tctx_task_work(tctx))
2231 clear_bit(0, &tctx->task_state);
2234 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
2235 enum task_work_notify_mode notify)
2237 struct io_uring_task *tctx = tsk->io_uring;
2238 struct io_wq_work_node *node, *prev;
2241 WARN_ON_ONCE(!tctx);
2243 spin_lock(&tctx->task_lock);
2244 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2245 spin_unlock(&tctx->task_lock);
2247 /* task_work already pending, we're done */
2248 if (test_bit(0, &tctx->task_state) ||
2249 test_and_set_bit(0, &tctx->task_state))
2252 if (!task_work_add(tsk, &tctx->task_work, notify))
2256 * Slow path - we failed, find and delete work. if the work is not
2257 * in the list, it got run and we're fine.
2260 spin_lock(&tctx->task_lock);
2261 wq_list_for_each(node, prev, &tctx->task_list) {
2262 if (&req->io_task_work.node == node) {
2263 wq_list_del(&tctx->task_list, node, prev);
2268 spin_unlock(&tctx->task_lock);
2269 clear_bit(0, &tctx->task_state);
2273 static int io_req_task_work_add(struct io_kiocb *req)
2275 struct task_struct *tsk = req->task;
2276 struct io_ring_ctx *ctx = req->ctx;
2277 enum task_work_notify_mode notify;
2280 if (tsk->flags & PF_EXITING)
2284 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2285 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2286 * processing task_work. There's no reliable way to tell if TWA_RESUME
2290 if (!(ctx->flags & IORING_SETUP_SQPOLL))
2291 notify = TWA_SIGNAL;
2293 ret = io_task_work_add(tsk, req, notify);
2295 wake_up_process(tsk);
2300 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2301 task_work_func_t cb)
2303 struct task_struct *tsk = io_wq_get_task(req->ctx->io_wq);
2305 init_task_work(&req->task_work, cb);
2306 task_work_add(tsk, &req->task_work, TWA_NONE);
2307 wake_up_process(tsk);
2310 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2312 struct io_ring_ctx *ctx = req->ctx;
2314 spin_lock_irq(&ctx->completion_lock);
2315 io_cqring_fill_event(req, error);
2316 io_commit_cqring(ctx);
2317 spin_unlock_irq(&ctx->completion_lock);
2319 io_cqring_ev_posted(ctx);
2320 req_set_fail_links(req);
2321 io_double_put_req(req);
2324 static void io_req_task_cancel(struct callback_head *cb)
2326 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2327 struct io_ring_ctx *ctx = req->ctx;
2329 __io_req_task_cancel(req, -ECANCELED);
2330 percpu_ref_put(&ctx->refs);
2333 static void __io_req_task_submit(struct io_kiocb *req)
2335 struct io_ring_ctx *ctx = req->ctx;
2337 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2338 mutex_lock(&ctx->uring_lock);
2339 if (!ctx->sqo_dead && !(current->flags & PF_EXITING) &&
2340 !io_sq_thread_acquire_mm_files(ctx, req))
2341 __io_queue_sqe(req);
2343 __io_req_task_cancel(req, -EFAULT);
2344 mutex_unlock(&ctx->uring_lock);
2347 static void io_req_task_submit(struct callback_head *cb)
2349 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2351 __io_req_task_submit(req);
2354 static void io_req_task_queue(struct io_kiocb *req)
2358 req->task_work.func = io_req_task_submit;
2359 ret = io_req_task_work_add(req);
2360 if (unlikely(ret)) {
2361 percpu_ref_get(&req->ctx->refs);
2362 io_req_task_work_add_fallback(req, io_req_task_cancel);
2366 static inline void io_queue_next(struct io_kiocb *req)
2368 struct io_kiocb *nxt = io_req_find_next(req);
2371 io_req_task_queue(nxt);
2374 static void io_free_req(struct io_kiocb *req)
2381 struct task_struct *task;
2386 static inline void io_init_req_batch(struct req_batch *rb)
2393 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2394 struct req_batch *rb)
2397 io_put_task(rb->task, rb->task_refs);
2399 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2402 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2403 struct io_submit_state *state)
2407 if (req->task != rb->task) {
2409 io_put_task(rb->task, rb->task_refs);
2410 rb->task = req->task;
2416 io_dismantle_req(req);
2417 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2418 state->reqs[state->free_reqs++] = req;
2420 list_add(&req->compl.list, &state->comp.free_list);
2423 static void io_submit_flush_completions(struct io_comp_state *cs,
2424 struct io_ring_ctx *ctx)
2427 struct io_kiocb *req;
2428 struct req_batch rb;
2430 io_init_req_batch(&rb);
2431 spin_lock_irq(&ctx->completion_lock);
2432 for (i = 0; i < nr; i++) {
2434 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2436 io_commit_cqring(ctx);
2437 spin_unlock_irq(&ctx->completion_lock);
2439 io_cqring_ev_posted(ctx);
2440 for (i = 0; i < nr; i++) {
2443 /* submission and completion refs */
2444 if (refcount_sub_and_test(2, &req->refs))
2445 io_req_free_batch(&rb, req, &ctx->submit_state);
2448 io_req_free_batch_finish(ctx, &rb);
2453 * Drop reference to request, return next in chain (if there is one) if this
2454 * was the last reference to this request.
2456 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2458 struct io_kiocb *nxt = NULL;
2460 if (refcount_dec_and_test(&req->refs)) {
2461 nxt = io_req_find_next(req);
2467 static void io_put_req(struct io_kiocb *req)
2469 if (refcount_dec_and_test(&req->refs))
2473 static void io_put_req_deferred_cb(struct callback_head *cb)
2475 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2480 static void io_free_req_deferred(struct io_kiocb *req)
2484 req->task_work.func = io_put_req_deferred_cb;
2485 ret = io_req_task_work_add(req);
2487 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2490 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2492 if (refcount_sub_and_test(refs, &req->refs))
2493 io_free_req_deferred(req);
2496 static void io_double_put_req(struct io_kiocb *req)
2498 /* drop both submit and complete references */
2499 if (refcount_sub_and_test(2, &req->refs))
2503 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2505 /* See comment at the top of this file */
2507 return __io_cqring_events(ctx);
2510 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2512 struct io_rings *rings = ctx->rings;
2514 /* make sure SQ entry isn't read before tail */
2515 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2518 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2520 unsigned int cflags;
2522 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2523 cflags |= IORING_CQE_F_BUFFER;
2524 req->flags &= ~REQ_F_BUFFER_SELECTED;
2529 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2531 struct io_buffer *kbuf;
2533 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2534 return io_put_kbuf(req, kbuf);
2537 static inline bool io_run_task_work(void)
2540 * Not safe to run on exiting task, and the task_work handling will
2541 * not add work to such a task.
2543 if (unlikely(current->flags & PF_EXITING))
2545 if (current->task_works) {
2546 __set_current_state(TASK_RUNNING);
2555 * Find and free completed poll iocbs
2557 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2558 struct list_head *done)
2560 struct req_batch rb;
2561 struct io_kiocb *req;
2563 /* order with ->result store in io_complete_rw_iopoll() */
2566 io_init_req_batch(&rb);
2567 while (!list_empty(done)) {
2570 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2571 list_del(&req->inflight_entry);
2573 if (READ_ONCE(req->result) == -EAGAIN) {
2574 req->iopoll_completed = 0;
2575 if (io_rw_reissue(req))
2579 if (req->flags & REQ_F_BUFFER_SELECTED)
2580 cflags = io_put_rw_kbuf(req);
2582 __io_cqring_fill_event(req, req->result, cflags);
2585 if (refcount_dec_and_test(&req->refs))
2586 io_req_free_batch(&rb, req, &ctx->submit_state);
2589 io_commit_cqring(ctx);
2590 io_cqring_ev_posted_iopoll(ctx);
2591 io_req_free_batch_finish(ctx, &rb);
2594 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2597 struct io_kiocb *req, *tmp;
2603 * Only spin for completions if we don't have multiple devices hanging
2604 * off our complete list, and we're under the requested amount.
2606 spin = !ctx->poll_multi_file && *nr_events < min;
2609 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2610 struct kiocb *kiocb = &req->rw.kiocb;
2613 * Move completed and retryable entries to our local lists.
2614 * If we find a request that requires polling, break out
2615 * and complete those lists first, if we have entries there.
2617 if (READ_ONCE(req->iopoll_completed)) {
2618 list_move_tail(&req->inflight_entry, &done);
2621 if (!list_empty(&done))
2624 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2628 /* iopoll may have completed current req */
2629 if (READ_ONCE(req->iopoll_completed))
2630 list_move_tail(&req->inflight_entry, &done);
2637 if (!list_empty(&done))
2638 io_iopoll_complete(ctx, nr_events, &done);
2644 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2645 * non-spinning poll check - we'll still enter the driver poll loop, but only
2646 * as a non-spinning completion check.
2648 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2651 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2654 ret = io_do_iopoll(ctx, nr_events, min);
2657 if (*nr_events >= min)
2665 * We can't just wait for polled events to come to us, we have to actively
2666 * find and complete them.
2668 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2670 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2673 mutex_lock(&ctx->uring_lock);
2674 while (!list_empty(&ctx->iopoll_list)) {
2675 unsigned int nr_events = 0;
2677 io_do_iopoll(ctx, &nr_events, 0);
2679 /* let it sleep and repeat later if can't complete a request */
2683 * Ensure we allow local-to-the-cpu processing to take place,
2684 * in this case we need to ensure that we reap all events.
2685 * Also let task_work, etc. to progress by releasing the mutex
2687 if (need_resched()) {
2688 mutex_unlock(&ctx->uring_lock);
2690 mutex_lock(&ctx->uring_lock);
2693 mutex_unlock(&ctx->uring_lock);
2696 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2698 unsigned int nr_events = 0;
2699 int iters = 0, ret = 0;
2702 * We disallow the app entering submit/complete with polling, but we
2703 * still need to lock the ring to prevent racing with polled issue
2704 * that got punted to a workqueue.
2706 mutex_lock(&ctx->uring_lock);
2709 * Don't enter poll loop if we already have events pending.
2710 * If we do, we can potentially be spinning for commands that
2711 * already triggered a CQE (eg in error).
2713 if (test_bit(0, &ctx->cq_check_overflow))
2714 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2715 if (io_cqring_events(ctx))
2719 * If a submit got punted to a workqueue, we can have the
2720 * application entering polling for a command before it gets
2721 * issued. That app will hold the uring_lock for the duration
2722 * of the poll right here, so we need to take a breather every
2723 * now and then to ensure that the issue has a chance to add
2724 * the poll to the issued list. Otherwise we can spin here
2725 * forever, while the workqueue is stuck trying to acquire the
2728 if (!(++iters & 7)) {
2729 mutex_unlock(&ctx->uring_lock);
2731 mutex_lock(&ctx->uring_lock);
2734 ret = io_iopoll_getevents(ctx, &nr_events, min);
2738 } while (min && !nr_events && !need_resched());
2740 mutex_unlock(&ctx->uring_lock);
2744 static void kiocb_end_write(struct io_kiocb *req)
2747 * Tell lockdep we inherited freeze protection from submission
2750 if (req->flags & REQ_F_ISREG) {
2751 struct inode *inode = file_inode(req->file);
2753 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2755 file_end_write(req->file);
2759 static bool io_resubmit_prep(struct io_kiocb *req)
2761 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2763 struct iov_iter iter;
2765 /* already prepared */
2766 if (req->async_data)
2769 switch (req->opcode) {
2770 case IORING_OP_READV:
2771 case IORING_OP_READ_FIXED:
2772 case IORING_OP_READ:
2775 case IORING_OP_WRITEV:
2776 case IORING_OP_WRITE_FIXED:
2777 case IORING_OP_WRITE:
2781 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2786 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2789 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2793 static bool io_rw_reissue(struct io_kiocb *req)
2796 umode_t mode = file_inode(req->file)->i_mode;
2799 if (!S_ISBLK(mode) && !S_ISREG(mode))
2801 if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2804 lockdep_assert_held(&req->ctx->uring_lock);
2806 ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2808 if (!ret && io_resubmit_prep(req)) {
2809 refcount_inc(&req->refs);
2810 io_queue_async_work(req);
2813 req_set_fail_links(req);
2818 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2819 unsigned int issue_flags)
2823 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2825 if (res != req->result)
2826 req_set_fail_links(req);
2828 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2829 kiocb_end_write(req);
2830 if (req->flags & REQ_F_BUFFER_SELECTED)
2831 cflags = io_put_rw_kbuf(req);
2832 __io_req_complete(req, issue_flags, res, cflags);
2835 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2837 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2839 __io_complete_rw(req, res, res2, 0);
2842 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2844 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2846 if (kiocb->ki_flags & IOCB_WRITE)
2847 kiocb_end_write(req);
2849 if (res != -EAGAIN && res != req->result)
2850 req_set_fail_links(req);
2852 WRITE_ONCE(req->result, res);
2853 /* order with io_poll_complete() checking ->result */
2855 WRITE_ONCE(req->iopoll_completed, 1);
2859 * After the iocb has been issued, it's safe to be found on the poll list.
2860 * Adding the kiocb to the list AFTER submission ensures that we don't
2861 * find it from a io_iopoll_getevents() thread before the issuer is done
2862 * accessing the kiocb cookie.
2864 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2866 struct io_ring_ctx *ctx = req->ctx;
2869 * Track whether we have multiple files in our lists. This will impact
2870 * how we do polling eventually, not spinning if we're on potentially
2871 * different devices.
2873 if (list_empty(&ctx->iopoll_list)) {
2874 ctx->poll_multi_file = false;
2875 } else if (!ctx->poll_multi_file) {
2876 struct io_kiocb *list_req;
2878 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2880 if (list_req->file != req->file)
2881 ctx->poll_multi_file = true;
2885 * For fast devices, IO may have already completed. If it has, add
2886 * it to the front so we find it first.
2888 if (READ_ONCE(req->iopoll_completed))
2889 list_add(&req->inflight_entry, &ctx->iopoll_list);
2891 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2894 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2895 * task context or in io worker task context. If current task context is
2896 * sq thread, we don't need to check whether should wake up sq thread.
2898 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2899 wq_has_sleeper(&ctx->sq_data->wait))
2900 wake_up(&ctx->sq_data->wait);
2903 static inline void io_state_file_put(struct io_submit_state *state)
2905 if (state->file_refs) {
2906 fput_many(state->file, state->file_refs);
2907 state->file_refs = 0;
2912 * Get as many references to a file as we have IOs left in this submission,
2913 * assuming most submissions are for one file, or at least that each file
2914 * has more than one submission.
2916 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2921 if (state->file_refs) {
2922 if (state->fd == fd) {
2926 io_state_file_put(state);
2928 state->file = fget_many(fd, state->ios_left);
2929 if (unlikely(!state->file))
2933 state->file_refs = state->ios_left - 1;
2937 static bool io_bdev_nowait(struct block_device *bdev)
2939 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2943 * If we tracked the file through the SCM inflight mechanism, we could support
2944 * any file. For now, just ensure that anything potentially problematic is done
2947 static bool io_file_supports_async(struct file *file, int rw)
2949 umode_t mode = file_inode(file)->i_mode;
2951 if (S_ISBLK(mode)) {
2952 if (IS_ENABLED(CONFIG_BLOCK) &&
2953 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2957 if (S_ISCHR(mode) || S_ISSOCK(mode))
2959 if (S_ISREG(mode)) {
2960 if (IS_ENABLED(CONFIG_BLOCK) &&
2961 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2962 file->f_op != &io_uring_fops)
2967 /* any ->read/write should understand O_NONBLOCK */
2968 if (file->f_flags & O_NONBLOCK)
2971 if (!(file->f_mode & FMODE_NOWAIT))
2975 return file->f_op->read_iter != NULL;
2977 return file->f_op->write_iter != NULL;
2980 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2982 struct io_ring_ctx *ctx = req->ctx;
2983 struct kiocb *kiocb = &req->rw.kiocb;
2984 struct file *file = req->file;
2988 if (S_ISREG(file_inode(file)->i_mode))
2989 req->flags |= REQ_F_ISREG;
2991 kiocb->ki_pos = READ_ONCE(sqe->off);
2992 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2993 req->flags |= REQ_F_CUR_POS;
2994 kiocb->ki_pos = file->f_pos;
2996 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2997 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2998 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3002 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
3003 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
3004 req->flags |= REQ_F_NOWAIT;
3006 ioprio = READ_ONCE(sqe->ioprio);
3008 ret = ioprio_check_cap(ioprio);
3012 kiocb->ki_ioprio = ioprio;
3014 kiocb->ki_ioprio = get_current_ioprio();
3016 if (ctx->flags & IORING_SETUP_IOPOLL) {
3017 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
3018 !kiocb->ki_filp->f_op->iopoll)
3021 kiocb->ki_flags |= IOCB_HIPRI;
3022 kiocb->ki_complete = io_complete_rw_iopoll;
3023 req->iopoll_completed = 0;
3025 if (kiocb->ki_flags & IOCB_HIPRI)
3027 kiocb->ki_complete = io_complete_rw;
3030 req->rw.addr = READ_ONCE(sqe->addr);
3031 req->rw.len = READ_ONCE(sqe->len);
3032 req->buf_index = READ_ONCE(sqe->buf_index);
3036 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3042 case -ERESTARTNOINTR:
3043 case -ERESTARTNOHAND:
3044 case -ERESTART_RESTARTBLOCK:
3046 * We can't just restart the syscall, since previously
3047 * submitted sqes may already be in progress. Just fail this
3053 kiocb->ki_complete(kiocb, ret, 0);
3057 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3058 unsigned int issue_flags)
3060 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3061 struct io_async_rw *io = req->async_data;
3063 /* add previously done IO, if any */
3064 if (io && io->bytes_done > 0) {
3066 ret = io->bytes_done;
3068 ret += io->bytes_done;
3071 if (req->flags & REQ_F_CUR_POS)
3072 req->file->f_pos = kiocb->ki_pos;
3073 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
3074 __io_complete_rw(req, ret, 0, issue_flags);
3076 io_rw_done(kiocb, ret);
3079 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3081 struct io_ring_ctx *ctx = req->ctx;
3082 size_t len = req->rw.len;
3083 struct io_mapped_ubuf *imu;
3084 u16 index, buf_index = req->buf_index;
3088 if (unlikely(buf_index >= ctx->nr_user_bufs))
3090 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3091 imu = &ctx->user_bufs[index];
3092 buf_addr = req->rw.addr;
3095 if (buf_addr + len < buf_addr)
3097 /* not inside the mapped region */
3098 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
3102 * May not be a start of buffer, set size appropriately
3103 * and advance us to the beginning.
3105 offset = buf_addr - imu->ubuf;
3106 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3110 * Don't use iov_iter_advance() here, as it's really slow for
3111 * using the latter parts of a big fixed buffer - it iterates
3112 * over each segment manually. We can cheat a bit here, because
3115 * 1) it's a BVEC iter, we set it up
3116 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3117 * first and last bvec
3119 * So just find our index, and adjust the iterator afterwards.
3120 * If the offset is within the first bvec (or the whole first
3121 * bvec, just use iov_iter_advance(). This makes it easier
3122 * since we can just skip the first segment, which may not
3123 * be PAGE_SIZE aligned.
3125 const struct bio_vec *bvec = imu->bvec;
3127 if (offset <= bvec->bv_len) {
3128 iov_iter_advance(iter, offset);
3130 unsigned long seg_skip;
3132 /* skip first vec */
3133 offset -= bvec->bv_len;
3134 seg_skip = 1 + (offset >> PAGE_SHIFT);
3136 iter->bvec = bvec + seg_skip;
3137 iter->nr_segs -= seg_skip;
3138 iter->count -= bvec->bv_len + offset;
3139 iter->iov_offset = offset & ~PAGE_MASK;
3146 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3149 mutex_unlock(&ctx->uring_lock);
3152 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3155 * "Normal" inline submissions always hold the uring_lock, since we
3156 * grab it from the system call. Same is true for the SQPOLL offload.
3157 * The only exception is when we've detached the request and issue it
3158 * from an async worker thread, grab the lock for that case.
3161 mutex_lock(&ctx->uring_lock);
3164 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3165 int bgid, struct io_buffer *kbuf,
3168 struct io_buffer *head;
3170 if (req->flags & REQ_F_BUFFER_SELECTED)
3173 io_ring_submit_lock(req->ctx, needs_lock);
3175 lockdep_assert_held(&req->ctx->uring_lock);
3177 head = idr_find(&req->ctx->io_buffer_idr, bgid);
3179 if (!list_empty(&head->list)) {
3180 kbuf = list_last_entry(&head->list, struct io_buffer,
3182 list_del(&kbuf->list);
3185 idr_remove(&req->ctx->io_buffer_idr, bgid);
3187 if (*len > kbuf->len)
3190 kbuf = ERR_PTR(-ENOBUFS);
3193 io_ring_submit_unlock(req->ctx, needs_lock);
3198 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3201 struct io_buffer *kbuf;
3204 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3205 bgid = req->buf_index;
3206 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3209 req->rw.addr = (u64) (unsigned long) kbuf;
3210 req->flags |= REQ_F_BUFFER_SELECTED;
3211 return u64_to_user_ptr(kbuf->addr);
3214 #ifdef CONFIG_COMPAT
3215 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3218 struct compat_iovec __user *uiov;
3219 compat_ssize_t clen;
3223 uiov = u64_to_user_ptr(req->rw.addr);
3224 if (!access_ok(uiov, sizeof(*uiov)))
3226 if (__get_user(clen, &uiov->iov_len))
3232 buf = io_rw_buffer_select(req, &len, needs_lock);
3234 return PTR_ERR(buf);
3235 iov[0].iov_base = buf;
3236 iov[0].iov_len = (compat_size_t) len;
3241 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3244 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3248 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3251 len = iov[0].iov_len;
3254 buf = io_rw_buffer_select(req, &len, needs_lock);
3256 return PTR_ERR(buf);
3257 iov[0].iov_base = buf;
3258 iov[0].iov_len = len;
3262 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3265 if (req->flags & REQ_F_BUFFER_SELECTED) {
3266 struct io_buffer *kbuf;
3268 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3269 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3270 iov[0].iov_len = kbuf->len;
3273 if (req->rw.len != 1)
3276 #ifdef CONFIG_COMPAT
3277 if (req->ctx->compat)
3278 return io_compat_import(req, iov, needs_lock);
3281 return __io_iov_buffer_select(req, iov, needs_lock);
3284 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3285 struct iov_iter *iter, bool needs_lock)
3287 void __user *buf = u64_to_user_ptr(req->rw.addr);
3288 size_t sqe_len = req->rw.len;
3289 u8 opcode = req->opcode;
3292 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3294 return io_import_fixed(req, rw, iter);
3297 /* buffer index only valid with fixed read/write, or buffer select */
3298 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3301 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3302 if (req->flags & REQ_F_BUFFER_SELECT) {
3303 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3305 return PTR_ERR(buf);
3306 req->rw.len = sqe_len;
3309 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3314 if (req->flags & REQ_F_BUFFER_SELECT) {
3315 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3317 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3322 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3326 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3328 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3332 * For files that don't have ->read_iter() and ->write_iter(), handle them
3333 * by looping over ->read() or ->write() manually.
3335 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3337 struct kiocb *kiocb = &req->rw.kiocb;
3338 struct file *file = req->file;
3342 * Don't support polled IO through this interface, and we can't
3343 * support non-blocking either. For the latter, this just causes
3344 * the kiocb to be handled from an async context.
3346 if (kiocb->ki_flags & IOCB_HIPRI)
3348 if (kiocb->ki_flags & IOCB_NOWAIT)
3351 while (iov_iter_count(iter)) {
3355 if (!iov_iter_is_bvec(iter)) {
3356 iovec = iov_iter_iovec(iter);
3358 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3359 iovec.iov_len = req->rw.len;
3363 nr = file->f_op->read(file, iovec.iov_base,
3364 iovec.iov_len, io_kiocb_ppos(kiocb));
3366 nr = file->f_op->write(file, iovec.iov_base,
3367 iovec.iov_len, io_kiocb_ppos(kiocb));
3376 if (nr != iovec.iov_len)
3380 iov_iter_advance(iter, nr);
3386 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3387 const struct iovec *fast_iov, struct iov_iter *iter)
3389 struct io_async_rw *rw = req->async_data;
3391 memcpy(&rw->iter, iter, sizeof(*iter));
3392 rw->free_iovec = iovec;
3394 /* can only be fixed buffers, no need to do anything */
3395 if (iov_iter_is_bvec(iter))
3398 unsigned iov_off = 0;
3400 rw->iter.iov = rw->fast_iov;
3401 if (iter->iov != fast_iov) {
3402 iov_off = iter->iov - fast_iov;
3403 rw->iter.iov += iov_off;
3405 if (rw->fast_iov != fast_iov)
3406 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3407 sizeof(struct iovec) * iter->nr_segs);
3409 req->flags |= REQ_F_NEED_CLEANUP;
3413 static inline int __io_alloc_async_data(struct io_kiocb *req)
3415 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3416 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3417 return req->async_data == NULL;
3420 static int io_alloc_async_data(struct io_kiocb *req)
3422 if (!io_op_defs[req->opcode].needs_async_data)
3425 return __io_alloc_async_data(req);
3428 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3429 const struct iovec *fast_iov,
3430 struct iov_iter *iter, bool force)
3432 if (!force && !io_op_defs[req->opcode].needs_async_data)
3434 if (!req->async_data) {
3435 if (__io_alloc_async_data(req)) {
3440 io_req_map_rw(req, iovec, fast_iov, iter);
3445 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3447 struct io_async_rw *iorw = req->async_data;
3448 struct iovec *iov = iorw->fast_iov;
3451 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3452 if (unlikely(ret < 0))
3455 iorw->bytes_done = 0;
3456 iorw->free_iovec = iov;
3458 req->flags |= REQ_F_NEED_CLEANUP;
3462 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3466 ret = io_prep_rw(req, sqe);
3470 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3473 /* either don't need iovec imported or already have it */
3474 if (!req->async_data)
3476 return io_rw_prep_async(req, READ);
3480 * This is our waitqueue callback handler, registered through lock_page_async()
3481 * when we initially tried to do the IO with the iocb armed our waitqueue.
3482 * This gets called when the page is unlocked, and we generally expect that to
3483 * happen when the page IO is completed and the page is now uptodate. This will
3484 * queue a task_work based retry of the operation, attempting to copy the data
3485 * again. If the latter fails because the page was NOT uptodate, then we will
3486 * do a thread based blocking retry of the operation. That's the unexpected
3489 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3490 int sync, void *arg)
3492 struct wait_page_queue *wpq;
3493 struct io_kiocb *req = wait->private;
3494 struct wait_page_key *key = arg;
3496 wpq = container_of(wait, struct wait_page_queue, wait);
3498 if (!wake_page_match(wpq, key))
3501 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3502 list_del_init(&wait->entry);
3504 /* submit ref gets dropped, acquire a new one */
3505 refcount_inc(&req->refs);
3506 io_req_task_queue(req);
3511 * This controls whether a given IO request should be armed for async page
3512 * based retry. If we return false here, the request is handed to the async
3513 * worker threads for retry. If we're doing buffered reads on a regular file,
3514 * we prepare a private wait_page_queue entry and retry the operation. This
3515 * will either succeed because the page is now uptodate and unlocked, or it
3516 * will register a callback when the page is unlocked at IO completion. Through
3517 * that callback, io_uring uses task_work to setup a retry of the operation.
3518 * That retry will attempt the buffered read again. The retry will generally
3519 * succeed, or in rare cases where it fails, we then fall back to using the
3520 * async worker threads for a blocking retry.
3522 static bool io_rw_should_retry(struct io_kiocb *req)
3524 struct io_async_rw *rw = req->async_data;
3525 struct wait_page_queue *wait = &rw->wpq;
3526 struct kiocb *kiocb = &req->rw.kiocb;
3528 /* never retry for NOWAIT, we just complete with -EAGAIN */
3529 if (req->flags & REQ_F_NOWAIT)
3532 /* Only for buffered IO */
3533 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3537 * just use poll if we can, and don't attempt if the fs doesn't
3538 * support callback based unlocks
3540 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3543 wait->wait.func = io_async_buf_func;
3544 wait->wait.private = req;
3545 wait->wait.flags = 0;
3546 INIT_LIST_HEAD(&wait->wait.entry);
3547 kiocb->ki_flags |= IOCB_WAITQ;
3548 kiocb->ki_flags &= ~IOCB_NOWAIT;
3549 kiocb->ki_waitq = wait;
3553 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3555 if (req->file->f_op->read_iter)
3556 return call_read_iter(req->file, &req->rw.kiocb, iter);
3557 else if (req->file->f_op->read)
3558 return loop_rw_iter(READ, req, iter);
3563 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3565 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3566 struct kiocb *kiocb = &req->rw.kiocb;
3567 struct iov_iter __iter, *iter = &__iter;
3568 struct io_async_rw *rw = req->async_data;
3569 ssize_t io_size, ret, ret2;
3570 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3576 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3580 io_size = iov_iter_count(iter);
3581 req->result = io_size;
3583 /* Ensure we clear previously set non-block flag */
3584 if (!force_nonblock)
3585 kiocb->ki_flags &= ~IOCB_NOWAIT;
3587 kiocb->ki_flags |= IOCB_NOWAIT;
3589 /* If the file doesn't support async, just async punt */
3590 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3591 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3592 return ret ?: -EAGAIN;
3595 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3596 if (unlikely(ret)) {
3601 ret = io_iter_do_read(req, iter);
3603 if (ret == -EIOCBQUEUED) {
3604 /* it's faster to check here then delegate to kfree */
3608 } else if (ret == -EAGAIN) {
3609 /* IOPOLL retry should happen for io-wq threads */
3610 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3612 /* no retry on NONBLOCK nor RWF_NOWAIT */
3613 if (req->flags & REQ_F_NOWAIT)
3615 /* some cases will consume bytes even on error returns */
3616 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3618 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3619 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3620 /* read all, failed, already did sync or don't want to retry */
3624 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3628 rw = req->async_data;
3629 /* now use our persistent iterator, if we aren't already */
3634 rw->bytes_done += ret;
3635 /* if we can retry, do so with the callbacks armed */
3636 if (!io_rw_should_retry(req)) {
3637 kiocb->ki_flags &= ~IOCB_WAITQ;
3642 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3643 * we get -EIOCBQUEUED, then we'll get a notification when the
3644 * desired page gets unlocked. We can also get a partial read
3645 * here, and if we do, then just retry at the new offset.
3647 ret = io_iter_do_read(req, iter);
3648 if (ret == -EIOCBQUEUED)
3650 /* we got some bytes, but not all. retry. */
3651 } while (ret > 0 && ret < io_size);
3653 kiocb_done(kiocb, ret, issue_flags);
3657 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3661 ret = io_prep_rw(req, sqe);
3665 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3668 /* either don't need iovec imported or already have it */
3669 if (!req->async_data)
3671 return io_rw_prep_async(req, WRITE);
3674 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3676 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3677 struct kiocb *kiocb = &req->rw.kiocb;
3678 struct iov_iter __iter, *iter = &__iter;
3679 struct io_async_rw *rw = req->async_data;
3680 ssize_t ret, ret2, io_size;
3681 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3687 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3691 io_size = iov_iter_count(iter);
3692 req->result = io_size;
3694 /* Ensure we clear previously set non-block flag */
3695 if (!force_nonblock)
3696 kiocb->ki_flags &= ~IOCB_NOWAIT;
3698 kiocb->ki_flags |= IOCB_NOWAIT;
3700 /* If the file doesn't support async, just async punt */
3701 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3704 /* file path doesn't support NOWAIT for non-direct_IO */
3705 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3706 (req->flags & REQ_F_ISREG))
3709 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3714 * Open-code file_start_write here to grab freeze protection,
3715 * which will be released by another thread in
3716 * io_complete_rw(). Fool lockdep by telling it the lock got
3717 * released so that it doesn't complain about the held lock when
3718 * we return to userspace.
3720 if (req->flags & REQ_F_ISREG) {
3721 sb_start_write(file_inode(req->file)->i_sb);
3722 __sb_writers_release(file_inode(req->file)->i_sb,
3725 kiocb->ki_flags |= IOCB_WRITE;
3727 if (req->file->f_op->write_iter)
3728 ret2 = call_write_iter(req->file, kiocb, iter);
3729 else if (req->file->f_op->write)
3730 ret2 = loop_rw_iter(WRITE, req, iter);
3735 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3736 * retry them without IOCB_NOWAIT.
3738 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3740 /* no retry on NONBLOCK nor RWF_NOWAIT */
3741 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3743 if (!force_nonblock || ret2 != -EAGAIN) {
3744 /* IOPOLL retry should happen for io-wq threads */
3745 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3748 kiocb_done(kiocb, ret2, issue_flags);
3751 /* some cases will consume bytes even on error returns */
3752 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3753 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3754 return ret ?: -EAGAIN;
3757 /* it's reportedly faster than delegating the null check to kfree() */
3763 static int io_renameat_prep(struct io_kiocb *req,
3764 const struct io_uring_sqe *sqe)
3766 struct io_rename *ren = &req->rename;
3767 const char __user *oldf, *newf;
3769 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3772 ren->old_dfd = READ_ONCE(sqe->fd);
3773 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3774 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3775 ren->new_dfd = READ_ONCE(sqe->len);
3776 ren->flags = READ_ONCE(sqe->rename_flags);
3778 ren->oldpath = getname(oldf);
3779 if (IS_ERR(ren->oldpath))
3780 return PTR_ERR(ren->oldpath);
3782 ren->newpath = getname(newf);
3783 if (IS_ERR(ren->newpath)) {
3784 putname(ren->oldpath);
3785 return PTR_ERR(ren->newpath);
3788 req->flags |= REQ_F_NEED_CLEANUP;
3792 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3794 struct io_rename *ren = &req->rename;
3797 if (issue_flags & IO_URING_F_NONBLOCK)
3800 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3801 ren->newpath, ren->flags);
3803 req->flags &= ~REQ_F_NEED_CLEANUP;
3805 req_set_fail_links(req);
3806 io_req_complete(req, ret);
3810 static int io_unlinkat_prep(struct io_kiocb *req,
3811 const struct io_uring_sqe *sqe)
3813 struct io_unlink *un = &req->unlink;
3814 const char __user *fname;
3816 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3819 un->dfd = READ_ONCE(sqe->fd);
3821 un->flags = READ_ONCE(sqe->unlink_flags);
3822 if (un->flags & ~AT_REMOVEDIR)
3825 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3826 un->filename = getname(fname);
3827 if (IS_ERR(un->filename))
3828 return PTR_ERR(un->filename);
3830 req->flags |= REQ_F_NEED_CLEANUP;
3834 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3836 struct io_unlink *un = &req->unlink;
3839 if (issue_flags & IO_URING_F_NONBLOCK)
3842 if (un->flags & AT_REMOVEDIR)
3843 ret = do_rmdir(un->dfd, un->filename);
3845 ret = do_unlinkat(un->dfd, un->filename);
3847 req->flags &= ~REQ_F_NEED_CLEANUP;
3849 req_set_fail_links(req);
3850 io_req_complete(req, ret);
3854 static int io_shutdown_prep(struct io_kiocb *req,
3855 const struct io_uring_sqe *sqe)
3857 #if defined(CONFIG_NET)
3858 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3860 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3864 req->shutdown.how = READ_ONCE(sqe->len);
3871 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3873 #if defined(CONFIG_NET)
3874 struct socket *sock;
3877 if (issue_flags & IO_URING_F_NONBLOCK)
3880 sock = sock_from_file(req->file);
3881 if (unlikely(!sock))
3884 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3886 req_set_fail_links(req);
3887 io_req_complete(req, ret);
3894 static int __io_splice_prep(struct io_kiocb *req,
3895 const struct io_uring_sqe *sqe)
3897 struct io_splice* sp = &req->splice;
3898 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3900 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3904 sp->len = READ_ONCE(sqe->len);
3905 sp->flags = READ_ONCE(sqe->splice_flags);
3907 if (unlikely(sp->flags & ~valid_flags))
3910 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3911 (sp->flags & SPLICE_F_FD_IN_FIXED));
3914 req->flags |= REQ_F_NEED_CLEANUP;
3916 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3918 * Splice operation will be punted aync, and here need to
3919 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3921 io_req_init_async(req);
3922 req->work.flags |= IO_WQ_WORK_UNBOUND;
3928 static int io_tee_prep(struct io_kiocb *req,
3929 const struct io_uring_sqe *sqe)
3931 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3933 return __io_splice_prep(req, sqe);
3936 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3938 struct io_splice *sp = &req->splice;
3939 struct file *in = sp->file_in;
3940 struct file *out = sp->file_out;
3941 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3944 if (issue_flags & IO_URING_F_NONBLOCK)
3947 ret = do_tee(in, out, sp->len, flags);
3949 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3950 req->flags &= ~REQ_F_NEED_CLEANUP;
3953 req_set_fail_links(req);
3954 io_req_complete(req, ret);
3958 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3960 struct io_splice* sp = &req->splice;
3962 sp->off_in = READ_ONCE(sqe->splice_off_in);
3963 sp->off_out = READ_ONCE(sqe->off);
3964 return __io_splice_prep(req, sqe);
3967 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3969 struct io_splice *sp = &req->splice;
3970 struct file *in = sp->file_in;
3971 struct file *out = sp->file_out;
3972 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3973 loff_t *poff_in, *poff_out;
3976 if (issue_flags & IO_URING_F_NONBLOCK)
3979 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3980 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3983 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3985 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3986 req->flags &= ~REQ_F_NEED_CLEANUP;
3989 req_set_fail_links(req);
3990 io_req_complete(req, ret);
3995 * IORING_OP_NOP just posts a completion event, nothing else.
3997 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3999 struct io_ring_ctx *ctx = req->ctx;
4001 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4004 __io_req_complete(req, issue_flags, 0, 0);
4008 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4010 struct io_ring_ctx *ctx = req->ctx;
4015 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4017 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4020 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4021 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4024 req->sync.off = READ_ONCE(sqe->off);
4025 req->sync.len = READ_ONCE(sqe->len);
4029 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4031 loff_t end = req->sync.off + req->sync.len;
4034 /* fsync always requires a blocking context */
4035 if (issue_flags & IO_URING_F_NONBLOCK)
4038 ret = vfs_fsync_range(req->file, req->sync.off,
4039 end > 0 ? end : LLONG_MAX,
4040 req->sync.flags & IORING_FSYNC_DATASYNC);
4042 req_set_fail_links(req);
4043 io_req_complete(req, ret);
4047 static int io_fallocate_prep(struct io_kiocb *req,
4048 const struct io_uring_sqe *sqe)
4050 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
4052 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4055 req->sync.off = READ_ONCE(sqe->off);
4056 req->sync.len = READ_ONCE(sqe->addr);
4057 req->sync.mode = READ_ONCE(sqe->len);
4061 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4065 /* fallocate always requiring blocking context */
4066 if (issue_flags & IO_URING_F_NONBLOCK)
4068 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4071 req_set_fail_links(req);
4072 io_req_complete(req, ret);
4076 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4078 const char __user *fname;
4081 if (unlikely(sqe->ioprio || sqe->buf_index))
4083 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4086 /* open.how should be already initialised */
4087 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4088 req->open.how.flags |= O_LARGEFILE;
4090 req->open.dfd = READ_ONCE(sqe->fd);
4091 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4092 req->open.filename = getname(fname);
4093 if (IS_ERR(req->open.filename)) {
4094 ret = PTR_ERR(req->open.filename);
4095 req->open.filename = NULL;
4098 req->open.nofile = rlimit(RLIMIT_NOFILE);
4099 req->flags |= REQ_F_NEED_CLEANUP;
4103 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4107 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4109 mode = READ_ONCE(sqe->len);
4110 flags = READ_ONCE(sqe->open_flags);
4111 req->open.how = build_open_how(flags, mode);
4112 return __io_openat_prep(req, sqe);
4115 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4117 struct open_how __user *how;
4121 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4123 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4124 len = READ_ONCE(sqe->len);
4125 if (len < OPEN_HOW_SIZE_VER0)
4128 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4133 return __io_openat_prep(req, sqe);
4136 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4138 struct open_flags op;
4141 bool resolve_nonblock;
4144 ret = build_open_flags(&req->open.how, &op);
4147 nonblock_set = op.open_flag & O_NONBLOCK;
4148 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4149 if (issue_flags & IO_URING_F_NONBLOCK) {
4151 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4152 * it'll always -EAGAIN
4154 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4156 op.lookup_flags |= LOOKUP_CACHED;
4157 op.open_flag |= O_NONBLOCK;
4160 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4164 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4165 /* only retry if RESOLVE_CACHED wasn't already set by application */
4166 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
4167 file == ERR_PTR(-EAGAIN)) {
4169 * We could hang on to this 'fd', but seems like marginal
4170 * gain for something that is now known to be a slower path.
4171 * So just put it, and we'll get a new one when we retry.
4179 ret = PTR_ERR(file);
4181 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4182 file->f_flags &= ~O_NONBLOCK;
4183 fsnotify_open(file);
4184 fd_install(ret, file);
4187 putname(req->open.filename);
4188 req->flags &= ~REQ_F_NEED_CLEANUP;
4190 req_set_fail_links(req);
4191 io_req_complete(req, ret);
4195 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4197 return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
4200 static int io_remove_buffers_prep(struct io_kiocb *req,
4201 const struct io_uring_sqe *sqe)
4203 struct io_provide_buf *p = &req->pbuf;
4206 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4209 tmp = READ_ONCE(sqe->fd);
4210 if (!tmp || tmp > USHRT_MAX)
4213 memset(p, 0, sizeof(*p));
4215 p->bgid = READ_ONCE(sqe->buf_group);
4219 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4220 int bgid, unsigned nbufs)
4224 /* shouldn't happen */
4228 /* the head kbuf is the list itself */
4229 while (!list_empty(&buf->list)) {
4230 struct io_buffer *nxt;
4232 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4233 list_del(&nxt->list);
4240 idr_remove(&ctx->io_buffer_idr, bgid);
4245 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4247 struct io_provide_buf *p = &req->pbuf;
4248 struct io_ring_ctx *ctx = req->ctx;
4249 struct io_buffer *head;
4251 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4253 io_ring_submit_lock(ctx, !force_nonblock);
4255 lockdep_assert_held(&ctx->uring_lock);
4258 head = idr_find(&ctx->io_buffer_idr, p->bgid);
4260 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4262 req_set_fail_links(req);
4264 /* need to hold the lock to complete IOPOLL requests */
4265 if (ctx->flags & IORING_SETUP_IOPOLL) {
4266 __io_req_complete(req, issue_flags, ret, 0);
4267 io_ring_submit_unlock(ctx, !force_nonblock);
4269 io_ring_submit_unlock(ctx, !force_nonblock);
4270 __io_req_complete(req, issue_flags, ret, 0);
4275 static int io_provide_buffers_prep(struct io_kiocb *req,
4276 const struct io_uring_sqe *sqe)
4278 struct io_provide_buf *p = &req->pbuf;
4281 if (sqe->ioprio || sqe->rw_flags)
4284 tmp = READ_ONCE(sqe->fd);
4285 if (!tmp || tmp > USHRT_MAX)
4288 p->addr = READ_ONCE(sqe->addr);
4289 p->len = READ_ONCE(sqe->len);
4291 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4294 p->bgid = READ_ONCE(sqe->buf_group);
4295 tmp = READ_ONCE(sqe->off);
4296 if (tmp > USHRT_MAX)
4302 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4304 struct io_buffer *buf;
4305 u64 addr = pbuf->addr;
4306 int i, bid = pbuf->bid;
4308 for (i = 0; i < pbuf->nbufs; i++) {
4309 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4314 buf->len = pbuf->len;
4319 INIT_LIST_HEAD(&buf->list);
4322 list_add_tail(&buf->list, &(*head)->list);
4326 return i ? i : -ENOMEM;
4329 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4331 struct io_provide_buf *p = &req->pbuf;
4332 struct io_ring_ctx *ctx = req->ctx;
4333 struct io_buffer *head, *list;
4335 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4337 io_ring_submit_lock(ctx, !force_nonblock);
4339 lockdep_assert_held(&ctx->uring_lock);
4341 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4343 ret = io_add_buffers(p, &head);
4348 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4351 __io_remove_buffers(ctx, head, p->bgid, -1U);
4357 req_set_fail_links(req);
4359 /* need to hold the lock to complete IOPOLL requests */
4360 if (ctx->flags & IORING_SETUP_IOPOLL) {
4361 __io_req_complete(req, issue_flags, ret, 0);
4362 io_ring_submit_unlock(ctx, !force_nonblock);
4364 io_ring_submit_unlock(ctx, !force_nonblock);
4365 __io_req_complete(req, issue_flags, ret, 0);
4370 static int io_epoll_ctl_prep(struct io_kiocb *req,
4371 const struct io_uring_sqe *sqe)
4373 #if defined(CONFIG_EPOLL)
4374 if (sqe->ioprio || sqe->buf_index)
4376 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4379 req->epoll.epfd = READ_ONCE(sqe->fd);
4380 req->epoll.op = READ_ONCE(sqe->len);
4381 req->epoll.fd = READ_ONCE(sqe->off);
4383 if (ep_op_has_event(req->epoll.op)) {
4384 struct epoll_event __user *ev;
4386 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4387 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4397 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4399 #if defined(CONFIG_EPOLL)
4400 struct io_epoll *ie = &req->epoll;
4402 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4404 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4405 if (force_nonblock && ret == -EAGAIN)
4409 req_set_fail_links(req);
4410 __io_req_complete(req, issue_flags, ret, 0);
4417 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4419 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4420 if (sqe->ioprio || sqe->buf_index || sqe->off)
4422 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4425 req->madvise.addr = READ_ONCE(sqe->addr);
4426 req->madvise.len = READ_ONCE(sqe->len);
4427 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4434 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4436 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4437 struct io_madvise *ma = &req->madvise;
4440 if (issue_flags & IO_URING_F_NONBLOCK)
4443 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4445 req_set_fail_links(req);
4446 io_req_complete(req, ret);
4453 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4455 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4457 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4460 req->fadvise.offset = READ_ONCE(sqe->off);
4461 req->fadvise.len = READ_ONCE(sqe->len);
4462 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4466 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4468 struct io_fadvise *fa = &req->fadvise;
4471 if (issue_flags & IO_URING_F_NONBLOCK) {
4472 switch (fa->advice) {
4473 case POSIX_FADV_NORMAL:
4474 case POSIX_FADV_RANDOM:
4475 case POSIX_FADV_SEQUENTIAL:
4482 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4484 req_set_fail_links(req);
4485 io_req_complete(req, ret);
4489 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4491 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4493 if (sqe->ioprio || sqe->buf_index)
4495 if (req->flags & REQ_F_FIXED_FILE)
4498 req->statx.dfd = READ_ONCE(sqe->fd);
4499 req->statx.mask = READ_ONCE(sqe->len);
4500 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4501 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4502 req->statx.flags = READ_ONCE(sqe->statx_flags);
4507 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4509 struct io_statx *ctx = &req->statx;
4512 if (issue_flags & IO_URING_F_NONBLOCK) {
4513 /* only need file table for an actual valid fd */
4514 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4515 req->flags |= REQ_F_NO_FILE_TABLE;
4519 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4523 req_set_fail_links(req);
4524 io_req_complete(req, ret);
4528 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4530 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4532 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4533 sqe->rw_flags || sqe->buf_index)
4535 if (req->flags & REQ_F_FIXED_FILE)
4538 req->close.fd = READ_ONCE(sqe->fd);
4542 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4544 struct files_struct *files = current->files;
4545 struct io_close *close = &req->close;
4546 struct fdtable *fdt;
4552 spin_lock(&files->file_lock);
4553 fdt = files_fdtable(files);
4554 if (close->fd >= fdt->max_fds) {
4555 spin_unlock(&files->file_lock);
4558 file = fdt->fd[close->fd];
4560 spin_unlock(&files->file_lock);
4564 if (file->f_op == &io_uring_fops) {
4565 spin_unlock(&files->file_lock);
4570 /* if the file has a flush method, be safe and punt to async */
4571 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4572 spin_unlock(&files->file_lock);
4576 ret = __close_fd_get_file(close->fd, &file);
4577 spin_unlock(&files->file_lock);
4584 /* No ->flush() or already async, safely close from here */
4585 ret = filp_close(file, current->files);
4588 req_set_fail_links(req);
4591 __io_req_complete(req, issue_flags, ret, 0);
4595 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4597 struct io_ring_ctx *ctx = req->ctx;
4602 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4604 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4607 req->sync.off = READ_ONCE(sqe->off);
4608 req->sync.len = READ_ONCE(sqe->len);
4609 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4613 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4617 /* sync_file_range always requires a blocking context */
4618 if (issue_flags & IO_URING_F_NONBLOCK)
4621 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4624 req_set_fail_links(req);
4625 io_req_complete(req, ret);
4629 #if defined(CONFIG_NET)
4630 static int io_setup_async_msg(struct io_kiocb *req,
4631 struct io_async_msghdr *kmsg)
4633 struct io_async_msghdr *async_msg = req->async_data;
4637 if (io_alloc_async_data(req)) {
4638 kfree(kmsg->free_iov);
4641 async_msg = req->async_data;
4642 req->flags |= REQ_F_NEED_CLEANUP;
4643 memcpy(async_msg, kmsg, sizeof(*kmsg));
4644 async_msg->msg.msg_name = &async_msg->addr;
4645 /* if were using fast_iov, set it to the new one */
4646 if (!async_msg->free_iov)
4647 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4652 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4653 struct io_async_msghdr *iomsg)
4655 iomsg->msg.msg_name = &iomsg->addr;
4656 iomsg->free_iov = iomsg->fast_iov;
4657 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4658 req->sr_msg.msg_flags, &iomsg->free_iov);
4661 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4663 struct io_async_msghdr *async_msg = req->async_data;
4664 struct io_sr_msg *sr = &req->sr_msg;
4667 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4670 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4671 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4672 sr->len = READ_ONCE(sqe->len);
4674 #ifdef CONFIG_COMPAT
4675 if (req->ctx->compat)
4676 sr->msg_flags |= MSG_CMSG_COMPAT;
4679 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4681 ret = io_sendmsg_copy_hdr(req, async_msg);
4683 req->flags |= REQ_F_NEED_CLEANUP;
4687 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4689 struct io_async_msghdr iomsg, *kmsg;
4690 struct socket *sock;
4694 sock = sock_from_file(req->file);
4695 if (unlikely(!sock))
4698 kmsg = req->async_data;
4700 ret = io_sendmsg_copy_hdr(req, &iomsg);
4706 flags = req->sr_msg.msg_flags;
4707 if (flags & MSG_DONTWAIT)
4708 req->flags |= REQ_F_NOWAIT;
4709 else if (issue_flags & IO_URING_F_NONBLOCK)
4710 flags |= MSG_DONTWAIT;
4712 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4713 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4714 return io_setup_async_msg(req, kmsg);
4715 if (ret == -ERESTARTSYS)
4718 /* fast path, check for non-NULL to avoid function call */
4720 kfree(kmsg->free_iov);
4721 req->flags &= ~REQ_F_NEED_CLEANUP;
4723 req_set_fail_links(req);
4724 __io_req_complete(req, issue_flags, ret, 0);
4728 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4730 struct io_sr_msg *sr = &req->sr_msg;
4733 struct socket *sock;
4737 sock = sock_from_file(req->file);
4738 if (unlikely(!sock))
4741 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4745 msg.msg_name = NULL;
4746 msg.msg_control = NULL;
4747 msg.msg_controllen = 0;
4748 msg.msg_namelen = 0;
4750 flags = req->sr_msg.msg_flags;
4751 if (flags & MSG_DONTWAIT)
4752 req->flags |= REQ_F_NOWAIT;
4753 else if (issue_flags & IO_URING_F_NONBLOCK)
4754 flags |= MSG_DONTWAIT;
4756 msg.msg_flags = flags;
4757 ret = sock_sendmsg(sock, &msg);
4758 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4760 if (ret == -ERESTARTSYS)
4764 req_set_fail_links(req);
4765 __io_req_complete(req, issue_flags, ret, 0);
4769 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4770 struct io_async_msghdr *iomsg)
4772 struct io_sr_msg *sr = &req->sr_msg;
4773 struct iovec __user *uiov;
4777 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4778 &iomsg->uaddr, &uiov, &iov_len);
4782 if (req->flags & REQ_F_BUFFER_SELECT) {
4785 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4787 sr->len = iomsg->fast_iov[0].iov_len;
4788 iomsg->free_iov = NULL;
4790 iomsg->free_iov = iomsg->fast_iov;
4791 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4792 &iomsg->free_iov, &iomsg->msg.msg_iter,
4801 #ifdef CONFIG_COMPAT
4802 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4803 struct io_async_msghdr *iomsg)
4805 struct compat_msghdr __user *msg_compat;
4806 struct io_sr_msg *sr = &req->sr_msg;
4807 struct compat_iovec __user *uiov;
4812 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4813 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4818 uiov = compat_ptr(ptr);
4819 if (req->flags & REQ_F_BUFFER_SELECT) {
4820 compat_ssize_t clen;
4824 if (!access_ok(uiov, sizeof(*uiov)))
4826 if (__get_user(clen, &uiov->iov_len))
4831 iomsg->free_iov = NULL;
4833 iomsg->free_iov = iomsg->fast_iov;
4834 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4835 UIO_FASTIOV, &iomsg->free_iov,
4836 &iomsg->msg.msg_iter, true);
4845 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4846 struct io_async_msghdr *iomsg)
4848 iomsg->msg.msg_name = &iomsg->addr;
4850 #ifdef CONFIG_COMPAT
4851 if (req->ctx->compat)
4852 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4855 return __io_recvmsg_copy_hdr(req, iomsg);
4858 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4861 struct io_sr_msg *sr = &req->sr_msg;
4862 struct io_buffer *kbuf;
4864 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4869 req->flags |= REQ_F_BUFFER_SELECTED;
4873 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4875 return io_put_kbuf(req, req->sr_msg.kbuf);
4878 static int io_recvmsg_prep(struct io_kiocb *req,
4879 const struct io_uring_sqe *sqe)
4881 struct io_async_msghdr *async_msg = req->async_data;
4882 struct io_sr_msg *sr = &req->sr_msg;
4885 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4888 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4889 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4890 sr->len = READ_ONCE(sqe->len);
4891 sr->bgid = READ_ONCE(sqe->buf_group);
4893 #ifdef CONFIG_COMPAT
4894 if (req->ctx->compat)
4895 sr->msg_flags |= MSG_CMSG_COMPAT;
4898 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4900 ret = io_recvmsg_copy_hdr(req, async_msg);
4902 req->flags |= REQ_F_NEED_CLEANUP;
4906 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4908 struct io_async_msghdr iomsg, *kmsg;
4909 struct socket *sock;
4910 struct io_buffer *kbuf;
4912 int ret, cflags = 0;
4913 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4915 sock = sock_from_file(req->file);
4916 if (unlikely(!sock))
4919 kmsg = req->async_data;
4921 ret = io_recvmsg_copy_hdr(req, &iomsg);
4927 if (req->flags & REQ_F_BUFFER_SELECT) {
4928 kbuf = io_recv_buffer_select(req, !force_nonblock);
4930 return PTR_ERR(kbuf);
4931 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4932 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4933 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4934 1, req->sr_msg.len);
4937 flags = req->sr_msg.msg_flags;
4938 if (flags & MSG_DONTWAIT)
4939 req->flags |= REQ_F_NOWAIT;
4940 else if (force_nonblock)
4941 flags |= MSG_DONTWAIT;
4943 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4944 kmsg->uaddr, flags);
4945 if (force_nonblock && ret == -EAGAIN)
4946 return io_setup_async_msg(req, kmsg);
4947 if (ret == -ERESTARTSYS)
4950 if (req->flags & REQ_F_BUFFER_SELECTED)
4951 cflags = io_put_recv_kbuf(req);
4952 /* fast path, check for non-NULL to avoid function call */
4954 kfree(kmsg->free_iov);
4955 req->flags &= ~REQ_F_NEED_CLEANUP;
4957 req_set_fail_links(req);
4958 __io_req_complete(req, issue_flags, ret, cflags);
4962 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4964 struct io_buffer *kbuf;
4965 struct io_sr_msg *sr = &req->sr_msg;
4967 void __user *buf = sr->buf;
4968 struct socket *sock;
4971 int ret, cflags = 0;
4972 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4974 sock = sock_from_file(req->file);
4975 if (unlikely(!sock))
4978 if (req->flags & REQ_F_BUFFER_SELECT) {
4979 kbuf = io_recv_buffer_select(req, !force_nonblock);
4981 return PTR_ERR(kbuf);
4982 buf = u64_to_user_ptr(kbuf->addr);
4985 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4989 msg.msg_name = NULL;
4990 msg.msg_control = NULL;
4991 msg.msg_controllen = 0;
4992 msg.msg_namelen = 0;
4993 msg.msg_iocb = NULL;
4996 flags = req->sr_msg.msg_flags;
4997 if (flags & MSG_DONTWAIT)
4998 req->flags |= REQ_F_NOWAIT;
4999 else if (force_nonblock)
5000 flags |= MSG_DONTWAIT;
5002 ret = sock_recvmsg(sock, &msg, flags);
5003 if (force_nonblock && ret == -EAGAIN)
5005 if (ret == -ERESTARTSYS)
5008 if (req->flags & REQ_F_BUFFER_SELECTED)
5009 cflags = io_put_recv_kbuf(req);
5011 req_set_fail_links(req);
5012 __io_req_complete(req, issue_flags, ret, cflags);
5016 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5018 struct io_accept *accept = &req->accept;
5020 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5022 if (sqe->ioprio || sqe->len || sqe->buf_index)
5025 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5026 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5027 accept->flags = READ_ONCE(sqe->accept_flags);
5028 accept->nofile = rlimit(RLIMIT_NOFILE);
5032 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5034 struct io_accept *accept = &req->accept;
5035 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5036 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5039 if (req->file->f_flags & O_NONBLOCK)
5040 req->flags |= REQ_F_NOWAIT;
5042 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
5043 accept->addr_len, accept->flags,
5045 if (ret == -EAGAIN && force_nonblock)
5048 if (ret == -ERESTARTSYS)
5050 req_set_fail_links(req);
5052 __io_req_complete(req, issue_flags, ret, 0);
5056 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5058 struct io_connect *conn = &req->connect;
5059 struct io_async_connect *io = req->async_data;
5061 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5063 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
5066 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5067 conn->addr_len = READ_ONCE(sqe->addr2);
5072 return move_addr_to_kernel(conn->addr, conn->addr_len,
5076 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5078 struct io_async_connect __io, *io;
5079 unsigned file_flags;
5081 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5083 if (req->async_data) {
5084 io = req->async_data;
5086 ret = move_addr_to_kernel(req->connect.addr,
5087 req->connect.addr_len,
5094 file_flags = force_nonblock ? O_NONBLOCK : 0;
5096 ret = __sys_connect_file(req->file, &io->address,
5097 req->connect.addr_len, file_flags);
5098 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5099 if (req->async_data)
5101 if (io_alloc_async_data(req)) {
5105 io = req->async_data;
5106 memcpy(req->async_data, &__io, sizeof(__io));
5109 if (ret == -ERESTARTSYS)
5113 req_set_fail_links(req);
5114 __io_req_complete(req, issue_flags, ret, 0);
5117 #else /* !CONFIG_NET */
5118 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5123 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5128 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5133 static int io_recvmsg_prep(struct io_kiocb *req,
5134 const struct io_uring_sqe *sqe)
5139 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5144 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5149 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5154 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5159 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5164 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5168 #endif /* CONFIG_NET */
5170 struct io_poll_table {
5171 struct poll_table_struct pt;
5172 struct io_kiocb *req;
5176 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5177 __poll_t mask, task_work_func_t func)
5181 /* for instances that support it check for an event match first: */
5182 if (mask && !(mask & poll->events))
5185 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5187 list_del_init(&poll->wait.entry);
5190 req->task_work.func = func;
5191 percpu_ref_get(&req->ctx->refs);
5194 * If this fails, then the task is exiting. When a task exits, the
5195 * work gets canceled, so just cancel this request as well instead
5196 * of executing it. We can't safely execute it anyway, as we may not
5197 * have the needed state needed for it anyway.
5199 ret = io_req_task_work_add(req);
5200 if (unlikely(ret)) {
5201 WRITE_ONCE(poll->canceled, true);
5202 io_req_task_work_add_fallback(req, func);
5207 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5208 __acquires(&req->ctx->completion_lock)
5210 struct io_ring_ctx *ctx = req->ctx;
5212 if (!req->result && !READ_ONCE(poll->canceled)) {
5213 struct poll_table_struct pt = { ._key = poll->events };
5215 req->result = vfs_poll(req->file, &pt) & poll->events;
5218 spin_lock_irq(&ctx->completion_lock);
5219 if (!req->result && !READ_ONCE(poll->canceled)) {
5220 add_wait_queue(poll->head, &poll->wait);
5227 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5229 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5230 if (req->opcode == IORING_OP_POLL_ADD)
5231 return req->async_data;
5232 return req->apoll->double_poll;
5235 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5237 if (req->opcode == IORING_OP_POLL_ADD)
5239 return &req->apoll->poll;
5242 static void io_poll_remove_double(struct io_kiocb *req)
5244 struct io_poll_iocb *poll = io_poll_get_double(req);
5246 lockdep_assert_held(&req->ctx->completion_lock);
5248 if (poll && poll->head) {
5249 struct wait_queue_head *head = poll->head;
5251 spin_lock(&head->lock);
5252 list_del_init(&poll->wait.entry);
5253 if (poll->wait.private)
5254 refcount_dec(&req->refs);
5256 spin_unlock(&head->lock);
5260 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5262 struct io_ring_ctx *ctx = req->ctx;
5264 io_poll_remove_double(req);
5265 req->poll.done = true;
5266 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5267 io_commit_cqring(ctx);
5270 static void io_poll_task_func(struct callback_head *cb)
5272 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5273 struct io_ring_ctx *ctx = req->ctx;
5274 struct io_kiocb *nxt;
5276 if (io_poll_rewait(req, &req->poll)) {
5277 spin_unlock_irq(&ctx->completion_lock);
5279 hash_del(&req->hash_node);
5280 io_poll_complete(req, req->result, 0);
5281 spin_unlock_irq(&ctx->completion_lock);
5283 nxt = io_put_req_find_next(req);
5284 io_cqring_ev_posted(ctx);
5286 __io_req_task_submit(nxt);
5289 percpu_ref_put(&ctx->refs);
5292 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5293 int sync, void *key)
5295 struct io_kiocb *req = wait->private;
5296 struct io_poll_iocb *poll = io_poll_get_single(req);
5297 __poll_t mask = key_to_poll(key);
5299 /* for instances that support it check for an event match first: */
5300 if (mask && !(mask & poll->events))
5303 list_del_init(&wait->entry);
5305 if (poll && poll->head) {
5308 spin_lock(&poll->head->lock);
5309 done = list_empty(&poll->wait.entry);
5311 list_del_init(&poll->wait.entry);
5312 /* make sure double remove sees this as being gone */
5313 wait->private = NULL;
5314 spin_unlock(&poll->head->lock);
5316 /* use wait func handler, so it matches the rq type */
5317 poll->wait.func(&poll->wait, mode, sync, key);
5320 refcount_dec(&req->refs);
5324 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5325 wait_queue_func_t wake_func)
5329 poll->canceled = false;
5330 poll->events = events;
5331 INIT_LIST_HEAD(&poll->wait.entry);
5332 init_waitqueue_func_entry(&poll->wait, wake_func);
5335 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5336 struct wait_queue_head *head,
5337 struct io_poll_iocb **poll_ptr)
5339 struct io_kiocb *req = pt->req;
5342 * If poll->head is already set, it's because the file being polled
5343 * uses multiple waitqueues for poll handling (eg one for read, one
5344 * for write). Setup a separate io_poll_iocb if this happens.
5346 if (unlikely(poll->head)) {
5347 struct io_poll_iocb *poll_one = poll;
5349 /* already have a 2nd entry, fail a third attempt */
5351 pt->error = -EINVAL;
5354 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5356 pt->error = -ENOMEM;
5359 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5360 refcount_inc(&req->refs);
5361 poll->wait.private = req;
5368 if (poll->events & EPOLLEXCLUSIVE)
5369 add_wait_queue_exclusive(head, &poll->wait);
5371 add_wait_queue(head, &poll->wait);
5374 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5375 struct poll_table_struct *p)
5377 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5378 struct async_poll *apoll = pt->req->apoll;
5380 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5383 static void io_async_task_func(struct callback_head *cb)
5385 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5386 struct async_poll *apoll = req->apoll;
5387 struct io_ring_ctx *ctx = req->ctx;
5389 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5391 if (io_poll_rewait(req, &apoll->poll)) {
5392 spin_unlock_irq(&ctx->completion_lock);
5393 percpu_ref_put(&ctx->refs);
5397 /* If req is still hashed, it cannot have been canceled. Don't check. */
5398 if (hash_hashed(&req->hash_node))
5399 hash_del(&req->hash_node);
5401 io_poll_remove_double(req);
5402 spin_unlock_irq(&ctx->completion_lock);
5404 if (!READ_ONCE(apoll->poll.canceled))
5405 __io_req_task_submit(req);
5407 __io_req_task_cancel(req, -ECANCELED);
5409 percpu_ref_put(&ctx->refs);
5410 kfree(apoll->double_poll);
5414 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5417 struct io_kiocb *req = wait->private;
5418 struct io_poll_iocb *poll = &req->apoll->poll;
5420 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5423 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5426 static void io_poll_req_insert(struct io_kiocb *req)
5428 struct io_ring_ctx *ctx = req->ctx;
5429 struct hlist_head *list;
5431 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5432 hlist_add_head(&req->hash_node, list);
5435 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5436 struct io_poll_iocb *poll,
5437 struct io_poll_table *ipt, __poll_t mask,
5438 wait_queue_func_t wake_func)
5439 __acquires(&ctx->completion_lock)
5441 struct io_ring_ctx *ctx = req->ctx;
5442 bool cancel = false;
5444 INIT_HLIST_NODE(&req->hash_node);
5445 io_init_poll_iocb(poll, mask, wake_func);
5446 poll->file = req->file;
5447 poll->wait.private = req;
5449 ipt->pt._key = mask;
5451 ipt->error = -EINVAL;
5453 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5455 spin_lock_irq(&ctx->completion_lock);
5456 if (likely(poll->head)) {
5457 spin_lock(&poll->head->lock);
5458 if (unlikely(list_empty(&poll->wait.entry))) {
5464 if (mask || ipt->error)
5465 list_del_init(&poll->wait.entry);
5467 WRITE_ONCE(poll->canceled, true);
5468 else if (!poll->done) /* actually waiting for an event */
5469 io_poll_req_insert(req);
5470 spin_unlock(&poll->head->lock);
5476 static bool io_arm_poll_handler(struct io_kiocb *req)
5478 const struct io_op_def *def = &io_op_defs[req->opcode];
5479 struct io_ring_ctx *ctx = req->ctx;
5480 struct async_poll *apoll;
5481 struct io_poll_table ipt;
5485 if (!req->file || !file_can_poll(req->file))
5487 if (req->flags & REQ_F_POLLED)
5491 else if (def->pollout)
5495 /* if we can't nonblock try, then no point in arming a poll handler */
5496 if (!io_file_supports_async(req->file, rw))
5499 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5500 if (unlikely(!apoll))
5502 apoll->double_poll = NULL;
5504 req->flags |= REQ_F_POLLED;
5509 mask |= POLLIN | POLLRDNORM;
5511 mask |= POLLOUT | POLLWRNORM;
5513 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5514 if ((req->opcode == IORING_OP_RECVMSG) &&
5515 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5518 mask |= POLLERR | POLLPRI;
5520 ipt.pt._qproc = io_async_queue_proc;
5522 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5524 if (ret || ipt.error) {
5525 io_poll_remove_double(req);
5526 spin_unlock_irq(&ctx->completion_lock);
5527 kfree(apoll->double_poll);
5531 spin_unlock_irq(&ctx->completion_lock);
5532 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5533 apoll->poll.events);
5537 static bool __io_poll_remove_one(struct io_kiocb *req,
5538 struct io_poll_iocb *poll)
5540 bool do_complete = false;
5542 spin_lock(&poll->head->lock);
5543 WRITE_ONCE(poll->canceled, true);
5544 if (!list_empty(&poll->wait.entry)) {
5545 list_del_init(&poll->wait.entry);
5548 spin_unlock(&poll->head->lock);
5549 hash_del(&req->hash_node);
5553 static bool io_poll_remove_one(struct io_kiocb *req)
5557 io_poll_remove_double(req);
5559 if (req->opcode == IORING_OP_POLL_ADD) {
5560 do_complete = __io_poll_remove_one(req, &req->poll);
5562 struct async_poll *apoll = req->apoll;
5564 /* non-poll requests have submit ref still */
5565 do_complete = __io_poll_remove_one(req, &apoll->poll);
5568 kfree(apoll->double_poll);
5574 io_cqring_fill_event(req, -ECANCELED);
5575 io_commit_cqring(req->ctx);
5576 req_set_fail_links(req);
5577 io_put_req_deferred(req, 1);
5584 * Returns true if we found and killed one or more poll requests
5586 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5587 struct files_struct *files)
5589 struct hlist_node *tmp;
5590 struct io_kiocb *req;
5593 spin_lock_irq(&ctx->completion_lock);
5594 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5595 struct hlist_head *list;
5597 list = &ctx->cancel_hash[i];
5598 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5599 if (io_match_task(req, tsk, files))
5600 posted += io_poll_remove_one(req);
5603 spin_unlock_irq(&ctx->completion_lock);
5606 io_cqring_ev_posted(ctx);
5611 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5613 struct hlist_head *list;
5614 struct io_kiocb *req;
5616 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5617 hlist_for_each_entry(req, list, hash_node) {
5618 if (sqe_addr != req->user_data)
5620 if (io_poll_remove_one(req))
5628 static int io_poll_remove_prep(struct io_kiocb *req,
5629 const struct io_uring_sqe *sqe)
5631 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5633 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5637 req->poll_remove.addr = READ_ONCE(sqe->addr);
5642 * Find a running poll command that matches one specified in sqe->addr,
5643 * and remove it if found.
5645 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5647 struct io_ring_ctx *ctx = req->ctx;
5650 spin_lock_irq(&ctx->completion_lock);
5651 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5652 spin_unlock_irq(&ctx->completion_lock);
5655 req_set_fail_links(req);
5656 io_req_complete(req, ret);
5660 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5663 struct io_kiocb *req = wait->private;
5664 struct io_poll_iocb *poll = &req->poll;
5666 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5669 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5670 struct poll_table_struct *p)
5672 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5674 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5677 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5679 struct io_poll_iocb *poll = &req->poll;
5682 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5684 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5687 events = READ_ONCE(sqe->poll32_events);
5689 events = swahw32(events);
5691 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5692 (events & EPOLLEXCLUSIVE);
5696 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5698 struct io_poll_iocb *poll = &req->poll;
5699 struct io_ring_ctx *ctx = req->ctx;
5700 struct io_poll_table ipt;
5703 ipt.pt._qproc = io_poll_queue_proc;
5705 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5708 if (mask) { /* no async, we'd stolen it */
5710 io_poll_complete(req, mask, 0);
5712 spin_unlock_irq(&ctx->completion_lock);
5715 io_cqring_ev_posted(ctx);
5721 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5723 struct io_timeout_data *data = container_of(timer,
5724 struct io_timeout_data, timer);
5725 struct io_kiocb *req = data->req;
5726 struct io_ring_ctx *ctx = req->ctx;
5727 unsigned long flags;
5729 spin_lock_irqsave(&ctx->completion_lock, flags);
5730 list_del_init(&req->timeout.list);
5731 atomic_set(&req->ctx->cq_timeouts,
5732 atomic_read(&req->ctx->cq_timeouts) + 1);
5734 io_cqring_fill_event(req, -ETIME);
5735 io_commit_cqring(ctx);
5736 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5738 io_cqring_ev_posted(ctx);
5739 req_set_fail_links(req);
5741 return HRTIMER_NORESTART;
5744 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5747 struct io_timeout_data *io;
5748 struct io_kiocb *req;
5751 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5752 if (user_data == req->user_data) {
5759 return ERR_PTR(ret);
5761 io = req->async_data;
5762 ret = hrtimer_try_to_cancel(&io->timer);
5764 return ERR_PTR(-EALREADY);
5765 list_del_init(&req->timeout.list);
5769 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5771 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5774 return PTR_ERR(req);
5776 req_set_fail_links(req);
5777 io_cqring_fill_event(req, -ECANCELED);
5778 io_put_req_deferred(req, 1);
5782 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5783 struct timespec64 *ts, enum hrtimer_mode mode)
5785 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5786 struct io_timeout_data *data;
5789 return PTR_ERR(req);
5791 req->timeout.off = 0; /* noseq */
5792 data = req->async_data;
5793 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5794 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5795 data->timer.function = io_timeout_fn;
5796 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5800 static int io_timeout_remove_prep(struct io_kiocb *req,
5801 const struct io_uring_sqe *sqe)
5803 struct io_timeout_rem *tr = &req->timeout_rem;
5805 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5807 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5809 if (sqe->ioprio || sqe->buf_index || sqe->len)
5812 tr->addr = READ_ONCE(sqe->addr);
5813 tr->flags = READ_ONCE(sqe->timeout_flags);
5814 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5815 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5817 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5819 } else if (tr->flags) {
5820 /* timeout removal doesn't support flags */
5827 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5829 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5834 * Remove or update an existing timeout command
5836 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5838 struct io_timeout_rem *tr = &req->timeout_rem;
5839 struct io_ring_ctx *ctx = req->ctx;
5842 spin_lock_irq(&ctx->completion_lock);
5843 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5844 ret = io_timeout_cancel(ctx, tr->addr);
5846 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5847 io_translate_timeout_mode(tr->flags));
5849 io_cqring_fill_event(req, ret);
5850 io_commit_cqring(ctx);
5851 spin_unlock_irq(&ctx->completion_lock);
5852 io_cqring_ev_posted(ctx);
5854 req_set_fail_links(req);
5859 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5860 bool is_timeout_link)
5862 struct io_timeout_data *data;
5864 u32 off = READ_ONCE(sqe->off);
5866 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5868 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5870 if (off && is_timeout_link)
5872 flags = READ_ONCE(sqe->timeout_flags);
5873 if (flags & ~IORING_TIMEOUT_ABS)
5876 req->timeout.off = off;
5878 if (!req->async_data && io_alloc_async_data(req))
5881 data = req->async_data;
5884 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5887 data->mode = io_translate_timeout_mode(flags);
5888 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5892 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5894 struct io_ring_ctx *ctx = req->ctx;
5895 struct io_timeout_data *data = req->async_data;
5896 struct list_head *entry;
5897 u32 tail, off = req->timeout.off;
5899 spin_lock_irq(&ctx->completion_lock);
5902 * sqe->off holds how many events that need to occur for this
5903 * timeout event to be satisfied. If it isn't set, then this is
5904 * a pure timeout request, sequence isn't used.
5906 if (io_is_timeout_noseq(req)) {
5907 entry = ctx->timeout_list.prev;
5911 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5912 req->timeout.target_seq = tail + off;
5914 /* Update the last seq here in case io_flush_timeouts() hasn't.
5915 * This is safe because ->completion_lock is held, and submissions
5916 * and completions are never mixed in the same ->completion_lock section.
5918 ctx->cq_last_tm_flush = tail;
5921 * Insertion sort, ensuring the first entry in the list is always
5922 * the one we need first.
5924 list_for_each_prev(entry, &ctx->timeout_list) {
5925 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5928 if (io_is_timeout_noseq(nxt))
5930 /* nxt.seq is behind @tail, otherwise would've been completed */
5931 if (off >= nxt->timeout.target_seq - tail)
5935 list_add(&req->timeout.list, entry);
5936 data->timer.function = io_timeout_fn;
5937 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5938 spin_unlock_irq(&ctx->completion_lock);
5942 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5944 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5946 return req->user_data == (unsigned long) data;
5949 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5951 enum io_wq_cancel cancel_ret;
5954 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5955 switch (cancel_ret) {
5956 case IO_WQ_CANCEL_OK:
5959 case IO_WQ_CANCEL_RUNNING:
5962 case IO_WQ_CANCEL_NOTFOUND:
5970 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5971 struct io_kiocb *req, __u64 sqe_addr,
5974 unsigned long flags;
5977 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5978 if (ret != -ENOENT) {
5979 spin_lock_irqsave(&ctx->completion_lock, flags);
5983 spin_lock_irqsave(&ctx->completion_lock, flags);
5984 ret = io_timeout_cancel(ctx, sqe_addr);
5987 ret = io_poll_cancel(ctx, sqe_addr);
5991 io_cqring_fill_event(req, ret);
5992 io_commit_cqring(ctx);
5993 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5994 io_cqring_ev_posted(ctx);
5997 req_set_fail_links(req);
6001 static int io_async_cancel_prep(struct io_kiocb *req,
6002 const struct io_uring_sqe *sqe)
6004 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6006 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6008 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
6011 req->cancel.addr = READ_ONCE(sqe->addr);
6015 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6017 struct io_ring_ctx *ctx = req->ctx;
6019 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
6023 static int io_rsrc_update_prep(struct io_kiocb *req,
6024 const struct io_uring_sqe *sqe)
6026 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
6028 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6030 if (sqe->ioprio || sqe->rw_flags)
6033 req->rsrc_update.offset = READ_ONCE(sqe->off);
6034 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6035 if (!req->rsrc_update.nr_args)
6037 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6041 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6043 struct io_ring_ctx *ctx = req->ctx;
6044 struct io_uring_rsrc_update up;
6047 if (issue_flags & IO_URING_F_NONBLOCK)
6050 up.offset = req->rsrc_update.offset;
6051 up.data = req->rsrc_update.arg;
6053 mutex_lock(&ctx->uring_lock);
6054 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
6055 mutex_unlock(&ctx->uring_lock);
6058 req_set_fail_links(req);
6059 __io_req_complete(req, issue_flags, ret, 0);
6063 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6065 switch (req->opcode) {
6068 case IORING_OP_READV:
6069 case IORING_OP_READ_FIXED:
6070 case IORING_OP_READ:
6071 return io_read_prep(req, sqe);
6072 case IORING_OP_WRITEV:
6073 case IORING_OP_WRITE_FIXED:
6074 case IORING_OP_WRITE:
6075 return io_write_prep(req, sqe);
6076 case IORING_OP_POLL_ADD:
6077 return io_poll_add_prep(req, sqe);
6078 case IORING_OP_POLL_REMOVE:
6079 return io_poll_remove_prep(req, sqe);
6080 case IORING_OP_FSYNC:
6081 return io_prep_fsync(req, sqe);
6082 case IORING_OP_SYNC_FILE_RANGE:
6083 return io_prep_sfr(req, sqe);
6084 case IORING_OP_SENDMSG:
6085 case IORING_OP_SEND:
6086 return io_sendmsg_prep(req, sqe);
6087 case IORING_OP_RECVMSG:
6088 case IORING_OP_RECV:
6089 return io_recvmsg_prep(req, sqe);
6090 case IORING_OP_CONNECT:
6091 return io_connect_prep(req, sqe);
6092 case IORING_OP_TIMEOUT:
6093 return io_timeout_prep(req, sqe, false);
6094 case IORING_OP_TIMEOUT_REMOVE:
6095 return io_timeout_remove_prep(req, sqe);
6096 case IORING_OP_ASYNC_CANCEL:
6097 return io_async_cancel_prep(req, sqe);
6098 case IORING_OP_LINK_TIMEOUT:
6099 return io_timeout_prep(req, sqe, true);
6100 case IORING_OP_ACCEPT:
6101 return io_accept_prep(req, sqe);
6102 case IORING_OP_FALLOCATE:
6103 return io_fallocate_prep(req, sqe);
6104 case IORING_OP_OPENAT:
6105 return io_openat_prep(req, sqe);
6106 case IORING_OP_CLOSE:
6107 return io_close_prep(req, sqe);
6108 case IORING_OP_FILES_UPDATE:
6109 return io_rsrc_update_prep(req, sqe);
6110 case IORING_OP_STATX:
6111 return io_statx_prep(req, sqe);
6112 case IORING_OP_FADVISE:
6113 return io_fadvise_prep(req, sqe);
6114 case IORING_OP_MADVISE:
6115 return io_madvise_prep(req, sqe);
6116 case IORING_OP_OPENAT2:
6117 return io_openat2_prep(req, sqe);
6118 case IORING_OP_EPOLL_CTL:
6119 return io_epoll_ctl_prep(req, sqe);
6120 case IORING_OP_SPLICE:
6121 return io_splice_prep(req, sqe);
6122 case IORING_OP_PROVIDE_BUFFERS:
6123 return io_provide_buffers_prep(req, sqe);
6124 case IORING_OP_REMOVE_BUFFERS:
6125 return io_remove_buffers_prep(req, sqe);
6127 return io_tee_prep(req, sqe);
6128 case IORING_OP_SHUTDOWN:
6129 return io_shutdown_prep(req, sqe);
6130 case IORING_OP_RENAMEAT:
6131 return io_renameat_prep(req, sqe);
6132 case IORING_OP_UNLINKAT:
6133 return io_unlinkat_prep(req, sqe);
6136 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6141 static int io_req_defer_prep(struct io_kiocb *req,
6142 const struct io_uring_sqe *sqe)
6146 if (io_alloc_async_data(req))
6148 return io_req_prep(req, sqe);
6151 static u32 io_get_sequence(struct io_kiocb *req)
6153 struct io_kiocb *pos;
6154 struct io_ring_ctx *ctx = req->ctx;
6155 u32 total_submitted, nr_reqs = 0;
6157 io_for_each_link(pos, req)
6160 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6161 return total_submitted - nr_reqs;
6164 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6166 struct io_ring_ctx *ctx = req->ctx;
6167 struct io_defer_entry *de;
6171 /* Still need defer if there is pending req in defer list. */
6172 if (likely(list_empty_careful(&ctx->defer_list) &&
6173 !(req->flags & REQ_F_IO_DRAIN)))
6176 seq = io_get_sequence(req);
6177 /* Still a chance to pass the sequence check */
6178 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6181 if (!req->async_data) {
6182 ret = io_req_defer_prep(req, sqe);
6186 io_prep_async_link(req);
6187 de = kmalloc(sizeof(*de), GFP_KERNEL);
6191 spin_lock_irq(&ctx->completion_lock);
6192 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6193 spin_unlock_irq(&ctx->completion_lock);
6195 io_queue_async_work(req);
6196 return -EIOCBQUEUED;
6199 trace_io_uring_defer(ctx, req, req->user_data);
6202 list_add_tail(&de->list, &ctx->defer_list);
6203 spin_unlock_irq(&ctx->completion_lock);
6204 return -EIOCBQUEUED;
6207 static void __io_clean_op(struct io_kiocb *req)
6209 if (req->flags & REQ_F_BUFFER_SELECTED) {
6210 switch (req->opcode) {
6211 case IORING_OP_READV:
6212 case IORING_OP_READ_FIXED:
6213 case IORING_OP_READ:
6214 kfree((void *)(unsigned long)req->rw.addr);
6216 case IORING_OP_RECVMSG:
6217 case IORING_OP_RECV:
6218 kfree(req->sr_msg.kbuf);
6221 req->flags &= ~REQ_F_BUFFER_SELECTED;
6224 if (req->flags & REQ_F_NEED_CLEANUP) {
6225 switch (req->opcode) {
6226 case IORING_OP_READV:
6227 case IORING_OP_READ_FIXED:
6228 case IORING_OP_READ:
6229 case IORING_OP_WRITEV:
6230 case IORING_OP_WRITE_FIXED:
6231 case IORING_OP_WRITE: {
6232 struct io_async_rw *io = req->async_data;
6234 kfree(io->free_iovec);
6237 case IORING_OP_RECVMSG:
6238 case IORING_OP_SENDMSG: {
6239 struct io_async_msghdr *io = req->async_data;
6241 kfree(io->free_iov);
6244 case IORING_OP_SPLICE:
6246 io_put_file(req, req->splice.file_in,
6247 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6249 case IORING_OP_OPENAT:
6250 case IORING_OP_OPENAT2:
6251 if (req->open.filename)
6252 putname(req->open.filename);
6254 case IORING_OP_RENAMEAT:
6255 putname(req->rename.oldpath);
6256 putname(req->rename.newpath);
6258 case IORING_OP_UNLINKAT:
6259 putname(req->unlink.filename);
6262 req->flags &= ~REQ_F_NEED_CLEANUP;
6266 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6268 struct io_ring_ctx *ctx = req->ctx;
6271 switch (req->opcode) {
6273 ret = io_nop(req, issue_flags);
6275 case IORING_OP_READV:
6276 case IORING_OP_READ_FIXED:
6277 case IORING_OP_READ:
6278 ret = io_read(req, issue_flags);
6280 case IORING_OP_WRITEV:
6281 case IORING_OP_WRITE_FIXED:
6282 case IORING_OP_WRITE:
6283 ret = io_write(req, issue_flags);
6285 case IORING_OP_FSYNC:
6286 ret = io_fsync(req, issue_flags);
6288 case IORING_OP_POLL_ADD:
6289 ret = io_poll_add(req, issue_flags);
6291 case IORING_OP_POLL_REMOVE:
6292 ret = io_poll_remove(req, issue_flags);
6294 case IORING_OP_SYNC_FILE_RANGE:
6295 ret = io_sync_file_range(req, issue_flags);
6297 case IORING_OP_SENDMSG:
6298 ret = io_sendmsg(req, issue_flags);
6300 case IORING_OP_SEND:
6301 ret = io_send(req, issue_flags);
6303 case IORING_OP_RECVMSG:
6304 ret = io_recvmsg(req, issue_flags);
6306 case IORING_OP_RECV:
6307 ret = io_recv(req, issue_flags);
6309 case IORING_OP_TIMEOUT:
6310 ret = io_timeout(req, issue_flags);
6312 case IORING_OP_TIMEOUT_REMOVE:
6313 ret = io_timeout_remove(req, issue_flags);
6315 case IORING_OP_ACCEPT:
6316 ret = io_accept(req, issue_flags);
6318 case IORING_OP_CONNECT:
6319 ret = io_connect(req, issue_flags);
6321 case IORING_OP_ASYNC_CANCEL:
6322 ret = io_async_cancel(req, issue_flags);
6324 case IORING_OP_FALLOCATE:
6325 ret = io_fallocate(req, issue_flags);
6327 case IORING_OP_OPENAT:
6328 ret = io_openat(req, issue_flags);
6330 case IORING_OP_CLOSE:
6331 ret = io_close(req, issue_flags);
6333 case IORING_OP_FILES_UPDATE:
6334 ret = io_files_update(req, issue_flags);
6336 case IORING_OP_STATX:
6337 ret = io_statx(req, issue_flags);
6339 case IORING_OP_FADVISE:
6340 ret = io_fadvise(req, issue_flags);
6342 case IORING_OP_MADVISE:
6343 ret = io_madvise(req, issue_flags);
6345 case IORING_OP_OPENAT2:
6346 ret = io_openat2(req, issue_flags);
6348 case IORING_OP_EPOLL_CTL:
6349 ret = io_epoll_ctl(req, issue_flags);
6351 case IORING_OP_SPLICE:
6352 ret = io_splice(req, issue_flags);
6354 case IORING_OP_PROVIDE_BUFFERS:
6355 ret = io_provide_buffers(req, issue_flags);
6357 case IORING_OP_REMOVE_BUFFERS:
6358 ret = io_remove_buffers(req, issue_flags);
6361 ret = io_tee(req, issue_flags);
6363 case IORING_OP_SHUTDOWN:
6364 ret = io_shutdown(req, issue_flags);
6366 case IORING_OP_RENAMEAT:
6367 ret = io_renameat(req, issue_flags);
6369 case IORING_OP_UNLINKAT:
6370 ret = io_unlinkat(req, issue_flags);
6380 /* If the op doesn't have a file, we're not polling for it */
6381 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6382 const bool in_async = io_wq_current_is_worker();
6384 /* workqueue context doesn't hold uring_lock, grab it now */
6386 mutex_lock(&ctx->uring_lock);
6388 io_iopoll_req_issued(req, in_async);
6391 mutex_unlock(&ctx->uring_lock);
6397 static void io_wq_submit_work(struct io_wq_work *work)
6399 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6400 struct io_kiocb *timeout;
6403 timeout = io_prep_linked_timeout(req);
6405 io_queue_linked_timeout(timeout);
6407 if (work->flags & IO_WQ_WORK_CANCEL)
6412 ret = io_issue_sqe(req, 0);
6414 * We can get EAGAIN for polled IO even though we're
6415 * forcing a sync submission from here, since we can't
6416 * wait for request slots on the block side.
6425 struct io_ring_ctx *lock_ctx = NULL;
6427 if (req->ctx->flags & IORING_SETUP_IOPOLL)
6428 lock_ctx = req->ctx;
6431 * io_iopoll_complete() does not hold completion_lock to
6432 * complete polled io, so here for polled io, we can not call
6433 * io_req_complete() directly, otherwise there maybe concurrent
6434 * access to cqring, defer_list, etc, which is not safe. Given
6435 * that io_iopoll_complete() is always called under uring_lock,
6436 * so here for polled io, we also get uring_lock to complete
6440 mutex_lock(&lock_ctx->uring_lock);
6442 req_set_fail_links(req);
6443 io_req_complete(req, ret);
6446 mutex_unlock(&lock_ctx->uring_lock);
6450 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6453 struct fixed_rsrc_table *table;
6455 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6456 return table->files[index & IORING_FILE_TABLE_MASK];
6459 static struct file *io_file_get(struct io_submit_state *state,
6460 struct io_kiocb *req, int fd, bool fixed)
6462 struct io_ring_ctx *ctx = req->ctx;
6466 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6468 fd = array_index_nospec(fd, ctx->nr_user_files);
6469 file = io_file_from_index(ctx, fd);
6470 io_set_resource_node(req);
6472 trace_io_uring_file_get(ctx, fd);
6473 file = __io_file_get(state, fd);
6476 if (file && unlikely(file->f_op == &io_uring_fops))
6477 io_req_track_inflight(req);
6481 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6483 struct io_timeout_data *data = container_of(timer,
6484 struct io_timeout_data, timer);
6485 struct io_kiocb *prev, *req = data->req;
6486 struct io_ring_ctx *ctx = req->ctx;
6487 unsigned long flags;
6489 spin_lock_irqsave(&ctx->completion_lock, flags);
6490 prev = req->timeout.head;
6491 req->timeout.head = NULL;
6494 * We don't expect the list to be empty, that will only happen if we
6495 * race with the completion of the linked work.
6497 if (prev && refcount_inc_not_zero(&prev->refs))
6498 io_remove_next_linked(prev);
6501 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6504 req_set_fail_links(prev);
6505 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6506 io_put_req_deferred(prev, 1);
6508 io_req_complete_post(req, -ETIME, 0);
6509 io_put_req_deferred(req, 1);
6511 return HRTIMER_NORESTART;
6514 static void __io_queue_linked_timeout(struct io_kiocb *req)
6517 * If the back reference is NULL, then our linked request finished
6518 * before we got a chance to setup the timer
6520 if (req->timeout.head) {
6521 struct io_timeout_data *data = req->async_data;
6523 data->timer.function = io_link_timeout_fn;
6524 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6529 static void io_queue_linked_timeout(struct io_kiocb *req)
6531 struct io_ring_ctx *ctx = req->ctx;
6533 spin_lock_irq(&ctx->completion_lock);
6534 __io_queue_linked_timeout(req);
6535 spin_unlock_irq(&ctx->completion_lock);
6537 /* drop submission reference */
6541 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6543 struct io_kiocb *nxt = req->link;
6545 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6546 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6549 nxt->timeout.head = req;
6550 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6551 req->flags |= REQ_F_LINK_TIMEOUT;
6555 static void __io_queue_sqe(struct io_kiocb *req)
6557 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6558 const struct cred *old_creds = NULL;
6561 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6562 (req->work.flags & IO_WQ_WORK_CREDS) &&
6563 req->work.identity->creds != current_cred())
6564 old_creds = override_creds(req->work.identity->creds);
6566 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6569 revert_creds(old_creds);
6572 * We async punt it if the file wasn't marked NOWAIT, or if the file
6573 * doesn't support non-blocking read/write attempts
6575 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6576 if (!io_arm_poll_handler(req)) {
6578 * Queued up for async execution, worker will release
6579 * submit reference when the iocb is actually submitted.
6581 io_queue_async_work(req);
6583 } else if (likely(!ret)) {
6584 /* drop submission reference */
6585 if (req->flags & REQ_F_COMPLETE_INLINE) {
6586 struct io_ring_ctx *ctx = req->ctx;
6587 struct io_comp_state *cs = &ctx->submit_state.comp;
6589 cs->reqs[cs->nr++] = req;
6590 if (cs->nr == ARRAY_SIZE(cs->reqs))
6591 io_submit_flush_completions(cs, ctx);
6596 req_set_fail_links(req);
6598 io_req_complete(req, ret);
6601 io_queue_linked_timeout(linked_timeout);
6604 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6608 ret = io_req_defer(req, sqe);
6610 if (ret != -EIOCBQUEUED) {
6612 req_set_fail_links(req);
6614 io_req_complete(req, ret);
6616 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6617 if (!req->async_data) {
6618 ret = io_req_defer_prep(req, sqe);
6622 io_queue_async_work(req);
6625 ret = io_req_prep(req, sqe);
6629 __io_queue_sqe(req);
6633 static inline void io_queue_link_head(struct io_kiocb *req)
6635 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6637 io_req_complete(req, -ECANCELED);
6639 io_queue_sqe(req, NULL);
6642 struct io_submit_link {
6643 struct io_kiocb *head;
6644 struct io_kiocb *last;
6647 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6648 struct io_submit_link *link)
6650 struct io_ring_ctx *ctx = req->ctx;
6654 * If we already have a head request, queue this one for async
6655 * submittal once the head completes. If we don't have a head but
6656 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6657 * submitted sync once the chain is complete. If none of those
6658 * conditions are true (normal request), then just queue it.
6661 struct io_kiocb *head = link->head;
6664 * Taking sequential execution of a link, draining both sides
6665 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6666 * requests in the link. So, it drains the head and the
6667 * next after the link request. The last one is done via
6668 * drain_next flag to persist the effect across calls.
6670 if (req->flags & REQ_F_IO_DRAIN) {
6671 head->flags |= REQ_F_IO_DRAIN;
6672 ctx->drain_next = 1;
6674 ret = io_req_defer_prep(req, sqe);
6675 if (unlikely(ret)) {
6676 /* fail even hard links since we don't submit */
6677 head->flags |= REQ_F_FAIL_LINK;
6680 trace_io_uring_link(ctx, req, head);
6681 link->last->link = req;
6684 /* last request of a link, enqueue the link */
6685 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6686 io_queue_link_head(head);
6690 if (unlikely(ctx->drain_next)) {
6691 req->flags |= REQ_F_IO_DRAIN;
6692 ctx->drain_next = 0;
6694 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6695 ret = io_req_defer_prep(req, sqe);
6697 req->flags |= REQ_F_FAIL_LINK;
6701 io_queue_sqe(req, sqe);
6709 * Batched submission is done, ensure local IO is flushed out.
6711 static void io_submit_state_end(struct io_submit_state *state,
6712 struct io_ring_ctx *ctx)
6715 io_submit_flush_completions(&state->comp, ctx);
6716 if (state->plug_started)
6717 blk_finish_plug(&state->plug);
6718 io_state_file_put(state);
6722 * Start submission side cache.
6724 static void io_submit_state_start(struct io_submit_state *state,
6725 unsigned int max_ios)
6727 state->plug_started = false;
6728 state->ios_left = max_ios;
6731 static void io_commit_sqring(struct io_ring_ctx *ctx)
6733 struct io_rings *rings = ctx->rings;
6736 * Ensure any loads from the SQEs are done at this point,
6737 * since once we write the new head, the application could
6738 * write new data to them.
6740 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6744 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6745 * that is mapped by userspace. This means that care needs to be taken to
6746 * ensure that reads are stable, as we cannot rely on userspace always
6747 * being a good citizen. If members of the sqe are validated and then later
6748 * used, it's important that those reads are done through READ_ONCE() to
6749 * prevent a re-load down the line.
6751 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6753 u32 *sq_array = ctx->sq_array;
6757 * The cached sq head (or cq tail) serves two purposes:
6759 * 1) allows us to batch the cost of updating the user visible
6761 * 2) allows the kernel side to track the head on its own, even
6762 * though the application is the one updating it.
6764 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6765 if (likely(head < ctx->sq_entries))
6766 return &ctx->sq_sqes[head];
6768 /* drop invalid entries */
6769 ctx->cached_sq_dropped++;
6770 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6775 * Check SQE restrictions (opcode and flags).
6777 * Returns 'true' if SQE is allowed, 'false' otherwise.
6779 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6780 struct io_kiocb *req,
6781 unsigned int sqe_flags)
6783 if (!ctx->restricted)
6786 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6789 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6790 ctx->restrictions.sqe_flags_required)
6793 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6794 ctx->restrictions.sqe_flags_required))
6800 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6801 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6802 IOSQE_BUFFER_SELECT)
6804 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6805 const struct io_uring_sqe *sqe)
6807 struct io_submit_state *state;
6808 unsigned int sqe_flags;
6811 req->opcode = READ_ONCE(sqe->opcode);
6812 req->user_data = READ_ONCE(sqe->user_data);
6813 req->async_data = NULL;
6818 req->fixed_rsrc_refs = NULL;
6819 /* one is dropped after submission, the other at completion */
6820 refcount_set(&req->refs, 2);
6821 req->task = current;
6824 if (unlikely(req->opcode >= IORING_OP_LAST))
6827 if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6830 sqe_flags = READ_ONCE(sqe->flags);
6831 /* enforce forwards compatibility on users */
6832 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6835 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6838 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6839 !io_op_defs[req->opcode].buffer_select)
6842 id = READ_ONCE(sqe->personality);
6844 struct io_identity *iod;
6846 iod = idr_find(&ctx->personality_idr, id);
6849 refcount_inc(&iod->count);
6851 __io_req_init_async(req);
6852 get_cred(iod->creds);
6853 req->work.identity = iod;
6854 req->work.flags |= IO_WQ_WORK_CREDS;
6857 /* same numerical values with corresponding REQ_F_*, safe to copy */
6858 req->flags |= sqe_flags;
6859 state = &ctx->submit_state;
6862 * Plug now if we have more than 1 IO left after this, and the target
6863 * is potentially a read/write to block based storage.
6865 if (!state->plug_started && state->ios_left > 1 &&
6866 io_op_defs[req->opcode].plug) {
6867 blk_start_plug(&state->plug);
6868 state->plug_started = true;
6872 if (io_op_defs[req->opcode].needs_file) {
6873 bool fixed = req->flags & REQ_F_FIXED_FILE;
6875 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6876 if (unlikely(!req->file))
6884 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6886 struct io_submit_link link;
6887 int i, submitted = 0;
6889 /* if we have a backlog and couldn't flush it all, return BUSY */
6890 if (test_bit(0, &ctx->sq_check_overflow)) {
6891 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6895 /* make sure SQ entry isn't read before tail */
6896 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6898 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6901 percpu_counter_add(¤t->io_uring->inflight, nr);
6902 refcount_add(nr, ¤t->usage);
6904 io_submit_state_start(&ctx->submit_state, nr);
6907 for (i = 0; i < nr; i++) {
6908 const struct io_uring_sqe *sqe;
6909 struct io_kiocb *req;
6912 req = io_alloc_req(ctx);
6913 if (unlikely(!req)) {
6915 submitted = -EAGAIN;
6918 sqe = io_get_sqe(ctx);
6919 if (unlikely(!sqe)) {
6920 kmem_cache_free(req_cachep, req);
6923 /* will complete beyond this point, count as submitted */
6926 err = io_init_req(ctx, req, sqe);
6927 if (unlikely(err)) {
6930 io_req_complete(req, err);
6934 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6935 true, ctx->flags & IORING_SETUP_SQPOLL);
6936 err = io_submit_sqe(req, sqe, &link);
6941 if (unlikely(submitted != nr)) {
6942 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6943 struct io_uring_task *tctx = current->io_uring;
6944 int unused = nr - ref_used;
6946 percpu_ref_put_many(&ctx->refs, unused);
6947 percpu_counter_sub(&tctx->inflight, unused);
6948 put_task_struct_many(current, unused);
6951 io_queue_link_head(link.head);
6952 io_submit_state_end(&ctx->submit_state, ctx);
6954 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6955 io_commit_sqring(ctx);
6960 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6962 /* Tell userspace we may need a wakeup call */
6963 spin_lock_irq(&ctx->completion_lock);
6964 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6965 spin_unlock_irq(&ctx->completion_lock);
6968 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6970 spin_lock_irq(&ctx->completion_lock);
6971 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6972 spin_unlock_irq(&ctx->completion_lock);
6975 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6977 unsigned int to_submit;
6980 to_submit = io_sqring_entries(ctx);
6981 /* if we're handling multiple rings, cap submit size for fairness */
6982 if (cap_entries && to_submit > 8)
6985 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6986 unsigned nr_events = 0;
6988 mutex_lock(&ctx->uring_lock);
6989 if (!list_empty(&ctx->iopoll_list))
6990 io_do_iopoll(ctx, &nr_events, 0);
6992 if (to_submit && !ctx->sqo_dead &&
6993 likely(!percpu_ref_is_dying(&ctx->refs)))
6994 ret = io_submit_sqes(ctx, to_submit);
6995 mutex_unlock(&ctx->uring_lock);
6998 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6999 wake_up(&ctx->sqo_sq_wait);
7004 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7006 struct io_ring_ctx *ctx;
7007 unsigned sq_thread_idle = 0;
7009 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7010 if (sq_thread_idle < ctx->sq_thread_idle)
7011 sq_thread_idle = ctx->sq_thread_idle;
7014 sqd->sq_thread_idle = sq_thread_idle;
7017 static void io_sqd_init_new(struct io_sq_data *sqd)
7019 struct io_ring_ctx *ctx;
7021 while (!list_empty(&sqd->ctx_new_list)) {
7022 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
7023 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
7024 complete(&ctx->sq_thread_comp);
7027 io_sqd_update_thread_idle(sqd);
7030 static int io_sq_thread(void *data)
7032 struct cgroup_subsys_state *cur_css = NULL;
7033 struct files_struct *old_files = current->files;
7034 struct nsproxy *old_nsproxy = current->nsproxy;
7035 const struct cred *old_cred = NULL;
7036 struct io_sq_data *sqd = data;
7037 struct io_ring_ctx *ctx;
7038 unsigned long timeout = 0;
7042 current->files = NULL;
7043 current->nsproxy = NULL;
7044 task_unlock(current);
7046 while (!kthread_should_stop()) {
7048 bool cap_entries, sqt_spin, needs_sched;
7051 * Any changes to the sqd lists are synchronized through the
7052 * kthread parking. This synchronizes the thread vs users,
7053 * the users are synchronized on the sqd->ctx_lock.
7055 if (kthread_should_park()) {
7058 * When sq thread is unparked, in case the previous park operation
7059 * comes from io_put_sq_data(), which means that sq thread is going
7060 * to be stopped, so here needs to have a check.
7062 if (kthread_should_stop())
7066 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
7067 io_sqd_init_new(sqd);
7068 timeout = jiffies + sqd->sq_thread_idle;
7072 cap_entries = !list_is_singular(&sqd->ctx_list);
7073 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7074 if (current->cred != ctx->creds) {
7076 revert_creds(old_cred);
7077 old_cred = override_creds(ctx->creds);
7079 io_sq_thread_associate_blkcg(ctx, &cur_css);
7081 current->loginuid = ctx->loginuid;
7082 current->sessionid = ctx->sessionid;
7085 ret = __io_sq_thread(ctx, cap_entries);
7086 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7089 io_sq_thread_drop_mm_files();
7092 if (sqt_spin || !time_after(jiffies, timeout)) {
7094 io_sq_thread_drop_mm_files();
7097 timeout = jiffies + sqd->sq_thread_idle;
7102 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7103 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7104 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7105 !list_empty_careful(&ctx->iopoll_list)) {
7106 needs_sched = false;
7109 if (io_sqring_entries(ctx)) {
7110 needs_sched = false;
7115 if (needs_sched && !kthread_should_park()) {
7116 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7117 io_ring_set_wakeup_flag(ctx);
7120 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7121 io_ring_clear_wakeup_flag(ctx);
7124 finish_wait(&sqd->wait, &wait);
7125 timeout = jiffies + sqd->sq_thread_idle;
7129 io_sq_thread_drop_mm_files();
7132 io_sq_thread_unassociate_blkcg();
7134 revert_creds(old_cred);
7137 current->files = old_files;
7138 current->nsproxy = old_nsproxy;
7139 task_unlock(current);
7146 struct io_wait_queue {
7147 struct wait_queue_entry wq;
7148 struct io_ring_ctx *ctx;
7150 unsigned nr_timeouts;
7153 static inline bool io_should_wake(struct io_wait_queue *iowq)
7155 struct io_ring_ctx *ctx = iowq->ctx;
7158 * Wake up if we have enough events, or if a timeout occurred since we
7159 * started waiting. For timeouts, we always want to return to userspace,
7160 * regardless of event count.
7162 return io_cqring_events(ctx) >= iowq->to_wait ||
7163 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7166 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7167 int wake_flags, void *key)
7169 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7173 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7174 * the task, and the next invocation will do it.
7176 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
7177 return autoremove_wake_function(curr, mode, wake_flags, key);
7181 static int io_run_task_work_sig(void)
7183 if (io_run_task_work())
7185 if (!signal_pending(current))
7187 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
7188 return -ERESTARTSYS;
7192 /* when returns >0, the caller should retry */
7193 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7194 struct io_wait_queue *iowq,
7195 signed long *timeout)
7199 /* make sure we run task_work before checking for signals */
7200 ret = io_run_task_work_sig();
7201 if (ret || io_should_wake(iowq))
7203 /* let the caller flush overflows, retry */
7204 if (test_bit(0, &ctx->cq_check_overflow))
7207 *timeout = schedule_timeout(*timeout);
7208 return !*timeout ? -ETIME : 1;
7212 * Wait until events become available, if we don't already have some. The
7213 * application must reap them itself, as they reside on the shared cq ring.
7215 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7216 const sigset_t __user *sig, size_t sigsz,
7217 struct __kernel_timespec __user *uts)
7219 struct io_wait_queue iowq = {
7222 .func = io_wake_function,
7223 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7226 .to_wait = min_events,
7228 struct io_rings *rings = ctx->rings;
7229 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7233 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7234 if (io_cqring_events(ctx) >= min_events)
7236 if (!io_run_task_work())
7241 #ifdef CONFIG_COMPAT
7242 if (in_compat_syscall())
7243 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7247 ret = set_user_sigmask(sig, sigsz);
7254 struct timespec64 ts;
7256 if (get_timespec64(&ts, uts))
7258 timeout = timespec64_to_jiffies(&ts);
7261 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7262 trace_io_uring_cqring_wait(ctx, min_events);
7264 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7265 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7266 TASK_INTERRUPTIBLE);
7267 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7268 finish_wait(&ctx->wait, &iowq.wq);
7271 restore_saved_sigmask_unless(ret == -EINTR);
7273 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7276 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7278 #if defined(CONFIG_UNIX)
7279 if (ctx->ring_sock) {
7280 struct sock *sock = ctx->ring_sock->sk;
7281 struct sk_buff *skb;
7283 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7289 for (i = 0; i < ctx->nr_user_files; i++) {
7292 file = io_file_from_index(ctx, i);
7299 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7301 struct fixed_rsrc_data *data;
7303 data = container_of(ref, struct fixed_rsrc_data, refs);
7304 complete(&data->done);
7307 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7309 spin_lock_bh(&ctx->rsrc_ref_lock);
7312 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7314 spin_unlock_bh(&ctx->rsrc_ref_lock);
7317 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
7318 struct fixed_rsrc_data *rsrc_data,
7319 struct fixed_rsrc_ref_node *ref_node)
7321 io_rsrc_ref_lock(ctx);
7322 rsrc_data->node = ref_node;
7323 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
7324 io_rsrc_ref_unlock(ctx);
7325 percpu_ref_get(&rsrc_data->refs);
7328 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
7329 struct io_ring_ctx *ctx,
7330 struct fixed_rsrc_ref_node *backup_node)
7332 struct fixed_rsrc_ref_node *ref_node;
7335 io_rsrc_ref_lock(ctx);
7336 ref_node = data->node;
7337 io_rsrc_ref_unlock(ctx);
7339 percpu_ref_kill(&ref_node->refs);
7341 percpu_ref_kill(&data->refs);
7343 /* wait for all refs nodes to complete */
7344 flush_delayed_work(&ctx->rsrc_put_work);
7346 ret = wait_for_completion_interruptible(&data->done);
7349 ret = io_run_task_work_sig();
7351 percpu_ref_resurrect(&data->refs);
7352 reinit_completion(&data->done);
7353 io_sqe_rsrc_set_node(ctx, data, backup_node);
7358 destroy_fixed_rsrc_ref_node(backup_node);
7362 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7364 struct fixed_rsrc_data *data;
7366 data = kzalloc(sizeof(*data), GFP_KERNEL);
7370 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7371 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7376 init_completion(&data->done);
7380 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7382 percpu_ref_exit(&data->refs);
7387 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7389 struct fixed_rsrc_data *data = ctx->file_data;
7390 struct fixed_rsrc_ref_node *backup_node;
7391 unsigned nr_tables, i;
7396 backup_node = alloc_fixed_rsrc_ref_node(ctx);
7399 init_fixed_file_ref_node(ctx, backup_node);
7401 ret = io_rsrc_ref_quiesce(data, ctx, backup_node);
7405 __io_sqe_files_unregister(ctx);
7406 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7407 for (i = 0; i < nr_tables; i++)
7408 kfree(data->table[i].files);
7409 free_fixed_rsrc_data(data);
7410 ctx->file_data = NULL;
7411 ctx->nr_user_files = 0;
7415 static void io_put_sq_data(struct io_sq_data *sqd)
7417 if (refcount_dec_and_test(&sqd->refs)) {
7419 * The park is a bit of a work-around, without it we get
7420 * warning spews on shutdown with SQPOLL set and affinity
7421 * set to a single CPU.
7424 kthread_park(sqd->thread);
7425 kthread_stop(sqd->thread);
7432 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7434 struct io_ring_ctx *ctx_attach;
7435 struct io_sq_data *sqd;
7438 f = fdget(p->wq_fd);
7440 return ERR_PTR(-ENXIO);
7441 if (f.file->f_op != &io_uring_fops) {
7443 return ERR_PTR(-EINVAL);
7446 ctx_attach = f.file->private_data;
7447 sqd = ctx_attach->sq_data;
7450 return ERR_PTR(-EINVAL);
7453 refcount_inc(&sqd->refs);
7458 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7460 struct io_sq_data *sqd;
7462 if (p->flags & IORING_SETUP_ATTACH_WQ)
7463 return io_attach_sq_data(p);
7465 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7467 return ERR_PTR(-ENOMEM);
7469 refcount_set(&sqd->refs, 1);
7470 INIT_LIST_HEAD(&sqd->ctx_list);
7471 INIT_LIST_HEAD(&sqd->ctx_new_list);
7472 mutex_init(&sqd->ctx_lock);
7473 mutex_init(&sqd->lock);
7474 init_waitqueue_head(&sqd->wait);
7478 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7479 __releases(&sqd->lock)
7483 kthread_unpark(sqd->thread);
7484 mutex_unlock(&sqd->lock);
7487 static void io_sq_thread_park(struct io_sq_data *sqd)
7488 __acquires(&sqd->lock)
7492 mutex_lock(&sqd->lock);
7493 kthread_park(sqd->thread);
7496 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7498 struct io_sq_data *sqd = ctx->sq_data;
7503 * We may arrive here from the error branch in
7504 * io_sq_offload_create() where the kthread is created
7505 * without being waked up, thus wake it up now to make
7506 * sure the wait will complete.
7508 wake_up_process(sqd->thread);
7509 wait_for_completion(&ctx->sq_thread_comp);
7511 io_sq_thread_park(sqd);
7514 mutex_lock(&sqd->ctx_lock);
7515 list_del(&ctx->sqd_list);
7516 io_sqd_update_thread_idle(sqd);
7517 mutex_unlock(&sqd->ctx_lock);
7520 io_sq_thread_unpark(sqd);
7522 io_put_sq_data(sqd);
7523 ctx->sq_data = NULL;
7527 static void io_finish_async(struct io_ring_ctx *ctx)
7529 io_sq_thread_stop(ctx);
7532 io_wq_destroy(ctx->io_wq);
7537 #if defined(CONFIG_UNIX)
7539 * Ensure the UNIX gc is aware of our file set, so we are certain that
7540 * the io_uring can be safely unregistered on process exit, even if we have
7541 * loops in the file referencing.
7543 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7545 struct sock *sk = ctx->ring_sock->sk;
7546 struct scm_fp_list *fpl;
7547 struct sk_buff *skb;
7550 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7554 skb = alloc_skb(0, GFP_KERNEL);
7563 fpl->user = get_uid(ctx->user);
7564 for (i = 0; i < nr; i++) {
7565 struct file *file = io_file_from_index(ctx, i + offset);
7569 fpl->fp[nr_files] = get_file(file);
7570 unix_inflight(fpl->user, fpl->fp[nr_files]);
7575 fpl->max = SCM_MAX_FD;
7576 fpl->count = nr_files;
7577 UNIXCB(skb).fp = fpl;
7578 skb->destructor = unix_destruct_scm;
7579 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7580 skb_queue_head(&sk->sk_receive_queue, skb);
7582 for (i = 0; i < nr_files; i++)
7593 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7594 * causes regular reference counting to break down. We rely on the UNIX
7595 * garbage collection to take care of this problem for us.
7597 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7599 unsigned left, total;
7603 left = ctx->nr_user_files;
7605 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7607 ret = __io_sqe_files_scm(ctx, this_files, total);
7611 total += this_files;
7617 while (total < ctx->nr_user_files) {
7618 struct file *file = io_file_from_index(ctx, total);
7628 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7634 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7635 unsigned nr_tables, unsigned nr_files)
7639 for (i = 0; i < nr_tables; i++) {
7640 struct fixed_rsrc_table *table = &file_data->table[i];
7641 unsigned this_files;
7643 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7644 table->files = kcalloc(this_files, sizeof(struct file *),
7648 nr_files -= this_files;
7654 for (i = 0; i < nr_tables; i++) {
7655 struct fixed_rsrc_table *table = &file_data->table[i];
7656 kfree(table->files);
7661 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7663 struct file *file = prsrc->file;
7664 #if defined(CONFIG_UNIX)
7665 struct sock *sock = ctx->ring_sock->sk;
7666 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7667 struct sk_buff *skb;
7670 __skb_queue_head_init(&list);
7673 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7674 * remove this entry and rearrange the file array.
7676 skb = skb_dequeue(head);
7678 struct scm_fp_list *fp;
7680 fp = UNIXCB(skb).fp;
7681 for (i = 0; i < fp->count; i++) {
7684 if (fp->fp[i] != file)
7687 unix_notinflight(fp->user, fp->fp[i]);
7688 left = fp->count - 1 - i;
7690 memmove(&fp->fp[i], &fp->fp[i + 1],
7691 left * sizeof(struct file *));
7698 __skb_queue_tail(&list, skb);
7708 __skb_queue_tail(&list, skb);
7710 skb = skb_dequeue(head);
7713 if (skb_peek(&list)) {
7714 spin_lock_irq(&head->lock);
7715 while ((skb = __skb_dequeue(&list)) != NULL)
7716 __skb_queue_tail(head, skb);
7717 spin_unlock_irq(&head->lock);
7724 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7726 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7727 struct io_ring_ctx *ctx = rsrc_data->ctx;
7728 struct io_rsrc_put *prsrc, *tmp;
7730 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7731 list_del(&prsrc->list);
7732 ref_node->rsrc_put(ctx, prsrc);
7736 percpu_ref_exit(&ref_node->refs);
7738 percpu_ref_put(&rsrc_data->refs);
7741 static void io_rsrc_put_work(struct work_struct *work)
7743 struct io_ring_ctx *ctx;
7744 struct llist_node *node;
7746 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7747 node = llist_del_all(&ctx->rsrc_put_llist);
7750 struct fixed_rsrc_ref_node *ref_node;
7751 struct llist_node *next = node->next;
7753 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7754 __io_rsrc_put_work(ref_node);
7759 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7762 struct fixed_rsrc_table *table;
7764 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7765 return &table->files[i & IORING_FILE_TABLE_MASK];
7768 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7770 struct fixed_rsrc_ref_node *ref_node;
7771 struct fixed_rsrc_data *data;
7772 struct io_ring_ctx *ctx;
7773 bool first_add = false;
7776 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7777 data = ref_node->rsrc_data;
7780 io_rsrc_ref_lock(ctx);
7781 ref_node->done = true;
7783 while (!list_empty(&ctx->rsrc_ref_list)) {
7784 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7785 struct fixed_rsrc_ref_node, node);
7786 /* recycle ref nodes in order */
7787 if (!ref_node->done)
7789 list_del(&ref_node->node);
7790 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7792 io_rsrc_ref_unlock(ctx);
7794 if (percpu_ref_is_dying(&data->refs))
7798 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7800 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7803 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7804 struct io_ring_ctx *ctx)
7806 struct fixed_rsrc_ref_node *ref_node;
7808 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7812 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7817 INIT_LIST_HEAD(&ref_node->node);
7818 INIT_LIST_HEAD(&ref_node->rsrc_list);
7819 ref_node->done = false;
7823 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7824 struct fixed_rsrc_ref_node *ref_node)
7826 ref_node->rsrc_data = ctx->file_data;
7827 ref_node->rsrc_put = io_ring_file_put;
7830 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7832 percpu_ref_exit(&ref_node->refs);
7837 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7840 __s32 __user *fds = (__s32 __user *) arg;
7841 unsigned nr_tables, i;
7843 int fd, ret = -ENOMEM;
7844 struct fixed_rsrc_ref_node *ref_node;
7845 struct fixed_rsrc_data *file_data;
7851 if (nr_args > IORING_MAX_FIXED_FILES)
7854 file_data = alloc_fixed_rsrc_data(ctx);
7857 ctx->file_data = file_data;
7859 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7860 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7862 if (!file_data->table)
7865 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7868 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7869 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7873 /* allow sparse sets */
7883 * Don't allow io_uring instances to be registered. If UNIX
7884 * isn't enabled, then this causes a reference cycle and this
7885 * instance can never get freed. If UNIX is enabled we'll
7886 * handle it just fine, but there's still no point in allowing
7887 * a ring fd as it doesn't support regular read/write anyway.
7889 if (file->f_op == &io_uring_fops) {
7893 *io_fixed_file_slot(file_data, i) = file;
7896 ret = io_sqe_files_scm(ctx);
7898 io_sqe_files_unregister(ctx);
7902 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7904 io_sqe_files_unregister(ctx);
7907 init_fixed_file_ref_node(ctx, ref_node);
7909 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7912 for (i = 0; i < ctx->nr_user_files; i++) {
7913 file = io_file_from_index(ctx, i);
7917 for (i = 0; i < nr_tables; i++)
7918 kfree(file_data->table[i].files);
7919 ctx->nr_user_files = 0;
7921 free_fixed_rsrc_data(ctx->file_data);
7922 ctx->file_data = NULL;
7926 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7929 #if defined(CONFIG_UNIX)
7930 struct sock *sock = ctx->ring_sock->sk;
7931 struct sk_buff_head *head = &sock->sk_receive_queue;
7932 struct sk_buff *skb;
7935 * See if we can merge this file into an existing skb SCM_RIGHTS
7936 * file set. If there's no room, fall back to allocating a new skb
7937 * and filling it in.
7939 spin_lock_irq(&head->lock);
7940 skb = skb_peek(head);
7942 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7944 if (fpl->count < SCM_MAX_FD) {
7945 __skb_unlink(skb, head);
7946 spin_unlock_irq(&head->lock);
7947 fpl->fp[fpl->count] = get_file(file);
7948 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7950 spin_lock_irq(&head->lock);
7951 __skb_queue_head(head, skb);
7956 spin_unlock_irq(&head->lock);
7963 return __io_sqe_files_scm(ctx, 1, index);
7969 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7971 struct io_rsrc_put *prsrc;
7972 struct fixed_rsrc_ref_node *ref_node = data->node;
7974 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7979 list_add(&prsrc->list, &ref_node->rsrc_list);
7984 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7987 return io_queue_rsrc_removal(data, (void *)file);
7990 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7991 struct io_uring_rsrc_update *up,
7994 struct fixed_rsrc_data *data = ctx->file_data;
7995 struct fixed_rsrc_ref_node *ref_node;
7996 struct file *file, **file_slot;
8000 bool needs_switch = false;
8002 if (check_add_overflow(up->offset, nr_args, &done))
8004 if (done > ctx->nr_user_files)
8007 ref_node = alloc_fixed_rsrc_ref_node(ctx);
8010 init_fixed_file_ref_node(ctx, ref_node);
8012 fds = u64_to_user_ptr(up->data);
8013 for (done = 0; done < nr_args; done++) {
8015 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
8019 if (fd == IORING_REGISTER_FILES_SKIP)
8022 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8023 file_slot = io_fixed_file_slot(ctx->file_data, i);
8026 err = io_queue_file_removal(data, *file_slot);
8030 needs_switch = true;
8039 * Don't allow io_uring instances to be registered. If
8040 * UNIX isn't enabled, then this causes a reference
8041 * cycle and this instance can never get freed. If UNIX
8042 * is enabled we'll handle it just fine, but there's
8043 * still no point in allowing a ring fd as it doesn't
8044 * support regular read/write anyway.
8046 if (file->f_op == &io_uring_fops) {
8052 err = io_sqe_file_register(ctx, file, i);
8062 percpu_ref_kill(&data->node->refs);
8063 io_sqe_rsrc_set_node(ctx, data, ref_node);
8065 destroy_fixed_rsrc_ref_node(ref_node);
8067 return done ? done : err;
8070 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
8073 struct io_uring_rsrc_update up;
8075 if (!ctx->file_data)
8079 if (copy_from_user(&up, arg, sizeof(up)))
8084 return __io_sqe_files_update(ctx, &up, nr_args);
8087 static struct io_wq_work *io_free_work(struct io_wq_work *work)
8089 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8091 req = io_put_req_find_next(req);
8092 return req ? &req->work : NULL;
8095 static int io_init_wq_offload(struct io_ring_ctx *ctx,
8096 struct io_uring_params *p)
8098 struct io_wq_data data;
8100 struct io_ring_ctx *ctx_attach;
8101 unsigned int concurrency;
8104 data.user = ctx->user;
8105 data.free_work = io_free_work;
8106 data.do_work = io_wq_submit_work;
8108 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
8109 /* Do QD, or 4 * CPUS, whatever is smallest */
8110 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8112 ctx->io_wq = io_wq_create(concurrency, &data);
8113 if (IS_ERR(ctx->io_wq)) {
8114 ret = PTR_ERR(ctx->io_wq);
8120 f = fdget(p->wq_fd);
8124 if (f.file->f_op != &io_uring_fops) {
8129 ctx_attach = f.file->private_data;
8130 /* @io_wq is protected by holding the fd */
8131 if (!io_wq_get(ctx_attach->io_wq, &data)) {
8136 ctx->io_wq = ctx_attach->io_wq;
8142 static int io_uring_alloc_task_context(struct task_struct *task)
8144 struct io_uring_task *tctx;
8147 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
8148 if (unlikely(!tctx))
8151 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8152 if (unlikely(ret)) {
8158 init_waitqueue_head(&tctx->wait);
8160 atomic_set(&tctx->in_idle, 0);
8161 tctx->sqpoll = false;
8162 io_init_identity(&tctx->__identity);
8163 tctx->identity = &tctx->__identity;
8164 task->io_uring = tctx;
8165 spin_lock_init(&tctx->task_lock);
8166 INIT_WQ_LIST(&tctx->task_list);
8167 tctx->task_state = 0;
8168 init_task_work(&tctx->task_work, tctx_task_work);
8172 void __io_uring_free(struct task_struct *tsk)
8174 struct io_uring_task *tctx = tsk->io_uring;
8176 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8177 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
8178 if (tctx->identity != &tctx->__identity)
8179 kfree(tctx->identity);
8180 percpu_counter_destroy(&tctx->inflight);
8182 tsk->io_uring = NULL;
8185 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8186 struct io_uring_params *p)
8190 if (ctx->flags & IORING_SETUP_SQPOLL) {
8191 struct io_sq_data *sqd;
8194 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
8197 sqd = io_get_sq_data(p);
8204 io_sq_thread_park(sqd);
8205 mutex_lock(&sqd->ctx_lock);
8206 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
8207 mutex_unlock(&sqd->ctx_lock);
8208 io_sq_thread_unpark(sqd);
8210 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8211 if (!ctx->sq_thread_idle)
8212 ctx->sq_thread_idle = HZ;
8217 if (p->flags & IORING_SETUP_SQ_AFF) {
8218 int cpu = p->sq_thread_cpu;
8221 if (cpu >= nr_cpu_ids)
8223 if (!cpu_online(cpu))
8226 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8227 cpu, "io_uring-sq");
8229 sqd->thread = kthread_create(io_sq_thread, sqd,
8232 if (IS_ERR(sqd->thread)) {
8233 ret = PTR_ERR(sqd->thread);
8237 ret = io_uring_alloc_task_context(sqd->thread);
8240 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8241 /* Can't have SQ_AFF without SQPOLL */
8247 ret = io_init_wq_offload(ctx, p);
8253 io_finish_async(ctx);
8257 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8259 struct io_sq_data *sqd = ctx->sq_data;
8261 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8262 wake_up_process(sqd->thread);
8265 static inline void __io_unaccount_mem(struct user_struct *user,
8266 unsigned long nr_pages)
8268 atomic_long_sub(nr_pages, &user->locked_vm);
8271 static inline int __io_account_mem(struct user_struct *user,
8272 unsigned long nr_pages)
8274 unsigned long page_limit, cur_pages, new_pages;
8276 /* Don't allow more pages than we can safely lock */
8277 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8280 cur_pages = atomic_long_read(&user->locked_vm);
8281 new_pages = cur_pages + nr_pages;
8282 if (new_pages > page_limit)
8284 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8285 new_pages) != cur_pages);
8290 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8293 __io_unaccount_mem(ctx->user, nr_pages);
8295 if (ctx->mm_account)
8296 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8299 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8303 if (ctx->limit_mem) {
8304 ret = __io_account_mem(ctx->user, nr_pages);
8309 if (ctx->mm_account)
8310 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8315 static void io_mem_free(void *ptr)
8322 page = virt_to_head_page(ptr);
8323 if (put_page_testzero(page))
8324 free_compound_page(page);
8327 static void *io_mem_alloc(size_t size)
8329 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8330 __GFP_NORETRY | __GFP_ACCOUNT;
8332 return (void *) __get_free_pages(gfp_flags, get_order(size));
8335 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8338 struct io_rings *rings;
8339 size_t off, sq_array_size;
8341 off = struct_size(rings, cqes, cq_entries);
8342 if (off == SIZE_MAX)
8346 off = ALIGN(off, SMP_CACHE_BYTES);
8354 sq_array_size = array_size(sizeof(u32), sq_entries);
8355 if (sq_array_size == SIZE_MAX)
8358 if (check_add_overflow(off, sq_array_size, &off))
8364 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8368 if (!ctx->user_bufs)
8371 for (i = 0; i < ctx->nr_user_bufs; i++) {
8372 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8374 for (j = 0; j < imu->nr_bvecs; j++)
8375 unpin_user_page(imu->bvec[j].bv_page);
8377 if (imu->acct_pages)
8378 io_unaccount_mem(ctx, imu->acct_pages);
8383 kfree(ctx->user_bufs);
8384 ctx->user_bufs = NULL;
8385 ctx->nr_user_bufs = 0;
8389 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8390 void __user *arg, unsigned index)
8392 struct iovec __user *src;
8394 #ifdef CONFIG_COMPAT
8396 struct compat_iovec __user *ciovs;
8397 struct compat_iovec ciov;
8399 ciovs = (struct compat_iovec __user *) arg;
8400 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8403 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8404 dst->iov_len = ciov.iov_len;
8408 src = (struct iovec __user *) arg;
8409 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8415 * Not super efficient, but this is just a registration time. And we do cache
8416 * the last compound head, so generally we'll only do a full search if we don't
8419 * We check if the given compound head page has already been accounted, to
8420 * avoid double accounting it. This allows us to account the full size of the
8421 * page, not just the constituent pages of a huge page.
8423 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8424 int nr_pages, struct page *hpage)
8428 /* check current page array */
8429 for (i = 0; i < nr_pages; i++) {
8430 if (!PageCompound(pages[i]))
8432 if (compound_head(pages[i]) == hpage)
8436 /* check previously registered pages */
8437 for (i = 0; i < ctx->nr_user_bufs; i++) {
8438 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8440 for (j = 0; j < imu->nr_bvecs; j++) {
8441 if (!PageCompound(imu->bvec[j].bv_page))
8443 if (compound_head(imu->bvec[j].bv_page) == hpage)
8451 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8452 int nr_pages, struct io_mapped_ubuf *imu,
8453 struct page **last_hpage)
8457 for (i = 0; i < nr_pages; i++) {
8458 if (!PageCompound(pages[i])) {
8463 hpage = compound_head(pages[i]);
8464 if (hpage == *last_hpage)
8466 *last_hpage = hpage;
8467 if (headpage_already_acct(ctx, pages, i, hpage))
8469 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8473 if (!imu->acct_pages)
8476 ret = io_account_mem(ctx, imu->acct_pages);
8478 imu->acct_pages = 0;
8482 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8483 struct io_mapped_ubuf *imu,
8484 struct page **last_hpage)
8486 struct vm_area_struct **vmas = NULL;
8487 struct page **pages = NULL;
8488 unsigned long off, start, end, ubuf;
8490 int ret, pret, nr_pages, i;
8492 ubuf = (unsigned long) iov->iov_base;
8493 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8494 start = ubuf >> PAGE_SHIFT;
8495 nr_pages = end - start;
8499 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8503 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8508 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8514 mmap_read_lock(current->mm);
8515 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8517 if (pret == nr_pages) {
8518 /* don't support file backed memory */
8519 for (i = 0; i < nr_pages; i++) {
8520 struct vm_area_struct *vma = vmas[i];
8523 !is_file_hugepages(vma->vm_file)) {
8529 ret = pret < 0 ? pret : -EFAULT;
8531 mmap_read_unlock(current->mm);
8534 * if we did partial map, or found file backed vmas,
8535 * release any pages we did get
8538 unpin_user_pages(pages, pret);
8543 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8545 unpin_user_pages(pages, pret);
8550 off = ubuf & ~PAGE_MASK;
8551 size = iov->iov_len;
8552 for (i = 0; i < nr_pages; i++) {
8555 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8556 imu->bvec[i].bv_page = pages[i];
8557 imu->bvec[i].bv_len = vec_len;
8558 imu->bvec[i].bv_offset = off;
8562 /* store original address for later verification */
8564 imu->len = iov->iov_len;
8565 imu->nr_bvecs = nr_pages;
8573 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8577 if (!nr_args || nr_args > UIO_MAXIOV)
8580 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8582 if (!ctx->user_bufs)
8588 static int io_buffer_validate(struct iovec *iov)
8591 * Don't impose further limits on the size and buffer
8592 * constraints here, we'll -EINVAL later when IO is
8593 * submitted if they are wrong.
8595 if (!iov->iov_base || !iov->iov_len)
8598 /* arbitrary limit, but we need something */
8599 if (iov->iov_len > SZ_1G)
8605 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8606 unsigned int nr_args)
8610 struct page *last_hpage = NULL;
8612 ret = io_buffers_map_alloc(ctx, nr_args);
8616 for (i = 0; i < nr_args; i++) {
8617 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8619 ret = io_copy_iov(ctx, &iov, arg, i);
8623 ret = io_buffer_validate(&iov);
8627 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8631 ctx->nr_user_bufs++;
8635 io_sqe_buffers_unregister(ctx);
8640 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8642 __s32 __user *fds = arg;
8648 if (copy_from_user(&fd, fds, sizeof(*fds)))
8651 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8652 if (IS_ERR(ctx->cq_ev_fd)) {
8653 int ret = PTR_ERR(ctx->cq_ev_fd);
8654 ctx->cq_ev_fd = NULL;
8661 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8663 if (ctx->cq_ev_fd) {
8664 eventfd_ctx_put(ctx->cq_ev_fd);
8665 ctx->cq_ev_fd = NULL;
8672 static int __io_destroy_buffers(int id, void *p, void *data)
8674 struct io_ring_ctx *ctx = data;
8675 struct io_buffer *buf = p;
8677 __io_remove_buffers(ctx, buf, id, -1U);
8681 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8683 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8684 idr_destroy(&ctx->io_buffer_idr);
8687 static void io_req_cache_free(struct list_head *list)
8689 while (!list_empty(list)) {
8690 struct io_kiocb *req;
8692 req = list_first_entry(list, struct io_kiocb, compl.list);
8693 list_del(&req->compl.list);
8694 kmem_cache_free(req_cachep, req);
8698 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8700 struct io_submit_state *submit_state = &ctx->submit_state;
8703 * Some may use context even when all refs and requests have been put,
8704 * and they are free to do so while still holding uring_lock, see
8705 * __io_req_task_submit(). Wait for them to finish.
8707 mutex_lock(&ctx->uring_lock);
8708 mutex_unlock(&ctx->uring_lock);
8710 io_finish_async(ctx);
8711 io_sqe_buffers_unregister(ctx);
8713 if (ctx->sqo_task) {
8714 put_task_struct(ctx->sqo_task);
8715 ctx->sqo_task = NULL;
8716 mmdrop(ctx->mm_account);
8717 ctx->mm_account = NULL;
8720 if (submit_state->free_reqs)
8721 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8722 submit_state->reqs);
8724 #ifdef CONFIG_BLK_CGROUP
8725 if (ctx->sqo_blkcg_css)
8726 css_put(ctx->sqo_blkcg_css);
8729 io_sqe_files_unregister(ctx);
8730 io_eventfd_unregister(ctx);
8731 io_destroy_buffers(ctx);
8732 idr_destroy(&ctx->personality_idr);
8734 #if defined(CONFIG_UNIX)
8735 if (ctx->ring_sock) {
8736 ctx->ring_sock->file = NULL; /* so that iput() is called */
8737 sock_release(ctx->ring_sock);
8741 io_mem_free(ctx->rings);
8742 io_mem_free(ctx->sq_sqes);
8744 percpu_ref_exit(&ctx->refs);
8745 free_uid(ctx->user);
8746 put_cred(ctx->creds);
8747 kfree(ctx->cancel_hash);
8748 io_req_cache_free(&ctx->submit_state.comp.free_list);
8749 io_req_cache_free(&ctx->submit_state.comp.locked_free_list);
8753 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8755 struct io_ring_ctx *ctx = file->private_data;
8758 poll_wait(file, &ctx->cq_wait, wait);
8760 * synchronizes with barrier from wq_has_sleeper call in
8764 if (!io_sqring_full(ctx))
8765 mask |= EPOLLOUT | EPOLLWRNORM;
8768 * Don't flush cqring overflow list here, just do a simple check.
8769 * Otherwise there could possible be ABBA deadlock:
8772 * lock(&ctx->uring_lock);
8774 * lock(&ctx->uring_lock);
8777 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8778 * pushs them to do the flush.
8780 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8781 mask |= EPOLLIN | EPOLLRDNORM;
8786 static int io_uring_fasync(int fd, struct file *file, int on)
8788 struct io_ring_ctx *ctx = file->private_data;
8790 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8793 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8795 struct io_identity *iod;
8797 iod = idr_remove(&ctx->personality_idr, id);
8799 put_cred(iod->creds);
8800 if (refcount_dec_and_test(&iod->count))
8808 static int io_remove_personalities(int id, void *p, void *data)
8810 struct io_ring_ctx *ctx = data;
8812 io_unregister_personality(ctx, id);
8816 static void io_ring_exit_work(struct work_struct *work)
8818 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8822 * If we're doing polled IO and end up having requests being
8823 * submitted async (out-of-line), then completions can come in while
8824 * we're waiting for refs to drop. We need to reap these manually,
8825 * as nobody else will be looking for them.
8828 io_uring_try_cancel_requests(ctx, NULL, NULL);
8829 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8830 io_ring_ctx_free(ctx);
8833 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8835 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8837 return req->ctx == data;
8840 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8842 mutex_lock(&ctx->uring_lock);
8843 percpu_ref_kill(&ctx->refs);
8845 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8848 /* if force is set, the ring is going away. always drop after that */
8849 ctx->cq_overflow_flushed = 1;
8851 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8852 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8853 mutex_unlock(&ctx->uring_lock);
8855 io_kill_timeouts(ctx, NULL, NULL);
8856 io_poll_remove_all(ctx, NULL, NULL);
8859 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8861 /* if we failed setting up the ctx, we might not have any rings */
8862 io_iopoll_try_reap_events(ctx);
8864 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8866 * Use system_unbound_wq to avoid spawning tons of event kworkers
8867 * if we're exiting a ton of rings at the same time. It just adds
8868 * noise and overhead, there's no discernable change in runtime
8869 * over using system_wq.
8871 queue_work(system_unbound_wq, &ctx->exit_work);
8874 static int io_uring_release(struct inode *inode, struct file *file)
8876 struct io_ring_ctx *ctx = file->private_data;
8878 file->private_data = NULL;
8879 io_ring_ctx_wait_and_kill(ctx);
8883 struct io_task_cancel {
8884 struct task_struct *task;
8885 struct files_struct *files;
8888 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8890 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8891 struct io_task_cancel *cancel = data;
8894 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8895 unsigned long flags;
8896 struct io_ring_ctx *ctx = req->ctx;
8898 /* protect against races with linked timeouts */
8899 spin_lock_irqsave(&ctx->completion_lock, flags);
8900 ret = io_match_task(req, cancel->task, cancel->files);
8901 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8903 ret = io_match_task(req, cancel->task, cancel->files);
8908 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8909 struct task_struct *task,
8910 struct files_struct *files)
8912 struct io_defer_entry *de = NULL;
8915 spin_lock_irq(&ctx->completion_lock);
8916 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8917 if (io_match_task(de->req, task, files)) {
8918 list_cut_position(&list, &ctx->defer_list, &de->list);
8922 spin_unlock_irq(&ctx->completion_lock);
8924 while (!list_empty(&list)) {
8925 de = list_first_entry(&list, struct io_defer_entry, list);
8926 list_del_init(&de->list);
8927 req_set_fail_links(de->req);
8928 io_put_req(de->req);
8929 io_req_complete(de->req, -ECANCELED);
8934 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8935 struct task_struct *task,
8936 struct files_struct *files)
8938 struct io_task_cancel cancel = { .task = task, .files = files, };
8941 enum io_wq_cancel cret;
8945 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb,
8947 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8950 /* SQPOLL thread does its own polling */
8951 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8952 while (!list_empty_careful(&ctx->iopoll_list)) {
8953 io_iopoll_try_reap_events(ctx);
8958 ret |= io_poll_remove_all(ctx, task, files);
8959 ret |= io_kill_timeouts(ctx, task, files);
8960 ret |= io_run_task_work();
8961 io_cqring_overflow_flush(ctx, true, task, files);
8968 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8969 struct task_struct *task,
8970 struct files_struct *files)
8972 struct io_kiocb *req;
8975 spin_lock_irq(&ctx->inflight_lock);
8976 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8977 cnt += io_match_task(req, task, files);
8978 spin_unlock_irq(&ctx->inflight_lock);
8982 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8983 struct task_struct *task,
8984 struct files_struct *files)
8986 while (!list_empty_careful(&ctx->inflight_list)) {
8990 inflight = io_uring_count_inflight(ctx, task, files);
8994 io_uring_try_cancel_requests(ctx, task, files);
8997 io_sq_thread_unpark(ctx->sq_data);
8998 prepare_to_wait(&task->io_uring->wait, &wait,
8999 TASK_UNINTERRUPTIBLE);
9000 if (inflight == io_uring_count_inflight(ctx, task, files))
9002 finish_wait(&task->io_uring->wait, &wait);
9004 io_sq_thread_park(ctx->sq_data);
9008 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
9010 mutex_lock(&ctx->uring_lock);
9012 mutex_unlock(&ctx->uring_lock);
9014 /* make sure callers enter the ring to get error */
9016 io_ring_set_wakeup_flag(ctx);
9020 * We need to iteratively cancel requests, in case a request has dependent
9021 * hard links. These persist even for failure of cancelations, hence keep
9022 * looping until none are found.
9024 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
9025 struct files_struct *files)
9027 struct task_struct *task = current;
9029 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9030 io_disable_sqo_submit(ctx);
9031 task = ctx->sq_data->thread;
9032 atomic_inc(&task->io_uring->in_idle);
9033 io_sq_thread_park(ctx->sq_data);
9036 io_cancel_defer_files(ctx, task, files);
9038 io_uring_cancel_files(ctx, task, files);
9040 io_uring_try_cancel_requests(ctx, task, NULL);
9042 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9043 atomic_dec(&task->io_uring->in_idle);
9045 * If the files that are going away are the ones in the thread
9046 * identity, clear them out.
9048 if (task->io_uring->identity->files == files)
9049 task->io_uring->identity->files = NULL;
9050 io_sq_thread_unpark(ctx->sq_data);
9055 * Note that this task has used io_uring. We use it for cancelation purposes.
9057 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
9059 struct io_uring_task *tctx = current->io_uring;
9062 if (unlikely(!tctx)) {
9063 ret = io_uring_alloc_task_context(current);
9066 tctx = current->io_uring;
9068 if (tctx->last != file) {
9069 void *old = xa_load(&tctx->xa, (unsigned long)file);
9073 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
9080 /* one and only SQPOLL file note, held by sqo_task */
9081 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
9082 current != ctx->sqo_task);
9088 * This is race safe in that the task itself is doing this, hence it
9089 * cannot be going through the exit/cancel paths at the same time.
9090 * This cannot be modified while exit/cancel is running.
9092 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
9093 tctx->sqpoll = true;
9099 * Remove this io_uring_file -> task mapping.
9101 static void io_uring_del_task_file(struct file *file)
9103 struct io_uring_task *tctx = current->io_uring;
9105 if (tctx->last == file)
9107 file = xa_erase(&tctx->xa, (unsigned long)file);
9112 static void io_uring_remove_task_files(struct io_uring_task *tctx)
9115 unsigned long index;
9117 xa_for_each(&tctx->xa, index, file)
9118 io_uring_del_task_file(file);
9121 void __io_uring_files_cancel(struct files_struct *files)
9123 struct io_uring_task *tctx = current->io_uring;
9125 unsigned long index;
9127 /* make sure overflow events are dropped */
9128 atomic_inc(&tctx->in_idle);
9129 xa_for_each(&tctx->xa, index, file)
9130 io_uring_cancel_task_requests(file->private_data, files);
9131 atomic_dec(&tctx->in_idle);
9134 io_uring_remove_task_files(tctx);
9137 static s64 tctx_inflight(struct io_uring_task *tctx)
9139 return percpu_counter_sum(&tctx->inflight);
9142 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
9144 struct io_uring_task *tctx;
9150 tctx = ctx->sq_data->thread->io_uring;
9151 io_disable_sqo_submit(ctx);
9153 atomic_inc(&tctx->in_idle);
9155 /* read completions before cancelations */
9156 inflight = tctx_inflight(tctx);
9159 io_uring_cancel_task_requests(ctx, NULL);
9161 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9163 * If we've seen completions, retry without waiting. This
9164 * avoids a race where a completion comes in before we did
9165 * prepare_to_wait().
9167 if (inflight == tctx_inflight(tctx))
9169 finish_wait(&tctx->wait, &wait);
9171 atomic_dec(&tctx->in_idle);
9175 * Find any io_uring fd that this task has registered or done IO on, and cancel
9178 void __io_uring_task_cancel(void)
9180 struct io_uring_task *tctx = current->io_uring;
9184 /* make sure overflow events are dropped */
9185 atomic_inc(&tctx->in_idle);
9187 /* trigger io_disable_sqo_submit() */
9190 unsigned long index;
9192 xa_for_each(&tctx->xa, index, file)
9193 io_uring_cancel_sqpoll(file->private_data);
9197 /* read completions before cancelations */
9198 inflight = tctx_inflight(tctx);
9201 __io_uring_files_cancel(NULL);
9203 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9206 * If we've seen completions, retry without waiting. This
9207 * avoids a race where a completion comes in before we did
9208 * prepare_to_wait().
9210 if (inflight == tctx_inflight(tctx))
9212 finish_wait(&tctx->wait, &wait);
9215 atomic_dec(&tctx->in_idle);
9217 io_uring_remove_task_files(tctx);
9220 static int io_uring_flush(struct file *file, void *data)
9222 struct io_uring_task *tctx = current->io_uring;
9223 struct io_ring_ctx *ctx = file->private_data;
9225 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
9226 io_uring_cancel_task_requests(ctx, NULL);
9231 /* we should have cancelled and erased it before PF_EXITING */
9232 WARN_ON_ONCE((current->flags & PF_EXITING) &&
9233 xa_load(&tctx->xa, (unsigned long)file));
9236 * fput() is pending, will be 2 if the only other ref is our potential
9237 * task file note. If the task is exiting, drop regardless of count.
9239 if (atomic_long_read(&file->f_count) != 2)
9242 if (ctx->flags & IORING_SETUP_SQPOLL) {
9243 /* there is only one file note, which is owned by sqo_task */
9244 WARN_ON_ONCE(ctx->sqo_task != current &&
9245 xa_load(&tctx->xa, (unsigned long)file));
9246 /* sqo_dead check is for when this happens after cancellation */
9247 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
9248 !xa_load(&tctx->xa, (unsigned long)file));
9250 io_disable_sqo_submit(ctx);
9253 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
9254 io_uring_del_task_file(file);
9258 static void *io_uring_validate_mmap_request(struct file *file,
9259 loff_t pgoff, size_t sz)
9261 struct io_ring_ctx *ctx = file->private_data;
9262 loff_t offset = pgoff << PAGE_SHIFT;
9267 case IORING_OFF_SQ_RING:
9268 case IORING_OFF_CQ_RING:
9271 case IORING_OFF_SQES:
9275 return ERR_PTR(-EINVAL);
9278 page = virt_to_head_page(ptr);
9279 if (sz > page_size(page))
9280 return ERR_PTR(-EINVAL);
9287 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9289 size_t sz = vma->vm_end - vma->vm_start;
9293 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9295 return PTR_ERR(ptr);
9297 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9298 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9301 #else /* !CONFIG_MMU */
9303 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9305 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9308 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9310 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9313 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9314 unsigned long addr, unsigned long len,
9315 unsigned long pgoff, unsigned long flags)
9319 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9321 return PTR_ERR(ptr);
9323 return (unsigned long) ptr;
9326 #endif /* !CONFIG_MMU */
9328 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9334 if (!io_sqring_full(ctx))
9337 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9339 if (unlikely(ctx->sqo_dead)) {
9344 if (!io_sqring_full(ctx))
9348 } while (!signal_pending(current));
9350 finish_wait(&ctx->sqo_sq_wait, &wait);
9355 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9356 struct __kernel_timespec __user **ts,
9357 const sigset_t __user **sig)
9359 struct io_uring_getevents_arg arg;
9362 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9363 * is just a pointer to the sigset_t.
9365 if (!(flags & IORING_ENTER_EXT_ARG)) {
9366 *sig = (const sigset_t __user *) argp;
9372 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9373 * timespec and sigset_t pointers if good.
9375 if (*argsz != sizeof(arg))
9377 if (copy_from_user(&arg, argp, sizeof(arg)))
9379 *sig = u64_to_user_ptr(arg.sigmask);
9380 *argsz = arg.sigmask_sz;
9381 *ts = u64_to_user_ptr(arg.ts);
9385 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9386 u32, min_complete, u32, flags, const void __user *, argp,
9389 struct io_ring_ctx *ctx;
9396 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9397 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9405 if (f.file->f_op != &io_uring_fops)
9409 ctx = f.file->private_data;
9410 if (!percpu_ref_tryget(&ctx->refs))
9414 if (ctx->flags & IORING_SETUP_R_DISABLED)
9418 * For SQ polling, the thread will do all submissions and completions.
9419 * Just return the requested submit count, and wake the thread if
9423 if (ctx->flags & IORING_SETUP_SQPOLL) {
9424 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9427 if (unlikely(ctx->sqo_dead))
9429 if (flags & IORING_ENTER_SQ_WAKEUP)
9430 wake_up(&ctx->sq_data->wait);
9431 if (flags & IORING_ENTER_SQ_WAIT) {
9432 ret = io_sqpoll_wait_sq(ctx);
9436 submitted = to_submit;
9437 } else if (to_submit) {
9438 ret = io_uring_add_task_file(ctx, f.file);
9441 mutex_lock(&ctx->uring_lock);
9442 submitted = io_submit_sqes(ctx, to_submit);
9443 mutex_unlock(&ctx->uring_lock);
9445 if (submitted != to_submit)
9448 if (flags & IORING_ENTER_GETEVENTS) {
9449 const sigset_t __user *sig;
9450 struct __kernel_timespec __user *ts;
9452 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9456 min_complete = min(min_complete, ctx->cq_entries);
9459 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9460 * space applications don't need to do io completion events
9461 * polling again, they can rely on io_sq_thread to do polling
9462 * work, which can reduce cpu usage and uring_lock contention.
9464 if (ctx->flags & IORING_SETUP_IOPOLL &&
9465 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9466 ret = io_iopoll_check(ctx, min_complete);
9468 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9473 percpu_ref_put(&ctx->refs);
9476 return submitted ? submitted : ret;
9479 #ifdef CONFIG_PROC_FS
9480 static int io_uring_show_cred(int id, void *p, void *data)
9482 struct io_identity *iod = p;
9483 const struct cred *cred = iod->creds;
9484 struct seq_file *m = data;
9485 struct user_namespace *uns = seq_user_ns(m);
9486 struct group_info *gi;
9491 seq_printf(m, "%5d\n", id);
9492 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9493 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9494 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9495 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9496 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9497 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9498 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9499 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9500 seq_puts(m, "\n\tGroups:\t");
9501 gi = cred->group_info;
9502 for (g = 0; g < gi->ngroups; g++) {
9503 seq_put_decimal_ull(m, g ? " " : "",
9504 from_kgid_munged(uns, gi->gid[g]));
9506 seq_puts(m, "\n\tCapEff:\t");
9507 cap = cred->cap_effective;
9508 CAP_FOR_EACH_U32(__capi)
9509 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9514 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9516 struct io_sq_data *sq = NULL;
9521 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9522 * since fdinfo case grabs it in the opposite direction of normal use
9523 * cases. If we fail to get the lock, we just don't iterate any
9524 * structures that could be going away outside the io_uring mutex.
9526 has_lock = mutex_trylock(&ctx->uring_lock);
9528 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9531 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9532 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9533 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9534 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9535 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9538 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9540 seq_printf(m, "%5u: <none>\n", i);
9542 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9543 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9544 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9546 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9547 (unsigned int) buf->len);
9549 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9550 seq_printf(m, "Personalities:\n");
9551 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9553 seq_printf(m, "PollList:\n");
9554 spin_lock_irq(&ctx->completion_lock);
9555 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9556 struct hlist_head *list = &ctx->cancel_hash[i];
9557 struct io_kiocb *req;
9559 hlist_for_each_entry(req, list, hash_node)
9560 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9561 req->task->task_works != NULL);
9563 spin_unlock_irq(&ctx->completion_lock);
9565 mutex_unlock(&ctx->uring_lock);
9568 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9570 struct io_ring_ctx *ctx = f->private_data;
9572 if (percpu_ref_tryget(&ctx->refs)) {
9573 __io_uring_show_fdinfo(ctx, m);
9574 percpu_ref_put(&ctx->refs);
9579 static const struct file_operations io_uring_fops = {
9580 .release = io_uring_release,
9581 .flush = io_uring_flush,
9582 .mmap = io_uring_mmap,
9584 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9585 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9587 .poll = io_uring_poll,
9588 .fasync = io_uring_fasync,
9589 #ifdef CONFIG_PROC_FS
9590 .show_fdinfo = io_uring_show_fdinfo,
9594 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9595 struct io_uring_params *p)
9597 struct io_rings *rings;
9598 size_t size, sq_array_offset;
9600 /* make sure these are sane, as we already accounted them */
9601 ctx->sq_entries = p->sq_entries;
9602 ctx->cq_entries = p->cq_entries;
9604 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9605 if (size == SIZE_MAX)
9608 rings = io_mem_alloc(size);
9613 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9614 rings->sq_ring_mask = p->sq_entries - 1;
9615 rings->cq_ring_mask = p->cq_entries - 1;
9616 rings->sq_ring_entries = p->sq_entries;
9617 rings->cq_ring_entries = p->cq_entries;
9618 ctx->sq_mask = rings->sq_ring_mask;
9619 ctx->cq_mask = rings->cq_ring_mask;
9621 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9622 if (size == SIZE_MAX) {
9623 io_mem_free(ctx->rings);
9628 ctx->sq_sqes = io_mem_alloc(size);
9629 if (!ctx->sq_sqes) {
9630 io_mem_free(ctx->rings);
9638 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9642 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9646 ret = io_uring_add_task_file(ctx, file);
9651 fd_install(fd, file);
9656 * Allocate an anonymous fd, this is what constitutes the application
9657 * visible backing of an io_uring instance. The application mmaps this
9658 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9659 * we have to tie this fd to a socket for file garbage collection purposes.
9661 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9664 #if defined(CONFIG_UNIX)
9667 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9670 return ERR_PTR(ret);
9673 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9674 O_RDWR | O_CLOEXEC);
9675 #if defined(CONFIG_UNIX)
9677 sock_release(ctx->ring_sock);
9678 ctx->ring_sock = NULL;
9680 ctx->ring_sock->file = file;
9686 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9687 struct io_uring_params __user *params)
9689 struct user_struct *user = NULL;
9690 struct io_ring_ctx *ctx;
9696 if (entries > IORING_MAX_ENTRIES) {
9697 if (!(p->flags & IORING_SETUP_CLAMP))
9699 entries = IORING_MAX_ENTRIES;
9703 * Use twice as many entries for the CQ ring. It's possible for the
9704 * application to drive a higher depth than the size of the SQ ring,
9705 * since the sqes are only used at submission time. This allows for
9706 * some flexibility in overcommitting a bit. If the application has
9707 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9708 * of CQ ring entries manually.
9710 p->sq_entries = roundup_pow_of_two(entries);
9711 if (p->flags & IORING_SETUP_CQSIZE) {
9713 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9714 * to a power-of-two, if it isn't already. We do NOT impose
9715 * any cq vs sq ring sizing.
9719 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9720 if (!(p->flags & IORING_SETUP_CLAMP))
9722 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9724 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9725 if (p->cq_entries < p->sq_entries)
9728 p->cq_entries = 2 * p->sq_entries;
9731 user = get_uid(current_user());
9733 ctx = io_ring_ctx_alloc(p);
9738 ctx->compat = in_compat_syscall();
9739 ctx->limit_mem = !capable(CAP_IPC_LOCK);
9741 ctx->creds = get_current_cred();
9743 ctx->loginuid = current->loginuid;
9744 ctx->sessionid = current->sessionid;
9746 ctx->sqo_task = get_task_struct(current);
9749 * This is just grabbed for accounting purposes. When a process exits,
9750 * the mm is exited and dropped before the files, hence we need to hang
9751 * on to this mm purely for the purposes of being able to unaccount
9752 * memory (locked/pinned vm). It's not used for anything else.
9754 mmgrab(current->mm);
9755 ctx->mm_account = current->mm;
9757 #ifdef CONFIG_BLK_CGROUP
9759 * The sq thread will belong to the original cgroup it was inited in.
9760 * If the cgroup goes offline (e.g. disabling the io controller), then
9761 * issued bios will be associated with the closest cgroup later in the
9765 ctx->sqo_blkcg_css = blkcg_css();
9766 ret = css_tryget_online(ctx->sqo_blkcg_css);
9769 /* don't init against a dying cgroup, have the user try again */
9770 ctx->sqo_blkcg_css = NULL;
9775 ret = io_allocate_scq_urings(ctx, p);
9779 ret = io_sq_offload_create(ctx, p);
9783 if (!(p->flags & IORING_SETUP_R_DISABLED))
9784 io_sq_offload_start(ctx);
9786 memset(&p->sq_off, 0, sizeof(p->sq_off));
9787 p->sq_off.head = offsetof(struct io_rings, sq.head);
9788 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9789 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9790 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9791 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9792 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9793 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9795 memset(&p->cq_off, 0, sizeof(p->cq_off));
9796 p->cq_off.head = offsetof(struct io_rings, cq.head);
9797 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9798 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9799 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9800 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9801 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9802 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9804 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9805 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9806 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9807 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9808 IORING_FEAT_EXT_ARG;
9810 if (copy_to_user(params, p, sizeof(*p))) {
9815 file = io_uring_get_file(ctx);
9817 ret = PTR_ERR(file);
9822 * Install ring fd as the very last thing, so we don't risk someone
9823 * having closed it before we finish setup
9825 ret = io_uring_install_fd(ctx, file);
9827 io_disable_sqo_submit(ctx);
9828 /* fput will clean it up */
9833 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9836 io_disable_sqo_submit(ctx);
9837 io_ring_ctx_wait_and_kill(ctx);
9842 * Sets up an aio uring context, and returns the fd. Applications asks for a
9843 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9844 * params structure passed in.
9846 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9848 struct io_uring_params p;
9851 if (copy_from_user(&p, params, sizeof(p)))
9853 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9858 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9859 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9860 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9861 IORING_SETUP_R_DISABLED))
9864 return io_uring_create(entries, &p, params);
9867 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9868 struct io_uring_params __user *, params)
9870 return io_uring_setup(entries, params);
9873 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9875 struct io_uring_probe *p;
9879 size = struct_size(p, ops, nr_args);
9880 if (size == SIZE_MAX)
9882 p = kzalloc(size, GFP_KERNEL);
9887 if (copy_from_user(p, arg, size))
9890 if (memchr_inv(p, 0, size))
9893 p->last_op = IORING_OP_LAST - 1;
9894 if (nr_args > IORING_OP_LAST)
9895 nr_args = IORING_OP_LAST;
9897 for (i = 0; i < nr_args; i++) {
9899 if (!io_op_defs[i].not_supported)
9900 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9905 if (copy_to_user(arg, p, size))
9912 static int io_register_personality(struct io_ring_ctx *ctx)
9914 struct io_identity *id;
9917 id = kmalloc(sizeof(*id), GFP_KERNEL);
9921 io_init_identity(id);
9922 id->creds = get_current_cred();
9924 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9926 put_cred(id->creds);
9932 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9933 unsigned int nr_args)
9935 struct io_uring_restriction *res;
9939 /* Restrictions allowed only if rings started disabled */
9940 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9943 /* We allow only a single restrictions registration */
9944 if (ctx->restrictions.registered)
9947 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9950 size = array_size(nr_args, sizeof(*res));
9951 if (size == SIZE_MAX)
9954 res = memdup_user(arg, size);
9956 return PTR_ERR(res);
9960 for (i = 0; i < nr_args; i++) {
9961 switch (res[i].opcode) {
9962 case IORING_RESTRICTION_REGISTER_OP:
9963 if (res[i].register_op >= IORING_REGISTER_LAST) {
9968 __set_bit(res[i].register_op,
9969 ctx->restrictions.register_op);
9971 case IORING_RESTRICTION_SQE_OP:
9972 if (res[i].sqe_op >= IORING_OP_LAST) {
9977 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9979 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9980 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9982 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9983 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9992 /* Reset all restrictions if an error happened */
9994 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9996 ctx->restrictions.registered = true;
10002 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10004 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10007 if (ctx->restrictions.registered)
10008 ctx->restricted = 1;
10010 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10012 io_sq_offload_start(ctx);
10017 static bool io_register_op_must_quiesce(int op)
10020 case IORING_UNREGISTER_FILES:
10021 case IORING_REGISTER_FILES_UPDATE:
10022 case IORING_REGISTER_PROBE:
10023 case IORING_REGISTER_PERSONALITY:
10024 case IORING_UNREGISTER_PERSONALITY:
10031 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10032 void __user *arg, unsigned nr_args)
10033 __releases(ctx->uring_lock)
10034 __acquires(ctx->uring_lock)
10039 * We're inside the ring mutex, if the ref is already dying, then
10040 * someone else killed the ctx or is already going through
10041 * io_uring_register().
10043 if (percpu_ref_is_dying(&ctx->refs))
10046 if (io_register_op_must_quiesce(opcode)) {
10047 percpu_ref_kill(&ctx->refs);
10050 * Drop uring mutex before waiting for references to exit. If
10051 * another thread is currently inside io_uring_enter() it might
10052 * need to grab the uring_lock to make progress. If we hold it
10053 * here across the drain wait, then we can deadlock. It's safe
10054 * to drop the mutex here, since no new references will come in
10055 * after we've killed the percpu ref.
10057 mutex_unlock(&ctx->uring_lock);
10059 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10062 ret = io_run_task_work_sig();
10067 mutex_lock(&ctx->uring_lock);
10070 percpu_ref_resurrect(&ctx->refs);
10075 if (ctx->restricted) {
10076 if (opcode >= IORING_REGISTER_LAST) {
10081 if (!test_bit(opcode, ctx->restrictions.register_op)) {
10088 case IORING_REGISTER_BUFFERS:
10089 ret = io_sqe_buffers_register(ctx, arg, nr_args);
10091 case IORING_UNREGISTER_BUFFERS:
10093 if (arg || nr_args)
10095 ret = io_sqe_buffers_unregister(ctx);
10097 case IORING_REGISTER_FILES:
10098 ret = io_sqe_files_register(ctx, arg, nr_args);
10100 case IORING_UNREGISTER_FILES:
10102 if (arg || nr_args)
10104 ret = io_sqe_files_unregister(ctx);
10106 case IORING_REGISTER_FILES_UPDATE:
10107 ret = io_sqe_files_update(ctx, arg, nr_args);
10109 case IORING_REGISTER_EVENTFD:
10110 case IORING_REGISTER_EVENTFD_ASYNC:
10114 ret = io_eventfd_register(ctx, arg);
10117 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10118 ctx->eventfd_async = 1;
10120 ctx->eventfd_async = 0;
10122 case IORING_UNREGISTER_EVENTFD:
10124 if (arg || nr_args)
10126 ret = io_eventfd_unregister(ctx);
10128 case IORING_REGISTER_PROBE:
10130 if (!arg || nr_args > 256)
10132 ret = io_probe(ctx, arg, nr_args);
10134 case IORING_REGISTER_PERSONALITY:
10136 if (arg || nr_args)
10138 ret = io_register_personality(ctx);
10140 case IORING_UNREGISTER_PERSONALITY:
10144 ret = io_unregister_personality(ctx, nr_args);
10146 case IORING_REGISTER_ENABLE_RINGS:
10148 if (arg || nr_args)
10150 ret = io_register_enable_rings(ctx);
10152 case IORING_REGISTER_RESTRICTIONS:
10153 ret = io_register_restrictions(ctx, arg, nr_args);
10161 if (io_register_op_must_quiesce(opcode)) {
10162 /* bring the ctx back to life */
10163 percpu_ref_reinit(&ctx->refs);
10165 reinit_completion(&ctx->ref_comp);
10170 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10171 void __user *, arg, unsigned int, nr_args)
10173 struct io_ring_ctx *ctx;
10182 if (f.file->f_op != &io_uring_fops)
10185 ctx = f.file->private_data;
10187 mutex_lock(&ctx->uring_lock);
10188 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10189 mutex_unlock(&ctx->uring_lock);
10190 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10191 ctx->cq_ev_fd != NULL, ret);
10197 static int __init io_uring_init(void)
10199 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10200 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10201 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10204 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10205 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10206 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10207 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10208 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10209 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10210 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10211 BUILD_BUG_SQE_ELEM(8, __u64, off);
10212 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10213 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10214 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10215 BUILD_BUG_SQE_ELEM(24, __u32, len);
10216 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10217 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10218 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10219 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10220 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10221 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10222 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10223 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10224 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10225 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10226 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10227 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10228 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10229 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10230 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10231 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10232 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10233 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10234 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10236 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10237 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10238 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10242 __initcall(io_uring_init);