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 struct io_mapped_ubuf {
193 struct bio_vec *bvec;
194 unsigned int nr_bvecs;
195 unsigned long acct_pages;
201 struct list_head list;
208 struct fixed_rsrc_table {
212 struct fixed_rsrc_ref_node {
213 struct percpu_ref refs;
214 struct list_head node;
215 struct list_head rsrc_list;
216 struct fixed_rsrc_data *rsrc_data;
217 void (*rsrc_put)(struct io_ring_ctx *ctx,
218 struct io_rsrc_put *prsrc);
219 struct llist_node llist;
223 struct fixed_rsrc_data {
224 struct fixed_rsrc_table *table;
225 struct io_ring_ctx *ctx;
227 struct fixed_rsrc_ref_node *node;
228 struct percpu_ref refs;
229 struct completion done;
233 struct list_head list;
239 struct io_restriction {
240 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
241 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
242 u8 sqe_flags_allowed;
243 u8 sqe_flags_required;
251 /* ctx's that are using this sqd */
252 struct list_head ctx_list;
253 struct list_head ctx_new_list;
254 struct mutex ctx_lock;
256 struct task_struct *thread;
257 struct wait_queue_head wait;
259 unsigned sq_thread_idle;
264 struct percpu_ref refs;
265 } ____cacheline_aligned_in_smp;
269 unsigned int compat: 1;
270 unsigned int limit_mem: 1;
271 unsigned int cq_overflow_flushed: 1;
272 unsigned int drain_next: 1;
273 unsigned int eventfd_async: 1;
274 unsigned int restricted: 1;
275 unsigned int sqo_dead: 1;
278 * Ring buffer of indices into array of io_uring_sqe, which is
279 * mmapped by the application using the IORING_OFF_SQES offset.
281 * This indirection could e.g. be used to assign fixed
282 * io_uring_sqe entries to operations and only submit them to
283 * the queue when needed.
285 * The kernel modifies neither the indices array nor the entries
289 unsigned cached_sq_head;
292 unsigned sq_thread_idle;
293 unsigned cached_sq_dropped;
294 unsigned cached_cq_overflow;
295 unsigned long sq_check_overflow;
297 struct list_head defer_list;
298 struct list_head timeout_list;
299 struct list_head cq_overflow_list;
301 struct io_uring_sqe *sq_sqes;
302 } ____cacheline_aligned_in_smp;
304 struct io_rings *rings;
310 * For SQPOLL usage - we hold a reference to the parent task, so we
311 * have access to the ->files
313 struct task_struct *sqo_task;
315 /* Only used for accounting purposes */
316 struct mm_struct *mm_account;
318 #ifdef CONFIG_BLK_CGROUP
319 struct cgroup_subsys_state *sqo_blkcg_css;
322 struct io_sq_data *sq_data; /* if using sq thread polling */
324 struct wait_queue_head sqo_sq_wait;
325 struct list_head sqd_list;
328 * If used, fixed file set. Writers must ensure that ->refs is dead,
329 * readers must ensure that ->refs is alive as long as the file* is
330 * used. Only updated through io_uring_register(2).
332 struct fixed_rsrc_data *file_data;
333 unsigned nr_user_files;
335 /* if used, fixed mapped user buffers */
336 unsigned nr_user_bufs;
337 struct io_mapped_ubuf *user_bufs;
339 struct user_struct *user;
341 const struct cred *creds;
345 unsigned int sessionid;
348 struct completion ref_comp;
349 struct completion sq_thread_comp;
351 /* if all else fails... */
352 struct io_kiocb *fallback_req;
354 #if defined(CONFIG_UNIX)
355 struct socket *ring_sock;
358 struct idr io_buffer_idr;
360 struct idr personality_idr;
363 unsigned cached_cq_tail;
366 atomic_t cq_timeouts;
367 unsigned cq_last_tm_flush;
368 unsigned long cq_check_overflow;
369 struct wait_queue_head cq_wait;
370 struct fasync_struct *cq_fasync;
371 struct eventfd_ctx *cq_ev_fd;
372 } ____cacheline_aligned_in_smp;
375 struct mutex uring_lock;
376 wait_queue_head_t wait;
377 } ____cacheline_aligned_in_smp;
380 spinlock_t completion_lock;
383 * ->iopoll_list is protected by the ctx->uring_lock for
384 * io_uring instances that don't use IORING_SETUP_SQPOLL.
385 * For SQPOLL, only the single threaded io_sq_thread() will
386 * manipulate the list, hence no extra locking is needed there.
388 struct list_head iopoll_list;
389 struct hlist_head *cancel_hash;
390 unsigned cancel_hash_bits;
391 bool poll_multi_file;
393 spinlock_t inflight_lock;
394 struct list_head inflight_list;
395 } ____cacheline_aligned_in_smp;
397 struct delayed_work rsrc_put_work;
398 struct llist_head rsrc_put_llist;
399 struct list_head rsrc_ref_list;
400 spinlock_t rsrc_ref_lock;
402 struct work_struct exit_work;
403 struct io_restriction restrictions;
407 * First field must be the file pointer in all the
408 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
410 struct io_poll_iocb {
412 struct wait_queue_head *head;
416 struct wait_queue_entry wait;
419 struct io_poll_remove {
429 struct io_timeout_data {
430 struct io_kiocb *req;
431 struct hrtimer timer;
432 struct timespec64 ts;
433 enum hrtimer_mode mode;
438 struct sockaddr __user *addr;
439 int __user *addr_len;
441 unsigned long nofile;
461 struct list_head list;
462 /* head of the link, used by linked timeouts only */
463 struct io_kiocb *head;
466 struct io_timeout_rem {
471 struct timespec64 ts;
476 /* NOTE: kiocb has the file as the first member, so don't do it here */
484 struct sockaddr __user *addr;
491 struct user_msghdr __user *umsg;
497 struct io_buffer *kbuf;
503 struct filename *filename;
505 unsigned long nofile;
508 struct io_rsrc_update {
534 struct epoll_event event;
538 struct file *file_out;
539 struct file *file_in;
546 struct io_provide_buf {
560 const char __user *filename;
561 struct statx __user *buffer;
573 struct filename *oldpath;
574 struct filename *newpath;
582 struct filename *filename;
585 struct io_completion {
587 struct list_head list;
591 struct io_async_connect {
592 struct sockaddr_storage address;
595 struct io_async_msghdr {
596 struct iovec fast_iov[UIO_FASTIOV];
598 struct sockaddr __user *uaddr;
600 struct sockaddr_storage addr;
604 struct iovec fast_iov[UIO_FASTIOV];
605 const struct iovec *free_iovec;
606 struct iov_iter iter;
608 struct wait_page_queue wpq;
612 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
613 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
614 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
615 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
616 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
617 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
623 REQ_F_LINK_TIMEOUT_BIT,
625 REQ_F_NEED_CLEANUP_BIT,
627 REQ_F_BUFFER_SELECTED_BIT,
628 REQ_F_NO_FILE_TABLE_BIT,
629 REQ_F_WORK_INITIALIZED_BIT,
630 REQ_F_LTIMEOUT_ACTIVE_BIT,
631 REQ_F_COMPLETE_INLINE_BIT,
633 /* not a real bit, just to check we're not overflowing the space */
639 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
640 /* drain existing IO first */
641 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
643 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
644 /* doesn't sever on completion < 0 */
645 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
647 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
648 /* IOSQE_BUFFER_SELECT */
649 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
651 /* fail rest of links */
652 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
653 /* on inflight list */
654 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
655 /* read/write uses file position */
656 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
657 /* must not punt to workers */
658 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
659 /* has or had linked timeout */
660 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
662 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
664 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
665 /* already went through poll handler */
666 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
667 /* buffer already selected */
668 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
669 /* doesn't need file table for this request */
670 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
671 /* io_wq_work is initialized */
672 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
673 /* linked timeout is active, i.e. prepared by link's head */
674 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
675 /* completion is deferred through io_comp_state */
676 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
680 struct io_poll_iocb poll;
681 struct io_poll_iocb *double_poll;
685 * NOTE! Each of the iocb union members has the file pointer
686 * as the first entry in their struct definition. So you can
687 * access the file pointer through any of the sub-structs,
688 * or directly as just 'ki_filp' in this struct.
694 struct io_poll_iocb poll;
695 struct io_poll_remove poll_remove;
696 struct io_accept accept;
698 struct io_cancel cancel;
699 struct io_timeout timeout;
700 struct io_timeout_rem timeout_rem;
701 struct io_connect connect;
702 struct io_sr_msg sr_msg;
704 struct io_close close;
705 struct io_rsrc_update rsrc_update;
706 struct io_fadvise fadvise;
707 struct io_madvise madvise;
708 struct io_epoll epoll;
709 struct io_splice splice;
710 struct io_provide_buf pbuf;
711 struct io_statx statx;
712 struct io_shutdown shutdown;
713 struct io_rename rename;
714 struct io_unlink unlink;
715 /* use only after cleaning per-op data, see io_clean_op() */
716 struct io_completion compl;
719 /* opcode allocated if it needs to store data for async defer */
722 /* polled IO has completed */
728 struct io_ring_ctx *ctx;
731 struct task_struct *task;
734 struct io_kiocb *link;
735 struct percpu_ref *fixed_rsrc_refs;
738 * 1. used with ctx->iopoll_list with reads/writes
739 * 2. to track reqs with ->files (see io_op_def::file_table)
741 struct list_head inflight_entry;
742 struct callback_head task_work;
743 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
744 struct hlist_node hash_node;
745 struct async_poll *apoll;
746 struct io_wq_work work;
749 struct io_defer_entry {
750 struct list_head list;
751 struct io_kiocb *req;
755 #define IO_IOPOLL_BATCH 8
757 struct io_comp_state {
759 struct list_head list;
760 struct io_ring_ctx *ctx;
763 struct io_submit_state {
764 struct blk_plug plug;
767 * io_kiocb alloc cache
769 void *reqs[IO_IOPOLL_BATCH];
770 unsigned int free_reqs;
775 * Batch completion logic
777 struct io_comp_state comp;
780 * File reference cache
784 unsigned int file_refs;
785 unsigned int ios_left;
789 /* needs req->file assigned */
790 unsigned needs_file : 1;
791 /* hash wq insertion if file is a regular file */
792 unsigned hash_reg_file : 1;
793 /* unbound wq insertion if file is a non-regular file */
794 unsigned unbound_nonreg_file : 1;
795 /* opcode is not supported by this kernel */
796 unsigned not_supported : 1;
797 /* set if opcode supports polled "wait" */
799 unsigned pollout : 1;
800 /* op supports buffer selection */
801 unsigned buffer_select : 1;
802 /* must always have async data allocated */
803 unsigned needs_async_data : 1;
804 /* should block plug */
806 /* size of async data needed, if any */
807 unsigned short async_size;
811 static const struct io_op_def io_op_defs[] = {
812 [IORING_OP_NOP] = {},
813 [IORING_OP_READV] = {
815 .unbound_nonreg_file = 1,
818 .needs_async_data = 1,
820 .async_size = sizeof(struct io_async_rw),
821 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
823 [IORING_OP_WRITEV] = {
826 .unbound_nonreg_file = 1,
828 .needs_async_data = 1,
830 .async_size = sizeof(struct io_async_rw),
831 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
834 [IORING_OP_FSYNC] = {
836 .work_flags = IO_WQ_WORK_BLKCG,
838 [IORING_OP_READ_FIXED] = {
840 .unbound_nonreg_file = 1,
843 .async_size = sizeof(struct io_async_rw),
844 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
846 [IORING_OP_WRITE_FIXED] = {
849 .unbound_nonreg_file = 1,
852 .async_size = sizeof(struct io_async_rw),
853 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
856 [IORING_OP_POLL_ADD] = {
858 .unbound_nonreg_file = 1,
860 [IORING_OP_POLL_REMOVE] = {},
861 [IORING_OP_SYNC_FILE_RANGE] = {
863 .work_flags = IO_WQ_WORK_BLKCG,
865 [IORING_OP_SENDMSG] = {
867 .unbound_nonreg_file = 1,
869 .needs_async_data = 1,
870 .async_size = sizeof(struct io_async_msghdr),
871 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
873 [IORING_OP_RECVMSG] = {
875 .unbound_nonreg_file = 1,
878 .needs_async_data = 1,
879 .async_size = sizeof(struct io_async_msghdr),
880 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
882 [IORING_OP_TIMEOUT] = {
883 .needs_async_data = 1,
884 .async_size = sizeof(struct io_timeout_data),
885 .work_flags = IO_WQ_WORK_MM,
887 [IORING_OP_TIMEOUT_REMOVE] = {
888 /* used by timeout updates' prep() */
889 .work_flags = IO_WQ_WORK_MM,
891 [IORING_OP_ACCEPT] = {
893 .unbound_nonreg_file = 1,
895 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
897 [IORING_OP_ASYNC_CANCEL] = {},
898 [IORING_OP_LINK_TIMEOUT] = {
899 .needs_async_data = 1,
900 .async_size = sizeof(struct io_timeout_data),
901 .work_flags = IO_WQ_WORK_MM,
903 [IORING_OP_CONNECT] = {
905 .unbound_nonreg_file = 1,
907 .needs_async_data = 1,
908 .async_size = sizeof(struct io_async_connect),
909 .work_flags = IO_WQ_WORK_MM,
911 [IORING_OP_FALLOCATE] = {
913 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
915 [IORING_OP_OPENAT] = {
916 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
917 IO_WQ_WORK_FS | IO_WQ_WORK_MM,
919 [IORING_OP_CLOSE] = {
920 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
922 [IORING_OP_FILES_UPDATE] = {
923 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
925 [IORING_OP_STATX] = {
926 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
927 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
931 .unbound_nonreg_file = 1,
935 .async_size = sizeof(struct io_async_rw),
936 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
938 [IORING_OP_WRITE] = {
940 .unbound_nonreg_file = 1,
943 .async_size = sizeof(struct io_async_rw),
944 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
947 [IORING_OP_FADVISE] = {
949 .work_flags = IO_WQ_WORK_BLKCG,
951 [IORING_OP_MADVISE] = {
952 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
956 .unbound_nonreg_file = 1,
958 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
962 .unbound_nonreg_file = 1,
965 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
967 [IORING_OP_OPENAT2] = {
968 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
969 IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
971 [IORING_OP_EPOLL_CTL] = {
972 .unbound_nonreg_file = 1,
973 .work_flags = IO_WQ_WORK_FILES,
975 [IORING_OP_SPLICE] = {
978 .unbound_nonreg_file = 1,
979 .work_flags = IO_WQ_WORK_BLKCG,
981 [IORING_OP_PROVIDE_BUFFERS] = {},
982 [IORING_OP_REMOVE_BUFFERS] = {},
986 .unbound_nonreg_file = 1,
988 [IORING_OP_SHUTDOWN] = {
991 [IORING_OP_RENAMEAT] = {
992 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
993 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
995 [IORING_OP_UNLINKAT] = {
996 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
997 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
1001 enum io_mem_account {
1006 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1007 struct task_struct *task,
1008 struct files_struct *files);
1009 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
1010 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
1011 struct io_ring_ctx *ctx);
1012 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
1013 struct fixed_rsrc_ref_node *ref_node);
1015 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
1016 struct io_comp_state *cs);
1017 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1018 static void io_put_req(struct io_kiocb *req);
1019 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1020 static void io_double_put_req(struct io_kiocb *req);
1021 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1022 static void __io_queue_linked_timeout(struct io_kiocb *req);
1023 static void io_queue_linked_timeout(struct io_kiocb *req);
1024 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1025 struct io_uring_rsrc_update *ip,
1027 static void __io_clean_op(struct io_kiocb *req);
1028 static struct file *io_file_get(struct io_submit_state *state,
1029 struct io_kiocb *req, int fd, bool fixed);
1030 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs);
1031 static void io_rsrc_put_work(struct work_struct *work);
1033 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1034 struct iovec **iovec, struct iov_iter *iter,
1036 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1037 const struct iovec *fast_iov,
1038 struct iov_iter *iter, bool force);
1039 static void io_req_task_queue(struct io_kiocb *req);
1041 static struct kmem_cache *req_cachep;
1043 static const struct file_operations io_uring_fops;
1045 struct sock *io_uring_get_socket(struct file *file)
1047 #if defined(CONFIG_UNIX)
1048 if (file->f_op == &io_uring_fops) {
1049 struct io_ring_ctx *ctx = file->private_data;
1051 return ctx->ring_sock->sk;
1056 EXPORT_SYMBOL(io_uring_get_socket);
1058 #define io_for_each_link(pos, head) \
1059 for (pos = (head); pos; pos = pos->link)
1061 static inline void io_clean_op(struct io_kiocb *req)
1063 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1067 static inline void io_set_resource_node(struct io_kiocb *req)
1069 struct io_ring_ctx *ctx = req->ctx;
1071 if (!req->fixed_rsrc_refs) {
1072 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1073 percpu_ref_get(req->fixed_rsrc_refs);
1077 static bool io_match_task(struct io_kiocb *head,
1078 struct task_struct *task,
1079 struct files_struct *files)
1081 struct io_kiocb *req;
1083 if (task && head->task != task) {
1084 /* in terms of cancelation, always match if req task is dead */
1085 if (head->task->flags & PF_EXITING)
1092 io_for_each_link(req, head) {
1093 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1095 if (req->file && req->file->f_op == &io_uring_fops)
1097 if ((req->work.flags & IO_WQ_WORK_FILES) &&
1098 req->work.identity->files == files)
1104 static void io_sq_thread_drop_mm_files(void)
1106 struct files_struct *files = current->files;
1107 struct mm_struct *mm = current->mm;
1110 kthread_unuse_mm(mm);
1115 struct nsproxy *nsproxy = current->nsproxy;
1118 current->files = NULL;
1119 current->nsproxy = NULL;
1120 task_unlock(current);
1121 put_files_struct(files);
1122 put_nsproxy(nsproxy);
1126 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1128 if (current->flags & PF_EXITING)
1131 if (!current->files) {
1132 struct files_struct *files;
1133 struct nsproxy *nsproxy;
1135 task_lock(ctx->sqo_task);
1136 files = ctx->sqo_task->files;
1138 task_unlock(ctx->sqo_task);
1141 atomic_inc(&files->count);
1142 get_nsproxy(ctx->sqo_task->nsproxy);
1143 nsproxy = ctx->sqo_task->nsproxy;
1144 task_unlock(ctx->sqo_task);
1147 current->files = files;
1148 current->nsproxy = nsproxy;
1149 task_unlock(current);
1154 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1156 struct mm_struct *mm;
1158 if (current->flags & PF_EXITING)
1163 /* Should never happen */
1164 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL)))
1167 task_lock(ctx->sqo_task);
1168 mm = ctx->sqo_task->mm;
1169 if (unlikely(!mm || !mmget_not_zero(mm)))
1171 task_unlock(ctx->sqo_task);
1181 static int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1182 struct io_kiocb *req)
1184 const struct io_op_def *def = &io_op_defs[req->opcode];
1187 if (def->work_flags & IO_WQ_WORK_MM) {
1188 ret = __io_sq_thread_acquire_mm(ctx);
1193 if (def->needs_file || (def->work_flags & IO_WQ_WORK_FILES)) {
1194 ret = __io_sq_thread_acquire_files(ctx);
1202 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1203 struct cgroup_subsys_state **cur_css)
1206 #ifdef CONFIG_BLK_CGROUP
1207 /* puts the old one when swapping */
1208 if (*cur_css != ctx->sqo_blkcg_css) {
1209 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1210 *cur_css = ctx->sqo_blkcg_css;
1215 static void io_sq_thread_unassociate_blkcg(void)
1217 #ifdef CONFIG_BLK_CGROUP
1218 kthread_associate_blkcg(NULL);
1222 static inline void req_set_fail_links(struct io_kiocb *req)
1224 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1225 req->flags |= REQ_F_FAIL_LINK;
1229 * None of these are dereferenced, they are simply used to check if any of
1230 * them have changed. If we're under current and check they are still the
1231 * same, we're fine to grab references to them for actual out-of-line use.
1233 static void io_init_identity(struct io_identity *id)
1235 id->files = current->files;
1236 id->mm = current->mm;
1237 #ifdef CONFIG_BLK_CGROUP
1239 id->blkcg_css = blkcg_css();
1242 id->creds = current_cred();
1243 id->nsproxy = current->nsproxy;
1244 id->fs = current->fs;
1245 id->fsize = rlimit(RLIMIT_FSIZE);
1247 id->loginuid = current->loginuid;
1248 id->sessionid = current->sessionid;
1250 refcount_set(&id->count, 1);
1253 static inline void __io_req_init_async(struct io_kiocb *req)
1255 memset(&req->work, 0, sizeof(req->work));
1256 req->flags |= REQ_F_WORK_INITIALIZED;
1260 * Note: must call io_req_init_async() for the first time you
1261 * touch any members of io_wq_work.
1263 static inline void io_req_init_async(struct io_kiocb *req)
1265 struct io_uring_task *tctx = current->io_uring;
1267 if (req->flags & REQ_F_WORK_INITIALIZED)
1270 __io_req_init_async(req);
1272 /* Grab a ref if this isn't our static identity */
1273 req->work.identity = tctx->identity;
1274 if (tctx->identity != &tctx->__identity)
1275 refcount_inc(&req->work.identity->count);
1278 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1280 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1282 complete(&ctx->ref_comp);
1285 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1287 return !req->timeout.off;
1290 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1292 struct io_ring_ctx *ctx;
1295 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1299 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1300 if (!ctx->fallback_req)
1304 * Use 5 bits less than the max cq entries, that should give us around
1305 * 32 entries per hash list if totally full and uniformly spread.
1307 hash_bits = ilog2(p->cq_entries);
1311 ctx->cancel_hash_bits = hash_bits;
1312 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1314 if (!ctx->cancel_hash)
1316 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1318 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1319 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1322 ctx->flags = p->flags;
1323 init_waitqueue_head(&ctx->sqo_sq_wait);
1324 INIT_LIST_HEAD(&ctx->sqd_list);
1325 init_waitqueue_head(&ctx->cq_wait);
1326 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1327 init_completion(&ctx->ref_comp);
1328 init_completion(&ctx->sq_thread_comp);
1329 idr_init(&ctx->io_buffer_idr);
1330 idr_init(&ctx->personality_idr);
1331 mutex_init(&ctx->uring_lock);
1332 init_waitqueue_head(&ctx->wait);
1333 spin_lock_init(&ctx->completion_lock);
1334 INIT_LIST_HEAD(&ctx->iopoll_list);
1335 INIT_LIST_HEAD(&ctx->defer_list);
1336 INIT_LIST_HEAD(&ctx->timeout_list);
1337 spin_lock_init(&ctx->inflight_lock);
1338 INIT_LIST_HEAD(&ctx->inflight_list);
1339 spin_lock_init(&ctx->rsrc_ref_lock);
1340 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1341 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1342 init_llist_head(&ctx->rsrc_put_llist);
1345 if (ctx->fallback_req)
1346 kmem_cache_free(req_cachep, ctx->fallback_req);
1347 kfree(ctx->cancel_hash);
1352 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1354 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1355 struct io_ring_ctx *ctx = req->ctx;
1357 return seq != ctx->cached_cq_tail
1358 + READ_ONCE(ctx->cached_cq_overflow);
1364 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1366 if (req->work.identity == &tctx->__identity)
1368 if (refcount_dec_and_test(&req->work.identity->count))
1369 kfree(req->work.identity);
1372 static void io_req_clean_work(struct io_kiocb *req)
1374 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1377 if (req->work.flags & IO_WQ_WORK_MM)
1378 mmdrop(req->work.identity->mm);
1379 #ifdef CONFIG_BLK_CGROUP
1380 if (req->work.flags & IO_WQ_WORK_BLKCG)
1381 css_put(req->work.identity->blkcg_css);
1383 if (req->work.flags & IO_WQ_WORK_CREDS)
1384 put_cred(req->work.identity->creds);
1385 if (req->work.flags & IO_WQ_WORK_FS) {
1386 struct fs_struct *fs = req->work.identity->fs;
1388 spin_lock(&req->work.identity->fs->lock);
1391 spin_unlock(&req->work.identity->fs->lock);
1395 if (req->work.flags & IO_WQ_WORK_FILES) {
1396 put_files_struct(req->work.identity->files);
1397 put_nsproxy(req->work.identity->nsproxy);
1399 if (req->flags & REQ_F_INFLIGHT) {
1400 struct io_ring_ctx *ctx = req->ctx;
1401 struct io_uring_task *tctx = req->task->io_uring;
1402 unsigned long flags;
1404 spin_lock_irqsave(&ctx->inflight_lock, flags);
1405 list_del(&req->inflight_entry);
1406 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1407 req->flags &= ~REQ_F_INFLIGHT;
1408 if (atomic_read(&tctx->in_idle))
1409 wake_up(&tctx->wait);
1412 req->flags &= ~REQ_F_WORK_INITIALIZED;
1413 req->work.flags &= ~(IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG | IO_WQ_WORK_FS |
1414 IO_WQ_WORK_CREDS | IO_WQ_WORK_FILES);
1415 io_put_identity(req->task->io_uring, req);
1419 * Create a private copy of io_identity, since some fields don't match
1420 * the current context.
1422 static bool io_identity_cow(struct io_kiocb *req)
1424 struct io_uring_task *tctx = current->io_uring;
1425 const struct cred *creds = NULL;
1426 struct io_identity *id;
1428 if (req->work.flags & IO_WQ_WORK_CREDS)
1429 creds = req->work.identity->creds;
1431 id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1432 if (unlikely(!id)) {
1433 req->work.flags |= IO_WQ_WORK_CANCEL;
1438 * We can safely just re-init the creds we copied Either the field
1439 * matches the current one, or we haven't grabbed it yet. The only
1440 * exception is ->creds, through registered personalities, so handle
1441 * that one separately.
1443 io_init_identity(id);
1447 /* add one for this request */
1448 refcount_inc(&id->count);
1450 /* drop tctx and req identity references, if needed */
1451 if (tctx->identity != &tctx->__identity &&
1452 refcount_dec_and_test(&tctx->identity->count))
1453 kfree(tctx->identity);
1454 if (req->work.identity != &tctx->__identity &&
1455 refcount_dec_and_test(&req->work.identity->count))
1456 kfree(req->work.identity);
1458 req->work.identity = id;
1459 tctx->identity = id;
1463 static void io_req_track_inflight(struct io_kiocb *req)
1465 struct io_ring_ctx *ctx = req->ctx;
1467 if (!(req->flags & REQ_F_INFLIGHT)) {
1468 io_req_init_async(req);
1469 req->flags |= REQ_F_INFLIGHT;
1471 spin_lock_irq(&ctx->inflight_lock);
1472 list_add(&req->inflight_entry, &ctx->inflight_list);
1473 spin_unlock_irq(&ctx->inflight_lock);
1477 static bool io_grab_identity(struct io_kiocb *req)
1479 const struct io_op_def *def = &io_op_defs[req->opcode];
1480 struct io_identity *id = req->work.identity;
1482 if (def->work_flags & IO_WQ_WORK_FSIZE) {
1483 if (id->fsize != rlimit(RLIMIT_FSIZE))
1485 req->work.flags |= IO_WQ_WORK_FSIZE;
1487 #ifdef CONFIG_BLK_CGROUP
1488 if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1489 (def->work_flags & IO_WQ_WORK_BLKCG)) {
1491 if (id->blkcg_css != blkcg_css()) {
1496 * This should be rare, either the cgroup is dying or the task
1497 * is moving cgroups. Just punt to root for the handful of ios.
1499 if (css_tryget_online(id->blkcg_css))
1500 req->work.flags |= IO_WQ_WORK_BLKCG;
1504 if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1505 if (id->creds != current_cred())
1507 get_cred(id->creds);
1508 req->work.flags |= IO_WQ_WORK_CREDS;
1511 if (!uid_eq(current->loginuid, id->loginuid) ||
1512 current->sessionid != id->sessionid)
1515 if (!(req->work.flags & IO_WQ_WORK_FS) &&
1516 (def->work_flags & IO_WQ_WORK_FS)) {
1517 if (current->fs != id->fs)
1519 spin_lock(&id->fs->lock);
1520 if (!id->fs->in_exec) {
1522 req->work.flags |= IO_WQ_WORK_FS;
1524 req->work.flags |= IO_WQ_WORK_CANCEL;
1526 spin_unlock(¤t->fs->lock);
1528 if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1529 (def->work_flags & IO_WQ_WORK_FILES) &&
1530 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1531 if (id->files != current->files ||
1532 id->nsproxy != current->nsproxy)
1534 atomic_inc(&id->files->count);
1535 get_nsproxy(id->nsproxy);
1536 req->work.flags |= IO_WQ_WORK_FILES;
1537 io_req_track_inflight(req);
1539 if (!(req->work.flags & IO_WQ_WORK_MM) &&
1540 (def->work_flags & IO_WQ_WORK_MM)) {
1541 if (id->mm != current->mm)
1544 req->work.flags |= IO_WQ_WORK_MM;
1550 static void io_prep_async_work(struct io_kiocb *req)
1552 const struct io_op_def *def = &io_op_defs[req->opcode];
1553 struct io_ring_ctx *ctx = req->ctx;
1555 io_req_init_async(req);
1557 if (req->flags & REQ_F_FORCE_ASYNC)
1558 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1560 if (req->flags & REQ_F_ISREG) {
1561 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1562 io_wq_hash_work(&req->work, file_inode(req->file));
1564 if (def->unbound_nonreg_file)
1565 req->work.flags |= IO_WQ_WORK_UNBOUND;
1568 /* if we fail grabbing identity, we must COW, regrab, and retry */
1569 if (io_grab_identity(req))
1572 if (!io_identity_cow(req))
1575 /* can't fail at this point */
1576 if (!io_grab_identity(req))
1580 static void io_prep_async_link(struct io_kiocb *req)
1582 struct io_kiocb *cur;
1584 io_for_each_link(cur, req)
1585 io_prep_async_work(cur);
1588 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1590 struct io_ring_ctx *ctx = req->ctx;
1591 struct io_kiocb *link = io_prep_linked_timeout(req);
1593 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1594 &req->work, req->flags);
1595 io_wq_enqueue(ctx->io_wq, &req->work);
1599 static void io_queue_async_work(struct io_kiocb *req)
1601 struct io_kiocb *link;
1603 /* init ->work of the whole link before punting */
1604 io_prep_async_link(req);
1605 link = __io_queue_async_work(req);
1608 io_queue_linked_timeout(link);
1611 static void io_kill_timeout(struct io_kiocb *req)
1613 struct io_timeout_data *io = req->async_data;
1616 ret = hrtimer_try_to_cancel(&io->timer);
1618 atomic_set(&req->ctx->cq_timeouts,
1619 atomic_read(&req->ctx->cq_timeouts) + 1);
1620 list_del_init(&req->timeout.list);
1621 io_cqring_fill_event(req, 0);
1622 io_put_req_deferred(req, 1);
1627 * Returns true if we found and killed one or more timeouts
1629 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1630 struct files_struct *files)
1632 struct io_kiocb *req, *tmp;
1635 spin_lock_irq(&ctx->completion_lock);
1636 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1637 if (io_match_task(req, tsk, files)) {
1638 io_kill_timeout(req);
1642 spin_unlock_irq(&ctx->completion_lock);
1643 return canceled != 0;
1646 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1649 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1650 struct io_defer_entry, list);
1652 if (req_need_defer(de->req, de->seq))
1654 list_del_init(&de->list);
1655 io_req_task_queue(de->req);
1657 } while (!list_empty(&ctx->defer_list));
1660 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1664 if (list_empty(&ctx->timeout_list))
1667 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1670 u32 events_needed, events_got;
1671 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1672 struct io_kiocb, timeout.list);
1674 if (io_is_timeout_noseq(req))
1678 * Since seq can easily wrap around over time, subtract
1679 * the last seq at which timeouts were flushed before comparing.
1680 * Assuming not more than 2^31-1 events have happened since,
1681 * these subtractions won't have wrapped, so we can check if
1682 * target is in [last_seq, current_seq] by comparing the two.
1684 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1685 events_got = seq - ctx->cq_last_tm_flush;
1686 if (events_got < events_needed)
1689 list_del_init(&req->timeout.list);
1690 io_kill_timeout(req);
1691 } while (!list_empty(&ctx->timeout_list));
1693 ctx->cq_last_tm_flush = seq;
1696 static void io_commit_cqring(struct io_ring_ctx *ctx)
1698 io_flush_timeouts(ctx);
1700 /* order cqe stores with ring update */
1701 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1703 if (unlikely(!list_empty(&ctx->defer_list)))
1704 __io_queue_deferred(ctx);
1707 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1709 struct io_rings *r = ctx->rings;
1711 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1714 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1716 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1719 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1721 struct io_rings *rings = ctx->rings;
1725 * writes to the cq entry need to come after reading head; the
1726 * control dependency is enough as we're using WRITE_ONCE to
1729 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1732 tail = ctx->cached_cq_tail++;
1733 return &rings->cqes[tail & ctx->cq_mask];
1736 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1740 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1742 if (!ctx->eventfd_async)
1744 return io_wq_current_is_worker();
1747 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1749 /* see waitqueue_active() comment */
1752 if (waitqueue_active(&ctx->wait))
1753 wake_up(&ctx->wait);
1754 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1755 wake_up(&ctx->sq_data->wait);
1756 if (io_should_trigger_evfd(ctx))
1757 eventfd_signal(ctx->cq_ev_fd, 1);
1758 if (waitqueue_active(&ctx->cq_wait)) {
1759 wake_up_interruptible(&ctx->cq_wait);
1760 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1764 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1766 /* see waitqueue_active() comment */
1769 if (ctx->flags & IORING_SETUP_SQPOLL) {
1770 if (waitqueue_active(&ctx->wait))
1771 wake_up(&ctx->wait);
1773 if (io_should_trigger_evfd(ctx))
1774 eventfd_signal(ctx->cq_ev_fd, 1);
1775 if (waitqueue_active(&ctx->cq_wait)) {
1776 wake_up_interruptible(&ctx->cq_wait);
1777 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1781 /* Returns true if there are no backlogged entries after the flush */
1782 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1783 struct task_struct *tsk,
1784 struct files_struct *files)
1786 struct io_rings *rings = ctx->rings;
1787 struct io_kiocb *req, *tmp;
1788 struct io_uring_cqe *cqe;
1789 unsigned long flags;
1790 bool all_flushed, posted;
1793 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1797 spin_lock_irqsave(&ctx->completion_lock, flags);
1798 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1799 if (!io_match_task(req, tsk, files))
1802 cqe = io_get_cqring(ctx);
1806 list_move(&req->compl.list, &list);
1808 WRITE_ONCE(cqe->user_data, req->user_data);
1809 WRITE_ONCE(cqe->res, req->result);
1810 WRITE_ONCE(cqe->flags, req->compl.cflags);
1812 ctx->cached_cq_overflow++;
1813 WRITE_ONCE(ctx->rings->cq_overflow,
1814 ctx->cached_cq_overflow);
1819 all_flushed = list_empty(&ctx->cq_overflow_list);
1821 clear_bit(0, &ctx->sq_check_overflow);
1822 clear_bit(0, &ctx->cq_check_overflow);
1823 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1827 io_commit_cqring(ctx);
1828 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1830 io_cqring_ev_posted(ctx);
1832 while (!list_empty(&list)) {
1833 req = list_first_entry(&list, struct io_kiocb, compl.list);
1834 list_del(&req->compl.list);
1841 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1842 struct task_struct *tsk,
1843 struct files_struct *files)
1845 if (test_bit(0, &ctx->cq_check_overflow)) {
1846 /* iopoll syncs against uring_lock, not completion_lock */
1847 if (ctx->flags & IORING_SETUP_IOPOLL)
1848 mutex_lock(&ctx->uring_lock);
1849 __io_cqring_overflow_flush(ctx, force, tsk, files);
1850 if (ctx->flags & IORING_SETUP_IOPOLL)
1851 mutex_unlock(&ctx->uring_lock);
1855 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1857 struct io_ring_ctx *ctx = req->ctx;
1858 struct io_uring_cqe *cqe;
1860 trace_io_uring_complete(ctx, req->user_data, res);
1863 * If we can't get a cq entry, userspace overflowed the
1864 * submission (by quite a lot). Increment the overflow count in
1867 cqe = io_get_cqring(ctx);
1869 WRITE_ONCE(cqe->user_data, req->user_data);
1870 WRITE_ONCE(cqe->res, res);
1871 WRITE_ONCE(cqe->flags, cflags);
1872 } else if (ctx->cq_overflow_flushed ||
1873 atomic_read(&req->task->io_uring->in_idle)) {
1875 * If we're in ring overflow flush mode, or in task cancel mode,
1876 * then we cannot store the request for later flushing, we need
1877 * to drop it on the floor.
1879 ctx->cached_cq_overflow++;
1880 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1882 if (list_empty(&ctx->cq_overflow_list)) {
1883 set_bit(0, &ctx->sq_check_overflow);
1884 set_bit(0, &ctx->cq_check_overflow);
1885 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1889 req->compl.cflags = cflags;
1890 refcount_inc(&req->refs);
1891 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1895 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1897 __io_cqring_fill_event(req, res, 0);
1900 static void io_req_complete_post(struct io_kiocb *req, long res,
1901 unsigned int cflags)
1903 struct io_ring_ctx *ctx = req->ctx;
1904 unsigned long flags;
1906 spin_lock_irqsave(&ctx->completion_lock, flags);
1907 __io_cqring_fill_event(req, res, cflags);
1908 io_commit_cqring(ctx);
1909 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1911 io_cqring_ev_posted(ctx);
1914 static inline void io_req_complete_nostate(struct io_kiocb *req, long res,
1915 unsigned int cflags)
1917 io_req_complete_post(req, res, cflags);
1921 static void io_submit_flush_completions(struct io_comp_state *cs)
1923 struct io_ring_ctx *ctx = cs->ctx;
1925 spin_lock_irq(&ctx->completion_lock);
1926 while (!list_empty(&cs->list)) {
1927 struct io_kiocb *req;
1929 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1930 list_del(&req->compl.list);
1931 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1934 * io_free_req() doesn't care about completion_lock unless one
1935 * of these flags is set. REQ_F_WORK_INITIALIZED is in the list
1936 * because of a potential deadlock with req->work.fs->lock
1937 * We defer both, completion and submission refs.
1939 if (req->flags & (REQ_F_FAIL_LINK|REQ_F_LINK_TIMEOUT
1940 |REQ_F_WORK_INITIALIZED)) {
1941 spin_unlock_irq(&ctx->completion_lock);
1942 io_double_put_req(req);
1943 spin_lock_irq(&ctx->completion_lock);
1945 io_double_put_req(req);
1948 io_commit_cqring(ctx);
1949 spin_unlock_irq(&ctx->completion_lock);
1951 io_cqring_ev_posted(ctx);
1955 static void io_req_complete_state(struct io_kiocb *req, long res,
1956 unsigned int cflags, struct io_comp_state *cs)
1960 req->compl.cflags = cflags;
1961 req->flags |= REQ_F_COMPLETE_INLINE;
1964 static inline void __io_req_complete(struct io_kiocb *req, long res,
1965 unsigned cflags, struct io_comp_state *cs)
1968 io_req_complete_nostate(req, res, cflags);
1970 io_req_complete_state(req, res, cflags, cs);
1973 static inline void io_req_complete(struct io_kiocb *req, long res)
1975 __io_req_complete(req, res, 0, NULL);
1978 static inline bool io_is_fallback_req(struct io_kiocb *req)
1980 return req == (struct io_kiocb *)
1981 ((unsigned long) req->ctx->fallback_req & ~1UL);
1984 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1986 struct io_kiocb *req;
1988 req = ctx->fallback_req;
1989 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1995 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1996 struct io_submit_state *state)
1998 if (!state->free_reqs) {
1999 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2003 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
2004 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
2007 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2008 * retry single alloc to be on the safe side.
2010 if (unlikely(ret <= 0)) {
2011 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2012 if (!state->reqs[0])
2013 return io_get_fallback_req(ctx);
2016 state->free_reqs = ret;
2020 return state->reqs[state->free_reqs];
2023 static inline void io_put_file(struct io_kiocb *req, struct file *file,
2030 static void io_dismantle_req(struct io_kiocb *req)
2034 if (req->async_data)
2035 kfree(req->async_data);
2037 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
2038 if (req->fixed_rsrc_refs)
2039 percpu_ref_put(req->fixed_rsrc_refs);
2040 io_req_clean_work(req);
2043 static inline void io_put_task(struct task_struct *task, int nr)
2045 struct io_uring_task *tctx = task->io_uring;
2047 percpu_counter_sub(&tctx->inflight, nr);
2048 if (unlikely(atomic_read(&tctx->in_idle)))
2049 wake_up(&tctx->wait);
2050 put_task_struct_many(task, nr);
2053 static void __io_free_req(struct io_kiocb *req)
2055 struct io_ring_ctx *ctx = req->ctx;
2057 io_dismantle_req(req);
2058 io_put_task(req->task, 1);
2060 if (likely(!io_is_fallback_req(req)))
2061 kmem_cache_free(req_cachep, req);
2063 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
2064 percpu_ref_put(&ctx->refs);
2067 static inline void io_remove_next_linked(struct io_kiocb *req)
2069 struct io_kiocb *nxt = req->link;
2071 req->link = nxt->link;
2075 static void io_kill_linked_timeout(struct io_kiocb *req)
2077 struct io_ring_ctx *ctx = req->ctx;
2078 struct io_kiocb *link;
2079 bool cancelled = false;
2080 unsigned long flags;
2082 spin_lock_irqsave(&ctx->completion_lock, flags);
2086 * Can happen if a linked timeout fired and link had been like
2087 * req -> link t-out -> link t-out [-> ...]
2089 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
2090 struct io_timeout_data *io = link->async_data;
2093 io_remove_next_linked(req);
2094 link->timeout.head = NULL;
2095 ret = hrtimer_try_to_cancel(&io->timer);
2097 io_cqring_fill_event(link, -ECANCELED);
2098 io_commit_cqring(ctx);
2102 req->flags &= ~REQ_F_LINK_TIMEOUT;
2103 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2106 io_cqring_ev_posted(ctx);
2112 static void io_fail_links(struct io_kiocb *req)
2114 struct io_kiocb *link, *nxt;
2115 struct io_ring_ctx *ctx = req->ctx;
2116 unsigned long flags;
2118 spin_lock_irqsave(&ctx->completion_lock, flags);
2126 trace_io_uring_fail_link(req, link);
2127 io_cqring_fill_event(link, -ECANCELED);
2130 * It's ok to free under spinlock as they're not linked anymore,
2131 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
2134 if (link->flags & REQ_F_WORK_INITIALIZED)
2135 io_put_req_deferred(link, 2);
2137 io_double_put_req(link);
2140 io_commit_cqring(ctx);
2141 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2143 io_cqring_ev_posted(ctx);
2146 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2148 if (req->flags & REQ_F_LINK_TIMEOUT)
2149 io_kill_linked_timeout(req);
2152 * If LINK is set, we have dependent requests in this chain. If we
2153 * didn't fail this request, queue the first one up, moving any other
2154 * dependencies to the next request. In case of failure, fail the rest
2157 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
2158 struct io_kiocb *nxt = req->link;
2167 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2169 if (likely(!(req->link) && !(req->flags & REQ_F_LINK_TIMEOUT)))
2171 return __io_req_find_next(req);
2174 static int io_req_task_work_add(struct io_kiocb *req)
2176 struct task_struct *tsk = req->task;
2177 struct io_ring_ctx *ctx = req->ctx;
2178 enum task_work_notify_mode notify;
2181 if (tsk->flags & PF_EXITING)
2185 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2186 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2187 * processing task_work. There's no reliable way to tell if TWA_RESUME
2191 if (!(ctx->flags & IORING_SETUP_SQPOLL))
2192 notify = TWA_SIGNAL;
2194 ret = task_work_add(tsk, &req->task_work, notify);
2196 wake_up_process(tsk);
2201 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2202 void (*cb)(struct callback_head *))
2204 struct task_struct *tsk = io_wq_get_task(req->ctx->io_wq);
2206 init_task_work(&req->task_work, cb);
2207 task_work_add(tsk, &req->task_work, TWA_NONE);
2208 wake_up_process(tsk);
2211 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2213 struct io_ring_ctx *ctx = req->ctx;
2215 spin_lock_irq(&ctx->completion_lock);
2216 io_cqring_fill_event(req, error);
2217 io_commit_cqring(ctx);
2218 spin_unlock_irq(&ctx->completion_lock);
2220 io_cqring_ev_posted(ctx);
2221 req_set_fail_links(req);
2222 io_double_put_req(req);
2225 static void io_req_task_cancel(struct callback_head *cb)
2227 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2228 struct io_ring_ctx *ctx = req->ctx;
2230 __io_req_task_cancel(req, -ECANCELED);
2231 percpu_ref_put(&ctx->refs);
2234 static void __io_req_task_submit(struct io_kiocb *req)
2236 struct io_ring_ctx *ctx = req->ctx;
2238 mutex_lock(&ctx->uring_lock);
2239 if (!ctx->sqo_dead &&
2240 !__io_sq_thread_acquire_mm(ctx) &&
2241 !__io_sq_thread_acquire_files(ctx))
2242 __io_queue_sqe(req, NULL);
2244 __io_req_task_cancel(req, -EFAULT);
2245 mutex_unlock(&ctx->uring_lock);
2248 static void io_req_task_submit(struct callback_head *cb)
2250 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2251 struct io_ring_ctx *ctx = req->ctx;
2253 __io_req_task_submit(req);
2254 percpu_ref_put(&ctx->refs);
2257 static void io_req_task_queue(struct io_kiocb *req)
2261 init_task_work(&req->task_work, io_req_task_submit);
2262 percpu_ref_get(&req->ctx->refs);
2264 ret = io_req_task_work_add(req);
2266 io_req_task_work_add_fallback(req, io_req_task_cancel);
2269 static inline void io_queue_next(struct io_kiocb *req)
2271 struct io_kiocb *nxt = io_req_find_next(req);
2274 io_req_task_queue(nxt);
2277 static void io_free_req(struct io_kiocb *req)
2284 void *reqs[IO_IOPOLL_BATCH];
2287 struct task_struct *task;
2291 static inline void io_init_req_batch(struct req_batch *rb)
2298 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
2299 struct req_batch *rb)
2301 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
2302 percpu_ref_put_many(&ctx->refs, rb->to_free);
2306 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2307 struct req_batch *rb)
2310 __io_req_free_batch_flush(ctx, rb);
2312 io_put_task(rb->task, rb->task_refs);
2317 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
2319 if (unlikely(io_is_fallback_req(req))) {
2325 if (req->task != rb->task) {
2327 io_put_task(rb->task, rb->task_refs);
2328 rb->task = req->task;
2333 io_dismantle_req(req);
2334 rb->reqs[rb->to_free++] = req;
2335 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
2336 __io_req_free_batch_flush(req->ctx, rb);
2340 * Drop reference to request, return next in chain (if there is one) if this
2341 * was the last reference to this request.
2343 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2345 struct io_kiocb *nxt = NULL;
2347 if (refcount_dec_and_test(&req->refs)) {
2348 nxt = io_req_find_next(req);
2354 static void io_put_req(struct io_kiocb *req)
2356 if (refcount_dec_and_test(&req->refs))
2360 static void io_put_req_deferred_cb(struct callback_head *cb)
2362 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2367 static void io_free_req_deferred(struct io_kiocb *req)
2371 init_task_work(&req->task_work, io_put_req_deferred_cb);
2372 ret = io_req_task_work_add(req);
2374 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2377 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2379 if (refcount_sub_and_test(refs, &req->refs))
2380 io_free_req_deferred(req);
2383 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
2385 struct io_kiocb *nxt;
2388 * A ref is owned by io-wq in which context we're. So, if that's the
2389 * last one, it's safe to steal next work. False negatives are Ok,
2390 * it just will be re-punted async in io_put_work()
2392 if (refcount_read(&req->refs) != 1)
2395 nxt = io_req_find_next(req);
2396 return nxt ? &nxt->work : NULL;
2399 static void io_double_put_req(struct io_kiocb *req)
2401 /* drop both submit and complete references */
2402 if (refcount_sub_and_test(2, &req->refs))
2406 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2408 /* See comment at the top of this file */
2410 return __io_cqring_events(ctx);
2413 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2415 struct io_rings *rings = ctx->rings;
2417 /* make sure SQ entry isn't read before tail */
2418 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2421 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2423 unsigned int cflags;
2425 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2426 cflags |= IORING_CQE_F_BUFFER;
2427 req->flags &= ~REQ_F_BUFFER_SELECTED;
2432 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2434 struct io_buffer *kbuf;
2436 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2437 return io_put_kbuf(req, kbuf);
2440 static inline bool io_run_task_work(void)
2443 * Not safe to run on exiting task, and the task_work handling will
2444 * not add work to such a task.
2446 if (unlikely(current->flags & PF_EXITING))
2448 if (current->task_works) {
2449 __set_current_state(TASK_RUNNING);
2457 static void io_iopoll_queue(struct list_head *again)
2459 struct io_kiocb *req;
2462 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2463 list_del(&req->inflight_entry);
2464 __io_complete_rw(req, -EAGAIN, 0, NULL);
2465 } while (!list_empty(again));
2469 * Find and free completed poll iocbs
2471 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2472 struct list_head *done)
2474 struct req_batch rb;
2475 struct io_kiocb *req;
2478 /* order with ->result store in io_complete_rw_iopoll() */
2481 io_init_req_batch(&rb);
2482 while (!list_empty(done)) {
2485 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2486 if (READ_ONCE(req->result) == -EAGAIN) {
2488 req->iopoll_completed = 0;
2489 list_move_tail(&req->inflight_entry, &again);
2492 list_del(&req->inflight_entry);
2494 if (req->flags & REQ_F_BUFFER_SELECTED)
2495 cflags = io_put_rw_kbuf(req);
2497 __io_cqring_fill_event(req, req->result, cflags);
2500 if (refcount_dec_and_test(&req->refs))
2501 io_req_free_batch(&rb, req);
2504 io_commit_cqring(ctx);
2505 io_cqring_ev_posted_iopoll(ctx);
2506 io_req_free_batch_finish(ctx, &rb);
2508 if (!list_empty(&again))
2509 io_iopoll_queue(&again);
2512 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2515 struct io_kiocb *req, *tmp;
2521 * Only spin for completions if we don't have multiple devices hanging
2522 * off our complete list, and we're under the requested amount.
2524 spin = !ctx->poll_multi_file && *nr_events < min;
2527 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2528 struct kiocb *kiocb = &req->rw.kiocb;
2531 * Move completed and retryable entries to our local lists.
2532 * If we find a request that requires polling, break out
2533 * and complete those lists first, if we have entries there.
2535 if (READ_ONCE(req->iopoll_completed)) {
2536 list_move_tail(&req->inflight_entry, &done);
2539 if (!list_empty(&done))
2542 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2546 /* iopoll may have completed current req */
2547 if (READ_ONCE(req->iopoll_completed))
2548 list_move_tail(&req->inflight_entry, &done);
2555 if (!list_empty(&done))
2556 io_iopoll_complete(ctx, nr_events, &done);
2562 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2563 * non-spinning poll check - we'll still enter the driver poll loop, but only
2564 * as a non-spinning completion check.
2566 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2569 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2572 ret = io_do_iopoll(ctx, nr_events, min);
2575 if (*nr_events >= min)
2583 * We can't just wait for polled events to come to us, we have to actively
2584 * find and complete them.
2586 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2588 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2591 mutex_lock(&ctx->uring_lock);
2592 while (!list_empty(&ctx->iopoll_list)) {
2593 unsigned int nr_events = 0;
2595 io_do_iopoll(ctx, &nr_events, 0);
2597 /* let it sleep and repeat later if can't complete a request */
2601 * Ensure we allow local-to-the-cpu processing to take place,
2602 * in this case we need to ensure that we reap all events.
2603 * Also let task_work, etc. to progress by releasing the mutex
2605 if (need_resched()) {
2606 mutex_unlock(&ctx->uring_lock);
2608 mutex_lock(&ctx->uring_lock);
2611 mutex_unlock(&ctx->uring_lock);
2614 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2616 unsigned int nr_events = 0;
2617 int iters = 0, ret = 0;
2620 * We disallow the app entering submit/complete with polling, but we
2621 * still need to lock the ring to prevent racing with polled issue
2622 * that got punted to a workqueue.
2624 mutex_lock(&ctx->uring_lock);
2627 * Don't enter poll loop if we already have events pending.
2628 * If we do, we can potentially be spinning for commands that
2629 * already triggered a CQE (eg in error).
2631 if (test_bit(0, &ctx->cq_check_overflow))
2632 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2633 if (io_cqring_events(ctx))
2637 * If a submit got punted to a workqueue, we can have the
2638 * application entering polling for a command before it gets
2639 * issued. That app will hold the uring_lock for the duration
2640 * of the poll right here, so we need to take a breather every
2641 * now and then to ensure that the issue has a chance to add
2642 * the poll to the issued list. Otherwise we can spin here
2643 * forever, while the workqueue is stuck trying to acquire the
2646 if (!(++iters & 7)) {
2647 mutex_unlock(&ctx->uring_lock);
2649 mutex_lock(&ctx->uring_lock);
2652 ret = io_iopoll_getevents(ctx, &nr_events, min);
2656 } while (min && !nr_events && !need_resched());
2658 mutex_unlock(&ctx->uring_lock);
2662 static void kiocb_end_write(struct io_kiocb *req)
2665 * Tell lockdep we inherited freeze protection from submission
2668 if (req->flags & REQ_F_ISREG) {
2669 struct inode *inode = file_inode(req->file);
2671 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2673 file_end_write(req->file);
2676 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2677 struct io_comp_state *cs)
2679 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2682 if (kiocb->ki_flags & IOCB_WRITE)
2683 kiocb_end_write(req);
2685 if (res != req->result)
2686 req_set_fail_links(req);
2687 if (req->flags & REQ_F_BUFFER_SELECTED)
2688 cflags = io_put_rw_kbuf(req);
2689 __io_req_complete(req, res, cflags, cs);
2693 static bool io_resubmit_prep(struct io_kiocb *req)
2695 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2696 ssize_t ret = -ECANCELED;
2697 struct iov_iter iter;
2700 /* already prepared */
2701 if (req->async_data)
2704 switch (req->opcode) {
2705 case IORING_OP_READV:
2706 case IORING_OP_READ_FIXED:
2707 case IORING_OP_READ:
2710 case IORING_OP_WRITEV:
2711 case IORING_OP_WRITE_FIXED:
2712 case IORING_OP_WRITE:
2716 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2721 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2724 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2732 static bool io_rw_reissue(struct io_kiocb *req, long res)
2738 if (res != -EAGAIN && res != -EOPNOTSUPP)
2740 mode = file_inode(req->file)->i_mode;
2741 if ((!S_ISBLK(mode) && !S_ISREG(mode)) || io_wq_current_is_worker())
2744 lockdep_assert_held(&req->ctx->uring_lock);
2746 ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2748 if (!ret && io_resubmit_prep(req)) {
2749 refcount_inc(&req->refs);
2750 io_queue_async_work(req);
2753 req_set_fail_links(req);
2758 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2759 struct io_comp_state *cs)
2761 if (!io_rw_reissue(req, res))
2762 io_complete_rw_common(&req->rw.kiocb, res, cs);
2765 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2767 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2769 __io_complete_rw(req, res, res2, NULL);
2772 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2774 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2776 if (kiocb->ki_flags & IOCB_WRITE)
2777 kiocb_end_write(req);
2779 if (res != -EAGAIN && res != req->result)
2780 req_set_fail_links(req);
2782 WRITE_ONCE(req->result, res);
2783 /* order with io_poll_complete() checking ->result */
2785 WRITE_ONCE(req->iopoll_completed, 1);
2789 * After the iocb has been issued, it's safe to be found on the poll list.
2790 * Adding the kiocb to the list AFTER submission ensures that we don't
2791 * find it from a io_iopoll_getevents() thread before the issuer is done
2792 * accessing the kiocb cookie.
2794 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2796 struct io_ring_ctx *ctx = req->ctx;
2799 * Track whether we have multiple files in our lists. This will impact
2800 * how we do polling eventually, not spinning if we're on potentially
2801 * different devices.
2803 if (list_empty(&ctx->iopoll_list)) {
2804 ctx->poll_multi_file = false;
2805 } else if (!ctx->poll_multi_file) {
2806 struct io_kiocb *list_req;
2808 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2810 if (list_req->file != req->file)
2811 ctx->poll_multi_file = true;
2815 * For fast devices, IO may have already completed. If it has, add
2816 * it to the front so we find it first.
2818 if (READ_ONCE(req->iopoll_completed))
2819 list_add(&req->inflight_entry, &ctx->iopoll_list);
2821 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2824 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2825 * task context or in io worker task context. If current task context is
2826 * sq thread, we don't need to check whether should wake up sq thread.
2828 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2829 wq_has_sleeper(&ctx->sq_data->wait))
2830 wake_up(&ctx->sq_data->wait);
2833 static inline void io_state_file_put(struct io_submit_state *state)
2835 if (state->file_refs) {
2836 fput_many(state->file, state->file_refs);
2837 state->file_refs = 0;
2842 * Get as many references to a file as we have IOs left in this submission,
2843 * assuming most submissions are for one file, or at least that each file
2844 * has more than one submission.
2846 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2851 if (state->file_refs) {
2852 if (state->fd == fd) {
2856 io_state_file_put(state);
2858 state->file = fget_many(fd, state->ios_left);
2859 if (unlikely(!state->file))
2863 state->file_refs = state->ios_left - 1;
2867 static bool io_bdev_nowait(struct block_device *bdev)
2869 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2873 * If we tracked the file through the SCM inflight mechanism, we could support
2874 * any file. For now, just ensure that anything potentially problematic is done
2877 static bool io_file_supports_async(struct file *file, int rw)
2879 umode_t mode = file_inode(file)->i_mode;
2881 if (S_ISBLK(mode)) {
2882 if (IS_ENABLED(CONFIG_BLOCK) &&
2883 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2887 if (S_ISCHR(mode) || S_ISSOCK(mode))
2889 if (S_ISREG(mode)) {
2890 if (IS_ENABLED(CONFIG_BLOCK) &&
2891 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2892 file->f_op != &io_uring_fops)
2897 /* any ->read/write should understand O_NONBLOCK */
2898 if (file->f_flags & O_NONBLOCK)
2901 if (!(file->f_mode & FMODE_NOWAIT))
2905 return file->f_op->read_iter != NULL;
2907 return file->f_op->write_iter != NULL;
2910 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2912 struct io_ring_ctx *ctx = req->ctx;
2913 struct kiocb *kiocb = &req->rw.kiocb;
2917 if (S_ISREG(file_inode(req->file)->i_mode))
2918 req->flags |= REQ_F_ISREG;
2920 kiocb->ki_pos = READ_ONCE(sqe->off);
2921 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2922 req->flags |= REQ_F_CUR_POS;
2923 kiocb->ki_pos = req->file->f_pos;
2925 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2926 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2927 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2931 ioprio = READ_ONCE(sqe->ioprio);
2933 ret = ioprio_check_cap(ioprio);
2937 kiocb->ki_ioprio = ioprio;
2939 kiocb->ki_ioprio = get_current_ioprio();
2941 /* don't allow async punt if RWF_NOWAIT was requested */
2942 if (kiocb->ki_flags & IOCB_NOWAIT)
2943 req->flags |= REQ_F_NOWAIT;
2945 if (ctx->flags & IORING_SETUP_IOPOLL) {
2946 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2947 !kiocb->ki_filp->f_op->iopoll)
2950 kiocb->ki_flags |= IOCB_HIPRI;
2951 kiocb->ki_complete = io_complete_rw_iopoll;
2952 req->iopoll_completed = 0;
2954 if (kiocb->ki_flags & IOCB_HIPRI)
2956 kiocb->ki_complete = io_complete_rw;
2959 req->rw.addr = READ_ONCE(sqe->addr);
2960 req->rw.len = READ_ONCE(sqe->len);
2961 req->buf_index = READ_ONCE(sqe->buf_index);
2965 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2971 case -ERESTARTNOINTR:
2972 case -ERESTARTNOHAND:
2973 case -ERESTART_RESTARTBLOCK:
2975 * We can't just restart the syscall, since previously
2976 * submitted sqes may already be in progress. Just fail this
2982 kiocb->ki_complete(kiocb, ret, 0);
2986 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2987 struct io_comp_state *cs)
2989 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2990 struct io_async_rw *io = req->async_data;
2992 /* add previously done IO, if any */
2993 if (io && io->bytes_done > 0) {
2995 ret = io->bytes_done;
2997 ret += io->bytes_done;
3000 if (req->flags & REQ_F_CUR_POS)
3001 req->file->f_pos = kiocb->ki_pos;
3002 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
3003 __io_complete_rw(req, ret, 0, cs);
3005 io_rw_done(kiocb, ret);
3008 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
3009 struct iov_iter *iter)
3011 struct io_ring_ctx *ctx = req->ctx;
3012 size_t len = req->rw.len;
3013 struct io_mapped_ubuf *imu;
3014 u16 index, buf_index = req->buf_index;
3018 if (unlikely(buf_index >= ctx->nr_user_bufs))
3020 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3021 imu = &ctx->user_bufs[index];
3022 buf_addr = req->rw.addr;
3025 if (buf_addr + len < buf_addr)
3027 /* not inside the mapped region */
3028 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
3032 * May not be a start of buffer, set size appropriately
3033 * and advance us to the beginning.
3035 offset = buf_addr - imu->ubuf;
3036 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3040 * Don't use iov_iter_advance() here, as it's really slow for
3041 * using the latter parts of a big fixed buffer - it iterates
3042 * over each segment manually. We can cheat a bit here, because
3045 * 1) it's a BVEC iter, we set it up
3046 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3047 * first and last bvec
3049 * So just find our index, and adjust the iterator afterwards.
3050 * If the offset is within the first bvec (or the whole first
3051 * bvec, just use iov_iter_advance(). This makes it easier
3052 * since we can just skip the first segment, which may not
3053 * be PAGE_SIZE aligned.
3055 const struct bio_vec *bvec = imu->bvec;
3057 if (offset <= bvec->bv_len) {
3058 iov_iter_advance(iter, offset);
3060 unsigned long seg_skip;
3062 /* skip first vec */
3063 offset -= bvec->bv_len;
3064 seg_skip = 1 + (offset >> PAGE_SHIFT);
3066 iter->bvec = bvec + seg_skip;
3067 iter->nr_segs -= seg_skip;
3068 iter->count -= bvec->bv_len + offset;
3069 iter->iov_offset = offset & ~PAGE_MASK;
3076 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3079 mutex_unlock(&ctx->uring_lock);
3082 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3085 * "Normal" inline submissions always hold the uring_lock, since we
3086 * grab it from the system call. Same is true for the SQPOLL offload.
3087 * The only exception is when we've detached the request and issue it
3088 * from an async worker thread, grab the lock for that case.
3091 mutex_lock(&ctx->uring_lock);
3094 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3095 int bgid, struct io_buffer *kbuf,
3098 struct io_buffer *head;
3100 if (req->flags & REQ_F_BUFFER_SELECTED)
3103 io_ring_submit_lock(req->ctx, needs_lock);
3105 lockdep_assert_held(&req->ctx->uring_lock);
3107 head = idr_find(&req->ctx->io_buffer_idr, bgid);
3109 if (!list_empty(&head->list)) {
3110 kbuf = list_last_entry(&head->list, struct io_buffer,
3112 list_del(&kbuf->list);
3115 idr_remove(&req->ctx->io_buffer_idr, bgid);
3117 if (*len > kbuf->len)
3120 kbuf = ERR_PTR(-ENOBUFS);
3123 io_ring_submit_unlock(req->ctx, needs_lock);
3128 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3131 struct io_buffer *kbuf;
3134 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3135 bgid = req->buf_index;
3136 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3139 req->rw.addr = (u64) (unsigned long) kbuf;
3140 req->flags |= REQ_F_BUFFER_SELECTED;
3141 return u64_to_user_ptr(kbuf->addr);
3144 #ifdef CONFIG_COMPAT
3145 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3148 struct compat_iovec __user *uiov;
3149 compat_ssize_t clen;
3153 uiov = u64_to_user_ptr(req->rw.addr);
3154 if (!access_ok(uiov, sizeof(*uiov)))
3156 if (__get_user(clen, &uiov->iov_len))
3162 buf = io_rw_buffer_select(req, &len, needs_lock);
3164 return PTR_ERR(buf);
3165 iov[0].iov_base = buf;
3166 iov[0].iov_len = (compat_size_t) len;
3171 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3174 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3178 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3181 len = iov[0].iov_len;
3184 buf = io_rw_buffer_select(req, &len, needs_lock);
3186 return PTR_ERR(buf);
3187 iov[0].iov_base = buf;
3188 iov[0].iov_len = len;
3192 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3195 if (req->flags & REQ_F_BUFFER_SELECTED) {
3196 struct io_buffer *kbuf;
3198 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3199 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3200 iov[0].iov_len = kbuf->len;
3203 if (req->rw.len != 1)
3206 #ifdef CONFIG_COMPAT
3207 if (req->ctx->compat)
3208 return io_compat_import(req, iov, needs_lock);
3211 return __io_iov_buffer_select(req, iov, needs_lock);
3214 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
3215 struct iovec **iovec, struct iov_iter *iter,
3218 void __user *buf = u64_to_user_ptr(req->rw.addr);
3219 size_t sqe_len = req->rw.len;
3223 opcode = req->opcode;
3224 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3226 return io_import_fixed(req, rw, iter);
3229 /* buffer index only valid with fixed read/write, or buffer select */
3230 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3233 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3234 if (req->flags & REQ_F_BUFFER_SELECT) {
3235 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3237 return PTR_ERR(buf);
3238 req->rw.len = sqe_len;
3241 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3246 if (req->flags & REQ_F_BUFFER_SELECT) {
3247 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3249 ret = (*iovec)->iov_len;
3250 iov_iter_init(iter, rw, *iovec, 1, ret);
3256 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3260 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3262 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3266 * For files that don't have ->read_iter() and ->write_iter(), handle them
3267 * by looping over ->read() or ->write() manually.
3269 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3271 struct kiocb *kiocb = &req->rw.kiocb;
3272 struct file *file = req->file;
3276 * Don't support polled IO through this interface, and we can't
3277 * support non-blocking either. For the latter, this just causes
3278 * the kiocb to be handled from an async context.
3280 if (kiocb->ki_flags & IOCB_HIPRI)
3282 if (kiocb->ki_flags & IOCB_NOWAIT)
3285 while (iov_iter_count(iter)) {
3289 if (!iov_iter_is_bvec(iter)) {
3290 iovec = iov_iter_iovec(iter);
3292 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3293 iovec.iov_len = req->rw.len;
3297 nr = file->f_op->read(file, iovec.iov_base,
3298 iovec.iov_len, io_kiocb_ppos(kiocb));
3300 nr = file->f_op->write(file, iovec.iov_base,
3301 iovec.iov_len, io_kiocb_ppos(kiocb));
3310 if (nr != iovec.iov_len)
3314 iov_iter_advance(iter, nr);
3320 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3321 const struct iovec *fast_iov, struct iov_iter *iter)
3323 struct io_async_rw *rw = req->async_data;
3325 memcpy(&rw->iter, iter, sizeof(*iter));
3326 rw->free_iovec = iovec;
3328 /* can only be fixed buffers, no need to do anything */
3329 if (iov_iter_is_bvec(iter))
3332 unsigned iov_off = 0;
3334 rw->iter.iov = rw->fast_iov;
3335 if (iter->iov != fast_iov) {
3336 iov_off = iter->iov - fast_iov;
3337 rw->iter.iov += iov_off;
3339 if (rw->fast_iov != fast_iov)
3340 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3341 sizeof(struct iovec) * iter->nr_segs);
3343 req->flags |= REQ_F_NEED_CLEANUP;
3347 static inline int __io_alloc_async_data(struct io_kiocb *req)
3349 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3350 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3351 return req->async_data == NULL;
3354 static int io_alloc_async_data(struct io_kiocb *req)
3356 if (!io_op_defs[req->opcode].needs_async_data)
3359 return __io_alloc_async_data(req);
3362 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3363 const struct iovec *fast_iov,
3364 struct iov_iter *iter, bool force)
3366 if (!force && !io_op_defs[req->opcode].needs_async_data)
3368 if (!req->async_data) {
3369 if (__io_alloc_async_data(req))
3372 io_req_map_rw(req, iovec, fast_iov, iter);
3377 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3379 struct io_async_rw *iorw = req->async_data;
3380 struct iovec *iov = iorw->fast_iov;
3383 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3384 if (unlikely(ret < 0))
3387 iorw->bytes_done = 0;
3388 iorw->free_iovec = iov;
3390 req->flags |= REQ_F_NEED_CLEANUP;
3394 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3398 ret = io_prep_rw(req, sqe);
3402 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3405 /* either don't need iovec imported or already have it */
3406 if (!req->async_data)
3408 return io_rw_prep_async(req, READ);
3412 * This is our waitqueue callback handler, registered through lock_page_async()
3413 * when we initially tried to do the IO with the iocb armed our waitqueue.
3414 * This gets called when the page is unlocked, and we generally expect that to
3415 * happen when the page IO is completed and the page is now uptodate. This will
3416 * queue a task_work based retry of the operation, attempting to copy the data
3417 * again. If the latter fails because the page was NOT uptodate, then we will
3418 * do a thread based blocking retry of the operation. That's the unexpected
3421 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3422 int sync, void *arg)
3424 struct wait_page_queue *wpq;
3425 struct io_kiocb *req = wait->private;
3426 struct wait_page_key *key = arg;
3429 wpq = container_of(wait, struct wait_page_queue, wait);
3431 if (!wake_page_match(wpq, key))
3434 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3435 list_del_init(&wait->entry);
3437 init_task_work(&req->task_work, io_req_task_submit);
3438 percpu_ref_get(&req->ctx->refs);
3440 /* submit ref gets dropped, acquire a new one */
3441 refcount_inc(&req->refs);
3442 ret = io_req_task_work_add(req);
3444 io_req_task_work_add_fallback(req, io_req_task_cancel);
3449 * This controls whether a given IO request should be armed for async page
3450 * based retry. If we return false here, the request is handed to the async
3451 * worker threads for retry. If we're doing buffered reads on a regular file,
3452 * we prepare a private wait_page_queue entry and retry the operation. This
3453 * will either succeed because the page is now uptodate and unlocked, or it
3454 * will register a callback when the page is unlocked at IO completion. Through
3455 * that callback, io_uring uses task_work to setup a retry of the operation.
3456 * That retry will attempt the buffered read again. The retry will generally
3457 * succeed, or in rare cases where it fails, we then fall back to using the
3458 * async worker threads for a blocking retry.
3460 static bool io_rw_should_retry(struct io_kiocb *req)
3462 struct io_async_rw *rw = req->async_data;
3463 struct wait_page_queue *wait = &rw->wpq;
3464 struct kiocb *kiocb = &req->rw.kiocb;
3466 /* never retry for NOWAIT, we just complete with -EAGAIN */
3467 if (req->flags & REQ_F_NOWAIT)
3470 /* Only for buffered IO */
3471 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3475 * just use poll if we can, and don't attempt if the fs doesn't
3476 * support callback based unlocks
3478 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3481 wait->wait.func = io_async_buf_func;
3482 wait->wait.private = req;
3483 wait->wait.flags = 0;
3484 INIT_LIST_HEAD(&wait->wait.entry);
3485 kiocb->ki_flags |= IOCB_WAITQ;
3486 kiocb->ki_flags &= ~IOCB_NOWAIT;
3487 kiocb->ki_waitq = wait;
3491 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3493 if (req->file->f_op->read_iter)
3494 return call_read_iter(req->file, &req->rw.kiocb, iter);
3495 else if (req->file->f_op->read)
3496 return loop_rw_iter(READ, req, iter);
3501 static int io_read(struct io_kiocb *req, bool force_nonblock,
3502 struct io_comp_state *cs)
3504 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3505 struct kiocb *kiocb = &req->rw.kiocb;
3506 struct iov_iter __iter, *iter = &__iter;
3507 struct io_async_rw *rw = req->async_data;
3508 ssize_t io_size, ret, ret2;
3515 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3519 io_size = iov_iter_count(iter);
3520 req->result = io_size;
3523 /* Ensure we clear previously set non-block flag */
3524 if (!force_nonblock)
3525 kiocb->ki_flags &= ~IOCB_NOWAIT;
3527 kiocb->ki_flags |= IOCB_NOWAIT;
3529 /* If the file doesn't support async, just async punt */
3530 no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3534 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3538 ret = io_iter_do_read(req, iter);
3540 if (ret == -EIOCBQUEUED) {
3543 } else if (ret == -EAGAIN) {
3544 /* IOPOLL retry should happen for io-wq threads */
3545 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3547 /* no retry on NONBLOCK marked file */
3548 if (req->file->f_flags & O_NONBLOCK)
3550 /* some cases will consume bytes even on error returns */
3551 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3554 } else if (ret <= 0) {
3555 /* make sure -ERESTARTSYS -> -EINTR is done */
3559 /* read it all, or we did blocking attempt. no retry. */
3560 if (!iov_iter_count(iter) || !force_nonblock ||
3561 (req->file->f_flags & O_NONBLOCK) || !(req->flags & REQ_F_ISREG))
3566 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3573 rw = req->async_data;
3574 /* it's copied and will be cleaned with ->io */
3576 /* now use our persistent iterator, if we aren't already */
3579 rw->bytes_done += ret;
3580 /* if we can retry, do so with the callbacks armed */
3581 if (!io_rw_should_retry(req)) {
3582 kiocb->ki_flags &= ~IOCB_WAITQ;
3587 * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3588 * get -EIOCBQUEUED, then we'll get a notification when the desired
3589 * page gets unlocked. We can also get a partial read here, and if we
3590 * do, then just retry at the new offset.
3592 ret = io_iter_do_read(req, iter);
3593 if (ret == -EIOCBQUEUED) {
3596 } else if (ret > 0 && ret < io_size) {
3597 /* we got some bytes, but not all. retry. */
3601 kiocb_done(kiocb, ret, cs);
3604 /* it's reportedly faster than delegating the null check to kfree() */
3610 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3614 ret = io_prep_rw(req, sqe);
3618 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3621 /* either don't need iovec imported or already have it */
3622 if (!req->async_data)
3624 return io_rw_prep_async(req, WRITE);
3627 static int io_write(struct io_kiocb *req, bool force_nonblock,
3628 struct io_comp_state *cs)
3630 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3631 struct kiocb *kiocb = &req->rw.kiocb;
3632 struct iov_iter __iter, *iter = &__iter;
3633 struct io_async_rw *rw = req->async_data;
3634 ssize_t ret, ret2, io_size;
3640 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3644 io_size = iov_iter_count(iter);
3645 req->result = io_size;
3647 /* Ensure we clear previously set non-block flag */
3648 if (!force_nonblock)
3649 kiocb->ki_flags &= ~IOCB_NOWAIT;
3651 kiocb->ki_flags |= IOCB_NOWAIT;
3653 /* If the file doesn't support async, just async punt */
3654 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3657 /* file path doesn't support NOWAIT for non-direct_IO */
3658 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3659 (req->flags & REQ_F_ISREG))
3662 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3667 * Open-code file_start_write here to grab freeze protection,
3668 * which will be released by another thread in
3669 * io_complete_rw(). Fool lockdep by telling it the lock got
3670 * released so that it doesn't complain about the held lock when
3671 * we return to userspace.
3673 if (req->flags & REQ_F_ISREG) {
3674 sb_start_write(file_inode(req->file)->i_sb);
3675 __sb_writers_release(file_inode(req->file)->i_sb,
3678 kiocb->ki_flags |= IOCB_WRITE;
3680 if (req->file->f_op->write_iter)
3681 ret2 = call_write_iter(req->file, kiocb, iter);
3682 else if (req->file->f_op->write)
3683 ret2 = loop_rw_iter(WRITE, req, iter);
3688 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3689 * retry them without IOCB_NOWAIT.
3691 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3693 /* no retry on NONBLOCK marked file */
3694 if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3696 if (!force_nonblock || ret2 != -EAGAIN) {
3697 /* IOPOLL retry should happen for io-wq threads */
3698 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3701 kiocb_done(kiocb, ret2, cs);
3704 /* some cases will consume bytes even on error returns */
3705 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3706 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3711 /* it's reportedly faster than delegating the null check to kfree() */
3717 static int io_renameat_prep(struct io_kiocb *req,
3718 const struct io_uring_sqe *sqe)
3720 struct io_rename *ren = &req->rename;
3721 const char __user *oldf, *newf;
3723 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3726 ren->old_dfd = READ_ONCE(sqe->fd);
3727 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3728 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3729 ren->new_dfd = READ_ONCE(sqe->len);
3730 ren->flags = READ_ONCE(sqe->rename_flags);
3732 ren->oldpath = getname(oldf);
3733 if (IS_ERR(ren->oldpath))
3734 return PTR_ERR(ren->oldpath);
3736 ren->newpath = getname(newf);
3737 if (IS_ERR(ren->newpath)) {
3738 putname(ren->oldpath);
3739 return PTR_ERR(ren->newpath);
3742 req->flags |= REQ_F_NEED_CLEANUP;
3746 static int io_renameat(struct io_kiocb *req, bool force_nonblock)
3748 struct io_rename *ren = &req->rename;
3754 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3755 ren->newpath, ren->flags);
3757 req->flags &= ~REQ_F_NEED_CLEANUP;
3759 req_set_fail_links(req);
3760 io_req_complete(req, ret);
3764 static int io_unlinkat_prep(struct io_kiocb *req,
3765 const struct io_uring_sqe *sqe)
3767 struct io_unlink *un = &req->unlink;
3768 const char __user *fname;
3770 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3773 un->dfd = READ_ONCE(sqe->fd);
3775 un->flags = READ_ONCE(sqe->unlink_flags);
3776 if (un->flags & ~AT_REMOVEDIR)
3779 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3780 un->filename = getname(fname);
3781 if (IS_ERR(un->filename))
3782 return PTR_ERR(un->filename);
3784 req->flags |= REQ_F_NEED_CLEANUP;
3788 static int io_unlinkat(struct io_kiocb *req, bool force_nonblock)
3790 struct io_unlink *un = &req->unlink;
3796 if (un->flags & AT_REMOVEDIR)
3797 ret = do_rmdir(un->dfd, un->filename);
3799 ret = do_unlinkat(un->dfd, un->filename);
3801 req->flags &= ~REQ_F_NEED_CLEANUP;
3803 req_set_fail_links(req);
3804 io_req_complete(req, ret);
3808 static int io_shutdown_prep(struct io_kiocb *req,
3809 const struct io_uring_sqe *sqe)
3811 #if defined(CONFIG_NET)
3812 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3814 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3818 req->shutdown.how = READ_ONCE(sqe->len);
3825 static int io_shutdown(struct io_kiocb *req, bool force_nonblock)
3827 #if defined(CONFIG_NET)
3828 struct socket *sock;
3834 sock = sock_from_file(req->file);
3835 if (unlikely(!sock))
3838 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3840 req_set_fail_links(req);
3841 io_req_complete(req, ret);
3848 static int __io_splice_prep(struct io_kiocb *req,
3849 const struct io_uring_sqe *sqe)
3851 struct io_splice* sp = &req->splice;
3852 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3854 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3858 sp->len = READ_ONCE(sqe->len);
3859 sp->flags = READ_ONCE(sqe->splice_flags);
3861 if (unlikely(sp->flags & ~valid_flags))
3864 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3865 (sp->flags & SPLICE_F_FD_IN_FIXED));
3868 req->flags |= REQ_F_NEED_CLEANUP;
3870 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3872 * Splice operation will be punted aync, and here need to
3873 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3875 io_req_init_async(req);
3876 req->work.flags |= IO_WQ_WORK_UNBOUND;
3882 static int io_tee_prep(struct io_kiocb *req,
3883 const struct io_uring_sqe *sqe)
3885 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3887 return __io_splice_prep(req, sqe);
3890 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3892 struct io_splice *sp = &req->splice;
3893 struct file *in = sp->file_in;
3894 struct file *out = sp->file_out;
3895 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3901 ret = do_tee(in, out, sp->len, flags);
3903 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3904 req->flags &= ~REQ_F_NEED_CLEANUP;
3907 req_set_fail_links(req);
3908 io_req_complete(req, ret);
3912 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3914 struct io_splice* sp = &req->splice;
3916 sp->off_in = READ_ONCE(sqe->splice_off_in);
3917 sp->off_out = READ_ONCE(sqe->off);
3918 return __io_splice_prep(req, sqe);
3921 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3923 struct io_splice *sp = &req->splice;
3924 struct file *in = sp->file_in;
3925 struct file *out = sp->file_out;
3926 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3927 loff_t *poff_in, *poff_out;
3933 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3934 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3937 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3939 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3940 req->flags &= ~REQ_F_NEED_CLEANUP;
3943 req_set_fail_links(req);
3944 io_req_complete(req, ret);
3949 * IORING_OP_NOP just posts a completion event, nothing else.
3951 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3953 struct io_ring_ctx *ctx = req->ctx;
3955 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3958 __io_req_complete(req, 0, 0, cs);
3962 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3964 struct io_ring_ctx *ctx = req->ctx;
3969 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3971 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3974 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3975 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3978 req->sync.off = READ_ONCE(sqe->off);
3979 req->sync.len = READ_ONCE(sqe->len);
3983 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3985 loff_t end = req->sync.off + req->sync.len;
3988 /* fsync always requires a blocking context */
3992 ret = vfs_fsync_range(req->file, req->sync.off,
3993 end > 0 ? end : LLONG_MAX,
3994 req->sync.flags & IORING_FSYNC_DATASYNC);
3996 req_set_fail_links(req);
3997 io_req_complete(req, ret);
4001 static int io_fallocate_prep(struct io_kiocb *req,
4002 const struct io_uring_sqe *sqe)
4004 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
4006 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4009 req->sync.off = READ_ONCE(sqe->off);
4010 req->sync.len = READ_ONCE(sqe->addr);
4011 req->sync.mode = READ_ONCE(sqe->len);
4015 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
4019 /* fallocate always requiring blocking context */
4022 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4025 req_set_fail_links(req);
4026 io_req_complete(req, ret);
4030 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4032 const char __user *fname;
4035 if (unlikely(sqe->ioprio || sqe->buf_index))
4037 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4040 /* open.how should be already initialised */
4041 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4042 req->open.how.flags |= O_LARGEFILE;
4044 req->open.dfd = READ_ONCE(sqe->fd);
4045 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4046 req->open.filename = getname(fname);
4047 if (IS_ERR(req->open.filename)) {
4048 ret = PTR_ERR(req->open.filename);
4049 req->open.filename = NULL;
4052 req->open.nofile = rlimit(RLIMIT_NOFILE);
4053 req->flags |= REQ_F_NEED_CLEANUP;
4057 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4061 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4063 mode = READ_ONCE(sqe->len);
4064 flags = READ_ONCE(sqe->open_flags);
4065 req->open.how = build_open_how(flags, mode);
4066 return __io_openat_prep(req, sqe);
4069 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4071 struct open_how __user *how;
4075 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4077 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4078 len = READ_ONCE(sqe->len);
4079 if (len < OPEN_HOW_SIZE_VER0)
4082 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4087 return __io_openat_prep(req, sqe);
4090 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
4092 struct open_flags op;
4095 bool resolve_nonblock;
4098 ret = build_open_flags(&req->open.how, &op);
4101 nonblock_set = op.open_flag & O_NONBLOCK;
4102 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4103 if (force_nonblock) {
4105 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4106 * it'll always -EAGAIN
4108 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4110 op.lookup_flags |= LOOKUP_CACHED;
4111 op.open_flag |= O_NONBLOCK;
4114 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4118 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4119 /* only retry if RESOLVE_CACHED wasn't already set by application */
4120 if ((!resolve_nonblock && force_nonblock) && file == ERR_PTR(-EAGAIN)) {
4122 * We could hang on to this 'fd', but seems like marginal
4123 * gain for something that is now known to be a slower path.
4124 * So just put it, and we'll get a new one when we retry.
4132 ret = PTR_ERR(file);
4134 if (force_nonblock && !nonblock_set)
4135 file->f_flags &= ~O_NONBLOCK;
4136 fsnotify_open(file);
4137 fd_install(ret, file);
4140 putname(req->open.filename);
4141 req->flags &= ~REQ_F_NEED_CLEANUP;
4143 req_set_fail_links(req);
4144 io_req_complete(req, ret);
4148 static int io_openat(struct io_kiocb *req, bool force_nonblock)
4150 return io_openat2(req, force_nonblock);
4153 static int io_remove_buffers_prep(struct io_kiocb *req,
4154 const struct io_uring_sqe *sqe)
4156 struct io_provide_buf *p = &req->pbuf;
4159 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4162 tmp = READ_ONCE(sqe->fd);
4163 if (!tmp || tmp > USHRT_MAX)
4166 memset(p, 0, sizeof(*p));
4168 p->bgid = READ_ONCE(sqe->buf_group);
4172 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4173 int bgid, unsigned nbufs)
4177 /* shouldn't happen */
4181 /* the head kbuf is the list itself */
4182 while (!list_empty(&buf->list)) {
4183 struct io_buffer *nxt;
4185 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4186 list_del(&nxt->list);
4193 idr_remove(&ctx->io_buffer_idr, bgid);
4198 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
4199 struct io_comp_state *cs)
4201 struct io_provide_buf *p = &req->pbuf;
4202 struct io_ring_ctx *ctx = req->ctx;
4203 struct io_buffer *head;
4206 io_ring_submit_lock(ctx, !force_nonblock);
4208 lockdep_assert_held(&ctx->uring_lock);
4211 head = idr_find(&ctx->io_buffer_idr, p->bgid);
4213 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4215 req_set_fail_links(req);
4217 /* need to hold the lock to complete IOPOLL requests */
4218 if (ctx->flags & IORING_SETUP_IOPOLL) {
4219 __io_req_complete(req, ret, 0, cs);
4220 io_ring_submit_unlock(ctx, !force_nonblock);
4222 io_ring_submit_unlock(ctx, !force_nonblock);
4223 __io_req_complete(req, ret, 0, cs);
4228 static int io_provide_buffers_prep(struct io_kiocb *req,
4229 const struct io_uring_sqe *sqe)
4231 struct io_provide_buf *p = &req->pbuf;
4234 if (sqe->ioprio || sqe->rw_flags)
4237 tmp = READ_ONCE(sqe->fd);
4238 if (!tmp || tmp > USHRT_MAX)
4241 p->addr = READ_ONCE(sqe->addr);
4242 p->len = READ_ONCE(sqe->len);
4244 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4247 p->bgid = READ_ONCE(sqe->buf_group);
4248 tmp = READ_ONCE(sqe->off);
4249 if (tmp > USHRT_MAX)
4255 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4257 struct io_buffer *buf;
4258 u64 addr = pbuf->addr;
4259 int i, bid = pbuf->bid;
4261 for (i = 0; i < pbuf->nbufs; i++) {
4262 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4267 buf->len = pbuf->len;
4272 INIT_LIST_HEAD(&buf->list);
4275 list_add_tail(&buf->list, &(*head)->list);
4279 return i ? i : -ENOMEM;
4282 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
4283 struct io_comp_state *cs)
4285 struct io_provide_buf *p = &req->pbuf;
4286 struct io_ring_ctx *ctx = req->ctx;
4287 struct io_buffer *head, *list;
4290 io_ring_submit_lock(ctx, !force_nonblock);
4292 lockdep_assert_held(&ctx->uring_lock);
4294 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4296 ret = io_add_buffers(p, &head);
4301 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4304 __io_remove_buffers(ctx, head, p->bgid, -1U);
4310 req_set_fail_links(req);
4312 /* need to hold the lock to complete IOPOLL requests */
4313 if (ctx->flags & IORING_SETUP_IOPOLL) {
4314 __io_req_complete(req, ret, 0, cs);
4315 io_ring_submit_unlock(ctx, !force_nonblock);
4317 io_ring_submit_unlock(ctx, !force_nonblock);
4318 __io_req_complete(req, ret, 0, cs);
4323 static int io_epoll_ctl_prep(struct io_kiocb *req,
4324 const struct io_uring_sqe *sqe)
4326 #if defined(CONFIG_EPOLL)
4327 if (sqe->ioprio || sqe->buf_index)
4329 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4332 req->epoll.epfd = READ_ONCE(sqe->fd);
4333 req->epoll.op = READ_ONCE(sqe->len);
4334 req->epoll.fd = READ_ONCE(sqe->off);
4336 if (ep_op_has_event(req->epoll.op)) {
4337 struct epoll_event __user *ev;
4339 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4340 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4350 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
4351 struct io_comp_state *cs)
4353 #if defined(CONFIG_EPOLL)
4354 struct io_epoll *ie = &req->epoll;
4357 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4358 if (force_nonblock && ret == -EAGAIN)
4362 req_set_fail_links(req);
4363 __io_req_complete(req, ret, 0, cs);
4370 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4372 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4373 if (sqe->ioprio || sqe->buf_index || sqe->off)
4375 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4378 req->madvise.addr = READ_ONCE(sqe->addr);
4379 req->madvise.len = READ_ONCE(sqe->len);
4380 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4387 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
4389 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4390 struct io_madvise *ma = &req->madvise;
4396 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4398 req_set_fail_links(req);
4399 io_req_complete(req, ret);
4406 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4408 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4410 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4413 req->fadvise.offset = READ_ONCE(sqe->off);
4414 req->fadvise.len = READ_ONCE(sqe->len);
4415 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4419 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
4421 struct io_fadvise *fa = &req->fadvise;
4424 if (force_nonblock) {
4425 switch (fa->advice) {
4426 case POSIX_FADV_NORMAL:
4427 case POSIX_FADV_RANDOM:
4428 case POSIX_FADV_SEQUENTIAL:
4435 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4437 req_set_fail_links(req);
4438 io_req_complete(req, ret);
4442 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4444 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4446 if (sqe->ioprio || sqe->buf_index)
4448 if (req->flags & REQ_F_FIXED_FILE)
4451 req->statx.dfd = READ_ONCE(sqe->fd);
4452 req->statx.mask = READ_ONCE(sqe->len);
4453 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4454 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4455 req->statx.flags = READ_ONCE(sqe->statx_flags);
4460 static int io_statx(struct io_kiocb *req, bool force_nonblock)
4462 struct io_statx *ctx = &req->statx;
4465 if (force_nonblock) {
4466 /* only need file table for an actual valid fd */
4467 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4468 req->flags |= REQ_F_NO_FILE_TABLE;
4472 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4476 req_set_fail_links(req);
4477 io_req_complete(req, ret);
4481 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4483 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4485 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4486 sqe->rw_flags || sqe->buf_index)
4488 if (req->flags & REQ_F_FIXED_FILE)
4491 req->close.fd = READ_ONCE(sqe->fd);
4495 static int io_close(struct io_kiocb *req, bool force_nonblock,
4496 struct io_comp_state *cs)
4498 struct files_struct *files = current->files;
4499 struct io_close *close = &req->close;
4500 struct fdtable *fdt;
4506 spin_lock(&files->file_lock);
4507 fdt = files_fdtable(files);
4508 if (close->fd >= fdt->max_fds) {
4509 spin_unlock(&files->file_lock);
4512 file = fdt->fd[close->fd];
4514 spin_unlock(&files->file_lock);
4518 if (file->f_op == &io_uring_fops) {
4519 spin_unlock(&files->file_lock);
4524 /* if the file has a flush method, be safe and punt to async */
4525 if (file->f_op->flush && force_nonblock) {
4526 spin_unlock(&files->file_lock);
4530 ret = __close_fd_get_file(close->fd, &file);
4531 spin_unlock(&files->file_lock);
4538 /* No ->flush() or already async, safely close from here */
4539 ret = filp_close(file, current->files);
4542 req_set_fail_links(req);
4545 __io_req_complete(req, ret, 0, cs);
4549 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4551 struct io_ring_ctx *ctx = req->ctx;
4556 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4558 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4561 req->sync.off = READ_ONCE(sqe->off);
4562 req->sync.len = READ_ONCE(sqe->len);
4563 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4567 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
4571 /* sync_file_range always requires a blocking context */
4575 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4578 req_set_fail_links(req);
4579 io_req_complete(req, ret);
4583 #if defined(CONFIG_NET)
4584 static int io_setup_async_msg(struct io_kiocb *req,
4585 struct io_async_msghdr *kmsg)
4587 struct io_async_msghdr *async_msg = req->async_data;
4591 if (io_alloc_async_data(req)) {
4592 if (kmsg->iov != kmsg->fast_iov)
4596 async_msg = req->async_data;
4597 req->flags |= REQ_F_NEED_CLEANUP;
4598 memcpy(async_msg, kmsg, sizeof(*kmsg));
4602 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4603 struct io_async_msghdr *iomsg)
4605 iomsg->iov = iomsg->fast_iov;
4606 iomsg->msg.msg_name = &iomsg->addr;
4607 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4608 req->sr_msg.msg_flags, &iomsg->iov);
4611 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4613 struct io_async_msghdr *async_msg = req->async_data;
4614 struct io_sr_msg *sr = &req->sr_msg;
4617 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4620 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4621 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4622 sr->len = READ_ONCE(sqe->len);
4624 #ifdef CONFIG_COMPAT
4625 if (req->ctx->compat)
4626 sr->msg_flags |= MSG_CMSG_COMPAT;
4629 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4631 ret = io_sendmsg_copy_hdr(req, async_msg);
4633 req->flags |= REQ_F_NEED_CLEANUP;
4637 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4638 struct io_comp_state *cs)
4640 struct io_async_msghdr iomsg, *kmsg;
4641 struct socket *sock;
4645 sock = sock_from_file(req->file);
4646 if (unlikely(!sock))
4649 if (req->async_data) {
4650 kmsg = req->async_data;
4651 kmsg->msg.msg_name = &kmsg->addr;
4652 /* if iov is set, it's allocated already */
4654 kmsg->iov = kmsg->fast_iov;
4655 kmsg->msg.msg_iter.iov = kmsg->iov;
4657 ret = io_sendmsg_copy_hdr(req, &iomsg);
4663 flags = req->sr_msg.msg_flags;
4664 if (flags & MSG_DONTWAIT)
4665 req->flags |= REQ_F_NOWAIT;
4666 else if (force_nonblock)
4667 flags |= MSG_DONTWAIT;
4669 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4670 if (force_nonblock && ret == -EAGAIN)
4671 return io_setup_async_msg(req, kmsg);
4672 if (ret == -ERESTARTSYS)
4675 if (kmsg->iov != kmsg->fast_iov)
4677 req->flags &= ~REQ_F_NEED_CLEANUP;
4679 req_set_fail_links(req);
4680 __io_req_complete(req, ret, 0, cs);
4684 static int io_send(struct io_kiocb *req, bool force_nonblock,
4685 struct io_comp_state *cs)
4687 struct io_sr_msg *sr = &req->sr_msg;
4690 struct socket *sock;
4694 sock = sock_from_file(req->file);
4695 if (unlikely(!sock))
4698 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4702 msg.msg_name = NULL;
4703 msg.msg_control = NULL;
4704 msg.msg_controllen = 0;
4705 msg.msg_namelen = 0;
4707 flags = req->sr_msg.msg_flags;
4708 if (flags & MSG_DONTWAIT)
4709 req->flags |= REQ_F_NOWAIT;
4710 else if (force_nonblock)
4711 flags |= MSG_DONTWAIT;
4713 msg.msg_flags = flags;
4714 ret = sock_sendmsg(sock, &msg);
4715 if (force_nonblock && ret == -EAGAIN)
4717 if (ret == -ERESTARTSYS)
4721 req_set_fail_links(req);
4722 __io_req_complete(req, ret, 0, cs);
4726 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4727 struct io_async_msghdr *iomsg)
4729 struct io_sr_msg *sr = &req->sr_msg;
4730 struct iovec __user *uiov;
4734 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4735 &iomsg->uaddr, &uiov, &iov_len);
4739 if (req->flags & REQ_F_BUFFER_SELECT) {
4742 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4744 sr->len = iomsg->iov[0].iov_len;
4745 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4749 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4750 &iomsg->iov, &iomsg->msg.msg_iter,
4759 #ifdef CONFIG_COMPAT
4760 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4761 struct io_async_msghdr *iomsg)
4763 struct compat_msghdr __user *msg_compat;
4764 struct io_sr_msg *sr = &req->sr_msg;
4765 struct compat_iovec __user *uiov;
4770 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4771 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4776 uiov = compat_ptr(ptr);
4777 if (req->flags & REQ_F_BUFFER_SELECT) {
4778 compat_ssize_t clen;
4782 if (!access_ok(uiov, sizeof(*uiov)))
4784 if (__get_user(clen, &uiov->iov_len))
4789 iomsg->iov[0].iov_len = clen;
4792 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4793 UIO_FASTIOV, &iomsg->iov,
4794 &iomsg->msg.msg_iter, true);
4803 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4804 struct io_async_msghdr *iomsg)
4806 iomsg->msg.msg_name = &iomsg->addr;
4807 iomsg->iov = iomsg->fast_iov;
4809 #ifdef CONFIG_COMPAT
4810 if (req->ctx->compat)
4811 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4814 return __io_recvmsg_copy_hdr(req, iomsg);
4817 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4820 struct io_sr_msg *sr = &req->sr_msg;
4821 struct io_buffer *kbuf;
4823 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4828 req->flags |= REQ_F_BUFFER_SELECTED;
4832 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4834 return io_put_kbuf(req, req->sr_msg.kbuf);
4837 static int io_recvmsg_prep(struct io_kiocb *req,
4838 const struct io_uring_sqe *sqe)
4840 struct io_async_msghdr *async_msg = req->async_data;
4841 struct io_sr_msg *sr = &req->sr_msg;
4844 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4847 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4848 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4849 sr->len = READ_ONCE(sqe->len);
4850 sr->bgid = READ_ONCE(sqe->buf_group);
4852 #ifdef CONFIG_COMPAT
4853 if (req->ctx->compat)
4854 sr->msg_flags |= MSG_CMSG_COMPAT;
4857 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4859 ret = io_recvmsg_copy_hdr(req, async_msg);
4861 req->flags |= REQ_F_NEED_CLEANUP;
4865 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4866 struct io_comp_state *cs)
4868 struct io_async_msghdr iomsg, *kmsg;
4869 struct socket *sock;
4870 struct io_buffer *kbuf;
4872 int ret, cflags = 0;
4874 sock = sock_from_file(req->file);
4875 if (unlikely(!sock))
4878 if (req->async_data) {
4879 kmsg = req->async_data;
4880 kmsg->msg.msg_name = &kmsg->addr;
4881 /* if iov is set, it's allocated already */
4883 kmsg->iov = kmsg->fast_iov;
4884 kmsg->msg.msg_iter.iov = kmsg->iov;
4886 ret = io_recvmsg_copy_hdr(req, &iomsg);
4892 if (req->flags & REQ_F_BUFFER_SELECT) {
4893 kbuf = io_recv_buffer_select(req, !force_nonblock);
4895 return PTR_ERR(kbuf);
4896 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4897 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4898 1, req->sr_msg.len);
4901 flags = req->sr_msg.msg_flags;
4902 if (flags & MSG_DONTWAIT)
4903 req->flags |= REQ_F_NOWAIT;
4904 else if (force_nonblock)
4905 flags |= MSG_DONTWAIT;
4907 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4908 kmsg->uaddr, flags);
4909 if (force_nonblock && ret == -EAGAIN)
4910 return io_setup_async_msg(req, kmsg);
4911 if (ret == -ERESTARTSYS)
4914 if (req->flags & REQ_F_BUFFER_SELECTED)
4915 cflags = io_put_recv_kbuf(req);
4916 if (kmsg->iov != kmsg->fast_iov)
4918 req->flags &= ~REQ_F_NEED_CLEANUP;
4920 req_set_fail_links(req);
4921 __io_req_complete(req, ret, cflags, cs);
4925 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4926 struct io_comp_state *cs)
4928 struct io_buffer *kbuf;
4929 struct io_sr_msg *sr = &req->sr_msg;
4931 void __user *buf = sr->buf;
4932 struct socket *sock;
4935 int ret, cflags = 0;
4937 sock = sock_from_file(req->file);
4938 if (unlikely(!sock))
4941 if (req->flags & REQ_F_BUFFER_SELECT) {
4942 kbuf = io_recv_buffer_select(req, !force_nonblock);
4944 return PTR_ERR(kbuf);
4945 buf = u64_to_user_ptr(kbuf->addr);
4948 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4952 msg.msg_name = NULL;
4953 msg.msg_control = NULL;
4954 msg.msg_controllen = 0;
4955 msg.msg_namelen = 0;
4956 msg.msg_iocb = NULL;
4959 flags = req->sr_msg.msg_flags;
4960 if (flags & MSG_DONTWAIT)
4961 req->flags |= REQ_F_NOWAIT;
4962 else if (force_nonblock)
4963 flags |= MSG_DONTWAIT;
4965 ret = sock_recvmsg(sock, &msg, flags);
4966 if (force_nonblock && ret == -EAGAIN)
4968 if (ret == -ERESTARTSYS)
4971 if (req->flags & REQ_F_BUFFER_SELECTED)
4972 cflags = io_put_recv_kbuf(req);
4974 req_set_fail_links(req);
4975 __io_req_complete(req, ret, cflags, cs);
4979 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4981 struct io_accept *accept = &req->accept;
4983 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4985 if (sqe->ioprio || sqe->len || sqe->buf_index)
4988 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4989 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4990 accept->flags = READ_ONCE(sqe->accept_flags);
4991 accept->nofile = rlimit(RLIMIT_NOFILE);
4995 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4996 struct io_comp_state *cs)
4998 struct io_accept *accept = &req->accept;
4999 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5002 if (req->file->f_flags & O_NONBLOCK)
5003 req->flags |= REQ_F_NOWAIT;
5005 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
5006 accept->addr_len, accept->flags,
5008 if (ret == -EAGAIN && force_nonblock)
5011 if (ret == -ERESTARTSYS)
5013 req_set_fail_links(req);
5015 __io_req_complete(req, ret, 0, cs);
5019 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5021 struct io_connect *conn = &req->connect;
5022 struct io_async_connect *io = req->async_data;
5024 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5026 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
5029 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5030 conn->addr_len = READ_ONCE(sqe->addr2);
5035 return move_addr_to_kernel(conn->addr, conn->addr_len,
5039 static int io_connect(struct io_kiocb *req, bool force_nonblock,
5040 struct io_comp_state *cs)
5042 struct io_async_connect __io, *io;
5043 unsigned file_flags;
5046 if (req->async_data) {
5047 io = req->async_data;
5049 ret = move_addr_to_kernel(req->connect.addr,
5050 req->connect.addr_len,
5057 file_flags = force_nonblock ? O_NONBLOCK : 0;
5059 ret = __sys_connect_file(req->file, &io->address,
5060 req->connect.addr_len, file_flags);
5061 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5062 if (req->async_data)
5064 if (io_alloc_async_data(req)) {
5068 io = req->async_data;
5069 memcpy(req->async_data, &__io, sizeof(__io));
5072 if (ret == -ERESTARTSYS)
5076 req_set_fail_links(req);
5077 __io_req_complete(req, ret, 0, cs);
5080 #else /* !CONFIG_NET */
5081 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5086 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
5087 struct io_comp_state *cs)
5092 static int io_send(struct io_kiocb *req, bool force_nonblock,
5093 struct io_comp_state *cs)
5098 static int io_recvmsg_prep(struct io_kiocb *req,
5099 const struct io_uring_sqe *sqe)
5104 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
5105 struct io_comp_state *cs)
5110 static int io_recv(struct io_kiocb *req, bool force_nonblock,
5111 struct io_comp_state *cs)
5116 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5121 static int io_accept(struct io_kiocb *req, bool force_nonblock,
5122 struct io_comp_state *cs)
5127 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5132 static int io_connect(struct io_kiocb *req, bool force_nonblock,
5133 struct io_comp_state *cs)
5137 #endif /* CONFIG_NET */
5139 struct io_poll_table {
5140 struct poll_table_struct pt;
5141 struct io_kiocb *req;
5145 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5146 __poll_t mask, task_work_func_t func)
5150 /* for instances that support it check for an event match first: */
5151 if (mask && !(mask & poll->events))
5154 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5156 list_del_init(&poll->wait.entry);
5159 init_task_work(&req->task_work, func);
5160 percpu_ref_get(&req->ctx->refs);
5163 * If this fails, then the task is exiting. When a task exits, the
5164 * work gets canceled, so just cancel this request as well instead
5165 * of executing it. We can't safely execute it anyway, as we may not
5166 * have the needed state needed for it anyway.
5168 ret = io_req_task_work_add(req);
5169 if (unlikely(ret)) {
5170 WRITE_ONCE(poll->canceled, true);
5171 io_req_task_work_add_fallback(req, func);
5176 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5177 __acquires(&req->ctx->completion_lock)
5179 struct io_ring_ctx *ctx = req->ctx;
5181 if (!req->result && !READ_ONCE(poll->canceled)) {
5182 struct poll_table_struct pt = { ._key = poll->events };
5184 req->result = vfs_poll(req->file, &pt) & poll->events;
5187 spin_lock_irq(&ctx->completion_lock);
5188 if (!req->result && !READ_ONCE(poll->canceled)) {
5189 add_wait_queue(poll->head, &poll->wait);
5196 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5198 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5199 if (req->opcode == IORING_OP_POLL_ADD)
5200 return req->async_data;
5201 return req->apoll->double_poll;
5204 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5206 if (req->opcode == IORING_OP_POLL_ADD)
5208 return &req->apoll->poll;
5211 static void io_poll_remove_double(struct io_kiocb *req)
5213 struct io_poll_iocb *poll = io_poll_get_double(req);
5215 lockdep_assert_held(&req->ctx->completion_lock);
5217 if (poll && poll->head) {
5218 struct wait_queue_head *head = poll->head;
5220 spin_lock(&head->lock);
5221 list_del_init(&poll->wait.entry);
5222 if (poll->wait.private)
5223 refcount_dec(&req->refs);
5225 spin_unlock(&head->lock);
5229 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5231 struct io_ring_ctx *ctx = req->ctx;
5233 io_poll_remove_double(req);
5234 req->poll.done = true;
5235 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5236 io_commit_cqring(ctx);
5239 static void io_poll_task_func(struct callback_head *cb)
5241 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5242 struct io_ring_ctx *ctx = req->ctx;
5243 struct io_kiocb *nxt;
5245 if (io_poll_rewait(req, &req->poll)) {
5246 spin_unlock_irq(&ctx->completion_lock);
5248 hash_del(&req->hash_node);
5249 io_poll_complete(req, req->result, 0);
5250 spin_unlock_irq(&ctx->completion_lock);
5252 nxt = io_put_req_find_next(req);
5253 io_cqring_ev_posted(ctx);
5255 __io_req_task_submit(nxt);
5258 percpu_ref_put(&ctx->refs);
5261 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5262 int sync, void *key)
5264 struct io_kiocb *req = wait->private;
5265 struct io_poll_iocb *poll = io_poll_get_single(req);
5266 __poll_t mask = key_to_poll(key);
5268 /* for instances that support it check for an event match first: */
5269 if (mask && !(mask & poll->events))
5272 list_del_init(&wait->entry);
5274 if (poll && poll->head) {
5277 spin_lock(&poll->head->lock);
5278 done = list_empty(&poll->wait.entry);
5280 list_del_init(&poll->wait.entry);
5281 /* make sure double remove sees this as being gone */
5282 wait->private = NULL;
5283 spin_unlock(&poll->head->lock);
5285 /* use wait func handler, so it matches the rq type */
5286 poll->wait.func(&poll->wait, mode, sync, key);
5289 refcount_dec(&req->refs);
5293 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5294 wait_queue_func_t wake_func)
5298 poll->canceled = false;
5299 poll->events = events;
5300 INIT_LIST_HEAD(&poll->wait.entry);
5301 init_waitqueue_func_entry(&poll->wait, wake_func);
5304 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5305 struct wait_queue_head *head,
5306 struct io_poll_iocb **poll_ptr)
5308 struct io_kiocb *req = pt->req;
5311 * If poll->head is already set, it's because the file being polled
5312 * uses multiple waitqueues for poll handling (eg one for read, one
5313 * for write). Setup a separate io_poll_iocb if this happens.
5315 if (unlikely(poll->head)) {
5316 struct io_poll_iocb *poll_one = poll;
5318 /* already have a 2nd entry, fail a third attempt */
5320 pt->error = -EINVAL;
5323 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5325 pt->error = -ENOMEM;
5328 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5329 refcount_inc(&req->refs);
5330 poll->wait.private = req;
5337 if (poll->events & EPOLLEXCLUSIVE)
5338 add_wait_queue_exclusive(head, &poll->wait);
5340 add_wait_queue(head, &poll->wait);
5343 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5344 struct poll_table_struct *p)
5346 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5347 struct async_poll *apoll = pt->req->apoll;
5349 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5352 static void io_async_task_func(struct callback_head *cb)
5354 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5355 struct async_poll *apoll = req->apoll;
5356 struct io_ring_ctx *ctx = req->ctx;
5358 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5360 if (io_poll_rewait(req, &apoll->poll)) {
5361 spin_unlock_irq(&ctx->completion_lock);
5362 percpu_ref_put(&ctx->refs);
5366 /* If req is still hashed, it cannot have been canceled. Don't check. */
5367 if (hash_hashed(&req->hash_node))
5368 hash_del(&req->hash_node);
5370 io_poll_remove_double(req);
5371 spin_unlock_irq(&ctx->completion_lock);
5373 if (!READ_ONCE(apoll->poll.canceled))
5374 __io_req_task_submit(req);
5376 __io_req_task_cancel(req, -ECANCELED);
5378 percpu_ref_put(&ctx->refs);
5379 kfree(apoll->double_poll);
5383 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5386 struct io_kiocb *req = wait->private;
5387 struct io_poll_iocb *poll = &req->apoll->poll;
5389 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5392 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5395 static void io_poll_req_insert(struct io_kiocb *req)
5397 struct io_ring_ctx *ctx = req->ctx;
5398 struct hlist_head *list;
5400 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5401 hlist_add_head(&req->hash_node, list);
5404 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5405 struct io_poll_iocb *poll,
5406 struct io_poll_table *ipt, __poll_t mask,
5407 wait_queue_func_t wake_func)
5408 __acquires(&ctx->completion_lock)
5410 struct io_ring_ctx *ctx = req->ctx;
5411 bool cancel = false;
5413 INIT_HLIST_NODE(&req->hash_node);
5414 io_init_poll_iocb(poll, mask, wake_func);
5415 poll->file = req->file;
5416 poll->wait.private = req;
5418 ipt->pt._key = mask;
5420 ipt->error = -EINVAL;
5422 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5424 spin_lock_irq(&ctx->completion_lock);
5425 if (likely(poll->head)) {
5426 spin_lock(&poll->head->lock);
5427 if (unlikely(list_empty(&poll->wait.entry))) {
5433 if (mask || ipt->error)
5434 list_del_init(&poll->wait.entry);
5436 WRITE_ONCE(poll->canceled, true);
5437 else if (!poll->done) /* actually waiting for an event */
5438 io_poll_req_insert(req);
5439 spin_unlock(&poll->head->lock);
5445 static bool io_arm_poll_handler(struct io_kiocb *req)
5447 const struct io_op_def *def = &io_op_defs[req->opcode];
5448 struct io_ring_ctx *ctx = req->ctx;
5449 struct async_poll *apoll;
5450 struct io_poll_table ipt;
5454 if (!req->file || !file_can_poll(req->file))
5456 if (req->flags & REQ_F_POLLED)
5460 else if (def->pollout)
5464 /* if we can't nonblock try, then no point in arming a poll handler */
5465 if (!io_file_supports_async(req->file, rw))
5468 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5469 if (unlikely(!apoll))
5471 apoll->double_poll = NULL;
5473 req->flags |= REQ_F_POLLED;
5478 mask |= POLLIN | POLLRDNORM;
5480 mask |= POLLOUT | POLLWRNORM;
5482 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5483 if ((req->opcode == IORING_OP_RECVMSG) &&
5484 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5487 mask |= POLLERR | POLLPRI;
5489 ipt.pt._qproc = io_async_queue_proc;
5491 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5493 if (ret || ipt.error) {
5494 io_poll_remove_double(req);
5495 spin_unlock_irq(&ctx->completion_lock);
5496 kfree(apoll->double_poll);
5500 spin_unlock_irq(&ctx->completion_lock);
5501 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5502 apoll->poll.events);
5506 static bool __io_poll_remove_one(struct io_kiocb *req,
5507 struct io_poll_iocb *poll)
5509 bool do_complete = false;
5511 spin_lock(&poll->head->lock);
5512 WRITE_ONCE(poll->canceled, true);
5513 if (!list_empty(&poll->wait.entry)) {
5514 list_del_init(&poll->wait.entry);
5517 spin_unlock(&poll->head->lock);
5518 hash_del(&req->hash_node);
5522 static bool io_poll_remove_one(struct io_kiocb *req)
5526 io_poll_remove_double(req);
5528 if (req->opcode == IORING_OP_POLL_ADD) {
5529 do_complete = __io_poll_remove_one(req, &req->poll);
5531 struct async_poll *apoll = req->apoll;
5533 /* non-poll requests have submit ref still */
5534 do_complete = __io_poll_remove_one(req, &apoll->poll);
5537 kfree(apoll->double_poll);
5543 io_cqring_fill_event(req, -ECANCELED);
5544 io_commit_cqring(req->ctx);
5545 req_set_fail_links(req);
5546 io_put_req_deferred(req, 1);
5553 * Returns true if we found and killed one or more poll requests
5555 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5556 struct files_struct *files)
5558 struct hlist_node *tmp;
5559 struct io_kiocb *req;
5562 spin_lock_irq(&ctx->completion_lock);
5563 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5564 struct hlist_head *list;
5566 list = &ctx->cancel_hash[i];
5567 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5568 if (io_match_task(req, tsk, files))
5569 posted += io_poll_remove_one(req);
5572 spin_unlock_irq(&ctx->completion_lock);
5575 io_cqring_ev_posted(ctx);
5580 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5582 struct hlist_head *list;
5583 struct io_kiocb *req;
5585 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5586 hlist_for_each_entry(req, list, hash_node) {
5587 if (sqe_addr != req->user_data)
5589 if (io_poll_remove_one(req))
5597 static int io_poll_remove_prep(struct io_kiocb *req,
5598 const struct io_uring_sqe *sqe)
5600 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5602 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5606 req->poll_remove.addr = READ_ONCE(sqe->addr);
5611 * Find a running poll command that matches one specified in sqe->addr,
5612 * and remove it if found.
5614 static int io_poll_remove(struct io_kiocb *req)
5616 struct io_ring_ctx *ctx = req->ctx;
5619 spin_lock_irq(&ctx->completion_lock);
5620 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5621 spin_unlock_irq(&ctx->completion_lock);
5624 req_set_fail_links(req);
5625 io_req_complete(req, ret);
5629 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5632 struct io_kiocb *req = wait->private;
5633 struct io_poll_iocb *poll = &req->poll;
5635 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5638 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5639 struct poll_table_struct *p)
5641 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5643 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5646 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5648 struct io_poll_iocb *poll = &req->poll;
5651 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5653 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5656 events = READ_ONCE(sqe->poll32_events);
5658 events = swahw32(events);
5660 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5661 (events & EPOLLEXCLUSIVE);
5665 static int io_poll_add(struct io_kiocb *req)
5667 struct io_poll_iocb *poll = &req->poll;
5668 struct io_ring_ctx *ctx = req->ctx;
5669 struct io_poll_table ipt;
5672 ipt.pt._qproc = io_poll_queue_proc;
5674 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5677 if (mask) { /* no async, we'd stolen it */
5679 io_poll_complete(req, mask, 0);
5681 spin_unlock_irq(&ctx->completion_lock);
5684 io_cqring_ev_posted(ctx);
5690 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5692 struct io_timeout_data *data = container_of(timer,
5693 struct io_timeout_data, timer);
5694 struct io_kiocb *req = data->req;
5695 struct io_ring_ctx *ctx = req->ctx;
5696 unsigned long flags;
5698 spin_lock_irqsave(&ctx->completion_lock, flags);
5699 list_del_init(&req->timeout.list);
5700 atomic_set(&req->ctx->cq_timeouts,
5701 atomic_read(&req->ctx->cq_timeouts) + 1);
5703 io_cqring_fill_event(req, -ETIME);
5704 io_commit_cqring(ctx);
5705 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5707 io_cqring_ev_posted(ctx);
5708 req_set_fail_links(req);
5710 return HRTIMER_NORESTART;
5713 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5716 struct io_timeout_data *io;
5717 struct io_kiocb *req;
5720 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5721 if (user_data == req->user_data) {
5728 return ERR_PTR(ret);
5730 io = req->async_data;
5731 ret = hrtimer_try_to_cancel(&io->timer);
5733 return ERR_PTR(-EALREADY);
5734 list_del_init(&req->timeout.list);
5738 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5740 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5743 return PTR_ERR(req);
5745 req_set_fail_links(req);
5746 io_cqring_fill_event(req, -ECANCELED);
5747 io_put_req_deferred(req, 1);
5751 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5752 struct timespec64 *ts, enum hrtimer_mode mode)
5754 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5755 struct io_timeout_data *data;
5758 return PTR_ERR(req);
5760 req->timeout.off = 0; /* noseq */
5761 data = req->async_data;
5762 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5763 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5764 data->timer.function = io_timeout_fn;
5765 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5769 static int io_timeout_remove_prep(struct io_kiocb *req,
5770 const struct io_uring_sqe *sqe)
5772 struct io_timeout_rem *tr = &req->timeout_rem;
5774 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5776 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5778 if (sqe->ioprio || sqe->buf_index || sqe->len)
5781 tr->addr = READ_ONCE(sqe->addr);
5782 tr->flags = READ_ONCE(sqe->timeout_flags);
5783 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5784 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5786 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5788 } else if (tr->flags) {
5789 /* timeout removal doesn't support flags */
5796 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5798 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5803 * Remove or update an existing timeout command
5805 static int io_timeout_remove(struct io_kiocb *req)
5807 struct io_timeout_rem *tr = &req->timeout_rem;
5808 struct io_ring_ctx *ctx = req->ctx;
5811 spin_lock_irq(&ctx->completion_lock);
5812 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5813 ret = io_timeout_cancel(ctx, tr->addr);
5815 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5816 io_translate_timeout_mode(tr->flags));
5818 io_cqring_fill_event(req, ret);
5819 io_commit_cqring(ctx);
5820 spin_unlock_irq(&ctx->completion_lock);
5821 io_cqring_ev_posted(ctx);
5823 req_set_fail_links(req);
5828 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5829 bool is_timeout_link)
5831 struct io_timeout_data *data;
5833 u32 off = READ_ONCE(sqe->off);
5835 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5837 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5839 if (off && is_timeout_link)
5841 flags = READ_ONCE(sqe->timeout_flags);
5842 if (flags & ~IORING_TIMEOUT_ABS)
5845 req->timeout.off = off;
5847 if (!req->async_data && io_alloc_async_data(req))
5850 data = req->async_data;
5853 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5856 data->mode = io_translate_timeout_mode(flags);
5857 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5861 static int io_timeout(struct io_kiocb *req)
5863 struct io_ring_ctx *ctx = req->ctx;
5864 struct io_timeout_data *data = req->async_data;
5865 struct list_head *entry;
5866 u32 tail, off = req->timeout.off;
5868 spin_lock_irq(&ctx->completion_lock);
5871 * sqe->off holds how many events that need to occur for this
5872 * timeout event to be satisfied. If it isn't set, then this is
5873 * a pure timeout request, sequence isn't used.
5875 if (io_is_timeout_noseq(req)) {
5876 entry = ctx->timeout_list.prev;
5880 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5881 req->timeout.target_seq = tail + off;
5883 /* Update the last seq here in case io_flush_timeouts() hasn't.
5884 * This is safe because ->completion_lock is held, and submissions
5885 * and completions are never mixed in the same ->completion_lock section.
5887 ctx->cq_last_tm_flush = tail;
5890 * Insertion sort, ensuring the first entry in the list is always
5891 * the one we need first.
5893 list_for_each_prev(entry, &ctx->timeout_list) {
5894 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5897 if (io_is_timeout_noseq(nxt))
5899 /* nxt.seq is behind @tail, otherwise would've been completed */
5900 if (off >= nxt->timeout.target_seq - tail)
5904 list_add(&req->timeout.list, entry);
5905 data->timer.function = io_timeout_fn;
5906 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5907 spin_unlock_irq(&ctx->completion_lock);
5911 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5913 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5915 return req->user_data == (unsigned long) data;
5918 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5920 enum io_wq_cancel cancel_ret;
5923 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5924 switch (cancel_ret) {
5925 case IO_WQ_CANCEL_OK:
5928 case IO_WQ_CANCEL_RUNNING:
5931 case IO_WQ_CANCEL_NOTFOUND:
5939 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5940 struct io_kiocb *req, __u64 sqe_addr,
5943 unsigned long flags;
5946 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5947 if (ret != -ENOENT) {
5948 spin_lock_irqsave(&ctx->completion_lock, flags);
5952 spin_lock_irqsave(&ctx->completion_lock, flags);
5953 ret = io_timeout_cancel(ctx, sqe_addr);
5956 ret = io_poll_cancel(ctx, sqe_addr);
5960 io_cqring_fill_event(req, ret);
5961 io_commit_cqring(ctx);
5962 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5963 io_cqring_ev_posted(ctx);
5966 req_set_fail_links(req);
5970 static int io_async_cancel_prep(struct io_kiocb *req,
5971 const struct io_uring_sqe *sqe)
5973 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5975 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5977 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5980 req->cancel.addr = READ_ONCE(sqe->addr);
5984 static int io_async_cancel(struct io_kiocb *req)
5986 struct io_ring_ctx *ctx = req->ctx;
5988 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5992 static int io_rsrc_update_prep(struct io_kiocb *req,
5993 const struct io_uring_sqe *sqe)
5995 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5997 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5999 if (sqe->ioprio || sqe->rw_flags)
6002 req->rsrc_update.offset = READ_ONCE(sqe->off);
6003 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6004 if (!req->rsrc_update.nr_args)
6006 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6010 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
6011 struct io_comp_state *cs)
6013 struct io_ring_ctx *ctx = req->ctx;
6014 struct io_uring_rsrc_update up;
6020 up.offset = req->rsrc_update.offset;
6021 up.data = req->rsrc_update.arg;
6023 mutex_lock(&ctx->uring_lock);
6024 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
6025 mutex_unlock(&ctx->uring_lock);
6028 req_set_fail_links(req);
6029 __io_req_complete(req, ret, 0, cs);
6033 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6035 switch (req->opcode) {
6038 case IORING_OP_READV:
6039 case IORING_OP_READ_FIXED:
6040 case IORING_OP_READ:
6041 return io_read_prep(req, sqe);
6042 case IORING_OP_WRITEV:
6043 case IORING_OP_WRITE_FIXED:
6044 case IORING_OP_WRITE:
6045 return io_write_prep(req, sqe);
6046 case IORING_OP_POLL_ADD:
6047 return io_poll_add_prep(req, sqe);
6048 case IORING_OP_POLL_REMOVE:
6049 return io_poll_remove_prep(req, sqe);
6050 case IORING_OP_FSYNC:
6051 return io_prep_fsync(req, sqe);
6052 case IORING_OP_SYNC_FILE_RANGE:
6053 return io_prep_sfr(req, sqe);
6054 case IORING_OP_SENDMSG:
6055 case IORING_OP_SEND:
6056 return io_sendmsg_prep(req, sqe);
6057 case IORING_OP_RECVMSG:
6058 case IORING_OP_RECV:
6059 return io_recvmsg_prep(req, sqe);
6060 case IORING_OP_CONNECT:
6061 return io_connect_prep(req, sqe);
6062 case IORING_OP_TIMEOUT:
6063 return io_timeout_prep(req, sqe, false);
6064 case IORING_OP_TIMEOUT_REMOVE:
6065 return io_timeout_remove_prep(req, sqe);
6066 case IORING_OP_ASYNC_CANCEL:
6067 return io_async_cancel_prep(req, sqe);
6068 case IORING_OP_LINK_TIMEOUT:
6069 return io_timeout_prep(req, sqe, true);
6070 case IORING_OP_ACCEPT:
6071 return io_accept_prep(req, sqe);
6072 case IORING_OP_FALLOCATE:
6073 return io_fallocate_prep(req, sqe);
6074 case IORING_OP_OPENAT:
6075 return io_openat_prep(req, sqe);
6076 case IORING_OP_CLOSE:
6077 return io_close_prep(req, sqe);
6078 case IORING_OP_FILES_UPDATE:
6079 return io_rsrc_update_prep(req, sqe);
6080 case IORING_OP_STATX:
6081 return io_statx_prep(req, sqe);
6082 case IORING_OP_FADVISE:
6083 return io_fadvise_prep(req, sqe);
6084 case IORING_OP_MADVISE:
6085 return io_madvise_prep(req, sqe);
6086 case IORING_OP_OPENAT2:
6087 return io_openat2_prep(req, sqe);
6088 case IORING_OP_EPOLL_CTL:
6089 return io_epoll_ctl_prep(req, sqe);
6090 case IORING_OP_SPLICE:
6091 return io_splice_prep(req, sqe);
6092 case IORING_OP_PROVIDE_BUFFERS:
6093 return io_provide_buffers_prep(req, sqe);
6094 case IORING_OP_REMOVE_BUFFERS:
6095 return io_remove_buffers_prep(req, sqe);
6097 return io_tee_prep(req, sqe);
6098 case IORING_OP_SHUTDOWN:
6099 return io_shutdown_prep(req, sqe);
6100 case IORING_OP_RENAMEAT:
6101 return io_renameat_prep(req, sqe);
6102 case IORING_OP_UNLINKAT:
6103 return io_unlinkat_prep(req, sqe);
6106 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6111 static int io_req_defer_prep(struct io_kiocb *req,
6112 const struct io_uring_sqe *sqe)
6116 if (io_alloc_async_data(req))
6118 return io_req_prep(req, sqe);
6121 static u32 io_get_sequence(struct io_kiocb *req)
6123 struct io_kiocb *pos;
6124 struct io_ring_ctx *ctx = req->ctx;
6125 u32 total_submitted, nr_reqs = 0;
6127 io_for_each_link(pos, req)
6130 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6131 return total_submitted - nr_reqs;
6134 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6136 struct io_ring_ctx *ctx = req->ctx;
6137 struct io_defer_entry *de;
6141 /* Still need defer if there is pending req in defer list. */
6142 if (likely(list_empty_careful(&ctx->defer_list) &&
6143 !(req->flags & REQ_F_IO_DRAIN)))
6146 seq = io_get_sequence(req);
6147 /* Still a chance to pass the sequence check */
6148 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6151 if (!req->async_data) {
6152 ret = io_req_defer_prep(req, sqe);
6156 io_prep_async_link(req);
6157 de = kmalloc(sizeof(*de), GFP_KERNEL);
6161 spin_lock_irq(&ctx->completion_lock);
6162 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6163 spin_unlock_irq(&ctx->completion_lock);
6165 io_queue_async_work(req);
6166 return -EIOCBQUEUED;
6169 trace_io_uring_defer(ctx, req, req->user_data);
6172 list_add_tail(&de->list, &ctx->defer_list);
6173 spin_unlock_irq(&ctx->completion_lock);
6174 return -EIOCBQUEUED;
6177 static void __io_clean_op(struct io_kiocb *req)
6179 if (req->flags & REQ_F_BUFFER_SELECTED) {
6180 switch (req->opcode) {
6181 case IORING_OP_READV:
6182 case IORING_OP_READ_FIXED:
6183 case IORING_OP_READ:
6184 kfree((void *)(unsigned long)req->rw.addr);
6186 case IORING_OP_RECVMSG:
6187 case IORING_OP_RECV:
6188 kfree(req->sr_msg.kbuf);
6191 req->flags &= ~REQ_F_BUFFER_SELECTED;
6194 if (req->flags & REQ_F_NEED_CLEANUP) {
6195 switch (req->opcode) {
6196 case IORING_OP_READV:
6197 case IORING_OP_READ_FIXED:
6198 case IORING_OP_READ:
6199 case IORING_OP_WRITEV:
6200 case IORING_OP_WRITE_FIXED:
6201 case IORING_OP_WRITE: {
6202 struct io_async_rw *io = req->async_data;
6204 kfree(io->free_iovec);
6207 case IORING_OP_RECVMSG:
6208 case IORING_OP_SENDMSG: {
6209 struct io_async_msghdr *io = req->async_data;
6210 if (io->iov != io->fast_iov)
6214 case IORING_OP_SPLICE:
6216 io_put_file(req, req->splice.file_in,
6217 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6219 case IORING_OP_OPENAT:
6220 case IORING_OP_OPENAT2:
6221 if (req->open.filename)
6222 putname(req->open.filename);
6224 case IORING_OP_RENAMEAT:
6225 putname(req->rename.oldpath);
6226 putname(req->rename.newpath);
6228 case IORING_OP_UNLINKAT:
6229 putname(req->unlink.filename);
6232 req->flags &= ~REQ_F_NEED_CLEANUP;
6236 static int io_issue_sqe(struct io_kiocb *req, bool force_nonblock,
6237 struct io_comp_state *cs)
6239 struct io_ring_ctx *ctx = req->ctx;
6242 switch (req->opcode) {
6244 ret = io_nop(req, cs);
6246 case IORING_OP_READV:
6247 case IORING_OP_READ_FIXED:
6248 case IORING_OP_READ:
6249 ret = io_read(req, force_nonblock, cs);
6251 case IORING_OP_WRITEV:
6252 case IORING_OP_WRITE_FIXED:
6253 case IORING_OP_WRITE:
6254 ret = io_write(req, force_nonblock, cs);
6256 case IORING_OP_FSYNC:
6257 ret = io_fsync(req, force_nonblock);
6259 case IORING_OP_POLL_ADD:
6260 ret = io_poll_add(req);
6262 case IORING_OP_POLL_REMOVE:
6263 ret = io_poll_remove(req);
6265 case IORING_OP_SYNC_FILE_RANGE:
6266 ret = io_sync_file_range(req, force_nonblock);
6268 case IORING_OP_SENDMSG:
6269 ret = io_sendmsg(req, force_nonblock, cs);
6271 case IORING_OP_SEND:
6272 ret = io_send(req, force_nonblock, cs);
6274 case IORING_OP_RECVMSG:
6275 ret = io_recvmsg(req, force_nonblock, cs);
6277 case IORING_OP_RECV:
6278 ret = io_recv(req, force_nonblock, cs);
6280 case IORING_OP_TIMEOUT:
6281 ret = io_timeout(req);
6283 case IORING_OP_TIMEOUT_REMOVE:
6284 ret = io_timeout_remove(req);
6286 case IORING_OP_ACCEPT:
6287 ret = io_accept(req, force_nonblock, cs);
6289 case IORING_OP_CONNECT:
6290 ret = io_connect(req, force_nonblock, cs);
6292 case IORING_OP_ASYNC_CANCEL:
6293 ret = io_async_cancel(req);
6295 case IORING_OP_FALLOCATE:
6296 ret = io_fallocate(req, force_nonblock);
6298 case IORING_OP_OPENAT:
6299 ret = io_openat(req, force_nonblock);
6301 case IORING_OP_CLOSE:
6302 ret = io_close(req, force_nonblock, cs);
6304 case IORING_OP_FILES_UPDATE:
6305 ret = io_files_update(req, force_nonblock, cs);
6307 case IORING_OP_STATX:
6308 ret = io_statx(req, force_nonblock);
6310 case IORING_OP_FADVISE:
6311 ret = io_fadvise(req, force_nonblock);
6313 case IORING_OP_MADVISE:
6314 ret = io_madvise(req, force_nonblock);
6316 case IORING_OP_OPENAT2:
6317 ret = io_openat2(req, force_nonblock);
6319 case IORING_OP_EPOLL_CTL:
6320 ret = io_epoll_ctl(req, force_nonblock, cs);
6322 case IORING_OP_SPLICE:
6323 ret = io_splice(req, force_nonblock);
6325 case IORING_OP_PROVIDE_BUFFERS:
6326 ret = io_provide_buffers(req, force_nonblock, cs);
6328 case IORING_OP_REMOVE_BUFFERS:
6329 ret = io_remove_buffers(req, force_nonblock, cs);
6332 ret = io_tee(req, force_nonblock);
6334 case IORING_OP_SHUTDOWN:
6335 ret = io_shutdown(req, force_nonblock);
6337 case IORING_OP_RENAMEAT:
6338 ret = io_renameat(req, force_nonblock);
6340 case IORING_OP_UNLINKAT:
6341 ret = io_unlinkat(req, force_nonblock);
6351 /* If the op doesn't have a file, we're not polling for it */
6352 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6353 const bool in_async = io_wq_current_is_worker();
6355 /* workqueue context doesn't hold uring_lock, grab it now */
6357 mutex_lock(&ctx->uring_lock);
6359 io_iopoll_req_issued(req, in_async);
6362 mutex_unlock(&ctx->uring_lock);
6368 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
6370 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6371 struct io_kiocb *timeout;
6374 timeout = io_prep_linked_timeout(req);
6376 io_queue_linked_timeout(timeout);
6378 if (work->flags & IO_WQ_WORK_CANCEL)
6383 ret = io_issue_sqe(req, false, NULL);
6385 * We can get EAGAIN for polled IO even though we're
6386 * forcing a sync submission from here, since we can't
6387 * wait for request slots on the block side.
6396 struct io_ring_ctx *lock_ctx = NULL;
6398 if (req->ctx->flags & IORING_SETUP_IOPOLL)
6399 lock_ctx = req->ctx;
6402 * io_iopoll_complete() does not hold completion_lock to
6403 * complete polled io, so here for polled io, we can not call
6404 * io_req_complete() directly, otherwise there maybe concurrent
6405 * access to cqring, defer_list, etc, which is not safe. Given
6406 * that io_iopoll_complete() is always called under uring_lock,
6407 * so here for polled io, we also get uring_lock to complete
6411 mutex_lock(&lock_ctx->uring_lock);
6413 req_set_fail_links(req);
6414 io_req_complete(req, ret);
6417 mutex_unlock(&lock_ctx->uring_lock);
6420 return io_steal_work(req);
6423 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6426 struct fixed_rsrc_table *table;
6428 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6429 return table->files[index & IORING_FILE_TABLE_MASK];
6432 static struct file *io_file_get(struct io_submit_state *state,
6433 struct io_kiocb *req, int fd, bool fixed)
6435 struct io_ring_ctx *ctx = req->ctx;
6439 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6441 fd = array_index_nospec(fd, ctx->nr_user_files);
6442 file = io_file_from_index(ctx, fd);
6443 io_set_resource_node(req);
6445 trace_io_uring_file_get(ctx, fd);
6446 file = __io_file_get(state, fd);
6449 if (file && unlikely(file->f_op == &io_uring_fops))
6450 io_req_track_inflight(req);
6454 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6456 struct io_timeout_data *data = container_of(timer,
6457 struct io_timeout_data, timer);
6458 struct io_kiocb *prev, *req = data->req;
6459 struct io_ring_ctx *ctx = req->ctx;
6460 unsigned long flags;
6462 spin_lock_irqsave(&ctx->completion_lock, flags);
6463 prev = req->timeout.head;
6464 req->timeout.head = NULL;
6467 * We don't expect the list to be empty, that will only happen if we
6468 * race with the completion of the linked work.
6470 if (prev && refcount_inc_not_zero(&prev->refs))
6471 io_remove_next_linked(prev);
6474 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6477 req_set_fail_links(prev);
6478 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6479 io_put_req_deferred(prev, 1);
6481 io_req_complete_post(req, -ETIME, 0);
6482 io_put_req_deferred(req, 1);
6484 return HRTIMER_NORESTART;
6487 static void __io_queue_linked_timeout(struct io_kiocb *req)
6490 * If the back reference is NULL, then our linked request finished
6491 * before we got a chance to setup the timer
6493 if (req->timeout.head) {
6494 struct io_timeout_data *data = req->async_data;
6496 data->timer.function = io_link_timeout_fn;
6497 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6502 static void io_queue_linked_timeout(struct io_kiocb *req)
6504 struct io_ring_ctx *ctx = req->ctx;
6506 spin_lock_irq(&ctx->completion_lock);
6507 __io_queue_linked_timeout(req);
6508 spin_unlock_irq(&ctx->completion_lock);
6510 /* drop submission reference */
6514 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6516 struct io_kiocb *nxt = req->link;
6518 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6519 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6522 nxt->timeout.head = req;
6523 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6524 req->flags |= REQ_F_LINK_TIMEOUT;
6528 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs)
6530 struct io_kiocb *linked_timeout;
6531 const struct cred *old_creds = NULL;
6535 linked_timeout = io_prep_linked_timeout(req);
6537 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6538 (req->work.flags & IO_WQ_WORK_CREDS) &&
6539 req->work.identity->creds != current_cred()) {
6541 revert_creds(old_creds);
6542 if (old_creds == req->work.identity->creds)
6543 old_creds = NULL; /* restored original creds */
6545 old_creds = override_creds(req->work.identity->creds);
6548 ret = io_issue_sqe(req, true, cs);
6551 * We async punt it if the file wasn't marked NOWAIT, or if the file
6552 * doesn't support non-blocking read/write attempts
6554 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6555 if (!io_arm_poll_handler(req)) {
6557 * Queued up for async execution, worker will release
6558 * submit reference when the iocb is actually submitted.
6560 io_queue_async_work(req);
6564 io_queue_linked_timeout(linked_timeout);
6565 } else if (likely(!ret)) {
6566 /* drop submission reference */
6567 if (req->flags & REQ_F_COMPLETE_INLINE) {
6568 list_add_tail(&req->compl.list, &cs->list);
6570 io_submit_flush_completions(cs);
6573 req = io_put_req_find_next(req);
6577 io_queue_linked_timeout(linked_timeout);
6580 if (!(req->flags & REQ_F_FORCE_ASYNC))
6582 io_queue_async_work(req);
6585 /* un-prep timeout, so it'll be killed as any other linked */
6586 req->flags &= ~REQ_F_LINK_TIMEOUT;
6587 req_set_fail_links(req);
6589 io_req_complete(req, ret);
6593 revert_creds(old_creds);
6596 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6597 struct io_comp_state *cs)
6601 ret = io_req_defer(req, sqe);
6603 if (ret != -EIOCBQUEUED) {
6605 req_set_fail_links(req);
6607 io_req_complete(req, ret);
6609 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6610 if (!req->async_data) {
6611 ret = io_req_defer_prep(req, sqe);
6615 io_queue_async_work(req);
6618 ret = io_req_prep(req, sqe);
6622 __io_queue_sqe(req, cs);
6626 static inline void io_queue_link_head(struct io_kiocb *req,
6627 struct io_comp_state *cs)
6629 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6631 io_req_complete(req, -ECANCELED);
6633 io_queue_sqe(req, NULL, cs);
6636 struct io_submit_link {
6637 struct io_kiocb *head;
6638 struct io_kiocb *last;
6641 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6642 struct io_submit_link *link, struct io_comp_state *cs)
6644 struct io_ring_ctx *ctx = req->ctx;
6648 * If we already have a head request, queue this one for async
6649 * submittal once the head completes. If we don't have a head but
6650 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6651 * submitted sync once the chain is complete. If none of those
6652 * conditions are true (normal request), then just queue it.
6655 struct io_kiocb *head = link->head;
6658 * Taking sequential execution of a link, draining both sides
6659 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6660 * requests in the link. So, it drains the head and the
6661 * next after the link request. The last one is done via
6662 * drain_next flag to persist the effect across calls.
6664 if (req->flags & REQ_F_IO_DRAIN) {
6665 head->flags |= REQ_F_IO_DRAIN;
6666 ctx->drain_next = 1;
6668 ret = io_req_defer_prep(req, sqe);
6669 if (unlikely(ret)) {
6670 /* fail even hard links since we don't submit */
6671 head->flags |= REQ_F_FAIL_LINK;
6674 trace_io_uring_link(ctx, req, head);
6675 link->last->link = req;
6678 /* last request of a link, enqueue the link */
6679 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6680 io_queue_link_head(head, cs);
6684 if (unlikely(ctx->drain_next)) {
6685 req->flags |= REQ_F_IO_DRAIN;
6686 ctx->drain_next = 0;
6688 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6689 ret = io_req_defer_prep(req, sqe);
6691 req->flags |= REQ_F_FAIL_LINK;
6695 io_queue_sqe(req, sqe, cs);
6703 * Batched submission is done, ensure local IO is flushed out.
6705 static void io_submit_state_end(struct io_submit_state *state)
6707 if (!list_empty(&state->comp.list))
6708 io_submit_flush_completions(&state->comp);
6709 if (state->plug_started)
6710 blk_finish_plug(&state->plug);
6711 io_state_file_put(state);
6712 if (state->free_reqs)
6713 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6717 * Start submission side cache.
6719 static void io_submit_state_start(struct io_submit_state *state,
6720 struct io_ring_ctx *ctx, unsigned int max_ios)
6722 state->plug_started = false;
6724 INIT_LIST_HEAD(&state->comp.list);
6725 state->comp.ctx = ctx;
6726 state->free_reqs = 0;
6727 state->file_refs = 0;
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);
6774 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6776 ctx->cached_sq_head++;
6780 * Check SQE restrictions (opcode and flags).
6782 * Returns 'true' if SQE is allowed, 'false' otherwise.
6784 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6785 struct io_kiocb *req,
6786 unsigned int sqe_flags)
6788 if (!ctx->restricted)
6791 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6794 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6795 ctx->restrictions.sqe_flags_required)
6798 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6799 ctx->restrictions.sqe_flags_required))
6805 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6806 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6807 IOSQE_BUFFER_SELECT)
6809 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6810 const struct io_uring_sqe *sqe,
6811 struct io_submit_state *state)
6813 unsigned int sqe_flags;
6816 req->opcode = READ_ONCE(sqe->opcode);
6817 req->user_data = READ_ONCE(sqe->user_data);
6818 req->async_data = NULL;
6823 req->fixed_rsrc_refs = NULL;
6824 /* one is dropped after submission, the other at completion */
6825 refcount_set(&req->refs, 2);
6826 req->task = current;
6829 if (unlikely(req->opcode >= IORING_OP_LAST))
6832 if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6835 sqe_flags = READ_ONCE(sqe->flags);
6836 /* enforce forwards compatibility on users */
6837 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6840 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6843 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6844 !io_op_defs[req->opcode].buffer_select)
6847 id = READ_ONCE(sqe->personality);
6849 struct io_identity *iod;
6851 iod = idr_find(&ctx->personality_idr, id);
6854 refcount_inc(&iod->count);
6856 __io_req_init_async(req);
6857 get_cred(iod->creds);
6858 req->work.identity = iod;
6859 req->work.flags |= IO_WQ_WORK_CREDS;
6862 /* same numerical values with corresponding REQ_F_*, safe to copy */
6863 req->flags |= sqe_flags;
6866 * Plug now if we have more than 1 IO left after this, and the target
6867 * is potentially a read/write to block based storage.
6869 if (!state->plug_started && state->ios_left > 1 &&
6870 io_op_defs[req->opcode].plug) {
6871 blk_start_plug(&state->plug);
6872 state->plug_started = true;
6876 if (io_op_defs[req->opcode].needs_file) {
6877 bool fixed = req->flags & REQ_F_FIXED_FILE;
6879 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6880 if (unlikely(!req->file))
6888 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6890 struct io_submit_state state;
6891 struct io_submit_link link;
6892 int i, submitted = 0;
6894 /* if we have a backlog and couldn't flush it all, return BUSY */
6895 if (test_bit(0, &ctx->sq_check_overflow)) {
6896 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6900 /* make sure SQ entry isn't read before tail */
6901 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6903 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6906 percpu_counter_add(¤t->io_uring->inflight, nr);
6907 refcount_add(nr, ¤t->usage);
6909 io_submit_state_start(&state, ctx, nr);
6912 for (i = 0; i < nr; i++) {
6913 const struct io_uring_sqe *sqe;
6914 struct io_kiocb *req;
6917 sqe = io_get_sqe(ctx);
6918 if (unlikely(!sqe)) {
6919 io_consume_sqe(ctx);
6922 req = io_alloc_req(ctx, &state);
6923 if (unlikely(!req)) {
6925 submitted = -EAGAIN;
6928 io_consume_sqe(ctx);
6929 /* will complete beyond this point, count as submitted */
6932 err = io_init_req(ctx, req, sqe, &state);
6933 if (unlikely(err)) {
6936 io_req_complete(req, err);
6940 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6941 true, ctx->flags & IORING_SETUP_SQPOLL);
6942 err = io_submit_sqe(req, sqe, &link, &state.comp);
6947 if (unlikely(submitted != nr)) {
6948 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6949 struct io_uring_task *tctx = current->io_uring;
6950 int unused = nr - ref_used;
6952 percpu_ref_put_many(&ctx->refs, unused);
6953 percpu_counter_sub(&tctx->inflight, unused);
6954 put_task_struct_many(current, unused);
6957 io_queue_link_head(link.head, &state.comp);
6958 io_submit_state_end(&state);
6960 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6961 io_commit_sqring(ctx);
6966 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6968 /* Tell userspace we may need a wakeup call */
6969 spin_lock_irq(&ctx->completion_lock);
6970 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6971 spin_unlock_irq(&ctx->completion_lock);
6974 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6976 spin_lock_irq(&ctx->completion_lock);
6977 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6978 spin_unlock_irq(&ctx->completion_lock);
6981 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6983 unsigned int to_submit;
6986 to_submit = io_sqring_entries(ctx);
6987 /* if we're handling multiple rings, cap submit size for fairness */
6988 if (cap_entries && to_submit > 8)
6991 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6992 unsigned nr_events = 0;
6994 mutex_lock(&ctx->uring_lock);
6995 if (!list_empty(&ctx->iopoll_list))
6996 io_do_iopoll(ctx, &nr_events, 0);
6998 if (to_submit && !ctx->sqo_dead &&
6999 likely(!percpu_ref_is_dying(&ctx->refs)))
7000 ret = io_submit_sqes(ctx, to_submit);
7001 mutex_unlock(&ctx->uring_lock);
7004 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
7005 wake_up(&ctx->sqo_sq_wait);
7010 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7012 struct io_ring_ctx *ctx;
7013 unsigned sq_thread_idle = 0;
7015 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7016 if (sq_thread_idle < ctx->sq_thread_idle)
7017 sq_thread_idle = ctx->sq_thread_idle;
7020 sqd->sq_thread_idle = sq_thread_idle;
7023 static void io_sqd_init_new(struct io_sq_data *sqd)
7025 struct io_ring_ctx *ctx;
7027 while (!list_empty(&sqd->ctx_new_list)) {
7028 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
7029 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
7030 complete(&ctx->sq_thread_comp);
7033 io_sqd_update_thread_idle(sqd);
7036 static int io_sq_thread(void *data)
7038 struct cgroup_subsys_state *cur_css = NULL;
7039 struct files_struct *old_files = current->files;
7040 struct nsproxy *old_nsproxy = current->nsproxy;
7041 const struct cred *old_cred = NULL;
7042 struct io_sq_data *sqd = data;
7043 struct io_ring_ctx *ctx;
7044 unsigned long timeout = 0;
7048 current->files = NULL;
7049 current->nsproxy = NULL;
7050 task_unlock(current);
7052 while (!kthread_should_stop()) {
7054 bool cap_entries, sqt_spin, needs_sched;
7057 * Any changes to the sqd lists are synchronized through the
7058 * kthread parking. This synchronizes the thread vs users,
7059 * the users are synchronized on the sqd->ctx_lock.
7061 if (kthread_should_park()) {
7064 * When sq thread is unparked, in case the previous park operation
7065 * comes from io_put_sq_data(), which means that sq thread is going
7066 * to be stopped, so here needs to have a check.
7068 if (kthread_should_stop())
7072 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
7073 io_sqd_init_new(sqd);
7074 timeout = jiffies + sqd->sq_thread_idle;
7078 cap_entries = !list_is_singular(&sqd->ctx_list);
7079 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7080 if (current->cred != ctx->creds) {
7082 revert_creds(old_cred);
7083 old_cred = override_creds(ctx->creds);
7085 io_sq_thread_associate_blkcg(ctx, &cur_css);
7087 current->loginuid = ctx->loginuid;
7088 current->sessionid = ctx->sessionid;
7091 ret = __io_sq_thread(ctx, cap_entries);
7092 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7095 io_sq_thread_drop_mm_files();
7098 if (sqt_spin || !time_after(jiffies, timeout)) {
7100 io_sq_thread_drop_mm_files();
7103 timeout = jiffies + sqd->sq_thread_idle;
7108 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7109 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7110 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7111 !list_empty_careful(&ctx->iopoll_list)) {
7112 needs_sched = false;
7115 if (io_sqring_entries(ctx)) {
7116 needs_sched = false;
7121 if (needs_sched && !kthread_should_park()) {
7122 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7123 io_ring_set_wakeup_flag(ctx);
7126 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7127 io_ring_clear_wakeup_flag(ctx);
7130 finish_wait(&sqd->wait, &wait);
7131 timeout = jiffies + sqd->sq_thread_idle;
7135 io_sq_thread_drop_mm_files();
7138 io_sq_thread_unassociate_blkcg();
7140 revert_creds(old_cred);
7143 current->files = old_files;
7144 current->nsproxy = old_nsproxy;
7145 task_unlock(current);
7152 struct io_wait_queue {
7153 struct wait_queue_entry wq;
7154 struct io_ring_ctx *ctx;
7156 unsigned nr_timeouts;
7159 static inline bool io_should_wake(struct io_wait_queue *iowq)
7161 struct io_ring_ctx *ctx = iowq->ctx;
7164 * Wake up if we have enough events, or if a timeout occurred since we
7165 * started waiting. For timeouts, we always want to return to userspace,
7166 * regardless of event count.
7168 return io_cqring_events(ctx) >= iowq->to_wait ||
7169 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7172 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7173 int wake_flags, void *key)
7175 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7179 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7180 * the task, and the next invocation will do it.
7182 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
7183 return autoremove_wake_function(curr, mode, wake_flags, key);
7187 static int io_run_task_work_sig(void)
7189 if (io_run_task_work())
7191 if (!signal_pending(current))
7193 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
7194 return -ERESTARTSYS;
7199 * Wait until events become available, if we don't already have some. The
7200 * application must reap them itself, as they reside on the shared cq ring.
7202 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7203 const sigset_t __user *sig, size_t sigsz,
7204 struct __kernel_timespec __user *uts)
7206 struct io_wait_queue iowq = {
7209 .func = io_wake_function,
7210 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7213 .to_wait = min_events,
7215 struct io_rings *rings = ctx->rings;
7216 struct timespec64 ts;
7217 signed long timeout = 0;
7221 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7222 if (io_cqring_events(ctx) >= min_events)
7224 if (!io_run_task_work())
7229 #ifdef CONFIG_COMPAT
7230 if (in_compat_syscall())
7231 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7235 ret = set_user_sigmask(sig, sigsz);
7242 if (get_timespec64(&ts, uts))
7244 timeout = timespec64_to_jiffies(&ts);
7247 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7248 trace_io_uring_cqring_wait(ctx, min_events);
7250 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7251 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7252 TASK_INTERRUPTIBLE);
7253 /* make sure we run task_work before checking for signals */
7254 ret = io_run_task_work_sig();
7256 finish_wait(&ctx->wait, &iowq.wq);
7261 if (io_should_wake(&iowq))
7263 if (test_bit(0, &ctx->cq_check_overflow)) {
7264 finish_wait(&ctx->wait, &iowq.wq);
7268 timeout = schedule_timeout(timeout);
7277 finish_wait(&ctx->wait, &iowq.wq);
7279 restore_saved_sigmask_unless(ret == -EINTR);
7281 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7284 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7286 #if defined(CONFIG_UNIX)
7287 if (ctx->ring_sock) {
7288 struct sock *sock = ctx->ring_sock->sk;
7289 struct sk_buff *skb;
7291 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7297 for (i = 0; i < ctx->nr_user_files; i++) {
7300 file = io_file_from_index(ctx, i);
7307 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7309 struct fixed_rsrc_data *data;
7311 data = container_of(ref, struct fixed_rsrc_data, refs);
7312 complete(&data->done);
7315 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7317 spin_lock_bh(&ctx->rsrc_ref_lock);
7320 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7322 spin_unlock_bh(&ctx->rsrc_ref_lock);
7325 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
7326 struct fixed_rsrc_data *rsrc_data,
7327 struct fixed_rsrc_ref_node *ref_node)
7329 io_rsrc_ref_lock(ctx);
7330 rsrc_data->node = ref_node;
7331 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
7332 io_rsrc_ref_unlock(ctx);
7333 percpu_ref_get(&rsrc_data->refs);
7336 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
7337 struct io_ring_ctx *ctx,
7338 struct fixed_rsrc_ref_node *backup_node)
7340 struct fixed_rsrc_ref_node *ref_node;
7343 io_rsrc_ref_lock(ctx);
7344 ref_node = data->node;
7345 io_rsrc_ref_unlock(ctx);
7347 percpu_ref_kill(&ref_node->refs);
7349 percpu_ref_kill(&data->refs);
7351 /* wait for all refs nodes to complete */
7352 flush_delayed_work(&ctx->rsrc_put_work);
7354 ret = wait_for_completion_interruptible(&data->done);
7357 ret = io_run_task_work_sig();
7359 percpu_ref_resurrect(&data->refs);
7360 reinit_completion(&data->done);
7361 io_sqe_rsrc_set_node(ctx, data, backup_node);
7366 destroy_fixed_rsrc_ref_node(backup_node);
7370 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7372 struct fixed_rsrc_data *data;
7374 data = kzalloc(sizeof(*data), GFP_KERNEL);
7378 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7379 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7384 init_completion(&data->done);
7388 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7390 percpu_ref_exit(&data->refs);
7395 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7397 struct fixed_rsrc_data *data = ctx->file_data;
7398 struct fixed_rsrc_ref_node *backup_node;
7399 unsigned nr_tables, i;
7404 backup_node = alloc_fixed_rsrc_ref_node(ctx);
7407 init_fixed_file_ref_node(ctx, backup_node);
7409 ret = io_rsrc_ref_quiesce(data, ctx, backup_node);
7413 __io_sqe_files_unregister(ctx);
7414 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7415 for (i = 0; i < nr_tables; i++)
7416 kfree(data->table[i].files);
7417 free_fixed_rsrc_data(data);
7418 ctx->file_data = NULL;
7419 ctx->nr_user_files = 0;
7423 static void io_put_sq_data(struct io_sq_data *sqd)
7425 if (refcount_dec_and_test(&sqd->refs)) {
7427 * The park is a bit of a work-around, without it we get
7428 * warning spews on shutdown with SQPOLL set and affinity
7429 * set to a single CPU.
7432 kthread_park(sqd->thread);
7433 kthread_stop(sqd->thread);
7440 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7442 struct io_ring_ctx *ctx_attach;
7443 struct io_sq_data *sqd;
7446 f = fdget(p->wq_fd);
7448 return ERR_PTR(-ENXIO);
7449 if (f.file->f_op != &io_uring_fops) {
7451 return ERR_PTR(-EINVAL);
7454 ctx_attach = f.file->private_data;
7455 sqd = ctx_attach->sq_data;
7458 return ERR_PTR(-EINVAL);
7461 refcount_inc(&sqd->refs);
7466 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7468 struct io_sq_data *sqd;
7470 if (p->flags & IORING_SETUP_ATTACH_WQ)
7471 return io_attach_sq_data(p);
7473 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7475 return ERR_PTR(-ENOMEM);
7477 refcount_set(&sqd->refs, 1);
7478 INIT_LIST_HEAD(&sqd->ctx_list);
7479 INIT_LIST_HEAD(&sqd->ctx_new_list);
7480 mutex_init(&sqd->ctx_lock);
7481 mutex_init(&sqd->lock);
7482 init_waitqueue_head(&sqd->wait);
7486 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7487 __releases(&sqd->lock)
7491 kthread_unpark(sqd->thread);
7492 mutex_unlock(&sqd->lock);
7495 static void io_sq_thread_park(struct io_sq_data *sqd)
7496 __acquires(&sqd->lock)
7500 mutex_lock(&sqd->lock);
7501 kthread_park(sqd->thread);
7504 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7506 struct io_sq_data *sqd = ctx->sq_data;
7511 * We may arrive here from the error branch in
7512 * io_sq_offload_create() where the kthread is created
7513 * without being waked up, thus wake it up now to make
7514 * sure the wait will complete.
7516 wake_up_process(sqd->thread);
7517 wait_for_completion(&ctx->sq_thread_comp);
7519 io_sq_thread_park(sqd);
7522 mutex_lock(&sqd->ctx_lock);
7523 list_del(&ctx->sqd_list);
7524 io_sqd_update_thread_idle(sqd);
7525 mutex_unlock(&sqd->ctx_lock);
7528 io_sq_thread_unpark(sqd);
7530 io_put_sq_data(sqd);
7531 ctx->sq_data = NULL;
7535 static void io_finish_async(struct io_ring_ctx *ctx)
7537 io_sq_thread_stop(ctx);
7540 io_wq_destroy(ctx->io_wq);
7545 #if defined(CONFIG_UNIX)
7547 * Ensure the UNIX gc is aware of our file set, so we are certain that
7548 * the io_uring can be safely unregistered on process exit, even if we have
7549 * loops in the file referencing.
7551 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7553 struct sock *sk = ctx->ring_sock->sk;
7554 struct scm_fp_list *fpl;
7555 struct sk_buff *skb;
7558 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7562 skb = alloc_skb(0, GFP_KERNEL);
7571 fpl->user = get_uid(ctx->user);
7572 for (i = 0; i < nr; i++) {
7573 struct file *file = io_file_from_index(ctx, i + offset);
7577 fpl->fp[nr_files] = get_file(file);
7578 unix_inflight(fpl->user, fpl->fp[nr_files]);
7583 fpl->max = SCM_MAX_FD;
7584 fpl->count = nr_files;
7585 UNIXCB(skb).fp = fpl;
7586 skb->destructor = unix_destruct_scm;
7587 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7588 skb_queue_head(&sk->sk_receive_queue, skb);
7590 for (i = 0; i < nr_files; i++)
7601 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7602 * causes regular reference counting to break down. We rely on the UNIX
7603 * garbage collection to take care of this problem for us.
7605 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7607 unsigned left, total;
7611 left = ctx->nr_user_files;
7613 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7615 ret = __io_sqe_files_scm(ctx, this_files, total);
7619 total += this_files;
7625 while (total < ctx->nr_user_files) {
7626 struct file *file = io_file_from_index(ctx, total);
7636 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7642 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7643 unsigned nr_tables, unsigned nr_files)
7647 for (i = 0; i < nr_tables; i++) {
7648 struct fixed_rsrc_table *table = &file_data->table[i];
7649 unsigned this_files;
7651 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7652 table->files = kcalloc(this_files, sizeof(struct file *),
7656 nr_files -= this_files;
7662 for (i = 0; i < nr_tables; i++) {
7663 struct fixed_rsrc_table *table = &file_data->table[i];
7664 kfree(table->files);
7669 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7671 struct file *file = prsrc->file;
7672 #if defined(CONFIG_UNIX)
7673 struct sock *sock = ctx->ring_sock->sk;
7674 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7675 struct sk_buff *skb;
7678 __skb_queue_head_init(&list);
7681 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7682 * remove this entry and rearrange the file array.
7684 skb = skb_dequeue(head);
7686 struct scm_fp_list *fp;
7688 fp = UNIXCB(skb).fp;
7689 for (i = 0; i < fp->count; i++) {
7692 if (fp->fp[i] != file)
7695 unix_notinflight(fp->user, fp->fp[i]);
7696 left = fp->count - 1 - i;
7698 memmove(&fp->fp[i], &fp->fp[i + 1],
7699 left * sizeof(struct file *));
7706 __skb_queue_tail(&list, skb);
7716 __skb_queue_tail(&list, skb);
7718 skb = skb_dequeue(head);
7721 if (skb_peek(&list)) {
7722 spin_lock_irq(&head->lock);
7723 while ((skb = __skb_dequeue(&list)) != NULL)
7724 __skb_queue_tail(head, skb);
7725 spin_unlock_irq(&head->lock);
7732 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7734 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7735 struct io_ring_ctx *ctx = rsrc_data->ctx;
7736 struct io_rsrc_put *prsrc, *tmp;
7738 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7739 list_del(&prsrc->list);
7740 ref_node->rsrc_put(ctx, prsrc);
7744 percpu_ref_exit(&ref_node->refs);
7746 percpu_ref_put(&rsrc_data->refs);
7749 static void io_rsrc_put_work(struct work_struct *work)
7751 struct io_ring_ctx *ctx;
7752 struct llist_node *node;
7754 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7755 node = llist_del_all(&ctx->rsrc_put_llist);
7758 struct fixed_rsrc_ref_node *ref_node;
7759 struct llist_node *next = node->next;
7761 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7762 __io_rsrc_put_work(ref_node);
7767 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7769 struct fixed_rsrc_ref_node *ref_node;
7770 struct fixed_rsrc_data *data;
7771 struct io_ring_ctx *ctx;
7772 bool first_add = false;
7775 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7776 data = ref_node->rsrc_data;
7779 io_rsrc_ref_lock(ctx);
7780 ref_node->done = true;
7782 while (!list_empty(&ctx->rsrc_ref_list)) {
7783 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7784 struct fixed_rsrc_ref_node, node);
7785 /* recycle ref nodes in order */
7786 if (!ref_node->done)
7788 list_del(&ref_node->node);
7789 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7791 io_rsrc_ref_unlock(ctx);
7793 if (percpu_ref_is_dying(&data->refs))
7797 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7799 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7802 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7803 struct io_ring_ctx *ctx)
7805 struct fixed_rsrc_ref_node *ref_node;
7807 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7811 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7816 INIT_LIST_HEAD(&ref_node->node);
7817 INIT_LIST_HEAD(&ref_node->rsrc_list);
7818 ref_node->done = false;
7822 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7823 struct fixed_rsrc_ref_node *ref_node)
7825 ref_node->rsrc_data = ctx->file_data;
7826 ref_node->rsrc_put = io_ring_file_put;
7829 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7831 percpu_ref_exit(&ref_node->refs);
7835 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7838 __s32 __user *fds = (__s32 __user *) arg;
7839 unsigned nr_tables, i;
7841 int fd, ret = -ENOMEM;
7842 struct fixed_rsrc_ref_node *ref_node;
7843 struct fixed_rsrc_data *file_data;
7849 if (nr_args > IORING_MAX_FIXED_FILES)
7852 file_data = alloc_fixed_rsrc_data(ctx);
7855 ctx->file_data = file_data;
7857 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7858 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7860 if (!file_data->table)
7863 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7866 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7867 struct fixed_rsrc_table *table;
7870 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7874 /* allow sparse sets */
7884 * Don't allow io_uring instances to be registered. If UNIX
7885 * isn't enabled, then this causes a reference cycle and this
7886 * instance can never get freed. If UNIX is enabled we'll
7887 * handle it just fine, but there's still no point in allowing
7888 * a ring fd as it doesn't support regular read/write anyway.
7890 if (file->f_op == &io_uring_fops) {
7894 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7895 index = i & IORING_FILE_TABLE_MASK;
7896 table->files[index] = file;
7899 ret = io_sqe_files_scm(ctx);
7901 io_sqe_files_unregister(ctx);
7905 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7907 io_sqe_files_unregister(ctx);
7910 init_fixed_file_ref_node(ctx, ref_node);
7912 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7915 for (i = 0; i < ctx->nr_user_files; i++) {
7916 file = io_file_from_index(ctx, i);
7920 for (i = 0; i < nr_tables; i++)
7921 kfree(file_data->table[i].files);
7922 ctx->nr_user_files = 0;
7924 free_fixed_rsrc_data(ctx->file_data);
7925 ctx->file_data = NULL;
7929 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7932 #if defined(CONFIG_UNIX)
7933 struct sock *sock = ctx->ring_sock->sk;
7934 struct sk_buff_head *head = &sock->sk_receive_queue;
7935 struct sk_buff *skb;
7938 * See if we can merge this file into an existing skb SCM_RIGHTS
7939 * file set. If there's no room, fall back to allocating a new skb
7940 * and filling it in.
7942 spin_lock_irq(&head->lock);
7943 skb = skb_peek(head);
7945 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7947 if (fpl->count < SCM_MAX_FD) {
7948 __skb_unlink(skb, head);
7949 spin_unlock_irq(&head->lock);
7950 fpl->fp[fpl->count] = get_file(file);
7951 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7953 spin_lock_irq(&head->lock);
7954 __skb_queue_head(head, skb);
7959 spin_unlock_irq(&head->lock);
7966 return __io_sqe_files_scm(ctx, 1, index);
7972 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7974 struct io_rsrc_put *prsrc;
7975 struct fixed_rsrc_ref_node *ref_node = data->node;
7977 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7982 list_add(&prsrc->list, &ref_node->rsrc_list);
7987 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7990 return io_queue_rsrc_removal(data, (void *)file);
7993 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7994 struct io_uring_rsrc_update *up,
7997 struct fixed_rsrc_data *data = ctx->file_data;
7998 struct fixed_rsrc_ref_node *ref_node;
8003 bool needs_switch = false;
8005 if (check_add_overflow(up->offset, nr_args, &done))
8007 if (done > ctx->nr_user_files)
8010 ref_node = alloc_fixed_rsrc_ref_node(ctx);
8013 init_fixed_file_ref_node(ctx, ref_node);
8015 fds = u64_to_user_ptr(up->data);
8016 for (done = 0; done < nr_args; done++) {
8017 struct fixed_rsrc_table *table;
8021 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
8025 if (fd == IORING_REGISTER_FILES_SKIP)
8028 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8029 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8030 index = i & IORING_FILE_TABLE_MASK;
8031 if (table->files[index]) {
8032 file = table->files[index];
8033 err = io_queue_file_removal(data, file);
8036 table->files[index] = NULL;
8037 needs_switch = true;
8046 * Don't allow io_uring instances to be registered. If
8047 * UNIX isn't enabled, then this causes a reference
8048 * cycle and this instance can never get freed. If UNIX
8049 * is enabled we'll handle it just fine, but there's
8050 * still no point in allowing a ring fd as it doesn't
8051 * support regular read/write anyway.
8053 if (file->f_op == &io_uring_fops) {
8058 table->files[index] = file;
8059 err = io_sqe_file_register(ctx, file, i);
8061 table->files[index] = NULL;
8069 percpu_ref_kill(&data->node->refs);
8070 io_sqe_rsrc_set_node(ctx, data, ref_node);
8072 destroy_fixed_rsrc_ref_node(ref_node);
8074 return done ? done : err;
8077 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
8080 struct io_uring_rsrc_update up;
8082 if (!ctx->file_data)
8086 if (copy_from_user(&up, arg, sizeof(up)))
8091 return __io_sqe_files_update(ctx, &up, nr_args);
8094 static void io_free_work(struct io_wq_work *work)
8096 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8098 /* Consider that io_steal_work() relies on this ref */
8102 static int io_init_wq_offload(struct io_ring_ctx *ctx,
8103 struct io_uring_params *p)
8105 struct io_wq_data data;
8107 struct io_ring_ctx *ctx_attach;
8108 unsigned int concurrency;
8111 data.user = ctx->user;
8112 data.free_work = io_free_work;
8113 data.do_work = io_wq_submit_work;
8115 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
8116 /* Do QD, or 4 * CPUS, whatever is smallest */
8117 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8119 ctx->io_wq = io_wq_create(concurrency, &data);
8120 if (IS_ERR(ctx->io_wq)) {
8121 ret = PTR_ERR(ctx->io_wq);
8127 f = fdget(p->wq_fd);
8131 if (f.file->f_op != &io_uring_fops) {
8136 ctx_attach = f.file->private_data;
8137 /* @io_wq is protected by holding the fd */
8138 if (!io_wq_get(ctx_attach->io_wq, &data)) {
8143 ctx->io_wq = ctx_attach->io_wq;
8149 static int io_uring_alloc_task_context(struct task_struct *task)
8151 struct io_uring_task *tctx;
8154 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
8155 if (unlikely(!tctx))
8158 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8159 if (unlikely(ret)) {
8165 init_waitqueue_head(&tctx->wait);
8167 atomic_set(&tctx->in_idle, 0);
8168 tctx->sqpoll = false;
8169 io_init_identity(&tctx->__identity);
8170 tctx->identity = &tctx->__identity;
8171 task->io_uring = tctx;
8175 void __io_uring_free(struct task_struct *tsk)
8177 struct io_uring_task *tctx = tsk->io_uring;
8179 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8180 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
8181 if (tctx->identity != &tctx->__identity)
8182 kfree(tctx->identity);
8183 percpu_counter_destroy(&tctx->inflight);
8185 tsk->io_uring = NULL;
8188 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8189 struct io_uring_params *p)
8193 if (ctx->flags & IORING_SETUP_SQPOLL) {
8194 struct io_sq_data *sqd;
8197 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
8200 sqd = io_get_sq_data(p);
8207 io_sq_thread_park(sqd);
8208 mutex_lock(&sqd->ctx_lock);
8209 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
8210 mutex_unlock(&sqd->ctx_lock);
8211 io_sq_thread_unpark(sqd);
8213 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8214 if (!ctx->sq_thread_idle)
8215 ctx->sq_thread_idle = HZ;
8220 if (p->flags & IORING_SETUP_SQ_AFF) {
8221 int cpu = p->sq_thread_cpu;
8224 if (cpu >= nr_cpu_ids)
8226 if (!cpu_online(cpu))
8229 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8230 cpu, "io_uring-sq");
8232 sqd->thread = kthread_create(io_sq_thread, sqd,
8235 if (IS_ERR(sqd->thread)) {
8236 ret = PTR_ERR(sqd->thread);
8240 ret = io_uring_alloc_task_context(sqd->thread);
8243 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8244 /* Can't have SQ_AFF without SQPOLL */
8250 ret = io_init_wq_offload(ctx, p);
8256 io_finish_async(ctx);
8260 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8262 struct io_sq_data *sqd = ctx->sq_data;
8264 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8265 wake_up_process(sqd->thread);
8268 static inline void __io_unaccount_mem(struct user_struct *user,
8269 unsigned long nr_pages)
8271 atomic_long_sub(nr_pages, &user->locked_vm);
8274 static inline int __io_account_mem(struct user_struct *user,
8275 unsigned long nr_pages)
8277 unsigned long page_limit, cur_pages, new_pages;
8279 /* Don't allow more pages than we can safely lock */
8280 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8283 cur_pages = atomic_long_read(&user->locked_vm);
8284 new_pages = cur_pages + nr_pages;
8285 if (new_pages > page_limit)
8287 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8288 new_pages) != cur_pages);
8293 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8294 enum io_mem_account acct)
8297 __io_unaccount_mem(ctx->user, nr_pages);
8299 if (ctx->mm_account) {
8300 if (acct == ACCT_LOCKED) {
8301 mmap_write_lock(ctx->mm_account);
8302 ctx->mm_account->locked_vm -= nr_pages;
8303 mmap_write_unlock(ctx->mm_account);
8304 }else if (acct == ACCT_PINNED) {
8305 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8310 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8311 enum io_mem_account acct)
8315 if (ctx->limit_mem) {
8316 ret = __io_account_mem(ctx->user, nr_pages);
8321 if (ctx->mm_account) {
8322 if (acct == ACCT_LOCKED) {
8323 mmap_write_lock(ctx->mm_account);
8324 ctx->mm_account->locked_vm += nr_pages;
8325 mmap_write_unlock(ctx->mm_account);
8326 } else if (acct == ACCT_PINNED) {
8327 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8334 static void io_mem_free(void *ptr)
8341 page = virt_to_head_page(ptr);
8342 if (put_page_testzero(page))
8343 free_compound_page(page);
8346 static void *io_mem_alloc(size_t size)
8348 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8351 return (void *) __get_free_pages(gfp_flags, get_order(size));
8354 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8357 struct io_rings *rings;
8358 size_t off, sq_array_size;
8360 off = struct_size(rings, cqes, cq_entries);
8361 if (off == SIZE_MAX)
8365 off = ALIGN(off, SMP_CACHE_BYTES);
8373 sq_array_size = array_size(sizeof(u32), sq_entries);
8374 if (sq_array_size == SIZE_MAX)
8377 if (check_add_overflow(off, sq_array_size, &off))
8383 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
8387 pages = (size_t)1 << get_order(
8388 rings_size(sq_entries, cq_entries, NULL));
8389 pages += (size_t)1 << get_order(
8390 array_size(sizeof(struct io_uring_sqe), sq_entries));
8395 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8399 if (!ctx->user_bufs)
8402 for (i = 0; i < ctx->nr_user_bufs; i++) {
8403 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8405 for (j = 0; j < imu->nr_bvecs; j++)
8406 unpin_user_page(imu->bvec[j].bv_page);
8408 if (imu->acct_pages)
8409 io_unaccount_mem(ctx, imu->acct_pages, ACCT_PINNED);
8414 kfree(ctx->user_bufs);
8415 ctx->user_bufs = NULL;
8416 ctx->nr_user_bufs = 0;
8420 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8421 void __user *arg, unsigned index)
8423 struct iovec __user *src;
8425 #ifdef CONFIG_COMPAT
8427 struct compat_iovec __user *ciovs;
8428 struct compat_iovec ciov;
8430 ciovs = (struct compat_iovec __user *) arg;
8431 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8434 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8435 dst->iov_len = ciov.iov_len;
8439 src = (struct iovec __user *) arg;
8440 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8446 * Not super efficient, but this is just a registration time. And we do cache
8447 * the last compound head, so generally we'll only do a full search if we don't
8450 * We check if the given compound head page has already been accounted, to
8451 * avoid double accounting it. This allows us to account the full size of the
8452 * page, not just the constituent pages of a huge page.
8454 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8455 int nr_pages, struct page *hpage)
8459 /* check current page array */
8460 for (i = 0; i < nr_pages; i++) {
8461 if (!PageCompound(pages[i]))
8463 if (compound_head(pages[i]) == hpage)
8467 /* check previously registered pages */
8468 for (i = 0; i < ctx->nr_user_bufs; i++) {
8469 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8471 for (j = 0; j < imu->nr_bvecs; j++) {
8472 if (!PageCompound(imu->bvec[j].bv_page))
8474 if (compound_head(imu->bvec[j].bv_page) == hpage)
8482 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8483 int nr_pages, struct io_mapped_ubuf *imu,
8484 struct page **last_hpage)
8488 for (i = 0; i < nr_pages; i++) {
8489 if (!PageCompound(pages[i])) {
8494 hpage = compound_head(pages[i]);
8495 if (hpage == *last_hpage)
8497 *last_hpage = hpage;
8498 if (headpage_already_acct(ctx, pages, i, hpage))
8500 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8504 if (!imu->acct_pages)
8507 ret = io_account_mem(ctx, imu->acct_pages, ACCT_PINNED);
8509 imu->acct_pages = 0;
8513 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8514 struct io_mapped_ubuf *imu,
8515 struct page **last_hpage)
8517 struct vm_area_struct **vmas = NULL;
8518 struct page **pages = NULL;
8519 unsigned long off, start, end, ubuf;
8521 int ret, pret, nr_pages, i;
8523 ubuf = (unsigned long) iov->iov_base;
8524 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8525 start = ubuf >> PAGE_SHIFT;
8526 nr_pages = end - start;
8530 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8534 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8539 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8545 mmap_read_lock(current->mm);
8546 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8548 if (pret == nr_pages) {
8549 /* don't support file backed memory */
8550 for (i = 0; i < nr_pages; i++) {
8551 struct vm_area_struct *vma = vmas[i];
8554 !is_file_hugepages(vma->vm_file)) {
8560 ret = pret < 0 ? pret : -EFAULT;
8562 mmap_read_unlock(current->mm);
8565 * if we did partial map, or found file backed vmas,
8566 * release any pages we did get
8569 unpin_user_pages(pages, pret);
8574 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8576 unpin_user_pages(pages, pret);
8581 off = ubuf & ~PAGE_MASK;
8582 size = iov->iov_len;
8583 for (i = 0; i < nr_pages; i++) {
8586 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8587 imu->bvec[i].bv_page = pages[i];
8588 imu->bvec[i].bv_len = vec_len;
8589 imu->bvec[i].bv_offset = off;
8593 /* store original address for later verification */
8595 imu->len = iov->iov_len;
8596 imu->nr_bvecs = nr_pages;
8604 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8608 if (!nr_args || nr_args > UIO_MAXIOV)
8611 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8613 if (!ctx->user_bufs)
8619 static int io_buffer_validate(struct iovec *iov)
8622 * Don't impose further limits on the size and buffer
8623 * constraints here, we'll -EINVAL later when IO is
8624 * submitted if they are wrong.
8626 if (!iov->iov_base || !iov->iov_len)
8629 /* arbitrary limit, but we need something */
8630 if (iov->iov_len > SZ_1G)
8636 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8637 unsigned int nr_args)
8641 struct page *last_hpage = NULL;
8643 ret = io_buffers_map_alloc(ctx, nr_args);
8647 for (i = 0; i < nr_args; i++) {
8648 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8650 ret = io_copy_iov(ctx, &iov, arg, i);
8654 ret = io_buffer_validate(&iov);
8658 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8662 ctx->nr_user_bufs++;
8666 io_sqe_buffers_unregister(ctx);
8671 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8673 __s32 __user *fds = arg;
8679 if (copy_from_user(&fd, fds, sizeof(*fds)))
8682 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8683 if (IS_ERR(ctx->cq_ev_fd)) {
8684 int ret = PTR_ERR(ctx->cq_ev_fd);
8685 ctx->cq_ev_fd = NULL;
8692 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8694 if (ctx->cq_ev_fd) {
8695 eventfd_ctx_put(ctx->cq_ev_fd);
8696 ctx->cq_ev_fd = NULL;
8703 static int __io_destroy_buffers(int id, void *p, void *data)
8705 struct io_ring_ctx *ctx = data;
8706 struct io_buffer *buf = p;
8708 __io_remove_buffers(ctx, buf, id, -1U);
8712 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8714 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8715 idr_destroy(&ctx->io_buffer_idr);
8718 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8720 io_finish_async(ctx);
8721 io_sqe_buffers_unregister(ctx);
8723 if (ctx->sqo_task) {
8724 put_task_struct(ctx->sqo_task);
8725 ctx->sqo_task = NULL;
8726 mmdrop(ctx->mm_account);
8727 ctx->mm_account = NULL;
8730 #ifdef CONFIG_BLK_CGROUP
8731 if (ctx->sqo_blkcg_css)
8732 css_put(ctx->sqo_blkcg_css);
8735 io_sqe_files_unregister(ctx);
8736 io_eventfd_unregister(ctx);
8737 io_destroy_buffers(ctx);
8738 idr_destroy(&ctx->personality_idr);
8740 #if defined(CONFIG_UNIX)
8741 if (ctx->ring_sock) {
8742 ctx->ring_sock->file = NULL; /* so that iput() is called */
8743 sock_release(ctx->ring_sock);
8747 io_mem_free(ctx->rings);
8748 io_mem_free(ctx->sq_sqes);
8750 percpu_ref_exit(&ctx->refs);
8751 free_uid(ctx->user);
8752 put_cred(ctx->creds);
8753 kfree(ctx->cancel_hash);
8754 kmem_cache_free(req_cachep, ctx->fallback_req);
8758 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8760 struct io_ring_ctx *ctx = file->private_data;
8763 poll_wait(file, &ctx->cq_wait, wait);
8765 * synchronizes with barrier from wq_has_sleeper call in
8769 if (!io_sqring_full(ctx))
8770 mask |= EPOLLOUT | EPOLLWRNORM;
8771 io_cqring_overflow_flush(ctx, false, NULL, NULL);
8772 if (io_cqring_events(ctx))
8773 mask |= EPOLLIN | EPOLLRDNORM;
8778 static int io_uring_fasync(int fd, struct file *file, int on)
8780 struct io_ring_ctx *ctx = file->private_data;
8782 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8785 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8787 struct io_identity *iod;
8789 iod = idr_remove(&ctx->personality_idr, id);
8791 put_cred(iod->creds);
8792 if (refcount_dec_and_test(&iod->count))
8800 static int io_remove_personalities(int id, void *p, void *data)
8802 struct io_ring_ctx *ctx = data;
8804 io_unregister_personality(ctx, id);
8808 static void io_ring_exit_work(struct work_struct *work)
8810 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8814 * If we're doing polled IO and end up having requests being
8815 * submitted async (out-of-line), then completions can come in while
8816 * we're waiting for refs to drop. We need to reap these manually,
8817 * as nobody else will be looking for them.
8820 io_uring_try_cancel_requests(ctx, NULL, NULL);
8821 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8822 io_ring_ctx_free(ctx);
8825 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8827 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8829 return req->ctx == data;
8832 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8834 mutex_lock(&ctx->uring_lock);
8835 percpu_ref_kill(&ctx->refs);
8837 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8840 /* if force is set, the ring is going away. always drop after that */
8841 ctx->cq_overflow_flushed = 1;
8843 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8844 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8845 mutex_unlock(&ctx->uring_lock);
8847 io_kill_timeouts(ctx, NULL, NULL);
8848 io_poll_remove_all(ctx, NULL, NULL);
8851 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8853 /* if we failed setting up the ctx, we might not have any rings */
8854 io_iopoll_try_reap_events(ctx);
8857 * Do this upfront, so we won't have a grace period where the ring
8858 * is closed but resources aren't reaped yet. This can cause
8859 * spurious failure in setting up a new ring.
8861 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
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);
8995 prepare_to_wait(&task->io_uring->wait, &wait,
8996 TASK_UNINTERRUPTIBLE);
8997 if (inflight == io_uring_count_inflight(ctx, task, files))
8999 finish_wait(&task->io_uring->wait, &wait);
9003 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
9005 mutex_lock(&ctx->uring_lock);
9007 mutex_unlock(&ctx->uring_lock);
9009 /* make sure callers enter the ring to get error */
9011 io_ring_set_wakeup_flag(ctx);
9015 * We need to iteratively cancel requests, in case a request has dependent
9016 * hard links. These persist even for failure of cancelations, hence keep
9017 * looping until none are found.
9019 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
9020 struct files_struct *files)
9022 struct task_struct *task = current;
9024 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9025 io_disable_sqo_submit(ctx);
9026 task = ctx->sq_data->thread;
9027 atomic_inc(&task->io_uring->in_idle);
9028 io_sq_thread_park(ctx->sq_data);
9031 io_cancel_defer_files(ctx, task, files);
9033 io_uring_cancel_files(ctx, task, files);
9035 io_uring_try_cancel_requests(ctx, task, NULL);
9037 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9038 atomic_dec(&task->io_uring->in_idle);
9040 * If the files that are going away are the ones in the thread
9041 * identity, clear them out.
9043 if (task->io_uring->identity->files == files)
9044 task->io_uring->identity->files = NULL;
9045 io_sq_thread_unpark(ctx->sq_data);
9050 * Note that this task has used io_uring. We use it for cancelation purposes.
9052 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
9054 struct io_uring_task *tctx = current->io_uring;
9057 if (unlikely(!tctx)) {
9058 ret = io_uring_alloc_task_context(current);
9061 tctx = current->io_uring;
9063 if (tctx->last != file) {
9064 void *old = xa_load(&tctx->xa, (unsigned long)file);
9068 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
9075 /* one and only SQPOLL file note, held by sqo_task */
9076 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
9077 current != ctx->sqo_task);
9083 * This is race safe in that the task itself is doing this, hence it
9084 * cannot be going through the exit/cancel paths at the same time.
9085 * This cannot be modified while exit/cancel is running.
9087 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
9088 tctx->sqpoll = true;
9094 * Remove this io_uring_file -> task mapping.
9096 static void io_uring_del_task_file(struct file *file)
9098 struct io_uring_task *tctx = current->io_uring;
9100 if (tctx->last == file)
9102 file = xa_erase(&tctx->xa, (unsigned long)file);
9107 static void io_uring_remove_task_files(struct io_uring_task *tctx)
9110 unsigned long index;
9112 xa_for_each(&tctx->xa, index, file)
9113 io_uring_del_task_file(file);
9116 void __io_uring_files_cancel(struct files_struct *files)
9118 struct io_uring_task *tctx = current->io_uring;
9120 unsigned long index;
9122 /* make sure overflow events are dropped */
9123 atomic_inc(&tctx->in_idle);
9124 xa_for_each(&tctx->xa, index, file)
9125 io_uring_cancel_task_requests(file->private_data, files);
9126 atomic_dec(&tctx->in_idle);
9129 io_uring_remove_task_files(tctx);
9132 static s64 tctx_inflight(struct io_uring_task *tctx)
9134 unsigned long index;
9138 inflight = percpu_counter_sum(&tctx->inflight);
9143 * If we have SQPOLL rings, then we need to iterate and find them, and
9144 * add the pending count for those.
9146 xa_for_each(&tctx->xa, index, file) {
9147 struct io_ring_ctx *ctx = file->private_data;
9149 if (ctx->flags & IORING_SETUP_SQPOLL) {
9150 struct io_uring_task *__tctx = ctx->sqo_task->io_uring;
9152 inflight += percpu_counter_sum(&__tctx->inflight);
9160 * Find any io_uring fd that this task has registered or done IO on, and cancel
9163 void __io_uring_task_cancel(void)
9165 struct io_uring_task *tctx = current->io_uring;
9169 /* make sure overflow events are dropped */
9170 atomic_inc(&tctx->in_idle);
9172 /* trigger io_disable_sqo_submit() */
9174 __io_uring_files_cancel(NULL);
9177 /* read completions before cancelations */
9178 inflight = tctx_inflight(tctx);
9181 __io_uring_files_cancel(NULL);
9183 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9186 * If we've seen completions, retry without waiting. This
9187 * avoids a race where a completion comes in before we did
9188 * prepare_to_wait().
9190 if (inflight == tctx_inflight(tctx))
9192 finish_wait(&tctx->wait, &wait);
9195 atomic_dec(&tctx->in_idle);
9197 io_uring_remove_task_files(tctx);
9200 static int io_uring_flush(struct file *file, void *data)
9202 struct io_uring_task *tctx = current->io_uring;
9203 struct io_ring_ctx *ctx = file->private_data;
9205 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
9206 io_uring_cancel_task_requests(ctx, NULL);
9211 /* we should have cancelled and erased it before PF_EXITING */
9212 WARN_ON_ONCE((current->flags & PF_EXITING) &&
9213 xa_load(&tctx->xa, (unsigned long)file));
9216 * fput() is pending, will be 2 if the only other ref is our potential
9217 * task file note. If the task is exiting, drop regardless of count.
9219 if (atomic_long_read(&file->f_count) != 2)
9222 if (ctx->flags & IORING_SETUP_SQPOLL) {
9223 /* there is only one file note, which is owned by sqo_task */
9224 WARN_ON_ONCE(ctx->sqo_task != current &&
9225 xa_load(&tctx->xa, (unsigned long)file));
9226 /* sqo_dead check is for when this happens after cancellation */
9227 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
9228 !xa_load(&tctx->xa, (unsigned long)file));
9230 io_disable_sqo_submit(ctx);
9233 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
9234 io_uring_del_task_file(file);
9238 static void *io_uring_validate_mmap_request(struct file *file,
9239 loff_t pgoff, size_t sz)
9241 struct io_ring_ctx *ctx = file->private_data;
9242 loff_t offset = pgoff << PAGE_SHIFT;
9247 case IORING_OFF_SQ_RING:
9248 case IORING_OFF_CQ_RING:
9251 case IORING_OFF_SQES:
9255 return ERR_PTR(-EINVAL);
9258 page = virt_to_head_page(ptr);
9259 if (sz > page_size(page))
9260 return ERR_PTR(-EINVAL);
9267 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9269 size_t sz = vma->vm_end - vma->vm_start;
9273 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9275 return PTR_ERR(ptr);
9277 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9278 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9281 #else /* !CONFIG_MMU */
9283 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9285 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9288 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9290 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9293 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9294 unsigned long addr, unsigned long len,
9295 unsigned long pgoff, unsigned long flags)
9299 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9301 return PTR_ERR(ptr);
9303 return (unsigned long) ptr;
9306 #endif /* !CONFIG_MMU */
9308 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9314 if (!io_sqring_full(ctx))
9317 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9319 if (unlikely(ctx->sqo_dead)) {
9324 if (!io_sqring_full(ctx))
9328 } while (!signal_pending(current));
9330 finish_wait(&ctx->sqo_sq_wait, &wait);
9335 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9336 struct __kernel_timespec __user **ts,
9337 const sigset_t __user **sig)
9339 struct io_uring_getevents_arg arg;
9342 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9343 * is just a pointer to the sigset_t.
9345 if (!(flags & IORING_ENTER_EXT_ARG)) {
9346 *sig = (const sigset_t __user *) argp;
9352 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9353 * timespec and sigset_t pointers if good.
9355 if (*argsz != sizeof(arg))
9357 if (copy_from_user(&arg, argp, sizeof(arg)))
9359 *sig = u64_to_user_ptr(arg.sigmask);
9360 *argsz = arg.sigmask_sz;
9361 *ts = u64_to_user_ptr(arg.ts);
9365 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9366 u32, min_complete, u32, flags, const void __user *, argp,
9369 struct io_ring_ctx *ctx;
9376 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9377 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9385 if (f.file->f_op != &io_uring_fops)
9389 ctx = f.file->private_data;
9390 if (!percpu_ref_tryget(&ctx->refs))
9394 if (ctx->flags & IORING_SETUP_R_DISABLED)
9398 * For SQ polling, the thread will do all submissions and completions.
9399 * Just return the requested submit count, and wake the thread if
9403 if (ctx->flags & IORING_SETUP_SQPOLL) {
9404 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9407 if (unlikely(ctx->sqo_dead))
9409 if (flags & IORING_ENTER_SQ_WAKEUP)
9410 wake_up(&ctx->sq_data->wait);
9411 if (flags & IORING_ENTER_SQ_WAIT) {
9412 ret = io_sqpoll_wait_sq(ctx);
9416 submitted = to_submit;
9417 } else if (to_submit) {
9418 ret = io_uring_add_task_file(ctx, f.file);
9421 mutex_lock(&ctx->uring_lock);
9422 submitted = io_submit_sqes(ctx, to_submit);
9423 mutex_unlock(&ctx->uring_lock);
9425 if (submitted != to_submit)
9428 if (flags & IORING_ENTER_GETEVENTS) {
9429 const sigset_t __user *sig;
9430 struct __kernel_timespec __user *ts;
9432 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9436 min_complete = min(min_complete, ctx->cq_entries);
9439 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9440 * space applications don't need to do io completion events
9441 * polling again, they can rely on io_sq_thread to do polling
9442 * work, which can reduce cpu usage and uring_lock contention.
9444 if (ctx->flags & IORING_SETUP_IOPOLL &&
9445 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9446 ret = io_iopoll_check(ctx, min_complete);
9448 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9453 percpu_ref_put(&ctx->refs);
9456 return submitted ? submitted : ret;
9459 #ifdef CONFIG_PROC_FS
9460 static int io_uring_show_cred(int id, void *p, void *data)
9462 struct io_identity *iod = p;
9463 const struct cred *cred = iod->creds;
9464 struct seq_file *m = data;
9465 struct user_namespace *uns = seq_user_ns(m);
9466 struct group_info *gi;
9471 seq_printf(m, "%5d\n", id);
9472 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9473 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9474 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9475 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9476 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9477 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9478 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9479 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9480 seq_puts(m, "\n\tGroups:\t");
9481 gi = cred->group_info;
9482 for (g = 0; g < gi->ngroups; g++) {
9483 seq_put_decimal_ull(m, g ? " " : "",
9484 from_kgid_munged(uns, gi->gid[g]));
9486 seq_puts(m, "\n\tCapEff:\t");
9487 cap = cred->cap_effective;
9488 CAP_FOR_EACH_U32(__capi)
9489 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9494 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9496 struct io_sq_data *sq = NULL;
9501 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9502 * since fdinfo case grabs it in the opposite direction of normal use
9503 * cases. If we fail to get the lock, we just don't iterate any
9504 * structures that could be going away outside the io_uring mutex.
9506 has_lock = mutex_trylock(&ctx->uring_lock);
9508 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9511 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9512 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9513 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9514 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9515 struct fixed_rsrc_table *table;
9518 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
9519 f = table->files[i & IORING_FILE_TABLE_MASK];
9521 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9523 seq_printf(m, "%5u: <none>\n", i);
9525 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9526 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9527 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9529 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9530 (unsigned int) buf->len);
9532 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9533 seq_printf(m, "Personalities:\n");
9534 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9536 seq_printf(m, "PollList:\n");
9537 spin_lock_irq(&ctx->completion_lock);
9538 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9539 struct hlist_head *list = &ctx->cancel_hash[i];
9540 struct io_kiocb *req;
9542 hlist_for_each_entry(req, list, hash_node)
9543 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9544 req->task->task_works != NULL);
9546 spin_unlock_irq(&ctx->completion_lock);
9548 mutex_unlock(&ctx->uring_lock);
9551 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9553 struct io_ring_ctx *ctx = f->private_data;
9555 if (percpu_ref_tryget(&ctx->refs)) {
9556 __io_uring_show_fdinfo(ctx, m);
9557 percpu_ref_put(&ctx->refs);
9562 static const struct file_operations io_uring_fops = {
9563 .release = io_uring_release,
9564 .flush = io_uring_flush,
9565 .mmap = io_uring_mmap,
9567 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9568 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9570 .poll = io_uring_poll,
9571 .fasync = io_uring_fasync,
9572 #ifdef CONFIG_PROC_FS
9573 .show_fdinfo = io_uring_show_fdinfo,
9577 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9578 struct io_uring_params *p)
9580 struct io_rings *rings;
9581 size_t size, sq_array_offset;
9583 /* make sure these are sane, as we already accounted them */
9584 ctx->sq_entries = p->sq_entries;
9585 ctx->cq_entries = p->cq_entries;
9587 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9588 if (size == SIZE_MAX)
9591 rings = io_mem_alloc(size);
9596 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9597 rings->sq_ring_mask = p->sq_entries - 1;
9598 rings->cq_ring_mask = p->cq_entries - 1;
9599 rings->sq_ring_entries = p->sq_entries;
9600 rings->cq_ring_entries = p->cq_entries;
9601 ctx->sq_mask = rings->sq_ring_mask;
9602 ctx->cq_mask = rings->cq_ring_mask;
9604 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9605 if (size == SIZE_MAX) {
9606 io_mem_free(ctx->rings);
9611 ctx->sq_sqes = io_mem_alloc(size);
9612 if (!ctx->sq_sqes) {
9613 io_mem_free(ctx->rings);
9621 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9625 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9629 ret = io_uring_add_task_file(ctx, file);
9634 fd_install(fd, file);
9639 * Allocate an anonymous fd, this is what constitutes the application
9640 * visible backing of an io_uring instance. The application mmaps this
9641 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9642 * we have to tie this fd to a socket for file garbage collection purposes.
9644 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9647 #if defined(CONFIG_UNIX)
9650 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9653 return ERR_PTR(ret);
9656 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9657 O_RDWR | O_CLOEXEC);
9658 #if defined(CONFIG_UNIX)
9660 sock_release(ctx->ring_sock);
9661 ctx->ring_sock = NULL;
9663 ctx->ring_sock->file = file;
9669 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9670 struct io_uring_params __user *params)
9672 struct user_struct *user = NULL;
9673 struct io_ring_ctx *ctx;
9680 if (entries > IORING_MAX_ENTRIES) {
9681 if (!(p->flags & IORING_SETUP_CLAMP))
9683 entries = IORING_MAX_ENTRIES;
9687 * Use twice as many entries for the CQ ring. It's possible for the
9688 * application to drive a higher depth than the size of the SQ ring,
9689 * since the sqes are only used at submission time. This allows for
9690 * some flexibility in overcommitting a bit. If the application has
9691 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9692 * of CQ ring entries manually.
9694 p->sq_entries = roundup_pow_of_two(entries);
9695 if (p->flags & IORING_SETUP_CQSIZE) {
9697 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9698 * to a power-of-two, if it isn't already. We do NOT impose
9699 * any cq vs sq ring sizing.
9703 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9704 if (!(p->flags & IORING_SETUP_CLAMP))
9706 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9708 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9709 if (p->cq_entries < p->sq_entries)
9712 p->cq_entries = 2 * p->sq_entries;
9715 user = get_uid(current_user());
9716 limit_mem = !capable(CAP_IPC_LOCK);
9719 ret = __io_account_mem(user,
9720 ring_pages(p->sq_entries, p->cq_entries));
9727 ctx = io_ring_ctx_alloc(p);
9730 __io_unaccount_mem(user, ring_pages(p->sq_entries,
9735 ctx->compat = in_compat_syscall();
9737 ctx->creds = get_current_cred();
9739 ctx->loginuid = current->loginuid;
9740 ctx->sessionid = current->sessionid;
9742 ctx->sqo_task = get_task_struct(current);
9745 * This is just grabbed for accounting purposes. When a process exits,
9746 * the mm is exited and dropped before the files, hence we need to hang
9747 * on to this mm purely for the purposes of being able to unaccount
9748 * memory (locked/pinned vm). It's not used for anything else.
9750 mmgrab(current->mm);
9751 ctx->mm_account = current->mm;
9753 #ifdef CONFIG_BLK_CGROUP
9755 * The sq thread will belong to the original cgroup it was inited in.
9756 * If the cgroup goes offline (e.g. disabling the io controller), then
9757 * issued bios will be associated with the closest cgroup later in the
9761 ctx->sqo_blkcg_css = blkcg_css();
9762 ret = css_tryget_online(ctx->sqo_blkcg_css);
9765 /* don't init against a dying cgroup, have the user try again */
9766 ctx->sqo_blkcg_css = NULL;
9773 * Account memory _before_ installing the file descriptor. Once
9774 * the descriptor is installed, it can get closed at any time. Also
9775 * do this before hitting the general error path, as ring freeing
9776 * will un-account as well.
9778 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9780 ctx->limit_mem = limit_mem;
9782 ret = io_allocate_scq_urings(ctx, p);
9786 ret = io_sq_offload_create(ctx, p);
9790 if (!(p->flags & IORING_SETUP_R_DISABLED))
9791 io_sq_offload_start(ctx);
9793 memset(&p->sq_off, 0, sizeof(p->sq_off));
9794 p->sq_off.head = offsetof(struct io_rings, sq.head);
9795 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9796 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9797 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9798 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9799 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9800 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9802 memset(&p->cq_off, 0, sizeof(p->cq_off));
9803 p->cq_off.head = offsetof(struct io_rings, cq.head);
9804 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9805 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9806 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9807 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9808 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9809 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9811 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9812 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9813 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9814 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9815 IORING_FEAT_EXT_ARG;
9817 if (copy_to_user(params, p, sizeof(*p))) {
9822 file = io_uring_get_file(ctx);
9824 ret = PTR_ERR(file);
9829 * Install ring fd as the very last thing, so we don't risk someone
9830 * having closed it before we finish setup
9832 ret = io_uring_install_fd(ctx, file);
9834 io_disable_sqo_submit(ctx);
9835 /* fput will clean it up */
9840 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9843 io_disable_sqo_submit(ctx);
9844 io_ring_ctx_wait_and_kill(ctx);
9849 * Sets up an aio uring context, and returns the fd. Applications asks for a
9850 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9851 * params structure passed in.
9853 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9855 struct io_uring_params p;
9858 if (copy_from_user(&p, params, sizeof(p)))
9860 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9865 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9866 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9867 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9868 IORING_SETUP_R_DISABLED))
9871 return io_uring_create(entries, &p, params);
9874 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9875 struct io_uring_params __user *, params)
9877 return io_uring_setup(entries, params);
9880 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9882 struct io_uring_probe *p;
9886 size = struct_size(p, ops, nr_args);
9887 if (size == SIZE_MAX)
9889 p = kzalloc(size, GFP_KERNEL);
9894 if (copy_from_user(p, arg, size))
9897 if (memchr_inv(p, 0, size))
9900 p->last_op = IORING_OP_LAST - 1;
9901 if (nr_args > IORING_OP_LAST)
9902 nr_args = IORING_OP_LAST;
9904 for (i = 0; i < nr_args; i++) {
9906 if (!io_op_defs[i].not_supported)
9907 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9912 if (copy_to_user(arg, p, size))
9919 static int io_register_personality(struct io_ring_ctx *ctx)
9921 struct io_identity *id;
9924 id = kmalloc(sizeof(*id), GFP_KERNEL);
9928 io_init_identity(id);
9929 id->creds = get_current_cred();
9931 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9933 put_cred(id->creds);
9939 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9940 unsigned int nr_args)
9942 struct io_uring_restriction *res;
9946 /* Restrictions allowed only if rings started disabled */
9947 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9950 /* We allow only a single restrictions registration */
9951 if (ctx->restrictions.registered)
9954 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9957 size = array_size(nr_args, sizeof(*res));
9958 if (size == SIZE_MAX)
9961 res = memdup_user(arg, size);
9963 return PTR_ERR(res);
9967 for (i = 0; i < nr_args; i++) {
9968 switch (res[i].opcode) {
9969 case IORING_RESTRICTION_REGISTER_OP:
9970 if (res[i].register_op >= IORING_REGISTER_LAST) {
9975 __set_bit(res[i].register_op,
9976 ctx->restrictions.register_op);
9978 case IORING_RESTRICTION_SQE_OP:
9979 if (res[i].sqe_op >= IORING_OP_LAST) {
9984 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9986 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9987 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9989 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9990 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9999 /* Reset all restrictions if an error happened */
10001 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10003 ctx->restrictions.registered = true;
10009 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10011 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10014 if (ctx->restrictions.registered)
10015 ctx->restricted = 1;
10017 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10019 io_sq_offload_start(ctx);
10024 static bool io_register_op_must_quiesce(int op)
10027 case IORING_UNREGISTER_FILES:
10028 case IORING_REGISTER_FILES_UPDATE:
10029 case IORING_REGISTER_PROBE:
10030 case IORING_REGISTER_PERSONALITY:
10031 case IORING_UNREGISTER_PERSONALITY:
10038 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10039 void __user *arg, unsigned nr_args)
10040 __releases(ctx->uring_lock)
10041 __acquires(ctx->uring_lock)
10046 * We're inside the ring mutex, if the ref is already dying, then
10047 * someone else killed the ctx or is already going through
10048 * io_uring_register().
10050 if (percpu_ref_is_dying(&ctx->refs))
10053 if (io_register_op_must_quiesce(opcode)) {
10054 percpu_ref_kill(&ctx->refs);
10057 * Drop uring mutex before waiting for references to exit. If
10058 * another thread is currently inside io_uring_enter() it might
10059 * need to grab the uring_lock to make progress. If we hold it
10060 * here across the drain wait, then we can deadlock. It's safe
10061 * to drop the mutex here, since no new references will come in
10062 * after we've killed the percpu ref.
10064 mutex_unlock(&ctx->uring_lock);
10066 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10069 ret = io_run_task_work_sig();
10074 mutex_lock(&ctx->uring_lock);
10077 percpu_ref_resurrect(&ctx->refs);
10082 if (ctx->restricted) {
10083 if (opcode >= IORING_REGISTER_LAST) {
10088 if (!test_bit(opcode, ctx->restrictions.register_op)) {
10095 case IORING_REGISTER_BUFFERS:
10096 ret = io_sqe_buffers_register(ctx, arg, nr_args);
10098 case IORING_UNREGISTER_BUFFERS:
10100 if (arg || nr_args)
10102 ret = io_sqe_buffers_unregister(ctx);
10104 case IORING_REGISTER_FILES:
10105 ret = io_sqe_files_register(ctx, arg, nr_args);
10107 case IORING_UNREGISTER_FILES:
10109 if (arg || nr_args)
10111 ret = io_sqe_files_unregister(ctx);
10113 case IORING_REGISTER_FILES_UPDATE:
10114 ret = io_sqe_files_update(ctx, arg, nr_args);
10116 case IORING_REGISTER_EVENTFD:
10117 case IORING_REGISTER_EVENTFD_ASYNC:
10121 ret = io_eventfd_register(ctx, arg);
10124 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10125 ctx->eventfd_async = 1;
10127 ctx->eventfd_async = 0;
10129 case IORING_UNREGISTER_EVENTFD:
10131 if (arg || nr_args)
10133 ret = io_eventfd_unregister(ctx);
10135 case IORING_REGISTER_PROBE:
10137 if (!arg || nr_args > 256)
10139 ret = io_probe(ctx, arg, nr_args);
10141 case IORING_REGISTER_PERSONALITY:
10143 if (arg || nr_args)
10145 ret = io_register_personality(ctx);
10147 case IORING_UNREGISTER_PERSONALITY:
10151 ret = io_unregister_personality(ctx, nr_args);
10153 case IORING_REGISTER_ENABLE_RINGS:
10155 if (arg || nr_args)
10157 ret = io_register_enable_rings(ctx);
10159 case IORING_REGISTER_RESTRICTIONS:
10160 ret = io_register_restrictions(ctx, arg, nr_args);
10168 if (io_register_op_must_quiesce(opcode)) {
10169 /* bring the ctx back to life */
10170 percpu_ref_reinit(&ctx->refs);
10172 reinit_completion(&ctx->ref_comp);
10177 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10178 void __user *, arg, unsigned int, nr_args)
10180 struct io_ring_ctx *ctx;
10189 if (f.file->f_op != &io_uring_fops)
10192 ctx = f.file->private_data;
10194 mutex_lock(&ctx->uring_lock);
10195 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10196 mutex_unlock(&ctx->uring_lock);
10197 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10198 ctx->cq_ev_fd != NULL, ret);
10204 static int __init io_uring_init(void)
10206 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10207 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10208 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10211 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10212 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10213 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10214 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10215 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10216 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10217 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10218 BUILD_BUG_SQE_ELEM(8, __u64, off);
10219 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10220 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10221 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10222 BUILD_BUG_SQE_ELEM(24, __u32, len);
10223 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10224 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10225 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10226 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10227 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10228 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10229 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10230 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10231 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10232 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10233 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10234 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10235 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10236 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10237 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10238 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10239 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10240 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10241 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10243 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10244 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10245 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
10248 __initcall(io_uring_init);