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_cqe (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/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/tracehook.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
93 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
96 #define IORING_MAX_FIXED_FILES (1U << 15)
97 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
98 IORING_REGISTER_LAST + IORING_OP_LAST)
100 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
101 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
102 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
104 #define IORING_MAX_REG_BUFFERS (1U << 14)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
109 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
110 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
112 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
115 u32 head ____cacheline_aligned_in_smp;
116 u32 tail ____cacheline_aligned_in_smp;
120 * This data is shared with the application through the mmap at offsets
121 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
123 * The offsets to the member fields are published through struct
124 * io_sqring_offsets when calling io_uring_setup.
128 * Head and tail offsets into the ring; the offsets need to be
129 * masked to get valid indices.
131 * The kernel controls head of the sq ring and the tail of the cq ring,
132 * and the application controls tail of the sq ring and the head of the
135 struct io_uring sq, cq;
137 * Bitmasks to apply to head and tail offsets (constant, equals
140 u32 sq_ring_mask, cq_ring_mask;
141 /* Ring sizes (constant, power of 2) */
142 u32 sq_ring_entries, cq_ring_entries;
144 * Number of invalid entries dropped by the kernel due to
145 * invalid index stored in array
147 * Written by the kernel, shouldn't be modified by the
148 * application (i.e. get number of "new events" by comparing to
151 * After a new SQ head value was read by the application this
152 * counter includes all submissions that were dropped reaching
153 * the new SQ head (and possibly more).
159 * Written by the kernel, shouldn't be modified by the
162 * The application needs a full memory barrier before checking
163 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
169 * Written by the application, shouldn't be modified by the
174 * Number of completion events lost because the queue was full;
175 * this should be avoided by the application by making sure
176 * there are not more requests pending than there is space in
177 * the completion queue.
179 * Written by the kernel, shouldn't be modified by the
180 * application (i.e. get number of "new events" by comparing to
183 * As completion events come in out of order this counter is not
184 * ordered with any other data.
188 * Ring buffer of completion events.
190 * The kernel writes completion events fresh every time they are
191 * produced, so the application is allowed to modify pending
194 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
197 enum io_uring_cmd_flags {
198 IO_URING_F_NONBLOCK = 1,
199 IO_URING_F_COMPLETE_DEFER = 2,
202 struct io_mapped_ubuf {
205 unsigned int nr_bvecs;
206 unsigned long acct_pages;
207 struct bio_vec bvec[];
212 struct io_overflow_cqe {
213 struct io_uring_cqe cqe;
214 struct list_head list;
217 struct io_fixed_file {
218 /* file * with additional FFS_* flags */
219 unsigned long file_ptr;
223 struct list_head list;
228 struct io_mapped_ubuf *buf;
232 struct io_file_table {
233 struct io_fixed_file *files;
236 struct io_rsrc_node {
237 struct percpu_ref refs;
238 struct list_head node;
239 struct list_head rsrc_list;
240 struct io_rsrc_data *rsrc_data;
241 struct llist_node llist;
245 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
247 struct io_rsrc_data {
248 struct io_ring_ctx *ctx;
254 struct completion done;
259 struct list_head list;
265 struct io_restriction {
266 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
267 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
268 u8 sqe_flags_allowed;
269 u8 sqe_flags_required;
274 IO_SQ_THREAD_SHOULD_STOP = 0,
275 IO_SQ_THREAD_SHOULD_PARK,
280 atomic_t park_pending;
283 /* ctx's that are using this sqd */
284 struct list_head ctx_list;
286 struct task_struct *thread;
287 struct wait_queue_head wait;
289 unsigned sq_thread_idle;
295 struct completion exited;
298 #define IO_COMPL_BATCH 32
299 #define IO_REQ_CACHE_SIZE 32
300 #define IO_REQ_ALLOC_BATCH 8
302 struct io_submit_link {
303 struct io_kiocb *head;
304 struct io_kiocb *last;
307 struct io_submit_state {
308 struct blk_plug plug;
309 struct io_submit_link link;
312 * io_kiocb alloc cache
314 void *reqs[IO_REQ_CACHE_SIZE];
315 unsigned int free_reqs;
320 * Batch completion logic
322 struct io_kiocb *compl_reqs[IO_COMPL_BATCH];
323 unsigned int compl_nr;
324 /* inline/task_work completion list, under ->uring_lock */
325 struct list_head free_list;
327 unsigned int ios_left;
331 /* const or read-mostly hot data */
333 struct percpu_ref refs;
335 struct io_rings *rings;
337 unsigned int compat: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
341 unsigned int off_timeout_used: 1;
342 unsigned int drain_active: 1;
343 } ____cacheline_aligned_in_smp;
345 /* submission data */
347 struct mutex uring_lock;
350 * Ring buffer of indices into array of io_uring_sqe, which is
351 * mmapped by the application using the IORING_OFF_SQES offset.
353 * This indirection could e.g. be used to assign fixed
354 * io_uring_sqe entries to operations and only submit them to
355 * the queue when needed.
357 * The kernel modifies neither the indices array nor the entries
361 struct io_uring_sqe *sq_sqes;
362 unsigned cached_sq_head;
364 struct list_head defer_list;
367 * Fixed resources fast path, should be accessed only under
368 * uring_lock, and updated through io_uring_register(2)
370 struct io_rsrc_node *rsrc_node;
371 struct io_file_table file_table;
372 unsigned nr_user_files;
373 unsigned nr_user_bufs;
374 struct io_mapped_ubuf **user_bufs;
376 struct io_submit_state submit_state;
377 struct list_head timeout_list;
378 struct list_head cq_overflow_list;
379 struct xarray io_buffers;
380 struct xarray personalities;
382 unsigned sq_thread_idle;
383 } ____cacheline_aligned_in_smp;
385 /* IRQ completion list, under ->completion_lock */
386 struct list_head locked_free_list;
387 unsigned int locked_free_nr;
389 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
395 unsigned long check_cq_overflow;
398 unsigned cached_cq_tail;
400 struct eventfd_ctx *cq_ev_fd;
401 struct wait_queue_head poll_wait;
402 struct wait_queue_head cq_wait;
404 atomic_t cq_timeouts;
405 struct fasync_struct *cq_fasync;
406 unsigned cq_last_tm_flush;
407 } ____cacheline_aligned_in_smp;
410 spinlock_t completion_lock;
412 spinlock_t timeout_lock;
415 * ->iopoll_list is protected by the ctx->uring_lock for
416 * io_uring instances that don't use IORING_SETUP_SQPOLL.
417 * For SQPOLL, only the single threaded io_sq_thread() will
418 * manipulate the list, hence no extra locking is needed there.
420 struct list_head iopoll_list;
421 struct hlist_head *cancel_hash;
422 unsigned cancel_hash_bits;
423 bool poll_multi_queue;
424 } ____cacheline_aligned_in_smp;
426 struct io_restriction restrictions;
428 /* slow path rsrc auxilary data, used by update/register */
430 struct io_rsrc_node *rsrc_backup_node;
431 struct io_mapped_ubuf *dummy_ubuf;
432 struct io_rsrc_data *file_data;
433 struct io_rsrc_data *buf_data;
435 struct delayed_work rsrc_put_work;
436 struct llist_head rsrc_put_llist;
437 struct list_head rsrc_ref_list;
438 spinlock_t rsrc_ref_lock;
441 /* Keep this last, we don't need it for the fast path */
443 #if defined(CONFIG_UNIX)
444 struct socket *ring_sock;
446 /* hashed buffered write serialization */
447 struct io_wq_hash *hash_map;
449 /* Only used for accounting purposes */
450 struct user_struct *user;
451 struct mm_struct *mm_account;
453 /* ctx exit and cancelation */
454 struct llist_head fallback_llist;
455 struct delayed_work fallback_work;
456 struct work_struct exit_work;
457 struct list_head tctx_list;
458 struct completion ref_comp;
462 struct io_uring_task {
463 /* submission side */
466 struct wait_queue_head wait;
467 const struct io_ring_ctx *last;
469 struct percpu_counter inflight;
470 atomic_t inflight_tracked;
473 spinlock_t task_lock;
474 struct io_wq_work_list task_list;
475 struct callback_head task_work;
480 * First field must be the file pointer in all the
481 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
483 struct io_poll_iocb {
485 struct wait_queue_head *head;
489 struct wait_queue_entry wait;
492 struct io_poll_update {
498 bool update_user_data;
506 struct io_timeout_data {
507 struct io_kiocb *req;
508 struct hrtimer timer;
509 struct timespec64 ts;
510 enum hrtimer_mode mode;
515 struct sockaddr __user *addr;
516 int __user *addr_len;
519 unsigned long nofile;
539 struct list_head list;
540 /* head of the link, used by linked timeouts only */
541 struct io_kiocb *head;
542 /* for linked completions */
543 struct io_kiocb *prev;
546 struct io_timeout_rem {
551 struct timespec64 ts;
556 /* NOTE: kiocb has the file as the first member, so don't do it here */
564 struct sockaddr __user *addr;
571 struct compat_msghdr __user *umsg_compat;
572 struct user_msghdr __user *umsg;
578 struct io_buffer *kbuf;
585 struct filename *filename;
587 unsigned long nofile;
590 struct io_rsrc_update {
616 struct epoll_event event;
620 struct file *file_out;
621 struct file *file_in;
628 struct io_provide_buf {
642 const char __user *filename;
643 struct statx __user *buffer;
655 struct filename *oldpath;
656 struct filename *newpath;
664 struct filename *filename;
667 struct io_completion {
672 struct io_async_connect {
673 struct sockaddr_storage address;
676 struct io_async_msghdr {
677 struct iovec fast_iov[UIO_FASTIOV];
678 /* points to an allocated iov, if NULL we use fast_iov instead */
679 struct iovec *free_iov;
680 struct sockaddr __user *uaddr;
682 struct sockaddr_storage addr;
686 struct iovec fast_iov[UIO_FASTIOV];
687 const struct iovec *free_iovec;
688 struct iov_iter iter;
690 struct wait_page_queue wpq;
694 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
695 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
696 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
697 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
698 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
699 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
701 /* first byte is taken by user flags, shift it to not overlap */
706 REQ_F_LINK_TIMEOUT_BIT,
707 REQ_F_NEED_CLEANUP_BIT,
709 REQ_F_BUFFER_SELECTED_BIT,
710 REQ_F_COMPLETE_INLINE_BIT,
712 REQ_F_DONT_REISSUE_BIT,
715 REQ_F_ARM_LTIMEOUT_BIT,
716 /* keep async read/write and isreg together and in order */
717 REQ_F_NOWAIT_READ_BIT,
718 REQ_F_NOWAIT_WRITE_BIT,
721 /* not a real bit, just to check we're not overflowing the space */
727 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
728 /* drain existing IO first */
729 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
731 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
732 /* doesn't sever on completion < 0 */
733 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
735 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
736 /* IOSQE_BUFFER_SELECT */
737 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
739 /* fail rest of links */
740 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
741 /* on inflight list, should be cancelled and waited on exit reliably */
742 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
743 /* read/write uses file position */
744 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
745 /* must not punt to workers */
746 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
747 /* has or had linked timeout */
748 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
750 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
751 /* already went through poll handler */
752 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
753 /* buffer already selected */
754 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
755 /* completion is deferred through io_comp_state */
756 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
757 /* caller should reissue async */
758 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
759 /* don't attempt request reissue, see io_rw_reissue() */
760 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
761 /* supports async reads */
762 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
763 /* supports async writes */
764 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
766 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
767 /* has creds assigned */
768 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
769 /* skip refcounting if not set */
770 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
771 /* there is a linked timeout that has to be armed */
772 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
776 struct io_poll_iocb poll;
777 struct io_poll_iocb *double_poll;
780 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
782 struct io_task_work {
784 struct io_wq_work_node node;
785 struct llist_node fallback_node;
787 io_req_tw_func_t func;
791 IORING_RSRC_FILE = 0,
792 IORING_RSRC_BUFFER = 1,
796 * NOTE! Each of the iocb union members has the file pointer
797 * as the first entry in their struct definition. So you can
798 * access the file pointer through any of the sub-structs,
799 * or directly as just 'ki_filp' in this struct.
805 struct io_poll_iocb poll;
806 struct io_poll_update poll_update;
807 struct io_accept accept;
809 struct io_cancel cancel;
810 struct io_timeout timeout;
811 struct io_timeout_rem timeout_rem;
812 struct io_connect connect;
813 struct io_sr_msg sr_msg;
815 struct io_close close;
816 struct io_rsrc_update rsrc_update;
817 struct io_fadvise fadvise;
818 struct io_madvise madvise;
819 struct io_epoll epoll;
820 struct io_splice splice;
821 struct io_provide_buf pbuf;
822 struct io_statx statx;
823 struct io_shutdown shutdown;
824 struct io_rename rename;
825 struct io_unlink unlink;
826 /* use only after cleaning per-op data, see io_clean_op() */
827 struct io_completion compl;
830 /* opcode allocated if it needs to store data for async defer */
833 /* polled IO has completed */
839 struct io_ring_ctx *ctx;
842 struct task_struct *task;
845 struct io_kiocb *link;
846 struct percpu_ref *fixed_rsrc_refs;
848 /* used with ctx->iopoll_list with reads/writes */
849 struct list_head inflight_entry;
850 struct io_task_work io_task_work;
851 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
852 struct hlist_node hash_node;
853 struct async_poll *apoll;
854 struct io_wq_work work;
855 const struct cred *creds;
857 /* store used ubuf, so we can prevent reloading */
858 struct io_mapped_ubuf *imu;
861 struct io_tctx_node {
862 struct list_head ctx_node;
863 struct task_struct *task;
864 struct io_ring_ctx *ctx;
867 struct io_defer_entry {
868 struct list_head list;
869 struct io_kiocb *req;
874 /* needs req->file assigned */
875 unsigned needs_file : 1;
876 /* hash wq insertion if file is a regular file */
877 unsigned hash_reg_file : 1;
878 /* unbound wq insertion if file is a non-regular file */
879 unsigned unbound_nonreg_file : 1;
880 /* opcode is not supported by this kernel */
881 unsigned not_supported : 1;
882 /* set if opcode supports polled "wait" */
884 unsigned pollout : 1;
885 /* op supports buffer selection */
886 unsigned buffer_select : 1;
887 /* do prep async if is going to be punted */
888 unsigned needs_async_setup : 1;
889 /* should block plug */
891 /* size of async data needed, if any */
892 unsigned short async_size;
895 static const struct io_op_def io_op_defs[] = {
896 [IORING_OP_NOP] = {},
897 [IORING_OP_READV] = {
899 .unbound_nonreg_file = 1,
902 .needs_async_setup = 1,
904 .async_size = sizeof(struct io_async_rw),
906 [IORING_OP_WRITEV] = {
909 .unbound_nonreg_file = 1,
911 .needs_async_setup = 1,
913 .async_size = sizeof(struct io_async_rw),
915 [IORING_OP_FSYNC] = {
918 [IORING_OP_READ_FIXED] = {
920 .unbound_nonreg_file = 1,
923 .async_size = sizeof(struct io_async_rw),
925 [IORING_OP_WRITE_FIXED] = {
928 .unbound_nonreg_file = 1,
931 .async_size = sizeof(struct io_async_rw),
933 [IORING_OP_POLL_ADD] = {
935 .unbound_nonreg_file = 1,
937 [IORING_OP_POLL_REMOVE] = {},
938 [IORING_OP_SYNC_FILE_RANGE] = {
941 [IORING_OP_SENDMSG] = {
943 .unbound_nonreg_file = 1,
945 .needs_async_setup = 1,
946 .async_size = sizeof(struct io_async_msghdr),
948 [IORING_OP_RECVMSG] = {
950 .unbound_nonreg_file = 1,
953 .needs_async_setup = 1,
954 .async_size = sizeof(struct io_async_msghdr),
956 [IORING_OP_TIMEOUT] = {
957 .async_size = sizeof(struct io_timeout_data),
959 [IORING_OP_TIMEOUT_REMOVE] = {
960 /* used by timeout updates' prep() */
962 [IORING_OP_ACCEPT] = {
964 .unbound_nonreg_file = 1,
967 [IORING_OP_ASYNC_CANCEL] = {},
968 [IORING_OP_LINK_TIMEOUT] = {
969 .async_size = sizeof(struct io_timeout_data),
971 [IORING_OP_CONNECT] = {
973 .unbound_nonreg_file = 1,
975 .needs_async_setup = 1,
976 .async_size = sizeof(struct io_async_connect),
978 [IORING_OP_FALLOCATE] = {
981 [IORING_OP_OPENAT] = {},
982 [IORING_OP_CLOSE] = {},
983 [IORING_OP_FILES_UPDATE] = {},
984 [IORING_OP_STATX] = {},
987 .unbound_nonreg_file = 1,
991 .async_size = sizeof(struct io_async_rw),
993 [IORING_OP_WRITE] = {
995 .unbound_nonreg_file = 1,
998 .async_size = sizeof(struct io_async_rw),
1000 [IORING_OP_FADVISE] = {
1003 [IORING_OP_MADVISE] = {},
1004 [IORING_OP_SEND] = {
1006 .unbound_nonreg_file = 1,
1009 [IORING_OP_RECV] = {
1011 .unbound_nonreg_file = 1,
1015 [IORING_OP_OPENAT2] = {
1017 [IORING_OP_EPOLL_CTL] = {
1018 .unbound_nonreg_file = 1,
1020 [IORING_OP_SPLICE] = {
1023 .unbound_nonreg_file = 1,
1025 [IORING_OP_PROVIDE_BUFFERS] = {},
1026 [IORING_OP_REMOVE_BUFFERS] = {},
1030 .unbound_nonreg_file = 1,
1032 [IORING_OP_SHUTDOWN] = {
1035 [IORING_OP_RENAMEAT] = {},
1036 [IORING_OP_UNLINKAT] = {},
1039 /* requests with any of those set should undergo io_disarm_next() */
1040 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1042 static bool io_disarm_next(struct io_kiocb *req);
1043 static void io_uring_del_tctx_node(unsigned long index);
1044 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1045 struct task_struct *task,
1047 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1049 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1050 long res, unsigned int cflags);
1051 static void io_put_req(struct io_kiocb *req);
1052 static void io_put_req_deferred(struct io_kiocb *req);
1053 static void io_dismantle_req(struct io_kiocb *req);
1054 static void io_queue_linked_timeout(struct io_kiocb *req);
1055 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1056 struct io_uring_rsrc_update2 *up,
1058 static void io_clean_op(struct io_kiocb *req);
1059 static struct file *io_file_get(struct io_ring_ctx *ctx,
1060 struct io_kiocb *req, int fd, bool fixed);
1061 static void __io_queue_sqe(struct io_kiocb *req);
1062 static void io_rsrc_put_work(struct work_struct *work);
1064 static void io_req_task_queue(struct io_kiocb *req);
1065 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1066 static int io_req_prep_async(struct io_kiocb *req);
1068 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1069 unsigned int issue_flags, u32 slot_index);
1071 static struct kmem_cache *req_cachep;
1073 static const struct file_operations io_uring_fops;
1075 struct sock *io_uring_get_socket(struct file *file)
1077 #if defined(CONFIG_UNIX)
1078 if (file->f_op == &io_uring_fops) {
1079 struct io_ring_ctx *ctx = file->private_data;
1081 return ctx->ring_sock->sk;
1086 EXPORT_SYMBOL(io_uring_get_socket);
1088 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1091 mutex_lock(&ctx->uring_lock);
1096 #define io_for_each_link(pos, head) \
1097 for (pos = (head); pos; pos = pos->link)
1100 * Shamelessly stolen from the mm implementation of page reference checking,
1101 * see commit f958d7b528b1 for details.
1103 #define req_ref_zero_or_close_to_overflow(req) \
1104 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1106 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1108 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1109 return atomic_inc_not_zero(&req->refs);
1112 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1114 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1117 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1118 return atomic_dec_and_test(&req->refs);
1121 static inline void req_ref_put(struct io_kiocb *req)
1123 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1124 WARN_ON_ONCE(req_ref_put_and_test(req));
1127 static inline void req_ref_get(struct io_kiocb *req)
1129 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1130 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1131 atomic_inc(&req->refs);
1134 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1136 if (!(req->flags & REQ_F_REFCOUNT)) {
1137 req->flags |= REQ_F_REFCOUNT;
1138 atomic_set(&req->refs, nr);
1142 static inline void io_req_set_refcount(struct io_kiocb *req)
1144 __io_req_set_refcount(req, 1);
1147 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1149 struct io_ring_ctx *ctx = req->ctx;
1151 if (!req->fixed_rsrc_refs) {
1152 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1153 percpu_ref_get(req->fixed_rsrc_refs);
1157 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1159 bool got = percpu_ref_tryget(ref);
1161 /* already at zero, wait for ->release() */
1163 wait_for_completion(compl);
1164 percpu_ref_resurrect(ref);
1166 percpu_ref_put(ref);
1169 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1172 struct io_kiocb *req;
1174 if (task && head->task != task)
1179 io_for_each_link(req, head) {
1180 if (req->flags & REQ_F_INFLIGHT)
1186 static inline void req_set_fail(struct io_kiocb *req)
1188 req->flags |= REQ_F_FAIL;
1191 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1193 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1195 complete(&ctx->ref_comp);
1198 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1200 return !req->timeout.off;
1203 static void io_fallback_req_func(struct work_struct *work)
1205 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1206 fallback_work.work);
1207 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1208 struct io_kiocb *req, *tmp;
1209 bool locked = false;
1211 percpu_ref_get(&ctx->refs);
1212 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1213 req->io_task_work.func(req, &locked);
1216 if (ctx->submit_state.compl_nr)
1217 io_submit_flush_completions(ctx);
1218 mutex_unlock(&ctx->uring_lock);
1220 percpu_ref_put(&ctx->refs);
1224 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1226 struct io_ring_ctx *ctx;
1229 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1234 * Use 5 bits less than the max cq entries, that should give us around
1235 * 32 entries per hash list if totally full and uniformly spread.
1237 hash_bits = ilog2(p->cq_entries);
1241 ctx->cancel_hash_bits = hash_bits;
1242 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1244 if (!ctx->cancel_hash)
1246 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1248 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1249 if (!ctx->dummy_ubuf)
1251 /* set invalid range, so io_import_fixed() fails meeting it */
1252 ctx->dummy_ubuf->ubuf = -1UL;
1254 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1255 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1258 ctx->flags = p->flags;
1259 init_waitqueue_head(&ctx->sqo_sq_wait);
1260 INIT_LIST_HEAD(&ctx->sqd_list);
1261 init_waitqueue_head(&ctx->poll_wait);
1262 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1263 init_completion(&ctx->ref_comp);
1264 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1265 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1266 mutex_init(&ctx->uring_lock);
1267 init_waitqueue_head(&ctx->cq_wait);
1268 spin_lock_init(&ctx->completion_lock);
1269 spin_lock_init(&ctx->timeout_lock);
1270 INIT_LIST_HEAD(&ctx->iopoll_list);
1271 INIT_LIST_HEAD(&ctx->defer_list);
1272 INIT_LIST_HEAD(&ctx->timeout_list);
1273 spin_lock_init(&ctx->rsrc_ref_lock);
1274 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1275 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1276 init_llist_head(&ctx->rsrc_put_llist);
1277 INIT_LIST_HEAD(&ctx->tctx_list);
1278 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1279 INIT_LIST_HEAD(&ctx->locked_free_list);
1280 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1283 kfree(ctx->dummy_ubuf);
1284 kfree(ctx->cancel_hash);
1289 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1291 struct io_rings *r = ctx->rings;
1293 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1297 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1299 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1300 struct io_ring_ctx *ctx = req->ctx;
1302 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1308 #define FFS_ASYNC_READ 0x1UL
1309 #define FFS_ASYNC_WRITE 0x2UL
1311 #define FFS_ISREG 0x4UL
1313 #define FFS_ISREG 0x0UL
1315 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1317 static inline bool io_req_ffs_set(struct io_kiocb *req)
1319 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1322 static void io_req_track_inflight(struct io_kiocb *req)
1324 if (!(req->flags & REQ_F_INFLIGHT)) {
1325 req->flags |= REQ_F_INFLIGHT;
1326 atomic_inc(¤t->io_uring->inflight_tracked);
1330 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1332 req->flags &= ~REQ_F_LINK_TIMEOUT;
1335 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1337 if (WARN_ON_ONCE(!req->link))
1340 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1341 req->flags |= REQ_F_LINK_TIMEOUT;
1343 /* linked timeouts should have two refs once prep'ed */
1344 io_req_set_refcount(req);
1345 __io_req_set_refcount(req->link, 2);
1349 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1351 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1353 return __io_prep_linked_timeout(req);
1356 static void io_prep_async_work(struct io_kiocb *req)
1358 const struct io_op_def *def = &io_op_defs[req->opcode];
1359 struct io_ring_ctx *ctx = req->ctx;
1361 if (!(req->flags & REQ_F_CREDS)) {
1362 req->flags |= REQ_F_CREDS;
1363 req->creds = get_current_cred();
1366 req->work.list.next = NULL;
1367 req->work.flags = 0;
1368 if (req->flags & REQ_F_FORCE_ASYNC)
1369 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1371 if (req->flags & REQ_F_ISREG) {
1372 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1373 io_wq_hash_work(&req->work, file_inode(req->file));
1374 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1375 if (def->unbound_nonreg_file)
1376 req->work.flags |= IO_WQ_WORK_UNBOUND;
1379 switch (req->opcode) {
1380 case IORING_OP_SPLICE:
1382 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1383 req->work.flags |= IO_WQ_WORK_UNBOUND;
1388 static void io_prep_async_link(struct io_kiocb *req)
1390 struct io_kiocb *cur;
1392 if (req->flags & REQ_F_LINK_TIMEOUT) {
1393 struct io_ring_ctx *ctx = req->ctx;
1395 spin_lock(&ctx->completion_lock);
1396 io_for_each_link(cur, req)
1397 io_prep_async_work(cur);
1398 spin_unlock(&ctx->completion_lock);
1400 io_for_each_link(cur, req)
1401 io_prep_async_work(cur);
1405 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1407 struct io_ring_ctx *ctx = req->ctx;
1408 struct io_kiocb *link = io_prep_linked_timeout(req);
1409 struct io_uring_task *tctx = req->task->io_uring;
1411 /* must not take the lock, NULL it as a precaution */
1415 BUG_ON(!tctx->io_wq);
1417 /* init ->work of the whole link before punting */
1418 io_prep_async_link(req);
1421 * Not expected to happen, but if we do have a bug where this _can_
1422 * happen, catch it here and ensure the request is marked as
1423 * canceled. That will make io-wq go through the usual work cancel
1424 * procedure rather than attempt to run this request (or create a new
1427 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1428 req->work.flags |= IO_WQ_WORK_CANCEL;
1430 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1431 &req->work, req->flags);
1432 io_wq_enqueue(tctx->io_wq, &req->work);
1434 io_queue_linked_timeout(link);
1437 static void io_kill_timeout(struct io_kiocb *req, int status)
1438 __must_hold(&req->ctx->completion_lock)
1439 __must_hold(&req->ctx->timeout_lock)
1441 struct io_timeout_data *io = req->async_data;
1443 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1444 atomic_set(&req->ctx->cq_timeouts,
1445 atomic_read(&req->ctx->cq_timeouts) + 1);
1446 list_del_init(&req->timeout.list);
1447 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1448 io_put_req_deferred(req);
1452 static void io_queue_deferred(struct io_ring_ctx *ctx)
1454 while (!list_empty(&ctx->defer_list)) {
1455 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1456 struct io_defer_entry, list);
1458 if (req_need_defer(de->req, de->seq))
1460 list_del_init(&de->list);
1461 io_req_task_queue(de->req);
1466 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1467 __must_hold(&ctx->completion_lock)
1469 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1471 spin_lock_irq(&ctx->timeout_lock);
1472 while (!list_empty(&ctx->timeout_list)) {
1473 u32 events_needed, events_got;
1474 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1475 struct io_kiocb, timeout.list);
1477 if (io_is_timeout_noseq(req))
1481 * Since seq can easily wrap around over time, subtract
1482 * the last seq at which timeouts were flushed before comparing.
1483 * Assuming not more than 2^31-1 events have happened since,
1484 * these subtractions won't have wrapped, so we can check if
1485 * target is in [last_seq, current_seq] by comparing the two.
1487 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1488 events_got = seq - ctx->cq_last_tm_flush;
1489 if (events_got < events_needed)
1492 list_del_init(&req->timeout.list);
1493 io_kill_timeout(req, 0);
1495 ctx->cq_last_tm_flush = seq;
1496 spin_unlock_irq(&ctx->timeout_lock);
1499 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1501 if (ctx->off_timeout_used)
1502 io_flush_timeouts(ctx);
1503 if (ctx->drain_active)
1504 io_queue_deferred(ctx);
1507 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1509 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1510 __io_commit_cqring_flush(ctx);
1511 /* order cqe stores with ring update */
1512 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1515 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1517 struct io_rings *r = ctx->rings;
1519 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1522 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1524 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1527 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1529 struct io_rings *rings = ctx->rings;
1530 unsigned tail, mask = ctx->cq_entries - 1;
1533 * writes to the cq entry need to come after reading head; the
1534 * control dependency is enough as we're using WRITE_ONCE to
1537 if (__io_cqring_events(ctx) == ctx->cq_entries)
1540 tail = ctx->cached_cq_tail++;
1541 return &rings->cqes[tail & mask];
1544 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1546 if (likely(!ctx->cq_ev_fd))
1548 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1550 return !ctx->eventfd_async || io_wq_current_is_worker();
1554 * This should only get called when at least one event has been posted.
1555 * Some applications rely on the eventfd notification count only changing
1556 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1557 * 1:1 relationship between how many times this function is called (and
1558 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1560 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1563 * wake_up_all() may seem excessive, but io_wake_function() and
1564 * io_should_wake() handle the termination of the loop and only
1565 * wake as many waiters as we need to.
1567 if (wq_has_sleeper(&ctx->cq_wait))
1568 wake_up_all(&ctx->cq_wait);
1569 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1570 wake_up(&ctx->sq_data->wait);
1571 if (io_should_trigger_evfd(ctx))
1572 eventfd_signal(ctx->cq_ev_fd, 1);
1573 if (waitqueue_active(&ctx->poll_wait)) {
1574 wake_up_interruptible(&ctx->poll_wait);
1575 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1579 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1581 if (ctx->flags & IORING_SETUP_SQPOLL) {
1582 if (wq_has_sleeper(&ctx->cq_wait))
1583 wake_up_all(&ctx->cq_wait);
1585 if (io_should_trigger_evfd(ctx))
1586 eventfd_signal(ctx->cq_ev_fd, 1);
1587 if (waitqueue_active(&ctx->poll_wait)) {
1588 wake_up_interruptible(&ctx->poll_wait);
1589 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1593 /* Returns true if there are no backlogged entries after the flush */
1594 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1596 bool all_flushed, posted;
1598 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1602 spin_lock(&ctx->completion_lock);
1603 while (!list_empty(&ctx->cq_overflow_list)) {
1604 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1605 struct io_overflow_cqe *ocqe;
1609 ocqe = list_first_entry(&ctx->cq_overflow_list,
1610 struct io_overflow_cqe, list);
1612 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1614 io_account_cq_overflow(ctx);
1617 list_del(&ocqe->list);
1621 all_flushed = list_empty(&ctx->cq_overflow_list);
1623 clear_bit(0, &ctx->check_cq_overflow);
1624 WRITE_ONCE(ctx->rings->sq_flags,
1625 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1629 io_commit_cqring(ctx);
1630 spin_unlock(&ctx->completion_lock);
1632 io_cqring_ev_posted(ctx);
1636 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1640 if (test_bit(0, &ctx->check_cq_overflow)) {
1641 /* iopoll syncs against uring_lock, not completion_lock */
1642 if (ctx->flags & IORING_SETUP_IOPOLL)
1643 mutex_lock(&ctx->uring_lock);
1644 ret = __io_cqring_overflow_flush(ctx, false);
1645 if (ctx->flags & IORING_SETUP_IOPOLL)
1646 mutex_unlock(&ctx->uring_lock);
1652 /* must to be called somewhat shortly after putting a request */
1653 static inline void io_put_task(struct task_struct *task, int nr)
1655 struct io_uring_task *tctx = task->io_uring;
1657 if (likely(task == current)) {
1658 tctx->cached_refs += nr;
1660 percpu_counter_sub(&tctx->inflight, nr);
1661 if (unlikely(atomic_read(&tctx->in_idle)))
1662 wake_up(&tctx->wait);
1663 put_task_struct_many(task, nr);
1667 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1668 long res, unsigned int cflags)
1670 struct io_overflow_cqe *ocqe;
1672 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1675 * If we're in ring overflow flush mode, or in task cancel mode,
1676 * or cannot allocate an overflow entry, then we need to drop it
1679 io_account_cq_overflow(ctx);
1682 if (list_empty(&ctx->cq_overflow_list)) {
1683 set_bit(0, &ctx->check_cq_overflow);
1684 WRITE_ONCE(ctx->rings->sq_flags,
1685 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1688 ocqe->cqe.user_data = user_data;
1689 ocqe->cqe.res = res;
1690 ocqe->cqe.flags = cflags;
1691 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1695 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1696 long res, unsigned int cflags)
1698 struct io_uring_cqe *cqe;
1700 trace_io_uring_complete(ctx, user_data, res, cflags);
1703 * If we can't get a cq entry, userspace overflowed the
1704 * submission (by quite a lot). Increment the overflow count in
1707 cqe = io_get_cqe(ctx);
1709 WRITE_ONCE(cqe->user_data, user_data);
1710 WRITE_ONCE(cqe->res, res);
1711 WRITE_ONCE(cqe->flags, cflags);
1714 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1717 /* not as hot to bloat with inlining */
1718 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1719 long res, unsigned int cflags)
1721 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1724 static void io_req_complete_post(struct io_kiocb *req, long res,
1725 unsigned int cflags)
1727 struct io_ring_ctx *ctx = req->ctx;
1729 spin_lock(&ctx->completion_lock);
1730 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1732 * If we're the last reference to this request, add to our locked
1735 if (req_ref_put_and_test(req)) {
1736 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1737 if (req->flags & IO_DISARM_MASK)
1738 io_disarm_next(req);
1740 io_req_task_queue(req->link);
1744 io_dismantle_req(req);
1745 io_put_task(req->task, 1);
1746 list_add(&req->inflight_entry, &ctx->locked_free_list);
1747 ctx->locked_free_nr++;
1749 if (!percpu_ref_tryget(&ctx->refs))
1752 io_commit_cqring(ctx);
1753 spin_unlock(&ctx->completion_lock);
1756 io_cqring_ev_posted(ctx);
1757 percpu_ref_put(&ctx->refs);
1761 static inline bool io_req_needs_clean(struct io_kiocb *req)
1763 return req->flags & IO_REQ_CLEAN_FLAGS;
1766 static void io_req_complete_state(struct io_kiocb *req, long res,
1767 unsigned int cflags)
1769 if (io_req_needs_clean(req))
1772 req->compl.cflags = cflags;
1773 req->flags |= REQ_F_COMPLETE_INLINE;
1776 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1777 long res, unsigned cflags)
1779 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1780 io_req_complete_state(req, res, cflags);
1782 io_req_complete_post(req, res, cflags);
1785 static inline void io_req_complete(struct io_kiocb *req, long res)
1787 __io_req_complete(req, 0, res, 0);
1790 static void io_req_complete_failed(struct io_kiocb *req, long res)
1793 io_req_complete_post(req, res, 0);
1797 * Don't initialise the fields below on every allocation, but do that in
1798 * advance and keep them valid across allocations.
1800 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1804 req->async_data = NULL;
1805 /* not necessary, but safer to zero */
1809 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1810 struct io_submit_state *state)
1812 spin_lock(&ctx->completion_lock);
1813 list_splice_init(&ctx->locked_free_list, &state->free_list);
1814 ctx->locked_free_nr = 0;
1815 spin_unlock(&ctx->completion_lock);
1818 /* Returns true IFF there are requests in the cache */
1819 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1821 struct io_submit_state *state = &ctx->submit_state;
1825 * If we have more than a batch's worth of requests in our IRQ side
1826 * locked cache, grab the lock and move them over to our submission
1829 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1830 io_flush_cached_locked_reqs(ctx, state);
1832 nr = state->free_reqs;
1833 while (!list_empty(&state->free_list)) {
1834 struct io_kiocb *req = list_first_entry(&state->free_list,
1835 struct io_kiocb, inflight_entry);
1837 list_del(&req->inflight_entry);
1838 state->reqs[nr++] = req;
1839 if (nr == ARRAY_SIZE(state->reqs))
1843 state->free_reqs = nr;
1848 * A request might get retired back into the request caches even before opcode
1849 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1850 * Because of that, io_alloc_req() should be called only under ->uring_lock
1851 * and with extra caution to not get a request that is still worked on.
1853 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1854 __must_hold(&ctx->uring_lock)
1856 struct io_submit_state *state = &ctx->submit_state;
1857 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1860 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1862 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1865 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1869 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1870 * retry single alloc to be on the safe side.
1872 if (unlikely(ret <= 0)) {
1873 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1874 if (!state->reqs[0])
1879 for (i = 0; i < ret; i++)
1880 io_preinit_req(state->reqs[i], ctx);
1881 state->free_reqs = ret;
1884 return state->reqs[state->free_reqs];
1887 static inline void io_put_file(struct file *file)
1893 static void io_dismantle_req(struct io_kiocb *req)
1895 unsigned int flags = req->flags;
1897 if (io_req_needs_clean(req))
1899 if (!(flags & REQ_F_FIXED_FILE))
1900 io_put_file(req->file);
1901 if (req->fixed_rsrc_refs)
1902 percpu_ref_put(req->fixed_rsrc_refs);
1903 if (req->async_data) {
1904 kfree(req->async_data);
1905 req->async_data = NULL;
1909 static void __io_free_req(struct io_kiocb *req)
1911 struct io_ring_ctx *ctx = req->ctx;
1913 io_dismantle_req(req);
1914 io_put_task(req->task, 1);
1916 spin_lock(&ctx->completion_lock);
1917 list_add(&req->inflight_entry, &ctx->locked_free_list);
1918 ctx->locked_free_nr++;
1919 spin_unlock(&ctx->completion_lock);
1921 percpu_ref_put(&ctx->refs);
1924 static inline void io_remove_next_linked(struct io_kiocb *req)
1926 struct io_kiocb *nxt = req->link;
1928 req->link = nxt->link;
1932 static bool io_kill_linked_timeout(struct io_kiocb *req)
1933 __must_hold(&req->ctx->completion_lock)
1934 __must_hold(&req->ctx->timeout_lock)
1936 struct io_kiocb *link = req->link;
1938 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1939 struct io_timeout_data *io = link->async_data;
1941 io_remove_next_linked(req);
1942 link->timeout.head = NULL;
1943 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1944 io_cqring_fill_event(link->ctx, link->user_data,
1946 io_put_req_deferred(link);
1953 static void io_fail_links(struct io_kiocb *req)
1954 __must_hold(&req->ctx->completion_lock)
1956 struct io_kiocb *nxt, *link = req->link;
1963 trace_io_uring_fail_link(req, link);
1964 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1965 io_put_req_deferred(link);
1970 static bool io_disarm_next(struct io_kiocb *req)
1971 __must_hold(&req->ctx->completion_lock)
1973 bool posted = false;
1975 if (req->flags & REQ_F_ARM_LTIMEOUT) {
1976 struct io_kiocb *link = req->link;
1978 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1979 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1980 io_remove_next_linked(req);
1981 io_cqring_fill_event(link->ctx, link->user_data,
1983 io_put_req_deferred(link);
1986 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
1987 struct io_ring_ctx *ctx = req->ctx;
1989 spin_lock_irq(&ctx->timeout_lock);
1990 posted = io_kill_linked_timeout(req);
1991 spin_unlock_irq(&ctx->timeout_lock);
1993 if (unlikely((req->flags & REQ_F_FAIL) &&
1994 !(req->flags & REQ_F_HARDLINK))) {
1995 posted |= (req->link != NULL);
2001 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2003 struct io_kiocb *nxt;
2006 * If LINK is set, we have dependent requests in this chain. If we
2007 * didn't fail this request, queue the first one up, moving any other
2008 * dependencies to the next request. In case of failure, fail the rest
2011 if (req->flags & IO_DISARM_MASK) {
2012 struct io_ring_ctx *ctx = req->ctx;
2015 spin_lock(&ctx->completion_lock);
2016 posted = io_disarm_next(req);
2018 io_commit_cqring(req->ctx);
2019 spin_unlock(&ctx->completion_lock);
2021 io_cqring_ev_posted(ctx);
2028 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2030 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2032 return __io_req_find_next(req);
2035 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2040 if (ctx->submit_state.compl_nr)
2041 io_submit_flush_completions(ctx);
2042 mutex_unlock(&ctx->uring_lock);
2045 percpu_ref_put(&ctx->refs);
2048 static void tctx_task_work(struct callback_head *cb)
2050 bool locked = false;
2051 struct io_ring_ctx *ctx = NULL;
2052 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2056 struct io_wq_work_node *node;
2058 spin_lock_irq(&tctx->task_lock);
2059 node = tctx->task_list.first;
2060 INIT_WQ_LIST(&tctx->task_list);
2062 tctx->task_running = false;
2063 spin_unlock_irq(&tctx->task_lock);
2068 struct io_wq_work_node *next = node->next;
2069 struct io_kiocb *req = container_of(node, struct io_kiocb,
2072 if (req->ctx != ctx) {
2073 ctx_flush_and_put(ctx, &locked);
2075 /* if not contended, grab and improve batching */
2076 locked = mutex_trylock(&ctx->uring_lock);
2077 percpu_ref_get(&ctx->refs);
2079 req->io_task_work.func(req, &locked);
2086 ctx_flush_and_put(ctx, &locked);
2089 static void io_req_task_work_add(struct io_kiocb *req)
2091 struct task_struct *tsk = req->task;
2092 struct io_uring_task *tctx = tsk->io_uring;
2093 enum task_work_notify_mode notify;
2094 struct io_wq_work_node *node;
2095 unsigned long flags;
2098 WARN_ON_ONCE(!tctx);
2100 spin_lock_irqsave(&tctx->task_lock, flags);
2101 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2102 running = tctx->task_running;
2104 tctx->task_running = true;
2105 spin_unlock_irqrestore(&tctx->task_lock, flags);
2107 /* task_work already pending, we're done */
2112 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2113 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2114 * processing task_work. There's no reliable way to tell if TWA_RESUME
2117 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2118 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2119 wake_up_process(tsk);
2123 spin_lock_irqsave(&tctx->task_lock, flags);
2124 tctx->task_running = false;
2125 node = tctx->task_list.first;
2126 INIT_WQ_LIST(&tctx->task_list);
2127 spin_unlock_irqrestore(&tctx->task_lock, flags);
2130 req = container_of(node, struct io_kiocb, io_task_work.node);
2132 if (llist_add(&req->io_task_work.fallback_node,
2133 &req->ctx->fallback_llist))
2134 schedule_delayed_work(&req->ctx->fallback_work, 1);
2138 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2140 struct io_ring_ctx *ctx = req->ctx;
2142 /* ctx is guaranteed to stay alive while we hold uring_lock */
2143 io_tw_lock(ctx, locked);
2144 io_req_complete_failed(req, req->result);
2147 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2149 struct io_ring_ctx *ctx = req->ctx;
2151 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2152 io_tw_lock(ctx, locked);
2153 /* req->task == current here, checking PF_EXITING is safe */
2154 if (likely(!(req->task->flags & PF_EXITING)))
2155 __io_queue_sqe(req);
2157 io_req_complete_failed(req, -EFAULT);
2160 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2163 req->io_task_work.func = io_req_task_cancel;
2164 io_req_task_work_add(req);
2167 static void io_req_task_queue(struct io_kiocb *req)
2169 req->io_task_work.func = io_req_task_submit;
2170 io_req_task_work_add(req);
2173 static void io_req_task_queue_reissue(struct io_kiocb *req)
2175 req->io_task_work.func = io_queue_async_work;
2176 io_req_task_work_add(req);
2179 static inline void io_queue_next(struct io_kiocb *req)
2181 struct io_kiocb *nxt = io_req_find_next(req);
2184 io_req_task_queue(nxt);
2187 static void io_free_req(struct io_kiocb *req)
2193 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2199 struct task_struct *task;
2204 static inline void io_init_req_batch(struct req_batch *rb)
2211 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2212 struct req_batch *rb)
2215 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2217 io_put_task(rb->task, rb->task_refs);
2220 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2221 struct io_submit_state *state)
2224 io_dismantle_req(req);
2226 if (req->task != rb->task) {
2228 io_put_task(rb->task, rb->task_refs);
2229 rb->task = req->task;
2235 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2236 state->reqs[state->free_reqs++] = req;
2238 list_add(&req->inflight_entry, &state->free_list);
2241 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2242 __must_hold(&ctx->uring_lock)
2244 struct io_submit_state *state = &ctx->submit_state;
2245 int i, nr = state->compl_nr;
2246 struct req_batch rb;
2248 spin_lock(&ctx->completion_lock);
2249 for (i = 0; i < nr; i++) {
2250 struct io_kiocb *req = state->compl_reqs[i];
2252 __io_cqring_fill_event(ctx, req->user_data, req->result,
2255 io_commit_cqring(ctx);
2256 spin_unlock(&ctx->completion_lock);
2257 io_cqring_ev_posted(ctx);
2259 io_init_req_batch(&rb);
2260 for (i = 0; i < nr; i++) {
2261 struct io_kiocb *req = state->compl_reqs[i];
2263 if (req_ref_put_and_test(req))
2264 io_req_free_batch(&rb, req, &ctx->submit_state);
2267 io_req_free_batch_finish(ctx, &rb);
2268 state->compl_nr = 0;
2272 * Drop reference to request, return next in chain (if there is one) if this
2273 * was the last reference to this request.
2275 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2277 struct io_kiocb *nxt = NULL;
2279 if (req_ref_put_and_test(req)) {
2280 nxt = io_req_find_next(req);
2286 static inline void io_put_req(struct io_kiocb *req)
2288 if (req_ref_put_and_test(req))
2292 static inline void io_put_req_deferred(struct io_kiocb *req)
2294 if (req_ref_put_and_test(req)) {
2295 req->io_task_work.func = io_free_req_work;
2296 io_req_task_work_add(req);
2300 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2302 /* See comment at the top of this file */
2304 return __io_cqring_events(ctx);
2307 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2309 struct io_rings *rings = ctx->rings;
2311 /* make sure SQ entry isn't read before tail */
2312 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2315 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2317 unsigned int cflags;
2319 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2320 cflags |= IORING_CQE_F_BUFFER;
2321 req->flags &= ~REQ_F_BUFFER_SELECTED;
2326 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2328 struct io_buffer *kbuf;
2330 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2332 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2333 return io_put_kbuf(req, kbuf);
2336 static inline bool io_run_task_work(void)
2338 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2339 __set_current_state(TASK_RUNNING);
2340 tracehook_notify_signal();
2348 * Find and free completed poll iocbs
2350 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2351 struct list_head *done)
2353 struct req_batch rb;
2354 struct io_kiocb *req;
2356 /* order with ->result store in io_complete_rw_iopoll() */
2359 io_init_req_batch(&rb);
2360 while (!list_empty(done)) {
2361 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2362 list_del(&req->inflight_entry);
2364 if (READ_ONCE(req->result) == -EAGAIN &&
2365 !(req->flags & REQ_F_DONT_REISSUE)) {
2366 req->iopoll_completed = 0;
2367 io_req_task_queue_reissue(req);
2371 __io_cqring_fill_event(ctx, req->user_data, req->result,
2372 io_put_rw_kbuf(req));
2375 if (req_ref_put_and_test(req))
2376 io_req_free_batch(&rb, req, &ctx->submit_state);
2379 io_commit_cqring(ctx);
2380 io_cqring_ev_posted_iopoll(ctx);
2381 io_req_free_batch_finish(ctx, &rb);
2384 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2387 struct io_kiocb *req, *tmp;
2392 * Only spin for completions if we don't have multiple devices hanging
2393 * off our complete list, and we're under the requested amount.
2395 spin = !ctx->poll_multi_queue && *nr_events < min;
2397 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2398 struct kiocb *kiocb = &req->rw.kiocb;
2402 * Move completed and retryable entries to our local lists.
2403 * If we find a request that requires polling, break out
2404 * and complete those lists first, if we have entries there.
2406 if (READ_ONCE(req->iopoll_completed)) {
2407 list_move_tail(&req->inflight_entry, &done);
2410 if (!list_empty(&done))
2413 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2414 if (unlikely(ret < 0))
2419 /* iopoll may have completed current req */
2420 if (READ_ONCE(req->iopoll_completed))
2421 list_move_tail(&req->inflight_entry, &done);
2424 if (!list_empty(&done))
2425 io_iopoll_complete(ctx, nr_events, &done);
2431 * We can't just wait for polled events to come to us, we have to actively
2432 * find and complete them.
2434 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2436 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2439 mutex_lock(&ctx->uring_lock);
2440 while (!list_empty(&ctx->iopoll_list)) {
2441 unsigned int nr_events = 0;
2443 io_do_iopoll(ctx, &nr_events, 0);
2445 /* let it sleep and repeat later if can't complete a request */
2449 * Ensure we allow local-to-the-cpu processing to take place,
2450 * in this case we need to ensure that we reap all events.
2451 * Also let task_work, etc. to progress by releasing the mutex
2453 if (need_resched()) {
2454 mutex_unlock(&ctx->uring_lock);
2456 mutex_lock(&ctx->uring_lock);
2459 mutex_unlock(&ctx->uring_lock);
2462 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2464 unsigned int nr_events = 0;
2468 * We disallow the app entering submit/complete with polling, but we
2469 * still need to lock the ring to prevent racing with polled issue
2470 * that got punted to a workqueue.
2472 mutex_lock(&ctx->uring_lock);
2474 * Don't enter poll loop if we already have events pending.
2475 * If we do, we can potentially be spinning for commands that
2476 * already triggered a CQE (eg in error).
2478 if (test_bit(0, &ctx->check_cq_overflow))
2479 __io_cqring_overflow_flush(ctx, false);
2480 if (io_cqring_events(ctx))
2484 * If a submit got punted to a workqueue, we can have the
2485 * application entering polling for a command before it gets
2486 * issued. That app will hold the uring_lock for the duration
2487 * of the poll right here, so we need to take a breather every
2488 * now and then to ensure that the issue has a chance to add
2489 * the poll to the issued list. Otherwise we can spin here
2490 * forever, while the workqueue is stuck trying to acquire the
2493 if (list_empty(&ctx->iopoll_list)) {
2494 u32 tail = ctx->cached_cq_tail;
2496 mutex_unlock(&ctx->uring_lock);
2498 mutex_lock(&ctx->uring_lock);
2500 /* some requests don't go through iopoll_list */
2501 if (tail != ctx->cached_cq_tail ||
2502 list_empty(&ctx->iopoll_list))
2505 ret = io_do_iopoll(ctx, &nr_events, min);
2506 } while (!ret && nr_events < min && !need_resched());
2508 mutex_unlock(&ctx->uring_lock);
2512 static void kiocb_end_write(struct io_kiocb *req)
2515 * Tell lockdep we inherited freeze protection from submission
2518 if (req->flags & REQ_F_ISREG) {
2519 struct super_block *sb = file_inode(req->file)->i_sb;
2521 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2527 static bool io_resubmit_prep(struct io_kiocb *req)
2529 struct io_async_rw *rw = req->async_data;
2532 return !io_req_prep_async(req);
2533 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2534 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2538 static bool io_rw_should_reissue(struct io_kiocb *req)
2540 umode_t mode = file_inode(req->file)->i_mode;
2541 struct io_ring_ctx *ctx = req->ctx;
2543 if (!S_ISBLK(mode) && !S_ISREG(mode))
2545 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2546 !(ctx->flags & IORING_SETUP_IOPOLL)))
2549 * If ref is dying, we might be running poll reap from the exit work.
2550 * Don't attempt to reissue from that path, just let it fail with
2553 if (percpu_ref_is_dying(&ctx->refs))
2556 * Play it safe and assume not safe to re-import and reissue if we're
2557 * not in the original thread group (or in task context).
2559 if (!same_thread_group(req->task, current) || !in_task())
2564 static bool io_resubmit_prep(struct io_kiocb *req)
2568 static bool io_rw_should_reissue(struct io_kiocb *req)
2574 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2576 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2577 kiocb_end_write(req);
2578 if (res != req->result) {
2579 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2580 io_rw_should_reissue(req)) {
2581 req->flags |= REQ_F_REISSUE;
2590 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2592 unsigned int cflags = io_put_rw_kbuf(req);
2593 long res = req->result;
2596 struct io_ring_ctx *ctx = req->ctx;
2597 struct io_submit_state *state = &ctx->submit_state;
2599 io_req_complete_state(req, res, cflags);
2600 state->compl_reqs[state->compl_nr++] = req;
2601 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2602 io_submit_flush_completions(ctx);
2604 io_req_complete_post(req, res, cflags);
2608 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2609 unsigned int issue_flags)
2611 if (__io_complete_rw_common(req, res))
2613 __io_req_complete(req, 0, req->result, io_put_rw_kbuf(req));
2616 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2618 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2620 if (__io_complete_rw_common(req, res))
2623 req->io_task_work.func = io_req_task_complete;
2624 io_req_task_work_add(req);
2627 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2629 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2631 if (kiocb->ki_flags & IOCB_WRITE)
2632 kiocb_end_write(req);
2633 if (unlikely(res != req->result)) {
2634 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2635 io_resubmit_prep(req))) {
2637 req->flags |= REQ_F_DONT_REISSUE;
2641 WRITE_ONCE(req->result, res);
2642 /* order with io_iopoll_complete() checking ->result */
2644 WRITE_ONCE(req->iopoll_completed, 1);
2648 * After the iocb has been issued, it's safe to be found on the poll list.
2649 * Adding the kiocb to the list AFTER submission ensures that we don't
2650 * find it from a io_do_iopoll() thread before the issuer is done
2651 * accessing the kiocb cookie.
2653 static void io_iopoll_req_issued(struct io_kiocb *req)
2655 struct io_ring_ctx *ctx = req->ctx;
2656 const bool in_async = io_wq_current_is_worker();
2658 /* workqueue context doesn't hold uring_lock, grab it now */
2659 if (unlikely(in_async))
2660 mutex_lock(&ctx->uring_lock);
2663 * Track whether we have multiple files in our lists. This will impact
2664 * how we do polling eventually, not spinning if we're on potentially
2665 * different devices.
2667 if (list_empty(&ctx->iopoll_list)) {
2668 ctx->poll_multi_queue = false;
2669 } else if (!ctx->poll_multi_queue) {
2670 struct io_kiocb *list_req;
2671 unsigned int queue_num0, queue_num1;
2673 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2676 if (list_req->file != req->file) {
2677 ctx->poll_multi_queue = true;
2679 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2680 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2681 if (queue_num0 != queue_num1)
2682 ctx->poll_multi_queue = true;
2687 * For fast devices, IO may have already completed. If it has, add
2688 * it to the front so we find it first.
2690 if (READ_ONCE(req->iopoll_completed))
2691 list_add(&req->inflight_entry, &ctx->iopoll_list);
2693 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2695 if (unlikely(in_async)) {
2697 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2698 * in sq thread task context or in io worker task context. If
2699 * current task context is sq thread, we don't need to check
2700 * whether should wake up sq thread.
2702 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2703 wq_has_sleeper(&ctx->sq_data->wait))
2704 wake_up(&ctx->sq_data->wait);
2706 mutex_unlock(&ctx->uring_lock);
2710 static bool io_bdev_nowait(struct block_device *bdev)
2712 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2716 * If we tracked the file through the SCM inflight mechanism, we could support
2717 * any file. For now, just ensure that anything potentially problematic is done
2720 static bool __io_file_supports_nowait(struct file *file, int rw)
2722 umode_t mode = file_inode(file)->i_mode;
2724 if (S_ISBLK(mode)) {
2725 if (IS_ENABLED(CONFIG_BLOCK) &&
2726 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2732 if (S_ISREG(mode)) {
2733 if (IS_ENABLED(CONFIG_BLOCK) &&
2734 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2735 file->f_op != &io_uring_fops)
2740 /* any ->read/write should understand O_NONBLOCK */
2741 if (file->f_flags & O_NONBLOCK)
2744 if (!(file->f_mode & FMODE_NOWAIT))
2748 return file->f_op->read_iter != NULL;
2750 return file->f_op->write_iter != NULL;
2753 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2755 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2757 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2760 return __io_file_supports_nowait(req->file, rw);
2763 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2765 struct io_ring_ctx *ctx = req->ctx;
2766 struct kiocb *kiocb = &req->rw.kiocb;
2767 struct file *file = req->file;
2771 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2772 req->flags |= REQ_F_ISREG;
2774 kiocb->ki_pos = READ_ONCE(sqe->off);
2775 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2776 req->flags |= REQ_F_CUR_POS;
2777 kiocb->ki_pos = file->f_pos;
2779 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2780 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2781 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2785 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2786 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2787 req->flags |= REQ_F_NOWAIT;
2789 ioprio = READ_ONCE(sqe->ioprio);
2791 ret = ioprio_check_cap(ioprio);
2795 kiocb->ki_ioprio = ioprio;
2797 kiocb->ki_ioprio = get_current_ioprio();
2799 if (ctx->flags & IORING_SETUP_IOPOLL) {
2800 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2801 !kiocb->ki_filp->f_op->iopoll)
2804 kiocb->ki_flags |= IOCB_HIPRI;
2805 kiocb->ki_complete = io_complete_rw_iopoll;
2806 req->iopoll_completed = 0;
2808 if (kiocb->ki_flags & IOCB_HIPRI)
2810 kiocb->ki_complete = io_complete_rw;
2813 if (req->opcode == IORING_OP_READ_FIXED ||
2814 req->opcode == IORING_OP_WRITE_FIXED) {
2816 io_req_set_rsrc_node(req);
2819 req->rw.addr = READ_ONCE(sqe->addr);
2820 req->rw.len = READ_ONCE(sqe->len);
2821 req->buf_index = READ_ONCE(sqe->buf_index);
2825 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2831 case -ERESTARTNOINTR:
2832 case -ERESTARTNOHAND:
2833 case -ERESTART_RESTARTBLOCK:
2835 * We can't just restart the syscall, since previously
2836 * submitted sqes may already be in progress. Just fail this
2842 kiocb->ki_complete(kiocb, ret, 0);
2846 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2847 unsigned int issue_flags)
2849 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2850 struct io_async_rw *io = req->async_data;
2851 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2853 /* add previously done IO, if any */
2854 if (io && io->bytes_done > 0) {
2856 ret = io->bytes_done;
2858 ret += io->bytes_done;
2861 if (req->flags & REQ_F_CUR_POS)
2862 req->file->f_pos = kiocb->ki_pos;
2863 if (ret >= 0 && check_reissue)
2864 __io_complete_rw(req, ret, 0, issue_flags);
2866 io_rw_done(kiocb, ret);
2868 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2869 req->flags &= ~REQ_F_REISSUE;
2870 if (io_resubmit_prep(req)) {
2871 io_req_task_queue_reissue(req);
2874 __io_req_complete(req, issue_flags, ret,
2875 io_put_rw_kbuf(req));
2880 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2881 struct io_mapped_ubuf *imu)
2883 size_t len = req->rw.len;
2884 u64 buf_end, buf_addr = req->rw.addr;
2887 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2889 /* not inside the mapped region */
2890 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2894 * May not be a start of buffer, set size appropriately
2895 * and advance us to the beginning.
2897 offset = buf_addr - imu->ubuf;
2898 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2902 * Don't use iov_iter_advance() here, as it's really slow for
2903 * using the latter parts of a big fixed buffer - it iterates
2904 * over each segment manually. We can cheat a bit here, because
2907 * 1) it's a BVEC iter, we set it up
2908 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2909 * first and last bvec
2911 * So just find our index, and adjust the iterator afterwards.
2912 * If the offset is within the first bvec (or the whole first
2913 * bvec, just use iov_iter_advance(). This makes it easier
2914 * since we can just skip the first segment, which may not
2915 * be PAGE_SIZE aligned.
2917 const struct bio_vec *bvec = imu->bvec;
2919 if (offset <= bvec->bv_len) {
2920 iov_iter_advance(iter, offset);
2922 unsigned long seg_skip;
2924 /* skip first vec */
2925 offset -= bvec->bv_len;
2926 seg_skip = 1 + (offset >> PAGE_SHIFT);
2928 iter->bvec = bvec + seg_skip;
2929 iter->nr_segs -= seg_skip;
2930 iter->count -= bvec->bv_len + offset;
2931 iter->iov_offset = offset & ~PAGE_MASK;
2938 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2940 struct io_ring_ctx *ctx = req->ctx;
2941 struct io_mapped_ubuf *imu = req->imu;
2942 u16 index, buf_index = req->buf_index;
2945 if (unlikely(buf_index >= ctx->nr_user_bufs))
2947 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2948 imu = READ_ONCE(ctx->user_bufs[index]);
2951 return __io_import_fixed(req, rw, iter, imu);
2954 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2957 mutex_unlock(&ctx->uring_lock);
2960 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2963 * "Normal" inline submissions always hold the uring_lock, since we
2964 * grab it from the system call. Same is true for the SQPOLL offload.
2965 * The only exception is when we've detached the request and issue it
2966 * from an async worker thread, grab the lock for that case.
2969 mutex_lock(&ctx->uring_lock);
2972 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2973 int bgid, struct io_buffer *kbuf,
2976 struct io_buffer *head;
2978 if (req->flags & REQ_F_BUFFER_SELECTED)
2981 io_ring_submit_lock(req->ctx, needs_lock);
2983 lockdep_assert_held(&req->ctx->uring_lock);
2985 head = xa_load(&req->ctx->io_buffers, bgid);
2987 if (!list_empty(&head->list)) {
2988 kbuf = list_last_entry(&head->list, struct io_buffer,
2990 list_del(&kbuf->list);
2993 xa_erase(&req->ctx->io_buffers, bgid);
2995 if (*len > kbuf->len)
2998 kbuf = ERR_PTR(-ENOBUFS);
3001 io_ring_submit_unlock(req->ctx, needs_lock);
3006 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3009 struct io_buffer *kbuf;
3012 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3013 bgid = req->buf_index;
3014 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3017 req->rw.addr = (u64) (unsigned long) kbuf;
3018 req->flags |= REQ_F_BUFFER_SELECTED;
3019 return u64_to_user_ptr(kbuf->addr);
3022 #ifdef CONFIG_COMPAT
3023 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3026 struct compat_iovec __user *uiov;
3027 compat_ssize_t clen;
3031 uiov = u64_to_user_ptr(req->rw.addr);
3032 if (!access_ok(uiov, sizeof(*uiov)))
3034 if (__get_user(clen, &uiov->iov_len))
3040 buf = io_rw_buffer_select(req, &len, needs_lock);
3042 return PTR_ERR(buf);
3043 iov[0].iov_base = buf;
3044 iov[0].iov_len = (compat_size_t) len;
3049 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3052 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3056 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3059 len = iov[0].iov_len;
3062 buf = io_rw_buffer_select(req, &len, needs_lock);
3064 return PTR_ERR(buf);
3065 iov[0].iov_base = buf;
3066 iov[0].iov_len = len;
3070 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3073 if (req->flags & REQ_F_BUFFER_SELECTED) {
3074 struct io_buffer *kbuf;
3076 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3077 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3078 iov[0].iov_len = kbuf->len;
3081 if (req->rw.len != 1)
3084 #ifdef CONFIG_COMPAT
3085 if (req->ctx->compat)
3086 return io_compat_import(req, iov, needs_lock);
3089 return __io_iov_buffer_select(req, iov, needs_lock);
3092 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3093 struct iov_iter *iter, bool needs_lock)
3095 void __user *buf = u64_to_user_ptr(req->rw.addr);
3096 size_t sqe_len = req->rw.len;
3097 u8 opcode = req->opcode;
3100 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3102 return io_import_fixed(req, rw, iter);
3105 /* buffer index only valid with fixed read/write, or buffer select */
3106 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3109 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3110 if (req->flags & REQ_F_BUFFER_SELECT) {
3111 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3113 return PTR_ERR(buf);
3114 req->rw.len = sqe_len;
3117 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3122 if (req->flags & REQ_F_BUFFER_SELECT) {
3123 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3125 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3130 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3134 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3136 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3140 * For files that don't have ->read_iter() and ->write_iter(), handle them
3141 * by looping over ->read() or ->write() manually.
3143 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3145 struct kiocb *kiocb = &req->rw.kiocb;
3146 struct file *file = req->file;
3150 * Don't support polled IO through this interface, and we can't
3151 * support non-blocking either. For the latter, this just causes
3152 * the kiocb to be handled from an async context.
3154 if (kiocb->ki_flags & IOCB_HIPRI)
3156 if (kiocb->ki_flags & IOCB_NOWAIT)
3159 while (iov_iter_count(iter)) {
3163 if (!iov_iter_is_bvec(iter)) {
3164 iovec = iov_iter_iovec(iter);
3166 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3167 iovec.iov_len = req->rw.len;
3171 nr = file->f_op->read(file, iovec.iov_base,
3172 iovec.iov_len, io_kiocb_ppos(kiocb));
3174 nr = file->f_op->write(file, iovec.iov_base,
3175 iovec.iov_len, io_kiocb_ppos(kiocb));
3184 if (nr != iovec.iov_len)
3188 iov_iter_advance(iter, nr);
3194 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3195 const struct iovec *fast_iov, struct iov_iter *iter)
3197 struct io_async_rw *rw = req->async_data;
3199 memcpy(&rw->iter, iter, sizeof(*iter));
3200 rw->free_iovec = iovec;
3202 /* can only be fixed buffers, no need to do anything */
3203 if (iov_iter_is_bvec(iter))
3206 unsigned iov_off = 0;
3208 rw->iter.iov = rw->fast_iov;
3209 if (iter->iov != fast_iov) {
3210 iov_off = iter->iov - fast_iov;
3211 rw->iter.iov += iov_off;
3213 if (rw->fast_iov != fast_iov)
3214 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3215 sizeof(struct iovec) * iter->nr_segs);
3217 req->flags |= REQ_F_NEED_CLEANUP;
3221 static inline int io_alloc_async_data(struct io_kiocb *req)
3223 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3224 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3225 return req->async_data == NULL;
3228 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3229 const struct iovec *fast_iov,
3230 struct iov_iter *iter, bool force)
3232 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3234 if (!req->async_data) {
3235 if (io_alloc_async_data(req)) {
3240 io_req_map_rw(req, iovec, fast_iov, iter);
3245 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3247 struct io_async_rw *iorw = req->async_data;
3248 struct iovec *iov = iorw->fast_iov;
3251 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3252 if (unlikely(ret < 0))
3255 iorw->bytes_done = 0;
3256 iorw->free_iovec = iov;
3258 req->flags |= REQ_F_NEED_CLEANUP;
3262 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3264 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3266 return io_prep_rw(req, sqe);
3270 * This is our waitqueue callback handler, registered through lock_page_async()
3271 * when we initially tried to do the IO with the iocb armed our waitqueue.
3272 * This gets called when the page is unlocked, and we generally expect that to
3273 * happen when the page IO is completed and the page is now uptodate. This will
3274 * queue a task_work based retry of the operation, attempting to copy the data
3275 * again. If the latter fails because the page was NOT uptodate, then we will
3276 * do a thread based blocking retry of the operation. That's the unexpected
3279 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3280 int sync, void *arg)
3282 struct wait_page_queue *wpq;
3283 struct io_kiocb *req = wait->private;
3284 struct wait_page_key *key = arg;
3286 wpq = container_of(wait, struct wait_page_queue, wait);
3288 if (!wake_page_match(wpq, key))
3291 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3292 list_del_init(&wait->entry);
3293 io_req_task_queue(req);
3298 * This controls whether a given IO request should be armed for async page
3299 * based retry. If we return false here, the request is handed to the async
3300 * worker threads for retry. If we're doing buffered reads on a regular file,
3301 * we prepare a private wait_page_queue entry and retry the operation. This
3302 * will either succeed because the page is now uptodate and unlocked, or it
3303 * will register a callback when the page is unlocked at IO completion. Through
3304 * that callback, io_uring uses task_work to setup a retry of the operation.
3305 * That retry will attempt the buffered read again. The retry will generally
3306 * succeed, or in rare cases where it fails, we then fall back to using the
3307 * async worker threads for a blocking retry.
3309 static bool io_rw_should_retry(struct io_kiocb *req)
3311 struct io_async_rw *rw = req->async_data;
3312 struct wait_page_queue *wait = &rw->wpq;
3313 struct kiocb *kiocb = &req->rw.kiocb;
3315 /* never retry for NOWAIT, we just complete with -EAGAIN */
3316 if (req->flags & REQ_F_NOWAIT)
3319 /* Only for buffered IO */
3320 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3324 * just use poll if we can, and don't attempt if the fs doesn't
3325 * support callback based unlocks
3327 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3330 wait->wait.func = io_async_buf_func;
3331 wait->wait.private = req;
3332 wait->wait.flags = 0;
3333 INIT_LIST_HEAD(&wait->wait.entry);
3334 kiocb->ki_flags |= IOCB_WAITQ;
3335 kiocb->ki_flags &= ~IOCB_NOWAIT;
3336 kiocb->ki_waitq = wait;
3340 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3342 if (req->file->f_op->read_iter)
3343 return call_read_iter(req->file, &req->rw.kiocb, iter);
3344 else if (req->file->f_op->read)
3345 return loop_rw_iter(READ, req, iter);
3350 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3352 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3353 struct kiocb *kiocb = &req->rw.kiocb;
3354 struct iov_iter __iter, *iter = &__iter;
3355 struct io_async_rw *rw = req->async_data;
3356 ssize_t io_size, ret, ret2;
3357 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3363 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3367 io_size = iov_iter_count(iter);
3368 req->result = io_size;
3370 /* Ensure we clear previously set non-block flag */
3371 if (!force_nonblock)
3372 kiocb->ki_flags &= ~IOCB_NOWAIT;
3374 kiocb->ki_flags |= IOCB_NOWAIT;
3376 /* If the file doesn't support async, just async punt */
3377 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3378 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3379 return ret ?: -EAGAIN;
3382 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3383 if (unlikely(ret)) {
3388 ret = io_iter_do_read(req, iter);
3390 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3391 req->flags &= ~REQ_F_REISSUE;
3392 /* IOPOLL retry should happen for io-wq threads */
3393 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3395 /* no retry on NONBLOCK nor RWF_NOWAIT */
3396 if (req->flags & REQ_F_NOWAIT)
3398 /* some cases will consume bytes even on error returns */
3399 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3401 } else if (ret == -EIOCBQUEUED) {
3403 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3404 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3405 /* read all, failed, already did sync or don't want to retry */
3409 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3414 rw = req->async_data;
3415 /* now use our persistent iterator, if we aren't already */
3420 rw->bytes_done += ret;
3421 /* if we can retry, do so with the callbacks armed */
3422 if (!io_rw_should_retry(req)) {
3423 kiocb->ki_flags &= ~IOCB_WAITQ;
3428 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3429 * we get -EIOCBQUEUED, then we'll get a notification when the
3430 * desired page gets unlocked. We can also get a partial read
3431 * here, and if we do, then just retry at the new offset.
3433 ret = io_iter_do_read(req, iter);
3434 if (ret == -EIOCBQUEUED)
3436 /* we got some bytes, but not all. retry. */
3437 kiocb->ki_flags &= ~IOCB_WAITQ;
3438 } while (ret > 0 && ret < io_size);
3440 kiocb_done(kiocb, ret, issue_flags);
3442 /* it's faster to check here then delegate to kfree */
3448 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3450 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3452 return io_prep_rw(req, sqe);
3455 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3457 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3458 struct kiocb *kiocb = &req->rw.kiocb;
3459 struct iov_iter __iter, *iter = &__iter;
3460 struct io_async_rw *rw = req->async_data;
3461 ssize_t ret, ret2, io_size;
3462 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3468 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3472 io_size = iov_iter_count(iter);
3473 req->result = io_size;
3475 /* Ensure we clear previously set non-block flag */
3476 if (!force_nonblock)
3477 kiocb->ki_flags &= ~IOCB_NOWAIT;
3479 kiocb->ki_flags |= IOCB_NOWAIT;
3481 /* If the file doesn't support async, just async punt */
3482 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3485 /* file path doesn't support NOWAIT for non-direct_IO */
3486 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3487 (req->flags & REQ_F_ISREG))
3490 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3495 * Open-code file_start_write here to grab freeze protection,
3496 * which will be released by another thread in
3497 * io_complete_rw(). Fool lockdep by telling it the lock got
3498 * released so that it doesn't complain about the held lock when
3499 * we return to userspace.
3501 if (req->flags & REQ_F_ISREG) {
3502 sb_start_write(file_inode(req->file)->i_sb);
3503 __sb_writers_release(file_inode(req->file)->i_sb,
3506 kiocb->ki_flags |= IOCB_WRITE;
3508 if (req->file->f_op->write_iter)
3509 ret2 = call_write_iter(req->file, kiocb, iter);
3510 else if (req->file->f_op->write)
3511 ret2 = loop_rw_iter(WRITE, req, iter);
3515 if (req->flags & REQ_F_REISSUE) {
3516 req->flags &= ~REQ_F_REISSUE;
3521 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3522 * retry them without IOCB_NOWAIT.
3524 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3526 /* no retry on NONBLOCK nor RWF_NOWAIT */
3527 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3529 if (!force_nonblock || ret2 != -EAGAIN) {
3530 /* IOPOLL retry should happen for io-wq threads */
3531 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3534 kiocb_done(kiocb, ret2, issue_flags);
3537 /* some cases will consume bytes even on error returns */
3538 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3539 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3540 return ret ?: -EAGAIN;
3543 /* it's reportedly faster than delegating the null check to kfree() */
3549 static int io_renameat_prep(struct io_kiocb *req,
3550 const struct io_uring_sqe *sqe)
3552 struct io_rename *ren = &req->rename;
3553 const char __user *oldf, *newf;
3555 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3557 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3559 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3562 ren->old_dfd = READ_ONCE(sqe->fd);
3563 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3564 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3565 ren->new_dfd = READ_ONCE(sqe->len);
3566 ren->flags = READ_ONCE(sqe->rename_flags);
3568 ren->oldpath = getname(oldf);
3569 if (IS_ERR(ren->oldpath))
3570 return PTR_ERR(ren->oldpath);
3572 ren->newpath = getname(newf);
3573 if (IS_ERR(ren->newpath)) {
3574 putname(ren->oldpath);
3575 return PTR_ERR(ren->newpath);
3578 req->flags |= REQ_F_NEED_CLEANUP;
3582 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3584 struct io_rename *ren = &req->rename;
3587 if (issue_flags & IO_URING_F_NONBLOCK)
3590 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3591 ren->newpath, ren->flags);
3593 req->flags &= ~REQ_F_NEED_CLEANUP;
3596 io_req_complete(req, ret);
3600 static int io_unlinkat_prep(struct io_kiocb *req,
3601 const struct io_uring_sqe *sqe)
3603 struct io_unlink *un = &req->unlink;
3604 const char __user *fname;
3606 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3608 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3611 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3614 un->dfd = READ_ONCE(sqe->fd);
3616 un->flags = READ_ONCE(sqe->unlink_flags);
3617 if (un->flags & ~AT_REMOVEDIR)
3620 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3621 un->filename = getname(fname);
3622 if (IS_ERR(un->filename))
3623 return PTR_ERR(un->filename);
3625 req->flags |= REQ_F_NEED_CLEANUP;
3629 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3631 struct io_unlink *un = &req->unlink;
3634 if (issue_flags & IO_URING_F_NONBLOCK)
3637 if (un->flags & AT_REMOVEDIR)
3638 ret = do_rmdir(un->dfd, un->filename);
3640 ret = do_unlinkat(un->dfd, un->filename);
3642 req->flags &= ~REQ_F_NEED_CLEANUP;
3645 io_req_complete(req, ret);
3649 static int io_shutdown_prep(struct io_kiocb *req,
3650 const struct io_uring_sqe *sqe)
3652 #if defined(CONFIG_NET)
3653 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3655 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3656 sqe->buf_index || sqe->splice_fd_in))
3659 req->shutdown.how = READ_ONCE(sqe->len);
3666 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3668 #if defined(CONFIG_NET)
3669 struct socket *sock;
3672 if (issue_flags & IO_URING_F_NONBLOCK)
3675 sock = sock_from_file(req->file);
3676 if (unlikely(!sock))
3679 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3682 io_req_complete(req, ret);
3689 static int __io_splice_prep(struct io_kiocb *req,
3690 const struct io_uring_sqe *sqe)
3692 struct io_splice *sp = &req->splice;
3693 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3695 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3699 sp->len = READ_ONCE(sqe->len);
3700 sp->flags = READ_ONCE(sqe->splice_flags);
3702 if (unlikely(sp->flags & ~valid_flags))
3705 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3706 (sp->flags & SPLICE_F_FD_IN_FIXED));
3709 req->flags |= REQ_F_NEED_CLEANUP;
3713 static int io_tee_prep(struct io_kiocb *req,
3714 const struct io_uring_sqe *sqe)
3716 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3718 return __io_splice_prep(req, sqe);
3721 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3723 struct io_splice *sp = &req->splice;
3724 struct file *in = sp->file_in;
3725 struct file *out = sp->file_out;
3726 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3729 if (issue_flags & IO_URING_F_NONBLOCK)
3732 ret = do_tee(in, out, sp->len, flags);
3734 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3736 req->flags &= ~REQ_F_NEED_CLEANUP;
3740 io_req_complete(req, ret);
3744 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3746 struct io_splice *sp = &req->splice;
3748 sp->off_in = READ_ONCE(sqe->splice_off_in);
3749 sp->off_out = READ_ONCE(sqe->off);
3750 return __io_splice_prep(req, sqe);
3753 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3755 struct io_splice *sp = &req->splice;
3756 struct file *in = sp->file_in;
3757 struct file *out = sp->file_out;
3758 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3759 loff_t *poff_in, *poff_out;
3762 if (issue_flags & IO_URING_F_NONBLOCK)
3765 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3766 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3769 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3771 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3773 req->flags &= ~REQ_F_NEED_CLEANUP;
3777 io_req_complete(req, ret);
3782 * IORING_OP_NOP just posts a completion event, nothing else.
3784 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3786 struct io_ring_ctx *ctx = req->ctx;
3788 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3791 __io_req_complete(req, issue_flags, 0, 0);
3795 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3797 struct io_ring_ctx *ctx = req->ctx;
3802 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3804 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
3808 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3809 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3812 req->sync.off = READ_ONCE(sqe->off);
3813 req->sync.len = READ_ONCE(sqe->len);
3817 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3819 loff_t end = req->sync.off + req->sync.len;
3822 /* fsync always requires a blocking context */
3823 if (issue_flags & IO_URING_F_NONBLOCK)
3826 ret = vfs_fsync_range(req->file, req->sync.off,
3827 end > 0 ? end : LLONG_MAX,
3828 req->sync.flags & IORING_FSYNC_DATASYNC);
3831 io_req_complete(req, ret);
3835 static int io_fallocate_prep(struct io_kiocb *req,
3836 const struct io_uring_sqe *sqe)
3838 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
3841 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3844 req->sync.off = READ_ONCE(sqe->off);
3845 req->sync.len = READ_ONCE(sqe->addr);
3846 req->sync.mode = READ_ONCE(sqe->len);
3850 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3854 /* fallocate always requiring blocking context */
3855 if (issue_flags & IO_URING_F_NONBLOCK)
3857 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3861 io_req_complete(req, ret);
3865 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3867 const char __user *fname;
3870 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3872 if (unlikely(sqe->ioprio || sqe->buf_index))
3874 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3877 /* open.how should be already initialised */
3878 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3879 req->open.how.flags |= O_LARGEFILE;
3881 req->open.dfd = READ_ONCE(sqe->fd);
3882 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3883 req->open.filename = getname(fname);
3884 if (IS_ERR(req->open.filename)) {
3885 ret = PTR_ERR(req->open.filename);
3886 req->open.filename = NULL;
3890 req->open.file_slot = READ_ONCE(sqe->file_index);
3891 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
3894 req->open.nofile = rlimit(RLIMIT_NOFILE);
3895 req->flags |= REQ_F_NEED_CLEANUP;
3899 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3901 u64 mode = READ_ONCE(sqe->len);
3902 u64 flags = READ_ONCE(sqe->open_flags);
3904 req->open.how = build_open_how(flags, mode);
3905 return __io_openat_prep(req, sqe);
3908 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3910 struct open_how __user *how;
3914 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3915 len = READ_ONCE(sqe->len);
3916 if (len < OPEN_HOW_SIZE_VER0)
3919 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3924 return __io_openat_prep(req, sqe);
3927 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3929 struct open_flags op;
3931 bool resolve_nonblock, nonblock_set;
3932 bool fixed = !!req->open.file_slot;
3935 ret = build_open_flags(&req->open.how, &op);
3938 nonblock_set = op.open_flag & O_NONBLOCK;
3939 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3940 if (issue_flags & IO_URING_F_NONBLOCK) {
3942 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3943 * it'll always -EAGAIN
3945 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3947 op.lookup_flags |= LOOKUP_CACHED;
3948 op.open_flag |= O_NONBLOCK;
3952 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3957 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3960 * We could hang on to this 'fd' on retrying, but seems like
3961 * marginal gain for something that is now known to be a slower
3962 * path. So just put it, and we'll get a new one when we retry.
3967 ret = PTR_ERR(file);
3968 /* only retry if RESOLVE_CACHED wasn't already set by application */
3969 if (ret == -EAGAIN &&
3970 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
3975 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3976 file->f_flags &= ~O_NONBLOCK;
3977 fsnotify_open(file);
3980 fd_install(ret, file);
3982 ret = io_install_fixed_file(req, file, issue_flags,
3983 req->open.file_slot - 1);
3985 putname(req->open.filename);
3986 req->flags &= ~REQ_F_NEED_CLEANUP;
3989 __io_req_complete(req, issue_flags, ret, 0);
3993 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3995 return io_openat2(req, issue_flags);
3998 static int io_remove_buffers_prep(struct io_kiocb *req,
3999 const struct io_uring_sqe *sqe)
4001 struct io_provide_buf *p = &req->pbuf;
4004 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4008 tmp = READ_ONCE(sqe->fd);
4009 if (!tmp || tmp > USHRT_MAX)
4012 memset(p, 0, sizeof(*p));
4014 p->bgid = READ_ONCE(sqe->buf_group);
4018 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4019 int bgid, unsigned nbufs)
4023 /* shouldn't happen */
4027 /* the head kbuf is the list itself */
4028 while (!list_empty(&buf->list)) {
4029 struct io_buffer *nxt;
4031 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4032 list_del(&nxt->list);
4039 xa_erase(&ctx->io_buffers, bgid);
4044 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4046 struct io_provide_buf *p = &req->pbuf;
4047 struct io_ring_ctx *ctx = req->ctx;
4048 struct io_buffer *head;
4050 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4052 io_ring_submit_lock(ctx, !force_nonblock);
4054 lockdep_assert_held(&ctx->uring_lock);
4057 head = xa_load(&ctx->io_buffers, p->bgid);
4059 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4063 /* complete before unlock, IOPOLL may need the lock */
4064 __io_req_complete(req, issue_flags, ret, 0);
4065 io_ring_submit_unlock(ctx, !force_nonblock);
4069 static int io_provide_buffers_prep(struct io_kiocb *req,
4070 const struct io_uring_sqe *sqe)
4072 unsigned long size, tmp_check;
4073 struct io_provide_buf *p = &req->pbuf;
4076 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4079 tmp = READ_ONCE(sqe->fd);
4080 if (!tmp || tmp > USHRT_MAX)
4083 p->addr = READ_ONCE(sqe->addr);
4084 p->len = READ_ONCE(sqe->len);
4086 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4089 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4092 size = (unsigned long)p->len * p->nbufs;
4093 if (!access_ok(u64_to_user_ptr(p->addr), size))
4096 p->bgid = READ_ONCE(sqe->buf_group);
4097 tmp = READ_ONCE(sqe->off);
4098 if (tmp > USHRT_MAX)
4104 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4106 struct io_buffer *buf;
4107 u64 addr = pbuf->addr;
4108 int i, bid = pbuf->bid;
4110 for (i = 0; i < pbuf->nbufs; i++) {
4111 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4116 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4121 INIT_LIST_HEAD(&buf->list);
4124 list_add_tail(&buf->list, &(*head)->list);
4128 return i ? i : -ENOMEM;
4131 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4133 struct io_provide_buf *p = &req->pbuf;
4134 struct io_ring_ctx *ctx = req->ctx;
4135 struct io_buffer *head, *list;
4137 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4139 io_ring_submit_lock(ctx, !force_nonblock);
4141 lockdep_assert_held(&ctx->uring_lock);
4143 list = head = xa_load(&ctx->io_buffers, p->bgid);
4145 ret = io_add_buffers(p, &head);
4146 if (ret >= 0 && !list) {
4147 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4149 __io_remove_buffers(ctx, head, p->bgid, -1U);
4153 /* complete before unlock, IOPOLL may need the lock */
4154 __io_req_complete(req, issue_flags, ret, 0);
4155 io_ring_submit_unlock(ctx, !force_nonblock);
4159 static int io_epoll_ctl_prep(struct io_kiocb *req,
4160 const struct io_uring_sqe *sqe)
4162 #if defined(CONFIG_EPOLL)
4163 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4165 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4168 req->epoll.epfd = READ_ONCE(sqe->fd);
4169 req->epoll.op = READ_ONCE(sqe->len);
4170 req->epoll.fd = READ_ONCE(sqe->off);
4172 if (ep_op_has_event(req->epoll.op)) {
4173 struct epoll_event __user *ev;
4175 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4176 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4186 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4188 #if defined(CONFIG_EPOLL)
4189 struct io_epoll *ie = &req->epoll;
4191 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4193 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4194 if (force_nonblock && ret == -EAGAIN)
4199 __io_req_complete(req, issue_flags, ret, 0);
4206 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4208 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4209 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4211 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4214 req->madvise.addr = READ_ONCE(sqe->addr);
4215 req->madvise.len = READ_ONCE(sqe->len);
4216 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4223 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4225 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4226 struct io_madvise *ma = &req->madvise;
4229 if (issue_flags & IO_URING_F_NONBLOCK)
4232 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4235 io_req_complete(req, ret);
4242 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4244 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4246 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4249 req->fadvise.offset = READ_ONCE(sqe->off);
4250 req->fadvise.len = READ_ONCE(sqe->len);
4251 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4255 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4257 struct io_fadvise *fa = &req->fadvise;
4260 if (issue_flags & IO_URING_F_NONBLOCK) {
4261 switch (fa->advice) {
4262 case POSIX_FADV_NORMAL:
4263 case POSIX_FADV_RANDOM:
4264 case POSIX_FADV_SEQUENTIAL:
4271 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4274 __io_req_complete(req, issue_flags, ret, 0);
4278 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4280 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4282 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4284 if (req->flags & REQ_F_FIXED_FILE)
4287 req->statx.dfd = READ_ONCE(sqe->fd);
4288 req->statx.mask = READ_ONCE(sqe->len);
4289 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4290 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4291 req->statx.flags = READ_ONCE(sqe->statx_flags);
4296 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4298 struct io_statx *ctx = &req->statx;
4301 if (issue_flags & IO_URING_F_NONBLOCK)
4304 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4309 io_req_complete(req, ret);
4313 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4315 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4317 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4318 sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4320 if (req->flags & REQ_F_FIXED_FILE)
4323 req->close.fd = READ_ONCE(sqe->fd);
4327 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4329 struct files_struct *files = current->files;
4330 struct io_close *close = &req->close;
4331 struct fdtable *fdt;
4332 struct file *file = NULL;
4335 spin_lock(&files->file_lock);
4336 fdt = files_fdtable(files);
4337 if (close->fd >= fdt->max_fds) {
4338 spin_unlock(&files->file_lock);
4341 file = fdt->fd[close->fd];
4342 if (!file || file->f_op == &io_uring_fops) {
4343 spin_unlock(&files->file_lock);
4348 /* if the file has a flush method, be safe and punt to async */
4349 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4350 spin_unlock(&files->file_lock);
4354 ret = __close_fd_get_file(close->fd, &file);
4355 spin_unlock(&files->file_lock);
4362 /* No ->flush() or already async, safely close from here */
4363 ret = filp_close(file, current->files);
4369 __io_req_complete(req, issue_flags, ret, 0);
4373 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4375 struct io_ring_ctx *ctx = req->ctx;
4377 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4379 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4383 req->sync.off = READ_ONCE(sqe->off);
4384 req->sync.len = READ_ONCE(sqe->len);
4385 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4389 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4393 /* sync_file_range always requires a blocking context */
4394 if (issue_flags & IO_URING_F_NONBLOCK)
4397 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4401 io_req_complete(req, ret);
4405 #if defined(CONFIG_NET)
4406 static int io_setup_async_msg(struct io_kiocb *req,
4407 struct io_async_msghdr *kmsg)
4409 struct io_async_msghdr *async_msg = req->async_data;
4413 if (io_alloc_async_data(req)) {
4414 kfree(kmsg->free_iov);
4417 async_msg = req->async_data;
4418 req->flags |= REQ_F_NEED_CLEANUP;
4419 memcpy(async_msg, kmsg, sizeof(*kmsg));
4420 async_msg->msg.msg_name = &async_msg->addr;
4421 /* if were using fast_iov, set it to the new one */
4422 if (!async_msg->free_iov)
4423 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4428 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4429 struct io_async_msghdr *iomsg)
4431 iomsg->msg.msg_name = &iomsg->addr;
4432 iomsg->free_iov = iomsg->fast_iov;
4433 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4434 req->sr_msg.msg_flags, &iomsg->free_iov);
4437 static int io_sendmsg_prep_async(struct io_kiocb *req)
4441 ret = io_sendmsg_copy_hdr(req, req->async_data);
4443 req->flags |= REQ_F_NEED_CLEANUP;
4447 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4449 struct io_sr_msg *sr = &req->sr_msg;
4451 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4454 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4455 sr->len = READ_ONCE(sqe->len);
4456 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4457 if (sr->msg_flags & MSG_DONTWAIT)
4458 req->flags |= REQ_F_NOWAIT;
4460 #ifdef CONFIG_COMPAT
4461 if (req->ctx->compat)
4462 sr->msg_flags |= MSG_CMSG_COMPAT;
4467 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4469 struct io_async_msghdr iomsg, *kmsg;
4470 struct socket *sock;
4475 sock = sock_from_file(req->file);
4476 if (unlikely(!sock))
4479 kmsg = req->async_data;
4481 ret = io_sendmsg_copy_hdr(req, &iomsg);
4487 flags = req->sr_msg.msg_flags;
4488 if (issue_flags & IO_URING_F_NONBLOCK)
4489 flags |= MSG_DONTWAIT;
4490 if (flags & MSG_WAITALL)
4491 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4493 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4494 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4495 return io_setup_async_msg(req, kmsg);
4496 if (ret == -ERESTARTSYS)
4499 /* fast path, check for non-NULL to avoid function call */
4501 kfree(kmsg->free_iov);
4502 req->flags &= ~REQ_F_NEED_CLEANUP;
4505 __io_req_complete(req, issue_flags, ret, 0);
4509 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4511 struct io_sr_msg *sr = &req->sr_msg;
4514 struct socket *sock;
4519 sock = sock_from_file(req->file);
4520 if (unlikely(!sock))
4523 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4527 msg.msg_name = NULL;
4528 msg.msg_control = NULL;
4529 msg.msg_controllen = 0;
4530 msg.msg_namelen = 0;
4532 flags = req->sr_msg.msg_flags;
4533 if (issue_flags & IO_URING_F_NONBLOCK)
4534 flags |= MSG_DONTWAIT;
4535 if (flags & MSG_WAITALL)
4536 min_ret = iov_iter_count(&msg.msg_iter);
4538 msg.msg_flags = flags;
4539 ret = sock_sendmsg(sock, &msg);
4540 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4542 if (ret == -ERESTARTSYS)
4547 __io_req_complete(req, issue_flags, ret, 0);
4551 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4552 struct io_async_msghdr *iomsg)
4554 struct io_sr_msg *sr = &req->sr_msg;
4555 struct iovec __user *uiov;
4559 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4560 &iomsg->uaddr, &uiov, &iov_len);
4564 if (req->flags & REQ_F_BUFFER_SELECT) {
4567 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4569 sr->len = iomsg->fast_iov[0].iov_len;
4570 iomsg->free_iov = NULL;
4572 iomsg->free_iov = iomsg->fast_iov;
4573 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4574 &iomsg->free_iov, &iomsg->msg.msg_iter,
4583 #ifdef CONFIG_COMPAT
4584 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4585 struct io_async_msghdr *iomsg)
4587 struct io_sr_msg *sr = &req->sr_msg;
4588 struct compat_iovec __user *uiov;
4593 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4598 uiov = compat_ptr(ptr);
4599 if (req->flags & REQ_F_BUFFER_SELECT) {
4600 compat_ssize_t clen;
4604 if (!access_ok(uiov, sizeof(*uiov)))
4606 if (__get_user(clen, &uiov->iov_len))
4611 iomsg->free_iov = NULL;
4613 iomsg->free_iov = iomsg->fast_iov;
4614 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4615 UIO_FASTIOV, &iomsg->free_iov,
4616 &iomsg->msg.msg_iter, true);
4625 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4626 struct io_async_msghdr *iomsg)
4628 iomsg->msg.msg_name = &iomsg->addr;
4630 #ifdef CONFIG_COMPAT
4631 if (req->ctx->compat)
4632 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4635 return __io_recvmsg_copy_hdr(req, iomsg);
4638 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4641 struct io_sr_msg *sr = &req->sr_msg;
4642 struct io_buffer *kbuf;
4644 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4649 req->flags |= REQ_F_BUFFER_SELECTED;
4653 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4655 return io_put_kbuf(req, req->sr_msg.kbuf);
4658 static int io_recvmsg_prep_async(struct io_kiocb *req)
4662 ret = io_recvmsg_copy_hdr(req, req->async_data);
4664 req->flags |= REQ_F_NEED_CLEANUP;
4668 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4670 struct io_sr_msg *sr = &req->sr_msg;
4672 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4675 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4676 sr->len = READ_ONCE(sqe->len);
4677 sr->bgid = READ_ONCE(sqe->buf_group);
4678 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4679 if (sr->msg_flags & MSG_DONTWAIT)
4680 req->flags |= REQ_F_NOWAIT;
4682 #ifdef CONFIG_COMPAT
4683 if (req->ctx->compat)
4684 sr->msg_flags |= MSG_CMSG_COMPAT;
4689 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4691 struct io_async_msghdr iomsg, *kmsg;
4692 struct socket *sock;
4693 struct io_buffer *kbuf;
4696 int ret, cflags = 0;
4697 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4699 sock = sock_from_file(req->file);
4700 if (unlikely(!sock))
4703 kmsg = req->async_data;
4705 ret = io_recvmsg_copy_hdr(req, &iomsg);
4711 if (req->flags & REQ_F_BUFFER_SELECT) {
4712 kbuf = io_recv_buffer_select(req, !force_nonblock);
4714 return PTR_ERR(kbuf);
4715 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4716 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4717 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4718 1, req->sr_msg.len);
4721 flags = req->sr_msg.msg_flags;
4723 flags |= MSG_DONTWAIT;
4724 if (flags & MSG_WAITALL)
4725 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4727 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4728 kmsg->uaddr, flags);
4729 if (force_nonblock && ret == -EAGAIN)
4730 return io_setup_async_msg(req, kmsg);
4731 if (ret == -ERESTARTSYS)
4734 if (req->flags & REQ_F_BUFFER_SELECTED)
4735 cflags = io_put_recv_kbuf(req);
4736 /* fast path, check for non-NULL to avoid function call */
4738 kfree(kmsg->free_iov);
4739 req->flags &= ~REQ_F_NEED_CLEANUP;
4740 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4742 __io_req_complete(req, issue_flags, ret, cflags);
4746 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4748 struct io_buffer *kbuf;
4749 struct io_sr_msg *sr = &req->sr_msg;
4751 void __user *buf = sr->buf;
4752 struct socket *sock;
4756 int ret, cflags = 0;
4757 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4759 sock = sock_from_file(req->file);
4760 if (unlikely(!sock))
4763 if (req->flags & REQ_F_BUFFER_SELECT) {
4764 kbuf = io_recv_buffer_select(req, !force_nonblock);
4766 return PTR_ERR(kbuf);
4767 buf = u64_to_user_ptr(kbuf->addr);
4770 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4774 msg.msg_name = NULL;
4775 msg.msg_control = NULL;
4776 msg.msg_controllen = 0;
4777 msg.msg_namelen = 0;
4778 msg.msg_iocb = NULL;
4781 flags = req->sr_msg.msg_flags;
4783 flags |= MSG_DONTWAIT;
4784 if (flags & MSG_WAITALL)
4785 min_ret = iov_iter_count(&msg.msg_iter);
4787 ret = sock_recvmsg(sock, &msg, flags);
4788 if (force_nonblock && ret == -EAGAIN)
4790 if (ret == -ERESTARTSYS)
4793 if (req->flags & REQ_F_BUFFER_SELECTED)
4794 cflags = io_put_recv_kbuf(req);
4795 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4797 __io_req_complete(req, issue_flags, ret, cflags);
4801 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4803 struct io_accept *accept = &req->accept;
4805 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4807 if (sqe->ioprio || sqe->len || sqe->buf_index)
4810 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4811 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4812 accept->flags = READ_ONCE(sqe->accept_flags);
4813 accept->nofile = rlimit(RLIMIT_NOFILE);
4815 accept->file_slot = READ_ONCE(sqe->file_index);
4816 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
4817 (accept->flags & SOCK_CLOEXEC)))
4819 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4821 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
4822 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
4826 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4828 struct io_accept *accept = &req->accept;
4829 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4830 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4831 bool fixed = !!accept->file_slot;
4835 if (req->file->f_flags & O_NONBLOCK)
4836 req->flags |= REQ_F_NOWAIT;
4839 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
4840 if (unlikely(fd < 0))
4843 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
4848 ret = PTR_ERR(file);
4849 if (ret == -EAGAIN && force_nonblock)
4851 if (ret == -ERESTARTSYS)
4854 } else if (!fixed) {
4855 fd_install(fd, file);
4858 ret = io_install_fixed_file(req, file, issue_flags,
4859 accept->file_slot - 1);
4861 __io_req_complete(req, issue_flags, ret, 0);
4865 static int io_connect_prep_async(struct io_kiocb *req)
4867 struct io_async_connect *io = req->async_data;
4868 struct io_connect *conn = &req->connect;
4870 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4873 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4875 struct io_connect *conn = &req->connect;
4877 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4879 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
4883 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4884 conn->addr_len = READ_ONCE(sqe->addr2);
4888 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4890 struct io_async_connect __io, *io;
4891 unsigned file_flags;
4893 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4895 if (req->async_data) {
4896 io = req->async_data;
4898 ret = move_addr_to_kernel(req->connect.addr,
4899 req->connect.addr_len,
4906 file_flags = force_nonblock ? O_NONBLOCK : 0;
4908 ret = __sys_connect_file(req->file, &io->address,
4909 req->connect.addr_len, file_flags);
4910 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4911 if (req->async_data)
4913 if (io_alloc_async_data(req)) {
4917 memcpy(req->async_data, &__io, sizeof(__io));
4920 if (ret == -ERESTARTSYS)
4925 __io_req_complete(req, issue_flags, ret, 0);
4928 #else /* !CONFIG_NET */
4929 #define IO_NETOP_FN(op) \
4930 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4932 return -EOPNOTSUPP; \
4935 #define IO_NETOP_PREP(op) \
4937 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4939 return -EOPNOTSUPP; \
4942 #define IO_NETOP_PREP_ASYNC(op) \
4944 static int io_##op##_prep_async(struct io_kiocb *req) \
4946 return -EOPNOTSUPP; \
4949 IO_NETOP_PREP_ASYNC(sendmsg);
4950 IO_NETOP_PREP_ASYNC(recvmsg);
4951 IO_NETOP_PREP_ASYNC(connect);
4952 IO_NETOP_PREP(accept);
4955 #endif /* CONFIG_NET */
4957 struct io_poll_table {
4958 struct poll_table_struct pt;
4959 struct io_kiocb *req;
4964 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4965 __poll_t mask, io_req_tw_func_t func)
4967 /* for instances that support it check for an event match first: */
4968 if (mask && !(mask & poll->events))
4971 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4973 list_del_init(&poll->wait.entry);
4976 req->io_task_work.func = func;
4979 * If this fails, then the task is exiting. When a task exits, the
4980 * work gets canceled, so just cancel this request as well instead
4981 * of executing it. We can't safely execute it anyway, as we may not
4982 * have the needed state needed for it anyway.
4984 io_req_task_work_add(req);
4988 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4989 __acquires(&req->ctx->completion_lock)
4991 struct io_ring_ctx *ctx = req->ctx;
4993 /* req->task == current here, checking PF_EXITING is safe */
4994 if (unlikely(req->task->flags & PF_EXITING))
4995 WRITE_ONCE(poll->canceled, true);
4997 if (!req->result && !READ_ONCE(poll->canceled)) {
4998 struct poll_table_struct pt = { ._key = poll->events };
5000 req->result = vfs_poll(req->file, &pt) & poll->events;
5003 spin_lock(&ctx->completion_lock);
5004 if (!req->result && !READ_ONCE(poll->canceled)) {
5005 add_wait_queue(poll->head, &poll->wait);
5012 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5014 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5015 if (req->opcode == IORING_OP_POLL_ADD)
5016 return req->async_data;
5017 return req->apoll->double_poll;
5020 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5022 if (req->opcode == IORING_OP_POLL_ADD)
5024 return &req->apoll->poll;
5027 static void io_poll_remove_double(struct io_kiocb *req)
5028 __must_hold(&req->ctx->completion_lock)
5030 struct io_poll_iocb *poll = io_poll_get_double(req);
5032 lockdep_assert_held(&req->ctx->completion_lock);
5034 if (poll && poll->head) {
5035 struct wait_queue_head *head = poll->head;
5037 spin_lock_irq(&head->lock);
5038 list_del_init(&poll->wait.entry);
5039 if (poll->wait.private)
5042 spin_unlock_irq(&head->lock);
5046 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5047 __must_hold(&req->ctx->completion_lock)
5049 struct io_ring_ctx *ctx = req->ctx;
5050 unsigned flags = IORING_CQE_F_MORE;
5053 if (READ_ONCE(req->poll.canceled)) {
5055 req->poll.events |= EPOLLONESHOT;
5057 error = mangle_poll(mask);
5059 if (req->poll.events & EPOLLONESHOT)
5061 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5062 req->poll.done = true;
5065 if (flags & IORING_CQE_F_MORE)
5068 io_commit_cqring(ctx);
5069 return !(flags & IORING_CQE_F_MORE);
5072 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5074 struct io_ring_ctx *ctx = req->ctx;
5075 struct io_kiocb *nxt;
5077 if (io_poll_rewait(req, &req->poll)) {
5078 spin_unlock(&ctx->completion_lock);
5082 done = io_poll_complete(req, req->result);
5084 io_poll_remove_double(req);
5085 hash_del(&req->hash_node);
5088 add_wait_queue(req->poll.head, &req->poll.wait);
5090 spin_unlock(&ctx->completion_lock);
5091 io_cqring_ev_posted(ctx);
5094 nxt = io_put_req_find_next(req);
5096 io_req_task_submit(nxt, locked);
5101 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5102 int sync, void *key)
5104 struct io_kiocb *req = wait->private;
5105 struct io_poll_iocb *poll = io_poll_get_single(req);
5106 __poll_t mask = key_to_poll(key);
5107 unsigned long flags;
5109 /* for instances that support it check for an event match first: */
5110 if (mask && !(mask & poll->events))
5112 if (!(poll->events & EPOLLONESHOT))
5113 return poll->wait.func(&poll->wait, mode, sync, key);
5115 list_del_init(&wait->entry);
5120 spin_lock_irqsave(&poll->head->lock, flags);
5121 done = list_empty(&poll->wait.entry);
5123 list_del_init(&poll->wait.entry);
5124 /* make sure double remove sees this as being gone */
5125 wait->private = NULL;
5126 spin_unlock_irqrestore(&poll->head->lock, flags);
5128 /* use wait func handler, so it matches the rq type */
5129 poll->wait.func(&poll->wait, mode, sync, key);
5136 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5137 wait_queue_func_t wake_func)
5141 poll->canceled = false;
5142 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5143 /* mask in events that we always want/need */
5144 poll->events = events | IO_POLL_UNMASK;
5145 INIT_LIST_HEAD(&poll->wait.entry);
5146 init_waitqueue_func_entry(&poll->wait, wake_func);
5149 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5150 struct wait_queue_head *head,
5151 struct io_poll_iocb **poll_ptr)
5153 struct io_kiocb *req = pt->req;
5156 * The file being polled uses multiple waitqueues for poll handling
5157 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5160 if (unlikely(pt->nr_entries)) {
5161 struct io_poll_iocb *poll_one = poll;
5163 /* double add on the same waitqueue head, ignore */
5164 if (poll_one->head == head)
5166 /* already have a 2nd entry, fail a third attempt */
5168 if ((*poll_ptr)->head == head)
5170 pt->error = -EINVAL;
5174 * Can't handle multishot for double wait for now, turn it
5175 * into one-shot mode.
5177 if (!(poll_one->events & EPOLLONESHOT))
5178 poll_one->events |= EPOLLONESHOT;
5179 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5181 pt->error = -ENOMEM;
5184 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5186 poll->wait.private = req;
5193 if (poll->events & EPOLLEXCLUSIVE)
5194 add_wait_queue_exclusive(head, &poll->wait);
5196 add_wait_queue(head, &poll->wait);
5199 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5200 struct poll_table_struct *p)
5202 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5203 struct async_poll *apoll = pt->req->apoll;
5205 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5208 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5210 struct async_poll *apoll = req->apoll;
5211 struct io_ring_ctx *ctx = req->ctx;
5213 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5215 if (io_poll_rewait(req, &apoll->poll)) {
5216 spin_unlock(&ctx->completion_lock);
5220 hash_del(&req->hash_node);
5221 io_poll_remove_double(req);
5222 spin_unlock(&ctx->completion_lock);
5224 if (!READ_ONCE(apoll->poll.canceled))
5225 io_req_task_submit(req, locked);
5227 io_req_complete_failed(req, -ECANCELED);
5230 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5233 struct io_kiocb *req = wait->private;
5234 struct io_poll_iocb *poll = &req->apoll->poll;
5236 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5239 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5242 static void io_poll_req_insert(struct io_kiocb *req)
5244 struct io_ring_ctx *ctx = req->ctx;
5245 struct hlist_head *list;
5247 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5248 hlist_add_head(&req->hash_node, list);
5251 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5252 struct io_poll_iocb *poll,
5253 struct io_poll_table *ipt, __poll_t mask,
5254 wait_queue_func_t wake_func)
5255 __acquires(&ctx->completion_lock)
5257 struct io_ring_ctx *ctx = req->ctx;
5258 bool cancel = false;
5260 INIT_HLIST_NODE(&req->hash_node);
5261 io_init_poll_iocb(poll, mask, wake_func);
5262 poll->file = req->file;
5263 poll->wait.private = req;
5265 ipt->pt._key = mask;
5268 ipt->nr_entries = 0;
5270 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5271 if (unlikely(!ipt->nr_entries) && !ipt->error)
5272 ipt->error = -EINVAL;
5274 spin_lock(&ctx->completion_lock);
5275 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5276 io_poll_remove_double(req);
5277 if (likely(poll->head)) {
5278 spin_lock_irq(&poll->head->lock);
5279 if (unlikely(list_empty(&poll->wait.entry))) {
5285 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5286 list_del_init(&poll->wait.entry);
5288 WRITE_ONCE(poll->canceled, true);
5289 else if (!poll->done) /* actually waiting for an event */
5290 io_poll_req_insert(req);
5291 spin_unlock_irq(&poll->head->lock);
5303 static int io_arm_poll_handler(struct io_kiocb *req)
5305 const struct io_op_def *def = &io_op_defs[req->opcode];
5306 struct io_ring_ctx *ctx = req->ctx;
5307 struct async_poll *apoll;
5308 struct io_poll_table ipt;
5309 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5312 if (!req->file || !file_can_poll(req->file))
5313 return IO_APOLL_ABORTED;
5314 if (req->flags & REQ_F_POLLED)
5315 return IO_APOLL_ABORTED;
5316 if (!def->pollin && !def->pollout)
5317 return IO_APOLL_ABORTED;
5321 mask |= POLLIN | POLLRDNORM;
5323 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5324 if ((req->opcode == IORING_OP_RECVMSG) &&
5325 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5329 mask |= POLLOUT | POLLWRNORM;
5332 /* if we can't nonblock try, then no point in arming a poll handler */
5333 if (!io_file_supports_nowait(req, rw))
5334 return IO_APOLL_ABORTED;
5336 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5337 if (unlikely(!apoll))
5338 return IO_APOLL_ABORTED;
5339 apoll->double_poll = NULL;
5341 req->flags |= REQ_F_POLLED;
5342 ipt.pt._qproc = io_async_queue_proc;
5343 io_req_set_refcount(req);
5345 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5347 spin_unlock(&ctx->completion_lock);
5348 if (ret || ipt.error)
5349 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5351 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5352 mask, apoll->poll.events);
5356 static bool __io_poll_remove_one(struct io_kiocb *req,
5357 struct io_poll_iocb *poll, bool do_cancel)
5358 __must_hold(&req->ctx->completion_lock)
5360 bool do_complete = false;
5364 spin_lock_irq(&poll->head->lock);
5366 WRITE_ONCE(poll->canceled, true);
5367 if (!list_empty(&poll->wait.entry)) {
5368 list_del_init(&poll->wait.entry);
5371 spin_unlock_irq(&poll->head->lock);
5372 hash_del(&req->hash_node);
5376 static bool io_poll_remove_one(struct io_kiocb *req)
5377 __must_hold(&req->ctx->completion_lock)
5381 io_poll_remove_double(req);
5382 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5385 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5386 io_commit_cqring(req->ctx);
5388 io_put_req_deferred(req);
5394 * Returns true if we found and killed one or more poll requests
5396 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5399 struct hlist_node *tmp;
5400 struct io_kiocb *req;
5403 spin_lock(&ctx->completion_lock);
5404 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5405 struct hlist_head *list;
5407 list = &ctx->cancel_hash[i];
5408 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5409 if (io_match_task(req, tsk, cancel_all))
5410 posted += io_poll_remove_one(req);
5413 spin_unlock(&ctx->completion_lock);
5416 io_cqring_ev_posted(ctx);
5421 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5423 __must_hold(&ctx->completion_lock)
5425 struct hlist_head *list;
5426 struct io_kiocb *req;
5428 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5429 hlist_for_each_entry(req, list, hash_node) {
5430 if (sqe_addr != req->user_data)
5432 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5439 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5441 __must_hold(&ctx->completion_lock)
5443 struct io_kiocb *req;
5445 req = io_poll_find(ctx, sqe_addr, poll_only);
5448 if (io_poll_remove_one(req))
5454 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5459 events = READ_ONCE(sqe->poll32_events);
5461 events = swahw32(events);
5463 if (!(flags & IORING_POLL_ADD_MULTI))
5464 events |= EPOLLONESHOT;
5465 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5468 static int io_poll_update_prep(struct io_kiocb *req,
5469 const struct io_uring_sqe *sqe)
5471 struct io_poll_update *upd = &req->poll_update;
5474 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5476 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5478 flags = READ_ONCE(sqe->len);
5479 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5480 IORING_POLL_ADD_MULTI))
5482 /* meaningless without update */
5483 if (flags == IORING_POLL_ADD_MULTI)
5486 upd->old_user_data = READ_ONCE(sqe->addr);
5487 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5488 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5490 upd->new_user_data = READ_ONCE(sqe->off);
5491 if (!upd->update_user_data && upd->new_user_data)
5493 if (upd->update_events)
5494 upd->events = io_poll_parse_events(sqe, flags);
5495 else if (sqe->poll32_events)
5501 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5504 struct io_kiocb *req = wait->private;
5505 struct io_poll_iocb *poll = &req->poll;
5507 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5510 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5511 struct poll_table_struct *p)
5513 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5515 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5518 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5520 struct io_poll_iocb *poll = &req->poll;
5523 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5525 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5527 flags = READ_ONCE(sqe->len);
5528 if (flags & ~IORING_POLL_ADD_MULTI)
5531 io_req_set_refcount(req);
5532 poll->events = io_poll_parse_events(sqe, flags);
5536 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5538 struct io_poll_iocb *poll = &req->poll;
5539 struct io_ring_ctx *ctx = req->ctx;
5540 struct io_poll_table ipt;
5543 ipt.pt._qproc = io_poll_queue_proc;
5545 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5548 if (mask) { /* no async, we'd stolen it */
5550 io_poll_complete(req, mask);
5552 spin_unlock(&ctx->completion_lock);
5555 io_cqring_ev_posted(ctx);
5556 if (poll->events & EPOLLONESHOT)
5562 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5564 struct io_ring_ctx *ctx = req->ctx;
5565 struct io_kiocb *preq;
5569 spin_lock(&ctx->completion_lock);
5570 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5576 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5578 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5583 * Don't allow racy completion with singleshot, as we cannot safely
5584 * update those. For multishot, if we're racing with completion, just
5585 * let completion re-add it.
5587 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5588 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5592 /* we now have a detached poll request. reissue. */
5596 spin_unlock(&ctx->completion_lock);
5598 io_req_complete(req, ret);
5601 /* only mask one event flags, keep behavior flags */
5602 if (req->poll_update.update_events) {
5603 preq->poll.events &= ~0xffff;
5604 preq->poll.events |= req->poll_update.events & 0xffff;
5605 preq->poll.events |= IO_POLL_UNMASK;
5607 if (req->poll_update.update_user_data)
5608 preq->user_data = req->poll_update.new_user_data;
5609 spin_unlock(&ctx->completion_lock);
5611 /* complete update request, we're done with it */
5612 io_req_complete(req, ret);
5615 ret = io_poll_add(preq, issue_flags);
5618 io_req_complete(preq, ret);
5624 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5627 io_req_complete_post(req, -ETIME, 0);
5630 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5632 struct io_timeout_data *data = container_of(timer,
5633 struct io_timeout_data, timer);
5634 struct io_kiocb *req = data->req;
5635 struct io_ring_ctx *ctx = req->ctx;
5636 unsigned long flags;
5638 spin_lock_irqsave(&ctx->timeout_lock, flags);
5639 list_del_init(&req->timeout.list);
5640 atomic_set(&req->ctx->cq_timeouts,
5641 atomic_read(&req->ctx->cq_timeouts) + 1);
5642 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5644 req->io_task_work.func = io_req_task_timeout;
5645 io_req_task_work_add(req);
5646 return HRTIMER_NORESTART;
5649 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5651 __must_hold(&ctx->timeout_lock)
5653 struct io_timeout_data *io;
5654 struct io_kiocb *req;
5657 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5658 found = user_data == req->user_data;
5663 return ERR_PTR(-ENOENT);
5665 io = req->async_data;
5666 if (hrtimer_try_to_cancel(&io->timer) == -1)
5667 return ERR_PTR(-EALREADY);
5668 list_del_init(&req->timeout.list);
5672 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5673 __must_hold(&ctx->completion_lock)
5674 __must_hold(&ctx->timeout_lock)
5676 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5679 return PTR_ERR(req);
5682 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5683 io_put_req_deferred(req);
5687 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5688 struct timespec64 *ts, enum hrtimer_mode mode)
5689 __must_hold(&ctx->timeout_lock)
5691 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5692 struct io_timeout_data *data;
5695 return PTR_ERR(req);
5697 req->timeout.off = 0; /* noseq */
5698 data = req->async_data;
5699 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5700 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5701 data->timer.function = io_timeout_fn;
5702 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5706 static int io_timeout_remove_prep(struct io_kiocb *req,
5707 const struct io_uring_sqe *sqe)
5709 struct io_timeout_rem *tr = &req->timeout_rem;
5711 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5713 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5715 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5718 tr->addr = READ_ONCE(sqe->addr);
5719 tr->flags = READ_ONCE(sqe->timeout_flags);
5720 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5721 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5723 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5725 } else if (tr->flags) {
5726 /* timeout removal doesn't support flags */
5733 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5735 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5740 * Remove or update an existing timeout command
5742 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5744 struct io_timeout_rem *tr = &req->timeout_rem;
5745 struct io_ring_ctx *ctx = req->ctx;
5748 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
5749 spin_lock(&ctx->completion_lock);
5750 spin_lock_irq(&ctx->timeout_lock);
5751 ret = io_timeout_cancel(ctx, tr->addr);
5752 spin_unlock_irq(&ctx->timeout_lock);
5753 spin_unlock(&ctx->completion_lock);
5755 spin_lock_irq(&ctx->timeout_lock);
5756 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5757 io_translate_timeout_mode(tr->flags));
5758 spin_unlock_irq(&ctx->timeout_lock);
5763 io_req_complete_post(req, ret, 0);
5767 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5768 bool is_timeout_link)
5770 struct io_timeout_data *data;
5772 u32 off = READ_ONCE(sqe->off);
5774 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5776 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
5779 if (off && is_timeout_link)
5781 flags = READ_ONCE(sqe->timeout_flags);
5782 if (flags & ~IORING_TIMEOUT_ABS)
5785 req->timeout.off = off;
5786 if (unlikely(off && !req->ctx->off_timeout_used))
5787 req->ctx->off_timeout_used = true;
5789 if (!req->async_data && io_alloc_async_data(req))
5792 data = req->async_data;
5795 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5798 data->mode = io_translate_timeout_mode(flags);
5799 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5801 if (is_timeout_link) {
5802 struct io_submit_link *link = &req->ctx->submit_state.link;
5806 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5808 req->timeout.head = link->last;
5809 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5814 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5816 struct io_ring_ctx *ctx = req->ctx;
5817 struct io_timeout_data *data = req->async_data;
5818 struct list_head *entry;
5819 u32 tail, off = req->timeout.off;
5821 spin_lock_irq(&ctx->timeout_lock);
5824 * sqe->off holds how many events that need to occur for this
5825 * timeout event to be satisfied. If it isn't set, then this is
5826 * a pure timeout request, sequence isn't used.
5828 if (io_is_timeout_noseq(req)) {
5829 entry = ctx->timeout_list.prev;
5833 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5834 req->timeout.target_seq = tail + off;
5836 /* Update the last seq here in case io_flush_timeouts() hasn't.
5837 * This is safe because ->completion_lock is held, and submissions
5838 * and completions are never mixed in the same ->completion_lock section.
5840 ctx->cq_last_tm_flush = tail;
5843 * Insertion sort, ensuring the first entry in the list is always
5844 * the one we need first.
5846 list_for_each_prev(entry, &ctx->timeout_list) {
5847 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5850 if (io_is_timeout_noseq(nxt))
5852 /* nxt.seq is behind @tail, otherwise would've been completed */
5853 if (off >= nxt->timeout.target_seq - tail)
5857 list_add(&req->timeout.list, entry);
5858 data->timer.function = io_timeout_fn;
5859 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5860 spin_unlock_irq(&ctx->timeout_lock);
5864 struct io_cancel_data {
5865 struct io_ring_ctx *ctx;
5869 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5871 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5872 struct io_cancel_data *cd = data;
5874 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5877 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5878 struct io_ring_ctx *ctx)
5880 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5881 enum io_wq_cancel cancel_ret;
5884 if (!tctx || !tctx->io_wq)
5887 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5888 switch (cancel_ret) {
5889 case IO_WQ_CANCEL_OK:
5892 case IO_WQ_CANCEL_RUNNING:
5895 case IO_WQ_CANCEL_NOTFOUND:
5903 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
5905 struct io_ring_ctx *ctx = req->ctx;
5908 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
5910 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5914 spin_lock(&ctx->completion_lock);
5915 spin_lock_irq(&ctx->timeout_lock);
5916 ret = io_timeout_cancel(ctx, sqe_addr);
5917 spin_unlock_irq(&ctx->timeout_lock);
5920 ret = io_poll_cancel(ctx, sqe_addr, false);
5922 spin_unlock(&ctx->completion_lock);
5926 static int io_async_cancel_prep(struct io_kiocb *req,
5927 const struct io_uring_sqe *sqe)
5929 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5931 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5933 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
5937 req->cancel.addr = READ_ONCE(sqe->addr);
5941 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5943 struct io_ring_ctx *ctx = req->ctx;
5944 u64 sqe_addr = req->cancel.addr;
5945 struct io_tctx_node *node;
5948 ret = io_try_cancel_userdata(req, sqe_addr);
5952 /* slow path, try all io-wq's */
5953 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5955 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5956 struct io_uring_task *tctx = node->task->io_uring;
5958 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5962 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5966 io_req_complete_post(req, ret, 0);
5970 static int io_rsrc_update_prep(struct io_kiocb *req,
5971 const struct io_uring_sqe *sqe)
5973 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5975 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
5978 req->rsrc_update.offset = READ_ONCE(sqe->off);
5979 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5980 if (!req->rsrc_update.nr_args)
5982 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5986 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5988 struct io_ring_ctx *ctx = req->ctx;
5989 struct io_uring_rsrc_update2 up;
5992 if (issue_flags & IO_URING_F_NONBLOCK)
5995 up.offset = req->rsrc_update.offset;
5996 up.data = req->rsrc_update.arg;
6001 mutex_lock(&ctx->uring_lock);
6002 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6003 &up, req->rsrc_update.nr_args);
6004 mutex_unlock(&ctx->uring_lock);
6008 __io_req_complete(req, issue_flags, ret, 0);
6012 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6014 switch (req->opcode) {
6017 case IORING_OP_READV:
6018 case IORING_OP_READ_FIXED:
6019 case IORING_OP_READ:
6020 return io_read_prep(req, sqe);
6021 case IORING_OP_WRITEV:
6022 case IORING_OP_WRITE_FIXED:
6023 case IORING_OP_WRITE:
6024 return io_write_prep(req, sqe);
6025 case IORING_OP_POLL_ADD:
6026 return io_poll_add_prep(req, sqe);
6027 case IORING_OP_POLL_REMOVE:
6028 return io_poll_update_prep(req, sqe);
6029 case IORING_OP_FSYNC:
6030 return io_fsync_prep(req, sqe);
6031 case IORING_OP_SYNC_FILE_RANGE:
6032 return io_sfr_prep(req, sqe);
6033 case IORING_OP_SENDMSG:
6034 case IORING_OP_SEND:
6035 return io_sendmsg_prep(req, sqe);
6036 case IORING_OP_RECVMSG:
6037 case IORING_OP_RECV:
6038 return io_recvmsg_prep(req, sqe);
6039 case IORING_OP_CONNECT:
6040 return io_connect_prep(req, sqe);
6041 case IORING_OP_TIMEOUT:
6042 return io_timeout_prep(req, sqe, false);
6043 case IORING_OP_TIMEOUT_REMOVE:
6044 return io_timeout_remove_prep(req, sqe);
6045 case IORING_OP_ASYNC_CANCEL:
6046 return io_async_cancel_prep(req, sqe);
6047 case IORING_OP_LINK_TIMEOUT:
6048 return io_timeout_prep(req, sqe, true);
6049 case IORING_OP_ACCEPT:
6050 return io_accept_prep(req, sqe);
6051 case IORING_OP_FALLOCATE:
6052 return io_fallocate_prep(req, sqe);
6053 case IORING_OP_OPENAT:
6054 return io_openat_prep(req, sqe);
6055 case IORING_OP_CLOSE:
6056 return io_close_prep(req, sqe);
6057 case IORING_OP_FILES_UPDATE:
6058 return io_rsrc_update_prep(req, sqe);
6059 case IORING_OP_STATX:
6060 return io_statx_prep(req, sqe);
6061 case IORING_OP_FADVISE:
6062 return io_fadvise_prep(req, sqe);
6063 case IORING_OP_MADVISE:
6064 return io_madvise_prep(req, sqe);
6065 case IORING_OP_OPENAT2:
6066 return io_openat2_prep(req, sqe);
6067 case IORING_OP_EPOLL_CTL:
6068 return io_epoll_ctl_prep(req, sqe);
6069 case IORING_OP_SPLICE:
6070 return io_splice_prep(req, sqe);
6071 case IORING_OP_PROVIDE_BUFFERS:
6072 return io_provide_buffers_prep(req, sqe);
6073 case IORING_OP_REMOVE_BUFFERS:
6074 return io_remove_buffers_prep(req, sqe);
6076 return io_tee_prep(req, sqe);
6077 case IORING_OP_SHUTDOWN:
6078 return io_shutdown_prep(req, sqe);
6079 case IORING_OP_RENAMEAT:
6080 return io_renameat_prep(req, sqe);
6081 case IORING_OP_UNLINKAT:
6082 return io_unlinkat_prep(req, sqe);
6085 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6090 static int io_req_prep_async(struct io_kiocb *req)
6092 if (!io_op_defs[req->opcode].needs_async_setup)
6094 if (WARN_ON_ONCE(req->async_data))
6096 if (io_alloc_async_data(req))
6099 switch (req->opcode) {
6100 case IORING_OP_READV:
6101 return io_rw_prep_async(req, READ);
6102 case IORING_OP_WRITEV:
6103 return io_rw_prep_async(req, WRITE);
6104 case IORING_OP_SENDMSG:
6105 return io_sendmsg_prep_async(req);
6106 case IORING_OP_RECVMSG:
6107 return io_recvmsg_prep_async(req);
6108 case IORING_OP_CONNECT:
6109 return io_connect_prep_async(req);
6111 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6116 static u32 io_get_sequence(struct io_kiocb *req)
6118 u32 seq = req->ctx->cached_sq_head;
6120 /* need original cached_sq_head, but it was increased for each req */
6121 io_for_each_link(req, req)
6126 static bool io_drain_req(struct io_kiocb *req)
6128 struct io_kiocb *pos;
6129 struct io_ring_ctx *ctx = req->ctx;
6130 struct io_defer_entry *de;
6135 * If we need to drain a request in the middle of a link, drain the
6136 * head request and the next request/link after the current link.
6137 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6138 * maintained for every request of our link.
6140 if (ctx->drain_next) {
6141 req->flags |= REQ_F_IO_DRAIN;
6142 ctx->drain_next = false;
6144 /* not interested in head, start from the first linked */
6145 io_for_each_link(pos, req->link) {
6146 if (pos->flags & REQ_F_IO_DRAIN) {
6147 ctx->drain_next = true;
6148 req->flags |= REQ_F_IO_DRAIN;
6153 /* Still need defer if there is pending req in defer list. */
6154 if (likely(list_empty_careful(&ctx->defer_list) &&
6155 !(req->flags & REQ_F_IO_DRAIN))) {
6156 ctx->drain_active = false;
6160 seq = io_get_sequence(req);
6161 /* Still a chance to pass the sequence check */
6162 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6165 ret = io_req_prep_async(req);
6168 io_prep_async_link(req);
6169 de = kmalloc(sizeof(*de), GFP_KERNEL);
6173 io_req_complete_failed(req, ret);
6177 spin_lock(&ctx->completion_lock);
6178 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6179 spin_unlock(&ctx->completion_lock);
6181 io_queue_async_work(req, NULL);
6185 trace_io_uring_defer(ctx, req, req->user_data);
6188 list_add_tail(&de->list, &ctx->defer_list);
6189 spin_unlock(&ctx->completion_lock);
6193 static void io_clean_op(struct io_kiocb *req)
6195 if (req->flags & REQ_F_BUFFER_SELECTED) {
6196 switch (req->opcode) {
6197 case IORING_OP_READV:
6198 case IORING_OP_READ_FIXED:
6199 case IORING_OP_READ:
6200 kfree((void *)(unsigned long)req->rw.addr);
6202 case IORING_OP_RECVMSG:
6203 case IORING_OP_RECV:
6204 kfree(req->sr_msg.kbuf);
6209 if (req->flags & REQ_F_NEED_CLEANUP) {
6210 switch (req->opcode) {
6211 case IORING_OP_READV:
6212 case IORING_OP_READ_FIXED:
6213 case IORING_OP_READ:
6214 case IORING_OP_WRITEV:
6215 case IORING_OP_WRITE_FIXED:
6216 case IORING_OP_WRITE: {
6217 struct io_async_rw *io = req->async_data;
6219 kfree(io->free_iovec);
6222 case IORING_OP_RECVMSG:
6223 case IORING_OP_SENDMSG: {
6224 struct io_async_msghdr *io = req->async_data;
6226 kfree(io->free_iov);
6229 case IORING_OP_SPLICE:
6231 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6232 io_put_file(req->splice.file_in);
6234 case IORING_OP_OPENAT:
6235 case IORING_OP_OPENAT2:
6236 if (req->open.filename)
6237 putname(req->open.filename);
6239 case IORING_OP_RENAMEAT:
6240 putname(req->rename.oldpath);
6241 putname(req->rename.newpath);
6243 case IORING_OP_UNLINKAT:
6244 putname(req->unlink.filename);
6248 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6249 kfree(req->apoll->double_poll);
6253 if (req->flags & REQ_F_INFLIGHT) {
6254 struct io_uring_task *tctx = req->task->io_uring;
6256 atomic_dec(&tctx->inflight_tracked);
6258 if (req->flags & REQ_F_CREDS)
6259 put_cred(req->creds);
6261 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6264 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6266 struct io_ring_ctx *ctx = req->ctx;
6267 const struct cred *creds = NULL;
6270 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6271 creds = override_creds(req->creds);
6273 switch (req->opcode) {
6275 ret = io_nop(req, issue_flags);
6277 case IORING_OP_READV:
6278 case IORING_OP_READ_FIXED:
6279 case IORING_OP_READ:
6280 ret = io_read(req, issue_flags);
6282 case IORING_OP_WRITEV:
6283 case IORING_OP_WRITE_FIXED:
6284 case IORING_OP_WRITE:
6285 ret = io_write(req, issue_flags);
6287 case IORING_OP_FSYNC:
6288 ret = io_fsync(req, issue_flags);
6290 case IORING_OP_POLL_ADD:
6291 ret = io_poll_add(req, issue_flags);
6293 case IORING_OP_POLL_REMOVE:
6294 ret = io_poll_update(req, issue_flags);
6296 case IORING_OP_SYNC_FILE_RANGE:
6297 ret = io_sync_file_range(req, issue_flags);
6299 case IORING_OP_SENDMSG:
6300 ret = io_sendmsg(req, issue_flags);
6302 case IORING_OP_SEND:
6303 ret = io_send(req, issue_flags);
6305 case IORING_OP_RECVMSG:
6306 ret = io_recvmsg(req, issue_flags);
6308 case IORING_OP_RECV:
6309 ret = io_recv(req, issue_flags);
6311 case IORING_OP_TIMEOUT:
6312 ret = io_timeout(req, issue_flags);
6314 case IORING_OP_TIMEOUT_REMOVE:
6315 ret = io_timeout_remove(req, issue_flags);
6317 case IORING_OP_ACCEPT:
6318 ret = io_accept(req, issue_flags);
6320 case IORING_OP_CONNECT:
6321 ret = io_connect(req, issue_flags);
6323 case IORING_OP_ASYNC_CANCEL:
6324 ret = io_async_cancel(req, issue_flags);
6326 case IORING_OP_FALLOCATE:
6327 ret = io_fallocate(req, issue_flags);
6329 case IORING_OP_OPENAT:
6330 ret = io_openat(req, issue_flags);
6332 case IORING_OP_CLOSE:
6333 ret = io_close(req, issue_flags);
6335 case IORING_OP_FILES_UPDATE:
6336 ret = io_files_update(req, issue_flags);
6338 case IORING_OP_STATX:
6339 ret = io_statx(req, issue_flags);
6341 case IORING_OP_FADVISE:
6342 ret = io_fadvise(req, issue_flags);
6344 case IORING_OP_MADVISE:
6345 ret = io_madvise(req, issue_flags);
6347 case IORING_OP_OPENAT2:
6348 ret = io_openat2(req, issue_flags);
6350 case IORING_OP_EPOLL_CTL:
6351 ret = io_epoll_ctl(req, issue_flags);
6353 case IORING_OP_SPLICE:
6354 ret = io_splice(req, issue_flags);
6356 case IORING_OP_PROVIDE_BUFFERS:
6357 ret = io_provide_buffers(req, issue_flags);
6359 case IORING_OP_REMOVE_BUFFERS:
6360 ret = io_remove_buffers(req, issue_flags);
6363 ret = io_tee(req, issue_flags);
6365 case IORING_OP_SHUTDOWN:
6366 ret = io_shutdown(req, issue_flags);
6368 case IORING_OP_RENAMEAT:
6369 ret = io_renameat(req, issue_flags);
6371 case IORING_OP_UNLINKAT:
6372 ret = io_unlinkat(req, issue_flags);
6380 revert_creds(creds);
6383 /* If the op doesn't have a file, we're not polling for it */
6384 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6385 io_iopoll_req_issued(req);
6390 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6392 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6394 req = io_put_req_find_next(req);
6395 return req ? &req->work : NULL;
6398 static void io_wq_submit_work(struct io_wq_work *work)
6400 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6401 struct io_kiocb *timeout;
6404 /* one will be dropped by ->io_free_work() after returning to io-wq */
6405 if (!(req->flags & REQ_F_REFCOUNT))
6406 __io_req_set_refcount(req, 2);
6410 timeout = io_prep_linked_timeout(req);
6412 io_queue_linked_timeout(timeout);
6414 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6415 if (work->flags & IO_WQ_WORK_CANCEL)
6420 ret = io_issue_sqe(req, 0);
6422 * We can get EAGAIN for polled IO even though we're
6423 * forcing a sync submission from here, since we can't
6424 * wait for request slots on the block side.
6432 /* avoid locking problems by failing it from a clean context */
6434 io_req_task_queue_fail(req, ret);
6437 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6440 return &table->files[i];
6443 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6446 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6448 return (struct file *) (slot->file_ptr & FFS_MASK);
6451 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6453 unsigned long file_ptr = (unsigned long) file;
6455 if (__io_file_supports_nowait(file, READ))
6456 file_ptr |= FFS_ASYNC_READ;
6457 if (__io_file_supports_nowait(file, WRITE))
6458 file_ptr |= FFS_ASYNC_WRITE;
6459 if (S_ISREG(file_inode(file)->i_mode))
6460 file_ptr |= FFS_ISREG;
6461 file_slot->file_ptr = file_ptr;
6464 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6465 struct io_kiocb *req, int fd)
6468 unsigned long file_ptr;
6470 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6472 fd = array_index_nospec(fd, ctx->nr_user_files);
6473 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6474 file = (struct file *) (file_ptr & FFS_MASK);
6475 file_ptr &= ~FFS_MASK;
6476 /* mask in overlapping REQ_F and FFS bits */
6477 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6478 io_req_set_rsrc_node(req);
6482 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6483 struct io_kiocb *req, int fd)
6485 struct file *file = fget(fd);
6487 trace_io_uring_file_get(ctx, fd);
6489 /* we don't allow fixed io_uring files */
6490 if (file && unlikely(file->f_op == &io_uring_fops))
6491 io_req_track_inflight(req);
6495 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6496 struct io_kiocb *req, int fd, bool fixed)
6499 return io_file_get_fixed(ctx, req, fd);
6501 return io_file_get_normal(ctx, req, fd);
6504 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6506 struct io_kiocb *prev = req->timeout.prev;
6510 ret = io_try_cancel_userdata(req, prev->user_data);
6511 io_req_complete_post(req, ret ?: -ETIME, 0);
6514 io_req_complete_post(req, -ETIME, 0);
6518 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6520 struct io_timeout_data *data = container_of(timer,
6521 struct io_timeout_data, timer);
6522 struct io_kiocb *prev, *req = data->req;
6523 struct io_ring_ctx *ctx = req->ctx;
6524 unsigned long flags;
6526 spin_lock_irqsave(&ctx->timeout_lock, flags);
6527 prev = req->timeout.head;
6528 req->timeout.head = NULL;
6531 * We don't expect the list to be empty, that will only happen if we
6532 * race with the completion of the linked work.
6535 io_remove_next_linked(prev);
6536 if (!req_ref_inc_not_zero(prev))
6539 req->timeout.prev = prev;
6540 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6542 req->io_task_work.func = io_req_task_link_timeout;
6543 io_req_task_work_add(req);
6544 return HRTIMER_NORESTART;
6547 static void io_queue_linked_timeout(struct io_kiocb *req)
6549 struct io_ring_ctx *ctx = req->ctx;
6551 spin_lock_irq(&ctx->timeout_lock);
6553 * If the back reference is NULL, then our linked request finished
6554 * before we got a chance to setup the timer
6556 if (req->timeout.head) {
6557 struct io_timeout_data *data = req->async_data;
6559 data->timer.function = io_link_timeout_fn;
6560 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6563 spin_unlock_irq(&ctx->timeout_lock);
6564 /* drop submission reference */
6568 static void __io_queue_sqe(struct io_kiocb *req)
6569 __must_hold(&req->ctx->uring_lock)
6571 struct io_kiocb *linked_timeout;
6575 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6578 * We async punt it if the file wasn't marked NOWAIT, or if the file
6579 * doesn't support non-blocking read/write attempts
6582 if (req->flags & REQ_F_COMPLETE_INLINE) {
6583 struct io_ring_ctx *ctx = req->ctx;
6584 struct io_submit_state *state = &ctx->submit_state;
6586 state->compl_reqs[state->compl_nr++] = req;
6587 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6588 io_submit_flush_completions(ctx);
6592 linked_timeout = io_prep_linked_timeout(req);
6594 io_queue_linked_timeout(linked_timeout);
6595 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6596 linked_timeout = io_prep_linked_timeout(req);
6598 switch (io_arm_poll_handler(req)) {
6599 case IO_APOLL_READY:
6601 io_unprep_linked_timeout(req);
6603 case IO_APOLL_ABORTED:
6605 * Queued up for async execution, worker will release
6606 * submit reference when the iocb is actually submitted.
6608 io_queue_async_work(req, NULL);
6613 io_queue_linked_timeout(linked_timeout);
6615 io_req_complete_failed(req, ret);
6619 static inline void io_queue_sqe(struct io_kiocb *req)
6620 __must_hold(&req->ctx->uring_lock)
6622 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6625 if (likely(!(req->flags & REQ_F_FORCE_ASYNC))) {
6626 __io_queue_sqe(req);
6628 int ret = io_req_prep_async(req);
6631 io_req_complete_failed(req, ret);
6633 io_queue_async_work(req, NULL);
6638 * Check SQE restrictions (opcode and flags).
6640 * Returns 'true' if SQE is allowed, 'false' otherwise.
6642 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6643 struct io_kiocb *req,
6644 unsigned int sqe_flags)
6646 if (likely(!ctx->restricted))
6649 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6652 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6653 ctx->restrictions.sqe_flags_required)
6656 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6657 ctx->restrictions.sqe_flags_required))
6663 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6664 const struct io_uring_sqe *sqe)
6665 __must_hold(&ctx->uring_lock)
6667 struct io_submit_state *state;
6668 unsigned int sqe_flags;
6669 int personality, ret = 0;
6671 /* req is partially pre-initialised, see io_preinit_req() */
6672 req->opcode = READ_ONCE(sqe->opcode);
6673 /* same numerical values with corresponding REQ_F_*, safe to copy */
6674 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6675 req->user_data = READ_ONCE(sqe->user_data);
6677 req->fixed_rsrc_refs = NULL;
6678 req->task = current;
6680 /* enforce forwards compatibility on users */
6681 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6683 if (unlikely(req->opcode >= IORING_OP_LAST))
6685 if (!io_check_restriction(ctx, req, sqe_flags))
6688 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6689 !io_op_defs[req->opcode].buffer_select)
6691 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6692 ctx->drain_active = true;
6694 personality = READ_ONCE(sqe->personality);
6696 req->creds = xa_load(&ctx->personalities, personality);
6699 get_cred(req->creds);
6700 req->flags |= REQ_F_CREDS;
6702 state = &ctx->submit_state;
6705 * Plug now if we have more than 1 IO left after this, and the target
6706 * is potentially a read/write to block based storage.
6708 if (!state->plug_started && state->ios_left > 1 &&
6709 io_op_defs[req->opcode].plug) {
6710 blk_start_plug(&state->plug);
6711 state->plug_started = true;
6714 if (io_op_defs[req->opcode].needs_file) {
6715 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6716 (sqe_flags & IOSQE_FIXED_FILE));
6717 if (unlikely(!req->file))
6725 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6726 const struct io_uring_sqe *sqe)
6727 __must_hold(&ctx->uring_lock)
6729 struct io_submit_link *link = &ctx->submit_state.link;
6732 ret = io_init_req(ctx, req, sqe);
6733 if (unlikely(ret)) {
6736 /* fail even hard links since we don't submit */
6737 req_set_fail(link->head);
6738 io_req_complete_failed(link->head, -ECANCELED);
6741 io_req_complete_failed(req, ret);
6745 ret = io_req_prep(req, sqe);
6749 /* don't need @sqe from now on */
6750 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6752 ctx->flags & IORING_SETUP_SQPOLL);
6755 * If we already have a head request, queue this one for async
6756 * submittal once the head completes. If we don't have a head but
6757 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6758 * submitted sync once the chain is complete. If none of those
6759 * conditions are true (normal request), then just queue it.
6762 struct io_kiocb *head = link->head;
6764 ret = io_req_prep_async(req);
6767 trace_io_uring_link(ctx, req, head);
6768 link->last->link = req;
6771 /* last request of a link, enqueue the link */
6772 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6777 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6789 * Batched submission is done, ensure local IO is flushed out.
6791 static void io_submit_state_end(struct io_submit_state *state,
6792 struct io_ring_ctx *ctx)
6794 if (state->link.head)
6795 io_queue_sqe(state->link.head);
6796 if (state->compl_nr)
6797 io_submit_flush_completions(ctx);
6798 if (state->plug_started)
6799 blk_finish_plug(&state->plug);
6803 * Start submission side cache.
6805 static void io_submit_state_start(struct io_submit_state *state,
6806 unsigned int max_ios)
6808 state->plug_started = false;
6809 state->ios_left = max_ios;
6810 /* set only head, no need to init link_last in advance */
6811 state->link.head = NULL;
6814 static void io_commit_sqring(struct io_ring_ctx *ctx)
6816 struct io_rings *rings = ctx->rings;
6819 * Ensure any loads from the SQEs are done at this point,
6820 * since once we write the new head, the application could
6821 * write new data to them.
6823 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6827 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6828 * that is mapped by userspace. This means that care needs to be taken to
6829 * ensure that reads are stable, as we cannot rely on userspace always
6830 * being a good citizen. If members of the sqe are validated and then later
6831 * used, it's important that those reads are done through READ_ONCE() to
6832 * prevent a re-load down the line.
6834 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6836 unsigned head, mask = ctx->sq_entries - 1;
6837 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6840 * The cached sq head (or cq tail) serves two purposes:
6842 * 1) allows us to batch the cost of updating the user visible
6844 * 2) allows the kernel side to track the head on its own, even
6845 * though the application is the one updating it.
6847 head = READ_ONCE(ctx->sq_array[sq_idx]);
6848 if (likely(head < ctx->sq_entries))
6849 return &ctx->sq_sqes[head];
6851 /* drop invalid entries */
6853 WRITE_ONCE(ctx->rings->sq_dropped,
6854 READ_ONCE(ctx->rings->sq_dropped) + 1);
6858 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6859 __must_hold(&ctx->uring_lock)
6861 struct io_uring_task *tctx;
6864 /* make sure SQ entry isn't read before tail */
6865 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6866 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6869 tctx = current->io_uring;
6870 tctx->cached_refs -= nr;
6871 if (unlikely(tctx->cached_refs < 0)) {
6872 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
6874 percpu_counter_add(&tctx->inflight, refill);
6875 refcount_add(refill, ¤t->usage);
6876 tctx->cached_refs += refill;
6878 io_submit_state_start(&ctx->submit_state, nr);
6880 while (submitted < nr) {
6881 const struct io_uring_sqe *sqe;
6882 struct io_kiocb *req;
6884 req = io_alloc_req(ctx);
6885 if (unlikely(!req)) {
6887 submitted = -EAGAIN;
6890 sqe = io_get_sqe(ctx);
6891 if (unlikely(!sqe)) {
6892 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
6895 /* will complete beyond this point, count as submitted */
6897 if (io_submit_sqe(ctx, req, sqe))
6901 if (unlikely(submitted != nr)) {
6902 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6903 int unused = nr - ref_used;
6905 current->io_uring->cached_refs += unused;
6906 percpu_ref_put_many(&ctx->refs, unused);
6909 io_submit_state_end(&ctx->submit_state, ctx);
6910 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6911 io_commit_sqring(ctx);
6916 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
6918 return READ_ONCE(sqd->state);
6921 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6923 /* Tell userspace we may need a wakeup call */
6924 spin_lock(&ctx->completion_lock);
6925 WRITE_ONCE(ctx->rings->sq_flags,
6926 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
6927 spin_unlock(&ctx->completion_lock);
6930 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6932 spin_lock(&ctx->completion_lock);
6933 WRITE_ONCE(ctx->rings->sq_flags,
6934 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
6935 spin_unlock(&ctx->completion_lock);
6938 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6940 unsigned int to_submit;
6943 to_submit = io_sqring_entries(ctx);
6944 /* if we're handling multiple rings, cap submit size for fairness */
6945 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
6946 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
6948 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6949 unsigned nr_events = 0;
6950 const struct cred *creds = NULL;
6952 if (ctx->sq_creds != current_cred())
6953 creds = override_creds(ctx->sq_creds);
6955 mutex_lock(&ctx->uring_lock);
6956 if (!list_empty(&ctx->iopoll_list))
6957 io_do_iopoll(ctx, &nr_events, 0);
6960 * Don't submit if refs are dying, good for io_uring_register(),
6961 * but also it is relied upon by io_ring_exit_work()
6963 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6964 !(ctx->flags & IORING_SETUP_R_DISABLED))
6965 ret = io_submit_sqes(ctx, to_submit);
6966 mutex_unlock(&ctx->uring_lock);
6968 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
6969 wake_up(&ctx->sqo_sq_wait);
6971 revert_creds(creds);
6977 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6979 struct io_ring_ctx *ctx;
6980 unsigned sq_thread_idle = 0;
6982 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6983 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6984 sqd->sq_thread_idle = sq_thread_idle;
6987 static bool io_sqd_handle_event(struct io_sq_data *sqd)
6989 bool did_sig = false;
6990 struct ksignal ksig;
6992 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6993 signal_pending(current)) {
6994 mutex_unlock(&sqd->lock);
6995 if (signal_pending(current))
6996 did_sig = get_signal(&ksig);
6998 mutex_lock(&sqd->lock);
7000 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7003 static int io_sq_thread(void *data)
7005 struct io_sq_data *sqd = data;
7006 struct io_ring_ctx *ctx;
7007 unsigned long timeout = 0;
7008 char buf[TASK_COMM_LEN];
7011 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7012 set_task_comm(current, buf);
7014 if (sqd->sq_cpu != -1)
7015 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7017 set_cpus_allowed_ptr(current, cpu_online_mask);
7018 current->flags |= PF_NO_SETAFFINITY;
7020 mutex_lock(&sqd->lock);
7022 bool cap_entries, sqt_spin = false;
7024 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7025 if (io_sqd_handle_event(sqd))
7027 timeout = jiffies + sqd->sq_thread_idle;
7030 cap_entries = !list_is_singular(&sqd->ctx_list);
7031 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7032 int ret = __io_sq_thread(ctx, cap_entries);
7034 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7037 if (io_run_task_work())
7040 if (sqt_spin || !time_after(jiffies, timeout)) {
7043 timeout = jiffies + sqd->sq_thread_idle;
7047 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7048 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7049 bool needs_sched = true;
7051 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7052 io_ring_set_wakeup_flag(ctx);
7054 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7055 !list_empty_careful(&ctx->iopoll_list)) {
7056 needs_sched = false;
7059 if (io_sqring_entries(ctx)) {
7060 needs_sched = false;
7066 mutex_unlock(&sqd->lock);
7068 mutex_lock(&sqd->lock);
7070 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7071 io_ring_clear_wakeup_flag(ctx);
7074 finish_wait(&sqd->wait, &wait);
7075 timeout = jiffies + sqd->sq_thread_idle;
7078 io_uring_cancel_generic(true, sqd);
7080 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7081 io_ring_set_wakeup_flag(ctx);
7083 mutex_unlock(&sqd->lock);
7085 complete(&sqd->exited);
7089 struct io_wait_queue {
7090 struct wait_queue_entry wq;
7091 struct io_ring_ctx *ctx;
7093 unsigned nr_timeouts;
7096 static inline bool io_should_wake(struct io_wait_queue *iowq)
7098 struct io_ring_ctx *ctx = iowq->ctx;
7099 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7102 * Wake up if we have enough events, or if a timeout occurred since we
7103 * started waiting. For timeouts, we always want to return to userspace,
7104 * regardless of event count.
7106 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7109 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7110 int wake_flags, void *key)
7112 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7116 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7117 * the task, and the next invocation will do it.
7119 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7120 return autoremove_wake_function(curr, mode, wake_flags, key);
7124 static int io_run_task_work_sig(void)
7126 if (io_run_task_work())
7128 if (!signal_pending(current))
7130 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7131 return -ERESTARTSYS;
7135 /* when returns >0, the caller should retry */
7136 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7137 struct io_wait_queue *iowq,
7138 signed long *timeout)
7142 /* make sure we run task_work before checking for signals */
7143 ret = io_run_task_work_sig();
7144 if (ret || io_should_wake(iowq))
7146 /* let the caller flush overflows, retry */
7147 if (test_bit(0, &ctx->check_cq_overflow))
7150 *timeout = schedule_timeout(*timeout);
7151 return !*timeout ? -ETIME : 1;
7155 * Wait until events become available, if we don't already have some. The
7156 * application must reap them itself, as they reside on the shared cq ring.
7158 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7159 const sigset_t __user *sig, size_t sigsz,
7160 struct __kernel_timespec __user *uts)
7162 struct io_wait_queue iowq;
7163 struct io_rings *rings = ctx->rings;
7164 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7168 io_cqring_overflow_flush(ctx);
7169 if (io_cqring_events(ctx) >= min_events)
7171 if (!io_run_task_work())
7176 #ifdef CONFIG_COMPAT
7177 if (in_compat_syscall())
7178 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7182 ret = set_user_sigmask(sig, sigsz);
7189 struct timespec64 ts;
7191 if (get_timespec64(&ts, uts))
7193 timeout = timespec64_to_jiffies(&ts);
7196 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7197 iowq.wq.private = current;
7198 INIT_LIST_HEAD(&iowq.wq.entry);
7200 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7201 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7203 trace_io_uring_cqring_wait(ctx, min_events);
7205 /* if we can't even flush overflow, don't wait for more */
7206 if (!io_cqring_overflow_flush(ctx)) {
7210 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7211 TASK_INTERRUPTIBLE);
7212 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7213 finish_wait(&ctx->cq_wait, &iowq.wq);
7217 restore_saved_sigmask_unless(ret == -EINTR);
7219 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7222 static void io_free_page_table(void **table, size_t size)
7224 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7226 for (i = 0; i < nr_tables; i++)
7231 static void **io_alloc_page_table(size_t size)
7233 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7234 size_t init_size = size;
7237 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7241 for (i = 0; i < nr_tables; i++) {
7242 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7244 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7246 io_free_page_table(table, init_size);
7254 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7256 percpu_ref_exit(&ref_node->refs);
7260 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7262 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7263 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7264 unsigned long flags;
7265 bool first_add = false;
7267 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7270 while (!list_empty(&ctx->rsrc_ref_list)) {
7271 node = list_first_entry(&ctx->rsrc_ref_list,
7272 struct io_rsrc_node, node);
7273 /* recycle ref nodes in order */
7276 list_del(&node->node);
7277 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7279 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7282 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7285 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7287 struct io_rsrc_node *ref_node;
7289 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7293 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7298 INIT_LIST_HEAD(&ref_node->node);
7299 INIT_LIST_HEAD(&ref_node->rsrc_list);
7300 ref_node->done = false;
7304 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7305 struct io_rsrc_data *data_to_kill)
7307 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7308 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7311 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7313 rsrc_node->rsrc_data = data_to_kill;
7314 spin_lock_irq(&ctx->rsrc_ref_lock);
7315 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7316 spin_unlock_irq(&ctx->rsrc_ref_lock);
7318 atomic_inc(&data_to_kill->refs);
7319 percpu_ref_kill(&rsrc_node->refs);
7320 ctx->rsrc_node = NULL;
7323 if (!ctx->rsrc_node) {
7324 ctx->rsrc_node = ctx->rsrc_backup_node;
7325 ctx->rsrc_backup_node = NULL;
7329 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7331 if (ctx->rsrc_backup_node)
7333 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7334 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7337 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7341 /* As we may drop ->uring_lock, other task may have started quiesce */
7345 data->quiesce = true;
7347 ret = io_rsrc_node_switch_start(ctx);
7350 io_rsrc_node_switch(ctx, data);
7352 /* kill initial ref, already quiesced if zero */
7353 if (atomic_dec_and_test(&data->refs))
7355 mutex_unlock(&ctx->uring_lock);
7356 flush_delayed_work(&ctx->rsrc_put_work);
7357 ret = wait_for_completion_interruptible(&data->done);
7359 mutex_lock(&ctx->uring_lock);
7363 atomic_inc(&data->refs);
7364 /* wait for all works potentially completing data->done */
7365 flush_delayed_work(&ctx->rsrc_put_work);
7366 reinit_completion(&data->done);
7368 ret = io_run_task_work_sig();
7369 mutex_lock(&ctx->uring_lock);
7371 data->quiesce = false;
7376 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7378 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7379 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7381 return &data->tags[table_idx][off];
7384 static void io_rsrc_data_free(struct io_rsrc_data *data)
7386 size_t size = data->nr * sizeof(data->tags[0][0]);
7389 io_free_page_table((void **)data->tags, size);
7393 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7394 u64 __user *utags, unsigned nr,
7395 struct io_rsrc_data **pdata)
7397 struct io_rsrc_data *data;
7401 data = kzalloc(sizeof(*data), GFP_KERNEL);
7404 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7412 data->do_put = do_put;
7415 for (i = 0; i < nr; i++) {
7416 u64 *tag_slot = io_get_tag_slot(data, i);
7418 if (copy_from_user(tag_slot, &utags[i],
7424 atomic_set(&data->refs, 1);
7425 init_completion(&data->done);
7429 io_rsrc_data_free(data);
7433 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7435 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7436 GFP_KERNEL_ACCOUNT);
7437 return !!table->files;
7440 static void io_free_file_tables(struct io_file_table *table)
7442 kvfree(table->files);
7443 table->files = NULL;
7446 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7448 #if defined(CONFIG_UNIX)
7449 if (ctx->ring_sock) {
7450 struct sock *sock = ctx->ring_sock->sk;
7451 struct sk_buff *skb;
7453 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7459 for (i = 0; i < ctx->nr_user_files; i++) {
7462 file = io_file_from_index(ctx, i);
7467 io_free_file_tables(&ctx->file_table);
7468 io_rsrc_data_free(ctx->file_data);
7469 ctx->file_data = NULL;
7470 ctx->nr_user_files = 0;
7473 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7477 if (!ctx->file_data)
7479 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7481 __io_sqe_files_unregister(ctx);
7485 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7486 __releases(&sqd->lock)
7488 WARN_ON_ONCE(sqd->thread == current);
7491 * Do the dance but not conditional clear_bit() because it'd race with
7492 * other threads incrementing park_pending and setting the bit.
7494 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7495 if (atomic_dec_return(&sqd->park_pending))
7496 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7497 mutex_unlock(&sqd->lock);
7500 static void io_sq_thread_park(struct io_sq_data *sqd)
7501 __acquires(&sqd->lock)
7503 WARN_ON_ONCE(sqd->thread == current);
7505 atomic_inc(&sqd->park_pending);
7506 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7507 mutex_lock(&sqd->lock);
7509 wake_up_process(sqd->thread);
7512 static void io_sq_thread_stop(struct io_sq_data *sqd)
7514 WARN_ON_ONCE(sqd->thread == current);
7515 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7517 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7518 mutex_lock(&sqd->lock);
7520 wake_up_process(sqd->thread);
7521 mutex_unlock(&sqd->lock);
7522 wait_for_completion(&sqd->exited);
7525 static void io_put_sq_data(struct io_sq_data *sqd)
7527 if (refcount_dec_and_test(&sqd->refs)) {
7528 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7530 io_sq_thread_stop(sqd);
7535 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7537 struct io_sq_data *sqd = ctx->sq_data;
7540 io_sq_thread_park(sqd);
7541 list_del_init(&ctx->sqd_list);
7542 io_sqd_update_thread_idle(sqd);
7543 io_sq_thread_unpark(sqd);
7545 io_put_sq_data(sqd);
7546 ctx->sq_data = NULL;
7550 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7552 struct io_ring_ctx *ctx_attach;
7553 struct io_sq_data *sqd;
7556 f = fdget(p->wq_fd);
7558 return ERR_PTR(-ENXIO);
7559 if (f.file->f_op != &io_uring_fops) {
7561 return ERR_PTR(-EINVAL);
7564 ctx_attach = f.file->private_data;
7565 sqd = ctx_attach->sq_data;
7568 return ERR_PTR(-EINVAL);
7570 if (sqd->task_tgid != current->tgid) {
7572 return ERR_PTR(-EPERM);
7575 refcount_inc(&sqd->refs);
7580 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7583 struct io_sq_data *sqd;
7586 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7587 sqd = io_attach_sq_data(p);
7592 /* fall through for EPERM case, setup new sqd/task */
7593 if (PTR_ERR(sqd) != -EPERM)
7597 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7599 return ERR_PTR(-ENOMEM);
7601 atomic_set(&sqd->park_pending, 0);
7602 refcount_set(&sqd->refs, 1);
7603 INIT_LIST_HEAD(&sqd->ctx_list);
7604 mutex_init(&sqd->lock);
7605 init_waitqueue_head(&sqd->wait);
7606 init_completion(&sqd->exited);
7610 #if defined(CONFIG_UNIX)
7612 * Ensure the UNIX gc is aware of our file set, so we are certain that
7613 * the io_uring can be safely unregistered on process exit, even if we have
7614 * loops in the file referencing.
7616 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7618 struct sock *sk = ctx->ring_sock->sk;
7619 struct scm_fp_list *fpl;
7620 struct sk_buff *skb;
7623 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7627 skb = alloc_skb(0, GFP_KERNEL);
7636 fpl->user = get_uid(current_user());
7637 for (i = 0; i < nr; i++) {
7638 struct file *file = io_file_from_index(ctx, i + offset);
7642 fpl->fp[nr_files] = get_file(file);
7643 unix_inflight(fpl->user, fpl->fp[nr_files]);
7648 fpl->max = SCM_MAX_FD;
7649 fpl->count = nr_files;
7650 UNIXCB(skb).fp = fpl;
7651 skb->destructor = unix_destruct_scm;
7652 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7653 skb_queue_head(&sk->sk_receive_queue, skb);
7655 for (i = 0; i < nr_files; i++)
7666 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7667 * causes regular reference counting to break down. We rely on the UNIX
7668 * garbage collection to take care of this problem for us.
7670 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7672 unsigned left, total;
7676 left = ctx->nr_user_files;
7678 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7680 ret = __io_sqe_files_scm(ctx, this_files, total);
7684 total += this_files;
7690 while (total < ctx->nr_user_files) {
7691 struct file *file = io_file_from_index(ctx, total);
7701 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7707 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7709 struct file *file = prsrc->file;
7710 #if defined(CONFIG_UNIX)
7711 struct sock *sock = ctx->ring_sock->sk;
7712 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7713 struct sk_buff *skb;
7716 __skb_queue_head_init(&list);
7719 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7720 * remove this entry and rearrange the file array.
7722 skb = skb_dequeue(head);
7724 struct scm_fp_list *fp;
7726 fp = UNIXCB(skb).fp;
7727 for (i = 0; i < fp->count; i++) {
7730 if (fp->fp[i] != file)
7733 unix_notinflight(fp->user, fp->fp[i]);
7734 left = fp->count - 1 - i;
7736 memmove(&fp->fp[i], &fp->fp[i + 1],
7737 left * sizeof(struct file *));
7744 __skb_queue_tail(&list, skb);
7754 __skb_queue_tail(&list, skb);
7756 skb = skb_dequeue(head);
7759 if (skb_peek(&list)) {
7760 spin_lock_irq(&head->lock);
7761 while ((skb = __skb_dequeue(&list)) != NULL)
7762 __skb_queue_tail(head, skb);
7763 spin_unlock_irq(&head->lock);
7770 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7772 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7773 struct io_ring_ctx *ctx = rsrc_data->ctx;
7774 struct io_rsrc_put *prsrc, *tmp;
7776 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7777 list_del(&prsrc->list);
7780 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7782 io_ring_submit_lock(ctx, lock_ring);
7783 spin_lock(&ctx->completion_lock);
7784 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7786 io_commit_cqring(ctx);
7787 spin_unlock(&ctx->completion_lock);
7788 io_cqring_ev_posted(ctx);
7789 io_ring_submit_unlock(ctx, lock_ring);
7792 rsrc_data->do_put(ctx, prsrc);
7796 io_rsrc_node_destroy(ref_node);
7797 if (atomic_dec_and_test(&rsrc_data->refs))
7798 complete(&rsrc_data->done);
7801 static void io_rsrc_put_work(struct work_struct *work)
7803 struct io_ring_ctx *ctx;
7804 struct llist_node *node;
7806 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7807 node = llist_del_all(&ctx->rsrc_put_llist);
7810 struct io_rsrc_node *ref_node;
7811 struct llist_node *next = node->next;
7813 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7814 __io_rsrc_put_work(ref_node);
7819 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7820 unsigned nr_args, u64 __user *tags)
7822 __s32 __user *fds = (__s32 __user *) arg;
7831 if (nr_args > IORING_MAX_FIXED_FILES)
7833 if (nr_args > rlimit(RLIMIT_NOFILE))
7835 ret = io_rsrc_node_switch_start(ctx);
7838 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7844 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7847 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7848 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7852 /* allow sparse sets */
7855 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7862 if (unlikely(!file))
7866 * Don't allow io_uring instances to be registered. If UNIX
7867 * isn't enabled, then this causes a reference cycle and this
7868 * instance can never get freed. If UNIX is enabled we'll
7869 * handle it just fine, but there's still no point in allowing
7870 * a ring fd as it doesn't support regular read/write anyway.
7872 if (file->f_op == &io_uring_fops) {
7876 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7879 ret = io_sqe_files_scm(ctx);
7881 __io_sqe_files_unregister(ctx);
7885 io_rsrc_node_switch(ctx, NULL);
7888 for (i = 0; i < ctx->nr_user_files; i++) {
7889 file = io_file_from_index(ctx, i);
7893 io_free_file_tables(&ctx->file_table);
7894 ctx->nr_user_files = 0;
7896 io_rsrc_data_free(ctx->file_data);
7897 ctx->file_data = NULL;
7901 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7904 #if defined(CONFIG_UNIX)
7905 struct sock *sock = ctx->ring_sock->sk;
7906 struct sk_buff_head *head = &sock->sk_receive_queue;
7907 struct sk_buff *skb;
7910 * See if we can merge this file into an existing skb SCM_RIGHTS
7911 * file set. If there's no room, fall back to allocating a new skb
7912 * and filling it in.
7914 spin_lock_irq(&head->lock);
7915 skb = skb_peek(head);
7917 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7919 if (fpl->count < SCM_MAX_FD) {
7920 __skb_unlink(skb, head);
7921 spin_unlock_irq(&head->lock);
7922 fpl->fp[fpl->count] = get_file(file);
7923 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7925 spin_lock_irq(&head->lock);
7926 __skb_queue_head(head, skb);
7931 spin_unlock_irq(&head->lock);
7938 return __io_sqe_files_scm(ctx, 1, index);
7944 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
7945 unsigned int issue_flags, u32 slot_index)
7947 struct io_ring_ctx *ctx = req->ctx;
7948 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
7949 struct io_fixed_file *file_slot;
7952 io_ring_submit_lock(ctx, !force_nonblock);
7953 if (file->f_op == &io_uring_fops)
7956 if (!ctx->file_data)
7959 if (slot_index >= ctx->nr_user_files)
7962 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
7963 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
7965 if (file_slot->file_ptr)
7968 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
7969 io_fixed_file_set(file_slot, file);
7970 ret = io_sqe_file_register(ctx, file, slot_index);
7972 file_slot->file_ptr = 0;
7978 io_ring_submit_unlock(ctx, !force_nonblock);
7984 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7985 struct io_rsrc_node *node, void *rsrc)
7987 struct io_rsrc_put *prsrc;
7989 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7993 prsrc->tag = *io_get_tag_slot(data, idx);
7995 list_add(&prsrc->list, &node->rsrc_list);
7999 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8000 struct io_uring_rsrc_update2 *up,
8003 u64 __user *tags = u64_to_user_ptr(up->tags);
8004 __s32 __user *fds = u64_to_user_ptr(up->data);
8005 struct io_rsrc_data *data = ctx->file_data;
8006 struct io_fixed_file *file_slot;
8010 bool needs_switch = false;
8012 if (!ctx->file_data)
8014 if (up->offset + nr_args > ctx->nr_user_files)
8017 for (done = 0; done < nr_args; done++) {
8020 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8021 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8025 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8029 if (fd == IORING_REGISTER_FILES_SKIP)
8032 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8033 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8035 if (file_slot->file_ptr) {
8036 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8037 err = io_queue_rsrc_removal(data, up->offset + done,
8038 ctx->rsrc_node, file);
8041 file_slot->file_ptr = 0;
8042 needs_switch = true;
8051 * Don't allow io_uring instances to be registered. If
8052 * UNIX isn't enabled, then this causes a reference
8053 * cycle and this instance can never get freed. If UNIX
8054 * is enabled we'll handle it just fine, but there's
8055 * still no point in allowing a ring fd as it doesn't
8056 * support regular read/write anyway.
8058 if (file->f_op == &io_uring_fops) {
8063 *io_get_tag_slot(data, up->offset + done) = tag;
8064 io_fixed_file_set(file_slot, file);
8065 err = io_sqe_file_register(ctx, file, i);
8067 file_slot->file_ptr = 0;
8075 io_rsrc_node_switch(ctx, data);
8076 return done ? done : err;
8079 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8080 struct task_struct *task)
8082 struct io_wq_hash *hash;
8083 struct io_wq_data data;
8084 unsigned int concurrency;
8086 mutex_lock(&ctx->uring_lock);
8087 hash = ctx->hash_map;
8089 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8091 mutex_unlock(&ctx->uring_lock);
8092 return ERR_PTR(-ENOMEM);
8094 refcount_set(&hash->refs, 1);
8095 init_waitqueue_head(&hash->wait);
8096 ctx->hash_map = hash;
8098 mutex_unlock(&ctx->uring_lock);
8102 data.free_work = io_wq_free_work;
8103 data.do_work = io_wq_submit_work;
8105 /* Do QD, or 4 * CPUS, whatever is smallest */
8106 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8108 return io_wq_create(concurrency, &data);
8111 static int io_uring_alloc_task_context(struct task_struct *task,
8112 struct io_ring_ctx *ctx)
8114 struct io_uring_task *tctx;
8117 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8118 if (unlikely(!tctx))
8121 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8122 if (unlikely(ret)) {
8127 tctx->io_wq = io_init_wq_offload(ctx, task);
8128 if (IS_ERR(tctx->io_wq)) {
8129 ret = PTR_ERR(tctx->io_wq);
8130 percpu_counter_destroy(&tctx->inflight);
8136 init_waitqueue_head(&tctx->wait);
8137 atomic_set(&tctx->in_idle, 0);
8138 atomic_set(&tctx->inflight_tracked, 0);
8139 task->io_uring = tctx;
8140 spin_lock_init(&tctx->task_lock);
8141 INIT_WQ_LIST(&tctx->task_list);
8142 init_task_work(&tctx->task_work, tctx_task_work);
8146 void __io_uring_free(struct task_struct *tsk)
8148 struct io_uring_task *tctx = tsk->io_uring;
8150 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8151 WARN_ON_ONCE(tctx->io_wq);
8152 WARN_ON_ONCE(tctx->cached_refs);
8154 percpu_counter_destroy(&tctx->inflight);
8156 tsk->io_uring = NULL;
8159 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8160 struct io_uring_params *p)
8164 /* Retain compatibility with failing for an invalid attach attempt */
8165 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8166 IORING_SETUP_ATTACH_WQ) {
8169 f = fdget(p->wq_fd);
8172 if (f.file->f_op != &io_uring_fops) {
8178 if (ctx->flags & IORING_SETUP_SQPOLL) {
8179 struct task_struct *tsk;
8180 struct io_sq_data *sqd;
8183 sqd = io_get_sq_data(p, &attached);
8189 ctx->sq_creds = get_current_cred();
8191 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8192 if (!ctx->sq_thread_idle)
8193 ctx->sq_thread_idle = HZ;
8195 io_sq_thread_park(sqd);
8196 list_add(&ctx->sqd_list, &sqd->ctx_list);
8197 io_sqd_update_thread_idle(sqd);
8198 /* don't attach to a dying SQPOLL thread, would be racy */
8199 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8200 io_sq_thread_unpark(sqd);
8207 if (p->flags & IORING_SETUP_SQ_AFF) {
8208 int cpu = p->sq_thread_cpu;
8211 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8218 sqd->task_pid = current->pid;
8219 sqd->task_tgid = current->tgid;
8220 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8227 ret = io_uring_alloc_task_context(tsk, ctx);
8228 wake_up_new_task(tsk);
8231 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8232 /* Can't have SQ_AFF without SQPOLL */
8239 complete(&ctx->sq_data->exited);
8241 io_sq_thread_finish(ctx);
8245 static inline void __io_unaccount_mem(struct user_struct *user,
8246 unsigned long nr_pages)
8248 atomic_long_sub(nr_pages, &user->locked_vm);
8251 static inline int __io_account_mem(struct user_struct *user,
8252 unsigned long nr_pages)
8254 unsigned long page_limit, cur_pages, new_pages;
8256 /* Don't allow more pages than we can safely lock */
8257 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8260 cur_pages = atomic_long_read(&user->locked_vm);
8261 new_pages = cur_pages + nr_pages;
8262 if (new_pages > page_limit)
8264 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8265 new_pages) != cur_pages);
8270 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8273 __io_unaccount_mem(ctx->user, nr_pages);
8275 if (ctx->mm_account)
8276 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8279 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8284 ret = __io_account_mem(ctx->user, nr_pages);
8289 if (ctx->mm_account)
8290 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8295 static void io_mem_free(void *ptr)
8302 page = virt_to_head_page(ptr);
8303 if (put_page_testzero(page))
8304 free_compound_page(page);
8307 static void *io_mem_alloc(size_t size)
8309 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8310 __GFP_NORETRY | __GFP_ACCOUNT;
8312 return (void *) __get_free_pages(gfp_flags, get_order(size));
8315 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8318 struct io_rings *rings;
8319 size_t off, sq_array_size;
8321 off = struct_size(rings, cqes, cq_entries);
8322 if (off == SIZE_MAX)
8326 off = ALIGN(off, SMP_CACHE_BYTES);
8334 sq_array_size = array_size(sizeof(u32), sq_entries);
8335 if (sq_array_size == SIZE_MAX)
8338 if (check_add_overflow(off, sq_array_size, &off))
8344 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8346 struct io_mapped_ubuf *imu = *slot;
8349 if (imu != ctx->dummy_ubuf) {
8350 for (i = 0; i < imu->nr_bvecs; i++)
8351 unpin_user_page(imu->bvec[i].bv_page);
8352 if (imu->acct_pages)
8353 io_unaccount_mem(ctx, imu->acct_pages);
8359 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8361 io_buffer_unmap(ctx, &prsrc->buf);
8365 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8369 for (i = 0; i < ctx->nr_user_bufs; i++)
8370 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8371 kfree(ctx->user_bufs);
8372 io_rsrc_data_free(ctx->buf_data);
8373 ctx->user_bufs = NULL;
8374 ctx->buf_data = NULL;
8375 ctx->nr_user_bufs = 0;
8378 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8385 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8387 __io_sqe_buffers_unregister(ctx);
8391 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8392 void __user *arg, unsigned index)
8394 struct iovec __user *src;
8396 #ifdef CONFIG_COMPAT
8398 struct compat_iovec __user *ciovs;
8399 struct compat_iovec ciov;
8401 ciovs = (struct compat_iovec __user *) arg;
8402 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8405 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8406 dst->iov_len = ciov.iov_len;
8410 src = (struct iovec __user *) arg;
8411 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8417 * Not super efficient, but this is just a registration time. And we do cache
8418 * the last compound head, so generally we'll only do a full search if we don't
8421 * We check if the given compound head page has already been accounted, to
8422 * avoid double accounting it. This allows us to account the full size of the
8423 * page, not just the constituent pages of a huge page.
8425 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8426 int nr_pages, struct page *hpage)
8430 /* check current page array */
8431 for (i = 0; i < nr_pages; i++) {
8432 if (!PageCompound(pages[i]))
8434 if (compound_head(pages[i]) == hpage)
8438 /* check previously registered pages */
8439 for (i = 0; i < ctx->nr_user_bufs; i++) {
8440 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8442 for (j = 0; j < imu->nr_bvecs; j++) {
8443 if (!PageCompound(imu->bvec[j].bv_page))
8445 if (compound_head(imu->bvec[j].bv_page) == hpage)
8453 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8454 int nr_pages, struct io_mapped_ubuf *imu,
8455 struct page **last_hpage)
8459 imu->acct_pages = 0;
8460 for (i = 0; i < nr_pages; i++) {
8461 if (!PageCompound(pages[i])) {
8466 hpage = compound_head(pages[i]);
8467 if (hpage == *last_hpage)
8469 *last_hpage = hpage;
8470 if (headpage_already_acct(ctx, pages, i, hpage))
8472 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8476 if (!imu->acct_pages)
8479 ret = io_account_mem(ctx, imu->acct_pages);
8481 imu->acct_pages = 0;
8485 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8486 struct io_mapped_ubuf **pimu,
8487 struct page **last_hpage)
8489 struct io_mapped_ubuf *imu = NULL;
8490 struct vm_area_struct **vmas = NULL;
8491 struct page **pages = NULL;
8492 unsigned long off, start, end, ubuf;
8494 int ret, pret, nr_pages, i;
8496 if (!iov->iov_base) {
8497 *pimu = ctx->dummy_ubuf;
8501 ubuf = (unsigned long) iov->iov_base;
8502 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8503 start = ubuf >> PAGE_SHIFT;
8504 nr_pages = end - start;
8509 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8513 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8518 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8523 mmap_read_lock(current->mm);
8524 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8526 if (pret == nr_pages) {
8527 /* don't support file backed memory */
8528 for (i = 0; i < nr_pages; i++) {
8529 struct vm_area_struct *vma = vmas[i];
8531 if (vma_is_shmem(vma))
8534 !is_file_hugepages(vma->vm_file)) {
8540 ret = pret < 0 ? pret : -EFAULT;
8542 mmap_read_unlock(current->mm);
8545 * if we did partial map, or found file backed vmas,
8546 * release any pages we did get
8549 unpin_user_pages(pages, pret);
8553 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8555 unpin_user_pages(pages, pret);
8559 off = ubuf & ~PAGE_MASK;
8560 size = iov->iov_len;
8561 for (i = 0; i < nr_pages; i++) {
8564 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8565 imu->bvec[i].bv_page = pages[i];
8566 imu->bvec[i].bv_len = vec_len;
8567 imu->bvec[i].bv_offset = off;
8571 /* store original address for later verification */
8573 imu->ubuf_end = ubuf + iov->iov_len;
8574 imu->nr_bvecs = nr_pages;
8585 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8587 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8588 return ctx->user_bufs ? 0 : -ENOMEM;
8591 static int io_buffer_validate(struct iovec *iov)
8593 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8596 * Don't impose further limits on the size and buffer
8597 * constraints here, we'll -EINVAL later when IO is
8598 * submitted if they are wrong.
8601 return iov->iov_len ? -EFAULT : 0;
8605 /* arbitrary limit, but we need something */
8606 if (iov->iov_len > SZ_1G)
8609 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8615 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8616 unsigned int nr_args, u64 __user *tags)
8618 struct page *last_hpage = NULL;
8619 struct io_rsrc_data *data;
8625 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8627 ret = io_rsrc_node_switch_start(ctx);
8630 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8633 ret = io_buffers_map_alloc(ctx, nr_args);
8635 io_rsrc_data_free(data);
8639 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8640 ret = io_copy_iov(ctx, &iov, arg, i);
8643 ret = io_buffer_validate(&iov);
8646 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8651 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8657 WARN_ON_ONCE(ctx->buf_data);
8659 ctx->buf_data = data;
8661 __io_sqe_buffers_unregister(ctx);
8663 io_rsrc_node_switch(ctx, NULL);
8667 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8668 struct io_uring_rsrc_update2 *up,
8669 unsigned int nr_args)
8671 u64 __user *tags = u64_to_user_ptr(up->tags);
8672 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8673 struct page *last_hpage = NULL;
8674 bool needs_switch = false;
8680 if (up->offset + nr_args > ctx->nr_user_bufs)
8683 for (done = 0; done < nr_args; done++) {
8684 struct io_mapped_ubuf *imu;
8685 int offset = up->offset + done;
8688 err = io_copy_iov(ctx, &iov, iovs, done);
8691 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8695 err = io_buffer_validate(&iov);
8698 if (!iov.iov_base && tag) {
8702 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8706 i = array_index_nospec(offset, ctx->nr_user_bufs);
8707 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8708 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8709 ctx->rsrc_node, ctx->user_bufs[i]);
8710 if (unlikely(err)) {
8711 io_buffer_unmap(ctx, &imu);
8714 ctx->user_bufs[i] = NULL;
8715 needs_switch = true;
8718 ctx->user_bufs[i] = imu;
8719 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8723 io_rsrc_node_switch(ctx, ctx->buf_data);
8724 return done ? done : err;
8727 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8729 __s32 __user *fds = arg;
8735 if (copy_from_user(&fd, fds, sizeof(*fds)))
8738 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8739 if (IS_ERR(ctx->cq_ev_fd)) {
8740 int ret = PTR_ERR(ctx->cq_ev_fd);
8742 ctx->cq_ev_fd = NULL;
8749 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8751 if (ctx->cq_ev_fd) {
8752 eventfd_ctx_put(ctx->cq_ev_fd);
8753 ctx->cq_ev_fd = NULL;
8760 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8762 struct io_buffer *buf;
8763 unsigned long index;
8765 xa_for_each(&ctx->io_buffers, index, buf)
8766 __io_remove_buffers(ctx, buf, index, -1U);
8769 static void io_req_cache_free(struct list_head *list)
8771 struct io_kiocb *req, *nxt;
8773 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8774 list_del(&req->inflight_entry);
8775 kmem_cache_free(req_cachep, req);
8779 static void io_req_caches_free(struct io_ring_ctx *ctx)
8781 struct io_submit_state *state = &ctx->submit_state;
8783 mutex_lock(&ctx->uring_lock);
8785 if (state->free_reqs) {
8786 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8787 state->free_reqs = 0;
8790 io_flush_cached_locked_reqs(ctx, state);
8791 io_req_cache_free(&state->free_list);
8792 mutex_unlock(&ctx->uring_lock);
8795 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8797 if (data && !atomic_dec_and_test(&data->refs))
8798 wait_for_completion(&data->done);
8801 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8803 io_sq_thread_finish(ctx);
8805 if (ctx->mm_account) {
8806 mmdrop(ctx->mm_account);
8807 ctx->mm_account = NULL;
8810 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8811 io_wait_rsrc_data(ctx->buf_data);
8812 io_wait_rsrc_data(ctx->file_data);
8814 mutex_lock(&ctx->uring_lock);
8816 __io_sqe_buffers_unregister(ctx);
8818 __io_sqe_files_unregister(ctx);
8820 __io_cqring_overflow_flush(ctx, true);
8821 mutex_unlock(&ctx->uring_lock);
8822 io_eventfd_unregister(ctx);
8823 io_destroy_buffers(ctx);
8825 put_cred(ctx->sq_creds);
8827 /* there are no registered resources left, nobody uses it */
8829 io_rsrc_node_destroy(ctx->rsrc_node);
8830 if (ctx->rsrc_backup_node)
8831 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8832 flush_delayed_work(&ctx->rsrc_put_work);
8834 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8835 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8837 #if defined(CONFIG_UNIX)
8838 if (ctx->ring_sock) {
8839 ctx->ring_sock->file = NULL; /* so that iput() is called */
8840 sock_release(ctx->ring_sock);
8844 io_mem_free(ctx->rings);
8845 io_mem_free(ctx->sq_sqes);
8847 percpu_ref_exit(&ctx->refs);
8848 free_uid(ctx->user);
8849 io_req_caches_free(ctx);
8851 io_wq_put_hash(ctx->hash_map);
8852 kfree(ctx->cancel_hash);
8853 kfree(ctx->dummy_ubuf);
8857 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8859 struct io_ring_ctx *ctx = file->private_data;
8862 poll_wait(file, &ctx->poll_wait, wait);
8864 * synchronizes with barrier from wq_has_sleeper call in
8868 if (!io_sqring_full(ctx))
8869 mask |= EPOLLOUT | EPOLLWRNORM;
8872 * Don't flush cqring overflow list here, just do a simple check.
8873 * Otherwise there could possible be ABBA deadlock:
8876 * lock(&ctx->uring_lock);
8878 * lock(&ctx->uring_lock);
8881 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8882 * pushs them to do the flush.
8884 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8885 mask |= EPOLLIN | EPOLLRDNORM;
8890 static int io_uring_fasync(int fd, struct file *file, int on)
8892 struct io_ring_ctx *ctx = file->private_data;
8894 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8897 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8899 const struct cred *creds;
8901 creds = xa_erase(&ctx->personalities, id);
8910 struct io_tctx_exit {
8911 struct callback_head task_work;
8912 struct completion completion;
8913 struct io_ring_ctx *ctx;
8916 static void io_tctx_exit_cb(struct callback_head *cb)
8918 struct io_uring_task *tctx = current->io_uring;
8919 struct io_tctx_exit *work;
8921 work = container_of(cb, struct io_tctx_exit, task_work);
8923 * When @in_idle, we're in cancellation and it's racy to remove the
8924 * node. It'll be removed by the end of cancellation, just ignore it.
8926 if (!atomic_read(&tctx->in_idle))
8927 io_uring_del_tctx_node((unsigned long)work->ctx);
8928 complete(&work->completion);
8931 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8933 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8935 return req->ctx == data;
8938 static void io_ring_exit_work(struct work_struct *work)
8940 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8941 unsigned long timeout = jiffies + HZ * 60 * 5;
8942 unsigned long interval = HZ / 20;
8943 struct io_tctx_exit exit;
8944 struct io_tctx_node *node;
8948 * If we're doing polled IO and end up having requests being
8949 * submitted async (out-of-line), then completions can come in while
8950 * we're waiting for refs to drop. We need to reap these manually,
8951 * as nobody else will be looking for them.
8954 io_uring_try_cancel_requests(ctx, NULL, true);
8956 struct io_sq_data *sqd = ctx->sq_data;
8957 struct task_struct *tsk;
8959 io_sq_thread_park(sqd);
8961 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8962 io_wq_cancel_cb(tsk->io_uring->io_wq,
8963 io_cancel_ctx_cb, ctx, true);
8964 io_sq_thread_unpark(sqd);
8967 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
8968 /* there is little hope left, don't run it too often */
8971 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
8973 init_completion(&exit.completion);
8974 init_task_work(&exit.task_work, io_tctx_exit_cb);
8977 * Some may use context even when all refs and requests have been put,
8978 * and they are free to do so while still holding uring_lock or
8979 * completion_lock, see io_req_task_submit(). Apart from other work,
8980 * this lock/unlock section also waits them to finish.
8982 mutex_lock(&ctx->uring_lock);
8983 while (!list_empty(&ctx->tctx_list)) {
8984 WARN_ON_ONCE(time_after(jiffies, timeout));
8986 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8988 /* don't spin on a single task if cancellation failed */
8989 list_rotate_left(&ctx->tctx_list);
8990 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8991 if (WARN_ON_ONCE(ret))
8993 wake_up_process(node->task);
8995 mutex_unlock(&ctx->uring_lock);
8996 wait_for_completion(&exit.completion);
8997 mutex_lock(&ctx->uring_lock);
8999 mutex_unlock(&ctx->uring_lock);
9000 spin_lock(&ctx->completion_lock);
9001 spin_unlock(&ctx->completion_lock);
9003 io_ring_ctx_free(ctx);
9006 /* Returns true if we found and killed one or more timeouts */
9007 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9010 struct io_kiocb *req, *tmp;
9013 spin_lock(&ctx->completion_lock);
9014 spin_lock_irq(&ctx->timeout_lock);
9015 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9016 if (io_match_task(req, tsk, cancel_all)) {
9017 io_kill_timeout(req, -ECANCELED);
9021 spin_unlock_irq(&ctx->timeout_lock);
9023 io_commit_cqring(ctx);
9024 spin_unlock(&ctx->completion_lock);
9026 io_cqring_ev_posted(ctx);
9027 return canceled != 0;
9030 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9032 unsigned long index;
9033 struct creds *creds;
9035 mutex_lock(&ctx->uring_lock);
9036 percpu_ref_kill(&ctx->refs);
9038 __io_cqring_overflow_flush(ctx, true);
9039 xa_for_each(&ctx->personalities, index, creds)
9040 io_unregister_personality(ctx, index);
9041 mutex_unlock(&ctx->uring_lock);
9043 io_kill_timeouts(ctx, NULL, true);
9044 io_poll_remove_all(ctx, NULL, true);
9046 /* if we failed setting up the ctx, we might not have any rings */
9047 io_iopoll_try_reap_events(ctx);
9049 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9051 * Use system_unbound_wq to avoid spawning tons of event kworkers
9052 * if we're exiting a ton of rings at the same time. It just adds
9053 * noise and overhead, there's no discernable change in runtime
9054 * over using system_wq.
9056 queue_work(system_unbound_wq, &ctx->exit_work);
9059 static int io_uring_release(struct inode *inode, struct file *file)
9061 struct io_ring_ctx *ctx = file->private_data;
9063 file->private_data = NULL;
9064 io_ring_ctx_wait_and_kill(ctx);
9068 struct io_task_cancel {
9069 struct task_struct *task;
9073 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9075 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9076 struct io_task_cancel *cancel = data;
9079 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
9080 struct io_ring_ctx *ctx = req->ctx;
9082 /* protect against races with linked timeouts */
9083 spin_lock(&ctx->completion_lock);
9084 ret = io_match_task(req, cancel->task, cancel->all);
9085 spin_unlock(&ctx->completion_lock);
9087 ret = io_match_task(req, cancel->task, cancel->all);
9092 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9093 struct task_struct *task, bool cancel_all)
9095 struct io_defer_entry *de;
9098 spin_lock(&ctx->completion_lock);
9099 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9100 if (io_match_task(de->req, task, cancel_all)) {
9101 list_cut_position(&list, &ctx->defer_list, &de->list);
9105 spin_unlock(&ctx->completion_lock);
9106 if (list_empty(&list))
9109 while (!list_empty(&list)) {
9110 de = list_first_entry(&list, struct io_defer_entry, list);
9111 list_del_init(&de->list);
9112 io_req_complete_failed(de->req, -ECANCELED);
9118 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9120 struct io_tctx_node *node;
9121 enum io_wq_cancel cret;
9124 mutex_lock(&ctx->uring_lock);
9125 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9126 struct io_uring_task *tctx = node->task->io_uring;
9129 * io_wq will stay alive while we hold uring_lock, because it's
9130 * killed after ctx nodes, which requires to take the lock.
9132 if (!tctx || !tctx->io_wq)
9134 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9135 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9137 mutex_unlock(&ctx->uring_lock);
9142 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9143 struct task_struct *task,
9146 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9147 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9150 enum io_wq_cancel cret;
9154 ret |= io_uring_try_cancel_iowq(ctx);
9155 } else if (tctx && tctx->io_wq) {
9157 * Cancels requests of all rings, not only @ctx, but
9158 * it's fine as the task is in exit/exec.
9160 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9162 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9165 /* SQPOLL thread does its own polling */
9166 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9167 (ctx->sq_data && ctx->sq_data->thread == current)) {
9168 while (!list_empty_careful(&ctx->iopoll_list)) {
9169 io_iopoll_try_reap_events(ctx);
9174 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9175 ret |= io_poll_remove_all(ctx, task, cancel_all);
9176 ret |= io_kill_timeouts(ctx, task, cancel_all);
9178 ret |= io_run_task_work();
9185 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9187 struct io_uring_task *tctx = current->io_uring;
9188 struct io_tctx_node *node;
9191 if (unlikely(!tctx)) {
9192 ret = io_uring_alloc_task_context(current, ctx);
9195 tctx = current->io_uring;
9197 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9198 node = kmalloc(sizeof(*node), GFP_KERNEL);
9202 node->task = current;
9204 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9211 mutex_lock(&ctx->uring_lock);
9212 list_add(&node->ctx_node, &ctx->tctx_list);
9213 mutex_unlock(&ctx->uring_lock);
9220 * Note that this task has used io_uring. We use it for cancelation purposes.
9222 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9224 struct io_uring_task *tctx = current->io_uring;
9226 if (likely(tctx && tctx->last == ctx))
9228 return __io_uring_add_tctx_node(ctx);
9232 * Remove this io_uring_file -> task mapping.
9234 static void io_uring_del_tctx_node(unsigned long index)
9236 struct io_uring_task *tctx = current->io_uring;
9237 struct io_tctx_node *node;
9241 node = xa_erase(&tctx->xa, index);
9245 WARN_ON_ONCE(current != node->task);
9246 WARN_ON_ONCE(list_empty(&node->ctx_node));
9248 mutex_lock(&node->ctx->uring_lock);
9249 list_del(&node->ctx_node);
9250 mutex_unlock(&node->ctx->uring_lock);
9252 if (tctx->last == node->ctx)
9257 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9259 struct io_wq *wq = tctx->io_wq;
9260 struct io_tctx_node *node;
9261 unsigned long index;
9263 xa_for_each(&tctx->xa, index, node)
9264 io_uring_del_tctx_node(index);
9267 * Must be after io_uring_del_task_file() (removes nodes under
9268 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9270 io_wq_put_and_exit(wq);
9275 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9278 return atomic_read(&tctx->inflight_tracked);
9279 return percpu_counter_sum(&tctx->inflight);
9282 static void io_uring_drop_tctx_refs(struct task_struct *task)
9284 struct io_uring_task *tctx = task->io_uring;
9285 unsigned int refs = tctx->cached_refs;
9288 tctx->cached_refs = 0;
9289 percpu_counter_sub(&tctx->inflight, refs);
9290 put_task_struct_many(task, refs);
9295 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9296 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9298 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9300 struct io_uring_task *tctx = current->io_uring;
9301 struct io_ring_ctx *ctx;
9305 WARN_ON_ONCE(sqd && sqd->thread != current);
9307 if (!current->io_uring)
9310 io_wq_exit_start(tctx->io_wq);
9312 atomic_inc(&tctx->in_idle);
9314 io_uring_drop_tctx_refs(current);
9315 /* read completions before cancelations */
9316 inflight = tctx_inflight(tctx, !cancel_all);
9321 struct io_tctx_node *node;
9322 unsigned long index;
9324 xa_for_each(&tctx->xa, index, node) {
9325 /* sqpoll task will cancel all its requests */
9326 if (node->ctx->sq_data)
9328 io_uring_try_cancel_requests(node->ctx, current,
9332 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9333 io_uring_try_cancel_requests(ctx, current,
9337 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9338 io_uring_drop_tctx_refs(current);
9340 * If we've seen completions, retry without waiting. This
9341 * avoids a race where a completion comes in before we did
9342 * prepare_to_wait().
9344 if (inflight == tctx_inflight(tctx, !cancel_all))
9346 finish_wait(&tctx->wait, &wait);
9348 atomic_dec(&tctx->in_idle);
9350 io_uring_clean_tctx(tctx);
9352 /* for exec all current's requests should be gone, kill tctx */
9353 __io_uring_free(current);
9357 void __io_uring_cancel(bool cancel_all)
9359 io_uring_cancel_generic(cancel_all, NULL);
9362 static void *io_uring_validate_mmap_request(struct file *file,
9363 loff_t pgoff, size_t sz)
9365 struct io_ring_ctx *ctx = file->private_data;
9366 loff_t offset = pgoff << PAGE_SHIFT;
9371 case IORING_OFF_SQ_RING:
9372 case IORING_OFF_CQ_RING:
9375 case IORING_OFF_SQES:
9379 return ERR_PTR(-EINVAL);
9382 page = virt_to_head_page(ptr);
9383 if (sz > page_size(page))
9384 return ERR_PTR(-EINVAL);
9391 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9393 size_t sz = vma->vm_end - vma->vm_start;
9397 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9399 return PTR_ERR(ptr);
9401 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9402 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9405 #else /* !CONFIG_MMU */
9407 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9409 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9412 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9414 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9417 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9418 unsigned long addr, unsigned long len,
9419 unsigned long pgoff, unsigned long flags)
9423 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9425 return PTR_ERR(ptr);
9427 return (unsigned long) ptr;
9430 #endif /* !CONFIG_MMU */
9432 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9437 if (!io_sqring_full(ctx))
9439 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9441 if (!io_sqring_full(ctx))
9444 } while (!signal_pending(current));
9446 finish_wait(&ctx->sqo_sq_wait, &wait);
9450 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9451 struct __kernel_timespec __user **ts,
9452 const sigset_t __user **sig)
9454 struct io_uring_getevents_arg arg;
9457 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9458 * is just a pointer to the sigset_t.
9460 if (!(flags & IORING_ENTER_EXT_ARG)) {
9461 *sig = (const sigset_t __user *) argp;
9467 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9468 * timespec and sigset_t pointers if good.
9470 if (*argsz != sizeof(arg))
9472 if (copy_from_user(&arg, argp, sizeof(arg)))
9474 *sig = u64_to_user_ptr(arg.sigmask);
9475 *argsz = arg.sigmask_sz;
9476 *ts = u64_to_user_ptr(arg.ts);
9480 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9481 u32, min_complete, u32, flags, const void __user *, argp,
9484 struct io_ring_ctx *ctx;
9491 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9492 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9496 if (unlikely(!f.file))
9500 if (unlikely(f.file->f_op != &io_uring_fops))
9504 ctx = f.file->private_data;
9505 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9509 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9513 * For SQ polling, the thread will do all submissions and completions.
9514 * Just return the requested submit count, and wake the thread if
9518 if (ctx->flags & IORING_SETUP_SQPOLL) {
9519 io_cqring_overflow_flush(ctx);
9521 if (unlikely(ctx->sq_data->thread == NULL)) {
9525 if (flags & IORING_ENTER_SQ_WAKEUP)
9526 wake_up(&ctx->sq_data->wait);
9527 if (flags & IORING_ENTER_SQ_WAIT) {
9528 ret = io_sqpoll_wait_sq(ctx);
9532 submitted = to_submit;
9533 } else if (to_submit) {
9534 ret = io_uring_add_tctx_node(ctx);
9537 mutex_lock(&ctx->uring_lock);
9538 submitted = io_submit_sqes(ctx, to_submit);
9539 mutex_unlock(&ctx->uring_lock);
9541 if (submitted != to_submit)
9544 if (flags & IORING_ENTER_GETEVENTS) {
9545 const sigset_t __user *sig;
9546 struct __kernel_timespec __user *ts;
9548 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9552 min_complete = min(min_complete, ctx->cq_entries);
9555 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9556 * space applications don't need to do io completion events
9557 * polling again, they can rely on io_sq_thread to do polling
9558 * work, which can reduce cpu usage and uring_lock contention.
9560 if (ctx->flags & IORING_SETUP_IOPOLL &&
9561 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9562 ret = io_iopoll_check(ctx, min_complete);
9564 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9569 percpu_ref_put(&ctx->refs);
9572 return submitted ? submitted : ret;
9575 #ifdef CONFIG_PROC_FS
9576 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9577 const struct cred *cred)
9579 struct user_namespace *uns = seq_user_ns(m);
9580 struct group_info *gi;
9585 seq_printf(m, "%5d\n", id);
9586 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9587 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9588 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9589 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9590 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9591 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9592 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9593 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9594 seq_puts(m, "\n\tGroups:\t");
9595 gi = cred->group_info;
9596 for (g = 0; g < gi->ngroups; g++) {
9597 seq_put_decimal_ull(m, g ? " " : "",
9598 from_kgid_munged(uns, gi->gid[g]));
9600 seq_puts(m, "\n\tCapEff:\t");
9601 cap = cred->cap_effective;
9602 CAP_FOR_EACH_U32(__capi)
9603 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9608 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9610 struct io_sq_data *sq = NULL;
9615 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9616 * since fdinfo case grabs it in the opposite direction of normal use
9617 * cases. If we fail to get the lock, we just don't iterate any
9618 * structures that could be going away outside the io_uring mutex.
9620 has_lock = mutex_trylock(&ctx->uring_lock);
9622 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9628 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9629 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9630 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9631 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9632 struct file *f = io_file_from_index(ctx, i);
9635 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9637 seq_printf(m, "%5u: <none>\n", i);
9639 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9640 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9641 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9642 unsigned int len = buf->ubuf_end - buf->ubuf;
9644 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9646 if (has_lock && !xa_empty(&ctx->personalities)) {
9647 unsigned long index;
9648 const struct cred *cred;
9650 seq_printf(m, "Personalities:\n");
9651 xa_for_each(&ctx->personalities, index, cred)
9652 io_uring_show_cred(m, index, cred);
9654 seq_printf(m, "PollList:\n");
9655 spin_lock(&ctx->completion_lock);
9656 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9657 struct hlist_head *list = &ctx->cancel_hash[i];
9658 struct io_kiocb *req;
9660 hlist_for_each_entry(req, list, hash_node)
9661 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9662 req->task->task_works != NULL);
9664 spin_unlock(&ctx->completion_lock);
9666 mutex_unlock(&ctx->uring_lock);
9669 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9671 struct io_ring_ctx *ctx = f->private_data;
9673 if (percpu_ref_tryget(&ctx->refs)) {
9674 __io_uring_show_fdinfo(ctx, m);
9675 percpu_ref_put(&ctx->refs);
9680 static const struct file_operations io_uring_fops = {
9681 .release = io_uring_release,
9682 .mmap = io_uring_mmap,
9684 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9685 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9687 .poll = io_uring_poll,
9688 .fasync = io_uring_fasync,
9689 #ifdef CONFIG_PROC_FS
9690 .show_fdinfo = io_uring_show_fdinfo,
9694 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9695 struct io_uring_params *p)
9697 struct io_rings *rings;
9698 size_t size, sq_array_offset;
9700 /* make sure these are sane, as we already accounted them */
9701 ctx->sq_entries = p->sq_entries;
9702 ctx->cq_entries = p->cq_entries;
9704 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9705 if (size == SIZE_MAX)
9708 rings = io_mem_alloc(size);
9713 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9714 rings->sq_ring_mask = p->sq_entries - 1;
9715 rings->cq_ring_mask = p->cq_entries - 1;
9716 rings->sq_ring_entries = p->sq_entries;
9717 rings->cq_ring_entries = p->cq_entries;
9719 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9720 if (size == SIZE_MAX) {
9721 io_mem_free(ctx->rings);
9726 ctx->sq_sqes = io_mem_alloc(size);
9727 if (!ctx->sq_sqes) {
9728 io_mem_free(ctx->rings);
9736 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9740 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9744 ret = io_uring_add_tctx_node(ctx);
9749 fd_install(fd, file);
9754 * Allocate an anonymous fd, this is what constitutes the application
9755 * visible backing of an io_uring instance. The application mmaps this
9756 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9757 * we have to tie this fd to a socket for file garbage collection purposes.
9759 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9762 #if defined(CONFIG_UNIX)
9765 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9768 return ERR_PTR(ret);
9771 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9772 O_RDWR | O_CLOEXEC);
9773 #if defined(CONFIG_UNIX)
9775 sock_release(ctx->ring_sock);
9776 ctx->ring_sock = NULL;
9778 ctx->ring_sock->file = file;
9784 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9785 struct io_uring_params __user *params)
9787 struct io_ring_ctx *ctx;
9793 if (entries > IORING_MAX_ENTRIES) {
9794 if (!(p->flags & IORING_SETUP_CLAMP))
9796 entries = IORING_MAX_ENTRIES;
9800 * Use twice as many entries for the CQ ring. It's possible for the
9801 * application to drive a higher depth than the size of the SQ ring,
9802 * since the sqes are only used at submission time. This allows for
9803 * some flexibility in overcommitting a bit. If the application has
9804 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9805 * of CQ ring entries manually.
9807 p->sq_entries = roundup_pow_of_two(entries);
9808 if (p->flags & IORING_SETUP_CQSIZE) {
9810 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9811 * to a power-of-two, if it isn't already. We do NOT impose
9812 * any cq vs sq ring sizing.
9816 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9817 if (!(p->flags & IORING_SETUP_CLAMP))
9819 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9821 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9822 if (p->cq_entries < p->sq_entries)
9825 p->cq_entries = 2 * p->sq_entries;
9828 ctx = io_ring_ctx_alloc(p);
9831 ctx->compat = in_compat_syscall();
9832 if (!capable(CAP_IPC_LOCK))
9833 ctx->user = get_uid(current_user());
9836 * This is just grabbed for accounting purposes. When a process exits,
9837 * the mm is exited and dropped before the files, hence we need to hang
9838 * on to this mm purely for the purposes of being able to unaccount
9839 * memory (locked/pinned vm). It's not used for anything else.
9841 mmgrab(current->mm);
9842 ctx->mm_account = current->mm;
9844 ret = io_allocate_scq_urings(ctx, p);
9848 ret = io_sq_offload_create(ctx, p);
9851 /* always set a rsrc node */
9852 ret = io_rsrc_node_switch_start(ctx);
9855 io_rsrc_node_switch(ctx, NULL);
9857 memset(&p->sq_off, 0, sizeof(p->sq_off));
9858 p->sq_off.head = offsetof(struct io_rings, sq.head);
9859 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9860 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9861 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9862 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9863 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9864 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9866 memset(&p->cq_off, 0, sizeof(p->cq_off));
9867 p->cq_off.head = offsetof(struct io_rings, cq.head);
9868 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9869 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9870 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9871 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9872 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9873 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9875 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9876 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9877 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9878 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9879 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9880 IORING_FEAT_RSRC_TAGS;
9882 if (copy_to_user(params, p, sizeof(*p))) {
9887 file = io_uring_get_file(ctx);
9889 ret = PTR_ERR(file);
9894 * Install ring fd as the very last thing, so we don't risk someone
9895 * having closed it before we finish setup
9897 ret = io_uring_install_fd(ctx, file);
9899 /* fput will clean it up */
9904 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9907 io_ring_ctx_wait_and_kill(ctx);
9912 * Sets up an aio uring context, and returns the fd. Applications asks for a
9913 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9914 * params structure passed in.
9916 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9918 struct io_uring_params p;
9921 if (copy_from_user(&p, params, sizeof(p)))
9923 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9928 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9929 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9930 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9931 IORING_SETUP_R_DISABLED))
9934 return io_uring_create(entries, &p, params);
9937 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9938 struct io_uring_params __user *, params)
9940 return io_uring_setup(entries, params);
9943 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9945 struct io_uring_probe *p;
9949 size = struct_size(p, ops, nr_args);
9950 if (size == SIZE_MAX)
9952 p = kzalloc(size, GFP_KERNEL);
9957 if (copy_from_user(p, arg, size))
9960 if (memchr_inv(p, 0, size))
9963 p->last_op = IORING_OP_LAST - 1;
9964 if (nr_args > IORING_OP_LAST)
9965 nr_args = IORING_OP_LAST;
9967 for (i = 0; i < nr_args; i++) {
9969 if (!io_op_defs[i].not_supported)
9970 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9975 if (copy_to_user(arg, p, size))
9982 static int io_register_personality(struct io_ring_ctx *ctx)
9984 const struct cred *creds;
9988 creds = get_current_cred();
9990 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9991 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9999 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10000 unsigned int nr_args)
10002 struct io_uring_restriction *res;
10006 /* Restrictions allowed only if rings started disabled */
10007 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10010 /* We allow only a single restrictions registration */
10011 if (ctx->restrictions.registered)
10014 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10017 size = array_size(nr_args, sizeof(*res));
10018 if (size == SIZE_MAX)
10021 res = memdup_user(arg, size);
10023 return PTR_ERR(res);
10027 for (i = 0; i < nr_args; i++) {
10028 switch (res[i].opcode) {
10029 case IORING_RESTRICTION_REGISTER_OP:
10030 if (res[i].register_op >= IORING_REGISTER_LAST) {
10035 __set_bit(res[i].register_op,
10036 ctx->restrictions.register_op);
10038 case IORING_RESTRICTION_SQE_OP:
10039 if (res[i].sqe_op >= IORING_OP_LAST) {
10044 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10046 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10047 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10049 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10050 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10059 /* Reset all restrictions if an error happened */
10061 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10063 ctx->restrictions.registered = true;
10069 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10071 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10074 if (ctx->restrictions.registered)
10075 ctx->restricted = 1;
10077 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10078 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10079 wake_up(&ctx->sq_data->wait);
10083 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10084 struct io_uring_rsrc_update2 *up,
10092 if (check_add_overflow(up->offset, nr_args, &tmp))
10094 err = io_rsrc_node_switch_start(ctx);
10099 case IORING_RSRC_FILE:
10100 return __io_sqe_files_update(ctx, up, nr_args);
10101 case IORING_RSRC_BUFFER:
10102 return __io_sqe_buffers_update(ctx, up, nr_args);
10107 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10110 struct io_uring_rsrc_update2 up;
10114 memset(&up, 0, sizeof(up));
10115 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10117 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10120 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10121 unsigned size, unsigned type)
10123 struct io_uring_rsrc_update2 up;
10125 if (size != sizeof(up))
10127 if (copy_from_user(&up, arg, sizeof(up)))
10129 if (!up.nr || up.resv)
10131 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10134 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10135 unsigned int size, unsigned int type)
10137 struct io_uring_rsrc_register rr;
10139 /* keep it extendible */
10140 if (size != sizeof(rr))
10143 memset(&rr, 0, sizeof(rr));
10144 if (copy_from_user(&rr, arg, size))
10146 if (!rr.nr || rr.resv || rr.resv2)
10150 case IORING_RSRC_FILE:
10151 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10152 rr.nr, u64_to_user_ptr(rr.tags));
10153 case IORING_RSRC_BUFFER:
10154 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10155 rr.nr, u64_to_user_ptr(rr.tags));
10160 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10163 struct io_uring_task *tctx = current->io_uring;
10164 cpumask_var_t new_mask;
10167 if (!tctx || !tctx->io_wq)
10170 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10173 cpumask_clear(new_mask);
10174 if (len > cpumask_size())
10175 len = cpumask_size();
10177 if (copy_from_user(new_mask, arg, len)) {
10178 free_cpumask_var(new_mask);
10182 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10183 free_cpumask_var(new_mask);
10187 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10189 struct io_uring_task *tctx = current->io_uring;
10191 if (!tctx || !tctx->io_wq)
10194 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10197 static bool io_register_op_must_quiesce(int op)
10200 case IORING_REGISTER_BUFFERS:
10201 case IORING_UNREGISTER_BUFFERS:
10202 case IORING_REGISTER_FILES:
10203 case IORING_UNREGISTER_FILES:
10204 case IORING_REGISTER_FILES_UPDATE:
10205 case IORING_REGISTER_PROBE:
10206 case IORING_REGISTER_PERSONALITY:
10207 case IORING_UNREGISTER_PERSONALITY:
10208 case IORING_REGISTER_FILES2:
10209 case IORING_REGISTER_FILES_UPDATE2:
10210 case IORING_REGISTER_BUFFERS2:
10211 case IORING_REGISTER_BUFFERS_UPDATE:
10212 case IORING_REGISTER_IOWQ_AFF:
10213 case IORING_UNREGISTER_IOWQ_AFF:
10220 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10224 percpu_ref_kill(&ctx->refs);
10227 * Drop uring mutex before waiting for references to exit. If another
10228 * thread is currently inside io_uring_enter() it might need to grab the
10229 * uring_lock to make progress. If we hold it here across the drain
10230 * wait, then we can deadlock. It's safe to drop the mutex here, since
10231 * no new references will come in after we've killed the percpu ref.
10233 mutex_unlock(&ctx->uring_lock);
10235 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10238 ret = io_run_task_work_sig();
10239 } while (ret >= 0);
10240 mutex_lock(&ctx->uring_lock);
10243 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10247 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10248 void __user *arg, unsigned nr_args)
10249 __releases(ctx->uring_lock)
10250 __acquires(ctx->uring_lock)
10255 * We're inside the ring mutex, if the ref is already dying, then
10256 * someone else killed the ctx or is already going through
10257 * io_uring_register().
10259 if (percpu_ref_is_dying(&ctx->refs))
10262 if (ctx->restricted) {
10263 if (opcode >= IORING_REGISTER_LAST)
10265 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10266 if (!test_bit(opcode, ctx->restrictions.register_op))
10270 if (io_register_op_must_quiesce(opcode)) {
10271 ret = io_ctx_quiesce(ctx);
10277 case IORING_REGISTER_BUFFERS:
10278 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10280 case IORING_UNREGISTER_BUFFERS:
10282 if (arg || nr_args)
10284 ret = io_sqe_buffers_unregister(ctx);
10286 case IORING_REGISTER_FILES:
10287 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10289 case IORING_UNREGISTER_FILES:
10291 if (arg || nr_args)
10293 ret = io_sqe_files_unregister(ctx);
10295 case IORING_REGISTER_FILES_UPDATE:
10296 ret = io_register_files_update(ctx, arg, nr_args);
10298 case IORING_REGISTER_EVENTFD:
10299 case IORING_REGISTER_EVENTFD_ASYNC:
10303 ret = io_eventfd_register(ctx, arg);
10306 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10307 ctx->eventfd_async = 1;
10309 ctx->eventfd_async = 0;
10311 case IORING_UNREGISTER_EVENTFD:
10313 if (arg || nr_args)
10315 ret = io_eventfd_unregister(ctx);
10317 case IORING_REGISTER_PROBE:
10319 if (!arg || nr_args > 256)
10321 ret = io_probe(ctx, arg, nr_args);
10323 case IORING_REGISTER_PERSONALITY:
10325 if (arg || nr_args)
10327 ret = io_register_personality(ctx);
10329 case IORING_UNREGISTER_PERSONALITY:
10333 ret = io_unregister_personality(ctx, nr_args);
10335 case IORING_REGISTER_ENABLE_RINGS:
10337 if (arg || nr_args)
10339 ret = io_register_enable_rings(ctx);
10341 case IORING_REGISTER_RESTRICTIONS:
10342 ret = io_register_restrictions(ctx, arg, nr_args);
10344 case IORING_REGISTER_FILES2:
10345 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10347 case IORING_REGISTER_FILES_UPDATE2:
10348 ret = io_register_rsrc_update(ctx, arg, nr_args,
10351 case IORING_REGISTER_BUFFERS2:
10352 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10354 case IORING_REGISTER_BUFFERS_UPDATE:
10355 ret = io_register_rsrc_update(ctx, arg, nr_args,
10356 IORING_RSRC_BUFFER);
10358 case IORING_REGISTER_IOWQ_AFF:
10360 if (!arg || !nr_args)
10362 ret = io_register_iowq_aff(ctx, arg, nr_args);
10364 case IORING_UNREGISTER_IOWQ_AFF:
10366 if (arg || nr_args)
10368 ret = io_unregister_iowq_aff(ctx);
10375 if (io_register_op_must_quiesce(opcode)) {
10376 /* bring the ctx back to life */
10377 percpu_ref_reinit(&ctx->refs);
10378 reinit_completion(&ctx->ref_comp);
10383 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10384 void __user *, arg, unsigned int, nr_args)
10386 struct io_ring_ctx *ctx;
10395 if (f.file->f_op != &io_uring_fops)
10398 ctx = f.file->private_data;
10400 io_run_task_work();
10402 mutex_lock(&ctx->uring_lock);
10403 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10404 mutex_unlock(&ctx->uring_lock);
10405 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10406 ctx->cq_ev_fd != NULL, ret);
10412 static int __init io_uring_init(void)
10414 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10415 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10416 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10419 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10420 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10421 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10422 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10423 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10424 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10425 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10426 BUILD_BUG_SQE_ELEM(8, __u64, off);
10427 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10428 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10429 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10430 BUILD_BUG_SQE_ELEM(24, __u32, len);
10431 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10432 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10433 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10434 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10435 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10436 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10437 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10438 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10439 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10440 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10441 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10442 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10443 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10444 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10445 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10446 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10447 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10448 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10449 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10450 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10451 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10453 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10454 sizeof(struct io_uring_rsrc_update));
10455 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10456 sizeof(struct io_uring_rsrc_update2));
10457 /* should fit into one byte */
10458 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10460 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10461 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10463 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10467 __initcall(io_uring_init);